You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

manager_run.go 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package eventsource
  5. import (
  6. "context"
  7. "time"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/graceful"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. )
  14. // Init starts this eventsource
  15. func (m *Manager) Init() {
  16. if setting.UI.Notification.EventSourceUpdateTime <= 0 {
  17. return
  18. }
  19. go graceful.GetManager().RunWithShutdownContext(m.Run)
  20. }
  21. // Run runs the manager within a provided context
  22. func (m *Manager) Run(ctx context.Context) {
  23. then := timeutil.TimeStampNow().Add(-2)
  24. timer := time.NewTicker(setting.UI.Notification.EventSourceUpdateTime)
  25. loop:
  26. for {
  27. select {
  28. case <-ctx.Done():
  29. timer.Stop()
  30. break loop
  31. case <-timer.C:
  32. m.mutex.Lock()
  33. connectionCount := len(m.messengers)
  34. if connectionCount == 0 {
  35. log.Trace("Event source has no listeners")
  36. // empty the connection channel
  37. select {
  38. case <-m.connection:
  39. default:
  40. }
  41. }
  42. m.mutex.Unlock()
  43. if connectionCount == 0 {
  44. // No listeners so the source can be paused
  45. log.Trace("Pausing the eventsource")
  46. select {
  47. case <-ctx.Done():
  48. break loop
  49. case <-m.connection:
  50. log.Trace("Connection detected - restarting the eventsource")
  51. // OK we're back so lets reset the timer and start again
  52. // We won't change the "then" time because there could be concurrency issues
  53. select {
  54. case <-timer.C:
  55. default:
  56. }
  57. continue
  58. }
  59. }
  60. now := timeutil.TimeStampNow().Add(-2)
  61. uidCounts, err := models.GetUIDsAndNotificationCounts(then, now)
  62. if err != nil {
  63. log.Error("Unable to get UIDcounts: %v", err)
  64. }
  65. for _, uidCount := range uidCounts {
  66. m.SendMessage(uidCount.UserID, &Event{
  67. Name: "notification-count",
  68. Data: uidCount,
  69. })
  70. }
  71. then = now
  72. }
  73. }
  74. m.UnregisterAll()
  75. }