region HA: replay a whole copy once when the draining box hands over
Task 3 of the held-requests build (spec §25.3 H2, H3, §25.5, §25.15). - edge/replay.go: copyWholeBody, H2's one body preparation. Before the first send, a body is read whole only when it is absent or has a known Content-Length of at most 64 KiB. Chunked and unknown-length bodies are never read early; they stream as today and are never replayed. The copy's first send is marked X-Carlos-Replayable: 1 and drops Expect. - One attempt counter per request (nextForwardAttempt), spent by the front forward, the §6.5 backhaul holder follow and the backhaul connect fallback: two attempts at most, never a third (I4). - forwardha.go: a handover answer to a marked first attempt is consumed before the proxy writes anything. Its ref must be in view and pass name authority (handoverAuthority); the copy then goes there, unmarked, as the second and last attempt. A ref naming this box serves the request through the ordinary local path with the body restored. Any other answer, and a handover answer to anything else, is relayed as today, without the handover header. The holder is noted, so it is cached. Held-stream requests follow from memory: no ForwardTarget call. - backhaul_holder.go: the same rules cross-region; the ref must be in the destination's region view with the checked owner's serving claim (handoverAlternative). - handover.go (Task 2): the draining box reads a marked hop's body (known length, at most 64 KiB, bounded at 1 s) before its handover answer, so the answer is not lost to the reset of a connection closed with the body unread. Its release of a client's request streams the body as before (forwardHAStreaming).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/backhaul_holder.go+61 −5internal/edge/backhaul_retry.go+58 −0internal/edge/edge.go+1 −1internal/edge/forwardha.go+158 −5internal/edge/forwardha_test.go+18 −2internal/edge/handover.go+24 −1internal/edge/replay.go+109 −0internal/edge/replay_test.go+866 −0
Intent
<task-notification> <task-id>a8b92a57abc36621e</task-id> <tool-use-id>toolu_01SweSwvXNxPyEQ8a1pKfhk6</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a8b92a57abc36621e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: MoveState holds" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: **DONE**. The remaining P1 is fixed: the bounded exit's exemption now depends on whether the connection was actually hijacked, not on the request's headers. Commit (not pushed): `2c138f20`. - **The fix:** the exit wraps the response in a small writer that records a successful hijack and removes its own `Connection: close` at that moment. A hijack only happens on the proxy's 101 for an upgrade the holder accepted. Every other answer gets the full close, flush and past read deadline, whatever the request claimed. That covers refusals, Lost, the handover answer, the hop cap, an unreachable holder and the relayed answer. - **Regression:** eight new raw HTTP/1.1 cases, each carrying a client's `Connection: Upgrade` token and an unfinished body: - a taken client at the hop cap, chunked and small fixed-length; - a taken client with an unreachable holder, both body types; - Refused, both body types; - Lost; - the replayable-hop handover answer. These also cover the other refusals the re-reviewer said had regressed. The successful-101 upgrade test is kept. Tests: the handover tests and the neighbouring edge tests pass, as do the census test, gofmt, vet and the darwin/windows builds. Putting back the old header-based exemption (G1) and skipping the close for an upgrade token (G2) both fail the new cases. G3 and G4 survive for the same reason as last round: the proxy writes its own `Connection: Upgrade` on a 101, and any cleanup after a hijack lands only once the upgraded session is over. Concerns: the re-reviewer noted that R3.3 has now drawn findings in two rounds running, which triggers stopping rule 2. This fix is the remedy they recommended (bounded cleanup in one place for every response that doesn't hijack), with a guard test. Whether that settles the rule or still needs Paul's choice is your call. Census: proposal re-run; only the edge envelope changed, and the seal is unchanged. The cross-family verdict on #280 is still owed. Report (fix round 2 appended): `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-2-report.md`</result> <usage><subagent_tokens>356116</subagent_tokens><tool_uses>8</tool_uses><duration_ms>471667</duration_ms></usage> </task-notification>
diff --git a/internal/edge/backhaul_holder.go b/internal/edge/backhaul_holder.go| index fed31871e..1600788f5 100644 |
| --- a/internal/edge/backhaul_holder.go |
| +++ b/internal/edge/backhaul_holder.go |
| @@ -164,12 +164,39 @@ func (t backhaulHolderTransport) RoundTrip(r *http.Request) (*http.Response, err |
| return resp, nil |
| } |
| -func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, owner backhaulOwner, retry bool) { |
| +// backhaulAttempt is one attempt of a backhauled request, and spends one |
| +// of r's attempts (nextForwardAttempt, replay.go): a §6.5 holder follow, a |
| +// connect fallback and a handover follow (§25.5) are the second and last. |
| +// On the first it copies the body whole when it can (copyWholeBody) and |
| +// marks the hop replayable; whole is that copy on the second. |
| +func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, owner backhaulOwner, whole *wholeBody) { |
| + n, ok := nextForwardAttempt(r) |
| + if !ok { |
| + // I4: never a third attempt. |
| + e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s: no attempt left", host, box)) |
| + w.WriteHeader(http.StatusBadGateway) |
| + return |
| + } |
| + retry := n < maxForwardAttempts |
| + if n == 1 && whole == nil { |
| + c, err := copyWholeBody(r) |
| + if err != nil { |
| + e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s (%s): reading the request body: %v", host, box, dial, err)) |
| + w.WriteHeader(http.StatusBadGateway) |
| + return |
| + } |
| + whole = c |
| + } |
| + original := r |
| + marked := false |
| + if whole != nil { |
| + marked = n == 1 |
| + r = whole.request(original, marked) |
| + } |
| var nextDial, nextRef, nextReason string |
| // Only connection failures disprove a hint. A canceled client or an |
| // error after connecting says nothing about which box holds the lease. |
| var connectFailed, connected atomic.Bool |
| - original := r |
| r = r.WithContext(httptrace.WithClientTrace(r.Context(), &httptrace.ClientTrace{ |
| GotConn: func(httptrace.GotConnInfo) { connected.Store(true) }, |
| ConnectDone: func(_, _ string, err error) { |
| @@ -184,6 +211,10 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia |
| }, |
| })) |
| tr := backhaulHolderTransport{RoundTripper: e.backhaulTransport(dial), response: func(resp *http.Response) error { |
| + // A handover answer is the platform's, to this hop only: never |
| + // relayed to the client. |
| + handover := resp.Header.Get(HandoverHeader) |
| + resp.Header.Del(HandoverHeader) |
| if resp.StatusCode != http.StatusServiceUnavailable { |
| return nil |
| } |
| @@ -191,6 +222,29 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia |
| if ref != box { |
| e.dropBackhaulHolder(host, box, "holder refusal", owner) |
| } |
| + if handover != "" { |
| + // §25.5: followed only on a marked first attempt (H2, H3), to a |
| + // ref in the destination's region view with the checked owner's |
| + // name authority. Anything else is today's answer, with neither |
| + // the §6.5 follow nor the holder learned from it. |
| + if !marked || !retry { |
| + return nil |
| + } |
| + hRef, _, ok := ParseHandover(handover) |
| + if !ok { |
| + return nil |
| + } |
| + now := time.Now() |
| + addr, ok := e.homes.Load().handoverAlternative(host, hRef, box, owner, now) |
| + if !ok { |
| + return nil |
| + } |
| + if e.backhaulHolders.remember(host, hRef, owner, now) { |
| + e.logThrottled("backhaul-holder-learn "+hRef, fmt.Sprintf("backhaul holder learned for %s: %s", host, hRef)) |
| + } |
| + nextDial, nextRef, nextReason = addr, hRef, "handover" |
| + return errBackhaulHolder |
| + } |
| if ref == "" || ref == "none" || ref == box { |
| return nil |
| } |
| @@ -236,8 +290,10 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia |
| if nextRef != "" { |
| e.logThrottled("backhaul-retry "+nextRef, fmt.Sprintf("backhaul %s for %s: %s to %s", nextReason, host, box, nextRef)) |
| // First attempt plus one retry, at most two attempts total. A connect |
| - // fallback and a §6.5 holder follow spend the same retry budget. |
| - // Start with the original context so trace callbacks cannot accumulate. |
| - e.backhaulAttempt(w, original, host, nextDial, nextRef, key, owner, false) |
| + // fallback, a §6.5 holder follow and a handover follow spend the |
| + // same budget (nextForwardAttempt). Start with the original context |
| + // so trace callbacks cannot accumulate; a copied body goes again |
| + // from the copy, unmarked. |
| + e.backhaulAttempt(w, original, host, nextDial, nextRef, key, owner, whole) |
| } |
| } |
diff --git a/internal/edge/backhaul_retry.go b/internal/edge/backhaul_retry.go| index a1c8f03d9..65656255b 100644 |
| --- a/internal/edge/backhaul_retry.go |
| +++ b/internal/edge/backhaul_retry.go |
| @@ -5,6 +5,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| const backhaulSuspectTTL = 60 * time.Second |
| @@ -90,3 +91,60 @@ func (m *homeMap) backhaulAlternative(host, failed string, expected backhaulOwne |
| } |
| return chosen.Serving.Dial, chosen.Serving.Box, true |
| } |
| + |
| +// handoverAlternative checks the ref a handover answer from destination |
| +// names, for a backhauled request for host with the checked owner (region |
| +// HA §25.5 "Cross-region first boxes"): not this box, a serving claim of |
| +// that owner for the name, and in destination's region view. It answers |
| +// the address to dial. |
| +func (m *homeMap) handoverAlternative(host, ref, destination string, owner backhaulOwner, now time.Time) (string, bool) { |
| + if m == nil || m.self == "" || ref == "" || ref == m.self { |
| + return "", false |
| + } |
| + snap := m.snapshot() |
| + original := resolveHomeName(host, nil, false, snap.hosts) |
| + if original.State != edgesfile.NameDialable || !owner.matches(backhaulOwnerOf(original.Authority)) { |
| + return "", false |
| + } |
| + for _, c := range snap.hosts[original.Authority.Name].claims { |
| + if c.Box == ref && c.Eligible && owner.matches(backhaulOwnerOf(c)) { |
| + return m.boxInRegionSnapshot(snap, ref, destination, now) |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// handoverAuthority is name authority for the ref of a handover answer to |
| +// a front forward for rt, a box already in this box's view (§25.5 |
| +// "Release"). When no peer publishes rt's name, the route itself is the |
| +// authority, and every box in view serves its pool. When the name is |
| +// published, its authority must be rt's own (host, account and app) and |
| +// ref must hold a serving claim of that authority. A held name refuses. |
| +func (m *homeMap) handoverAuthority(rt registry.Route, ref string) bool { |
| + if m == nil || ref == "" { |
| + return false |
| + } |
| + snap := m.snapshot() |
| + res := resolveHomeName(rt.Host, nil, false, snap.hosts) |
| + switch res.State { |
| + case edgesfile.NameAbsent: |
| + return true |
| + case edgesfile.NameDialable: |
| + default: |
| + return false |
| + } |
| + a := res.Authority |
| + target := a.Name |
| + if a.Class == edgesfile.NameAlias { |
| + target = a.TargetHost |
| + } |
| + if target != rt.Host || a.Account != registry.EffectiveAccount(rt.Account) || a.App != rt.App { |
| + return false |
| + } |
| + for _, c := range snap.hosts[a.Name].claims { |
| + if c.Box == ref && c.Eligible && c.Class == a.Class && c.Account == a.Account && c.App == a.App && c.TargetHost == a.TargetHost { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 0d4dee711..64946d7ed 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -4272,7 +4272,7 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box |
| return false |
| } |
| eip, box = e.backhaulTarget(host, eip, box, owner) |
| - e.backhaulAttempt(w, r, host, eip, box, key, owner, true) |
| + e.backhaulAttempt(w, withForwardAttempts(r), host, eip, box, key, owner, nil) |
| return true |
| } |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| index f0441228e..3ba7ee801 100644 |
| --- a/internal/edge/forwardha.go |
| +++ b/internal/edge/forwardha.go |
| @@ -231,7 +231,12 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin |
| if d.Ref == "" { |
| return false |
| } |
| - res := e.forwardHAAndNote(w, r, host, up.route, fw, d) |
| + res, here := e.forwardHAFollow(w, r, host, up.route, fw, d) |
| + if here && e.localPoolEligible(up.route) { |
| + // A handover answer named this box: served here, through the |
| + // ordinary local path, which spends no attempt. |
| + return false |
| + } |
| if res.Outcome == ForwardNotInView && !e.localPoolEligible(up.route) { |
| HAUnavailableResponse(w, r) |
| return true |
| @@ -243,7 +248,68 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin |
| return res.Outcome != ForwardNotInView |
| } |
| +// forwardHAAndNote is forwardHAFollow for a caller that cannot serve here: |
| +// a handover answer naming this box is reported as ForwardNotInView, and |
| +// the caller gives today's answer for that. |
| func (e *Edge) forwardHAAndNote(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, fw HAForwarder, d ForwardDecision) ForwardResult { |
| + res, _ := e.forwardHAFollow(w, r, host, rt, fw, d) |
| + return res |
| +} |
| + |
| +// forwardHAStreaming is forwardHAAndNote with the body streamed as today, |
| +// never copied, marked or replayed: the draining box's release of a |
| +// client's request to the confirmed holder (§25.5 "Release"), whose |
| +// every exit must answer without waiting for a body (R3.3). |
| +func (e *Edge) forwardHAStreaming(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, fw HAForwarder, d ForwardDecision) ForwardResult { |
| + return e.forwardHANoted(w, withForwardAttempts(r), host, rt, fw, d, &forwardAttempt{rt: rt, stream: true}) |
| +} |
| + |
| +// forwardAttempt is one forward's share of a request's attempts (replay.go): |
| +// the route its handover ref is checked against, the request whose body |
| +// is restored once copied (orig, for local service), the whole copy, and |
| +// the next attempt a handover answer asked for. |
| +type forwardAttempt struct { |
| + rt registry.Route |
| + orig *http.Request |
| + whole *wholeBody |
| + next *handoverNext |
| + // stream: the body is never copied (forwardHAStreaming). |
| + stream bool |
| +} |
| + |
| +// handoverNext is where a first attempt's handover answer sends the |
| +// request: the box ref, dialled at dial, or this box (here). |
| +type handoverNext struct { |
| + ref, dial string |
| + here bool |
| +} |
| + |
| +// forwardHAFollow forwards r to d.Ref and tells the activator how it went, |
| +// as forwardHAAndNote always has, and follows a handover answer to the |
| +// first attempt (region HA §25.5 "Release", H2, H3): the body was copied |
| +// whole before that attempt and the attempt was marked replayable, the |
| +// answer's ref is in view and passes name authority, and the copy goes |
| +// there as the second and last attempt, unmarked. here is true when the |
| +// ref named this box: nothing more was sent, r's body is the copy again, |
| +// and the result is ForwardNotInView, so the caller serves r here or gives |
| +// today's answer. |
| +func (e *Edge) forwardHAFollow(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, fw HAForwarder, d ForwardDecision) (ForwardResult, bool) { |
| + at := &forwardAttempt{rt: rt, orig: r} |
| + r = withForwardAttempts(r) |
| + res := e.forwardHANoted(w, r, host, rt, fw, d, at) |
| + next := at.next |
| + if next == nil { |
| + return res, false |
| + } |
| + if next.here { |
| + return ForwardResult{Outcome: ForwardNotInView, Ref: next.ref, Gen: d.Gen, Kind: d.Kind, PeerGen: d.PeerGen}, true |
| + } |
| + e.logThrottled("forward-handover "+next.ref, fmt.Sprintf("forward %s: %s handed the request over to %s; sending it there", host, d.Ref, next.ref)) |
| + second := &forwardAttempt{rt: rt, orig: at.orig, whole: at.whole} |
| + return e.forwardHANoted(w, r, host, rt, fw, ForwardDecision{Ref: next.ref, Kind: Holder}, second), false |
| +} |
| + |
| +func (e *Edge) forwardHANoted(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, fw HAForwarder, d ForwardDecision, at *forwardAttempt) ForwardResult { |
| var observation *forwardDialObservation |
| if d.Kind != Holder { |
| observation = &forwardDialObservation{report: func() { |
| @@ -253,7 +319,7 @@ func (e *Edge) forwardHAAndNote(w http.ResponseWriter, r *http.Request, host str |
| } |
| res := e.forwardHAObserved(w, r, host, d, func(res ForwardResult) { |
| fw.NoteForward(rt.Host, res) |
| - }) |
| + }, at) |
| if d.Kind != Holder || res.Status == 0 { |
| fw.NoteForward(rt.Host, res) |
| } |
| @@ -273,10 +339,18 @@ func (e *Edge) forwardHAAndNote(w http.ResponseWriter, r *http.Request, host str |
| // 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 string, d ForwardDecision) ForwardResult { |
| - return e.forwardHAObserved(w, r, host, d, nil) |
| + return e.forwardHAObserved(w, r, host, d, nil, nil) |
| } |
| -func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host string, d ForwardDecision, note func(ForwardResult)) ForwardResult { |
| +// forwardHAObserved is one attempt. With at, it spends one of r's attempts |
| +// (nextForwardAttempt): on the first it copies the body whole when it can |
| +// (copyWholeBody) and marks the hop replayable, on the second it sends the |
| +// copy unmarked, and it never makes a third. A handover answer to a marked |
| +// first attempt is consumed before the proxy writes anything and, when its |
| +// ref checks out (handoverInRegion), recorded in at.next for the caller to |
| +// follow. Every other answer, the handover answer to anything else |
| +// included, is relayed as today, without the handover header. |
| +func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host string, d ForwardDecision, note func(ForwardResult), at *forwardAttempt) ForwardResult { |
| ref := d.Ref |
| res := ForwardResult{Outcome: ForwardNotInView, Ref: ref, Gen: d.Gen, Kind: d.Kind, PeerGen: d.PeerGen} |
| m := e.homes.Load() |
| @@ -298,6 +372,39 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st |
| // its admission ticket end (handover.go); a ForwardNotInView above falls |
| // back to local service with the ticket still held. |
| ReleaseMoveTicket(r) |
| + n, ok := nextForwardAttempt(r) |
| + if !ok { |
| + // I4: never a third attempt. Unreachable while one forward at a |
| + // time spends the counter; today's answer if it ever is reached. |
| + answerHolderUnreachable(w, r) |
| + return res |
| + } |
| + marked := false |
| + if at != nil && !at.stream { |
| + if n == 1 && at.whole == nil { |
| + whole, err := copyWholeBody(r) |
| + if err != nil { |
| + // The body broke off before it was all here, as it would |
| + // have while being proxied: the same answer, before any dial. |
| + if r.Context().Err() != nil { |
| + res.Outcome = ForwardCanceled |
| + } |
| + e.logThrottled("forward-error "+ref, fmt.Sprintf("forward %s → %s: reading the request body: %v", host, ref, err)) |
| + w.WriteHeader(http.StatusBadGateway) |
| + return res |
| + } |
| + if whole != nil { |
| + at.whole = whole |
| + if at.orig != nil { |
| + at.orig.Body = whole.reader() |
| + } |
| + } |
| + } |
| + if at.whole != nil { |
| + marked = n == 1 |
| + r = at.whole.request(r, marked) |
| + } |
| + } |
| stopObservation := func() {} |
| if d.Kind == Holder && note != nil { |
| silent := res |
| @@ -308,6 +415,9 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st |
| defer stopObservation() |
| } |
| onError := func(w http.ResponseWriter, r *http.Request, err error) { |
| + if errors.Is(err, errHandoverFollow) { |
| + return // consumed for a second attempt; nothing is written |
| + } |
| if res.Status == 0 && (r.Context().Err() != nil || errors.Is(err, errForwardDialQueued)) { |
| res.Outcome = ForwardCanceled |
| } |
| @@ -336,10 +446,53 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st |
| note(res) |
| } |
| } |
| - e.hopTo(w, r, host, dial, ref, key, "forward", e.forwardTransport(dial), onError, onResponse) |
| + tr := backhaulHolderTransport{RoundTripper: e.forwardTransport(dial), response: func(resp *http.Response) error { |
| + v := resp.Header.Get(HandoverHeader) |
| + if v == "" { |
| + return nil |
| + } |
| + resp.Header.Del(HandoverHeader) |
| + if !marked || resp.StatusCode != http.StatusServiceUnavailable { |
| + return nil |
| + } |
| + next, ok := e.handoverInRegion(v, at.rt) |
| + if !ok { |
| + return nil |
| + } |
| + at.next = &next |
| + // The answer is noted as the holder's 503 naming the new holder, |
| + // which is what it carries in X-Carlos-Holder: the activator's |
| + // holder cache follows it (or drops itself, for this box). |
| + stopObservation() |
| + res.Status, res.Holder = resp.StatusCode, next.ref |
| + if d.Kind == Holder && note != nil { |
| + note(res) |
| + } |
| + return errHandoverFollow |
| + }} |
| + e.hopTo(w, r, host, dial, ref, key, "forward", tr, onError, onResponse) |
| return res |
| } |
| +// handoverInRegion checks the ref of a handover answer (HandoverHeader's |
| +// value v) to a front forward for rt: this box, or a box in this box's |
| +// view that passes name authority for rt (handoverAuthority). |
| +func (e *Edge) handoverInRegion(v string, rt registry.Route) (handoverNext, bool) { |
| + ref, _, ok := ParseHandover(v) |
| + m := e.homes.Load() |
| + if !ok || m == nil || m.self == "" { |
| + return handoverNext{}, false |
| + } |
| + if ref == m.self { |
| + return handoverNext{ref: ref, here: true}, true |
| + } |
| + dial, ok := m.boxInView(ref, time.Now()) |
| + if !ok || !m.handoverAuthority(rt, ref) { |
| + return handoverNext{}, false |
| + } |
| + return handoverNext{ref: ref, dial: dial}, true |
| +} |
| + |
| const holderHeaderSuspectAfter = 3 * time.Second |
| // Observation never cancels the transport. Joining at final headers orders |
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go| index 1f97b70e8..3f897db3d 100644 |
| --- a/internal/edge/forwardha_test.go |
| +++ b/internal/edge/forwardha_test.go |
| @@ -15,6 +15,7 @@ package edge |
| import ( |
| "bufio" |
| "context" |
| + "crypto/sha256" |
| "crypto/tls" |
| "errors" |
| "fmt" |
| @@ -158,6 +159,16 @@ func fwApp(t *testing.T, box string) *fwAppServer { |
| echo.ServeHTTP(w, r) |
| case r.URL.Path == "/missing": |
| http.NotFound(w, r) |
| + case r.URL.Path == "/echo-body": |
| + // The body as delivered: its length and a digest, so a replay |
| + // can be checked byte for byte (replay_test.go). |
| + b, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + http.Error(w, err.Error(), http.StatusBadRequest) |
| + return |
| + } |
| + sum := sha256.Sum256(b) |
| + fmt.Fprintf(w, "%s|%d|%x", box, len(b), sum[:8]) |
| case r.URL.Path == "/echo-replayable": |
| // What the app was handed of the replay mark, and an app's |
| // attempt at the platform's handover answer (handover.go). |
| @@ -227,6 +238,8 @@ type fwScene struct { |
| type fwOpts struct { |
| // aAct replaces annie's forwarding fake (nil keeps it). |
| aAct Activator |
| + // bAct replaces betty's (nil keeps it). |
| + bAct Activator |
| // aTarget is the box annie's fake names ("" is betty). |
| aTarget string |
| // bettyLacks leaves betty without the HA hosts: in view, not serving. |
| @@ -272,14 +285,17 @@ func newFwScene(t *testing.T, o fwOpts) *fwScene { |
| if o.aTarget != "" { |
| x.aAct.target = o.aTarget |
| } |
| - var aAct Activator = x.aAct |
| + var aAct, bAct Activator = x.aAct, x.bAct |
| if o.aAct != nil { |
| aAct = o.aAct |
| } |
| + if o.bAct != nil { |
| + bAct = o.bAct |
| + } |
| extra := backhaulSceneExtra{ |
| homeRoutes: routes(x.aApp.srv.Listener.Addr().String()), |
| homeAct: aAct, |
| - farAct: x.bAct, |
| + farAct: bAct, |
| certs: append(append([]string(nil), fwHosts...), o.certs...), |
| } |
| if !o.bettyLacks { |
diff --git a/internal/edge/handover.go b/internal/edge/handover.go| index f86b5df6b..03e44f3bd 100644 |
| --- a/internal/edge/handover.go |
| +++ b/internal/edge/handover.go |
| @@ -25,6 +25,7 @@ import ( |
| "bufio" |
| "context" |
| "fmt" |
| + "io" |
| "net" |
| "net/http" |
| "strconv" |
| @@ -233,6 +234,7 @@ func (e *Edge) moveGate(w http.ResponseWriter, r *http.Request, host string, rt |
| handoverExit(w, r, answerHolderUnreachable) |
| return r, true |
| } |
| + drainReplayable(w, r) |
| handoverExit(w, r, func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set(HandoverHeader, FormatHandover(c.Holder, c.Gen)) |
| w.Header().Set(holderHeader, c.Holder) |
| @@ -252,7 +254,7 @@ func (e *Edge) moveGate(w http.ResponseWriter, r *http.Request, host string, rt |
| return r, true |
| } |
| handoverExit(w, r, func(w http.ResponseWriter, r *http.Request) { |
| - res := e.forwardHAAndNote(w, r, host, rt, fw, ForwardDecision{Ref: d.Holder, Kind: Holder, Gen: d.ForwardGen}) |
| + res := e.forwardHAStreaming(w, r, host, rt, fw, ForwardDecision{Ref: d.Holder, Kind: Holder, Gen: d.ForwardGen}) |
| if res.Outcome == ForwardNotInView { |
| answerHolderUnreachable(w, r) |
| } |
| @@ -264,6 +266,27 @@ func (e *Edge) moveGate(w http.ResponseWriter, r *http.Request, host string, rt |
| return r, true |
| } |
| +// replayDrainBound bounds reading a replayable hop's body before its |
| +// handover answer (drainReplayable). |
| +const replayDrainBound = time.Second |
| + |
| +// drainReplayable reads and discards a replayable hop's body before the |
| +// handover answer is written, best effort. Its sender holds a whole copy, |
| +// of known length and at most replayBodyLimit, and writes it at once, so |
| +// the read is bounded by that length and by replayDrainBound. Without it, |
| +// a sender still writing a body this box never read can meet the reset |
| +// of the closing connection and lose the answer that lets it send the |
| +// copy on (seen at 64 KiB on loopback). Any other framing is not read at |
| +// all, and neither is a hop that is not marked; the answer is the same |
| +// either way. |
| +func drainReplayable(w http.ResponseWriter, r *http.Request) { |
| + if !arrivedReplayable(r) || len(r.TransferEncoding) > 0 || r.ContentLength <= 0 || r.ContentLength > replayBodyLimit { |
| + return |
| + } |
| + _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(replayDrainBound)) |
| + _, _ = io.Copy(io.Discard, io.LimitReader(r.Body, r.ContentLength)) |
| +} |
| + |
| // handoverExit is the one response path of every handover exit (R3.3): a |
| // release to the confirmed holder, a handover answer, a refusal, a cap, a |
| // timeout, a lost lease and a failed move. It enables full duplex before |
diff --git a/internal/edge/replay.go b/internal/edge/replay.go| new file mode 100644 |
| index 000000000..fea669e95 |
| --- /dev/null |
| +++ b/internal/edge/replay.go |
| @@ -0,0 +1,109 @@ |
| +package edge |
| + |
| +// The first box's half of held requests (region HA spec §25.3 H2, H3, |
| +// §25.5 "Release", §25.15). A box that forwards an HA request, in region |
| +// (forwardHA) or across regions (backhaulAttempt), may send it a second |
| +// time only from a whole copy of its body, and the attempts it makes are |
| +// counted in one place. |
| +// |
| +// - H2, the copy: copyWholeBody, called once, before the first send. A |
| +// body is copied whole only when that changes nothing for a request |
| +// that is not replayable: no body, or a known Content-Length of at |
| +// most replayBodyLimit. Chunked and unknown-length bodies of any size |
| +// are never read here; they stream as today and are never replayed. |
| +// - H3, the budget: nextForwardAttempt, one counter per request, which |
| +// the front forward, the backhaul holder follow (§6.5) and the |
| +// backhaul connect fallback all spend. At most maxForwardAttempts, and |
| +// a handover answer is followed only when it answered attempt 1. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "sync/atomic" |
| +) |
| + |
| +// replayBodyLimit is the largest body a first box copies whole (§25.5's |
| +// bound table, §25.8 as amended by R3.6). |
| +const replayBodyLimit = 64 << 10 |
| + |
| +// maxForwardAttempts is I4's limit: a request is forwarded at most twice. |
| +const maxForwardAttempts = 2 |
| + |
| +// errHandoverFollow is a first attempt's handover answer that the |
| +// forward's transport consumed, so it can be sent again; the proxy writes |
| +// nothing for it. |
| +var errHandoverFollow = errors.New("handover follow") |
| + |
| +type forwardAttemptsKey struct{} |
| + |
| +// withForwardAttempts is r carrying its attempt counter, installed once |
| +// where a forward begins; a request that already carries one keeps it. |
| +func withForwardAttempts(r *http.Request) *http.Request { |
| + if _, ok := r.Context().Value(forwardAttemptsKey{}).(*atomic.Int32); ok { |
| + return r |
| + } |
| + return r.WithContext(context.WithValue(r.Context(), forwardAttemptsKey{}, new(atomic.Int32))) |
| +} |
| + |
| +// nextForwardAttempt spends one of r's forward attempts and answers its |
| +// number. ok is false once maxForwardAttempts are spent: the request is |
| +// never sent a third time. A request with no counter is treated as on its |
| +// last attempt, so nothing about it is ever followed. |
| +func nextForwardAttempt(r *http.Request) (n int, ok bool) { |
| + c, has := r.Context().Value(forwardAttemptsKey{}).(*atomic.Int32) |
| + if !has { |
| + return maxForwardAttempts, true |
| + } |
| + n = int(c.Add(1)) |
| + return n, n <= maxForwardAttempts |
| +} |
| + |
| +// wholeBody is a request body read whole into memory before its first |
| +// send. |
| +type wholeBody struct{ b []byte } |
| + |
| +// copyWholeBody is H2's one body preparation. It reads r's body whole |
| +// when r has no body or a known Content-Length of at most replayBodyLimit, |
| +// and answers nil, reading nothing, for anything else. An error is a body |
| +// that could not be read in full (the client left or broke off), and r |
| +// cannot be sent. |
| +func copyWholeBody(r *http.Request) (*wholeBody, error) { |
| + if len(r.TransferEncoding) > 0 || r.ContentLength < 0 || r.ContentLength > replayBodyLimit { |
| + return nil, nil |
| + } |
| + if r.ContentLength == 0 { |
| + return &wholeBody{}, nil |
| + } |
| + b := make([]byte, r.ContentLength) |
| + if _, err := io.ReadFull(r.Body, b); err != nil { |
| + return nil, err |
| + } |
| + return &wholeBody{b: b}, nil |
| +} |
| + |
| +// reader is a fresh reader over the copy. |
| +func (c *wholeBody) reader() io.ReadCloser { |
| + if len(c.b) == 0 { |
| + return http.NoBody |
| + } |
| + return io.NopCloser(bytes.NewReader(c.b)) |
| +} |
| + |
| +// request is r for one send of the copy: a fresh body reader, and its own |
| +// header, marked ReplayableHeader only when marked (the first attempt). |
| +// Expect is dropped: the body is already here, so nobody need be asked |
| +// for it. |
| +func (c *wholeBody) request(r *http.Request, marked bool) *http.Request { |
| + out := r.WithContext(r.Context()) |
| + out.Header = r.Header.Clone() |
| + out.Header.Del("Expect") |
| + out.Header.Del(ReplayableHeader) |
| + if marked { |
| + out.Header.Set(ReplayableHeader, "1") |
| + } |
| + out.Body = c.reader() |
| + return out |
| +} |
diff --git a/internal/edge/replay_test.go b/internal/edge/replay_test.go| new file mode 100644 |
| index 000000000..894cfc89f |
| --- /dev/null |
| +++ b/internal/edge/replay_test.go |
| @@ -0,0 +1,866 @@ |
| +package edge |
| + |
| +// The first box's half of held requests (region HA §25.3 H2, H3; §25.5 |
| +// "Release"): a box that forwards an HA request sends it a second time only |
| +// from a whole copy of the body, and only when the draining box answered |
| +// its first attempt with X-Carlos-Handover. |
| +// |
| +// The in-region scene is the forward scene (forwardha_test.go) with a third |
| +// box. Annie is the first box: her activator names betty as the holder. |
| +// Betty is the draining box A: her fake mover gives a replayable hop the |
| +// handover answer naming dora, and any other hop today's answer. Dora is the |
| +// confirmed holder B and serves. Every request is a real client's, through |
| +// annie's real Edge.ServeHTTP over real TLS and HTTP/1.1, and every hop is a |
| +// real signed hop over the forward transport. |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// rpDoraEIP is dora's address as her edges file publishes it. The forward |
| +// dial seam sends it to dora's door and every other address to betty's. |
| +const rpDoraEIP = "127.0.0.3" |
| + |
| +// rpMover is a box's activator with MoveState, scripted by mode: |
| +// - "handover": a replayable hop gets the handover answer naming ref, any |
| +// other hop today's answer (Task 2's real decision, in short); |
| +// - "all": every hop gets the handover answer, replayable or not; |
| +// - "": nothing is moving, and the box serves. |
| +// |
| +// Path /reset is answered by closing the connection with no response. |
| +type rpMover struct { |
| + *fwAct |
| + mu sync.Mutex |
| + mode string |
| + ref string |
| + asks []MoveAsk |
| +} |
| + |
| +var _ HAMover = (*rpMover)(nil) |
| + |
| +func (m *rpMover) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, next http.Handler) bool { |
| + if r.URL.Path == "/reset" { |
| + conn, _, err := http.NewResponseController(w).Hijack() |
| + if err == nil { |
| + if tc, ok := conn.(*tls.Conn); ok { |
| + if raw, ok := tc.NetConn().(*net.TCPConn); ok { |
| + raw.SetLinger(0) |
| + } |
| + } |
| + conn.Close() |
| + } |
| + return true |
| + } |
| + return m.fwAct.ServeHTTP(w, r, rt, next) |
| +} |
| + |
| +func (m *rpMover) MoveState(_ registry.Route, ask MoveAsk) MoveDecision { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.asks = append(m.asks, ask) |
| + switch { |
| + case ask.Hop && (m.mode == "all" || m.mode == "handover" && ask.Replayable): |
| + return MoveDecision{Phase: MoveTaken, Holder: m.ref, Gen: 9} |
| + case ask.Hop && m.mode == "handover": |
| + return MoveDecision{Phase: MoveRefused} |
| + } |
| + return MoveDecision{} |
| +} |
| + |
| +func (m *rpMover) ConfirmMoveHolder(context.Context, registry.Route, func() boxchoice.WakeSnapshot) MoveDecision { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return MoveDecision{Phase: MoveTaken, Holder: m.ref, Gen: 9} |
| +} |
| + |
| +func (m *rpMover) set(mode, ref string) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.mode, m.ref = mode, ref |
| +} |
| + |
| +// marks are the replay marks of the hops this box was asked about, in |
| +// order, and then forgets them. |
| +func (m *rpMover) marks() []bool { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + var out []bool |
| + for _, a := range m.asks { |
| + if a.Hop { |
| + out = append(out, a.Replayable) |
| + } |
| + } |
| + m.asks = nil |
| + return out |
| +} |
| + |
| +// rpFirst is annie's activator: fwAct, plus the memory-only forward a |
| +// held-stream request uses, counted. |
| +type rpFirst struct { |
| + *fwAct |
| + mem atomic.Int64 |
| +} |
| + |
| +func (a *rpFirst) ForwardTargetFromMemory(registry.Route, func() boxchoice.WakeSnapshot) (ForwardDecision, bool) { |
| + a.mem.Add(1) |
| + return ForwardDecision{Ref: a.target, Gen: a.gen}, true |
| +} |
| + |
| +type rpScene struct { |
| + *fwScene |
| + first *rpFirst |
| + drain *rpMover // betty, the draining box |
| + dora *backhaulEdge |
| + doraAct *rpMover |
| + doraApp *fwAppServer |
| + dialMu sync.Mutex |
| + dials []string |
| +} |
| + |
| +func newRpScene(t *testing.T) *rpScene { |
| + t.Helper() |
| + x := &rpScene{ |
| + first: &rpFirst{fwAct: &fwAct{target: "betty"}}, |
| + drain: &rpMover{fwAct: &fwAct{}, mode: "handover", ref: "dora"}, |
| + } |
| + x.fwScene = newFwScene(t, fwOpts{aAct: x.first, bAct: x.drain, certs: []string{hoAlias}}) |
| + x.aAct = x.first.fwAct |
| + x.doraApp = fwApp(t, "dora") |
| + x.doraAct = &rpMover{fwAct: &fwAct{}} |
| + x.dora = newBackhaulEdgeWith(t, x.bucket, "dora", x.ca, nil, x.doraAct, []registry.Route{{ |
| + Host: fwHost, Kind: "instance", Hibernate: true, Addr: x.doraApp.srv.Listener.Addr().String(), Status: "ready", Account: "abc", App: "shop", |
| + }}) |
| + if err := x.dora.reg.SetHA(fwHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, be := range []*backhaulEdge{x.a, x.b, x.dora} { |
| + if err := be.reg.UpsertAlias(registry.RouteAlias{Alias: hoAlias, Host: fwHost, Account: "abc", App: "shop", CreatedAt: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := be.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + x.publishDora(t, "ie") |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + x.dialMu.Lock() |
| + x.dials = append(x.dials, addr) |
| + x.dialMu.Unlock() |
| + to := x.b.tlsAddr |
| + if h, _, _ := net.SplitHostPort(addr); h == rpDoraEIP { |
| + to = x.dora.tlsAddr |
| + } |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, to) |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| + return x |
| +} |
| + |
| +// publishDora writes dora's edges file in region (in view when "ie") and |
| +// folds it on every box. |
| +func (x *rpScene) publishDora(t *testing.T, region string) { |
| + t.Helper() |
| + putJSON(t, x.seed, "control/edges/dora.json", fmt.Sprintf( |
| + `{"v":1,"box":"dora","eip":%q,"region":%q,"placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{}}`, |
| + rpDoraEIP, region, time.Now().UTC().Format(time.RFC3339))) |
| + if err := x.dora.mirror.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, be := range []*backhaulEdge{x.a, x.b, x.dora} { |
| + refreshHomeMap(t, be.homes) |
| + } |
| +} |
| + |
| +func (x *rpScene) dialled() []string { |
| + x.dialMu.Lock() |
| + defer x.dialMu.Unlock() |
| + d := x.dials |
| + x.dials = nil |
| + return d |
| +} |
| + |
| +// counts are the requests that reached betty's and dora's doors. |
| +func (x *rpScene) counts(t *testing.T) (betty, dora int64) { |
| + t.Helper() |
| + laWaitFor(t, "every edge's handlers to return", func() bool { |
| + return x.a.served.Load() == x.a.calls.Load() && x.b.served.Load() == x.b.calls.Load() && x.dora.served.Load() == x.dora.calls.Load() |
| + }) |
| + return x.b.calls.Load(), x.dora.calls.Load() |
| +} |
| + |
| +// post sends method to annie with body: of known length, or chunked |
| +// (unknown length) when chunked is set. |
| +func (x *rpScene) post(t *testing.T, method, host, path string, body []byte, chunked bool) (*http.Response, string) { |
| + t.Helper() |
| + var rd io.Reader = bytes.NewReader(body) |
| + if chunked { |
| + rd = io.MultiReader(bytes.NewReader(body)) // hides the length |
| + } |
| + req, err := http.NewRequest(method, "https://"+host+path, rd) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if body == nil { |
| + req.Body, req.ContentLength = nil, 0 |
| + } |
| + resp, err := x.a.client.Do(req) |
| + if err != nil { |
| + t.Fatalf("%s %s%s: %v", method, host, path, err) |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp, string(b) |
| +} |
| + |
| +func rpBody(t *testing.T, n int) []byte { |
| + t.Helper() |
| + b := make([]byte, n) |
| + if _, err := rand.Read(b); err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +func rpEcho(box string, body []byte) string { |
| + sum := sha256.Sum256(body) |
| + return fmt.Sprintf("%s|%d|%x", box, len(body), sum[:8]) |
| +} |
| + |
| +// wantToday is today's answer to a request the move did not let through: |
| +// betty's 503, Retry-After: 10, relayed, with no handover header. |
| +func wantToday(t *testing.T, resp *http.Response, body string) { |
| + t.Helper() |
| + wantTodayStatus(t, resp.StatusCode, resp.Header, body, false) |
| +} |
| + |
| +// wantTodayStatus is wantToday. streamed allows a 502 as well: a body |
| +// this box streams (not replayable) and the draining box refuses at once |
| +// without reading (R3.3) can meet the reset of the closing connection |
| +// before the 503 is read. That is Task 2's bounded exit, unchanged here; |
| +// what matters is that nothing is replayed. |
| +func wantTodayStatus(t *testing.T, status int, h http.Header, body string, streamed bool) { |
| + t.Helper() |
| + if streamed && status == http.StatusBadGateway && h.Get(HandoverHeader) == "" { |
| + return |
| + } |
| + resp := &http.Response{StatusCode: status, Header: h} |
| + if resp.StatusCode != 503 || resp.Header.Get("Retry-After") != "10" || resp.Header.Get(HandoverHeader) != "" || !strings.Contains(body, "retry shortly") { |
| + t.Fatalf("%d %v %q, want today's answer (503, Retry-After: 10, no handover header)", resp.StatusCode, resp.Header, body) |
| + } |
| +} |
| + |
| +func equalMarks(got []bool, want ...bool) bool { |
| + if len(got) != len(want) { |
| + return false |
| + } |
| + for i := range got { |
| + if got[i] != want[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// A body of known length up to 64 KiB, and no body at all, is copied whole |
| +// before the first send, marked replayable, and replayed once to the holder |
| +// the handover answer names, without the mark, byte for byte. |
| +func TestReplayWholeCopyOnce(t *testing.T) { |
| + x := newRpScene(t) |
| + for _, tc := range []struct { |
| + name string |
| + method string |
| + n int |
| + }{ |
| + {"POST 64 KiB", http.MethodPost, 64 << 10}, |
| + {"POST 10 bytes", http.MethodPost, 10}, |
| + {"POST empty", http.MethodPost, 0}, |
| + {"GET", http.MethodGet, -1}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + b0, d0 := x.counts(t) |
| + var body []byte |
| + if tc.n >= 0 { |
| + body = rpBody(t, tc.n) |
| + } |
| + resp, got := x.post(t, tc.method, fwHost, "/echo-body", body, false) |
| + if resp.StatusCode != 200 || got != rpEcho("dora", body) { |
| + t.Fatalf("%d %q, want dora's echo %q", resp.StatusCode, got, rpEcho("dora", body)) |
| + } |
| + if resp.Header.Get(HandoverHeader) != "" { |
| + t.Fatalf("the handover header reached the client: %v", resp.Header) |
| + } |
| + b, d := x.counts(t) |
| + if b-b0 != 1 || d-d0 != 1 { |
| + t.Fatalf("betty saw %d, dora %d; want one attempt each", b-b0, d-d0) |
| + } |
| + if m := x.drain.marks(); !equalMarks(m, true) { |
| + t.Fatalf("betty's hop marks %v, want [true]", m) |
| + } |
| + if m := x.doraAct.marks(); !equalMarks(m, false) { |
| + t.Fatalf("dora's hop marks %v, want [false]: the second attempt is never marked", m) |
| + } |
| + }) |
| + } |
| + if n := x.bApp.n.Load(); n != 0 { |
| + t.Fatalf("betty's app saw %d requests, want none", n) |
| + } |
| + // The holder is cached: the first attempt's answer is noted naming dora, |
| + // then the second attempt's from dora. |
| + notes := x.first.noted() |
| + if len(notes) < 2 { |
| + t.Fatalf("notes %v", notes) |
| + } |
| + last := notes[len(notes)-2:] |
| + if last[0].res.Ref != "betty" || last[0].res.Status != 503 || last[0].res.Holder != "dora" || last[1].res.Ref != "dora" || last[1].res.Status != 200 { |
| + t.Fatalf("notes %+v, want betty's 503 naming dora, then dora's 200", last) |
| + } |
| +} |
| + |
| +// Over 64 KiB, and of unknown length however small, a body is not copied: |
| +// it streams as today, unmarked, and gets today's answer. |
| +func TestReplayNotWholeGetsTodaysAnswer(t *testing.T) { |
| + x := newRpScene(t) |
| + for _, tc := range []struct { |
| + name string |
| + n int |
| + chunked bool |
| + }{ |
| + {"64 KiB + 1", 64<<10 + 1, false}, |
| + {"10 bytes chunked", 10, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + b0, d0 := x.counts(t) |
| + resp, body := x.post(t, http.MethodPost, fwHost, "/echo-body", rpBody(t, tc.n), tc.chunked) |
| + wantTodayStatus(t, resp.StatusCode, resp.Header, body, tc.n > replayBodyLimit) |
| + b, d := x.counts(t) |
| + if b-b0 != 1 || d-d0 != 0 { |
| + t.Fatalf("betty saw %d, dora %d; want one attempt, to betty", b-b0, d-d0) |
| + } |
| + if m := x.drain.marks(); !equalMarks(m, false) { |
| + t.Fatalf("betty's hop marks %v, want [false]", m) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// rpRaw sends one raw HTTP/1.1 request to annie's door and returns the |
| +// connection's reader. |
| +func (x *rpScene) rawConn(t *testing.T, host string) (*tls.Conn, *bufio.Reader) { |
| + t.Helper() |
| + raw, err := net.DialTimeout("tcp", x.a.tlsAddr, 5*time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := tls.Client(raw, &tls.Config{ServerName: host, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12}) |
| + t.Cleanup(func() { c.Close() }) |
| + c.SetDeadline(time.Now().Add(15 * time.Second)) |
| + return c, bufio.NewReader(c) |
| +} |
| + |
| +// A chunked body with trailers, on the wire: not replayable, today's |
| +// answer. |
| +func TestReplayChunkedWithTrailers(t *testing.T) { |
| + x := newRpScene(t) |
| + c, br := x.rawConn(t, fwHost) |
| + fmt.Fprintf(c, "POST /echo-body HTTP/1.1\r\nHost: %s\r\nTransfer-Encoding: chunked\r\nTrailer: X-Sum\r\n\r\na\r\n0123456789\r\n0\r\nX-Sum: 1\r\n\r\n", fwHost) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + wantToday(t, resp, string(b)) |
| + if _, d := x.counts(t); d != 0 { |
| + t.Fatalf("dora saw %d requests, want none", d) |
| + } |
| + if m := x.drain.marks(); !equalMarks(m, false) { |
| + t.Fatalf("betty's hop marks %v, want [false]", m) |
| + } |
| +} |
| + |
| +// Expect: 100-continue: annie asks for the body (100 Continue), copies it |
| +// whole, and the replay delivers it byte for byte. |
| +func TestReplayExpectContinue(t *testing.T) { |
| + x := newRpScene(t) |
| + body := rpBody(t, 2048) |
| + c, br := x.rawConn(t, fwHost) |
| + fmt.Fprintf(c, "POST /echo-body HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\nExpect: 100-continue\r\n\r\n", fwHost, len(body)) |
| + line, err := br.ReadString('\n') |
| + if err != nil || !strings.HasPrefix(line, "HTTP/1.1 100") { |
| + t.Fatalf("interim: %q %v, want 100 Continue", line, err) |
| + } |
| + for { |
| + l, err := br.ReadString('\n') |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if l == "\r\n" { |
| + break |
| + } |
| + } |
| + c.Write(body) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 200 || string(got) != rpEcho("dora", body) { |
| + t.Fatalf("%d %q, want dora's echo", resp.StatusCode, got) |
| + } |
| + if b, d := x.counts(t); b != 1 || d != 1 { |
| + t.Fatalf("betty saw %d, dora %d", b, d) |
| + } |
| +} |
| + |
| +// No replay after a connection reset, or after any answer but the |
| +// handover answer: the request gets today's answer, from one attempt. |
| +func TestReplayNeverAfterOtherAnswers(t *testing.T) { |
| + x := newRpScene(t) |
| + x.drain.set("", "dora") |
| + for _, tc := range []struct { |
| + name, path string |
| + status int |
| + }{ |
| + {"connection reset", "/reset", http.StatusBadGateway}, |
| + {"the holder's 503 naming another box", "/platform-held?ref=dora", 503}, |
| + {"an app's 503", "/holder?ref=dora", 503}, |
| + {"a 200", "/echo-body", 200}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + b0, d0 := x.counts(t) |
| + resp, _ := x.post(t, http.MethodPost, fwHost, tc.path, rpBody(t, 100), false) |
| + if resp.StatusCode != tc.status { |
| + t.Fatalf("%d, want %d", resp.StatusCode, tc.status) |
| + } |
| + b, d := x.counts(t) |
| + if b-b0 != 1 || d-d0 != 0 { |
| + t.Fatalf("betty saw %d, dora %d; want one attempt", b-b0, d-d0) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A handover answer to the second attempt gets today's answer, and the |
| +// request is never sent a third time. |
| +func TestReplaySecondAttemptHandoverGetsTodaysAnswer(t *testing.T) { |
| + x := newRpScene(t) |
| + x.doraAct.set("all", "betty") |
| + resp, body := x.post(t, http.MethodPost, fwHost, "/echo-body", rpBody(t, 10), false) |
| + wantToday(t, resp, body) |
| + if b, d := x.counts(t); b != 1 || d != 1 { |
| + t.Fatalf("betty saw %d, dora %d; want exactly two attempts", b, d) |
| + } |
| + if dl := x.dialled(); len(dl) != 2 { |
| + t.Fatalf("dials %v, want two", dl) |
| + } |
| +} |
| + |
| +// A ref naming this box serves the request here, through the ordinary |
| +// local path, with the body intact. |
| +func TestReplayRefNamingThisBoxServesLocally(t *testing.T) { |
| + x := newRpScene(t) |
| + x.drain.set("handover", "annie") |
| + body := rpBody(t, 1000) |
| + resp, got := x.post(t, http.MethodPost, fwHost, "/echo-body", body, false) |
| + if resp.StatusCode != 200 || got != rpEcho("annie", body) { |
| + t.Fatalf("%d %q, want annie's own echo", resp.StatusCode, got) |
| + } |
| + if b, d := x.counts(t); b != 1 || d != 0 { |
| + t.Fatalf("betty saw %d, dora %d", b, d) |
| + } |
| + if dl := x.dialled(); len(dl) != 1 { |
| + t.Fatalf("dials %v, want only betty", dl) |
| + } |
| +} |
| + |
| +// A ref that is not in this box's view, or does not parse, gets today's |
| +// answer. |
| +func TestReplayRefNotInViewGetsTodaysAnswer(t *testing.T) { |
| + x := newRpScene(t) |
| + for _, tc := range []struct{ name, ref string }{ |
| + {"unknown box", "zed"}, |
| + {"another region", "dora"}, |
| + {"no ref", ""}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + if tc.name == "another region" { |
| + x.publishDora(t, "us") |
| + defer x.publishDora(t, "ie") |
| + } |
| + x.drain.set("handover", tc.ref) |
| + b0, d0 := x.counts(t) |
| + resp, body := x.post(t, http.MethodPost, fwHost, "/echo-body", rpBody(t, 10), false) |
| + wantToday(t, resp, body) |
| + b, d := x.counts(t) |
| + if b-b0 != 1 || d-d0 != 0 { |
| + t.Fatalf("betty saw %d, dora %d", b-b0, d-d0) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// An alias request is replayed like any other, under the alias's name. |
| +func TestReplayAliasRequest(t *testing.T) { |
| + x := newRpScene(t) |
| + body := rpBody(t, 300) |
| + resp, got := x.post(t, http.MethodPost, hoAlias, "/echo-body", body, false) |
| + if resp.StatusCode != 200 || got != rpEcho("dora", body) { |
| + t.Fatalf("%d %q, want dora's echo", resp.StatusCode, got) |
| + } |
| + if b, d := x.counts(t); b != 1 || d != 1 { |
| + t.Fatalf("betty saw %d, dora %d", b, d) |
| + } |
| +} |
| + |
| +// A marked held-stream request follows the handover answer from memory: |
| +// no lock read on annie, and nothing woken. |
| +func TestReplayMarkedStreamFromMemory(t *testing.T) { |
| + x := newRpScene(t) |
| + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) |
| + defer cancel() |
| + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+fwHost+"/events?carlos_hold=1", nil) |
| + req.Header.Set("Accept", "text/event-stream") |
| + resp, err := x.a.client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cancel() |
| + resp.Body.Close() |
| + if b, d := x.counts(t); b != 1 || d != 1 { |
| + t.Fatalf("betty saw %d, dora %d; want the stream followed to dora", b, d) |
| + } |
| + if n := x.first.asked.Load(); n != 0 { |
| + t.Fatalf("annie asked ForwardTarget %d times, want 0 (memory only)", n) |
| + } |
| + if n := x.first.mem.Load(); n != 1 { |
| + t.Fatalf("annie asked memory %d times, want 1", n) |
| + } |
| + if m := x.drain.marks(); !equalMarks(m, true) { |
| + t.Fatalf("betty's marks %v", m) |
| + } |
| +} |
| + |
| +// Cross-region: a backhaul first box (dennis, region us) sends a POST to |
| +// annie (eu), which is moving the host and answers with the handover |
| +// naming betty (eu); dennis replays its whole copy to betty once. |
| +func newRpBackhaul(t *testing.T) (*BackhaulHolderScene, *rpMover) { |
| + t.Helper() |
| + mv := &rpMover{fwAct: &fwAct{}, mode: "handover", ref: "betty"} |
| + app := fwApp(t, "annie") |
| + rt := registry.Route{Host: HAForwardHost, Kind: "instance", Hibernate: true, Addr: app.srv.Listener.Addr().String(), Status: "ready", Account: "abc", App: "shop"} |
| + s := NewBackhaulHolderScene(t, t.TempDir(), mv, rt) |
| + if err := s.first.reg.SetHA(HAForwardHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.first.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return s, mv |
| +} |
| + |
| +func (s *BackhaulHolderScene) send(t *testing.T, body []byte, chunked bool) (int, http.Header, string) { |
| + t.Helper() |
| + var rd io.Reader = bytes.NewReader(body) |
| + if chunked { |
| + rd = io.MultiReader(bytes.NewReader(body)) |
| + } |
| + req, err := http.NewRequest(http.MethodPost, "https://"+HAForwardHost+"/echo-body", rd) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := s.sender.client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + b, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, resp.Header, string(b) |
| +} |
| + |
| +func TestReplayCrossRegionThroughBackhaul(t *testing.T) { |
| + t.Run("whole copy, replayed once", func(t *testing.T) { |
| + s, mv := newRpBackhaul(t) |
| + body := rpBody(t, 64<<10) |
| + status, h, got := s.send(t, body, false) |
| + if status != 200 || got != rpEcho("holder", body) || h.Get(HandoverHeader) != "" { |
| + t.Fatalf("%d %v %q, want betty's echo", status, h, got) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 1 { |
| + t.Fatalf("calls=%d/%d, want one attempt each", a, b) |
| + } |
| + if m := mv.marks(); !equalMarks(m, true) { |
| + t.Fatalf("annie's marks %v, want [true]", m) |
| + } |
| + // The holder is cached: the next request goes straight to betty. |
| + if status, _, got := s.send(t, body, false); status != 200 || got != rpEcho("holder", body) { |
| + t.Fatalf("next: %d %q", status, got) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 2 { |
| + t.Fatalf("calls=%d/%d, want the cached holder", a, b) |
| + } |
| + }) |
| + for _, tc := range []struct { |
| + name string |
| + n int |
| + chunked bool |
| + ref string |
| + }{ |
| + {"64 KiB + 1", 64<<10 + 1, false, "betty"}, |
| + {"10 bytes chunked", 10, true, "betty"}, |
| + {"ref not in view", 10, false, "zed"}, |
| + {"ref naming the first box", 10, false, "dennis"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, mv := newRpBackhaul(t) |
| + mv.set("handover", tc.ref) |
| + status, h, got := s.send(t, rpBody(t, tc.n), tc.chunked) |
| + // As wantTodayStatus: a streamed body refused at once may see 502. |
| + streamedReset := tc.n > replayBodyLimit && status == http.StatusBadGateway && h.Get(HandoverHeader) == "" |
| + if !streamedReset && (status != 503 || h.Get("Retry-After") != "10" || h.Get(HandoverHeader) != "") { |
| + t.Fatalf("%d %v %q, want today's answer", status, h, got) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 0 { |
| + t.Fatalf("calls=%d/%d, want one attempt", a, b) |
| + } |
| + }) |
| + } |
| + t.Run("a second-attempt handover gets today's answer", func(t *testing.T) { |
| + s, _ := newRpBackhaul(t) |
| + second := &rpMover{fwAct: &fwAct{}, mode: "all", ref: "annie"} |
| + rt := registry.Route{Host: HAForwardHost, Kind: "instance", Hibernate: true, Addr: s.app.srv.Listener.Addr().String(), Status: "ready", Account: "abc", App: "shop"} |
| + s.HolderActivator(t, second, rt) |
| + if err := s.holder.reg.SetHA(HAForwardHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.holder.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, h, got := s.send(t, rpBody(t, 10), false) |
| + if status != 503 || h.Get("Retry-After") != "10" || h.Get(HandoverHeader) != "" { |
| + t.Fatalf("%d %v %q, want today's answer", status, h, got) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 1 { |
| + t.Fatalf("calls=%d/%d, want exactly two attempts", a, b) |
| + } |
| + if m := second.marks(); !equalMarks(m, false) { |
| + t.Fatalf("betty's marks %v, want [false]", m) |
| + } |
| + }) |
| +} |
| + |
| +// A ref that is in view but fails name authority: a peer publishes the |
| +// name for another owner, and dora claims nothing for it. |
| +func TestReplayRefFailsNameAuthority(t *testing.T) { |
| + x := newRpScene(t) |
| + m := x.a.edge.homes.Load() |
| + rt := registry.Route{Host: fwHost, Account: "abc", App: "shop"} |
| + if !m.handoverAuthority(rt, "dora") { |
| + t.Fatal("an unpublished name in view: refused, want allowed") |
| + } |
| + putJSON(t, x.seed, "control/edges/dora.json", fmt.Sprintf( |
| + `{"v":1,"box":"dora","eip":%q,"region":"ie","placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{%q:{"role":"home","account":"abc","app":"other"}}}`, |
| + rpDoraEIP, time.Now().UTC().Format(time.RFC3339), fwHost)) |
| + refreshHomeMap(t, x.a.homes) |
| + if m.handoverAuthority(rt, "dora") { |
| + t.Fatal("dora claims the name for another app: allowed, want refused") |
| + } |
| + putJSON(t, x.seed, "control/edges/dora.json", fmt.Sprintf( |
| + `{"v":1,"box":"dora","eip":%q,"region":"ie","placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{%q:{"role":"home","account":"abc","app":"shop"}}}`, |
| + rpDoraEIP, time.Now().UTC().Format(time.RFC3339), fwHost)) |
| + refreshHomeMap(t, x.a.homes) |
| + if !m.handoverAuthority(rt, "dora") { |
| + t.Fatal("dora claims the name for this owner: refused, want allowed") |
| + } |
| + if m.handoverAuthority(rt, "zed") { |
| + t.Fatal("a box with no claim for a published name: allowed, want refused") |
| + } |
| +} |
| + |
| +// H3: one counter per request, two attempts, never a third; a request |
| +// with no counter is on its last attempt. |
| +func TestForwardAttemptsBudget(t *testing.T) { |
| + r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/", nil) |
| + if n, ok := nextForwardAttempt(r); n != maxForwardAttempts || !ok { |
| + t.Fatalf("no counter: %d %v, want the last attempt", n, ok) |
| + } |
| + r = withForwardAttempts(r) |
| + if again := withForwardAttempts(r); again != r { |
| + t.Fatal("a second install replaced the counter") |
| + } |
| + for want := 1; want <= 3; want++ { |
| + n, ok := nextForwardAttempt(r) |
| + if n != want || ok != (want <= 2) { |
| + t.Fatalf("attempt %d: %d %v", want, n, ok) |
| + } |
| + } |
| +} |
| + |
| +// H2: only no body, or a known length of at most 64 KiB, is copied; an |
| +// unreadable body is an error; nothing else is read at all. |
| +func TestCopyWholeBody(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + n int64 |
| + te []string |
| + short bool |
| + want bool |
| + wantErr bool |
| + }{ |
| + {"none", 0, nil, false, true, false}, |
| + {"64 KiB", 64 << 10, nil, false, true, false}, |
| + {"64 KiB + 1", 64<<10 + 1, nil, false, false, false}, |
| + {"unknown length", -1, nil, false, false, false}, |
| + {"chunked", 10, []string{"chunked"}, false, false, false}, |
| + {"short", 10, nil, true, false, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + src := &countingReader{r: bytes.NewReader(make([]byte, max(tc.n, 0)))} |
| + if tc.short { |
| + src.r = bytes.NewReader(make([]byte, 3)) |
| + } |
| + r := httptest.NewRequest(http.MethodPost, "https://"+fwHost+"/", nil) |
| + r.Body, r.ContentLength, r.TransferEncoding = io.NopCloser(src), tc.n, tc.te |
| + c, err := copyWholeBody(r) |
| + if (err != nil) != tc.wantErr || (c != nil) != tc.want { |
| + t.Fatalf("copy %v err %v", c != nil, err) |
| + } |
| + if !tc.want && !tc.wantErr && src.n != 0 { |
| + t.Fatalf("read %d bytes of a body that is not replayable", src.n) |
| + } |
| + if c != nil { |
| + out := c.request(r, true) |
| + b, _ := io.ReadAll(out.Body) |
| + if int64(len(b)) != tc.n || out.Header.Get(ReplayableHeader) != "1" || r.Header.Get(ReplayableHeader) != "" { |
| + t.Fatalf("copy %d bytes, marks %q/%q", len(b), out.Header.Get(ReplayableHeader), r.Header.Get(ReplayableHeader)) |
| + } |
| + if second := c.request(r, false); second.Header.Get(ReplayableHeader) != "" { |
| + t.Fatal("the second attempt is marked") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type countingReader struct { |
| + r io.Reader |
| + n int |
| +} |
| + |
| +func (c *countingReader) Read(p []byte) (int, error) { |
| + n, err := c.r.Read(p) |
| + c.n += n |
| + return n, err |
| +} |
| + |
| +// Cross-region name authority: a holder in the destination's region view |
| +// that claims the name for another owner is not followed. |
| +func TestReplayCrossRegionNameAuthority(t *testing.T) { |
| + s, _ := newRpBackhaul(t) |
| + m := s.sender.edge.homes.Load() |
| + owner, ok := m.Owner(HAForwardHost) |
| + if !ok { |
| + t.Fatal("no owner") |
| + } |
| + o := backhaulOwnerOf(owner) |
| + if _, ok := m.handoverAlternative(HAForwardHost, "betty", "annie", o, time.Now()); !ok { |
| + t.Fatal("betty serves the owner's name in annie's region: refused, want allowed") |
| + } |
| + other := o |
| + other.app = "other" |
| + if _, ok := m.handoverAlternative(HAForwardHost, "betty", "annie", other, time.Now()); ok { |
| + t.Fatal("another owner: allowed, want refused") |
| + } |
| + for _, ref := range []string{"dennis", "zed", ""} { |
| + if _, ok := m.handoverAlternative(HAForwardHost, ref, "annie", o, time.Now()); ok { |
| + t.Fatalf("ref %q: allowed, want refused", ref) |
| + } |
| + } |
| + s.HolderFile(t, "hosts", map[string]any{"elsewhere.test": map[string]any{"role": "home", "account": "abc", "app": "shop"}}) |
| + if _, ok := m.handoverAlternative(HAForwardHost, "betty", "annie", o, time.Now()); ok { |
| + t.Fatal("betty no longer claims the name: allowed, want refused") |
| + } |
| + status, h, got := s.send(t, rpBody(t, 10), false) |
| + if status != 503 || h.Get("Retry-After") != "10" || h.Get(HandoverHeader) != "" { |
| + t.Fatalf("%d %v %q, want today's answer", status, h, got) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 0 { |
| + t.Fatalf("calls=%d/%d, want no follow", a, b) |
| + } |
| +} |
| + |
| +// A handover answer to a first attempt that was not marked (the body was |
| +// not copied whole) is never followed, however the draining box answers: |
| +// there is nothing to send again. |
| +func TestReplayUnmarkedFirstAttemptNeverFollowed(t *testing.T) { |
| + t.Run("in region", func(t *testing.T) { |
| + x := newRpScene(t) |
| + x.drain.set("all", "dora") |
| + resp, body := x.post(t, http.MethodPost, fwHost, "/echo-body", rpBody(t, 10), true) |
| + wantToday(t, resp, body) |
| + if b, d := x.counts(t); b != 1 || d != 0 { |
| + t.Fatalf("betty saw %d, dora %d", b, d) |
| + } |
| + }) |
| + t.Run("cross region", func(t *testing.T) { |
| + s, mv := newRpBackhaul(t) |
| + mv.set("all", "betty") |
| + status, h, got := s.send(t, rpBody(t, 10), true) |
| + if status != 503 || h.Get("Retry-After") != "10" || h.Get(HandoverHeader) != "" { |
| + t.Fatalf("%d %v %q, want today's answer", status, h, got) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 0 { |
| + t.Fatalf("calls=%d/%d, want one attempt", a, b) |
| + } |
| + }) |
| +} |
| + |
| +// In region, end to end: a ref in view that fails name authority gets |
| +// today's answer. |
| +func TestReplayRefFailsNameAuthorityEndToEnd(t *testing.T) { |
| + x := newRpScene(t) |
| + putJSON(t, x.seed, "control/edges/dora.json", fmt.Sprintf( |
| + `{"v":1,"box":"dora","eip":%q,"region":"ie","placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{%q:{"role":"home","account":"abc","app":"other"}}}`, |
| + rpDoraEIP, time.Now().UTC().Format(time.RFC3339), fwHost)) |
| + refreshHomeMap(t, x.a.homes) |
| + resp, body := x.post(t, http.MethodPost, fwHost, "/echo-body", rpBody(t, 10), false) |
| + wantToday(t, resp, body) |
| + if b, d := x.counts(t); b != 1 || d != 0 { |
| + t.Fatalf("betty saw %d, dora %d", b, d) |
| + } |
| +} |
| + |
| +// The largest replayable body, again and again: the draining box reads it |
| +// before its handover answer (drainReplayable), so the answer is never |
| +// lost to the reset of a connection closed with the body unread. |
| +func TestReplayLargestBodyIsReliable(t *testing.T) { |
| + x := newRpScene(t) |
| + for i := range 20 { |
| + body := rpBody(t, 64<<10) |
| + resp, got := x.post(t, http.MethodPost, fwHost, "/echo-body", body, false) |
| + if resp.StatusCode != 200 || got != rpEcho("dora", body) { |
| + t.Fatalf("round %d: %d %q, want dora's echo", i, resp.StatusCode, got) |
| + } |
| + } |
| +} |