region HA: answer handovers first, linger after; HA-only backhaul copies
Task 3 fix round 1 (Astra r1: three P2s, one P3; controller's ruling). - handover.go: the handover exit no longer reads a body before it answers (drainReplayable is gone). After the answer it lingers: the read deadline goes 1 s ahead, so net/http writes the final framing, discards what the sender is still writing, half-closes when more is left, then closes. The sender gets the handover answer or today's 503 with Retry-After: 10 instead of a reset. - The first box asks its client connection to close after a relayed answer the upstream closes after, while the client's streamed body is unfinished (closeAfterEarlyAnswer), so that body is neither reused nor discarded under the transport still sending it. - backhaul: the whole copy is made only for an HA route by the box's HA ingress projection (backhaulHA); every other backhaul streams as it did. Test: a non-HA body's first bytes reach the app before the client finishes. - A handover naming this box clears the already-met Expect header, so local service sends one 100 Continue. - Tests: no 502 allowances left; 1 MiB bodies, a stalled small marked hop answered before the linger, Expect on local service.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/backhaul_holder.go+27 −6internal/edge/edge.go+1 −1internal/edge/forwardha.go+12 −0internal/edge/handover.go+17 −26internal/edge/handover_test.go+9 −0internal/edge/replay.go+45 −0internal/edge/replay_test.go+109 −18
Intent
<task-notification> <task-id>aef76dee7dd89daec</task-id> <tool-use-id>toolu_017GkUbmtZvBUhBjfBqw1FXq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/aef76dee7dd89daec.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: replay + attempts" 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_WITH_CONCERNS Commits: `fa508370` (code and tests), `bf69eeb0` (census). Base `2c138f20`; nothing pushed. Tests: RED was shown first; every new `TestReplay*` test passes and all 19 mutations fail at least one test. The neighbouring edge tests, the targeted activator tests, the census test, gofmt, vet and the darwin/windows builds all pass. Concerns: 1. **Task 2 code changed.** I added `drainReplayable` to Task 2's `moveGate`. Without it, the draining box closes without reading a 64 KiB body, the forwarder gets a connection reset, and the handover answer is lost (3 of 20 runs on loopback). The read is best effort: at most 64 KiB, capped at 1 s, and it never changes the answer. It is a short wait inside an R3.3 exit, so it needs a ruling. 2. **502 instead of 503.** When Task 2 refuses an over-64 KiB non-replayable hop at once, the client can see a 502 instead of the 503 with `Retry-After: 10`. Nothing is replayed either way; the tests accept either status for that case only. 3. **Mixed builds.** During a roll, an older holder passes `X-Carlos-Replayable` through to its app. 4. **Untested paths.** A ref naming this box on the metadata-ingress path, or on the draining box's own release, is not tested end to end. Both give the answer those paths already give. 5. **Census.** The census was re-proposed (seal `054a05cf...`) and the census test passes. The cross-family verdict on #280 is still owed. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-3-report.md</result> <usage><subagent_tokens>302127</subagent_tokens><tool_uses>88</tool_uses><duration_ms>3026648</duration_ms></usage> </task-notification>
<task-notification> <task-id>aef76dee7dd89daec</task-id> <tool-use-id>toolu_01MVUUvkhk44mnfuGuwNGHSH</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/aef76dee7dd89daec.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: replay + attempts" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>The high-count runs are still going; I'll wait for them to finish.</result> <usage><subagent_tokens>383451</subagent_tokens><tool_uses>46</tool_uses><duration_ms>2274638</duration_ms></usage> </task-notification>
diff --git a/internal/edge/backhaul_holder.go b/internal/edge/backhaul_holder.go| index 1600788f5..7eff89103 100644 |
| --- a/internal/edge/backhaul_holder.go |
| +++ b/internal/edge/backhaul_holder.go |
| @@ -144,6 +144,18 @@ func (e *Edge) backhaulTarget(host, dial, box string, owner backhaulOwner) (stri |
| var errBackhaulHolder = errors.New("backhaul holder follow") |
| +// backhaulHA reports whether a backhauled request for host is for a |
| +// born-HA route by trusted routing metadata: this box's HA ingress |
| +// projection (built from platform records, memory-only) names an HA route |
| +// of the checked owner for it. Only such a request has its body copied |
| +// whole (§25.5 "Cross-region first boxes"); every other backhaul streams |
| +// as before. A var only so a test can stand in for metadata it cannot |
| +// arrange through the front door. |
| +var backhaulHA = func(e *Edge, host string, owner backhaulOwner) bool { |
| + rt, known := e.ingressRoute(host) |
| + return known && rt.HA && rt.Host != "" && rt.Account == owner.account && rt.App == owner.app |
| +} |
| + |
| // backhaulHolderTransport consumes a followed refusal before the proxy can |
| // copy its status, headers or body. The normal proxy still owns every other |
| // response, including upgrades and the second attempt's refusal. |
| @@ -167,9 +179,10 @@ func (t backhaulHolderTransport) RoundTrip(r *http.Request) (*http.Response, err |
| // 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) { |
| +// On the first, for an HA host only (ha, backhaulHA), it copies the body |
| +// whole when it can (copyWholeBody) and marks the hop replayable; whole is |
| +// that copy on the second. Any other request streams as it always has. |
| +func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, owner backhaulOwner, ha bool, whole *wholeBody) { |
| n, ok := nextForwardAttempt(r) |
| if !ok { |
| // I4: never a third attempt. |
| @@ -178,7 +191,7 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia |
| return |
| } |
| retry := n < maxForwardAttempts |
| - if n == 1 && whole == nil { |
| + if ha && 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)) |
| @@ -284,7 +297,15 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia |
| e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s (%s): %v", host, box, dial, err)) |
| w.WriteHeader(http.StatusBadGateway) |
| } |
| - e.hopTo(w, r, host, dial, box, key, "backhaul", tr, onError, nil) |
| + var onResponse func(*http.Response) |
| + if ha { |
| + if whole == nil { |
| + var streamed *streamedBody |
| + r, streamed = watchBody(r) |
| + onResponse = func(resp *http.Response) { closeAfterEarlyAnswer(w, r, streamed, resp) } |
| + } |
| + } |
| + e.hopTo(w, r, host, dial, box, key, "backhaul", tr, onError, onResponse) |
| // The refused hop releases its capacity slot before the holder starts a |
| // response that may stream or remain upgraded indefinitely. |
| if nextRef != "" { |
| @@ -294,6 +315,6 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia |
| // 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) |
| + e.backhaulAttempt(w, original, host, nextDial, nextRef, key, owner, ha, whole) |
| } |
| } |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 64946d7ed..92eff000c 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, withForwardAttempts(r), host, eip, box, key, owner, nil) |
| + e.backhaulAttempt(w, withForwardAttempts(r), host, eip, box, key, owner, backhaulHA(e, host, owner), nil) |
| return true |
| } |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| index 3ba7ee801..4b84a7473 100644 |
| --- a/internal/edge/forwardha.go |
| +++ b/internal/edge/forwardha.go |
| @@ -396,7 +396,12 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st |
| if whole != nil { |
| at.whole = whole |
| if at.orig != nil { |
| + // For local service, should a handover name this box: |
| + // the body is the copy again, and its Expect is already |
| + // met (net/http sent the 100 Continue when the copy was |
| + // read), so no second interim answer reaches the client. |
| at.orig.Body = whole.reader() |
| + at.orig.Header.Del("Expect") |
| } |
| } |
| } |
| @@ -437,6 +442,12 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st |
| e.logThrottled("forward-error "+ref, fmt.Sprintf("forward %s → %s (%s): %v", host, ref, dial, err)) |
| w.WriteHeader(http.StatusBadGateway) |
| } |
| + // A body that is not copied streams as today, watched for its end |
| + // (closeAfterEarlyAnswer). |
| + var streamed *streamedBody |
| + if at == nil || at.whole == nil { |
| + r, streamed = watchBody(r) |
| + } |
| onResponse := func(resp *http.Response) { |
| // ModifyResponse sees final headers, including 101; 100/103 bypass it. |
| stopObservation() |
| @@ -445,6 +456,7 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st |
| if d.Kind == Holder && note != nil { |
| note(res) |
| } |
| + closeAfterEarlyAnswer(w, r, streamed, resp) |
| } |
| tr := backhaulHolderTransport{RoundTripper: e.forwardTransport(dial), response: func(resp *http.Response) error { |
| v := resp.Header.Get(HandoverHeader) |
diff --git a/internal/edge/handover.go b/internal/edge/handover.go| index 03e44f3bd..9502ff6bd 100644 |
| --- a/internal/edge/handover.go |
| +++ b/internal/edge/handover.go |
| @@ -25,7 +25,6 @@ import ( |
| "bufio" |
| "context" |
| "fmt" |
| - "io" |
| "net" |
| "net/http" |
| "strconv" |
| @@ -234,7 +233,6 @@ 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) |
| @@ -266,26 +264,9 @@ 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)) |
| -} |
| +// exitLingerBound is how long a handover exit's connection lingers after |
| +// the answer, reading what the sender is still writing (handoverExit). |
| +const exitLingerBound = time.Second |
| // 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 |
| @@ -293,9 +274,19 @@ func drainReplayable(w http.ResponseWriter, r *http.Request) { |
| // answer writes anything, so net/http never drains an unread body before |
| // the answer and a streaming upload can still be read while it is |
| // relayed; asks for the connection to close after it (HTTP/1); then |
| -// flushes and puts the read deadline in the past, so net/http's drain of |
| -// the unread body after the handler fails at once instead of waiting on a |
| -// slow client. No exit waits for a body. |
| +// flushes. The answer is on the wire before anything waits for a body. |
| +// |
| +// The connection then lingers, after the answer and never before it: the |
| +// read deadline is put exitLingerBound ahead, and the handler returns. |
| +// net/http then writes the response's final framing and flushes it, reads |
| +// and discards what is left of the unread body (up to its own post-handler |
| +// limit) until the body ends or the deadline passes, half-closes and waits |
| +// when more is left than that limit, and only then closes. A sender still |
| +// writing its body therefore reads the whole answer, the handover answer or |
| +// today's 503 with Retry-After, instead of meeting the reset of a |
| +// connection closed with its bytes unread (a lost answer, seen on loopback |
| +// at 64 KiB). The linger is bounded in time and holds no handler: a slow |
| +// or stalled body only delays the close. |
| // |
| // The one exception is decided by what happened, never by what the |
| // request claimed: a connection that answer actually hijacked (the proxy's |
| @@ -316,7 +307,7 @@ func handoverExit(w http.ResponseWriter, r *http.Request, answer func(http.Respo |
| return |
| } |
| _ = rc.Flush() |
| - _ = rc.SetReadDeadline(time.Now()) |
| + _ = rc.SetReadDeadline(time.Now().Add(exitLingerBound)) |
| } |
| // exitWriter is handoverExit's view of the response: it records a |
diff --git a/internal/edge/handover_test.go b/internal/edge/handover_test.go| index ead837336..61b92910b 100644 |
| --- a/internal/edge/handover_test.go |
| +++ b/internal/edge/handover_test.go |
| @@ -488,6 +488,10 @@ func TestHandoverExitOnUnfinishedBodies(t *testing.T) { |
| {name: "fixed length, stalled", framing: "Content-Length: 100000", sent: "0123456789", status: 503, retry: "10"}, |
| {name: "fixed length, small, stalled", framing: "Content-Length: 1000", sent: "0123456789", status: 503, retry: "10"}, |
| {name: "replayable hop, chunked, unfinished", framing: "Transfer-Encoding: chunked", sent: "5\r\nhello\r\n", hop: true, taken: true, status: 503, retry: "10"}, |
| + // Task 3 fix round 1: a marked, short fixed-length hop whose body |
| + // never finishes still gets its handover answer at once; the |
| + // connection only lingers after it. |
| + {name: "replayable hop, small fixed length, stalled", framing: "Content-Length: 1000", sent: "0123456789", hop: true, taken: true, status: 503, retry: "10"}, |
| {name: "taken client, hop at its cap, chunked", framing: "Transfer-Encoding: chunked", sent: "5\r\nhello\r\n", taken: true, status: 503, retry: "2", |
| setup: func(t *testing.T, _ *hoScene) { |
| old := backhaulMaxInflight.Load() |
| @@ -552,12 +556,17 @@ func TestHandoverExitOnUnfinishedBodies(t *testing.T) { |
| hdr += "Connection: Upgrade\r\nUpgrade: websocket\r\n" |
| } |
| fmt.Fprintf(conn, "POST /upload HTTP/1.1\r\nHost: %s\r\n%s\r\n%s\r\n%s", fwHost, c.framing, hdr, c.sent) |
| + sent := time.Now() |
| conn.SetReadDeadline(time.Now().Add(3 * time.Second)) |
| br := bufio.NewReader(conn) |
| resp, err := http.ReadResponse(br, nil) |
| if err != nil { |
| t.Fatalf("no answer while the body is unfinished: %v", err) |
| } |
| + // The answer comes first: well before the linger after it ends. |
| + if waited := time.Since(sent); waited >= exitLingerBound/2 { |
| + t.Fatalf("headers after %v, want them before the %v linger", waited, exitLingerBound) |
| + } |
| b, err := io.ReadAll(resp.Body) |
| if err != nil { |
| t.Fatalf("answer body: %v", err) |
diff --git a/internal/edge/replay.go b/internal/edge/replay.go| index fea669e95..4dee7cab0 100644 |
| --- a/internal/edge/replay.go |
| +++ b/internal/edge/replay.go |
| @@ -107,3 +107,48 @@ func (c *wholeBody) request(r *http.Request, marked bool) *http.Request { |
| out.Body = c.reader() |
| return out |
| } |
| + |
| +// streamedBody is a client's body the proxy streams upstream, watched |
| +// for its end: whether every byte of it has been read. |
| +type streamedBody struct { |
| + io.ReadCloser |
| + want int64 // Content-Length, -1 when unknown |
| + n int64 // read so far; only the reading goroutine touches it |
| + done atomic.Bool |
| +} |
| + |
| +func (b *streamedBody) Read(p []byte) (int, error) { |
| + n, err := b.ReadCloser.Read(p) |
| + b.n += int64(n) |
| + if err == io.EOF || (b.want >= 0 && b.n >= b.want) { |
| + b.done.Store(true) |
| + } |
| + return n, err |
| +} |
| + |
| +// watchBody is r with its body watched (streamedBody), when it has one. |
| +func watchBody(r *http.Request) (*http.Request, *streamedBody) { |
| + if r.Body == nil || r.Body == http.NoBody || r.ContentLength == 0 { |
| + return r, nil |
| + } |
| + b := &streamedBody{ReadCloser: r.Body, want: r.ContentLength} |
| + out := r.WithContext(r.Context()) |
| + out.Body = b |
| + return out, b |
| +} |
| + |
| +// closeAfterEarlyAnswer asks this box's connection with the client to |
| +// close after the relayed answer when the upstream closes its own after |
| +// it and the client's streamed body has not all been sent on: an upstream |
| +// such as a draining box (R3.3) can answer before it has read the body. |
| +// Closing tells the client not to reuse a connection it may still be |
| +// writing on, and keeps net/http from discarding the rest of the body |
| +// under the transport still sending it upstream (which cut the relayed |
| +// answer short). A body that did all go upstream leaves the connection |
| +// as it is. |
| +func closeAfterEarlyAnswer(w http.ResponseWriter, r *http.Request, body *streamedBody, resp *http.Response) { |
| + if body == nil || body.done.Load() || !resp.Close || r.ProtoMajor != 1 || resp.StatusCode == http.StatusSwitchingProtocols { |
| + return |
| + } |
| + w.Header().Set("Connection", "close") |
| +} |
diff --git a/internal/edge/replay_test.go b/internal/edge/replay_test.go| index 894cfc89f..de2c46549 100644 |
| --- a/internal/edge/replay_test.go |
| +++ b/internal/edge/replay_test.go |
| @@ -253,20 +253,6 @@ func rpEcho(box string, body []byte) string { |
| // 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) |
| } |
| @@ -349,12 +335,14 @@ func TestReplayNotWholeGetsTodaysAnswer(t *testing.T) { |
| chunked bool |
| }{ |
| {"64 KiB + 1", 64<<10 + 1, false}, |
| + {"1 MiB", 1 << 20, false}, |
| {"10 bytes chunked", 10, true}, |
| + {"1 MiB chunked", 1 << 20, 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) |
| + wantToday(t, resp, body) |
| 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) |
| @@ -571,6 +559,11 @@ func newRpBackhaul(t *testing.T) (*BackhaulHolderScene, *rpMover) { |
| 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) |
| + // The HA ingress projection is region-scoped, so the sender (us) has |
| + // no record of this eu host; stand in for trusted HA metadata here. |
| + old := backhaulHA |
| + backhaulHA = func(_ *Edge, host string, o backhaulOwner) bool { return host == HAForwardHost && o.app == "shop" } |
| + t.Cleanup(func() { backhaulHA = old }) |
| if err := s.first.reg.SetHA(HAForwardHost); err != nil { |
| t.Fatal(err) |
| } |
| @@ -628,6 +621,7 @@ func TestReplayCrossRegionThroughBackhaul(t *testing.T) { |
| ref string |
| }{ |
| {"64 KiB + 1", 64<<10 + 1, false, "betty"}, |
| + {"1 MiB", 1 << 20, false, "betty"}, |
| {"10 bytes chunked", 10, true, "betty"}, |
| {"ref not in view", 10, false, "zed"}, |
| {"ref naming the first box", 10, false, "dennis"}, |
| @@ -636,9 +630,7 @@ func TestReplayCrossRegionThroughBackhaul(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) != "") { |
| + 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 { |
| @@ -864,3 +856,102 @@ func TestReplayLargestBodyIsReliable(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// P3: Expect: 100-continue on local service. A handover naming this box |
| +// serves the copy here, and the client sees exactly one 100 Continue |
| +// before the final answer. |
| +func TestReplayExpectContinueServedLocally(t *testing.T) { |
| + x := newRpScene(t) |
| + x.drain.set("handover", "annie") |
| + 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("annie", body) { |
| + t.Fatalf("%d %q, want annie's own echo after one 100 Continue", resp.StatusCode, got) |
| + } |
| + if b, d := x.counts(t); b != 1 || d != 0 { |
| + t.Fatalf("betty saw %d, dora %d", b, d) |
| + } |
| +} |
| + |
| +// A backhauled request for a host that is not HA keeps streaming its body |
| +// to the app: the app reads the first bytes before the client has sent the |
| +// rest, known length and small as the body is. |
| +func TestBackhaulNonHAStillStreams(t *testing.T) { |
| + const host = "stream.backhaul.test" |
| + first := make(chan string, 1) |
| + app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + buf := make([]byte, 5) |
| + if _, err := io.ReadFull(r.Body, buf); err != nil { |
| + http.Error(w, err.Error(), 400) |
| + return |
| + } |
| + first <- string(buf) |
| + rest, _ := io.ReadAll(r.Body) |
| + fmt.Fprintf(w, "%s%s", buf, rest) |
| + })) |
| + t.Cleanup(app.Close) |
| + s := newBackhaulSceneWith(t, backhaulSceneExtra{ |
| + homeRoutes: []registry.Route{{Host: host, Kind: "service", Addr: app.Listener.Addr().String(), Status: "ready"}}, |
| + certs: []string{host}, |
| + homeEntries: map[string]string{host: `{"role":"home"}`}, |
| + }) |
| + s.converge(t) |
| + pr, pw := io.Pipe() |
| + req, err := http.NewRequest(http.MethodPost, "https://"+host+"/up", pr) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.ContentLength = 10 |
| + type result struct { |
| + status int |
| + body string |
| + err error |
| + } |
| + done := make(chan result, 1) |
| + go func() { |
| + resp, err := s.b.client.Do(req) |
| + if err != nil { |
| + done <- result{err: err} |
| + return |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + done <- result{resp.StatusCode, string(b), nil} |
| + }() |
| + pw.Write([]byte("hello")) |
| + select { |
| + case got := <-first: |
| + if got != "hello" { |
| + t.Fatalf("first bytes %q", got) |
| + } |
| + case <-time.After(5 * time.Second): |
| + pw.Close() |
| + t.Fatal("the app saw nothing before the client finished: the backhaul buffered a non-HA body") |
| + } |
| + pw.Write([]byte("world")) |
| + pw.Close() |
| + r := <-done |
| + if r.err != nil || r.status != 200 || r.body != "helloworld" { |
| + t.Fatalf("%d %q %v", r.status, r.body, r.err) |
| + } |
| +} |