carlos / platform Public

edge: one shared close for move streams; encoded SSE is closed

Astra round 1 on held-move-speed, F1.1 and F1.2.

F1.1 (P1): when a move ended an idle SSE stream, its watcher closed the
body while the proxy closed it too. The body below carries the trailer
scrubs (stripAssetTrailers, stripAppHolder, scopeCookies), whose
callbacks assume one caller, so they ran concurrently on the same
trailer map, and the proxy's close could return before the watcher's
scrub had finished. eventBoundaryBody now closes its upstream through
one operation, shut: a sync.Once plus a done channel. The watcher and
Close both call it and both wait until the close, trailer cleanup
included, has completed, so the scrubs run once and finish before the
proxy copies trailers. Race witness through the real responseModifier
with announced and unannounced trailers
(TestMoveStreamCloseIsSharedWithTheTrailerScrubs, -race); calling the
upstream Close directly from the watcher makes it report a data race.

F1.2 (P1, controller ruling): an SSE response with any Content-Encoding
other than identity is not wrapped with the boundary reader, since its
bytes are not SSE text. It is marked like an upgraded connection and a
move ends it by cancelling the request's context, so the connection
closes and the client reconnects; EventSource discards the incomplete
event, as at a connection-drain cut today. Only unencoded
text/event-stream gets the whole-event end. Proxy-level test: the
client sends Accept-Encoding: gzip and the app answers a compressed,
flushed SSE stream; the boundary reader is never applied, the stream
is closed promptly and the in-flight wait takes under 1 s. §25.4 and
§25.8 say so in one plain sentence each.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f425885b903a5c0765e41daf98e1a0c482b33811 parent 8381c49
4 files changed, +298 −35
  • docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md +2 −2
  • internal/activator/movestreams_test.go +88 −3
  • internal/edge/movestreams.go +71 −30
  • internal/edge/movestreams_test.go +137 −0

Intent

Human

