-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmachine_test.go
More file actions
848 lines (781 loc) · 26.8 KB
/
Copy pathmachine_test.go
File metadata and controls
848 lines (781 loc) · 26.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
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
package di_test
// A model-based test over sequences of container OPERATIONS, not just
// registrations, driven either by a seeded generator or by the fuzzer.
//
// It deliberately does not predict outcomes. A predictive model of a
// container this size is itself likely to be wrong, and a wrong model that
// happens to agree with a wrong implementation hides bugs rather than
// finding them. Instead each sequence is checked against invariants taken
// from the documented guarantees, which hold whatever the sequence is:
//
// I1 Resolve never panics, with an error or anything else. Wiring
// problems are errors; only a rejected configuration panics, and only
// from Register, Get, All or Start.
// I2 A rejected configuration is rejected identically when the same
// read-only operation is repeated. (Different operations on one scope
// may legitimately be rejected for different reasons, and a resolve
// freezes several scopes, so the check is per operation.)
// I3 A stopped scope, and everything under it, refuses to resolve: an
// operation on it fails, or is rejected, but never succeeds.
// I4 A singleton is stable: two successful resolutions of a key from one
// scope return the identical value.
// I5 Nothing is stopped more often than it was built.
// I6 Once the root is stopped, every Worker hook has returned.
// I7 Explain and Graph render whatever state the sequence reached,
// panicking only where a resolution from the same scope would, and
// never deadlocking against the phase machine they read.
// I8 Validate builds nothing and is repeatable: two calls from one scope
// say the same thing, and the build count is what it was before.
//
// What happens to an instance once it exists is predicted rather than
// checked against invariants, by the model in lifecyclemodel_test.go. That
// half is a small state machine the package documents completely, and it is
// the half every review found defects in.
//
// Recovering a key whose resolution failed is pinned by a regression test
// instead: it needs a specific shape rather than a random one.
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/floatdrop/di"
)
// ---- the services under test ----------------------------------------------
type mk1 struct{ dep any }
type mk2 struct{ dep any }
type mk3 struct{ dep any }
type mkI interface{ marker() }
func (*mk1) marker() {}
const (
numKeys = 4 // mk1, mk2, mk3, mkI
// root, two children and a grandchild. The grandchild is what lets a
// scope between a resolver and the owner of a binding shadow a key that
// has already been served through it.
numScopes = 4
)
// parentOf[i] is the index of scope i's parent, -1 for the root.
var parentOf = [numScopes]int{-1, 0, 0, 1}
var keyNames = []string{"mk1", "mk2", "mk3", "mkI"}
// ---- operations ------------------------------------------------------------
type opKind uint8
const (
opRegister opKind = iota
opResolve
opGet
opMaybe
opAll
opStart
opStop
opShutdown
opRun
numOpKinds
)
type op struct {
kind opKind
scope uint8
key uint8
reg uint8 // which registration shape
// eager is the registration's Eager flag. On every other kind it is a
// spare bit the concurrent driver reads as a variant: a Stop whose
// context is far too short for the hooks it will run, which is how the
// deadline paths are reached at all.
eager bool
// override marks a registration Override(). Without it a repeated key in
// one scope is a rejection, which is a legitimate outcome and a shallow
// one; with it the sequence goes on to exercise what a replacement does
// to eagerness, resolution and teardown.
override bool
// wire registers the shape through Wire instead of Provide, for the shapes
// that have a constructor to hand over. It is how the reflective build
// path and its declared dependencies meet every oracle. The bit was spare
// until now, so every corpus entry keeps the meaning it had.
wire bool
}
func (o op) String() string {
names := []string{"Register", "Resolve", "Get", "Maybe", "All", "Start", "Stop", "Shutdown", "Run"}
if o.kind == opRegister {
return fmt.Sprintf("Register(s%d, %s, shape%d, eager=%v, override=%v, wire=%v)", o.scope, keyNames[o.key], o.reg, o.eager, o.override, o.wire)
}
if o.kind == opStop && o.eager {
return fmt.Sprintf("Stop(s%d, impatient)", o.scope)
}
return fmt.Sprintf("%s(s%d, %s)", names[o.kind], o.scope, keyNames[o.key])
}
func decode(data []byte) []op {
var ops []op
for i := 0; i+4 < len(data) && len(ops) < 24; i += 5 {
ops = append(ops, op{
kind: opKind(data[i] % uint8(numOpKinds)),
scope: data[i+1] % numScopes,
key: data[i+2] % numKeys,
reg: data[i+3] % 12,
eager: data[i+4]&1 == 1,
override: data[i+4]&2 == 2,
wire: data[i+4]&4 == 4,
})
}
return ops
}
// ---- the harness -----------------------------------------------------------
type machine struct {
t *testing.T
ops []op
scopes []*di.Scope
names []string
stopped []bool // scope index -> Stop has been called
// observed lifecycle, keyed by "scope/service"
builds map[string]int
starts map[string]int
stops map[string]int
runsLive atomic.Int32 // Worker hooks currently executing
// values seen per (scope, key), to check singleton stability
seen map[string]any
// registeredFrom remembers the scopes a constructor has already
// registered into, so the shape that registers does it once and never
// overrides what it registered before.
registeredFrom map[int]bool
lc *lifecycle
failedResolve map[string]bool
}
// fail reports a violation together with the sequence that produced it.
func (m *machine) fail(format string, args ...any) {
m.t.Helper()
m.t.Fatalf(format+"\n sequence: %v", append(args, m.ops)...)
}
func newMachine(t *testing.T, ops []op) *machine {
m := &machine{
t: t, ops: ops,
builds: map[string]int{}, starts: map[string]int{}, stops: map[string]int{},
seen: map[string]any{}, failedResolve: map[string]bool{},
registeredFrom: map[int]bool{},
stopped: make([]bool, numScopes),
}
root := di.New()
root.Observe(func(ev di.Event) {
id := ev.Scope + "/" + ev.Service
switch ev.Kind {
case di.EventBuild:
if ev.Err == nil {
m.builds[id]++
}
case di.EventStart:
if ev.Err == nil {
m.starts[id]++
}
case di.EventStop:
m.stops[id]++
}
})
c1 := root.Child("c1")
m.scopes = []*di.Scope{root, c1, root.Child("c2"), c1.Child("gc")}
m.names = []string{"root", "c1", "c2", "gc"}
m.lc = newLifecycle(m)
for i, sc := range m.scopes {
sc.Value(scopeName{m.names[i]})
}
return m
}
// scopeOf names the scope a constructor is running in, which for every
// lifetime is the scope that holds the instance and will stop it.
func (m *machine) scopeOf(sc *di.Scope) int { return m.indexOf(sc.Get[scopeName]().name) }
func (m *machine) indexOf(name string) int {
for i, n := range m.names {
if n == name {
return i
}
}
return 0
}
// reported is the build report of a Wire constructor: it has no scope handle,
// so the scope's name arrives as a dependency, which for a Scoped binding is
// the scope that resolved it and will hold the instance.
func reported[T any](m *machine, o op, sn scopeName, v T) T {
m.lc.built(m.indexOf(sn.name), o.reg, any(v))
return v
}
// outcome classifies what an operation did.
type outcome struct {
value any
err error
panicked bool // the operation panicked rather than returning
rejected string // a configuration rejection, which panics by design
}
// call runs f, classifying panics. A panic carrying a string is a rejected
// configuration. A panic carrying an error is how Get reports failure at top
// level. Anything else is a defect.
func (m *machine) call(what string, f func() (any, error)) outcome {
var out outcome
func() {
defer func() {
r := recover()
switch v := r.(type) {
case nil:
case string:
if !strings.HasPrefix(v, "di: ") {
m.fail("%s panicked with an unexpected string: %q", what, v)
}
out.rejected = v
case error:
out.err, out.panicked = v, true
default:
m.fail("%s panicked with %T: %v", what, r, r)
}
}()
out.value, out.err = f()
}()
return out
}
func (m *machine) run() {
for i, o := range m.ops {
m.step(i, o)
}
m.render()
m.finish()
}
// render enforces I7 against the state the sequence ended in, which is
// the richest one it reaches: every scope's graph, and every key explained
// from every scope. Once per sequence rather than once per operation,
// because the fuzzer runs this millions of times and the shapes a
// rendering can meet are decided by the registrations, not by where in the
// sequence it is asked.
func (m *machine) render() {
for i, s := range m.scopes {
g := s.Graph()
if !strings.HasPrefix(g, "digraph di {") || !strings.HasSuffix(g, "}\n") {
m.fail("Graph(s%d) rendered %q", i, g)
}
for k := range numKeys {
m.explain(s, i, k)
}
m.validate(s, i)
m.modules(s, i)
}
}
// modules renders the module report, which walks the same registry as
// Validate does. A configuration rejection is legitimate for the reason
// explain gives; anything else, or a report that does not end in a newline,
// is a defect.
func (m *machine) modules(s *di.Scope, scope int) {
defer func() {
if r := recover(); r != nil {
if _, rejected := r.(string); !rejected {
m.fail("Modules(s%d) panicked with %v", scope, r)
}
}
}()
if out := s.Modules(); out != "" && !strings.HasSuffix(out, "\n") {
m.fail("Modules(s%d) rendered %q", scope, out)
}
}
// validate enforces I8: Validate builds nothing and says the same thing
// twice. A configuration rejection is legitimate for the reason explain
// gives; whether what it says is right is pinned by validate_test.go, since
// predicting it here would model the lookup rules a second time.
func (m *machine) validate(s *di.Scope, scope int) {
defer func() {
if r := recover(); r != nil {
if _, rejected := r.(string); !rejected {
m.fail("Validate(s%d) panicked with %v", scope, r)
}
}
}()
before := m.totalBuilds()
for _, stubs := range [][]di.Stub{nil, {di.Provided[*mk2](), di.Provided[mkI]()}} {
first := s.Validate(stubs...)
second := s.Validate(stubs...)
if m.totalBuilds() != before {
m.fail("Validate(s%d) built something", scope)
}
if fmt.Sprint(first.Err()) != fmt.Sprint(second.Err()) ||
len(first.Owed) != len(second.Owed) || len(first.Unchecked) != len(second.Unchecked) {
m.fail("Validate(s%d) was not repeatable:\n %+v\n %+v", scope, first, second)
}
if len(stubs) > 0 && len(first.Owed) > 0 {
m.fail("Validate(s%d) with stubs owes nothing by definition, got %v", scope, first.Owed)
}
}
}
func (m *machine) totalBuilds() int {
n := 0
for _, c := range m.builds {
n += c
}
return n
}
// explain renders one key from one scope. A configuration rejection is a
// legitimate outcome, because Explain looks the key up and a lookup commits
// the pending batch, exactly as a resolution from this scope would; any
// other panic is a defect.
func (m *machine) explain(s *di.Scope, scope, k int) {
defer func() {
if r := recover(); r != nil {
if _, rejected := r.(string); !rejected {
m.fail("Explain(s%d, %s) panicked with %v", scope, keyNames[k], r)
}
}
}()
var out string
switch k {
case 0:
out = s.Explain[*mk1]()
case 1:
out = s.Explain[*mk2]()
case 2:
out = s.Explain[*mk3]()
default:
out = s.Explain[mkI]()
}
if !strings.HasSuffix(out, "\n") {
m.fail("Explain(s%d, %s) rendered %q", scope, keyNames[k], out)
}
}
func (m *machine) step(i int, o op) {
s := m.scopes[o.scope]
label := fmt.Sprintf("op %d %v", i, o)
switch o.kind {
case opRegister:
// Registered through Use, so the generators exercise attribution too:
// every binding the machine makes carries a module name, and the
// collision rejections it provokes name it.
m.call(label, func() (any, error) { s.Use(func(sc *di.Scope) { m.register(sc, o) }); return nil, nil })
case opResolve:
f := func() (any, error) { return m.resolve(s, o) }
out := m.call(label, f)
if out.panicked {
m.fail("%s: Resolve panicked with an error instead of returning it: %v", label, out.err)
}
if out.err == nil && out.rejected == "" {
m.checkStable(label, o, out.value)
}
if out.err != nil {
m.failedResolve[m.vkey(o)] = true
}
m.checkRepeatable(label, out, f)
m.checkStopped(label, o, out)
case opGet:
f := func() (any, error) { return m.get(s, o) }
out := m.call(label, f)
if out.err == nil && out.rejected == "" {
m.checkStable(label, o, out.value)
}
m.checkRepeatable(label, out, f)
case opMaybe:
f := func() (any, error) { return m.maybe(s, o) }
m.checkRepeatable(label, m.call(label, f), f)
case opAll:
f := func() (any, error) { return m.all(s, o) }
m.checkRepeatable(label, m.call(label, f), f)
case opStart:
out := m.call(label, func() (any, error) { return nil, s.Start(machineStartCtx(int(o.scope))) })
if out.rejected == "" {
m.lc.started(int(o.scope), out.err)
}
case opStop:
out := m.call(label, func() (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return nil, s.Stop(ctx)
})
if out.rejected == "" {
m.markStopped(int(o.scope))
m.lc.stopping(int(o.scope))
}
_ = out
case opRun:
// Run with a context that is already cancelled: it starts the scope,
// finds nothing to wait for, and stops again. That is the only way
// the generators reach Run at all, and Run is where a worker's
// failure and a Stop's errors are joined.
ctx, cancel := context.WithCancel(machineStartCtx(int(o.scope)))
cancel()
out := m.call(label, func() (any, error) {
return nil, s.Run(ctx, di.StopTimeout(2*time.Second))
})
if out.rejected == "" {
m.lc.ranAndStopped(int(o.scope), out.err)
if out.err == nil || !strings.Contains(out.err.Error(), "Start called twice") {
m.markStopped(int(o.scope))
}
}
case opShutdown:
// Sequentially this only records a cause; it is here so the operation
// exists in the shared encoding, and because Shutdown is what a hook
// must call now that it may not call Stop.
m.call(label, func() (any, error) { s.Shutdown(errShutdown); return nil, nil })
}
}
var errShutdown = errors.New("shutdown from the machine")
// marker is what the registering shape registers. It is its own type so that
// registering it can never override anything else, and registerFrom does it
// once per scope so it can never override itself either.
type marker struct{}
func (m *machine) registerFrom(sc *di.Scope, scope int) {
if m.registeredFrom[scope] {
return
}
m.registeredFrom[scope] = true
sc.Value(marker{})
}
// checkRepeatable enforces I2. It re-runs the identical operation and
// requires the same rejection. Only read-only operations are re-run:
// Register and Start mutate, so repeating them is not the same operation.
func (m *machine) checkRepeatable(label string, out outcome, again func() (any, error)) {
if out.rejected == "" {
return
}
second := m.call(label+" (repeat)", again)
if second.rejected != out.rejected {
m.fail("%s: rejection was not repeatable\n first: %s\n second: %q err=%v",
label, out.rejected, second.rejected, second.err)
}
}
// checkStopped enforces I3. A resolve from a stopped tree must not succeed:
// reporting only on the errors it did return would accept the very case the
// invariant exists to rule out.
func (m *machine) checkStopped(label string, o op, out outcome) {
if !m.stoppedTree(int(o.scope)) || out.rejected != "" {
return
}
if out.err == nil {
m.fail("%s: resolving from a stopped scope succeeded", label)
}
if !errors.Is(out.err, di.ErrStopped) && !errors.Is(out.err, di.ErrNotProvided) && !errors.Is(out.err, di.ErrCycle) {
m.fail("%s: resolving from a stopped scope gave %v", label, out.err)
}
}
// checkStable enforces I4: a key resolves to the same value each time.
func (m *machine) checkStable(label string, o op, v any) {
if v == nil {
return
}
k := m.vkey(o)
prev, ok := m.seen[k]
if !ok {
m.seen[k] = v
return
}
if prev != v {
m.fail("%s: %s resolved to a different value than before", label, keyNames[o.key])
}
}
func (m *machine) vkey(o op) string { return fmt.Sprintf("s%d/%s", o.scope, keyNames[o.key]) }
// markStopped records that scope i was stopped, along with its descendants.
func (m *machine) markStopped(i int) {
m.stopped[i] = true
for j := range m.stopped {
for a := j; a >= 0; a = parentOf[a] {
if a == i {
m.stopped[j] = true
break
}
}
}
}
// stoppedTree reports whether scope i or any ancestor has been stopped.
func (m *machine) stoppedTree(i int) bool {
for a := i; a >= 0; a = parentOf[a] {
if m.stopped[a] {
return true
}
}
return false
}
// finish enforces I5 and I6.
func (m *machine) finish() {
_ = m.call("final Stop", func() (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return nil, m.scopes[0].Stop(ctx)
})
m.lc.stopping(0)
m.lc.report()
for id, n := range m.stops {
if n > m.builds[id] {
m.fail("%s: stopped %d times but built %d", id, n, m.builds[id])
}
}
deadline := time.Now().Add(2 * time.Second)
for m.runsLive.Load() != 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if n := m.runsLive.Load(); n != 0 {
m.fail("%d Worker hooks still executing after the root was stopped", n)
}
}
// ---- registration shapes ---------------------------------------------------
// regShape registers one of ten shapes for T, chosen by op.reg, so a random
// sequence exercises lifetimes, hooks, groups, failures and dependencies.
func regShape[T any](m *machine, s *di.Scope, o op, plain func() T, dep func(*di.Scope) T, wire, wireScoped any) {
var b di.Binding[T]
// Every modelled shape reports its own build and its own hooks, so the
// model knows which instance is which without having to predict what
// serves a key. A Value binding has no constructor to report from, so it
// stays outside the model: hook returns what the model knows about each
// shape.
builtIn := func(scope int, v T) T {
m.lc.built(scope, o.reg, any(v))
return v
}
built := func(sc *di.Scope, v T) T { return builtIn(m.scopeOf(sc), v) }
hook := func(name string) func(context.Context, T) error {
return func(_ context.Context, v T) error {
m.lc.hookRan(any(v), name)
return nil
}
}
noop := func(context.Context, T) error { return nil }
switch o.reg {
case 0:
if o.wire {
// A Wire constructor has no scope handle; a singleton is built
// in the scope that registered it, which is this one.
b = s.Wire[T](func() T { return builtIn(int(o.scope), plain()) }).
OnStart(hook("OnStart")).OnStop(hook("OnStop"))
} else {
b = s.Provide(func(sc *di.Scope) T { return built(sc, plain()) }).
OnStart(hook("OnStart")).OnStop(hook("OnStop"))
}
case 1:
if o.wire {
// A wrapper over whatever serves the key, or a registration-time
// rejection when nothing does. The wrapped registration reports
// its own build; this reports the wrapper's, in the scope that
// resolves it, which for a scoped chain is not the registering
// one.
b = s.Wrap[T](func(_ T, sn scopeName) T { return reported(m, o, sn, plain()) }).
OnStop(hook("OnStop"))
} else {
b = s.Value(plain()).OnStop(noop)
}
case 2:
if o.wire {
// Scoped through Wire, with a dependency on another key: built
// through reflect in whichever scope resolves it, and the one
// shape whose declared dependency Validate has to leave to a
// descendant when the resolving scope is not there yet.
b = s.Wire[T](wireScoped).Scoped().
OnStop(hook("OnStop"))
} else {
b = s.Provide(func(sc *di.Scope) T { return built(sc, plain()) }).Scoped().
OnStop(hook("OnStop"))
}
case 3:
b = s.Provide(func(sc *di.Scope) T { return built(sc, plain()) }).Group().
OnStart(hook("OnStart")).OnStop(hook("OnStop"))
case 4:
b = s.Provide(func(sc *di.Scope) T { return built(sc, plain()) }).
Worker(func(ctx context.Context, _ T) error {
m.runsLive.Add(1)
defer m.runsLive.Add(-1)
<-ctx.Done()
return nil
}).OnStop(hook("OnStop"))
case 5:
if o.wire {
// A constructor of the wrong shape, one per key: Wire rejects it
// at registration, with a configuration panic the harness
// classifies like any other rejection.
switch o.key {
case 0:
b = s.Wire[T](42)
case 1:
b = s.Wire[T](func(...int) T { return plain() })
case 2:
b = s.Wire[T](func() {})
default:
b = s.Wire[T](func() (T, bool) { return plain(), false })
}
break
}
// A constructor that fails. resolve turns this into an error, so it
// exercises the failure paths rather than escaping as a panic.
b = s.Provide(func(*di.Scope) T { panic("injected constructor failure") })
case 6:
// Depends on another key, so chains and cycles arise; through Wire the
// dependency is declared, so Validate has something to walk.
if o.wire {
b = s.Wire[T](wire)
} else {
b = s.Provide(dep)
}
case 7:
// Draining, which the sequential machine had no shape for at all: the
// phase was exercised only where two calls overlap, and never where
// its boundary is known.
b = s.Provide(func(sc *di.Scope) T { return built(sc, plain()) }).
OnDrain(hook("OnDrain")).OnStop(hook("OnStop"))
case 8:
b = s.Provide(func(sc *di.Scope) T { return built(sc, plain()) }).
OnStart(hook("OnStart")).OnDrain(hook("OnDrain")).OnStop(hook("OnStop"))
case 9:
// A constructor that registers, and resolves what it registered. The
// registry is mutable during a resolution, and nothing here was
// exercising that: freeze runs inside the nested lookup, on a scope
// with a resolution already in flight.
b = s.Provide(func(sc *di.Scope) T {
m.registerFrom(sc, int(o.scope))
_, _ = sc.Resolve[marker]()
return built(sc, plain())
}).OnStop(hook("OnStop"))
case 10:
// The same, over its own key. That has to be rejected: the nested
// resolve would be served the replacement while this one goes on to
// return the old value, which is two live values for one key.
b = s.Provide(func(sc *di.Scope) T {
sc.Provide(func(*di.Scope) T { return plain() })
_, _ = sc.Resolve[T]()
return built(sc, plain())
}).OnStop(hook("OnStop"))
default:
b = s.Provide(func(*di.Scope) T { return plain() })
}
if o.eager {
b.Eager()
}
if o.override {
b.Override()
}
}
func (m *machine) register(s *di.Scope, o op) {
switch o.key {
case 0:
regShape(m, s, o,
func() *mk1 { return &mk1{} },
func(sc *di.Scope) *mk1 { return &mk1{dep: sc.Get[*mk2]()} },
func(d *mk2) *mk1 { return &mk1{dep: d} },
func(sn scopeName, d *mk2) *mk1 { return reported(m, o, sn, &mk1{dep: d}) })
case 1:
regShape(m, s, o,
func() *mk2 { return &mk2{} },
func(sc *di.Scope) *mk2 { return &mk2{dep: sc.Get[*mk3]()} },
func(d *mk3) *mk2 { return &mk2{dep: d} },
func(sn scopeName, d *mk3) *mk2 { return reported(m, o, sn, &mk2{dep: d}) })
case 2:
regShape(m, s, o,
func() *mk3 { return &mk3{} },
func(sc *di.Scope) *mk3 { return &mk3{dep: sc.Get[*mk1]()} },
func(d *mk1) *mk3 { return &mk3{dep: d} },
func(sn scopeName, d *mk1) *mk3 { return reported(m, o, sn, &mk3{dep: d}) })
default:
regShape(m, s, o,
func() mkI { return &mk1{} },
func(sc *di.Scope) mkI { _ = sc.Get[*mk2](); return &mk1{} },
func(*mk2) mkI { return &mk1{} },
func(sn scopeName, _ *mk2) mkI { return reported(m, o, sn, mkI(&mk1{})) })
}
}
// ---- resolution dispatch ---------------------------------------------------
func (m *machine) resolve(s *di.Scope, o op) (any, error) {
switch o.key {
case 0:
v, err := s.Resolve[*mk1]()
return v, err
case 1:
v, err := s.Resolve[*mk2]()
return v, err
case 2:
v, err := s.Resolve[*mk3]()
return v, err
default:
v, err := s.Resolve[mkI]()
return v, err
}
}
func (m *machine) get(s *di.Scope, o op) (any, error) {
switch o.key {
case 0:
return s.Get[*mk1](), nil
case 1:
return s.Get[*mk2](), nil
case 2:
return s.Get[*mk3](), nil
default:
return s.Get[mkI](), nil
}
}
func (m *machine) maybe(s *di.Scope, o op) (any, error) {
switch o.key {
case 0:
v, _ := s.Maybe[*mk1]()
return v, nil
case 1:
v, _ := s.Maybe[*mk2]()
return v, nil
case 2:
v, _ := s.Maybe[*mk3]()
return v, nil
default:
v, _ := s.Maybe[mkI]()
return v, nil
}
}
func (m *machine) all(s *di.Scope, o op) (any, error) {
switch o.key {
case 0:
return len(s.All[*mk1]()), nil
case 1:
return len(s.All[*mk2]()), nil
case 2:
return len(s.All[*mk3]()), nil
default:
return len(s.All[mkI]()), nil
}
}
// ---- drivers ---------------------------------------------------------------
// TestMachineSeeded runs a deterministic sweep, so CI is fast and any
// failure is reproducible from the seed alone.
func TestMachineSeeded(t *testing.T) {
rng := rand.New(rand.NewPCG(0xC0FFEE, 0xBEEF))
for iter := range 3000 {
n := 1 + rng.IntN(12)
data := make([]byte, n*5)
for i := range data {
data[i] = byte(rng.UintN(256))
}
ops := decode(data)
t.Run(fmt.Sprintf("iter%d", iter), func(t *testing.T) {
newMachine(t, ops).run()
})
if t.Failed() {
t.Fatalf("failing sequence: %v", ops)
}
}
}
// FuzzMachine is the coverage-guided driver over the same invariants. Run it
// with: go test -fuzz FuzzMachine -fuzztime 2m
func FuzzMachine(f *testing.F) {
f.Add([]byte{0, 0, 0, 0, 1, 5, 0, 0, 0, 0}) // register eager, then Start
f.Add([]byte{0, 0, 0, 6, 0, 1, 0, 0, 0, 0, 6, 0, 0, 0, 0}) // a dependency on an unprovided key, then stop
f.Add([]byte{0, 0, 0, 6, 0, 0, 0, 1, 6, 0, 0, 0, 2, 6, 0, 1, 0, 0, 0, 0}) // a dependency cycle
f.Add([]byte{0, 0, 0, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0}) // failing constructor, eager
// The wired shapes, which a random sequence rarely combines: a cycle of
// three Wire singletons, which Validate reports once; a Scoped Wire
// binding whose dependency the root cannot provide, owed from the root
// and missing from the child that resolves it; a singleton that would
// build such a binding in its own scope, the one capture Validate calls
// an error; and the four rejected constructor shapes.
f.Add([]byte{0, 0, 0, 6, 4, 0, 0, 1, 6, 4, 0, 0, 2, 6, 4, 2, 1, 0, 0, 0})
f.Add([]byte{0, 0, 0, 2, 4, 2, 1, 0, 0, 0})
f.Add([]byte{0, 0, 0, 2, 4, 0, 1, 1, 0, 4, 2, 1, 0, 0, 0})
f.Add([]byte{0, 0, 0, 6, 4, 0, 0, 1, 2, 4, 1, 0, 0, 0, 0})
f.Add([]byte{0, 0, 0, 5, 4, 0, 0, 1, 5, 4, 0, 0, 2, 5, 4, 0, 0, 3, 5, 4})
// Wrappers: over a singleton, started eagerly so both halves build and
// stop in order; over the parent's value from a child, resolved there;
// over a scoped chain; and over nothing, which is rejected.
f.Add([]byte{0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 5, 0, 0, 0, 0, 6, 0, 0, 0, 0})
f.Add([]byte{0, 0, 0, 0, 0, 0, 1, 0, 1, 4, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0})
f.Add([]byte{0, 0, 0, 2, 4, 0, 0, 1, 0, 0, 0, 0, 0, 1, 4, 2, 3, 0, 0, 0})
f.Add([]byte{0, 0, 0, 1, 4})
f.Fuzz(func(t *testing.T, data []byte) {
ops := decode(data)
if len(ops) == 0 {
return
}
newMachine(t, ops).run()
})
}