-
Notifications
You must be signed in to change notification settings - Fork 172
/
context_test.go
635 lines (538 loc) · 14.9 KB
/
context_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
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
package goka
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/IBM/sarama"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"github.com/lovoo/goka/codec"
)
func newEmitter(err error, done func(err error)) emitter {
return func(topic string, key string, value []byte, headers Headers) *Promise {
p := NewPromise()
if done != nil {
p.Then(done)
}
return p.finish(nil, err)
}
}
func newEmitterW(wg *sync.WaitGroup, err error, done func(err error)) emitter {
return func(topic string, key string, value []byte, headers Headers) *Promise {
wg.Add(1)
p := NewPromise()
if done != nil {
p.Then(done)
}
return p.finish(nil, err)
}
}
func TestContext_Emit(t *testing.T) {
var (
ack = 0
emitted = 0
group Group = "some-group"
)
ctx := &cbContext{
graph: DefineGroup(group),
commit: func() { ack++ },
wg: &sync.WaitGroup{},
trackOutputStats: func(ctx context.Context, topic string, size int) {},
}
// after that the message is processed
ctx.emitter = newEmitter(nil, func(err error) {
emitted++
require.NoError(t, err)
})
ctx.start()
ctx.emit("emit-topic", "key", []byte("value"), nil)
ctx.finish(nil)
// we can now for all callbacks -- it should also guarantee a memory fence
// to the emitted variable (which is not being locked)
ctx.wg.Wait()
// check everything is done
require.Equal(t, 1, emitted)
require.Equal(t, 1, ack)
}
func TestContext_DeferCommit(t *testing.T) {
var (
ack = 0
group Group = "some-group"
)
ctx := &cbContext{
graph: DefineGroup(group),
commit: func() { ack++ },
wg: &sync.WaitGroup{},
trackOutputStats: func(ctx context.Context, topic string, size int) {},
}
ctx.start()
doneFunc := ctx.DeferCommit()
ctx.finish(nil)
// ack is not done
require.Equal(t, 0, ack)
doneFunc(nil)
require.Equal(t, 1, ack)
}
func TestContext_DeferCommit_witherror(t *testing.T) {
var (
ack = 0
group Group = "some-group"
errToEmit = errors.New("async error")
)
failer := func(err error) {
require.True(t, strings.Contains(err.Error(), errToEmit.Error()))
}
ctx := &cbContext{
graph: DefineGroup(group),
commit: func() { ack++ },
wg: &sync.WaitGroup{},
trackOutputStats: func(ctx context.Context, topic string, size int) {},
asyncFailer: failer,
msg: &message{
key: "testKey",
},
}
ctx.start()
doneFunc := ctx.DeferCommit()
ctx.finish(nil)
// ack is not done
require.Equal(t, 0, ack)
doneFunc(fmt.Errorf("async error"))
// no commit, no ack, so we'll get the message again.
require.Equal(t, 0, ack)
require.Contains(t, ctx.errors.ErrorOrNil().Error(), "async error")
}
func TestContext_Timestamp(t *testing.T) {
ts := time.Now()
ctx := &cbContext{
msg: &message{
timestamp: ts,
},
}
require.Equal(t, ts, ctx.Timestamp())
}
func TestContext_EmitError(t *testing.T) {
var (
ack = 0
emitted = 0
errToEmit = errors.New("some error")
group Group = "some-group"
)
failer := func(err error) {
require.True(t, strings.Contains(err.Error(), errToEmit.Error()))
}
// test error case
ctx := &cbContext{
graph: DefineGroup(group, Persist(new(codec.String))),
wg: &sync.WaitGroup{},
trackOutputStats: func(ctx context.Context, topic string, size int) {},
syncFailer: failer,
asyncFailer: failer,
msg: &message{
key: "testKey",
},
}
ctx.emitter = newEmitter(errToEmit, func(err error) {
emitted++
require.Error(t, err)
require.Equal(t, errToEmit, err)
})
ctx.start()
ctx.emit("emit-topic", ctx.Key(), []byte("value"), nil)
ctx.finish(nil)
// we can now for all callbacks -- it should also guarantee a memory fence
// to the emitted variable (which is not being locked)
ctx.wg.Wait()
// check everything is done
require.Equal(t, 1, emitted)
// nothing should be committed here
require.Equal(t, 0, ack)
}
func TestContext_EmitToStateTopic(t *testing.T) {
var group Group = "some-group"
ctx := &cbContext{
graph: DefineGroup(group, Persist(c), Loop(c, cb)),
syncFailer: func(err error) { panic(err) },
}
require.PanicsWithError(t,
"cannot emit to table topic (use SetValue instead)",
func() { ctx.Emit(Stream(tableName(group)), "key", []byte("value")) },
)
require.PanicsWithError(t, "cannot emit to loop topic (use Loopback instead)",
func() { ctx.Emit(Stream(loopName(group)), "key", []byte("value")) },
)
require.PanicsWithError(t, "cannot emit to empty topic",
func() { ctx.Emit("", "key", []byte("value")) },
)
}
func TestContext_GetSetStateless(t *testing.T) {
// ctx stateless since no storage passed
ctx := &cbContext{
graph: DefineGroup("group"),
msg: new(message),
syncFailer: func(err error) { panic(err) },
}
require.PanicsWithError(t, "Cannot access state in stateless processor", func() { ctx.Value() })
require.PanicsWithError(t, "Cannot access state in stateless processor", func() { ctx.SetValue("whatever") })
}
func TestContext_Delete(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
offset = int64(123)
key = "key"
ack = 0
group Group = "some-group"
st = NewMockStorage(ctrl)
pt = &PartitionTable{
st: &storageProxy{
Storage: st,
},
stats: newTableStats(),
}
)
st.EXPECT().Delete(key).Return(nil)
ctx := &cbContext{
graph: DefineGroup(group, Persist(new(codec.String))),
wg: new(sync.WaitGroup),
commit: func() { ack++ },
msg: &message{offset: offset},
table: pt,
}
ctx.emitter = newEmitter(nil, nil)
ctx.start()
err := ctx.deleteKey(key, nil)
require.NoError(t, err)
ctx.finish(nil)
ctx.wg.Wait()
require.Equal(t, ctx.counters, struct {
emits int
dones int
stores int
}{1, 1, 1})
}
func TestContext_DeleteStateless(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
offset = int64(123)
key = "key"
group Group = "some-group"
)
ctx := &cbContext{
graph: DefineGroup(group),
wg: new(sync.WaitGroup),
msg: &message{offset: offset},
}
ctx.emitter = newEmitter(nil, nil)
err := ctx.deleteKey(key, nil)
require.True(t, strings.Contains(err.Error(), "Cannot access state in stateless processor"))
}
func TestContext_DeleteStorageError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
offset = int64(123)
key = "key"
group Group = "some-group"
st = NewMockStorage(ctrl)
pt = &PartitionTable{
st: &storageProxy{
Storage: st,
},
stats: newTableStats(),
}
retErr = errors.New("storage error")
)
st.EXPECT().Delete(key).Return(retErr)
ctx := &cbContext{
graph: DefineGroup(group, Persist(new(codec.String))),
wg: new(sync.WaitGroup),
msg: &message{offset: offset},
table: pt,
}
ctx.emitter = newEmitter(nil, nil)
err := ctx.deleteKey(key, nil)
require.True(t, strings.Contains(err.Error(), "error deleting key (key) from storage: storage error"))
}
func TestContext_Set(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
offset = int64(123)
ack = 0
key = "key"
value = "value"
group Group = "some-group"
st = NewMockStorage(ctrl)
pt = &PartitionTable{
st: &storageProxy{
Storage: st,
},
stats: newTableStats(),
}
)
st.EXPECT().Set(key, []byte(value)).Return(nil)
ctx := &cbContext{
graph: DefineGroup(group, Persist(new(codec.String))),
wg: new(sync.WaitGroup),
commit: func() { ack++ },
trackOutputStats: func(ctx context.Context, topic string, size int) {},
msg: &message{key: key, offset: offset},
table: pt,
ctx: context.Background(),
}
ctx.emitter = newEmitter(nil, nil)
ctx.start()
err := ctx.setValueForKey(key, value, nil)
require.NoError(t, err)
ctx.finish(nil)
ctx.wg.Wait()
require.Equal(t, ctx.counters, struct {
emits int
dones int
stores int
}{1, 1, 1})
require.Equal(t, 1, ack)
}
func TestContext_GetSetStateful(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
group Group = "some-group"
key = "key"
value = "value"
headers = Headers{"key": []byte("headerValue")}
offset = int64(123)
wg = new(sync.WaitGroup)
st = NewMockStorage(ctrl)
pt = &PartitionTable{
st: &storageProxy{
Storage: st,
},
state: newPartitionTableState().SetState(State(PartitionRunning)),
stats: newTableStats(),
}
)
st.EXPECT().Get(key).Return(nil, nil)
st.EXPECT().Set(key, []byte(value)).Return(nil)
st.EXPECT().Get(key).Return([]byte(value), nil)
graph := DefineGroup(group, Persist(new(codec.String)))
ctx := &cbContext{
table: pt,
wg: wg,
graph: graph,
trackOutputStats: func(ctx context.Context, topic string, size int) {},
msg: &message{key: key, offset: offset},
emitter: func(tp string, k string, v []byte, h Headers) *Promise {
wg.Add(1)
require.Equal(t, graph.GroupTable().Topic(), tp)
require.Equal(t, key, string(k))
require.Equal(t, value, string(v))
require.Equal(t, headers, h)
return NewPromise().finish(nil, nil)
},
ctx: context.Background(),
}
val := ctx.Value()
require.True(t, val == nil)
ctx.SetValue(value, WithCtxEmitHeaders(headers))
val = ctx.Value()
require.Equal(t, value, val)
}
func TestContext_SetErrors(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
group Group = "some-group"
key = "key"
value = "value"
offset int64 = 123
wg = new(sync.WaitGroup)
st = NewMockStorage(ctrl)
pt = &PartitionTable{
st: &storageProxy{
Storage: st,
},
stats: newTableStats(),
}
failed error
_ = failed // make linter happy
)
failer := func(err error) { failed = err }
ctx := &cbContext{
table: pt,
trackOutputStats: func(ctx context.Context, topic string, size int) {},
wg: wg,
graph: DefineGroup(group, Persist(new(codec.String))),
msg: &message{key: key, offset: offset},
syncFailer: failer,
asyncFailer: failer,
}
err := ctx.setValueForKey(key, nil, nil)
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "cannot set nil"))
err = ctx.setValueForKey(key, 123, nil) // cannot encode 123 as string
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "error encoding"))
st.EXPECT().Set(key, []byte(value)).Return(errors.New("some-error"))
err = ctx.setValueForKey(key, value, nil)
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "some-error"))
// TODO(jb): check if still valid
// finish with error
// ctx.emitter = newEmitterW(wg, fmt.Errorf("some-error"), func(err error) {
// require.Error(t, err)
// require.True(t, strings.Contains(err.Error(), "some-error"))
// })
// err = ctx.setValueForKey(key, value)
// require.NoError(t, err)
}
func TestContext_LoopbackNoLoop(t *testing.T) {
// ctx has no loop set
ctx := &cbContext{
graph: DefineGroup("group", Persist(c)),
msg: &message{},
syncFailer: func(err error) { panic(err) },
}
require.PanicsWithError(t, "no loop topic configured", func() {
ctx.Loopback("some-key", "whatever")
})
}
func TestContext_Loopback(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
key = "key"
value = "value"
headers = Headers{"key": []byte("headerValue")}
cnt = 0
)
graph := DefineGroup("group", Persist(c), Loop(c, cb))
ctx := &cbContext{
graph: graph,
msg: &message{},
trackOutputStats: func(ctx context.Context, topic string, size int) {},
emitter: func(tp string, k string, v []byte, h Headers) *Promise {
cnt++
require.Equal(t, graph.LoopStream().Topic(), tp)
require.Equal(t, key, string(k))
require.Equal(t, value, string(v))
require.Equal(t, headers, h)
return NewPromise()
},
}
ctx.Loopback(key, value, WithCtxEmitHeaders(headers))
require.True(t, cnt == 1)
}
func TestContext_Join(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
key = "key"
value = "value"
table Table = "table"
errSome = errors.New("some-error")
st = NewMockStorage(ctrl)
)
ctx := &cbContext{
graph: DefineGroup("group", Persist(c), Loop(c, cb), Join(table, c)),
msg: &message{key: key},
pviews: map[string]*PartitionTable{
string(table): {
log: defaultLogger,
st: &storageProxy{
Storage: st,
},
stats: newTableStats(),
},
},
syncFailer: func(err error) { panic(err) },
}
st.EXPECT().Get(key).Return([]byte(value), nil)
v := ctx.Join(table)
require.Equal(t, value, v)
st.EXPECT().Get(key).Return(nil, errSome)
require.Panics(t, func() { ctx.Join(table) })
require.Panics(t, func() { ctx.Join("other-table") })
ctx.pviews = nil
require.Panics(t, func() { ctx.Join(table) })
}
func TestContext_Lookup(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
key = "key"
value = "value"
table Table = "table"
errSome = errors.New("some-error")
st = NewMockStorage(ctrl)
)
ctx := &cbContext{
graph: DefineGroup("group", Persist(c), Loop(c, cb)),
msg: &message{key: key},
views: map[string]*View{
string(table): {
state: newViewSignal().SetState(State(ViewStateRunning)),
opts: &voptions{
tableCodec: c,
hasher: DefaultHasher(),
},
partitions: []*PartitionTable{
{
st: &storageProxy{
Storage: st,
},
state: newPartitionTableState().SetState(State(PartitionRunning)),
stats: newTableStats(),
},
},
},
},
syncFailer: func(err error) { panic(err) },
}
st.EXPECT().Get(key).Return([]byte(value), nil)
v := ctx.Lookup(table, key)
require.Equal(t, value, v)
st.EXPECT().Get(key).Return(nil, errSome)
require.Panics(t, func() { ctx.Lookup(table, key) })
require.Panics(t, func() { ctx.Lookup("other-table", key) })
ctx.views = nil
require.Panics(t, func() { ctx.Lookup(table, key) })
}
func TestContext_Headers(t *testing.T) {
// context without headers will return empty map
ctx := &cbContext{
msg: &message{
key: "key",
},
}
headers := ctx.Headers()
require.NotNil(t, headers)
require.Equal(t, 0, len(headers))
ctx = &cbContext{
msg: &message{
key: "key",
headers: []*sarama.RecordHeader{
{
Key: []byte("key"),
Value: []byte("value"),
},
},
},
}
headers = ctx.Headers()
require.Equal(t, []byte("value"), headers["key"])
}
func TestContext_Fail(t *testing.T) {
ctx := &cbContext{
syncFailer: func(err error) {
panic(fmt.Errorf("%#v", err))
},
}
require.Panics(t, func() { ctx.Fail(errors.New("blubb")) })
}