ha: recover adoption across route changes and preserve legacy wakes
Keep binding-scoped receipt history and reject stale phase transitions. Preserve legacy timer rows on ordinary restore, validate duty bindings through the store interface, and advance visitor revisions without a CAS or premature basis clear.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/haadopt.go+6 −3internal/activator/haadopt_test.go+166 −0internal/activator/haduties.go+21 −21internal/activator/haduties_test.go+10 −1internal/activator/hawake.go+3 −11internal/hostfiles/wake.go+17 −4internal/hostfiles/wake_test.go+56 −0internal/registry/ha_departures.go+96 −20internal/registry/ha_duties.go+9 −0internal/registry/ha_duties_test.go+164 −6internal/registry/remote_dispatch.go+2 −0
Intent
<task-notification> <task-id>b7835p06w</task-id> <tool-use-id>toolu_01WPTDkaq6tfsGfCwCdzDH4U</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/b7835p06w.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra B2" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a521de241f84b37f1</task-id> <tool-use-id>toolu_01HB4ZePpAXBW2xYr1ebJPc4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/a521de241f84b37f1.output</output-file> <status>completed</status> <summary>Agent "Opus review Task B2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task quality: Needs fixes.** I found 0 Critical, 2 Important and 10 Minor issues. The lease-authority core is sound. Adoption takes the lock only strictly after expiry (equality still counts as held), through the existing restricted acquire. Releasing writes an unclean marker naming this box, and a read-back confirms it. The import is one transaction, and adoption never restores files or secrets or starts a process. The tests behind this are strong, especially a request-count test that fails on any read beyond the lock, manifest and wake objects. **Important:** 1. **A recreated route, or a Pair change, blocks adoption for that departure on that host, permanently and silently** (`internal/registry/ha_departures.go:50,172`; `internal/activator/haadopt.go:276`). Old receipts are keyed `(departure_id, host, lifetime)`. Once the binding generation changes, `ImportHAWake` returns `ImportDeferred` with no error on every later call. The test `TestHAAdoptReceiptCannotCrossRouteRecreation` asserts this stall as the intended result. The plan only says an old receipt must not authorise a new binding. Here the host can never be adopted again under that departure, so its once-timers wait for a visitor wake. Fix: let a fresh import proceed under the current binding (add `binding` to the key, or archive the stale row in the same transaction), and add a witness for it. 2. **Ordinary HA wakes can now fail on legacy wake state** (`internal/hostfiles/wake.go:80-97` → `internal/registry/ha_departures.go:56-63`). `hostfiles.ImportWake` now runs the strict `ValidateHAWake`, which among other things requires a non-empty `Registration`. That column was added on 2026-09-16 with default `''` and is never backfilled. So an old timer row exported into `wake.json` would fail every box's wake for that host, not just adoption. The detailed error messages are also replaced by an opaque `ha_wake_invalid`. I could not verify whether such rows exist in production. Fix: either keep the old tolerance on the ordinary restore path, or show evidence that no such rows exist and add a witness for a legacy-shaped wake. In both cases, wrap the error with the failing field and host. **Notable Minors:** - The pre-acquire compare-and-swap on the ordinary visitor path can make a wake fail on a harmless revision bump. It also clears the `adopted` basis even when the acquire is then refused. - The remote parity test only covers 2 of the 8 new remote methods. - The tests for refused adoptions only check `Deferred`. They don't check that the stored phase and basis stayed unadopted. - The restart test never covers a crash between persisting `acquiring` and the acquire write. Full report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-duties/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B2-review-r1.md`</result> <usage><subagent_tokens>166100</subagent_tokens><tool_uses>40</tool_uses><duration_ms>573516</duration_ms></usage> </task-notification>
Check Astra B2 for P1b-3b slice T: ledger progress.md and task-B2-astra-a.md/.log in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-duties/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/; continue SDD.
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go| index b57c3a6f3..d4eacfc29 100644 |
| --- a/internal/activator/haadopt.go |
| +++ b/internal/activator/haadopt.go |
| @@ -358,18 +358,21 @@ type adoptionCauseKey struct{} |
| // bindDutyLifetime joins current record facts to the registry's monotonic revision. |
| func (b *ExecBackend) bindDutyLifetime(ctx context.Context, rt registry.Route, life string) (registry.DutyState, error) { |
| - d, ok, err := b.Registry.HADuty(rt.Host, life) |
| + return bindDutyLifetime(ctx, b.Registry, rt, life) |
| +} |
| +func bindDutyLifetime(ctx context.Context, store DutyStore, rt registry.Route, life string) (registry.DutyState, error) { |
| + d, ok, err := store.HADuty(rt.Host, life) |
| if err != nil || ok { |
| return d, err |
| } |
| - changed, err := b.Registry.BindHADuty(ctx, rt.Host, adoptionPair(rt), life, d.Revision) |
| + changed, err := store.BindHADuty(ctx, rt.Host, adoptionPair(rt), life, d.Revision) |
| if err != nil { |
| return d, err |
| } |
| if !changed { |
| return d, registry.ErrHAChanged |
| } |
| - return b.Registry.LoadDuty(ctx, rt.Host, life) |
| + return store.LoadDuty(ctx, rt.Host, life) |
| } |
| // A live local holder can discharge a departure without changing its wake state. |
diff --git a/internal/activator/haadopt_test.go b/internal/activator/haadopt_test.go| index f0e125add..09dbdbbb2 100644 |
| --- a/internal/activator/haadopt_test.go |
| +++ b/internal/activator/haadopt_test.go |
| @@ -85,6 +85,21 @@ func TestHAAdoptAuthority(t *testing.T) { |
| if got != Deferred { |
| t.Fatalf("refusal %v %v", got, err) |
| } |
| + d, ok, e := s.b.Registry.HADuty(s.rt.Host, req.Lifetime) |
| + if e != nil || !ok || d.Basis == DutyAdopted { |
| + t.Fatalf("refused duty %+v %v %v", d, ok, e) |
| + } |
| + p, exists, e := s.b.Registry.HAAdoption(ctx, s.rt.Host, req.Lifetime, req.Departure) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if strings.HasPrefix(kind, "marker ") { |
| + if !exists || p.Phase != "marker_pending" { |
| + t.Fatalf("refused marker phase %+v exists=%v", p, exists) |
| + } |
| + } else if exists { |
| + t.Fatalf("held refusal imported receipt %+v", p) |
| + } |
| } else { |
| if err != nil || got != Adopted { |
| t.Fatalf("adopt %v %v", got, err) |
| @@ -592,3 +607,154 @@ func TestHAAdoptSupersededAwake(t *testing.T) { |
| t.Fatalf("awake successor %v %v", got, err) |
| } |
| } |
| + |
| +func TestHAAdoptRecreatedRoute(t *testing.T) { |
| + for _, change := range []string{"recreate", "pair"} { |
| + t.Run(change, func(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + ctx := context.Background() |
| + interruptAdoptionBeforeAcquire(t, s, req) |
| + old, ok, err := s.b.Registry.HAAdoption(ctx, s.rt.Host, req.Lifetime, req.Departure) |
| + if err != nil || !ok || old.Phase != "acquiring" { |
| + t.Fatalf("interruption %+v %v %v", old, ok, err) |
| + } |
| + if change == "recreate" { |
| + if err := s.b.Registry.Delete(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.b.Registry.Upsert(s.rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + if ok, err := s.b.Registry.InstallLifetimeIf(s.rt.Host, req.Pair, registry.Pair{Incarnation: 2}); err != nil || !ok { |
| + t.Fatalf("pair %v %v", ok, err) |
| + } |
| + s.rt.Incarnation = 2 |
| + req.Pair = adoptionPair(s.rt) |
| + } |
| + d, err := s.b.bindDutyLifetime(ctx, s.rt, req.Lifetime) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Revision = d.Revision |
| + if got, err := s.a.AdoptHost(ctx, s.rt, req); err != nil || got != Adopted { |
| + t.Fatalf("fresh adoption %v %v", got, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHAOrdinaryRestoreLegacyWake(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + publishAdoptWake(t, s, hostfiles.WakeState{V: 1, Host: s.rt.Host, Timers: []hostfiles.WakeTimer{{Name: "legacy", Kind: "schedule", Spec: "@every 1m", Path: "/tick", NextAt: 9999999999}}}) |
| + putLockFor(t, s.b, s.rt, haAdoptMarker(t, "c", "i-c", req.Lifetime, 8, false)) |
| + done, err := s.a.begin(context.Background(), s.rt, true, nil) |
| + if done != nil { |
| + defer done() |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := s.b.Registry.TimersFor(s.rt.Host) |
| + if err != nil || len(rows) != 1 || rows[0].Name != "legacy" || rows[0].Registration == "" || rows[0].Spec != "@every 1m" || !s.wokeHere() { |
| + t.Fatalf("restore %+v woke=%v err=%v", rows, s.wokeHere(), err) |
| + } |
| +} |
| + |
| +func TestHAVisitorRefusalPreservesAdoption(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + ctx := context.Background() |
| + if got, err := s.a.AdoptHost(ctx, s.rt, req); err != nil || got != Adopted { |
| + t.Fatalf("adopt %v %v", got, err) |
| + } |
| + before, _, _ := s.b.Registry.HADuty(s.rt.Host, req.Lifetime) |
| + body, _ := json.Marshal(hafresh.Lock{Generation: 8, Owner: heldByB, ExpiresAt: time.Now().Add(time.Hour)}) |
| + putLockFor(t, s.b, s.rt, body) |
| + if held, err := s.b.Acquire(ctx, s.rt); err == nil { |
| + held.Release(ctx) |
| + t.Fatal("acquired peer") |
| + } |
| + after, ok, err := s.b.Registry.HADuty(s.rt.Host, req.Lifetime) |
| + if err != nil || !ok || after.Basis != DutyAdopted || after.Revision <= before.Revision { |
| + t.Fatalf("refusal lost basis or revision: before=%+v after=%+v ok=%v err=%v", before, after, ok, err) |
| + } |
| +} |
| + |
| +type wrappedDutyStore struct{ *registry.Registry } |
| + |
| +func TestHADutyStoreValidatesWrappedLifetime(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + s.a.DutyStore = wrappedDutyStore{s.b.Registry} |
| + if err := s.b.Registry.Delete(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.b.Registry.Upsert(s.rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.a.dutyState(context.Background(), s.rt.Host, "wrong-life"); err == nil { |
| + t.Fatal("wrapped store bound unvalidated lifetime") |
| + } |
| + if _, ok, err := s.b.Registry.HADuty(s.rt.Host, "wrong-life"); err != nil || ok { |
| + t.Fatalf("invalid binding %v %v", ok, err) |
| + } |
| + if _, err := s.a.dutyState(context.Background(), s.rt.Host, req.Lifetime); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func interruptAdoptionBeforeAcquire(t *testing.T, s *haSvc, req Adoption) { |
| + t.Helper() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + record := s.b.Cfg.Record |
| + index := s.b.Lifetimes |
| + s.b.Lifetimes = nil |
| + defer func() { s.b.Lifetimes = index }() |
| + s.b.Cfg.Record = func(ctx context.Context, rt registry.Route) (RecordFacts, error) { |
| + p, ok, err := s.b.Registry.HAAdoption(ctx, rt.Host, req.Lifetime, req.Departure) |
| + if err != nil { |
| + return RecordFacts{}, err |
| + } |
| + if ok && p.Phase == "acquiring" { |
| + cancel() |
| + return RecordFacts{}, context.Canceled |
| + } |
| + return record(ctx, rt) |
| + } |
| + defer func() { s.b.Cfg.Record = record }() |
| + start := len(s.fx.Requests()) |
| + if got, err := s.a.AdoptHost(ctx, s.rt, req); got != Deferred || err == nil { |
| + t.Fatalf("interrupt %v %v", got, err) |
| + } |
| + p, ok, err := s.b.Registry.HAAdoption(context.Background(), s.rt.Host, req.Lifetime, req.Departure) |
| + if err != nil || !ok || p.Phase != "acquiring" { |
| + t.Fatalf("phase %+v %v %v", p, ok, err) |
| + } |
| + for _, r := range s.fx.Requests()[start:] { |
| + if strings.HasPrefix(r, "PUT ") { |
| + t.Fatalf("acquire PUT before interruption: %s", r) |
| + } |
| + } |
| + v, err := lease.ReadLock(context.Background(), s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region) |
| + if err != nil || v.ETag != req.Observed.ETag { |
| + t.Fatalf("departed lock changed %+v %v", v, err) |
| + } |
| +} |
| + |
| +func TestHAAdoptRestartAcquiringDepartedLock(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + interruptAdoptionBeforeAcquire(t, s, req) |
| + path := s.b.Registry.Path() |
| + s.b.Registry.Close() |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + s.b.Registry = reg |
| + fresh := New(s.a.cfg, s.b, reg) |
| + fresh.DutyStore = reg |
| + if got, err := fresh.AdoptHost(context.Background(), s.rt, req); err != nil || got != Adopted { |
| + t.Fatalf("restart %v %v", got, err) |
| + } |
| +} |
diff --git a/internal/activator/haduties.go b/internal/activator/haduties.go| index f9e52c502..243c90962 100644 |
| --- a/internal/activator/haduties.go |
| +++ b/internal/activator/haduties.go |
| @@ -90,6 +90,9 @@ func DutyForTick(d DutyDecision, t registry.Timer, now time.Time) DutyDecision { |
| // current lifetime and revision atomically; a mismatch returns false. |
| // A pending import must never be stored as DutyAdopted. |
| type DutyStore interface { |
| + Get(string) (*registry.Route, error) |
| + HADuty(string, string) (DutyState, bool, error) |
| + BindHADuty(context.Context, string, registry.Pair, string, uint64) (bool, error) |
| LoadDuty(context.Context, string, string) (DutyState, error) |
| CompareDuty(context.Context, string, string, uint64, DutyState) (bool, error) |
| } |
| @@ -141,28 +144,25 @@ func dutyBackend(b Backend, rt registry.Route) interface { |
| func (a *Service) dutyState(ctx context.Context, host, life string) (DutyState, error) { |
| if a.DutyStore != nil { |
| - if reg, ok := a.DutyStore.(*registry.Registry); ok { |
| - rt, err := reg.Get(host) |
| - if err != nil { |
| - return DutyState{}, err |
| - } |
| - if rt == nil { |
| - return DutyState{}, registry.ErrHAChanged |
| - } |
| - b := adoptionBackend(a.backend, *rt) |
| - if b == nil { |
| - return DutyState{}, registry.ErrHAChanged |
| - } |
| - current, ha, err := b.isHA(ctx, *rt) |
| - if err != nil { |
| - return DutyState{}, err |
| - } |
| - if !ha || current.ID != life { |
| - return DutyState{}, registry.ErrHAChanged |
| - } |
| - return b.bindDutyLifetime(ctx, *rt, life) |
| + rt, err := a.DutyStore.Get(host) |
| + if err != nil { |
| + return DutyState{}, err |
| + } |
| + if rt == nil { |
| + return DutyState{}, registry.ErrHAChanged |
| + } |
| + b := dutyBackend(a.backend, *rt) |
| + if b == nil { |
| + return DutyState{}, registry.ErrHAChanged |
| + } |
| + current, ha, err := b.isHA(ctx, *rt) |
| + if err != nil { |
| + return DutyState{}, err |
| + } |
| + if !ha || current.ID != life { |
| + return DutyState{}, registry.ErrHAChanged |
| } |
| - return a.DutyStore.LoadDuty(ctx, host, life) |
| + return bindDutyLifetime(ctx, a.DutyStore, *rt, life) |
| } |
| a.duties.mu.Lock() |
| defer a.duties.mu.Unlock() |
diff --git a/internal/activator/haduties_test.go b/internal/activator/haduties_test.go| index f8f01fc2d..70435f69f 100644 |
| --- a/internal/activator/haduties_test.go |
| +++ b/internal/activator/haduties_test.go |
| @@ -247,10 +247,19 @@ func TestHADutyVisitorCoalescing(t *testing.T) { |
| } |
| type fakeDutyStore struct { |
| + reg *registry.Registry |
| mu sync.Mutex |
| rows map[string]DutyState |
| } |
| +func (s *fakeDutyStore) Get(host string) (*registry.Route, error) { return s.reg.Get(host) } |
| +func (s *fakeDutyStore) HADuty(host, life string) (DutyState, bool, error) { |
| + d, err := s.LoadDuty(context.Background(), host, life) |
| + return d, true, err |
| +} |
| +func (s *fakeDutyStore) BindHADuty(context.Context, string, registry.Pair, string, uint64) (bool, error) { |
| + return false, registry.ErrHAChanged |
| +} |
| func (s *fakeDutyStore) LoadDuty(_ context.Context, h, l string) (DutyState, error) { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| @@ -270,7 +279,7 @@ func (s *fakeDutyStore) CompareDuty(_ context.Context, h, l string, rev uint64, |
| func TestHADutyStoreDeadlineAndLifetime(t *testing.T) { |
| s := haHeldByB(t) |
| - store := &fakeDutyStore{rows: map[string]DutyState{}} |
| + store := &fakeDutyStore{reg: s.b.Registry, rows: map[string]DutyState{}} |
| s.a.DutyStore = store |
| now := time.Now() |
| s.a.now = func() time.Time { return now } |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index 69383c24b..dbf2b733e 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -336,20 +336,12 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) |
| if err := b.haContained(rt); err != nil { |
| return nil, refusedUncontained(err) |
| } |
| - if b.Registry != nil && entry.ID != "" { |
| - d, err := b.bindDutyLifetime(ctx, rt, entry.ID) |
| - if err != nil { |
| - return nil, err |
| - } |
| - d.Basis = "" |
| - ok, err := b.Registry.CompareDuty(ctx, host, entry.ID, d.Revision, d) |
| - if err != nil { |
| + if b.Registry != nil { |
| + if err := b.Registry.AdvanceHADuty(ctx, host); err != nil { |
| return nil, err |
| } |
| - if !ok { |
| - return nil, registry.ErrHAChanged |
| - } |
| } |
| + |
| proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| var held *lease.Held |
| if duty, ok := ctx.Value(dutyContextKey{}).(dutyRestriction); ok { |
diff --git a/internal/hostfiles/wake.go b/internal/hostfiles/wake.go| index 82bf5a39d..a066ebcd0 100644 |
| --- a/internal/hostfiles/wake.go |
| +++ b/internal/hostfiles/wake.go |
| @@ -78,7 +78,7 @@ func WakeStateOf(host string, rows []registry.Timer, nextDue int64, replication |
| } |
| func ImportWake(reg *registry.Registry, host string, ws WakeState) error { |
| - state, err := RegistryWake(host, ws) |
| + state, err := registryWake(host, ws) |
| if err != nil { |
| return err |
| } |
| @@ -87,14 +87,27 @@ func ImportWake(reg *registry.Registry, host string, ws WakeState) error { |
| // RegistryWake validates the wire state before a registry transaction begins. |
| func RegistryWake(host string, ws WakeState) (registry.HAWakeImport, error) { |
| - if ws.V != 1 || ws.Host != host { |
| - return registry.HAWakeImport{}, registry.ErrHAWake |
| + state, err := registryWake(host, ws) |
| + if err != nil { |
| + return state, err |
| + } |
| + return state, registry.ValidateHAWake(host, state) |
| +} |
| +func registryWake(host string, ws WakeState) (registry.HAWakeImport, error) { |
| + if ws.V != 1 { |
| + return registry.HAWakeImport{}, fmt.Errorf("%w host=%q field=version value=%d", registry.ErrHAWake, host, ws.V) |
| + } |
| + if ws.Host != host { |
| + return registry.HAWakeImport{}, fmt.Errorf("%w host=%q field=host value=%q", registry.ErrHAWake, host, ws.Host) |
| + } |
| + if !registry.ValidReplication(ws.Replication) { |
| + return registry.HAWakeImport{}, fmt.Errorf("%w host=%q field=replication value=%q", registry.ErrHAWake, host, ws.Replication) |
| } |
| state := registry.HAWakeImport{NextDue: ws.NextDue, Replication: ws.Replication} |
| for _, t := range ws.Timers { |
| state.Timers = append(state.Timers, registry.Timer{Host: host, Name: t.Name, Kind: t.Kind, Spec: t.Spec, Path: t.Path, NextAt: t.NextAt, LastAt: t.LastAt, LastStatus: t.LastStatus, LastMs: t.LastMs, Attempts: t.Attempts, CreatedAt: t.CreatedAt, DueAt: t.DueAt, Registration: t.Registration}) |
| } |
| - return state, registry.ValidateHAWake(host, state) |
| + return state, nil |
| } |
| // StageWake stages the wake state as a platform item. Unchanged state |
diff --git a/internal/hostfiles/wake_test.go b/internal/hostfiles/wake_test.go| index 72a44dd5d..73f439565 100644 |
| --- a/internal/hostfiles/wake_test.go |
| +++ b/internal/hostfiles/wake_test.go |
| @@ -2,7 +2,10 @@ package hostfiles |
| import ( |
| "context" |
| + "encoding/json" |
| + "errors" |
| "path/filepath" |
| + "strings" |
| "testing" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -189,3 +192,56 @@ func TestImportWakeForAHostWithNoRouteWritesNothing(t *testing.T) { |
| t.Fatalf("a refused import changed the timers: %+v", rows) |
| } |
| } |
| + |
| +func TestImportWakeLegacyRows(t *testing.T) { |
| + r := wakeReg(t) |
| + seedHost(t, r, "shop.test") |
| + var ws WakeState |
| + if err := json.Unmarshal([]byte(`{"v":1,"host":"shop.test","replication":"batched","next_due":77,"timers":[{"name":"legacy","kind":"schedule","spec":"@every 1m","path":"/tick","next_at":123,"registration":""}]}`), &ws); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := ImportWake(r, "shop.test", ws); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := r.TimersFor("shop.test") |
| + if err != nil || len(rows) != 1 || rows[0].Registration == "" || rows[0].Spec != "@every 1m" || rows[0].NextAt != 123 { |
| + t.Fatalf("legacy restore %+v %v", rows, err) |
| + } |
| + rt, err := r.Get("shop.test") |
| + if err != nil || rt.NextDue != 77 || rt.Replication != "batched" { |
| + t.Fatalf("route %+v %v", rt, err) |
| + } |
| + if _, err := RegistryWake("shop.test", ws); !errors.Is(err, registry.ErrHAWake) { |
| + t.Fatalf("adoption accepted legacy state: %v", err) |
| + } |
| +} |
| + |
| +func TestImportWakeValidationFields(t *testing.T) { |
| + for _, field := range []string{"version", "host", "replication", "registration", "spec", "path", "name", "kind"} { |
| + t.Run(field, func(t *testing.T) { |
| + ws := WakeState{V: 1, Host: "shop.test", Timers: []WakeTimer{{Name: "job", Kind: "once", Spec: "at 123", Path: "/job", Registration: "r"}}} |
| + switch field { |
| + case "version": |
| + ws.V = 2 |
| + case "host": |
| + ws.Host = "other.test" |
| + case "replication": |
| + ws.Replication = "bad" |
| + case "registration": |
| + ws.Timers[0].Registration = "" |
| + case "spec": |
| + ws.Timers[0].Spec = "bad" |
| + case "path": |
| + ws.Timers[0].Path = "//other" |
| + case "name": |
| + ws.Timers[0].Name = "bad name" |
| + case "kind": |
| + ws.Timers[0].Kind = "bad" |
| + } |
| + _, err := RegistryWake("shop.test", ws) |
| + if !errors.Is(err, registry.ErrHAWake) || !strings.Contains(err.Error(), "shop.test") || !strings.Contains(err.Error(), field) { |
| + t.Fatalf("field=%s err=%v", field, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/registry/ha_departures.go b/internal/registry/ha_departures.go| index 5ef90206e..ea3d973db 100644 |
| --- a/internal/registry/ha_departures.go |
| +++ b/internal/registry/ha_departures.go |
| @@ -2,8 +2,11 @@ package registry |
| import ( |
| "context" |
| + "crypto/rand" |
| "database/sql" |
| + "encoding/hex" |
| "errors" |
| + "fmt" |
| "net/url" |
| "os" |
| "regexp" |
| @@ -40,37 +43,99 @@ type HAAdoption struct { |
| Receipt, Lifetime, LockETag, WakeDigest, Phase string |
| LockGeneration, AcquiredGeneration int64 |
| Sequence int64 |
| + Binding uint64 |
| } |
| func (r *Registry) migrateHAAdoptions() error { |
| - _, err := r.sql.Exec(`CREATE TABLE IF NOT EXISTS ha_departure_hosts ( |
| + ctx := context.Background() |
| + tx, err := r.beginClaimTransaction(ctx, true) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + schema := `CREATE TABLE IF NOT EXISTS ha_departure_hosts ( |
| departure_id TEXT NOT NULL,host TEXT NOT NULL,lifetime TEXT NOT NULL, |
| departure_ref TEXT NOT NULL,departure_iid TEXT NOT NULL,lock_etag TEXT NOT NULL,lock_generation INTEGER NOT NULL,wake_digest TEXT NOT NULL,sequence INTEGER NOT NULL, |
| binding INTEGER NOT NULL,phase TEXT NOT NULL,acquired_generation INTEGER NOT NULL DEFAULT 0, |
| - PRIMARY KEY(departure_id,host,lifetime));`) |
| - return err |
| + PRIMARY KEY(departure_id,host,lifetime,binding));` |
| + if _, err = tx.ExecContext(ctx, schema); err != nil { |
| + return err |
| + } |
| + var keyed int |
| + if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM pragma_table_info('ha_departure_hosts') WHERE name='binding' AND pk>0`).Scan(&keyed); err != nil { |
| + return err |
| + } |
| + if keyed == 0 { |
| + if _, err = tx.ExecContext(ctx, `ALTER TABLE ha_departure_hosts RENAME TO ha_departure_hosts_unbound`); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, schema); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO ha_departure_hosts SELECT * FROM ha_departure_hosts_unbound; DROP TABLE ha_departure_hosts_unbound`); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| } |
| var haTimerName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`) |
| +func wakeFieldError(host, field string, value any) error { |
| + return fmt.Errorf("%w host=%q field=%s value=%v", ErrHAWake, host, field, value) |
| +} |
| func ValidateHAWake(host string, s HAWakeImport) error { |
| - if host == "" || s.NextDue < 0 || !ValidReplication(s.Replication) { |
| - return ErrHAWake |
| + if host == "" { |
| + return wakeFieldError(host, "host", host) |
| + } |
| + if s.NextDue < 0 { |
| + return wakeFieldError(host, "next_due", s.NextDue) |
| + } |
| + if !ValidReplication(s.Replication) { |
| + return wakeFieldError(host, "replication", s.Replication) |
| } |
| seen := map[string]bool{} |
| for _, t := range s.Timers { |
| - spec, err := timerspec.ParseSpec(t.Spec) |
| - if err != nil || spec.Kind != t.Kind || t.Host != host || !haTimerName.MatchString(t.Name) || seen[t.Name] || t.Registration == "" || t.ClaimOwnership.Valid() || t.NextAt < 0 || t.DueAt < 0 || t.LastAt < 0 || t.Attempts < 0 { |
| - return ErrHAWake |
| + field := "timers[" + t.Name + "]." |
| + if t.Host != host { |
| + return wakeFieldError(host, field+"host", t.Host) |
| + } |
| + if !haTimerName.MatchString(t.Name) || seen[t.Name] { |
| + return wakeFieldError(host, field+"name", t.Name) |
| } |
| seen[t.Name] = true |
| + if t.Registration == "" { |
| + return wakeFieldError(host, field+"registration", t.Registration) |
| + } |
| + spec, err := timerspec.ParseSpec(t.Spec) |
| + if err != nil { |
| + return wakeFieldError(host, field+"spec", t.Spec) |
| + } |
| + if spec.Kind != t.Kind { |
| + return wakeFieldError(host, field+"kind", t.Kind) |
| + } |
| + if t.ClaimOwnership.Valid() { |
| + return wakeFieldError(host, field+"claim_ownership", t.ClaimOwnership) |
| + } |
| + if t.NextAt < 0 { |
| + return wakeFieldError(host, field+"next_at", t.NextAt) |
| + } |
| + if t.DueAt < 0 { |
| + return wakeFieldError(host, field+"due_at", t.DueAt) |
| + } |
| + if t.LastAt < 0 { |
| + return wakeFieldError(host, field+"last_at", t.LastAt) |
| + } |
| + if t.Attempts < 0 { |
| + return wakeFieldError(host, field+"attempts", t.Attempts) |
| + } |
| u, err := url.ParseRequestURI(t.Path) |
| if err != nil || len(t.Path) > 256 || !strings.HasPrefix(t.Path, "/") || strings.HasPrefix(t.Path, "//") || strings.ContainsAny(t.Path, " \t\r\n") || u.Host != "" || u.Scheme != "" || u.User != nil { |
| - return ErrHAWake |
| + return wakeFieldError(host, field+"path", t.Path) |
| } |
| for _, seg := range strings.Split(u.Path, "/") { |
| if seg == ".." { |
| - return ErrHAWake |
| + return wakeFieldError(host, field+"path", t.Path) |
| } |
| } |
| } |
| @@ -98,6 +163,13 @@ func replaceHAWake(ctx context.Context, tx *claimTransaction, host string, s HAW |
| return err |
| } |
| for _, t := range s.Timers { |
| + if t.Registration == "" { |
| + var id [16]byte |
| + if _, err := rand.Read(id[:]); err != nil { |
| + return err |
| + } |
| + t.Registration = hex.EncodeToString(id[:]) |
| + } |
| if hostwrite.Enabled(os.Getenv) && rt.ClaimOwnership.Valid() { |
| t.ClaimOwnership = rt.ClaimOwnership |
| t.ClaimRowID = t.Registration |
| @@ -114,8 +186,16 @@ func (r *Registry) ReplaceHAWake(ctx context.Context, host string, s HAWakeImpor |
| _, err := r.remote.call(ctx, remoteRequest{Method: "ReplaceHAWake", Host: host, Wake: s}, nil) |
| return err |
| } |
| - if err := ValidateHAWake(host, s); err != nil { |
| - return err |
| + if !ValidReplication(s.Replication) { |
| + return wakeFieldError(host, "replication", s.Replication) |
| + } |
| + for _, t := range s.Timers { |
| + if t.ClaimOwnership.Valid() { |
| + return wakeFieldError(host, "timers.claim_ownership", t.ClaimOwnership) |
| + } |
| + if t.Host != host { |
| + return wakeFieldError(host, "timers.host", t.Host) |
| + } |
| } |
| tx, err := r.beginClaimTransaction(ctx, true) |
| if err != nil { |
| @@ -140,7 +220,7 @@ func (r *Registry) ImportHAWake(ctx context.Context, host string, expected Pair, |
| return ImportDeferred, err |
| } |
| if s.DepartureRef == "" || s.DepartureIID == "" || s.Lifetime == "" || s.Receipt == "" || s.LockETag == "" || s.WakeDigest == "" || s.LockGeneration < 0 { |
| - return ImportDeferred, ErrHAWake |
| + return ImportDeferred, wakeFieldError(host, "adoption_receipt", s.Receipt) |
| } |
| tx, err := r.beginClaimTransaction(ctx, true) |
| if err != nil { |
| @@ -165,13 +245,9 @@ func (r *Registry) ImportHAWake(ctx context.Context, host string, expected Pair, |
| } |
| var etag string |
| var generation int64 |
| - var receiptBinding uint64 |
| var departureRef, departureIID string |
| - err = tx.QueryRowContext(ctx, `SELECT lock_etag,lock_generation,binding,departure_ref,departure_iid FROM ha_departure_hosts WHERE departure_id=? AND host=? AND lifetime=?`, s.Receipt, host, s.Lifetime).Scan(&etag, &generation, &receiptBinding, &departureRef, &departureIID) |
| + err = tx.QueryRowContext(ctx, `SELECT lock_etag,lock_generation,departure_ref,departure_iid FROM ha_departure_hosts WHERE departure_id=? AND host=? AND lifetime=? AND binding=?`, s.Receipt, host, s.Lifetime, binding).Scan(&etag, &generation, &departureRef, &departureIID) |
| if err == nil { |
| - if receiptBinding != binding { |
| - return ImportDeferred, nil |
| - } |
| if etag != s.LockETag || generation != s.LockGeneration || departureRef != s.DepartureRef || departureIID != s.DepartureIID { |
| return ImportDeferred, ErrHAChanged |
| } |
| @@ -203,7 +279,7 @@ func (r *Registry) HAAdoption(ctx context.Context, host, life, receipt string) ( |
| return out.Adoption, out.Changed, err |
| } |
| a := HAAdoption{Receipt: receipt, Lifetime: life} |
| - err := r.sql.QueryRowContext(ctx, `SELECT lock_etag,lock_generation,wake_digest,sequence,phase,acquired_generation,departure_ref,departure_iid FROM ha_departure_hosts WHERE host=? AND lifetime=? AND departure_id=? AND binding=(SELECT binding FROM ha_duties WHERE host=? AND active=1 AND lifetime=?)`, host, life, receipt, host, life).Scan(&a.LockETag, &a.LockGeneration, &a.WakeDigest, &a.Sequence, &a.Phase, &a.AcquiredGeneration, &a.DepartureRef, &a.DepartureIID) |
| + err := r.sql.QueryRowContext(ctx, `SELECT lock_etag,lock_generation,wake_digest,sequence,phase,acquired_generation,departure_ref,departure_iid,binding FROM ha_departure_hosts WHERE host=? AND lifetime=? AND departure_id=? AND binding=(SELECT binding FROM ha_duties WHERE host=? AND active=1 AND lifetime=?)`, host, life, receipt, host, life).Scan(&a.LockETag, &a.LockGeneration, &a.WakeDigest, &a.Sequence, &a.Phase, &a.AcquiredGeneration, &a.DepartureRef, &a.DepartureIID, &a.Binding) |
| if errors.Is(err, sql.ErrNoRows) { |
| return a, false, nil |
| } |
| @@ -236,7 +312,7 @@ func (r *Registry) CompareHAAdoption(ctx context.Context, host string, pair Pair |
| if err != nil || n != 1 { |
| return false, err |
| } |
| - res, err = tx.ExecContext(ctx, `UPDATE ha_departure_hosts SET phase=?,acquired_generation=?,wake_digest=?,sequence=? WHERE host=? AND lifetime=? AND departure_id=? AND phase=? AND lock_etag=? AND lock_generation=? AND binding=(SELECT binding FROM ha_duties WHERE host=? AND active=1)`, a.Phase, a.AcquiredGeneration, a.WakeDigest, a.Sequence, host, a.Lifetime, a.Receipt, oldPhase, a.LockETag, a.LockGeneration, host) |
| + res, err = tx.ExecContext(ctx, `UPDATE ha_departure_hosts SET phase=?,acquired_generation=?,wake_digest=?,sequence=? WHERE host=? AND lifetime=? AND departure_id=? AND phase=? AND lock_etag=? AND lock_generation=? AND binding=? AND binding=(SELECT binding FROM ha_duties WHERE host=? AND active=1)`, a.Phase, a.AcquiredGeneration, a.WakeDigest, a.Sequence, host, a.Lifetime, a.Receipt, oldPhase, a.LockETag, a.LockGeneration, a.Binding, host) |
| if err != nil { |
| return false, err |
| } |
diff --git a/internal/registry/ha_duties.go b/internal/registry/ha_duties.go| index 6ac071727..6372c0063 100644 |
| --- a/internal/registry/ha_duties.go |
| +++ b/internal/registry/ha_duties.go |
| @@ -153,3 +153,12 @@ func (r *Registry) CompareDuty(ctx context.Context, host, life string, revision |
| n, err := res.RowsAffected() |
| return n == 1, err |
| } |
| + |
| +func (r *Registry) AdvanceHADuty(ctx context.Context, host string) error { |
| + if r.remote != nil { |
| + _, err := r.remote.call(ctx, remoteRequest{Method: "AdvanceHADuty", Host: host}, nil) |
| + return err |
| + } |
| + _, err := r.sql.ExecContext(ctx, `UPDATE ha_duties SET revision=revision+1 WHERE host=? AND active=1`, host) |
| + return err |
| +} |
diff --git a/internal/registry/ha_duties_test.go b/internal/registry/ha_duties_test.go| index 96e9ce77f..654fc541b 100644 |
| --- a/internal/registry/ha_duties_test.go |
| +++ b/internal/registry/ha_duties_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "errors" |
| "path/filepath" |
| "testing" |
| + "time" |
| ) |
| func adoptRegistry(t *testing.T) (*Registry, string) { |
| @@ -80,7 +81,9 @@ func TestHAAdoptRaces(t *testing.T) { |
| _ = r.Delete("shop.example.com") |
| _ = r.Upsert(Route{Host: "shop.example.com", Kind: "instance", Status: "ready"}) |
| case "acquire": |
| - _, _ = r.CompareDuty(context.Background(), "shop.example.com", "life", s.Revision, DutyState{Basis: "local-holder"}) |
| + if err := r.AdvanceHADuty(context.Background(), "shop.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| } |
| got, err := r.ImportHAWake(context.Background(), "shop.example.com", Pair{}, s) |
| if err != nil || got != ImportDeferred { |
| @@ -115,6 +118,40 @@ func TestHAAdoptRemoteParity(t *testing.T) { |
| if err := r.Upsert(Route{Host: "shop.example.com", Kind: "instance", Status: "ready"}); err != nil { |
| t.Fatal(err) |
| } |
| + ctx := context.Background() |
| + host := "shop.example.com" |
| + d, ok, err := r.HADuty(host, "life") |
| + if err != nil || ok { |
| + t.Fatalf("unbound %+v %v %v", d, ok, err) |
| + } |
| + if ok, err = r.BindHADuty(ctx, host, Pair{}, "life", d.Revision); err != nil || !ok { |
| + t.Fatalf("bind %v %v", ok, err) |
| + } |
| + if _, err = r.LoadDuty(ctx, host, "wrong-life"); !errors.Is(err, ErrHAChanged) { |
| + t.Fatalf("changed mapping %v", err) |
| + } |
| + d, err = r.LoadDuty(ctx, host, "life") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + next := DutyState{Basis: "local-release", HolderRef: "b", HolderIID: "i-b", ViewKey: "v", HolderEpoch: 3, NotBefore: time.Now().UTC().Truncate(time.Second)} |
| + if ok, err = r.CompareDuty(ctx, host, "life", d.Revision, next); err != nil || !ok { |
| + t.Fatalf("compare %v %v", ok, err) |
| + } |
| + if ok, err = r.CompareDuty(ctx, host, "life", d.Revision, next); err != nil || ok { |
| + t.Fatalf("stale compare %v %v", ok, err) |
| + } |
| + d, ok, err = r.HADuty(host, "life") |
| + if err != nil || !ok || d.Basis != next.Basis || d.HolderRef != next.HolderRef || d.HolderIID != next.HolderIID || d.ViewKey != next.ViewKey || d.HolderEpoch != next.HolderEpoch || !d.NotBefore.Equal(next.NotBefore) { |
| + t.Fatalf("duty %+v %v %v", d, ok, err) |
| + } |
| + if err = r.AdvanceHADuty(ctx, host); err != nil { |
| + t.Fatal(err) |
| + } |
| + advanced, ok, err := r.HADuty(host, "life") |
| + if err != nil || !ok || advanced.Revision != d.Revision+1 || advanced.Basis != d.Basis { |
| + t.Fatalf("advance %+v -> %+v %v %v", d, advanced, ok, err) |
| + } |
| s := adoptState(t, r) |
| got, err := r.ImportHAWake(context.Background(), "shop.example.com", Pair{}, s) |
| if err != nil || got != Imported { |
| @@ -124,7 +161,48 @@ func TestHAAdoptRemoteParity(t *testing.T) { |
| if err != nil || got != ImportReplayed { |
| t.Fatalf("replay %v %v", got, err) |
| } |
| - s.Timers[0].Kind = "bad" |
| + p, ok, err := r.HAAdoption(ctx, host, "life", s.Receipt) |
| + if err != nil || !ok || p.Phase != "imported_pending_authority" { |
| + t.Fatalf("receipt %+v %v %v", p, ok, err) |
| + } |
| + for _, phase := range []string{"acquiring", "acquired", "marker_pending", "adopted"} { |
| + d, err = r.LoadDuty(ctx, host, "life") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + old := p.Phase |
| + p.Phase = phase |
| + p.AcquiredGeneration = 6 |
| + if ok, err = r.CompareHAAdoption(ctx, host, Pair{}, d.Revision+99, old, p); err != nil || ok { |
| + t.Fatalf("stale phase %v %v", ok, err) |
| + } |
| + if ok, err = r.CompareHAAdoption(ctx, host, Pair{}, d.Revision, old, p); err != nil || !ok { |
| + t.Fatalf("phase %s %v %v", phase, ok, err) |
| + } |
| + read, found, e := r.HAAdoption(ctx, host, "life", s.Receipt) |
| + if e != nil || !found || read != p { |
| + t.Fatalf("phase roundtrip %+v want %+v %v %v", read, p, found, e) |
| + } |
| + } |
| + d, ok, err = r.HADuty(host, "life") |
| + if err != nil || !ok || d.Basis != "adopted" { |
| + t.Fatalf("adopted %+v %v %v", d, ok, err) |
| + } |
| + if ok, err = r.CompareHAAdoption(ctx, host, Pair{}, d.Revision, "adopted", p); !errors.Is(err, ErrHAChanged) || ok { |
| + t.Fatalf("invalid phase mapping %v %v", ok, err) |
| + } |
| + if _, ok, err = r.HAAdoption(ctx, host, "other", s.Receipt); err != nil || ok { |
| + t.Fatalf("missing mapping %v %v", ok, err) |
| + } |
| + s.Timers[0].Registration = "interim" |
| + if err = r.ReplaceHAWake(ctx, host, s); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := r.TimersFor(host) |
| + if err != nil || len(rows) != 1 || rows[0].Registration != "interim" { |
| + t.Fatalf("replace %+v %v", rows, err) |
| + } |
| + s.Replication = "bad" |
| if err = r.ReplaceHAWake(context.Background(), "shop.example.com", s); !errors.Is(err, ErrHAWake) { |
| t.Fatalf("error parity %v", err) |
| } |
| @@ -213,6 +291,22 @@ func TestHAAdoptReceiptCannotCrossRouteRecreation(t *testing.T) { |
| if _, err := r.ImportHAWake(ctx, "shop.example.com", Pair{}, s); err != nil { |
| t.Fatal(err) |
| } |
| + old, ok, err := r.HAAdoption(ctx, "shop.example.com", "life", s.Receipt) |
| + if err != nil || !ok { |
| + t.Fatalf("old receipt %v %v", ok, err) |
| + } |
| + for _, phase := range []string{"acquiring", "acquired", "marker_pending"} { |
| + d, _, err := r.HADuty("shop.example.com", "life") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + before := old.Phase |
| + old.Phase = phase |
| + old.AcquiredGeneration = 6 |
| + if ok, err := r.CompareHAAdoption(ctx, "shop.example.com", Pair{}, d.Revision, before, old); err != nil || !ok { |
| + t.Fatalf("old phase %v %v", ok, err) |
| + } |
| + } |
| if err := r.Delete("shop.example.com"); err != nil { |
| t.Fatal(err) |
| } |
| @@ -225,11 +319,75 @@ func TestHAAdoptReceiptCannotCrossRouteRecreation(t *testing.T) { |
| } |
| s.Revision = d.Revision |
| got, err := r.ImportHAWake(ctx, "shop.example.com", Pair{}, s) |
| - if err != nil || got != ImportDeferred { |
| + if err != nil || got != Imported { |
| t.Fatalf("recreated receipt %v %v", got, err) |
| } |
| - _, ok, err := r.HAAdoption(ctx, "shop.example.com", "life", s.Receipt) |
| - if err != nil || ok { |
| - t.Fatalf("retired receipt grants progress %v %v", ok, err) |
| + _, ok, err = r.HAAdoption(ctx, "shop.example.com", "life", s.Receipt) |
| + if err != nil || !ok { |
| + t.Fatalf("fresh receipt missing %v %v", ok, err) |
| + } |
| + fresh, _, err := r.HAAdoption(ctx, "shop.example.com", "life", s.Receipt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, phase := range []string{"acquiring", "acquired", "marker_pending"} { |
| + d, _, err := r.HADuty("shop.example.com", "life") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + before := fresh.Phase |
| + fresh.Phase = phase |
| + fresh.AcquiredGeneration = 6 |
| + if ok, err := r.CompareHAAdoption(ctx, "shop.example.com", Pair{}, d.Revision, before, fresh); err != nil || !ok { |
| + t.Fatalf("fresh phase %v %v", ok, err) |
| + } |
| + } |
| + d, _, err = r.HADuty("shop.example.com", "life") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + old.Phase = "adopted" |
| + old.AcquiredGeneration = 6 |
| + if changed, err := r.CompareHAAdoption(ctx, "shop.example.com", Pair{}, d.Revision, "marker_pending", old); err != nil || changed { |
| + t.Fatalf("old receipt crossed binding %v %v", changed, err) |
| + } |
| + var count int |
| + if err := r.sql.QueryRow(`SELECT COUNT(*) FROM ha_departure_hosts WHERE host='shop.example.com'`).Scan(&count); err != nil || count != 2 { |
| + t.Fatalf("history count=%d err=%v", count, err) |
| + } |
| + |
| +} |
| + |
| +func TestHAAdoptReceiptMigration(t *testing.T) { |
| + r, path := adoptRegistry(t) |
| + s := adoptState(t, r) |
| + if _, err := r.ImportHAWake(context.Background(), "shop.example.com", Pair{}, s); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.sql.Exec(`ALTER TABLE ha_departure_hosts RENAME TO original_receipts; |
| + CREATE TABLE ha_departure_hosts ( |
| + departure_id TEXT NOT NULL,host TEXT NOT NULL,lifetime TEXT NOT NULL, |
| + departure_ref TEXT NOT NULL,departure_iid TEXT NOT NULL,lock_etag TEXT NOT NULL,lock_generation INTEGER NOT NULL,wake_digest TEXT NOT NULL,sequence INTEGER NOT NULL, |
| + binding INTEGER NOT NULL,phase TEXT NOT NULL,acquired_generation INTEGER NOT NULL DEFAULT 0, |
| + PRIMARY KEY(departure_id,host,lifetime)); |
| + INSERT INTO ha_departure_hosts SELECT * FROM original_receipts; DROP TABLE original_receipts;`); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Close() |
| + for range 2 { |
| + var err error |
| + r, err = Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p, ok, err := r.HAAdoption(context.Background(), "shop.example.com", "life", s.Receipt) |
| + if err != nil || !ok || p.WakeDigest != s.WakeDigest || p.Phase != "imported_pending_authority" { |
| + t.Fatalf("migration %+v %v %v", p, ok, err) |
| + } |
| + var pk int |
| + if err := r.sql.QueryRow(`SELECT pk FROM pragma_table_info('ha_departure_hosts') WHERE name='binding'`).Scan(&pk); err != nil || pk == 0 { |
| + t.Fatalf("binding key=%d err=%v", pk, err) |
| + } |
| + r.Close() |
| } |
| } |
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go| index 53ebd3e79..33ba45a86 100644 |
| --- a/internal/registry/remote_dispatch.go |
| +++ b/internal/registry/remote_dispatch.go |
| @@ -150,6 +150,8 @@ type remoteResponse struct { |
| func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback func(remoteResponse) error) (out remoteResponse, err error) { |
| switch q.Method { |
| + case "AdvanceHADuty": |
| + err = r.AdvanceHADuty(ctx, q.Host) |
| case "HADuty": |
| out.Duty, out.Changed, err = r.HADuty(q.Host, q.Lifetime) |
| case "LoadDuty": |