carlos / platform Public

region HA: the take request, so a successor acquires a released host

A draining box asks a successor, with a signed POST to /.carlos/ha-take,
to acquire and wake a host whose lease it has just released (spec §25.7).
The receiver refuses unless it serves the host's pool, is admitted, is
not draining, and classifies the host as HA with the named lifetime. It
then runs the ordinary wake, whose acquire is hafresh.DecideAcquire, so
the take authorizes nothing the acquire table does not; it never
forwards and answers within the wake wait bound with the owner the
acquire read or wrote and the lock's generation.

- edge: hatake.go (receiver and the Take client for the drain driver),
  serveHAControl dispatches by path under the control signature, and a
  take transport whose header timeout outlasts a wake; ha_take read
  from edges files, and takes go only to a box that says ha_take: 1.
- activator: Service.TakeHost; errLeaseHeld carries the held lock's
  generation (lease.HeldError.Generation, additive).
- host: HA boxes publish ha_take: 1 (additive, omitempty).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 171c1024758cc57ba375e35055849d773b9eccd1 parent 3099980
14 files changed, +1,155 −10
  • internal/activator/activator.go +2 −0
  • internal/activator/hatake.go +105 −0
  • internal/activator/hatake_test.go +341 −0
  • internal/activator/hawake.go +1 −1
  • internal/edge/edge.go +4 −1
  • internal/edge/hadrain.go +10 −5
  • internal/edge/hadrain_test.go +18 −1
  • internal/edge/hatake.go +296 −0
  • internal/edge/hatake_test.go +324 −0
  • internal/edge/homemap.go +5 −1
  • internal/host/edgesfile.go +10 −0
  • internal/host/edgesfile_test.go +35 −0
  • internal/lease/ha.go +1 −1
  • internal/lease/lease.go +3 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index fb160a889..cb1c8eeb4 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1218,6 +1218,8 @@ var wakeBoundExtended func()
