Repository navigation
Expand file tree
/
Copy pathbackground.go
More file actions
996 lines (828 loc) · 27.4 KB
/
Copy pathbackground.go
File metadata and controls
996 lines (828 loc) · 27.4 KB
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
package vukem
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"slices"
"strconv"
"strings"
"text/tabwriter"
"time"
_ "time/tzdata" // SCHEDULE_TIMEZONE works on hosts without a zone database (Windows)
"github.com/AlexGalhardo/vukem/cache"
"github.com/AlexGalhardo/vukem/database"
"github.com/AlexGalhardo/vukem/mail"
"github.com/AlexGalhardo/vukem/queue"
"github.com/AlexGalhardo/vukem/schedule"
)
// WithJobs registers job handlers on the application queue. Handlers that
// need the app (database, clock, mailer) use WithJobsFunc.
func WithJobs(regs ...queue.Registration) Option {
return func(o *options) error { o.jobs = append(o.jobs, regs...); return nil }
}
// WithJobsFunc registers job handlers built from the app, so they reach
// its database, clock, mailer and other services without globals
// (generated apps pass jobs.All). fn runs once, inside the first
// app.Queue call; a panic in fn becomes that call's error. fn may get
// app.DB, app.Mailer, app.Crypt and app.Now; it must not dispatch: no
// app.Queue, app.Events.Dispatch (queued listeners), Mailer.SendLater /
// app.MailLater or running scheduled jobs, which wait for the queue being
// built and deadlock. Handlers may do all of that when they run.
func WithJobsFunc(fn func(app *App) []queue.Registration) Option {
return func(o *options) error { o.jobFuncs = append(o.jobFuncs, fn); return nil }
}
// WithQueueDriver replaces the driver chosen by QUEUE_CONNECTION (tests
// pass a queue.Fake). The last of WithQueueDriver and WithQueueDriverFunc
// wins.
func WithQueueDriver(d queue.Driver) Option {
return func(o *options) error { o.queueDriver, o.queueFunc = d, nil; return nil }
}
// WithQueueDriverFunc replaces the driver chosen by QUEUE_CONNECTION with
// one built by fn on the first app.Queue() call, after configuration
// loaded, so fn can read app.Source. fn returns ErrUseDefault to keep the
// QUEUE_CONNECTION driver. Any other error from fn, or a nil driver, is
// returned by app.Queue(). With QUEUE_CONNECTION=database, Boot runs fn
// instead (once either way) and creates the queue tables only when fn
// falls back to them; its error then fails the boot. fn must not call app.Queue() (or dispatch a
// job): it runs inside Queue's sync.Once and that call would deadlock.
func WithQueueDriverFunc(fn func(app *App) (queue.Driver, error)) Option {
return func(o *options) error { o.queueFunc, o.queueDriver = fn, nil; return nil }
}
// WithQueueWork sets the worker options of the queue runner that serve
// starts (QUEUE_IN_SERVE), in code instead of QUEUE_NAMES, QUEUE_CONCURRENCY
// and QUEUE_LIMITS. A field that is set replaces the value from the
// configuration: Queues, Concurrency, Limits, Sleep (the polling interval,
// 1s by default), StopTimeout, MaxJobs and StopWhenEmpty. Zero fields keep
// the configured value. It does not affect queue:work, which has its own
// flags.
func WithQueueWork(w queue.WorkOptions) Option {
return func(o *options) error { o.queueWork = w; return nil }
}
// withQueueWork applies the fields of over that are set on top of base.
func withQueueWork(base, over queue.WorkOptions) queue.WorkOptions {
if len(over.Queues) > 0 {
base.Queues = over.Queues
}
if over.Concurrency > 0 {
base.Concurrency = over.Concurrency
}
if over.Limits != nil {
base.Limits = over.Limits
}
if over.Sleep > 0 {
base.Sleep = over.Sleep
}
if over.StopTimeout > 0 {
base.StopTimeout = over.StopTimeout
}
if over.MaxJobs > 0 {
base.MaxJobs = over.MaxJobs
}
base.StopWhenEmpty = base.StopWhenEmpty || over.StopWhenEmpty
return base
}
// MailJobKind is the queue job that sends queued mail (App.MailLater).
const MailJobKind = "vukem.mail"
// QueueConfig is read from QUEUE_* variables.
type QueueConfig struct {
// Connection is "sync" (default: jobs run during Dispatch), "memory"
// (in process, run by a worker inside serve) or "database".
Connection string `env:"QUEUE_CONNECTION" default:"sync"`
// Queues lists the queues workers poll, in priority order.
Queues string `env:"QUEUE_NAMES" default:"default"`
// Concurrency is the number of parallel workers.
Concurrency int `env:"QUEUE_CONCURRENCY" default:"4"`
// Limits caps the running jobs of some queues, as "name=n" pairs
// separated by commas ("ingest=2"), so a slow queue cannot take every
// worker. It applies to the worker inside serve and to queue:work, per
// process.
Limits string `env:"QUEUE_LIMITS"`
// Table and FailedTable are the database driver's tables.
Table string `env:"QUEUE_TABLE" default:"jobs"`
FailedTable string `env:"QUEUE_FAILED_TABLE" default:"failed_jobs"`
// InServe runs a queue worker inside serve for the database driver
// and custom drivers (Redis). Set it to false when dedicated
// queue:work processes run the jobs instead; leaving it on next to
// them is safe (reservations are atomic), it only adds workers. The
// memory queue is always worked inside serve: no other process sees
// its jobs.
InServe bool `env:"QUEUE_IN_SERVE" default:"true"`
// AllowLegacyMail sends clear-text mail jobs queued before v0.24.0
// (an upgrade window: drain the queue before upgrading, or set it
// until the old jobs are gone). Off, they fail.
AllowLegacyMail bool `env:"QUEUE_ALLOW_LEGACY_MAIL"`
}
// QueueNames returns Queues as a list.
func (c QueueConfig) QueueNames() []string {
var out []string
for name := range strings.SplitSeq(c.Queues, ",") {
if name = strings.TrimSpace(name); name != "" {
out = append(out, name)
}
}
return out
}
// QueueLimits parses Limits ("name=n,..."; n >= 1).
func (c QueueConfig) QueueLimits() (map[string]int, error) {
var out map[string]int
for pair := range strings.SplitSeq(c.Limits, ",") {
if pair = strings.TrimSpace(pair); pair == "" {
continue
}
name, n, ok := strings.Cut(pair, "=")
name = strings.TrimSpace(name)
limit, err := strconv.Atoi(strings.TrimSpace(n))
if !ok || name == "" || err != nil || limit < 1 {
return nil, fmt.Errorf("vukem: QUEUE_LIMITS entry %q: want name=n with n >= 1", pair)
}
if out == nil {
out = map[string]int{}
}
out[name] = limit
}
return out, nil
}
// Queue returns the application queue, built from QUEUE_* on first use.
func (a *App) Queue() (*queue.Queue, error) {
a.queueOnce.Do(func() {
cfg, err := configLoad[QueueConfig](a)
if err != nil {
a.queueErr = err
return
}
d := a.queueDriver
if d == nil && a.queueDriverFunc != nil {
if d, err = a.resolveQueueDriverFunc(cfg); err != nil {
a.queueErr = fmt.Errorf("vukem: queue driver: %w", err)
return
}
}
switch {
case d != nil:
case cfg.Connection == "sync":
d = queue.Sync{}
case cfg.Connection == "memory":
d = queue.NewMemory()
case cfg.Connection == "database":
if d, err = a.databaseQueueDriver(cfg); err != nil {
a.queueErr = err
return
}
default:
a.queueErr = fmt.Errorf("vukem: unknown QUEUE_CONNECTION %q (sync, memory, database)", cfg.Connection)
return
}
// Delays and retries follow the app clock (WithClock, vukemtest fake
// clocks) on every driver that reads one, custom drivers included.
if c, ok := d.(queue.Clock); ok {
c.SetClock(a.now)
}
q := queue.New(d, a.Log)
q.SetClock(a.now)
for _, obs := range a.jobObservers() {
q.AddObserver(obs)
}
regs, err := a.jobRegistrations()
if err != nil {
a.queueErr = err
return
}
regs = append(regs, a.Events.Jobs()...)
regs = append(regs, queue.HandleKind(MailJobKind, a.sendQueuedMail))
if err := q.Register(regs...); err != nil {
a.queueErr = err
return
}
a.queue = q
})
return a.queue, a.queueErr
}
// jobRegistrations runs the WithJobsFunc functions; a panic in one becomes
// the Queue error instead of leaving a nil queue behind the sync.Once.
func (a *App) jobRegistrations() (regs []queue.Registration, err error) {
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("vukem: WithJobsFunc panicked: %v", p)
}
}()
regs = slices.Clone(a.jobs)
for _, fn := range a.jobFuncs {
regs = append(regs, fn(a)...)
}
return regs, nil
}
// prepareDatabaseQueue creates the database queue tables at Boot, so the
// first app.Queue() never runs DDL: called inside a transaction on SQLite,
// whose single writer connection the transaction holds, it would block
// until the timeout and fail.
//
// A WithQueueDriverFunc runs here to learn whether it falls back to the
// database queue (ErrUseDefault): only then are the tables needed, so a
// Redis driver adds no database dependency at boot.
func (a *App) prepareDatabaseQueue(ctx context.Context) error {
if a.queueDriver != nil {
return nil
}
cfg, err := configLoad[QueueConfig](a)
if err != nil || cfg.Connection != "database" {
return err
}
if a.queueDriverFunc != nil {
d, err := a.resolveQueueDriverFunc(cfg)
if err != nil {
return fmt.Errorf("vukem: queue driver: %w", err)
}
if d != nil {
return nil
}
}
d, err := a.databaseQueue(ctx, cfg)
if err != nil {
return fmt.Errorf("vukem: QUEUE_CONNECTION=database: create the queue tables at boot "+
"(database unreachable or not writable?): %w", err)
}
a.mu.Lock()
a.queueDB = d
a.mu.Unlock()
return nil
}
// resolveQueueDriverFunc runs WithQueueDriverFunc once; a nil driver
// without error means ErrUseDefault (build the QUEUE_CONNECTION driver).
func (a *App) resolveQueueDriverFunc(cfg QueueConfig) (queue.Driver, error) {
a.queueFuncOnce.Do(func() {
a.queueFuncDriver, a.queueFuncErr = lazyStore(a, a.queueDriverFunc, "WithQueueDriverFunc",
"QUEUE_CONNECTION="+cfg.Connection)
})
return a.queueFuncDriver, a.queueFuncErr
}
// databaseQueueDriver returns the driver Boot prepared, or builds it when
// the app was not booted.
func (a *App) databaseQueueDriver(cfg QueueConfig) (*queue.Database, error) {
a.mu.Lock()
d := a.queueDB
a.mu.Unlock()
if d != nil {
return d, nil
}
return a.databaseQueue(context.Background(), cfg)
}
func (a *App) databaseQueue(ctx context.Context, cfg QueueConfig) (*queue.Database, error) {
db, err := a.DB()
if err != nil {
return nil, err
}
d, err := queue.NewDatabase(db, queue.DatabaseOptions{Table: cfg.Table, FailedTable: cfg.FailedTable})
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err := d.CreateTables(ctx); err != nil {
return nil, err
}
return d, nil
}
// queuedMail is the payload of a MailJobKind job: the rendered message,
// encrypted with app.Crypt so bodies (reset links, tokens) and addresses
// never sit in the jobs tables, queue:failed output or logs in clear text.
// Message is the clear-text payload of jobs queued before v0.24.0, refused
// unless QUEUE_ALLOW_LEGACY_MAIL=true. The additional data is fixed, so
// someone with write access to the jobs table can replay a sealed mail;
// that access already allows far worse.
type queuedMail struct {
Sealed string `json:"sealed,omitempty"`
mail.Message
}
// ErrLegacyMail fails a clear-text mail job when QUEUE_ALLOW_LEGACY_MAIL
// is off.
var ErrLegacyMail = errors.New("vukem: clear-text mail job refused (QUEUE_ALLOW_LEGACY_MAIL is off)")
// mailJobAD binds sealed mail payloads to the mail job.
const mailJobAD = "queue:" + MailJobKind
func (a *App) enqueueMail(ctx context.Context, msg *mail.Message, opts ...queue.Option) error {
q, payload, err := a.mailJob(msg)
if err != nil {
return err
}
return q.DispatchKind(ctx, MailJobKind, payload, opts...)
}
func (a *App) enqueueMailTx(ctx context.Context, ex database.Executor, msg *mail.Message, opts ...queue.Option) error {
q, payload, err := a.mailJob(msg)
if err != nil {
return err
}
return q.DispatchKindTx(ctx, ex, MailJobKind, payload, opts...)
}
// mailJob seals msg into a MailJobKind payload.
func (a *App) mailJob(msg *mail.Message) (*queue.Queue, map[string]string, error) {
plain, err := json.Marshal(msg) //nolint:musttag // Go field names, as mail jobs always used
if err != nil {
return nil, nil, fmt.Errorf("vukem: encode queued mail: %w", err)
}
q, err := a.Queue()
if err != nil {
return nil, nil, err
}
return q, map[string]string{"sealed": a.Crypt.Seal(plain, []byte(mailJobAD))}, nil
}
func (a *App) sendQueuedMail(ctx context.Context, p queuedMail) error {
m, err := a.Mailer()
if err != nil {
return err
}
msg := p.Message
if p.Sealed == "" {
cfg, err := configLoad[QueueConfig](a)
if err != nil {
return err
}
if !cfg.AllowLegacyMail {
a.Log.WarnContext(
ctx,
"clear-text mail job refused (set QUEUE_ALLOW_LEGACY_MAIL=true to drain jobs queued before v0.24.0)",
)
return ErrLegacyMail
}
a.Log.WarnContext(
ctx,
"clear-text mail job sent (QUEUE_ALLOW_LEGACY_MAIL=true; unset it once old jobs are drained)",
)
} else {
plain, err := a.Crypt.Open(p.Sealed, []byte(mailJobAD))
if err != nil {
return fmt.Errorf("vukem: open queued mail: %w", err)
}
msg = mail.Message{}
if err := json.Unmarshal(plain, &msg); err != nil { //nolint:musttag // see mailJob
return fmt.Errorf("vukem: decode queued mail: %w", err)
}
}
return m.Transport().Send(ctx, &msg)
}
// MailLater renders mailable now and sends it from a queue job: see
// mail.Mailer.SendLater (the app's mailer encrypts the job payload).
func (a *App) MailLater(ctx context.Context, mailable mail.Mailable, opts ...queue.Option) error {
m, err := a.Mailer()
if err != nil {
return err
}
return m.SendLater(ctx, mailable, opts...)
}
// MailLaterTx is MailLater inside the transaction of ex: the mail is
// queued only if the transaction commits (see mail.Mailer.SendLaterTx and
// queue.Queue.DispatchTx).
func (a *App) MailLaterTx(ctx context.Context, ex database.Executor, mailable mail.Mailable,
opts ...queue.Option,
) error {
m, err := a.Mailer()
if err != nil {
return err
}
return m.SendLaterTx(ctx, ex, mailable, opts...)
}
// inServe reports whether serve runs a queue worker: always for memory,
// otherwise unless QUEUE_IN_SERVE=false, never for sync (jobs run inside
// Dispatch). custom is a driver set with WithQueueDriver(Func).
func (c QueueConfig) inServe(custom bool) bool {
switch {
case custom:
return c.InServe
case c.Connection == "memory":
return true
case c.Connection == "sync":
return false
default:
return c.InServe
}
}
// queueRunner works the queue inside the web process, so a
// single-process deploy still runs queued mail and jobs. It exits at once
// when the driver runs jobs inline (a custom sync driver). On shutdown,
// running jobs get SHUTDOWN_TIMEOUT before their context is cancelled.
func (a *App) queueRunner(cfg QueueConfig) Runner {
return RunnerFunc(func(ctx context.Context) error {
q, err := a.Queue()
if err != nil {
return err
}
if in, ok := q.Driver().(queue.Inline); ok && in.Inline() {
return nil
}
limits, err := cfg.QueueLimits()
if err != nil {
return err
}
if cfg.Connection != "memory" {
a.Log.InfoContext(ctx,
"queue worker running inside serve; set QUEUE_IN_SERVE=false if only queue:work should run jobs",
"queues", cfg.QueueNames(), "concurrency", cfg.Concurrency, "limits", limits)
}
return q.Work(ctx, withQueueWork(queue.WorkOptions{
Queues: cfg.QueueNames(),
Concurrency: cfg.Concurrency,
Limits: limits,
StopTimeout: a.Config.ShutdownTimeout,
}, a.queueWork))
})
}
func queueCommands() []Command {
return []Command{
queueWorkCommand(),
queueFailedCommand(),
queueRetryCommand("queue:retry"),
queueRetryCommand("queue:forget"),
}
}
func queueWorkCommand() Command {
var (
queues *string
concurrency *int
once, empty *bool
sleep *time.Duration
)
return CommandFunc{
CommandName: "queue:work",
Desc: "Process queued jobs until stopped (Ctrl+C drains running jobs within SHUTDOWN_TIMEOUT)",
DefineFlags: func(fs *flag.FlagSet) {
queues = fs.String("queue", "", "queues in priority order (default QUEUE_NAMES)")
concurrency = fs.Int("concurrency", 0, "parallel workers (default QUEUE_CONCURRENCY)")
once = fs.Bool("once", false, "process a single job")
empty = fs.Bool("stop-when-empty", false, "exit when no job is available")
sleep = fs.Duration("sleep", time.Second, "wait when the queue is empty")
},
Fn: func(ctx context.Context, app *App, _ []string) error {
// A worker sends queued mail as its normal work, so the
// production MAIL_MAILER requirement is a boot error here, as
// it is for serve (A81).
if err := app.RequireMailer(); err != nil {
return err
}
cfg, err := configLoad[QueueConfig](app)
if err != nil {
return err
}
if *queues != "" {
cfg.Queues = *queues
}
if *concurrency > 0 {
cfg.Concurrency = *concurrency
}
limits, err := cfg.QueueLimits()
if err != nil {
return err
}
q, err := app.Queue()
if err != nil {
return err
}
if _, ok := q.Driver().(queue.Sync); ok {
return errSyncWork
}
o := queue.WorkOptions{
Queues: cfg.QueueNames(),
Concurrency: cfg.Concurrency,
Limits: limits,
Sleep: *sleep,
StopWhenEmpty: *empty,
StopTimeout: app.Config.ShutdownTimeout,
}
if *once {
o.MaxJobs, o.Concurrency, o.StopWhenEmpty = 1, 1, true
}
app.Log.InfoContext(ctx, "queue worker started", "queues", o.Queues, "concurrency", o.Concurrency,
"limits", o.Limits)
return q.Work(ctx, o)
},
}
}
// ErrNoFailedStore is returned by the failed-job commands for drivers that
// do not keep failed jobs.
var ErrNoFailedStore = errors.New("vukem: the queue driver does not keep failed jobs (use QUEUE_CONNECTION=database)")
// errSyncWork stops queue:work on the sync driver, which would otherwise
// poll an always-empty queue forever.
var errSyncWork = errors.New("vukem: QUEUE_CONNECTION=sync runs jobs during Dispatch, " +
"so queue:work has nothing to process (use QUEUE_CONNECTION=database for a separate worker)")
func failedStore(app *App) (queue.FailedStore, error) {
q, err := app.Queue()
if err != nil {
return nil, err
}
switch d := q.Driver().(type) {
case queue.FailedStore:
return d, nil
case *queue.Memory:
// Its failed jobs live in the serving process; a command runs in
// its own process and would always print an empty list.
return nil, fmt.Errorf("vukem: the memory queue (QUEUE_CONNECTION=memory) keeps failed jobs "+
"inside the process that ran them, out of reach of this command: %w", ErrNoFailedStore)
case queue.Sync:
return nil, fmt.Errorf("vukem: QUEUE_CONNECTION=sync returns job errors to Dispatch "+
"and keeps no failed jobs: %w", ErrNoFailedStore)
default:
return nil, ErrNoFailedStore
}
}
func queueFailedCommand() Command {
var (
asJSON *bool
limit *int
)
return CommandFunc{
CommandName: "queue:failed",
Desc: "List failed jobs",
DefineFlags: func(fs *flag.FlagSet) {
asJSON = fs.Bool("json", false, "print JSON")
limit = fs.Int("limit", 100, "list at most this many jobs; 0 lists all")
},
Fn: func(ctx context.Context, app *App, _ []string) error {
fs, err := failedStore(app)
if err != nil {
return err
}
var jobs []queue.FailedJob
if pager, ok := fs.(queue.FailedPager); ok {
jobs, err = pager.FailedPage(ctx, *limit)
} else {
jobs, err = fs.Failed(ctx)
}
if err != nil {
return err
}
if *asJSON {
enc := json.NewEncoder(app.stdout)
enc.SetIndent("", " ")
return enc.Encode(jobs)
}
tw := tabwriter.NewWriter(app.stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tQUEUE\tKIND\tATTEMPTS\tFAILED AT\tERROR")
for i := range jobs {
j := &jobs[i]
msg, _, _ := strings.Cut(j.LastError, "\n")
fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t%s\t%s\n", j.ID, j.Queue, j.Kind, j.Attempts,
j.FailedAt.Format(time.RFC3339), msg)
}
return tw.Flush()
},
}
}
func queueRetryCommand(name string) Command {
desc := "Re-queue failed jobs: IDs or all"
if name == "queue:forget" {
desc = "Delete failed jobs: IDs or all"
}
return CommandFunc{
CommandName: name,
Desc: desc,
Fn: func(ctx context.Context, app *App, args []string) error {
if len(args) == 0 {
return fmt.Errorf("%s needs job IDs or \"all\"", name)
}
if len(args) == 1 && args[0] == "all" {
args = nil
}
fs, err := failedStore(app)
if err != nil {
return err
}
act, verb := fs.Retry, "re-queued"
if name == "queue:forget" {
act, verb = fs.Forget, "deleted"
}
n, err := act(ctx, args...)
if err != nil {
return err
}
fmt.Fprintf(app.stdout, "%d failed job(s) %s\n", n, verb)
return nil
},
}
}
// WithSchedule declares scheduled tasks (generated apps pass
// routes.Schedule).
func WithSchedule(fn func(s *schedule.Schedule, app *App)) Option {
return func(o *options) error { o.schedules = append(o.schedules, fn); return nil }
}
// ScheduleConfig is read from SCHEDULE_* variables.
type ScheduleConfig struct {
// Timezone of the expressions (IANA name, default UTC).
Timezone string `env:"SCHEDULE_TIMEZONE" default:"UTC"`
// InServe runs the scheduler inside serve. Set it to false when a
// dedicated schedule:work process (or a cron calling schedule:run)
// runs the schedule instead.
InServe bool `env:"SCHEDULE_IN_SERVE" default:"true"`
}
// scheduleRunner works the schedule inside the web process, so a
// single-process deploy still runs the built-in prune tasks. It exits at
// once when nothing is scheduled.
func (a *App) scheduleRunner() Runner {
return RunnerFunc(func(ctx context.Context) error {
s, err := a.Schedule()
if err != nil {
return err
}
if len(s.Tasks()) == 0 {
return nil
}
a.Log.InfoContext(ctx,
"scheduler running inside serve; set SCHEDULE_IN_SERVE=false if you run schedule:work",
"tasks", len(s.Tasks()))
return s.Work(ctx, a.now)
})
}
// Schedule returns the application schedule, built on first use. Locks
// for WithoutOverlapping and OnOneServer use App.Cache (set
// CACHE_STORE=database or Redis when several servers run the schedule;
// OnOneServer tasks make the in-process cache an error).
func (a *App) Schedule() (*schedule.Schedule, error) {
a.scheduleOnce.Do(func() {
cfg, err := configLoad[ScheduleConfig](a)
if err != nil {
a.scheduleErr = err
return
}
loc, err := time.LoadLocation(cfg.Timezone)
if err != nil {
a.scheduleErr = fmt.Errorf("vukem: SCHEDULE_TIMEZONE: %w", err)
return
}
locks, err := a.Cache()
if err != nil {
a.scheduleErr = err
return
}
s := schedule.New(schedule.Options{
Location: loc,
Log: a.Log,
Locks: locks,
// Apps sharing a cache store keep their task locks apart.
Namespace: lockNamespace(a.Config.Name),
Commands: a.Call,
Queue: func() (*queue.Queue, error) { return a.Queue() },
// Running tasks share the shutdown budget of the HTTP drain.
StopTimeout: a.Config.ShutdownTimeout,
})
// Database sessions keep expired rows until pruned.
if sess, err := configLoad[SessionConfig](a); err == nil && sess.Driver == "database" {
s.Command("session:prune").Hourly().WithoutOverlapping()
}
// So does the database cache, with one row per rate limit window.
if _, ok := storePruner(locks.Store()); ok {
s.Command("cache:prune").Hourly().WithoutOverlapping()
}
for _, fn := range a.schedules {
fn(s, a)
}
// OnOneServer with the in-process cache would run on every server.
if err := s.Validate(); err != nil {
a.scheduleErr = fmt.Errorf("vukem: %w", err)
return
}
a.schedule = s
})
return a.schedule, a.scheduleErr
}
// Call runs the app command name with args inside the current process (the
// app is already booted), e.g. from a scheduled task.
func (a *App) Call(ctx context.Context, name string, args []string) error {
for _, c := range a.Commands() {
if c.Name() != name {
continue
}
fs := flag.NewFlagSet(name, flag.ContinueOnError)
fs.SetOutput(a.stdout)
c.Flags(fs)
if err := fs.Parse(args); err != nil {
return fmt.Errorf("%s: %w", name, err)
}
return c.Run(ctx, a, fs.Args())
}
return fmt.Errorf("vukem: unknown command %q", name)
}
func scheduleCommands() []Command {
return []Command{
CommandFunc{
CommandName: "schedule:run",
Desc: "Run the scheduled tasks due now (call it every minute from cron)",
Fn: func(ctx context.Context, app *App, _ []string) error {
s, err := app.Schedule()
if err != nil {
return err
}
return s.RunDue(ctx, app.now().Truncate(time.Minute))
},
},
CommandFunc{
CommandName: "schedule:work",
Desc: "Run the scheduler in the foreground (pair with SCHEDULE_IN_SERVE=false on serve)",
Fn: func(ctx context.Context, app *App, _ []string) error {
if err := app.RequireMailer(); err != nil {
return err
}
s, err := app.Schedule()
if err != nil {
return err
}
app.Log.InfoContext(ctx, "scheduler started", "tasks", len(s.Tasks()))
return s.Work(ctx, app.now)
},
},
CommandFunc{
CommandName: "schedule:list",
Desc: "List the scheduled tasks and their next run",
Fn: func(_ context.Context, app *App, _ []string) error {
s, err := app.Schedule()
if err != nil {
return err
}
if len(s.Tasks()) == 0 {
return errors.New("no scheduled tasks (declare them in routes/schedule.go)")
}
tw := tabwriter.NewWriter(app.stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "TASK\tEXPRESSION\tNEXT RUN")
now := app.now()
for _, t := range s.Tasks() {
next := s.Next(t, now)
fmt.Fprintf(tw, "%s\t%s\t%s\n", t.Name(), t.Expression(),
strings.Replace(next.Format(time.RFC3339), "0001-01-01T00:00:00Z", "never", 1))
}
return tw.Flush()
},
},
CommandFunc{
CommandName: "session:prune",
Desc: "Delete expired database sessions (scheduled hourly with SESSION_DRIVER=database)",
Fn: func(ctx context.Context, app *App, _ []string) error {
if _, err := app.Sessions(); err != nil {
return err
}
if app.sessPruner == nil {
fmt.Fprintln(app.stdout, "Sessions are not stored in the database: nothing to prune.")
return nil
}
n, err := app.sessPruner.Prune(ctx)
if err != nil {
return err
}
fmt.Fprintf(app.stdout, "Pruned %d expired sessions.\n", n)
return nil
},
},
CommandFunc{
CommandName: "cache:prune",
Desc: "Delete expired database cache entries (scheduled hourly with CACHE_STORE=database)",
Fn: func(ctx context.Context, app *App, _ []string) error {
c, err := app.Cache()
if err != nil {
return err
}
p, ok := storePruner(c.Store())
if !ok {
fmt.Fprintln(app.stdout, "The cache does not keep expired entries: nothing to prune.")
return nil
}
n, err := p.Prune(ctx)
if err != nil {
return err
}
fmt.Fprintf(app.stdout, "Pruned %d expired cache entries.\n", n)
return nil
},
},
}
}
// pruner is a store that keeps expired rows until pruned (database cache).
type pruner interface {
Prune(ctx context.Context) (int64, error)
}
// storePruner finds the pruner in s, looking through stores that wrap
// another one (metrics, tracing) and expose it with Unwrap.
func storePruner(s cache.Store) (pruner, bool) {
for l := range cache.Layers(s) {
if p, ok := l.(pruner); ok {
return p, true
}
}
return nil, false
}
// lockNamespace turns APP_NAME into a lock key segment: lowercase ASCII
// letters and digits, other runs of characters become one "-".
func lockNamespace(name string) string {
var b strings.Builder
dash := false
for _, r := range strings.ToLower(name) {
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' {
if dash && b.Len() > 0 {
b.WriteByte('-')
}
b.WriteRune(r)
dash = false
continue
}
dash = true
}
if b.Len() == 0 {
return "app"
}
return b.String()
}