-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathproducer_test.go
302 lines (240 loc) · 8.37 KB
/
producer_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
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
package river
import (
"context"
"encoding/json"
"fmt"
"slices"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/riverqueue/river/internal/componentstatus"
"github.com/riverqueue/river/internal/dbadapter"
"github.com/riverqueue/river/internal/dbsqlc"
"github.com/riverqueue/river/internal/jobcompleter"
"github.com/riverqueue/river/internal/notifier"
"github.com/riverqueue/river/internal/rivercommon"
"github.com/riverqueue/river/internal/riverinternaltest"
)
func Test_Producer_CanSafelyCompleteJobsWhileFetchingNewOnes(t *testing.T) {
// We have encountered previous data races with the list of active jobs on
// Producer because we need to know the count of active jobs in order to
// determine how many we can fetch for the next batch, while we're managing
// the map of active jobs in a different goroutine.
//
// This test attempts to exercise that race condition so that the race
// detector can tell us if we're protected against it.
t.Parallel()
ctx := context.Background()
require := require.New(t)
dbPool := riverinternaltest.TestDB(ctx, t)
const maxJobCount = 10000
// This doesn't strictly mean that there are no more jobs left to process,
// merely that the final job we inserted is now being processed, which is
// close enough for our purposes here.
lastJobRun := make(chan struct{})
archetype := riverinternaltest.BaseServiceArchetype(t)
adapter := dbadapter.NewStandardAdapter(archetype, &dbadapter.StandardAdapterConfig{
Executor: dbPool,
WorkerName: "producer_test_worker",
})
completer := jobcompleter.NewInlineCompleter(archetype, adapter)
t.Cleanup(completer.Wait)
type WithJobNumArgs struct {
JobArgsReflectKind[WithJobNumArgs]
JobNum int `json:"job_num"`
}
workers := NewWorkers()
AddWorker(workers, WorkFunc(func(ctx context.Context, job *Job[WithJobNumArgs]) error {
var jobArgs WithJobNumArgs
require.NoError(json.Unmarshal(job.EncodedArgs, &jobArgs))
if jobArgs.JobNum == maxJobCount-1 {
select {
case <-ctx.Done():
case lastJobRun <- struct{}{}:
}
}
return nil
}))
ignoreNotifierStatusUpdates := func(componentstatus.Status) {}
notifier := notifier.New(archetype, dbPool.Config().ConnConfig, ignoreNotifierStatusUpdates)
config := &producerConfig{
ErrorHandler: newTestErrorHandler(),
// Fetch constantly to more aggressively trigger the potential data race:
FetchCooldown: time.Millisecond,
FetchPollInterval: time.Millisecond,
JobTimeout: DefaultJobTimeout,
MaxWorkerCount: 1000,
Notifier: notifier,
QueueName: rivercommon.DefaultQueue,
RetryPolicy: &DefaultClientRetryPolicy{},
WorkerName: "fakeWorkerNameTODO",
Workers: workers,
}
producer, err := newProducer(archetype, adapter, completer, config)
require.NoError(err)
params := make([]*dbadapter.JobInsertParams, maxJobCount)
for i := range params {
insertParams, err := insertParamsFromArgsAndOptions(WithJobNumArgs{JobNum: i}, nil)
require.NoError(err)
params[i] = insertParams
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
t.Cleanup(cancel)
go func() {
// The producer should never exceed its MaxWorkerCount. If it does, panic so
// we can get a trace.
for {
select {
case <-ctx.Done():
return
default:
}
numActiveJobs := producer.numJobsActive.Load()
if numActiveJobs > int32(config.MaxWorkerCount) {
panic(fmt.Sprintf("producer exceeded MaxWorkerCount=%d, actual count=%d", config.MaxWorkerCount, numActiveJobs))
}
}
}()
_, err = adapter.JobInsertMany(ctx, params)
require.NoError(err)
ignoreStatusUpdates := func(queue string, status componentstatus.Status) {}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
producer.Run(ctx, ctx, ignoreStatusUpdates)
wg.Done()
}()
select {
case <-lastJobRun:
t.Logf("Last job reported in; cancelling context")
cancel()
case <-ctx.Done():
t.Error("timed out waiting for last job to run")
}
wg.Wait()
}
func Test_Producer_Run(t *testing.T) {
t.Parallel()
ctx := context.Background()
type testBundle struct {
adapter *dbadapter.StandardAdapter
completer jobcompleter.JobCompleter
jobUpdates chan jobcompleter.CompleterJobUpdated
workers *Workers
}
setup := func(t *testing.T) (*producer, *testBundle) {
t.Helper()
dbPool := riverinternaltest.TestDB(ctx, t)
archetype := riverinternaltest.BaseServiceArchetype(t)
adapter := dbadapter.NewStandardAdapter(archetype, &dbadapter.StandardAdapterConfig{
Executor: dbPool,
WorkerName: "producer_test_worker",
})
completer := jobcompleter.NewInlineCompleter(archetype, adapter)
jobUpdates := make(chan jobcompleter.CompleterJobUpdated, 10)
completer.Subscribe(func(update jobcompleter.CompleterJobUpdated) {
jobUpdates <- update
})
workers := NewWorkers()
notifier := notifier.New(archetype, dbPool.Config().ConnConfig, func(componentstatus.Status) {})
config := &producerConfig{
ErrorHandler: newTestErrorHandler(),
FetchCooldown: DefaultFetchCooldown,
FetchPollInterval: 50 * time.Millisecond, // more aggressive than normal so in case we miss the event, tests still pass quickly
JobTimeout: DefaultJobTimeout,
MaxWorkerCount: 1000,
Notifier: notifier,
QueueName: rivercommon.DefaultQueue,
RetryPolicy: &DefaultClientRetryPolicy{},
WorkerName: "fakeWorkerNameTODO",
Workers: workers,
}
producer, err := newProducer(archetype, adapter, completer, config)
require.NoError(t, err)
return producer, &testBundle{
adapter: adapter,
completer: completer,
jobUpdates: jobUpdates,
workers: workers,
}
}
mustInsert := func(ctx context.Context, t *testing.T, adapter dbadapter.Adapter, args JobArgs) {
t.Helper()
insertParams, err := insertParamsFromArgsAndOptions(args, nil)
require.NoError(t, err)
_, err = adapter.JobInsert(ctx, insertParams)
require.NoError(t, err)
}
t.Run("NoOp", func(t *testing.T) {
t.Parallel()
producer, _ := setup(t)
fetchCtx, fetchCtxDone := context.WithCancel(ctx)
var wg sync.WaitGroup
wg.Add(1)
go func() {
producer.Run(fetchCtx, ctx, func(queue string, status componentstatus.Status) {})
wg.Done()
}()
fetchCtxDone()
wg.Wait()
})
t.Run("SimpleJob", func(t *testing.T) {
t.Parallel()
producer, bundle := setup(t)
fetchCtx, fetchCtxDone := context.WithCancel(ctx)
AddWorker(bundle.workers, &noOpWorker{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
producer.Run(fetchCtx, ctx, func(queue string, status componentstatus.Status) {})
wg.Done()
}()
// LIFO, so guarantee run loop finishes and producer exits, even in the
// event of a test failure.
t.Cleanup(wg.Wait)
t.Cleanup(fetchCtxDone)
mustInsert(ctx, t, bundle.adapter, &noOpArgs{})
update := riverinternaltest.WaitOrTimeout(t, bundle.jobUpdates)
require.Equal(t, dbsqlc.JobStateCompleted, update.Job.State)
})
t.Run("UnknownJobKind", func(t *testing.T) {
t.Parallel()
producer, bundle := setup(t)
fetchCtx, fetchCtxDone := context.WithCancel(ctx)
AddWorker(bundle.workers, &noOpWorker{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
producer.Run(fetchCtx, ctx, func(queue string, status componentstatus.Status) {})
wg.Done()
}()
// LIFO, so guarantee run loop finishes and producer exits, even in the
// event of a test failure.
t.Cleanup(wg.Wait)
t.Cleanup(fetchCtxDone)
mustInsert(ctx, t, bundle.adapter, &noOpArgs{})
mustInsert(ctx, t, bundle.adapter, &callbackArgs{}) // not registered
updates := riverinternaltest.WaitOrTimeoutN(t, bundle.jobUpdates, 2)
// Print updated jobs for debugging.
for _, update := range updates {
t.Logf("Job: %+v", update.Job)
}
// Order jobs come back in is not guaranteed, which is why this is
// written somewhat strangely.
findJob := func(kind string) *dbsqlc.RiverJob {
index := slices.IndexFunc(updates, func(u jobcompleter.CompleterJobUpdated) bool { return u.Job.Kind == kind })
require.NotEqualf(t, -1, index, "Job update not found", "Job update not found for kind: %s", kind)
return updates[index].Job
}
{
job := findJob((&callbackArgs{}).Kind())
require.Equal(t, dbsqlc.JobStateRetryable, job.State)
require.Equal(t, (&UnknownJobKindError{Kind: (&callbackArgs{}).Kind()}).Error(), job.Errors[0].Error)
}
{
job := findJob((&noOpArgs{}).Kind())
require.Equal(t, dbsqlc.JobStateCompleted, job.State)
}
})
}