Repository navigation
Expand file tree
/
Copy pathtransaction_test.go
More file actions
405 lines (360 loc) · 11.5 KB
/
Copy pathtransaction_test.go
File metadata and controls
405 lines (360 loc) · 11.5 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
package GoEventBus
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
)
// dummy handler just increments a counter
func makeCounterHandler(counter *uint64) HandlerFunc {
return func(ctx context.Context, ev Event) (Result, error) {
atomic.AddUint64(counter, 1)
return Result{Message: "ok"}, nil
}
}
type transactionSelectorFunc func(context.Context, any, []EventCandidate) (EventDecision, error)
func (f transactionSelectorFunc) SelectEvent(
ctx context.Context,
state any,
candidates []EventCandidate,
) (EventDecision, error) {
return f(ctx, state, candidates)
}
type transactionRecordingProvider struct {
published []Event
failAt int
}
func (p *transactionRecordingProvider) Publish(_ context.Context, event Event) error {
if p.failAt > 0 && len(p.published)+1 == p.failAt {
return errors.New("broker publish failed")
}
p.published = append(p.published, event)
return nil
}
func (p *transactionRecordingProvider) Consume(context.Context, EventConsumer) error {
return nil
}
func (p *transactionRecordingProvider) Close() error {
return nil
}
func TestTransaction_CommitPublishesToConfiguredProvider(t *testing.T) {
var localCalls uint64
dispatcher := Dispatcher{
"remote": hs(makeCounterHandler(&localCalls)),
}
provider := &transactionRecordingProvider{}
store := NewEventStore(&dispatcher, 8, DropOldest, WithProvider(provider))
t.Cleanup(func() { _ = store.Close(context.Background()) })
tx := store.BeginTransaction()
tx.Publish(Event{ID: "broker-1", Projection: "remote"})
tx.Publish(Event{ID: "broker-2", Projection: "remote"})
if err := tx.Commit(context.Background()); err != nil {
t.Fatalf("Commit: %v", err)
}
if got := atomic.LoadUint64(&localCalls); got != 0 {
t.Fatalf("local handler calls = %d, want 0 before provider consumption", got)
}
if len(provider.published) != 2 {
t.Fatalf("provider publishes = %d, want 2", len(provider.published))
}
if provider.published[0].ID != "broker-1" || provider.published[1].ID != "broker-2" {
t.Fatalf("provider publish order = [%q %q], want [broker-1 broker-2]",
provider.published[0].ID, provider.published[1].ID)
}
if err := tx.Commit(context.Background()); err != nil {
t.Fatalf("second Commit: %v", err)
}
if len(provider.published) != 2 {
t.Fatalf("second Commit republished events: got %d publishes, want 2", len(provider.published))
}
}
func TestTransaction_CommitProviderFailureRetainsOnlyUnpublishedSuffix(t *testing.T) {
provider := &transactionRecordingProvider{failAt: 2}
store := NewEventStore(&Dispatcher{}, 8, DropOldest, WithProvider(provider))
t.Cleanup(func() { _ = store.Close(context.Background()) })
tx := store.BeginTransaction()
tx.Publish(Event{ID: "broker-1", Projection: "remote"})
tx.Publish(Event{ID: "broker-2", Projection: "remote"})
tx.Publish(Event{ID: "broker-3", Projection: "remote"})
if err := tx.Commit(context.Background()); err == nil {
t.Fatal("Commit succeeded, want provider error")
}
if len(provider.published) != 1 || provider.published[0].ID != "broker-1" {
t.Fatalf("published before failure = %#v, want only broker-1", provider.published)
}
provider.failAt = 0
if err := tx.Commit(context.Background()); err != nil {
t.Fatalf("retry Commit: %v", err)
}
if len(provider.published) != 3 {
t.Fatalf("provider publishes after retry = %d, want 3", len(provider.published))
}
for i, want := range []string{"broker-1", "broker-2", "broker-3"} {
if provider.published[i].ID != want {
t.Fatalf("provider publish %d = %q, want %q", i, provider.published[i].ID, want)
}
}
}
func TestTransaction_DecideAndPublishWithJev(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("method = %s, want POST", r.Method)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"model":"typesafe/jev-1.13",
"id":"tx-jev-test",
"answers":{
"event_type":{
"type":"choice",
"choice":"invoice_created",
"probabilities":{"invoice_created":0.96,"order_created":0.04},
"confidence":0.92
}
}
}`))
}))
defer server.Close()
var processed uint64
var gotProjection any
dispatcher := Dispatcher{}
dispatcher.Register("invoice.created", func(_ context.Context, event Event) (Result, error) {
gotProjection = event.Projection
atomic.AddUint64(&processed, 1)
return Result{Message: "ok"}, nil
})
store := NewEventStore(&dispatcher, 8, DropOldest)
t.Cleanup(func() { _ = store.Close(context.Background()) })
tx := store.BeginTransaction()
selector := &JevSelector{
APIKey: "test-key",
Endpoint: server.URL,
Client: server.Client(),
}
decision, err := tx.DecideAndPublish(
context.Background(),
selector,
map[string]any{"message": "create an invoice for order 42"},
Event{ID: "evt-jev-tx", Data: map[string]any{"order_id": "42"}},
[]EventCandidate{
{
Key: "order_created",
Projection: "order.created",
Description: "A new order should be created",
},
{
Key: "invoice_created",
Projection: "invoice.created",
Description: "An invoice should be created",
},
},
)
if err != nil {
t.Fatalf("DecideAndPublish: %v", err)
}
if decision.Choice != "invoice_created" {
t.Fatalf("choice = %q, want invoice_created", decision.Choice)
}
if decision.Projection != "invoice.created" {
t.Fatalf("projection = %#v, want invoice.created", decision.Projection)
}
if decision.RequestID != "tx-jev-test" {
t.Fatalf("request ID = %q, want tx-jev-test", decision.RequestID)
}
if got := atomic.LoadUint64(&processed); got != 0 {
t.Fatalf("handler ran before Commit: %d", got)
}
if err := tx.Commit(context.Background()); err != nil {
t.Fatalf("Commit: %v", err)
}
if got := atomic.LoadUint64(&processed); got != 1 {
t.Fatalf("processed = %d, want 1", got)
}
if gotProjection != "invoice.created" {
t.Fatalf("handler projection = %#v, want invoice.created", gotProjection)
}
}
func TestTransaction_DecideAndPublishRollback(t *testing.T) {
var processed uint64
dispatcher := Dispatcher{
"selected": hs(makeCounterHandler(&processed)),
}
store := NewEventStore(&dispatcher, 8, DropOldest)
t.Cleanup(func() { _ = store.Close(context.Background()) })
selector := transactionSelectorFunc(func(
context.Context,
any,
[]EventCandidate,
) (EventDecision, error) {
return EventDecision{Choice: "selected", Confidence: 1}, nil
})
tx := store.BeginTransaction()
if _, err := tx.DecideAndPublish(
context.Background(),
selector,
"state",
Event{ID: "routed"},
[]EventCandidate{{Key: "selected", Projection: "selected"}},
); err != nil {
t.Fatalf("DecideAndPublish: %v", err)
}
tx.Rollback()
if err := tx.Commit(context.Background()); err != nil {
t.Fatalf("Commit after Rollback: %v", err)
}
if got := atomic.LoadUint64(&processed); got != 0 {
t.Fatalf("processed = %d after Rollback, want 0", got)
}
}
func TestTransaction_DecideAndPublishErrorDoesNotBuffer(t *testing.T) {
var processed uint64
dispatcher := Dispatcher{
"known": hs(makeCounterHandler(&processed)),
}
store := NewEventStore(&dispatcher, 8, DropOldest)
t.Cleanup(func() { _ = store.Close(context.Background()) })
selector := transactionSelectorFunc(func(
context.Context,
any,
[]EventCandidate,
) (EventDecision, error) {
return EventDecision{Choice: "unknown"}, nil
})
tx := store.BeginTransaction()
_, err := tx.DecideAndPublish(
context.Background(),
selector,
"state",
Event{ID: "bad"},
[]EventCandidate{{Key: "known", Projection: "known"}},
)
if !errors.Is(err, ErrUnknownEventChoice) {
t.Fatalf("error = %v, want ErrUnknownEventChoice", err)
}
if err := tx.Commit(context.Background()); err != nil {
t.Fatalf("Commit: %v", err)
}
if got := atomic.LoadUint64(&processed); got != 0 {
t.Fatalf("failed decision buffered an event: processed = %d", got)
}
}
func TestTransaction_CommitAndRollback(t *testing.T) {
// set up dispatcher with a no-op projection
var processed uint64
dispatcher := Dispatcher{
"p": hs(makeCounterHandler(&processed)),
}
es := NewEventStore(&dispatcher, 8, DropOldest)
ctx := context.Background()
// Test Commit
tx := es.BeginTransaction()
tx.Publish(Event{ID: "1", Projection: "p", Args: map[string]any{}})
tx.Publish(Event{ID: "2", Projection: "p", Args: map[string]any{}})
if err := tx.Commit(ctx); err != nil {
t.Fatalf("Commit failed: %v", err)
}
// actually publish into store
es.Publish()
if got := atomic.LoadUint64(&processed); got != 2 {
t.Errorf("expected 2 events processed, got %d", got)
}
// Test Rollback
processed = 0
tx2 := es.BeginTransaction()
tx2.Publish(Event{ID: "3", Projection: "p", Args: map[string]any{}})
tx2.Rollback()
if err := tx2.Commit(ctx); err != nil {
t.Fatalf("Commit after rollback should not error, got %v", err)
}
es.Publish()
if got := atomic.LoadUint64(&processed); got != 0 {
t.Errorf("expected 0 events after rollback, got %d", got)
}
}
func TestTransaction_RollbackPreservesIndependentStoreEvents(t *testing.T) {
var processed uint64
dispatcher := Dispatcher{
"p": hs(makeCounterHandler(&processed)),
}
store := NewEventStore(&dispatcher, 8, DropOldest)
tx := store.BeginTransaction()
tx.Publish(Event{ID: "transactional", Projection: "p"})
if err := store.Subscribe(context.Background(), Event{ID: "independent", Projection: "p"}); err != nil {
t.Fatalf("Subscribe: %v", err)
}
tx.Rollback()
store.Publish()
if got := atomic.LoadUint64(&processed); got != 1 {
t.Fatalf("Rollback discarded an independent event: processed %d, want 1", got)
}
}
func TestTransaction_PartialFailure(t *testing.T) {
// handler that errors on the second event
cnt := uint64(0)
dispatcher := Dispatcher{
"x": hs(func(ctx context.Context, ev Event) (Result, error) {
i := atomic.AddUint64(&cnt, 1)
if i == 2 {
return Result{}, errors.New("boom")
}
return Result{Message: "ok"}, nil
}),
}
es := NewEventStore(&dispatcher, 4, ReturnError)
ctx := context.Background()
tx := es.BeginTransaction()
tx.Publish(Event{ID: "a", Projection: "x", Args: map[string]any{}})
tx.Publish(Event{ID: "b", Projection: "x", Args: map[string]any{}})
err := tx.Commit(ctx)
if err == nil {
t.Fatal("expected Commit to return error on second event, got nil")
}
if err.Error() != "goeventbus: buffer is full" && err.Error() != "boom" {
// Depending on overrun policy, could bubble Subscribe error or handler error
t.Fatalf("unexpected error: %v", err)
}
}
func BenchmarkTransaction_SyncCommit(b *testing.B) {
dispatcher := Dispatcher{
"p": hs(func(ctx context.Context, ev Event) (Result, error) {
return Result{Message: "ok"}, nil
}),
}
es := NewEventStore(&dispatcher, 256, DropOldest)
es.Async = false
b.ResetTimer()
for i := 0; i < b.N; i++ {
tx := es.BeginTransaction()
// buffer N events per transaction
for j := 0; j < 16; j++ {
tx.Publish(Event{ID: "t", Projection: "p", Args: map[string]any{}})
}
if err := tx.Commit(context.Background()); err != nil {
b.Fatalf("Commit error: %v", err)
}
es.Publish()
}
}
func BenchmarkTransaction_AsyncCommit(b *testing.B) {
dispatcher := Dispatcher{
"p": hs(func(ctx context.Context, ev Event) (Result, error) {
return Result{Message: "ok"}, nil
}),
}
es := NewEventStore(&dispatcher, 256, DropOldest)
es.Async = true
b.ResetTimer()
for i := 0; i < b.N; i++ {
tx := es.BeginTransaction()
for j := 0; j < 16; j++ {
tx.Publish(Event{ID: "t", Projection: "p", Args: map[string]any{}})
}
if err := tx.Commit(context.Background()); err != nil {
b.Fatalf("Commit error: %v", err)
}
es.Publish()
es.Drain(context.Background())
}
}