|
| 1 | +package maintenance |
| 2 | + |
| 3 | +import ( |
| 4 | + "cmp" |
| 5 | + "context" |
| 6 | + "errors" |
| 7 | + "log/slog" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/riverqueue/river/internal/hooklookup" |
| 11 | + "github.com/riverqueue/river/riverdriver" |
| 12 | + "github.com/riverqueue/river/rivershared/baseservice" |
| 13 | + "github.com/riverqueue/river/rivershared/riversharedmaintenance" |
| 14 | + "github.com/riverqueue/river/rivershared/startstop" |
| 15 | + "github.com/riverqueue/river/rivershared/testsignal" |
| 16 | + "github.com/riverqueue/river/rivershared/util/testutil" |
| 17 | + "github.com/riverqueue/river/rivershared/util/timeutil" |
| 18 | + "github.com/riverqueue/river/rivertype" |
| 19 | +) |
| 20 | + |
| 21 | +const QueueStateCounterIntervalDefault = 10 * time.Second |
| 22 | + |
| 23 | +var jobStateAll = rivertype.JobStates() //nolint:gochecknoglobals |
| 24 | + |
| 25 | +// QueueStateCounterTestSignals are internal signals used exclusively in tests. |
| 26 | +type QueueStateCounterTestSignals struct { |
| 27 | + CountedOnce testsignal.TestSignal[struct{}] // notifies when a count pass finishes |
| 28 | +} |
| 29 | + |
| 30 | +func (ts *QueueStateCounterTestSignals) Init(tb testutil.TestingTB) { |
| 31 | + ts.CountedOnce.Init(tb) |
| 32 | +} |
| 33 | + |
| 34 | +type QueueStateCounterConfig struct { |
| 35 | + // HookLookupGlobal provides access to globally registered hooks. |
| 36 | + HookLookupGlobal hooklookup.HookLookupInterface |
| 37 | + |
| 38 | + // Interval is the amount of time between count runs. |
| 39 | + Interval time.Duration |
| 40 | + |
| 41 | + // QueueNames is the list of configured queue names. Counts are emitted for |
| 42 | + // all of these queues even if they have no jobs, with zero counts for all |
| 43 | + // states. |
| 44 | + QueueNames []string |
| 45 | + |
| 46 | + // Schema where River tables are located. Empty string omits schema, causing |
| 47 | + // Postgres to default to `search_path`. |
| 48 | + Schema string |
| 49 | +} |
| 50 | + |
| 51 | +func (c *QueueStateCounterConfig) mustValidate() *QueueStateCounterConfig { |
| 52 | + if c.Interval <= 0 { |
| 53 | + panic("QueueStateCounterConfig.Interval must be above zero") |
| 54 | + } |
| 55 | + |
| 56 | + return c |
| 57 | +} |
| 58 | + |
| 59 | +// QueueStateCounter periodically counts jobs by queue and state, logging the |
| 60 | +// results. This provides visibility into queue health without requiring |
| 61 | +// external monitoring queries. The maintenance service only runs if there is a |
| 62 | +// HookQueueStateCount hook registered that consumes the counts. |
| 63 | +type QueueStateCounter struct { |
| 64 | + riversharedmaintenance.QueueMaintainerServiceBase |
| 65 | + startstop.BaseStartStop |
| 66 | + |
| 67 | + // exported for test purposes |
| 68 | + Config *QueueStateCounterConfig |
| 69 | + TestSignals QueueStateCounterTestSignals |
| 70 | + |
| 71 | + exec riverdriver.Executor |
| 72 | +} |
| 73 | + |
| 74 | +func NewQueueStateCounter(archetype *baseservice.Archetype, config *QueueStateCounterConfig, exec riverdriver.Executor) *QueueStateCounter { |
| 75 | + return baseservice.Init(archetype, &QueueStateCounter{ |
| 76 | + Config: (&QueueStateCounterConfig{ |
| 77 | + HookLookupGlobal: config.HookLookupGlobal, |
| 78 | + Interval: cmp.Or(config.Interval, QueueStateCounterIntervalDefault), |
| 79 | + QueueNames: config.QueueNames, |
| 80 | + Schema: config.Schema, |
| 81 | + }).mustValidate(), |
| 82 | + exec: exec, |
| 83 | + }) |
| 84 | +} |
| 85 | + |
| 86 | +func (s *QueueStateCounter) Start(ctx context.Context) error { |
| 87 | + ctx, shouldStart, started, stopped := s.StartInit(ctx) |
| 88 | + if !shouldStart { |
| 89 | + return nil |
| 90 | + } |
| 91 | + |
| 92 | + s.StaggerStart(ctx) |
| 93 | + |
| 94 | + go func() { |
| 95 | + started() |
| 96 | + defer stopped() // this defer should come first so it's last out |
| 97 | + |
| 98 | + s.Logger.DebugContext(ctx, s.Name+riversharedmaintenance.LogPrefixRunLoopStarted) |
| 99 | + defer s.Logger.DebugContext(ctx, s.Name+riversharedmaintenance.LogPrefixRunLoopStopped) |
| 100 | + |
| 101 | + // If no hooks are registered, there's no one to send counts to, so |
| 102 | + // start, but don't do anything. |
| 103 | + if len(s.Config.HookLookupGlobal.ByHookKind(hooklookup.HookKindQueueStateCount)) < 1 { |
| 104 | + <-ctx.Done() |
| 105 | + return |
| 106 | + } |
| 107 | + |
| 108 | + ticker := timeutil.NewTickerWithInitialTick(ctx, s.Config.Interval) |
| 109 | + for { |
| 110 | + select { |
| 111 | + case <-ctx.Done(): |
| 112 | + return |
| 113 | + case <-ticker.C: |
| 114 | + } |
| 115 | + |
| 116 | + if err := s.runOnce(ctx); err != nil { |
| 117 | + if !errors.Is(err, context.Canceled) { |
| 118 | + s.Logger.ErrorContext(ctx, s.Name+": Error counting queue states", slog.String("error", err.Error())) |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + }() |
| 123 | + |
| 124 | + return nil |
| 125 | +} |
| 126 | + |
| 127 | +func (s *QueueStateCounter) runOnce(ctx context.Context) error { |
| 128 | + ctx, cancelFunc := context.WithTimeout(ctx, riversharedmaintenance.TimeoutDefault) |
| 129 | + defer cancelFunc() |
| 130 | + |
| 131 | + rawCounts, err := s.exec.JobCountByQueueAndState(ctx, &riverdriver.JobCountByQueueAndStateParams{ |
| 132 | + QueueNames: s.Config.QueueNames, |
| 133 | + Schema: s.Config.Schema, |
| 134 | + }) |
| 135 | + if err != nil { |
| 136 | + return err |
| 137 | + } |
| 138 | + |
| 139 | + byQueue := s.buildResults(ctx, rawCounts) |
| 140 | + |
| 141 | + for _, hook := range s.Config.HookLookupGlobal.ByHookKind(hooklookup.HookKindQueueStateCount) { |
| 142 | + hook.(rivertype.HookQueueStateCount).QueueStateCount(ctx, &rivertype.HookQueueStateCountParams{ //nolint:forcetypeassert |
| 143 | + ByQueue: byQueue, |
| 144 | + }) |
| 145 | + } |
| 146 | + |
| 147 | + s.TestSignals.CountedOnce.Signal(struct{}{}) |
| 148 | + |
| 149 | + return nil |
| 150 | +} |
| 151 | + |
| 152 | +// buildResults converts raw driver counts into results with all configured |
| 153 | +// queues and all job states filled in (zeroed where needed), logging one line |
| 154 | +// per queue. |
| 155 | +func (s *QueueStateCounter) buildResults(ctx context.Context, rawCounts map[string]map[rivertype.JobState]int) map[string]rivertype.HookQueueStateCountResult { |
| 156 | + // Ensure all configured queues are present, even if they have no jobs. |
| 157 | + for _, queue := range s.Config.QueueNames { |
| 158 | + if rawCounts[queue] == nil { |
| 159 | + rawCounts[queue] = make(map[rivertype.JobState]int) |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + countsByQueue := make(map[string]rivertype.HookQueueStateCountResult, len(rawCounts)) |
| 164 | + |
| 165 | + for queue, stateCounts := range rawCounts { |
| 166 | + attrs := make([]slog.Attr, 0, 2+len(jobStateAll)) |
| 167 | + attrs = append(attrs, slog.String("queue", queue)) |
| 168 | + total := 0 |
| 169 | + |
| 170 | + for _, state := range jobStateAll { |
| 171 | + if _, ok := stateCounts[state]; !ok { |
| 172 | + stateCounts[state] = 0 |
| 173 | + } |
| 174 | + total += stateCounts[state] |
| 175 | + attrs = append(attrs, slog.Int(string(state), stateCounts[state])) |
| 176 | + } |
| 177 | + |
| 178 | + attrs = append(attrs, slog.Int("total", total)) |
| 179 | + s.Logger.LogAttrs(ctx, slog.LevelInfo, s.Name+": Queue state counts", attrs...) |
| 180 | + |
| 181 | + countsByQueue[queue] = rivertype.HookQueueStateCountResult{ |
| 182 | + ByState: stateCounts, |
| 183 | + Total: total, |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + return countsByQueue |
| 188 | +} |
0 commit comments