oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package isolatedjob
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "slices"
9 "sync"
10 "time"
11)
12
13// Op names one Runner call, so a test can aim a fault at it.
14type Op string
15
16const (
17 OpLaunch Op = "launch"
18 OpGet Op = "get"
19 OpSuspend Op = "suspend"
20 OpResume Op = "resume"
21 OpStop Op = "stop"
22 OpList Op = "list"
23)
24
25// Fault is a provider misbehaviour the Fake can play once.
26type Fault string
27
28const (
29 // FaultThrottle: the call does nothing and returns ErrThrottled. Any op.
30 FaultThrottle Fault = "throttle"
31 // FaultLostReply: the call takes effect, then returns ErrLostReply in
32 // place of its answer. Any op.
33 FaultLostReply Fault = "lost reply"
34 // FaultIncompleteList: List returns (nil, ErrIncomplete). OpList only.
35 FaultIncompleteList Fault = "incomplete list"
36 // FaultUnknownState: Get reports StateUnknown; the VM is unchanged.
37 // OpGet only.
38 FaultUnknownState Fault = "unknown state"
39 // FaultAgeUnknown: Get reports AgeKnown false. OpGet only.
40 FaultAgeUnknown Fault = "age unknown"
41)
42
43// ErrLostReply is what a call hit by FaultLostReply returns. It is none of
44// the package's sentinels on purpose: the caller cannot tell whether the call
45// took effect, as with a timeout on a real provider.
46var ErrLostReply = errors.New("isolatedjob fake: reply lost; the call may have taken effect")
47
48// SpikeLimits returns the limits the 2026-11-18 spike found on AWS Lambda
49// MicroVMs (spec §15): 8 hours of lifetime counting suspended time, a
50// 4096-byte bootstrap, and open connections dropped by suspend.
51func SpikeLimits() Limits {
52 return Limits{
53 MaxLifetime: 28800 * time.Second,
54 MaxBootstrapBytes: 4096,
55 SuspendUsesLifetime: true,
56 ConnectionsSurvive: false,
57 }
58}
59
60// Fake is an in-memory Runner and NetworkAuditor for tests. It is safe for
61// concurrent use.
62//
63// Lifecycle. Launch creates a VM in starting. Tick moves every VM one step:
64// starting to running, suspending to suspended, stopping to stopped. Suspend
65// needs a running VM and moves it to suspending. Resume of a suspended VM is
66// accepted at once but the VM is still reported suspended until the next
67// Tick moves it to running, as AWS keeps a VM SUSPENDED while its /resume
68// hook runs; a second Resume in that window is accepted and changes nothing.
69// Resume of a running VM does nothing. Stop moves any live VM to stopping,
70// dropping a pending resume, and does nothing to a
71// stopped VM or a ref it never held. Other calls on a VM in the wrong state
72// return ErrConflict; calls on an unknown ref return ErrNotFound. Stopped VMs
73// stay visible to Get and List until Vanish removes them.
74//
75// Backstop. While the backstop is on (the default), Tick also moves to
76// stopping every VM whose lifetime has reached its spec's MaxLifetime, with
77// a reason naming the lifetime. Lifetime is measured on the clock's Mono from
78// launch and includes suspended time, unless the Limits say suspended time
79// does not count.
80//
81// Launch is idempotent on AttemptID, like a provider client token: the same
82// spec returns the same Ref even after that VM has stopped, and a different
83// spec under the same AttemptID returns ErrConflict. Launch validates the
84// spec against the fake's Limits first, so a bad spec never reaches the fake
85// provider and uses up no fault.
86//
87// Faults. Inject queues a fault for one op. The next call of that op takes
88// the oldest queued fault and uses it up, whatever the call's outcome. A call
89// whose context is already done returns the context's error and takes no
90// fault.
91type Fake struct {
92 clock Clock
93 limits Limits
94
95 mu sync.Mutex
96 backstop bool
97 nextID int
98 vms map[Ref]*fakeVM
99 order []Ref // creation order, for List
100 byAttempt map[string]Ref // the client-token table; Plant does not write it
101 faults map[Op][]Fault
102 stops []Ref
103 calls map[Op]int
104 audit NetworkAudit
105 auditErr error
106}
107
108type fakeVM struct {
109 ref Ref
110 spec LaunchSpec
111 state State
112 reason string
113 startedAt time.Time // Wall at launch
114 launched time.Duration // Mono at launch
115
116 // Suspended time, for providers whose lifetime leaves it out.
117 paused time.Duration // finished suspensions
118 pausedSince time.Duration // Mono when the current suspension began
119 isPaused bool
120
121 resuming bool // Resume accepted; the next Tick moves suspended to running
122
123 // vanished: the provider no longer shows the VM. The record stays so
124 // the client token still replays to the same Ref and spec.
125 vanished bool
126}
127
128// NewFake returns a Fake reading time from c and reporting limits l. Pass
129// SpikeLimits() for the limits the real provider has.
130func NewFake(c Clock, l Limits) *Fake {
131 return &Fake{
132 clock: c,
133 limits: l,
134 backstop: true,
135 vms: map[Ref]*fakeVM{},
136 byAttempt: map[string]Ref{},
137 faults: map[Op][]Fault{},
138 calls: map[Op]int{},
139 audit: NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true},
140 }
141}
142
143// Inject queues f for the next call of op. It panics when op cannot have f,
144// such as FaultIncompleteList on OpGet.
145func (f *Fake) Inject(op Op, fl Fault) {
146 ok := false
147 switch fl {
148 case FaultThrottle, FaultLostReply:
149 ok = slices.Contains([]Op{OpLaunch, OpGet, OpSuspend, OpResume, OpStop, OpList}, op)
150 case FaultIncompleteList:
151 ok = op == OpList
152 case FaultUnknownState, FaultAgeUnknown:
153 ok = op == OpGet
154 }
155 if !ok {
156 panic(fmt.Sprintf("isolatedjob fake: op %q cannot have fault %q", op, fl))
157 }
158 f.mu.Lock()
159 defer f.mu.Unlock()
160 f.faults[op] = append(f.faults[op], fl)
161}
162
163// takeFault removes and returns the oldest fault queued for op, or "".
164// The caller holds f.mu.
165func (f *Fake) takeFault(op Op) Fault {
166 q := f.faults[op]
167 if len(q) == 0 {
168 return ""
169 }
170 f.faults[op] = q[1:]
171 return q[0]
172}
173
174// begin starts one call of op: it checks ctx, takes the call's fault and
175// returns it, with the lock held. A throttle comes back as ErrThrottled.
176func (f *Fake) begin(ctx context.Context, op Op) (Fault, error) {
177 if err := ctx.Err(); err != nil {
178 return "", err
179 }
180 f.mu.Lock()
181 f.calls[op]++
182 fl := f.takeFault(op)
183 if fl == FaultThrottle {
184 f.mu.Unlock()
185 return fl, fmt.Errorf("%w: fake %s", ErrThrottled, op)
186 }
187 return fl, nil
188}
189
190// finish turns a lost reply into ErrLostReply; otherwise it returns err.
191func finish(fl Fault, op Op, err error) error {
192 if fl == FaultLostReply {
193 return fmt.Errorf("%w (fake %s)", ErrLostReply, op)
194 }
195 return err
196}
197
198// Launch starts a VM for s, or returns the VM already started for
199// s.AttemptID.
200func (f *Fake) Launch(ctx context.Context, s LaunchSpec) (Ref, error) {
201 if err := s.Validate(f.limits); err != nil {
202 return "", err
203 }
204 fl, err := f.begin(ctx, OpLaunch)
205 if err != nil {
206 return "", err
207 }
208 defer f.mu.Unlock()
209 ref, err := f.launchLocked(s)
210 if err = finish(fl, OpLaunch, err); err != nil {
211 return "", err
212 }
213 return ref, nil
214}
215
216func (f *Fake) launchLocked(s LaunchSpec) (Ref, error) {
217 if ref, ok := f.byAttempt[s.AttemptID]; ok {
218 if !sameSpec(f.vms[ref].spec, s) {
219 return "", fmt.Errorf("%w: attempt %s was launched with a different spec", ErrConflict, s.AttemptID)
220 }
221 return ref, nil
222 }
223 vm := f.addLocked(s, StateStarting)
224 f.byAttempt[s.AttemptID] = vm.ref
225 return vm.ref, nil
226}
227
228func sameSpec(a, b LaunchSpec) bool {
229 return a.AttemptID == b.AttemptID && a.Image == b.Image && a.Size == b.Size &&
230 a.MaxLifetime == b.MaxLifetime && bytes.Equal(a.Bootstrap, b.Bootstrap)
231}
232
233func (f *Fake) addLocked(s LaunchSpec, st State) *fakeVM {
234 f.nextID++
235 s.Bootstrap = bytes.Clone(s.Bootstrap)
236 vm := &fakeVM{
237 ref: Ref(fmt.Sprintf("vm-%04d", f.nextID)),
238 spec: s,
239 state: st,
240 startedAt: f.clock.Wall(),
241 launched: f.clock.Mono(),
242 }
243 f.vms[vm.ref] = vm
244 f.order = append(f.order, vm.ref)
245 return vm
246}
247
248// Plant adds a running VM that no Launch asked for, as an orphan left on the
249// provider, and returns its Ref. It counts in LiveByAttempt under
250// s.AttemptID, but a later Launch of s.AttemptID does not find it. s is not
251// validated; a zero MaxLifetime means the fake's Limits().MaxLifetime.
252func (f *Fake) Plant(s LaunchSpec) Ref {
253 f.mu.Lock()
254 defer f.mu.Unlock()
255 return f.addLocked(s, StateRunning).ref
256}
257
258// Get reads one VM.
259func (f *Fake) Get(ctx context.Context, ref Ref) (Job, error) {
260 fl, err := f.begin(ctx, OpGet)
261 if err != nil {
262 return Job{}, err
263 }
264 defer f.mu.Unlock()
265 vm, ok := f.visibleLocked(ref)
266 if !ok {
267 return Job{}, finish(fl, OpGet, fmt.Errorf("%w: %s", ErrNotFound, ref))
268 }
269 job := f.jobLocked(vm)
270 switch fl {
271 case FaultUnknownState:
272 job.State = StateUnknown
273 case FaultAgeUnknown:
274 job.ProviderAge, job.AgeKnown = 0, false
275 case FaultLostReply:
276 return Job{}, finish(fl, OpGet, nil)
277 }
278 return job, nil
279}
280
281func (f *Fake) jobLocked(vm *fakeVM) Job {
282 return Job{
283 Ref: vm.ref,
284 State: vm.state,
285 StartedAt: vm.startedAt,
286 Reason: vm.reason,
287 ProviderAge: f.clock.Mono() - vm.launched,
288 AgeKnown: true,
289 }
290}
291
292// Suspend moves a running VM to suspending.
293func (f *Fake) Suspend(ctx context.Context, ref Ref) error {
294 fl, err := f.begin(ctx, OpSuspend)
295 if err != nil {
296 return err
297 }
298 defer f.mu.Unlock()
299 vm, ok := f.visibleLocked(ref)
300 switch {
301 case !ok:
302 err = fmt.Errorf("%w: %s", ErrNotFound, ref)
303 case vm.state != StateRunning:
304 err = fmt.Errorf("%w: suspend %s while %s", ErrConflict, ref, vm.state)
305 default:
306 vm.state = StateSuspending
307 vm.isPaused, vm.pausedSince = true, f.clock.Mono()
308 }
309 return finish(fl, OpSuspend, err)
310}
311
312// Resume asks a suspended VM to resume; it reports suspended until the next
313// Tick. Suspended time ends when the resume is accepted. A running VM, or one
314// whose resume is already pending, is left alone.
315func (f *Fake) Resume(ctx context.Context, ref Ref) error {
316 fl, err := f.begin(ctx, OpResume)
317 if err != nil {
318 return err
319 }
320 defer f.mu.Unlock()
321 vm, ok := f.visibleLocked(ref)
322 switch {
323 case !ok:
324 err = fmt.Errorf("%w: %s", ErrNotFound, ref)
325 case vm.state == StateRunning:
326 case vm.state != StateSuspended:
327 err = fmt.Errorf("%w: resume %s while %s", ErrConflict, ref, vm.state)
328 default:
329 vm.resuming = true
330 vm.unpause(f.clock.Mono())
331 }
332 return finish(fl, OpResume, err)
333}
334
335func (vm *fakeVM) unpause(now time.Duration) {
336 if vm.isPaused {
337 vm.paused += now - vm.pausedSince
338 vm.isPaused = false
339 }
340}
341
342// Stop moves a live VM to stopping. A stopped VM, a stopping VM and a ref the
343// fake never held all succeed with no change. Every call that reaches the
344// fake is recorded for StopsIssued, throttled or not.
345func (f *Fake) Stop(ctx context.Context, ref Ref, reason string) error {
346 if err := ctx.Err(); err != nil {
347 return err
348 }
349 f.mu.Lock()
350 f.stops = append(f.stops, ref)
351 f.mu.Unlock()
352 fl, err := f.begin(ctx, OpStop)
353 if err != nil {
354 return err
355 }
356 defer f.mu.Unlock()
357 if vm, ok := f.visibleLocked(ref); ok && vm.state.Live() && vm.state != StateStopping {
358 f.stopLocked(vm, reason)
359 }
360 return finish(fl, OpStop, nil)
361}
362
363func (f *Fake) stopLocked(vm *fakeVM, reason string) {
364 vm.state = StateStopping
365 vm.reason = reason
366 vm.resuming = false
367 vm.unpause(f.clock.Mono())
368}
369
370// List returns every VM the fake holds, stopped ones included, in launch
371// order.
372func (f *Fake) List(ctx context.Context) ([]Job, error) {
373 fl, err := f.begin(ctx, OpList)
374 if err != nil {
375 return nil, err
376 }
377 defer f.mu.Unlock()
378 switch fl {
379 case FaultIncompleteList:
380 return nil, fmt.Errorf("%w: fake list", ErrIncomplete)
381 case FaultLostReply:
382 return nil, finish(fl, OpList, nil)
383 }
384 jobs := make([]Job, 0, len(f.order))
385 for _, ref := range f.order {
386 if vm, ok := f.visibleLocked(ref); ok {
387 jobs = append(jobs, f.jobLocked(vm))
388 }
389 }
390 return jobs, nil
391}
392
393// Limits returns the limits the fake was made with.
394func (f *Fake) Limits() Limits { return f.limits }
395
396// Tick moves every VM one lifecycle step, then, with the backstop on, stops
397// the VMs whose lifetime has run out.
398func (f *Fake) Tick() {
399 f.mu.Lock()
400 defer f.mu.Unlock()
401 now := f.clock.Mono()
402 for _, ref := range f.order {
403 vm, ok := f.visibleLocked(ref)
404 if !ok {
405 continue
406 }
407 switch vm.state {
408 case StateStarting:
409 vm.state = StateRunning
410 case StateSuspending:
411 vm.state = StateSuspended
412 case StateSuspended:
413 if vm.resuming {
414 vm.state, vm.resuming = StateRunning, false
415 }
416 case StateStopping:
417 vm.state = StateStopped
418 }
419 limit := vm.spec.MaxLifetime
420 if limit <= 0 {
421 limit = f.limits.MaxLifetime // a planted VM may name none
422 }
423 if f.backstop && vm.state.Live() && vm.state != StateStopping && f.lifetimeLocked(vm, now) >= limit {
424 f.stopLocked(vm, fmt.Sprintf("maximum lifetime %v reached", limit))
425 }
426 }
427}
428
429// lifetimeLocked is how much of its lifetime vm has used at now.
430func (f *Fake) lifetimeLocked(vm *fakeVM, now time.Duration) time.Duration {
431 used := now - vm.launched
432 if !f.limits.SuspendUsesLifetime {
433 used -= vm.paused
434 if vm.isPaused {
435 used -= now - vm.pausedSince
436 }
437 }
438 return used
439}
440
441// visibleLocked returns the VM for ref unless the fake never held it or it
442// has vanished. The caller holds f.mu.
443func (f *Fake) visibleLocked(ref Ref) (*fakeVM, bool) {
444 vm, ok := f.vms[ref]
445 if !ok || vm.vanished {
446 return nil, false
447 }
448 return vm, true
449}
450
451// Vanish makes the provider forget the VM for ref, in any state, as when a
452// stopped VM ages out or a VM is removed behind the controller's back. Get,
453// Suspend and Resume then return ErrNotFound, Stop returns nil, and List and
454// LiveByAttempt leave it out. It is not a Stop and is not recorded in
455// StopsIssued. The client token survives: a Launch replay of the same spec
456// still returns ref and a changed spec still conflicts. A ref the fake never
457// held is ignored.
458func (f *Fake) Vanish(ref Ref) {
459 f.mu.Lock()
460 defer f.mu.Unlock()
461 if vm, ok := f.vms[ref]; ok {
462 vm.vanished = true
463 vm.resuming = false
464 }
465}
466
467// Calls returns how many calls of op reached the fake provider: those past
468// spec validation and the context check, throttled ones included.
469func (f *Fake) Calls(op Op) int {
470 f.mu.Lock()
471 defer f.mu.Unlock()
472 return f.calls[op]
473}
474
475// SetBackstop turns the lifetime backstop on or off. It is on by default.
476func (f *Fake) SetBackstop(on bool) {
477 f.mu.Lock()
478 defer f.mu.Unlock()
479 f.backstop = on
480}
481
482// LiveByAttempt counts the live VMs under each attempt ID, planted ones
483// included. Attempts with no live VM are left out.
484func (f *Fake) LiveByAttempt() map[string]int {
485 f.mu.Lock()
486 defer f.mu.Unlock()
487 out := map[string]int{}
488 for _, vm := range f.vms {
489 if !vm.vanished && vm.state.Live() {
490 out[vm.spec.AttemptID]++
491 }
492 }
493 return out
494}
495
496// StopsIssued returns the refs passed to Stop, in call order.
497func (f *Fake) StopsIssued() []Ref {
498 f.mu.Lock()
499 defer f.mu.Unlock()
500 return slices.Clone(f.stops)
501}
502
503// SetAudit sets what AuditNetwork returns. The default is a passing audit
504// with no egress destinations.
505func (f *Fake) SetAudit(a NetworkAudit, err error) {
506 f.mu.Lock()
507 defer f.mu.Unlock()
508 a.EgressOnly = slices.Clone(a.EgressOnly)
509 f.audit, f.auditErr = a, err
510}
511
512// AuditNetwork returns what SetAudit last set.
513func (f *Fake) AuditNetwork(ctx context.Context) (NetworkAudit, error) {
514 if err := ctx.Err(); err != nil {
515 return NetworkAudit{}, err
516 }
517 f.mu.Lock()
518 defer f.mu.Unlock()
519 a := f.audit
520 a.EgressOnly = slices.Clone(a.EgressOnly)
521 return a, f.auditErr
522}
523
524var (
525 _ Runner = (*Fake)(nil)
526 _ NetworkAuditor = (*Fake)(nil)
527)
528