package isolatedjobtest import ( "context" "crypto/rand" "encoding/hex" "errors" "fmt" "slices" "testing" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // Harness is what Contract needs from one Runner implementation. type Harness struct { Runner isolatedjob.Runner // Image is a certified image the runner can launch. Image isolatedjob.ImageDigest // Settle waits until the VM's state satisfies want and returns the job // as last read. It returns an error when the VM cannot be read (which // may wrap isolatedjob.ErrNotFound) or when the state does not arrive in // the implementation's own time bound, and it bounds each read it makes. Settle func(ctx context.Context, ref isolatedjob.Ref, want func(isolatedjob.State) bool) (isolatedjob.Job, error) // ListLag is how long List may take to show a VM that Get already shows // as running. Zero means at once, as for the fake. ListLag time.Duration // Visibility is how long Get may answer ErrNotFound for a VM that // Launch has just returned, as a provider whose reads are eventually // consistent does. It bounds only the wait for a new VM to appear, never // a wait for a state. Zero means at once, as for the fake. Visibility time.Duration // CallTimeout bounds each Runner call the contract makes, so a stalled // request fails the run instead of hanging it. Zero means // DefaultCallTimeout. CallTimeout time.Duration // Logf, when set, gets the measured delays (how long Get took to show // each new VM, and List to show a running one) in place of t.Logf. A // live run leaves it nil, so they appear with go test -v. Logf func(format string, args ...any) } // logf writes one measurement through h.Logf, or t.Logf when it is nil. func (h Harness) logf(t *testing.T, format string, args ...any) { t.Helper() if h.Logf != nil { h.Logf(format, args...) return } t.Logf(format, args...) } // DefaultCallTimeout bounds each Runner call when the Harness sets no // CallTimeout. const DefaultCallTimeout = 30 * time.Second // call returns the context for one Runner call, bounded by CallTimeout. func (h Harness) call() (context.Context, context.CancelFunc) { d := h.CallTimeout if d <= 0 { d = DefaultCallTimeout } return context.WithTimeout(context.Background(), d) } func (h Harness) launch(s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { ctx, cancel := h.call() defer cancel() return h.Runner.Launch(ctx, s) } func (h Harness) get(ref isolatedjob.Ref) (isolatedjob.Job, error) { ctx, cancel := h.call() defer cancel() return h.Runner.Get(ctx, ref) } func (h Harness) list() ([]isolatedjob.Job, error) { ctx, cancel := h.call() defer cancel() return h.Runner.List(ctx) } func (h Harness) stop(ref isolatedjob.Ref, reason string) error { ctx, cancel := h.call() defer cancel() return h.Runner.Stop(ctx, ref, reason) } func (h Harness) suspend(ref isolatedjob.Ref) error { ctx, cancel := h.call() defer cancel() return h.Runner.Suspend(ctx, ref) } func (h Harness) resume(ref isolatedjob.Ref) error { ctx, cancel := h.call() defer cancel() return h.Runner.Resume(ctx, ref) } // contractLifetime keeps VMs launched by a live run short. const contractLifetime = 15 * time.Minute // Contract checks the behaviour every Runner must share. It uses only the // Runner interface and the Harness, so it runs against the fake and, behind // the hostedlive build tag, against a real provider. Each subtest stops the // VMs it launched. Attempt IDs carry a random part, so a second run against // a provider that remembers client tokens does not get the first run's VMs. // Every VM the contract launches must show in Get within h.Visibility // before any check reads it. func Contract(t *testing.T, h Harness) { t.Helper() run := randomHex(t, 6) n := 0 attempt := func() string { n++ return fmt.Sprintf("contract-%s-%d", run, n) } spec := func() isolatedjob.LaunchSpec { return isolatedjob.LaunchSpec{ AttemptID: attempt(), Image: h.Image, Size: isolatedjob.SizeSmall, MaxLifetime: min(contractLifetime, h.Runner.Limits().MaxLifetime), Bootstrap: []byte("contract-bootstrap"), } } launch := func(t *testing.T, s isolatedjob.LaunchSpec) isolatedjob.Ref { t.Helper() ref, err := h.launch(s) if err != nil { t.Fatalf("Launch(%s) = %v, want a ref", s.AttemptID, err) } t.Cleanup(func() { if err := h.stop(ref, "contract cleanup"); err != nil { t.Errorf("cleanup Stop(%s) = %v", ref, err) } }) appear(t, h, ref) return ref } settle := func(t *testing.T, ref isolatedjob.Ref, want isolatedjob.State) isolatedjob.Job { t.Helper() job, err := h.Settle(context.Background(), ref, func(s isolatedjob.State) bool { return s == want }) if err != nil { t.Fatalf("Settle(%s, %s) = %v", ref, want, err) } return job } t.Run("LaunchIdempotentOnAttempt", func(t *testing.T) { s := spec() first := launch(t, s) again, err := h.launch(s) if err != nil { t.Fatalf("second Launch(%s) = %v, want the first ref", s.AttemptID, err) } if again != first { t.Fatalf("second Launch(%s) = %s, want %s: one attempt must be one VM", s.AttemptID, again, first) } job, err := h.get(first) if err != nil { t.Fatalf("Get(%s) = %v", first, err) } if !job.State.Live() { t.Fatalf("Get(%s).State = %s, want a live state", first, job.State) } }) t.Run("ChangedSpecConflicts", func(t *testing.T) { s := spec() first := launch(t, s) changed := s changed.Bootstrap = []byte("another-bootstrap") ref, err := h.launch(changed) if !errors.Is(err, isolatedjob.ErrConflict) { t.Fatalf("Launch with the same attempt and a new bootstrap = (%q, %v), want ErrConflict", ref, err) } if ref == first { t.Fatalf("Launch with a changed spec returned the first VM %s", first) } }) t.Run("StopTwice", func(t *testing.T) { ref := launch(t, spec()) for i := 1; i <= 2; i++ { if err := h.stop(ref, "contract stop twice"); err != nil { t.Fatalf("Stop %d of %s = %v, want nil", i, ref, err) } } }) t.Run("StopUnknownRef", func(t *testing.T) { ref := isolatedjob.Ref("contract-never-launched-" + run) if err := h.stop(ref, "contract unknown ref"); err != nil { t.Fatalf("Stop(%s) of a ref the provider never held = %v, want nil", ref, err) } }) t.Run("GetAfterStop", func(t *testing.T) { ref := launch(t, spec()) if err := h.stop(ref, "contract get after stop"); err != nil { t.Fatalf("Stop(%s) = %v", ref, err) } _, err := h.Settle(context.Background(), ref, isolatedjob.State.Terminal) if err != nil && !errors.Is(err, isolatedjob.ErrNotFound) { t.Fatalf("Settle(%s, terminal) = %v, want a terminal state or ErrNotFound", ref, err) } job, err := h.get(ref) switch { case errors.Is(err, isolatedjob.ErrNotFound): case err != nil: t.Fatalf("Get(%s) after stop = %v, want a terminal state or ErrNotFound", ref, err) case !job.State.Terminal(): t.Fatalf("Get(%s) after stop = %s, want a terminal state or ErrNotFound, never %s", ref, job.State, isolatedjob.StateUnknown) } }) t.Run("SuspendResumeRoundTrip", func(t *testing.T) { ref := launch(t, spec()) settle(t, ref, isolatedjob.StateRunning) if err := h.suspend(ref); err != nil { t.Fatalf("Suspend(%s) = %v", ref, err) } settle(t, ref, isolatedjob.StateSuspended) if err := h.resume(ref); err != nil { t.Fatalf("Resume(%s) = %v", ref, err) } settle(t, ref, isolatedjob.StateRunning) }) t.Run("ResumeRunningIsNoop", func(t *testing.T) { ref := launch(t, spec()) settle(t, ref, isolatedjob.StateRunning) if err := h.resume(ref); err != nil { t.Fatalf("Resume(%s) of a running VM = %v, want nil", ref, err) } job, err := h.get(ref) if err != nil { t.Fatalf("Get(%s) = %v", ref, err) } if job.State != isolatedjob.StateRunning { t.Fatalf("Get(%s).State after a no-op resume = %s, want %s", ref, job.State, isolatedjob.StateRunning) } }) t.Run("OversizeBootstrapRefusedBeforeProvider", func(t *testing.T) { // A VM the contract launched must show in List first, so a List // that always comes back empty cannot pass the check below. known := launch(t, spec()) settle(t, known, isolatedjob.StateRunning) before := listUntil(t, h, known) s := spec() s.Bootstrap = make([]byte, h.Runner.Limits().MaxBootstrapBytes+1) for i := range s.Bootstrap { s.Bootstrap[i] = 'x' } ref, err := h.launch(s) if ref != "" { t.Cleanup(func() { _ = h.stop(ref, "contract cleanup") }) } if !errors.Is(err, isolatedjob.ErrBootstrapTooLarge) { t.Fatalf("Launch with a %d-byte bootstrap = (%q, %v), want ErrBootstrapTooLarge", len(s.Bootstrap), ref, err) } after := listRefs(t, h) if !slices.Contains(after, known) { t.Fatalf("List after a refused launch = %v, want it still to hold running VM %s", after, known) } for _, r := range after { if !slices.Contains(before, r) { t.Fatalf("List after a refused launch holds new VM %s; the refusal must come before the provider", r) } } }) t.Run("LimitsAreSane", func(t *testing.T) { l := h.Runner.Limits() if l.MaxLifetime <= 0 || l.MaxLifetime > isolatedjob.HardMaxLifetime { t.Errorf("Limits().MaxLifetime = %v, want above zero and at most %v", l.MaxLifetime, isolatedjob.HardMaxLifetime) } if l.MaxBootstrapBytes <= 0 { t.Errorf("Limits().MaxBootstrapBytes = %d, want above zero", l.MaxBootstrapBytes) } }) } // appear reads ref with Get until the provider shows it, for at most // h.Visibility after the first read. Only ErrNotFound and ErrThrottled are // read again; any other error, or ref still missing when the time is up, // fails the test. Zero Visibility is one read. Reads are spaced a // twentieth of Visibility apart, at most a second, so a short window in a // test costs little. func appear(t *testing.T, h Harness, ref isolatedjob.Ref) { t.Helper() start := time.Now() deadline := start.Add(h.Visibility) gap := min(time.Second, max(h.Visibility/20, time.Millisecond)) for reads := 1; ; reads++ { _, err := h.get(ref) if err == nil { h.logf(t, "visibility: Get showed new VM %s %v after Launch returned (%d reads)", ref, time.Since(start), reads) return } if !errors.Is(err, isolatedjob.ErrNotFound) && !errors.Is(err, isolatedjob.ErrThrottled) { t.Fatalf("Get(%s) of a VM Launch just returned = %v", ref, err) } if !time.Now().Before(deadline) { t.Fatalf("Get(%s) = %v for %v after Launch returned it, want the VM to appear", ref, err, h.Visibility) } time.Sleep(min(gap, time.Until(deadline))) } } func listRefs(t *testing.T, h Harness) []isolatedjob.Ref { t.Helper() jobs, err := h.list() if err != nil { t.Fatalf("List = %v", err) } refs := make([]isolatedjob.Ref, 0, len(jobs)) for _, j := range jobs { refs = append(refs, j.Ref) } return refs } // listUntil lists until the result holds a live job for ref, for at most // h.ListLag, and returns the refs of that list. It fails the test when ref // never shows. Each List is bounded by h.CallTimeout, so a stalled request // overruns ListLag by at most that; zero ListLag is one List. func listUntil(t *testing.T, h Harness, ref isolatedjob.Ref) []isolatedjob.Ref { t.Helper() start := time.Now() deadline := start.Add(h.ListLag) for lists := 1; ; lists++ { jobs, err := h.list() if err != nil { t.Fatalf("List = %v", err) } refs := make([]isolatedjob.Ref, 0, len(jobs)) found := false for _, j := range jobs { refs = append(refs, j.Ref) found = found || (j.Ref == ref && j.State.Live()) } if found { h.logf(t, "list lag: List showed running VM %s %v after Get did (%d lists)", ref, time.Since(start), lists) return refs } if !time.Now().Before(deadline) { t.Fatalf("List = %v after %v, want it to hold running VM %s", refs, h.ListLag, ref) } time.Sleep(min(time.Second, time.Until(deadline))) } } func randomHex(t *testing.T, n int) string { t.Helper() b := make([]byte, n) if _, err := rand.Read(b); err != nil { t.Fatalf("random attempt id: %v", err) } return hex.EncodeToString(b) }