region-ha-dead-holder-backoff
Squashed from region-ha-dead-holder-backoff into main.
14 files changed,
+1,436
−160
docs/superpowers/notes/census-proposal-region-ha-dead-holder-backoff.md+21 −0docs/superpowers/notes/census-region-ha-dead-holder-backoff-claims.md+4 −0internal/activator/hacache.go+163 −50internal/activator/haforward.go+29 −25internal/activator/haforward_test.go+34 −42internal/activator/hasuspect_test.go+481 −0internal/edge/backhaul_e2e_test.go+3 −0internal/edge/forwardha.go+153 −30internal/edge/forwardha_export_test.go+76 −0internal/edge/forwardha_test.go+355 −11internal/edge/forwardha_wiring_test.go+106 −0internal/host/haforward_wiring_test.go+2 −2internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-region-ha-dead-holder-backoff.tsv+8 −0
CI failed — run details
diff --git a/docs/superpowers/notes/census-proposal-region-ha-dead-holder-backoff.md b/docs/superpowers/notes/census-proposal-region-ha-dead-holder-backoff.md| new file mode 100644 |
| index 000000000..7c6dc3b24 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-region-ha-dead-holder-backoff.md |
| @@ -0,0 +1,21 @@ |
| +# Census approval: region-ha-dead-holder-backoff |
| + |
| +Ruling `census-ruling-region-ha-dead-holder-backoff`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/edge/forwardha.go` `Edge.frontForwardHA` | body | unchanged (5) | ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it. | |
| +| `internal/activator/haforward.go` `Service.ForwardTarget` | sites | -registry:Host | Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/edge`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/edge/forwardha.go` `Edge.frontForwardHA`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it |
| +- `internal/activator/haforward.go` `Service.ForwardTarget`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it |
| + |
| +Seal: `5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64` → `8f6a1865b0abcea9d4fb68232cc2a25263a106ec87f73bd4b3f2fb388971ebe5`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-dead-holder-backoff.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-region-ha-dead-holder-backoff-claims.md b/docs/superpowers/notes/census-region-ha-dead-holder-backoff-claims.md| new file mode 100644 |
| index 000000000..0dae7e6a2 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-region-ha-dead-holder-backoff-claims.md |
| @@ -0,0 +1,4 @@ |
| +# CLAIMS for the root-read census, branch region-ha-dead-holder-backoff (region HA P1b-2 follow-up: dead-holder backoff), round 2 (final) fixes. |
| +# Format (AGENTS.md "The census"): <file>:<unit><TAB><what changed>. Lines starting with # are ignored. |
| +internal/edge/forwardha.go:Edge.frontForwardHA ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it. |
| +internal/activator/haforward.go:Service.ForwardTarget Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it. |
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go| index c1b73ded7..520e1b923 100644 |
| --- a/internal/activator/hacache.go |
| +++ b/internal/activator/hacache.go |
| @@ -12,9 +12,16 @@ import ( |
| // 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. |
| +// missing. A suspect one names a holder that did not answer a forward: the |
| +// host's requests are refused until it expires, and the request after that |
| +// reads the lock again. Every entry carries a generation, handed out with |
| +// each forward and renewed by each change, so an outcome older than the |
| +// cache's news is ignored. (How many dials a dead holder costs is bounded |
| +// where the dials are made, in the edge's forward transport: |
| +// forwardDialGate.) 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 |
| @@ -24,6 +31,11 @@ const ( |
| // 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 |
| + // holderSuspectTTL is how long a holder that did not answer a forward |
| + // is suspect: its host's requests are refused at the front door, with |
| + // no lock read and no dial, so a dead holder whose lease has not run |
| + // out costs one lock read and one failed dial per host per 10 s per box. |
| + holderSuspectTTL = 10 * time.Second |
| ) |
| // holderCache is host to holder box reference. The zero value is ready; |
| @@ -34,21 +46,32 @@ type holderCache struct { |
| holders 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 |
| + seq uint64 // the last generation handed out |
| } |
| type holderEntry struct { |
| host string |
| ref string // "" for a negative entry |
| + suspect bool // ref did not answer a forward |
| expires time.Time |
| + // gen is the entry's generation, new with every put and every answer |
| + // from ref: a forward's failure counts only under it. |
| + gen uint64 |
| } |
| // 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. |
| +// before that news, so its answer is not cached and its callers look |
| +// again. suspect is the ref of the expired suspect entry the read |
| +// replaces: if the read fails, the box stays suspect and every caller is |
| +// refused (refuse). cached is whether the read's answer was cached. |
| type holderFlight struct { |
| - done chan struct{} |
| - ref string |
| - stale bool |
| + done chan struct{} |
| + ref string |
| + suspect string |
| + refuse bool |
| + cached bool |
| + stale bool |
| } |
| func (c *holderCache) clock() time.Time { |
| @@ -59,15 +82,11 @@ func (c *holderCache) clock() time.Time { |
| } |
| // 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). |
| +// positive false for a negative entry or a suspect one (which keeps its |
| +// ref), 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.holders[host] |
| if el == nil { |
| return "", false, false |
| @@ -77,7 +96,7 @@ func (c *holderCache) getLocked(host string) (string, bool, bool) { |
| c.removeLocked(el) |
| return "", false, false |
| } |
| - return e.ref, e.ref != "", true |
| + return e.ref, e.ref != "" && !e.suspect, true |
| } |
| // set names ref as host's holder for holderPositiveTTL. An empty ref sets |
| @@ -88,7 +107,7 @@ func (c *holderCache) set(host, ref string) { |
| } |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| - c.putLocked(host, ref, holderPositiveTTL) |
| + c.putLocked(host, ref, false, holderPositiveTTL) |
| } |
| // setNegative remembers for holderNegativeTTL that host is not held |
| @@ -96,7 +115,54 @@ func (c *holderCache) set(host, ref string) { |
| func (c *holderCache) setNegative(host string) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| - c.putLocked(host, "", holderNegativeTTL) |
| + c.putLocked(host, "", false, holderNegativeTTL) |
| +} |
| + |
| +// unreachable follows a forward under gen that could not connect: its box |
| +// is suspect for holderSuspectTTL. An outcome under an older generation is |
| +// ignored: the entry has changed since (a success, a holder header, a |
| +// drop), or it is suspect already, so of many forwards failing together |
| +// one lands. Generations are never reused, so gen also names the box. |
| +func (c *holderCache) unreachable(host string, gen uint64) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + el := c.holders[host] |
| + if el == nil || gen == 0 { |
| + return |
| + } |
| + if e := el.Value.(*holderEntry); e.gen == gen && e.ref != "" && !e.suspect { |
| + c.putLocked(host, e.ref, true, holderSuspectTTL) |
| + } |
| +} |
| + |
| +// answered follows a forward of host's to ref that came back with an |
| +// answer: ref is reachable. A suspect entry is replaced by ref as the |
| +// holder; an entry naming ref gets a new generation, so older failures no |
| +// longer count. With no entry, a read revalidating an expired suspect is |
| +// overtaken: ref is the holder, and the read's answer is not cached. Any |
| +// other entry stands, and nothing is set when no read is in flight: a |
| +// drop (this box taking the lease, a holder saying none) is not undone. |
| +func (c *holderCache) answered(host, ref string) { |
| + if ref == "" { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + el := c.holders[host] |
| + if el == nil { |
| + if f := c.flights[host]; f != nil && f.suspect != "" && !f.stale { |
| + c.putLocked(host, ref, false, holderPositiveTTL) |
| + } |
| + return |
| + } |
| + e := el.Value.(*holderEntry) |
| + switch { |
| + case e.suspect: |
| + c.putLocked(host, ref, false, holderPositiveTTL) |
| + case e.ref == ref: |
| + c.seq++ |
| + e.gen = c.seq |
| + } |
| } |
| // drop forgets host's entry, and any read in flight for it. |
| @@ -111,24 +177,26 @@ func (c *holderCache) drop(host string) { |
| } |
| } |
| -func (c *holderCache) putLocked(host, ref string, ttl time.Duration) { |
| +// 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 { |
| f.stale = true |
| } |
| if c.holders == nil { |
| c.holders = map[string]*list.Element{} |
| } |
| + c.seq++ |
| expires := c.clock().Add(ttl) |
| if el := c.holders[host]; el != nil { |
| e := el.Value.(*holderEntry) |
| - e.ref, e.expires = ref, expires |
| + e.ref, e.suspect, e.expires, e.gen = ref, suspect, expires, c.seq |
| c.order.MoveToBack(el) |
| return |
| } |
| for len(c.holders) >= holderCacheMax { |
| c.removeLocked(c.order.Front()) |
| } |
| - c.holders[host] = c.order.PushBack(&holderEntry{host: host, ref: ref, expires: expires}) |
| + c.holders[host] = c.order.PushBack(&holderEntry{host: host, ref: ref, suspect: suspect, expires: expires, gen: c.seq}) |
| } |
| func (c *holderCache) removeLocked(el *list.Element) { |
| @@ -136,48 +204,93 @@ func (c *holderCache) removeLocked(el *list.Element) { |
| 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 "" |
| +// resolve answers a request for host: the holder to forward to and the |
| +// generation to report its outcome under, "" to serve here, or refuse |
| +// while the holder is suspect. A live entry answers at once. A miss is 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. A read that replaces an expired suspect entry and fails keeps |
| +// the box suspect for another window and refuses its callers; a read |
| +// overtaken by news sends its callers to look again, within twice the |
| +// read's timeout in all. |
| +func (c *holderCache) resolve(ctx context.Context, host string, read func() (ref string, ok bool)) (string, bool, uint64) { |
| + deadline := time.Now().Add(2 * holderReadTimeout) |
| + for time.Now().Before(deadline) { |
| + c.mu.Lock() |
| + suspect := "" |
| + if el := c.holders[host]; el != nil { |
| + e := el.Value.(*holderEntry) |
| + if c.clock().Before(e.expires) { |
| + ref, refuse, gen := e.ref, e.suspect, e.gen |
| + c.mu.Unlock() |
| + if refuse { |
| + return "", true, 0 |
| + } |
| + if ref == "" { |
| + return "", false, 0 |
| + } |
| + return ref, false, gen |
| + } |
| + if e.suspect { |
| + suspect = e.ref |
| + } |
| + c.removeLocked(el) |
| } |
| + f := c.flights[host] |
| + if f != nil { |
| + c.mu.Unlock() |
| + select { |
| + case <-f.done: |
| + case <-ctx.Done(): |
| + return "", false, 0 |
| + } |
| + } else { |
| + f = &holderFlight{done: make(chan struct{}), suspect: suspect} |
| + if c.flights == nil { |
| + c.flights = map[string]*holderFlight{} |
| + } |
| + c.flights[host] = f |
| + c.mu.Unlock() |
| + c.runRead(host, f, read) |
| + } |
| + switch { |
| + case f.refuse: |
| + return "", true, 0 |
| + case f.cached, f.stale: |
| + continue |
| + } |
| + return f.ref, false, 0 |
| } |
| - f := &holderFlight{done: make(chan struct{})} |
| - if c.flights == nil { |
| - c.flights = map[string]*holderFlight{} |
| - } |
| - c.flights[host] = f |
| - c.mu.Unlock() |
| + return "", false, 0 |
| +} |
| +// runRead runs f's read for host and settles f: its answer cached, unless |
| +// news arrived while it ran (stale), or kept from caching when it could not |
| +// tell. |
| +func (c *holderCache) runRead(host string, f *holderFlight, read func() (string, bool)) { |
| ref, ok := "", false |
| defer func() { |
| c.mu.Lock() |
| + // Out of the map first, so the puts below do not mark f stale. |
| delete(c.flights, host) |
| - if ok && !f.stale { |
| - if ref != "" { |
| - c.putLocked(host, ref, holderPositiveTTL) |
| - } else { |
| - c.putLocked(host, "", holderNegativeTTL) |
| - } |
| + switch { |
| + case f.stale: |
| + case ok && ref != "": |
| + c.putLocked(host, ref, false, holderPositiveTTL) |
| + f.cached = true |
| + case ok: |
| + c.putLocked(host, "", false, holderNegativeTTL) |
| + f.cached = true |
| + case f.suspect != "": |
| + // A failed read proves no holder gone: the box that did not |
| + // answer stays suspect for another window. |
| + c.putLocked(host, f.suspect, true, holderSuspectTTL) |
| + f.refuse = true |
| } |
| 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| index 4daed63d1..9d0240102 100644 |
| --- a/internal/activator/haforward.go |
| +++ b/internal/activator/haforward.go |
| @@ -24,11 +24,12 @@ import ( |
| // (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. |
| +// that is out of view, answers "none", or answers 503 without naming |
| +// anyone is dropped at once, and the request is served here or retried |
| +// against a fresh read; one that is unreachable is suspect for 10 s, and |
| +// the request after that reads afresh; 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) |
| @@ -97,33 +98,28 @@ const holderReadTimeout = 2 * time.Second |
| // 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, |
| +// ForwardTarget says what to do with rt's request: forward it to the box |
| +// that holds the host, refuse it while that box is suspect, or serve it |
| +// here. Always here 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 { |
| +func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) edge.ForwardDecision { |
| if !rt.HA { |
| - return "" |
| + return edge.ForwardDecision{} |
| } |
| r := holderReaderFor(a.backend, rt) |
| if r == nil { |
| - return "" |
| + return edge.ForwardDecision{} |
| } |
| 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 edge.ForwardDecision{} |
| } |
| - return a.holders.resolve(ctx, rt.Host, func() (string, bool) { |
| + ref, refuse, gen := a.holders.resolve(ctx, rt.Host, func() (string, bool) { |
| // The read is every queued caller's, not only this one's: detached |
| // from this request's cancellation, so one visitor hanging up does |
| // not fail the rest, and bounded on its own. |
| @@ -140,6 +136,7 @@ func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) string { |
| self, _ := boxSelfRef(a.backend) |
| return otherHolder(v, self, a.holders.clock()), true |
| }) |
| + return edge.ForwardDecision{Ref: ref, Refuse: refuse, Gen: gen} |
| } |
| // otherHolder is the box v names as holding the host, when that is an |
| @@ -158,13 +155,18 @@ func otherHolder(v hafresh.View, self string, now time.Time) string { |
| } |
| // 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). |
| +// view, 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). A box that could not be connected to |
| +// is suspect for holderSuspectTTL, unless the forward's generation is |
| +// older than the entry's; any other answer from a box clears a suspect |
| +// entry: that box is the holder. |
| func (a *Service) NoteForward(host string, res edge.ForwardResult) { |
| switch { |
| - case res.Outcome == edge.ForwardNotInView, res.Outcome == edge.ForwardUnreachable: |
| + case res.Outcome == edge.ForwardNotInView: |
| a.holders.drop(host) |
| + case res.Outcome == edge.ForwardUnreachable: |
| + a.holders.unreachable(host, res.Gen) |
| case res.Holder == holderNone: |
| a.holders.drop(host) |
| case res.Holder != "": |
| @@ -175,6 +177,8 @@ func (a *Service) NoteForward(host string, res edge.ForwardResult) { |
| a.holders.set(host, res.Holder) |
| case res.Status == http.StatusServiceUnavailable: |
| a.holders.drop(host) |
| + case res.Status != 0: |
| + a.holders.answered(host, res.Ref) |
| } |
| } |
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go| index 226c5d6d9..d534f9f1c 100644 |
| --- a/internal/activator/haforward_test.go |
| +++ b/internal/activator/haforward_test.go |
| @@ -6,7 +6,6 @@ import ( |
| "fmt" |
| "net/http" |
| "net/http/httptest" |
| - "sync" |
| "sync/atomic" |
| "testing" |
| "time" |
| @@ -51,13 +50,14 @@ func haHeldByB(t *testing.T) *haSvc { |
| 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) |
| + d := s.a.ForwardTarget(context.Background(), s.rt) |
| + if d.Ref != "b" { |
| + t.Fatalf("ForwardTarget = %+v, want b", d) |
| } |
| 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" { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "b" { |
| t.Fatalf("ForwardTarget on a hit = %q, want b", got) |
| } |
| if n := lockGets(s.b, s.rt); n != 1 { |
| @@ -70,7 +70,7 @@ func TestForwardTargetServesHere(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 != "" { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" { |
| t.Fatalf("ForwardTarget for a host awake here = %q", got) |
| } |
| if n := lockGets(s.b, s.rt) - before; n != 0 { |
| @@ -83,18 +83,18 @@ func TestForwardTargetServesHere(t *testing.T) { |
| 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 != "" { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; 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 { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; 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 { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" || lockGets(s.b, s.rt) != 2 { |
| t.Fatalf("at 11 s: %q, %d reads, want \"\" and 2", got, lockGets(s.b, s.rt)) |
| } |
| }) |
| @@ -102,7 +102,7 @@ func TestForwardTargetServesHere(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 != "" { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" { |
| t.Fatalf("ForwardTarget over this box's own lease = %q", got) |
| } |
| }) |
| @@ -110,21 +110,21 @@ func TestForwardTargetServesHere(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 != "" { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; 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 { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; 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 != "" { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" { |
| t.Fatalf("a failed read = %q", got) |
| } |
| if _, _, found := s.a.holders.get(s.rt.Host); found { |
| @@ -144,22 +144,13 @@ func TestForwardTargetSingleFlight(t *testing.T) { |
| 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) |
| - }() |
| - } |
| + got := s.concurrently(20) |
| 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) |
| + for i := range 20 { |
| + if d := recv(t, got); d.Ref != "b" || d.Refuse { |
| + t.Fatalf("caller %d got %+v, want b", i, d) |
| } |
| } |
| if n := reads.Load(); n != 1 { |
| @@ -170,16 +161,16 @@ func TestForwardTargetSingleFlight(t *testing.T) { |
| } |
| } |
| -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) |
| - } |
| +// A box out of view drops the entry. (An unreachable one is suspect: |
| +// hasuspect_test.go.) |
| +func TestHolderCacheDroppedOutOfView(t *testing.T) { |
| + s := haHeldByB(t) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "b" { |
| + t.Fatalf("ForwardTarget = %q, want b", got) |
| + } |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardNotInView, Ref: "b"}) |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("a box out of view kept the entry") |
| } |
| } |
| @@ -191,7 +182,7 @@ func TestHolderCacheFollowsHolderHeader(t *testing.T) { |
| 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 { |
| + if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; 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"}) |
| @@ -403,13 +394,14 @@ func TestScheduledTickNeverForwards(t *testing.T) { |
| func TestForwardTargetThroughSplitBackend(t *testing.T) { |
| s := haHeldByB(t) |
| a := New(Config{Bucket: s.b.Cfg.Bucket, Idle: time.Hour}, &SplitBackend{Exec: s.b, Unit: &UnitBackend{}}, s.b.Registry) |
| - if got := a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| - t.Fatalf("ForwardTarget through the split backend = %q, want b", got) |
| + d := a.ForwardTarget(context.Background(), s.rt) |
| + if d.Ref != "b" { |
| + t.Fatalf("ForwardTarget through the split backend = %+v, want b", d) |
| } |
| if n := lockGets(s.b, s.rt); n != 1 { |
| t.Fatalf("%d lock reads on a miss, want 1", n) |
| } |
| - if got := a.ForwardTarget(context.Background(), s.rt); got != "b" || lockGets(s.b, s.rt) != 1 { |
| + if got := a.ForwardTarget(context.Background(), s.rt).Ref; got != "b" || lockGets(s.b, s.rt) != 1 { |
| t.Fatalf("a hit: %q with %d reads, want b and 1", got, lockGets(s.b, s.rt)) |
| } |
| // This box's identity is the exec half's: an answer naming it drops. |
| @@ -419,7 +411,7 @@ func TestForwardTargetThroughSplitBackend(t *testing.T) { |
| } |
| unit := s.rt |
| unit.Host, unit.Backing = "unit.example.com", registry.BackingUnit |
| - if got := a.ForwardTarget(context.Background(), unit); got != "" { |
| + if got := a.ForwardTarget(context.Background(), unit).Ref; got != "" { |
| t.Fatalf("a unit-backed row = %q", got) |
| } |
| } |
| @@ -490,7 +482,7 @@ func TestForwardTargetStalledReadIsBounded(t *testing.T) { |
| start := time.Now() |
| got := make(chan string, 10) |
| for range cap(got) { |
| - go func() { got <- s.a.ForwardTarget(context.Background(), s.rt) }() |
| + go func() { got <- s.a.ForwardTarget(context.Background(), s.rt).Ref }() |
| } |
| bound := time.After(holderReadTimeout + 2*time.Second) |
| for range cap(got) { |
| @@ -513,7 +505,7 @@ func TestForwardTargetStalledReadIsBounded(t *testing.T) { |
| t.Fatalf("%d flights left after the stalled read", flights) |
| } |
| t.Setenv("CARLOS_S3_ENDPOINT", s.fx.URL) |
| - if ref := s.a.ForwardTarget(context.Background(), s.rt); ref != "b" || lockGets(s.b, s.rt) != 1 { |
| + if ref := s.a.ForwardTarget(context.Background(), s.rt).Ref; ref != "b" || lockGets(s.b, s.rt) != 1 { |
| t.Fatalf("the lookup after the stall: %q with %d reads, want b and 1", ref, lockGets(s.b, s.rt)) |
| } |
| } |
diff --git a/internal/activator/hasuspect_test.go b/internal/activator/hasuspect_test.go| new file mode 100644 |
| index 000000000..d567d1ab9 |
| --- /dev/null |
| +++ b/internal/activator/hasuspect_test.go |
| @@ -0,0 +1,481 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// Region HA P1b-2 follow-up: a holder that did not answer a forward is |
| +// suspect for holderSuspectTTL. While it is, a visitor's request for the |
| +// host is refused at the front door with no lock read, no dial and no |
| +// local wake; with the edge's dial gate (forwardDialGate) a dead holder |
| +// whose lease has not run out costs each box one lock read and one failed |
| +// dial per window per host. |
| + |
| +// frontDoor is one visitor request for s's host at the edge's front door |
| +// (edge.frontForwardHA), over a forward that never connects. It asks |
| +// ForwardTarget and says what the edge does: "refused" (the front door's |
| +// 503, Retry-After: 10, TestFrontForwardSuspectRefusalRunsNoLocalStep), |
| +// "unreachable" (a forward to the named box that could not connect, counted |
| +// in forwards and noted as ForwardUnreachable: the same 503, |
| +// TestForwardHADialFailureIs503RetryTen), or "here" (served on this box). |
| +func (s *haSvc) frontDoor(t *testing.T, forwards *int) string { |
| + t.Helper() |
| + d := s.a.ForwardTarget(context.Background(), s.rt) |
| + switch { |
| + case d.Refuse: |
| + if d.Ref != "" { |
| + t.Fatalf("a refusal names %q", d.Ref) |
| + } |
| + return "refused" |
| + case d.Ref == "": |
| + return "here" |
| + } |
| + *forwards++ |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardUnreachable, Ref: d.Ref, Gen: d.Gen}) |
| + return "unreachable" |
| +} |
| + |
| +// decide is one ForwardTarget for s's route. |
| +func (s *haSvc) decide() edge.ForwardDecision { |
| + return s.a.ForwardTarget(context.Background(), s.rt) |
| +} |
| + |
| +// note is NoteForward for s's host of a forward decided as d. |
| +func (s *haSvc) note(d edge.ForwardDecision, res edge.ForwardResult) { |
| + res.Ref, res.Gen = d.Ref, d.Gen |
| + s.a.NoteForward(s.rt.Host, res) |
| +} |
| + |
| +// concurrently runs n ForwardTargets for s's route at once and returns a |
| +// channel of their decisions, in the order they return. |
| +func (s *haSvc) concurrently(n int) <-chan edge.ForwardDecision { |
| + out := make(chan edge.ForwardDecision, n) |
| + for range n { |
| + go func() { out <- s.decide() }() |
| + } |
| + return out |
| +} |
| + |
| +// recv is the next decision on ch, within 10 s. |
| +func recv(t *testing.T, ch <-chan edge.ForwardDecision) edge.ForwardDecision { |
| + t.Helper() |
| + select { |
| + case d := <-ch: |
| + return d |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("a request is still waiting") |
| + } |
| + return edge.ForwardDecision{} |
| +} |
| + |
| +// wokeHere is whether the host has an entry on this box: awake or waking. |
| +func (s *haSvc) wokeHere() bool { |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + return s.a.entries[s.rt.Host] != nil |
| +} |
| + |
| +// suspectB is haHeldByB on a fake cache clock, after one request that |
| +// forwarded to b and could not connect: b is suspect. |
| +func suspectB(t *testing.T) (*haSvc, *fakeClock) { |
| + t.Helper() |
| + s := haHeldByB(t) |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.holders.now = clk.now |
| + forwards := 0 |
| + if got := s.frontDoor(t, &forwards); got != "unreachable" || forwards != 1 || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("the first request: %s, %d forwards, %d reads; want unreachable, 1 and 1", got, forwards, lockGets(s.b, s.rt)) |
| + } |
| + if got := s.frontDoor(t, &forwards); got != "refused" { |
| + t.Fatalf("the request after an unreachable forward: %s, want refused", got) |
| + } |
| + return s, clk |
| +} |
| + |
| +func TestDeadHolderCostsOneReadAndDialPerWindow(t *testing.T) { |
| + s := haHeldByB(t) |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.holders.now = clk.now |
| + start := clk.now() |
| + forwards := 0 |
| + for i := range 50 { |
| + want := "refused" |
| + if i == 0 { |
| + want = "unreachable" |
| + } |
| + if got := s.frontDoor(t, &forwards); got != want { |
| + t.Fatalf("request %d at %v: %s, want %s", i, clk.now().Sub(start), got, want) |
| + } |
| + clk.advance(190 * time.Millisecond) // 50 requests in 9.5 s |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 || forwards != 1 { |
| + t.Fatalf("50 requests within the window: %d lock reads and %d forwards, want 1 and 1", n, forwards) |
| + } |
| + if s.wokeHere() { |
| + t.Fatal("a refused request woke the host here") |
| + } |
| + |
| + // The window is over: the next request reads the lock once, finds b's |
| + // lease still unexpired, forwards once more, and b is suspect again. |
| + clk.t = start.Add(holderSuspectTTL + time.Millisecond) |
| + if got := s.frontDoor(t, &forwards); got != "unreachable" { |
| + t.Fatalf("the request after the window: %s, want unreachable", got) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 2 || forwards != 2 { |
| + t.Fatalf("after the window: %d lock reads and %d forwards, want 2 and 2", n, forwards) |
| + } |
| + for i := range 10 { |
| + clk.advance(500 * time.Millisecond) |
| + if got := s.frontDoor(t, &forwards); got != "refused" { |
| + t.Fatalf("request %d of the second window: %s, want refused", i, got) |
| + } |
| + } |
| + if n := lockGets(s.b, s.rt); n != 2 || forwards != 2 { |
| + t.Fatalf("the second window: %d lock reads and %d forwards, want 2 and 2", n, forwards) |
| + } |
| +} |
| + |
| +// Concurrent requests after the window: one lock read, and all of them |
| +// forward to b under one generation (the edge's dial gate makes that one |
| +// dial). Of their twenty failures one lands: b is suspect once. |
| +func TestSuspectWindowEndReadsOnce(t *testing.T) { |
| + s, clk := suspectB(t) |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + 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 }) |
| + got := s.concurrently(20) |
| + waitFor(t, "the read", func() bool { return reads.Load() == 1 }) |
| + time.Sleep(50 * time.Millisecond) // the others queue on it |
| + close(gate) |
| + ds := make([]edge.ForwardDecision, 20) |
| + for i := range ds { |
| + ds[i] = recv(t, got) |
| + if ds[i].Ref != "b" || ds[i].Refuse || ds[i].Gen != ds[0].Gen { |
| + t.Fatalf("caller %d: %+v, want b under the first caller's gen %d", i, ds[i], ds[0].Gen) |
| + } |
| + } |
| + s.a.holders.mu.Lock() |
| + seq := s.a.holders.seq |
| + s.a.holders.mu.Unlock() |
| + for _, d := range ds { |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + } |
| + s.a.holders.mu.Lock() |
| + landed := s.a.holders.seq - seq |
| + s.a.holders.mu.Unlock() |
| + if landed != 1 || reads.Load() != 1 { |
| + t.Fatalf("20 failures under one gen changed the entry %d times with %d reads, want 1 and 1", landed, reads.Load()) |
| + } |
| + if d := s.decide(); !d.Refuse { |
| + t.Fatalf("after the failures: %+v, want a refusal", d) |
| + } |
| +} |
| + |
| +// A read that revalidates an expired suspect and fails proves nothing: the |
| +// window is renewed for the same box and every caller on that read is |
| +// refused, unless newer news arrived while it ran. |
| +func TestSuspectRevalidationFailureRenewsTheWindow(t *testing.T) { |
| + t.Run("error", func(t *testing.T) { |
| + s, clk := suspectB(t) |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + s.fx.FailNext("GET", http.StatusForbidden) |
| + forwards := 0 |
| + if got := s.frontDoor(t, &forwards); got != "refused" { |
| + t.Fatalf("a failed revalidation: %s, want refused", got) |
| + } |
| + reads := lockGets(s.b, s.rt) |
| + for i := range 5 { |
| + clk.advance(time.Second) |
| + if got := s.frontDoor(t, &forwards); got != "refused" { |
| + t.Fatalf("request %d of the renewed window: %s, want refused", i, got) |
| + } |
| + } |
| + if n := lockGets(s.b, s.rt); n != reads || forwards != 0 || s.wokeHere() { |
| + t.Fatalf("the renewed window: %d more reads, %d forwards, woke here %v; want none", n-reads, forwards, s.wokeHere()) |
| + } |
| + clk.advance(holderSuspectTTL) |
| + if got := s.frontDoor(t, &forwards); got != "unreachable" || lockGets(s.b, s.rt) != reads+1 { |
| + t.Fatalf("after the renewed window: %s with %d more reads, want unreachable and 1", got, lockGets(s.b, s.rt)-reads) |
| + } |
| + }) |
| + t.Run("timeout", func(t *testing.T) { |
| + s, clk := suspectB(t) |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + var reads atomic.Int32 |
| + old := readHolderLock |
| + readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) { |
| + reads.Add(1) |
| + <-ctx.Done() |
| + return hafresh.View{}, ctx.Err() |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + got := s.concurrently(5) |
| + for i := range 5 { |
| + if d := recv(t, got); !d.Refuse { |
| + t.Fatalf("caller %d on a timed-out revalidation: %+v, want a refusal", i, d) |
| + } |
| + } |
| + if d := s.decide(); !d.Refuse || reads.Load() != 1 { |
| + t.Fatalf("within the renewed window: %+v with %d reads, want a refusal and 1", d, reads.Load()) |
| + } |
| + }) |
| + t.Run("newer news", func(t *testing.T) { |
| + s, clk := suspectB(t) |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + gate := make(chan struct{}) |
| + var reads atomic.Int32 |
| + old := readHolderLock |
| + readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) { |
| + reads.Add(1) |
| + <-gate |
| + return hafresh.View{}, context.DeadlineExceeded |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + got := s.concurrently(1) |
| + waitFor(t, "the read", func() bool { return reads.Load() == 1 }) |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "c", Status: 503, Holder: "c"}) |
| + close(gate) |
| + if d := recv(t, got); d.Refuse || d.Ref != "c" { |
| + t.Fatalf("a failed read overtaken by X-Carlos-Holder: c: %+v, want a forward to c", d) |
| + } |
| + }) |
| +} |
| + |
| +// A forward that answers while a suspect's revalidation read runs is |
| +// newer news: the read's failure no longer renews the suspicion, and the |
| +// box that answered is the holder. It never recreates an entry that this |
| +// box taking the lease removed meanwhile. |
| +func TestSuccessDuringRevalidationWins(t *testing.T) { |
| + holdRead := func(t *testing.T) (started func() bool, release func()) { |
| + t.Helper() |
| + gate := make(chan struct{}) |
| + var reads atomic.Int32 |
| + old := readHolderLock |
| + readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) { |
| + reads.Add(1) |
| + <-gate |
| + return hafresh.View{}, context.DeadlineExceeded |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + return func() bool { return reads.Load() == 1 }, func() { close(gate) } |
| + } |
| + t.Run("success", func(t *testing.T) { |
| + s, clk := suspectB(t) |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + started, release := holdRead(t) |
| + got := s.concurrently(1) |
| + waitFor(t, "the revalidation read", started) |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "b", Status: http.StatusOK}) |
| + release() |
| + if d := recv(t, got); d.Refuse || d.Ref != "b" { |
| + t.Fatalf("the revalidating request after b answered and the read failed: %+v, want a forward to b", d) |
| + } |
| + if ref, positive, _ := s.a.holders.get(s.rt.Host); ref != "b" || !positive { |
| + t.Fatalf("the entry is %q (positive %v), want b", ref, positive) |
| + } |
| + }) |
| + t.Run("lease acquisition first", 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 |
| + s.a.holders.set(s.rt.Host, "b") |
| + s.note(s.decide(), edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + started, release := holdRead(t) |
| + got := s.concurrently(1) |
| + waitFor(t, "the revalidation read", started) |
| + if _, err := s.wakeForTest(context.Background()); err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "b", Status: http.StatusOK}) |
| + release() |
| + recv(t, got) |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("an entry came back after this box took the lease") |
| + } |
| + }) |
| +} |
| + |
| +// An unreachable outcome older than the cache's news is ignored: it cannot |
| +// make a holder suspect again after a success, a holder header, or this box |
| +// taking the lease cleared it. |
| +func TestStaleUnreachableIsIgnored(t *testing.T) { |
| + // three forwards to b outstanding under one generation. |
| + outstanding := func(t *testing.T, s *haSvc) (d1, d2, d3 edge.ForwardDecision) { |
| + t.Helper() |
| + d1, d2, d3 = s.decide(), s.decide(), s.decide() |
| + if d1.Ref != "b" || d2 != d1 || d3 != d1 { |
| + t.Fatalf("decisions %+v %+v %+v, want three to b on one gen", d1, d2, d3) |
| + } |
| + s.note(d2, edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + if d := s.decide(); !d.Refuse { |
| + t.Fatalf("after d2 failed: %+v, want a refusal", d) |
| + } |
| + return d1, d2, d3 |
| + } |
| + t.Run("same-ref success", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + d1, _, d3 := outstanding(t, s) |
| + s.note(d1, edge.ForwardResult{Outcome: edge.ForwardDone, Status: http.StatusOK}) |
| + s.note(d3, edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + if d := s.decide(); d.Refuse || d.Ref != "b" { |
| + t.Fatalf("an older failure after b answered: %+v, want a forward to b", d) |
| + } |
| + }) |
| + t.Run("holder header", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + d1, _, d3 := outstanding(t, s) |
| + s.note(d1, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "b"}) |
| + s.note(d3, edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + if d := s.decide(); d.Refuse || d.Ref != "b" { |
| + t.Fatalf("an older failure after X-Carlos-Holder: b: %+v, want a forward to b", d) |
| + } |
| + }) |
| + t.Run("lease acquisition", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + s.a.holders.set(s.rt.Host, "b") |
| + d := s.decide() |
| + if d.Ref != "b" { |
| + t.Fatalf("decision %+v, want b", d) |
| + } |
| + if _, err := s.wakeForTest(context.Background()); err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("an older failure made b suspect after this box took the lease") |
| + } |
| + }) |
| +} |
| + |
| +func TestSuspectClearedByTakingTheLease(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + s.a.holders.set(s.rt.Host, "b") |
| + s.note(s.decide(), edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + if d := s.decide(); !d.Refuse { |
| + t.Fatalf("a suspect holder: %+v, want a refusal", d) |
| + } |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil || e == nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("the suspect entry survived this box taking the lease") |
| + } |
| + if d := s.a.ForwardTarget(context.Background(), s.rt); d != (edge.ForwardDecision{}) { |
| + t.Fatalf("awake here: %+v, want served here", d) |
| + } |
| +} |
| + |
| +func TestSuspectClearedByAHolderHeader(t *testing.T) { |
| + s, _ := suspectB(t) |
| + host := s.rt.Host |
| + // Another box's answer names c: c is the holder, no read needed. |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "c", Status: 503, Holder: "c"}) |
| + if d := s.decide(); d.Ref != "c" || d.Refuse || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("after X-Carlos-Holder: c: %+v with %d reads, want c and 1", d, lockGets(s.b, s.rt)) |
| + } |
| + |
| + // Naming this box drops the entry: the next request reads the lock. |
| + s, _ = suspectB(t) |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "c", Status: 503, Holder: "a"}) |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("X-Carlos-Holder naming this box kept the suspect entry") |
| + } |
| +} |
| + |
| +func TestSuspectClearedByASuccessfulForward(t *testing.T) { |
| + for _, ref := range []string{"b", "c"} { |
| + s, _ := suspectB(t) |
| + // A forward begun before b went suspect comes back answered. |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: ref, Status: http.StatusOK}) |
| + if d := s.decide(); d.Ref != ref || d.Refuse || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("after %s answered: %+v with %d reads, want %s and 1", ref, d, lockGets(s.b, s.rt), ref) |
| + } |
| + } |
| + // A forward that came back with no answer (Status 0) proves nothing. |
| + s, _ := suspectB(t) |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "b"}) |
| + if d := s.a.ForwardTarget(context.Background(), s.rt); !d.Refuse { |
| + t.Fatalf("after a forward with no answer: %+v, want still refused", d) |
| + } |
| +} |
| + |
| +// An unreachable forward that began before newer news does not undo it: a |
| +// holder named since, or a lock read that found no holder, stands. |
| +func TestUnreachableKeepsNewerNews(t *testing.T) { |
| + s := haHeldByB(t) |
| + s.a.holders.set(s.rt.Host, "c") |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardUnreachable, Ref: "b"}) |
| + if d := s.decide(); d.Ref != "c" || d.Refuse { |
| + t.Fatalf("an old forward to b failed after c was named: %+v, want c", d) |
| + } |
| + s.a.holders.setNegative(s.rt.Host) |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardUnreachable, Ref: "b"}) |
| + if d := s.a.ForwardTarget(context.Background(), s.rt); d != (edge.ForwardDecision{}) { |
| + t.Fatalf("an old forward to b failed after a read found no holder: %+v, want served here", d) |
| + } |
| +} |
| + |
| +// P1b-1's takeover is still reached: once b's lease has expired and EC2 |
| +// says b is terminated, the first request after the suspect window reads |
| +// the lock, finds no live holder, and is served here, taking the host over. |
| +func TestSuspectThenExpiredLeaseTakesOver(t *testing.T) { |
| + s, clk := suspectB(t) |
| + oracle := &terminatedOracle{yes: map[string]bool{"i-b": true}} |
| + s.b.OwnerTerminated = oracle.terminated |
| + // b is gone and renews nothing: its lease runs out. |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute))) |
| + forwards := 0 |
| + if got := s.frontDoor(t, &forwards); got != "refused" { |
| + t.Fatalf("within the window: %s, want refused", got) |
| + } |
| + if len(oracle.calls()) != 0 || s.wokeHere() { |
| + t.Fatal("a refused request tried a wake here") |
| + } |
| + |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + if got := s.frontDoor(t, &forwards); got != "here" || forwards != 0 { |
| + t.Fatalf("after the window: %s with %d forwards, want here and none", got, forwards) |
| + } |
| + served := false |
| + rec := httptest.NewRecorder() |
| + s.a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), s.rt, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| + served = true |
| + w.WriteHeader(http.StatusOK) |
| + })) |
| + if !served || rec.Code != http.StatusOK { |
| + t.Fatalf("the request after the window: %d, proxied %v; want served here", rec.Code, served) |
| + } |
| + if got := oracle.calls(); len(got) != 1 || got[0] != "i-b" { |
| + t.Fatalf("OwnerTerminated asked about %v, want [i-b]", got) |
| + } |
| + v, err := hafresh.DecodeLock(lockBodyOf(s.b, s.rt), "x") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if o, ok := hafresh.ParseOwner(v.Lock.Owner); !ok || !o.HA || o.Ref != "a" { |
| + t.Fatalf("the lock is %+v, want this box's HA lease", v.Lock) |
| + } |
| + if d := s.a.ForwardTarget(context.Background(), s.rt); d != (edge.ForwardDecision{}) { |
| + t.Fatalf("awake here after the takeover: %+v, want served here", d) |
| + } |
| +} |
diff --git a/internal/edge/backhaul_e2e_test.go b/internal/edge/backhaul_e2e_test.go| index 909491b1e..b91bf2625 100644 |
| --- a/internal/edge/backhaul_e2e_test.go |
| +++ b/internal/edge/backhaul_e2e_test.go |
| @@ -243,6 +243,8 @@ type backhaulEdge struct { |
| local autocert.Cache |
| tlsAddr, plainAddr string |
| + // door is the 443 server at tlsAddr. |
| + door *httptest.Server |
| // calls counts requests that reached this box's 443 door, refusals |
| // included: "exactly one dial" and "never dialled at all" are both this |
| // number moving, or not, on the OTHER box. |
| @@ -385,6 +387,7 @@ func newBackhaulEdgeWith(t *testing.T, bucketDir, box string, ca *e2eCA, from *n |
| https.StartTLS() |
| t.Cleanup(https.Close) |
| be.tlsAddr = https.Listener.Addr().String() |
| + be.door = https |
| // :80, the live boot's composed chain (boot). |
| plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| index fc8407ec3..103eba4d6 100644 |
| --- a/internal/edge/forwardha.go |
| +++ b/internal/edge/forwardha.go |
| @@ -22,6 +22,7 @@ import ( |
| "fmt" |
| "net" |
| "net/http" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -31,15 +32,30 @@ import ( |
| // it with a type assertion on its Activator; an activator without it, or no |
| // activator, forwards nothing. |
| // |
| -// ForwardTarget names the box a request for rt should go to, or "" to serve |
| -// it here. NoteForward reports how the forward went, so the activator's |
| -// holder cache can follow it. host is rt.Host, the route's own host, never an |
| -// alias the request named. |
| +// ForwardTarget says what to do with a request for rt: forward it to a box, |
| +// refuse it at the front door, or serve it here. NoteForward reports how a |
| +// forward went, with the decision's Gen, so the activator's holder cache can |
| +// follow it and ignore an outcome older than what it has learned since. host |
| +// is rt.Host, the route's own host, never an alias the request named. |
| type HAForwarder interface { |
| - ForwardTarget(ctx context.Context, rt registry.Route) string |
| + ForwardTarget(ctx context.Context, rt registry.Route) ForwardDecision |
| NoteForward(host string, res ForwardResult) |
| } |
| +// ForwardDecision is ForwardTarget's answer. The zero value serves the request |
| +// here. |
| +type ForwardDecision struct { |
| + // Ref is the box to forward the request to. |
| + Ref string |
| + // Refuse answers the request at the front door as an unreachable forward |
| + // is answered (503, Retry-After: 10), without forwarding it or running |
| + // anything else: the host's holder did not answer a forward moments ago. |
| + Refuse bool |
| + // Gen is the activator's token for this forward, handed back in |
| + // ForwardResult. |
| + Gen uint64 |
| +} |
| + |
| // ForwardOutcome is how one forward ended. |
| type ForwardOutcome int |
| @@ -48,18 +64,24 @@ const ( |
| // key is mirrored. Nothing was written; the request is served here. |
| ForwardNotInView ForwardOutcome = iota |
| // ForwardUnreachable: the named box could not be connected to within |
| - // forwardDialTimeout. This box answered 503, Retry-After: 10. |
| + // forwardDialTimeout. This box answered 503, Retry-After: 10 |
| + // (answerHolderUnreachable). |
| ForwardUnreachable |
| // ForwardDone: the request went to the named box and its answer, whatever |
| - // it was, was relayed, or this box refused the hop itself (Status 0). |
| + // it was, was relayed, or this box refused the hop itself (Status 0), or |
| + // the request waited out its deadline behind another dial (Status 0, |
| + // errForwardDialQueued: it says nothing about the holder). |
| ForwardDone |
| ) |
| -// ForwardResult is what NoteForward is told. Status is the upstream's status, |
| -// 0 when no answer came back from it (a hop this box refused, or a failure |
| -// after connecting). Holder is the upstream's X-Carlos-Holder, "" when absent. |
| +// ForwardResult is what NoteForward is told. Ref and Gen are the decision's: |
| +// the box the request was sent to and the activator's token. Status is the upstream's status, 0 when no |
| +// answer came back from it (a hop this box refused, or a failure after |
| +// connecting). Holder is the upstream's X-Carlos-Holder, "" when absent. |
| type ForwardResult struct { |
| Outcome ForwardOutcome |
| + Ref string |
| + Gen uint64 |
| Status int |
| Holder string |
| } |
| @@ -107,13 +129,21 @@ type forwardConnectError struct{ err error } |
| func (e *forwardConnectError) Error() string { return "connect: " + e.err.Error() } |
| func (e *forwardConnectError) Unwrap() error { return e.err } |
| +// errForwardDialQueued is a request whose deadline passed while it waited |
| +// behind another request's dial to the holder. It never dialled, so it says |
| +// nothing about whether the holder is reachable: the visitor gets the |
| +// unreachable answer, but the forward is not reported unreachable (the dial |
| +// it waited on reports its own outcome). |
| +var errForwardDialQueued = errors.New("waited out the deadline behind another dial to the holder") |
| + |
| // frontForwardHA is the front-door decision, called in ServeHTTP right after |
| // route lookup. It reports whether it answered. False, serve here, unless the |
| // request has a local route (the caller's ok), is not a verified hop, a door |
| // call or a tunnel delivery, its route is born HA, activator-managed and not |
| -// reached through a regional name, and the activator names a box. Then the |
| -// request is forwarded, the activator is told how it went, and it is answered |
| -// unless the box was not in view. |
| +// reached through a regional name, and the activator names a box or refuses. |
| +// A refusal is answered here as an unreachable forward is, and nothing is |
| +// dialled or noted. Otherwise the request is forwarded, the activator is told |
| +// how it went, and it is answered unless the box was not in view. |
| func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host string, up upstream, hopped, isDoor bool) bool { |
| if hopped || isDoor || hopVerified(r.Context()) || fromTunnel(r.Context()) { |
| return false |
| @@ -125,46 +155,56 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin |
| if !ok { |
| return false |
| } |
| - ref := fw.ForwardTarget(r.Context(), up.route) |
| - if ref == "" { |
| + d := fw.ForwardTarget(r.Context(), up.route) |
| + if d.Refuse { |
| + answerHolderUnreachable(w, r) |
| + return true |
| + } |
| + if d.Ref == "" { |
| return false |
| } |
| - res := e.forwardHA(w, r, host, ref) |
| + res := e.forwardHA(w, r, host, d) |
| fw.NoteForward(up.route.Host, res) |
| return res.Outcome != ForwardNotInView |
| } |
| -// forwardHA sends r to the box labelled ref over a signed hop for host. A box |
| -// out of view, or no mesh key, writes nothing and answers ForwardNotInView. |
| -// Otherwise the hop is admitted and signed as backhaulTo's is, over this |
| -// edge's forward transport to ref. A failure to connect is answered 503, |
| -// Retry-After: 10; every other answer is the holder's, relayed as is. |
| +// forwardHA sends r to the box labelled d.Ref over a signed hop for host. A |
| +// box out of view, or no mesh key, writes nothing and answers |
| +// ForwardNotInView. Otherwise the hop is admitted and signed as backhaulTo's |
| +// is, over this edge's forward transport to the box. A failure to connect is |
| +// answered 503, Retry-After: 10; every other answer is the holder's, relayed |
| +// as is. |
| // |
| // It repeats the arrived-hop guard: a verified hop is never forwarded, so a |
| // forwarding loop needs this line and frontForwardHA's to be wrong at once. |
| -func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host, ref string) ForwardResult { |
| +func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host string, d ForwardDecision) ForwardResult { |
| + ref := d.Ref |
| + res := ForwardResult{Outcome: ForwardNotInView, Ref: ref, Gen: d.Gen} |
| m := e.homes.Load() |
| if m == nil || hopVerified(r.Context()) { |
| - return ForwardResult{Outcome: ForwardNotInView} |
| + return res |
| } |
| dial, ok := m.boxInView(ref, time.Now()) |
| if !ok { |
| - return ForwardResult{Outcome: ForwardNotInView} |
| + return res |
| } |
| key := signingKey(m.meshKeys()) |
| if len(key) == 0 { |
| e.logThrottled("forward-no-mesh-key", fmt.Sprintf("%s is held on %s but no mesh key is mirrored; serving here", host, ref)) |
| - return ForwardResult{Outcome: ForwardNotInView} |
| + return res |
| } |
| - res := ForwardResult{Outcome: ForwardDone} |
| + res.Outcome = ForwardDone |
| onError := func(w http.ResponseWriter, r *http.Request, err error) { |
| var connect *forwardConnectError |
| + if errors.Is(err, errForwardDialQueued) && r.Context().Err() == nil { |
| + e.logThrottled("forward-queued "+ref, fmt.Sprintf("forward %s → %s (%s): %v; answering 503 + Retry-After: 10", host, ref, dial, err)) |
| + answerHolderUnreachable(w, r) |
| + return |
| + } |
| if errors.As(err, &connect) && r.Context().Err() == nil { |
| e.logThrottled("forward-unreachable "+ref, fmt.Sprintf("forward %s → %s (%s): %v; answering 503 + Retry-After: 10", host, ref, dial, err)) |
| res.Outcome = ForwardUnreachable |
| - w.Header().Set("Retry-After", "10") |
| - MarkAnswered(r) |
| - http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable) |
| + answerHolderUnreachable(w, r) |
| return |
| } |
| // After connecting, or the client left: backhaul's bad gateway. |
| @@ -179,12 +219,24 @@ func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host, ref strin |
| return res |
| } |
| +// answerHolderUnreachable is the answer to a request whose holder could not |
| +// be connected to, now or moments ago: 503, Retry-After: 10. |
| +func answerHolderUnreachable(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Retry-After", "10") |
| + MarkAnswered(r) |
| + http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable) |
| +} |
| + |
| // forwardTransport is the cached transport to the holder at dial, as |
| // backhaulTransport is per EIP and for the same reasons, with one difference: |
| // connecting (TCP and TLS) has forwardDialTimeout in all, and a failure there |
| // is a forwardConnectError. A separate cache, so backhaulTo's 5 s transports |
| // to the same address are never this one. |
| // |
| +// Its TCP dials go through one forwardDialGate, the transport being one per |
| +// holder address: at most one dial to a holder is in flight, however many |
| +// requests need a connection and whatever the holder cache believes. |
| +// |
| // It does the TLS itself (DialTLSContext) so that the deadline and the error |
| // mark cover the handshake too. Verification is backhaulTransport's: the |
| // system roots (backhaulRootCAs) and the host from the outbound URL's |
| @@ -194,6 +246,7 @@ func (e *Edge) forwardTransport(dial string) *http.Transport { |
| if tr, ok := e.forwardTransports.Load(dial); ok { |
| return tr.(*http.Transport) |
| } |
| + gate := &forwardDialGate{} |
| tr := &http.Transport{ |
| DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| name, _, err := net.SplitHostPort(addr) |
| @@ -202,7 +255,9 @@ func (e *Edge) forwardTransport(dial string) *http.Transport { |
| } |
| ctx, cancel := context.WithTimeout(ctx, forwardDialTimeout) |
| defer cancel() |
| - raw, err := forwardDial(ctx, network, net.JoinHostPort(dial, backhaulPort)) |
| + raw, err := gate.dial(ctx, func(ctx context.Context) (net.Conn, error) { |
| + return forwardDial(ctx, network, net.JoinHostPort(dial, backhaulPort)) |
| + }) |
| if err != nil { |
| return nil, &forwardConnectError{err} |
| } |
| @@ -228,3 +283,71 @@ func (e *Edge) forwardTransport(dial string) *http.Transport { |
| } |
| return tr |
| } |
| + |
| +// forwardDialGate serializes one holder address's TCP dials: at most one is |
| +// in flight, always. A dial that arrives while one is in flight waits for |
| +// its outcome. A failure answers every waiter at once with its error, and |
| +// every dial that arrives until the failed one's forwardDialTimeout has run |
| +// out: a box that refuses at once costs no more dials than one that does |
| +// not answer. A success lets the next waiter take the gate and dial, while |
| +// the rest wait on that one; a burst toward a healthy holder dials one at a |
| +// time, which a same-region, millisecond dial affords. Each caller's own |
| +// deadline (forwardTransport's forwardDialTimeout) bounds its whole wait, |
| +// queueing and dial together. The dial in flight is detached from its |
| +// caller's cancellation, not from its deadline, so a visitor hanging up |
| +// does not fail the others. |
| +type forwardDialGate struct { |
| + mu sync.Mutex |
| + last *forwardDialCall |
| +} |
| + |
| +type forwardDialCall struct { |
| + done chan struct{} |
| + err error |
| + until time.Time // a failure answers later dials until then |
| +} |
| + |
| +func (g *forwardDialGate) dial(ctx context.Context, connect func(context.Context) (net.Conn, error)) (net.Conn, error) { |
| + for { |
| + g.mu.Lock() |
| + c := g.last |
| + if c == nil { |
| + break // g.mu held: take the gate |
| + } |
| + select { |
| + case <-c.done: |
| + if c.err != nil && time.Now().Before(c.until) { |
| + g.mu.Unlock() |
| + return nil, c.err |
| + } |
| + default: |
| + g.mu.Unlock() |
| + select { |
| + case <-c.done: |
| + case <-ctx.Done(): |
| + return nil, fmt.Errorf("%w: %w", errForwardDialQueued, ctx.Err()) |
| + } |
| + if c.err != nil { |
| + return nil, c.err // the dial waited on failed: so do its waiters |
| + } |
| + continue // it connected: take the gate, or wait on whoever did |
| + } |
| + break // settled and not a standing failure: take the gate |
| + } |
| + c := &forwardDialCall{done: make(chan struct{})} |
| + g.last = c |
| + g.mu.Unlock() |
| + start := time.Now() |
| + dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), forwardDialTimeout) |
| + if d, ok := ctx.Deadline(); ok { |
| + cancel() |
| + dctx, cancel = context.WithDeadline(context.WithoutCancel(ctx), d) |
| + } |
| + defer cancel() |
| + conn, err := connect(dctx) |
| + g.mu.Lock() |
| + c.err, c.until = err, start.Add(forwardDialTimeout) |
| + close(c.done) |
| + g.mu.Unlock() |
| + return conn, err |
| +} |
diff --git a/internal/edge/forwardha_export_test.go b/internal/edge/forwardha_export_test.go| new file mode 100644 |
| index 000000000..0b54ad493 |
| --- /dev/null |
| +++ b/internal/edge/forwardha_export_test.go |
| @@ -0,0 +1,76 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net" |
| + "net/http" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +// The forward scene (forwardha_test.go) for forwardha_wiring_test.go, the |
| +// guard test that drives the real activator through the real edge. It must |
| +// be package edge_test, because the activator imports this package; these |
| +// names exist only in this package's test build. |
| + |
| +// HAForwardHost is the born-HA host both boxes of the scene serve. |
| +const HAForwardHost = fwHost |
| + |
| +// HAForwardHolder is the holder box's ref in the scene. |
| +const HAForwardHolder = "betty" |
| + |
| +// HAForwardScene is a forward scene whose forwarding box (annie) runs act, |
| +// with every forward dial counted at the dial seam. |
| +type HAForwardScene struct { |
| + x *fwScene |
| + dials atomic.Int64 |
| + stall atomic.Bool |
| +} |
| + |
| +// NewHAForwardScene is newFwScene with act as annie's activator. |
| +func NewHAForwardScene(t *testing.T, act Activator) *HAForwardScene { |
| + t.Helper() |
| + s := &HAForwardScene{x: newFwScene(t, fwOpts{aAct: act})} |
| + addr := s.x.b.tlsAddr |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + s.dials.Add(1) |
| + if s.stall.Load() { |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, addr) |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| + return s |
| +} |
| + |
| +// Dials is the number of forward dials to the holder so far. |
| +func (s *HAForwardScene) Dials() int64 { return s.dials.Load() } |
| + |
| +// Get is one visitor GET of path on HAForwardHost through annie. |
| +func (s *HAForwardScene) Get(path string) (status int, retryAfter, body string, err error) { |
| + resp, err := s.x.a.client.Get("https://" + fwHost + path) |
| + if err != nil { |
| + return 0, "", "", err |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + return resp.StatusCode, resp.Header.Get("Retry-After"), string(b), err |
| +} |
| + |
| +// HolderDown is the holder box gone: its door's listener closed and its |
| +// connections cut, and annie's idle forward connections dropped. With |
| +// blackholed, a dial to it also stalls until its deadline, as a dial to a |
| +// terminated box's address does, rather than being refused at once. |
| +func (s *HAForwardScene) HolderDown(blackholed bool) { |
| + s.stall.Store(blackholed) |
| + s.x.b.door.Listener.Close() |
| + s.x.b.door.CloseClientConnections() |
| + s.x.a.edge.forwardTransports.Range(func(_, v any) bool { |
| + v.(*http.Transport).CloseIdleConnections() |
| + return true |
| + }) |
| +} |
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go| index 36526b817..b12ae1356 100644 |
| --- a/internal/edge/forwardha_test.go |
| +++ b/internal/edge/forwardha_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "bufio" |
| "context" |
| "crypto/tls" |
| + "errors" |
| "fmt" |
| "io" |
| "net" |
| @@ -59,9 +60,12 @@ var fwBigBody = strings.Repeat("<p>forwarded and compressible</p>\n", 2048) |
| var fwHosts = []string{fwHost, fwGatedHost, fwAssetHost, fwRateHost, fwLegacyHost} |
| // fwAct is a box's activator: it wakes nothing (the route's TCP upstream |
| -// answers) and, as an HAForwarder, names target and keeps every note. |
| +// answers) and, as an HAForwarder, names target (or refuses, when refuse is |
| +// set) and keeps every note. |
| type fwAct struct { |
| target string |
| + refuse bool |
| + gen uint64 |
| asked atomic.Int64 |
| mu sync.Mutex |
| notes []fwNote |
| @@ -87,10 +91,11 @@ func (a *fwAct) ServeHTTP(w http.ResponseWriter, r *http.Request, _ registry.Rou |
| return false |
| } |
| func (a *fwAct) RetireExcept(map[string]bool) {} |
| -func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route) string { |
| +func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route) ForwardDecision { |
| a.asked.Add(1) |
| - return a.target |
| + return ForwardDecision{Ref: a.target, Refuse: a.refuse, Gen: a.gen} |
| } |
| + |
| func (a *fwAct) NoteForward(host string, res ForwardResult) { |
| a.mu.Lock() |
| defer a.mu.Unlock() |
| @@ -469,7 +474,7 @@ func TestFrontForwardReachesTheHolder(t *testing.T) { |
| if got := x.bAct.asked.Load(); got != 0 { |
| t.Fatalf("betty asked its activator %d times for a hop, want 0", got) |
| } |
| - x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusOK}}) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusOK}}) |
| } |
| func TestFrontForwardRunsNoLocalStep(t *testing.T) { |
| @@ -603,6 +608,319 @@ func TestFrontForwardRunsNoLocalStep(t *testing.T) { |
| }) |
| } |
| +// The activator's refusal (a suspect holder, which did not answer a forward |
| +// moments ago) is answered at the front door as an unreachable forward is: |
| +// 503, Retry-After: 10, the same body, and nothing else. No dial, no note, |
| +// no request to either box's app, and no per-request step on either box: |
| +// not the gate, the asset cache, the guards, the rate limit, usage, |
| +// analytics or request records. |
| +func TestFrontForwardSuspectRefusalRunsNoLocalStep(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + x.aAct.refuse = true |
| + var dials atomic.Int64 |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + dials.Add(1) |
| + return old(ctx, network, addr) |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| + cookie := gate.CookieName + "=" + gate.Mint(fwGatedHost, x.hash, time.Now().Add(time.Hour)) |
| + calls := x.b.calls.Load() |
| + cases := []struct { |
| + name, host, path string |
| + hdr []string |
| + }{ |
| + {"plain", fwHost, "/", nil}, |
| + {"gated without the cookie", fwGatedHost, "/in", nil}, |
| + {"gated with the cookie", fwGatedHost, "/in", []string{"Cookie", cookie}}, |
| + {"asset", fwAssetHost, "/assets/app.js", nil}, |
| + {"watched path", fwHost, "/.env", nil}, |
| + {"rate 1", fwRateHost, "/", nil}, |
| + {"rate 2", fwRateHost, "/", nil}, |
| + } |
| + for _, c := range cases { |
| + resp, body := x.fetch(t, c.host, c.path, c.hdr...) |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" || |
| + body != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("%s = %d Retry-After %q %q, want the front door's 503", c.name, resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| + } |
| + if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| + t.Fatalf("%s: %s = %q, want none", c.name, holderHeader, v) |
| + } |
| + annie, betty := x.take(t, c.host) |
| + wantNothing(t, c.name, annie) |
| + wantNothing(t, c.name, betty) |
| + } |
| + if n := dials.Load(); n != 0 { |
| + t.Fatalf("%d dials, want none", n) |
| + } |
| + if n := x.b.calls.Load() - calls; n != 0 { |
| + t.Fatalf("betty saw %d requests, want none", n) |
| + } |
| + if notes := x.aAct.noted(); len(notes) != 0 { |
| + t.Fatalf("notes = %+v, want none: nothing was forwarded", notes) |
| + } |
| + if got := x.aAct.asked.Load(); got != int64(len(cases)) { |
| + t.Fatalf("annie asked its activator %d times, want %d", got, len(cases)) |
| + } |
| + if n, m := x.aApp.n.Load(), x.bApp.n.Load(); n != 0 || m != 0 { |
| + t.Fatalf("the apps saw %d and %d requests, want none", n, m) |
| + } |
| + if s := x.aStore.Stats(); s.Entries != 0 || s.Reserved != 0 { |
| + t.Fatalf("annie's asset store holds %+v", s) |
| + } |
| +} |
| + |
| +// The decision's Gen comes back in the forward's note. |
| +func TestForwardHANoteCarriesTheGen(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + x.aAct.gen = 7 |
| + if resp, _ := x.fetch(t, fwHost, "/"); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("GET = %d", resp.StatusCode) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Gen: 7, Status: http.StatusOK}}) |
| +} |
| + |
| +// The forward transport's dial gate: one dial in flight per holder address. |
| +// Dials that arrive meanwhile wait for it; a failure answers them, and every |
| +// dial until its forwardDialTimeout runs out, with no dial of their own; a |
| +// success lets each dial its own. |
| +func TestForwardDialGate(t *testing.T) { |
| + ctx := context.Background() |
| + t.Run("a failure answers its waiters and what follows", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + var dials atomic.Int64 |
| + release := make(chan struct{}) |
| + refused := errors.New("connection refused") |
| + connect := func(context.Context) (net.Conn, error) { |
| + if dials.Add(1) == 1 { |
| + <-release |
| + } |
| + return nil, refused |
| + } |
| + errs := make(chan error, 20) |
| + for range 20 { |
| + go func() { _, err := g.dial(ctx, connect); errs <- err }() |
| + } |
| + laWaitFor(t, "the first dial", func() bool { return dials.Load() == 1 }) |
| + time.Sleep(50 * time.Millisecond) |
| + if n := dials.Load(); n != 1 { |
| + t.Fatalf("%d dials in flight, want 1", n) |
| + } |
| + close(release) |
| + for range 20 { |
| + if err := <-errs; !errors.Is(err, refused) { |
| + t.Fatalf("a waiter got %v, want the dial's error", err) |
| + } |
| + } |
| + if _, err := g.dial(ctx, connect); !errors.Is(err, refused) || dials.Load() != 1 { |
| + t.Fatalf("a dial right after the failure: %v with %d dials, want the failure and 1", err, dials.Load()) |
| + } |
| + g.mu.Lock() |
| + g.last.until = time.Now() // the failure's time is up |
| + g.mu.Unlock() |
| + g.dial(ctx, connect) |
| + if n := dials.Load(); n != 2 { |
| + t.Fatalf("after the failure's time: %d dials, want 2", n) |
| + } |
| + }) |
| + t.Run("a waiter out of time behind a dial never reports it unreachable", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + var dials atomic.Int64 |
| + release := make(chan struct{}) |
| + connect := func(context.Context) (net.Conn, error) { |
| + dials.Add(1) |
| + <-release |
| + a, b := net.Pipe() |
| + b.Close() |
| + return a, nil |
| + } |
| + first := make(chan error, 1) |
| + go func() { |
| + conn, err := g.dial(ctx, connect) |
| + if conn != nil { |
| + conn.Close() |
| + } |
| + first <- err |
| + }() |
| + laWaitFor(t, "the first dial", func() bool { return dials.Load() == 1 }) |
| + short, cancel := context.WithTimeout(ctx, 50*time.Millisecond) |
| + defer cancel() |
| + _, err := g.dial(short, connect) |
| + if !errors.Is(err, errForwardDialQueued) || !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("a waiter out of time got %v, want errForwardDialQueued wrapping the deadline", err) |
| + } |
| + var connectErr *forwardConnectError |
| + if errors.As(err, &connectErr) { |
| + t.Fatalf("the queued waiter's error %v is a connect failure", err) |
| + } |
| + close(release) |
| + if err := <-first; err != nil { |
| + t.Fatalf("the first dial: %v", err) |
| + } |
| + if n := dials.Load(); n != 1 { |
| + t.Fatalf("%d dials, want 1: the waiter must not dial", n) |
| + } |
| + }) |
| + // countingConnect is a connect that records the most dials in flight at |
| + // once; each dial n waits on hold(n), then answers with fail(n). |
| + countingConnect := func(hold func(n int64), fail func(n int64) error) (func(context.Context) (net.Conn, error), *atomic.Int64, *atomic.Int64) { |
| + var dials, inFlight, most atomic.Int64 |
| + return func(context.Context) (net.Conn, error) { |
| + n := inFlight.Add(1) |
| + defer inFlight.Add(-1) |
| + for m := most.Load(); n > m && !most.CompareAndSwap(m, n); m = most.Load() { |
| + } |
| + d := dials.Add(1) |
| + hold(d) |
| + if err := fail(d); err != nil { |
| + return nil, err |
| + } |
| + a, b := net.Pipe() |
| + b.Close() |
| + return a, nil |
| + }, &dials, &most |
| + } |
| + t.Run("after a success the next waiter takes the gate", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + release := []chan struct{}{make(chan struct{}), make(chan struct{})} |
| + gone := errors.New("connection refused") |
| + connect, dials, most := countingConnect( |
| + func(n int64) { |
| + if n <= 2 { |
| + <-release[n-1] |
| + } |
| + }, |
| + func(n int64) error { |
| + if n == 2 { |
| + return gone |
| + } |
| + return nil |
| + }) |
| + type result struct { |
| + conn net.Conn |
| + err error |
| + } |
| + results := make(chan result, 5) |
| + for range 5 { |
| + go func() { |
| + conn, err := g.dial(ctx, connect) |
| + if conn != nil { |
| + conn.Close() |
| + } |
| + results <- result{conn, err} |
| + }() |
| + } |
| + laWaitFor(t, "the first dial", func() bool { return dials.Load() == 1 }) |
| + time.Sleep(50 * time.Millisecond) |
| + if most.Load() != 1 || dials.Load() != 1 { |
| + t.Fatalf("before the first connected: %d dials, %d at once; want 1 and 1", dials.Load(), most.Load()) |
| + } |
| + close(release[0]) // the first connects |
| + if r := <-results; r.err != nil { |
| + t.Fatalf("the first dial: %v", r.err) |
| + } |
| + // The next waiter takes the gate; the rest keep waiting. |
| + laWaitFor(t, "the second dial", func() bool { return dials.Load() == 2 }) |
| + time.Sleep(50 * time.Millisecond) |
| + if most.Load() != 1 || dials.Load() != 2 { |
| + t.Fatalf("after the first connected: %d dials, %d at once; want 2 and 1", dials.Load(), most.Load()) |
| + } |
| + select { |
| + case r := <-results: |
| + t.Fatalf("a waiter returned %v while the second dial was held", r.err) |
| + default: |
| + } |
| + close(release[1]) // the second fails: the holder is gone |
| + for i := range 4 { |
| + if r := <-results; !errors.Is(r.err, gone) { |
| + t.Fatalf("waiter %d after the second dial failed: %v, want its error", i, r.err) |
| + } |
| + } |
| + if dials.Load() != 2 || most.Load() != 1 { |
| + t.Fatalf("%d dials, %d at once; want 2 and 1", dials.Load(), most.Load()) |
| + } |
| + }) |
| + t.Run("a healthy burst dials one at a time", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + connect, dials, most := countingConnect(func(int64) { time.Sleep(5 * time.Millisecond) }, func(int64) error { return nil }) |
| + errs := make(chan error, 10) |
| + for range 10 { |
| + go func() { |
| + conn, err := g.dial(ctx, connect) |
| + if conn != nil { |
| + conn.Close() |
| + } |
| + errs <- err |
| + }() |
| + } |
| + for range 10 { |
| + if err := <-errs; err != nil { |
| + t.Fatalf("a dial to a healthy holder: %v", err) |
| + } |
| + } |
| + if dials.Load() != 10 || most.Load() != 1 { |
| + t.Fatalf("%d dials, %d at once; want one each, one at a time", dials.Load(), most.Load()) |
| + } |
| + }) |
| + t.Run("a waiter's deadline bounds its queueing", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + release := make(chan struct{}) |
| + defer close(release) |
| + go g.dial(ctx, func(context.Context) (net.Conn, error) { |
| + <-release |
| + a, b := net.Pipe() |
| + b.Close() |
| + return a, nil |
| + }) |
| + laWaitFor(t, "the first dial", func() bool { g.mu.Lock(); defer g.mu.Unlock(); return g.last != nil }) |
| + wctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) |
| + defer cancel() |
| + start := time.Now() |
| + _, err := g.dial(wctx, func(dctx context.Context) (net.Conn, error) { <-dctx.Done(); return nil, dctx.Err() }) |
| + if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > time.Second { |
| + t.Fatalf("a queued waiter past its deadline: %v after %v", err, time.Since(start)) |
| + } |
| + }) |
| + t.Run("a waiter's own deadline", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + release := make(chan struct{}) |
| + defer close(release) |
| + go g.dial(ctx, func(context.Context) (net.Conn, error) { <-release; return nil, errors.New("late") }) |
| + laWaitFor(t, "the first dial", func() bool { g.mu.Lock(); defer g.mu.Unlock(); return g.last != nil }) |
| + wctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond) |
| + defer cancel() |
| + if _, err := g.dial(wctx, func(context.Context) (net.Conn, error) { t.Error("the waiter dialled"); return nil, nil }); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("a waiter past its deadline: %v", err) |
| + } |
| + }) |
| + t.Run("the dial outlives its caller's hang-up", func(t *testing.T) { |
| + g := &forwardDialGate{} |
| + cctx, cancel := context.WithCancel(ctx) |
| + started := make(chan struct{}) |
| + var sawCancel atomic.Bool |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + g.dial(cctx, func(dctx context.Context) (net.Conn, error) { |
| + close(started) |
| + select { |
| + case <-dctx.Done(): |
| + sawCancel.Store(true) |
| + case <-time.After(100 * time.Millisecond): |
| + } |
| + return nil, errors.New("refused") |
| + }) |
| + }() |
| + <-started |
| + cancel() |
| + <-done |
| + if sawCancel.Load() { |
| + t.Fatal("the caller hanging up cancelled the dial its waiters share") |
| + } |
| + }) |
| +} |
| + |
| func TestForwardHAHolderLostHost(t *testing.T) { |
| x := newFwScene(t, fwOpts{bettyLacks: true}) |
| resp, body := x.fetch(t, fwHost, "/") |
| @@ -612,7 +930,7 @@ func TestForwardHAHolderLostHost(t *testing.T) { |
| if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| t.Fatalf("%s = %q, want none", holderHeader, v) |
| } |
| - x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable}}) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusServiceUnavailable}}) |
| if n := x.aApp.n.Load(); n != 0 { |
| t.Fatalf("annie's app saw %d requests", n) |
| } |
| @@ -751,7 +1069,7 @@ func TestForwardHANotInView(t *testing.T) { |
| if n := x.b.calls.Load() - calls; n != 0 { |
| t.Fatalf("betty saw %d requests", n) |
| } |
| - x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardNotInView}}) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardNotInView, Ref: "carol"}}) |
| // Served here, it is recorded here. |
| annie, _ := x.take(t, fwHost) |
| if annie.use.Requests != 1 || annie.use.HopRequests != 0 { |
| @@ -782,7 +1100,7 @@ func TestForwardHADialFailureIs503RetryTen(t *testing.T) { |
| t.Fatalf("the unreachable answer took %v, want about %v", took, forwardDialTimeout) |
| } |
| notes := x.aAct.noted() |
| - if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardUnreachable}}) { |
| + if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardUnreachable, Ref: "betty"}}) { |
| t.Fatalf("notes = %+v, want ForwardUnreachable last", notes) |
| } |
| if n := x.bApp.n.Load(); n != 0 { |
| @@ -838,6 +1156,32 @@ func TestForwardHADialFailureIs503RetryTen(t *testing.T) { |
| }) |
| } |
| +// TestForwardHAQueuedPastTheDeadlineIsNotUnreachable: a request that waited |
| +// out its deadline behind another request's dial gets the unreachable answer, |
| +// but the forward is not reported unreachable, so a healthy holder whose dials |
| +// are slow under a burst is never marked suspect by requests that never |
| +// dialled it. |
| +func TestForwardHAQueuedPastTheDeadlineIsNotUnreachable(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + old := forwardDial |
| + forwardDial = func(context.Context, string, string) (net.Conn, error) { |
| + return nil, fmt.Errorf("%w: %w", errForwardDialQueued, context.DeadlineExceeded) |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| + resp, body := x.fetch(t, fwHost, "/") |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" || |
| + body != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("GET = %d Retry-After %q %q, want the unreachable 503", resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| + } |
| + notes := x.aAct.noted() |
| + if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty"}}) { |
| + t.Fatalf("notes = %+v, want ForwardDone with no status last (not ForwardUnreachable)", notes) |
| + } |
| + if n := x.bApp.n.Load(); n != 0 { |
| + t.Fatalf("betty's app saw %d requests", n) |
| + } |
| +} |
| + |
| func TestForwardHAReadsHolderHeader(t *testing.T) { |
| x := newFwScene(t, fwOpts{}) |
| n := 0 |
| @@ -856,7 +1200,7 @@ func TestForwardHAReadsHolderHeader(t *testing.T) { |
| if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get(holderHeader) != ref { |
| t.Fatalf("platform refusal = %d %s %q, want betty's 503 naming %s", resp.StatusCode, holderHeader, resp.Header.Get(holderHeader), ref) |
| } |
| - note(t, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable, Holder: ref}) |
| + note(t, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusServiceUnavailable, Holder: ref}) |
| } |
| // An app's own X-Carlos-Holder never leaves the holder: not to the |
| // client, not into the note. |
| @@ -871,7 +1215,7 @@ func TestForwardHAReadsHolderHeader(t *testing.T) { |
| if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| t.Fatalf("app %s: the client received %s %q", tc.query, holderHeader, v) |
| } |
| - note(t, ForwardResult{Outcome: ForwardDone, Status: tc.status}) |
| + note(t, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: tc.status}) |
| } |
| } |
| @@ -899,7 +1243,7 @@ func TestForwardHAAppHolderTrailerNeverReachesTheClient(t *testing.T) { |
| t.Fatalf("announced=%s: X-Kept trailer = %q, want 1 (trailers %v): trailers must still cross", announced, got, resp.Trailer) |
| } |
| notes := x.aAct.noted() |
| - if len(notes) != i+1 || notes[i] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusOK}}) { |
| + if len(notes) != i+1 || notes[i] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusOK}}) { |
| t.Fatalf("notes = %+v, want ForwardDone 200 with no holder", notes) |
| } |
| } |
| @@ -958,5 +1302,5 @@ func TestForwardHAUpgradeSwitchesProtocols(t *testing.T) { |
| } |
| c.Close() |
| laWaitFor(t, "the forward's note", func() bool { return len(x.aAct.noted()) == 1 }) |
| - x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusSwitchingProtocols}}) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusSwitchingProtocols}}) |
| } |
diff --git a/internal/edge/forwardha_wiring_test.go b/internal/edge/forwardha_wiring_test.go| new file mode 100644 |
| index 000000000..dd059620a |
| --- /dev/null |
| +++ b/internal/edge/forwardha_wiring_test.go |
| @@ -0,0 +1,106 @@ |
| +// The dead-holder guard test (region HA P1b-2 follow-up): the real |
| +// activator, through the real edge, against a holder that served and then |
| +// went away while its lease and this box's cache entry stay live. It is |
| +// package edge_test because the activator imports internal/edge; the scene |
| +// comes from forwardha_export_test.go. |
| +package edge_test |
| + |
| +import ( |
| + "encoding/json" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| +) |
| + |
| +const unreachableBody = "instance is waking elsewhere; retry shortly\n" |
| + |
| +func TestDeadHolderGuardRealWiring(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + blackholed bool |
| + }{{"refused", false}, {"blackholed", true}} { |
| + t.Run(c.name, func(t *testing.T) { deadHolderGuard(t, c.blackholed) }) |
| + } |
| +} |
| + |
| +func deadHolderGuard(t *testing.T, blackholed bool) { |
| + fx := locktest.NewLockFixture(t) |
| + prefix := activator.HibernatePrefix("", edge.HAForwardHost) |
| + lockGets := func() int { |
| + n := 0 |
| + for _, r := range fx.Requests() { |
| + if r == "GET "+prefix+"/lock.json" { |
| + n++ |
| + } |
| + } |
| + return n |
| + } |
| + body, err := json.Marshal(hafresh.Lock{Generation: 9, ExpiresAt: time.Now().Add(10 * time.Minute).UTC(), |
| + Owner: "box/v1;ref=" + edge.HAForwardHolder + ";iid=i-b;pid=7;ha=1"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.PutLock(prefix, body) |
| + cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, |
| + Self: func() hafresh.Self { return hafresh.Self{Ref: "annie", IID: "i-a"} }} |
| + svc := activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil) |
| + x := edge.NewHAForwardScene(t, svc) |
| + |
| + // The holder serves one forward. |
| + if status, _, got, err := x.Get("/"); err != nil || status != 200 || got != "betty|"+edge.HAForwardHost+"|/" { |
| + t.Fatalf("the first forward: %d %q %v, want betty's 200", status, got, err) |
| + } |
| + if x.Dials() != 1 || lockGets() != 1 { |
| + t.Fatalf("the first forward: %d dials and %d lock reads, want 1 and 1", x.Dials(), lockGets()) |
| + } |
| + |
| + // The holder goes away; its lease and the cache entry stay live. |
| + x.HolderDown(blackholed) |
| + dials, reads := x.Dials(), lockGets() |
| + var wg sync.WaitGroup |
| + type answer struct { |
| + status int |
| + retry, body string |
| + err error |
| + } |
| + answers := make([]answer, 20) |
| + for i := range answers { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + var a answer |
| + a.status, a.retry, a.body, a.err = x.Get("/") |
| + answers[i] = a |
| + }() |
| + } |
| + wg.Wait() |
| + for i, a := range answers { |
| + if a.err != nil || a.status != 503 || a.retry != "10" || a.body != unreachableBody { |
| + t.Fatalf("request %d: %d Retry-After %q %q %v, want 503, 10", i, a.status, a.retry, a.body, a.err) |
| + } |
| + } |
| + if n, m := x.Dials()-dials, lockGets()-reads; n != 1 || m != 0 { |
| + t.Fatalf("20 concurrent requests for a gone holder: %d dials and %d lock reads, want 1 and 0", n, m) |
| + } |
| + |
| + // Within the window: refused at the front door, nothing dialled or read. |
| + dials, reads = x.Dials(), lockGets() |
| + start := time.Now() |
| + for i := range 10 { |
| + status, retry, got, err := x.Get("/") |
| + if err != nil || status != 503 || retry != "10" || got != unreachableBody { |
| + t.Fatalf("sequential request %d: %d Retry-After %q %q %v", i, status, retry, got, err) |
| + } |
| + } |
| + if took := time.Since(start); took >= 10*time.Second { |
| + t.Fatalf("the sequential requests took %v, past the window", took) |
| + } |
| + if n, m := x.Dials()-dials, lockGets()-reads; n != 0 || m != 0 { |
| + t.Fatalf("sequential requests within the window: %d dials and %d lock reads, want 0 and 0", n, m) |
| + } |
| +} |
diff --git a/internal/host/haforward_wiring_test.go b/internal/host/haforward_wiring_test.go| index c58a326cf..d190f4e01 100644 |
| --- a/internal/host/haforward_wiring_test.go |
| +++ b/internal/host/haforward_wiring_test.go |
| @@ -48,8 +48,8 @@ func TestAgentActivatorForwards(t *testing.T) { |
| if !ok { |
| t.Fatal("the activator the agent hands the edge is not an edge.HAForwarder") |
| } |
| - if got := fw.ForwardTarget(context.Background(), registry.Route{Host: "shop.example.com"}); got != "" { |
| - t.Fatalf("a host that is not born HA forwards to %q, want served here", got) |
| + if got := fw.ForwardTarget(context.Background(), registry.Route{Host: "shop.example.com"}); got != (edge.ForwardDecision{}) { |
| + t.Fatalf("a host that is not born HA forwards with %+v, want served here", got) |
| } |
| // No activator configured: act stays an interface with no value, and the |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index a0dbd1f36..12f796b46 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -39,3 +39,4 @@ plan14-root-reads-rootfs-fleet-followups.tsv 78b7e7e30ad3ada44388a4ee16f3950ef88 |
| plan14-root-reads-rootfs-worker-exit.tsv 7ebc3871ee3c93ff168bfa62d23d6be5a970786c67a9b8aa813e8cc4e39b3d74 |
| plan14-root-reads-region-ha-p1b2.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64 |
| plan14-root-reads-analytics-agents.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64 |
| +plan14-root-reads-region-ha-dead-holder-backoff.tsv 8f6a1865b0abcea9d4fb68232cc2a25263a106ec87f73bd4b3f2fb388971ebe5 |
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-dead-holder-backoff.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-dead-holder-backoff.tsv| new file mode 100644 |
| index 000000000..d57d4286a |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-region-ha-dead-holder-backoff.tsv |
| @@ -0,0 +1,8 @@ |
| +# Census overlay region-ha-dead-holder-backoff, written by census-propose (#369). census-ruling-region-ha-dead-holder-backoff, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-dead-holder-backoff.md. |
| +# 1 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy b286076f631f312f8205e0fb21e469fc58c59f1e910fb7e2becb0ffabc36d0f1 internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it. registry:HA@225,registry:Host@563,whole:Route@228,whole:Route@405,whole:Route@566 c5b342e1a71cff53bdc6666821708f962c5b2fc73bd6cba2e983cff54c839626 |
| +@legacy 98d129b191b29a10c516103399d33c1d72d5f2d992ed37211345da06bebcbb85 internal/activator/haforward.go Service.ForwardTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it. registry:HA@100,registry:Host@1000,registry:Host@262,registry:Host@383,whole:Route@176,whole:Route@741 da8dcb16995990c9fb3c7107cd0d1ef8d5424bddea08a70ad8133801b186cc53 |
| +internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it. registry:HA@225,registry:Host@563,whole:Route@228,whole:Route@405,whole:Route@566 c5b342e1a71cff53bdc6666821708f962c5b2fc73bd6cba2e983cff54c839626 |
| +internal/activator/haforward.go Service.ForwardTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it. registry:HA@100,registry:Host@1000,registry:Host@262,registry:Host@383,whole:Route@176,whole:Route@741 da8dcb16995990c9fb3c7107cd0d1ef8d5424bddea08a70ad8133801b186cc53 |
| +@coverage internal/activator d57a02d4526ac697a1885db1ffd483e922cb5529a0e90ba4c5a325c0f684f1a7 |
| +@coverage internal/edge 047409d8e9c6445bdb0a16a189ce4c88db09a8949d23892662547c42521296c5 |