forked from riverqueue/river
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_job_cancel_test.go
82 lines (66 loc) · 2.06 KB
/
example_job_cancel_test.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
package river_test
import (
"context"
"fmt"
"log/slog"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/riverqueue/river"
"github.com/riverqueue/river/internal/riverinternaltest"
"github.com/riverqueue/river/internal/util/slogutil"
"github.com/riverqueue/river/riverdriver/riverpgxv5"
)
type CancellingArgs struct {
ShouldCancel bool
}
func (args CancellingArgs) Kind() string { return "Cancelling" }
type CancellingWorker struct {
river.WorkerDefaults[CancellingArgs]
}
func (w *CancellingWorker) Work(ctx context.Context, j *river.Job[CancellingArgs]) error {
if j.Args.ShouldCancel {
fmt.Println("cancelling job")
return river.JobCancel(fmt.Errorf("this wrapped error message will be persisted to DB"))
}
return nil
}
// Example_jobCancel demonstrates how to permanently cancel a job from within
// Work using JobCancel.
func Example_jobCancel() { //nolint:dupl
ctx := context.Background()
dbPool, err := pgxpool.NewWithConfig(ctx, riverinternaltest.DatabaseConfig("river_testdb_example"))
if err != nil {
panic(err)
}
defer dbPool.Close()
// Required for the purpose of this test, but not necessary in real usage.
if err := riverinternaltest.TruncateRiverTables(ctx, dbPool); err != nil {
panic(err)
}
workers := river.NewWorkers()
river.AddWorker(workers, &CancellingWorker{})
riverClient, err := river.NewClient(riverpgxv5.New(dbPool), &river.Config{
Logger: slog.New(&slogutil.SlogMessageOnlyHandler{Level: slog.LevelWarn}),
Queues: map[string]river.QueueConfig{
river.QueueDefault: {MaxWorkers: 10},
},
Workers: workers,
})
if err != nil {
panic(err)
}
// Not strictly needed, but used to help this test wait until job is worked.
subscribeChan, subscribeCancel := riverClient.Subscribe(river.EventKindJobCancelled)
defer subscribeCancel()
if err := riverClient.Start(ctx); err != nil {
panic(err)
}
if _, err = riverClient.Insert(ctx, CancellingArgs{ShouldCancel: true}, nil); err != nil {
panic(err)
}
waitForNJobs(subscribeChan, 1)
if err := riverClient.Stop(ctx); err != nil {
panic(err)
}
// Output:
// cancelling job
}