region-ha p1b-2: the activator names a holder to forward to
ForwardTarget answers the edge from a bounded holder cache (50,000 hosts, 1 h positive, 10 s negative), or on a miss from one single-flight read of the host's lock.json; never for a host awake or waking here. NoteForward follows each forward's outcome; this box's acquire drops the entry. A forwarded request on an HA route that this box refuses names the holder (503, Retry-After: 1, X-Carlos-Holder: <ref>) or says none.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+15 −5internal/activator/hacache.go+183 −0internal/activator/haforward.go+166 −0internal/activator/haforward_test.go+398 −0
Intent
<task-notification> <task-id>a239b8399dde65d59</task-id> <tool-use-id>toolu_01PZ8ztfQuCWstSM3uCKwxcN</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/a239b8399dde65d59.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: front-door forward" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE. An app can no longer send `X-Carlos-Holder` as a trailer either. **Commits:** 84b52299 (Task 2), 58c9420e (fix round 1), aa34335b (this fix). The lock message after each commit comes from the amadan ledger hook; all three commits landed and the tree is clean. **What changed:** a new `stripAppHolder`, called from the response hook every app proxy goes through, now removes the holder field in three places: - the header; - the trailer name the app announces in its `Trailer:` header, removed straight away; - the trailer value, announced or not, removed when the body closes, before the proxy copies trailers on to the client. **Tests:** the new `TestForwardHAAppHolderTrailerNeverReachesTheClient` covers announced and unannounced trailers through a real forward. The client gets no `X-Carlos-Holder` anywhere, an ordinary trailer from the app still arrives, and the forward is reported with no holder. With the trailer strip removed, the test fails in each case. The forward set, the `Backhaul|Hop|Home|Regional|Gate` regression command, the darwin, windows and linux builds, and vet all pass. **Concerns:** none new. **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/.superpowers/sdd/2026-10-29-region-ha-p1b2-forwarding/task-2-report.md (fix round 2 appended)</result> <usage><subagent_tokens>264850</subagent_tokens><tool_uses>9</tool_uses><duration_ms>211084</duration_ms></usage> </task-notification>
<task-notification> <task-id>bj3to2pyu</task-id> <tool-use-id>toolu_017bXwYXJ4krRiYrV9FUmBRK</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/bj3to2pyu.output</output-file> <status>completed</status> <summary>Background command "Run the scoped re-review of fix round 2" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 20.1 g CO₂e (2,643,575 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b2-forwarding, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index bfedb62c8..b4a9b0412 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1268,6 +1268,10 @@ type Service struct { |
| // codepath was touched at all. Single-box v1 drops the field; it re-enters |
| // with the mesh port. |
| + // holders is the region HA holder cache (hacache.go): for a born-HA |
| + // host held by another box, which one, so the edge forwards there. |
| + holders holderCache |
| + |
| // 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 |
| // is the wrong trade there. |
| @@ -2542,6 +2546,10 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| w.steps.mark(a.now(), "checks") |
| *w.stopOutcome = stopObservation{} |
| lease, err := a.backend.Acquire(ctx, rt) |
| + if err == nil { |
| + // This box holds the host now: no holder elsewhere to forward to. |
| + a.holders.drop(host) |
| + } |
| // A row with a runtime that meets a held lease or refused config is |
| // refused, never failed (markOwnershipRefusal); a binary row's answer |
| // is main's. |
| @@ -5967,6 +5975,7 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| fenced := a.fences[rt.Host] != 0 |
| a.mu.Unlock() |
| if fenced { |
| + a.answerForwarded(w, r, rt, ErrFenced) |
| maintenanceResponse(w, r) |
| return true |
| } |
| @@ -6014,11 +6023,8 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| return true |
| } |
| - // mesh seam: Eleven proxied a member request for a host with no live |
| - // local entry and an HRW owner on another live box to that peer here (one |
| - // hop max, guarded by a forwarded marker); a host with ANY live local |
| - // entry stayed local — placement converges at the next sleep boundary, |
| - // since its state is already in S3. Single-box v1 always wakes locally. |
| + // A born-HA host held by another box was forwarded there by the edge |
| + // before this, on the activator's word (haforward.go). |
| release, err := a.begin(r.Context(), rt, stamp, r) |
| if err != nil { |
| @@ -6030,6 +6036,10 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| } |
| func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| + // A forwarded request's answer names the holder (haforward.go). |
| + if a.answerForwarded(w, r, rt, err) { |
| + return true |
| + } |
| var held *errLeaseHeld |
| var refused *errConfigRefused |
| var backoff *errResidentBackoff |
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go| new file mode 100644 |
| index 000000000..ca45c9ea8 |
| --- /dev/null |
| +++ b/internal/activator/hacache.go |
| @@ -0,0 +1,183 @@ |
| +package activator |
| + |
| +import ( |
| + "container/list" |
| + "context" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// The holder cache (region HA P1b-2; spec 2026-10-26 §6.6): for a born-HA |
| +// host this box does not hold, which box does, so the edge can forward a |
| +// visitor's request there without an S3 request on every one. A positive |
| +// entry names the holder; a negative one says "not held elsewhere, serve |
| +// here" and exists only to cap the lock reads of a host that keeps |
| +// missing. The cache is advice, never a lease: every way it can be wrong |
| +// ends in a drop (haforward.go's NoteForward, the acquire in doWake) or, |
| +// at the latest, its lifetime. |
| +const ( |
| + // holderCacheMax bounds the cache; the oldest entry set goes first. |
| + holderCacheMax = 50_000 |
| + // holderPositiveTTL is the longest a named holder is believed without |
| + // a forward's answer confirming it. |
| + holderPositiveTTL = time.Hour |
| + // holderNegativeTTL is how long a miss that found no other holder is |
| + // remembered: one lock read per host per 10 s per box at most. |
| + holderNegativeTTL = 10 * time.Second |
| +) |
| + |
| +// holderCache is host to holder box reference. The zero value is ready; |
| +// now is the clock seam (nil is the real clock). |
| +type holderCache struct { |
| + mu sync.Mutex |
| + now func() time.Time |
| + entries map[string]*list.Element // host -> *holderEntry in order |
| + order list.List // oldest set at the front |
| + flights map[string]*holderFlight // host -> the lock read in flight |
| +} |
| + |
| +type holderEntry struct { |
| + host string |
| + ref string // "" for a negative entry |
| + expires time.Time |
| +} |
| + |
| +// holderFlight is one lock read in flight for a host. stale is set when |
| +// the host's entry is set or dropped while the read runs: the read began |
| +// before that news, so its answer goes to its waiters but is not cached. |
| +type holderFlight struct { |
| + done chan struct{} |
| + ref string |
| + stale bool |
| +} |
| + |
| +func (c *holderCache) clock() time.Time { |
| + if c.now != nil { |
| + return c.now() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// get is host's live entry: its ref and positive true for a holder, |
| +// positive false for a negative entry, found false for none (an expired |
| +// entry is removed). |
| +func (c *holderCache) get(host string) (ref string, positive, found bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.getLocked(host) |
| +} |
| + |
| +func (c *holderCache) getLocked(host string) (string, bool, bool) { |
| + el := c.entries[host] |
| + if el == nil { |
| + return "", false, false |
| + } |
| + e := el.Value.(*holderEntry) |
| + if !c.clock().Before(e.expires) { |
| + c.removeLocked(el) |
| + return "", false, false |
| + } |
| + return e.ref, e.ref != "", true |
| +} |
| + |
| +// set names ref as host's holder for holderPositiveTTL. An empty ref sets |
| +// nothing. |
| +func (c *holderCache) set(host, ref string) { |
| + if ref == "" { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.putLocked(host, ref, holderPositiveTTL) |
| +} |
| + |
| +// setNegative remembers for holderNegativeTTL that host is not held |
| +// elsewhere. |
| +func (c *holderCache) setNegative(host string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.putLocked(host, "", holderNegativeTTL) |
| +} |
| + |
| +// drop forgets host's entry, and any read in flight for it. |
| +func (c *holderCache) drop(host string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if el := c.entries[host]; el != nil { |
| + c.removeLocked(el) |
| + } |
| + if f := c.flights[host]; f != nil { |
| + f.stale = true |
| + } |
| +} |
| + |
| +func (c *holderCache) putLocked(host, ref string, ttl time.Duration) { |
| + if f := c.flights[host]; f != nil { |
| + f.stale = true |
| + } |
| + if c.entries == nil { |
| + c.entries = map[string]*list.Element{} |
| + } |
| + expires := c.clock().Add(ttl) |
| + if el := c.entries[host]; el != nil { |
| + e := el.Value.(*holderEntry) |
| + e.ref, e.expires = ref, expires |
| + c.order.MoveToBack(el) |
| + return |
| + } |
| + for len(c.entries) >= holderCacheMax { |
| + c.removeLocked(c.order.Front()) |
| + } |
| + c.entries[host] = c.order.PushBack(&holderEntry{host: host, ref: ref, expires: expires}) |
| +} |
| + |
| +func (c *holderCache) removeLocked(el *list.Element) { |
| + delete(c.entries, el.Value.(*holderEntry).host) |
| + c.order.Remove(el) |
| +} |
| + |
| +// resolve answers a miss for host with one read at a time: the first |
| +// caller runs read and every caller meanwhile waits for its answer (or |
| +// its own ctx, answering ""). read names the holder ("" for none) and ok |
| +// false when it could not tell, which caches nothing. An entry set while |
| +// a caller queued is answered without a read. |
| +func (c *holderCache) resolve(ctx context.Context, host string, read func() (ref string, ok bool)) string { |
| + c.mu.Lock() |
| + if ref, _, found := c.getLocked(host); found { |
| + c.mu.Unlock() |
| + return ref |
| + } |
| + if f := c.flights[host]; f != nil { |
| + c.mu.Unlock() |
| + select { |
| + case <-f.done: |
| + return f.ref |
| + case <-ctx.Done(): |
| + return "" |
| + } |
| + } |
| + f := &holderFlight{done: make(chan struct{})} |
| + if c.flights == nil { |
| + c.flights = map[string]*holderFlight{} |
| + } |
| + c.flights[host] = f |
| + c.mu.Unlock() |
| + |
| + ref, ok := "", false |
| + defer func() { |
| + c.mu.Lock() |
| + delete(c.flights, host) |
| + if ok && !f.stale { |
| + if ref != "" { |
| + c.putLocked(host, ref, holderPositiveTTL) |
| + } else { |
| + c.putLocked(host, "", holderNegativeTTL) |
| + } |
| + } |
| + f.ref = ref |
| + c.mu.Unlock() |
| + close(f.done) |
| + }() |
| + ref, ok = read() |
| + return ref |
| +} |
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go| new file mode 100644 |
| index 000000000..fb898471c |
| --- /dev/null |
| +++ b/internal/activator/haforward.go |
| @@ -0,0 +1,166 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log" |
| + "net/http" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA forwarding, the activator's half (region HA P1b-2; spec |
| +// 2026-10-26 §6.2, §6.6). The edge asks ForwardTarget, for a visitor's |
| +// request for a born-HA host, which box to send it to, and tells |
| +// NoteForward how the forward went. The answer comes from the holder cache |
| +// (hacache.go), or on a miss from one read of the host's lock.json. A |
| +// forwarded request this box cannot serve is answered with |
| +// X-Carlos-Holder, so the forwarding box can follow the lease |
| +// (answerForwarded). |
| +// |
| +// Nothing here can keep a host from being served for long. A named box |
| +// that is out of view, unreachable, answers "none", or answers 503 without |
| +// naming anyone is dropped at once, and the request is served here or |
| +// retried against a fresh read; a box that stops holding the host without |
| +// any of those answers it itself, as a verified hop it can wake for. The |
| +// hour's lifetime bounds the rest. |
| + |
| +var _ edge.HAForwarder = (*Service)(nil) |
| + |
| +// holderHeader is edge's: the holder's diagnostic on an answer to a |
| +// forwarded request, the box that holds the lease or "none". |
| +const holderHeader = "X-Carlos-Holder" |
| + |
| +// holderNone is the header's value for a refusal that names no holder. |
| +const holderNone = "none" |
| + |
| +// forwardedHop is edge.HopVerified: whether r arrived as a proven hop from |
| +// another box. A var only so a test can make a request one. |
| +var forwardedHop = edge.HopVerified |
| + |
| +// readHolderLock is lease.ReadLock, the miss's one lock read. A var only so |
| +// a test can hold the read open. |
| +var readHolderLock = lease.ReadLock |
| + |
| +// holderLockReader is the backend's half of a miss: where rt's lock is, |
| +// and who this box is. The exec backend has it; a backend without it |
| +// forwards nothing. |
| +type holderLockReader interface { |
| + readHolderView(ctx context.Context, rt registry.Route) (hafresh.View, error) |
| + self() hafresh.Self |
| +} |
| + |
| +func (b *ExecBackend) readHolderView(ctx context.Context, rt registry.Route) (hafresh.View, error) { |
| + return readHolderLock(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region) |
| +} |
| + |
| +// holderReadErrLogged is when a failed lock read was last logged (unix |
| +// nanos): at most one line a minute for the box, since every request of |
| +// a host whose read fails reads again. |
| +var holderReadErrLogged atomic.Int64 |
| + |
| +// ForwardTarget names the box rt's request should be forwarded to, or "" |
| +// to serve it here: always "" for a host that is not born HA, or that is |
| +// awake or waking here (begin's own first look, a live entry). Otherwise |
| +// the cache answers; a miss reads the lock once, however many requests |
| +// miss together, and an unexpired HA lease of another box sets the entry, |
| +// anything else the negative one. A read that fails caches nothing. |
| +func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) string { |
| + if !rt.HA { |
| + return "" |
| + } |
| + r, ok := a.backend.(holderLockReader) |
| + if !ok { |
| + return "" |
| + } |
| + a.mu.Lock() |
| + here := a.entries[rt.Host] != nil |
| + a.mu.Unlock() |
| + if here { |
| + return "" |
| + } |
| + if ref, positive, found := a.holders.get(rt.Host); found { |
| + if positive { |
| + return ref |
| + } |
| + return "" |
| + } |
| + return a.holders.resolve(ctx, rt.Host, func() (string, bool) { |
| + v, err := r.readHolderView(ctx, rt) |
| + if err != nil { |
| + now := time.Now() |
| + if last := holderReadErrLogged.Load(); ctx.Err() == nil && now.UnixNano()-last >= int64(time.Minute) && holderReadErrLogged.CompareAndSwap(last, now.UnixNano()) { |
| + log.Printf("activator: %s: reading the holder: %v; serving here", rt.Host, err) |
| + } |
| + return "", false |
| + } |
| + return otherHolder(v, r.self().Ref, a.holders.clock()), true |
| + }) |
| +} |
| + |
| +// otherHolder is the box v names as holding the host, when that is an |
| +// unexpired HA lease of a box other than self: "" for an absent lock, a |
| +// release marker, an expired lease, a lock that is not in the HA box |
| +// format, or this box's own. |
| +func otherHolder(v hafresh.View, self string, now time.Time) string { |
| + if v.Absent || v.Lock.Release != nil || !now.Before(v.Lock.ExpiresAt) { |
| + return "" |
| + } |
| + o, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + if !ok || !o.HA || o.Ref == "" || o.Ref == self { |
| + return "" |
| + } |
| + return o.Ref |
| +} |
| + |
| +// NoteForward follows a forward's outcome for host: a named box out of |
| +// view or unreachable, an answer of "none", and a 503 that names nobody |
| +// drop the entry; an answer naming a box sets it, unless the box is this |
| +// one, which drops it (this box is never forwarded to). |
| +func (a *Service) NoteForward(host string, res edge.ForwardResult) { |
| + switch { |
| + case res.Outcome == edge.ForwardNotInView, res.Outcome == edge.ForwardUnreachable: |
| + a.holders.drop(host) |
| + case res.Holder == holderNone: |
| + a.holders.drop(host) |
| + case res.Holder != "": |
| + if r, ok := a.backend.(holderLockReader); ok && res.Holder == r.self().Ref { |
| + a.holders.drop(host) |
| + return |
| + } |
| + a.holders.set(host, res.Holder) |
| + case res.Status == http.StatusServiceUnavailable: |
| + a.holders.drop(host) |
| + } |
| +} |
| + |
| +// answerForwarded is the holder diagnostic on the refusal err of a |
| +// forwarded request (a verified hop) on an HA route; it reports whether it |
| +// wrote the whole answer. A held lease is 503, Retry-After: 1 and the |
| +// holder's ref, whoever holds it (this box's own previous process |
| +// included), so the forwarding box follows the lease. Any other refusal |
| +// gets X-Carlos-Holder: none, so the forwarding box stops forwarding, and |
| +// the caller writes today's answer under it. A cancelled request, a legacy |
| +// route and a request that was not forwarded are left as they are. |
| +func (a *Service) answerForwarded(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| + if !rt.HA || !forwardedHop(r) || errors.Is(err, context.Canceled) { |
| + return false |
| + } |
| + var held *errLeaseHeld |
| + if errors.As(err, &held) { |
| + if o, ok := hafresh.ParseOwner(held.holder); ok && o.Ref != "" { |
| + w.Header().Set("Retry-After", "1") |
| + w.Header().Set(holderHeader, o.Ref) |
| + edge.MarkAnswered(r) |
| + http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable) |
| + return true |
| + } |
| + } |
| + w.Header().Set(holderHeader, holderNone) |
| + return false |
| +} |
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go| new file mode 100644 |
| index 000000000..9c2d84acd |
| --- /dev/null |
| +++ b/internal/activator/haforward_test.go |
| @@ -0,0 +1,398 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA P1b-2: the activator names the box the edge forwards a born-HA |
| +// host's request to, follows each forward's outcome, and answers a |
| +// forwarded request it cannot serve with the holder's diagnostic. |
| + |
| +// asForwarded makes every request in the test a verified hop. |
| +func asForwarded(t *testing.T) { |
| + t.Helper() |
| + old := forwardedHop |
| + forwardedHop = func(*http.Request) bool { return true } |
| + t.Cleanup(func() { forwardedHop = old }) |
| +} |
| + |
| +// lockGets counts the GETs of rt's lock.json. |
| +func lockGets(b *ExecBackend, rt registry.Route) int { |
| + n := 0 |
| + for _, r := range haFixOf(b).fx.Requests() { |
| + if r == "GET "+lockKeyOf(b, rt) { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// haHeldByB is an HA service whose host's lock is b's unexpired HA lease, |
| +// with its route marked born HA. |
| +func haHeldByB(t *testing.T) *haSvc { |
| + t.Helper() |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(10*time.Minute))) |
| + return s |
| +} |
| + |
| +func TestForwardTargetNamesTheHolder(t *testing.T) { |
| + s := haHeldByB(t) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget = %q, want b", got) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("%d lock reads on a miss, want 1", n) |
| + } |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget on a hit = %q, want b", got) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("a hit read the lock: %d reads", n) |
| + } |
| +} |
| + |
| +func TestForwardTargetServesHere(t *testing.T) { |
| + t.Run("awake here", func(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + s.rt.HA = true |
| + before := lockGets(s.b, s.rt) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget for a host awake here = %q", got) |
| + } |
| + if n := lockGets(s.b, s.rt) - before; n != 0 { |
| + t.Fatalf("a host awake here read the lock %d times", n) |
| + } |
| + }) |
| + t.Run("release marker", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.holders.now = clk.now |
| + putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", haFixOf(s.b).lifetime, 5, true)) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget over a release marker = %q", got) |
| + } |
| + if _, positive, found := s.a.holders.get(s.rt.Host); !found || positive { |
| + t.Fatalf("no negative entry: found %v, positive %v", found, positive) |
| + } |
| + clk.advance(9 * time.Second) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("within 10 s: %q, %d reads, want \"\" and 1", got, lockGets(s.b, s.rt)) |
| + } |
| + clk.advance(2 * time.Second) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" || lockGets(s.b, s.rt) != 2 { |
| + t.Fatalf("at 11 s: %q, %d reads, want \"\" and 2", got, lockGets(s.b, s.rt)) |
| + } |
| + }) |
| + t.Run("own lease", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + putLockFor(t, s.b, s.rt, leaseBody(t, "box/v1;ref=a;iid=i-a;pid=99;ha=1", time.Now().Add(10*time.Minute))) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget over this box's own lease = %q", got) |
| + } |
| + }) |
| + t.Run("expired lease", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute))) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget over an expired lease = %q", got) |
| + } |
| + }) |
| + t.Run("legacy route", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + s.rt.HA = false |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" || lockGets(s.b, s.rt) != 0 { |
| + t.Fatalf("legacy route: %q, %d reads", got, lockGets(s.b, s.rt)) |
| + } |
| + }) |
| + t.Run("read error", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + s.fx.FailNext("GET", http.StatusForbidden) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("a failed read = %q", got) |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("a failed read cached an entry") |
| + } |
| + }) |
| +} |
| + |
| +func TestForwardTargetSingleFlight(t *testing.T) { |
| + s := haHeldByB(t) |
| + gate := make(chan struct{}) |
| + var reads atomic.Int32 |
| + old := readHolderLock |
| + readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) { |
| + reads.Add(1) |
| + <-gate |
| + return old(ctx, bucket, prefix, region) |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + var wg sync.WaitGroup |
| + got := make([]string, 20) |
| + for i := range got { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + got[i] = s.a.ForwardTarget(context.Background(), s.rt) |
| + }() |
| + } |
| + waitFor(t, "the first read", func() bool { return reads.Load() == 1 }) |
| + time.Sleep(50 * time.Millisecond) // the other 19 queue on it |
| + close(gate) |
| + wg.Wait() |
| + for i, ref := range got { |
| + if ref != "b" { |
| + t.Fatalf("caller %d got %q, want b", i, ref) |
| + } |
| + } |
| + if n := reads.Load(); n != 1 { |
| + t.Fatalf("%d lock reads for 20 concurrent misses, want 1", n) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("%d lock GETs, want 1", n) |
| + } |
| +} |
| + |
| +func TestHolderCacheDroppedOnUnreachable(t *testing.T) { |
| + for _, outcome := range []edge.ForwardOutcome{edge.ForwardUnreachable, edge.ForwardNotInView} { |
| + s := haHeldByB(t) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget = %q, want b", got) |
| + } |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: outcome}) |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatalf("outcome %d kept the entry", outcome) |
| + } |
| + } |
| +} |
| + |
| +func TestHolderCacheFollowsHolderHeader(t *testing.T) { |
| + s := haHeldByB(t) |
| + host := s.rt.Host |
| + s.a.holders.set(host, "b") |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "c"}) |
| + if ref, positive, _ := s.a.holders.get(host); ref != "c" || !positive { |
| + t.Fatalf("after X-Carlos-Holder: c the entry is %q", ref) |
| + } |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "c" || lockGets(s.b, s.rt) != 0 { |
| + t.Fatalf("ForwardTarget = %q with %d reads, want c and none", got, lockGets(s.b, s.rt)) |
| + } |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "none"}) |
| + if _, _, found := s.a.holders.get(host); found { |
| + t.Fatal("X-Carlos-Holder: none kept the entry") |
| + } |
| + // A holder naming this box itself is never forwarded to. |
| + s.a.holders.set(host, "b") |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "a"}) |
| + if _, _, found := s.a.holders.get(host); found { |
| + t.Fatal("X-Carlos-Holder naming this box set an entry") |
| + } |
| +} |
| + |
| +func TestHolderCacheBounds(t *testing.T) { |
| + clk := &fakeClock{t: time.Now()} |
| + c := &holderCache{now: clk.now} |
| + for i := range holderCacheMax + 1 { |
| + c.set(fmt.Sprintf("h%d.example.com", i), "b") |
| + } |
| + if n := len(c.entries); n != holderCacheMax { |
| + t.Fatalf("%d entries, want %d", n, holderCacheMax) |
| + } |
| + if _, _, found := c.get("h0.example.com"); found { |
| + t.Fatal("the oldest entry was not evicted") |
| + } |
| + if ref, _, found := c.get(fmt.Sprintf("h%d.example.com", holderCacheMax)); !found || ref != "b" { |
| + t.Fatal("the newest entry is missing") |
| + } |
| + clk.advance(59 * time.Minute) |
| + if _, _, found := c.get("h1.example.com"); !found { |
| + t.Fatal("an entry is gone before its hour") |
| + } |
| + clk.advance(2 * time.Minute) |
| + if _, _, found := c.get("h1.example.com"); found { |
| + t.Fatal("an entry outlived its hour") |
| + } |
| + c.setNegative("n.example.com") |
| + clk.advance(10 * time.Second) |
| + if _, _, found := c.get("n.example.com"); found { |
| + t.Fatal("a negative entry outlived 10 s") |
| + } |
| +} |
| + |
| +func TestTakingTheLeaseDropsTheEntry(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.a.holders.set(s.rt.Host, "b") |
| + if _, err := s.wakeForTest(context.Background()); err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("the entry survived this box taking the lease") |
| + } |
| +} |
| + |
| +// mustNotProxy is the proxy of a request that must be refused. |
| +func mustNotProxy(t *testing.T) http.Handler { |
| + return http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| + t.Error("the refused request was proxied") |
| + }) |
| +} |
| + |
| +func TestHoppedHeldAnswersWithTheHolder(t *testing.T) { |
| + asForwarded(t) |
| + t.Run("another box", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + rec := httptest.NewRecorder() |
| + s.a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), s.rt, mustNotProxy(t)) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") != "1" || rec.Header().Get(holderHeader) != "b" || |
| + rec.Body.String() != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("answer %d, Retry-After %q, holder %q, body %q", rec.Code, rec.Header().Get("Retry-After"), rec.Header().Get(holderHeader), rec.Body) |
| + } |
| + }) |
| + t.Run("this box's previous process", func(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + b.acquireErr = &errLeaseHeld{holder: "box/v1;ref=a;iid=i-a;pid=99;ha=1", retryAfter: 7 * time.Minute} |
| + rt := testRoute("shop.example.com") |
| + rt.HA = true |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), rt, mustNotProxy(t)) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") != "1" || rec.Header().Get(holderHeader) != "a" { |
| + t.Fatalf("answer %d, Retry-After %q, holder %q", rec.Code, rec.Header().Get("Retry-After"), rec.Header().Get(holderHeader)) |
| + } |
| + }) |
| +} |
| + |
| +// refusal is the answer to one request for shop.example.com, born HA or |
| +// not, on a fresh activator that setup arranges to refuse it. |
| +func refusal(t *testing.T, ha bool, setup func(*Service, *fakeBackend)) *httptest.ResponseRecorder { |
| + t.Helper() |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + setup(a, b) |
| + rt := testRoute("shop.example.com") |
| + rt.HA = ha |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), rt, mustNotProxy(t)) |
| + return rec |
| +} |
| + |
| +func TestHoppedOtherRefusalsSayNone(t *testing.T) { |
| + asForwarded(t) |
| + old := wakeWaitBound |
| + wakeWaitBound = 100 * time.Millisecond |
| + t.Cleanup(func() { wakeWaitBound = old }) |
| + cases := []struct { |
| + name string |
| + retry string |
| + setup func(*Service, *fakeBackend) |
| + }{ |
| + {"config refusal", "30", func(_ *Service, b *fakeBackend) { b.acquireErr = &errConfigRefused{err: errors.New("no key")} }}, |
| + {"lease refusal", "10", func(_ *Service, b *fakeBackend) { b.acquireErr = &errLeaseRefused{reason: "outside the nested layout"} }}, |
| + {"wake timeout", "5", func(_ *Service, b *fakeBackend) { |
| + gate := make(chan struct{}) |
| + b.startGate = gate |
| + t.Cleanup(func() { close(gate) }) |
| + }}, |
| + {"fence", "5", func(a *Service, _ *fakeBackend) { |
| + a.mu.Lock() |
| + a.fences = map[string]uint64{"shop.example.com": 1} |
| + a.mu.Unlock() |
| + }}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + today := refusal(t, false, c.setup) |
| + got := refusal(t, true, c.setup) |
| + if got.Code != 503 || got.Code != today.Code || got.Header().Get("Retry-After") != c.retry || |
| + today.Header().Get("Retry-After") != c.retry || got.Body.String() != today.Body.String() { |
| + t.Fatalf("HA %d %q %q, today %d %q %q", got.Code, got.Header().Get("Retry-After"), got.Body, |
| + today.Code, today.Header().Get("Retry-After"), today.Body) |
| + } |
| + if h := got.Header().Get(holderHeader); h != "none" { |
| + t.Fatalf("X-Carlos-Holder %q, want none", h) |
| + } |
| + if h := today.Header().Get(holderHeader); h != "" { |
| + t.Fatalf("a legacy route's refusal names a holder: %q", h) |
| + } |
| + }) |
| + } |
| + t.Run("cancelled", func(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + b.acquireErr = context.Canceled |
| + rt := testRoute("shop.example.com") |
| + rt.HA = true |
| + rec := httptest.NewRecorder() |
| + a.serveWakeError(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), rt, context.Canceled) |
| + if len(rec.Header()) != 0 || rec.Body.Len() != 0 { |
| + t.Fatalf("a cancelled request was answered: %v %q", rec.Header(), rec.Body) |
| + } |
| + }) |
| +} |
| + |
| +func TestLegacyHopUnchanged(t *testing.T) { |
| + asForwarded(t) |
| + rec := refusal(t, false, func(_ *Service, b *fakeBackend) { |
| + b.acquireErr = &errLeaseHeld{holder: heldByB, retryAfter: 7 * time.Second} |
| + }) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") != "8" { |
| + t.Fatalf("answer %d, Retry-After %q, want 503 and 8", rec.Code, rec.Header().Get("Retry-After")) |
| + } |
| + if _, ok := rec.Header()[holderHeader]; ok { |
| + t.Fatalf("a legacy hop's answer names a holder: %q", rec.Header().Get(holderHeader)) |
| + } |
| +} |
| + |
| +func TestHolderCacheDroppedOnHeaderless503(t *testing.T) { |
| + s := haHeldByB(t) |
| + host := s.rt.Host |
| + s.a.holders.set(host, "b") |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 200}) |
| + if ref, _, _ := s.a.holders.get(host); ref != "b" { |
| + t.Fatalf("a 200 changed the entry to %q", ref) |
| + } |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503}) |
| + if _, _, found := s.a.holders.get(host); found { |
| + t.Fatal("a 503 naming nobody kept the entry") |
| + } |
| +} |
| + |
| +func TestScheduledTickNeverForwards(t *testing.T) { |
| + s := haHeldByB(t) |
| + 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 }) |
| + rec := httptest.NewRecorder() |
| + s.a.ServeScheduled(rec, httptest.NewRequest("POST", "http://shop.example.com/", nil), s.rt, mustNotProxy(t)) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") == "" || rec.Header().Get("Retry-After") == "1" || |
| + rec.Body.String() != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("answer %d, Retry-After %q, body %q", rec.Code, rec.Header().Get("Retry-After"), rec.Body) |
| + } |
| + if _, ok := rec.Header()[holderHeader]; ok { |
| + t.Fatal("a scheduled tick's answer names a holder") |
| + } |
| + if reads.Load() != 0 { |
| + t.Fatal("the tick asked for a forward target") |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("the tick set a holder entry") |
| + } |
| +} |