handover: cut a moving host's streams; drop the graceful SSE end
Astra round 2 on held-move-speed, F2.1 (P1, same family as round 1's F1.1: response-body close versus trailer scrubbing). The move watcher's close of an SSE body could run the trailer scrubs before an outstanding transport Read had parsed the trailers (http.Transport's bodyEOFSignal early-close path), so platform trailers and an unscoped cookie could reach the client. Agent manager 8a3d302 ruled option (b): cut graceful boundary ending entirely. - eventBoundaryBody, its watcher, the shared close and the boundary detection are gone. responseModifier (cookiescope.go) is byte for byte what it is on main; nothing new touches the trailer wrappers. - The tenant proxies' ModifyResponse is classifyMoveStreams( responseModifier): it reads the response head first (101, or text/event-stream of any encoding), sets a flag on the request's StreamEnd, and never wraps the body. - At the move's start every long-lived stream of the host is cut by cancelling its request context, as the connection drain does at its bound: SSE of any encoding and upgraded connections; CloseHeldHost stays for edge-held streams. A stream classified mid-move is cut at once. Ordinary requests keep the 10 s bound. - Spec §25.8: streams are cut at the move's start and clients reconnect, today's connection-drain behaviour; §25.4 step 2 and §25.15 match. Tests: Astra's real-transport guard kept as TestMoveCutKeepsTheTrailerScrubs (real responseModifier, http.Transport, httputil.ReverseProxy; chunked SSE with announced and unannounced platform trailers and a wide-domain Set-Cookie trailer, cut by a move; 30 rounds, -race). With the scrubs removed it lets X-Carlos-Holder through, so it is not vacuous. TestClassifyMoveStreamsMarksStreamsOnly fails if the hook wraps a body. The activator SSE, gzip SSE, WebSocket, mid-move and ordinary-request tests now expect a cut; boundary-reader tests are deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+3 −3internal/activator/movestreams.go+15 −15internal/activator/movestreams_test.go+25 −50internal/edge/cookiescope.go+1 −4internal/edge/edge.go+6 −6internal/edge/movestreams.go+40 −243internal/edge/movestreams_test.go+113 −237internal/host/hadrain.go+6 −5
Intent
<task-notification> <task-id>b2m1j0582</task-id> <tool-use-id>toolu_0141Uub3xTVaoqFu4RvZBsof</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/b2m1j0582.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on the new tip" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bpli1z8ei</task-id> <tool-use-id>toolu_0112Y1KpR78yrwFBCMNzdcth</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/bpli1z8ei.output</output-file> <status>completed</status> <summary>Background command "Astra review round 2 (background)" completed (exit code 0)</summary> </task-notification>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="37eb5912-74fe-4d94-b220-5ed2781a44e0"> Agent manager 8a3d302: (b). Same family twice means cut it, and (b) removes the trailer-scrub race instead of guarding it. At the move start, end every long-lived stream by cancelling its request context, with no watcher and no body wrapper. Keep F2 as is. Update the §25.8 sentence: streams are cut at the move start and clients reconnect, which is today's drain behaviour. Keep Astra's real-transport trailer guard as a TEST, proving no platform trailer reaches the client on a cut. R3 is the last round: if it's clean (no P1) and CI is green, merge under the standing approval; if not, stop and tell me. </paseo-system>
<task-notification> <task-id>by3coxdrl</task-id> <tool-use-id>toolu_01YWrCG4KF7LSNRK7TycBXmB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/by3coxdrl.output</output-file> <status>completed</status> <summary>Background command "Wait for the CI rerun" completed (exit code 0)</summary> </task-notification>
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index b9674b51a..6e5f7f5ff 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -1102,7 +1102,7 @@ The roll tool runs a new root verb, `carlos system group-maintenance drain`, ove |
| 2. **Quiesce (H5).** A closes its local start gate for tenant leases. It then settles everything that crossed the gate before it closed: wakes that are restoring, acquires waiting on their conditional PUT, and lost-lease recovery workers. Each either ends awake, and is then moved in step 3, or fails. Pending stops and marker obligations are kept and settled (§5.2). Nothing is cancelled in a way that would drop a writer proof. |
| 3. **Move each awake host H,** up to 4 at a time, busiest first: |
| 1. *Hold.* From now `MoveState(H)` is `holding` (§25.5). |
| - 2. *Finish in-flight work.* First, at the move's start, A ends H's long-lived responses on A, because none of them ends on its own: unencoded SSE responses (`text/event-stream`) end at their next event boundary, encoded SSE responses and upgraded connections (WebSockets) are closed, and edge-held SSE streams are closed at an event boundary. A stream that opens later in the move, on a request admitted before it, is ended as soon as its response head shows it is a stream. Their clients reconnect and are held like any other request (§25.8). Every other request already admitted to H's app gets up to 10 s, today's HTTP drain bound. Then the stop proceeds as a shutdown stop does, which ends long requests and edge-held stream legs (#432 G5). (Build change, 2026-11-10: the streams used to be closed at step 5, so one open stream held every move for the whole 10 s.) |
| + 2. *Finish in-flight work.* First, at the move's start, A cuts H's long-lived responses on A, because none of them ends on its own: SSE responses (`text/event-stream`, any encoding) and upgraded connections (WebSockets) have their request cancelled and their connection closed, as at today's connection drain, and edge-held SSE streams are closed. A stream that opens later in the move, on a request admitted before it, is cut as soon as its response head shows it is a stream. Their clients reconnect and are held like any other request (§25.8). Every other request already admitted to H's app gets up to 10 s, today's HTTP drain bound. Then the stop proceeds as a shutdown stop does, which ends long requests and edge-held stream legs (#432 G5). (Build change, 2026-11-10: the streams used to be closed at step 5, so one open stream held every move for the whole 10 s.) |
| 3. *Release.* `finishStop` writes the marker (§5.2), with the drain as its stop reason and the existing budgets. The drain's release, and only the drain's, writes a litestream snapshot (level 9) at the final position after the final sync succeeds and before the store closes, so the snapshot's TXID is the marker's and the successor restores one file instead of every L0 file since the last compaction. If the snapshot fails, A logs it and the release goes on as before: the marker is as clean as it would have been, and the restore replays the L0 files. An idle sleep writes no snapshot. (Build change, 2026-11-10.) |
| 4. *Take.* A chooses a successor B: `ChooseRoomiest` over its eligible serving set (§6.3). **Always-on workers are not taken** (build ruling, 2026-11-09): the duty rule (§7.1, A11) gives a released worker's duties to its releaser, and a take that moved them would need new authority in the duty layer, the I3 family. A drain releases each worker with a marker, which leaves no lease naming A (H5), and the worker resumes on its HRW box (A10) through the departure scan's import (§7.4) after the provider action. The report lists such workers as released. A sends B a signed take request (§25.7). B acquires and wakes H, then answers with the owner it now sees in `lock.json`. That owner is the **confirmed holder**: B, or a third box that won the marker first (§6.7). |
| 5. *Release the holds* (§25.5). H's edge-held SSE streams on A were closed at step 2. Any opened on A during the move are closed now, per host, at an event boundary, so they reconnect to the new holder without waiting for the rest of the drain (R3.5). `MoveState(H)` becomes `taken(holder, lock generation)` and stays so until `drained` is acknowledged (§25.15 R3.4). |
| @@ -1189,7 +1189,7 @@ Both control paths, `/.carlos/ha-take` and `/.carlos/ha-drain`, are reserved on |
| - a call through the edge-local door (#175 P7), a tunnel delivery, or a request on a regional name for the moving host. None of these can be forwarded to another box, so A refuses them at once through the bounded exit (§25.15 R3.3) rather than holding them (build ruling, 2026-11-08); |
| - a request that arrives at A after its connection drain has begun (§25.4 step 4); |
| - any bound hit or failed move. |
| -- **Connections:** keep-alive connections are closed between requests. Any backhaul that carries a body closes the client's connection when the upstream answers before the client has finished sending, so the edge never drains an unbounded upload after an early answer; the client reconnects once and sees no error (build ruling, 2026-11-08). SSE streams and upgraded connections (WebSockets) for H are ended at the move's start, not at the take. Unencoded SSE ends at an event boundary; encoded streams and upgraded connections are closed and reconnect. Either way the browser reconnects with `Last-Event-ID` after its retry delay. The reconnect is held like any other request and forwarded once H is taken. WebSockets of hosts that were not moved and are still open through A 60 s after its leases have moved are closed, and their clients reconnect. Requests already dispatched to an app (uploads, downloads, upgrades) that run past H's 10 s drain, or past the final 60 s, are cut and never retried, because they may have reached the app (R3.5). |
| +- **Connections:** keep-alive connections are closed between requests. Any backhaul that carries a body closes the client's connection when the upstream answers before the client has finished sending, so the edge never drains an unbounded upload after an early answer; the client reconnects once and sees no error (build ruling, 2026-11-08). Streams for H (SSE and upgraded connections) are cut at the move's start and their clients reconnect, which is today's connection-drain behaviour. The reconnect is held like any other request and forwarded once H is taken. WebSockets of hosts that were not moved and are still open through A 60 s after its leases have moved are closed, and their clients reconnect. Requests already dispatched to an app (uploads, downloads, upgrades) that run past H's 10 s drain, or past the final 60 s, are cut and never retried, because they may have reached the app (R3.5). |
| - **Always-on workers** pause from their release until the departure finishes, a few minutes. They serve no HTTP requests. |
| - **An unplanned death:** today's behaviour, unchanged. |
| @@ -1330,7 +1330,7 @@ Paul approved all four §25.14 recommendations and Q1 to Q3 as recommended: drai |
| **The redirect lasts the whole drain (R3.4).** `taken(holder, gen)` is kept per host lifetime until `drained` is acknowledged, not for 30 s. Before A answers a hop from it, A checks the lock with one coalesced read, at most one per host per 5 s. The answer names the current owner, or, when the lock is a release marker, A's placement choice, which a hop receiver may acquire from the marker (§6.4). Anything else gets the bounded refusal. Budget: at most one lock GET per moved host per 5 s on the draining box, only while stale hops arrive. |
| -**Move speed (build change, 2026-11-10).** W4 on dev measured moves of 25 to 42 s: about 10 s waiting for the probe's SSE stream, which never ends, to reach the in-flight bound, and 27 to 29 s of restore replaying over 1,000 L0 files. Two changes, approved by the agent manager: streams are ended at the move's start rather than at the take (§25.4 step 2, §25.8), which R3.5 already allows since the reconnect is at an event boundary; and the drain's release writes a snapshot at the final position (§25.4 step 3.3, +1 PUT per moved host in §25.10). Holds' bounds, I1 and H1 to H5 are unchanged. A snapshot at every clean sleep, which would make every cross-box wake fast too, is a separate proposal for Paul. |
| +**Move speed (build change, 2026-11-10).** W4 on dev measured moves of 25 to 42 s: about 10 s waiting for the probe's SSE stream, which never ends, to reach the in-flight bound, and 27 to 29 s of restore replaying over 1,000 L0 files. Two changes, approved by the agent manager: streams are cut at the move's start rather than at the take (§25.4 step 2, §25.8), as the connection drain cuts them today (a graceful end at an event boundary was tried and dropped after Astra round 2: it could run the trailer scrubs before the transport had read the trailers); and the drain's release writes a snapshot at the final position (§25.4 step 3.3, +1 PUT per moved host in §25.10). Holds' bounds, I1 and H1 to H5 are unchanged. A snapshot at every clean sleep, which would make every cross-box wake fast too, is a separate proposal for Paul. |
| **What the build left owed (2026-11-09).** These are outside the branch and need their own steps: |
| - **The operator policy.** The module code carries the new resource-scoped grants (terminate in this group only, launch-template version reads, and S3 list and get on `control/edges/` and the region's lock keys). Applying them with tofu is a step on a card Paul approves. |
diff --git a/internal/activator/movestreams.go b/internal/activator/movestreams.go| index 7eb7a20fb..dca7d6d11 100644 |
| --- a/internal/activator/movestreams.go |
| +++ b/internal/activator/movestreams.go |
| @@ -1,15 +1,15 @@ |
| package activator |
| -// A move ends its host's long-lived responses at its start (region HA |
| -// spec §25.4 step 3.1, §25.8, R3.5). The drain waits up to its in-flight |
| -// bound (10 s) for the host's requests here before it releases the host; |
| -// an SSE stream or an upgraded connection (a WebSocket) never ends on its |
| -// own, so one open stream held every move to the whole bound. Now each |
| -// request served for a host carries an edge.StreamEnd, and EndMoveStreams |
| -// ends those whose response is a stream: SSE at its next event boundary, |
| -// an upgraded connection by closing it. Their clients reconnect and are |
| -// held by the move like any other request. An ordinary request is not |
| -// touched and keeps the bound. |
| +// A move cuts its host's long-lived responses at its start (region HA |
| +// spec §25.4 step 2, §25.8). The drain waits up to its in-flight bound |
| +// (10 s) for the host's requests here before it releases the host; an SSE |
| +// stream or an upgraded connection (a WebSocket) never ends on its own, |
| +// so one open stream held every move to the whole bound. Now each request |
| +// served for a host carries an edge.StreamEnd, and EndMoveStreams cuts |
| +// those whose response is a stream by cancelling the request's context, |
| +// as the connection drain does at its bound. Their clients reconnect and |
| +// are held by the move like any other request. An ordinary request is |
| +// not touched and keeps the bound. |
| // |
| // Memory only. The table has its own lock, so a request's track and |
| // untrack never take a.mu; a.mu may be held around reset (lock order: |
| @@ -99,11 +99,11 @@ func end(all []*edge.StreamEnd) int { |
| return n |
| } |
| -// EndMoveStreams ends host's long-lived responses on this box at the |
| -// move's start (§25.4 step 3.1): SSE streams at their next event boundary |
| -// and upgraded connections at once, and any that open later during the |
| -// move. It answers how many were ended now, and 0 when host is not moving |
| -// here (BeginMove first). |
| +// EndMoveStreams cuts host's long-lived responses on this box at the |
| +// move's start (§25.4 step 2): SSE streams of any encoding and upgraded |
| +// connections, now, and any that open later during the move. It answers |
| +// how many were cut now, and 0 when host is not moving here (BeginMove |
| +// first). |
| func (a *Service) EndMoveStreams(host string) int { |
| a.mu.Lock() |
| if a.moves.hosts[host] == nil { |
diff --git a/internal/activator/movestreams_test.go b/internal/activator/movestreams_test.go| index 8d8a969e6..2d52fcf96 100644 |
| --- a/internal/activator/movestreams_test.go |
| +++ b/internal/activator/movestreams_test.go |
| @@ -19,9 +19,10 @@ import ( |
| "github.com/carlosframework/platform/internal/edge" |
| ) |
| -// A move ends its host's long-lived responses at its start (region HA |
| -// §25.4 step 3.1, §25.8): an SSE stream or an upgraded connection open |
| -// when the move begins no longer holds the in-flight wait to its bound. |
| +// A move cuts its host's long-lived responses at its start (region HA |
| +// §25.4 step 2, §25.8): an SSE stream (of any encoding) or an upgraded |
| +// connection open when the move begins no longer holds the in-flight wait |
| +// to its bound. |
| // An ordinary request still does. The scene is haServiceEntry, served |
| // through a.ServeHTTP behind a reverse proxy with the edge's move hook, |
| // as the edge's tenant proxies have it (responseModifier). |
| @@ -99,28 +100,15 @@ func moveStreamUpstream(t *testing.T, release <-chan struct{}) *url.URL { |
| // proxy to up whose response hook is the edge's. |
| func moveStreamFront(t *testing.T, s *haSvc, up *url.URL) string { |
| t.Helper() |
| - front, _ := moveStreamFrontBodies(t, s, up) |
| - return front |
| -} |
| - |
| -// moveStreamFrontBodies is moveStreamFront that also reports, per |
| -// response, the type of the body the hook left for the proxy to copy. |
| -func moveStreamFrontBodies(t *testing.T, s *haSvc, up *url.URL) (string, <-chan string) { |
| - t.Helper() |
| - bodies := make(chan string, 16) |
| proxy := &httputil.ReverseProxy{ |
| - Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(up) }, |
| - ModifyResponse: func(resp *http.Response) error { |
| - edge.MarkMoveStream(resp) |
| - bodies <- fmt.Sprintf("%T", resp.Body) |
| - return nil |
| - }, |
| + Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(up) }, |
| + ModifyResponse: func(resp *http.Response) error { edge.MarkMoveStream(resp); return nil }, |
| } |
| front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| s.a.ServeHTTP(w, r, s.rt, proxy) |
| })) |
| t.Cleanup(front.Close) |
| - return front.URL, bodies |
| + return front.URL |
| } |
| func (s *haSvc) inflight() int { |
| @@ -180,21 +168,15 @@ func TestMoveEndsAnSSEStreamAtItsStart(t *testing.T) { |
| if err != nil || took > time.Second { |
| t.Fatalf("the in-flight wait took %v (%v): an open SSE stream held the move", took, err) |
| } |
| - // The client sees a clean end after a whole event. |
| - rest, err := io.ReadAll(br) |
| - if err != nil { |
| - t.Fatalf("the stream did not end cleanly: %v (after %q)", err, rest) |
| - } |
| - if len(rest) > 0 && !strings.HasSuffix(string(rest), "\n\n") { |
| - t.Fatalf("the stream ended mid-event: %q", rest) |
| - } |
| + // The stream is cut: the client's read ends, and it reconnects. |
| + wantStreamEnded(t, br) |
| if n := s.inflight(); n != 0 { |
| t.Fatalf("in flight = %d after the end", n) |
| } |
| } |
| // A stream that opens after the move's start (its request admitted before |
| -// it, on a ticket) is ended as soon as its head says it is one. |
| +// it, on a ticket) is cut as soon as its head says it is one. |
| func TestMoveEndsAStreamThatOpensAfterItsStart(t *testing.T) { |
| s, _ := haServiceEntry(t, "shop.example.com") |
| front := moveStreamFront(t, s, moveStreamUpstream(t, nil)) |
| @@ -206,25 +188,27 @@ func TestMoveEndsAStreamThatOpensAfterItsStart(t *testing.T) { |
| t.Fatal(err) |
| } |
| defer resp.Body.Close() |
| - done := make(chan error, 1) |
| - go func() { _, err := io.ReadAll(resp.Body); done <- err }() |
| + wantStreamEnded(t, resp.Body) |
| +} |
| + |
| +// wantStreamEnded waits for r to end, by EOF or by an error: a cut stream |
| +// ends either way. |
| +func wantStreamEnded(t *testing.T, r io.Reader) { |
| + t.Helper() |
| + done := make(chan struct{}) |
| + go func() { io.Copy(io.Discard, r); close(done) }() |
| select { |
| - case err := <-done: |
| - if err != nil { |
| - t.Fatalf("the late stream did not end cleanly: %v", err) |
| - } |
| + case <-done: |
| case <-time.After(2 * time.Second): |
| - t.Fatal("a stream opened during the move was not ended") |
| + t.Fatal("the stream was not cut") |
| } |
| } |
| -// F1.2 (Astra r1, controller ruling): a compressed SSE stream, which the |
| -// client asked for, is never scanned for event boundaries. The move ends |
| -// it at once by closing it, as an upgraded connection, and the drain does |
| -// not wait out the bound. |
| +// A compressed SSE stream, which the client asked for, is cut the same |
| +// way, and the drain does not wait out the bound. |
| func TestMoveClosesAnEncodedSSEStream(t *testing.T) { |
| s, _ := haServiceEntry(t, "shop.example.com") |
| - front, bodies := moveStreamFrontBodies(t, s, moveStreamUpstream(t, nil)) |
| + front := moveStreamFront(t, s, moveStreamUpstream(t, nil)) |
| client := &http.Client{Transport: &http.Transport{DisableCompression: true}} |
| req, _ := http.NewRequest(http.MethodGet, front+"/gzevents", nil) |
| req.Header.Set("Accept-Encoding", "gzip") |
| @@ -236,9 +220,6 @@ func TestMoveClosesAnEncodedSSEStream(t *testing.T) { |
| if resp.Header.Get("Content-Encoding") != "gzip" { |
| t.Fatalf("Content-Encoding %q", resp.Header.Get("Content-Encoding")) |
| } |
| - if body := <-bodies; strings.Contains(body, "eventBoundaryBody") { |
| - t.Fatalf("the boundary reader was applied to a gzip stream (%s)", body) |
| - } |
| // The client decodes two events before the move. |
| zr, err := gzip.NewReader(resp.Body) |
| if err != nil { |
| @@ -258,13 +239,7 @@ func TestMoveClosesAnEncodedSSEStream(t *testing.T) { |
| if err != nil || took > time.Second { |
| t.Fatalf("the in-flight wait took %v (%v): an encoded SSE stream held the move", took, err) |
| } |
| - ended := make(chan struct{}) |
| - go func() { io.Copy(io.Discard, br); close(ended) }() |
| - select { |
| - case <-ended: // closed; the client discards a partial event and reconnects |
| - case <-time.After(2 * time.Second): |
| - t.Fatal("the encoded stream was not closed") |
| - } |
| + wantStreamEnded(t, br) |
| } |
| func TestMoveEndsAnUpgradedConnectionAtItsStart(t *testing.T) { |
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go| index d4e899c1e..2f42a1298 100644 |
| --- a/internal/edge/cookiescope.go |
| +++ b/internal/edge/cookiescope.go |
| @@ -77,8 +77,7 @@ func appsDomainFromEnv() string { |
| // (stripAssetResponseHeaders, stripAssetTrailers: the edge's own are set |
| // after this, never inherited from the app), the removal of any |
| // X-Carlos-Holder the app set, as a header or a trailer (stripAppHolder), |
| -// the cookie scoping above, and the mark of a stream a move may end |
| -// (MarkMoveStream, movestreams.go), in that order. Only the marker depends on |
| +// and the cookie scoping above, in that order. Only the marker depends on |
| // order: it is read before the scrub deletes it. |
| // |
| // X-Carlos-Holder names the box holding an HA host's lease (forwardha.go), |
| @@ -99,8 +98,6 @@ func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| stripAssetTrailers(resp) |
| stripAppHolder(resp) |
| e.scopeCookies(rt, resp) |
| - // Last, so an SSE body's move wrapper is the outermost reader. |
| - MarkMoveStream(resp) |
| return nil |
| } |
| } |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index ab9c51822..e247f30db 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -1029,7 +1029,7 @@ func (e *Edge) Reload() error { |
| // Sets select only live assigned copies, before legacy fleet fallback. |
| case ArmReplica: |
| p := replicaProxy(t.Host, served.Fleet, e.replicaProberForRouting(), e.tunnels) |
| - p.ModifyResponse = e.responseModifier(t) |
| + p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy, viaTunnel = p, true |
| ten = tenancy{Arm: ArmReplica, Account: served.Account, App: served.App, Fleet: served.Fleet} |
| replicaRoutes = append(replicaRoutes, t) |
| @@ -1047,7 +1047,7 @@ func (e *Edge) Reload() error { |
| case ArmForward: |
| box, authoritative := fleetBoxOf(t) |
| p := fleetProxy(served.Fleet, box, authoritative, e.tunnels) |
| - p.ModifyResponse = e.responseModifier(t) |
| + p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy = p |
| viaTunnel = true |
| ten = tenancy{Arm: ArmForward, Account: served.Account, App: served.App, Fleet: served.Fleet} |
| @@ -1090,7 +1090,7 @@ func (e *Edge) Reload() error { |
| // wins outright rather than silently falling back to a stale Addr. |
| case ArmTunnel: |
| p := tunnelProxy(t.Tunnel, e.tunnels) |
| - p.ModifyResponse = e.responseModifier(t) |
| + p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy = p |
| viaTunnel = true |
| ten = tenancy{Arm: ArmTunnel, Account: t.Account, App: t.App, Tunnel: t.Tunnel} |
| @@ -1120,7 +1120,7 @@ func (e *Edge) Reload() error { |
| } |
| box, authoritative := fleetBoxOf(t) |
| p := fleetProxy(served.Fleet, box, authoritative, e.tunnels) |
| - p.ModifyResponse = e.responseModifier(t) |
| + p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy = p |
| viaTunnel = true |
| ten = tenancy{Arm: ArmFleet, Account: served.Account, App: served.App, Fleet: served.Fleet} |
| @@ -1136,7 +1136,7 @@ func (e *Edge) Reload() error { |
| } else { |
| p = unixProxy(t.Socket) |
| } |
| - p.ModifyResponse = e.responseModifier(t) |
| + p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy = p |
| // TCP upstreams. The gate is AddrList (registry), not t.Addr, so a |
| // multi-upstream route — which writes the Addrs column and leaves the |
| @@ -1188,7 +1188,7 @@ func (e *Edge) Reload() error { |
| probeSpecs[t.Host] = probeSpec{Host: t.Host, Addrs: addrs, Health: h} |
| p = multiProxy(t.Host, e.probers, e.hold) |
| } |
| - p.ModifyResponse = e.responseModifier(t) |
| + p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy = p |
| case ArmStatic: |
| proxy = e.staticHandlerFor(t) |
diff --git a/internal/edge/movestreams.go b/internal/edge/movestreams.go| index 90aba92cc..f9d326589 100644 |
| --- a/internal/edge/movestreams.go |
| +++ b/internal/edge/movestreams.go |
| @@ -1,59 +1,39 @@ |
| package edge |
| -// Long-lived responses a planned move ends at its start (region HA spec |
| -// §25.4 step 3.1, §25.8, R3.5). A move waits up to its in-flight bound for |
| -// the host's requests here to finish before it releases the host; an SSE |
| +// Long-lived responses a planned move cuts at its start (region HA spec |
| +// §25.4 step 2, §25.8). A move waits up to its in-flight bound for the |
| +// host's requests here to finish before it releases the host; an SSE |
| // stream or an upgraded connection never finishes on its own, so without |
| // this every move with one open waited the whole bound. |
| // |
| -// The activator gives each request it serves for an HA host a StreamEnd |
| -// (WithStreamEnd) and keeps it per host while the request runs. The |
| -// tenant proxies' response hook (responseModifier, MarkMoveStream) marks |
| -// it when the response turns out to be a stream: a 101 (an upgraded |
| -// connection, a WebSocket) or a text/event-stream. End is a no-op for any |
| -// other request, so an ordinary request keeps the move's bound. |
| +// The activator gives each request it serves a StreamEnd (WithStreamEnd) |
| +// and keeps it per host while the request runs. The tenant proxies' |
| +// response hook (classifyMoveStreams, around responseModifier) marks it |
| +// when the response head says it is a stream: a 101 (an upgraded |
| +// connection, a WebSocket) or a text/event-stream, of any encoding. It |
| +// reads the head only and never wraps the body, so the trailer scrubs |
| +// below keep their one closer, the proxy. |
| // |
| -// Ending a stream: |
| -// - unencoded SSE: the response body ends at its next event boundary, |
| -// as io.EOF, so the proxy finishes the response normally and the |
| -// client sees a clean end after a whole event. It reconnects |
| -// (EventSource sends Last-Event-ID) and is held by the move like any |
| -// other request; |
| -// - an encoded SSE stream (any Content-Encoding but identity) and an |
| -// upgraded connection: the request's context is cancelled, which makes |
| -// the proxy close the connection, as the connection drain does at its |
| -// bound. An EventSource discards the incomplete event. The client |
| -// reconnects and is held the same way. |
| +// Ending a stream cancels its request's context: the proxy stops copying |
| +// and the connection is closed, as the connection drain does at its |
| +// bound. The client reconnects (EventSource with Last-Event-ID) and is |
| +// held by the move like any other request. End is a no-op for any other |
| +// request, so an ordinary request keeps the move's bound. |
| import ( |
| "context" |
| - "io" |
| "mime" |
| "net/http" |
| - "strings" |
| "sync" |
| ) |
| -type streamKind uint8 |
| - |
| -const ( |
| - streamNone streamKind = iota |
| - // streamSSE: an unencoded SSE body, ended at an event boundary. |
| - streamSSE |
| - // streamCut: an upgraded connection or an encoded stream, ended by |
| - // cancelling the request's context. |
| - streamCut |
| -) |
| - |
| -// StreamEnd is one proxied request a move may end early. Memory only. |
| +// StreamEnd is one proxied request a move may cut. Memory only. |
| type StreamEnd struct { |
| cancel context.CancelFunc |
| mu sync.Mutex |
| - kind streamKind |
| + stream bool |
| ending bool |
| - // stop is closed once an SSE stream is to end at its next boundary. |
| - stop chan struct{} |
| } |
| type streamEndKey struct{} |
| @@ -62,56 +42,42 @@ type streamEndKey struct{} |
| // it, and the response hook finds it there. |
| func WithStreamEnd(r *http.Request) (*http.Request, *StreamEnd) { |
| ctx, cancel := context.WithCancel(r.Context()) |
| - s := &StreamEnd{cancel: cancel, stop: make(chan struct{})} |
| + s := &StreamEnd{cancel: cancel} |
| return r.WithContext(context.WithValue(ctx, streamEndKey{}, s)), s |
| } |
| -// End ends the request if its response is a stream, now or once it turns |
| -// out to be one: a request whose response has not started yet is ended |
| -// as soon as its head says it is a stream. A request that never becomes |
| -// one is not touched. Idempotent. |
| +// End cuts the request if its response is a stream, now or as soon as |
| +// its head says it is one. A request that never becomes one is not |
| +// touched. Idempotent. |
| func (s *StreamEnd) End() { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| - if s.ending { |
| - return |
| - } |
| s.ending = true |
| - s.endLocked() |
| + if s.stream { |
| + s.cancel() |
| + } |
| } |
| // Stream reports whether the response was marked as a stream. |
| func (s *StreamEnd) Stream() bool { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| - return s.kind != streamNone |
| -} |
| - |
| -func (s *StreamEnd) endLocked() { |
| - switch s.kind { |
| - case streamSSE: |
| - close(s.stop) |
| - case streamCut: |
| - s.cancel() |
| - } |
| + return s.stream |
| } |
| -func (s *StreamEnd) mark(k streamKind) { |
| +func (s *StreamEnd) mark() { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| - if s.kind != streamNone { |
| - return |
| - } |
| - s.kind = k |
| + s.stream = true |
| if s.ending { |
| - s.endLocked() |
| + s.cancel() |
| } |
| } |
| -// MarkMoveStream is the tenant proxies' response hook for moves: it marks |
| -// the request's StreamEnd when resp is a stream, and makes an SSE body |
| -// end at an event boundary once the StreamEnd is ended. A response whose |
| -// request has no StreamEnd is left as it is. |
| +// MarkMoveStream marks the request's StreamEnd when resp's head says it |
| +// is a stream: a 101, or a text/event-stream of any encoding. It reads |
| +// resp's status and Content-Type only, and changes nothing in resp. A |
| +// response whose request has no StreamEnd is left alone. |
| func MarkMoveStream(resp *http.Response) { |
| if resp == nil || resp.Request == nil { |
| return |
| @@ -120,190 +86,21 @@ func MarkMoveStream(resp *http.Response) { |
| if s == nil { |
| return |
| } |
| - switch { |
| - case resp.StatusCode == http.StatusSwitchingProtocols: |
| - s.mark(streamCut) |
| - case !isEventStream(resp.Header.Get("Content-Type")) || resp.Body == nil || resp.Body == http.NoBody: |
| - case !identityEncoded(resp.Header): |
| - // An encoded stream (gzip, say, negotiated by the client's own |
| - // Accept-Encoding, which the proxy passes on): its bytes are not |
| - // SSE text, so no event boundary can be found in them. It is |
| - // ended as an upgraded connection is, by closing it; the client |
| - // discards the incomplete event and reconnects. |
| - s.mark(streamCut) |
| - default: |
| - resp.Body = newEventBoundaryBody(resp.Body, s.stop) |
| - s.mark(streamSSE) |
| + if resp.StatusCode == http.StatusSwitchingProtocols || isEventStream(resp.Header.Get("Content-Type")) { |
| + s.mark() |
| } |
| } |
| -// identityEncoded reports whether h names no content coding but identity. |
| -func identityEncoded(h http.Header) bool { |
| - for _, v := range h.Values("Content-Encoding") { |
| - for _, c := range strings.Split(v, ",") { |
| - if c = strings.TrimSpace(c); c != "" && !strings.EqualFold(c, "identity") { |
| - return false |
| - } |
| - } |
| +// classifyMoveStreams is a tenant proxy's ModifyResponse: MarkMoveStream |
| +// on the response head, first, then mod (responseModifier), unchanged. |
| +func classifyMoveStreams(mod func(*http.Response) error) func(*http.Response) error { |
| + return func(resp *http.Response) error { |
| + MarkMoveStream(resp) |
| + return mod(resp) |
| } |
| - return true |
| } |
| func isEventStream(ct string) bool { |
| mt, _, err := mime.ParseMediaType(ct) |
| return err == nil && mt == "text/event-stream" |
| } |
| - |
| -// eventBoundaryBody passes an SSE body through until stop is closed, then |
| -// ends it with io.EOF at the first event boundary (a blank line) at or |
| -// after what it has already passed on. Bytes past that boundary are |
| -// dropped: the client gets them again after its reconnect. If stop closes |
| -// while what has been passed on ends at a boundary, the upstream body is |
| -// closed so a read blocked on it returns. |
| -// |
| -// The upstream body is closed by one shared operation (shut), whichever of |
| -// the watcher and the proxy gets there first: the body below carries the |
| -// trailer scrubs (stripAssetTrailers, stripAppHolder, scopeCookies), whose |
| -// callbacks run once, at that close. Every caller waits until the close, |
| -// those callbacks included, has completed, so the proxy never copies the |
| -// trailers before they are scrubbed and no callback runs twice or |
| -// concurrently. |
| -type eventBoundaryBody struct { |
| - rc io.ReadCloser |
| - stop <-chan struct{} |
| - |
| - closeOnce sync.Once |
| - // closed is closed once shut's close of rc has returned; closeErr is |
| - // its answer. |
| - closed chan struct{} |
| - closeErr error |
| - |
| - mu sync.Mutex |
| - // tail is the last bytes passed on (at most 3), for a boundary that |
| - // spans two reads; at is whether what was passed on ends at a |
| - // boundary (true before the first byte). |
| - tail []byte |
| - at bool |
| - ended bool |
| -} |
| - |
| -func newEventBoundaryBody(rc io.ReadCloser, stop <-chan struct{}) *eventBoundaryBody { |
| - b := &eventBoundaryBody{rc: rc, stop: stop, closed: make(chan struct{}), at: true} |
| - go b.watch() |
| - return b |
| -} |
| - |
| -// watch closes the upstream body when stop closes at a boundary, so a |
| -// blocked read returns and Read can end the stream. |
| -func (b *eventBoundaryBody) watch() { |
| - select { |
| - case <-b.stop: |
| - case <-b.closed: |
| - return |
| - } |
| - b.mu.Lock() |
| - at := b.at |
| - b.mu.Unlock() |
| - if at { |
| - _ = b.shut() |
| - } |
| -} |
| - |
| -// shut is the one close of the upstream body: the first caller closes it, |
| -// and every caller returns only once that close has completed. |
| -func (b *eventBoundaryBody) shut() error { |
| - b.closeOnce.Do(func() { |
| - b.closeErr = b.rc.Close() |
| - close(b.closed) |
| - }) |
| - <-b.closed |
| - return b.closeErr |
| -} |
| - |
| -func (b *eventBoundaryBody) stopped() bool { |
| - select { |
| - case <-b.stop: |
| - return true |
| - default: |
| - return false |
| - } |
| -} |
| - |
| -func (b *eventBoundaryBody) Read(p []byte) (int, error) { |
| - b.mu.Lock() |
| - if b.ended { |
| - b.mu.Unlock() |
| - return 0, io.EOF |
| - } |
| - if b.at && b.stopped() { |
| - b.ended = true |
| - b.mu.Unlock() |
| - return 0, io.EOF |
| - } |
| - b.mu.Unlock() |
| - n, err := b.rc.Read(p) |
| - b.mu.Lock() |
| - defer b.mu.Unlock() |
| - if b.stopped() { |
| - if k := boundaryIn(b.tail, p[:n]); k >= 0 { |
| - b.ended = true |
| - if k == 0 { |
| - return 0, io.EOF |
| - } |
| - return k, nil |
| - } |
| - } |
| - b.passed(p[:n]) |
| - return n, err |
| -} |
| - |
| -// passed records p as passed on. |
| -func (b *eventBoundaryBody) passed(p []byte) { |
| - if len(p) == 0 { |
| - return |
| - } |
| - t := append(b.tail, p...) |
| - if len(t) > 3 { |
| - t = t[len(t)-3:] |
| - } |
| - b.tail = append(b.tail[:0], t...) |
| - b.at = endsAtBoundary(b.tail) |
| -} |
| - |
| -// Close is the proxy's close: the shared one. |
| -func (b *eventBoundaryBody) Close() error { return b.shut() } |
| - |
| -// boundaryIn is the largest k (0 <= k <= len(p)) such that tail followed |
| -// by p[:k] ends at an event boundary, or -1 when there is none. |
| -func boundaryIn(tail, p []byte) int { |
| - for k := len(p); k >= 0; k-- { |
| - var last []byte |
| - if k >= 4 { |
| - last = p[k-4 : k] |
| - } else { |
| - last = append(append([]byte(nil), tail...), p[:k]...) |
| - } |
| - if endsAtBoundary(last) { |
| - return k |
| - } |
| - } |
| - return -1 |
| -} |
| - |
| -// endsAtBoundary reports whether b ends with a blank line: a line end |
| -// ("\r\n", "\n" or "\r") right after another. An empty b is the start of |
| -// the stream, a boundary too. |
| -func endsAtBoundary(b []byte) bool { |
| - n := len(b) |
| - switch { |
| - case n == 0: |
| - return true |
| - case n >= 2 && b[n-2] == '\r' && b[n-1] == '\n': |
| - n -= 2 |
| - case b[n-1] == '\n' || b[n-1] == '\r': |
| - n-- |
| - default: |
| - return false |
| - } |
| - return n > 0 && (b[n-1] == '\n' || b[n-1] == '\r') |
| -} |
diff --git a/internal/edge/movestreams_test.go b/internal/edge/movestreams_test.go| index 3474a97d9..f5fa3fc5c 100644 |
| --- a/internal/edge/movestreams_test.go |
| +++ b/internal/edge/movestreams_test.go |
| @@ -1,276 +1,152 @@ |
| package edge |
| import ( |
| - "errors" |
| + "bufio" |
| + "fmt" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| + "net/http/httputil" |
| + "net/url" |
| "strings" |
| - "sync" |
| - "sync/atomic" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| -func TestEndsAtBoundary(t *testing.T) { |
| - for in, want := range map[string]bool{ |
| - "": true, |
| - "\n\n": true, |
| - "a\n\n": true, |
| - "a\r\n\r\n": true, |
| - "\n\r\n": true, |
| - "a\r\r": true, |
| - "a\n": false, |
| - "a\r\n": false, |
| - "a\r": false, |
| - "data: x": false, |
| - "a\r\n\r": true, |
| - "data: x\n\nd": false, |
| - } { |
| - if got := endsAtBoundary([]byte(in)); got != want { |
| - t.Errorf("endsAtBoundary(%q) = %v, want %v", in, got, want) |
| - } |
| - } |
| +// The tenant proxies' hook marks a stream from its head and nothing else, |
| +// and never changes the response: the body the proxy reads is the one |
| +// responseModifier left, wrapper for wrapper. |
| +func TestClassifyMoveStreamsMarksStreamsOnly(t *testing.T) { |
| + e := &Edge{appsDomain: "example.com"} |
| + rt := registry.Route{Host: "shop.example.com"} |
| + hook := classifyMoveStreams(e.responseModifier(rt)) |
| for _, c := range []struct { |
| - tail, p string |
| - want int |
| + status int |
| + ct, enc string |
| + stream bool |
| }{ |
| - {"", "data: a\n\ndata: b", 9}, |
| - {"a\n", "\ndata: b", 1}, |
| - {"a\r\n", "\r\nx", 2}, |
| - {"\n\n", "data", 0}, |
| - {"x", "data: b\n", -1}, |
| - {"", "a\n\ndata: b\n\nc", 12}, |
| + {http.StatusOK, "text/event-stream; charset=utf-8", "", true}, |
| + {http.StatusOK, "text/event-stream", "gzip", true}, |
| + {http.StatusSwitchingProtocols, "", "", true}, |
| + {http.StatusOK, "text/html", "", false}, |
| + {http.StatusOK, "application/json", "gzip", false}, |
| } { |
| - if got := boundaryIn([]byte(c.tail), []byte(c.p)); got != c.want { |
| - t.Errorf("boundaryIn(%q, %q) = %d, want %d", c.tail, c.p, got, c.want) |
| - } |
| - } |
| -} |
| - |
| -// A stream ended mid-event passes on the rest of that event, then ends at |
| -// its boundary; bytes after the boundary are dropped. |
| -func TestEventBoundaryBodyEndsAfterTheEvent(t *testing.T) { |
| - pr, pw := io.Pipe() |
| - stop := make(chan struct{}) |
| - b := newEventBoundaryBody(pr, stop) |
| - defer b.Close() |
| - got := make(chan string, 1) |
| - go func() { all, _ := io.ReadAll(b); got <- string(all) }() |
| - pw.Write([]byte("id: 1\ndata: one\n\n")) |
| - pw.Write([]byte("id: 2\n")) |
| - time.Sleep(20 * time.Millisecond) |
| - close(stop) // mid-event: it is not cut here |
| - pw.Write([]byte("data: two\n\nid: 3\n")) |
| - select { |
| - case s := <-got: |
| - if s != "id: 1\ndata: one\n\nid: 2\ndata: two\n\n" { |
| - t.Fatalf("passed on %q", s) |
| - } |
| - case <-time.After(2 * time.Second): |
| - t.Fatal("the stream did not end at the boundary") |
| - } |
| -} |
| - |
| -// Ended between events, a read blocked on the upstream returns: the body |
| -// ends at once. |
| -func TestEventBoundaryBodyEndsABlockedRead(t *testing.T) { |
| - pr, pw := io.Pipe() |
| - defer pw.Close() |
| - stop := make(chan struct{}) |
| - b := newEventBoundaryBody(pr, stop) |
| - defer b.Close() |
| - got := make(chan error, 1) |
| - go func() { |
| - buf := make([]byte, 64) |
| - for { |
| - if _, err := b.Read(buf); err != nil { |
| - got <- err |
| - return |
| + mk := func(r *http.Request) *http.Response { |
| + resp := &http.Response{StatusCode: c.status, Header: http.Header{}, Trailer: http.Header{}, Request: r, Body: io.NopCloser(strings.NewReader("data: x\n\n"))} |
| + if c.ct != "" { |
| + resp.Header.Set("Content-Type", c.ct) |
| } |
| + if c.enc != "" { |
| + resp.Header.Set("Content-Encoding", c.enc) |
| + } |
| + return resp |
| } |
| - }() |
| - pw.Write([]byte("data: one\n\n")) |
| - time.Sleep(20 * time.Millisecond) |
| - close(stop) |
| - select { |
| - case err := <-got: |
| - if err != io.EOF { |
| - t.Fatalf("ended with %v, want io.EOF", err) |
| - } |
| - case <-time.After(2 * time.Second): |
| - t.Fatal("a read blocked between events was not ended") |
| - } |
| -} |
| - |
| -// The tenant proxies' response hook marks a stream and nothing else. |
| -func TestResponseModifierMarksMoveStreams(t *testing.T) { |
| - e := &Edge{} |
| - mod := e.responseModifier(registry.Route{Host: "shop.example.com"}) |
| - for _, c := range []struct { |
| - status int |
| - ct string |
| - want bool |
| - }{ |
| - {http.StatusOK, "text/event-stream; charset=utf-8", true}, |
| - {http.StatusSwitchingProtocols, "", true}, |
| - {http.StatusOK, "text/html", false}, |
| - {http.StatusOK, "application/json", false}, |
| - } { |
| r, s := WithStreamEnd(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)) |
| - resp := &http.Response{StatusCode: c.status, Header: http.Header{}, Request: r, Body: io.NopCloser(strings.NewReader("data: x\n\n"))} |
| - if c.ct != "" { |
| - resp.Header.Set("Content-Type", c.ct) |
| + resp := mk(r) |
| + if err := hook(resp); err != nil { |
| + t.Fatal(err) |
| } |
| - if err := mod(resp); err != nil { |
| + plain := mk(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)) |
| + if err := e.responseModifier(rt)(plain); err != nil { |
| t.Fatal(err) |
| } |
| - if s.Stream() != c.want { |
| - t.Errorf("%d %q: stream %v, want %v", c.status, c.ct, s.Stream(), c.want) |
| + if got, want := fmt.Sprintf("%T", resp.Body), fmt.Sprintf("%T", plain.Body); got != want { |
| + t.Errorf("%d %q: body %s, want responseModifier's own %s: the move hook wrapped it", c.status, c.ct, got, want) |
| } |
| - // End on a request that is not a stream touches nothing. |
| - s.End() |
| - if !c.want && r.Context().Err() != nil { |
| - t.Errorf("%d %q: an ordinary request was cancelled", c.status, c.ct) |
| + if s.Stream() != c.stream { |
| + t.Errorf("%d %q %q: stream %v, want %v", c.status, c.ct, c.enc, s.Stream(), c.stream) |
| } |
| - if c.status == http.StatusSwitchingProtocols && r.Context().Err() == nil { |
| - t.Error("an upgraded connection was not ended") |
| + s.End() |
| + if cut := r.Context().Err() != nil; cut != c.stream { |
| + t.Errorf("%d %q %q: cut %v by End, want %v", c.status, c.ct, c.enc, cut, c.stream) |
| } |
| } |
| -} |
| - |
| -// ctrlBody is an upstream SSE body: one event, then a read that blocks |
| -// until Close; Close blocks until release is closed, and counts. |
| -type ctrlBody struct { |
| - first bool |
| - unblock chan struct{} |
| - once sync.Once |
| - release chan struct{} |
| - closes atomic.Int32 |
| -} |
| - |
| -func (c *ctrlBody) Read(p []byte) (int, error) { |
| - if !c.first { |
| - c.first = true |
| - return copy(p, "data: x\n\n"), nil |
| - } |
| - <-c.unblock |
| - return 0, errors.New("read on closed body") |
| -} |
| - |
| -func (c *ctrlBody) Close() error { |
| - c.closes.Add(1) |
| - c.once.Do(func() { close(c.unblock) }) |
| - <-c.release |
| - return nil |
| -} |
| - |
| -// F1.1 (Astra r1): the move's watcher and the proxy close the body at the |
| -// same time, through the real response hook and its trailer scrubs. One |
| -// close runs; both callers return only after it, trailer scrubs included, |
| -// has completed. Run with -race. |
| -func TestMoveStreamCloseIsSharedWithTheTrailerScrubs(t *testing.T) { |
| - e := &Edge{} |
| - mod := e.responseModifier(registry.Route{Host: "shop.example.com"}) |
| + // A stream marked after End (it opened mid-move) is cut at once. |
| r, s := WithStreamEnd(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)) |
| - up := &ctrlBody{unblock: make(chan struct{}), release: make(chan struct{})} |
| - resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Request: r, Body: up, |
| - // Announced: X-Carlos-Holder (its value lands at EOF). Unannounced: |
| - // X-Carlos-Handover and Carlos-Cache, as net/http fills them. |
| - Trailer: http.Header{holderHeader: nil}} |
| - if err := mod(resp); err != nil { |
| - t.Fatal(err) |
| + s.End() |
| + if r.Context().Err() != nil { |
| + t.Fatal("End cut a request before its head said it is a stream") |
| } |
| - if _, ok := resp.Body.(*eventBoundaryBody); !ok { |
| - t.Fatalf("body is a %T, want the boundary reader outermost", resp.Body) |
| + hook(&http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Request: r, Body: http.NoBody}) |
| + if r.Context().Err() == nil { |
| + t.Fatal("a stream classified after End was not cut") |
| } |
| - if _, announced := resp.Trailer[holderHeader]; announced { |
| - t.Fatal("the announced holder trailer was not dropped at the hook") |
| - } |
| - // The values arrive as the transport fills them, before any close. |
| - resp.Trailer.Set(holderHeader, "box-z") |
| - resp.Trailer.Set(HandoverHeader, "1") |
| - resp.Trailer.Set("Carlos-Cache", "hit") |
| - resp.Trailer.Set("X-App", "kept") |
| +} |
| - buf := make([]byte, 64) |
| - if n, err := resp.Body.Read(buf); err != nil || string(buf[:n]) != "data: x\n\n" { |
| - t.Fatalf("first read: %q %v", buf[:n], err) |
| - } |
| - proxyClosed := make(chan error, 1) |
| - go func() { |
| - // The proxy: read on until the end, then close, then copy trailers. |
| - for { |
| - if _, err := resp.Body.Read(buf); err != nil { |
| - break |
| - } |
| - } |
| - proxyClosed <- resp.Body.Close() |
| - }() |
| - s.End() // the watcher closes too, at the boundary |
| - waitMoveStream(t, func() bool { return up.closes.Load() >= 1 }) |
| - select { |
| - case <-proxyClosed: |
| - t.Fatal("the proxy's close returned before the shared close completed") |
| - case <-time.After(50 * time.Millisecond): |
| - } |
| - close(up.release) |
| - if err := <-proxyClosed; err != nil { |
| - t.Fatal(err) |
| - } |
| - // After the proxy's Close returns, the scrubs have run: what it copies. |
| - for _, k := range []string{holderHeader, HandoverHeader, "Carlos-Cache"} { |
| - if v := resp.Trailer.Get(k); v != "" { |
| - t.Errorf("trailer %s = %q survived the close", k, v) |
| - } |
| - } |
| - if resp.Trailer.Get("X-App") != "kept" { |
| - t.Error("an app trailer was removed") |
| - } |
| - if n := up.closes.Load(); n != 1 { |
| - t.Fatalf("the upstream body was closed %d times, want once", n) |
| +// Astra round 2's guard, kept as a test: through the real responseModifier, |
| +// http.Transport and httputil.ReverseProxy, an SSE response whose trailers |
| +// (announced and unannounced platform trailers, and a wide-domain |
| +// Set-Cookie) arrive as a move cuts it. No platform trailer and no |
| +// unscoped cookie may reach the client, whatever the order. Run with -race. |
| +func TestMoveCutKeepsTheTrailerScrubs(t *testing.T) { |
| + for i := 0; i < 30; i++ { |
| + moveCutTrailerRound(t, i%3) |
| } |
| } |
| -func waitMoveStream(t *testing.T, cond func() bool) { |
| +func moveCutTrailerRound(t *testing.T, delay int) { |
| t.Helper() |
| - for deadline := time.Now().Add(2 * time.Second); !cond(); time.Sleep(time.Millisecond) { |
| - if time.Now().After(deadline) { |
| - t.Fatal("timed out") |
| - } |
| + cut := make(chan struct{}) |
| + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/event-stream") |
| + w.Header().Set("Trailer", holderHeader+", X-App") |
| + w.WriteHeader(http.StatusOK) |
| + io.WriteString(w, "data: x\n\n") |
| + w.(http.Flusher).Flush() |
| + <-cut |
| + time.Sleep(time.Duration(delay) * time.Millisecond) |
| + w.Header().Set(holderHeader, "forged") |
| + w.Header().Set("X-App", "kept") |
| + w.Header().Set(http.TrailerPrefix+HandoverHeader, "1") |
| + w.Header().Set(http.TrailerPrefix+"Carlos-Cache", "hit") |
| + w.Header().Set(http.TrailerPrefix+"Set-Cookie", "sid=forged; Domain=example.com") |
| + })) |
| + defer up.Close() |
| + u, _ := url.Parse(up.URL) |
| + e := &Edge{appsDomain: "example.com"} |
| + proxy := &httputil.ReverseProxy{ |
| + Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(u) }, |
| + ModifyResponse: classifyMoveStreams(e.responseModifier(registry.Route{Host: "shop.example.com"})), |
| + ErrorLog: nil, |
| + } |
| + ends := make(chan *StreamEnd, 1) |
| + front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + r, s := WithStreamEnd(r) |
| + ends <- s |
| + proxy.ServeHTTP(w, r) |
| + })) |
| + defer front.Close() |
| + resp, err := http.Get(front.URL + "/events") |
| + if err != nil { |
| + t.Fatal(err) |
| } |
| -} |
| - |
| -// F1.2 (controller ruling): an encoded SSE stream is never scanned for |
| -// event boundaries; a move ends it by closing it, as an upgrade. |
| -func TestMoveStreamEncodedSSEIsCutNotFramed(t *testing.T) { |
| - e := &Edge{} |
| - mod := e.responseModifier(registry.Route{Host: "shop.example.com"}) |
| - for _, enc := range []string{"gzip", "br", "identity, gzip"} { |
| - r, s := WithStreamEnd(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)) |
| - body := io.NopCloser(strings.NewReader("\x1f\x8b\x08\x00")) |
| - resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}, "Content-Encoding": {enc}}, Request: r, Body: body} |
| - if err := mod(resp); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, framed := resp.Body.(*eventBoundaryBody); framed { |
| - t.Fatalf("%s: the boundary reader was applied to an encoded stream", enc) |
| - } |
| - if !s.Stream() { |
| - t.Fatalf("%s: not marked as a stream", enc) |
| + defer resp.Body.Close() |
| + br := bufio.NewReader(resp.Body) |
| + if line, err := br.ReadString('\n'); err != nil || line != "data: x\n" { |
| + t.Fatalf("first line %q %v", line, err) |
| + } |
| + s := <-ends |
| + close(cut) // the app sends its trailers now |
| + s.End() // and the move cuts the stream |
| + done := make(chan struct{}) |
| + go func() { io.Copy(io.Discard, br); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the cut stream did not end") |
| + } |
| + for _, h := range []http.Header{resp.Header, resp.Trailer} { |
| + for _, k := range []string{holderHeader, HandoverHeader, "Carlos-Cache"} { |
| + if v := h.Get(k); v != "" { |
| + t.Fatalf("platform trailer %s = %q reached the client", k, v) |
| + } |
| } |
| - s.End() |
| - if r.Context().Err() == nil { |
| - t.Fatalf("%s: an encoded stream was not ended by closing it", enc) |
| + for _, c := range h.Values("Set-Cookie") { |
| + if strings.Contains(strings.ToLower(c), "domain=example.com") { |
| + t.Fatalf("an unscoped cookie reached the client: %q", c) |
| + } |
| } |
| } |
| - // identity is no coding: framed. |
| - r, _ := WithStreamEnd(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)) |
| - resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}, "Content-Encoding": {"identity"}}, Request: r, Body: io.NopCloser(strings.NewReader(""))} |
| - mod(resp) |
| - if _, framed := resp.Body.(*eventBoundaryBody); !framed { |
| - t.Fatal("an identity stream was not framed") |
| - } |
| } |
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go| index 156904860..4a3234cd4 100644 |
| --- a/internal/host/hadrain.go |
| +++ b/internal/host/hadrain.go |
| @@ -717,11 +717,12 @@ func (d *drainDriver) moveOne(ctx context.Context, txn string, h activator.Drain |
| } |
| return leave("begin", err.Error(), activator.DrainRelease{}) |
| } |
| - // 3.1: the host's long-lived responses here end now, at the move's |
| - // start, not at the take: SSE streams at an event boundary, upgraded |
| - // connections, and edge-held streams (R3.5). None ends on its own, so |
| - // each would hold the wait below to its bound. Their clients reconnect |
| - // and are held like any other request until the take (§25.8). |
| + // 3.1: the host's long-lived responses here are cut now, at the |
| + // move's start, not at the take: SSE streams and upgraded connections |
| + // (their request contexts cancelled), and edge-held streams. None ends |
| + // on its own, so each would hold the wait below to its bound. Their |
| + // clients reconnect and are held like any other request until the take |
| + // (§25.8), as at today's connection drain. |
| d.act.EndMoveStreams(host) |
| d.edge.CloseHeldHost(host) |
| // 3.2: tickets and the in-flight drain share today's 10 s bound for |