carlos / platform Public

tunnelclient: Task 1 fix round 1 (#471): no-write marker strip, pinned fence

- The shim strips an app-set Carlos-Tunnel-Upgraded when the handler
  returns having written nothing (x/net's implicit 200 from the live
  header map), on the plain and the upgrade path.
- The write fence is pinned deterministically: a Write blocked on the
  hub's stream window holds ServeHTTP open until it ends, and a Write
  after that gets net.ErrClosed. Two nil-in-production hooks on
  upgradedConn mark the guarded write and the fence. Replaces the
  scheduling-dependent TestHijackedConnRefusesWritesAfterTheHandler.
- shimWriter.FlushError returns the stream's error, as x/net's writer
  does; Flush calls it.
- TestShimRefusesABadToken covers two marker lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 8b89a04b20893b11094f322fe82b2e8c2327c1c1 parent 13985af
2 files changed, +195 −55
  • internal/tunnelclient/upgrade.go +31 −3
  • internal/tunnelclient/upgrade_box_test.go +164 −52

Intent

Human

<task-notification> <task-id>a232f2e8c830f59c6</task-id> <tool-use-id>toolu_01KBHvZriyrdxZKtzbGAu1U1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a232f2e8c830f59c6.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 2: interactive package" 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.** Both P2s and the P3 from Astra's review are fixed, test-first, in one commit. Nothing was pushed. **Commit:** `a62099ee` "interactive: one frame is one whole message; Dial checks the subprotocol (Task 2 fix 1)", on top of `6672a22e`. It changes only `internal/interactive/frames.go` and `frames_test.go`. **What changed:** - **Fragmentation (P2):** `Receive` now reads one frame at a time through x/net's own frame reader, so it sees the FIN bit and the real opcode. A fragmented message, a continuation, a text frame, a reserved bit or an empty frame is `ErrBadFrame`. An oversized frame is still `websocket.ErrFrameTooLarge`. - **Truncation (P2):** the payload is read to its declared length. A frame cut short is now an error wrapping `io.ErrUnexpectedEOF`, not a short success. - **Subprotocol (P3):** `DialFrame` now reads the handshake response itself and refuses with a new `ErrNoSubprotocol` unless the server answered exactly `carlos-interactive/1`. - `MaxFrame` and `RunMaxFrame` are unchanged. **Tests:** - **RED:** before the fix, the new raw-wire tests failed exactly as Astra described, plus one more hole: a frame with a reserved bit set was accepted. - **GREEN:** all 18 package tests pass under `-race`. `go vet` and `gofmt` are clean, and windows, darwin and linux/arm64 builds pass. - **Mutations:** removing each fix in turn (the FIN check, the full-length read, the subprotocol check) makes the tests fail. The file was restored byte for byte after each. **Concerns:** - **New rule for callers:** after any `Receive` error the connection is finished and must be closed. `Receive` must also be the connection's only reader. The doc comment says both, and the existing tests were changed to match. Later tasks already treat a receive error as the end of the connection. - **Depends on x/net details:** `Receive` relies on how x/net v0.60.0 reads frames internally. If an upgrade changed that, the package tests would fail loudly rather than pass silently. - **Not mine to commit:** the uncommitted edits to the plan and copy deck, and the untracked Codex findings file, come from the parallel amendment work. I left them alone. The full fix report, with commands, RED/GREEN output and the mutation results, is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/task-2-report.md`.</result> <usage><subagent_tokens>161718</subagent_tokens><tool_uses>12</tool_uses><duration_ms>258902</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bo1ryyd3a</task-id> <tool-use-id>toolu_016wx9wCFkLGXyNzVLdDwuVL</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bo1ryyd3a.output</output-file> <status>completed</status> <summary>Background command "Run the scoped Astra re-review of Plan 6 Task 2" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a6df1701ef5c7b658</task-id> <tool-use-id>toolu_01JV8mY2Bq7bdyY7wkk5LuF5</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a6df1701ef5c7b658.output</output-file> <status>completed</status> <summary>Agent "Write the Plan 6 amendment" 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>I've resolved all seven of Astra's round 1 findings in the plan. The new tip is `25b12960cf50e931c09efc27ac7cb1af5c984c98`, pushed to origin `rootfs-apps-6-interactive` and confirmed with `ls-remote`. It sits on Task 2's commit `6672a22e`, and the commit includes the findings file and the round 2 brief. No code was changed. Each finding was checked against the code first. The plan has a new subsection, "Amendment rev 2: review dispositions", and every changed line is marked "rev 2". - **P1-1 (hibernating rootfs rows never reach the lease kill), resolved by covering them, not refusing them.** - The lease watch is now installed for every rootfs instance, not only always-on ones. Its existing always-on behaviour is unchanged, so a hibernating row's web process keeps today's path. - Its new run and session stop and kill apply to every rootfs instance, including ones already stopping, and a start in flight is killed again when it returns. - The fallback for a replica with no lease signal now reaches a hibernating row's runs and sessions too. - A rootfs run or session is refused up front if no lease watch covers its instance. - The plan adds tests for hibernating rows, one for runs (Task 7a) and one for sessions (Task 9). - **P1-2 (nothing carried the declared-process choice), resolved.** - A new field, `CmdSpec.Process`, carries it through six hops: CLI `Open`, console, splice, box worker, activator, and root's `StagedImage.Process`. - The console no longer rewrites `Open` to the resolved command; it keeps the resolved argv only for the audit row. - Setting both `Process` and `Args`, or neither, is refused, and so is `Process` on a binary row. - The plan adds tests in Tasks 6, 8, 10, 11 and 12, including the same command with different env and working directory. - **P1-3 (renaming the cleanup function breaks the pinned guards), resolved.** `cleanCmdExe`, `removeCmdExe` and instancectl's `startRootfsCmd` keep their names and gain a role parameter, so every pinned list stays byte for byte. Task 6 now runs all four guards: - `TestRootfsFilesAreRemovedOnlyBehindTheProof` - `TestRootfsRemovalGuardFixtures` - `TestRootfsRemovalOwnersUnchanged` - `TestRootfsInvariantTablesOnlyGrow` In the same area, I moved Task 7a's rootfs run start and `KillOneShot` into `backend_rootfs.go` so the existing structural guard reads them. I also add two entries to detector lists that are only allowed to grow: `oneShotKiller` and the binary tty verbs. - **P1-4 (C47 had a third consumer), resolved.** All three checked copies change in Task 4's one commit, and the task runs all three gates: - RFS-6-C47 in the deck, checked once built. - `zdd.apps-set.nothing` in the zero-downtime record, checked by `TestZeroDowntimeCopyIsApplied`. - `IP1-57` in `2026-10-21-instance-policy-copy.json:82`, checked by `TestInstancePolicyCopyIsApplied`. A grep found no fourth; the other hits are notes no test reads. - **P1-5 (a pickup retry can't fit the window), resolved by refusing up front.** - The numbers: the pickup window is 60 s, and the console's lifetimes gate needs at least 60 s of draining (`lifetimeSettle`) before it activates. It also refuses both new run creates and the pickup write while draining. - So a fleet run still queued when a drain starts can never be picked in time. The relay now answers "not picked" with the reason `cutover`, and the box never dials it again. - The run then expires as any unpicked run does: the CLI shows today's "not picked up within 60 seconds" line, and the sweep records it after activation. - A run picked before the drain keeps running, and its final record write lands after activation. No new copy is needed. - **P2-6 (request budget too low), resolved.** Task 10's budget now counts the setting reads (one on the console, one on the box) and the extra lifetime-slot read on every judged record read. It separates the two record transitions from retries and says when the one extra clear attempt happens. - **P2-7 (wrong deck totals), resolved.** Recounted from the rows: 401 rows, 397 live (2 of them pending), 4 struck. Plan 1 has 99 rows and Plan 4 has 146, 2 of them struck. Two things carry over: - The two copy-gate tests on the branch are still red until `rootfsCopyIDs` gains "RFS-6-C65" in the commit that applies Paul's copy review. - A hibernating rootfs row's web process, and binary runs, still stop only through the sweep after a lease loss. That predates this plan and is outside its scope. The round 2 brief is `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-plan6-amendment-R2.md` (round 2 of 3).</result> <usage><subagent_tokens>497011</subagent_tokens><tool_uses>43</tool_uses><duration_ms>506714</duration_ms></usage> </task-notification>

Attributed to this commit: 61.4 g CO₂e (8,044,306 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-tunnel-websockets-471, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
index 6f31ea6d7..98be1a376 100644
--- a/internal/tunnelclient/upgrade.go
+++ b/internal/tunnelclient/upgrade.go
@@ -96,6 +96,11 @@ type upgradeShim struct{ h http.Handler }
func (s upgradeShim) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sw := &shimWriter{w: w}
+ // A handler that returns having written nothing gets x/net's implicit
+ // 200 from the live header map, which the writer's own methods never
+ // see: strip once more on the way out. Deferred first, so on an
+ // upgrade it runs after finish.
+ defer sw.stripUnwritten()
toks, marked := r.Header[UpgradeHeader]
if !marked {
s.h.ServeHTTP(sw, r)
@@ -152,6 +157,14 @@ func (s *shimWriter) Header() http.Header {
func (s *shimWriter) strip() { s.w.Header().Del(UpgradedHeader) }
+// stripUnwritten strips the marker if no header has gone out and the
+// stream was not hijacked (a hijack's 200 carries the marker on purpose).
+func (s *shimWriter) stripUnwritten() {
+ if s.conn == nil && !s.wroteHeader {
+ s.strip()
+ }
+}
+
func (s *shimWriter) WriteHeader(code int) {
if s.conn != nil {
return
@@ -176,15 +189,19 @@ func (s *shimWriter) Write(p []byte) (int, error) {
// Flush implements http.Flusher directly: the box's edge wrappers assert
// it on the writer they are given rather than going through Unwrap.
-func (s *shimWriter) Flush() {
+func (s *shimWriter) Flush() { _ = s.FlushError() }
+
+// FlushError is what http.ResponseController.Flush prefers: it reports the
+// stream's error, as the x/net writer does.
+func (s *shimWriter) FlushError() error {
if s.conn != nil {
- return
+ return nil
}
if !s.wroteHeader {
s.strip()
s.wroteHeader = true
}
- _ = http.NewResponseController(s.w).Flush()
+ return http.NewResponseController(s.w).Flush()
}
// Unwrap lets http.ResponseController reach the stream's deadlines.
@@ -256,6 +273,11 @@ type upgradedConn struct {
wmu sync.Mutex // one Write+Flush at a time
closed atomic.Bool
closeOnce sync.Once
+
+ // Test hooks, nil in production: hookWrite runs inside Write's guarded
+ // section just before the stream write, hookFence as fence starts.
+ // Set by a test right after Hijack, before the conn is shared.
+ hookWrite, hookFence func()
}
func (c *upgradedConn) Read(p []byte) (int, error) {
@@ -273,6 +295,9 @@ func (c *upgradedConn) Write(p []byte) (int, error) {
if c.closed.Load() {
return 0, net.ErrClosed
}
+ if c.hookWrite != nil {
+ c.hookWrite()
+ }
n, err := c.w.Write(p)
if err != nil {
return n, err
@@ -294,6 +319,9 @@ func (c *upgradedConn) Close() error {
// fence waits for every use of the writer in progress to finish. Called
// after Close, so none starts afterwards.
func (c *upgradedConn) fence() {
+ if c.hookFence != nil {
+ c.hookFence()
+ }
c.life.Lock() // an empty critical section: a barrier, not a guard
c.life.Unlock()
}
diff --git a/internal/tunnelclient/upgrade_box_test.go b/internal/tunnelclient/upgrade_box_test.go
index 0c5e63bbb..f276f909d 100644
--- a/internal/tunnelclient/upgrade_box_test.go
+++ b/internal/tunnelclient/upgrade_box_test.go
@@ -199,15 +199,23 @@ func TestShimStripsAnAppSetUpgradedMarker(t *testing.T) {
}
// The marker is stripped however the response's header goes out: an
-// implicit 200 on the first Write and a Flush before any Write.
+// implicit 200 on the first Write, a Flush before any Write, and the
+// implicit 200 x/net sends when the handler returns having written nothing.
func TestShimStripsTheMarkerOnImplicitHeaders(t *testing.T) {
- for _, name := range []string{"write", "flush"} {
+ for _, name := range []string{"write", "flush", "return"} {
t.Run(name, func(t *testing.T) {
+ want := "hello"
+ if name == "return" {
+ want = ""
+ }
cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(UpgradedHeader, "1")
w.Header().Set("X-App", "kept")
- if name == "flush" {
+ switch name {
+ case "flush":
w.(http.Flusher).Flush()
+ case "return":
+ return
}
io.WriteString(w, "hello")
})))
@@ -218,7 +226,8 @@ func TestShimStripsTheMarkerOnImplicitHeaders(t *testing.T) {
}
defer resp.Body.Close()
got, _ := io.ReadAll(resp.Body)
- if _, ok := resp.Header[UpgradedHeader]; ok || resp.Header.Get("X-App") != "kept" || string(got) != "hello" {
+ if _, ok := resp.Header[UpgradedHeader]; ok || resp.StatusCode != http.StatusOK ||
+ resp.Header.Get("X-App") != "kept" || string(got) != want {
t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
}
})
@@ -228,36 +237,54 @@ func TestShimStripsTheMarkerOnImplicitHeaders(t *testing.T) {
// An upgrade the box answers without hijacking (the gate's 302, a 404, a
// 502) is an ordinary response, and it too loses an app-set marker.
func TestShimStripsTheMarkerOnAnUnhijackedUpgrade(t *testing.T) {
- cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set(UpgradedHeader, "1")
- w.WriteHeader(http.StatusNotFound)
- io.WriteString(w, "no such page")
- })))
- pr, pw := io.Pipe()
- defer pw.Close()
- req, _ := http.NewRequest("GET", "https://shop.example.com/cable", pr)
- req.Header.Set(UpgradeHeader, "websocket")
- resp, err := cc.RoundTrip(req)
- if err != nil {
- t.Fatalf("round trip: %v", err)
- }
- defer resp.Body.Close()
- got, _ := io.ReadAll(resp.Body)
- if _, ok := resp.Header[UpgradedHeader]; ok || resp.StatusCode != http.StatusNotFound || string(got) != "no such page" {
- t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
+ for _, tc := range []struct {
+ name string
+ write bool
+ wantStatus int
+ wantBody string
+ }{
+ {"404", true, http.StatusNotFound, "no such page"},
+ {"returns without writing", false, http.StatusOK, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set(UpgradedHeader, "1")
+ w.Header().Set("X-App", "kept")
+ if tc.write {
+ w.WriteHeader(http.StatusNotFound)
+ io.WriteString(w, "no such page")
+ }
+ })))
+ pr, pw := io.Pipe()
+ defer pw.Close()
+ req, _ := http.NewRequest("GET", "https://shop.example.com/cable", pr)
+ req.Header.Set(UpgradeHeader, "websocket")
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ got, _ := io.ReadAll(resp.Body)
+ if _, ok := resp.Header[UpgradedHeader]; ok || resp.StatusCode != tc.wantStatus ||
+ resp.Header.Get("X-App") != "kept" || string(got) != tc.wantBody {
+ t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
+ }
+ })
}
}
func TestShimRefusesABadToken(t *testing.T) {
for _, tc := range []struct {
- name, token string
- reaches bool
+ name string
+ tokens []string
+ reaches bool
}{
- {"space", "web socket", false},
- {"65 bytes", strings.Repeat("a", MaxUpgradeTokenLen+1), false},
- {"empty", "", false},
- {"64 bytes (control)", strings.Repeat("a", MaxUpgradeTokenLen), true},
- {"websocket (control)", "websocket", true},
+ {"space", []string{"web socket"}, false},
+ {"65 bytes", []string{strings.Repeat("a", MaxUpgradeTokenLen+1)}, false},
+ {"empty", []string{""}, false},
+ {"two marker lines", []string{"websocket", "websocket"}, false},
+ {"64 bytes (control)", []string{strings.Repeat("a", MaxUpgradeTokenLen)}, true},
+ {"websocket (control)", []string{"websocket"}, true},
} {
t.Run(tc.name, func(t *testing.T) {
var ran bool
@@ -269,7 +296,7 @@ func TestShimRefusesABadToken(t *testing.T) {
w.WriteHeader(http.StatusNoContent)
})))
req, _ := http.NewRequest("GET", "https://shop.example.com/cable", nil)
- req.Header[UpgradeHeader] = []string{tc.token}
+ req.Header[UpgradeHeader] = tc.tokens
resp, err := cc.RoundTrip(req)
if err != nil {
t.Fatalf("round trip: %v", err)
@@ -279,12 +306,12 @@ func TestShimRefusesABadToken(t *testing.T) {
defer mu.Unlock()
if tc.reaches {
if !ran || resp.StatusCode != http.StatusNoContent {
- t.Fatalf("token %q: status %d, handler ran %v; want it to reach the handler", tc.token, resp.StatusCode, ran)
+ t.Fatalf("tokens %q: status %d, handler ran %v; want it to reach the handler", tc.tokens, resp.StatusCode, ran)
}
return
}
if ran || resp.StatusCode != http.StatusBadRequest {
- t.Fatalf("token %q: status %d, handler ran %v; want 400 and no handler", tc.token, resp.StatusCode, ran)
+ t.Fatalf("tokens %q: status %d, handler ran %v; want 400 and no handler", tc.tokens, resp.StatusCode, ran)
}
})
}
@@ -487,29 +514,50 @@ func TestLoopAppliesConfigLimits(t *testing.T) {
}
// The reverse proxy waits for only one direction of its splice before its
-// handler returns; the other copy goroutine can still be writing. Once the
-// handler has returned, a Write on the hijacked conn must fail with
-// net.ErrClosed, never reach the finished stream's writer (x/net panics).
-func TestHijackedConnRefusesWritesAfterTheHandler(t *testing.T) {
- returned := make(chan struct{})
- writerErr := make(chan error, 1)
- cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- defer close(returned)
+// handler returns; the other copy goroutine can still be inside a Write.
+// The shim must hold ServeHTTP open until that Write ends (x/net panics on,
+// or recycles the state of, a writer used after its handler returned), and
+// every Write after that must fail with net.ErrClosed.
+//
+// Deterministic: the hub never reads until the end, so a Write larger than
+// its 4 MiB stream window (x/net's transport default) cannot finish. The
+// conn's hooks say when the writer is inside the guarded section and when
+// finish reaches the fence; the hub then waits for whichever comes first,
+// the fence or ServeHTTP returning, and only one of them can come while the
+// write is blocked.
+func TestShimHoldsTheStreamWhileAWriteIsBlocked(t *testing.T) {
+ const big = 5 << 20
+ entered := make(chan struct{})
+ fencing := make(chan struct{})
+ served := make(chan struct{})
+ writeDone := make(chan error, 1)
+ lateWrite := make(chan error, 1)
+ shim := Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Errorf("hijack: %v", err)
return
}
+ uc := conn.(*upgradedConn)
+ var once sync.Once
+ uc.hookWrite = func() { once.Do(func() { close(entered) }) }
+ uc.hookFence = func() { close(fencing) }
go func() {
- <-returned
- for {
- if _, err := conn.Write([]byte("x")); err != nil {
- writerErr <- err
- return
- }
+ n, err := conn.Write(make([]byte, big))
+ if err == nil && n != big {
+ err = fmt.Errorf("short write: %d of %d", n, big)
}
+ writeDone <- err
+ <-served
+ _, err = conn.Write([]byte("late"))
+ lateWrite <- err
}()
- })))
+ <-entered // the writer holds the stream: return under it
+ }))
+ cc := h2Pair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(served)
+ shim.ServeHTTP(w, r)
+ }))
pr, pw := io.Pipe()
defer pw.Close()
req, _ := http.NewRequest("GET", "https://shop.example.com/cable", pr)
@@ -519,13 +567,77 @@ func TestHijackedConnRefusesWritesAfterTheHandler(t *testing.T) {
t.Fatalf("round trip: %v", err)
}
defer resp.Body.Close()
- go io.Copy(io.Discard, resp.Body) // keep the stream's window open
select {
- case err := <-writerErr:
- if !errors.Is(err, net.ErrClosed) {
- t.Fatalf("a write after the handler returned failed with %v, want net.ErrClosed", err)
+ case <-served:
+ t.Fatal("ServeHTTP returned while a Write was blocked in the stream's writer")
+ case <-fencing:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the handler never returned to the fence")
+ }
+ select {
+ case err := <-writeDone:
+ t.Fatalf("the %d-byte write ended (%v) with the hub not reading", big, err)
+ default:
+ }
+ go io.Copy(io.Discard, resp.Body) // open the window: the write can end
+ select {
+ case <-served:
+ case <-time.After(10 * time.Second):
+ t.Fatal("ServeHTTP did not return once the blocked write could end")
+ }
+ if err := <-writeDone; err != nil {
+ t.Fatalf("the blocked write: %v, want it complete", err)
+ }
+ if err := <-lateWrite; !errors.Is(err, net.ErrClosed) {
+ t.Fatalf("a write after ServeHTTP returned: %v, want net.ErrClosed", err)
+ }
+}
+
+// A flush on a plain tunneled request reports the stream's error, as the
+// x/net writer does (http.ResponseController prefers FlushError): the shim
+// must not turn it into nil. Deterministic: the handler flushes only after
+// the hub's reset has cancelled its context.
+func TestShimFlushReportsTheStreamError(t *testing.T) {
+ for _, reset := range []bool{false, true} {
+ name := "live stream (control)"
+ if reset {
+ name = "reset stream"
}
- case <-time.After(5 * time.Second):
- t.Fatal("writes after the handler returned kept succeeding")
+ t.Run(name, func(t *testing.T) {
+ entered := make(chan struct{})
+ flushErr := make(chan error, 1)
+ cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if reset {
+ close(entered)
+ <-r.Context().Done()
+ }
+ io.WriteString(w, "hello")
+ flushErr <- http.NewResponseController(w).Flush()
+ })))
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, "GET", "https://shop.example.com/", nil)
+ rt := make(chan error, 1)
+ go func() {
+ resp, err := cc.RoundTrip(req)
+ if err == nil {
+ io.ReadAll(resp.Body)
+ resp.Body.Close()
+ }
+ rt <- err
+ }()
+ if reset {
+ <-entered
+ cancel() // RST_STREAM(CANCEL): x/net closes the stream, then the handler's context
+ }
+ err := <-flushErr
+ <-rt
+ if reset && err == nil {
+ t.Fatal("a flush on a reset stream returned nil, want the stream's error")
+ }
+ if !reset && err != nil {
+ t.Fatalf("a flush on a live stream: %v", err)
+ }
+ })
}
}