oficina / alta Public

adopt: shared types and delivery probe

Types later tasks store (Identity, Snapshot, Witness, journal records),
SameIdentity, and a no-redirect probe that tells agent-access's 401
from an app's own 401.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev c80ac777702e0b3533deaeac8f4c9f0ef8d344aa parent ee7067d
4 files changed, +681 −0
  • adopt/delivery.go +197 −0
  • adopt/delivery_test.go +200 −0
  • adopt/types.go +168 −0
  • adopt/types_test.go +116 −0
diff --git a/adopt/delivery.go b/adopt/delivery.go
new file mode 100644
index 0000000..294b5a9
--- /dev/null
+++ b/adopt/delivery.go
@@ -0,0 +1,197 @@
+package adopt
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// OpsShape is what GET /api/v1/operations answers, reduced to the shapes
+// adoption tells apart. Slides and Calls already answer their own 401 there
+// (an app middleware, {"error":"unauthorized"}), so a bare 401 proves
+// nothing: only agent-access's own challenge counts.
+type OpsShape string
+
+const (
+ OpsAbsent OpsShape = "absent" // 404: the delegated-access code is not running
+ OpsApp401 OpsShape = "app-401" // a 401 that is not agent-access's challenge
+ OpsAgent401 OpsShape = "agent-401" // agent-access's challenge
+ OpsAgent200 OpsShape = "agent-200"
+ OpsOther OpsShape = "other"
+)
+
+// Delivery is what one probe saw of a running app. It carries versions and
+// status codes only, never a body beyond the version name.
+type Delivery struct {
+ Version, Header string
+ Redirected bool
+ Health int
+ Ops OpsShape
+ At time.Time
+}
+
+// agentShaped reports whether the delegated-access code answered.
+func (o OpsShape) agentShaped() bool { return o == OpsAgent401 || o == OpsAgent200 }
+
+// bodyLimit bounds every probe body.
+const bodyLimit = 1 << 20
+
+// Probe reads origin's /api/version, /healthz and /api/v1/operations
+// without following a redirect: a redirect is recorded in Delivered's
+// input, never chased. A plain-http origin must be loopback.
+func Probe(ctx context.Context, h *http.Client, origin string) (Delivery, error) {
+ u, err := url.Parse(origin)
+ if err != nil || u.Host == "" || u.Path != "" && u.Path != "/" {
+ return Delivery{}, errors.New("adopt: probe origin is not an origin")
+ }
+ if u.Scheme != "https" && !(u.Scheme == "http" && isLoopback(u.Hostname())) {
+ return Delivery{}, errors.New("adopt: probe origin must be https")
+ }
+ base := u.Scheme + "://" + u.Host
+ c := *h
+ c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+
+ d := Delivery{At: time.Now().UTC()}
+ status, hdr, body, err := get(ctx, &c, base+"/api/version")
+ if err != nil {
+ return Delivery{}, err
+ }
+ switch {
+ case status >= 300 && status < 400:
+ d.Redirected = true
+ case status == http.StatusOK:
+ d.Version = strings.TrimSpace(string(body))
+ d.Header = hdr.Get("X-Carlos-Version")
+ }
+ status, _, _, err = get(ctx, &c, base+"/healthz")
+ if err != nil {
+ return Delivery{}, err
+ }
+ if status >= 300 && status < 400 {
+ d.Redirected = true
+ }
+ d.Health = status
+ status, hdr, body, err = get(ctx, &c, base+"/api/v1/operations")
+ if err != nil {
+ return Delivery{}, err
+ }
+ if status >= 300 && status < 400 {
+ d.Redirected = true
+ }
+ d.Ops = shape(status, hdr, body)
+ return d, nil
+}
+
+func isLoopback(host string) bool {
+ if host == "localhost" {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
+// get does one GET. Its errors name the step, never the URL or a body.
+func get(ctx context.Context, c *http.Client, target string) (int, http.Header, []byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
+ if err != nil {
+ return 0, nil, nil, errors.New("adopt: probe request refused")
+ }
+ resp, err := c.Do(req)
+ if err != nil {
+ return 0, nil, nil, errors.New("adopt: probe unreachable")
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit))
+ if err != nil {
+ return 0, nil, nil, errors.New("adopt: probe answer unreadable")
+ }
+ return resp.StatusCode, resp.Header, body, nil
+}
+
+// shape classifies the operations answer. agent-401 is all of: status 401,
+// WWW-Authenticate beginning Bearer, Cache-Control no-store, and a body
+// {"error":{"code":"unauthenticated",…}}.
+func shape(status int, h http.Header, body []byte) OpsShape {
+ switch status {
+ case http.StatusNotFound:
+ return OpsAbsent
+ case http.StatusOK:
+ return OpsAgent200
+ case http.StatusUnauthorized:
+ if !strings.HasPrefix(h.Get("WWW-Authenticate"), "Bearer") ||
+ !hasToken(h.Get("Cache-Control"), "no-store") {
+ return OpsApp401
+ }
+ var b struct {
+ Error struct {
+ Code string `json:"code"`
+ } `json:"error"`
+ }
+ dec := json.NewDecoder(bytes.NewReader(body))
+ if dec.Decode(&b) != nil || b.Error.Code != "unauthenticated" {
+ return OpsApp401
+ }
+ return OpsAgent401
+ }
+ return OpsOther
+}
+
+func hasToken(header, want string) bool {
+ for _, t := range strings.Split(header, ",") {
+ if strings.EqualFold(strings.TrimSpace(t), want) {
+ return true
+ }
+ }
+ return false
+}
+
+// sameServing checks the parts delivery and rollback share: the version
+// and header unchanged, no redirect, health 200.
+func sameServing(before, now Delivery) error {
+ switch {
+ case now.Redirected:
+ return errors.New("adopt: the app redirected")
+ case before.Version == "" || now.Version != before.Version:
+ return errors.New("adopt: the served version changed")
+ case before.Header == "" || now.Header != before.Header:
+ return errors.New("adopt: the version header changed")
+ case now.Health != http.StatusOK:
+ return errors.New("adopt: the app is not healthy")
+ }
+ return nil
+}
+
+// Delivered says the restart delivered the new configuration: the same
+// version and header, no redirect, health 200, and the operations door
+// now agent-shaped where it was not.
+func Delivered(before, now Delivery) error {
+ if err := sameServing(before, now); err != nil {
+ return err
+ }
+ if before.Ops.agentShaped() {
+ return errors.New("adopt: the delegated-access door answered before the change")
+ }
+ if !now.Ops.agentShaped() {
+ return errors.New("adopt: the delegated-access door is not answering")
+ }
+ return nil
+}
+
+// Reverted says a rollback restart completed: the same version and header,
+// health 200, and the operations door back to the before shape.
+func Reverted(before, now Delivery) error {
+ if err := sameServing(before, now); err != nil {
+ return err
+ }
+ if now.Ops != before.Ops {
+ return errors.New("adopt: the operations door has not returned to its earlier shape")
+ }
+ return nil
+}
diff --git a/adopt/delivery_test.go b/adopt/delivery_test.go
new file mode 100644
index 0000000..29e2e68
--- /dev/null
+++ b/adopt/delivery_test.go
@@ -0,0 +1,200 @@
+package adopt
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// site is a fake app origin: version, header, healthz and operations are
+// each settable.
+type site struct {
+ version, header string
+ health int
+ ops func(w http.ResponseWriter)
+ redirectVersion bool
+}
+
+func (s *site) handler() http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/api/version", func(w http.ResponseWriter, r *http.Request) {
+ if s.redirectVersion {
+ http.Redirect(w, r, "/elsewhere", http.StatusFound)
+ return
+ }
+ w.Header().Set("X-Carlos-Version", s.header)
+ _, _ = w.Write([]byte(s.version + "\n"))
+ })
+ mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(s.health) })
+ mux.HandleFunc("/api/v1/operations", func(w http.ResponseWriter, r *http.Request) {
+ if s.ops == nil {
+ http.NotFound(w, r)
+ return
+ }
+ s.ops(w)
+ })
+ return mux
+}
+
+func agent401(w http.ResponseWriter) {
+ w.Header().Set("WWW-Authenticate", `Bearer realm="oficina"`)
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(401)
+ _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated","message":"x"}}`))
+}
+
+func probeOf(t *testing.T, s *site) Delivery {
+ t.Helper()
+ srv := httptest.NewServer(s.handler())
+ defer srv.Close()
+ d, err := Probe(context.Background(), srv.Client(), srv.URL)
+ if err != nil {
+ t.Fatalf("Probe: %v", err)
+ }
+ return d
+}
+
+func TestOperationsShapeDistinguishesAppMiddleware(t *testing.T) {
+ cases := map[string]struct {
+ ops func(w http.ResponseWriter)
+ want OpsShape
+ }{
+ "absent": {nil, "absent"},
+ "app-401": {func(w http.ResponseWriter) {
+ w.WriteHeader(401)
+ _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
+ }, "app-401"},
+ "app-401-with-bearer-but-string-error": {func(w http.ResponseWriter) {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(401)
+ _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
+ }, "app-401"},
+ "agent-401": {agent401, "agent-401"},
+ "agent-401-cache-missing": {func(w http.ResponseWriter) {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ w.WriteHeader(401)
+ _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated"}}`))
+ }, "app-401"},
+ "agent-401-wrong-scheme": {func(w http.ResponseWriter) {
+ w.Header().Set("WWW-Authenticate", "Basic")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(401)
+ _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated"}}`))
+ }, "app-401"},
+ "agent-401-wrong-code": {func(w http.ResponseWriter) {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(401)
+ _, _ = w.Write([]byte(`{"error":{"code":"other"}}`))
+ }, "app-401"},
+ "agent-200": {func(w http.ResponseWriter) { w.WriteHeader(200); _, _ = w.Write([]byte(`{}`)) }, "agent-200"},
+ "other": {func(w http.ResponseWriter) { w.WriteHeader(500) }, "other"},
+ }
+ for name, c := range cases {
+ t.Run(name, func(t *testing.T) {
+ d := probeOf(t, &site{version: "v1", header: "v1", health: 200, ops: c.ops})
+ if d.Ops != c.want {
+ t.Fatalf("ops = %q, want %q", d.Ops, c.want)
+ }
+ })
+ }
+}
+
+func TestProbeRecordsVersionHeaderHealth(t *testing.T) {
+ d := probeOf(t, &site{version: "v1.2", header: "rel-9", health: 200})
+ if d.Version != "v1.2" || d.Header != "rel-9" || d.Health != 200 || d.Redirected || d.At.IsZero() {
+ t.Fatalf("delivery = %+v", d)
+ }
+}
+
+func TestProbeRefusesRedirect(t *testing.T) {
+ s := &site{version: "v1", header: "v1", health: 200, redirectVersion: true}
+ srv := httptest.NewServer(s.handler())
+ defer srv.Close()
+ d, err := Probe(context.Background(), srv.Client(), srv.URL)
+ if err != nil {
+ t.Fatalf("Probe: %v", err)
+ }
+ if !d.Redirected || d.Version != "" {
+ t.Fatalf("a redirect must be recorded, not followed: %+v", d)
+ }
+ before := Delivery{Version: "v1", Header: "v1", Health: 200, Ops: "absent"}
+ now := Delivery{Version: "v1", Header: "v1", Health: 200, Ops: "agent-401", Redirected: true}
+ if err := Delivered(before, now); err == nil {
+ t.Fatal("Delivered accepted a redirect")
+ }
+}
+
+func TestProbeRefusesNonLoopbackHTTP(t *testing.T) {
+ if _, err := Probe(context.Background(), http.DefaultClient, "http://example.com"); err == nil {
+ t.Fatal("plain http to a non-loopback origin was accepted")
+ }
+}
+
+func TestProbeErrorsCarryNoBody(t *testing.T) {
+ s := &site{version: "secret-looking-body", header: "h", health: 200}
+ srv := httptest.NewServer(s.handler())
+ srv.Close()
+ _, err := Probe(context.Background(), srv.Client(), srv.URL)
+ if err == nil {
+ t.Fatal("expected a transport error")
+ }
+ if strings.Contains(err.Error(), "secret-looking-body") {
+ t.Fatal("error leaks a body")
+ }
+}
+
+func dl(v, h string, health int, ops OpsShape) Delivery {
+ return Delivery{Version: v, Header: h, Health: health, Ops: ops}
+}
+
+func TestDeliveredRefusesVersionOrHeaderChange(t *testing.T) {
+ before := dl("v1", "v1", 200, "absent")
+ if err := Delivered(before, dl("v1", "v1", 200, "agent-401")); err != nil {
+ t.Fatalf("good delivery refused: %v", err)
+ }
+ if err := Delivered(before, dl("v1", "v1", 200, "agent-200")); err != nil {
+ t.Fatalf("agent-200 refused: %v", err)
+ }
+ bad := map[string]Delivery{
+ "version": dl("v2", "v1", 200, "agent-401"),
+ "header": dl("v1", "v2", 200, "agent-401"),
+ "health": dl("v1", "v1", 503, "agent-401"),
+ "still-absent": dl("v1", "v1", 200, "absent"),
+ "still-app-401": dl("v1", "v1", 200, "app-401"),
+ "other": dl("v1", "v1", 200, "other"),
+ "redirect": {Version: "v1", Header: "v1", Health: 200, Ops: "agent-401", Redirected: true},
+ }
+ for n, now := range bad {
+ if err := Delivered(before, now); err == nil {
+ t.Errorf("%s: accepted", n)
+ }
+ }
+ // Before already agent-shaped: nothing was delivered by this run.
+ if err := Delivered(dl("v1", "v1", 200, "agent-401"), dl("v1", "v1", 200, "agent-401")); err == nil {
+ t.Error("an already agent-shaped before was accepted")
+ }
+}
+
+func TestRevertedRequiresBeforeShape(t *testing.T) {
+ before := dl("v1", "v1", 200, "app-401")
+ if err := Reverted(before, dl("v1", "v1", 200, "app-401")); err != nil {
+ t.Fatalf("good revert refused: %v", err)
+ }
+ bad := map[string]Delivery{
+ "still-agent": dl("v1", "v1", 200, "agent-401"),
+ "version": dl("v2", "v1", 200, "app-401"),
+ "header": dl("v1", "v2", 200, "app-401"),
+ "health": dl("v1", "v1", 503, "app-401"),
+ "other-shape": dl("v1", "v1", 200, "absent"),
+ }
+ for n, now := range bad {
+ if err := Reverted(before, now); err == nil {
+ t.Errorf("%s: accepted", n)
+ }
+ }
+}
diff --git a/adopt/types.go b/adopt/types.go
new file mode 100644
index 0000000..3413262
--- /dev/null
+++ b/adopt/types.go
@@ -0,0 +1,168 @@
+// Package adopt is the CARLOS half of the existing-team adoption runner.
+// This file holds the types the later tasks store and pass around.
+package adopt
+
+import (
+ "bytes"
+ "encoding/json"
+ "sort"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// Issuer is the connection issuer the apps are told to trust.
+const Issuer = "https://connect.oficina.works"
+
+// AgentKeys are the two keys adoption writes: issuer first, team second.
+// They are written and unset together, never one alone.
+func AgentKeys(app provision.App) [2]string {
+ return [2]string{app.Prefix + "_AGENT_ISSUER", app.Prefix + "_AGENT_TEAM"}
+}
+
+// CanonicalHost is the app's one public host, from Alta's own helper.
+func CanonicalHost(app provision.App) string {
+ return provision.PublicHost(provision.AdoptionLabel, app.Slug)
+}
+
+// Identity is what must not change while adoption runs. An instance's
+// persistent storage is identified by Slug, CreatedAt, ReplicaAssignment
+// and Seed: recreating the instance or swapping its storage gives a new
+// record or a new assignment, and a move changes Region and sets Move.
+// ReplicaAssignment and Seed are canonical JSON ("" when absent).
+type Identity struct {
+ Account, App, RecordHost, PublicHost, Slug, Environment, Channel, Region string
+ Owned, Moving bool
+ CreatedAt time.Time
+ RecordSeq uint64
+ ReplicaAssignment, Seed string
+}
+
+// IdentityOf describes an instance record with its effective view. It
+// never errors: JSON it cannot canonicalise is kept as its raw bytes, so a
+// change still shows.
+func IdentityOf(in carlosop.Instance, eff carlosop.Effective) Identity {
+ return Identity{
+ Account: in.Account, App: in.App, RecordHost: in.Host, PublicHost: in.PublicHost,
+ Slug: in.Slug, Environment: in.Environment, Channel: in.Channel, Region: in.Region,
+ Owned: eff.Owned, Moving: present(in.Move),
+ CreatedAt: in.CreatedAt, RecordSeq: in.RecordSeq,
+ ReplicaAssignment: canonical(in.ReplicaAssignment), Seed: canonical(in.Seed),
+ }
+}
+
+func present(raw json.RawMessage) bool {
+ t := bytes.TrimSpace(raw)
+ return len(t) > 0 && !bytes.Equal(t, []byte("null"))
+}
+
+// canonical re-encodes JSON with sorted keys and no spaces.
+func canonical(raw json.RawMessage) string {
+ if !present(raw) {
+ return ""
+ }
+ var v any
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.UseNumber()
+ if err := dec.Decode(&v); err != nil {
+ return string(raw)
+ }
+ out, err := json.Marshal(v)
+ if err != nil {
+ return string(raw)
+ }
+ return string(out)
+}
+
+// SameIdentity returns the sorted, distinct codes of what differs:
+// storage (slug, created_at, replica, seed), instance (record host, and
+// account or app), alias (public host), environment, owned, channel,
+// region, moving and record (the record's sequence).
+func SameIdentity(a, b Identity) []string {
+ set := map[string]bool{}
+ flag := func(differs bool, code string) {
+ if differs {
+ set[code] = true
+ }
+ }
+ flag(a.Slug != b.Slug || !a.CreatedAt.Equal(b.CreatedAt) ||
+ a.ReplicaAssignment != b.ReplicaAssignment || a.Seed != b.Seed, "storage")
+ flag(a.RecordHost != b.RecordHost || a.Account != b.Account || a.App != b.App, "instance")
+ flag(a.PublicHost != b.PublicHost, "alias")
+ flag(a.Environment != b.Environment, "environment")
+ flag(a.Owned != b.Owned, "owned")
+ flag(a.Channel != b.Channel, "channel")
+ flag(a.Region != b.Region, "region")
+ flag(a.Moving != b.Moving, "moving")
+ flag(a.RecordSeq != b.RecordSeq, "record")
+ codes := make([]string, 0, len(set))
+ for c := range set {
+ codes = append(codes, c)
+ }
+ sort.Strings(codes)
+ return codes
+}
+
+// Snapshot is one observation of an app's stored and effective config.
+// Values appear nowhere: Layers and the vars carry versions and digests,
+// so a Snapshot is sealed before it is stored.
+type Snapshot struct {
+ Identity Identity
+ WriteLayer string
+ Layer carlosop.Layer
+ Layers map[string]string
+ Vars []carlosop.EffectiveVar
+ HomeIssuer, HomeConsumer string
+ Delivery Delivery
+ At time.Time
+}
+
+// Witness is Paul's recorded confirmation for one app, bound to what he
+// observed. AfterVersion is the after snapshot's write-layer version,
+// sealed. Any change in Identity, Delivery or the config voids it.
+type Witness struct {
+ App, Typed string
+ Identity Identity
+ Delivery Delivery
+ AfterVersion string
+ At time.Time
+}
+
+// HomePreflight is Home's state before a phase, from signed inspects and
+// Paul's read-only counts. Phase is "pre-initialize" or "pre-plan-a".
+type HomePreflight struct {
+ Phase string
+ CredentialSeq int64
+ DirectorySeq int64
+ CredentialHead string
+ Generation *string
+ ProposedID int64
+ ProposedSQID string
+ Pending, Open bool
+ Counts map[string]int64
+ AttestedAt time.Time
+}
+
+// WriteRecord journals one app's write. State is sent, landed or stopped.
+type WriteRecord struct {
+ App, State string
+ Sent map[string]string
+ Receipt *carlosop.Receipt
+ Code string
+}
+
+// RollbackRecord journals one app's rollback. State is sent, unset,
+// restarted or stopped.
+type RollbackRecord struct {
+ App, State string
+ Receipt *carlosop.Receipt
+ Code string
+}
+
+// RequiredLiveChecks are the checks recorded as passed before Plan C.
+var RequiredLiveChecks = []string{
+ "non-member-refused", "member-allowed", "member-no-local-permission-refused",
+ "revoked-membership-refused", "local-access-kept", "owner-allowed",
+ "owner-revoked-refused", "owner-local-access-kept",
+}
diff --git a/adopt/types_test.go b/adopt/types_test.go
new file mode 100644
index 0000000..ea23fc7
--- /dev/null
+++ b/adopt/types_test.go
@@ -0,0 +1,116 @@
+package adopt
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+func TestAgentKeysAndCanonicalHost(t *testing.T) {
+ app, ok := provision.AppBySlug("docs")
+ if !ok {
+ t.Fatal("no docs app")
+ }
+ k := AgentKeys(app)
+ if k[0] != app.Prefix+"_AGENT_ISSUER" || k[1] != app.Prefix+"_AGENT_TEAM" {
+ t.Fatalf("keys = %v", k)
+ }
+ if CanonicalHost(app) != "docs.oficina.works" {
+ t.Fatalf("host = %q", CanonicalHost(app))
+ }
+ if Issuer != "https://connect.oficina.works" {
+ t.Fatal("issuer")
+ }
+}
+
+func inst() (carlosop.Instance, carlosop.Effective) {
+ return carlosop.Instance{
+ Host: "rec.example", PublicHost: "docs.oficina.works", Account: "bds", App: "docs", Slug: "s1",
+ Environment: "env1", Channel: "stable", Region: "eu", RecordSeq: 7,
+ CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
+ ReplicaAssignment: json.RawMessage(`{"b": 2, "a": 1}`), Seed: json.RawMessage(`{"x":[1, 2]}`),
+ },
+ carlosop.Effective{Host: "rec.example", Environment: "env1", Owned: false}
+}
+
+func TestIdentityOf(t *testing.T) {
+ in, eff := inst()
+ id := IdentityOf(in, eff)
+ if id.Account != "bds" || id.App != "docs" || id.RecordHost != "rec.example" || id.PublicHost != "docs.oficina.works" ||
+ id.Slug != "s1" || id.Environment != "env1" || id.Channel != "stable" || id.Region != "eu" || id.RecordSeq != 7 {
+ t.Fatalf("identity = %+v", id)
+ }
+ if id.Moving || id.Owned {
+ t.Fatal("moving/owned set")
+ }
+ if id.ReplicaAssignment != `{"a":1,"b":2}` || id.Seed != `{"x":[1,2]}` {
+ t.Fatalf("not canonical: %q %q", id.ReplicaAssignment, id.Seed)
+ }
+ in.Move = json.RawMessage(`{"to":"us"}`)
+ eff.Owned = true
+ id = IdentityOf(in, eff)
+ if !id.Moving || !id.Owned {
+ t.Fatal("moving/owned not carried")
+ }
+ in.Move = json.RawMessage(`null`)
+ if IdentityOf(in, eff).Moving {
+ t.Fatal("a JSON null move counts as moving")
+ }
+ in.ReplicaAssignment, in.Seed = nil, nil
+ id = IdentityOf(in, eff)
+ if id.ReplicaAssignment != "" || id.Seed != "" {
+ t.Fatal("absent should be empty")
+ }
+}
+
+func TestSameIdentityFlagsEachField(t *testing.T) {
+ in, eff := inst()
+ base := IdentityOf(in, eff)
+ if got := SameIdentity(base, base); len(got) != 0 {
+ t.Fatalf("equal identities differ: %v", got)
+ }
+ cases := []struct {
+ name, code string
+ mut func(*Identity)
+ }{
+ {"slug", "storage", func(i *Identity) { i.Slug = "s2" }},
+ {"created_at", "storage", func(i *Identity) { i.CreatedAt = i.CreatedAt.Add(time.Second) }},
+ {"replica", "storage", func(i *Identity) { i.ReplicaAssignment = `{"a":9}` }},
+ {"seed", "storage", func(i *Identity) { i.Seed = `{"x":[]}` }},
+ {"record-host", "instance", func(i *Identity) { i.RecordHost = "other.example" }},
+ {"public-host", "alias", func(i *Identity) { i.PublicHost = "other.oficina.works" }},
+ {"environment", "environment", func(i *Identity) { i.Environment = "env2" }},
+ {"owned", "owned", func(i *Identity) { i.Owned = !i.Owned }},
+ {"channel", "channel", func(i *Identity) { i.Channel = "beta" }},
+ {"region", "region", func(i *Identity) { i.Region = "us" }},
+ {"moving", "moving", func(i *Identity) { i.Moving = !i.Moving }},
+ {"record-seq", "record", func(i *Identity) { i.RecordSeq++ }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ b := base
+ c.mut(&b)
+ got := SameIdentity(base, b)
+ if !reflect.DeepEqual(got, []string{c.code}) {
+ t.Fatalf("codes = %v, want [%s]", got, c.code)
+ }
+ })
+ }
+ t.Run("several-sorted-unique", func(t *testing.T) {
+ b := base
+ b.Slug, b.Seed, b.Region = "z", "{}", "us"
+ if got := SameIdentity(base, b); !reflect.DeepEqual(got, []string{"region", "storage"}) {
+ t.Fatalf("codes = %v", got)
+ }
+ })
+}
+
+func TestRequiredLiveChecksFixed(t *testing.T) {
+ if len(RequiredLiveChecks) != 8 {
+ t.Fatal("eight live checks")
+ }
+}