-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_test.go
More file actions
379 lines (342 loc) · 12.8 KB
/
Copy pathcommand_test.go
File metadata and controls
379 lines (342 loc) · 12.8 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
package workerkit_test
import (
"context"
"encoding/json"
"errors"
"fmt"
. "github.com/jaredjakacky/workerkit"
"strings"
"testing"
"time"
opskit "github.com/jaredjakacky/opskit"
)
func TestCommandRequestValidate(t *testing.T) {
t.Parallel()
valid := []CommandRequest{
{Worker: "worker", Name: "sync"},
{Worker: "runtime/worker", Name: "queue/drain"},
{
Worker: "worker",
Name: "sync",
Payload: []byte(`{"id":1}`),
RequestedAt: time.Date(2026, 5, 15, 10, 0, 0, 0, time.UTC),
},
}
for _, req := range valid {
req := req
t.Run("valid "+req.Worker+" "+req.Name, func(t *testing.T) {
t.Parallel()
if err := req.Validate(); err != nil {
t.Fatalf("Validate returned error: %v", err)
}
})
}
invalid := []struct {
req CommandRequest
want string
}{
{
req: CommandRequest{Worker: "", Name: "sync"},
want: "invalid command target",
},
{
req: CommandRequest{Worker: "Runtime/worker", Name: "sync"},
want: "invalid command target",
},
{
req: CommandRequest{Worker: "worker", Name: ""},
want: "invalid command name",
},
{
req: CommandRequest{Worker: "worker", Name: "Sync"},
want: "invalid command name",
},
}
for _, tt := range invalid {
tt := tt
t.Run("invalid "+testName(tt.req.Worker)+" "+testName(tt.req.Name), func(t *testing.T) {
t.Parallel()
err := tt.req.Validate()
if err == nil {
t.Fatalf("Validate(%#v) returned nil, want error", tt.req)
}
if !strings.Contains(err.Error(), tt.want) {
t.Fatalf("Validate error = %q, want to contain %q", err.Error(), tt.want)
}
})
}
}
func TestCommandSpecValidate(t *testing.T) {
t.Parallel()
handler := CommandHandlerFunc(func(context.Context, CommandRequest) (CommandResult, error) {
return CommandResult{Message: "ok"}, nil
})
valid := []CommandSpec{
{Name: "sync", Handler: handler},
{Name: "queue/drain", Description: "drain a queue", Handler: handler},
}
for _, spec := range valid {
spec := spec
t.Run("valid "+spec.Name, func(t *testing.T) {
t.Parallel()
if err := spec.Validate(); err != nil {
t.Fatalf("Validate returned error: %v", err)
}
})
}
invalid := []struct {
spec CommandSpec
want string
}{
{
spec: CommandSpec{Name: "", Handler: handler},
want: "invalid command name",
},
{
spec: CommandSpec{Name: "Sync", Handler: handler},
want: "invalid command name",
},
{
spec: CommandSpec{Name: "sync"},
want: "command handler must not be nil",
},
}
for _, tt := range invalid {
tt := tt
t.Run("invalid "+testName(tt.spec.Name), func(t *testing.T) {
t.Parallel()
err := tt.spec.Validate()
if err == nil {
t.Fatalf("Validate(%#v) returned nil, want error", tt.spec)
}
if !strings.Contains(err.Error(), tt.want) {
t.Fatalf("Validate error = %q, want to contain %q", err.Error(), tt.want)
}
})
}
}
func TestCommandHandlerFunc(t *testing.T) {
t.Parallel()
wantErr := errors.New("command failed")
wantReq := CommandRequest{Worker: "worker", Name: "sync", Payload: []byte(`{"id":1}`)}
handler := CommandHandlerFunc(func(ctx context.Context, req CommandRequest) (CommandResult, error) {
if ctx == nil {
t.Fatal("context = nil")
}
if req.Worker != wantReq.Worker || req.Name != wantReq.Name || string(req.Payload) != string(wantReq.Payload) {
t.Fatalf("request = %#v, want %#v", req, wantReq)
}
return CommandResult{Message: "handled", Payload: []byte(`{"ok":true}`)}, wantErr
})
result, err := handler.HandleCommand(context.Background(), wantReq)
if !errors.Is(err, wantErr) {
t.Fatalf("HandleCommand error = %v, want %v", err, wantErr)
}
if result.Message != "handled" || string(result.Payload) != `{"ok":true}` {
t.Fatalf("result = %#v, want handled result", result)
}
}
func TestCommandInfoJSON(t *testing.T) {
t.Parallel()
body, err := json.Marshal(CommandInfo{
Worker: "runtime/worker",
Name: "sync",
Description: "synchronize worker state",
})
if err != nil {
t.Fatalf("Marshal returned error: %v", err)
}
if got, want := string(body), `{"worker":"runtime/worker","name":"sync","description":"synchronize worker state"}`; got != want {
t.Fatalf("json = %s, want %s", got, want)
}
body, err = json.Marshal(CommandInfo{
Worker: "runtime/worker",
Name: "sync",
})
if err != nil {
t.Fatalf("Marshal returned error: %v", err)
}
if got, want := string(body), `{"worker":"runtime/worker","name":"sync"}`; got != want {
t.Fatalf("json = %s, want %s", got, want)
}
}
func TestCommandFromOpskitTranslatesRequestAndCompletedResult(t *testing.T) {
t.Parallel()
requestedAt := time.Date(2026, 6, 20, 12, 0, 0, 0, time.UTC)
descriptor := opskit.CommandDescriptor{
Name: "cache/refresh",
Description: "refresh cache entries",
PayloadKind: "cache_refresh",
Dangerous: true,
Idempotent: true,
Attributes: []opskit.Attribute{opskit.Attr("scope", "cache")},
}
handler := opskit.CommandHandlerFunc(func(ctx context.Context, req opskit.CommandRequest) opskit.CommandResult {
if ctx == nil {
t.Fatal("context = nil")
}
if req.Name != descriptor.Name || string(req.Payload) != `{"force":true}` {
t.Fatalf("request = %#v, want translated name and payload", req)
}
if req.RequestedAt == nil || !req.RequestedAt.Equal(requestedAt) {
t.Fatalf("RequestedAt = %v, want %v", req.RequestedAt, requestedAt)
}
return opskit.CompletedCommand("refreshed", map[string]any{"count": 2}, time.Millisecond)
})
spec := CommandFromOpskit(descriptor, handler)
descriptor.Attributes[0] = opskit.Attr("scope", "mutated")
if spec.Name != "cache/refresh" || spec.Description != "refresh cache entries" || spec.PayloadKind != "cache_refresh" {
t.Fatalf("spec = %#v, want descriptor metadata", spec)
}
if !spec.Dangerous || !spec.Idempotent || spec.Attributes[0] != opskit.Attr("scope", "cache") {
t.Fatalf("spec metadata = %#v, want cloned advisory metadata", spec)
}
result, err := spec.Handler.HandleCommand(context.Background(), CommandRequest{
Name: descriptor.Name,
Payload: []byte(`{"force":true}`),
RequestedAt: requestedAt,
})
if err != nil {
t.Fatalf("HandleCommand error = %v", err)
}
if result.Message != "refreshed" || string(result.Payload) != `{"count":2}` {
t.Fatalf("result = %#v, want completed Opskit result", result)
}
}
func TestCommandFromOpskitMapsOutcomes(t *testing.T) {
t.Parallel()
tests := []struct {
name string
result opskit.CommandResult
wantErr error
wantCode string
wantPublicCode string
}{
{name: "rejected", result: opskit.RejectedCommand("disabled"), wantErr: ErrOpsCommandRejected, wantPublicCode: FailureCodeOpskitCommandRejected},
{name: "rejected with failure detail", result: opskit.CommandResult{State: opskit.StateNotReady, Accepted: false, Failure: &opskit.Failure{Code: "disabled", Message: "disabled"}}, wantErr: ErrOpsCommandRejected, wantCode: "disabled", wantPublicCode: "disabled"},
{name: "failed without detail", result: opskit.FailedCommand("refresh failed", 0), wantErr: ErrOpsCommandFailed, wantPublicCode: FailureCodeOpskitCommandFailed},
{name: "failed", result: opskit.FailedCommandWithFailure("refresh failed", opskit.Failure{Code: "unavailable", Message: "backend unavailable"}, 0), wantErr: ErrOpsCommandFailed, wantCode: "unavailable", wantPublicCode: "unavailable"},
{name: "failure detail implies failure", result: opskit.CommandResult{State: opskit.StateReady, Accepted: true, Failure: &opskit.Failure{Code: "inconsistent", Message: "inconsistent failure"}}, wantErr: ErrOpsCommandFailed, wantCode: "inconsistent", wantPublicCode: "inconsistent"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := CommandFromOpskit(opskit.CommandDescriptor{Name: "refresh"}, opskit.CommandHandlerFunc(
func(context.Context, opskit.CommandRequest) opskit.CommandResult { return tt.result },
))
_, err := spec.Handler.HandleCommand(context.Background(), CommandRequest{Name: "refresh"})
if !errors.Is(err, tt.wantErr) {
t.Fatalf("error = %v, want %v", err, tt.wantErr)
}
var opsErr *OpskitCommandError
if !errors.As(err, &opsErr) {
t.Fatalf("error = %T, want *OpskitCommandError", err)
}
if opsErr.Failure.Code != tt.wantCode {
t.Fatalf("failure code = %q, want %q", opsErr.Failure.Code, tt.wantCode)
}
if got := opsErr.OperationalFailure().Code; got != tt.wantPublicCode {
t.Fatalf("operational failure code = %q, want %q", got, tt.wantPublicCode)
}
if tt.result.Failure != nil {
tt.result.Failure.Code = "mutated"
if opsErr.Failure.Code != tt.wantCode {
t.Fatalf("failure code after source mutation = %q, want detached %q", opsErr.Failure.Code, tt.wantCode)
}
}
})
}
}
func TestOpskitCommandErrorZeroValueIsSafe(t *testing.T) {
t.Parallel()
err := &OpskitCommandError{}
if err.Error() != "opskit command failed" {
t.Fatalf("Error() = %q, want safe non-empty fallback", err.Error())
}
if failure := err.OperationalFailure(); failure.Code != FailureCodeOpskitCommandFailed || failure.Message != "opskit command failed" {
t.Fatalf("OperationalFailure() = %#v, want default Opskit failure", failure)
}
}
func TestCommandFromOpskitMapsCancellationAndResultEncoding(t *testing.T) {
t.Parallel()
canceled, cancel := context.WithCancel(context.Background())
cancel()
spec := CommandFromOpskit(opskit.CommandDescriptor{Name: "refresh"}, opskit.CommandHandlerFunc(
func(context.Context, opskit.CommandRequest) opskit.CommandResult {
return opskit.CompletedCommand("ignored", nil, 0)
},
))
if _, err := spec.Handler.HandleCommand(canceled, CommandRequest{Name: "refresh"}); !errors.Is(err, context.Canceled) {
t.Fatalf("canceled error = %v, want context.Canceled", err)
}
deadline, cancelDeadline := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancelDeadline()
if _, err := spec.Handler.HandleCommand(deadline, CommandRequest{Name: "refresh"}); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("deadline error = %v, want context.DeadlineExceeded", err)
}
const secret = "postgres://user:pass@internal/config"
cause := errors.New("marshal failed for " + secret)
spec = CommandFromOpskit(opskit.CommandDescriptor{Name: "refresh"}, opskit.CommandHandlerFunc(
func(context.Context, opskit.CommandRequest) opskit.CommandResult {
return opskit.CompletedCommand("invalid", commandTestFailingJSON{err: cause}, 0)
},
))
if _, err := spec.Handler.HandleCommand(context.Background(), CommandRequest{Name: "refresh"}); err == nil {
t.Fatal("encoding error = nil, want error")
} else {
if !errors.Is(err, ErrOpsCommandFailed) || strings.Contains(err.Error(), secret) {
t.Fatalf("encoding error = %v, want safe ErrOpsCommandFailed", err)
}
var opsErr *OpskitCommandError
if !errors.As(err, &opsErr) || opsErr.Failure.Code != FailureCodeOpskitResultEncodingFailed {
t.Fatalf("encoding error = %#v, want typed result_encoding_failed", err)
}
if !errors.Is(opsErr.Cause(), cause) {
t.Fatalf("encoding cause = %v, want private original cause", opsErr.Cause())
}
}
var nilHandler opskit.CommandHandler
if err := CommandFromOpskit(opskit.CommandDescriptor{Name: "refresh"}, nilHandler).Validate(); err == nil {
t.Fatal("Validate nil Opskit handler error = nil")
}
}
type commandTestFailingJSON struct {
err error
}
func (v commandTestFailingJSON) MarshalJSON() ([]byte, error) {
return nil, v.err
}
func TestCommandFromOpskitAcceptedAsyncAndNilResult(t *testing.T) {
t.Parallel()
for name, opsResult := range map[string]opskit.CommandResult{
"accepted": opskit.AcceptedCommand("queued"),
"completed": opskit.CompletedCommand("done", nil, 0),
"zero_failure": {State: opskit.StateReady, Accepted: true, Message: "done", Failure: &opskit.Failure{}},
} {
t.Run(name, func(t *testing.T) {
spec := CommandFromOpskit(opskit.CommandDescriptor{Name: "refresh"}, opskit.CommandHandlerFunc(
func(context.Context, opskit.CommandRequest) opskit.CommandResult { return opsResult },
))
result, err := spec.Handler.HandleCommand(context.Background(), CommandRequest{Name: "refresh"})
if err != nil {
t.Fatalf("HandleCommand error = %v", err)
}
if result.Message != opsResult.Message || result.Payload != nil {
t.Fatalf("result = %#v, want message with nil payload", result)
}
})
}
}
func ExampleCommandFromOpskit() {
descriptor := opskit.CommandDescriptor{
Name: "cache/refresh",
Description: "refresh cache entries",
Idempotent: true,
}
handler := opskit.CommandHandlerFunc(func(context.Context, opskit.CommandRequest) opskit.CommandResult {
return opskit.CompletedCommand("refreshed", map[string]bool{"ok": true}, 0)
})
spec := CommandFromOpskit(descriptor, handler)
result, _ := spec.Handler.HandleCommand(context.Background(), CommandRequest{Name: spec.Name})
fmt.Printf("%s %s\n", result.Message, result.Payload)
// Output: refreshed {"ok":true}
}