-
Notifications
You must be signed in to change notification settings - Fork 92
/
producer.go
719 lines (640 loc) · 23 KB
/
producer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package river
import (
"context"
"encoding/json"
"errors"
"log/slog"
"strings"
"sync/atomic"
"time"
"github.com/riverqueue/river/internal/jobcompleter"
"github.com/riverqueue/river/internal/notifier"
"github.com/riverqueue/river/internal/rivercommon"
"github.com/riverqueue/river/internal/util/chanutil"
"github.com/riverqueue/river/internal/workunit"
"github.com/riverqueue/river/riverdriver"
"github.com/riverqueue/river/rivershared/baseservice"
"github.com/riverqueue/river/rivershared/startstop"
"github.com/riverqueue/river/rivershared/testsignal"
"github.com/riverqueue/river/rivershared/util/randutil"
"github.com/riverqueue/river/rivershared/util/serviceutil"
"github.com/riverqueue/river/rivertype"
)
const (
queuePollIntervalDefault = 2 * time.Second
queueReportIntervalDefault = 10 * time.Minute
)
// Test-only properties.
type producerTestSignals struct {
DeletedExpiredQueueRecords testsignal.TestSignal[struct{}] // notifies when the producer deletes expired queue records
Paused testsignal.TestSignal[struct{}] // notifies when the producer is paused
PolledQueueConfig testsignal.TestSignal[struct{}] // notifies when the producer polls for queue settings
ReportedQueueStatus testsignal.TestSignal[struct{}] // notifies when the producer reports queue status
Resumed testsignal.TestSignal[struct{}] // notifies when the producer is resumed
StartedExecutors testsignal.TestSignal[struct{}] // notifies when runOnce finishes a pass
}
func (ts *producerTestSignals) Init() {
ts.DeletedExpiredQueueRecords.Init()
ts.Paused.Init()
ts.PolledQueueConfig.Init()
ts.ReportedQueueStatus.Init()
ts.Resumed.Init()
ts.StartedExecutors.Init()
}
type producerConfig struct {
ClientID string
Completer jobcompleter.JobCompleter
ErrorHandler ErrorHandler
// FetchCooldown is the minimum amount of time to wait between fetches of new
// jobs. Jobs will only be fetched *at most* this often, but if no new jobs
// are coming in via LISTEN/NOTIFY then fetches may be delayed as long as
// FetchPollInterval.
FetchCooldown time.Duration
// FetchPollInterval is the amount of time between periodic fetches for new
// jobs. Typically new jobs will be picked up ~immediately after insert via
// LISTEN/NOTIFY, but this provides a fallback.
FetchPollInterval time.Duration
GlobalMiddleware []rivertype.WorkerMiddleware
JobTimeout time.Duration
MaxWorkers int
// Notifier is a notifier for subscribing to new job inserts and job
// control. If nil, the producer will operate in poll-only mode.
Notifier *notifier.Notifier
Queue string
// QueueEventCallback gets called when a queue's config changes (such as
// pausing or resuming) events can be emitted to subscriptions.
QueueEventCallback func(event *Event)
// QueuePollInterval is the amount of time between periodic checks for
// queue setting changes. This is only used in poll-only mode (when no
// notifier is provided).
QueuePollInterval time.Duration
// QueueReportInterval is the amount of time between periodic reports
// of the queue status.
QueueReportInterval time.Duration
RetryPolicy ClientRetryPolicy
SchedulerInterval time.Duration
Workers *Workers
}
func (c *producerConfig) mustValidate() *producerConfig {
if c.Completer == nil {
panic("producerConfig.Completer is required")
}
if c.ClientID == "" {
panic("producerConfig.ClientID is required")
}
if c.FetchCooldown <= 0 {
panic("producerConfig.FetchCooldown must be great than zero")
}
if c.FetchPollInterval <= 0 {
panic("producerConfig.FetchPollInterval must be greater than zero")
}
if c.JobTimeout < -1 {
panic("producerConfig.JobTimeout must be greater or equal to zero")
}
if c.MaxWorkers == 0 {
panic("producerConfig.MaxWorkers is required")
}
if c.Queue == "" {
panic("producerConfig.Queue is required")
}
if c.QueuePollInterval == 0 {
c.QueuePollInterval = queuePollIntervalDefault
}
if c.QueuePollInterval <= 0 {
panic("producerConfig.QueueSettingsPollInterval must be greater than zero")
}
if c.QueueReportInterval == 0 {
c.QueueReportInterval = queueReportIntervalDefault
}
if c.QueueReportInterval <= 0 {
panic("producerConfig.QueueSettingsReportInterval must be greater than zero")
}
if c.RetryPolicy == nil {
panic("producerConfig.RetryPolicy is required")
}
if c.SchedulerInterval == 0 {
panic("producerConfig.SchedulerInterval is required")
}
if c.Workers == nil {
panic("producerConfig.Workers is required")
}
return c
}
// producer manages a fleet of Workers up to a maximum size. It periodically fetches jobs
// from the adapter and dispatches them to Workers. It receives completed job results from Workers.
//
// The producer never fetches more jobs than the number of free Worker slots it
// has available. This is not optimal for throughput compared to pre-fetching
// extra jobs, but it is better for smaller job counts or slower jobs where even
// distribution and minimizing execution latency is more important.
type producer struct {
baseservice.BaseService
startstop.BaseStartStop
// Jobs which are currently being worked. Only used by main goroutine.
activeJobs map[int64]*jobExecutor
completer jobcompleter.JobCompleter
config *producerConfig
exec riverdriver.Executor
errorHandler ErrorHandler
workers *Workers
// Receives job IDs to cancel. Written by notifier goroutine, only read from
// main goroutine.
cancelCh chan int64
// Set to true when the producer thinks it should trigger another fetch as
// soon as slots are available. This is written and read by the main
// goroutine.
fetchWhenSlotsAreAvailable bool
// Receives completed jobs from workers. Written by completed workers, only
// read from main goroutine.
jobResultCh chan *rivertype.JobRow
jobTimeout time.Duration
// An atomic count of the number of jobs actively being worked on. This is
// written to by the main goroutine, but read by the dispatcher.
numJobsActive atomic.Int32
numJobsRan atomic.Uint64
paused bool
// Receives control messages from the notifier goroutine. Written by notifier
// goroutine, only read from main goroutine.
queueControlCh chan *jobControlPayload
retryPolicy ClientRetryPolicy
testSignals producerTestSignals
}
func newProducer(archetype *baseservice.Archetype, exec riverdriver.Executor, config *producerConfig) *producer {
if archetype == nil {
panic("archetype is required")
}
if exec == nil {
panic("exec is required")
}
return baseservice.Init(archetype, &producer{
activeJobs: make(map[int64]*jobExecutor),
cancelCh: make(chan int64, 1000),
completer: config.Completer,
config: config.mustValidate(),
exec: exec,
errorHandler: config.ErrorHandler,
jobResultCh: make(chan *rivertype.JobRow, config.MaxWorkers),
jobTimeout: config.JobTimeout,
queueControlCh: make(chan *jobControlPayload, 100),
retryPolicy: config.RetryPolicy,
workers: config.Workers,
})
}
// Start starts the producer. It backgrounds a goroutine which is stopped when
// context is cancelled or Stop is invoked.
//
// This variant uses a single context as fetchCtx and workCtx, and is here to
// implement startstop.Service so that the producer can be stored as a service
// variable and used with various service utilities. StartWorkContext below
// should be preferred for production use.
func (p *producer) Start(ctx context.Context) error {
return p.StartWorkContext(ctx, ctx)
}
func (p *producer) Stop() {
p.Logger.Debug(p.Name + ": Stopping")
p.BaseStartStop.Stop()
p.Logger.Debug(p.Name + ": Stop returned")
}
// Start starts the producer. It backgrounds a goroutine which is stopped when
// context is cancelled or Stop is invoked.
//
// When fetchCtx is cancelled, no more jobs will be fetched; however, if a fetch
// is already in progress, It will be allowed to complete and run any fetched
// jobs. When workCtx is cancelled, any in-progress jobs will have their
// contexts cancelled too.
func (p *producer) StartWorkContext(fetchCtx, workCtx context.Context) error {
fetchCtx, shouldStart, started, stopped := p.StartInit(fetchCtx)
if !shouldStart {
return nil
}
queue, err := func() (*rivertype.Queue, error) {
ctx, cancel := context.WithTimeout(fetchCtx, 10*time.Second)
defer cancel()
p.Logger.DebugContext(ctx, p.Name+": Fetching initial queue settings", slog.String("queue", p.config.Queue))
return p.exec.QueueCreateOrSetUpdatedAt(ctx, &riverdriver.QueueCreateOrSetUpdatedAtParams{
Metadata: []byte("{}"),
Name: p.config.Queue,
})
}()
if err != nil {
stopped()
if errors.Is(err, startstop.ErrStop) || strings.HasSuffix(err.Error(), "conn closed") || fetchCtx.Err() != nil {
return nil //nolint:nilerr
}
p.Logger.ErrorContext(fetchCtx, p.Name+": Error fetching initial queue settings", slog.String("err", err.Error()))
return err
}
initiallyPaused := queue != nil && (queue.PausedAt != nil)
p.paused = initiallyPaused
// TODO: fetcher should have some jitter in it to avoid stampeding issues.
fetchLimiter := chanutil.NewDebouncedChan(fetchCtx, p.config.FetchCooldown, true)
var (
controlSub *notifier.Subscription
insertSub *notifier.Subscription
)
if p.config.Notifier == nil {
p.Logger.DebugContext(fetchCtx, p.Name+": No notifier configured; starting in poll mode", "client_id", p.config.ClientID)
go p.pollForSettingChanges(fetchCtx, initiallyPaused)
} else {
var err error
handleInsertNotification := func(topic notifier.NotificationTopic, payload string) {
var decoded insertPayload
if err := json.Unmarshal([]byte(payload), &decoded); err != nil {
p.Logger.ErrorContext(workCtx, p.Name+": Failed to unmarshal insert notification payload", slog.String("err", err.Error()))
return
}
if decoded.Queue != p.config.Queue {
return
}
p.Logger.DebugContext(workCtx, p.Name+": Received insert notification", slog.String("queue", decoded.Queue))
fetchLimiter.Call()
}
insertSub, err = p.config.Notifier.Listen(fetchCtx, notifier.NotificationTopicInsert, handleInsertNotification)
if err != nil {
stopped()
if strings.HasSuffix(err.Error(), "conn closed") || errors.Is(err, context.Canceled) {
return nil
}
return err
}
controlSub, err = p.config.Notifier.Listen(fetchCtx, notifier.NotificationTopicControl, p.handleControlNotification(workCtx))
if err != nil {
stopped()
if strings.HasSuffix(err.Error(), "conn closed") || errors.Is(err, context.Canceled) {
return nil
}
return err
}
}
go func() {
started()
defer stopped() // this defer should come first so it's last out
p.Logger.DebugContext(fetchCtx, p.Name+": Run loop started", slog.String("queue", p.config.Queue), slog.Bool("paused", p.paused))
defer func() {
p.Logger.DebugContext(fetchCtx, p.Name+": Run loop stopped", slog.String("queue", p.config.Queue), slog.Uint64("num_completed_jobs", p.numJobsRan.Load()))
}()
if insertSub != nil {
defer insertSub.Unlisten(fetchCtx)
}
if controlSub != nil {
defer controlSub.Unlisten(fetchCtx)
}
go p.heartbeatLogLoop(fetchCtx)
go p.reportQueueStatusLoop(fetchCtx)
p.fetchAndRunLoop(fetchCtx, workCtx, fetchLimiter)
p.executorShutdownLoop()
}()
return nil
}
type controlAction string
const (
controlActionCancel controlAction = "cancel"
controlActionPause controlAction = "pause"
controlActionResume controlAction = "resume"
)
type jobControlPayload struct {
Action controlAction `json:"action"`
JobID int64 `json:"job_id"`
Queue string `json:"queue"`
}
type insertPayload struct {
Queue string `json:"queue"`
}
func (p *producer) handleControlNotification(workCtx context.Context) func(notifier.NotificationTopic, string) {
return func(topic notifier.NotificationTopic, payload string) {
var decoded jobControlPayload
if err := json.Unmarshal([]byte(payload), &decoded); err != nil {
p.Logger.ErrorContext(workCtx, p.Name+": Failed to unmarshal job control notification payload", slog.String("err", err.Error()))
return
}
switch decoded.Action {
case controlActionPause, controlActionResume:
if decoded.Queue != rivercommon.AllQueuesString && decoded.Queue != p.config.Queue {
p.Logger.DebugContext(workCtx, p.Name+": Queue control notification for other queue", slog.String("action", string(decoded.Action)))
return
}
select {
case <-workCtx.Done():
case p.queueControlCh <- &decoded:
default:
p.Logger.WarnContext(workCtx, p.Name+": Queue control notification dropped due to full buffer", slog.String("action", string(decoded.Action)))
}
case controlActionCancel:
if decoded.Queue != p.config.Queue {
p.Logger.DebugContext(workCtx, p.Name+": Received job cancel notification for other queue",
slog.String("action", string(decoded.Action)),
slog.Int64("job_id", decoded.JobID),
slog.String("queue", decoded.Queue),
)
return
}
select {
case <-workCtx.Done():
case p.cancelCh <- decoded.JobID:
default:
p.Logger.WarnContext(workCtx, p.Name+": Job cancel notification dropped due to full buffer", slog.Int64("job_id", decoded.JobID))
}
default:
p.Logger.DebugContext(workCtx, p.Name+": Received job control notification with unknown action",
slog.String("action", string(decoded.Action)),
slog.Int64("job_id", decoded.JobID),
slog.String("queue", decoded.Queue),
)
}
}
}
func (p *producer) fetchAndRunLoop(fetchCtx, workCtx context.Context, fetchLimiter *chanutil.DebouncedChan) {
// Prime the fetchLimiter so we can make an initial fetch without waiting for
// an insert notification or a fetch poll.
fetchLimiter.Call()
fetchPollTimer := time.NewTimer(p.config.FetchPollInterval)
go func() {
for {
select {
case <-fetchCtx.Done():
// Stop fetch timer so no more fetches are triggered.
if !fetchPollTimer.Stop() {
<-fetchPollTimer.C
}
return
case <-fetchPollTimer.C:
fetchLimiter.Call()
fetchPollTimer.Reset(p.config.FetchPollInterval)
}
}
}()
fetchResultCh := make(chan producerFetchResult)
for {
select {
case <-fetchCtx.Done():
return
case msg := <-p.queueControlCh:
switch msg.Action {
case controlActionPause:
if p.paused {
continue
}
p.paused = true
p.Logger.DebugContext(workCtx, p.Name+": Paused", slog.String("queue", p.config.Queue), slog.String("queue_in_message", msg.Queue))
p.testSignals.Paused.Signal(struct{}{})
if p.config.QueueEventCallback != nil {
p.config.QueueEventCallback(&Event{Kind: EventKindQueuePaused, Queue: &rivertype.Queue{Name: p.config.Queue}})
}
case controlActionResume:
if !p.paused {
continue
}
p.paused = false
p.Logger.DebugContext(workCtx, p.Name+": Resumed", slog.String("queue", p.config.Queue), slog.String("queue_in_message", msg.Queue))
p.testSignals.Resumed.Signal(struct{}{})
if p.config.QueueEventCallback != nil {
p.config.QueueEventCallback(&Event{Kind: EventKindQueueResumed, Queue: &rivertype.Queue{Name: p.config.Queue}})
}
case controlActionCancel:
// Separate this case to make linter happy:
p.Logger.DebugContext(workCtx, p.Name+": Unhandled queue control action", "action", msg.Action)
default:
p.Logger.DebugContext(workCtx, p.Name+": Unknown queue control action", "action", msg.Action)
}
case jobID := <-p.cancelCh:
p.maybeCancelJob(jobID)
case <-fetchLimiter.C():
if p.paused {
continue
}
p.innerFetchLoop(workCtx, fetchResultCh)
// Ensure we can't start another fetch when fetchCtx is done, even if
// the fetchLimiter is also ready to fire:
select {
case <-fetchCtx.Done():
return
default:
}
case result := <-p.jobResultCh:
p.removeActiveJob(result.ID)
if p.fetchWhenSlotsAreAvailable {
// If we missed a fetch because all worker slots were full, or if we
// fetched the maximum number of jobs on the last attempt, get a little
// more aggressive triggering the fetch limiter now that we have a slot
// available.
p.fetchWhenSlotsAreAvailable = false
fetchLimiter.Call()
}
}
}
}
func (p *producer) innerFetchLoop(workCtx context.Context, fetchResultCh chan producerFetchResult) {
limit := p.maxJobsToFetch()
if limit <= 0 {
// We have no slots for new jobs, so don't bother fetching. However, since
// we knew it was time to fetch, we keep track of what happened so we can
// trigger another fetch as soon as we have open slots.
p.fetchWhenSlotsAreAvailable = true
return
}
go p.dispatchWork(workCtx, limit, fetchResultCh)
for {
select {
case result := <-fetchResultCh:
if result.err != nil {
p.Logger.ErrorContext(workCtx, p.Name+": Error fetching jobs", slog.String("err", result.err.Error()))
} else if len(result.jobs) > 0 {
p.startNewExecutors(workCtx, result.jobs)
if len(result.jobs) == limit {
// Fetch returned the maximum number of jobs that were requested,
// implying there may be more in the queue. Trigger another fetch when
// slots are available.
p.fetchWhenSlotsAreAvailable = true
}
}
return
case result := <-p.jobResultCh:
p.removeActiveJob(result.ID)
case jobID := <-p.cancelCh:
p.maybeCancelJob(jobID)
}
}
}
func (p *producer) executorShutdownLoop() {
// No more jobs will be fetched or executed. However, we must wait for all
// in-progress jobs to complete.
for {
if len(p.activeJobs) == 0 {
break
}
result := <-p.jobResultCh
p.removeActiveJob(result.ID)
}
}
func (p *producer) addActiveJob(id int64, executor *jobExecutor) {
p.numJobsActive.Add(1)
p.activeJobs[id] = executor
}
func (p *producer) removeActiveJob(id int64) {
delete(p.activeJobs, id)
p.numJobsActive.Add(-1)
p.numJobsRan.Add(1)
}
func (p *producer) maybeCancelJob(id int64) {
executor, ok := p.activeJobs[id]
if !ok {
return
}
executor.Cancel()
}
func (p *producer) dispatchWork(workCtx context.Context, count int, fetchResultCh chan<- producerFetchResult) {
// This intentionally removes any deadlines or cancellation from the parent
// context because we don't want it to get cancelled if the producer is asked
// to shut down. In that situation, we want to finish fetching any jobs we are
// in the midst of fetching, work them, and then stop. Otherwise we'd have a
// risk of shutting down when we had already fetched jobs in the database,
// leaving those jobs stranded. We'd then potentially have to release them
// back to the queue.
jobs, err := p.exec.JobGetAvailable(context.WithoutCancel(workCtx), &riverdriver.JobGetAvailableParams{
AttemptedBy: p.config.ClientID,
Max: count,
Queue: p.config.Queue,
})
if err != nil {
fetchResultCh <- producerFetchResult{err: err}
return
}
fetchResultCh <- producerFetchResult{jobs: jobs}
}
// Periodically logs an informational log line giving some insight into the
// current state of the producer.
func (p *producer) heartbeatLogLoop(ctx context.Context) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
type jobCount struct {
ran uint64
active int
}
var prevCount jobCount
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
curCount := jobCount{ran: p.numJobsRan.Load(), active: int(p.numJobsActive.Load())}
if curCount != prevCount {
p.Logger.InfoContext(ctx, p.Name+": Producer job counts",
slog.Uint64("num_completed_jobs", curCount.ran),
slog.Int("num_jobs_running", curCount.active),
slog.String("queue", p.config.Queue),
)
}
prevCount = curCount
}
}
}
func (p *producer) startNewExecutors(workCtx context.Context, jobs []*rivertype.JobRow) {
for _, job := range jobs {
workInfo, ok := p.workers.workersMap[job.Kind]
var workUnit workunit.WorkUnit
if ok {
workUnit = workInfo.workUnitFactory.MakeUnit(job)
}
// jobCancel will always be called by the executor to prevent leaks.
jobCtx, jobCancel := context.WithCancelCause(workCtx)
executor := baseservice.Init(&p.Archetype, &jobExecutor{
CancelFunc: jobCancel,
ClientJobTimeout: p.jobTimeout,
ClientRetryPolicy: p.retryPolicy,
Completer: p.completer,
ErrorHandler: p.errorHandler,
InformProducerDoneFunc: p.handleWorkerDone,
GlobalMiddleware: p.config.GlobalMiddleware,
JobRow: job,
SchedulerInterval: p.config.SchedulerInterval,
WorkUnit: workUnit,
})
p.addActiveJob(job.ID, executor)
go executor.Execute(jobCtx)
}
p.Logger.DebugContext(workCtx, p.Name+": Distributed batch of jobs to executors", "num_jobs", len(jobs))
p.testSignals.StartedExecutors.Signal(struct{}{})
}
func (p *producer) maxJobsToFetch() int {
return p.config.MaxWorkers - int(p.numJobsActive.Load())
}
func (p *producer) handleWorkerDone(job *rivertype.JobRow) {
p.jobResultCh <- job
}
func (p *producer) pollForSettingChanges(ctx context.Context, lastPaused bool) {
ticker := time.NewTicker(p.config.QueuePollInterval)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
updatedQueue, err := p.fetchQueueSettings(ctx)
if err != nil {
p.Logger.ErrorContext(ctx, p.Name+": Error fetching queue settings", slog.String("err", err.Error()))
continue
}
shouldBePaused := (updatedQueue.PausedAt != nil)
if lastPaused != shouldBePaused {
action := controlActionPause
if !shouldBePaused {
action = controlActionResume
}
payload := &jobControlPayload{
Action: action,
Queue: p.config.Queue,
}
p.Logger.DebugContext(ctx, p.Name+": Queue control state changed from polling",
slog.String("queue", p.config.Queue),
slog.String("action", string(action)),
slog.Bool("paused", shouldBePaused),
)
select {
case p.queueControlCh <- payload:
lastPaused = shouldBePaused
default:
p.Logger.WarnContext(ctx, p.Name+": Queue control notification dropped due to full buffer", slog.String("action", string(action)))
}
}
p.testSignals.PolledQueueConfig.Signal(struct{}{})
}
}
}
func (p *producer) fetchQueueSettings(ctx context.Context) (*rivertype.Queue, error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
return p.exec.QueueGet(ctx, p.config.Queue)
}
func (p *producer) reportQueueStatusLoop(ctx context.Context) {
serviceutil.CancellableSleep(ctx, randutil.DurationBetween(0, time.Second))
reportTicker := time.NewTicker(p.config.QueueReportInterval)
for {
select {
case <-ctx.Done():
reportTicker.Stop()
return
case <-reportTicker.C:
p.reportQueueStatusOnce(ctx)
}
}
}
func (p *producer) reportQueueStatusOnce(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
p.Logger.DebugContext(ctx, p.Name+": Reporting queue status", slog.String("queue", p.config.Queue))
_, err := p.exec.QueueCreateOrSetUpdatedAt(ctx, &riverdriver.QueueCreateOrSetUpdatedAtParams{
Metadata: []byte("{}"),
Name: p.config.Queue,
})
if err != nil && errors.Is(context.Cause(ctx), startstop.ErrStop) {
return
}
if err != nil {
p.Logger.ErrorContext(ctx, p.Name+": Queue status update, error updating in database", slog.String("err", err.Error()))
return
}
p.testSignals.ReportedQueueStatus.Signal(struct{}{})
}
type producerFetchResult struct {
jobs []*rivertype.JobRow
err error
}