type errLeaseHeld struct {
holder string
retryAfter time.Duration
+ // gen is the held lock's generation, when the HA acquire read it.
+ gen int64
}
func (e *errLeaseHeld) Error() string {
diff --git a/internal/activator/hatake.go b/internal/activator/hatake.go
new file mode 100644
index 000000000..82a884020
--- /dev/null
+++ b/internal/activator/hatake.go
@@ -0,0 +1,105 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The take request's receiver, the activator's half (region HA spec §25.7;
+// the edge's half is internal/edge/hatake.go). A draining box has released
+// a host as a release marker and asks this box to acquire and wake it.
+//
+// The take is a forwarded wake without a visitor. It runs this box's own
+// checks, then the ordinary wake (begin), whose acquire is the HA acquire
+// and so hafresh.DecideAcquire (I1). Nothing here reads or writes the lock
+// itself, and nothing the request carries is an input to the acquire: the
+// marker generation it names is reported, never trusted. A lock in any
+// state other than that marker gets the normal acquire decision. begin
+// never forwards, and bounds its wait by wakeWaitBound.
+
+var _ edge.HATaker = (*Service)(nil)
+
+// takeBackend is the backend's half of a take: the host's lifetime, from
+// the one HA classification (isHA), and the generation its last HA acquire
+// wrote. The exec backend has it; a backend without it takes nothing.
+type takeBackend interface {
+ haTakeLifetime(ctx context.Context, rt registry.Route) (lifetime string, ha bool, err error)
+ haAcquiredGeneration(host string) (int64, bool)
+}
+
+func takeBackendFor(b Backend, rt registry.Route) takeBackend {
+ switch b := b.(type) {
+ case *SplitBackend:
+ return takeBackendFor(b.pick(rt), rt)
+ case takeBackend:
+ return b
+ }
+ return nil
+}
+
+func (b *ExecBackend) haTakeLifetime(ctx context.Context, rt registry.Route) (string, bool, error) {
+ e, ha, err := b.isHA(ctx, rt)
+ return e.ID, ha, err
+}
+
+// haAcquiredGeneration is the generation host's last HA acquire wrote: one
+// past the lock it classified, or 1 over an absent lock (the lease
+// package's classifyAndTake). Renewals keep it.
+func (b *ExecBackend) haAcquiredGeneration(host string) (int64, bool) {
+ w, ok := b.haAcquired(host)
+ if !ok {
+ return 0, false
+ }
+ if w.view.Absent {
+ return 1, true
+ }
+ return w.view.Lock.Generation + 1, true
+}
+
+// TakeHost is the receiver's take of rt (edge.HATaker). It refuses, before
+// any lock request, unless this box serves rt's pool, is admitted (an
+// admission exemption does not count), is not draining, and classifies rt
+// as HA (isHA, the one classification) with the lifetime the take names:
+// a host only marked HA, with no lifetime, has no valid record. Then it wakes rt as a request
+// would, without counting activity, and answers the owner the acquire read
+// or wrote: this box at the generation it wrote, another box that holds
+// the lease at the generation the acquire read, or none with the reason.
+func (a *Service) TakeHost(ctx context.Context, rt registry.Route, lifetime string, markerGen int64) edge.TakeAnswer {
+ tb := takeBackendFor(a.backend, rt)
+ self, _ := boxSelfRef(a.backend)
+ switch {
+ case tb == nil || self == "":
+ return edge.TakeAnswer{Refused: edge.TakeRefusedNoRoute}
+ case !a.LocalEligible(rt):
+ return edge.TakeAnswer{Refused: edge.TakeRefusedPool}
+ case !a.TenantAdmitted():
+ return edge.TakeAnswer{Refused: edge.TakeRefusedAdmission}
+ case a.IsDraining():
+ return edge.TakeAnswer{Refused: edge.TakeRefusedDraining}
+ }
+ got, ha, err := tb.haTakeLifetime(ctx, rt)
+ if err != nil || !ha || got == "" || got != lifetime {
+ return edge.TakeAnswer{Refused: edge.TakeRefusedRecord}
+ }
+ release, err := a.begin(ctx, rt, false, nil)
+ if err == nil {
+ release()
+ gen, ok := tb.haAcquiredGeneration(rt.Host)
+ if !ok {
+ return edge.TakeAnswer{Reason: "the host is awake here without an HA lease"}
+ }
+ return edge.TakeAnswer{Holder: self, Gen: gen}
+ }
+ var held *errLeaseHeld
+ if errors.As(err, &held) {
+ if o, ok := hafresh.ParseOwner(held.holder); ok && o.HA && o.Ref != "" && o.Ref != self {
+ return edge.TakeAnswer{Holder: o.Ref, Gen: held.gen}
+ }
+ }
+ return edge.TakeAnswer{Reason: fmt.Sprintf("the wake failed (marker generation %d): %v", markerGen, err)}
+}
diff --git a/internal/activator/hatake_test.go b/internal/activator/hatake_test.go
new file mode 100644
index 000000000..9b0c117cd
--- /dev/null
+++ b/internal/activator/hatake_test.go
@@ -0,0 +1,341 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The take request's receiver (hatake.go; region HA §25.7). The scene is
+// haService: a real Service over the production exec backend and the real
+// HA lease against the lock fixture. This box is "a" (i-a); the draining
+// box that released the host is "x".
+
+// takeMarker is x's clean release marker at generation gen, for lifetime.
+func takeMarker(t *testing.T, lifetime string, gen int64) []byte {
+ t.Helper()
+ body, err := hafresh.MarkerBody(gen, hafresh.Marker{V: 1, Box: "x", IID: "i-x", Lifetime: lifetime, TXID: 3, Clean: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return body
+}
+
+// heldLock is owner's HA lease at gen, expiring at expires.
+func heldLock(t *testing.T, owner string, gen int64, expires time.Time) []byte {
+ t.Helper()
+ body, err := json.Marshal(hafresh.Lock{Generation: gen, ExpiresAt: expires.UTC(), Owner: owner})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return body
+}
+
+// lockReqs is every fixture request about s's host's lock, in order.
+func (s *haSvc) lockReqs() []string {
+ var out []string
+ for _, r := range s.fx.Requests() {
+ if strings.HasSuffix(r, " "+lockKeyOf(s.b, s.rt)) || strings.HasPrefix(r, "LIST "+s.b.Cfg.hibernatePrefix(s.rt.Host)) {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+func (s *haSvc) lockNow(t *testing.T) hafresh.Lock {
+ t.Helper()
+ v, err := hafresh.DecodeLock(lockBodyOf(s.b, s.rt), "x")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v.Lock
+}
+
+func (s *haSvc) awake() bool {
+ s.a.mu.Lock()
+ defer s.a.mu.Unlock()
+ e := s.a.entries[s.rt.Host]
+ return e != nil && e.state == actAwake
+}
+
+func (s *haSvc) lifetime() string { return haFixOf(s.b).lifetime }
+
+// The marker the take names: this box acquires it through the HA acquire,
+// wakes the host, and names itself at the generation it wrote. One take
+// costs exactly one lock GET and one conditional PUT, and no record read.
+func TestTakeTheNamedMarker(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ putLockFor(t, s.b, s.rt, takeMarker(t, s.lifetime(), 6))
+ recordsBefore := recordGets(s.b)
+ logs := captureLog(t)
+ ans := s.a.TakeHost(context.Background(), s.rt, s.lifetime(), 6)
+ if ans != (edge.TakeAnswer{Holder: "a", Gen: 7}) {
+ t.Fatalf("take: %+v, want a at generation 7", ans)
+ }
+ if !s.awake() {
+ t.Fatal("the host is not awake after the take")
+ }
+ l := s.lockNow(t)
+ if o, ok := hafresh.ParseOwner(l.Owner); !ok || o.Ref != "a" || !o.HA || l.Generation != 7 || l.Release != nil {
+ t.Fatalf("the lock is %+v, want a's HA lease at generation 7", l)
+ }
+ if got := s.lockReqs(); len(got) != 2 || !strings.HasPrefix(got[0], "GET ") || !strings.HasPrefix(got[1], "PUT ") {
+ t.Fatalf("lock requests %v, want exactly one GET and one PUT", got)
+ }
+ if n := recordGets(s.b) - recordsBefore; n != 0 {
+ t.Fatalf("the take read the record %d times, want 0 (the lifetime index answers)", n)
+ }
+ if spawns(s.b) == 0 {
+ t.Fatal("nothing was started")
+ }
+ if !strings.Contains(logs.String(), "(clean marker)") {
+ t.Fatalf("the acquire did not take the marker:\n%s", logs)
+ }
+ // Activity: a take is no visitor's request.
+ s.a.mu.Lock()
+ e := s.a.entries[s.rt.Host]
+ inflight := e.inflight
+ s.a.mu.Unlock()
+ if inflight != 0 {
+ t.Fatalf("in flight after the take = %d, want 0", inflight)
+ }
+ // A second take of a host awake here answers at once, from memory, and
+ // is not activity: the idle clock is not reset.
+ s.a.mu.Lock()
+ active := e.lastActive
+ s.a.mu.Unlock()
+ clk := &fakeClock{t: time.Now().Add(time.Hour)}
+ s.a.now = clk.now
+ before := len(s.fx.Requests())
+ if again := s.a.TakeHost(context.Background(), s.rt, s.lifetime(), 6); again != ans {
+ t.Fatalf("a second take: %+v, want %+v", again, ans)
+ }
+ if n := len(s.fx.Requests()) - before; n != 0 {
+ t.Fatalf("a second take made %d store requests, want 0", n)
+ }
+ s.a.mu.Lock()
+ after := e.lastActive
+ s.a.mu.Unlock()
+ if !after.Equal(active) {
+ t.Fatalf("a take reset the idle clock: %s, then %s", active, after)
+ }
+}
+
+// Every lock state other than the named marker gets the normal acquire
+// decision (hafresh.DecideAcquire): the take authorizes nothing more.
+func TestTakeOtherLockStatesGetTheAcquireTable(t *testing.T) {
+ future, past := time.Now().Add(time.Minute), time.Now().Add(-time.Minute)
+ for name, tc := range map[string]struct {
+ lock func(s *haSvc) []byte // nil: absent
+ markerGen int64
+ want edge.TakeAnswer
+ wantWrite bool
+ reason string
+ }{
+ "another marker generation": {
+ lock: func(s *haSvc) []byte { return takeMarker(t, s.lifetime(), 11) },
+ markerGen: 6, want: edge.TakeAnswer{Holder: "a", Gen: 12}, wantWrite: true,
+ },
+ "no marker, absent": {
+ lock: nil, markerGen: 6, want: edge.TakeAnswer{Holder: "a", Gen: 1}, wantWrite: true,
+ },
+ "held by a third box": {
+ lock: func(*haSvc) []byte { return heldLock(t, "box/v1;ref=c;iid=i-c;pid=7;ha=1", 7, future) },
+ markerGen: 6, want: edge.TakeAnswer{Holder: "c", Gen: 7},
+ },
+ "held by the draining box, unreleased": {
+ lock: func(*haSvc) []byte { return heldLock(t, "box/v1;ref=x;iid=i-x;pid=7;ha=1", 6, future) },
+ markerGen: 6, want: edge.TakeAnswer{Holder: "x", Gen: 6},
+ },
+ // The named generation, but not a marker: expiry alone never lets
+ // another box acquire, whatever the take says.
+ "another box's expired lease at the named generation": {
+ lock: func(*haSvc) []byte { return heldLock(t, "box/v1;ref=x;iid=i-x;pid=7;ha=1", 6, past) },
+ markerGen: 6, reason: hafresh.ReasonOtherExpired,
+ },
+ "a leftover legacy lock": {
+ lock: func(*haSvc) []byte { return heldLock(t, "x/123", 6, past) },
+ markerGen: 6, reason: hafresh.ReasonLeftoverLock,
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ var before []byte
+ if tc.lock != nil {
+ before = tc.lock(s)
+ putLockFor(t, s.b, s.rt, before)
+ }
+ ans := s.a.TakeHost(context.Background(), s.rt, s.lifetime(), tc.markerGen)
+ if tc.reason != "" {
+ if ans.Holder != "" || ans.Refused != "" || !strings.Contains(ans.Reason, tc.reason) {
+ t.Fatalf("take: %+v, want no holder for %q", ans, tc.reason)
+ }
+ } else if ans != tc.want {
+ t.Fatalf("take: %+v, want %+v", ans, tc.want)
+ }
+ wrote := false
+ for _, r := range s.lockReqs() {
+ if strings.HasPrefix(r, "PUT ") || strings.HasPrefix(r, "DELETE ") {
+ wrote = true
+ }
+ }
+ if wrote != tc.wantWrite {
+ t.Fatalf("lock writes %v (%v), want writes %v", s.lockReqs(), wrote, tc.wantWrite)
+ }
+ if !tc.wantWrite && string(lockBodyOf(s.b, s.rt)) != string(before) {
+ t.Fatalf("the lock changed: %s", lockBodyOf(s.b, s.rt))
+ }
+ if s.awake() != tc.wantWrite {
+ t.Fatalf("awake %v, want %v", s.awake(), tc.wantWrite)
+ }
+ })
+ }
+}
+
+// A third box wins the marker between this box's read and its write: the
+// conditional PUT fails, the re-read finds the winner's lease, and the
+// answer names the winner at its generation.
+func TestTakeThirdBoxWinsTheRace(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ putLockFor(t, s.b, s.rt, takeMarker(t, s.lifetime(), 6))
+ winner := heldLock(t, "box/v1;ref=c;iid=i-c;pid=9;ha=1", 7, time.Now().Add(time.Minute))
+ var once sync.Once
+ key := lockKeyOf(s.b, s.rt)
+ s.fx.BeforeWrite(func(_, k string) {
+ if k == key {
+ once.Do(func() { putLockFor(t, s.b, s.rt, winner) })
+ }
+ })
+ ans := s.a.TakeHost(context.Background(), s.rt, s.lifetime(), 6)
+ if ans != (edge.TakeAnswer{Holder: "c", Gen: 7}) {
+ t.Fatalf("take: %+v, want c at generation 7", ans)
+ }
+ if string(lockBodyOf(s.b, s.rt)) != string(winner) {
+ t.Fatalf("the winner's lease was overwritten: %s", lockBodyOf(s.b, s.rt))
+ }
+ if s.awake() {
+ t.Fatal("the losing box woke the host")
+ }
+ // GET, the PUT that lost, the re-read: no second write.
+ if got := s.lockReqs(); len(got) != 3 {
+ t.Fatalf("lock requests %v, want GET, PUT, GET", got)
+ }
+}
+
+// Each refusal is made before any lock request, and nothing wakes.
+func TestTakeRefusals(t *testing.T) {
+ for name, tc := range map[string]struct {
+ set func(s *haSvc)
+ lifetime func(s *haSvc) string
+ want string
+ }{
+ "not in the host's pool": {
+ set: func(s *haSvc) {
+ s.b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[]`) }
+ },
+ want: edge.TakeRefusedPool,
+ },
+ "not admitted": {
+ set: func(s *haSvc) { s.a.TenantAdmittedFunc = func() bool { return false } },
+ want: edge.TakeRefusedAdmission,
+ },
+ "admission exempt is still not admitted": {
+ set: func(s *haSvc) {
+ s.a.TenantAdmittedFunc = func() bool { return false }
+ s.a.TenantExempt = func(registry.Route) bool { return true }
+ },
+ want: edge.TakeRefusedAdmission,
+ },
+ "draining": {
+ set: func(s *haSvc) { s.a.SetDrainingSource(func() bool { return true }) },
+ want: edge.TakeRefusedDraining,
+ },
+ "another lifetime": {
+ lifetime: func(*haSvc) string { return "L-other" },
+ want: edge.TakeRefusedRecord,
+ },
+ "no record": {
+ set: func(s *haSvc) {
+ s.b.Lifetimes = &provision.LifetimeIndex{}
+ h := haFixOf(s.b)
+ h.mu.Lock()
+ delete(h.records, s.rt.Host)
+ h.mu.Unlock()
+ },
+ want: edge.TakeRefusedRecord,
+ },
+ "the record cannot be read": {
+ set: func(s *haSvc) {
+ s.b.Lifetimes = &provision.LifetimeIndex{}
+ failRecordReads(s.b)
+ },
+ want: edge.TakeRefusedRecord,
+ },
+ "a legacy route": {
+ set: func(s *haSvc) { s.rt.Provisioned = false },
+ want: edge.TakeRefusedRecord,
+ },
+ "a record that is not HA": {
+ set: func(s *haSvc) {
+ s.b.Lifetimes = &provision.LifetimeIndex{}
+ h := haFixOf(s.b)
+ h.mu.Lock()
+ h.records[s.rt.Host] = haRecord(s.rt.Host, false)
+ h.mu.Unlock()
+ },
+ want: edge.TakeRefusedRecord,
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ putLockFor(t, s.b, s.rt, takeMarker(t, s.lifetime(), 6))
+ lifetime := s.lifetime()
+ if tc.set != nil {
+ tc.set(s)
+ }
+ if tc.lifetime != nil {
+ lifetime = tc.lifetime(s)
+ }
+ ans := s.a.TakeHost(context.Background(), s.rt, lifetime, 6)
+ if ans.Refused != tc.want || ans.Holder != "" {
+ t.Fatalf("take: %+v, want refused %q", ans, tc.want)
+ }
+ if got := s.lockReqs(); len(got) != 0 {
+ t.Fatalf("a refused take made lock requests %v", got)
+ }
+ if s.awake() || spawns(s.b) != 0 {
+ t.Fatal("a refused take woke the host")
+ }
+ })
+ }
+}
+
+// A wake that fails names no holder, and the answer comes within the wake
+// wait bound.
+func TestTakeWithinTheWakeBound(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ putLockFor(t, s.b, s.rt, takeMarker(t, s.lifetime(), 6))
+ old := wakeWaitBound
+ wakeWaitBound = 200 * time.Millisecond
+ t.Cleanup(func() { wakeWaitBound = old })
+ release := make(chan struct{})
+ t.Cleanup(func() { close(release) })
+ s.ctl.onStart = func() { <-release }
+ began := time.Now()
+ ans := s.a.TakeHost(context.Background(), s.rt, s.lifetime(), 6)
+ if took := time.Since(began); took > 2*time.Second {
+ t.Fatalf("the take answered after %s", took)
+ }
+ if ans.Holder != "" || ans.Refused != "" || !strings.Contains(ans.Reason, errWakeTimeout.Error()) {
+ t.Fatalf("take: %+v, want no holder: the wake timed out", ans)
+ }
+}
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index b21afa856..5f06f3fae 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -304,7 +304,7 @@ func leaseError(err error) error {
if retry < time.Second {
retry = time.Second
}
- return &errLeaseHeld{holder: he.Owner, retryAfter: retry}
+ return &errLeaseHeld{holder: he.Owner, retryAfter: retry, gen: he.Generation}
}
var re *lease.RefusedError
if errors.As(err, &re) {
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 64946d7ed..61e2da5ee 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -371,7 +371,10 @@ type Edge struct {
// backhaul target, and keying per host would let a stranger's stream of
// invented hostnames grow this map without limit.
backhaulTransports sync.Map
- backhaulHolders backhaulHolderCache
+ // takeTransports is the take requests' own transports, per dial
+ // address (hatake.go).
+ takeTransports sync.Map
+ backhaulHolders backhaulHolderCache
// forwardTransports is the same for region HA forwards (forwardha.go),
// keyed by the holder's dial address: their own cache, with their own
// 2 s connect bound, so backhaulTo's transports never change.
diff --git a/internal/edge/hadrain.go b/internal/edge/hadrain.go
index 7364e6dd4..9d9b646b2 100644
--- a/internal/edge/hadrain.go
+++ b/internal/edge/hadrain.go
@@ -39,8 +39,8 @@ import (
// store read. A refresh that fails, or a fold holding another publication,
// 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
+// Both control paths, HADrainPath and HATakePath (§25.7, hatake.go), 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
@@ -189,7 +189,8 @@ func refuseHAControl(w http.ResponseWriter) {
// 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 {
+ p := r.URL.Path
+ if r.Method != http.MethodPost || (p != HADrainPath && p != HATakePath) || len(auth) != 1 || len(txns) != 1 {
w.Header().Set("Connection", "close")
refuseHAControl(w)
return
@@ -219,11 +220,15 @@ func (e *Edge) serveHAControl(w http.ResponseWriter, r *http.Request) {
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))
+ if !haControlField(txn) || !verifyHAControlEitherKey(current, next, e.box, r.Method, p, txn, auth[0], body, time.Now()) {
+ e.logThrottled("ha-control-refused "+p, fmt.Sprintf("%s request from %s refused (signature)", p, r.RemoteAddr))
refuseHAControl(w)
return
}
+ if p == HATakePath {
+ e.serveHATake(w, r, txn, body)
+ return
+ }
var ask haDrainAsk
if json.Unmarshal(body, &ask) != nil || ask.Txn != txn || !haControlField(ask.From) || ask.From == e.box || ask.ID == 0 ||
(ask.Phase != DrainPhaseDraining && ask.Phase != DrainPhaseDrained) {
diff --git a/internal/edge/hadrain_test.go b/internal/edge/hadrain_test.go
index 1c6ad365c..84f619924 100644
--- a/internal/edge/hadrain_test.go
+++ b/internal/edge/hadrain_test.go
@@ -96,6 +96,8 @@ type drainScene struct {
// view makes every file a holder-view peer: one data bucket and key,
// and a fresh generation.
view bool
+ // extra is more fields for a box's file, by box.
+ extra map[string]map[string]any
}
func newDrainScene(t *testing.T) *drainScene {
@@ -104,6 +106,13 @@ func newDrainScene(t *testing.T) *drainScene {
// 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()
+ return s.addWith(t, box, ip, host, region, nil)
+}
+
+// addWith is add with act as the box's activator and extra routes in its
+// registry.
+func (s *drainScene) addWith(t *testing.T, box, ip, host, region string, act Activator, extra ...registry.Route) *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) {
@@ -114,10 +123,15 @@ func (s *drainScene) add(t *testing.T, box, ip, host, region string) *drainBox {
}))
t.Cleanup(backend.Close)
x.store = &drainStore{Store: release.NewDirStore(s.bucket)}
- be := &backhaulEdge{store: x.store, reg: openReg(t), box: box}
+ be := &backhaulEdge{store: x.store, reg: openReg(t), box: box, act: act}
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)
}
+ for _, rt := range extra {
+ if err := be.reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
be.local = autocert.DirCache(t.TempDir())
tlsCfg := be.boot(t)
x.be = be
@@ -164,6 +178,9 @@ func (s *drainScene) fileHosts(t *testing.T, x *drainBox, gen time.Time, p drain
if p.id != 0 {
f["ha_drain"] = map[string]any{"txn": "txn-1", "id": p.id}
}
+ for k, v := range s.extra[x.box] {
+ f[k] = v
+ }
b, err := json.Marshal(f)
if err != nil {
t.Fatal(err)
diff --git a/internal/edge/hatake.go b/internal/edge/hatake.go
new file mode 100644
index 000000000..b4a2db36b
--- /dev/null
+++ b/internal/edge/hatake.go
@@ -0,0 +1,296 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The take request (region HA spec §25.7, §25.4 step 3.4). A draining box
+// A has released host H (its lease is now a release marker) and asks a
+// successor B, with a signed POST to HATakePath, to acquire and wake H.
+// The request names the host, its lifetime, the marker's generation and
+// the drain transaction. B:
+//
+// - refuses unless it serves H's pool, is admitted, is not draining, and
+// holds a valid record for H with that lifetime;
+// - runs the ordinary HA acquire (hafresh.DecideAcquire, I1) through the
+// activator's own wake, and never forwards. A lock in any state other
+// than that marker gets the normal acquire decision: the take
+// authorizes nothing the acquire table does not already allow;
+// - answers once H is awake or the wake has failed, within the wake wait
+// bound, with the owner it read or wrote in lock.json: itself, another
+// box (held), or none, and the lock's generation.
+//
+// A take is a forwarded wake without a visitor: it is answered before any
+// route, so it makes no request record, usage or analytics, and it is
+// never handed to an app. The request carries the control paths' own
+// signature (hadrain.go), bound to the receiver, method, path, transaction,
+// timestamp and body, and its body is bounded at 4 KiB.
+
+// TakeAnswer is a take receiver's answer.
+type TakeAnswer struct {
+ // Holder is the box lock.json names as the host's owner after the
+ // acquire: the receiver, or another box that holds it. "" is none.
+ Holder string
+ // Gen is that lock's generation, 0 with no holder.
+ Gen int64
+ // Refused is set when the receiver refused before any acquire: one of
+ // the TakeRefused reasons.
+ Refused string
+ // Reason says why there is no holder.
+ Reason string
+}
+
+// The receiver's refusals, made before any lock request.
+const (
+ TakeRefusedNoTaker = "no_taker"
+ TakeRefusedNoRoute = "no_route"
+ TakeRefusedPool = "pool"
+ TakeRefusedAdmission = "admission"
+ TakeRefusedDraining = "draining"
+ TakeRefusedRecord = "record"
+)
+
+// HATaker is the activator's half of a take. The edge finds it on its
+// Activator with a type assertion; without it every take is refused.
+type HATaker interface {
+ // TakeHost runs the receiver's checks, then the ordinary wake of rt,
+ // which acquires through the HA acquire, and answers the owner.
+ TakeHost(ctx context.Context, rt registry.Route, lifetime string, markerGen int64) TakeAnswer
+}
+
+const (
+ // haTakeServeBound bounds a take on the receiver: the activator's wake
+ // wait bound (30 s), with room for the checks.
+ haTakeServeBound = 35 * time.Second
+ // haTakeAskTimeout bounds one take on the asker, dial to answer. It
+ // outlasts the receiver's bound, so a slow wake is answered, not cut.
+ haTakeAskTimeout = 40 * time.Second
+ // haTakeMaxHost bounds the host a take names.
+ haTakeMaxHost = 253
+ // haTakeMaxReason bounds the reason an answer carries.
+ haTakeMaxReason = 512
+ // takeNone is the answer's holder when there is none.
+ takeNone = "none"
+)
+
+// haTakeAsk is the take request's JSON body.
+type haTakeAsk struct {
+ From string `json:"from"`
+ Txn string `json:"txn"`
+ Host string `json:"host"`
+ Lifetime string `json:"lifetime"`
+ MarkerGen int64 `json:"marker_gen"`
+}
+
+// haTakeAnswer is the answer's JSON body.
+type haTakeAnswer struct {
+ Holder string `json:"holder"`
+ Gen int64 `json:"gen"`
+ Refused string `json:"refused,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+// haTakeHost is a hostname a take may name: lower-case letters, digits,
+// dots and hyphens, bounded.
+func haTakeHost(s string) bool {
+ if s == "" || len(s) > haTakeMaxHost {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '.' || c == '-') {
+ return false
+ }
+ }
+ return true
+}
+
+// takeHook is a test seam, nil in production: called with every take this
+// edge hands to its activator.
+var takeHook func(host string)
+
+// serveHATake answers a verified take (serveHAControl has checked the
+// method, the path, the signature and the transaction header).
+func (e *Edge) serveHATake(w http.ResponseWriter, r *http.Request, txn string, body []byte) {
+ var ask haTakeAsk
+ if json.Unmarshal(body, &ask) != nil || ask.Txn != txn || !haControlField(ask.From) || ask.From == e.box ||
+ !haTakeHost(ask.Host) || !haControlField(ask.Lifetime) || ask.MarkerGen <= 0 {
+ refuseHAControl(w)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), haTakeServeBound)
+ defer cancel()
+ ans := e.takeHost(ctx, ask)
+ holder := ans.Holder
+ if holder == "" {
+ holder = takeNone
+ }
+ reason := ans.Reason
+ if len(reason) > haTakeMaxReason {
+ reason = reason[:haTakeMaxReason]
+ }
+ log.Printf("edge: ha-take %s from %s (txn %s, marker generation %d): holder %s, generation %d%s%s",
+ ask.Host, ask.From, ask.Txn, ask.MarkerGen, holder, ans.Gen, takeLogPart("refused", ans.Refused), takeLogPart("reason", reason))
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ json.NewEncoder(w).Encode(haTakeAnswer{Holder: holder, Gen: ans.Gen, Refused: ans.Refused, Reason: reason})
+}
+
+func takeLogPart(name, v string) string {
+ if v == "" {
+ return ""
+ }
+ return "; " + name + ": " + v
+}
+
+// takeHost is the take's route and activator: the host's own route on this
+// box, exactly (no catch-all, no alias), hibernate-managed here. Whether
+// it is HA is the activator's classification, from record facts.
+func (e *Edge) takeHost(ctx context.Context, ask haTakeAsk) TakeAnswer {
+ taker, ok := e.act.(HATaker)
+ if !ok {
+ return TakeAnswer{Refused: TakeRefusedNoTaker}
+ }
+ up, ok := e.current()[ask.Host]
+ if !ok || up.route.Host != ask.Host || !up.hibernating || up.viaTunnel {
+ return TakeAnswer{Refused: TakeRefusedNoRoute}
+ }
+ if takeHook != nil {
+ takeHook(ask.Host)
+ }
+ return taker.TakeHost(ctx, up.route, ask.Lifetime, ask.MarkerGen)
+}
+
+// TakeRefusedError is a take the successor refused before any acquire.
+type TakeRefusedError struct {
+ Peer, Reason string
+}
+
+func (e *TakeRefusedError) Error() string {
+ return fmt.Sprintf("ha-take: %s refused the take: %s", e.Peer, e.Reason)
+}
+
+// ErrTakeNoHolder is a take that ran and names no holder: the wake failed,
+// or the lock is in a state no acquire may take.
+var ErrTakeNoHolder = errors.New("ha-take: no holder")
+
+// ErrTakeUnsupported is a peer whose edges file does not say ha_take: 1.
+var ErrTakeUnsupported = errors.New("ha-take: the peer does not answer take requests")
+
+// takeCapable is whether f says ha_take: 1.
+func (f edgesFileView) takeCapable() bool {
+ var n int
+ return len(f.HATake) > 0 && placementField(f.HATake, &n) && n == 1
+}
+
+// PeerTakes is whether this edge's fold shows ref's edges file saying
+// ha_take: 1. Memory only.
+func (e *Edge) PeerTakes(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.takeCapable()
+}
+
+// Take asks peer to take host, whose lease this box has released as a
+// marker at generation markerGen, for drain transaction txn (§25.7). It
+// answers the confirmed holder, peer or a third box that won the marker
+// first, and the lock's generation. An error is a take with no confirmed
+// holder: one that could not be sent or got no answer, a
+// *TakeRefusedError, ErrTakeNoHolder (wrapped with the peer's reason),
+// ErrTakeUnsupported, or an answer naming this box. It is one request,
+// never retried here.
+func (e *Edge) Take(ctx context.Context, peer, host, lifetime string, markerGen int64, txn string) (holderRef string, lockGen int64, err error) {
+ m := e.homes.Load()
+ if m == nil || e.box == "" {
+ return "", 0, errors.New("ha-take: this edge has no home map or box name")
+ }
+ if !haControlField(txn) || !haControlField(peer) || peer == e.box {
+ return "", 0, fmt.Errorf("ha-take: bad transaction %q or peer %q", txn, peer)
+ }
+ if !haTakeHost(host) || !haControlField(lifetime) || markerGen <= 0 {
+ return "", 0, fmt.Errorf("ha-take: bad host %q, lifetime %q or marker generation %d", host, lifetime, markerGen)
+ }
+ if !e.PeerTakes(peer) {
+ return "", 0, fmt.Errorf("%w: %s", ErrTakeUnsupported, peer)
+ }
+ current, next := m.meshKeys()
+ key := signingKey(current, next)
+ if len(key) == 0 {
+ return "", 0, errors.New("ha-take: no mesh key to sign with")
+ }
+ dial, name, err := m.controlTarget(peer, e.certs.Load())
+ if err != nil {
+ return "", 0, err
+ }
+ body, err := json.Marshal(haTakeAsk{From: e.box, Txn: txn, Host: host, Lifetime: lifetime, MarkerGen: markerGen})
+ if err != nil {
+ return "", 0, err
+ }
+ if len(body) > haControlMaxBody {
+ return "", 0, errors.New("ha-take: request over the body bound")
+ }
+ ctx, cancel := context.WithTimeout(ctx, haTakeAskTimeout)
+ defer cancel()
+ u := url.URL{Scheme: "https", Host: name, Path: HATakePath}
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(body))
+ if err != nil {
+ return "", 0, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set(haControlTxnHeader, txn)
+ req.Header.Set(haControlAuthHeader, signHAControl(key, peer, http.MethodPost, HATakePath, txn, time.Now(), body))
+ resp, err := e.takeTransport(dial).RoundTrip(req)
+ if err != nil {
+ return "", 0, fmt.Errorf("ha-take: ask %s (%s): %w", peer, dial, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ io.Copy(io.Discard, io.LimitReader(resp.Body, haControlMaxBody))
+ return "", 0, fmt.Errorf("ha-take: %s answered %d", peer, resp.StatusCode)
+ }
+ var ans haTakeAnswer
+ if err := json.NewDecoder(io.LimitReader(resp.Body, haControlMaxBody)).Decode(&ans); err != nil {
+ return "", 0, fmt.Errorf("ha-take: %s's answer: %w", peer, err)
+ }
+ switch {
+ case ans.Refused != "":
+ return "", 0, &TakeRefusedError{Peer: peer, Reason: ans.Refused}
+ case ans.Holder == "" || ans.Holder == takeNone:
+ return "", 0, fmt.Errorf("%w: %s: %s", ErrTakeNoHolder, peer, ans.Reason)
+ case !haControlField(ans.Holder) || ans.Gen <= 0:
+ return "", 0, fmt.Errorf("ha-take: %s answered holder %q at generation %d", peer, ans.Holder, ans.Gen)
+ case ans.Holder == e.box:
+ return "", 0, fmt.Errorf("ha-take: %s says this box still holds %s", peer, host)
+ }
+ return ans.Holder, ans.Gen, nil
+}
+
+// takeTransport is the backhaul transport to dial, cloned with a response
+// header timeout of haTakeAskTimeout: a take is answered only once the
+// host is awake, which may take the whole wake wait bound.
+func (e *Edge) takeTransport(dial string) *http.Transport {
+ if tr, ok := e.takeTransports.Load(dial); ok {
+ return tr.(*http.Transport)
+ }
+ tr := e.backhaulTransport(dial).Clone()
+ tr.ResponseHeaderTimeout = haTakeAskTimeout
+ tr.MaxIdleConnsPerHost, tr.MaxIdleConns = 4, 4
+ if existing, loaded := e.takeTransports.LoadOrStore(dial, tr); loaded {
+ return existing.(*http.Transport)
+ }
+ return tr
+}
diff --git a/internal/edge/hatake_test.go b/internal/edge/hatake_test.go
new file mode 100644
index 000000000..3496757f6
--- /dev/null
+++ b/internal/edge/hatake_test.go
@@ -0,0 +1,324 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The take request (hatake.go; region HA §25.7) between real edges over
+// real TLS, as the drain scene runs them. The receiver's activator is a
+// fake that records what it was asked and answers as told.
+
+const takeHostName = "moving.example.com"
+
+// takeRoute is the moving host's row on a successor: an HA instance the
+// activator manages.
+var takeRoute = registry.Route{Host: takeHostName, Kind: "instance", HA: true, Hibernate: true, Provisioned: true,
+ Socket: "/nonexistent/take.sock", Status: "ready", Account: "bdk", App: "shop", Pool: "ha"}
+
+type takeCall struct {
+ host, lifetime string
+ markerGen int64
+}
+
+// takerAct is an Activator with a take half.
+type takerAct struct {
+ fakeActivator
+ mu sync.Mutex
+ calls []takeCall
+ answer TakeAnswer
+}
+
+func (f *takerAct) TakeHost(_ context.Context, rt registry.Route, lifetime string, markerGen int64) TakeAnswer {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls = append(f.calls, takeCall{rt.Host, lifetime, markerGen})
+ return f.answer
+}
+
+func (f *takerAct) taken() []takeCall {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]takeCall(nil), f.calls...)
+}
+
+func (f *takerAct) served() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.fakeActivator.served
+}
+
+func (f *takerAct) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
+ f.mu.Lock()
+ f.fakeActivator.served++
+ f.mu.Unlock()
+ w.WriteHeader(http.StatusTeapot)
+ return true
+}
+
+// takeScene is annie (draining, the asker), betty (the successor, with
+// a taker) and carol (a second edge, with a taker of her own).
+type takeScene struct {
+ *drainScene
+ annie, betty, carol *drainBox
+ bettyAct, carolAct *takerAct
+}
+
+func newTakeScene(t *testing.T) *takeScene {
+ t.Helper()
+ s := &takeScene{drainScene: newDrainScene(t), bettyAct: &takerAct{}, carolAct: &takerAct{}}
+ s.extra = map[string]map[string]any{"betty": {"ha_take": 1}, "carol": {"ha_take": 1}}
+ s.annie = s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1")
+ s.betty = s.addWith(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1", s.bettyAct, takeRoute)
+ s.carol = s.addWith(t, "carol", "127.0.0.13", "news.example.com", "eu-west-1", s.carolAct, takeRoute)
+ for _, x := range []*drainBox{s.annie, s.betty, s.carol} {
+ s.file(t, x, drainGen0, notDrain)
+ }
+ s.sync(t)
+ return s
+}
+
+func (s *takeScene) take(peer string) (string, int64, error) {
+ return s.annie.edge().Take(context.Background(), peer, takeHostName, "L-1", 6, "txn-1")
+}
+
+// A take reaches the successor's activator once, with the host's own row,
+// the lifetime and the marker generation, and the answer names the holder
+// at the lock's generation: the successor, or a third box that won.
+func TestTakeAnswersTheHolder(t *testing.T) {
+ s := newTakeScene(t)
+ for name, tc := range map[string]struct {
+ answer TakeAnswer
+ holder string
+ gen int64
+ }{
+ "the successor": {TakeAnswer{Holder: "betty", Gen: 7}, "betty", 7},
+ "a third box won first": {TakeAnswer{Holder: "carol", Gen: 7}, "carol", 7},
+ } {
+ t.Run(name, func(t *testing.T) {
+ s.bettyAct.mu.Lock()
+ s.bettyAct.answer, s.bettyAct.calls = tc.answer, nil
+ s.bettyAct.mu.Unlock()
+ holder, gen, err := s.take("betty")
+ if err != nil || holder != tc.holder || gen != tc.gen {
+ t.Fatalf("take: %q %d %v, want %s at %d", holder, gen, err, tc.holder, tc.gen)
+ }
+ if got := s.bettyAct.taken(); len(got) != 1 || got[0] != (takeCall{takeHostName, "L-1", 6}) {
+ t.Fatalf("betty's activator was asked %+v", got)
+ }
+ })
+ }
+ // No visitor: nothing reached an app or the activator's request path,
+ // and carol (not asked) took nothing.
+ if s.bettyAct.served() != 0 || len(s.betty.appSaw()) != 0 || len(s.carolAct.taken()) != 0 {
+ t.Fatalf("served %d, app %v, carol %v", s.bettyAct.served(), s.betty.appSaw(), s.carolAct.taken())
+ }
+}
+
+// What the asker makes of each answer that names no confirmed holder.
+func TestTakeAnswersWithoutAHolder(t *testing.T) {
+ s := newTakeScene(t)
+ for name, tc := range map[string]struct {
+ answer TakeAnswer
+ check func(error) bool
+ }{
+ "refused": {TakeAnswer{Refused: TakeRefusedDraining}, func(err error) bool {
+ var re *TakeRefusedError
+ return errors.As(err, &re) && re.Peer == "betty" && re.Reason == TakeRefusedDraining
+ }},
+ "none": {TakeAnswer{Reason: "the wake failed"}, func(err error) bool {
+ return errors.Is(err, ErrTakeNoHolder) && strings.Contains(err.Error(), "the wake failed")
+ }},
+ "the asker itself": {TakeAnswer{Holder: "annie", Gen: 6}, func(err error) bool {
+ return err != nil && strings.Contains(err.Error(), "this box still holds")
+ }},
+ "a holder with no generation": {TakeAnswer{Holder: "carol"}, func(err error) bool {
+ return err != nil && strings.Contains(err.Error(), "generation 0")
+ }},
+ } {
+ t.Run(name, func(t *testing.T) {
+ s.bettyAct.mu.Lock()
+ s.bettyAct.answer = tc.answer
+ s.bettyAct.mu.Unlock()
+ holder, gen, err := s.take("betty")
+ if holder != "" || gen != 0 || !tc.check(err) {
+ t.Fatalf("take: %q %d %v", holder, gen, err)
+ }
+ })
+ }
+}
+
+// A peer whose file does not say ha_take: 1 is never sent a take: on an
+// older box the path would reach a tenant's app.
+func TestTakeOnlyToAPeerThatSaysSo(t *testing.T) {
+ for name, v := range map[string]any{"absent": nil, "0": 0, "2": 2, "a string": "1", "true": true} {
+ t.Run(name, func(t *testing.T) {
+ s := newTakeScene(t)
+ if v == nil {
+ delete(s.extra, "betty")
+ } else {
+ s.extra["betty"] = map[string]any{"ha_take": v}
+ }
+ s.file(t, s.betty, drainGen0.Add(time.Second), notDrain)
+ s.sync(t)
+ before := s.betty.door.Load()
+ if _, _, err := s.take("betty"); !errors.Is(err, ErrTakeUnsupported) {
+ t.Fatalf("take: %v, want ErrTakeUnsupported", err)
+ }
+ if s.betty.door.Load() != before || s.annie.edge().PeerTakes("betty") {
+ t.Fatal("a take was sent to a box that does not answer them")
+ }
+ })
+ }
+ s := newTakeScene(t)
+ if !s.annie.edge().PeerTakes("betty") || s.annie.edge().PeerTakes("annie") || s.annie.edge().PeerTakes("nobody") {
+ t.Fatal("PeerTakes does not read ha_take: 1")
+ }
+}
+
+// The receiver's own refusals at the edge: no taker, and a host that is
+// not this box's own hibernate-managed row.
+func TestTakeReceiverRoute(t *testing.T) {
+ s := newTakeScene(t)
+ s.bettyAct.answer = TakeAnswer{Holder: "betty", Gen: 7}
+ for name, host := range map[string]string{
+ "a host not served here": "elsewhere.example.com",
+ "a row that is not an instance": "blog.example.com",
+ } {
+ t.Run(name, func(t *testing.T) {
+ _, _, err := s.annie.edge().Take(context.Background(), "betty", host, "L-1", 6, "txn-1")
+ var re *TakeRefusedError
+ if !errors.As(err, &re) || re.Reason != TakeRefusedNoRoute {
+ t.Fatalf("take of %s: %v, want refused %s", host, err, TakeRefusedNoRoute)
+ }
+ })
+ }
+ if got := s.bettyAct.taken(); len(got) != 0 {
+ t.Fatalf("the activator was asked %+v", got)
+ }
+ // annie has no taker at all.
+ s.extra["annie"] = map[string]any{"ha_take": 1}
+ s.file(t, s.annie, drainGen0.Add(time.Second), notDrain)
+ s.sync(t)
+ _, _, err := s.betty.edge().Take(context.Background(), "annie", takeHostName, "L-1", 6, "txn-1")
+ var re *TakeRefusedError
+ if !errors.As(err, &re) || re.Reason != TakeRefusedNoTaker {
+ t.Fatalf("a take of a box with no taker: %v", err)
+ }
+}
+
+// A take is accepted only as a signed request for this box. Sent as an
+// ordinary client request, through a second edge, as a hop, misaddressed
+// to another box, or forged, it is a bare 404, is never forwarded, and
+// neither wakes nor acquires anything anywhere.
+func TestTakeRefusesEverythingButASignedAsk(t *testing.T) {
+ s := newTakeScene(t)
+ s.bettyAct.answer = TakeAnswer{Holder: "betty", Gen: 7}
+ s.carolAct.answer = TakeAnswer{Holder: "carol", Gen: 7}
+ now := time.Now()
+ body := []byte(`{"from":"annie","txn":"txn-1","host":"moving.example.com","lifetime":"L-1","marker_gen":6}`)
+ signFor := func(receiver string, b []byte) string {
+ return signHAControl(s.key, receiver, http.MethodPost, HATakePath, "txn-1", now, b)
+ }
+ post := func(x *drainBox, host, auth, txn string, hop bool, b []byte) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "http://"+host+HATakePath, bytes.NewReader(b))
+ if auth != "" {
+ r.Header.Set(haControlAuthHeader, auth)
+ }
+ if txn != "" {
+ r.Header.Set(haControlTxnHeader, txn)
+ }
+ if hop {
+ r.Header.Set(hopHeader, "1")
+ r.Header.Set(hopAuthHeader, signHop(s.key, host, now))
+ }
+ w := httptest.NewRecorder()
+ x.edge().ServeHTTP(w, r)
+ return w
+ }
+ if w := post(s.betty, takeHostName, signFor("betty", body), "txn-1", false, body); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"holder":"betty"`) {
+ t.Fatalf("a good take: %d %q", w.Code, w.Body.String())
+ }
+ if n := len(s.bettyAct.taken()); n != 1 {
+ t.Fatalf("a good take reached the activator %d times", n)
+ }
+ s.bettyAct.mu.Lock()
+ s.bettyAct.calls = nil
+ s.bettyAct.mu.Unlock()
+ doorB, doorC := s.betty.door.Load(), s.carol.door.Load()
+ edit := func(from, to string) []byte { return bytes.Replace(body, []byte(from), []byte(to), 1) }
+ for name, tc := range map[string]struct {
+ x *drainBox
+ host, auth string
+ txn string
+ hop bool
+ body []byte
+ }{
+ "a client request through a second edge": {s.carol, takeHostName, "", "", false, body},
+ "a client request with headers": {s.carol, takeHostName, "1:00", "txn-1", false, body},
+ "betty's take sent to carol": {s.carol, takeHostName, signFor("betty", body), "txn-1", false, body},
+ "a client request to the successor": {s.betty, takeHostName, "", "", false, body},
+ "a verified hop": {s.betty, takeHostName, "", "", true, body},
+ "hop-signed": {s.betty, takeHostName, signHop(s.key, takeHostName, now), "txn-1", false, body},
+ "tampered host": {s.betty, takeHostName, signFor("betty", body), "txn-1", false, edit("moving", "other")},
+ "tampered marker generation": {s.betty, takeHostName, signFor("betty", body), "txn-1", false, edit(`"marker_gen":6`, `"marker_gen":7`)},
+ "other txn header": {s.betty, takeHostName, signFor("betty", body), "txn-2", false, body},
+ "txn mismatch in the body": {s.betty, takeHostName, signFor("betty", edit("txn-1", "txn-9")), "txn-1", false, edit("txn-1", "txn-9")},
+ "from itself": {s.betty, takeHostName, signFor("betty", edit("annie", "betty")), "txn-1", false, edit("annie", "betty")},
+ "no marker generation": {s.betty, takeHostName, signFor("betty", edit(`"marker_gen":6`, `"marker_gen":0`)), "txn-1", false, edit(`"marker_gen":6`, `"marker_gen":0`)},
+ "a bad host": {s.betty, takeHostName, signFor("betty", edit("moving.example.com", "Moving/x")), "txn-1", false, edit("moving.example.com", "Moving/x")},
+ "the drain path's signature": {s.betty, takeHostName, signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now, body), "txn-1", false, body},
+ "stale": {s.betty, takeHostName, signHAControl(s.key, "betty", http.MethodPost, HATakePath, "txn-1", now.Add(-2*hopSkew), body), "txn-1", false, body},
+ } {
+ if w := post(tc.x, tc.host, tc.auth, tc.txn, tc.hop, 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 b, c := s.bettyAct.taken(), s.carolAct.taken(); len(b) != 0 || len(c) != 0 {
+ t.Fatalf("a refused take reached an activator: betty %+v carol %+v", b, c)
+ }
+ if s.bettyAct.served() != 0 || s.carolAct.served() != 0 {
+ t.Fatal("a refused take reached an activator's request path")
+ }
+ if s.betty.door.Load() != doorB || s.carol.door.Load() != doorC || s.annie.door.Load() != 0 {
+ t.Fatal("a refused take was forwarded")
+ }
+ for _, x := range []*drainBox{s.annie, s.betty, s.carol} {
+ if got := x.appSaw(); len(got) != 0 {
+ t.Fatalf("%s's app saw %v", x.box, got)
+ }
+ }
+}
+
+// The take's own transport outlasts a wake: a successor that answers
+// after the backhaul's 30 s header timeout would otherwise look failed.
+func TestTakeTransportOutlastsAWake(t *testing.T) {
+ s := newTakeScene(t)
+ e := s.annie.edge()
+ tr := e.takeTransport("127.0.0.12")
+ if tr.ResponseHeaderTimeout != haTakeAskTimeout || haTakeAskTimeout <= haTakeServeBound || haTakeServeBound < 30*time.Second {
+ t.Fatalf("take header timeout %s, ask %s, serve bound %s", tr.ResponseHeaderTimeout, haTakeAskTimeout, haTakeServeBound)
+ }
+ if e.takeTransport("127.0.0.12") != tr || e.backhaulTransport("127.0.0.12").ResponseHeaderTimeout != backhaulHeaderTimeout {
+ t.Fatal("the take transport is not its own, cached per dial")
+ }
+}
+
+// The answer is JSON with the documented field names (Task 5's driver and
+// any later reader rely on them).
+func TestTakeAnswerShape(t *testing.T) {
+ b, err := json.Marshal(haTakeAnswer{Holder: "betty", Gen: 7})
+ if err != nil || string(b) != `{"holder":"betty","gen":7}` {
+ t.Fatalf("answer %s %v", b, err)
+ }
+}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index ddc312ff5..d4a788d81 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -173,7 +173,11 @@ type edgesFileView struct {
HADrained json.RawMessage `json:"ha_drained"`
// HADrain is the drain publication's identity (transaction and ID),
// which an acknowledgement names.
- HADrain json.RawMessage `json:"ha_drain"`
+ HADrain json.RawMessage `json:"ha_drain"`
+ // HATake is 1 when the box answers take requests itself (region HA
+ // §25.7, hatake.go). A take is sent only to a file that says so: on an
+ // older box the take path would reach a tenant's app.
+ HATake json.RawMessage `json:"ha_take"`
Role json.RawMessage `json:"role"`
Headroom json.RawMessage `json:"headroom"`
// placementNull is an explicit "placement": null. The holder decoder
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index ab50300e7..6a6dee1c8 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -366,6 +366,13 @@ type edgesFile struct {
// Absent is an older build, which would hand the notice path to a
// tenant's app, so senders skip it.
BurstNotices bool `json:"burst_notices,omitempty"`
+ // HATake is 1 on an HA box (capability region-ha-1): its edge answers
+ // take requests itself (region HA §25.7, internal/edge hatake.go), so a
+ // draining box may ask it to take a host. Additive (omitempty): every
+ // other box's file is unchanged, and a reader that does not know it
+ // ignores it. Absent is an older build or a box that is not HA, which a
+ // draining box never asks.
+ HATake int `json:"ha_take,omitempty"`
// SecretsKeyFP is the fingerprint of this box's CARLOS_SECRETS_KEY's
// public half (appconfig.KeyFingerprint), NEVER the key. Additive and
@@ -1007,6 +1014,9 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re
f.Capabilities = append(slices.Clone(f.Capabilities), edgesfile.NamesCapability)
}
f.BurstNotices = true
+ if slices.Contains(f.Capabilities, capRegionHA1) {
+ f.HATake = 1
+ }
f.PrivateIP, f.PrivateCIDR = private.Private, private.PrivateCIDR
// Before the gate copy, so an address change is a reason to write.
f.Addrs = boxAddrs(localAddrs)
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go
index 3e42af6f9..b441259e5 100644
--- a/internal/host/edgesfile_test.go
+++ b/internal/host/edgesfile_test.go
@@ -1465,6 +1465,41 @@ func TestEdgesFileAdvertisesBurstNotices(t *testing.T) {
}
}
+// An HA box says ha_take: 1 (region HA §25.7): its edge answers take
+// requests itself, and a draining box sends takes only to a file that says
+// so. Every other box's file is unchanged: no ha_take key at all.
+func TestEdgesFileAdvertisesHATake(t *testing.T) {
+ for name, tc := range map[string]struct {
+ caps []string
+ want string
+ }{
+ "an HA box": {[]string{capRegionHA1}, "1"},
+ "a non-HA box": {nil, ""},
+ "other ability": {[]string{"offline-1"}, ""},
+ } {
+ t.Run(name, func(t *testing.T) {
+ s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t)
+ seedRoute(t, reg, "app.example.com")
+ var last []byte
+ if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Capabilities: tc.caps}, "1.2.3.4", &last); err != nil {
+ t.Fatal(err)
+ }
+ body, _, err := s.Get(context.Background(), "control/edges/annie.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(body, &raw); err != nil {
+ t.Fatal(err)
+ }
+ got, ok := raw["ha_take"]
+ if tc.want == "" && ok || tc.want != "" && string(got) != tc.want {
+ t.Fatalf("ha_take = %q (present %v) in %s, want %q", got, ok, body, tc.want)
+ }
+ })
+ }
+}
+
func TestEdgesFileHeadroomAloneDoesNotRewriteTheFile(t *testing.T) {
st := &putCountingStore{Store: release.NewDirStore(t.TempDir())}
reg := edgesTestRegistry(t)
diff --git a/internal/lease/ha.go b/internal/lease/ha.go
index 665105510..f27722f16 100644
--- a/internal/lease/ha.go
+++ b/internal/lease/ha.go
@@ -136,7 +136,7 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas
case hafresh.ActTake:
return nil
case hafresh.ActHeld:
- return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt}
+ return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt, Generation: v.Lock.Generation}
default:
return &RefusedError{Reason: d.Reason}
}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index a12a84020..1c7e7b7c6 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -120,6 +120,9 @@ const l0RetentionCheckInterval = 1 * time.Hour
type HeldError struct {
Owner string
ExpiresAt time.Time
+ // Generation is the held lock's generation, when the HA acquire read
+ // it (0 otherwise). Diagnostic: the take request reports it.
+ Generation int64
}
func (e *HeldError) Error() string {