oficina / alta Public

adopt: host-scoped restart and witness

RestartCanonical restarts the canonical host only, after a dry run that
resolves exactly that route; RestartAndWait polls the probe every 5 s
for up to 5 min. RecordWitness binds Paul's typed sentence to the fresh
identity, delivery and the after snapshot's write-layer version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 23071b60af68eda645d462699c8a9201d05440a3 parent 21b2921
5 files changed, +784 −0
  • adopt/restart.go +123 −0
  • adopt/restart_test.go +358 −0
  • adopt/witness.go +79 −0
  • adopt/witness_test.go +211 −0
  • adopt/words.go +13 −0
diff --git a/adopt/restart.go b/adopt/restart.go
new file mode 100644
index 0000000..63a244c
--- /dev/null
+++ b/adopt/restart.go
@@ -0,0 +1,123 @@
+// This file holds the one way adoption restarts an app: the canonical
+// host alone, through the narrowed restart door, after a dry run shows
+// that the door resolves exactly that host.
+package adopt
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// RestartAndWait's polling. Variables only so tests can shorten them.
+var (
+ pollEvery = 5 * time.Second
+ pollLimit = 5 * time.Minute
+)
+
+// RestartCanonical restarts app's canonical host, and nothing else. Every
+// restart adoption makes, a rollback's included, comes through here; it
+// is the only caller of carlosop.RestartHost.
+//
+// id must be app's canonical record: its app, and the canonical host as
+// its record host or public alias. The restart door is first asked for a
+// dry run, which must resolve exactly [id.RecordHost]; anything else is
+// "restart-scope-<n>", n the number of routes it resolved, and nothing is
+// restarted. A route the dry run reports as hibernating is accepted: it
+// will not cycle now, but the next request wakes it on the new config,
+// and the probe that follows makes that request.
+//
+// A console without the narrowed door (carlosop.ErrNoScopedRestart), a
+// 503 or any other refusal is returned as it is, and nothing falls back
+// to the app-wide door. Without apply, only the dry run is made.
+func RestartCanonical(ctx context.Context, c *carlosop.Client, app provision.App, id Identity, apply bool) error {
+ host := CanonicalHost(app)
+ switch {
+ case c == nil:
+ return errors.New("adopt: no console client")
+ case id.App != app.Slug:
+ return errors.New("adopt: the identity is another app's")
+ case id.RecordHost == "" || id.RecordHost != host && id.PublicHost != host:
+ return errors.New("adopt: the identity is not the canonical host's")
+ }
+ routes, err := c.RestartHost(ctx, app.Slug, id.RecordHost, true)
+ if err != nil {
+ return err
+ }
+ if err := exactlyHost(routes, id.RecordHost); err != nil {
+ return err
+ }
+ if !apply {
+ return nil
+ }
+ routes, err = c.RestartHost(ctx, app.Slug, id.RecordHost, false)
+ if err != nil {
+ return err
+ }
+ // The request is made by now; a wider answer is still reported, so
+ // the run stops rather than carrying on as if one host cycled.
+ return exactlyHost(routes, id.RecordHost)
+}
+
+// exactlyHost is nil when routes is the one route host.
+func exactlyHost(routes []carlosop.RestartRoute, host string) error {
+ if len(routes) != 1 || routes[0].Host != host {
+ return fmt.Errorf("restart-scope-%d", len(routes))
+ }
+ return nil
+}
+
+// RestartAndWait restarts app's canonical host through RestartCanonical,
+// then probes its public origin every 5 s, for at most 5 min, until
+// until accepts what the probe saw, and returns that observation. A probe
+// that fails (the app is between processes) is polled through. Running
+// out of time is "restart-timeout", with the last reason.
+//
+// Without apply, it makes RestartCanonical's dry run and one probe, and
+// returns what that probe saw: nothing restarted, so nothing is waited
+// for and until is not asked.
+func RestartAndWait(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, id Identity, until func(Delivery) error, apply bool) (Delivery, error) {
+ if until == nil {
+ return Delivery{}, errors.New("adopt: nothing to wait for")
+ }
+ if err := RestartCanonical(ctx, c, app, id, apply); err != nil {
+ return Delivery{}, err
+ }
+ origin := provision.PublicOrigin(provision.AdoptionLabel, app.Slug)
+ if !apply {
+ return Probe(ctx, h, origin)
+ }
+ deadline := time.Now().Add(pollLimit)
+ var last Delivery
+ reason := errors.New("adopt: the app was not probed")
+ for {
+ // The restart is asynchronous, so the first probe waits too.
+ if time.Now().Add(pollEvery).After(deadline) {
+ return last, fmt.Errorf("adopt: restart-timeout: %w", reason)
+ }
+ t := time.NewTimer(pollEvery)
+ select {
+ case <-ctx.Done():
+ t.Stop()
+ return last, fmt.Errorf("adopt: stopped waiting for the restart: %w", ctx.Err())
+ case <-t.C:
+ }
+ d, err := Probe(ctx, h, origin)
+ if err != nil {
+ if ctx.Err() != nil {
+ return last, fmt.Errorf("adopt: stopped waiting for the restart: %w", ctx.Err())
+ }
+ reason = err
+ continue
+ }
+ last = d
+ if reason = until(d); reason == nil {
+ return d, nil
+ }
+ }
+}
diff --git a/adopt/restart_test.go b/adopt/restart_test.go
new file mode 100644
index 0000000..7ac761a
--- /dev/null
+++ b/adopt/restart_test.go
@@ -0,0 +1,358 @@
+package adopt
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+)
+
+// identity is the fixture's canonical identity, as Observe reads it.
+func (x *carlosFixture) identity(t *testing.T) Identity {
+ t.Helper()
+ snap, err := Observe(context.Background(), x.c, x.h, x.app)
+ if err != nil {
+ t.Fatalf("Observe: %v", err)
+ }
+ return snap.Identity
+}
+
+// dryRunRewriter puts a proxy in front of the fake console that edits the
+// routes of every dry-run answer from the restart door, as a console
+// that resolves a host more widely, or reports it hibernating, would. A
+// real request passes through untouched. The fixture's client is
+// replaced by one that speaks to the proxy.
+func (x *carlosFixture) dryRunRewriter(t *testing.T, edit func(routes []map[string]any) []map[string]any) {
+ t.Helper()
+ target, err := url.Parse(x.f.URL())
+ if err != nil {
+ t.Fatal(err)
+ }
+ rp := httputil.NewSingleHostReverseProxy(target)
+ rp.ModifyResponse = func(resp *http.Response) error {
+ if !strings.HasSuffix(resp.Request.URL.Path, "/restart/scope") || resp.StatusCode != 200 {
+ return nil
+ }
+ raw, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ return err
+ }
+ var answer map[string]any
+ if err := json.Unmarshal(raw, &answer); err != nil {
+ return err
+ }
+ if answer["dry_run"] == true {
+ var routes []map[string]any
+ for _, r := range answer["routes"].([]any) {
+ routes = append(routes, r.(map[string]any))
+ }
+ answer["routes"] = edit(routes)
+ if raw, err = json.Marshal(answer); err != nil {
+ return err
+ }
+ }
+ resp.Body = io.NopCloser(bytes.NewReader(raw))
+ resp.ContentLength = int64(len(raw))
+ resp.Header.Set("Content-Length", strconv.Itoa(len(raw)))
+ return nil
+ }
+ srv := httptest.NewServer(rp)
+ t.Cleanup(srv.Close)
+ x.c = carlosop.New(srv.URL, fixtureAccount, x.f.Token())
+ t.Cleanup(x.c.Close)
+}
+
+// noRestarts fails unless the fake saw no restart of any of hosts and no
+// app-wide restart.
+func (x *carlosFixture) noRestarts(t *testing.T, hosts ...string) {
+ t.Helper()
+ for _, h := range hosts {
+ if n := x.f.RestartCount(h); n != 0 {
+ t.Fatalf("%s restarted %d times", h, n)
+ }
+ }
+ if n := x.f.AppWideRestarts(); n != 0 {
+ t.Fatalf("app-wide restarts = %d", n)
+ }
+}
+
+// fastPolls shortens RestartAndWait's poll interval and limit for a test.
+func fastPolls(t *testing.T, every, limit time.Duration) {
+ t.Helper()
+ oldEvery, oldLimit := pollEvery, pollLimit
+ pollEvery, pollLimit = every, limit
+ t.Cleanup(func() { pollEvery, pollLimit = oldEvery, oldLimit })
+}
+
+func TestRestartAndWaitPollsEveryFiveSecondsForFiveMinutes(t *testing.T) {
+ if pollEvery != 5*time.Second || pollLimit != 5*time.Minute {
+ t.Fatalf("poll every %v for %v", pollEvery, pollLimit)
+ }
+}
+
+func TestRestartCanonicalLeavesOtherInstancesUntouched(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("staging.docs.example", "staging")
+ x.neighbour("bare.docs.example", "")
+ id := x.identity(t)
+ if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil {
+ t.Fatalf("RestartCanonical: %v", err)
+ }
+ if n := x.f.RestartCount("docs.oficina.works"); n != 1 {
+ t.Fatalf("canonical host restarted %d times, want 1", n)
+ }
+ x.noRestarts(t, "staging.docs.example", "bare.docs.example")
+ // The dry run comes first, then the one real request.
+ var doors []string
+ for _, r := range x.f.Requests() {
+ if strings.Contains(r, "restart") {
+ doors = append(doors, r)
+ }
+ }
+ if len(doors) != 2 {
+ t.Fatalf("restart requests %q, want a dry run then the request", doors)
+ }
+}
+
+func TestRestartCanonicalDryRunRestartsNothing(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ if err := RestartCanonical(context.Background(), x.c, x.app, id, false); err != nil {
+ t.Fatalf("RestartCanonical dry run: %v", err)
+ }
+ x.noRestarts(t, "docs.oficina.works")
+}
+
+func TestRestartCanonicalRefusesWiderDryRun(t *testing.T) {
+ cases := map[string]struct {
+ edit func([]map[string]any) []map[string]any
+ code string
+ }{
+ "neighbour added": {func(r []map[string]any) []map[string]any {
+ return append(r, map[string]any{"host": "staging.docs.example", "environment": "staging", "hibernate": false})
+ }, "restart-scope-2"},
+ "nothing resolved": {func([]map[string]any) []map[string]any { return []map[string]any{} }, "restart-scope-0"},
+ "another host": {func([]map[string]any) []map[string]any {
+ return []map[string]any{{"host": "staging.docs.example", "hibernate": false}}
+ }, "restart-scope-1"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("staging.docs.example", "staging")
+ id := x.identity(t)
+ x.dryRunRewriter(t, tc.edit)
+ err := RestartCanonical(context.Background(), x.c, x.app, id, true)
+ if err == nil || err.Error() != tc.code {
+ t.Fatalf("err = %v, want %s", err, tc.code)
+ }
+ x.noRestarts(t, "docs.oficina.works", "staging.docs.example")
+ })
+ }
+}
+
+// A hibernating canonical route is accepted: the probe wakes it, and
+// Delivered must still pass.
+func TestRestartCanonicalAcceptsHibernatingRoute(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ x.dryRunRewriter(t, func(r []map[string]any) []map[string]any {
+ r[0]["hibernate"] = true
+ return r
+ })
+ if err := RestartCanonical(context.Background(), x.c, x.app, id, true); err != nil {
+ t.Fatalf("RestartCanonical: %v", err)
+ }
+ if n := x.f.RestartCount("docs.oficina.works"); n != 1 {
+ t.Fatalf("restarted %d times", n)
+ }
+}
+
+func TestRestartCanonicalFailsClosedOnOldConsole(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("staging.docs.example", "staging")
+ id := x.identity(t)
+ x.f.NoScopedRestart()
+ err := RestartCanonical(context.Background(), x.c, x.app, id, true)
+ if !errors.Is(err, carlosop.ErrNoScopedRestart) {
+ t.Fatalf("err = %v, want ErrNoScopedRestart", err)
+ }
+ x.noRestarts(t, "docs.oficina.works", "staging.docs.example")
+ for _, r := range x.f.Requests() {
+ if strings.HasSuffix(r, " /restart") {
+ t.Fatalf("fell back to the app-wide door: %q", r)
+ }
+ }
+}
+
+func TestRestartCanonicalStopsOnUnavailableRegistry(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ x.f.FailRestart(http.StatusServiceUnavailable)
+ err := RestartCanonical(context.Background(), x.c, x.app, id, true)
+ var se *carlosop.StatusError
+ if !errors.As(err, &se) || se.Code != http.StatusServiceUnavailable {
+ t.Fatalf("err = %v, want a 503 status error", err)
+ }
+ x.noRestarts(t, "docs.oficina.works")
+}
+
+func TestRestartCanonicalRefusesAnotherAppsIdentity(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ cases := map[string]func(*Identity){
+ "no host": func(i *Identity) { i.RecordHost, i.PublicHost = "", "" },
+ "other host": func(i *Identity) { i.RecordHost, i.PublicHost = "staging.docs.example", "" },
+ "other app": func(i *Identity) { i.App = "sheets" },
+ }
+ for name, mutate := range cases {
+ t.Run(name, func(t *testing.T) {
+ bad := id
+ mutate(&bad)
+ if err := RestartCanonical(context.Background(), x.c, x.app, bad, true); err == nil {
+ t.Fatal("restarted for an identity that is not the canonical host's")
+ }
+ })
+ }
+ x.noRestarts(t, "docs.oficina.works")
+ for _, r := range x.f.Requests() {
+ if strings.Contains(r, "restart") {
+ t.Fatalf("sent %q for a refused identity", r)
+ }
+ }
+}
+
+func TestRestartAndWaitReturnsOnceUntilPasses(t *testing.T) {
+ fastPolls(t, 5*time.Millisecond, 2*time.Second)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ calls := 0
+ until := func(d Delivery) error {
+ calls++
+ if calls < 3 {
+ return errors.New("adopt: not yet")
+ }
+ return nil
+ }
+ d, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true)
+ if err != nil {
+ t.Fatalf("RestartAndWait: %v", err)
+ }
+ if calls != 3 || d.Version != valueVersion || d.Health != 200 {
+ t.Fatalf("calls %d delivery %+v", calls, d.Health)
+ }
+ if n := x.f.RestartCount("docs.oficina.works"); n != 1 {
+ t.Fatalf("restarted %d times", n)
+ }
+}
+
+func TestRestartAndWaitTimesOut(t *testing.T) {
+ fastPolls(t, 10*time.Millisecond, 120*time.Millisecond)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ before := x.site.delivery(t, x)
+ // The operations door never becomes agent-shaped.
+ until := func(d Delivery) error { return Delivered(before, d) }
+ start := time.Now()
+ _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, until, true)
+ if err == nil || !strings.Contains(err.Error(), "restart-timeout") {
+ t.Fatalf("err = %v, want restart-timeout", err)
+ }
+ if !strings.Contains(err.Error(), "the delegated-access door is not answering") {
+ t.Fatalf("err = %v, want the last reason", err)
+ }
+ if el := time.Since(start); el > 2*time.Second {
+ t.Fatalf("waited %v past a 120ms limit", el)
+ }
+ if n := x.f.RestartCount("docs.oficina.works"); n != 1 {
+ t.Fatalf("restarted %d times, want 1", n)
+ }
+}
+
+func TestRestartAndWaitKeepsPollingThroughUnreachable(t *testing.T) {
+ fastPolls(t, 5*time.Millisecond, 2*time.Second)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ probes := 0
+ h := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ if r.URL.Path == "/api/version" {
+ probes++
+ }
+ if probes <= 2 {
+ return nil, errors.New("connection refused")
+ }
+ return x.h.Transport.RoundTrip(r)
+ })}
+ d, err := RestartAndWait(context.Background(), x.c, h, x.app, id, func(Delivery) error { return nil }, true)
+ if err != nil || d.Version != valueVersion {
+ t.Fatalf("RestartAndWait: %v", err)
+ }
+}
+
+func TestRestartAndWaitStopsOnCancel(t *testing.T) {
+ fastPolls(t, 10*time.Millisecond, time.Minute)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ _, err := RestartAndWait(ctx, x.c, x.h, x.app, id, func(Delivery) error { return errors.New("adopt: never") }, true)
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("err = %v, want the context's", err)
+ }
+ if time.Since(start) > 5*time.Second {
+ t.Fatal("ignored the context")
+ }
+}
+
+func TestRestartAndWaitDryRunRestartsAndWaitsForNothing(t *testing.T) {
+ fastPolls(t, time.Hour, time.Hour)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ called := false
+ d, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, func(Delivery) error { called = true; return errors.New("x") }, false)
+ if err != nil {
+ t.Fatalf("dry run: %v", err)
+ }
+ if called || d.Version != valueVersion {
+ t.Fatalf("dry run evaluated until (%v) or did not probe", called)
+ }
+ x.noRestarts(t, "docs.oficina.works")
+}
+
+func TestRestartAndWaitDoesNotWaitWhenRestartRefused(t *testing.T) {
+ fastPolls(t, time.Hour, time.Hour)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ x.f.NoScopedRestart()
+ _, err := RestartAndWait(context.Background(), x.c, x.h, x.app, id, func(Delivery) error { return nil }, true)
+ if !errors.Is(err, carlosop.ErrNoScopedRestart) {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+// delivery probes the fixture's site as it stands.
+func (s *site) delivery(t *testing.T, x *carlosFixture) Delivery {
+ t.Helper()
+ d, err := Probe(context.Background(), x.h, "https://docs.oficina.works")
+ if err != nil {
+ t.Fatalf("Probe: %v", err)
+ }
+ return d
+}
diff --git a/adopt/witness.go b/adopt/witness.go
new file mode 100644
index 0000000..d34e191
--- /dev/null
+++ b/adopt/witness.go
@@ -0,0 +1,79 @@
+// This file records Paul's witnessed check of one app after its restart:
+// the spec's manual delivery evidence, in place of 522 Plan 2.
+package adopt
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// RecordWitness records Paul's witness for app. It refuses unless all of
+// these hold:
+//
+// - typed is WitnessSentence(app), surrounding space aside
+// (witness-sentence-mismatch), checked before anything is read;
+// - the after snapshot exists (witness-after-missing), and the baseline
+// it is measured against (witness-baseline-missing);
+// - a fresh observation's probe passes Delivered against the baseline
+// (witness-not-delivered);
+// - the fresh identity equals the after snapshot's
+// (witness-identity-<code>, one per SameIdentity code).
+//
+// The witness stores the sentence, the fresh identity and delivery, and
+// the after snapshot's write-layer version: it is bound to what was
+// observed, not to the clock, and a later change in any of them voids it.
+//
+// Without apply, it asks for no sentence and stores nothing; it observes
+// and refuses as it would with apply.
+func RecordWitness(ctx context.Context, s *Store, c *carlosop.Client, h *http.Client, app provision.App, typed string, apply bool) error {
+ if s == nil {
+ return errors.New("adopt: no adoption journal")
+ }
+ sentence := WitnessSentence(app)
+ if apply && strings.TrimSpace(typed) != sentence {
+ return errors.New("adopt: witness-sentence-mismatch")
+ }
+ after, ok, err := s.After(ctx, app.Slug)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("adopt: witness-after-missing")
+ }
+ base, ok, err := s.Baseline(ctx, app.Slug)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("adopt: witness-baseline-missing")
+ }
+ fresh, err := Observe(ctx, c, h, app)
+ if err != nil {
+ return err
+ }
+ if err := Delivered(base.Delivery, fresh.Delivery); err != nil {
+ return fmt.Errorf("adopt: witness-not-delivered: %w", err)
+ }
+ if codes := SameIdentity(after.Identity, fresh.Identity); len(codes) > 0 {
+ for i, code := range codes {
+ codes[i] = "witness-identity-" + code
+ }
+ return errors.New("adopt: " + strings.Join(codes, ", "))
+ }
+ if !apply {
+ return nil
+ }
+ return s.SaveWitness(ctx, Witness{
+ App: app.Slug, Typed: sentence,
+ Identity: fresh.Identity, Delivery: fresh.Delivery,
+ AfterVersion: after.Layer.Version,
+ At: time.Now().UTC(),
+ })
+}
diff --git a/adopt/witness_test.go b/adopt/witness_test.go
new file mode 100644
index 0000000..2195732
--- /dev/null
+++ b/adopt/witness_test.go
@@ -0,0 +1,211 @@
+package adopt
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// witnessFixture is an app configured and restarted: its baseline taken
+// with the operations door absent, the agent keys stored, the door now
+// answering agent-access's challenge, and the after snapshot recorded.
+type witnessFixture struct {
+ *carlosFixture
+ s *Store
+ after Snapshot
+}
+
+func newWitnessFixture(t *testing.T, slug string) *witnessFixture {
+ t.Helper()
+ x := newCarlosFixture(t, slug)
+ s := newJournal(t)
+ ctx := context.Background()
+ base, err := Observe(ctx, x.c, x.h, x.app)
+ if err != nil {
+ t.Fatalf("Observe baseline: %v", err)
+ }
+ if err := s.SaveBaseline(ctx, x.app.Slug, base); err != nil {
+ t.Fatal(err)
+ }
+ keys := AgentKeys(x.app)
+ x.f.SetVar(x.app.Slug, "", keys[0], Issuer)
+ x.f.SetVar(x.app.Slug, "", keys[1], "tm_fixture_sqid")
+ x.site.ops = agent401
+ after, err := Observe(ctx, x.c, x.h, x.app)
+ if err != nil {
+ t.Fatalf("Observe after: %v", err)
+ }
+ if err := s.SaveAfter(ctx, x.app.Slug, after); err != nil {
+ t.Fatal(err)
+ }
+ return &witnessFixture{carlosFixture: x, s: s, after: after}
+}
+
+func (w *witnessFixture) record(typed string, apply bool) error {
+ return RecordWitness(context.Background(), w.s, w.c, w.h, w.app, typed, apply)
+}
+
+func (w *witnessFixture) noWitness(t *testing.T) {
+ t.Helper()
+ if _, ok, err := w.s.Witness(context.Background(), w.app.Slug); err != nil || ok {
+ t.Fatalf("a witness was recorded (ok %v, err %v)", ok, err)
+ }
+}
+
+func TestWitnessSentenceNamesTheApp(t *testing.T) {
+ seen := map[string]string{}
+ for _, a := range provision.Apps {
+ s := WitnessSentence(a)
+ if !strings.Contains(s, CanonicalHost(a)) {
+ t.Fatalf("%s's sentence does not name its host: %q", a.Slug, s)
+ }
+ if other, dup := seen[s]; dup {
+ t.Fatalf("%s and %s share a sentence", a.Slug, other)
+ }
+ seen[s] = a.Slug
+ }
+}
+
+func TestWitnessRecordsBoundObservation(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ if err := w.record(" "+WitnessSentence(w.app)+"\n", true); err != nil {
+ t.Fatalf("RecordWitness: %v", err)
+ }
+ got, ok, err := w.s.Witness(context.Background(), "docs")
+ if err != nil || !ok {
+ t.Fatalf("no witness (ok %v, err %v)", ok, err)
+ }
+ if got.App != "docs" || got.Typed != WitnessSentence(w.app) || got.At.IsZero() {
+ t.Fatalf("witness app %q typed %q", got.App, got.Typed)
+ }
+ if codes := SameIdentity(got.Identity, w.after.Identity); len(codes) > 0 {
+ t.Fatalf("witness identity differs from the after snapshot's: %v", codes)
+ }
+ if got.AfterVersion == "" || got.AfterVersion != w.after.Layer.Version {
+ t.Fatal("witness is not bound to the after snapshot's write-layer version")
+ }
+ if got.Delivery.Ops != OpsAgent401 || got.Delivery.Version != valueVersion || got.Delivery.Header != valueVersion || got.Delivery.Health != 200 {
+ t.Fatalf("witness delivery ops %q health %d", got.Delivery.Ops, got.Delivery.Health)
+ }
+}
+
+func TestWitnessRefusesWrongAppSentence(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ for _, typed := range []string{
+ WitnessSentence(appNamed(t, "sheets")),
+ "",
+ strings.ToUpper(WitnessSentence(w.app)),
+ WitnessSentence(w.app) + " too",
+ } {
+ err := w.record(typed, true)
+ if err == nil || err.Error() != "adopt: witness-sentence-mismatch" {
+ t.Fatalf("typed %q: err = %v", typed, err)
+ }
+ }
+ w.noWitness(t)
+}
+
+// The sentence is checked before anything is read.
+func TestWitnessChecksSentenceBeforeReading(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ n := len(w.f.Requests())
+ if err := w.record("no", true); err == nil {
+ t.Fatal("accepted a wrong sentence")
+ }
+ if got := w.f.Requests(); len(got) != n {
+ t.Fatalf("read the console for a wrong sentence: %q", got[n:])
+ }
+}
+
+func TestWitnessRefusesWithoutAfterSnapshot(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ s := newJournal(t)
+ base, err := Observe(context.Background(), x.c, x.h, x.app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.SaveBaseline(context.Background(), "docs", base); err != nil {
+ t.Fatal(err)
+ }
+ x.site.ops = agent401
+ err = RecordWitness(context.Background(), s, x.c, x.h, x.app, WitnessSentence(x.app), true)
+ if err == nil || err.Error() != "adopt: witness-after-missing" {
+ t.Fatalf("err = %v", err)
+ }
+ if _, ok, _ := s.Witness(context.Background(), "docs"); ok {
+ t.Fatal("recorded a witness without an after snapshot")
+ }
+}
+
+func TestWitnessRefusesWithoutAgentShape(t *testing.T) {
+ cases := map[string]func(w *witnessFixture){
+ "absent": func(w *witnessFixture) { w.site.ops = nil },
+ "app-401": func(w *witnessFixture) {
+ w.site.ops = func(rw http.ResponseWriter) {
+ rw.WriteHeader(401)
+ _, _ = rw.Write([]byte(`{"error":"unauthorized"}`))
+ }
+ },
+ "unhealthy": func(w *witnessFixture) {
+ w.site.health = 503
+ },
+ "version moved": func(w *witnessFixture) {
+ w.site.version, w.site.header = "v1.5.0", "v1.5.0"
+ },
+ "redirect": func(w *witnessFixture) { w.site.redirectVersion = true },
+ }
+ for name, change := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ change(w)
+ if err := w.record(WitnessSentence(w.app), true); err == nil {
+ t.Fatal("recorded a witness the running app does not bear out")
+ }
+ w.noWitness(t)
+ })
+ }
+}
+
+func TestWitnessRefusesIdentityChangedSinceAfter(t *testing.T) {
+ cases := map[string]func(in *carlosop.Instance){
+ "record": func(in *carlosop.Instance) { in.RecordSeq++ },
+ "storage": func(in *carlosop.Instance) { in.Slug = "s-docs-recreated" },
+ "region": func(in *carlosop.Instance) { in.Region = "us" },
+ }
+ for name, change := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ in := carlosop.Instance{
+ Host: CanonicalHost(w.app), App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu",
+ CreatedAt: w.after.Identity.CreatedAt, RecordSeq: w.after.Identity.RecordSeq,
+ ReplicaAssignment: []byte(w.after.Identity.ReplicaAssignment),
+ }
+ change(&in)
+ w.f.AddInstance(in)
+ err := w.record(WitnessSentence(w.app), true)
+ if err == nil || err.Error() != "adopt: witness-identity-"+name {
+ t.Fatalf("err = %v, want witness-identity-%s", err, name)
+ }
+ w.noWitness(t)
+ })
+ }
+}
+
+func TestWitnessDryRunRecordsNothing(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ // A dry run asks for no sentence, so none is checked.
+ if err := w.record("", false); err != nil {
+ t.Fatalf("dry run: %v", err)
+ }
+ w.noWitness(t)
+ // It still observes, and refuses what apply would refuse.
+ w.site.ops = nil
+ if err := w.record("", false); err == nil {
+ t.Fatal("dry run passed an app the witness would refuse")
+ }
+ w.noWitness(t)
+}
diff --git a/adopt/words.go b/adopt/words.go
new file mode 100644
index 0000000..db4e7cd
--- /dev/null
+++ b/adopt/words.go
@@ -0,0 +1,13 @@
+// This file holds the words alta-adopt shows or asks Paul to type. They
+// go through the copy-review skill before merge (plan Task 14, step 5);
+// a change here is a change of copy.
+package adopt
+
+import "amadan.net/oficina/alta/provision"
+
+// WitnessSentence is what Paul types to witness app after its restart,
+// once he has signed in at its canonical host in his own browser. It
+// names the host, so a sentence typed for one app never records another.
+func WitnessSentence(app provision.App) string {
+ return "I signed in to " + CanonicalHost(app) + " and it works as before"
+}