<task-notification> <task-id>bkh6ztg9t</task-id> <tool-use-id>toolu_017cZQAS24ULdvzG974qAFnd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/bkh6ztg9t.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on 8381c497" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>blks822jt</task-id> <tool-use-id>toolu_01PwoYt2PdoZdGTStHAMSGnW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/blks822jt.output</output-file> <status>completed</status> <summary>Background command "Astra review round 1 (background)" 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 ff31ac7c5..b9674b51a 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: SSE responses (`text/event-stream`) end at their next event boundary, 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 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.)
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 closed at the move's start, not at the take: SSE at an event boundary, so the browser sees a clean end after a whole event and 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). 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).
- **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.
diff --git a/internal/activator/movestreams_test.go b/internal/activator/movestreams_test.go
index 0a530c0ea..8d8a969e6 100644
--- a/internal/activator/movestreams_test.go
+++ b/internal/activator/movestreams_test.go
@@ -2,6 +2,7 @@ package activator
import (
"bufio"
+ "compress/gzip"
"context"
"errors"
"fmt"
@@ -49,6 +50,28 @@ func moveStreamUpstream(t *testing.T, release <-chan struct{}) *url.URL {
case <-time.After(20 * time.Millisecond):
}
}
+ case "/gzevents":
+ // A compressed SSE stream, negotiated by the client's own
+ // Accept-Encoding (which the proxy passes on), flushed per event.
+ if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
+ t.Error("the client's Accept-Encoding did not reach the app")
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Content-Encoding", "gzip")
+ w.WriteHeader(http.StatusOK)
+ gz := gzip.NewWriter(w)
+ f := w.(http.Flusher)
+ for i := 0; ; i++ {
+ fmt.Fprintf(gz, "id: %d\ndata: tick %d\n\n", i, i)
+ gz.Flush()
+ f.Flush()
+ select {
+ case <-r.Context().Done():
+ return
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
case "/ws":
conn, brw, err := http.NewResponseController(w).Hijack()
if err != nil {
@@ -76,15 +99,28 @@ 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); return nil },
+ 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
+ },
}
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
+ return front.URL, bodies
}
func (s *haSvc) inflight() int {
@@ -182,6 +218,55 @@ func TestMoveEndsAStreamThatOpensAfterItsStart(t *testing.T) {
}
}
+// 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.
+func TestMoveClosesAnEncodedSSEStream(t *testing.T) {
+ s, _ := haServiceEntry(t, "shop.example.com")
+ front, bodies := moveStreamFrontBodies(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")
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ 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 {
+ t.Fatal(err)
+ }
+ br := bufio.NewReader(zr)
+ for seen := 0; seen < 2; {
+ line, err := br.ReadString('\n')
+ if err != nil {
+ t.Fatalf("reading the stream: %v", err)
+ }
+ if line == "\n" {
+ seen++
+ }
+ }
+ took, err := moveAndWait(t, s, 10*time.Second)
+ 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")
+ }
+}
+
func TestMoveEndsAnUpgradedConnectionAtItsStart(t *testing.T) {
s, _ := haServiceEntry(t, "shop.example.com")
front := moveStreamFront(t, s, moveStreamUpstream(t, nil))
diff --git a/internal/edge/movestreams.go b/internal/edge/movestreams.go
index 0ae88eace..90aba92cc 100644
--- a/internal/edge/movestreams.go
+++ b/internal/edge/movestreams.go
@@ -14,19 +14,23 @@ package edge
// other request, so an ordinary request keeps the move's bound.
//
// Ending a stream:
-// - 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 upgraded connection: the request's context is cancelled, which
-// makes the proxy close both sides, as the connection drain does at
-// its bound. The client reconnects and is held the same way.
+// - 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.
import (
"context"
"io"
"mime"
"net/http"
+ "strings"
"sync"
)
@@ -34,8 +38,11 @@ type streamKind uint8
const (
streamNone streamKind = iota
+ // streamSSE: an unencoded SSE body, ended at an event boundary.
streamSSE
- streamUpgrade
+ // 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.
@@ -84,7 +91,7 @@ func (s *StreamEnd) endLocked() {
switch s.kind {
case streamSSE:
close(s.stop)
- case streamUpgrade:
+ case streamCut:
s.cancel()
}
}
@@ -115,13 +122,33 @@ func MarkMoveStream(resp *http.Response) {
}
switch {
case resp.StatusCode == http.StatusSwitchingProtocols:
- s.mark(streamUpgrade)
- case isEventStream(resp.Header.Get("Content-Type")) && resp.Body != nil && resp.Body != http.NoBody:
+ 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)
}
}
+// 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
+ }
+ }
+ }
+ return true
+}
+
func isEventStream(ct string) bool {
mt, _, err := mime.ParseMediaType(ct)
return err == nil && mt == "text/event-stream"
@@ -133,23 +160,35 @@ func isEventStream(ct string) bool {
// 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{}
- done 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
- closed bool
+ tail []byte
+ at bool
+ ended bool
}
func newEventBoundaryBody(rc io.ReadCloser, stop <-chan struct{}) *eventBoundaryBody {
- b := &eventBoundaryBody{rc: rc, stop: stop, done: make(chan struct{}), at: true}
+ b := &eventBoundaryBody{rc: rc, stop: stop, closed: make(chan struct{}), at: true}
go b.watch()
return b
}
@@ -159,17 +198,28 @@ func newEventBoundaryBody(rc io.ReadCloser, stop <-chan struct{}) *eventBoundary
func (b *eventBoundaryBody) watch() {
select {
case <-b.stop:
- case <-b.done:
+ case <-b.closed:
return
}
b.mu.Lock()
at := b.at
b.mu.Unlock()
if at {
- _ = b.rc.Close()
+ _ = 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:
@@ -220,17 +270,8 @@ func (b *eventBoundaryBody) passed(p []byte) {
b.at = endsAtBoundary(b.tail)
}
-func (b *eventBoundaryBody) Close() error {
- b.mu.Lock()
- if b.closed {
- b.mu.Unlock()
- return nil
- }
- b.closed = true
- close(b.done)
- b.mu.Unlock()
- return b.rc.Close()
-}
+// 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.
diff --git a/internal/edge/movestreams_test.go b/internal/edge/movestreams_test.go
index da172d5dc..3474a97d9 100644
--- a/internal/edge/movestreams_test.go
+++ b/internal/edge/movestreams_test.go
@@ -1,10 +1,13 @@
package edge
import (
+ "errors"
"io"
"net/http"
"net/http/httptest"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -137,3 +140,137 @@ func TestResponseModifierMarksMoveStreams(t *testing.T) {
}
}
}
+
+// 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"})
+ 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)
+ }
+ if _, ok := resp.Body.(*eventBoundaryBody); !ok {
+ t.Fatalf("body is a %T, want the boundary reader outermost", resp.Body)
+ }
+ 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)
+ }
+}
+
+func waitMoveStream(t *testing.T, cond func() bool) {
+ t.Helper()
+ for deadline := time.Now().Add(2 * time.Second); !cond(); time.Sleep(time.Millisecond) {
+ if time.Now().After(deadline) {
+ t.Fatal("timed out")
+ }
+ }
+}
+
+// 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)
+ }
+ s.End()
+ if r.Context().Err() == nil {
+ t.Fatalf("%s: an encoded stream was not ended by closing it", enc)
+ }
+ }
+ // 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")
+ }
+}