-
Notifications
You must be signed in to change notification settings - Fork 0
/
function_test.go
501 lines (418 loc) · 13.7 KB
/
function_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
package dispatch_test
import (
"context"
"fmt"
"math/rand/v2"
"strconv"
"strings"
"testing"
"time"
"github.com/dispatchrun/coroutine"
"github.com/dispatchrun/dispatch-go"
"github.com/dispatchrun/dispatch-go/dispatchcoro"
"github.com/dispatchrun/dispatch-go/dispatchproto"
"github.com/dispatchrun/dispatch-go/dispatchtest"
)
func logMode(t *testing.T) {
t.Helper()
if coroutine.Durable {
t.Log("running in durable mode")
} else {
t.Log("running in volatile mode")
}
}
func TestCoroutineReturn(t *testing.T) {
logMode(t)
stringify := dispatch.Func("stringify", func(ctx context.Context, in int) (string, error) {
if in < 0 {
return "", fmt.Errorf("%w: %d", dispatch.ErrInvalidArgument, in)
}
return strconv.Itoa(in), nil
})
runner := dispatchtest.NewRunner(stringify)
output, err := dispatchtest.Call(runner, stringify, 11)
if err != nil {
t.Fatal(err)
} else if output != "11" {
t.Errorf("unexpected output: %s", output)
}
_, err = dispatchtest.Call(runner, stringify, -23)
if err == nil || !strings.Contains(err.Error(), "InvalidArgument: -23") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestCoroutineExit(t *testing.T) {
logMode(t)
stringify := dispatch.Func("stringify", func(ctx context.Context, in int) (string, error) {
var res dispatchproto.Response
if in < 0 {
res = dispatchproto.NewResponseErrorf("%w: %d", dispatch.ErrInvalidArgument, in)
} else {
res = dispatchproto.NewResponse(dispatchproto.String(strconv.Itoa(in)))
}
dispatchcoro.Yield(res)
panic("unreachable")
})
runner := dispatchtest.NewRunner(stringify)
output, err := dispatchtest.Call(runner, stringify, 11)
if err != nil {
t.Fatal(err)
} else if output != "11" {
t.Errorf("unexpected output: %s", output)
}
_, err = dispatchtest.Call(runner, stringify, -23)
if err == nil || !strings.Contains(err.Error(), "InvalidArgument: -23") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestCoroutinePoll(t *testing.T) {
logMode(t)
repeat := dispatch.Func("repeat", func(ctx context.Context, n int) (string, error) {
var repeated string
for i := 0; i < n; i++ {
// Call a mock identity function that returns its input.
call := dispatchproto.NewCall("http://example.com", "identity", dispatchproto.String("x"), dispatchproto.CorrelationID(uint64(i)))
poll := dispatchproto.NewResponse(dispatchproto.NewPoll(1, 2, time.Minute, dispatchproto.Calls(call)))
res := dispatchcoro.Yield(poll)
pollResult, ok := res.PollResult()
if !ok {
return "", fmt.Errorf("expected poll result, got %s", res)
}
callResults := pollResult.Results()
if len(callResults) != 1 {
return "", fmt.Errorf("expected one poll call result, got %s", pollResult)
}
callResult := callResults[0]
if got := callResult.CorrelationID(); got != uint64(i) {
return "", fmt.Errorf("unexpected correlation ID: got %v, want %v", got, uint64(i))
}
output, ok := callResult.Output()
if !ok {
return "", fmt.Errorf("expected call result output, got %s", callResults[0])
}
var s string
if err := output.Unmarshal(&s); err != nil {
return "", fmt.Errorf("unmarshal string: %w", err)
}
repeated += s
}
return repeated, nil
})
runner := dispatchtest.NewRunner(repeat)
// Continously run the coroutine until it returns/exits.
var req dispatchproto.Request = dispatchproto.NewRequest("repeat", dispatchproto.Int(3))
var res dispatchproto.Response
for {
res = runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
if _, done := res.Exit(); done {
break
}
// Check the poll directive.
poll, ok := res.Poll()
if !ok {
t.Fatalf("expected poll response, got %s", res)
}
if got := poll.MinResults(); got != 1 {
t.Errorf("unexpected poll min results: %v", got)
}
if got := poll.MaxResults(); got != 2 {
t.Errorf("unexpected poll max results: %v", got)
}
if got := poll.MaxWait(); got != time.Minute {
t.Errorf("unexpected poll max wait: %v", got)
}
// Check the call.
calls := poll.Calls()
if len(calls) != 1 {
t.Fatalf("expected one poll call, got %s", poll)
}
call := calls[0]
if got := call.Endpoint(); got != "http://example.com" {
t.Errorf("unexpected call endpoint: %v", got)
}
if got := call.Function(); got != "identity" {
t.Errorf("unexpected call endpoint: %v", got)
}
// Prepare the next request that carries the call result.
callResult := dispatchproto.NewCallResult(
call.Input(), // send call input back as the output
dispatchproto.CorrelationID(call.CorrelationID())) // correlation ID needs to match
pollResult := dispatchproto.NewPollResult(
dispatchproto.CoroutineState(poll.CoroutineState()), // send coroutine state back
dispatchproto.CallResults(callResult))
req = dispatchproto.NewRequest("repeat", pollResult)
}
exit, _ := res.Exit()
if err, ok := exit.Error(); ok {
t.Fatalf("unexpected error: %s", err)
}
var repeated string
output, ok := exit.Output()
if !ok {
t.Errorf("unexpected result, got %s", exit)
} else if err := output.Unmarshal(&repeated); err != nil {
t.Fatalf("unmarshal string: %v", err)
}
if repeated != "xxx" {
t.Errorf("unexpected function result: %q", repeated)
}
}
func TestCoroutineAwait(t *testing.T) {
logMode(t)
// This test is essentially the same as the test above, just
// using the higher level helpers for awaiting a call.
identity := dispatch.Func("identity", func(ctx context.Context, x string) (string, error) {
panic("not implemented") // this is a mock only
})
repeat := dispatch.Func("repeat", func(ctx context.Context, n int) (string, error) {
var repeated string
for i := 0; i < n; i++ {
res, err := identity.Await("x")
if err != nil {
return "", err
}
repeated += res
}
return repeated, nil
})
const repeatCount = 3
runner := dispatchtest.NewRunner(repeat)
req := dispatchproto.NewRequest("repeat", dispatchproto.Int(repeatCount))
var res dispatchproto.Response
requestCount := 0
for {
res = runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
if _, done := res.Exit(); done {
requestCount++
break
}
poll, ok := res.Poll()
if !ok {
t.Fatalf("expected poll response, got %s", res)
}
calls := poll.Calls()
if len(calls) != 1 {
t.Fatalf("expected one poll call, got %s", poll)
}
call := calls[0]
callResult := dispatchproto.NewCallResult(
call.Input(),
dispatchproto.CorrelationID(call.CorrelationID()))
pollResult := dispatchproto.NewPollResult(
dispatchproto.CoroutineState(poll.CoroutineState()),
dispatchproto.CallResults(callResult))
req = dispatchproto.NewRequest("repeat", pollResult)
requestCount++
}
if requestCount != repeatCount+1 { // one input request + `repeatCount` polls
t.Errorf("unexpected number of requests: got %d, want %d", requestCount, repeatCount+1)
}
exit, _ := res.Exit()
if err, ok := exit.Error(); ok {
t.Fatalf("unexpected error: %s", err)
}
var repeated string
output, ok := exit.Output()
if !ok {
t.Errorf("unexpected result, got %s", exit)
} else if err := output.Unmarshal(&repeated); err != nil {
t.Fatalf("unmarshal string: %v", err)
}
if want := strings.Repeat("x", repeatCount); repeated != want {
t.Errorf("unexpected function result: got %q, want %q", repeated, want)
}
}
func TestCoroutineGather(t *testing.T) {
logMode(t)
// This test is essentially the same as the test above, just
// using the higher level helpers for gathering the results
// of many calls.
identity := dispatch.Func("identity", func(ctx context.Context, x string) (string, error) {
panic("not implemented") // this is a mock only
})
repeat := dispatch.Func("repeat", func(ctx context.Context, n int) (string, error) {
inputs := make([]string, n)
for i := range inputs {
inputs[i] = "x"
}
results, err := identity.Gather(inputs)
if err != nil {
return "", err
}
return strings.Join(results, ""), nil
})
const repeatCount = 3
runner := dispatchtest.NewRunner(repeat)
req := dispatchproto.NewRequest("repeat", dispatchproto.Int(repeatCount))
res := runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
poll, ok := res.Poll()
if !ok {
t.Fatalf("expected poll response, got %s", res)
}
calls := poll.Calls()
if len(calls) != repeatCount {
t.Fatalf("expected %d poll calls, got %s", repeatCount, poll)
}
callResults := make([]dispatchproto.CallResult, len(calls))
for i, call := range calls {
callResults[i] = dispatchproto.NewCallResult(
call.Input(),
dispatchproto.CorrelationID(call.CorrelationID()))
}
// Send all results back at once.
pollResult := dispatchproto.NewPollResult(
dispatchproto.CoroutineState(poll.CoroutineState()),
dispatchproto.CallResults(callResults...))
req = dispatchproto.NewRequest("repeat", pollResult)
res = runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
exit, ok := res.Exit()
if !ok {
t.Fatalf("unexpected response, got %s", res)
}
if err, ok := exit.Error(); ok {
t.Fatalf("unexpected error: %s", err)
}
var repeated string
output, ok := exit.Output()
if !ok {
t.Errorf("unexpected result, got %s", exit)
} else if err := output.Unmarshal(&repeated); err != nil {
t.Fatalf("unmarshal string: %v", err)
}
if want := strings.Repeat("x", repeatCount); repeated != want {
t.Errorf("unexpected function result: got %q, want %q", repeated, want)
}
}
func TestCoroutineGatherSlow(t *testing.T) {
logMode(t)
// This test is essentially the same as the test above, just
// sending back call results one at a time, and in random order.
identity := dispatch.Func("identity", func(ctx context.Context, x string) (string, error) {
panic("not implemented") // this is a mock only
})
repeat := dispatch.Func("repeat", func(ctx context.Context, n int) (string, error) {
inputs := make([]string, n)
for i := range inputs {
inputs[i] = "x"
}
results, err := identity.Gather(inputs)
if err != nil {
return "", err
}
return strings.Join(results, ""), nil
})
const repeatCount = 3
runner := dispatchtest.NewRunner(repeat)
req := dispatchproto.NewRequest("repeat", dispatchproto.Int(repeatCount))
res := runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
poll, ok := res.Poll()
if !ok {
t.Fatalf("expected poll response, got %s", res)
}
calls := poll.Calls()
if len(calls) != repeatCount {
t.Fatalf("expected %d poll calls, got %s", repeatCount, poll)
}
callResults := make([]dispatchproto.CallResult, len(calls))
for i, call := range calls {
callResults[i] = dispatchproto.NewCallResult(
call.Input(),
dispatchproto.CorrelationID(call.CorrelationID()))
}
// Randomize call result order.
rand.Shuffle(len(callResults), func(i, j int) {
callResults[i], callResults[j] = callResults[j], callResults[i]
})
// Deliver an empty poll result, to assert it's a noop.
req = dispatchproto.NewRequest("repeat", poll.Result())
res = runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
// Deliver one call result at a time.
for i := range callResults {
if _, ok := res.Poll(); !ok {
t.Fatalf("expected previous response to be a poll before delivering call result %d, but got %s", i, res)
}
pollResult := poll.Result().With(dispatchproto.CallResults(callResults[i]))
req = dispatchproto.NewRequest("repeat", pollResult)
res = runner.RoundTrip(req)
if res.Status() != dispatchproto.OKStatus {
t.Errorf("unexpected status: %s", res.Status())
}
// Only the final response should be an exit.
if _, ok := res.Exit(); ok {
if i != len(callResults)-1 {
t.Errorf("unexpected exit after delivering call result %d: %s", i, res)
}
}
}
exit, ok := res.Exit()
if !ok {
t.Fatalf("unexpected response, got %s", res)
}
if err, ok := exit.Error(); ok {
t.Fatalf("unexpected error: %s", err)
}
var repeated string
output, ok := exit.Output()
if !ok {
t.Errorf("unexpected result, got %s", exit)
} else if err := output.Unmarshal(&repeated); err != nil {
t.Fatalf("unmarshal string: %v", err)
}
if want := strings.Repeat("x", repeatCount); repeated != want {
t.Errorf("unexpected function result: got %q, want %q", repeated, want)
}
}
func TestFunctionNewCallAndDispatchWithoutEndpoint(t *testing.T) {
fn := dispatch.Func("foo", func(ctx context.Context, input string) (string, error) {
panic("not implemented")
})
_, err := fn.BuildCall("bar") // allowed
if err != nil {
t.Fatal(err)
}
_, err = fn.Dispatch(context.Background(), "bar")
if err == nil || err.Error() != "cannot dispatch function call: function has not been registered with a Dispatch endpoint" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestFunctionDispatchWithoutClient(t *testing.T) {
// It's not necessary to have valid Client configuration when
// creating a Dispatch endpoint. In this case, there's no
// Dispatch API key available.
endpoint, err := dispatch.New(dispatch.EndpointUrl("http://example.com"), dispatch.Env( /* i.e. no env vars */ ))
if err != nil {
t.Fatal(err)
}
fn := dispatch.Func("foo", func(ctx context.Context, input string) (string, error) {
panic("not implemented")
})
endpoint.Register(fn)
if _, err := fn.BuildCall("bar"); err != nil { // allowed
t.Fatal(err)
}
// However, a client is not available.
_, err = fn.Dispatch(context.Background(), "bar")
if err == nil {
t.Fatal("expected an error")
} else if err.Error() != "cannot dispatch function call: Dispatch API key has not been set. Use APIKey(..), or set the DISPATCH_API_KEY environment variable" {
t.Errorf("unexpected error: %v", err)
}
}