region HA: hold requests for a moving host at one front-door decision
Task 2 of the held-requests build (spec §25.3 H1, §25.5, §25.15 r4). - activator/handover.go: MoveState, memory-only under a.mu: the loss latch first, then holding, releasing, taken(holder, gen) or none. "None" for a host held here issues an admission ticket under the lock that sets holding; begin ends it once the request is counted in flight. Holds are capped at 64 per host and 1,024 per box, and bounded at 30 s for a client and 25 s for a hop. A hop that is not replayable, and a request that cannot be forwarded, get today's answer at once. Taken lasts the whole drain; ConfirmMoveHolder reads the lock at most once per host per 5 s and names the owner or, on a marker, this box's placement choice. - The move API for Task 5: BeginMove, WaitMoveTickets, SetMoveReleasing, SetMoveTaken, SetMoveLeft, EndDrainMoves. - edge/handover.go: moveGate, called just before frontForwardHAIngress and just before frontForwardHA (ruling, option A). A held client request is released through the ordinary front forward to the confirmed holder. Every handover exit goes through handoverExit: full duplex, Connection: close, flush, read deadline in the past. - X-Carlos-Handover and X-Carlos-Replayable are defined once in edge. The first is stripped from app responses beside X-Carlos-Holder; the second is read from verified hops only and removed from every request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+8 −0internal/activator/haleaseloss.go+2 −0internal/activator/handover.go+439 −0internal/activator/handover_test.go+535 −0internal/edge/edge.go+27 −0internal/edge/forwardha.go+8 −0internal/edge/forwardha_test.go+8 −1internal/edge/haingress.go+7 −0internal/edge/handover.go+275 −0internal/edge/handover_test.go+614 −0
Intent
<task-notification> <task-id>a79933d5fcfe210b4</task-id> <tool-use-id>toolu_01RG943r3k9dChqYty6gtRJz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a79933d5fcfe210b4.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: drain state" 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>Status: DONE Commit: `b2f9d02c` region HA: control name from +rsa mirror entries too. It sits on top of `926057ca`, `ee8609ab` and `e2b0705a`; nothing is pushed. Fix: when neither box publishes a host, the TLS name for a control request now also comes from certificates stored only under the `+rsa` key. Each key is turned into its hostname and checked with the same certificate lookup a handshake uses, so an RSA-only deployment certificate is enough. Tests: I extended `TestHADrainHostlessMembers` with a case where each mirror holds only the `+rsa` entry. It forces a fresh TLS handshake, and the ask is answered "seen". With the round-1 code restored, that case fails with "no mirrored certificate". The covering edge run passes, and vet, gofmt and the darwin/windows builds are clean. The census test failed on the re-pinned `internal/edge` envelope, so I re-ran the proposal under the same NAME and it now passes. Concerns: the census still needs the cross-family verdict on #280. Report (round 2 section appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-1-report.md</result> <usage><subagent_tokens>359472</subagent_tokens><tool_uses>7</tool_uses><duration_ms>217364</duration_ms></usage> </task-notification>
<task-notification> <task-id>a8b92a57abc36621e</task-id> <tool-use-id>toolu_01URYgpYNT8Py6r9Ftkhcx6f</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a8b92a57abc36621e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: MoveState holds" 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>Status: **NEEDS_CONTEXT**. The ordering the brief asks for can't be met in the code as it stands, so I stopped before writing any code. Commits: none. Nothing was changed apart from the report. Tests: none run. Concerns: - **Login POSTs:** in `internal/edge/edge.go`, `frontForwardHA` (line 2210) runs before the gate-login re-resolution (2277-2350). No single point is both after the login change and before `frontForwardHA`. The spec's base commit 9622c65a has the same order (2197, then 2325). - **Metadata-only HA ingress:** these requests are answered inside `routeHAIngress` (its own `ForwardTarget` call) and never reach `frontForwardHA`. One call site in `ServeHTTP` would miss them. - **Admission:** the first `admissionRefuses` (2081) runs before `routeHAIngress`, so "before admission" and "after HA ingress metadata" also conflict. Admission stays open on a draining box, so this changes nothing for it. - **Recommended option A:** one decision function called from two places, just before `frontForwardHAIngress` and just before `frontForwardHA`. Each request reaches only one. Login POSTs are classified by their front route, as `frontForwardHA` already forwards them. This is safe because the gate answers every login POST itself, so none reaches an app or `begin`. It does not meet "one call site" or "after the gate-login change" word for word. - **Options B and C** would change paths that have no move in progress, which the rules forbid. **Option D** breaks H1 while the host is releasing. All four are in the report. Report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-2-report.md`</result> <usage><subagent_tokens>134592</subagent_tokens><tool_uses>20</tool_uses><duration_ms>188954</duration_ms></usage> </task-notification>
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index a0acc9243..fb160a889 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1375,6 +1375,9 @@ type Service struct { |
| // (retryOwedMarkers). |
| markers markerRetry |
| haLoss haLossState |
| + // moves is the planned handover's per-host state and admission |
| + // tickets (handover.go), under mu. |
| + moves moveTable |
| mu sync.Mutex |
| entries map[string]*actEntry |
| @@ -6516,6 +6519,8 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| http.Error(w, "instance is asleep; sidecar requests do not wake it", http.StatusServiceUnavailable) |
| return true |
| } |
| + // Activity-invisible by design, so not held for a move either. |
| + edge.ReleaseMoveTicket(r) |
| proxy.ServeHTTP(w, r) |
| return true |
| } |
| @@ -6528,6 +6533,9 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| return a.serveWakeError(w, r, rt, err) |
| } |
| defer release() |
| + // Counted in flight now: the request's admission ticket ends |
| + // (handover.go). |
| + edge.ReleaseMoveTicket(r) |
| proxy.ServeHTTP(w, r) |
| return true |
| } |
diff --git a/internal/activator/haleaseloss.go b/internal/activator/haleaseloss.go| index 3bb80b69e..ce1521b94 100644 |
| --- a/internal/activator/haleaseloss.go |
| +++ b/internal/activator/haleaseloss.go |
| @@ -81,6 +81,8 @@ func (a *Service) latchHALossLocked(e *actEntry) { |
| close(e.haRefused) |
| a.haLoss.hosts[e.host] = &haLeaseLoss{old: e, route: e.route, refused: e.haRefused} |
| a.holders.drop(e.host) |
| + // A held request for a moving host gets F-A's answer now (handover.go). |
| + a.pokeMoveLocked(e.host) |
| } |
| func haUnexpectedLoss(e *actEntry, err error) bool { |
diff --git a/internal/activator/handover.go b/internal/activator/handover.go| new file mode 100644 |
| index 000000000..c1c1c0cc8 |
| --- /dev/null |
| +++ b/internal/activator/handover.go |
| @@ -0,0 +1,439 @@ |
| +package activator |
| + |
| +// Held requests during a planned handover, the activator's half (region HA |
| +// spec §25.3 H1, §25.4 step 3, §25.5, §25.15 r4). While this box, draining, |
| +// moves an awake host H to a successor, the edge asks MoveState about every |
| +// request for H, at its front door (internal/edge/handover.go). The answer |
| +// is memory-only and made under a.mu: |
| +// |
| +// 1. the loss latch first: a lost lease gets F-A's answer in every phase; |
| +// 2. holding or releasing: the request is held, its body unread, within |
| +// the bounds below; a hop that is not replayable (or is a second |
| +// attempt) and a request that cannot be forwarded get today's answer |
| +// at once, never queued (R3.3); |
| +// 3. taken(holder, gen): released at once, a client's request to the |
| +// confirmed holder, a replayable hop with the handover answer after a |
| +// coalesced lock check (R3.4); |
| +// 4. anything else: none. For a host this box holds, the request takes an |
| +// admission ticket under the same lock that sets holding (R3.2), and |
| +// the move waits for tickets before it stops the app. |
| +// |
| +// The drain driver (Task 5) is the only caller of the move API below; no |
| +// driver logic lives here. Nothing in this file is an input to |
| +// hafresh.DecideAcquire (I1): the coalesced check only reads the lock. |
| +// |
| +// Move API, in the order the driver calls it for one host H: |
| +// |
| +// BeginMove(H) holding: refuses unless H is awake here with an |
| +// HA lease and no loss is latched. |
| +// WaitMoveTickets(ctx, H) waits for H's admission tickets (requests that |
| +// read "none" and are not yet counted in flight by |
| +// begin, or are waiting in begin) within ctx, which |
| +// the driver bounds by the 10 s in-flight drain. |
| +// SetMoveReleasing(H) the stop and marker are under way. |
| +// SetMoveTaken(H, ref, gen) the take answered: ref is the confirmed holder |
| +// from lock.json at generation gen (Task 4). |
| +// Holds are released. Kept until EndDrainMoves. |
| +// SetMoveLeft(H, reason) the move failed or was abandoned: every hold |
| +// gets today's answer and H's entry is dropped, |
| +// so later requests go on as today. |
| +// EndDrainMoves() the drain is over (drained acknowledged, or |
| +// cancelled): every move entry is dropped. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The bounds of §25.5's table. |
| +const ( |
| + moveHoldPerHost = 64 |
| + moveHoldPerBox = 1024 |
| + // moveCheckEvery is the coalesced lock check's spacing (R3.4). |
| + moveCheckEvery = 5 * time.Second |
| +) |
| + |
| +// moveHoldClient and moveHoldHop are how long a client's request and a |
| +// hop may be held: wakeWaitBound's 30 s, and 25 s inside the hop's 30 s |
| +// header timeout. Vars only so a test can shorten them. |
| +var ( |
| + moveHoldClient = 30 * time.Second |
| + moveHoldHop = 25 * time.Second |
| +) |
| + |
| +type movePhase uint8 |
| + |
| +const ( |
| + moveHolding movePhase = iota + 1 |
| + moveReleasing |
| + moveTaken |
| +) |
| + |
| +// hostMove is one host's move on this box. |
| +type hostMove struct { |
| + phase movePhase |
| + holder string |
| + gen int64 |
| + // changed is closed, and replaced, at every transition, and when the |
| + // loss latch closes for the host. |
| + changed chan struct{} |
| + // held is the number of requests held for the host now. |
| + held int |
| + // gone is set when the entry is dropped (left or drain ended). |
| + gone bool |
| + // check is the coalesced lock check (ConfirmMoveHolder). |
| + checkAt time.Time |
| + checkFlight chan struct{} |
| + checkResult edge.MoveDecision |
| +} |
| + |
| +// moveTable is the box's moves, guarded by a.mu. |
| +type moveTable struct { |
| + hosts map[string]*hostMove |
| + held int |
| + // tickets counts, per host, the requests that read "none" for a host |
| + // this box holds and have not yet finished, been forwarded or been |
| + // counted by begin. |
| + tickets map[string]int |
| + // ticketsDone is closed, and replaced, whenever a ticket ends. |
| + ticketsDone chan struct{} |
| +} |
| + |
| +var ( |
| + // ErrMoveNotHeld: BeginMove for a host that is not awake here with an |
| + // HA lease. |
| + ErrMoveNotHeld = errors.New("handover: host is not held here") |
| + // ErrMoveInProgress: BeginMove for a host already moving. |
| + ErrMoveInProgress = errors.New("handover: host is already moving") |
| + // ErrMoveUnknown: a move transition for a host that is not moving. |
| + ErrMoveUnknown = errors.New("handover: host is not moving") |
| +) |
| + |
| +func (m *hostMove) notifyLocked() { |
| + close(m.changed) |
| + m.changed = make(chan struct{}) |
| +} |
| + |
| +// pokeMoveLocked wakes host's holds to look again (the loss latch). |
| +func (a *Service) pokeMoveLocked(host string) { |
| + if m := a.moves.hosts[host]; m != nil { |
| + m.notifyLocked() |
| + } |
| +} |
| + |
| +// MoveState is the front-door handover decision for rt (H1). See the file |
| +// comment for the order. |
| +func (a *Service) MoveState(rt registry.Route, ask edge.MoveAsk) edge.MoveDecision { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + m := a.moves.hosts[rt.Host] |
| + if m == nil { |
| + return a.moveNoneLocked(rt) |
| + } |
| + if d, ok := a.moveDecideLocked(rt, m, ask); ok { |
| + return d |
| + } |
| + // Held: reserve a slot within the caps, or today's answer at once. |
| + if m.held >= moveHoldPerHost || a.moves.held >= moveHoldPerBox { |
| + return edge.MoveDecision{Phase: edge.MoveRefused} |
| + } |
| + m.held++ |
| + a.moves.held++ |
| + bound := moveHoldClient |
| + if ask.Hop { |
| + bound = moveHoldHop |
| + } |
| + return edge.MoveDecision{Phase: edge.MoveHolding, Wait: func(ctx context.Context) edge.MoveDecision { |
| + return a.waitMove(ctx, rt, m, ask, bound) |
| + }} |
| +} |
| + |
| +// moveNoneLocked is MoveState's "none": an admission ticket when this box |
| +// holds rt's host (an entry for the same route, in any state). |
| +func (a *Service) moveNoneLocked(rt registry.Route) edge.MoveDecision { |
| + e := a.entries[rt.Host] |
| + if e == nil || !samePoolRoute(e, rt) { |
| + return edge.MoveDecision{} |
| + } |
| + if a.moves.tickets == nil { |
| + a.moves.tickets = make(map[string]int) |
| + } |
| + a.moves.tickets[rt.Host]++ |
| + host := rt.Host |
| + return edge.MoveDecision{Done: func() { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + if a.moves.tickets[host]--; a.moves.tickets[host] <= 0 { |
| + delete(a.moves.tickets, host) |
| + } |
| + if a.moves.ticketsDone != nil { |
| + close(a.moves.ticketsDone) |
| + a.moves.ticketsDone = nil |
| + } |
| + }} |
| +} |
| + |
| +// moveDecideLocked answers every phase but a hold: ok false means hold. |
| +func (a *Service) moveDecideLocked(rt registry.Route, m *hostMove, ask edge.MoveAsk) (edge.MoveDecision, bool) { |
| + if m.gone { |
| + return edge.MoveDecision{Phase: edge.MoveRefused}, true |
| + } |
| + if a.haLeaseRefusalLocked(rt) != nil { |
| + return edge.MoveDecision{Phase: edge.MoveLost}, true |
| + } |
| + if ask.Hop && !ask.Replayable { |
| + return edge.MoveDecision{Phase: edge.MoveRefused}, true |
| + } |
| + if !ask.Hop && !ask.Forwardable { |
| + return edge.MoveDecision{Phase: edge.MoveRefused}, true |
| + } |
| + if m.phase != moveTaken { |
| + return edge.MoveDecision{}, false |
| + } |
| + d := edge.MoveDecision{Phase: edge.MoveTaken, Holder: m.holder, Gen: m.gen} |
| + if !ask.Hop { |
| + if res, hit := a.holders.peek(rt.Host); hit && res.Ref == m.holder { |
| + d.ForwardGen = res.Gen |
| + } |
| + } |
| + return d, true |
| +} |
| + |
| +// waitMove is a held request's wait. |
| +func (a *Service) waitMove(ctx context.Context, rt registry.Route, m *hostMove, ask edge.MoveAsk, bound time.Duration) edge.MoveDecision { |
| + timer := time.NewTimer(bound) |
| + defer timer.Stop() |
| + a.mu.Lock() |
| + defer func() { |
| + m.held-- |
| + a.moves.held-- |
| + a.mu.Unlock() |
| + }() |
| + for { |
| + if d, ok := a.moveDecideLocked(rt, m, ask); ok { |
| + return d |
| + } |
| + changed := m.changed |
| + a.mu.Unlock() |
| + select { |
| + case <-changed: |
| + case <-timer.C: |
| + a.mu.Lock() |
| + // A bound hit: today's answer, unless the lease was lost meanwhile. |
| + if d, ok := a.moveDecideLocked(rt, m, ask); ok && d.Phase == edge.MoveLost { |
| + return d |
| + } |
| + return edge.MoveDecision{Phase: edge.MoveRefused} |
| + case <-ctx.Done(): |
| + a.mu.Lock() |
| + return edge.MoveDecision{Phase: edge.MoveRefused} |
| + } |
| + a.mu.Lock() |
| + } |
| +} |
| + |
| +// BeginMove starts holding host's requests (§25.4 step 3.1). It refuses |
| +// unless host is awake here with an HA lease and no loss is latched for it. |
| +func (a *Service) BeginMove(host string) error { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + if m := a.moves.hosts[host]; m != nil { |
| + return ErrMoveInProgress |
| + } |
| + e := a.entries[host] |
| + if e == nil || e.state != actAwake { |
| + return ErrMoveNotHeld |
| + } |
| + if _, ha := haEntryRep(e); !ha { |
| + return ErrMoveNotHeld |
| + } |
| + if a.haLeaseRefusalLocked(e.route) != nil { |
| + return ErrHALeaseUnavailable |
| + } |
| + if a.moves.hosts == nil { |
| + a.moves.hosts = make(map[string]*hostMove) |
| + } |
| + a.moves.hosts[host] = &hostMove{phase: moveHolding, changed: make(chan struct{})} |
| + return nil |
| +} |
| + |
| +// WaitMoveTickets waits until host has no outstanding admission ticket, or |
| +// ctx ends (its error). Call it after BeginMove: from then on no new ticket |
| +// is issued for host, so the count only falls. |
| +func (a *Service) WaitMoveTickets(ctx context.Context, host string) error { |
| + for { |
| + a.mu.Lock() |
| + if a.moves.tickets[host] == 0 { |
| + a.mu.Unlock() |
| + return nil |
| + } |
| + if a.moves.ticketsDone == nil { |
| + a.moves.ticketsDone = make(chan struct{}) |
| + } |
| + done := a.moves.ticketsDone |
| + a.mu.Unlock() |
| + select { |
| + case <-done: |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| + } |
| +} |
| + |
| +// MoveTickets is host's outstanding admission tickets, for the drain |
| +// report. |
| +func (a *Service) MoveTickets(host string) int { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return a.moves.tickets[host] |
| +} |
| + |
| +// SetMoveReleasing marks host's stop and marker under way (§25.4 step |
| +// 3.2-3.3). Holds continue. |
| +func (a *Service) SetMoveReleasing(host string) error { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + m := a.moves.hosts[host] |
| + if m == nil || m.phase == moveTaken { |
| + return ErrMoveUnknown |
| + } |
| + m.phase = moveReleasing |
| + m.notifyLocked() |
| + return nil |
| +} |
| + |
| +// SetMoveTaken records the take's confirmed holder of host, read from |
| +// lock.json at generation lockGen (§25.4 step 3.4-3.5), and releases the |
| +// holds. The entry lasts until EndDrainMoves (R3.4). |
| +func (a *Service) SetMoveTaken(host, holderRef string, lockGen int64) error { |
| + if holderRef == "" { |
| + return errors.New("handover: a taken host needs a holder") |
| + } |
| + if self, ok := boxSelfRef(a.backend); ok && self == holderRef { |
| + return errors.New("handover: the confirmed holder cannot be this box") |
| + } |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + m := a.moves.hosts[host] |
| + if m == nil { |
| + return ErrMoveUnknown |
| + } |
| + m.phase, m.holder, m.gen = moveTaken, holderRef, lockGen |
| + m.checkAt, m.checkResult = time.Time{}, edge.MoveDecision{} |
| + a.holders.set(host, holderRef) |
| + m.notifyLocked() |
| + return nil |
| +} |
| + |
| +// SetMoveLeft ends host's move as failed (§25.4 failures): every hold gets |
| +// today's answer, and the entry is dropped so later requests go on as |
| +// today. |
| +func (a *Service) SetMoveLeft(host, reason string) { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + m := a.moves.hosts[host] |
| + if m == nil { |
| + return |
| + } |
| + log.Printf("activator: handover of %s left: %s; its held requests get today's answer", host, reason) |
| + m.gone = true |
| + delete(a.moves.hosts, host) |
| + m.notifyLocked() |
| +} |
| + |
| +// EndDrainMoves drops every move entry: the drain is over. A hold still |
| +// waiting gets today's answer. |
| +func (a *Service) EndDrainMoves() { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + for host, m := range a.moves.hosts { |
| + m.gone = true |
| + delete(a.moves.hosts, host) |
| + m.notifyLocked() |
| + } |
| +} |
| + |
| +// ConfirmMoveHolder is the coalesced lock check before a hop is answered |
| +// from taken (R3.4): at most one lock read per host per moveCheckEvery, |
| +// shared by every request in that window, failures included. It names the |
| +// lock's current owner, or this box's placement choice when the lock is a |
| +// release marker (a hop receiver may acquire from it, §6.4). Anything else |
| +// is MoveRefused. It authorizes nothing: it only reads. |
| +func (a *Service) ConfirmMoveHolder(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot) edge.MoveDecision { |
| + refused := edge.MoveDecision{Phase: edge.MoveRefused} |
| + r := holderReaderFor(a.backend, rt) |
| + a.mu.Lock() |
| + for { |
| + m := a.moves.hosts[rt.Host] |
| + if m == nil || m.phase != moveTaken || r == nil { |
| + a.mu.Unlock() |
| + return refused |
| + } |
| + if f := m.checkFlight; f != nil { |
| + a.mu.Unlock() |
| + select { |
| + case <-f: |
| + case <-ctx.Done(): |
| + return refused |
| + } |
| + a.mu.Lock() |
| + continue |
| + } |
| + if !m.checkAt.IsZero() && a.now().Before(m.checkAt.Add(moveCheckEvery)) { |
| + d := m.checkResult |
| + a.mu.Unlock() |
| + return d |
| + } |
| + f := make(chan struct{}) |
| + m.checkFlight, m.checkAt = f, a.now() |
| + a.mu.Unlock() |
| + d := a.readMoveHolder(ctx, rt, r, snapshot) |
| + a.mu.Lock() |
| + m.checkResult, m.checkFlight = d, nil |
| + close(f) |
| + a.mu.Unlock() |
| + return d |
| + } |
| +} |
| + |
| +// readMoveHolder is ConfirmMoveHolder's one read and its reading. |
| +func (a *Service) readMoveHolder(ctx context.Context, rt registry.Route, r holderLockReader, snapshot func() boxchoice.WakeSnapshot) edge.MoveDecision { |
| + refused := edge.MoveDecision{Phase: edge.MoveRefused} |
| + // Every waiter's read, not this request's: detached and bounded. |
| + rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), holderReadTimeout) |
| + defer cancel() |
| + v, err := r.readHolderView(rctx, rt) |
| + if err != nil { |
| + return refused |
| + } |
| + self := r.self() |
| + now := a.holders.clock() |
| + if ref := otherHolder(v, self, now); ref != "" { |
| + return edge.MoveDecision{Phase: edge.MoveTaken, Holder: ref, Gen: v.Lock.Generation} |
| + } |
| + if v.Absent || v.Lock.Release == nil { |
| + return refused |
| + } |
| + var s boxchoice.WakeSnapshot |
| + if snapshot != nil { |
| + s = snapshot() |
| + } |
| + // This box is draining: it is never its own placement choice. |
| + s.LocalDenied = true |
| + a.peers.mu.Lock() |
| + pv := a.peers.snapshotForLocked(now, s.Serving) |
| + a.peers.mu.Unlock() |
| + d := DecidePlacement(rt, self, &v, s, a.LocalEligible(rt), pv, now) |
| + if (d.Kind == Place || d.Kind == Recovery) && d.Ref != "" && d.Ref != self.Ref && d.Ref != s.Self { |
| + return edge.MoveDecision{Phase: edge.MoveTaken, Holder: d.Ref, Gen: v.Lock.Generation} |
| + } |
| + return refused |
| +} |
| + |
| +var _ edge.HAMover = (*Service)(nil) |
diff --git a/internal/activator/handover_test.go b/internal/activator/handover_test.go| new file mode 100644 |
| index 000000000..dd8e2e3ca |
| --- /dev/null |
| +++ b/internal/activator/handover_test.go |
| @@ -0,0 +1,535 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Held requests during a planned handover (handover.go; region HA §25.5, |
| +// §25.15). The scene is haServiceEntry: a real Service whose exec backend |
| +// woke the born-HA host for real, so this box holds its lease. |
| + |
| +var ( |
| + askClient = edge.MoveAsk{Forwardable: true} |
| + askReplayable = edge.MoveAsk{Hop: true, Replayable: true} |
| + askHop = edge.MoveAsk{Hop: true} |
| + askDoor = edge.MoveAsk{} |
| +) |
| + |
| +func shortMoveBounds(t *testing.T, client, hop time.Duration) { |
| + t.Helper() |
| + oc, oh := moveHoldClient, moveHoldHop |
| + moveHoldClient, moveHoldHop = client, hop |
| + t.Cleanup(func() { moveHoldClient, moveHoldHop = oc, oh }) |
| +} |
| + |
| +// waitAsync runs d.Wait in the background. |
| +func waitAsync(ctx context.Context, d edge.MoveDecision) <-chan edge.MoveDecision { |
| + ch := make(chan edge.MoveDecision, 1) |
| + go func() { ch <- d.Wait(ctx) }() |
| + return ch |
| +} |
| + |
| +func wantStill(t *testing.T, step string, ch <-chan edge.MoveDecision) { |
| + t.Helper() |
| + select { |
| + case d := <-ch: |
| + t.Fatalf("%s: the hold ended early: %+v", step, d) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| +} |
| + |
| +func wantDecision(t *testing.T, step string, ch <-chan edge.MoveDecision, phase edge.MovePhase) edge.MoveDecision { |
| + t.Helper() |
| + select { |
| + case d := <-ch: |
| + if d.Phase != phase { |
| + t.Fatalf("%s: %+v, want phase %d", step, d, phase) |
| + } |
| + return d |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("%s: the hold never ended", step) |
| + } |
| + return edge.MoveDecision{} |
| +} |
| + |
| +func TestMoveStateNoneWithoutAMove(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + other := s.rt |
| + other.Host = "elsewhere.example.com" |
| + if d := s.a.MoveState(other, askClient); d.Phase != edge.MoveNone || d.Done != nil { |
| + t.Fatalf("a host not held here: %+v, want none and no ticket", d) |
| + } |
| + d := s.a.MoveState(s.rt, askClient) |
| + if d.Phase != edge.MoveNone || d.Done == nil { |
| + t.Fatalf("a host held here: %+v, want none with a ticket", d) |
| + } |
| + if n := s.a.MoveTickets(s.rt.Host); n != 1 { |
| + t.Fatalf("tickets = %d, want 1", n) |
| + } |
| + d.Done() |
| + if n := s.a.MoveTickets(s.rt.Host); n != 0 { |
| + t.Fatalf("tickets after Done = %d, want 0", n) |
| + } |
| +} |
| + |
| +func TestMovePhasesAndRelease(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.a.BeginMove(s.rt.Host); !errors.Is(err, ErrMoveInProgress) { |
| + t.Fatalf("a second BeginMove = %v", err) |
| + } |
| + // Refused at once, never queued (R3.3). |
| + for name, ask := range map[string]edge.MoveAsk{"a hop that is not replayable": askHop, "a request that cannot be forwarded": askDoor} { |
| + if d := s.a.MoveState(s.rt, ask); d.Phase != edge.MoveRefused { |
| + t.Fatalf("%s: %+v, want refused at once", name, d) |
| + } |
| + } |
| + client := s.a.MoveState(s.rt, askClient) |
| + hop := s.a.MoveState(s.rt, askReplayable) |
| + if client.Phase != edge.MoveHolding || hop.Phase != edge.MoveHolding || client.Done != nil { |
| + t.Fatalf("holding: client %+v hop %+v", client, hop) |
| + } |
| + if n := s.a.MoveTickets(s.rt.Host); n != 0 { |
| + t.Fatalf("a held request took a ticket: %d", n) |
| + } |
| + cw, hw := waitAsync(t.Context(), client), waitAsync(t.Context(), hop) |
| + wantStill(t, "holding", cw) |
| + if err := s.a.SetMoveReleasing(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantStill(t, "releasing", cw) |
| + wantStill(t, "releasing", hw) |
| + late := s.a.MoveState(s.rt, askClient) |
| + if late.Phase != edge.MoveHolding { |
| + t.Fatalf("releasing: %+v, want held", late) |
| + } |
| + lw := waitAsync(t.Context(), late) |
| + if err := s.a.SetMoveTaken(s.rt.Host, "b", 9); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, ch := range map[string]<-chan edge.MoveDecision{"client": cw, "hop": hw, "late": lw} { |
| + d := wantDecision(t, name, ch, edge.MoveTaken) |
| + if d.Holder != "b" || d.Gen != 9 { |
| + t.Fatalf("%s: released to %+v, want b at 9", name, d) |
| + } |
| + } |
| + // taken: at once, for the whole drain (R3.4), long after 30 s. |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.now = clk.now |
| + clk.advance(31 * time.Second) |
| + if d := s.a.MoveState(s.rt, askClient); d.Phase != edge.MoveTaken || d.Holder != "b" { |
| + t.Fatalf("taken 31 s later: %+v", d) |
| + } |
| + if d := s.a.MoveState(s.rt, askHop); d.Phase != edge.MoveRefused { |
| + t.Fatalf("taken, a hop that is not replayable: %+v", d) |
| + } |
| + s.a.mu.Lock() |
| + held := s.a.moves.held |
| + s.a.mu.Unlock() |
| + if held != 0 { |
| + t.Fatalf("hold slots left taken: %d", held) |
| + } |
| + s.a.EndDrainMoves() |
| + if d := s.a.MoveState(s.rt, askClient); d.Phase != edge.MoveNone { |
| + t.Fatalf("after the drain: %+v, want none", d) |
| + } |
| +} |
| + |
| +func TestMoveSetAPIRefusals(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + if err := s.a.BeginMove("unknown.example.com"); !errors.Is(err, ErrMoveNotHeld) { |
| + t.Fatalf("BeginMove of a host not here = %v", err) |
| + } |
| + if err := s.a.SetMoveReleasing(s.rt.Host); !errors.Is(err, ErrMoveUnknown) { |
| + t.Fatalf("SetMoveReleasing without a move = %v", err) |
| + } |
| + if err := s.a.SetMoveTaken(s.rt.Host, "b", 1); !errors.Is(err, ErrMoveUnknown) { |
| + t.Fatalf("SetMoveTaken without a move = %v", err) |
| + } |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.a.SetMoveTaken(s.rt.Host, "a", 1); err == nil { |
| + t.Fatal("this box was accepted as its own successor") |
| + } |
| + if err := s.a.SetMoveTaken(s.rt.Host, "", 1); err == nil { |
| + t.Fatal("an empty holder was accepted") |
| + } |
| +} |
| + |
| +func TestMoveLeftAnswersTodaysAnswer(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + ch := waitAsync(t.Context(), s.a.MoveState(s.rt, askClient)) |
| + s.a.SetMoveLeft(s.rt.Host, "take failed") |
| + wantDecision(t, "left", ch, edge.MoveRefused) |
| + d := s.a.MoveState(s.rt, askClient) |
| + if d.Phase != edge.MoveNone { |
| + t.Fatalf("after a failed move: %+v, want none (today's path)", d) |
| + } |
| + if d.Done != nil { |
| + d.Done() |
| + } |
| + // EndDrainMoves answers a hold still waiting too. |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + ch = waitAsync(t.Context(), s.a.MoveState(s.rt, askReplayable)) |
| + s.a.EndDrainMoves() |
| + wantDecision(t, "drain ended", ch, edge.MoveRefused) |
| +} |
| + |
| +// F-A at each phase: the loss latch wins, and a held request gets it at once. |
| +func TestMoveLossFirstInEveryPhase(t *testing.T) { |
| + for _, phase := range []string{"holding", "releasing", "taken"} { |
| + t.Run(phase, func(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + var held <-chan edge.MoveDecision |
| + switch phase { |
| + case "releasing": |
| + s.a.SetMoveReleasing(s.rt.Host) |
| + case "taken": |
| + s.a.SetMoveTaken(s.rt.Host, "b", 3) |
| + } |
| + if phase != "taken" { |
| + held = waitAsync(t.Context(), s.a.MoveState(s.rt, askClient)) |
| + wantStill(t, phase, held) |
| + } |
| + s.a.mu.Lock() |
| + if phase == "taken" { |
| + s.a.haLoss.hosts = map[string]*haLeaseLoss{s.rt.Host: {route: s.rt, refused: make(chan struct{})}} |
| + } else { |
| + s.a.latchHALossLocked(e) |
| + } |
| + s.a.mu.Unlock() |
| + if held != nil { |
| + wantDecision(t, "the held request", held, edge.MoveLost) |
| + } |
| + for name, ask := range map[string]edge.MoveAsk{"client": askClient, "replayable hop": askReplayable, "hop": askHop, "door": askDoor} { |
| + if d := s.a.MoveState(s.rt, ask); d.Phase != edge.MoveLost { |
| + t.Fatalf("%s: %+v, want F-A", name, d) |
| + } |
| + } |
| + if err := s.a.BeginMove("shop.example.com"); err == nil { |
| + t.Fatal("BeginMove over a move") |
| + } |
| + }) |
| + } |
| + t.Run("BeginMove refuses a lost host", func(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.a.mu.Lock() |
| + s.a.latchHALossLocked(e) |
| + s.a.mu.Unlock() |
| + if err := s.a.BeginMove(s.rt.Host); err == nil { |
| + t.Fatal("BeginMove of a lost host") |
| + } |
| + }) |
| +} |
| + |
| +func TestMoveBoundsTable(t *testing.T) { |
| + if moveHoldPerHost != 64 || moveHoldPerBox != 1024 || moveHoldClient != 30*time.Second || moveHoldHop != 25*time.Second || moveCheckEvery != 5*time.Second { |
| + t.Fatalf("bounds %d %d %v %v %v differ from §25.5's table", moveHoldPerHost, moveHoldPerBox, moveHoldClient, moveHoldHop, moveCheckEvery) |
| + } |
| + if moveHoldClient != wakeWaitBound { |
| + t.Fatalf("a client's hold %v is not wakeWaitBound %v", moveHoldClient, wakeWaitBound) |
| + } |
| +} |
| + |
| +func TestMoveHoldTimeBounds(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + shortMoveBounds(t, 300*time.Millisecond, 100*time.Millisecond) |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + start := time.Now() |
| + hop := waitAsync(t.Context(), s.a.MoveState(s.rt, askReplayable)) |
| + client := waitAsync(t.Context(), s.a.MoveState(s.rt, askClient)) |
| + wantDecision(t, "the hop", hop, edge.MoveRefused) |
| + if el := time.Since(start); el < 100*time.Millisecond || el > 250*time.Millisecond { |
| + t.Fatalf("the hop was held %v, want its bound", el) |
| + } |
| + wantDecision(t, "the client", client, edge.MoveRefused) |
| + if el := time.Since(start); el < 300*time.Millisecond { |
| + t.Fatalf("the client was held %v, want its bound", el) |
| + } |
| + // A client that leaves ends its hold and its slot. |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + gone := waitAsync(ctx, s.a.MoveState(s.rt, askClient)) |
| + cancel() |
| + wantDecision(t, "a client that left", gone, edge.MoveRefused) |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + if s.a.moves.held != 0 || s.a.moves.hosts[s.rt.Host].held != 0 { |
| + t.Fatalf("slots left: box %d host %d", s.a.moves.held, s.a.moves.hosts[s.rt.Host].held) |
| + } |
| +} |
| + |
| +func TestMoveHoldCaps(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + var waits []<-chan edge.MoveDecision |
| + for range moveHoldPerHost { |
| + d := s.a.MoveState(s.rt, askClient) |
| + if d.Phase != edge.MoveHolding { |
| + t.Fatalf("hold %d: %+v", len(waits), d) |
| + } |
| + waits = append(waits, waitAsync(ctx, d)) |
| + } |
| + if d := s.a.MoveState(s.rt, askReplayable); d.Phase != edge.MoveRefused { |
| + t.Fatalf("the 65th: %+v, want today's answer", d) |
| + } |
| + // The box cap: other moving hosts' holds fill it (entries made here, |
| + // as BeginMove's; the cap is the table's alone). |
| + s.a.mu.Lock() |
| + for i := 0; s.a.moves.held < moveHoldPerBox; i++ { |
| + h := &hostMove{phase: moveHolding, changed: make(chan struct{})} |
| + n := min(moveHoldPerHost, moveHoldPerBox-s.a.moves.held) |
| + h.held = n |
| + s.a.moves.held += n |
| + s.a.moves.hosts["other"+string(rune('a'+i))+".example.com"] = h |
| + } |
| + third := registry.Route{Host: "third.example.com", HA: true} |
| + s.a.moves.hosts[third.Host] = &hostMove{phase: moveHolding, changed: make(chan struct{})} |
| + s.a.mu.Unlock() |
| + if d := s.a.MoveState(third, askClient); d.Phase != edge.MoveRefused { |
| + t.Fatalf("over the box cap: %+v, want today's answer", d) |
| + } |
| + // One slot back: the next request is held again. |
| + cancel() |
| + for _, ch := range waits { |
| + <-ch |
| + } |
| + if d := s.a.MoveState(third, askClient); d.Phase != edge.MoveHolding { |
| + t.Fatalf("under the box cap again: %+v", d) |
| + } |
| +} |
| + |
| +// R3.2 pause points. The ticket is taken under the lock that sets holding, |
| +// so every request crossing BeginMove is either counted or held. |
| +func TestMoveTicketsPausePoints(t *testing.T) { |
| + t.Run("right after MoveState returns none", func(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + d := s.a.MoveState(s.rt, askClient) |
| + if d.Done == nil { |
| + t.Fatal("no ticket") |
| + } |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) |
| + defer cancel() |
| + if err := s.a.WaitMoveTickets(ctx, s.rt.Host); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("the move did not wait for the ticket: %v", err) |
| + } |
| + done := make(chan error, 1) |
| + go func() { done <- s.a.WaitMoveTickets(t.Context(), s.rt.Host) }() |
| + time.Sleep(20 * time.Millisecond) |
| + d.Done() |
| + d.Done() // twice is once |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := s.a.MoveTickets(s.rt.Host); n != 0 { |
| + t.Fatalf("tickets = %d", n) |
| + } |
| + }) |
| + t.Run("after ForwardTarget returns local, until begin counts it", func(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + d := s.a.MoveState(s.rt, askClient) |
| + if f := s.a.ForwardTarget(t.Context(), s.rt, nil); f.Ref != "" || f.Refuse || f.Unavailable { |
| + t.Fatalf("ForwardTarget = %+v, want local", f) |
| + } |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + waited := make(chan error, 1) |
| + wctx, wcancel := context.WithTimeout(t.Context(), 5*time.Second) |
| + defer wcancel() |
| + go func() { waited <- s.a.WaitMoveTickets(wctx, s.rt.Host) }() |
| + select { |
| + case err := <-waited: |
| + t.Fatalf("the move went on past a request ForwardTarget sent here: %v", err) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + inProxy, leave := make(chan struct{}), make(chan struct{}) |
| + var inflight int |
| + proxy := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + s.a.mu.Lock() |
| + inflight = s.a.entries[s.rt.Host].inflight |
| + s.a.mu.Unlock() |
| + close(inProxy) |
| + <-leave |
| + }) |
| + r := edge.WithMoveTicket(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil), d.Done) |
| + served := make(chan bool, 1) |
| + go func() { served <- s.a.ServeHTTP(httptest.NewRecorder(), r, s.rt, proxy) }() |
| + <-inProxy |
| + if err := <-waited; err != nil { |
| + t.Fatal(err) |
| + } |
| + if inflight != 1 { |
| + t.Fatalf("in flight = %d when the ticket ended, want 1: the request must be counted first", inflight) |
| + } |
| + close(leave) |
| + <-served |
| + }) |
| + t.Run("while begin waits on a stop", func(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + stopping, finish := make(chan struct{}), make(chan struct{}) |
| + var once sync.Once |
| + prev := s.ctl.stopHook |
| + s.ctl.stopHook = func(id string, role instancectl.Role) { |
| + once.Do(func() { close(stopping); <-finish }) |
| + if prev != nil { |
| + prev(id, role) |
| + } |
| + } |
| + d := s.a.MoveState(s.rt, askClient) |
| + go s.stopForTest(e) |
| + <-stopping |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + r := edge.WithMoveTicket(httptest.NewRequestWithContext(ctx, http.MethodGet, "https://shop.example.com/", nil), d.Done) |
| + served := make(chan struct{}) |
| + go func() { |
| + s.a.ServeHTTP(httptest.NewRecorder(), r, s.rt, http.NotFoundHandler()) |
| + d.Done() // the edge's own end of the request |
| + close(served) |
| + }() |
| + waitUntil(t, "the request waiting in begin on the stop", func() bool { |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + return e.state == actStopping && e.haRefused != nil |
| + }) |
| + short, scancel := context.WithTimeout(t.Context(), 100*time.Millisecond) |
| + defer scancel() |
| + if err := s.a.WaitMoveTickets(short, s.rt.Host); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("a request waiting in begin was not counted: %v", err) |
| + } |
| + cancel() |
| + <-served |
| + if err := s.a.WaitMoveTickets(t.Context(), s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + close(finish) |
| + }) |
| +} |
| + |
| +// R3.4: one coalesced lock read per host per 5 s; the current owner, or |
| +// this box's placement choice on a marker; refusal otherwise. |
| +func TestConfirmMoveHolderCoalesced(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.now = clk.now |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.a.SetMoveTaken(s.rt.Host, "b", 4); err != nil { |
| + t.Fatal(err) |
| + } |
| + lockGets := func() int { |
| + n := 0 |
| + for _, r := range s.fx.Requests() { |
| + if strings.HasPrefix(r, "GET ") && strings.HasSuffix(r, s.b.Cfg.hibernatePrefix(s.rt.Host)+"/lock.json") { |
| + n++ |
| + } |
| + } |
| + return n |
| + } |
| + snap := func() func() boxchoice.WakeSnapshot { |
| + return func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) } |
| + } |
| + // The successor still holds: 31 s after the move, a peer caching this |
| + // box sends a hop. It is named, and twenty such hops cost one read. |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(time.Hour))) |
| + clk.advance(31 * time.Second) |
| + before, beforeAll := lockGets(), len(s.fx.Requests()) |
| + var wg sync.WaitGroup |
| + results := make(chan edge.MoveDecision, 20) |
| + for range 20 { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); results <- s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()) }() |
| + } |
| + wg.Wait() |
| + close(results) |
| + for d := range results { |
| + if d.Phase != edge.MoveTaken || d.Holder != "b" || d.Gen != 9 { |
| + t.Fatalf("31 s after: %+v, want b at the lock's generation", d) |
| + } |
| + } |
| + if got := lockGets() - before; got != 1 { |
| + t.Fatalf("20 hops read the lock %d times, want 1", got) |
| + } |
| + // The successor slept: a marker. Within 5 s the old answer stands and |
| + // nothing is read; after, one read names this box's placement choice |
| + // (never this box: it is draining). |
| + putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", "", 0, true)) |
| + clk.advance(4 * time.Second) |
| + if d := s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()); d.Holder != "b" || lockGets()-before != 1 { |
| + t.Fatalf("within 5 s: %+v, reads %d", d, lockGets()-before) |
| + } |
| + clk.advance(time.Second) |
| + if d := s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()); d.Phase != edge.MoveTaken || d.Holder != "b" || d.Gen != 6 { |
| + t.Fatalf("on b's marker: %+v, want the placement choice b", d) |
| + } |
| + // A third box acquired from the marker: named after the next 5 s. |
| + putLockFor(t, s.b, s.rt, leaseBody(t, "box/v1;ref=c;iid=i-c;pid=8;ha=1", time.Now().Add(time.Hour))) |
| + clk.advance(5 * time.Second) |
| + if d := s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()); d.Phase != edge.MoveTaken || d.Holder != "c" { |
| + t.Fatalf("after a third box acquired: %+v, want c", d) |
| + } |
| + // This box's own lease, or a read that fails: the bounded refusal, |
| + // also coalesced. |
| + putLockFor(t, s.b, s.rt, leaseBody(t, "box/v1;ref=a;iid=i-a;pid=99;ha=1", time.Now().Add(time.Hour))) |
| + clk.advance(5 * time.Second) |
| + if d := s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()); d.Phase != edge.MoveRefused { |
| + t.Fatalf("a lock naming this box: %+v, want refused", d) |
| + } |
| + reads := lockGets() - before |
| + if reads != 4 { |
| + t.Fatalf("lock reads = %d, want 4 (one per 5 s window)", reads) |
| + } |
| + for _, r := range s.fx.Requests()[beforeAll:] { |
| + if strings.Contains(r, "lock.json") && !strings.HasPrefix(r, "GET ") { |
| + t.Fatalf("the check wrote the lock: %s", r) |
| + } |
| + } |
| + // Not taken: no read at all. |
| + s.a.EndDrainMoves() |
| + if d := s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()); d.Phase != edge.MoveRefused || lockGets()-before != reads { |
| + t.Fatalf("after the drain: %+v", d) |
| + } |
| +} |
| + |
| +func waitUntil(t *testing.T, what string, cond func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(10 * time.Second) |
| + for !cond() { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("timed out waiting for %s", what) |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 706a9700b..0d4dee711 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -2061,6 +2061,15 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| if !hopped { |
| r.Header.Del(assetFillHeader) |
| } |
| + // The replay mark (handover.go, region HA §25.5) is the platform's: read |
| + // once, here, from a verified hop only, and removed from every request, |
| + // so no client can set it and no app ever sees it. |
| + if r.Header.Get(ReplayableHeader) != "" { |
| + if hopped && r.Header.Get(ReplayableHeader) == "1" { |
| + r = r.WithContext(context.WithValue(r.Context(), replayableKey{}, true)) |
| + } |
| + r.Header.Del(ReplayableHeader) |
| + } |
| // The tunnel's upgrade marker (tunnelclient.UpgradeHeader, #471 §4.4) |
| // is this hub's to send, and only on a stream its upgrade branch |
| // admitted: never a client's, on any arm. |
| @@ -2207,9 +2216,23 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // which a forward never needs, and before the login POST reads the body |
| // (the hop proxies it). A verified hop, a door call and a tunnel |
| // delivery are never forwarded; nor is a regional name. |
| + // The handover decision (handover.go, region HA H1 as ruled): for an HA |
| + // route this box serves, right before the front forward and every |
| + // per-request step below. A host that is not moving here goes on as |
| + // today, carrying its admission ticket while it is in this handler. |
| + if up.route.HA && up.hibernating { |
| + var answered bool |
| + if r, answered = e.moveGate(w, r, host, up.route, true, up.regional == regionalNone && !isDoor && !fromTunnel(r.Context())); answered { |
| + return |
| + } |
| + defer ReleaseMoveTicket(r) |
| + } |
| if e.frontForwardHA(w, r, host, up, hopped, isDoor) { |
| return |
| } |
| + if movePauseHook != nil && up.route.HA { |
| + movePauseHook("local", up.route.Host) |
| + } |
| // Edge-held streams: classification (spec 2026-10-28 §3.1, §3.8 step |
| // 2), on the upstream this box will serve, before the login POST |
| @@ -2553,6 +2576,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| defer release() |
| w = &slotWriter{ResponseWriter: w, release: release} |
| } |
| + // An open held stream is not in-flight work for the instance: its |
| + // legs are admitted on their own (AdmitHeldLeg), so its admission |
| + // ticket ends here. |
| + ReleaseMoveTicket(r) |
| e.serveHeld(w, r, up.route, up.proxy) |
| return |
| } |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| index d959b91c4..f0171cbb2 100644 |
| --- a/internal/edge/forwardha.go |
| +++ b/internal/edge/forwardha.go |
| @@ -125,14 +125,20 @@ const holderHeader = "X-Carlos-Holder" |
| // which is when httputil.ReverseProxy has filled resp.Trailer and before it |
| // copies it out (stripAssetTrailers' arrangement). A 101 keeps its body: it |
| // is the raw connection, and carries no trailers. |
| +// |
| +// X-Carlos-Handover (HandoverHeader) is the platform's too, and is removed |
| +// beside it in the same places. |
| func stripAppHolder(resp *http.Response) { |
| resp.Header.Del(holderHeader) |
| + resp.Header.Del(HandoverHeader) |
| resp.Trailer.Del(holderHeader) |
| + resp.Trailer.Del(HandoverHeader) |
| if resp.StatusCode == http.StatusSwitchingProtocols || resp.Body == nil { |
| return |
| } |
| resp.Body = &trailerCookieBody{ReadCloser: resp.Body, close: func() { |
| resp.Trailer.Del(holderHeader) |
| + resp.Trailer.Del(HandoverHeader) |
| }} |
| } |
| @@ -225,6 +231,8 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin |
| if d.Ref == "" { |
| return false |
| } |
| + // Forwarded: the holder counts it, not this box (handover.go). |
| + ReleaseMoveTicket(r) |
| res := e.forwardHAAndNote(w, r, host, up.route, fw, d) |
| if res.Outcome == ForwardNotInView && !e.localPoolEligible(up.route) { |
| HAUnavailableResponse(w, r) |
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go| index 931d438ad..1f97b70e8 100644 |
| --- a/internal/edge/forwardha_test.go |
| +++ b/internal/edge/forwardha_test.go |
| @@ -158,6 +158,11 @@ func fwApp(t *testing.T, box string) *fwAppServer { |
| echo.ServeHTTP(w, r) |
| case r.URL.Path == "/missing": |
| http.NotFound(w, r) |
| + case r.URL.Path == "/echo-replayable": |
| + // What the app was handed of the replay mark, and an app's |
| + // attempt at the platform's handover answer (handover.go). |
| + w.Header().Set(HandoverHeader, "holder=app; gen=1") |
| + fmt.Fprintf(w, "%s|replayable=%q", box, r.Header.Get(ReplayableHeader)) |
| case r.URL.Path == "/holder": |
| if ref := r.URL.Query().Get("ref"); ref != "" { |
| w.Header().Set(holderHeader, ref) |
| @@ -226,6 +231,8 @@ type fwOpts struct { |
| aTarget string |
| // bettyLacks leaves betty without the HA hosts: in view, not serving. |
| bettyLacks bool |
| + // certs are more names both boxes hold certificates for. |
| + certs []string |
| } |
| func newFwScene(t *testing.T, o fwOpts) *fwScene { |
| @@ -273,7 +280,7 @@ func newFwScene(t *testing.T, o fwOpts) *fwScene { |
| homeRoutes: routes(x.aApp.srv.Listener.Addr().String()), |
| homeAct: aAct, |
| farAct: x.bAct, |
| - certs: fwHosts, |
| + certs: append(append([]string(nil), fwHosts...), o.certs...), |
| } |
| if !o.bettyLacks { |
| extra.farRoutes = routes(x.bApp.srv.Listener.Addr().String()) |
diff --git a/internal/edge/haingress.go b/internal/edge/haingress.go| index eb00a0abb..b80bceaa0 100644 |
| --- a/internal/edge/haingress.go |
| +++ b/internal/edge/haingress.go |
| @@ -123,6 +123,13 @@ func (e *Edge) routeHAIngress(w http.ResponseWriter, r *http.Request, host strin |
| if local && e.localPoolEligible(rt) && e.localPoolEligible(up.route) && up.route.Host == rt.Host && up.route.Account == rt.Account && up.route.App == rt.App && up.route.Pool == rt.Pool && up.route.Incarnation == rt.Incarnation && up.route.ServingSeq == rt.ServingSeq && up.route.HA { |
| return false |
| } |
| + // The handover decision (handover.go), on the primary route chosen |
| + // above. This path never serves here, so a ticket ends at once. |
| + _, door := doorCallerFrom(r.Context()) |
| + r, answered := e.moveGate(w, r, host, rt, false, !door && !fromTunnel(r.Context())) |
| + if answered { |
| + return true |
| + } |
| return e.frontForwardHAIngress(w, r, host, rt) |
| } |
diff --git a/internal/edge/handover.go b/internal/edge/handover.go| new file mode 100644 |
| index 000000000..a69f5599d |
| --- /dev/null |
| +++ b/internal/edge/handover.go |
| @@ -0,0 +1,275 @@ |
| +package edge |
| + |
| +// Held requests during a planned handover, the edge's half (region HA spec |
| +// §25.3 H1, §25.5, §25.15). While this box, draining, moves a host it holds |
| +// to a successor, every request for that host is classified by one |
| +// activator decision, MoveState, made in moveGate. moveGate is called from |
| +// exactly two places, and an HA request reaches exactly one of them |
| +// (ruling 2026-11-08, option A): |
| +// |
| +// - routeHAIngress, just before frontForwardHAIngress, on the primary |
| +// route that metadata and alias authority chose; |
| +// - ServeHTTP, just before frontForwardHA, on the accepted route, after |
| +// the regional gate, HA ingress and alias authority. |
| +// |
| +// Both are before admission's later checks, the door scope, the import and |
| +// plan gates, recording, the guards, the password gate, rate limits, |
| +// compression, the cache, the held-stream branch and the activator. A login |
| +// POST is classified by its front route, as frontForwardHA forwards it; the |
| +// gate answers every login POST itself, so none reaches an app or begin. |
| +// |
| +// Every handover exit is written by handoverExit, one bounded, full-duplex, |
| +// connection-closing response path (R3.3). |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// HandoverHeader is A's answer to a replayable first-attempt hop for a host |
| +// it has moved: "not delivered, send it there". Value: FormatHandover. Only |
| +// the platform sets it, only on an answer to a verified hop; an app's is |
| +// removed at the tenant response boundary (stripAppHolder). Task 3's first |
| +// box honours it only on its first attempt (H3). |
| +const HandoverHeader = "X-Carlos-Handover" |
| + |
| +// ReplayableHeader marks a hop whose sender holds a whole copy of the body |
| +// and may send it once more (H2). The first box sets it, and only on its |
| +// first attempt: A reads its presence as "replayable first attempt". It is |
| +// removed from every inbound request at the front door (ServeHTTP) once |
| +// read, so no client can set it and no app ever sees it. |
| +const ReplayableHeader = "X-Carlos-Replayable" |
| + |
| +// FormatHandover is HandoverHeader's value: "holder=<ref>; gen=<n>", where |
| +// gen is the lock generation the holder was confirmed at. |
| +func FormatHandover(holder string, gen int64) string { |
| + return fmt.Sprintf("holder=%s; gen=%d", holder, gen) |
| +} |
| + |
| +// ParseHandover reads FormatHandover's value. ok is false for anything |
| +// else, an empty holder included. |
| +func ParseHandover(v string) (holder string, gen int64, ok bool) { |
| + parts := strings.Split(v, ";") |
| + if len(parts) != 2 { |
| + return "", 0, false |
| + } |
| + h, okH := strings.CutPrefix(strings.TrimSpace(parts[0]), "holder=") |
| + g, okG := strings.CutPrefix(strings.TrimSpace(parts[1]), "gen=") |
| + if !okH || !okG || h == "" || strings.ContainsAny(h, " \t,=") { |
| + return "", 0, false |
| + } |
| + n, err := strconv.ParseInt(g, 10, 64) |
| + if err != nil || n < 0 { |
| + return "", 0, false |
| + } |
| + return h, n, true |
| +} |
| + |
| +// MovePhase is MoveState's answer for one request. |
| +type MovePhase uint8 |
| + |
| +const ( |
| + // MoveNone: the host is not moving here. The request goes on as today. |
| + MoveNone MovePhase = iota |
| + // MoveLost: the host's lease is lost (the loss latch, F-A). |
| + MoveLost |
| + // MoveHolding: the request is held; call Wait. |
| + MoveHolding |
| + // MoveTaken: the host has moved to Holder, confirmed at lock Gen. |
| + MoveTaken |
| + // MoveRefused: today's answer at once: a hop that is not replayable, a |
| + // request that cannot be forwarded, a bound hit or a failed move. |
| + MoveRefused |
| +) |
| + |
| +// MoveAsk is what MoveState needs to know about the request. |
| +type MoveAsk struct { |
| + // Hop: the request arrived as a verified hop. |
| + Hop bool |
| + // Replayable: a hop marked ReplayableHeader (its sender's first |
| + // attempt, with a whole copy of the body). |
| + Replayable bool |
| + // Forwardable: a client request this box may front-forward (not a door |
| + // call, a tunnel delivery or a regional name). |
| + Forwardable bool |
| +} |
| + |
| +// MoveDecision is MoveState's answer. |
| +type MoveDecision struct { |
| + Phase MovePhase |
| + Holder string |
| + Gen int64 |
| + // ForwardGen is the holder cache's token for a forward to Holder |
| + // (ForwardDecision.Gen). |
| + ForwardGen uint64 |
| + // Done ends an admission ticket (MoveNone, for a host this box holds): |
| + // the request finished, was forwarded or was counted by begin. nil when |
| + // there is none. Safe to call more than once. |
| + Done func() |
| + // Wait (MoveHolding only) waits until the host leaves holding or |
| + // releasing, the hold's bound passes, or ctx ends, and answers again; |
| + // never MoveHolding. It gives the hold's slot back. |
| + Wait func(ctx context.Context) MoveDecision |
| +} |
| + |
| +// HAMover is the activator's half of held requests. The edge finds it on its |
| +// Activator with a type assertion; without it nothing is ever held. |
| +type HAMover interface { |
| + // MoveState is memory-only: the loss latch first, then holding, |
| + // releasing, taken, or none. |
| + MoveState(rt registry.Route, ask MoveAsk) MoveDecision |
| + // ConfirmMoveHolder checks a taken host's lock, coalesced to at most |
| + // one read per host per 5 s, before a hop is answered from it. It |
| + // answers MoveTaken naming the current owner, or this box's placement |
| + // choice when the lock is a release marker, and MoveRefused otherwise. |
| + ConfirmMoveHolder(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot) MoveDecision |
| +} |
| + |
| +// moveDecisionHook is called once per moveGate decision, with the host. |
| +// Tests count with it; nil in production. |
| +var moveDecisionHook func(host string) |
| + |
| +// movePauseHook is a test seam at the pause points: "none" right after |
| +// MoveState returns none, "local" right after frontForwardHA chose to |
| +// serve here. nil in production. |
| +var movePauseHook func(point, host string) |
| + |
| +type moveTicketKey struct{} |
| + |
| +type moveTicket struct { |
| + once sync.Once |
| + done func() |
| +} |
| + |
| +func (t *moveTicket) end() { t.once.Do(t.done) } |
| + |
| +// WithMoveTicket is r carrying the admission ticket done |
| +// (MoveDecision.Done), as moveGate carries it: ReleaseMoveTicket ends it, |
| +// once. |
| +func WithMoveTicket(r *http.Request, done func()) *http.Request { |
| + return r.WithContext(context.WithValue(r.Context(), moveTicketKey{}, &moveTicket{done: done})) |
| +} |
| + |
| +// ReleaseMoveTicket ends r's admission ticket, if it has one: the |
| +// activator calls it once begin has counted the request in flight. |
| +func ReleaseMoveTicket(r *http.Request) { |
| + if r == nil { |
| + return |
| + } |
| + if t, ok := r.Context().Value(moveTicketKey{}).(*moveTicket); ok { |
| + t.end() |
| + } |
| +} |
| + |
| +type replayableKey struct{} |
| + |
| +// arrivedReplayable is whether r arrived as a verified hop marked |
| +// ReplayableHeader (read at the front door, before the header is removed). |
| +func arrivedReplayable(r *http.Request) bool { |
| + v, _ := r.Context().Value(replayableKey{}).(bool) |
| + return v |
| +} |
| + |
| +// moveSnapshot is the wake snapshot for rt, as frontForwardHA builds it. |
| +func (e *Edge) moveSnapshot(rt registry.Route) func() boxchoice.WakeSnapshot { |
| + return func() boxchoice.WakeSnapshot { |
| + m := e.homes.Load() |
| + if m == nil { |
| + return boxchoice.WakeSnapshot{} |
| + } |
| + return m.wakeSnapshot(rt, time.Now()) |
| + } |
| +} |
| + |
| +// moveGate is the front-door handover decision for rt, the request's |
| +// primary route. It reports whether it answered; otherwise it returns the |
| +// request to go on with (carrying its admission ticket, if any). local |
| +// says whether this call site may serve the request here; when it may not, |
| +// a ticket is ended at once. forwardable says whether a client request may |
| +// be front-forwarded. |
| +func (e *Edge) moveGate(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, local, forwardable bool) (*http.Request, bool) { |
| + mv, ok := e.act.(HAMover) |
| + if !ok || !rt.HA { |
| + return r, false |
| + } |
| + if moveDecisionHook != nil { |
| + moveDecisionHook(rt.Host) |
| + } |
| + hop := hopVerified(r.Context()) |
| + d := mv.MoveState(rt, MoveAsk{Hop: hop, Replayable: hop && arrivedReplayable(r), Forwardable: forwardable && !hop}) |
| + if d.Phase == MoveHolding { |
| + d = d.Wait(r.Context()) |
| + } |
| + switch d.Phase { |
| + case MoveNone: |
| + if d.Done != nil { |
| + if !local { |
| + d.Done() |
| + } else { |
| + r = WithMoveTicket(r, d.Done) |
| + } |
| + } |
| + if movePauseHook != nil { |
| + movePauseHook("none", rt.Host) |
| + } |
| + return r, false |
| + case MoveLost: |
| + handoverExit(w, r, HAUnavailableResponse) |
| + case MoveTaken: |
| + if hop { |
| + c := mv.ConfirmMoveHolder(r.Context(), rt, e.moveSnapshot(rt)) |
| + if c.Phase != MoveTaken || c.Holder == "" { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return r, true |
| + } |
| + handoverExit(w, r, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set(HandoverHeader, FormatHandover(c.Holder, c.Gen)) |
| + w.Header().Set(holderHeader, c.Holder) |
| + answerHolderUnreachable(w, r) |
| + }) |
| + return r, true |
| + } |
| + // A client's request: the ordinary front forward to the confirmed |
| + // holder. Its first attempt; the holder runs the gate, accounting |
| + // and recording once, and the unread body streams as today. |
| + fw, ok := e.act.(HAForwarder) |
| + if !ok || d.Holder == "" { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return r, true |
| + } |
| + res := e.forwardHAAndNote(w, r, host, rt, fw, ForwardDecision{Ref: d.Holder, Kind: Holder, Gen: d.ForwardGen}) |
| + if res.Outcome == ForwardNotInView { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + } |
| + default: |
| + // MoveRefused, and anything unexpected: today's answer. |
| + handoverExit(w, r, answerHolderUnreachable) |
| + } |
| + return r, true |
| +} |
| + |
| +// handoverExit is the one response path of every handover exit (R3.3): a |
| +// handover answer, a refusal, a cap, a timeout, a lost lease and a failed |
| +// move. It enables full duplex before writing, so net/http never drains an |
| +// unread body before the answer; asks for the connection to close after |
| +// it (HTTP/1); flushes; and then puts the read deadline in the past, so |
| +// net/http's drain of the unread body after the handler fails at once |
| +// instead of waiting on a slow client. No exit waits for a body. |
| +func handoverExit(w http.ResponseWriter, r *http.Request, answer func(http.ResponseWriter, *http.Request)) { |
| + rc := http.NewResponseController(w) |
| + _ = rc.EnableFullDuplex() |
| + if r.ProtoMajor == 1 { |
| + w.Header().Set("Connection", "close") |
| + } |
| + answer(w, r) |
| + _ = rc.Flush() |
| + _ = rc.SetReadDeadline(time.Now()) |
| +} |
diff --git a/internal/edge/handover_test.go b/internal/edge/handover_test.go| new file mode 100644 |
| index 000000000..d08669c6a |
| --- /dev/null |
| +++ b/internal/edge/handover_test.go |
| @@ -0,0 +1,614 @@ |
| +package edge |
| + |
| +// Held requests during a planned handover, the edge's half (handover.go). |
| +// The scene is the forward scene (forwardha_test.go): two real Edges, real |
| +// TLS and real hop auth. Annie is the draining box. Her activator is |
| +// fwMover, which answers MoveState as the test sets it; the activator's |
| +// own decision is tested in internal/activator/handover_test.go. |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/gate" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const ( |
| + hoAlias = "www.alias.forward.test" |
| + hoMetaHost = "meta.forward.test" |
| +) |
| + |
| +// fwMover is fwAct with MoveState. |
| +type fwMover struct { |
| + *fwAct |
| + mu sync.Mutex |
| + phase MovePhase |
| + holder string |
| + gen int64 |
| + release chan struct{} // holding: Wait returns after once this closes |
| + after MoveDecision |
| + asks []MoveAsk |
| + hosts []string |
| + confirm MoveDecision |
| + // tickets: issued and ended. |
| + issued, ended, confirms, waits atomic.Int64 |
| +} |
| + |
| +var _ HAMover = (*fwMover)(nil) |
| + |
| +func newFwMover() *fwMover { |
| + return &fwMover{fwAct: &fwAct{target: "betty"}, release: make(chan struct{})} |
| +} |
| + |
| +func (m *fwMover) set(phase MovePhase) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.phase = phase |
| +} |
| + |
| +func (m *fwMover) MoveState(rt registry.Route, ask MoveAsk) MoveDecision { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.asks = append(m.asks, ask) |
| + m.hosts = append(m.hosts, rt.Host) |
| + switch m.phase { |
| + case MoveNone: |
| + m.issued.Add(1) |
| + var once sync.Once |
| + return MoveDecision{Done: func() { once.Do(func() { m.ended.Add(1) }) }} |
| + case MoveHolding: |
| + if ask.Hop && !ask.Replayable { |
| + return MoveDecision{Phase: MoveRefused} |
| + } |
| + release := m.release |
| + return MoveDecision{Phase: MoveHolding, Wait: func(ctx context.Context) MoveDecision { |
| + m.waits.Add(1) |
| + select { |
| + case <-release: |
| + case <-ctx.Done(): |
| + return MoveDecision{Phase: MoveRefused} |
| + } |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.after |
| + }} |
| + case MoveTaken: |
| + if ask.Hop && !ask.Replayable || !ask.Hop && !ask.Forwardable { |
| + return MoveDecision{Phase: MoveRefused} |
| + } |
| + return MoveDecision{Phase: MoveTaken, Holder: m.holder, Gen: m.gen} |
| + } |
| + return MoveDecision{Phase: m.phase} |
| +} |
| + |
| +func (m *fwMover) ConfirmMoveHolder(context.Context, registry.Route, func() boxchoice.WakeSnapshot) MoveDecision { |
| + m.confirms.Add(1) |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.confirm |
| +} |
| + |
| +func (m *fwMover) seen() ([]string, []MoveAsk) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + h, a := m.hosts, m.asks |
| + m.hosts, m.asks = nil, nil |
| + return h, a |
| +} |
| + |
| +type hoScene struct { |
| + *fwScene |
| + mv *fwMover |
| + // decisions counts moveGate's decisions per host. |
| + decisions sync.Map |
| + plain *httptest.Server // annie's edge over plain HTTP, for hops |
| +} |
| + |
| +func newHoScene(t *testing.T) *hoScene { |
| + t.Helper() |
| + mv := newFwMover() |
| + x := &hoScene{mv: mv} |
| + x.fwScene = newFwScene(t, fwOpts{aAct: mv, certs: []string{hoAlias}}) |
| + x.aAct = mv.fwAct |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + if err := be.reg.UpsertAlias(registry.RouteAlias{Alias: hoAlias, Host: fwHost, Account: "abc", App: "shop", CreatedAt: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := be.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + old := moveDecisionHook |
| + moveDecisionHook = func(host string) { |
| + n, _ := x.decisions.LoadOrStore(host, new(atomic.Int64)) |
| + n.(*atomic.Int64).Add(1) |
| + } |
| + t.Cleanup(func() { moveDecisionHook = old }) |
| + x.plain = httptest.NewServer(x.a.edge) |
| + t.Cleanup(x.plain.Close) |
| + return x |
| +} |
| + |
| +func (x *hoScene) decided(host string) int64 { |
| + n, ok := x.decisions.Load(host) |
| + if !ok { |
| + return 0 |
| + } |
| + return n.(*atomic.Int64).Swap(0) |
| +} |
| + |
| +// hop sends a signed hop to annie over plain HTTP. |
| +func (x *hoScene) hop(t *testing.T, method, host, path string, replayable bool, body io.Reader) *http.Response { |
| + t.Helper() |
| + req, err := http.NewRequest(method, x.plain.URL+path, body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = host |
| + key := signingKey(x.a.edge.homes.Load().meshKeys()) |
| + req.Header.Set(hopHeader, "1") |
| + req.Header.Set(hopAuthHeader, signHop(key, host, time.Now())) |
| + if replayable { |
| + req.Header.Set(ReplayableHeader, "1") |
| + } |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { resp.Body.Close() }) |
| + return resp |
| +} |
| + |
| +// direct is a request straight into annie's ServeHTTP. |
| +func (x *hoScene) direct(method, host, path string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, "https://"+host+path, nil) |
| + w := httptest.NewRecorder() |
| + x.a.edge.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +func (x *hoScene) metaIngress(t *testing.T) { |
| + t.Helper() |
| + rt := registry.Route{Host: hoMetaHost, HA: true, Hibernate: true, Kind: "instance", Account: "abc", App: "shop"} |
| + x.a.edge.SetHAIngressLookup(func(host string) (registry.Route, bool) { return rt, host == hoMetaHost }) |
| +} |
| + |
| +func loginPost(t *testing.T, x *fwScene, host string) *http.Response { |
| + t.Helper() |
| + form := url.Values{"password": {fwPassword}, "next": {"/in"}} |
| + req, err := http.NewRequest(http.MethodPost, "https://"+host+gate.LoginPath, strings.NewReader(form.Encode())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + c := *x.a.client |
| + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + return resp |
| +} |
| + |
| +// Every HA request kind passes through the decision exactly once during a |
| +// move, never twice (ruling 2026-11-08, option A), and a client's request |
| +// released from taken is the holder's alone: annie runs no local step. |
| +func TestMoveGateEveryRouteKindOnce(t *testing.T) { |
| + x := newHoScene(t) |
| + x.metaIngress(t) |
| + x.mv.mu.Lock() |
| + x.mv.phase, x.mv.holder, x.mv.gen = MoveTaken, "betty", 9 |
| + x.mv.confirm = MoveDecision{Phase: MoveTaken, Holder: "betty", Gen: 9} |
| + x.mv.mu.Unlock() |
| + cookie := gate.CookieName + "=" + gate.Mint(fwGatedHost, x.hash, time.Now().Add(time.Hour)) |
| + aApp := x.aApp.n.Load() |
| + |
| + type kind struct { |
| + name, host string |
| + run func(t *testing.T) |
| + } |
| + kinds := []kind{ |
| + {"direct", fwHost, func(t *testing.T) { |
| + resp, body := x.fetch(t, fwHost, "/k") |
| + if resp.StatusCode != 200 || body != "betty|"+fwHost+"|/k" { |
| + t.Fatalf("%d %q, want betty's answer", resp.StatusCode, body) |
| + } |
| + }}, |
| + {"gated, with the gate cookie", fwGatedHost, func(t *testing.T) { |
| + resp, body := x.fetch(t, fwGatedHost, "/in", "Cookie", cookie) |
| + if resp.StatusCode != 200 || body != "betty|"+fwGatedHost+"|/in" { |
| + t.Fatalf("%d %q: the cookie did not reach the holder's gate", resp.StatusCode, body) |
| + } |
| + }}, |
| + {"login POST, by its front route", fwGatedHost, func(t *testing.T) { |
| + resp := loginPost(t, x.fwScene, fwGatedHost) |
| + if resp.StatusCode != http.StatusSeeOther || len(resp.Cookies()) == 0 { |
| + t.Fatalf("login: %d %v, want the holder's redirect and cookie", resp.StatusCode, resp.Header) |
| + } |
| + }}, |
| + {"alias, on the primary", fwHost, func(t *testing.T) { |
| + resp, body := x.fetch(t, hoAlias, "/a") |
| + if resp.StatusCode != 200 || !strings.HasPrefix(body, "betty|") { |
| + t.Fatalf("%d %q, want betty's answer", resp.StatusCode, body) |
| + } |
| + }}, |
| + {"marked held stream", fwHost, func(t *testing.T) { |
| + // The holder holds the stream open: headers are enough. |
| + calls := x.b.calls.Load() |
| + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) |
| + defer cancel() |
| + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+fwHost+"/events?carlos_hold=1", nil) |
| + req.Header.Set("Accept", "text/event-stream") |
| + resp, err := x.a.client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cancel() |
| + resp.Body.Close() |
| + if x.b.calls.Load() != calls+1 { |
| + t.Fatalf("the marked stream did not go to the holder: %d", resp.StatusCode) |
| + } |
| + }}, |
| + {"metadata-only HA ingress", hoMetaHost, func(t *testing.T) { |
| + w := x.direct(http.MethodGet, hoMetaHost, "/m") |
| + if w.Code == 0 { |
| + t.Fatal("no answer") |
| + } |
| + }}, |
| + {"replayable hop", fwHost, func(t *testing.T) { |
| + resp := x.hop(t, http.MethodPost, fwHost, "/h", true, strings.NewReader("body")) |
| + if resp.StatusCode != 503 || resp.Header.Get(HandoverHeader) != "holder=betty; gen=9" || !resp.Close { |
| + t.Fatalf("%d %v, want the handover answer, connection closed", resp.StatusCode, resp.Header) |
| + } |
| + }}, |
| + {"hop, not replayable", fwHost, func(t *testing.T) { |
| + resp := x.hop(t, http.MethodGet, fwHost, "/h", false, nil) |
| + if resp.StatusCode != 503 || resp.Header.Get(HandoverHeader) != "" || resp.Header.Get("Retry-After") != "10" { |
| + t.Fatalf("%d %v, want today's answer", resp.StatusCode, resp.Header) |
| + } |
| + }}, |
| + } |
| + for _, k := range kinds { |
| + t.Run(k.name, func(t *testing.T) { |
| + x.decisions.Range(func(_, v any) bool { v.(*atomic.Int64).Store(0); return true }) |
| + k.run(t) |
| + laWaitFor(t, "both edges' handlers to return", func() bool { |
| + return x.a.served.Load() == x.a.calls.Load() && x.b.served.Load() == x.b.calls.Load() |
| + }) |
| + total := int64(0) |
| + x.decisions.Range(func(_, v any) bool { total += v.(*atomic.Int64).Load(); return true }) |
| + if got := x.decided(k.host); got != 1 || total != 1 { |
| + t.Fatalf("decisions for %s = %d (all hosts %d), want exactly 1", k.host, got, total) |
| + } |
| + }) |
| + } |
| + if n := x.aApp.n.Load() - aApp; n != 0 { |
| + t.Fatalf("annie's app saw %d requests during the move, want none", n) |
| + } |
| +} |
| + |
| +// Held, then released to the confirmed holder: once-only accounting (the |
| +// holder meters, observes and records each request once; annie nothing). |
| +func TestMoveHoldReleasesThroughTheFrontForward(t *testing.T) { |
| + x := newHoScene(t) |
| + x.mv.set(MoveHolding) |
| + x.mv.after = MoveDecision{Phase: MoveTaken, Holder: "betty", Gen: 9} |
| + cookie := gate.CookieName + "=" + gate.Mint(fwGatedHost, x.hash, time.Now().Add(time.Hour)) |
| + plain := x.fetchAsync(fwHost, "/p") |
| + gated := make(chan e2eResult, 1) |
| + go func() { |
| + resp, err := x.try(x.a, "https://"+fwGatedHost+"/g", e2eHeaders([]string{"Cookie", cookie}), true) |
| + if err != nil { |
| + gated <- e2eResult{err: err} |
| + return |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + gated <- e2eResult{resp: resp, body: string(b), err: err} |
| + }() |
| + laWaitFor(t, "both requests held", func() bool { return x.mv.waits.Load() == 2 }) |
| + time.Sleep(50 * time.Millisecond) |
| + if x.aApp.n.Load() != 0 || x.b.calls.Load() != 0 { |
| + t.Fatalf("a held request went on: annie app %d, betty %d", x.aApp.n.Load(), x.b.calls.Load()) |
| + } |
| + close(x.mv.release) |
| + p, g := e2eAwait(t, plain), e2eAwait(t, gated) |
| + if p.resp.StatusCode != 200 || p.body != "betty|"+fwHost+"|/p" { |
| + t.Fatalf("released: %d %q", p.resp.StatusCode, p.body) |
| + } |
| + if g.resp.StatusCode != 200 || g.body != "betty|"+fwGatedHost+"|/g" { |
| + t.Fatalf("released gated: %d %q", g.resp.StatusCode, g.body) |
| + } |
| + // One drain of each meter: usage per host; observations and records |
| + // per box, two in all. |
| + laWaitFor(t, "both edges' handlers to return", func() bool { |
| + return x.a.served.Load() == x.a.calls.Load() && x.b.served.Load() == x.b.calls.Load() |
| + }) |
| + if rows := x.aMeter.Drain().Rows; len(rows) != 0 || len(x.aObs.snap()) != 0 { |
| + t.Fatalf("annie metered %+v or observed: want nothing", rows) |
| + } |
| + x.aRec.mu.Lock() |
| + aRecs := len(x.aRec.resp) + len(x.aRec.match) |
| + x.aRec.mu.Unlock() |
| + rows := x.bMeter.Drain().Rows |
| + for host, body := range map[string]string{fwHost: p.body, fwGatedHost: g.body} { |
| + if u := rows[host]; u.Requests != 1 || u.HopRequests != 1 || u.BytesOut != int64(len(body)) { |
| + t.Fatalf("the holder metered %s %+v, want one hop request", host, u) |
| + } |
| + } |
| + x.bRec.mu.Lock() |
| + bResp := len(x.bRec.resp) |
| + x.bRec.mu.Unlock() |
| + if aRecs != 0 || len(x.bObs.snap()) != 2 || bResp != 2 { |
| + t.Fatalf("records: annie %d, betty observed %d recorded %d; want 0, 2, 2", aRecs, len(x.bObs.snap()), bResp) |
| + } |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d", n) |
| + } |
| +} |
| + |
| +// Every refusal is the approved answer, written through the bounded exit, |
| +// and annie records nothing for it. |
| +func TestMoveGateAnswers(t *testing.T) { |
| + x := newHoScene(t) |
| + for _, c := range []struct { |
| + phase MovePhase |
| + holder string |
| + }{{MoveLost, "none"}, {MoveRefused, ""}} { |
| + x.mv.set(c.phase) |
| + resp, body := x.fetch(t, fwHost, "/x") |
| + if resp.StatusCode != 503 || resp.Header.Get("Retry-After") != "10" || resp.Header.Get(holderHeader) != c.holder || !resp.Close { |
| + t.Fatalf("phase %d: %d %v %q", c.phase, resp.StatusCode, resp.Header, body) |
| + } |
| + want := HAUnavailableMessage + "\n" |
| + if c.phase == MoveRefused { |
| + want = "instance is waking elsewhere; retry shortly\n" |
| + } |
| + if body != want { |
| + t.Fatalf("phase %d body %q, want %q", c.phase, body, want) |
| + } |
| + annie, _ := x.take(t, fwHost) |
| + wantNothing(t, "a handover refusal", annie) |
| + } |
| + // A held request whose move fails gets today's answer at release. |
| + x.mv.set(MoveHolding) |
| + x.mv.after = MoveDecision{Phase: MoveRefused} |
| + ch := x.fetchAsync(fwHost, "/y") |
| + laWaitFor(t, "held", func() bool { return x.mv.waits.Load() == 1 }) |
| + close(x.mv.release) |
| + if r := e2eAwait(t, ch); r.resp.StatusCode != 503 || r.resp.Header.Get("Retry-After") != "10" { |
| + t.Fatalf("failed move: %d %v", r.resp.StatusCode, r.resp.Header) |
| + } |
| + // Marked requests are held too, and start no held task. |
| + x.mv.release = make(chan struct{}) |
| + x.mv.after = MoveDecision{Phase: MoveLost} |
| + ch = x.fetchAsync(fwHost, "/s?carlos_hold=1") |
| + laWaitFor(t, "the marked request held", func() bool { return x.mv.waits.Load() == 2 }) |
| + close(x.mv.release) |
| + if r := e2eAwait(t, ch); r.resp.StatusCode != 503 || r.resp.Header.Get(holderHeader) != "none" { |
| + t.Fatalf("marked, lost: %d %v", r.resp.StatusCode, r.resp.Header) |
| + } |
| +} |
| + |
| +// R3.2: the ticket outlives both pause points and ends once, before a |
| +// forward or at the end of the request. |
| +func TestMoveTicketPausePoints(t *testing.T) { |
| + x := newHoScene(t) |
| + x.mv.target = "" |
| + var atNone, atLocal atomic.Int64 |
| + atNone.Store(-1) |
| + atLocal.Store(-1) |
| + old := movePauseHook |
| + movePauseHook = func(point, host string) { |
| + switch point { |
| + case "none": |
| + atNone.Store(x.mv.ended.Load()) |
| + case "local": |
| + atLocal.Store(x.mv.ended.Load()) |
| + } |
| + } |
| + t.Cleanup(func() { movePauseHook = old }) |
| + resp, body := x.fetch(t, fwHost, "/local") |
| + if resp.StatusCode != 200 || !strings.HasPrefix(body, "annie|") { |
| + t.Fatalf("%d %q", resp.StatusCode, body) |
| + } |
| + laWaitFor(t, "annie's handler", func() bool { return x.a.served.Load() == x.a.calls.Load() }) |
| + if atNone.Load() != 0 || atLocal.Load() != 0 { |
| + t.Fatalf("the ticket ended before a pause point: none=%d local=%d", atNone.Load(), atLocal.Load()) |
| + } |
| + if x.mv.issued.Load() != 1 || x.mv.ended.Load() != 1 { |
| + t.Fatalf("tickets issued %d ended %d, want 1 and 1", x.mv.issued.Load(), x.mv.ended.Load()) |
| + } |
| + // A forwarded request's ticket ends before the forward is dialled. |
| + x.mv.target = "betty" |
| + x.CloseIdle() |
| + var atDial atomic.Int64 |
| + atDial.Store(-1) |
| + prev := forwardDial |
| + forwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + atDial.CompareAndSwap(-1, x.mv.ended.Load()) |
| + return prev(ctx, network, addr) |
| + } |
| + t.Cleanup(func() { forwardDial = prev }) |
| + if resp, _ := x.fetch(t, fwHost, "/fwd"); resp.StatusCode != 200 { |
| + t.Fatalf("forward: %d", resp.StatusCode) |
| + } |
| + if atDial.Load() != 2 { |
| + t.Fatalf("tickets ended at the dial = %d, want 2 (this one before the forward)", atDial.Load()) |
| + } |
| + laWaitFor(t, "annie's handler", func() bool { return x.a.served.Load() == x.a.calls.Load() }) |
| + if x.mv.issued.Load() != 2 || x.mv.ended.Load() != 2 { |
| + t.Fatalf("issued %d ended %d", x.mv.issued.Load(), x.mv.ended.Load()) |
| + } |
| +} |
| + |
| +// CloseIdle drops annie's idle forward connections, so the next forward |
| +// dials. |
| +func (x *hoScene) CloseIdle() { |
| + x.a.edge.forwardTransports.Range(func(_, v any) bool { |
| + v.(*http.Transport).CloseIdleConnections() |
| + return true |
| + }) |
| +} |
| + |
| +// R3.3: the bounded exit on a real HTTP/1.1 connection whose body never |
| +// finishes. The answer arrives, the connection closes and the handler |
| +// returns, though not a byte more of the body is sent. |
| +func TestHandoverExitOnUnfinishedBodies(t *testing.T) { |
| + for _, c := range []struct { |
| + name, framing, sent string |
| + hop bool |
| + }{ |
| + {"chunked, unfinished", "Transfer-Encoding: chunked", "5\r\nhello\r\n", false}, |
| + {"fixed length, stalled", "Content-Length: 100000", "0123456789", false}, |
| + {"fixed length, small, stalled", "Content-Length: 1000", "0123456789", false}, |
| + {"replayable hop, chunked, unfinished", "Transfer-Encoding: chunked", "5\r\nhello\r\n", true}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + x := newHoScene(t) |
| + x.mv.mu.Lock() |
| + x.mv.phase = MoveRefused |
| + if c.hop { |
| + x.mv.phase, x.mv.holder, x.mv.gen = MoveTaken, "betty", 9 |
| + x.mv.confirm = MoveDecision{Phase: MoveTaken, Holder: "betty", Gen: 9} |
| + } |
| + x.mv.mu.Unlock() |
| + conn, err := tls.Dial("tcp", x.a.tlsAddr, &tls.Config{ServerName: fwHost, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + hdr := "" |
| + if c.hop { |
| + key := signingKey(x.a.edge.homes.Load().meshKeys()) |
| + hdr = fmt.Sprintf("%s: 1\r\n%s: %s\r\n%s: 1\r\n", hopHeader, hopAuthHeader, signHop(key, fwHost, time.Now()), ReplayableHeader) |
| + } |
| + fmt.Fprintf(conn, "POST /upload HTTP/1.1\r\nHost: %s\r\n%s\r\n%s\r\n%s", fwHost, c.framing, hdr, c.sent) |
| + conn.SetReadDeadline(time.Now().Add(3 * time.Second)) |
| + br := bufio.NewReader(conn) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatalf("no answer while the body is unfinished: %v", err) |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatalf("answer body: %v", err) |
| + } |
| + if resp.StatusCode != 503 || !resp.Close || resp.Header.Get("Retry-After") != "10" { |
| + t.Fatalf("%d %v %q", resp.StatusCode, resp.Header, b) |
| + } |
| + if c.hop && resp.Header.Get(HandoverHeader) != "holder=betty; gen=9" { |
| + t.Fatalf("hop: %v", resp.Header) |
| + } |
| + if _, err := br.ReadByte(); err != io.EOF { |
| + t.Fatalf("the connection stayed open after the answer: %v", err) |
| + } |
| + laWaitFor(t, "annie's handler to return", func() bool { return x.a.served.Load() == x.a.calls.Load() }) |
| + if x.aApp.n.Load() != 0 || x.b.calls.Load() != 0 { |
| + t.Fatal("the refused upload went on") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// With no move, every pre-existing 503 path answers byte for byte as it |
| +// does without the handover decision at all. |
| +func TestMoveNoneLeavesEvery503Unchanged(t *testing.T) { |
| + type answer struct { |
| + status int |
| + retry, holder, conn, ctype, body string |
| + appA, appB int64 |
| + } |
| + run := func(t *testing.T, withMover bool, setup func(*fwAct, *fwScene), path string) answer { |
| + var x *fwScene |
| + if withMover { |
| + h := newHoScene(t) |
| + x = h.fwScene |
| + setup(h.mv.fwAct, x) |
| + } else { |
| + x = newFwScene(t, fwOpts{}) |
| + setup(x.aAct, x) |
| + } |
| + resp, body := x.fetch(t, fwHost, path) |
| + return answer{resp.StatusCode, resp.Header.Get("Retry-After"), resp.Header.Get(holderHeader), resp.Header.Get("Connection"), resp.Header.Get("Content-Type"), body, x.aApp.n.Load(), x.bApp.n.Load()} |
| + } |
| + for _, c := range []struct { |
| + name string |
| + path string |
| + setup func(*fwAct, *fwScene) |
| + }{ |
| + {"activator unavailable (F-A)", "/u", func(a *fwAct, _ *fwScene) { a.unavailable = true }}, |
| + {"suspect holder refused", "/r", func(a *fwAct, _ *fwScene) { a.refuse = true }}, |
| + {"the activator's own refusal here", "/platform-held?ref=carol", func(a *fwAct, _ *fwScene) { a.target = "" }}, |
| + {"the app's 503 here", "/holder?ref=carol", func(a *fwAct, _ *fwScene) { a.target = "" }}, |
| + {"the holder's 503, relayed", "/holder", func(*fwAct, *fwScene) {}}, |
| + {"placement not in view", "/p", func(a *fwAct, _ *fwScene) { a.target, a.kind = "nobody", Placement }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + before := run(t, false, c.setup, c.path) |
| + after := run(t, true, c.setup, c.path) |
| + if before != after { |
| + t.Fatalf("changed by the decision:\n before %+v\n after %+v", before, after) |
| + } |
| + if before.status != 503 { |
| + t.Fatalf("the case is not a 503: %+v", before) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The platform's headers: X-Carlos-Replayable never reaches an app, from |
| +// a client or a hop; an app's X-Carlos-Handover never reaches a client. |
| +func TestHandoverHeadersStripped(t *testing.T) { |
| + x := newHoScene(t) |
| + x.mv.target = "" |
| + resp, body := x.fetch(t, fwHost, "/echo-replayable", ReplayableHeader, "1") |
| + if resp.StatusCode != 200 || body != `annie|replayable=""` || resp.Header.Get(HandoverHeader) != "" { |
| + t.Fatalf("a client's mark: %d %q %v", resp.StatusCode, body, resp.Header) |
| + } |
| + r := x.hop(t, http.MethodGet, fwHost, "/echo-replayable", true, nil) |
| + b, _ := io.ReadAll(r.Body) |
| + if r.StatusCode != 200 || string(b) != `annie|replayable=""` || r.Header.Get(HandoverHeader) != "" { |
| + t.Fatalf("a hop's mark reached the app: %d %q %v", r.StatusCode, b, r.Header) |
| + } |
| + if _, asks := x.mv.seen(); len(asks) != 2 || asks[0].Replayable || !asks[1].Replayable || !asks[1].Hop { |
| + t.Fatalf("the decision was asked %+v: a client's mark must not count, a hop's must", asks) |
| + } |
| + // Through a forward: betty's app's header is stripped at betty's |
| + // tenant boundary. |
| + x.mv.target = "betty" |
| + resp, body = x.fetch(t, fwHost, "/echo-replayable", ReplayableHeader, "1") |
| + if resp.StatusCode != 200 || body != `betty|replayable=""` || resp.Header.Get(HandoverHeader) != "" { |
| + t.Fatalf("forwarded: %d %q %v", resp.StatusCode, body, resp.Header) |
| + } |
| +} |
| + |
| +func TestParseHandover(t *testing.T) { |
| + if v := FormatHandover("betty", 12); v != "holder=betty; gen=12" { |
| + t.Fatalf("format = %q", v) |
| + } |
| + if h, g, ok := ParseHandover("holder=betty; gen=12"); !ok || h != "betty" || g != 12 { |
| + t.Fatalf("parse = %q %d %v", h, g, ok) |
| + } |
| + for _, bad := range []string{"", "holder=; gen=1", "holder=b", "holder=b; gen=x", "holder=b; gen=-1", "gen=1; holder=b", "holder=b c; gen=1", "holder=b; gen=1; x=y"} { |
| + if _, _, ok := ParseHandover(bad); ok { |
| + t.Fatalf("parsed %q", bad) |
| + } |
| + } |
| +} |