carlos / platform Public

region HA: drain state, placement withdrawal and drain acks

Task 1 of the held-requests build (spec §25.4 steps 1 and 4, §25.5,
§25.7, R3.8, R3.9).

- The edges file carries a box-level drain state through the existing
  publisher: the existing box-level draining field (every reader treats
  it as a placement withdrawal) and an additive ha_drained. Admission's
  drained, name authority and holder reachability are unchanged. The
  loop republishes a wanted state until it is reported with its
  generation.
- A draining box is local-denied in wake and duty placement from the
  moment it starts, §6.3 rule 1 included; peers read ha_drained as
  local-denied too. Silence from a draining holder costs no lock
  re-read and no placement suspicion. Folding ha_drained drops
  holder-cache entries naming the box.
- /.carlos/ha-drain: a signed ask (its own mesh-key MAC over receiver,
  method, path, transaction, timestamp and body; 4 KiB bound). The
  receiver refreshes its fold once per (transaction, generation) and
  answers from memory after; a failed refresh answers not seen. Both
  control paths, ha-drain and ha-take, are refused at the front door on
  every ingress and never forwarded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 926057ca19da583b4dd3c8bf4313baecf939b576 parent 0b9a0b4
16 files changed, +1,541 −10
  • internal/activator/activator.go +3 −0
  • internal/activator/hacache.go +22 −0
  • internal/activator/hadrain.go +58 −0
  • internal/activator/hadrain_test.go +148 −0
  • internal/activator/haduties.go +2 −0
  • internal/activator/haforward.go +11 −0
  • internal/edge/edge.go +10 −0
  • internal/edge/hadrain.go +457 −0
  • internal/edge/hadrain_test.go +484 −0
  • internal/edge/homemap.go +16 −2
  • internal/edge/wakeplacement.go +6 −3
  • internal/host/agent.go +6 −0
  • internal/host/dbreads.go +2 −2
  • internal/host/edgesfile.go +26 −3
  • internal/host/hadrainstate.go +133 −0
  • internal/host/hadrainstate_test.go +157 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index b0528e92e..a0acc9243 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1362,6 +1362,9 @@ type Service struct {
peers placementPeers
placementLog placementDiagnostics
OnHAOverCapacity func(region, host, ref string)
+ // drain is this box's and its peers' planned-handover drain state
+ // (hadrain.go).
+ drain drainSources
// lifeCtx is cancelled by Shutdown: the seam that lets an in-flight worker
// spawn be TORN DOWN rather than waited out. See Shutdown for why waiting
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go
index a53ccd53a..687b30a30 100644
--- a/internal/activator/hacache.go
+++ b/internal/activator/hacache.go
@@ -190,6 +190,28 @@ func (c *holderCache) drop(host string) {
}
}
+// dropRef forgets every entry naming ref, suspect or not, and marks any
+// read in flight revalidating ref stale, so its answer is not cached
+// (§25.4 step 4: ref published drained). Negative entries and entries
+// naming other boxes stand. A scan, run once per drained publication.
+func (c *holderCache) dropRef(ref string) {
+ if ref == "" {
+ return
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for _, el := range c.holders {
+ if el.Value.(*holderEntry).ref == ref {
+ c.removeLocked(el)
+ }
+ }
+ for _, f := range c.flights {
+ if f.suspect == ref {
+ f.stale = true
+ }
+ }
+}
+
// putLocked sets host's entry under a new generation.
func (c *holderCache) putLocked(host, ref string, suspect bool, ttl time.Duration) {
if f := c.flights[host]; f != nil {
diff --git a/internal/activator/hadrain.go b/internal/activator/hadrain.go
new file mode 100644
index 000000000..9706ea5f3
--- /dev/null
+++ b/internal/activator/hadrain.go
@@ -0,0 +1,58 @@
+package activator
+
+import "sync/atomic"
+
+// Planned-handover drain state, as the activator reads it (region HA spec
+// §25.4 steps 1 and 4, §25.5 "Silence"). The box's own state lives with the
+// agent, which publishes it in its edges file (internal/host); peers' states
+// come from this edge's fold of their files. Both are sources set once at
+// wiring; unset, nothing drains and nothing changes.
+//
+// The drain withdraws placement only. Name authority, admission and holder
+// reachability are unchanged: a draining box still answers as a holder and
+// a forwarder.
+type drainSources struct {
+ local atomic.Pointer[func() bool]
+ peer atomic.Pointer[func(ref string) bool]
+}
+
+// SetDrainingSource sets where IsDraining reads this box's own drain state.
+func (a *Service) SetDrainingSource(fn func() bool) {
+ if fn == nil {
+ a.drain.local.Store(nil)
+ return
+ }
+ a.drain.local.Store(&fn)
+}
+
+// IsDraining is whether this box is in the drain state: it then places
+// nothing on itself (§25.4 step 1), from the moment the state is set, before
+// its own publication folds back.
+func (a *Service) IsDraining() bool {
+ fn := a.drain.local.Load()
+ return fn != nil && (*fn)()
+}
+
+// SetPeerDrainView sets how the activator learns that another box is in
+// the drain state: the edge's fold of that box's edges file.
+func (a *Service) SetPeerDrainView(fn func(ref string) bool) {
+ if fn == nil {
+ a.drain.peer.Store(nil)
+ return
+ }
+ a.drain.peer.Store(&fn)
+}
+
+// peerDraining is whether ref's folded edges file says it is draining.
+func (a *Service) peerDraining(ref string) bool {
+ fn := a.drain.peer.Load()
+ return ref != "" && fn != nil && (*fn)(ref)
+}
+
+// DropHoldersNaming forgets every holder-cache entry naming ref. The edge
+// calls it when its fold first sees ref's file say drained (§25.4 step 4):
+// no lease names ref any more, so nothing should be forwarded there as to
+// a holder.
+func (a *Service) DropHoldersNaming(ref string) {
+ a.holders.dropRef(ref)
+}
diff --git a/internal/activator/hadrain_test.go b/internal/activator/hadrain_test.go
new file mode 100644
index 000000000..864b85ec6
--- /dev/null
+++ b/internal/activator/hadrain_test.go
@@ -0,0 +1,148 @@
+package activator
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Region HA §25.4 step 1: a draining box places nothing on itself. §6.3
+// rule 1 included: a clean marker naming this box no longer sends the wake
+// here; it goes to the roomiest other serving box.
+func TestDrainingSelfCleanMarkerWakesElsewhere(t *testing.T) {
+ for _, draining := range []bool{false, true} {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ putLockFor(t, s.b, s.rt, markerBody(t, "a", "i-a", haFixOf(s.b).lifetime, 5, true))
+ s.a.SetDrainingSource(func() bool { return draining })
+ if s.a.IsDraining() != draining {
+ t.Fatalf("IsDraining %v, want %v", s.a.IsDraining(), draining)
+ }
+ snap := placementSnapshot(time.Now())
+ // a is the roomier box here, so only the drain moves the wake.
+ snap.Serving[0].MemFreeMiB = 90
+ d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return snap })
+ if !draining && (d.Ref != "" || d.Unavailable || d.Refuse) {
+ t.Fatalf("not draining: %+v, want the wake here (clean releaser)", d)
+ }
+ if draining && (d.Ref != "b" || d.Kind != edge.Placement) {
+ t.Fatalf("draining: %+v, want a placement forward to b", d)
+ }
+ }
+}
+
+// A draining box's duty view is local-denied, so no duty or adoption
+// starts here; the same rule as its published file's draining field.
+func TestDrainingSelfDeniesDuties(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ s.a.SetDutyView(func(registry.Route) boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) })
+ in, _, err := s.a.dutyInput(context.Background(), s.rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if in.LocalDenied {
+ t.Fatalf("not draining yet denied: %+v", in)
+ }
+ s.a.SetDrainingSource(func() bool { return true })
+ if in, _, err = s.a.dutyInput(context.Background(), s.rt); err != nil || !in.LocalDenied {
+ t.Fatalf("draining duty input %+v (%v), want local-denied", in, err)
+ }
+}
+
+// §25.5 Silence: a held hop is silent by design, so silence from a box in
+// the drain state costs no lock re-read and no placement suspicion. Every
+// other outcome, and silence from any other box, is unchanged.
+func TestSilentDrainingHolderIsNotSuspect(t *testing.T) {
+ s := haHeldByB(t)
+ s.a.SetPeerDrainView(func(ref string) bool { return ref == "b" })
+ d := s.decide()
+ if d.Ref != "b" {
+ t.Fatalf("decision %+v, want b", d)
+ }
+ var reads atomic.Int32
+ old := readHolderLock
+ readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ reads.Add(1)
+ return old(ctx, bucket, prefix, region)
+ }
+ t.Cleanup(func() { readHolderLock = old })
+ s.a.NoteForward(s.rt.Host, edge.ForwardResult{Kind: edge.Holder, Outcome: edge.ForwardSilent, Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen})
+ if s.a.peers.snapshot(time.Now()).Suspect["b"] {
+ t.Fatal("silence from a draining box made it a placement suspect")
+ }
+ s.a.holders.mu.Lock()
+ e := *s.a.holders.holders[s.rt.Host].Value.(*holderEntry)
+ s.a.holders.mu.Unlock()
+ if e.suspect || e.silent || e.ref != "b" {
+ t.Fatalf("silence from a draining box changed the entry: %+v", e)
+ }
+ for range 5 {
+ if got := s.decide(); got.Ref != "b" || got.Refuse {
+ t.Fatalf("after silence %+v, want b", got)
+ }
+ }
+ if reads.Load() != 0 {
+ t.Fatalf("%d lock re-reads after silence from a draining box, want 0", reads.Load())
+ }
+ // Unreachable from the same draining box is unchanged: suspect.
+ d = s.decide()
+ s.a.NoteForward(s.rt.Host, edge.ForwardResult{Kind: edge.Holder, Outcome: edge.ForwardUnreachable, Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen})
+ if !s.a.peers.snapshot(time.Now()).Suspect["b"] {
+ t.Fatal("an unreachable draining box must still be suspect")
+ }
+}
+
+// Silence from a box that is not draining keeps today's rule (pinned by
+// TestSilentHolderRevalidatesOnce): silent, a placement suspect.
+func TestSilentHolderNotDrainingUnchanged(t *testing.T) {
+ s := haHeldByB(t)
+ s.a.SetPeerDrainView(func(ref string) bool { return ref == "c" })
+ d := s.decide()
+ s.a.NoteForward(s.rt.Host, edge.ForwardResult{Kind: edge.Holder, Outcome: edge.ForwardSilent, Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen})
+ if !s.a.peers.snapshot(time.Now()).Suspect["b"] {
+ t.Fatal("silence from a serving box must still exclude placement")
+ }
+ s.a.holders.mu.Lock()
+ e := *s.a.holders.holders[s.rt.Host].Value.(*holderEntry)
+ s.a.holders.mu.Unlock()
+ if !e.silent || !e.suspect {
+ t.Fatalf("silence from a serving box: %+v, want silent and suspect", e)
+ }
+}
+
+// §25.4 step 4: when a box publishes drained, every box that folds it drops
+// the holder-cache entries naming it. Others stand.
+func TestDropHoldersNaming(t *testing.T) {
+ var c holderCache
+ c.set("one.example.com", "a")
+ c.set("two.example.com", "b")
+ c.set("three.example.com", "a")
+ c.setNegative("four.example.com")
+ c.mu.Lock()
+ gen := c.holders["three.example.com"].Value.(*holderEntry).gen
+ c.mu.Unlock()
+ c.unreachable("three.example.com", gen) // suspect entries naming a go too
+ c.dropRef("a")
+ for host, want := range map[string]bool{"one.example.com": false, "two.example.com": true, "three.example.com": false, "four.example.com": true} {
+ if _, _, found := c.get(host); found != want {
+ t.Errorf("%s: found %v, want %v", host, found, want)
+ }
+ }
+ c.dropRef("")
+ if _, _, found := c.get("four.example.com"); !found {
+ t.Fatal("an empty ref dropped a negative entry")
+ }
+ s := haService(t, "shop.example.com")
+ s.a.holders.set("x.example.com", "a")
+ s.a.DropHoldersNaming("a")
+ if _, _, found := s.a.holders.get("x.example.com"); found {
+ t.Fatal("DropHoldersNaming left the entry")
+ }
+}
diff --git a/internal/activator/haduties.go b/internal/activator/haduties.go
index fe3850b52..2bdb63f29 100644
--- a/internal/activator/haduties.go
+++ b/internal/activator/haduties.go
@@ -225,6 +225,8 @@ func (a *Service) dutyInput(ctx context.Context, rt registry.Route) (DutyInput,
a.mu.Lock()
i.LocalDenied = a.shuttingDown || a.fences[rt.Host] != 0 || a.disabled(rt)
a.mu.Unlock()
+ // A draining box starts no duty and adopts nothing (§25.4 step 1).
+ i.LocalDenied = i.LocalDenied || a.IsDraining()
i.LocalDenied = i.LocalDenied || rt.Replica || rt.Tunnel != "" || rt.ImportGate != "" || (rt.Status != "" && rt.Status != "ready")
a.duties.mu.Lock()
view := a.duties.view
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go
index 58663b8a0..f3c124803 100644
--- a/internal/activator/haforward.go
+++ b/internal/activator/haforward.go
@@ -201,6 +201,10 @@ func (a *Service) decideForward(rt registry.Route, r holderLockReader, resolved
if snapshot != nil {
s = snapshot()
}
+ // A draining box places nothing on itself (§25.4 step 1), from the
+ // moment it starts, before its own published file folds back here:
+ // the same local denial that file's draining field gives.
+ s.LocalDenied = s.LocalDenied || a.IsDraining()
now := a.holders.clock()
// Decide and reserve against the same peer state. A concurrent failure
// cannot turn a selected peer suspect between the rule and admission.
@@ -262,6 +266,13 @@ func (a *Service) NoteForward(host string, res edge.ForwardResult) {
if res.Outcome == edge.ForwardCanceled {
return
}
+ // §25.5 "Silence": a held hop is silent by design, so silence from a
+ // box in the drain state costs no lock re-read and no placement
+ // suspicion. Every other outcome from it, and silence from any other
+ // box, goes on as before.
+ if res.Outcome == edge.ForwardSilent && a.peerDraining(res.Ref) {
+ return
+ }
self, _ := boxSelfRef(a.backend)
accepted := false
note := func() {
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 7ef38b291..d1cf55ecd 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -358,6 +358,9 @@ type Edge struct {
// an inbound hop. Atomic because it is armed in RunWithActivatorReady after
// construction, and read on the request path while that is happening.
homes atomic.Pointer[homeMap]
+ // peerDrained is the hook a fold runs when it first sees a peer's file
+ // say ha_drained (hadrain.go, SetPeerDrainedHook).
+ peerDrained atomic.Pointer[func(string)]
// backhaulTransports caches the outbound TLS transport of each backhaul
// target, keyed by the home box's EIP — see backhaulTransport. Bounded by
// the number of BOXES in the deployment, never by hostnames: a catch-all
@@ -1938,6 +1941,13 @@ func firstSegmentClean(p string) string {
}
func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // The planned-handover control paths (hadrain.go, region HA §25.7) are
+ // reserved on every ingress and answered first: a client's request for
+ // either is refused here and never forwarded or handed to an app.
+ if haControlPath(r.URL.Path) {
+ e.serveHAControl(w, r)
+ return
+ }
if e.handleDemoRequest(w, r, true) {
return
}
diff --git a/internal/edge/hadrain.go b/internal/edge/hadrain.go
new file mode 100644
index 000000000..a126eabb4
--- /dev/null
+++ b/internal/edge/hadrain.go
@@ -0,0 +1,457 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+)
+
+// Planned-handover drain acknowledgements (region HA spec §25.4 steps 1 and
+// 4, §25.7, R3.8, R3.9).
+//
+// A draining box A publishes its drain state in its edges file, then asks
+// every live box that views its region whether it now sees it: a POST to
+// HADrainPath naming the drain transaction and the generation of A's file.
+// The receiver refreshes its fold of the edges files (one normal fold read:
+// a LIST and a GET per file) unless it has already folded that generation,
+// and answers whether A's folded file says draining. An answer for a
+// (transaction, generation) the fold has settled is remembered, so a repeat
+// ask costs no store read. A refresh that fails answers "not seen" and is
+// not remembered.
+//
+// Both control paths, HADrainPath and HATakePath (§25.7, the take request a
+// later task adds), are reserved on every ingress: ServeHTTP answers them
+// first, ahead of every route and every forward, so a client's request for
+// either is refused at the front door and reaches no app on any box. Each
+// carries its own mesh-key signature over the receiver, the method, the
+// path, the drain transaction, the timestamp and the body. The ordinary hop
+// signature binds only host and time (mesh.go), so it is not enough here.
+//
+// This reader is member-blind (§24.3): it reads the asker's own file, by
+// its exact key, whatever its name shape, region or pool. A terminated
+// member's unchanged file keeps answering as it was last published until
+// the departure removes it, which a drain never relies on: the asker is
+// alive and asking.
+const (
+ HADrainPath = "/.carlos/ha-drain"
+ HATakePath = "/.carlos/ha-take"
+
+ haControlAuthHeader = "X-Carlos-HA-Auth"
+ haControlTxnHeader = "X-Carlos-HA-Txn"
+ // haControlMaxBody bounds a control request's body (R3.8).
+ haControlMaxBody = 4 << 10
+ // haControlReadTimeout bounds reading a control request's body.
+ haControlReadTimeout = 2 * time.Second
+ // haDrainAskTimeout bounds one ask, dial to answer, the receiver's fold
+ // read included.
+ haDrainAskTimeout = 15 * time.Second
+ // haDrainRefreshTimeout bounds the receiver's fold read for one ask.
+ haDrainRefreshTimeout = 10 * time.Second
+ // haDrainAcksMax bounds the remembered answers; the oldest goes first.
+ haDrainAcksMax = 256
+ // haControlMaxField bounds the transaction id and the asker's name.
+ haControlMaxField = 128
+)
+
+// haControlDomain separates the control paths' MAC from the hop's, the
+// door mark's and the probe-burst notice's, by the NUL argument
+// hopDoorDomain makes.
+const haControlDomain = "carlos-ha-control\x00"
+
+// haDrainAsk is the ask's JSON body.
+type haDrainAsk struct {
+ From string `json:"from"`
+ Txn string `json:"txn"`
+ Generation string `json:"generation"`
+}
+
+// haDrainAnswer is the receiver's answer.
+type haDrainAnswer struct {
+ Seen bool `json:"seen"`
+}
+
+// haControlPath reports whether p, cleaned, is one of the reserved control
+// paths or beneath one.
+func haControlPath(p string) bool {
+ if !strings.HasPrefix(p, "/") {
+ p = "/" + p
+ }
+ c := path.Clean(p)
+ for _, reserved := range []string{HADrainPath, HATakePath} {
+ if c == reserved || strings.HasPrefix(c, reserved+"/") {
+ return true
+ }
+ }
+ return false
+}
+
+// signHAControl is the value of haControlAuthHeader: the timestamp, then
+// the hex HMAC over the domain, the receiving box's name, the method, the
+// path, the transaction, the timestamp and the body.
+func signHAControl(key []byte, receiver, method, p, txn string, now time.Time, body []byte) string {
+ ts := strconv.FormatInt(now.Unix(), 10)
+ return ts + ":" + hex.EncodeToString(haControlMAC(key, receiver, method, p, txn, ts, body))
+}
+
+// verifyHAControlEitherKey checks header under either mirrored key: the
+// timestamp within ±hopSkew of now, the MAC compared in constant time.
+func verifyHAControlEitherKey(current, next []byte, receiver, method, p, txn, header string, body []byte, now time.Time) bool {
+ ts, sig, ok := strings.Cut(header, ":")
+ if !ok || ts == "" || sig == "" {
+ return false
+ }
+ sec, err := strconv.ParseInt(ts, 10, 64)
+ if err != nil {
+ return false
+ }
+ skew := now.Sub(time.Unix(sec, 0))
+ if skew < 0 {
+ skew = -skew
+ }
+ if skew > hopSkew {
+ return false
+ }
+ got, err := hex.DecodeString(sig)
+ if err != nil {
+ return false
+ }
+ if len(next) > 0 && hmac.Equal(got, haControlMAC(next, receiver, method, p, txn, ts, body)) {
+ return true
+ }
+ return len(current) > 0 && hmac.Equal(got, haControlMAC(current, receiver, method, p, txn, ts, body))
+}
+
+func haControlMAC(key []byte, receiver, method, p, txn, ts string, body []byte) []byte {
+ mac := hmac.New(sha256.New, key)
+ for _, part := range []string{haControlDomain, receiver, method, p, txn, ts} {
+ mac.Write([]byte(part))
+ mac.Write([]byte("\n"))
+ }
+ mac.Write(body)
+ return mac.Sum(nil)
+}
+
+// haControlField is a transaction id or box name a control request may
+// carry: printable ASCII with no slash, bounded.
+func haControlField(s string) bool {
+ if s == "" || len(s) > haControlMaxField {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if c := s[i]; c <= ' ' || c > '~' || c == '/' {
+ return false
+ }
+ }
+ return true
+}
+
+// refuseHAControl answers a refused control request: a bare 404, so a
+// refusal says no more than a missing page does.
+func refuseHAControl(w http.ResponseWriter) {
+ w.WriteHeader(http.StatusNotFound)
+}
+
+// serveHAControl answers a request for a reserved control path. It is
+// called for every such request, whoever sent it; anything that is not a
+// signed ask for this box is refused.
+func (e *Edge) serveHAControl(w http.ResponseWriter, r *http.Request) {
+ auth, txns := r.Header.Values(haControlAuthHeader), r.Header.Values(haControlTxnHeader)
+ if r.Method != http.MethodPost || r.URL.Path != HADrainPath || len(auth) != 1 || len(txns) != 1 {
+ w.Header().Set("Connection", "close")
+ refuseHAControl(w)
+ return
+ }
+ // The body is read before any answer, bounded in time and size, as a
+ // probe-burst notice's is (burst_notice.go): net/http would otherwise
+ // drain an unread body before writing the refusal, with no deadline.
+ rc := http.NewResponseController(w)
+ bounded := rc.SetReadDeadline(time.Now().Add(haControlReadTimeout)) == nil
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, haControlMaxBody))
+ if err != nil {
+ w.Header().Set("Connection", "close")
+ refuseHAControl(w)
+ return
+ }
+ if bounded {
+ rc.SetReadDeadline(time.Time{})
+ }
+ m := e.homes.Load()
+ if m == nil || e.box == "" {
+ refuseHAControl(w)
+ return
+ }
+ current, next := m.meshKeys()
+ if len(current) == 0 && len(next) == 0 {
+ refuseHAControl(w)
+ return
+ }
+ txn := txns[0]
+ if !haControlField(txn) || !verifyHAControlEitherKey(current, next, e.box, r.Method, HADrainPath, txn, auth[0], body, time.Now()) {
+ e.logThrottled("ha-drain-refused", fmt.Sprintf("ha-drain ask from %s refused (signature)", r.RemoteAddr))
+ refuseHAControl(w)
+ return
+ }
+ var ask haDrainAsk
+ if json.Unmarshal(body, &ask) != nil || ask.Txn != txn || !haControlField(ask.From) || ask.From == e.box {
+ refuseHAControl(w)
+ return
+ }
+ gen, err := time.Parse(time.RFC3339, ask.Generation)
+ if err != nil {
+ refuseHAControl(w)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), haDrainRefreshTimeout)
+ defer cancel()
+ seen := m.drainSeen(ctx, ask.From, ask.Txn, gen)
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ json.NewEncoder(w).Encode(haDrainAnswer{Seen: seen})
+}
+
+// drainAcks is the receiver's memory of answered asks (R3.9). mu also
+// serializes asks, so concurrent asks for one generation share one fold
+// read.
+type drainAcks struct {
+ mu sync.Mutex
+ seen map[string]bool
+ order []string
+}
+
+// drainSeen answers an ask from box from for transaction txn about the
+// generation gen of its file: whether the fold shows that file, at gen or
+// later, draining. The fold is read again unless it already settles the
+// question; a failed read answers false and remembers nothing.
+func (m *homeMap) drainSeen(ctx context.Context, from, txn string, gen time.Time) bool {
+ a := &m.drainAcks
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ key := txn + "\x00" + from + "\x00" + gen.UTC().Format(time.RFC3339)
+ if seen, ok := a.seen[key]; ok {
+ return seen
+ }
+ seen, settled := m.foldedDrain(from, gen)
+ if !settled {
+ if err := m.refreshHostsNow(ctx); err != nil {
+ return false
+ }
+ if seen, settled = m.foldedDrain(from, gen); !settled {
+ return false
+ }
+ }
+ if a.seen == nil {
+ a.seen = make(map[string]bool)
+ }
+ for len(a.order) >= haDrainAcksMax {
+ delete(a.seen, a.order[0])
+ a.order = a.order[1:]
+ }
+ a.seen[key] = seen
+ a.order = append(a.order, key)
+ return seen
+}
+
+// foldedDrain reads from's file in the current fold. settled is true when
+// the fold answers for gen: a later generation (draining or not), or gen
+// itself already draining. A file at gen that is not draining may be an
+// earlier publication in the same second (generations are whole seconds),
+// so it is not settled and is read again.
+func (m *homeMap) foldedDrain(from string, gen time.Time) (seen, settled bool) {
+ f, ok := m.snapshot().files[edgesPrefix+from+".json"]
+ if !ok || f.Box != from {
+ return false, false
+ }
+ var text string
+ if !placementField(f.Generation, &text) {
+ return false, false
+ }
+ at, err := time.Parse(time.RFC3339, text)
+ if err != nil {
+ return false, false
+ }
+ draining := f.drainState()
+ switch {
+ case at.After(gen):
+ return draining, true
+ case at.Equal(gen) && draining:
+ return true, true
+ }
+ return false, false
+}
+
+// drainState is whether f says its box is in the drain state: draining, or
+// drained (which a drained box also publishes as draining).
+func (f edgesFileView) drainState() bool {
+ var draining, drained bool
+ placementField(f.Draining, &draining)
+ placementField(f.HADrained, &drained)
+ return draining || drained
+}
+
+// drainedState is whether f says ha_drained.
+func (f edgesFileView) drainedState() bool {
+ var drained bool
+ placementField(f.HADrained, &drained)
+ return drained
+}
+
+// refreshHostsNow is one fold read on an ask's behalf: the hosts half of a
+// refresh, under the poll's own lock, so it never races the poll.
+func (m *homeMap) refreshHostsNow(ctx context.Context) error {
+ m.refreshMu.Lock()
+ defer m.refreshMu.Unlock()
+ if err := m.refreshHosts(ctx); err != nil {
+ return err
+ }
+ m.health.MapLoaded()
+ return nil
+}
+
+// notePeerDrained runs the drained hook for each box whose file in files
+// says ha_drained, once per generation of that file. Caller holds
+// refreshMu.
+func (m *homeMap) notePeerDrained(files map[string]edgesFileView) {
+ if m.peerDrained == nil {
+ return
+ }
+ now := make(map[string]string)
+ for _, f := range files {
+ if f.Box == "" || f.Box == m.self || !f.drainedState() {
+ continue
+ }
+ now[f.Box] = string(f.Generation)
+ }
+ for box, gen := range now {
+ if m.drainedNoted[box] != gen {
+ m.peerDrained(box)
+ }
+ }
+ m.drainedNoted = now
+}
+
+// PeerDraining is whether this edge's fold shows ref's edges file in the
+// drain state. Memory only.
+func (e *Edge) PeerDraining(ref string) bool {
+ m := e.homes.Load()
+ if m == nil || ref == "" {
+ return false
+ }
+ f, ok := m.snapshot().files[edgesPrefix+ref+".json"]
+ return ok && f.Box == ref && f.drainState()
+}
+
+// SetPeerDrainedHook sets what runs when this edge's fold first sees a
+// peer's file say drained (§25.4 step 4): the activator's holder-cache
+// drop. It runs inside the fold, before an ask that caused the fold is
+// answered.
+func (e *Edge) SetPeerDrainedHook(fn func(ref string)) {
+ if fn == nil {
+ e.peerDrained.Store(nil)
+ return
+ }
+ e.peerDrained.Store(&fn)
+}
+
+func (e *Edge) runPeerDrained(ref string) {
+ if fn := e.peerDrained.Load(); fn != nil {
+ (*fn)(ref)
+ }
+}
+
+// AskDrainSeen asks peer whether it sees this box draining at generation,
+// for drain transaction txn. seen is the peer's answer; err is a request
+// that got no answer (no key, no file for the peer, a dial or a refusal).
+// A drain driver asks again on its own cadence.
+func (e *Edge) AskDrainSeen(ctx context.Context, peer, txn, generation string) (bool, error) {
+ m := e.homes.Load()
+ if m == nil || e.box == "" {
+ return false, errors.New("ha-drain: this edge has no home map or box name")
+ }
+ if !haControlField(txn) || !haControlField(peer) || peer == e.box {
+ return false, fmt.Errorf("ha-drain: bad transaction %q or peer %q", txn, peer)
+ }
+ if _, err := time.Parse(time.RFC3339, generation); err != nil {
+ return false, fmt.Errorf("ha-drain: generation %q: %w", generation, err)
+ }
+ current, next := m.meshKeys()
+ key := signingKey(current, next)
+ if len(key) == 0 {
+ return false, errors.New("ha-drain: no mesh key to sign with")
+ }
+ dial, host, err := m.controlTarget(peer)
+ if err != nil {
+ return false, err
+ }
+ body, err := json.Marshal(haDrainAsk{From: e.box, Txn: txn, Generation: generation})
+ if err != nil {
+ return false, err
+ }
+ if len(body) > haControlMaxBody {
+ return false, errors.New("ha-drain: ask over the body bound")
+ }
+ ctx, cancel := context.WithTimeout(ctx, haDrainAskTimeout)
+ defer cancel()
+ u := url.URL{Scheme: "https", Host: host, Path: HADrainPath}
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(body))
+ if err != nil {
+ return false, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set(haControlTxnHeader, txn)
+ req.Header.Set(haControlAuthHeader, signHAControl(key, peer, http.MethodPost, HADrainPath, txn, time.Now(), body))
+ resp, err := e.backhaulTransport(dial).RoundTrip(req)
+ if err != nil {
+ return false, fmt.Errorf("ha-drain: ask %s (%s): %w", peer, dial, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
+ return false, fmt.Errorf("ha-drain: %s answered %d", peer, resp.StatusCode)
+ }
+ var ans haDrainAnswer
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 4<<10)).Decode(&ans); err != nil {
+ return false, fmt.Errorf("ha-drain: %s's answer: %w", peer, err)
+ }
+ return ans.Seen, nil
+}
+
+// controlTarget is where a control request to peer goes: its dial address,
+// by the same rule a hop uses, and a host to ask for. The host is the
+// lowest non-wildcard name peer publishes, else the lowest this box
+// publishes: every edge serves every mirrored certificate (certsync.go), and
+// a group member may publish no hosts (§24.1).
+func (m *homeMap) controlTarget(peer string) (dial, host string, err error) {
+ snap := m.snapshot()
+ f, ok := snap.files[edgesPrefix+peer+".json"]
+ if !ok || f.Box != peer {
+ return "", "", fmt.Errorf("ha-drain: no edges file for %s", peer)
+ }
+ own, ownKnown := snap.files[edgesPrefix+m.self+".json"]
+ ownKnown = ownKnown && own.Box == m.self
+ reader := edgesfile.Reader{Box: m.self, Self: own.dialPoint(), SelfKnown: ownKnown, PrivateDial: m.privateDial}
+ if dial = reader.Dial(f.dialPoint()); dial == "" {
+ return "", "", fmt.Errorf("ha-drain: no dial address for %s", peer)
+ }
+ if host = burstNoticeHost(f.Hosts); host == "" && ownKnown {
+ host = burstNoticeHost(own.Hosts)
+ }
+ if host == "" {
+ return "", "", fmt.Errorf("ha-drain: no host to address %s by", peer)
+ }
+ return dial, host, nil
+}
diff --git a/internal/edge/hadrain_test.go b/internal/edge/hadrain_test.go
new file mode 100644
index 000000000..7afce9d48
--- /dev/null
+++ b/internal/edge/hadrain_test.go
@@ -0,0 +1,484 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/crypto/acme/autocert"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Planned-handover drain acknowledgements (region HA spec §25.4 steps 1
+// and 4, §25.7, R3.8, R3.9). Every box is a real Edge behind a real TLS
+// listener over one bucket, as in the probe-burst scene.
+
+// drainStore counts the edges-file reads one box makes, and can fail them.
+type drainStore struct {
+ release.Store
+ mu sync.Mutex
+ lists int
+ gets int
+ fail bool
+}
+
+func (d *drainStore) List(ctx context.Context, prefix string) ([]string, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if prefix == edgesPrefix {
+ d.lists++
+ if d.fail {
+ return nil, errors.New("SlowDown: please reduce your request rate")
+ }
+ }
+ return d.Store.List(ctx, prefix)
+}
+
+func (d *drainStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ d.mu.Lock()
+ if strings.HasPrefix(key, edgesPrefix) {
+ d.gets++
+ if d.fail {
+ d.mu.Unlock()
+ return nil, "", errors.New("SlowDown: please reduce your request rate")
+ }
+ }
+ d.mu.Unlock()
+ return d.Store.Get(ctx, key)
+}
+
+func (d *drainStore) reads() (lists, gets int) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.lists, d.gets
+}
+
+func (d *drainStore) setFail(v bool) {
+ d.mu.Lock()
+ d.fail = v
+ d.mu.Unlock()
+}
+
+// drainBox is one box of a drain scene.
+type drainBox struct {
+ box, ip, host, region string
+ be *backhaulEdge
+ store *drainStore
+ // door counts requests reaching this box's 443; app counts those its
+ // app saw, by path.
+ door atomic.Int64
+ mu sync.Mutex
+ app []string
+}
+
+func (x *drainBox) edge() *Edge { return x.be.live.Load().edge }
+
+func (x *drainBox) appSaw() []string {
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ return append([]string(nil), x.app...)
+}
+
+type drainScene struct {
+ *noticeScene
+ boxes []*drainBox
+}
+
+func newDrainScene(t *testing.T) *drainScene {
+ return &drainScene{noticeScene: newNoticeScene(t, true)}
+}
+
+// add boots a box serving host from an app that records every path.
+func (s *drainScene) add(t *testing.T, box, ip, host, region string) *drainBox {
+ t.Helper()
+ x := &drainBox{box: box, ip: ip, host: host, region: region}
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ x.mu.Lock()
+ x.app = append(x.app, r.URL.Path)
+ x.mu.Unlock()
+ io.WriteString(w, "the app")
+ }))
+ t.Cleanup(backend.Close)
+ x.store = &drainStore{Store: release.NewDirStore(s.bucket)}
+ be := &backhaulEdge{store: x.store, reg: openReg(t), box: box}
+ if err := be.reg.Upsert(registry.Route{Host: host, Kind: "service", Addr: backend.Listener.Addr().String(), Status: "ready", Account: "bdk", App: box}); err != nil {
+ t.Fatal(err)
+ }
+ be.local = autocert.DirCache(t.TempDir())
+ tlsCfg := be.boot(t)
+ x.be = be
+ srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ x.door.Add(1)
+ be.live.Load().edge.ServeHTTP(w, r)
+ }))
+ srv.Listener.Close()
+ srv.Listener = s.listen(t, ip)
+ srv.TLS = tlsCfg
+ srv.StartTLS()
+ t.Cleanup(srv.Close)
+ s.ca.publish(t, s.seed, host)
+ s.boxes = append(s.boxes, x)
+ return x
+}
+
+// file writes x's edges file at gen with the given drain state.
+func (s *drainScene) file(t *testing.T, x *drainBox, gen time.Time, draining, drained bool) {
+ t.Helper()
+ f := map[string]any{"v": 1, "box": x.box, "eip": x.ip, "region": x.region, "generation": gen.UTC().Format(time.RFC3339),
+ "hosts": map[string]any{x.host: map[string]any{"role": "home"}}}
+ if draining {
+ f["draining"] = true
+ }
+ if drained {
+ f["ha_drained"] = true
+ }
+ b, err := json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ putJSON(t, s.seed, edgesPrefix+x.box+".json", string(b))
+}
+
+// sync brings every box's mirror and home map up to date.
+func (s *drainScene) sync(t *testing.T) {
+ t.Helper()
+ for _, x := range s.boxes {
+ if err := x.be.mirror.Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ refreshHomeMap(t, x.be.homes)
+ }
+ s.key, _ = s.boxes[0].be.homes.meshKeys()
+}
+
+var drainGen0 = time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
+
+func genText(t time.Time) string { return t.UTC().Format(time.RFC3339) }
+
+// A receiver refreshes its fold of the asker's file once for a generation
+// it has not folded, answers what it sees, and answers every later ask for
+// that generation from memory (R3.9). Fixed and cross-region receivers
+// answer alike: the fold is member-blind.
+func TestHADrainAckOneFoldReadPerGeneration(t *testing.T) {
+ for _, tc := range []struct{ name, receiver, region string }{
+ {"fixed same region", "betty", "eu-west-1"},
+ {"member", "g-0123456789abcdef0123", "eu-west-1"},
+ {"fixed other region", "adi", "us-east-1"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := newDrainScene(t)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ b := s.add(t, tc.receiver, "127.0.0.12", "blog.example.com", tc.region)
+ s.file(t, a, drainGen0, false, false)
+ s.file(t, b, drainGen0, false, false)
+ s.sync(t)
+ ctx := context.Background()
+
+ // annie publishes the drain state; betty has not folded it.
+ gen1 := drainGen0.Add(time.Minute)
+ s.file(t, a, gen1, true, false)
+ l0, g0 := b.store.reads()
+ seen, err := a.edge().AskDrainSeen(ctx, b.box, "txn-1", genText(gen1))
+ if err != nil || !seen {
+ t.Fatalf("first ask: seen=%v err=%v, want seen", seen, err)
+ }
+ l1, g1 := b.store.reads()
+ if l1-l0 != 1 || g1-g0 != 2 {
+ t.Fatalf("first ask cost %d lists and %d gets, want one fold read (1 list, 2 gets)", l1-l0, g1-g0)
+ }
+ if !b.edge().PeerDraining("annie") {
+ t.Fatal("the receiver's fold does not show annie draining after the ack")
+ }
+ for range 5 {
+ if seen, err := a.edge().AskDrainSeen(ctx, b.box, "txn-1", genText(gen1)); err != nil || !seen {
+ t.Fatalf("repeat ask: seen=%v err=%v", seen, err)
+ }
+ }
+ if l, g := b.store.reads(); l != l1 || g != g1 {
+ t.Fatalf("repeat asks read the store: %d lists, %d gets more", l-l1, g-g1)
+ }
+
+ // drained: a new generation, one more fold read, then memory.
+ gen2 := gen1.Add(time.Minute)
+ s.file(t, a, gen2, true, true)
+ if seen, err := a.edge().AskDrainSeen(ctx, b.box, "txn-1", genText(gen2)); err != nil || !seen {
+ t.Fatalf("drained ask: seen=%v err=%v", seen, err)
+ }
+ if seen, err := a.edge().AskDrainSeen(ctx, b.box, "txn-1", genText(gen2)); err != nil || !seen {
+ t.Fatalf("drained repeat: seen=%v err=%v", seen, err)
+ }
+ if l, g := b.store.reads(); l-l1 != 1 || g-g1 != 2 {
+ t.Fatalf("drained round cost %d lists and %d gets, want one fold read", l-l1, g-g1)
+ }
+ })
+ }
+}
+
+// A refresh that fails answers "not seen", caches nothing, and the next
+// ask reads again.
+func TestHADrainAckFailedRefreshNotSeen(t *testing.T) {
+ s := newDrainScene(t)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1")
+ s.file(t, a, drainGen0, false, false)
+ s.file(t, b, drainGen0, false, false)
+ s.sync(t)
+ gen1 := drainGen0.Add(time.Minute)
+ s.file(t, a, gen1, true, false)
+ l0, _ := b.store.reads()
+ b.store.setFail(true)
+ ctx := context.Background()
+ for range 2 {
+ if seen, err := a.edge().AskDrainSeen(ctx, "betty", "txn-1", genText(gen1)); err != nil || seen {
+ t.Fatalf("failed refresh: seen=%v err=%v, want an answer of not seen", seen, err)
+ }
+ }
+ if l, _ := b.store.reads(); l-l0 != 2 {
+ t.Fatalf("a failed refresh was cached: %d lists", l)
+ }
+ if b.edge().PeerDraining("annie") {
+ t.Fatal("the fold changed on a failed refresh")
+ }
+ b.store.setFail(false)
+ if seen, err := a.edge().AskDrainSeen(ctx, "betty", "txn-1", genText(gen1)); err != nil || !seen {
+ t.Fatalf("after recovery: seen=%v err=%v", seen, err)
+ }
+}
+
+// The fold answers what it sees: a generation that is not draining is not
+// seen, and a same-second file that is not draining is read again rather
+// than remembered.
+func TestHADrainAckAnswersTheFold(t *testing.T) {
+ s := newDrainScene(t)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1")
+ s.file(t, a, drainGen0, false, false)
+ s.file(t, b, drainGen0, false, false)
+ s.sync(t)
+ ctx := context.Background()
+ // Same second, not draining yet: not seen, and not remembered.
+ for range 2 {
+ if seen, err := a.edge().AskDrainSeen(ctx, "betty", "txn-1", genText(drainGen0)); err != nil || seen {
+ t.Fatalf("not draining: seen=%v err=%v", seen, err)
+ }
+ }
+ l, _ := b.store.reads()
+ s.file(t, a, drainGen0, true, false)
+ if seen, err := a.edge().AskDrainSeen(ctx, "betty", "txn-1", genText(drainGen0)); err != nil || !seen {
+ t.Fatalf("same-second drain: seen=%v err=%v", seen, err)
+ }
+ if l2, _ := b.store.reads(); l2 != l+1 {
+ t.Fatalf("same-second drain read %d times, want 1", l2-l)
+ }
+ // A later generation that cleared the drain: not seen.
+ gen := drainGen0.Add(time.Minute)
+ s.file(t, a, gen, false, false)
+ if seen, err := a.edge().AskDrainSeen(ctx, "betty", "txn-2", genText(gen)); err != nil || seen {
+ t.Fatalf("cancelled drain: seen=%v err=%v", seen, err)
+ }
+}
+
+// Folding a drained file drops holder-cache entries naming the box, once
+// per generation, on the box that folds it.
+func TestHADrainedFoldDropsHolders(t *testing.T) {
+ s := newDrainScene(t)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1")
+ var mu sync.Mutex
+ var dropped []string
+ b.edge().SetPeerDrainedHook(func(ref string) {
+ mu.Lock()
+ dropped = append(dropped, ref)
+ mu.Unlock()
+ })
+ s.file(t, a, drainGen0, true, false)
+ s.file(t, b, drainGen0, false, false)
+ s.sync(t)
+ refreshHomeMap(t, b.be.homes)
+ if len(dropped) != 0 {
+ t.Fatalf("draining alone dropped %v", dropped)
+ }
+ gen := drainGen0.Add(time.Minute)
+ s.file(t, a, gen, true, true)
+ if seen, err := a.edge().AskDrainSeen(context.Background(), "betty", "txn-1", genText(gen)); err != nil || !seen {
+ t.Fatalf("drained ask: seen=%v err=%v", seen, err)
+ }
+ mu.Lock()
+ got := append([]string(nil), dropped...)
+ mu.Unlock()
+ if len(got) != 1 || got[0] != "annie" {
+ t.Fatalf("dropped %v by the ack, want [annie]", got)
+ }
+ refreshHomeMap(t, b.be.homes)
+ refreshHomeMap(t, b.be.homes)
+ mu.Lock()
+ defer mu.Unlock()
+ if len(dropped) != 1 {
+ t.Fatalf("dropped %v, want once per generation", dropped)
+ }
+ if !b.edge().PeerDraining("annie") || b.edge().PeerDraining("betty") || b.edge().PeerDraining("nobody") {
+ t.Fatal("PeerDraining does not follow the fold")
+ }
+}
+
+// The control paths carry their own signature (R3.8). A forged, stale,
+// tampered, misaddressed, oversized or hop-signed request is refused with a
+// bare 404 and reads nothing; none reaches the app.
+func TestHADrainRefusesForgery(t *testing.T) {
+ s := newDrainScene(t)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1")
+ s.file(t, a, drainGen0, true, false)
+ s.file(t, b, drainGen0, false, false)
+ s.sync(t)
+ now := time.Now()
+ body := []byte(fmt.Sprintf(`{"from":"annie","txn":"txn-1","generation":%q}`, genText(drainGen0)))
+ good := func() (string, string, []byte) {
+ return signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now, body), "txn-1", body
+ }
+ post := func(method, auth, txn string, body []byte) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, "http://blog.example.com"+HADrainPath, bytes.NewReader(body))
+ if auth != "" {
+ r.Header.Set(haControlAuthHeader, auth)
+ }
+ if txn != "" {
+ r.Header.Set(haControlTxnHeader, txn)
+ }
+ w := httptest.NewRecorder()
+ b.edge().ServeHTTP(w, r)
+ return w
+ }
+ auth, txn, _ := good()
+ if w := post(http.MethodPost, auth, txn, body); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"seen":true`) {
+ t.Fatalf("a good ask: %d %q", w.Code, w.Body.String())
+ }
+ other := []byte("0123456789abcdef0123456789abcdef")
+ big := bytes.Repeat([]byte("x"), haControlMaxBody+1)
+ for name, tc := range map[string]struct {
+ method, auth, txn string
+ body []byte
+ }{
+ "no auth": {http.MethodPost, "", txn, body},
+ "no txn": {http.MethodPost, auth, "", body},
+ "other txn": {http.MethodPost, auth, "txn-2", body},
+ "other key": {http.MethodPost, signHAControl(other, "betty", http.MethodPost, HADrainPath, "txn-1", now, body), txn, body},
+ "other receiver": {http.MethodPost, signHAControl(s.key, "annie", http.MethodPost, HADrainPath, "txn-1", now, body), txn, body},
+ "other path": {http.MethodPost, signHAControl(s.key, "betty", http.MethodPost, HATakePath, "txn-1", now, body), txn, body},
+ "other method": {http.MethodPut, auth, txn, body},
+ "stale": {http.MethodPost, signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now.Add(-2*hopSkew), body), txn, body},
+ "tampered body": {http.MethodPost, auth, txn, bytes.Replace(body, []byte("annie"), []byte("betty"), 1)},
+ "hop signature": {http.MethodPost, signHop(s.key, "blog.example.com", now), txn, body},
+ "oversized": {http.MethodPost, signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now, big), txn, big},
+ } {
+ if w := post(tc.method, tc.auth, tc.txn, tc.body); w.Code != http.StatusNotFound || w.Body.Len() != 0 {
+ t.Errorf("%s: answered %d %q, want a bare 404", name, w.Code, w.Body.String())
+ }
+ }
+ if got := b.appSaw(); len(got) != 0 {
+ t.Fatalf("the app saw %v", got)
+ }
+}
+
+// Both control paths are reserved on every ingress: a client request for
+// either is refused at the front door and never forwarded, whether it
+// names a host served here or one homed on another box.
+func TestHAControlPathsReservedOnEveryIngress(t *testing.T) {
+ s := newDrainScene(t)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1")
+ s.file(t, a, drainGen0, false, false)
+ s.file(t, b, drainGen0, false, false)
+ s.sync(t)
+ send := func(x *drainBox, host, path string, hop bool) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "http://"+host+path, strings.NewReader(`{"from":"annie"}`))
+ r.Header.Set(haControlAuthHeader, "1:00")
+ if hop {
+ r.Header.Set(hopHeader, "1")
+ r.Header.Set(hopAuthHeader, signHop(s.key, host, time.Now()))
+ }
+ w := httptest.NewRecorder()
+ x.edge().ServeHTTP(w, r)
+ return w
+ }
+ // The harness forwards an ordinary path through betty to annie.
+ if w := send(b, a.host, "/ordinary", false); w.Code != http.StatusOK || a.door.Load() != 1 {
+ t.Fatalf("control forward: %d, annie's door %d", w.Code, a.door.Load())
+ }
+ before := a.door.Load()
+ for _, p := range []string{HADrainPath, HATakePath, HADrainPath + "/", HATakePath + "/x", "/.carlos//ha-drain", "/.carlos/./ha-take"} {
+ for name, tc := range map[string]struct {
+ x *drainBox
+ host string
+ hop bool
+ }{
+ "through a second edge": {b, a.host, false},
+ "served here": {a, a.host, false},
+ "as a verified hop": {a, a.host, true},
+ } {
+ if w := send(tc.x, tc.host, p, tc.hop); w.Code != http.StatusNotFound || w.Body.Len() != 0 {
+ t.Errorf("%s %s: answered %d %q, want a bare 404", name, p, w.Code, w.Body.String())
+ }
+ }
+ }
+ if a.door.Load() != before {
+ t.Fatalf("a control path was forwarded: annie's door moved by %d", a.door.Load()-before)
+ }
+ for _, x := range []*drainBox{a, b} {
+ for _, p := range x.appSaw() {
+ if strings.Contains(p, "ha-") {
+ t.Fatalf("%s's app saw %s", x.box, p)
+ }
+ }
+ }
+}
+
+// ha_drained is local-denied in placement, as draining is.
+func TestWakeSnapshotHADrained(t *testing.T) {
+ peer := wakeFile("peer")
+ peer["ha_drained"] = true
+ wantWakeRefs(t, wakeMap(t, wakeFile("self"), peer), "self")
+ bad := wakeFile("peer")
+ bad["ha_drained"] = "yes"
+ wantWakeRefs(t, wakeMap(t, wakeFile("self"), bad), "self")
+}
+
+// The signature binds each part on its own: receiver, method, path,
+// transaction, timestamp and body.
+func TestHAControlSignatureBindsEachPart(t *testing.T) {
+ key := []byte("0123456789abcdef0123456789abcdef")
+ now := time.Now()
+ body := []byte(`{"x":1}`)
+ sig := signHAControl(key, "betty", http.MethodPost, HADrainPath, "txn-1", now, body)
+ if !verifyHAControlEitherKey(key, nil, "betty", http.MethodPost, HADrainPath, "txn-1", sig, body, now) {
+ t.Fatal("a good signature did not verify")
+ }
+ if !verifyHAControlEitherKey(nil, key, "betty", http.MethodPost, HADrainPath, "txn-1", sig, body, now) {
+ t.Fatal("the next key did not verify")
+ }
+ for name, ok := range map[string]bool{
+ "receiver": verifyHAControlEitherKey(key, nil, "annie", http.MethodPost, HADrainPath, "txn-1", sig, body, now),
+ "method": verifyHAControlEitherKey(key, nil, "betty", http.MethodPut, HADrainPath, "txn-1", sig, body, now),
+ "path": verifyHAControlEitherKey(key, nil, "betty", http.MethodPost, HATakePath, "txn-1", sig, body, now),
+ "txn": verifyHAControlEitherKey(key, nil, "betty", http.MethodPost, HADrainPath, "txn-2", sig, body, now),
+ "body": verifyHAControlEitherKey(key, nil, "betty", http.MethodPost, HADrainPath, "txn-1", sig, []byte(`{"x":2}`), now),
+ "skew": verifyHAControlEitherKey(key, nil, "betty", http.MethodPost, HADrainPath, "txn-1", sig, body, now.Add(2*hopSkew)),
+ "hop": verifyHopEitherKey(key, nil, "betty", sig, now),
+ "notice": verifyBurstNoticeEitherKey(key, nil, "betty", sig, body, now),
+ } {
+ if ok {
+ t.Errorf("a signature verified with another %s", name)
+ }
+ }
+}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 204f7f800..e13ede322 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -166,8 +166,13 @@ type edgesFileView struct {
Capabilities json.RawMessage `json:"capabilities"`
HibernationConfigured json.RawMessage `json:"hibernation_configured"`
Draining json.RawMessage `json:"draining"`
- Role json.RawMessage `json:"role"`
- Headroom json.RawMessage `json:"headroom"`
+ // HADrained is a planned handover's last step (region HA §25.4 step
+ // 4): no lease names the box. Placement reads it as local-denied, and
+ // a fold that first sees it drops holder-cache entries naming the box
+ // (hadrain.go).
+ HADrained json.RawMessage `json:"ha_drained"`
+ Role json.RawMessage `json:"role"`
+ Headroom json.RawMessage `json:"headroom"`
// placementNull is an explicit "placement": null. The holder decoder
// reads it as "" as before; cold-wake placement refuses it, because an
// omitted or empty placement is the home scope and null is neither.
@@ -376,6 +381,13 @@ type homeMap struct {
hostsAge time.Duration
actedGen uint64
actedOK bool
+
+ // drainAcks remembers answered drain asks (hadrain.go). peerDrained is
+ // the edge's drained hook (nil: none), and drainedNoted, guarded by
+ // refreshMu, the generation of each drained file it last ran for.
+ drainAcks drainAcks
+ peerDrained func(ref string)
+ drainedNoted map[string]string
}
func newHomeMap(s release.Store, self string) *homeMap {
@@ -396,6 +408,7 @@ func (e *Edge) newHomeMap() *homeMap {
m.health = e.lbHealth
m.watch = e.changeWatch
m.departureTick = e.departureTick
+ m.peerDrained = e.runPeerDrained
return m
}
@@ -620,6 +633,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
wake := m.hostsWake
served := m.servedWake
m.mu.Unlock()
+ m.notePeerDrained(next)
// A partial read reflects no generation: the file it could not read or
// parse is retried on the next poll, as it always was.
m.lastHosts, m.hostsAge = m.clock(), jitteredBackstop()
diff --git a/internal/edge/wakeplacement.go b/internal/edge/wakeplacement.go
index 2733d684a..89a53dd1e 100644
--- a/internal/edge/wakeplacement.go
+++ b/internal/edge/wakeplacement.go
@@ -33,13 +33,16 @@ func placementField[T any](raw json.RawMessage, dst *T) bool {
func decodeWakePlacement(f edgesFileView) wakePlacementFields {
p := wakePlacementFields{valid: true}
role := "serve"
- var draining, drained bool
+ var draining, drained, haDrained bool
// Safety fields are read even when other evidence is invalid or stale.
+ // draining is the box-level drain state (region HA §25.4 step 1) and
+ // ha_drained its last step; drained is admission's.
roleOK := placementField(f.Role, &role)
drainingOK := placementField(f.Draining, &draining)
drainedOK := placementField(f.Drained, &drained)
- p.localDenied = !roleOK || !drainingOK || !drainedOK || role != "serve" || draining || drained || !f.HomeEligible()
- p.valid = roleOK && drainingOK && drainedOK
+ haDrainedOK := placementField(f.HADrained, &haDrained)
+ p.localDenied = !roleOK || !drainingOK || !drainedOK || !haDrainedOK || role != "serve" || draining || drained || haDrained || !f.HomeEligible()
+ p.valid = roleOK && drainingOK && drainedOK && haDrainedOK
p.valid = placementField(f.Generation, &p.generation) && p.valid
var capabilities []json.RawMessage
p.valid = placementField(f.Capabilities, &capabilities) && p.valid
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 5dd252a99..3568ec80d 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1203,6 +1203,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if act != nil {
act.SetHeldWakeHook(e.HeldWake)
if svc != nil {
+ // Planned-handover drain (region HA §25.4): this box's own
+ // state, peers' states from the edge's fold, and the
+ // holder-cache drop when a peer publishes drained.
+ svc.SetDrainingSource(boxDrain.IsDraining)
+ svc.SetPeerDrainView(e.PeerDraining)
+ e.SetPeerDrainedHook(svc.DropHoldersNaming)
svc.SetDutyView(func(rt registry.Route) boxchoice.WakeSnapshot {
if rt.IsSidecar() {
entry, ok := boxLifetimes.Lookup(rt.Host)
diff --git a/internal/host/dbreads.go b/internal/host/dbreads.go
index 777dc8a60..e9ee113ca 100644
--- a/internal/host/dbreads.go
+++ b/internal/host/dbreads.go
@@ -89,8 +89,8 @@ var dbReadsNudge = make(chan struct{}, 1)
// dbReadsDraining is the draining flag this box last published in its edges
// file, which the edges loop stores on every pass. The agent reads the same
// value the console's evidence rule reads, so the two never disagree (spec
-// §7.1). Nothing on main sets an edges file's Draining yet (region HA's
-// placer will); until then it is false.
+// §7.1). A planned handover's drain sets it (region HA §25.4 step 1,
+// hadrainstate.go); otherwise it is false.
var dbReadsDraining atomic.Bool
func nudgeDBReads() {
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index 0bb439c3b..67e92ec4d 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -284,6 +284,13 @@ type edgesFile struct {
Box string `json:"box"`
EIP string `json:"eip"`
Region string `json:"region,omitempty"`
+
+ // DrainSource receives each written file's drain state and generation
+ // (hadrainstate.go); DrainPublishRequired writes the file even when its
+ // body did not change, until the wanted drain state is reported.
+ DrainSource haDrainSource `json:"-"`
+ DrainPublishRequired bool `json:"-"`
+
// PrivateIP is the address an edge in this box's region dials (region
// HA spec 2 §6), and PrivateCIDR the region network that holds it,
// both validated by edgesfile.PrivateAddress before they are written.
@@ -378,8 +385,16 @@ type edgesFile struct {
// Capabilities gates multi-box regions (spec §8): "region-ha-1" once
// CARLOS_REGION_HA is on.
Capabilities []string `json:"capabilities,omitempty"`
- // Draining is set while the placer empties this box (spec 4).
+ // Draining is set while the placer empties this box (spec 4): a
+ // planned handover's drain state (region HA §25.4 step 1,
+ // hadrainstate.go). Every reader treats it as withdrawn from placement
+ // only; it is not admission's Drained above.
Draining bool `json:"draining,omitempty"`
+ // HADrained is the drain's last step (§25.4 step 4): no lease names this
+ // box. Published only while Draining. Additive: peers drop holder-cache
+ // entries naming the box when they fold it, and placement reads it as
+ // local-denied.
+ HADrained bool `json:"ha_drained,omitempty"`
// Headroom is what placement chooses by (spec 2). It is refreshed when
// the file is written for another reason and on the loop's own tick; a
// headroom change alone never forces a write (see edgesFileWrite).
@@ -1009,7 +1024,7 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re
return fmt.Errorf("edges: marshal: %w", err)
}
}
- if bytes.Equal(cmp, *last) && !(refresh && f.Headroom != nil) && !f.RolePublishRequired {
+ if bytes.Equal(cmp, *last) && !(refresh && f.Headroom != nil) && !f.RolePublishRequired && !f.DrainPublishRequired {
if assets != nil {
assets.passDone(clocks, settled, false, nil)
}
@@ -1028,6 +1043,9 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re
if f.RoleSource != nil {
f.RoleSource.EdgesPublished(f.BoxRole, *f.Admitted, *f.Drained)
}
+ if f.DrainSource != nil {
+ f.DrainSource.EdgesDrainPublished(f.Draining, f.HADrained, f.Generation)
+ }
if assets != nil {
assets.passDone(clocks, settled, true, f.Hosts)
}
@@ -1290,13 +1308,18 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy)
key = edgesChangeKey(key, pub.servingDigest())
}
roleIdent := snapshotBoxRole(ident)
- if !state.dueWithRole(now, key, err == nil, pub.rewriteDue(), roleIdent) {
+ // A wanted drain state not yet published is a pass on this tick
+ // (region HA §25.4), with the schedule's retry backoff.
+ drainDue := boxDrain.needsPublish()
+ if !state.dueWithRole(now, key, err == nil, pub.rewriteDue() || drainDue, roleIdent) {
continue
}
if state.timed() {
eip = readPublicIP()
}
ident.Capabilities = withDemoMovedCapability(withDBReadCapability(withOfflineCapability(baseCaps, armedOfflineCapable()), dbReadsCapable()), os.Getenv)
+ ident.Draining, ident.HADrained = boxDrain.want()
+ ident.DrainSource, ident.DrainPublishRequired = boxDrain, drainDue
dbReadsDraining.Store(ident.Draining)
ident.Headroom = headroomFor(headroomCapabilities(ident.Capabilities), dataDir, reg)
ident = withMovesFields(ident, dataDir, optDir)
diff --git a/internal/host/hadrainstate.go b/internal/host/hadrainstate.go
new file mode 100644
index 000000000..c316cce1b
--- /dev/null
+++ b/internal/host/hadrainstate.go
@@ -0,0 +1,133 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "sync"
+)
+
+// haDrainState is this box's planned-handover drain state (region HA spec
+// §25.4 steps 1 and 4): what the box wants its edges file to say, and what
+// the edges loop last published. The drain driver sets it; the edges loop
+// carries it through the existing publisher (edgesFileWriteClaims), which
+// reports each publication back with its generation, the value the driver's
+// acknowledgement asks name.
+//
+// draining is the edges file's existing box-level field, which every
+// placement reader already reads as withdrawn (§24 table in the Task 1
+// report): wake and duty placement (internal/edge wakeplacement.go), the
+// console's capacity count and choosers (boxchoice.Eligible), db-read
+// elections and forwarding. drained is published as the additive
+// ha_drained beside it, and implies draining. Neither is admission's
+// drained (box_role/admitted/drained), so name authority, admission and
+// holder reachability are unchanged.
+type haDrainState struct {
+ mu sync.Mutex
+ draining, drained bool
+ pub haDrainPublished
+ // changed is closed and replaced at every reported publication.
+ changed chan struct{}
+}
+
+// haDrainSource is what edgesFileWriteClaims reports a written file's drain
+// state to.
+type haDrainSource interface {
+ EdgesDrainPublished(draining, drained bool, generation string)
+}
+
+// haDrainPublished is what the edges loop last wrote.
+type haDrainPublished struct {
+ Draining, Drained bool
+ Generation string
+}
+
+func newHADrainState() *haDrainState {
+ return &haDrainState{changed: make(chan struct{})}
+}
+
+// boxDrain is this process's drain state. The activator reads IsDraining
+// (agent.go wires it); the edges loop publishes it.
+var boxDrain = newHADrainState()
+
+// setDraining sets or clears the drain state. Clearing it clears drained.
+// The next edges loop tick publishes the change.
+func (s *haDrainState) setDraining(on bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.draining = on
+ if !on {
+ s.drained = false
+ }
+}
+
+// setDrained sets or clears drained, which needs draining.
+func (s *haDrainState) setDrained(on bool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if on && !s.draining {
+ return errors.New("ha drain: drained without draining")
+ }
+ s.drained = on
+ return nil
+}
+
+// IsDraining is whether this box is in the drain state now, published or
+// not: it places nothing on itself from the moment the state is set.
+func (s *haDrainState) IsDraining() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.draining
+}
+
+// want is the state the edges file should carry.
+func (s *haDrainState) want() (draining, drained bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.draining, s.drained
+}
+
+// needsPublish is whether the wanted state has not been reported published:
+// it differs from the last publication, or it is a drain state no
+// publication of this process has reported. The edges loop then runs a pass
+// and writes the file even if its body did not change.
+func (s *haDrainState) needsPublish() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.draining != s.pub.Draining || s.drained != s.pub.Drained || (s.draining && s.pub.Generation == "")
+}
+
+// EdgesDrainPublished is the edges loop's report of a written file.
+func (s *haDrainState) EdgesDrainPublished(draining, drained bool, generation string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.pub = haDrainPublished{Draining: draining, Drained: drained, Generation: generation}
+ close(s.changed)
+ s.changed = make(chan struct{})
+}
+
+// published is the last reported publication.
+func (s *haDrainState) published() haDrainPublished {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.pub
+}
+
+// waitPublished waits until the wanted state is published and returns that
+// publication's generation, the one a drain acknowledgement names.
+func (s *haDrainState) waitPublished(ctx context.Context) (string, error) {
+ for {
+ s.mu.Lock()
+ if s.draining == s.pub.Draining && s.drained == s.pub.Drained && s.pub.Generation != "" {
+ gen := s.pub.Generation
+ s.mu.Unlock()
+ return gen, nil
+ }
+ ch := s.changed
+ s.mu.Unlock()
+ select {
+ case <-ch:
+ case <-ctx.Done():
+ return "", ctx.Err()
+ }
+ }
+}
diff --git a/internal/host/hadrainstate_test.go b/internal/host/hadrainstate_test.go
new file mode 100644
index 000000000..9a7250065
--- /dev/null
+++ b/internal/host/hadrainstate_test.go
@@ -0,0 +1,157 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The drain state's transitions: drained needs draining, clearing draining
+// clears drained, and IsDraining follows the wanted state at once.
+func TestHADrainStateTransitions(t *testing.T) {
+ s := newHADrainState()
+ if s.IsDraining() || s.needsPublish() {
+ t.Fatal("a new state drains")
+ }
+ if err := s.setDrained(true); err == nil {
+ t.Fatal("drained without draining")
+ }
+ s.setDraining(true)
+ if !s.IsDraining() || !s.needsPublish() {
+ t.Fatal("draining not wanted")
+ }
+ if err := s.setDrained(true); err != nil {
+ t.Fatal(err)
+ }
+ if d, dd := s.want(); !d || !dd {
+ t.Fatalf("want %v %v", d, dd)
+ }
+ s.setDraining(false)
+ if d, dd := s.want(); d || dd || s.IsDraining() {
+ t.Fatalf("cleared state still wants %v %v", d, dd)
+ }
+}
+
+// The existing publisher carries the state: the box-level draining field
+// and ha_drained, each change written and reported with its generation, and
+// a wanted state not yet reported forces a write even when the body did not
+// change (the seeded gate after a restart).
+func TestHADrainPublishedThroughEdgesFile(t *testing.T) {
+ ctx := context.Background()
+ st := release.NewDirStore(t.TempDir())
+ reg := edgesTestRegistry(t)
+ seedRoute(t, reg, "shop.example.com")
+ drain := newHADrainState()
+ pass := func(last *[]byte) map[string]json.RawMessage {
+ t.Helper()
+ ident := edgesFile{Box: "box", DrainSource: drain}
+ ident.Draining, ident.HADrained = drain.want()
+ ident.DrainPublishRequired = drain.needsPublish()
+ if err := edgesFilePass(ctx, st, reg, ident, "203.0.113.1", last); err != nil {
+ t.Fatal(err)
+ }
+ body, _, err := st.Get(ctx, edgesFileKey("box"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]json.RawMessage
+ if err := json.Unmarshal(body, &f); err != nil {
+ t.Fatal(err)
+ }
+ return f
+ }
+ var last []byte
+ f := pass(&last)
+ if _, ok := f["draining"]; ok {
+ t.Fatalf("a box not draining published draining: %s", f["draining"])
+ }
+ if _, ok := f["ha_drained"]; ok {
+ t.Fatal("a box not draining published ha_drained")
+ }
+ drain.setDraining(true)
+ f = pass(&last)
+ p := drain.published()
+ if string(f["draining"]) != "true" || !p.Draining || p.Drained || p.Generation == "" || `"`+p.Generation+`"` != string(f["generation"]) {
+ t.Fatalf("draining publication %+v, file %s %s", p, f["draining"], f["generation"])
+ }
+ if drain.needsPublish() {
+ t.Fatal("a published state still needs publishing")
+ }
+ if err := drain.setDrained(true); err != nil {
+ t.Fatal(err)
+ }
+ f = pass(&last)
+ if p = drain.published(); string(f["ha_drained"]) != "true" || string(f["draining"]) != "true" || !p.Drained {
+ t.Fatalf("drained publication %+v, file %s", p, f["ha_drained"])
+ }
+ // A restarted publisher whose gate is seeded from a file that already
+ // says draining still reports, so a driver waiting on it is answered.
+ seeded := seedEdgesFileGate(ctx, st, "box")
+ fresh := newHADrainState()
+ fresh.setDraining(true)
+ if err := fresh.setDrained(true); err != nil {
+ t.Fatal(err)
+ }
+ drain = fresh
+ pass(&seeded)
+ if p := fresh.published(); !p.Draining || !p.Drained || p.Generation == "" {
+ t.Fatalf("a seeded gate swallowed the publication: %+v", p)
+ }
+}
+
+// waitPublished returns the generation once the wanted state is reported,
+// and gives up with its context.
+func TestHADrainWaitPublished(t *testing.T) {
+ s := newHADrainState()
+ s.setDraining(true)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if _, err := s.waitPublished(ctx); !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("unpublished wait: %v", err)
+ }
+ done := make(chan string, 1)
+ go func() {
+ gen, err := s.waitPublished(context.Background())
+ if err != nil {
+ t.Error(err)
+ }
+ done <- gen
+ }()
+ time.Sleep(10 * time.Millisecond)
+ s.EdgesDrainPublished(true, false, "2026-11-08T12:00:00Z")
+ select {
+ case gen := <-done:
+ if gen != "2026-11-08T12:00:00Z" {
+ t.Fatalf("generation %q", gen)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("waitPublished did not return")
+ }
+}
+
+// A wanted state not yet published makes the loop's next tick a pass,
+// whatever the registry and timer say; once published it does not.
+func TestHADrainForcesAPass(t *testing.T) {
+ start := time.Date(2026, 11, 8, 9, 0, 0, 0, time.UTC)
+ state := &edgesLoopState{sched: newEdgesFileSchedule(start, func() time.Duration { return 5 * time.Minute })}
+ drain := newHADrainState()
+ clock := start.Add(2 * time.Second)
+ if state.dueWithRole(clock, "fp", true, drain.needsPublish(), edgesFile{}) {
+ t.Fatal("due with nothing to publish")
+ }
+ drain.setDraining(true)
+ clock = clock.Add(2 * time.Second)
+ if !state.dueWithRole(clock, "fp", true, drain.needsPublish(), edgesFile{}) {
+ t.Fatal("a wanted drain state did not make the tick a pass")
+ }
+ state.done(clock, true)
+ drain.EdgesDrainPublished(true, false, "2026-11-08T09:00:04Z")
+ clock = clock.Add(2 * time.Second)
+ if state.dueWithRole(clock, "fp", true, drain.needsPublish(), edgesFile{}) {
+ t.Fatal("due after the state was published")
+ }
+}