| new file mode 100644 |
| index 000000000..a319caab7 |
| --- /dev/null |
| +++ b/internal/host/hadepartures_g3_test.go |
| @@ -0,0 +1,689 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math/rand" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/hostfiles" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type g3Departure struct { |
| + a departureArm |
| + c *Controller |
| + fx *locktest.LockFixture |
| + store release.Store |
| + queue *departureSQSTransport |
| + now, start, expiry time.Time |
| + dead, peer hadeparture.Box |
| + id, edgesKey, edgesTag string |
| + records []provision.Record |
| + pages int |
| +} |
| + |
| +func newG3Departure(t *testing.T, n int) *g3Departure { |
| + t.Helper() |
| + t.Cleanup(lease.ProcessStateForTest()) |
| + previous := metricsDepartures.Load() |
| + t.Cleanup(func() { metricsDepartures.Store(previous) }) |
| + x := &g3Departure{fx: locktest.NewLockFixture(t), start: time.Now().Add(-time.Hour).UTC()} |
| + x.now, x.expiry = x.start, x.start.Add(15*time.Minute) |
| + x.a, _, _ = departureArmFixtureBucket(t, x.fx.Bucket) |
| + a := &x.a |
| + a.Backend.Registry = a.Registry |
| + a.Backend.DataDir = filepath.Join(t.TempDir(), "data") |
| + a.Backend.RunDirOverride = filepath.Join(t.TempDir(), "run") |
| + a.Backend.Control = instancectl.NewClient("/unused/control.sock") |
| + var err error |
| + x.store, err = a.OpenStore(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.dead = hadeparture.Box{Account: a.Self.Account, InstanceID: "i-1123456789abcdef0", Scope: a.Self.Scope} |
| + x.dead.Ref = groupReferenceOf(x.dead.Account, x.dead.InstanceID) |
| + x.peer = hadeparture.Box{Account: a.Self.Account, InstanceID: "i-2123456789abcdef0", Scope: a.Self.Scope} |
| + x.peer.Ref = groupReferenceOf(x.peer.Account, x.peer.InstanceID) |
| + signer := boxidtest.NewSigner(t) |
| + a.Verifier = boxid.Verifier{Account: a.Self.Account, Certs: signer.Certs()} |
| + for _, b := range []hadeparture.Box{a.Self, x.dead, x.peer} { |
| + _, raw := signer.Record(t, b.Ref, b.Account, b.Scope.CloudRegion, b.InstanceID) |
| + if _, err = x.store.Put(t.Context(), boxid.Key(b.Ref), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for i := 0; i < n; i++ { |
| + rec := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: fmt.Sprintf("g3-%03d.example.com", i), Channel: "stable", HA: true, CreatedAt: x.start.Add(-time.Hour)} |
| + if i > 0 { |
| + rec.Region = "elsewhere" |
| + } |
| + x.records = append(x.records, rec) |
| + if err = provision.CreateRecord(t.Context(), x.store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + a.Backend.Cfg.Record = func(ctx context.Context, rt registry.Route) (activator.RecordFacts, error) { |
| + rec, _, e := provision.FindRecordByHost(ctx, x.store, rt.Host) |
| + if e != nil { |
| + return activator.RecordFacts{}, e |
| + } |
| + return activator.RecordFactsOf(*rec) |
| + } |
| + rec := x.records[0] |
| + rt := registry.Route{Host: rec.Host, Kind: "instance", Account: rec.Account, App: rec.App, Channel: rec.Channel, Status: "ready", HA: true, Provisioned: true, Hibernate: true, DBPath: provision.NestedDBPath(a.Backend.DataDir, rec.Host), Socket: filepath.Join(a.Backend.RunDirOverride, "instances", provision.InstanceID(rec.Host), "app.sock")} |
| + if err = a.Registry.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + files, err := lease.NewFilesStore(t.Context(), x.fx.Bucket, a.Self.Scope.CloudRegion) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.Backend.FilesStore = files |
| + a.Service = activator.New(a.Backend.Cfg, a.Backend, a.Registry) |
| + a.Service.DutyStore = a.Registry |
| + lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion}) |
| + if err = lease.SetObligationDir(t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| + pub, err := hostfiles.Open(t.Context(), files, "instances/"+rec.Host+"/files/0/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + due := time.Now().Add(48 * time.Hour).Unix() |
| + if err = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: rec.Host, NextDue: due, Timers: []hostfiles.WakeTimer{{Name: "reminder", Kind: "once", Spec: fmt.Sprintf("at %d", due), Path: "/remind", NextAt: due, DueAt: due, Registration: "original"}}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = pub.Commit(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.putLock(t, x.dead, 5, x.expiry) |
| + x.edgesKey = "control/edges/" + x.dead.Ref + ".json" |
| + x.writeEdges(t) |
| + x.queue = &departureSQSTransport{queue: "g3-receiver", body: string(terminationHint(x.dead.InstanceID))} |
| + a.MakeQueue = func(ctx context.Context) (hadeparture.Queue, error) { return x.queue.open(ctx, departureCloud(a.Self)) } |
| + c, life, err := armHADepartures(t.Context(), *a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.c = c |
| + select { |
| + case <-life.Started(): |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("queue startup") |
| + } |
| + if err = life.Stop(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + c.cfg.Now = func() time.Time { return x.now } |
| + c.cfg.Logf = func(string, ...any) {} |
| + c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { x.pages++; return nil } |
| + for _, b := range []hadeparture.Box{a.Self, x.dead, x.peer} { |
| + tag := "known" |
| + if b.Ref == x.dead.Ref { |
| + tag = x.edgesTag |
| + } |
| + obs, e := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: b, EdgesKey: "control/edges/" + b.Ref + ".json", EdgesETag: tag}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if b.Ref == x.dead.Ref { |
| + x.dead = obs.Box |
| + if e = c.Enqueue(t.Context(), obs); e != nil { |
| + t.Fatal(e) |
| + } |
| + x.id = departureID(c.cfg.DeploymentBucket, obs.Box) |
| + } |
| + } |
| + x.reconcile(t) |
| + return x |
| +} |
| +func (x *g3Departure) putLock(t *testing.T, b hadeparture.Box, gen int64, expiry time.Time) { |
| + t.Helper() |
| + raw, err := json.Marshal(hafresh.Lock{Generation: gen, Owner: hafresh.OwnerFor(hafresh.Self{Ref: b.Ref, IID: b.InstanceID}, 1, true), ExpiresAt: expiry}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.fx.PutLock("instances/"+x.records[0].Host, raw) |
| +} |
| +func (x *g3Departure) writeEdges(t *testing.T) { |
| + t.Helper() |
| + raw, _ := json.Marshal(edgesFile{V: 1, Box: x.dead.Ref, BoxID: x.dead.Ref, Region: x.dead.Scope.CloudRegion, Placement: x.dead.Scope.Placement, DataBucket: x.dead.Scope.DataBucket, SecretsKeyFP: x.dead.Scope.SecretsKeyFP, EIP: fmt.Sprint(x.now.UnixNano())}) |
| + var err error |
| + x.edgesTag, err = x.store.Put(t.Context(), x.edgesKey, raw, x.edgesTag) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func (x *g3Departure) reconcile(t *testing.T) { |
| + t.Helper() |
| + at := x.now.Add(time.Second) |
| + cfg := provision.ReconcileConfig{DataDir: x.a.Backend.DataDir, Departures: x.a.Inventory.Begin(at.String(), at, at, true), Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }} |
| + if err := provision.Reconcile(t.Context(), x.store, x.a.Registry, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.ReconcileSidecars(t.Context(), x.store, x.a.Registry, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv := x.a.Inventory.Snapshot(); !inv.Complete || len(inv.Records) != len(x.records) { |
| + t.Fatalf("inventory: %+v", inv) |
| + } |
| +} |
| +func (x *g3Departure) row(t *testing.T) registry.HADeparture { |
| + t.Helper() |
| + d, e := x.a.Registry.Departure(t.Context(), x.id) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return d |
| +} |
| + |
| +func TestDepartureG3Production(t *testing.T) { |
| + for _, mode := range []string{"peer", "adopt", "unbound", "churn_each_pass", "churn_two_minutes", "churn_released", "late_edges"} { |
| + t.Run(mode, func(t *testing.T) { |
| + n := 100 |
| + if mode == "churn_two_minutes" || mode == "churn_released" { |
| + n = 260 |
| + } |
| + x := newG3Departure(t, n) |
| + if mode == "churn_released" { |
| + entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| + raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID}) |
| + x.fx.PutLock("instances/"+x.records[0].Host, raw) |
| + x.expiry = x.start.Add(-time.Second) |
| + } |
| + end := x.expiry.Add(time.Duration(2*((n+31)/32))*30*time.Second + time.Minute) |
| + nextChurn := x.start.Add(2 * time.Minute) |
| + takeover := false |
| + passes := 0 |
| + for !x.now.After(end) { |
| + d := x.row(t) |
| + if d.Phase == "complete" { |
| + break |
| + } |
| + if (mode == "peer" || mode == "unbound") && !takeover && !x.now.Before(x.expiry.Add(5*time.Second)) { |
| + peer := x.peer |
| + if mode == "unbound" { |
| + peer.InstanceID = "i-3123456789abcdef0" |
| + peer.Ref = groupReferenceOf(peer.Account, peer.InstanceID) |
| + } |
| + x.putLock(t, peer, 6, x.expiry.Add(time.Hour)) |
| + takeover = true |
| + } |
| + if !x.now.Before(d.NextAttempt) && x.now.Sub(x.start)%(30*time.Second) == 0 { |
| + if mode == "churn_each_pass" && passes > 0 || (mode == "churn_two_minutes" || mode == "churn_released") && !x.now.Before(nextChurn) { |
| + rec := &x.records[1] |
| + rec.Channel = fmt.Sprintf("churn-%d", passes) |
| + key := provision.RecordKey(rec.Account, rec.App, rec.Host) |
| + _, tag, e := x.store.Get(t.Context(), key) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + raw, _ := json.Marshal(rec) |
| + if _, e = x.store.Put(t.Context(), key, raw, tag); e != nil { |
| + t.Fatal(e) |
| + } |
| + x.reconcile(t) |
| + nextChurn = x.now.Add(2 * time.Minute) |
| + } |
| + if mode == "late_edges" && passes == 1 { |
| + x.writeEdges(t) |
| + } |
| + if e := x.c.step(t.Context()); e != nil { |
| + // A changed ETag is refused by the conditional delete, then rebound |
| + // from a fresh read on the next completion attempt. |
| + if mode != "late_edges" || !errors.Is(e, release.ErrCASConflict) { |
| + t.Fatal(e) |
| + } |
| + } |
| + passes++ |
| + d = x.row(t) |
| + if mode != "late_edges" && (mode != "unbound" || !takeover) { |
| + if d.LastError == "blocked" || d.RetryCount != 0 || x.pages != 0 { |
| + t.Fatalf("wait/churn treated as failure: %+v pages=%d", d, x.pages) |
| + } |
| + } |
| + if !x.now.After(x.expiry) { |
| + entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| + _, adopted, e := x.a.Registry.HAAdoption(t.Context(), x.records[0].Host, entry.ID, x.id) |
| + if e != nil || adopted || d.Phase == "complete" { |
| + t.Fatalf("early adoption/deletion: %+v %v", d, e) |
| + } |
| + if _, _, e = x.store.Get(t.Context(), x.edgesKey); e != nil { |
| + t.Fatal("early edges deletion", e) |
| + } |
| + _, _, acks := x.queue.counts() |
| + if acks != 0 { |
| + t.Fatal("early ack") |
| + } |
| + } |
| + } |
| + x.now = x.now.Add(time.Second) |
| + } |
| + d := x.row(t) |
| + _, _, acks := x.queue.counts() |
| + if mode == "unbound" { |
| + if d.Phase == "complete" || d.LastError != "blocked" || d.RetryCount == 0 || x.pages == 0 || acks != 0 { |
| + t.Fatalf("unbound successor discharged: %+v pages=%d acks=%d", d, x.pages, acks) |
| + } |
| + if _, _, e := x.store.Get(t.Context(), x.edgesKey); e != nil { |
| + t.Fatal(e) |
| + } |
| + return |
| + } |
| + if mode == "late_edges" { |
| + scan, e := x.a.Registry.DepartureScan(t.Context(), x.id) |
| + if e != nil || scan.EdgesETag != x.edgesTag || scan.EdgesETag == d.EdgesETag { |
| + t.Fatalf("new ETag not durably bound: %+v %v", scan, e) |
| + } |
| + } |
| + if d.Phase != "complete" || acks != 1 { |
| + t.Fatalf("not finalized within %s: %+v acks=%d", end.Sub(x.expiry), d, acks) |
| + } |
| + if _, _, e := x.store.Get(t.Context(), x.edgesKey); !errors.Is(e, os.ErrNotExist) { |
| + t.Fatalf("edges retained: %v", e) |
| + } |
| + timer, e := x.a.Registry.GetTimer(x.records[0].Host, "reminder") |
| + if mode == "peer" { |
| + if timer != nil { |
| + t.Fatal("peer takeover imported locally") |
| + } |
| + } else if e != nil || timer == nil || timer.Registration != "original" { |
| + t.Fatalf("wake not imported: %+v %v", timer, e) |
| + } |
| + t.Logf("%d records, %d due passes; complete %s after expiry", n, passes, x.now.Sub(x.expiry)) |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureG3Simulation(t *testing.T) { |
| + seeds := 64 |
| + if testing.Short() { |
| + seeds = 12 |
| + } |
| + for seed := int64(0); seed < int64(seeds); seed++ { |
| + t.Run(fmt.Sprint(seed), func(t *testing.T) { |
| + rng := rand.New(rand.NewSource(seed)) |
| + n := 1 + rng.Intn(300) |
| + x := newScanRig(t, n) |
| + rng.Shuffle(n, func(i, j int) { x.inv.Records[i], x.inv.Records[j] = x.inv.Records[j], x.inv.Records[i] }) |
| + start := x.now |
| + lastExpiry := start |
| + type duty struct { |
| + kind int |
| + expiry time.Time |
| + recovered bool |
| + } |
| + duties := map[string]*duty{} |
| + blocker := false |
| + for _, h := range x.inv.Records { |
| + kind := rng.Intn(4) |
| + if seed%3 == 0 && kind == 3 { |
| + kind = 4 |
| + } |
| + if kind == 0 { |
| + delete(x.locks.views, h.Host) |
| + continue |
| + } |
| + d := &duty{kind: kind} |
| + duties[h.Host] = d |
| + if kind >= 2 { |
| + // Every dead lock is observed before any takeover. Positions vary. |
| + d.expiry = start.Add(time.Duration(600+rng.Intn(900)) * time.Second) |
| + v := x.locks.views[h.Host] |
| + v.Lock.Release = nil |
| + v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: x.d.Box.Ref, IID: x.d.Box.InstanceID}, 1, true) |
| + v.Lock.ExpiresAt = d.expiry |
| + x.locks.views[h.Host] = v |
| + if d.expiry.After(lastExpiry) { |
| + lastExpiry = d.expiry |
| + } |
| + } |
| + if kind == 4 { |
| + blocker = true |
| + } |
| + } |
| + x.c.cfg.ValidateSuccessor = func(_ context.Context, ref, iid string) (bool, error) { |
| + return ref == "peer" || ref == x.c.cfg.Self.Ref, nil |
| + } |
| + adopt := x.c.cfg.Adopt |
| + x.c.cfg.Adopt = func(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) { |
| + if v.Lock.Release == nil && !x.now.After(v.Lock.ExpiresAt) { |
| + t.Fatalf("seed %d: early adoption of %s", seed, h.Host) |
| + } |
| + result, e := adopt(ctx, h, d, v) |
| + if e == nil { |
| + duties[h.Host].recovered = true |
| + } |
| + return result, e |
| + } |
| + pages := 0 |
| + x.c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { pages++; return nil } |
| + // At most one mutation per 30s interval and at most 320 live records. |
| + // Each full page therefore clears at least 31 outstanding revisions. |
| + // Allow a residual dirty walk, a clean adoption walk, and a rescan, |
| + // plus one extra walk for expiries distributed across a page boundary. |
| + bound := lastExpiry.Add(time.Duration(4*((320+30)/31))*30*time.Second + time.Minute) |
| + serial := n |
| + for !x.now.After(bound) { |
| + for host, d := range duties { |
| + if (d.kind == 3 || d.kind == 4) && !d.recovered && x.now.After(d.expiry.Add(5*time.Second)) { |
| + v := x.locks.views[host] |
| + ref := "peer" |
| + if d.kind == 4 { |
| + ref = "unbound" |
| + } |
| + v.ETag = "takeover" |
| + v.Lock.Generation = 2 |
| + v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: "i-peer"}, 1, true) |
| + v.Lock.ExpiresAt = bound.Add(time.Hour) |
| + x.locks.views[host] = v |
| + d.recovered = d.kind == 3 |
| + } |
| + } |
| + if x.now.After(start) && rng.Intn(4) != 0 { |
| + candidates := []int{} |
| + for i, h := range x.inv.Records { |
| + if duties[h.Host] == nil { |
| + candidates = append(candidates, i) |
| + } |
| + } |
| + action := rng.Intn(3) |
| + if action == 0 && len(x.inv.Records) < 320 { |
| + serial++ |
| + x.inv.Records = append(x.inv.Records, provision.DepartureHost{Host: fmt.Sprintf("churn-%d.example.com", serial), Lifetime: "new", Kind: "instance", HA: true, Revision: fmt.Sprint(serial)}) |
| + } else if len(candidates) > 0 { |
| + i := candidates[rng.Intn(len(candidates))] |
| + if action == 1 { |
| + x.inv.Records = append(x.inv.Records[:i], x.inv.Records[i+1:]...) |
| + } else { |
| + x.inv.Records[i].Revision = x.now.String() |
| + } |
| + } |
| + } |
| + row, e := x.r.Departure(t.Context(), x.d.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if !x.now.Before(row.NextAttempt) { |
| + if _, e = x.c.ScanPass(t.Context()); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + row, e = x.r.Departure(t.Context(), x.d.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if row.Phase == "complete" { |
| + for host, d := range duties { |
| + if !d.recovered { |
| + t.Fatalf("seed %d deleted before %s recovered: %+v", seed, host, d) |
| + } |
| + } |
| + if blocker { |
| + t.Fatal("unbound successor completed") |
| + } |
| + return |
| + } |
| + if !blocker && (row.LastError == "blocked" || pages != 0) { |
| + t.Fatalf("seed %d wait/churn paged: %+v", seed, row) |
| + } |
| + x.now = x.now.Add(30 * time.Second) |
| + } |
| + if !blocker { |
| + t.Fatalf("seed %d: failed liveness bound %s", seed, bound.Sub(lastExpiry)) |
| + } |
| + if pages == 0 { |
| + t.Fatal("real blocker never paged") |
| + } |
| + if _, _, e := x.store.Get(t.Context(), x.d.EdgesKey); e != nil { |
| + t.Fatal("blocked edges deleted", e) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureG3InventoryWrites(t *testing.T) { |
| + x := newG3Departure(t, 100) |
| + digest := departureInventoryDigest(x.a.Inventory.Snapshot()) |
| + check := func(name string, changed bool) { |
| + t.Helper() |
| + x.reconcile(t) |
| + next := departureInventoryDigest(x.a.Inventory.Snapshot()) |
| + if (next != digest) != changed { |
| + t.Fatalf("%s: digest changed=%v, want %v", name, next != digest, changed) |
| + } |
| + t.Logf("%s: digest changed=%v", name, next != digest) |
| + digest = next |
| + } |
| + m := release.Manifest{App: "shop", Version: "v1abc", Kind: "binary", Artifacts: map[string]release.Artifact{"linux-amd64": {}}} |
| + if e := release.Ship(t.Context(), x.store, "bab", m, map[string][]byte{"linux-amd64": []byte("test binary")}); e != nil { |
| + t.Fatal(e) |
| + } |
| + check("ship", false) |
| + seed, _, e := release.GenerateKey() |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + key, e := release.ParseSigningKey(seed, "test") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = release.Promote(t.Context(), x.store, key, "bab", "shop", "stable", "v1abc"); e != nil { |
| + t.Fatal(e) |
| + } |
| + check("promote", false) |
| + pub, e := hostfiles.Open(t.Context(), x.a.Backend.FilesStore, "instances/"+x.records[0].Host+"/files/0/") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: x.records[0].Host}); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = pub.Commit(t.Context()); e != nil { |
| + t.Fatal(e) |
| + } |
| + check("wake-state publication", false) |
| + rec := x.records[1] |
| + recordKey := provision.RecordKey(rec.Account, rec.App, rec.Host) |
| + raw, tag, e := x.store.Get(t.Context(), recordKey) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = x.store.Put(t.Context(), recordKey, append(raw, '\n'), tag); e != nil { |
| + t.Fatal(e) |
| + } |
| + check("raw record whitespace", true) |
| + _, tag, e = x.store.Get(t.Context(), recordKey) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + rec.Channel = "canary/test" |
| + if e = provision.UpdateRecord(t.Context(), x.store, rec, tag); e != nil { |
| + t.Fatal(e) |
| + } |
| + check("instance channel update", true) |
| + // Reproduce the old digest/cursor rule independently of lease failures: |
| + // nine pages cannot finish if a raw-record write resets it every four. |
| + oldGeneration := digest |
| + cursor, resets := 0, 0 |
| + for pass := 0; pass < 80; pass++ { |
| + current := fmt.Sprint(pass / 4) |
| + if current != oldGeneration { |
| + cursor = 0 |
| + resets++ |
| + oldGeneration = current |
| + } |
| + cursor += 32 |
| + if cursor >= 260 { |
| + t.Fatal("legacy cursor unexpectedly completed") |
| + } |
| + } |
| + t.Logf("legacy 260-record walk, write every 2m: %d resets in 40m, cursor=%d", resets, cursor) |
| +} |
| + |
| +func TestDepartureG3CatchUp(t *testing.T) { |
| + for _, mode := range []string{"changed", "added", "removed", "inflight"} { |
| + t.Run(mode, func(t *testing.T) { |
| + x := newScanRig(t, 65) |
| + x.locks.views = map[string]hafresh.View{} |
| + x.pass(t) |
| + h := x.inv.Records[0] |
| + marker := hafresh.Marker{V: 1, Box: x.d.Box.Ref, IID: x.d.Box.InstanceID, Lifetime: h.Lifetime} |
| + change := func() { |
| + if mode == "removed" { |
| + x.inv.Records = x.inv.Records[1:] |
| + return |
| + } |
| + if mode == "added" { |
| + h.Host = "added.example.com" |
| + x.inv.Records = append([]provision.DepartureHost{h}, x.inv.Records...) |
| + } else { |
| + x.inv.Records[0].Revision = "changed" |
| + } |
| + x.locks.views[h.Host] = hafresh.View{ETag: "dead", Lock: hafresh.Lock{Generation: 1, Owner: hafresh.MarkerOwner(marker), Release: &marker, ExpiresAt: time.Unix(0, 0)}} |
| + } |
| + if mode == "inflight" { |
| + inventory := x.c.cfg.Inventory |
| + reads := 0 |
| + x.c.cfg.Inventory = func() provision.InventorySnapshot { |
| + reads++ |
| + if reads == 2 { |
| + change() |
| + } |
| + return inventory() |
| + } |
| + } else { |
| + change() |
| + } |
| + for i := 0; i < 8; i++ { |
| + x.pass(t) |
| + row, e := x.r.Departure(t.Context(), x.d.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if row.LastError == "blocked" { |
| + t.Fatal("inventory change blocked") |
| + } |
| + if row.Phase == "complete" { |
| + want := 1 |
| + if mode == "removed" { |
| + want = 0 |
| + } |
| + if x.imports != want { |
| + t.Fatalf("catch-up imports=%d want=%d", x.imports, want) |
| + } |
| + return |
| + } |
| + } |
| + t.Fatal("catch-up never completed") |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureG3EdgesRebindRefusals(t *testing.T) { |
| + for _, mode := range []string{"wrong_scope", "wrong_ref", "null_placement", "malformed", "unbound"} { |
| + t.Run(mode, func(t *testing.T) { |
| + x := newG3Departure(t, 1) |
| + if e := x.c.step(t.Context()); e != nil { |
| + t.Fatal(e) |
| + } |
| + view := edgesfile.PlacementView{V: 1, Box: x.dead.Ref, BoxID: x.dead.Ref, Region: x.dead.Scope.CloudRegion, Placement: x.dead.Scope.Placement, DataBucket: x.dead.Scope.DataBucket, SecretsKeyFP: x.dead.Scope.SecretsKeyFP} |
| + if mode == "wrong_scope" { |
| + view.DataBucket = "another" |
| + } |
| + if mode == "wrong_ref" { |
| + view.BoxID = x.peer.Ref |
| + } |
| + raw, _ := json.Marshal(view) |
| + if mode == "malformed" { |
| + raw = []byte("{") |
| + } |
| + if mode == "null_placement" { |
| + var obj map[string]any |
| + _ = json.Unmarshal(raw, &obj) |
| + obj["placement"] = nil |
| + raw, _ = json.Marshal(obj) |
| + } |
| + tag, e := x.store.Put(t.Context(), x.edgesKey, raw, x.edgesTag) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + x.now = x.expiry.Add(30 * time.Second) |
| + if e = x.c.step(t.Context()); e != nil { |
| + t.Fatal(e) |
| + } |
| + x.now = x.now.Add(30 * time.Second) |
| + if e = x.c.step(t.Context()); !errors.Is(e, release.ErrCASConflict) { |
| + t.Fatalf("stale ETag accepted: %v", e) |
| + } |
| + if mode == "unbound" { |
| + x.c.cfg.Identities = nil |
| + } |
| + if e = x.c.Complete(t.Context(), x.id); !errors.Is(e, errDepartureIdentity) { |
| + t.Fatalf("unsafe rebind: %v", e) |
| + } |
| + if _, current, e := x.store.Get(t.Context(), x.edgesKey); e != nil || current != tag { |
| + t.Fatal("replacement deleted", current, e) |
| + } |
| + if d := x.row(t); d.Phase == "complete" || d.LastError != "replacement_binding" { |
| + t.Fatalf("unsafe completion: %+v", d) |
| + } |
| + _, _, acks := x.queue.counts() |
| + if acks != 0 { |
| + t.Fatal("unsafe acknowledgement") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureG3LateEdges(t *testing.T) { |
| + x := newG3Departure(t, 1) |
| + d := x.row(t) |
| + scan, e := x.a.Registry.DepartureScan(t.Context(), x.id) |
| + if e != nil || d.EdgesETag == "" || scan.EdgesETag != "" { |
| + t.Fatalf("enrollment binding: departure=%q scan=%q %v", d.EdgesETag, scan.EdgesETag, e) |
| + } |
| + entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| + raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID}) |
| + x.fx.PutLock("instances/"+x.records[0].Host, raw) |
| + if e = x.c.step(t.Context()); e != nil { |
| + t.Fatal(e) |
| + } |
| + x.now = x.now.Add(30 * time.Second) |
| + x.writeEdges(t) |
| + if e = x.c.step(t.Context()); !errors.Is(e, release.ErrCASConflict) { |
| + t.Fatalf("stale ETag was not refused: %v", e) |
| + } |
| + x.now = x.now.Add(30 * time.Second) |
| + if e = x.c.step(t.Context()); e != nil { |
| + t.Fatal("late publication stuck", e) |
| + } |
| + if d = x.row(t); d.Phase != "complete" { |
| + t.Fatalf("late publication never finalized: %+v", d) |
| + } |
| + scan, e = x.a.Registry.DepartureScan(t.Context(), x.id) |
| + if e != nil || scan.EdgesETag != x.edgesTag { |
| + t.Fatalf("replacement ETag not persisted: %+v %v", scan, e) |
| + } |
| + _, _, acks := x.queue.counts() |
| + if acks != 1 { |
| + t.Fatal("missing ack", acks) |
| + } |
| +} |