From 42ef932d58379a26543c7c30942c6b5b5dd2d2b0 Mon Sep 17 00:00:00 2001 From: MasterCoderK <8674856+DiamondGo@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:22:20 -0700 Subject: [PATCH 1/4] feat: add resumable batch transport for v0.2.3 --- README.md | 425 ++++++++++++++++++------ batch.go | 268 +++++++++++++++ batch_resume_test.go | 757 +++++++++++++++++++++++++++++++++++++++++++ client.go | 57 ++-- handler.go | 32 +- protocol.go | 22 +- resumable_client.go | 64 +++- resume_server.go | 14 +- resume_test.go | 54 ++- session.go | 4 + session_guard.go | 2 +- 11 files changed, 1516 insertions(+), 183 deletions(-) create mode 100644 batch.go create mode 100644 batch_resume_test.go diff --git a/README.md b/README.md index 480a064..5850dc5 100644 --- a/README.md +++ b/README.md @@ -1,177 +1,400 @@ # pollmux -HTTP 长轮询虚拟连接 + yamux 多路复用的共享传输库。 +An HTTP virtual connection and yamux multiplexing library for Go. It supports finite HTTP batches, streaming HTTP in either direction, and WebSocket transport, with optional session resumption after transport failures. -把"字节如何在两台机器之间流动"这一层单独抽出来:客户端、服务端 handler、以及 yamux 配置与重连循环这些容易各写一遍的胶水。 +pollmux handles **how bytes move between two machines**, not what those bytes mean or which application roles the endpoints play. Roles, endpoints, subdomains, and client identifiers belong in the opaque `meta` map. Applications supply authentication, routing, stream handling, and lifecycle policy. -pollmux 只管字节怎么在两台机器之间流动,不管这些字节是什么、也不管两端是什么角色。应用语义(role、endpoint、subdomain、client_id 之类)一律走不透明的 `meta`。 +## Installation ---- +Requires Go 1.25 or later, as declared in [go.mod](go.mod). -## 用之前必须先知道的几件事 +```sh +go get github.com/DiamondGo/pollmux +``` -### 一、`EnableKeepAlive` 必须为 false +The library uses HashiCorp yamux and coder/websocket. A client connection implements an ordered byte stream through [`Conn`](client.go#L33); pass it to [`ClientSession()`](yamux.go#L60) on the end that opens yamux streams, and pass the server-side [`Session`](session.go#L24) to [`ServerSession()`](yamux.go#L65) on the end that accepts them. These roles are application choices, not necessarily HTTP client/server roles. -这不是可选优化,是**正确性前提**。请始终用 `pollmux.YamuxConfig()` 构造 yamux 配置,或至少保证这一项为 false。 +## Before deploying -yamux 的 keepalive 会周期性发 PING 并要求对端在 `ConnectionWriteTimeout`(默认 10s)内回 PONG。但在长轮询传输上,一次 PING-PONG 往返需要: +- **Keep yamux keepalive disabled.** Use the session helpers above, or [`YamuxConfig()`](yamux.go#L40). Enabling yamux PING/PONG can close a healthy polling connection. +- **Check proxy behavior, not just negotiated capabilities.** Streaming HTTP requires live forwarding of request/response bodies. An upload probe can reject some broken paths but cannot prove that real traffic will work. Prefer WebSocket where ordinary HTTP bodies are buffered, or use finite batches. +- **Protect every session endpoint with the same authentication middleware**, including resume. The connect authentication hook does not authenticate later requests. +- **Resume is bounded, in-memory recovery**, not persistence or an unlimited outage guarantee. Preserve replica affinity, budget replay memory, and enable resume on both hops of a relay if streams must survive either hop failing. -1. PING 写进本地发送缓冲 → 等下一次 POST 把它送出去; -2. 服务端 yamux 处理后把 PONG 写进它的下行管道; -3. PONG 要等客户端**下一次 poll** 才被取回 —— 而此刻很可能有一个 poll 正挂在服务端等待,最长可挂 `poll_timeout`(默认 30s)。 +## Configuration and routing -30s > 10s,于是 yamux 在链路完全健康的情况下断定"连接已死"并关闭会话。**存活性完全由 poll 循环承担**:poll 的 `ResponseHeaderTimeout` 被设为服务端下发的 `poll_timeout` 加一段宽限,超时即判定传输失败;服务端侧则靠 `session_timeout` 与 `pollInFlight` 感知客户端消失。 +All handlers for a deployment should share one store, configuration, and hook set. The default path prefix is `/tunnel`. -这个约束很容易在每个建 yamux 会话的地方靠一句注释重复传递。收进 `YamuxConfig()` 就是为了它只存在一处。 +| Method | Path | Handler | +|---|---|---| +| POST | `/tunnel/connect` | [`ConnectHandler()`](handler.go#L288) | +| POST | `/tunnel/{id}/poll` | [`PollHandler()`](handler.go#L422), for both HTTP directions | +| DELETE | `/tunnel/{id}` | [`DeleteHandler()`](handler.go#L836) | +| GET | `/tunnel/{id}/ws` | [`WebSocketHandler()`](websocket.go#L62), when WebSocket is offered | +| POST | `/tunnel/{id}/resume` | [`ResumeHandler()`](resume_server.go#L208), when resume is offered | -`PollMode = "stream"` 下结论不变,但机制更简单:流式响应内部本来就周期性地发心跳帧(见下),这本身就是一条应用层 keepalive,yamux 自己的 PING/PONG 彻底没有存在必要——但仍然必须保持关闭,理由和 batch 模式一样:yamux 不知道底下是 batch 还是 stream,打开 keepalive 唯一的效果就是白白重新触发上面这套超时问题。 +The following is a **routing helper for an existing Go server**, not a complete application. It requires imports for `net/http` and `github.com/DiamondGo/pollmux`. Supply a non-nil authentication/authorization middleware and application hooks; the connect hook should start application session processing asynchronously rather than wait for streams before returning. Mount the returned handler at the server root, and call the returned stop function during shutdown. -### 二、上下行吞吐是不对称的(在 batch 模式下,以及在只开了一半流式的情况下) +```go +func tunnelRoutes( + hooks pollmux.Hooks, + authenticate func(http.Handler) http.Handler, +) (http.Handler, func()) { + store := pollmux.NewSessionStore() + cfg := pollmux.ServerConfig{ + PollMode: pollmux.PollModeStream, + EnableWebSocket: true, + EnableResume: true, + } -两个方向走的是**不同机制**,性能特征因此不同——但这只在你只开了一个方向的流式模式时才成立。两个方向都开(见下一节)之后,两边其实是同一种机制。 + mux := http.NewServeMux() + mux.Handle("POST /tunnel/connect", pollmux.ConnectHandler(store, cfg, hooks)) + mux.Handle("POST /tunnel/{id}/poll", pollmux.PollHandler(store, cfg, hooks)) + mux.Handle("DELETE /tunnel/{id}", pollmux.DeleteHandler(store, cfg, hooks)) + mux.Handle("GET /tunnel/{id}/ws", pollmux.WebSocketHandler(store, cfg, hooks)) + mux.Handle("POST /tunnel/{id}/resume", pollmux.ResumeHandler(store, cfg, hooks)) -| 方向 | 机制 | 受什么限制 | -|---|---|---| -| 上行(客户端 → 服务端,`PreferStreamUpload = false`) | 数据到达即发一个离散 POST,短窗口内合并,同一时刻只有一个请求在途 | **每 RTT 最多发出一个 `max_send_bytes` 分片** | -| 上行(客户端 → 服务端,`PreferStreamUpload = true`) | 一条长驻 POST 的请求体保持打开,数据随到随发 | 链路带宽本身,不再逐 RTT 摊销 | -| 下行(服务端 → 客户端,`PollMode = "batch"`) | 长轮询响应,一次最多带回 `poll_buffer_bytes` | **每 RTT 最多一个缓冲区** | -| 下行(服务端 → 客户端,`PollMode = "stream"`) | 长轮询响应保持打开,数据随到随推 | 链路带宽本身,不再逐 RTT 摊销 | + stop := pollmux.StartSweeper(store, cfg, hooks) + // One wrapper protects connect AND every subsequent session request. + return authenticate(mux), stop +} +``` + +The standard router supplies the `id` path value. With another router, configure [`ServerConfig.SessionIDFunc`](handler.go#L60) to extract it. Middleware must preserve streaming, WebSocket upgrade, and response-controller capabilities; do not wrap these routes in middleware that buffers entire responses. + +For an **existing client function**, with `ctx`, `baseURL`, and `token` supplied by the application, configure and connect as follows: + +```go +connector := &pollmux.Connector{ + BaseURL: baseURL, + AuthToken: token, + PreferWebSocket: true, + PreferStream: true, + PreferResume: true, + // UploadStreamPreference is left empty: probe HTTP upload streaming + // if WebSocket is not negotiated and the server offers streamed uploads. +} +conn, err := connector.Connect(ctx) +if err != nil { + return err +} +defer conn.Close() + +muxSession, err := pollmux.ClientSession(conn) +if err != nil { + return err +} +defer muxSession.Close() +// Open and handle application streams here, before this function returns. +``` + +This client snippet belongs inside a function returning an error, with imports for `github.com/DiamondGo/pollmux` and any application dependencies. Keep the connector for subsequent reconnects. Closing the connection intentionally deletes its server session; it is not how to trigger resume. + +### Selecting HTTP directions + +The server offers both HTTP streaming directions with [`ServerConfig.PollMode`](handler.go#L70) set to [`PollModeStream`](handler.go#L25). There is no separate server-side upload-stream switch. The directions are nevertheless negotiated **independently**: request field `prefer_stream_mode` selects response field `poll_mode`, while `prefer_stream_upload` selects `upload_stream_mode`. An absent upload mode means batch, so a server predating upload streaming can ignore the new preference without receiving frames it cannot understand. + +To select a specific HTTP combination, leave [`Connector.PreferWebSocket`](client.go#L141) false and use this table. The server must offer streaming for any requested stream direction. + +| Download: server → client | Upload: client → server | [`PreferStream`](client.go#L112) | [`UploadStreamPreference`](client.go#L126) | +|---|---|---|---| +| Batch | Batch | false | `"batch"` | +| Stream | Batch | true | `"batch"` | +| Batch | Stream | false | `"stream"` | +| Stream | Stream | true | `"stream"` | + +An empty upload preference is the default **auto-probe** setting, not forced streaming. It requests upload streaming even when the download preference is false. To guarantee pure batch, explicitly choose `"batch"` for uploads, or use a batch-only server. Forced `"stream"` skips the probe and should only be used on a verified path. + +All four HTTP combinations can resume when both endpoints support the batch-resume capability. WebSocket is negotiated separately and, when selected, replaces both HTTP directions. + +## yamux correctness and memory + +### Keepalive must stay disabled + +[`YamuxConfig()`](yamux.go#L40) sets [`EnableKeepAlive`](yamux.go#L44) to false. This is a correctness requirement, not an optional optimization. yamux's keepalive expects a PING/PONG round trip within its connection write timeout, normally 10 seconds. Batched transport can delay that exchange across polling boundaries; the default long-poll timeout is 30 seconds. A healthy transport can therefore be declared dead by yamux. + +Liveness belongs to the underlying transport instead: + +- Batch polls wait for headers for the negotiated poll timeout plus the client's grace period. +- Streamed downloads use heartbeats and a read-idle watchdog. +- Streamed uploads have a server-side read-idle watchdog. +- WebSocket has application heartbeats and read-idle detection in both directions. +- The server uses in-flight request tracking, session expiry, and, where negotiated, resume grace to manage session lifetime. + +Keep yamux keepalive disabled for streaming and WebSocket too. Switching transport must not accidentally reintroduce a second, incompatible liveness policy. + +### Stream windows are not free memory + +The configured [`MaxStreamWindowSize`](yamux.go#L27) is 256 KiB, yamux's **minimum accepted window**, not just a tunable default. Lowering it below 256 KiB is rejected by yamux. A smaller window would also lower the amount one stream could have in flight per RTT. + +The flow-control buffering budget is roughly window size × concurrent streams: **256 KiB × 256 streams ≈ 64 MiB per tunnel**, multiplied by the number of tunnels in a multi-tenant deployment. This is not a hard bound on total process memory: pipes, replay buffers, HTTP bodies, and application state add overhead. [`BufferedPipe`](pipe.go#L23) itself has no backpressure; normal yamux flow control is what bounds ordinary stream traffic. Applications writing arbitrary bytes directly to a connection cannot assume the same protection. + +Limit concurrent streams rather than trying to shrink the window below yamux's floor. Use [`BufferedPipe.HiWater()`](pipe.go#L65), [`Session.HiWater()`](session.go#L299), and [`ServerConfig.HighWaterWarn`](handler.go#L65) to observe actual buffering. + +## Transport behavior and caveats + +### Finite HTTP batches + +HTTP uploads and downloads are independent requests to the poll endpoint: + +- `X-Send-Only: true`: one finite upload, coalesced from queued writes, followed by an immediate response. Only one upload is in flight at a time. +- `X-Receive-Only: true`: one long-poll response, containing at most the negotiated `poll_buffer_bytes`. An idle poll returns 204, then the client polls again. + +Uploads never wait for the downstream long poll. The default client poll interval is zero: waiting belongs inside the server's long poll, not an extra client sleep. A configured interval is applied after idle responses, not after data. + +For **resumable** batch polls, the header timeout is `poll_timeout_ms + PollGrace`. A whole-request timeout of `DialTimeout + poll timeout + PollGrace` also bounds body consumption: receiving headers and then stalling halfway through a response is a transport failure, not an indefinitely healthy poll. Batch uploads use the client's send timeout. See [resumable batch wire behavior](#resumable-batch-wire-behavior) for offsets and replay. + +### Streamed HTTP downloads + +Downloads stream only when the client requests them and the server offers them. Otherwise they silently fall back to batch. Unknown or absent negotiated download modes are treated as batch, supporting older peers without changing [`ProtocolVersion`](protocol.go#L22). + +The server flushes response headers immediately, then sends length-prefixed data and control frames. The important controls are: -早期版本这里写的是"上行基本不受 RTT 限制"——**这个结论是错的**,已经用 benchmark 证伪:上行原来的离散 POST 实现和 batch 模式下行是同一种"一个 RTT 一个分片"的结构,只是分片大小换成了 `max_send_bytes` 而不是 `poll_buffer_bytes`。`bench_test.go` 的 `BenchmarkUploadThroughput_Batch_150msRTT` 在这台开发机上量到约 1.9 MB/s,和下面 batch 下行的量级完全一致,不是巧合。 +- [`HeartbeatInterval`](handler.go#L78), default 10 seconds: send a heartbeat when idle. +- [`StreamMaxDuration`](handler.go#L92), default 45 seconds: end a response cleanly and immediately open the next one. Rotation is checked between complete frames, not in the middle of a frame; allow timing margin. -batch 模式下行的含义要算一下:`poll_buffer_bytes` 默认 256KB,在 150ms RTT 下单条隧道下行上限约 **1.7 MB/s**。这个上限来自"离散 POST + 批量响应"这个模型本身,不是实现缺陷。彻底解法是流式化:下行把 `ServerConfig.PollMode` 设为 `"stream"`,上行把 `PreferStreamUpload`/`UploadStreamMode` 也谈成 `"stream"`(两者通常一起开,见下一节),响应/请求体都不再等一整个 RTT 攒够一个缓冲区才收发,而是保持连接打开,数据一到就编帧推送。仓库自带的 `bench_test.go` 在这台开发机上的一次实测(150ms RTT,8MB payload): +Keep the stream duration **comfortably below the tightest applicable proxy timeout** on the deployed path. Local validation requires the configured stream duration to be at least twice the heartbeat interval, but cannot discover a CDN's or reverse proxy's timeouts. Configure those explicitly and verify actual forwarding. The server sends `X-Accel-Buffering: no` as a best-effort hint, not a guarantee that every intermediary disables buffering. -| | batch | stream | +Since headers arrive immediately, the client's response-header timeout only covers setup. A separate watchdog resets on every complete frame, including heartbeats; no frame within heartbeat interval + [`Connector.PollGrace`](client.go#L89), default 10 seconds, fails the transport. + +HTTP stream framing distinguishes: + +| Frame | Meaning | +|---|---| +| [`frameData`](frame.go#L15) | Ordinary, non-resumable payload | +| [`frameHeartbeat`](frame.go#L16) | Idle liveness signal | +| [`frameEnd`](frame.go#L20) | Benign request/response rotation; reopen immediately on the same session | +| [`frameGone`](frame.go#L26) | Server session is closed; do not keep polling it or try to revive it | +| [`frameSeqData`](frame.go#L37) / [`frameAck`](frame.go#L36) | Numbered payload / cumulative acknowledgment on resumable sessions | + +A clean body end at a frame boundary is also a benign rotation. A partial frame or read error is a transport failure. Session-gone is equivalent to HTTP 410, **not** an idle heartbeat or normal rotation. Confusing these conditions would leave clients polling a dead session forever. + +### Streamed HTTP uploads and the auto probe + +Streamed uploads use a long-lived POST with `X-Send-Stream: true`. The server consumes complete frames and delivers them as they arrive, rather than waiting for the entire request to finish. The directions share the negotiated heartbeat and stream-duration settings. + +**The writer controls rotation.** The server rotates downstream responses; the client rotates upstream requests, checking duration only after finishing a complete frame. A server ending an upload arbitrarily in the middle of a frame could abandon bytes already removed from the client's queue and desynchronize yamux. Upload-side session closure is reported with HTTP 410, not a downstream-only gone frame. On resumable connections, failure of either direction cancels its companion before recovery; upload-side detection is not necessarily instantaneous and may wait until another write or heartbeat. The server refreshes a read deadline after each received frame. + +[`Connector.UploadStreamPreference`](client.go#L126) has three settings: + +| Setting | Behavior | +|---|---| +| `"batch"` | Do not request upload streaming; no probe | +| `"stream"` | Use it if negotiated; no probe; requires a verified streaming path | +| `""` (default) | Request it, then probe if negotiated; fall back when the probe fails | + +The automatic probe is bounded by [`UploadProbeTimeout`](client.go#L129), default 15 seconds. It sends more than one yamux window of filler through a real framed upload, ends it normally, and waits for the actual 200 response. `X-Send-Stream-Probe` tells the server to discard filler rather than deliver it to the application. Explicit batch/stream preferences avoid this probe latency; auto mode can add up to the probe timeout to a connection attempt. + +For a session negotiated as resumable, **a failed probe causes a best-effort DELETE of the original session and a fresh connect with batch uploads**. Its upload mode is not changed in place. Resume remains requested only if the original response echoed `batch_resume`; an older server without that capability falls back without resume. The download preference is preserved. For a non-resumable connection, a failed probe simply selects ordinary batch uploads for that connection. Streaming is not periodically re-probed on an established connection. + +**A passing probe is not proof of compatibility.** Some proxies, observed with Cloudflare standard/non-Enterprise HTTP proxy paths, buffer long-lived request bodies before forwarding them. With yamux, filling a stream window while the peer cannot receive bytes or return window updates can produce a permanent hang, not merely lower throughput. A short, continuous connect-time probe may pass while a long-lived, intermittently written production body still stalls. This has also been observed in real deployments. Verify the entire path under realistic bidirectional traffic, or choose WebSocket/finite batches instead. + +### WebSocket + +Enable [`ServerConfig.EnableWebSocket`](handler.go#L101) and request [`Connector.PreferWebSocket`](client.go#L141), wire field `prefer_websocket`. If the server does not offer it, negotiation silently falls back to the separately negotiated HTTP directions. When selected, `transport` is `"websocket"`; the upload probe is skipped. + +WebSocket is **an alternative transport, not a third poll mode**. After connect, one upgrade at `/tunnel/{id}/ws` carries both directions; the poll/send-stream loops are not used. DELETE still handles intentional teardown, and resumable connections use the resume endpoint before attaching a replacement WebSocket. + +Ordinary WebSocket binary messages contain a one-byte type tag plus payload; native message boundaries replace HTTP's length prefix. Resumable messages add byte offsets and acknowledgments. WebSocket uses its native close mechanism rather than HTTP stream end/gone frames. Without resume, an unexpected close, including a clean peer close, signals transport failure; with resume, transport loss triggers recovery of the same session if possible. + +Heartbeats use the negotiated heartbeat interval. Each side has a read-idle watchdog: heartbeat interval + client poll grace, or heartbeat interval + the server's internal 10-second margin. There is **no forced stream-duration rotation** for WebSocket. The connect response currently includes `stream_max_duration_ms`, but the WebSocket path does not use it. + +Proxies commonly forward WebSocket messages live even when they buffer ordinary HTTP bodies; this is why WebSocket is useful on those paths. It still requires upgrade support and is still subject to intermediary lifetime limits and network failures. Heartbeats and HTTP stream rotation do not prevent an intermediary from killing a connection at its maximum age. + +## Resuming the same session after transport loss + +### Opt-in and backward-compatible negotiation + +Resume requires all of the following: + +1. [`Connector.PreferResume`](client.go#L150) is true. +2. [`ServerConfig.EnableResume`](handler.go#L111) is true. +3. [`ResumeHandler()`](resume_server.go#L208) is mounted at `POST /{prefix}/{id}/resume` behind the **same authentication middleware as poll, DELETE, and WebSocket**. +4. The connect response actually negotiates `resumable: true`. + +The API switches remain the same: the client requests `prefer_resume` and the server responds with `resumable`. New clients automatically send [`ConnectRequest.BatchResume`](protocol.go#L186), wire field `batch_resume`, when requesting resume. This capability **does not enable resume on its own**. New servers echo [`ConnectResponse.BatchResume`](protocol.go#L309) only for resumable sessions when the client advertised it. + +| Negotiated transport | With batch-resume capability | Without batch-resume capability | |---|---|---| -| 下行 `BenchmarkThroughput_*` | ~1.0 MB/s | ~28.7 MB/s | -| 上行 `BenchmarkUploadThroughput_*` | ~1.9 MB/s | ~30 MB/s | +| Batch upload + batch download | Resumable | Not resumable | +| Batch upload + stream download | Resumable | Not resumable | +| Stream upload + batch download | Resumable | Not resumable | +| Stream upload + stream download | Resumable | Original stream resume supported | +| WebSocket | Resumable | Original WebSocket resume supported | -两个方向流式化之后都不再随 RTT 线性下降,量级也基本对齐。这是本地回环 + 人为延迟的模拟数据,不是真实链路的数字;生产环境请在自己的部署上重新跑一遍这些 benchmark(`go test -run '^$' -bench Benchmark -benchtime=1x`)。 +Every resumable entry still requires both resume switches. This additive capability protects older resumable clients from receiving a batch wire format they do not understand. Older servers may support only two-way-stream/WebSocket resume, or ignore resume entirely. Absent capability must never be interpreted as permission for resumable batches; absent `resumable` means ordinary non-resumable operation. The protocol version remains 1. -同一个数字也出现在 yamux 的流窗口上:yamux 强制 `MaxStreamWindowSize ≥ 256KB`(`mux.go:83`,地板值不是默认值),所以两处的 256KB 是对齐的。调小任何一个都会成为新瓶颈。 +### Reliability and lifecycle -代价是内存:256KB × 256 并发流 = **64MB/隧道**最坏值,多租户下要乘以隧道数。这个界由 yamux 的流控提供(`BufferedPipe` 自身没有背压),要压低就调并发流上限,不是调窗口。`BufferedPipe.HiWater()` 可以读到实际水位,用它判断离最坏值有多远。 +Without resume, transport loss ends the virtual connection, and a reconnect creates a new session ID and a new yamux session. Existing application streams cannot survive that replacement. -### 三、流式模式(`PollMode = "stream"`) +With resume, a reliable byte layer sits below yamux. Each direction has absolute byte offsets, cumulative acknowledgments, and a replay buffer. Bytes remain retained until the peer acknowledges receiving them; a successful local HTTP write alone is not an acknowledgment. Stream/WebSocket transports carry numbered data and ACK frames, with ACKs sent alongside reverse traffic/heartbeats and an eager ACK wakeup at half a yamux window. -开启方式:服务端 `ServerConfig.PollMode = pollmux.PollModeStream`,客户端 `Connector.PreferStream = true`。两边都要设——协商在 connect 时一次性谈好,按"客户端请求 && 服务端支持"决定,任一边不满足都静默降级到 `batch`,不报错。旧服务端(不认识 `prefer_stream_mode` 字段)和旧客户端(不发这个字段)完全无感知,`ProtocolVersion` 不需要跟着升级。 +On transport failure, the client stops both directions, then sends `POST /{prefix}/{id}/resume` with its protocol version and `recv_offset`: the number of downstream bytes received contiguously. The server first cancels and waits out old attachments, then answers with its contiguous upstream `recv_offset`. Each side replays from the other side's offset before sending new bytes. Duplicate or overlapping replay is discarded; gaps and impossible acknowledgments are rejected rather than corrupting yamux's byte stream. Only one transport owns each direction at a time, including during a resume handshake. -新增两个只在流式模式下生效的旋钮,和其余参数一样由服务端权威下发(见"参数下发"一节): +**The session ID, server session, and yamux session stay the same.** A successful recovery is internal to the connection and does not close its transport-failed signal. Reads can block through the outage. Transport-level writes queue locally without waiting for the network, avoiding yamux's connection write timeout during recovery, but **application/yamux stream writes can still block on flow control** once their window is exhausted. Application contexts, stream deadlines, and business timeouts still apply; resume does not suspend or extend them. This is ordered byte-stream recovery, not a guarantee that an application has processed or committed a business operation. -- `ServerConfig.HeartbeatInterval`(默认 10s):下行响应空闲多久发一次心跳帧,语义上相当于 batch 模式里 `PollTimeout` 的角色。 -- `ServerConfig.StreamMaxDuration`(默认 45s):一条流式响应最长占用多久,到点服务端主动干净结束、客户端立即重开一条。这不是流控,是为了避开链路上中间代理(nginx、Cloudflare 之类)自己的 idle/read 超时——**这个值必须留在你部署链路里最紧的那个中间层超时之下**,pollmux 自己检测不到外部代理的超时设置,量清楚这件事是使用者的责任(可以参考 `ServerConfig.check()` 里 `StreamMaxDuration >= 2×HeartbeatInterval` 的自检,同样的道理,但那只管本地两个参数是否自洽,管不到外部代理)。 +During a valid detached grace period, the server does not evict the session using ordinary idle timeout. [`CloseSessionIfNoPollInFlight()`](handler.go#L888) also treats it as busy, so a reaper using that helper need not learn a separate resume policy. Applications can inspect [`Session.Resumable()`](session.go#L122) and [`Session.ResumeDeadline()`](session.go#L132) for monitoring. Explicit session close, DELETE, and shutdown still terminate it; resume never resurrects a deliberately closed session. -客户端侧多一层存活性检测:流式响应的 HTTP 响应头几乎立刻返回(不像 batch 要等一整个长轮询超时),所以 `ResponseHeaderTimeout` 只覆盖连接建立,不再是"链路是否还活着"的信号;取而代之的是一个读空闲看门狗,每收到一帧(心跳或数据)就重置,超过 `HeartbeatInterval + PollGrace` 没收到任何帧就判定传输失败。 +### Resumable batch wire behavior -响应体内部有四种帧:`frameData`(数据)、`frameHeartbeat`(心跳)、`frameEnd`(良性结束——`StreamMaxDuration` 到期轮转,会话仍然活着,客户端应立即重开一条新的流式轮询)、`frameGone`(致命结束——会话已经在服务端被关闭,重开轮询只会对着一个不存在的 session id 反复拿到同样的 `frameGone`,客户端必须把它当成 batch 模式里 410 的等价物,触发 `TransportFailed` 走重连,而不是重开轮询)。这两种"结束"语义不同,帧类型也必须不同——`v0.1.0` 曾经两者共用 `frameEnd`,导致会话被关闭后客户端分不清,一直对着死会话重开轮询,`v0.1.1` 起分离为独立帧类型修复。 +Resumable batches are **raw, bounded, finite HTTP bodies**, not framed streams hidden inside batch requests. Upload payloads remain bounded by `max_send_bytes`; download payloads remain bounded by `poll_buffer_bytes`. A buffering proxy can forward these finite bodies without supporting live request-body streaming. -### 四、上行流式模式 +| Message | Required offset headers | +|---|---| +| Send-only batch request | `X-Send-Offset`: absolute starting upload byte offset; `X-Recv-Offset`: cumulative downstream acknowledgment | +| Receive-only batch request, with an empty body | `X-Recv-Offset`: cumulative downstream acknowledgment | +| 200 batch poll response | `X-Send-Offset`: absolute starting download byte offset; `X-Recv-Offset`: cumulative upstream acknowledgment | +| Successful batch upload response or 204 idle poll response | `X-Recv-Offset`: cumulative upstream acknowledgment | -上一节的流式化只覆盖下行。上行(客户端 → 服务端)默认仍然是离散 POST——"二、上下行吞吐是不对称的"里已经说明,这不是"基本不受 RTT 限制",而是和 batch 下行同构的瓶颈,只是分片大小不同。上行流式化把同一套思路应用到反方向。 +Offsets are unsigned decimal byte counts, present even when zero. Each required header must have exactly one value; missing, malformed, duplicated, or ambiguous values are rejected. Every batch request and successful batch response carries the cumulative receive acknowledgment, **including 204**. Mixed HTTP sessions use these headers on the batch direction and numbered frames/ACKs on the streaming direction. -开启方式:客户端 `Connector.PreferStream = true` 会同时请求下行和上行两种流式(内部分别置位 `ConnectRequest.PreferStreamMode` 和 `PreferStreamUpload`),服务端只要 `ServerConfig.PollMode = pollmux.PollModeStream` 就同时支持两个方向——**没有单独的"只支持上行"开关**,一个部署要么两个方向都提供,要么都不提供。两个方向仍然在协议层面**独立协商**(`ConnectResponse.PollMode` 和 `UploadStreamMode` 是两个字段),纯粹是为了让新旧版本的客户端/服务端可以任意混搭:一个只认识下行流式的旧服务端,收到不认识的 `prefer_stream_upload` 字段会直接忽略,新客户端读到 `UploadStreamMode` 是空字符串就照常退回离散 POST 上行,不会去发它读不懂的请求。 +The server reads an entire upload successfully before accepting its data into the reliable byte stream. An incomplete upload is not partially delivered. The client likewise consumes and validates a complete bounded poll body before delivery; an explicit response length detects truncation. Upload success responses must have an empty body and be consumed successfully before their acknowledgment is accepted. -机制上行方向不是对下行 `pollStream` 简单镜像,因为上行方向读者和写者是反过来的:客户端是写者(把数据编帧写进请求体),服务端是读者(`PollHandler` 收到 `X-Send-Stream: true` 后转给 `pollSendStream`,循环解帧、边收边喂给应用层,不等请求结束)。这个角色反转带来一个关键设计决定: +If an upload was accepted but its 200 response was lost, or a download was truncated after leaving the server queue, the sender still retains the unacknowledged bytes. The client performs the resume handshake **before retransmitting**, and the absolute offsets prevent duplicate delivery while replaying whatever is missing. A raw batch retry without the handshake is not the client's recovery algorithm. -**轮转(`StreamMaxDuration` 到期后开下一条请求)永远由写者决定,不是读者。** 下行方向服务端是写者,服务端说了算;上行方向客户端是写者,改成客户端说了算——客户端在写完一个完整的数据/心跳帧之后才检查是否到点,从不在帧中途做这个决定。原因是正确性:如果读者单方面决定"够了,我要回应了",它没法保证自己是在帧边界上做这个决定,一旦在帧中途把响应发回去,请求体会被 net/http 当成没读完直接把连接关掉,此时数据可能已经从本地缓冲区取出、正在传输路上,会真实丢失、造成 yamux 流失步。写者永远知道"刚完成一个完整单元、现在切换安全"这件事,读者不知道。 +Pure-batch resumable sessions must have [`Connector.PollInterval`](client.go#L86) **strictly below the negotiated resume grace**; connect rejects an interval reaching that grace. Between finite requests there may be no attachment, so a healthy client must poll again before its detached session expires. The default zero interval is recommended. -其他要点: +### Recovery limits and failure cases -- `frameGone` 在上行方向用不上——它在下行方向的语义是"服务端主动通知会话已关闭",但上行方向服务端是读者,没有主动写请求体的机会。会话被服务端关闭这件事,上行方向靠 410 状态码表达(`pollSendStream` 发现 `Session` 已关闭就直接回 410,客户端按老规矩当传输失败处理),不需要新的帧类型。 -- 上行方向"会话已死"的检测**不是独立的**,是从下行那条腿"借"来的:两个方向总是一起协商、一起打开,会话被关闭时下行那条腿的 `frameGone` 会先感知到并触发 `c.fail()`,进而通过共享的 `context` 取消掉上行这条腿正在进行的请求。上行自己的 410 检测只是兜底,不是第一道防线——独立触发时最长要等到下一次心跳(写者试图往一个已经断开的管道里写心跳帧时才会发现),不是瞬时的。 -- 服务端读上行请求体时用 `http.ResponseController.SetReadDeadline` 做空闲看门狗(每收到一帧就重置),这是 Go 1.20+ 的标准机制,不需要额外的 context/goroutine 拼接。 +| Setting | Default / limit | +|---|---| +| [`ServerConfig.ResumeGrace`](handler.go#L119) | 30 seconds detached; hard maximum 5 minutes; configuration above the maximum panics | +| [`MaxReplayBytes`](handler.go#L126) on the server and [`Connector.MaxReplayBytes`](client.go#L155) on the client | 16 MiB per outgoing direction; independently configured, not negotiated | +| [`ServerConfig.MaxDetachedResumable`](handler.go#L133) | 1,024 detached resumable sessions; the sweeper evicts longest-detached first; negative disables the cap | -详见 pollmux 仓库的 `DESIGN.md`(不随库发布,是给下一个改这块的人看的实现笔记)。 +Start the configured [`StartSweeper()`](handler.go#L902) to enforce grace expiry and the detached-session cap. A detached session retains application state and replay memory, so grace and population limits are important memory controls, not just retry tuning. The replay limit covers retained, transmitted-but-unacknowledged bytes, not all queued data or total session memory. Normal yamux windowing helps bound pending traffic per active stream, but concurrency still matters. -#### 连接期自动探测:`Connector.UploadStreamPreference` +Recovery ends and the client signals transport failure for a fresh-session reconnect when, for example: -生产环境实测过一个前提:并不是每条链路都能如实转发一个长驻、持续写入的 chunked 请求体。Cloudflare 标准(非 Enterprise)套餐对普通 HTTP 代理走的是"攒完整个请求体再转发给源站"的模型,不支持把一个还没结束的请求体实时流式转发——一旦上行方向的 yamux 单流未确认数据超过 `MaxStreamWindowSize`(256KB),发送方等待的窗口更新永远等不到,整条隧道会**永久挂死**,不是变慢。这不是理论风险,是线上复现过的真实故障。 +- The server session is missing, expired, deleted, or closed, or the resume endpoint definitively refuses it. +- Transient resume failures outlast the advertised `resume_grace_ms`. Detection and retries must fit within the server's actual retention window; a client-side retry budget does not extend a server deadline. +- A replay buffer exceeds its configured limit. The current transport may continue working, but the session loses resumability; its next transport loss cannot be repaired. +- A byte gap, impossible ACK, or resume offset outside the retained range makes replay unsafe. +- Repeated successful handshakes produce unusable replacement transports: five consecutive failures lasting less than two seconds **without peer-visible byte progress** trip a stability guard. Progress or a sufficiently stable transport resets it. -`Connector.UploadStreamPreference` 是三态开关,用来在"能获得流式上行的吞吐"和"不确定链路是否支持时不要挂死生产"之间做选择: +Transient resume retries use jittered exponential waits, starting at 250 milliseconds and capped at two seconds, within the advertised grace budget. A definitive 4xx resume refusal is not retried for that session. -- `PollModeBatch`:永远不用上行流式,哪怕服务端提供。`ConnectRequest.PreferStreamUpload` 直接发 `false`,不协商、不探测。 -- `PollModeStream`:只要服务端提供就直接用,不做探测。只在你已经用其他方式确认过这条链路(有没有经过 Cloudflare 之类的缓冲代理)能实时转发长驻请求体时才应该这么配置。 -- `""`(默认,自动):协商成功后,`Connect` 先做一次一次性探测——通过一个真正的 send-stream 请求推送超过 `MaxStreamWindowSize` 的填充数据、正常以 `frameEnd` 结束、等真实响应,整个过程套一个 `Connector.UploadProbeTimeout`(默认 15s,可调)的硬超时。探测在超时内正常收到 200 就采用流式上行;超时或出错(`context deadline exceeded` 是最常见的一种,代表这条链路没在超时内把请求转发到源站)就退回离散 POST,这条连接的生命周期内不会再重试流式。探测是有意做成"和生产真实一条 send-stream 请求完全同形"的——推送、结束、等响应——而不是发明一套"请求体还开着就提前应答"的专用协议:那种设计在本地回环网络下用 Go 标准库实测就不可靠(客户端能否在请求体写完之前先读到响应头,取决于 Go/内核缓冲区的内部实现细节,不是文档承诺的行为),线上环境只会更不可控。探测请求带 `X-Send-Stream-Probe` 头,服务端据此丢弃这些帧而不写入会话,不会污染真实数据。 +Sessions and replay buffers are **process-local and not persistent**. A server restart loses them. Load-balanced deployments require affinity so connect, poll/upload, resume, DELETE, and WebSocket requests reach the process holding that session. Resume does not migrate sessions across replicas. In a consumer ↔ broker ↔ provider relay, **both hops need resume** for streams to survive a transport failure on either hop. -三态里显式配置的两种(`batch`/`stream`)总是零延迟;只有默认的自动档会在每次 `Connect` 上多付出一次探测的时间成本(成功时通常几毫秒,失败时最多 `UploadProbeTimeout`)。 +### Authentication boundary -### 五、WebSocket 传输模式 +[`Hooks.Authenticate`](handler.go#L249) authenticates **connect requests only**. It is not called by poll, DELETE, WebSocket, or resume handlers. Session IDs are random 128-bit values, but the application must still apply the same credential and session-authorization policy to **all** those routes. The client's bearer token is sent on subsequent requests as well. -上面两节解决的是"轮询本身有 RTT 瓶颈";WebSocket 传输模式解决的是另一个、更根本的问题:**有些中间代理对普通 HTTP 干脆不支持真正的双向流式转发**。 +A caller reaching resume with an out-of-range `recv_offset` permanently invalidates that session's resumability and gets 409. This is intentional: letting an inconsistent peer guess offsets until one happens to fit could silently replay the wrong bytes. An authorized caller capable of this could also DELETE the session outright; that security argument only holds if no endpoint bypasses the common middleware. Never expose resume unprotected just because connect has an authentication hook. -生产环境复现过这个故事的两半:一开始怀疑只有上行(长驻 chunked 请求体)会被 Cloudflare 标准套餐整体缓冲(见上一节),于是给上行加了连接期自动探测。但探测用的是一次性、无间隔的大块灌包,和真实隧道流量"长时间打开、数据一阵一阵地来、中间有大段空档"的模式并不一样——探测通过之后,真实流量在同一条链路上还是会挂死,且没有任何报错,双端日志只看到会话每隔几十秒静默重连一次。用一个独立 endpoint 做对照实验(同一个 broker、同一条 Cloudflare 链路,只切 `upload_stream_preference`)确认了这一点:自动档下 9/9 请求全部超时,强制 `"batch"` 下 6/6 请求全部在一秒内成功。换句话说,探测这道防线本身是不可靠的,问题也不是只出在上行方向的字节数上,而是这条链路对"长时间保持打开、间歇性写入"这种模式本身处理有问题。 +Client-declared metadata is not authenticated identity. Metadata returned by the authentication hook overrides matching client-supplied keys in the connect response. Use that hook for connect-specific policy in addition to shared route middleware. -WebSocket 是绕开这个问题的正确层:Cloudflare(以及几乎所有反向代理)对 WebSocket 连接是逐帧透传的,不会像对付一个长驻 HTTP 请求体那样整体缓冲——这是 WebSocket 协议本身的地位决定的,不依赖套餐等级或额外配置。 +## Status codes -**开启方式**:服务端 `ServerConfig.EnableWebSocket = true`,客户端 `Connector.PreferWebSocket = true`。协商独立于 `PollMode`/`UploadStreamPreference`(各自的 wire 字段是 `ConnectRequest.PreferWebSocket` / `ConnectResponse.Transport`),网关不支持时静默降级到 `PollMode`/`UploadStreamPreference` 已经谈好的结果,旧版本双方完全无感知——这条路径是纯新增的,不修改、不复用批量/流式轮询的任何现有代码路径。 +### Connect and HTTP polling/upload -**这不是轮询的第三个模式,是轮询的替代品**:协商到 `Transport = "websocket"` 的会话,客户端不再发 `/connect` 之外的任何 POST 请求,而是对 `{prefix}/{id}/ws` 发起一次 WebSocket 升级,之后两个方向的数据都在这一条连接上收发,直到会话结束。`PollHandler`/`pollLoop`/`pollLoopStream`/`sendLoopStream` 这些既有代码路径完全不参与——一个会话要么走轮询(batch 或 stream 二选一),要么走 WebSocket,不会混用。 +| Status | Meaning | Client behavior | +|---|---|---| +| 200 | Connected, data available, or upload accepted | Continue; honor negotiated framing/offsets | +| 204 | Idle long-poll timeout: **normal heartbeat**, not closure | Poll again, subject to any configured idle interval; resumable batches still process ACKs | +| 400 | Malformed request, invalid batch headers/offsets, or wrong negotiated direction | Error, not a successful empty poll; inconsistent byte state can make the session unrecoverable | +| 401 | Authentication rejected | Connect returns [`ErrUnauthorized`](client.go#L29); reconnect may retry with backoff | +| 404 | Unknown session | That session cannot be recovered; reconnect with a fresh one | +| **410** | **Session closed by the server** | Stop using that session promptly; do not treat it as 204 or normal rotation | +| **413** | Upload body exceeds advertised `max_send_bytes`: **protocol violation** | Server closes the session; diagnose and reconnect, not shrink-and-retry | +| 426 | Unsupported protocol version | Connect returns [`ErrProtocolVersion`](client.go#L24); the reconnect loop stops rather than retry forever | +| 503 | A prior resumable attachment is still detaching, or a resume prevents attachment | Transient transport/attachment failure; recovery may retry within grace | +| 3xx | Often an anti-scanning/authentication redirect | Not followed; inspect credentials and routing | -**帧格式复用,但只用得到一半**:WebSocket 连接上的每条消息是一个字节的类型标签(复用 `frame.go` 的 `frameType`)加payload,`frameData` 传数据、`frameHeartbeat` 传心跳——WebSocket 本身自带消息边界,所以不需要 `frame.go` 那套用于 HTTP chunked body 的长度前缀。`frameEnd`/`frameGone` 在这条路径上没有对应物:WebSocket 有自己原生的关闭握手,"这个会话结束了"直接体现为把连接关掉(干净关闭还是异常关闭,客户端一律当传输失败处理并重连——和 `frameGone` 今天的语义一致,`OutcomePeerClosed` vs `OutcomeTransportFailed` 的判断权在更上层,不需要靠帧类型区分)。 +**410 and 204 must remain distinct.** Otherwise closure looks like a healthy idle session and the client repeatedly polls a dead ID. Streaming HTTP uses the same status meanings before headers are committed; subsequent control frames express rotation or session closure inside the body. -**心跳与存活检测复用 `HeartbeatInterval`,但没有 `StreamMaxDuration`**:`ServerConfig.HeartbeatInterval` 照旧决定"空闲多久发一次心跳帧",两端各自的读空闲看门狗都是 `HeartbeatInterval + 宽限`(服务端侧宽限沿用内部的 `defaultStreamReadGrace`,客户端侧沿用 `Connector.PollGrace`,和流式轮询的看门狗是同一套参数、同一个量级)。但 `StreamMaxDuration`(流式轮询里"一条长驻响应最长开多久,到点强制轮转"那个参数)在这条路径上完全用不上——它存在的理由是"避开中间代理自己的 idle/read 超时",而 WebSocket 连接不需要靠周期性重开来避开这类超时,只要心跳按时发,一条连接可以一直开着。 +**413 is not normal size negotiation.** A conforming client already clamps its batch upload size to the minimum of its local chunk cap and the server's advertised maximum. Exceeding that maximum indicates a bug or protocol violation, not a reason to introduce a stateful halve-and-retry algorithm. -**依赖**:`go.mod` 新增 `github.com/coder/websocket`。选它是因为 API 是 context-native 的(`Read(ctx)`/`Write(ctx, ...)`),和这个库本身大量用 context 做超时/取消的风格一致;没有引入额外的传递依赖。 +Clients do not follow redirects. This preserves the actual auth/routing error instead of turning it into a confusing response-parsing failure at another URL. For resumable connections, recoverable transport problems are handled internally first; transport failure reaches the caller only when recovery is no longer possible. -### 六、跨重连会话恢复(`PreferResume` / `EnableResume`) +### Resume endpoint -前五节解决的都是"链路健康时怎么跑得快、跑得稳"。这一节解决另一类问题:**链路被外部按存活时间掐断时,隧道上的流为什么必死、以及怎么让它不死**。 +| Status | Meaning | +|---|---| +| 200 | Resumed; JSON includes `resumed: true` and the server's upstream `recv_offset` | +| 400 | Malformed resume request | +| 404 | Unknown session | +| 409 | Not negotiated as resumable, no longer resumable, or offset outside the replayable range; abandon this session | +| 410 | Session is closed | +| 426 | Protocol version mismatch | +| 503 | Previous transport has not detached, or another resume is in progress; retry shortly | -默认模型下,底层传输(poll / send-stream / WebSocket)一断,客户端就丢弃整个 yamux 会话,下一轮 `Connect` 拿到的是一个全新 session id,旧会话里所有 stream(比如一条 SSH 的 TCP 流)随之被切断。生产上 consumer 与 provider 各有一条传输经过 Cloudflare/反向代理,任意一条被中间层的最大连接存活时间(观察到约一小时)掐断,SSH 就断一次。心跳、`StreamMaxDuration` 滚动这些秒级机制保护不了这件事——它们不是原因。 +Authentication middleware may also reject a resume request. Resume 4xx responses are definitive for that session; network errors and server-side transient failures may be retried within grace. -开启方式:服务端 `ServerConfig.EnableResume = true` 并**挂载 `ResumeHandler`**(`POST {prefix}/{id}/resume`),客户端 `Connector.PreferResume = true`。协商仍是"客户端请求 && 服务端支持"的纯附加模式,`ConnectRequest.PreferResume` / `ConnectResponse.Resumable`,`ProtocolVersion` 不变,老客户端 × 新服务端、新客户端 × 老服务端都退化为今天的行为。**只有两种传输能恢复**:WebSocket,或上下行都是流式(`PollMode = "stream"` 且上行也谈成 stream)。batch 一个响应即一条消息,接缝语义太弱,`EnableResume` 与 batch 组合时 `Resumable` 直接为 false。 +### WebSocket upgrade -**它做了什么**:在 yamux 与 pollmux 传输之间插了一层可靠续传层(`reliable.go`),两端共用同一份实现—— +The upgrade has its own error surface: 404 for an unknown session, 400 for a session not negotiated for WebSocket, 410 for a closed session, and 409 for an already attached non-resumable WebSocket. Resumable sessions can replace stale attachments, but may return 503 if the previous attachment has not let go. Connect negotiation still uses the ordinary connect statuses above. -- 每方向给数据字节编累积序号(和 TCP 一样按字节计),数据帧改用带 8 字节绝对 offset 的 `frameSeqData`,对端收到后用 `frameAck(offset)` 回确认。ACK 搭载在反向数据/心跳帧上,收满半个 yamux 窗口还会主动叫醒发送方立刻发一次,正常运行不多花 RTT。 -- 已发未确认的字节留在重放缓冲里。传输断开后,客户端不再新建会话,而是 `POST /{id}/resume` 交换双方各自"已连续收到多少字节",服务端把下行重放缓冲回退到客户端声明的位置,客户端把上行缓冲回退到服务端声明的位置,新传输附着后先重放缺口、再继续。接收方按 offset 去重:重放过来的、已经收到过的字节丢掉,出现空洞则判定不可恢复。**接缝处无丢失、无重复、严格保序**,否则 yamux 帧流一错位整条会话就废了。 -- yamux **只构建一次**。瞬断期间 `Read` 阻塞、`Write` 立即返回(字节编号后进缓冲),yamux 从不卡在底层写上,所以 `ConnectionWriteTimeout` 不会触发;对端的窗口更新也发不过来,yamux 自己的流控让每条 stream 最多再写约 `MaxStreamWindowSize`(256KB)就停手,重放缓冲因此天然封顶在"256KB × 活跃流数"。 -- 服务端的 `*Session` 本来就跨请求存活;现在传输脱离后它进入宽限期(`ServerConfig.ResumeGrace`,默认 30s,上限 `MaxResumeGrace` 5 分钟),期间不被 `SessionTimeout` 淘汰,`CloseSessionIfNoPollInFlight` 也会把它当成"仍有传输附着"而拒绝关闭——所以一个周期性调用它的 fast reaper(HttpBroker 那种)**不需要任何改动**,宽限期一过它自然返回 true。`Session.Resumable()` / `Session.ResumeDeadline()` 供状态页和 reaper 观察。 -- 应用侧无感:HttpBroker 的 `ServerSession(session)` / `ClientSession(conn)` / `bridgeStream` 的 `io.Copy` 一行不改,只加配置。 +## Authoritative parameter negotiation -**什么时候会放弃恢复、退化成今天的"新建会话"**(客户端 `TransportFailed` 触发、`ReconnectLoop` 照旧转一圈):宽限期内没能完成 `/resume`(服务端回 404/410,或客户端按下发的 `resume_grace_ms` 重试用尽);服务端主动关闭了会话(410 / `frameGone`,比如对端离开、被 DELETE);任一方向重放缓冲超过 `MaxReplayBytes`(默认 16MB,两端各自独立配置,超过后会话继续在当前传输上工作但不再可恢复);offset 越界或出现空洞(这是 bug 信号,宁可重建也绝不错误重放);`UploadStreamPreference` 自动探测失败——上行退回离散 POST 就没法续传,客户端会删掉这个会话、不带 `PreferResume` 重连一次,调用方拿到的是一个普通连接。 +The server sends [`Limits`](protocol.go#L215) at connect time: `max_send_bytes`, `poll_timeout_ms`, `session_timeout_ms`, and `poll_buffer_bytes`; streaming in either direction or WebSocket additionally supplies `heartbeat_interval_ms` and `stream_max_duration_ms`. Resumable sessions also receive `resume_grace_ms`. WebSocket ignores stream duration even though it is included. -**要注意的两件事**:一,**两跳都要开**。consumer↔broker 与 provider↔broker 任一跳不可恢复,那一跳断裂时流照样死。二,恢复窗口是内存放大面:脱离的会话在宽限期内持有 `*Session` 加最多 `MaxReplayBytes` 的重放缓冲。`ResumeGrace` 有硬上限,`ServerConfig.MaxDetachedResumable`(默认 1024)封顶同时处于脱离状态的可恢复会话数、超出时 sweeper 先淘汰脱离最久的。三,**`/resume` 必须挂在与 `/poll`、`DELETE`、`/ws` 完全相同的鉴权中间件后面**。库本身对这几个端点都不调用 `Hooks.Authenticate`(它绑定的是 `ConnectRequest`),信任边界是 128 位随机 session id 加应用自己的中间件。一个带着越界 `recv_offset` 的 `/resume` 会让该会话永久失去可恢复性(409)——这是故意的:只拒绝不标记的话,状态错乱的对端可以换几个 offset 反复试到落进可重放区间,那就是"错误重放",比断流严重得多;诚实的客户端收到 409 本来也会放弃这个会话。能打到这个端点的人同样能直接 `DELETE` 会话,所以它没有引入 session id 本身没有的能力,但前提是鉴权层没有漏掉它。 +**Configure shared transport limits on the server, not independently at both ends.** Clients validate the response and can only choose more conservative behavior, such as a smaller upload chunk. The server's negotiated modes and limits are authoritative; requests do not override a session's negotiated direction later. -`/resume` 的状态码:200 恢复成功(响应体带服务端的 `recv_offset`);404 会话不存在、410 已关闭、409 不可恢复(未协商、已判定不可恢复、offset 超出可重放范围——客户端一律放弃并重建);426 协议版本;503 稍后重试(旧传输还没脱离干净,或另一个 resume 正在进行)。 +Useful defaults are: ---- +| Parameter | Default | +|---|---| +| Server poll timeout / session idle timeout / sweep interval | 30 s / 60 s / 5 s | +| Poll response payload cap / server upload payload cap | 256 KiB / 1 MiB | +| Client upload chunk cap | 512 KiB, clamped to server maximum | +| Client extra idle poll interval / poll grace | 0 / 10 s | +| Client send timeout / dial timeout | 15 s / 10 s | +| Send/receive coalescing window | 2 ms | +| Stream heartbeat / nominal rotation duration | 10 s / 45 s | -## 协议与行为约定 +Connect rejects `poll timeout + PollInterval >= session timeout`, because that would let a healthy client be evicted. A resumable pure-batch connection additionally requires `PollInterval < resume grace`. Resumable responses require a positive grace; streaming responses require positive heartbeat/duration settings; WebSocket requires a positive heartbeat. Server validation rejects explicitly inconsistent timing settings, including a session timeout below twice the poll timeout. These checks do not validate external proxy deadlines or application deadlines. -### 状态码 +## Throughput: batches are RTT-limited in both directions -| 状态码 | 含义 | 客户端反应 | +| Direction | Mechanism | Main transport ceiling | |---|---|---| -| 200 | 有数据 / 发送成功 | 继续 | -| 204 | 长轮询超时无数据,**正常心跳** | 立即重新 poll | -| 401 | 鉴权失败 | 致命 → 传输失败 → 退避重连 | -| 404 | 会话不存在 | 致命 → 重连 | -| **410** | **会话已被服务端关闭** | 致命 → 立即重连 | -| **413** | 请求体超限 —— **协议违规** | 致命 → 记录并重连 | -| 426 | `protocol_version` 不支持 | 致命 → 停止重试(`ErrProtocolVersion`)| -| 3xx | 反扫描重定向,通常意味着鉴权失败 | 致命 → 检查 token | +| Batch upload | Coalesced finite POSTs, one in flight | At most one effective upload chunk per request round trip | +| Stream upload | Open framed request body | Avoids the per-batch RTT ceiling, assuming live forwarding | +| Batch download | One finite long-poll response at a time | At most one `poll_buffer_bytes` payload per round trip | +| Stream download | Open framed response body | Avoids the per-batch RTT ceiling, assuming live forwarding | + +Batch uploads are **not RTT-independent**: their effective chunk is the smaller of client chunk cap and server upload cap. Mixed-direction HTTP removes the batch ceiling only from the streamed direction. With both directions streamed, the transport mechanisms are similar, but bandwidth, flow control, per-stream windows, proxies, and application behavior still limit actual throughput. + +For example, a 256 KiB download batch over 150 ms RTT has an idealized ceiling of about **1.7 MB/s** before other overhead. Historical development-machine measurements for an 8 MiB payload with an artificial 150 ms poll-endpoint delay were: + +| Direction | Batch | Stream | +|---|---|---| +| Download | ~1.0 | ~28.7 | +| Upload | ~1.9 | ~30 | + +These are the benchmark's reported `MB/s` values (its calculation uses MiB/s). They are **loopback measurements with injected per-request delay, not real WAN results or production guarantees**. The benchmarks transfer raw connection bytes rather than measure a complete application over yamux; in particular, a single yamux stream still has its own window/RTT constraint. The synthetic delay models request overhead, not every network effect. Resume adds retention, acknowledgment, and replay work; these historical figures are not a resumable-transport performance claim. + +Rerun the benchmarks in your own environment: + +```sh +go test -run '^$' -bench Benchmark -benchtime=1x +``` -**410 与 204 必须分开**:两者共用一个码的话,服务端关掉会话之后客户端会把它当成正常心跳,继续空转轮询一个死会话,直到自己的 `session_timeout` 到期才重连。分开之后是秒级。 +See [bench_test.go](bench_test.go) for the workload and injected-delay setup. -**413 是协议违规而不是可恢复状况**:服务端在 connect 时下发 `max_send_bytes`,客户端取 `min(本地配置, 下发值)`,所以守规矩的客户端不可能发出超限请求。收到 413 说明对端有 bug,正确反应是大声记日志并重连,而不是减半重试 —— 那是一条带状态的重试路径,是 bug 的温床。 +## Reconnect policy -**3xx 不会被跟随**:客户端设了 `CheckRedirect: http.ErrUseLastResponse`。否则 Go 默认跟随重定向,`resp.StatusCode` 根本看不到 3xx,一次清晰的鉴权失败会变成别处一个莫名其妙的解析错误。 +[`ReconnectLoop`](reconnect.go#L54) obtains a connection, runs the application's serve callback, closes the connection afterwards, and chooses the next action from the reported outcome: -流式模式不引入新状态码——上面这张表在 `PollMode = "stream"` 下原样适用(410、413 等语义不变),分帧发生在响应体内部,是应用层的事,不需要 HTTP 层再表达一次。 +- [`OutcomeTransportFailed`](reconnect.go#L17): wait with exponential backoff, doubling up to the maximum. Connect errors also advance backoff, except a protocol-version error stops the loop. +- [`OutcomePeerClosed`](reconnect.go#L21): wait only the short peer-closed pause; **do not advance or reset accumulated backoff**. +- [`OutcomeSuperseded`](reconnect.go#L25): a newer connect replaced the session; stop reconnecting. +- [`OutcomeShutdown`](reconnect.go#L27): stop on application shutdown. -WebSocket 传输模式用的是升级请求本身的状态码,和上面这张表是两套独立的错误面:404(会话不存在)、400(会话没有协商 WebSocket 传输,例如客户端连错了 endpoint 或服务端 `EnableWebSocket` 中途被关掉)、409(会话已经有一条 WebSocket 挂着,正常运行下不会触发——见下方"这不是轮询的第三个模式")。协商阶段的握手(`/connect`)仍然走上面那张表。 +Defaults are 1 second initial backoff, 3 minutes maximum backoff, and a 500 ms peer-closed pause. **A successful connect alone does not reset backoff.** On a transport-failed outcome, backoff resets only after the connection has served for at least [`MinStableDuration`](reconnect.go#L72), default **5 seconds**. Connections that repeatedly succeed and then fail immediately therefore continue escalating rather than hammering the server at the initial delay. A negative stable-duration setting disables this reset. -### 参数下发 +The application must distinguish peer departure from transport failure. After the yamux session closes, recheck [`Conn.TransportFailed()`](client.go#L45), and handle supersession separately; yamux close alone does not identify the cause. Closing a yamux session also closes its underlying connection. If the application wants a peer to leave while retaining the tunnel, it needs separate application-level signaling. -需要两端一致的数字由服务端做权威并在 connect 时下发(`max_send_bytes`、`poll_timeout`、`session_timeout`、`poll_buffer_bytes`,流式模式或 WebSocket 传输下再加 `heartbeat_interval_ms`)。WebSocket 传输协商时 `stream_max_duration_ms` 也会跟着一起下发(内部复用了流式轮询同一套"这次 connect 要不要带上 Heartbeat/StreamMaxDuration"的判断),但 WebSocket 的客户端/服务端实现都不读它——上一节已经说明这条路径不需要强制轮转。客户端只能更保守,不能更激进。这与 HTTP/2 的 SETTINGS、TCP 的 MSS 协商是同一个道理:**不要两边各配一份**。 +With resume enabled, successful internal recovery keeps the same connection and yamux session alive; the outer reconnect loop is only needed after recovery fails or the application otherwise ends that session. -客户端在 connect 时还会自检 —— 如果 `poll_timeout + PollInterval >= session_timeout`,说明这个客户端健康时也会被服务端当成掉线扫掉,于是直接返回错误而不是带着这个隐患跑起来。 +## Tests -### `ReconnectLoop` 的退避 +Run the test suite with: -- `OutcomeTransportFailed`(链路问题)→ 退避并翻倍,上限 `MaxBackoff`。 -- `OutcomePeerClosed`(对端走了,链路健康)→ 只短暂停顿,**不推进退避**。 -- **每次连接成功都会重置退避。** 因此"连上就立刻断"的抖动链路会稳定在 `InitialBackoff` 反复重试,不会升级。这是为了真实故障恢复后能立刻恢复速度而做的取舍。 +```sh +go test ./... +``` -注意 `OutcomePeerClosed` 需要调用方判断:yamux 会话结束本身不区分"链路断了"和"对端走了",要在 `sess.CloseChan()` 触发后再查一次 `conn.TransportFailed()`。另外 `yamux.Session.Close()` 会连底层 conn 一起关,所以如果底层 conn 就是这条隧道,关 yamux 等于拆隧道,对端只会看到传输失败 —— 想要"对端走了但隧道保留",需要应用层另设信令。 +[batch_resume_test.go](batch_resume_test.go) covers deterministic lost upload responses and truncated download bodies, raw offset deduplication/replay, malformed or ambiguous offsets, incomplete and oversized uploads, stalled bodies, lifecycle failures, capability/backward compatibility, concurrent streams, and repeated transport kills for pure-batch and both mixed HTTP combinations. Stream and WebSocket recovery tests are in [resume_test.go](resume_test.go); reconnect timing behavior is covered in [reconnect_test.go](reconnect_test.go). diff --git a/batch.go b/batch.go new file mode 100644 index 0000000..99c1cb6 --- /dev/null +++ b/batch.go @@ -0,0 +1,268 @@ +package pollmux + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "time" +) + +// Resumable batches carry raw, bounded bodies, just like legacy batches. The +// offsets live in headers rather than frames, so MaxSendBytes/PollBufferSize +// still bound payload bytes and no streaming support is required of a proxy. +// A successful write to HTTP is not an acknowledgement: reliable retains the +// bytes until the peer reports receiving them in a later request/response. +func batchOffset(h http.Header, name string) (uint64, error) { + values := h.Values(name) + if len(values) != 1 { + return 0, fmt.Errorf("pollmux: expected exactly one %s header", name) + } + n, err := strconv.ParseUint(values[0], 10, 64) + if err != nil { + return 0, fmt.Errorf("pollmux: invalid %s: %w", name, err) + } + return n, nil +} + +func setBatchOffset(h http.Header, name string, off uint64) { + h.Set(name, strconv.FormatUint(off, 10)) +} + +// pollBatchResumable owns exactly one direction until the request finishes. +// ResumeHandler can cancel even a parked poll or a half-read upload before +// examining offsets. Incomplete uploads never enter the reliable byte stream. +func pollBatchResumable(w http.ResponseWriter, r *http.Request, s *Session, st *SessionStore, cfg ServerConfig, h Hooks, send bool) { + ack, err := batchOffset(r.Header, HeaderRecvOffset) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + var off uint64 + if send { + off, err = batchOffset(r.Header, HeaderSendOffset) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + } else if r.ContentLength != 0 { + writeError(w, http.StatusBadRequest, "receive-only batch must have an empty body") + return + } + + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + rc := http.NewResponseController(w) + defer rc.SetReadDeadline(time.Time{}) + defer rc.SetWriteDeadline(time.Time{}) + kind := attachDown + if send { + kind = attachUp + // Set this before publishing the attachment: a concurrent resume must + // never have its cancellation deadline overwritten by a later reset. + rc.SetReadDeadline(time.Now().Add(cfg.PollTimeout + defaultStreamReadGrace)) + } + att, err := s.att.attach(kind, func() { + cancel() + rc.SetReadDeadline(time.Now()) + rc.SetWriteDeadline(time.Now()) + s.rs.interruptOut() + }) + if err != nil { + writeError(w, http.StatusServiceUnavailable, "previous transport is still detaching, retry") + return + } + defer s.att.detach(att) + // A disconnected caller must not keep a poll parked for PollTimeout. + stop := context.AfterFunc(ctx, s.rs.interruptOut) + defer stop() + + var data []byte + if send { + data, err = io.ReadAll(http.MaxBytesReader(w, r.Body, int64(cfg.MaxSendBytes))) + if err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + closeSession(st, h, s, ReasonProtocolViolation) + writeError(w, http.StatusRequestEntityTooLarge, "batch body exceeds max_send_bytes") + } else { + writeError(w, http.StatusBadRequest, "failed to read batch body") + } + return + } + } + if ctx.Err() != nil { + return + } + if err := s.rs.ack(ack); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + if send { + if err := s.rs.recvIn(off, data); err != nil { + status := http.StatusBadRequest + if errors.Is(err, io.ErrClosedPipe) { + status = http.StatusGone + } + writeError(w, status, err.Error()) + return + } + setBatchOffset(w.Header(), HeaderRecvOffset, s.rs.recvOffsetNow()) + w.Header().Set("Content-Length", "0") + w.WriteHeader(http.StatusOK) + return + } + + buf := make([]byte, cfg.PollBufferSize) + off, n, err := s.rs.nextOut(buf, cfg.PollTimeout, cfg.CoalesceWindow) + if ctx.Err() != nil { + return + } + if errors.Is(err, io.EOF) { + writeError(w, http.StatusGone, "session closed") + return + } + if err != nil && !errors.Is(err, errPipeInterrupted) { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + setBatchOffset(w.Header(), HeaderRecvOffset, s.rs.recvOffsetNow()) + if n == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + setBatchOffset(w.Header(), HeaderSendOffset, off) + w.Header().Set("Content-Type", "application/octet-stream") + // Explicit length lets a client detect a response truncated mid-batch. + w.Header().Set("Content-Length", strconv.Itoa(n)) + w.WriteHeader(http.StatusOK) + w.Write(buf[:n]) +} + +// batchDownLoop always has a receive-only request in flight, including while +// idle. It acknowledges downstream bytes on the next poll, not merely when a +// large transfer crosses reliable's eager-ack threshold. +func (c *resumableConn) batchDownLoop(ctx context.Context) error { + for { + got, err := c.doBatchPoll(ctx) + if err != nil { + return err + } + if !got && c.pollInterval > 0 && !sleepOrDone(ctx, c.pollInterval) { + return ctx.Err() + } + if ctx.Err() != nil { + return ctx.Err() + } + } +} + +func (c *resumableConn) doBatchPoll(ctx context.Context) (bool, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.pollURL, nil) + if err != nil { + return false, err + } + req.Header.Set(HeaderReceiveOnly, "true") + setBatchOffset(req.Header, HeaderRecvOffset, c.rl.recvOffsetNow()) + c.setAuth(req) + if c.localHealth != nil { + if c.localHealth() { + req.Header.Set(HeaderLocalHealth, "ok") + } else { + req.Header.Set(HeaderLocalHealth, "down") + } + } + resp, err := c.pollClient.Do(req) + if err != nil { + return false, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { + return false, &fatalPollError{status: resp.StatusCode} + } + data, err := io.ReadAll(io.LimitReader(resp.Body, int64(c.maxFrame)+1)) + if err != nil { + return false, fmt.Errorf("pollmux: reading batch response: %w", err) + } + if len(data) > c.maxFrame { + return false, errors.New("pollmux: batch response exceeds poll_buffer_bytes") + } + ack, err := batchOffset(resp.Header, HeaderRecvOffset) + if err != nil { + return false, err + } + if resp.StatusCode == http.StatusOK { + off, err := batchOffset(resp.Header, HeaderSendOffset) + if err != nil { + return false, err + } + if err := c.rl.recvIn(off, data); err != nil { + return false, err + } + } + if err := c.rl.ack(ack); err != nil { + return false, err + } + return len(data) > 0, nil +} + +// batchUpLoop retains one in-flight upload at a time. A failed request leaves +// its bytes in replay; supervise exchanges offsets before any retry, avoiding +// the ambiguous "server accepted it but its 200 was lost" duplicate delivery. +func (c *resumableConn) batchUpLoop(ctx context.Context) error { + buf := make([]byte, c.maxSendChunk) + c.rl.resetAck() + for { + off, n, err := c.rl.nextOut(buf, c.limits.PollTimeout(), c.coalesceWindow) + if ctx.Err() != nil { + return ctx.Err() + } + if err != nil && !errors.Is(err, errPipeInterrupted) { + return err + } + _, due := c.rl.takeAck() + if n == 0 && !due { + continue + } + if err := c.doBatchSend(ctx, off, buf[:n]); err != nil { + return err + } + } +} + +func (c *resumableConn) doBatchSend(ctx context.Context, off uint64, data []byte) error { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.pollURL, bytes.NewReader(data)) + if err != nil { + return err + } + req.Header.Set(HeaderSendOnly, "true") + req.Header.Set("Content-Type", "application/octet-stream") + setBatchOffset(req.Header, HeaderSendOffset, off) + setBatchOffset(req.Header, HeaderRecvOffset, c.rl.recvOffsetNow()) + c.setAuth(req) + resp, err := c.httpClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return &fatalPollError{status: resp.StatusCode} + } + // Batch send responses have no body. Finish reading before accepting the + // ack, so truncated/invalid responses are never mistaken for completion. + body, err := io.ReadAll(io.LimitReader(resp.Body, 1)) + if err != nil { + return err + } + if len(body) != 0 { + return errors.New("pollmux: unexpected batch send response body") + } + ack, err := batchOffset(resp.Header, HeaderRecvOffset) + if err != nil { + return err + } + return c.rl.ack(ack) +} diff --git a/batch_resume_test.go b/batch_resume_test.go new file mode 100644 index 0000000..9eeea2c --- /dev/null +++ b/batch_resume_test.go @@ -0,0 +1,757 @@ +package pollmux + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync/atomic" + "testing" + "testing/iotest" + "time" +) + +func connectResumableBatch(t *testing.T, ts *httptest.Server) ConnectResponse { + t.Helper() + resp, cr := postConnect(t, ts, ConnectRequest{ProtocolVersion: ProtocolVersion, PreferResume: true, BatchResume: true}) + if resp.StatusCode != http.StatusOK || !cr.Resumable || !cr.BatchResume || cr.PollMode == PollModeStream { + t.Fatalf("batch connect = (%d, %+v)", resp.StatusCode, cr) + } + return cr +} + +// rawBatch makes a fully bounded request, including the acknowledgement even +// when zero. It returns a closed response and the bytes read from its body. +func rawBatch(t *testing.T, ts *httptest.Server, id string, send bool, off, ack uint64, body []byte) (*http.Response, []byte) { + t.Helper() + req, _ := http.NewRequest(http.MethodPost, ts.URL+"/tunnel/"+id+"/poll", bytes.NewReader(body)) + setBatchOffset(req.Header, HeaderRecvOffset, ack) + if send { + req.Header.Set(HeaderSendOnly, "true") + setBatchOffset(req.Header, HeaderSendOffset, off) + } else { + req.Header.Set(HeaderReceiveOnly, "true") + } + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + t.Fatal(err) + } + return resp, data +} + +func requireBatchOffset(t *testing.T, resp *http.Response, name string, want uint64) { + t.Helper() + got, err := batchOffset(resp.Header, name) + if err != nil || got != want { + t.Fatalf("%s = (%d, %v), want %d", name, got, err, want) + } +} + +func TestBatchResumeUploadDeduplicatesAndReportsOffset(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + for _, tc := range []struct { + off uint64 + data string + want uint64 + }{ + {0, "abc", 3}, {0, "abc", 3}, {1, "bcde", 5}, + } { + resp, _ := rawBatch(t, ts, cr.SessionID, true, tc.off, 0, []byte(tc.data)) + if resp.StatusCode != http.StatusOK { + t.Fatalf("upload = %d", resp.StatusCode) + } + requireBatchOffset(t, resp, HeaderRecvOffset, tc.want) + } + got := make([]byte, 5) + if _, err := io.ReadFull(s, got); err != nil || string(got) != "abcde" { + t.Fatalf("upstream = %q, %v", got, err) + } + if s.toServer.Buffered() != 0 { + t.Fatal("duplicate bytes reached the application") + } + resp, rr := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusOK || rr.RecvOffset != 5 { + t.Fatalf("resume = (%d, %+v)", resp.StatusCode, rr) + } +} + +func TestBatchResumeDownstreamReplaysOnlyMissingBytes(t *testing.T) { + cfg := testResumeServerConfig() + cfg.PollBufferSize = 5 + ts, st := newResumeTestServer(t, cfg, Hooks{}) + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + s.Write([]byte("abcdefghij")) + resp, data := rawBatch(t, ts, cr.SessionID, false, 0, 0, nil) + if resp.StatusCode != http.StatusOK || string(data) != "abcde" { + t.Fatalf("first batch = %d %q", resp.StatusCode, data) + } + requireBatchOffset(t, resp, HeaderSendOffset, 0) + if s.rs.unacked() != 5 { + t.Fatal("HTTP write released unacknowledged data") + } + + // Treat only the first two bytes as received before the old link failed. + resp, _ = postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion, RecvOffset: 2}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("resume = %d", resp.StatusCode) + } + resp, data = rawBatch(t, ts, cr.SessionID, false, 0, 2, nil) + if string(data) != "cde" { + t.Fatalf("replay = %q", data) + } + requireBatchOffset(t, resp, HeaderSendOffset, 2) + resp, data = rawBatch(t, ts, cr.SessionID, false, 0, 5, nil) + if string(data) != "fghij" { + t.Fatalf("new data = %q", data) + } + requireBatchOffset(t, resp, HeaderSendOffset, 5) + resp, _ = rawBatch(t, ts, cr.SessionID, false, 0, 10, nil) + if resp.StatusCode != http.StatusNoContent { + t.Fatalf("idle = %d", resp.StatusCode) + } + requireBatchOffset(t, resp, HeaderRecvOffset, 0) + if s.rs.unacked() != 0 { + t.Fatal("next poll did not release acknowledged replay") + } +} + +func TestBatchResumeRejectsInvalidRequests(t *testing.T) { + cases := []struct { + name string + headers map[string]string + body string + broken bool + }{ + {"missing ack", map[string]string{HeaderSendOnly: "true", HeaderSendOffset: "0"}, "abc", false}, + {"missing sequence", map[string]string{HeaderSendOnly: "true", HeaderRecvOffset: "0"}, "abc", false}, + {"negative sequence", map[string]string{HeaderSendOnly: "true", HeaderSendOffset: "-1", HeaderRecvOffset: "0"}, "abc", false}, + {"overflow sequence", map[string]string{HeaderSendOnly: "true", HeaderSendOffset: "18446744073709551616", HeaderRecvOffset: "0"}, "abc", false}, + {"malformed ack", map[string]string{HeaderReceiveOnly: "true", HeaderRecvOffset: "abc"}, "", false}, + {"both directions", map[string]string{HeaderSendOnly: "true", HeaderReceiveOnly: "true", HeaderSendOffset: "0", HeaderRecvOffset: "0"}, "abc", false}, + {"no direction", map[string]string{HeaderRecvOffset: "0"}, "", false}, + {"poll with body", map[string]string{HeaderReceiveOnly: "true", HeaderRecvOffset: "0"}, "abc", false}, + {"unnumbered stream", map[string]string{HeaderSendStream: "true"}, "abc", false}, + {"gap", map[string]string{HeaderSendOnly: "true", HeaderSendOffset: "1", HeaderRecvOffset: "0"}, "abc", true}, + {"impossible ack", map[string]string{HeaderReceiveOnly: "true", HeaderRecvOffset: "1"}, "", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableBatch(t, ts) + resp := poll(t, ts, cr.SessionID, []byte(tc.body), tc.headers) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d", resp.StatusCode) + } + s, _ := st.Get(cr.SessionID) + if s.rs.recvOffsetNow() != 0 || s.toServer.Buffered() != 0 { + t.Fatal("invalid data entered session") + } + if s.Resumable() == tc.broken { + t.Fatalf("Resumable = %v, broken = %v", s.Resumable(), tc.broken) + } + }) + } +} + +func TestBatchResumeIncompleteUploadIsNotDelivered(t *testing.T) { + cfg := testResumeServerConfig() + ts, st := newResumeTestServer(t, cfg, Hooks{}) + cr := connectResumableBatch(t, ts) + r := httptest.NewRequest(http.MethodPost, "/tunnel/"+cr.SessionID+"/poll", io.MultiReader(strings.NewReader("abc"), iotest.ErrReader(io.ErrUnexpectedEOF))) + r.SetPathValue("id", cr.SessionID) + r.Header.Set(HeaderSendOnly, "true") + setBatchOffset(r.Header, HeaderRecvOffset, 0) + setBatchOffset(r.Header, HeaderSendOffset, 0) + w := httptest.NewRecorder() + PollHandler(st, cfg, Hooks{}).ServeHTTP(w, r) + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d", w.Code) + } + s, _ := st.Get(cr.SessionID) + if s.rs.recvOffsetNow() != 0 || s.toServer.Buffered() != 0 { + t.Fatal("partial upload was delivered") + } + resp, _ := rawBatch(t, ts, cr.SessionID, true, 0, 0, []byte("abcdef")) + if resp.StatusCode != http.StatusOK { + t.Fatalf("retry = %d", resp.StatusCode) + } + requireBatchOffset(t, resp, HeaderRecvOffset, 6) +} + +func TestBatchResumeOversizedUploadClosesSession(t *testing.T) { + cfg := testResumeServerConfig() + cfg.MaxSendBytes = 4 + var closed atomic.Int32 + ts, st := newResumeTestServer(t, cfg, Hooks{OnDisconnect: func(_ *Session, reason DisconnectReason) { + if reason != ReasonProtocolViolation { + t.Errorf("reason = %v", reason) + } + closed.Add(1) + }}) + cr := connectResumableBatch(t, ts) + resp, _ := rawBatch(t, ts, cr.SessionID, true, 0, 0, []byte("12345")) + if resp.StatusCode != http.StatusRequestEntityTooLarge || st.Len() != 0 || closed.Load() != 1 { + t.Fatalf("oversized upload = status %d, sessions %d, callbacks %d", resp.StatusCode, st.Len(), closed.Load()) + } +} + +func TestBatchResumeKicksParkedPoll(t *testing.T) { + cfg := testResumeServerConfig() + cfg.PollTimeout = 5 * time.Second + cfg.SessionTimeout = 10 * time.Second + ts, st := newResumeTestServer(t, cfg, Hooks{}) + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + done := make(chan struct{}) + go func() { + defer close(done) + req, _ := http.NewRequest(http.MethodPost, ts.URL+"/tunnel/"+cr.SessionID+"/poll", nil) + req.Header.Set(HeaderReceiveOnly, "true") + setBatchOffset(req.Header, HeaderRecvOffset, 0) + if resp, err := ts.Client().Do(req); err == nil { + resp.Body.Close() + } + }() + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 }) + resp, _ := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("resume = %d", resp.StatusCode) + } + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("old poll did not detach promptly") + } +} + +func TestBatchResumeKicksIncompleteUploadBeforeExchangingOffsets(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + conn, err := net.DialTimeout("tcp", strings.TrimPrefix(ts.URL, "http://"), time.Second) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + // Leave half of a declared body outstanding without closing the socket. + if _, err := fmt.Fprintf(conn, "POST /tunnel/%s/poll HTTP/1.1\r\nHost: test\r\nContent-Length: 6\r\n%s: true\r\n%s: 0\r\n%s: 0\r\n\r\nabc", + cr.SessionID, HeaderSendOnly, HeaderSendOffset, HeaderRecvOffset); err != nil { + t.Fatal(err) + } + waitFor(t, time.Second, func() bool { + s.att.mu.Lock() + defer s.att.mu.Unlock() + return s.att.up != nil + }) + resp, rr := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusOK || rr.RecvOffset != 0 || s.toServer.Buffered() != 0 { + t.Fatalf("resume with partial upload = %d, %+v", resp.StatusCode, rr) + } + conn.Close() + resp, _ = rawBatch(t, ts, cr.SessionID, true, 0, 0, []byte("abcdef")) + if resp.StatusCode != http.StatusOK { + t.Fatalf("replacement upload = %d", resp.StatusCode) + } + requireBatchOffset(t, resp, HeaderRecvOffset, 6) +} + +func TestBatchResumeClientValidatesResponses(t *testing.T) { + for _, tc := range []struct { + name string + status int + headers map[string]string + body string + }{ + {"missing ack", 200, map[string]string{HeaderSendOffset: "0"}, "abc"}, + {"missing offset", 200, map[string]string{HeaderRecvOffset: "0"}, "abc"}, + {"bad offset", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "x"}, "abc"}, + {"gap", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "1"}, "abc"}, + {"bad ack", 204, map[string]string{HeaderRecvOffset: "1"}, ""}, + {"oversized", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "0"}, "123456789"}, + {"truncated", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "0", "Content-Length": "8"}, "abc"}, + {"closed", 410, nil, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for k, v := range tc.headers { + w.Header().Set(k, v) + } + w.WriteHeader(tc.status) + io.WriteString(w, tc.body) + })) + defer ts.Close() + c := &resumableConn{rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), 1024), pollClient: ts.Client(), pollURL: ts.URL, maxFrame: 8} + if _, err := c.doBatchPoll(context.Background()); err == nil { + t.Fatal("accepted invalid response") + } + }) + } +} + +func TestBatchResumeClientDeduplicatesResponses(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + setBatchOffset(w.Header(), HeaderRecvOffset, 0) + setBatchOffset(w.Header(), HeaderSendOffset, 0) + io.WriteString(w, "abc") + })) + defer ts.Close() + c := &resumableConn{rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), 1024), pollClient: ts.Client(), pollURL: ts.URL, maxFrame: 8} + for i := 0; i < 2; i++ { + if _, err := c.doBatchPoll(context.Background()); err != nil { + t.Fatal(err) + } + } + if c.rl.in.Buffered() != 3 || c.rl.recvOffsetNow() != 3 { + t.Fatal("replayed response reached application twice") + } +} + +func TestE2EResumeSurvivesTransportKills_HTTPBatchDirections(t *testing.T) { + for _, mode := range []string{PollModeBatch, "stream-batch", "batch-stream"} { + t.Run(mode, func(t *testing.T) { testE2EResumeSurvivesTransportKills(t, mode) }) + } +} + +func TestE2EResumeIdleKillIsInvisible_HTTPBatchDirections(t *testing.T) { + for _, mode := range []string{PollModeBatch, "stream-batch", "batch-stream"} { + t.Run(mode, func(t *testing.T) { testE2EResumeIdleKillIsInvisible(t, mode) }) + } +} + +// Deterministic faults at the two ambiguity points: after an upload has been +// delivered, and halfway through a download whose bytes left the server pipe. +func TestE2EBatchResumeLostResponses(t *testing.T) { + for _, upload := range []bool{true, false} { + t.Run(map[bool]string{true: "upload accepted, response lost", false: "download truncated"}[upload], func(t *testing.T) { + var armed, injected atomic.Bool + middleware := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + match := r.Header.Get(HeaderReceiveOnly) == "true" + if upload { + match = r.Header.Get(HeaderSendOnly) == "true" + } + if !armed.Load() || !match { + next.ServeHTTP(w, r) + return + } + rec := httptest.NewRecorder() + next.ServeHTTP(rec, r) + if rec.Code == 200 && (upload || rec.Body.Len() > 1) && armed.CompareAndSwap(true, false) { + injected.Store(true) + if !upload { + for k, vs := range rec.Header() { + w.Header()[k] = vs + } + w.WriteHeader(rec.Code) + w.Write(rec.Body.Bytes()[:rec.Body.Len()/2]) + w.(http.Flusher).Flush() + } + panic(http.ErrAbortHandler) + } + for k, vs := range rec.Header() { + w.Header()[k] = vs + } + w.WriteHeader(rec.Code) + w.Write(rec.Body.Bytes()) + }) + } + e := newResumeE2E(t, PollModeBatch, nil, middleware) + conn, sess := e.dial(t, nil) + id := conn.SessionID() + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(10 * time.Second)) + stream.Write([]byte("ready")) + buf := make([]byte, 5) + if _, err := io.ReadFull(stream, buf); err != nil { + t.Fatal(err) + } + armed.Store(true) + payload := bytes.Repeat([]byte("batch-resume"), 4096) + if _, err := stream.Write(payload); err != nil { + t.Fatal(err) + } + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil || !bytes.Equal(got, payload) { + t.Fatalf("echo corrupted: %v", err) + } + waitFor(t, 3*time.Second, func() bool { return e.resumes.Load() > 0 }) + if !injected.Load() || conn.SessionID() != id || sess.IsClosed() || isClosed(conn.TransportFailed()) || len(e.reasons()) != 0 { + t.Fatal("fault did not preserve the original session and stream") + } + }) + } +} + +func TestBatchResumeCapabilityIsBackwardCompatible(t *testing.T) { + // Emulate an older server by ignoring the additive request capability. + middleware := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/connect") { + var req ConnectRequest + json.NewDecoder(r.Body).Decode(&req) + req.BatchResume = false + body, _ := json.Marshal(req) + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + } + next.ServeHTTP(w, r) + }) + } + e := newResumeE2E(t, PollModeBatch, nil, middleware) + conn, sess := e.dial(t, nil) + if _, ok := conn.(*resumableConn); ok { + t.Fatal("older batch server unexpectedly enabled resume") + } + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(5 * time.Second)) + stream.Write([]byte("legacy")) + got := make([]byte, 6) + if _, err := io.ReadFull(stream, got); err != nil || string(got) != "legacy" { + t.Fatalf("legacy echo = %q, %v", got, err) + } +} + +func TestBatchOffsetRejectsAmbiguousHeaders(t *testing.T) { + for _, values := range [][]string{nil, {""}, {"-1"}, {"+1"}, {"1, 2"}, {"1", "2"}, {"18446744073709551616"}} { + h := http.Header{} + for _, v := range values { + h.Add(HeaderRecvOffset, v) + } + if _, err := batchOffset(h, HeaderRecvOffset); err == nil { + t.Fatalf("accepted headers %q", values) + } + } + h := http.Header{} + setBatchOffset(h, HeaderRecvOffset, ^uint64(0)) + if off, err := batchOffset(h, HeaderRecvOffset); err != nil || off != ^uint64(0) { + t.Fatalf("max offset = %d, %v", off, err) + } +} + +func TestBatchResumeClientBoundsStalledResponseBody(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + setBatchOffset(w.Header(), HeaderRecvOffset, 0) + setBatchOffset(w.Header(), HeaderSendOffset, 0) + w.Header().Set("Content-Length", strconv.Itoa(10)) + w.WriteHeader(200) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer ts.Close() + client := ts.Client() + client.Timeout = 50 * time.Millisecond + c := &resumableConn{rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), 1024), pollClient: client, pollURL: ts.URL, maxFrame: 16} + if _, err := c.doBatchPoll(context.Background()); err == nil || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("stalled body error = %v", err) + } +} + +func TestBatchResumeGraceExpiryEndsOriginalStreams(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, func(cfg *ServerConfig) { cfg.ResumeGrace = 300 * time.Millisecond }, nil) + conn, sess := e.dial(t, nil) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + e.proxy.refuse.Store(true) + e.proxy.killAll() + select { + case <-conn.TransportFailed(): + case <-time.After(5 * time.Second): + t.Fatal("resume did not give up after grace expiry") + } + select { + case <-sess.CloseChan(): + case <-time.After(time.Second): + t.Fatal("original yamux session did not close") + } + waitFor(t, time.Second, func() bool { return e.store.Len() == 0 }) +} + +func TestBatchResumeDoesNotResurrectClosedSession(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, nil, nil) + conn, _ := e.dial(t, nil) + s, _ := e.store.Get(conn.SessionID()) + CloseSession(e.store, e.hooks, s, ReasonServerClose) + select { + case <-conn.TransportFailed(): + case <-time.After(3 * time.Second): + t.Fatal("closed session did not fail") + } + if e.store.Len() != 0 || e.resumes.Load() != 0 { + t.Fatal("client tried to resurrect a closed session") + } +} + +func TestBatchResumeReplayOverflowFailsOnlyAfterTransportLoss(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, nil, nil) + conn, sess := e.dial(t, func(c *Connector) { c.MaxReplayBytes = 1024; c.MaxSendChunk = 8192 }) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(5 * time.Second)) + payload := bytes.Repeat([]byte("x"), 8192) + if _, err := stream.Write(payload); err != nil { + t.Fatal(err) + } + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil || !bytes.Equal(got, payload) { + t.Fatalf("echo after overflow = %v", err) + } + rc := conn.(*resumableConn) + if !rc.rl.isBroken() || isClosed(conn.TransportFailed()) { + t.Fatal("overflow must disable resume, not the live transport") + } + e.proxy.killAll() + select { + case <-conn.TransportFailed(): + case <-time.After(3 * time.Second): + t.Fatal("overflowed replay was used to resume") + } +} + +func TestBatchResumeCloseWhileOfflineUnblocksReadersAndSupervisor(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, nil, nil) + conn, sess := e.dial(t, nil) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + e.proxy.refuse.Store(true) + e.proxy.killAll() + done := make(chan error, 1) + go func() { done <- conn.Close() }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("Close hung while offline") + } + select { + case <-sess.CloseChan(): + case <-time.After(time.Second): + t.Fatal("yamux read remained blocked after Close") + } +} + +func TestBatchResumeRejectsPollIntervalBeyondGrace(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, func(c *ServerConfig) { c.ResumeGrace = 100 * time.Millisecond }, nil) + c := e.connector(func(c *Connector) { c.PollInterval = 100 * time.Millisecond }) + conn, err := c.Connect(context.Background()) + if conn != nil { + conn.Close() + } + if err == nil || !strings.Contains(err.Error(), "resume_grace") { + t.Fatalf("bad interval error = %v", err) + } +} + +func TestBatchResumeRequestAttachmentsCannotRaceHandshake(t *testing.T) { + a := newAttachments() + if !a.beginResume() { + t.Fatal("could not begin resume") + } + for _, kind := range []attachKind{attachUp, attachDown, attachBoth} { + if _, err := a.attach(kind, func() {}); !errors.Is(err, errStillAttached) { + t.Fatalf("attach during resume = %v", err) + } + } + a.endResume() + att, err := a.attach(attachBoth, func() {}) + if err != nil { + t.Fatal(err) + } + a.detach(att) +} + +func TestBatchResumePreservesMetadataAuthAndChunkLimits(t *testing.T) { + var largest atomic.Int64 + var polls, sends, resumes atomic.Int32 + middleware := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer test-token" { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.Header.Get(HeaderSendOnly) == "true" { + sends.Add(1) + for old := largest.Load(); r.ContentLength > old; old = largest.Load() { + if largest.CompareAndSwap(old, r.ContentLength) { + break + } + } + } + if r.Header.Get(HeaderReceiveOnly) == "true" { + polls.Add(1) + if r.Header.Get(HeaderLocalHealth) != "ok" { + t.Error("local health was not forwarded") + } + } + if strings.HasSuffix(r.URL.Path, "/resume") { + resumes.Add(1) + } + next.ServeHTTP(w, r) + }) + } + e := newResumeE2E(t, PollModeBatch, func(c *ServerConfig) { c.MaxSendBytes = 2048 }, middleware) + conn, sess := e.dial(t, func(c *Connector) { + c.AuthToken = "test-token" + c.Meta = map[string]string{"endpoint": "example"} + c.LocalHealth = func() bool { return true } + c.MaxSendChunk = 4096 + }) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(10 * time.Second)) + for i := 0; i < 2; i++ { + if i == 1 { + e.proxy.killAll() + } + payload := bytes.Repeat([]byte("z"), 8192) + if _, err := stream.Write(payload); err != nil { + t.Fatal(err) + } + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil || !bytes.Equal(got, payload) { + t.Fatalf("echo = %v", err) + } + } + if polls.Load() == 0 || sends.Load() < 8 || resumes.Load() == 0 || largest.Load() > 2048 || conn.Meta()["endpoint"] != "example" { + t.Fatalf("limits/metadata not preserved: polls %d sends %d resumes %d largest %d meta %v", polls.Load(), sends.Load(), resumes.Load(), largest.Load(), conn.Meta()) + } +} + +func TestBatchResumeConcurrentStreams(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, nil, nil) + conn, sess := e.dial(t, nil) + id := conn.SessionID() + const count = 8 + ready := make(chan struct{}, count) + start := make(chan struct{}) + done := make(chan error, count) + for i := 0; i < count; i++ { + go func(i int) { + stream, err := sess.Open() + if err != nil { + ready <- struct{}{} + done <- err + return + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(10 * time.Second)) + ready <- struct{}{} + <-start + payload := bytes.Repeat([]byte{byte(i)}, 64<<10) + for j := 0; j < 4; j++ { + if _, err := stream.Write(payload); err != nil { + done <- err + return + } + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil { + done <- err + return + } + if !bytes.Equal(got, payload) { + done <- errors.New("stream contents interleaved or duplicated") + return + } + } + done <- nil + }(i) + } + for i := 0; i < count; i++ { + select { + case <-ready: + case <-time.After(5 * time.Second): + t.Fatal("streams did not open") + } + } + close(start) + for i := 0; i < 3; i++ { + e.proxy.killAll() + time.Sleep(15 * time.Millisecond) + } + for i := 0; i < count; i++ { + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("stream did not recover") + } + } + if conn.SessionID() != id || sess.IsClosed() || isClosed(conn.TransportFailed()) || e.resumes.Load() == 0 { + t.Fatal("concurrent streams did not retain their session") + } +} + +func TestBatchResumeOlderServerUploadProbeFallback(t *testing.T) { + middleware := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(HeaderSendStreamProbe) == "true" { + w.WriteHeader(http.StatusBadGateway) + return + } + if strings.HasSuffix(r.URL.Path, "/connect") { + var req ConnectRequest + json.NewDecoder(r.Body).Decode(&req) + req.BatchResume = false + body, _ := json.Marshal(req) + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + } + next.ServeHTTP(w, r) + }) + } + e := newResumeE2E(t, PollModeStream, nil, middleware) + conn, sess := e.dial(t, func(c *Connector) { c.UploadStreamPreference = "" }) + hc, ok := conn.(*httpConn) + if !ok || hc.uploadStreamMode { + t.Fatalf("legacy fallback = %T, want non-resumable discrete uploads", conn) + } + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(5 * time.Second)) + stream.Write([]byte("legacy")) + buf := make([]byte, 6) + if _, err := io.ReadFull(stream, buf); err != nil || string(buf) != "legacy" { + t.Fatalf("legacy fallback echo = %q, %v", buf, err) + } +} diff --git a/client.go b/client.go index 0c5f111..7b7f9f3 100644 --- a/client.go +++ b/client.go @@ -142,14 +142,11 @@ type Connector struct { // PreferResume asks the server to make the session resumable: if the // transport later fails, the Conn resumes the same session (see // ResumeHandler) instead of surfacing TransportFailed, and the yamux - // session on top of it — with every stream in it — carries on. Only - // honoured for WebSocket transport or stream mode in both directions; - // ignored by a server with ServerConfig.EnableResume off, or an older - // server, with no visible difference to the caller. With - // UploadStreamPreference on auto, a failed upload probe means the - // connection falls back to a non-resumable one (it reconnects once, - // without asking for resume), since the probe's fallback — discrete - // uploads — cannot be resumed. + // session on top of it — with every stream in it — carries on. Supported + // for WebSocket and HTTP batch/stream directions. Older servers may only + // support two-way streams and WebSocket, or ignore resume entirely. A + // failed auto upload probe reconnects with batch uploads, retaining resume + // if the server advertised BatchResume support. PreferResume bool // MaxReplayBytes caps how much unacknowledged data each direction of a // resumable connection retains for replay; beyond it the connection @@ -191,13 +188,12 @@ func (c *Connector) logger() *slog.Logger { // Connect registers with the server and returns a ready virtual connection. func (c *Connector) Connect(ctx context.Context) (Conn, error) { - return c.connect(ctx, c.PreferResume) + return c.connect(ctx, c.PreferResume, false) } -// connect is Connect with the resume preference as a parameter, so the one -// case where a resumable connect has to be redone without resume (an upload -// probe failing, see below) can recurse exactly once. -func (c *Connector) connect(ctx context.Context, preferResume bool) (Conn, error) { +// connect can retry once with batch uploads after an unsuccessful stream probe, +// without mutating the caller's Connector or losing resume on capable servers. +func (c *Connector) connect(ctx context.Context, preferResume, forceBatchUpload bool) (Conn, error) { if c.BaseURL == "" { return nil, errors.New("pollmux: Connector.BaseURL is required") } @@ -226,7 +222,7 @@ func (c *Connector) connect(ctx context.Context, preferResume bool) (Conn, error CheckRedirect: noRedirect, } - cr, err := c.doConnect(ctx, connectClient, base, preferResume) + cr, err := c.doConnect(ctx, connectClient, base, preferResume, forceBatchUpload) if err != nil { return nil, err } @@ -236,15 +232,13 @@ func (c *Connector) connect(ctx context.Context, preferResume bool) (Conn, error } if cr.Resumable { - // The server only negotiates this for WebSocket or two-way stream - // mode; anything else is a server bug, and the grace is the client's - // retry budget, so both are checked the same way the stream-mode - // limits are below. + // The grace is the retry budget. Older servers may resume only streams + // or WebSocket; batch needs an explicit capability acknowledgement. if cr.Limits.ResumeGraceMS <= 0 { return nil, fmt.Errorf("pollmux: server negotiated a resumable session but sent non-positive resume_grace_ms=%d", cr.Limits.ResumeGraceMS) } - if cr.Transport != TransportWebSocket && (cr.PollMode != PollModeStream || cr.UploadStreamMode != PollModeStream) { + if cr.Transport != TransportWebSocket && !cr.BatchResume && (cr.PollMode != PollModeStream || cr.UploadStreamMode != PollModeStream) { return nil, fmt.Errorf("pollmux: server negotiated a resumable session on transport=%q poll_mode=%q upload_stream_mode=%q, "+ "which cannot be resumed", cr.Transport, cr.PollMode, cr.UploadStreamMode) } @@ -297,6 +291,10 @@ func (c *Connector) connect(ctx context.Context, preferResume bool) (Conn, error c.PollInterval, cycle, cr.Limits.PollTimeout(), cr.Limits.SessionTimeout(), ) } + if cr.Resumable && negotiatedMode == PollModeBatch && !negotiatedUpload && c.PollInterval >= cr.Limits.ResumeGrace() { + return nil, fmt.Errorf("pollmux: PollInterval=%v reaches resume_grace=%v; a healthy batch session would expire between polls", + c.PollInterval, cr.Limits.ResumeGrace()) + } // The server is authoritative: we may clamp down, never up. This is what // makes an oversized request impossible from a well-behaved client, and in @@ -307,24 +305,18 @@ func (c *Connector) connect(ctx context.Context, preferResume bool) (Conn, error logger := c.logger().With("session_id", cr.SessionID) if cr.Resumable { - // Two-way stream mode, negotiated resumable. The reliable layer - // needs the upload leg to actually be a send-stream, so the auto - // probe runs first, exactly as it would for a plain stream - // connection; if the path fails it, this session is useless (its - // fallback, discrete uploads, cannot be resumed) — drop it and - // connect again without asking for resume. - if c.UploadStreamPreference == "" { + // Probe only streamed uploads. A failed probe needs a fresh negotiation, + // since the existing session's upload mode is immutable. + if negotiatedUpload && c.UploadStreamPreference == "" { probeTimeout := orDuration(c.UploadProbeTimeout, DefaultUploadProbeTimeout) probeClient := &http.Client{Transport: c.newTransport(dialTimeout, cr.Limits.StreamMaxDuration()+pollGrace), CheckRedirect: noRedirect} ok := probeUploadStream(ctx, probeClient, fmt.Sprintf("%s/%s/poll", base, cr.SessionID), c.AuthToken, probeTimeout) probeClient.CloseIdleConnections() if !ok { - logger.Warn("pollmux: upload-stream probe did not pass within timeout; "+ - "a resumable session needs streamed uploads, so reconnecting without resume — "+ - "a proxy on this path likely buffers a long-lived request body instead of forwarding it live", + logger.Warn("pollmux: upload-stream probe did not pass; reconnecting with batch uploads", "probe_timeout", probeTimeout) c.deleteSession(base, cr.SessionID, connectClient) - return c.connect(ctx, false) + return c.connect(ctx, cr.BatchResume, true) } } return c.connectResumable(ctx, base, cr, dialTimeout, sendTimeout, pollGrace, coalesce) @@ -458,14 +450,15 @@ func (c *Connector) newTransport(dialTimeout, responseHeaderTimeout time.Duratio } // doConnect performs POST {prefix}/connect and parses the response. -func (c *Connector) doConnect(ctx context.Context, client *http.Client, base string, preferResume bool) (*ConnectResponse, error) { +func (c *Connector) doConnect(ctx context.Context, client *http.Client, base string, preferResume, forceBatchUpload bool) (*ConnectResponse, error) { body, err := json.Marshal(ConnectRequest{ ProtocolVersion: ProtocolVersion, Meta: c.Meta, PreferStreamMode: c.PreferStream, - PreferStreamUpload: c.UploadStreamPreference != PollModeBatch, + PreferStreamUpload: !forceBatchUpload && c.UploadStreamPreference != PollModeBatch, PreferWebSocket: c.PreferWebSocket, PreferResume: preferResume, + BatchResume: preferResume, }) if err != nil { return nil, fmt.Errorf("pollmux: failed to encode connect request: %w", err) diff --git a/handler.go b/handler.go index af3abde..63980d9 100644 --- a/handler.go +++ b/handler.go @@ -103,9 +103,9 @@ type ServerConfig struct { // EnableResume lets ConnectHandler negotiate a resumable session for a // client that sends PreferResume: the session and the yamux session on // top of it survive the transport breaking, as long as the client - // resumes (see ResumeHandler) within ResumeGrace. Only WebSocket - // transport and stream mode in both directions can be resumed; a batch - // negotiation ignores this. A client that does not ask, or a server + // resumes (see ResumeHandler) within ResumeGrace. WebSocket, stream and + // batch transports are supported; batch requires the client's BatchResume + // capability. A client that does not ask, or a server // with this left false, is completely unaffected. Mount ResumeHandler // when turning this on. EnableResume bool @@ -347,6 +347,7 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { s := newSession(id, meta) s.pollMode = negotiatedMode + s.uploadStream = negotiatedUpload == PollModeStream s.watchHighWater(cfg.HighWaterWarn, cfg.Logger) // Decided here, before the session is published, because @@ -360,6 +361,7 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { resumable := negotiateResume(cfg, req, transport, negotiatedMode, negotiatedUpload) if resumable { s.enableResume(cfg.MaxReplayBytes, cfg.ResumeGrace) + s.batchResume = req.BatchResume } // Register before the callback. The client's first poll can beat @@ -406,6 +408,7 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { UploadStreamMode: uploadStreamMode, Transport: transport, Resumable: resumable, + BatchResume: resumable && req.BatchResume, }) }) } @@ -442,21 +445,28 @@ func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { } if r.Header.Get(HeaderSendStream) == "true" { + if s.rs != nil && (s.transport == TransportWebSocket || !s.uploadStream) { + writeError(w, http.StatusBadRequest, "session did not negotiate streamed uploads") + return + } pollSendStream(w, r, s, cfg) return } if s.rs != nil { - // A resumable session only ever negotiated stream mode in both - // directions (or WebSocket, which never comes through here), so - // the only other request shape it accepts is a receive-only - // stream poll. A discrete send would bypass the reliable layer's - // numbering and corrupt the upstream offsets. - if r.Header.Get(HeaderReceiveOnly) != "true" || r.Header.Get(HeaderSendOnly) == "true" { - writeError(w, http.StatusBadRequest, "resumable session accepts only stream requests") + send := r.Header.Get(HeaderSendOnly) == "true" + receive := r.Header.Get(HeaderReceiveOnly) == "true" + if s.transport == TransportWebSocket || send == receive { + writeError(w, http.StatusBadRequest, "resumable HTTP session requires exactly one direction") return } - pollStream(w, r, s, cfg) + if receive && s.pollMode == PollModeStream { + pollStream(w, r, s, cfg) + } else if s.batchResume && (!send || !s.uploadStream) { + pollBatchResumable(w, r, s, st, cfg, h, send) + } else { + writeError(w, http.StatusBadRequest, "session did not negotiate this batch direction") + } return } diff --git a/protocol.go b/protocol.go index d916dbf..3e880a9 100644 --- a/protocol.go +++ b/protocol.go @@ -42,6 +42,12 @@ const ( // server discards the frames instead of writing them upstream. Always // sent together with HeaderSendStream, never alone. HeaderSendStreamProbe = "X-Send-Stream-Probe" + // HeaderSendOffset is the absolute byte offset of a resumable batch body. + // It appears on send-only requests and on data-bearing poll responses. + HeaderSendOffset = "X-Send-Offset" + // HeaderRecvOffset acknowledges all bytes below this offset in the opposite + // direction. Every resumable batch request and successful response carries it. + HeaderRecvOffset = "X-Recv-Offset" ) // Server-side defaults. See ServerConfig. @@ -169,10 +175,15 @@ type ConnectRequest struct { PreferWebSocket bool `json:"prefer_websocket,omitempty"` // PreferResume asks the server to make this session resumable across // transport failures (see ConnectResponse.Resumable and reliable.go). - // Gated by ServerConfig.EnableResume and by the negotiated transport: - // only WebSocket, or stream mode in both directions, can be resumed. An - // old server ignores the field and the client works exactly as before. + // Gated by ServerConfig.EnableResume. Batch directions additionally require + // BatchResume, so clients predating that protocol keep their old behaviour. + // An old server ignores the field and the client works exactly as before. PreferResume bool `json:"prefer_resume,omitempty"` + // BatchResume advertises support for numbered batch requests/responses. + // It does not enable resume on its own: PreferResume must also be true. + // Servers echo it only when resume is enabled for this session. Keeping it + // separate protects older resumable clients that only understand streams. + BatchResume bool `json:"batch_resume,omitempty"` } // ResumeRequest is the JSON body of POST {prefix}/{id}/resume, sent by a @@ -291,6 +302,11 @@ type ConnectResponse struct { // and reattaches through ResumeHandler instead of reconnecting. Empty // from an older server; a client must treat that as false. Resumable bool `json:"resumable,omitempty"` + // BatchResume confirms support for resumable batch directions, including + // falling back to discrete uploads when a stream-upload probe fails. + // Absent on older servers; their original stream/WebSocket resume remains + // usable, but batch directions must not be treated as resumable. + BatchResume bool `json:"batch_resume,omitempty"` } // errorResponse is the JSON body of any non-2xx answer from the handlers. diff --git a/resumable_client.go b/resumable_client.go index 59d24e8..a5c46ab 100644 --- a/resumable_client.go +++ b/resumable_client.go @@ -54,18 +54,22 @@ type resumableConn struct { rl *reliable // out: yamux → server (writePipe); in: server → yamux (readPipe) - // transport is TransportWebSocket or PollModeStream — the only two the - // server will negotiate Resumable for. - transport string - pollURL string - resumeURL string - deleteURL string - wsURL string - authToken string - - // pollClient and sendStreamClient serve the stream-mode legs, with the - // same timeouts httpConn gives them; httpClient serves the short, - // bounded requests — resume, DELETE, and the WebSocket dial. + // HTTP directions independently use batch or stream. transport is only + // TransportWebSocket for a single bidirectional WebSocket attachment. + transport string + pollStream bool + uploadStream bool + maxSendChunk int + pollInterval time.Duration + pollURL string + resumeURL string + deleteURL string + wsURL string + authToken string + + // pollClient handles batch or streamed downloads; sendStreamClient handles + // streamed uploads. httpClient serves bounded batch uploads, resume, + // DELETE, and the WebSocket dial. pollClient *http.Client sendStreamClient *http.Client httpClient *http.Client @@ -285,8 +289,20 @@ func (c *resumableConn) runLegs() error { go func() { errCh <- c.wsReadLoop(legCtx, ws) }() go func() { errCh <- c.wsWriteLoop(legCtx, ws) }() } else { - go func() { errCh <- c.downLoop(legCtx) }() - go func() { errCh <- c.upLoop(legCtx) }() + go func() { + if c.pollStream { + errCh <- c.downLoop(legCtx) + } else { + errCh <- c.batchDownLoop(legCtx) + } + }() + go func() { + if c.uploadStream { + errCh <- c.upLoop(legCtx) + } else { + errCh <- c.batchUpLoop(legCtx) + } + }() } err := <-errCh @@ -729,6 +745,10 @@ func (c *Connector) connectResumable(ctx context.Context, base string, cr *Conne logger: logger, rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), c.MaxReplayBytes), transport: cr.Transport, + pollStream: cr.PollMode == PollModeStream, + uploadStream: cr.UploadStreamMode == PollModeStream, + maxSendChunk: min(orInt(c.MaxSendChunk, DefaultMaxSendChunk), cr.Limits.MaxSendBytes), + pollInterval: c.PollInterval, pollURL: fmt.Sprintf("%s/%s/poll", base, cr.SessionID), resumeURL: fmt.Sprintf("%s/%s/resume", base, cr.SessionID), deleteURL: fmt.Sprintf("%s/%s", base, cr.SessionID), @@ -761,9 +781,21 @@ func (c *Connector) connectResumable(ctx context.Context, base string, cr *Conne } conn.ws.Store(ws) } else { + headerTimeout := pollGrace conn.transport = PollModeStream - conn.pollClient = &http.Client{Transport: c.newTransport(dialTimeout, pollGrace), CheckRedirect: noRedirect} - conn.sendStreamClient = &http.Client{Transport: c.newTransport(dialTimeout, cr.Limits.StreamMaxDuration()+pollGrace), CheckRedirect: noRedirect} + if !conn.pollStream { + conn.transport = PollModeBatch + headerTimeout += cr.Limits.PollTimeout() + } + // Bound batch bodies too: ResponseHeaderTimeout alone cannot detect a + // peer that sends headers and then stalls halfway through the payload. + conn.pollClient = &http.Client{Transport: c.newTransport(dialTimeout, headerTimeout), CheckRedirect: noRedirect} + if !conn.pollStream { + conn.pollClient.Timeout = dialTimeout + headerTimeout + } + if conn.uploadStream { + conn.sendStreamClient = &http.Client{Transport: c.newTransport(dialTimeout, cr.Limits.StreamMaxDuration()+pollGrace), CheckRedirect: noRedirect} + } } c.adoptSession(cr.SessionID) diff --git a/resume_server.go b/resume_server.go index 53f4ea4..5323455 100644 --- a/resume_server.go +++ b/resume_server.go @@ -76,6 +76,11 @@ func (a *attachments) attach(kind attachKind, kick func()) (*attachment, error) for _, k := range kinds { for { a.mu.Lock() + if a.resuming { + a.mu.Unlock() + a.detach(att) + return nil, errStillAttached + } slot := a.slot(k) old := *slot if old == nil { @@ -271,10 +276,9 @@ func ResumeHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { } // negotiateResume decides whether a session is made resumable: the server -// must enable it, the client must ask, and the negotiated transport must be -// one the reliable layer covers — WebSocket, or stream mode in both -// directions. Batch mode is left out on purpose: one response per message -// gives the seam nothing to replay into. +// must enable it and the client must ask. Older resumable clients only know +// WebSocket and two-way streams; batch/mixed HTTP needs the additional +// BatchResume capability to avoid upgrading such clients to an unknown wire format. func negotiateResume(cfg ServerConfig, req ConnectRequest, transport, pollMode, uploadMode string) bool { if !cfg.EnableResume || !req.PreferResume { return false @@ -282,5 +286,5 @@ func negotiateResume(cfg ServerConfig, req ConnectRequest, transport, pollMode, if transport == TransportWebSocket { return true } - return pollMode == PollModeStream && uploadMode == PollModeStream + return req.BatchResume || (pollMode == PollModeStream && uploadMode == PollModeStream) } diff --git a/resume_test.go b/resume_test.go index 8b30521..1997eb0 100644 --- a/resume_test.go +++ b/resume_test.go @@ -189,6 +189,11 @@ func TestConnectNegotiatesResumeOnlyForResumableTransports(t *testing.T) { {"download-only stream", nil, ConnectRequest{PreferStreamMode: true, PreferResume: true}, false}, {"upload-only stream", nil, ConnectRequest{PreferStreamUpload: true, PreferResume: true}, false}, {"batch", nil, ConnectRequest{PreferResume: true}, false}, + {"batch with capability", nil, ConnectRequest{PreferResume: true, BatchResume: true}, true}, + {"download-only stream with capability", nil, ConnectRequest{PreferStreamMode: true, PreferResume: true, BatchResume: true}, true}, + {"upload-only stream with capability", nil, ConnectRequest{PreferStreamUpload: true, PreferResume: true, BatchResume: true}, true}, + {"batch capability alone", nil, ConnectRequest{BatchResume: true}, false}, + {"batch server has resume off", func(c *ServerConfig) { c.EnableResume = false }, ConnectRequest{PreferResume: true, BatchResume: true}, false}, {"client does not ask", nil, ConnectRequest{PreferStreamMode: true, PreferStreamUpload: true}, false}, {"server has resume off", func(c *ServerConfig) { c.EnableResume = false }, ConnectRequest{PreferStreamMode: true, PreferStreamUpload: true, PreferResume: true}, false}, @@ -211,6 +216,9 @@ func TestConnectNegotiatesResumeOnlyForResumableTransports(t *testing.T) { t.Fatalf("Resumable = %v, want %v (transport=%q poll_mode=%q upload=%q)", cr.Resumable, tc.want, cr.Transport, cr.PollMode, cr.UploadStreamMode) } + if cr.BatchResume != (tc.want && tc.req.BatchResume) { + t.Fatalf("BatchResume = %v, want %v", cr.BatchResume, tc.want && tc.req.BatchResume) + } if tc.want && cr.Limits.ResumeGrace() != cfg.ResumeGrace { t.Fatalf("resume_grace_ms = %v, want %v", cr.Limits.ResumeGrace(), cfg.ResumeGrace) } @@ -247,7 +255,7 @@ func TestResumeHandlerStatuses(t *testing.T) { t.Fatalf("unknown session = %d, want 404", resp.StatusCode) } - plain := connectOK(t, ts) // batch: never resumable + plain := connectOK(t, ts) // no resume requested if resp, _ := postResume(t, ts, plain.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}); resp.StatusCode != http.StatusConflict { t.Fatalf("non-resumable session = %d, want 409", resp.StatusCode) } @@ -864,6 +872,9 @@ func newResumeE2E(t *testing.T, mode string, tweak func(*ServerConfig), middlewa ResumeGrace: 3 * time.Second, }, } + if mode == PollModeBatch { + e.cfg.PollMode = PollModeBatch + } if tweak != nil { tweak(&e.cfg) } @@ -923,11 +934,14 @@ func (e *resumeE2E) connector(tweak func(*Connector)) *Connector { PollGrace: 300 * time.Millisecond, SendTimeout: time.Second, DialTimeout: time.Second, - PreferStream: true, + PreferStream: e.mode != PollModeBatch && e.mode != "batch-stream", UploadStreamPreference: PollModeStream, PreferWebSocket: e.mode == TransportWebSocket, PreferResume: true, } + if e.mode == PollModeBatch || e.mode == "stream-batch" { + c.UploadStreamPreference = PollModeBatch + } if tweak != nil { tweak(c) } @@ -1315,9 +1329,8 @@ func TestE2EResumeStaysOffWhenClientDoesNotAsk(t *testing.T) { } } -// Auto upload probe fails on a resumable connect: the client cannot run the -// reliable layer over discrete uploads, so it drops that session and -// connects again without resume — one session left, one clean delete. +// A failed upload probe renegotiates batch uploads without giving up resume +// on a server that supports the numbered batch protocol. func TestE2EResumeFallsBackWhenUploadProbeFails(t *testing.T) { stall := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1336,24 +1349,37 @@ func TestE2EResumeFallsBackWhenUploadProbeFails(t *testing.T) { }) } e := newResumeE2E(t, PollModeStream, nil, stall) - conn, _ := e.dial(t, func(c *Connector) { + conn, sess := e.dial(t, func(c *Connector) { c.UploadStreamPreference = "" c.UploadProbeTimeout = 300 * time.Millisecond }) - if _, ok := conn.(*resumableConn); ok { - t.Fatal("kept a resumable conn after the probe failed") - } - hc, ok := conn.(*httpConn) - if !ok || hc.uploadStreamMode { - t.Fatalf("fallback conn = %T (uploadStreamMode=%v), want *httpConn on discrete uploads", conn, ok && hc.uploadStreamMode) + rc, ok := conn.(*resumableConn) + if !ok || rc.uploadStream || !rc.pollStream { + t.Fatalf("fallback conn = %T, want resumable stream download with batch upload", conn) } waitFor(t, 2*time.Second, func() bool { return e.store.Len() == 1 }) if r := e.reasons(); len(r) != 1 || r[0] != ReasonClientDelete { t.Fatalf("disconnects = %v, want the abandoned session deleted once", r) } s, _ := e.store.Get(conn.SessionID()) - if s.Resumable() { - t.Fatal("the replacement session must not be resumable") + if !s.Resumable() { + t.Fatal("the replacement session must remain resumable") + } + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.SetDeadline(time.Now().Add(10 * time.Second)) + stream.Write([]byte("before")) + buf := make([]byte, 6) + if _, err := io.ReadFull(stream, buf); err != nil { + t.Fatal(err) + } + e.proxy.killAll() + stream.Write([]byte("after!")) + if _, err := io.ReadFull(stream, buf); err != nil || string(buf) != "after!" { + t.Fatalf("fallback stream did not survive a kill: %q, %v", buf, err) } } diff --git a/session.go b/session.go index 5521763..18ff557 100644 --- a/session.go +++ b/session.go @@ -37,6 +37,10 @@ type Session struct { // so PollHandler can read it with no lock, the same way it already // treats meta as effectively immutable post-construction. pollMode string + // uploadStream and batchResume are negotiated once, before publication. + // They keep legacy raw batch bodies out of the reliable byte stream. + uploadStream bool + batchResume bool // transport is "" or TransportWebSocket, set once by ConnectHandler // alongside pollMode and likewise never mutated after. WebSocketHandler diff --git a/session_guard.go b/session_guard.go index 5419447..9cbb784 100644 --- a/session_guard.go +++ b/session_guard.go @@ -59,5 +59,5 @@ func isSessionClosedErr(err error) bool { return true } var f *fatalPollError - return errors.As(err, &f) && f.status == http.StatusGone + return errors.As(err, &f) && (f.status == http.StatusGone || f.status == http.StatusNotFound) } From c881e3a6195f22441e496f99c9be266d5d34988f Mon Sep 17 00:00:00 2001 From: MasterCoderK <8674856+DiamondGo@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:39:53 -0700 Subject: [PATCH 2/4] fix: address review findings on resumable batch transport - Restart every batch poll response at the poll's cumulative ack, so a response lost without a handshake (e.g. a stale poll delivered late by a proxy) is resent instead of leaving a gap that breaks the session. - Refuse poll, WebSocket and resume attaches once a detached resumable session's grace has expired, even before the sweeper evicts it. - Accept an empty chunked receive-only poll; reject only actual body bytes. - Reject a 200 batch poll response with an empty body on the client. - Make the concurrent-streams test keep killing until a resume is observed. --- README.md | 8 +++-- batch.go | 33 ++++++++++++++---- batch_resume_test.go | 80 ++++++++++++++++++++++++++++++++++++++++++-- reliable.go | 14 ++++++++ resume_test.go | 32 ++++++++++++++++++ session.go | 22 ++++++++++-- websocket.go | 2 +- 7 files changed, 175 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 5850dc5..39f8504 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ On transport failure, the client stops both directions, then sends `POST /{prefi **The session ID, server session, and yamux session stay the same.** A successful recovery is internal to the connection and does not close its transport-failed signal. Reads can block through the outage. Transport-level writes queue locally without waiting for the network, avoiding yamux's connection write timeout during recovery, but **application/yamux stream writes can still block on flow control** once their window is exhausted. Application contexts, stream deadlines, and business timeouts still apply; resume does not suspend or extend them. This is ordered byte-stream recovery, not a guarantee that an application has processed or committed a business operation. -During a valid detached grace period, the server does not evict the session using ordinary idle timeout. [`CloseSessionIfNoPollInFlight()`](handler.go#L888) also treats it as busy, so a reaper using that helper need not learn a separate resume policy. Applications can inspect [`Session.Resumable()`](session.go#L122) and [`Session.ResumeDeadline()`](session.go#L132) for monitoring. Explicit session close, DELETE, and shutdown still terminate it; resume never resurrects a deliberately closed session. +During a valid detached grace period, the server does not evict the session using ordinary idle timeout. [`CloseSessionIfNoPollInFlight()`](handler.go#L888) also treats it as busy, so a reaper using that helper need not learn a separate resume policy. Applications can inspect [`Session.Resumable()`](session.go#L122) and [`Session.ResumeDeadline()`](session.go#L132) for monitoring. Explicit session close, DELETE, and shutdown still terminate it; resume never resurrects a deliberately closed session. Once the grace has run out, any late attach (poll, upload, WebSocket, or resume) gets 410 even if the sweeper has not evicted the session yet, so the recovery window is exactly `resume_grace_ms`. ### Resumable batch wire behavior @@ -243,8 +243,8 @@ Resumable batches are **raw, bounded, finite HTTP bodies**, not framed streams h | Message | Required offset headers | |---|---| | Send-only batch request | `X-Send-Offset`: absolute starting upload byte offset; `X-Recv-Offset`: cumulative downstream acknowledgment | -| Receive-only batch request, with an empty body | `X-Recv-Offset`: cumulative downstream acknowledgment | -| 200 batch poll response | `X-Send-Offset`: absolute starting download byte offset; `X-Recv-Offset`: cumulative upstream acknowledgment | +| Receive-only batch request, with an empty body (`Content-Length: 0` or an empty chunked body) | `X-Recv-Offset`: cumulative downstream acknowledgment | +| 200 batch poll response, always with a non-empty body | `X-Send-Offset`: absolute starting download byte offset; `X-Recv-Offset`: cumulative upstream acknowledgment | | Successful batch upload response or 204 idle poll response | `X-Recv-Offset`: cumulative upstream acknowledgment | Offsets are unsigned decimal byte counts, present even when zero. Each required header must have exactly one value; missing, malformed, duplicated, or ambiguous values are rejected. Every batch request and successful batch response carries the cumulative receive acknowledgment, **including 204**. Mixed HTTP sessions use these headers on the batch direction and numbered frames/ACKs on the streaming direction. @@ -253,6 +253,8 @@ The server reads an entire upload successfully before accepting its data into th If an upload was accepted but its 200 response was lost, or a download was truncated after leaving the server queue, the sender still retains the unacknowledged bytes. The client performs the resume handshake **before retransmitting**, and the absolute offsets prevent duplicate delivery while replaying whatever is missing. A raw batch retry without the handshake is not the client's recovery algorithm. +Batch downloads are strictly serial, so the server also starts every poll response at that poll's cumulative acknowledgment. A response lost without any handshake, such as a stale poll that a proxy delivered after the client had already resumed, is therefore resent by the next poll instead of leaving a gap. An idle poll is answered with 204; the client rejects a 200 with an empty body as malformed. + Pure-batch resumable sessions must have [`Connector.PollInterval`](client.go#L86) **strictly below the negotiated resume grace**; connect rejects an interval reaching that grace. Between finite requests there may be no attachment, so a healthy client must poll again before its detached session expires. The default zero interval is recommended. ### Recovery limits and failure cases diff --git a/batch.go b/batch.go index 99c1cb6..d56ec0b 100644 --- a/batch.go +++ b/batch.go @@ -32,6 +32,17 @@ func setBatchOffset(h http.Header, name string, off uint64) { h.Set(name, strconv.FormatUint(off, 10)) } +// bodyIsEmpty reports whether a body of unknown length (chunked, or an HTTP/2 +// request without content-length) carries no bytes. The deadline is cleared +// before returning: a parked poll must not inherit it, or the server's +// background read would cancel the request once it expired. +func bodyIsEmpty(rc *http.ResponseController, body io.Reader) bool { + rc.SetReadDeadline(time.Now().Add(defaultStreamReadGrace)) + defer rc.SetReadDeadline(time.Time{}) + n, err := io.Copy(io.Discard, io.LimitReader(body, 1)) + return n == 0 && err == nil +} + // pollBatchResumable owns exactly one direction until the request finishes. // ResumeHandler can cancel even a parked poll or a half-read upload before // examining offsets. Incomplete uploads never enter the reliable byte stream. @@ -41,6 +52,12 @@ func pollBatchResumable(w http.ResponseWriter, r *http.Request, s *Session, st * writeError(w, http.StatusBadRequest, err.Error()) return } + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + rc := http.NewResponseController(w) + defer rc.SetReadDeadline(time.Time{}) + defer rc.SetWriteDeadline(time.Time{}) + var off uint64 if send { off, err = batchOffset(r.Header, HeaderSendOffset) @@ -48,16 +65,10 @@ func pollBatchResumable(w http.ResponseWriter, r *http.Request, s *Session, st * writeError(w, http.StatusBadRequest, err.Error()) return } - } else if r.ContentLength != 0 { + } else if r.ContentLength != 0 && !bodyIsEmpty(rc, r.Body) { writeError(w, http.StatusBadRequest, "receive-only batch must have an empty body") return } - - ctx, cancel := context.WithCancel(r.Context()) - defer cancel() - rc := http.NewResponseController(w) - defer rc.SetReadDeadline(time.Time{}) - defer rc.SetWriteDeadline(time.Time{}) kind := attachDown if send { kind = attachUp @@ -116,6 +127,9 @@ func pollBatchResumable(w http.ResponseWriter, r *http.Request, s *Session, st * return } + // A batch client polls serially, so its ack is exactly where this response + // must start. Anything past it went out in a response the client never got. + s.rs.rewindToAcked() buf := make([]byte, cfg.PollBufferSize) off, n, err := s.rs.nextOut(buf, cfg.PollTimeout, cfg.CoalesceWindow) if ctx.Err() != nil { @@ -190,6 +204,11 @@ func (c *resumableConn) doBatchPoll(ctx context.Context) (bool, error) { if len(data) > c.maxFrame { return false, errors.New("pollmux: batch response exceeds poll_buffer_bytes") } + // An idle poll is 204; an empty 200 is malformed and, with no PollInterval, + // would otherwise be re-polled in a tight loop. + if resp.StatusCode == http.StatusOK && len(data) == 0 { + return false, errors.New("pollmux: batch response is 200 with an empty body") + } ack, err := batchOffset(resp.Header, HeaderRecvOffset) if err != nil { return false, err diff --git a/batch_resume_test.go b/batch_resume_test.go index 9eeea2c..aba5928 100644 --- a/batch_resume_test.go +++ b/batch_resume_test.go @@ -1,6 +1,7 @@ package pollmux import ( + "bufio" "bytes" "context" "encoding/json" @@ -130,6 +131,74 @@ func TestBatchResumeDownstreamReplaysOnlyMissingBytes(t *testing.T) { } } +// A poll whose response never reached the client (a stale request delivered +// late, say) is not followed by a handshake; the next poll's ack alone must be +// enough to resend what was lost. +func TestBatchResumePollRestartsAtItsAcknowledgement(t *testing.T) { + cfg := testResumeServerConfig() + cfg.PollBufferSize = 5 + ts, st := newResumeTestServer(t, cfg, Hooks{}) + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + s.Write([]byte("abcdefghij")) + if _, data := rawBatch(t, ts, cr.SessionID, false, 0, 0, nil); string(data) != "abcde" { + t.Fatalf("lost batch = %q", data) + } + resp, data := rawBatch(t, ts, cr.SessionID, false, 0, 0, nil) + if string(data) != "abcde" { + t.Fatalf("poll after lost response = %q, want the lost bytes again", data) + } + requireBatchOffset(t, resp, HeaderSendOffset, 0) + resp, data = rawBatch(t, ts, cr.SessionID, false, 0, 5, nil) + if string(data) != "fghij" { + t.Fatalf("next batch = %q", data) + } + requireBatchOffset(t, resp, HeaderSendOffset, 5) + // A stale ack cannot rewind below what the client already confirmed. + resp, data = rawBatch(t, ts, cr.SessionID, false, 0, 0, nil) + if string(data) != "fghij" { + t.Fatalf("poll with stale ack = %q", data) + } + requireBatchOffset(t, resp, HeaderSendOffset, 5) + if !s.Resumable() { + t.Fatal("stale ack broke resumability") + } +} + +// Proxies may re-frame an empty POST as chunked; only actual bytes make a +// receive-only poll malformed. +func TestBatchResumeChunkedReceiveOnlyPoll(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + s.Write([]byte("down")) + for _, tc := range []struct { + chunks string + want int + }{{"0\r\n\r\n", http.StatusOK}, {"3\r\nabc\r\n0\r\n\r\n", http.StatusBadRequest}} { + conn, err := net.DialTimeout("tcp", strings.TrimPrefix(ts.URL, "http://"), time.Second) + if err != nil { + t.Fatal(err) + } + if _, err := fmt.Fprintf(conn, "POST /tunnel/%s/poll HTTP/1.1\r\nHost: test\r\nTransfer-Encoding: chunked\r\n%s: true\r\n%s: 0\r\n\r\n%s", + cr.SessionID, HeaderReceiveOnly, HeaderRecvOffset, tc.chunks); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + t.Fatal(err) + } + data, _ := io.ReadAll(resp.Body) + conn.Close() + if resp.StatusCode != tc.want { + t.Fatalf("chunked poll %q = %d, want %d", tc.chunks, resp.StatusCode, tc.want) + } + if tc.want == http.StatusOK && string(data) != "down" { + t.Fatalf("chunked poll data = %q", data) + } + } +} + func TestBatchResumeRejectsInvalidRequests(t *testing.T) { cases := []struct { name string @@ -283,6 +352,7 @@ func TestBatchResumeClientValidatesResponses(t *testing.T) { {"gap", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "1"}, "abc"}, {"bad ack", 204, map[string]string{HeaderRecvOffset: "1"}, ""}, {"oversized", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "0"}, "123456789"}, + {"empty data", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "0"}, ""}, {"truncated", 200, map[string]string{HeaderRecvOffset: "0", HeaderSendOffset: "0", "Content-Length": "8"}, "abc"}, {"closed", 410, nil, ""}, } { @@ -700,7 +770,12 @@ func TestBatchResumeConcurrentStreams(t *testing.T) { } } close(start) - for i := 0; i < 3; i++ { + // A kill can land between finite batch requests and break nothing, so keep + // going until one demonstrably forced a resume. + for i := 0; i < 3 || e.resumes.Load() == 0; i++ { + if i == 300 { + t.Fatal("no transport kill forced a resume") + } e.proxy.killAll() time.Sleep(15 * time.Millisecond) } @@ -715,7 +790,8 @@ func TestBatchResumeConcurrentStreams(t *testing.T) { } } if conn.SessionID() != id || sess.IsClosed() || isClosed(conn.TransportFailed()) || e.resumes.Load() == 0 { - t.Fatal("concurrent streams did not retain their session") + t.Fatalf("concurrent streams did not retain their session: id changed=%v yamux closed=%v transport failed=%v resumes=%d", + conn.SessionID() != id, sess.IsClosed(), isClosed(conn.TransportFailed()), e.resumes.Load()) } } diff --git a/reliable.go b/reliable.go index 820a5a5..f345e0c 100644 --- a/reliable.go +++ b/reliable.go @@ -215,6 +215,20 @@ func (r *reliable) resumeOut(peerRecv uint64) bool { return true } +// rewindToAcked makes the next nextOut resend everything the peer has not +// acknowledged. Only valid for a direction whose transport carries at most one +// response at a time and opens each request with a cumulative ack (batch +// polls): there, anything sent but not acked was lost along with its response, +// even when no resume handshake follows, as with a stale request that attached +// late and answered a peer no longer listening. +func (r *reliable) rewindToAcked() { + r.mu.Lock() + if !r.broken { + r.sentCursor = r.ackedOffset + } + r.mu.Unlock() +} + // recvOffsetNow is what this end reports in a resume handshake. func (r *reliable) recvOffsetNow() uint64 { r.mu.Lock() diff --git a/resume_test.go b/resume_test.go index 1997eb0..61bfb45 100644 --- a/resume_test.go +++ b/resume_test.go @@ -1622,3 +1622,35 @@ func TestRelayStreamDiesOnKillWithoutResume(t *testing.T) { t.Fatal("consumer reused the dead session id") } } + +// Grace is enforced at attach time, not only by the sweeper: a session past it +// must not be revived by a request that beats the next sweep. +func TestResumeExpiredGraceRefusesLateAttach(t *testing.T) { + expire := func(s *Session) { + s.mu.Lock() + s.detachedAt = time.Now().Add(-2 * s.resumeGrace) + s.mu.Unlock() + } + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + + cr := connectResumableBatch(t, ts) + s, _ := st.Get(cr.SessionID) + expire(s) + if resp, _ := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}); resp.StatusCode != http.StatusGone { + t.Fatalf("resume after grace = %d, want 410", resp.StatusCode) + } + if resp, _ := rawBatch(t, ts, cr.SessionID, false, 0, 0, nil); resp.StatusCode != http.StatusGone { + t.Fatalf("poll after grace = %d, want 410", resp.StatusCode) + } + if s.PollInFlight() != 0 { + t.Fatal("refused attach left the session marked active") + } + + _, wcr := postConnect(t, ts, ConnectRequest{ProtocolVersion: ProtocolVersion, PreferWebSocket: true, PreferResume: true}) + ws, _ := st.Get(wcr.SessionID) + expire(ws) + _, resp, err := websocket.Dial(context.Background(), ts.URL+"/tunnel/"+wcr.SessionID+"/ws", nil) + if err == nil || resp == nil || resp.StatusCode != http.StatusGone { + t.Fatalf("websocket after grace = (%v, %v), want 410", resp, err) + } +} diff --git a/session.go b/session.go index 18ff557..f06cce9 100644 --- a/session.go +++ b/session.go @@ -148,6 +148,14 @@ func (s *Session) inResumeGraceLocked(now time.Time) bool { now.Sub(s.detachedAt) <= s.resumeGrace } +// resumeExpiredLocked reports whether s is a detached resumable session whose +// grace has run out but which the sweeper has not evicted yet. Such a session +// must not be revived by a late attach. s.mu must be held. +func (s *Session) resumeExpiredLocked(now time.Time) bool { + return s.rs != nil && s.pollInFlight == 0 && !s.rs.isBroken() && + now.Sub(s.detachedAt) > s.resumeGrace +} + // watchHighWater arms the high-water warning on both pipes. func (s *Session) watchHighWater(threshold int, logger *slog.Logger) { if threshold <= 0 || logger == nil { @@ -205,11 +213,11 @@ func (s *Session) closePipes() { } // beginPoll atomically attaches a poll or persistent transport unless the -// session has already been closed. +// session has already been closed or its resume grace has expired. func (s *Session) beginPoll() bool { s.mu.Lock() defer s.mu.Unlock() - if s.closed { + if s.closed || s.resumeExpiredLocked(time.Now()) { return false } s.pollInFlight++ @@ -234,7 +242,7 @@ func (s *Session) noteDetachedLocked() { func (s *Session) beginWebSocket() bool { s.mu.Lock() defer s.mu.Unlock() - if s.closed || s.wsAttached { + if s.closed || s.wsAttached || s.resumeExpiredLocked(time.Now()) { return false } s.wsAttached = true @@ -255,6 +263,14 @@ func (s *Session) writeUpstream(p []byte) (int, error) { return s.toServer.Write(p) } +// refusesAttach reports whether every future attach will be refused: the +// session is closed, or it is resumable and its grace expired while detached. +func (s *Session) refusesAttach() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.closed || s.resumeExpiredLocked(time.Now()) +} + // IsClosed reports whether Close has been called. func (s *Session) IsClosed() bool { s.mu.Lock() diff --git a/websocket.go b/websocket.go index bac1d97..da2c2f1 100644 --- a/websocket.go +++ b/websocket.go @@ -115,7 +115,7 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler } if !s.beginWebSocket() { - if s.IsClosed() { + if s.refusesAttach() { writeError(w, http.StatusGone, "session closed") } else { writeError(w, http.StatusConflict, "session already has a websocket attached") From 143308e3bd5d67a73f7e44ae2736cca898a0a5b7 Mon Sep 17 00:00:00 2001 From: MasterCoderK <8674856+DiamondGo@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:57:58 -0700 Subject: [PATCH 3/4] fix: spare healthy batch sessions from the detached cap; drop redundant acks - A resumable pure-batch session has nothing attached between two polls, so the sweeper counted healthy clients against MaxDetachedResumable and could evict them. The client now declares poll_interval_ms at connect; the server counts such a session only once it has been detached longer than that interval (clamped to the grace) plus a fixed 10s allowance. - Batch requests and responses already carry the cumulative ack, so turn off the reliable layer's eager-ack wakeup for those directions and skip ack-only uploads when downloads are batch. An 8 MiB echo previously added about one empty 204 poll per upload plus several ack-only uploads. - Fix README code links whose line numbers had drifted. --- README.md | 22 +++++----- batch.go | 4 +- batch_resume_test.go | 95 ++++++++++++++++++++++++++++++++++++++++++++ client.go | 1 + handler.go | 16 +++++++- protocol.go | 12 ++++++ reliable.go | 12 +++++- reliable_test.go | 11 +++++ resumable_client.go | 2 + session.go | 13 ++++++ store.go | 8 ++-- 11 files changed, 177 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 39f8504..95f35fc 100644 --- a/README.md +++ b/README.md @@ -27,9 +27,9 @@ All handlers for a deployment should share one store, configuration, and hook se | Method | Path | Handler | |---|---|---| -| POST | `/tunnel/connect` | [`ConnectHandler()`](handler.go#L288) | -| POST | `/tunnel/{id}/poll` | [`PollHandler()`](handler.go#L422), for both HTTP directions | -| DELETE | `/tunnel/{id}` | [`DeleteHandler()`](handler.go#L836) | +| POST | `/tunnel/connect` | [`ConnectHandler()`](handler.go#L291) | +| POST | `/tunnel/{id}/poll` | [`PollHandler()`](handler.go#L434), for both HTTP directions | +| DELETE | `/tunnel/{id}` | [`DeleteHandler()`](handler.go#L848) | | GET | `/tunnel/{id}/ws` | [`WebSocketHandler()`](websocket.go#L62), when WebSocket is offered | | POST | `/tunnel/{id}/resume` | [`ResumeHandler()`](resume_server.go#L208), when resume is offered | @@ -129,7 +129,7 @@ The configured [`MaxStreamWindowSize`](yamux.go#L27) is 256 KiB, yamux's **minim The flow-control buffering budget is roughly window size × concurrent streams: **256 KiB × 256 streams ≈ 64 MiB per tunnel**, multiplied by the number of tunnels in a multi-tenant deployment. This is not a hard bound on total process memory: pipes, replay buffers, HTTP bodies, and application state add overhead. [`BufferedPipe`](pipe.go#L23) itself has no backpressure; normal yamux flow control is what bounds ordinary stream traffic. Applications writing arbitrary bytes directly to a connection cannot assume the same protection. -Limit concurrent streams rather than trying to shrink the window below yamux's floor. Use [`BufferedPipe.HiWater()`](pipe.go#L65), [`Session.HiWater()`](session.go#L299), and [`ServerConfig.HighWaterWarn`](handler.go#L65) to observe actual buffering. +Limit concurrent streams rather than trying to shrink the window below yamux's floor. Use [`BufferedPipe.HiWater()`](pipe.go#L65), [`Session.HiWater()`](session.go#L328), and [`ServerConfig.HighWaterWarn`](handler.go#L65) to observe actual buffering. ## Transport behavior and caveats @@ -212,7 +212,7 @@ Resume requires all of the following: 3. [`ResumeHandler()`](resume_server.go#L208) is mounted at `POST /{prefix}/{id}/resume` behind the **same authentication middleware as poll, DELETE, and WebSocket**. 4. The connect response actually negotiates `resumable: true`. -The API switches remain the same: the client requests `prefer_resume` and the server responds with `resumable`. New clients automatically send [`ConnectRequest.BatchResume`](protocol.go#L186), wire field `batch_resume`, when requesting resume. This capability **does not enable resume on its own**. New servers echo [`ConnectResponse.BatchResume`](protocol.go#L309) only for resumable sessions when the client advertised it. +The API switches remain the same: the client requests `prefer_resume` and the server responds with `resumable`. New clients automatically send [`ConnectRequest.BatchResume`](protocol.go#L192), wire field `batch_resume`, when requesting resume. This capability **does not enable resume on its own**. New servers echo [`ConnectResponse.BatchResume`](protocol.go#L321) only for resumable sessions when the client advertised it. | Negotiated transport | With batch-resume capability | Without batch-resume capability | |---|---|---| @@ -228,13 +228,13 @@ Every resumable entry still requires both resume switches. This additive capabil Without resume, transport loss ends the virtual connection, and a reconnect creates a new session ID and a new yamux session. Existing application streams cannot survive that replacement. -With resume, a reliable byte layer sits below yamux. Each direction has absolute byte offsets, cumulative acknowledgments, and a replay buffer. Bytes remain retained until the peer acknowledges receiving them; a successful local HTTP write alone is not an acknowledgment. Stream/WebSocket transports carry numbered data and ACK frames, with ACKs sent alongside reverse traffic/heartbeats and an eager ACK wakeup at half a yamux window. +With resume, a reliable byte layer sits below yamux. Each direction has absolute byte offsets, cumulative acknowledgments, and a replay buffer. Bytes remain retained until the peer acknowledges receiving them; a successful local HTTP write alone is not an acknowledgment. Stream/WebSocket transports carry numbered data and ACK frames, with ACKs sent alongside reverse traffic/heartbeats and an eager ACK wakeup at half a yamux window. Batch requests and responses carry the cumulative ACK in headers every time, so a direction whose ACKs travel that way skips the eager wakeup and never issues ACK-only requests. On transport failure, the client stops both directions, then sends `POST /{prefix}/{id}/resume` with its protocol version and `recv_offset`: the number of downstream bytes received contiguously. The server first cancels and waits out old attachments, then answers with its contiguous upstream `recv_offset`. Each side replays from the other side's offset before sending new bytes. Duplicate or overlapping replay is discarded; gaps and impossible acknowledgments are rejected rather than corrupting yamux's byte stream. Only one transport owns each direction at a time, including during a resume handshake. **The session ID, server session, and yamux session stay the same.** A successful recovery is internal to the connection and does not close its transport-failed signal. Reads can block through the outage. Transport-level writes queue locally without waiting for the network, avoiding yamux's connection write timeout during recovery, but **application/yamux stream writes can still block on flow control** once their window is exhausted. Application contexts, stream deadlines, and business timeouts still apply; resume does not suspend or extend them. This is ordered byte-stream recovery, not a guarantee that an application has processed or committed a business operation. -During a valid detached grace period, the server does not evict the session using ordinary idle timeout. [`CloseSessionIfNoPollInFlight()`](handler.go#L888) also treats it as busy, so a reaper using that helper need not learn a separate resume policy. Applications can inspect [`Session.Resumable()`](session.go#L122) and [`Session.ResumeDeadline()`](session.go#L132) for monitoring. Explicit session close, DELETE, and shutdown still terminate it; resume never resurrects a deliberately closed session. Once the grace has run out, any late attach (poll, upload, WebSocket, or resume) gets 410 even if the sweeper has not evicted the session yet, so the recovery window is exactly `resume_grace_ms`. +During a valid detached grace period, the server does not evict the session using ordinary idle timeout. [`CloseSessionIfNoPollInFlight()`](handler.go#L900) also treats it as busy, so a reaper using that helper need not learn a separate resume policy. Applications can inspect [`Session.Resumable()`](session.go#L127) and [`Session.ResumeDeadline()`](session.go#L137) for monitoring. Explicit session close, DELETE, and shutdown still terminate it; resume never resurrects a deliberately closed session. Once the grace has run out, any late attach (poll, upload, WebSocket, or resume) gets 410 even if the sweeper has not evicted the session yet, so the recovery window is exactly `resume_grace_ms`. ### Resumable batch wire behavior @@ -263,9 +263,9 @@ Pure-batch resumable sessions must have [`Connector.PollInterval`](client.go#L86 |---|---| | [`ServerConfig.ResumeGrace`](handler.go#L119) | 30 seconds detached; hard maximum 5 minutes; configuration above the maximum panics | | [`MaxReplayBytes`](handler.go#L126) on the server and [`Connector.MaxReplayBytes`](client.go#L155) on the client | 16 MiB per outgoing direction; independently configured, not negotiated | -| [`ServerConfig.MaxDetachedResumable`](handler.go#L133) | 1,024 detached resumable sessions; the sweeper evicts longest-detached first; negative disables the cap | +| [`ServerConfig.MaxDetachedResumable`](handler.go#L136) | 1,024 detached resumable sessions; the sweeper evicts longest-detached first; negative disables the cap. A pure-batch session counts only after it has been detached longer than the client's declared `poll_interval_ms` (clamped to the grace) plus 10 seconds, because a healthy one has nothing attached between polls | -Start the configured [`StartSweeper()`](handler.go#L902) to enforce grace expiry and the detached-session cap. A detached session retains application state and replay memory, so grace and population limits are important memory controls, not just retry tuning. The replay limit covers retained, transmitted-but-unacknowledged bytes, not all queued data or total session memory. Normal yamux windowing helps bound pending traffic per active stream, but concurrency still matters. +Start the configured [`StartSweeper()`](handler.go#L914) to enforce grace expiry and the detached-session cap. A detached session retains application state and replay memory, so grace and population limits are important memory controls, not just retry tuning. The replay limit covers retained, transmitted-but-unacknowledged bytes, not all queued data or total session memory. Normal yamux windowing helps bound pending traffic per active stream, but concurrency still matters. Recovery ends and the client signals transport failure for a fresh-session reconnect when, for example: @@ -281,7 +281,7 @@ Sessions and replay buffers are **process-local and not persistent**. A server r ### Authentication boundary -[`Hooks.Authenticate`](handler.go#L249) authenticates **connect requests only**. It is not called by poll, DELETE, WebSocket, or resume handlers. Session IDs are random 128-bit values, but the application must still apply the same credential and session-authorization policy to **all** those routes. The client's bearer token is sent on subsequent requests as well. +[`Hooks.Authenticate`](handler.go#L252) authenticates **connect requests only**. It is not called by poll, DELETE, WebSocket, or resume handlers. Session IDs are random 128-bit values, but the application must still apply the same credential and session-authorization policy to **all** those routes. The client's bearer token is sent on subsequent requests as well. A caller reaching resume with an out-of-range `recv_offset` permanently invalidates that session's resumability and gets 409. This is intentional: letting an inconsistent peer guess offsets until one happens to fit could silently replay the wrong bytes. An authorized caller capable of this could also DELETE the session outright; that security argument only holds if no endpoint bypasses the common middleware. Never expose resume unprotected just because connect has an authentication hook. @@ -330,7 +330,7 @@ The upgrade has its own error surface: 404 for an unknown session, 400 for a ses ## Authoritative parameter negotiation -The server sends [`Limits`](protocol.go#L215) at connect time: `max_send_bytes`, `poll_timeout_ms`, `session_timeout_ms`, and `poll_buffer_bytes`; streaming in either direction or WebSocket additionally supplies `heartbeat_interval_ms` and `stream_max_duration_ms`. Resumable sessions also receive `resume_grace_ms`. WebSocket ignores stream duration even though it is included. +The server sends [`Limits`](protocol.go#L227) at connect time: `max_send_bytes`, `poll_timeout_ms`, `session_timeout_ms`, and `poll_buffer_bytes`; streaming in either direction or WebSocket additionally supplies `heartbeat_interval_ms` and `stream_max_duration_ms`. Resumable sessions also receive `resume_grace_ms`. WebSocket ignores stream duration even though it is included. **Configure shared transport limits on the server, not independently at both ends.** Clients validate the response and can only choose more conservative behavior, such as a smaller upload chunk. The server's negotiated modes and limits are authoritative; requests do not override a session's negotiated direction later. diff --git a/batch.go b/batch.go index d56ec0b..6fd4d45 100644 --- a/batch.go +++ b/batch.go @@ -242,8 +242,10 @@ func (c *resumableConn) batchUpLoop(ctx context.Context) error { if err != nil && !errors.Is(err, errPipeInterrupted) { return err } + // An ack-only upload is only needed when downloads stream; batch polls + // carry the ack themselves. _, due := c.rl.takeAck() - if n == 0 && !due { + if n == 0 && (!due || !c.pollStream) { continue } if err := c.doBatchSend(ctx, off, buf[:n]); err != nil { diff --git a/batch_resume_test.go b/batch_resume_test.go index aba5928..31a72f7 100644 --- a/batch_resume_test.go +++ b/batch_resume_test.go @@ -831,3 +831,98 @@ func TestBatchResumeOlderServerUploadProbeFallback(t *testing.T) { t.Fatalf("legacy fallback echo = %q, %v", buf, err) } } + +// Healthy pure-batch clients have nothing attached between polls; they must +// not be mistaken for the detached excess MaxDetachedResumable evicts. +func TestBatchResumeDetachedCapSparesHealthyPollers(t *testing.T) { + e := newResumeE2E(t, PollModeBatch, func(c *ServerConfig) { c.MaxDetachedResumable = 2 }, nil) + for i := 0; i < 6; i++ { + e.dial(t, func(c *Connector) { c.PollInterval = 300 * time.Millisecond }) + } + time.Sleep(2 * time.Second) + if n := e.store.Len(); n != 6 || len(e.reasons()) != 0 { + t.Fatalf("sessions = %d, disconnects = %v; healthy pollers were evicted", n, e.reasons()) + } +} + +// A pure-batch session counts toward the cap once it has been detached longer +// than its declared poll interval plus the allowance; nothing earlier. +func TestBatchResumeDetachedCapCountsAfterPollGap(t *testing.T) { + cfg := testResumeServerConfig() + cfg.ResumeGrace = time.Minute + ts, st := newResumeTestServer(t, cfg, Hooks{}) + connect := func(interval time.Duration, detachedFor time.Duration) *Session { + _, cr := postConnect(t, ts, ConnectRequest{ProtocolVersion: ProtocolVersion, PreferResume: true, BatchResume: true, + PollIntervalMS: interval.Milliseconds()}) + s, _ := st.Get(cr.SessionID) + s.mu.Lock() + s.detachedAt = time.Now().Add(-detachedFor) + s.mu.Unlock() + return s + } + oldest := connect(0, 40*time.Second) + gone := connect(0, 30*time.Second) + slowPoller := connect(25*time.Second, 30*time.Second) + betweenPolls := connect(0, time.Second) + st.maxDetachedResumable = 1 + st.sweep(time.Hour, nil) + for _, tc := range []struct { + name string + s *Session + want bool + }{{"oldest detached", oldest, true}, {"detached", gone, false}, {"within declared interval", slowPoller, false}, {"between polls", betweenPolls, false}} { + if tc.s.IsClosed() != tc.want { + t.Errorf("%s: evicted = %v, want %v", tc.name, tc.s.IsClosed(), tc.want) + } + } +} + +// Acks ride on every batch request and response, so a bulk transfer must not +// add ack-only uploads or early 204 polls to carry them. +func TestBatchResumeAcksAddNoRequests(t *testing.T) { + var ackOnlyUploads, idlePolls atomic.Int64 + mw := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(HeaderSendOnly) == "true" && r.ContentLength == 0 { + ackOnlyUploads.Add(1) + } + if r.Header.Get(HeaderReceiveOnly) == "true" { + sw := &statusWriter{ResponseWriter: w} + next.ServeHTTP(sw, r) + if sw.status == http.StatusNoContent { + idlePolls.Add(1) + } + return + } + next.ServeHTTP(w, r) + }) + } + e := newResumeE2E(t, PollModeBatch, func(c *ServerConfig) { c.PollTimeout = 5 * time.Second; c.SessionTimeout = 10 * time.Second }, mw) + _, sess := e.dial(t, nil) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + payload := bytes.Repeat([]byte("x"), 8<<20) + go stream.Write(payload) + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil || !bytes.Equal(got, payload) { + t.Fatalf("echo = %v", err) + } + if ackOnlyUploads.Load() != 0 || idlePolls.Load() != 0 { + t.Fatalf("ack-only uploads = %d, early 204 polls = %d; want none", ackOnlyUploads.Load(), idlePolls.Load()) + } +} + +type statusWriter struct { + http.ResponseWriter + status int +} + +func (w *statusWriter) WriteHeader(code int) { + w.status = code + w.ResponseWriter.WriteHeader(code) +} + +func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } diff --git a/client.go b/client.go index 7b7f9f3..499c288 100644 --- a/client.go +++ b/client.go @@ -459,6 +459,7 @@ func (c *Connector) doConnect(ctx context.Context, client *http.Client, base str PreferWebSocket: c.PreferWebSocket, PreferResume: preferResume, BatchResume: preferResume, + PollIntervalMS: c.PollInterval.Milliseconds(), }) if err != nil { return nil, fmt.Errorf("pollmux: failed to encode connect request: %w", err) diff --git a/handler.go b/handler.go index 63980d9..2bc1ad6 100644 --- a/handler.go +++ b/handler.go @@ -128,8 +128,11 @@ type ServerConfig struct { // MaxDetachedResumable caps how many resumable sessions may be waiting // detached at once, bounding the memory a burst of disconnects — or a // client that connects and vanishes on purpose — can hold. The sweeper - // evicts the longest-detached first. Defaults to - // DefaultMaxDetachedResumable; negative disables the cap. + // evicts the longest-detached first. A pure-batch session counts only + // after it has been detached longer than the client's declared + // PollInterval plus a fixed allowance, since between two healthy polls it + // has nothing attached. Defaults to DefaultMaxDetachedResumable; negative + // disables the cap. MaxDetachedResumable int // Logger receives diagnostics. Nil disables logging. @@ -362,6 +365,15 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { if resumable { s.enableResume(cfg.MaxReplayBytes, cfg.ResumeGrace) s.batchResume = req.BatchResume + if transport == "" && !s.uploadStream { + // Every upload response carries the upstream ack, so waking the + // download leg early to carry it would only cost a request. + s.rs.disableEagerAck() + if negotiatedMode == PollModeBatch { + ms := min(max(req.PollIntervalMS, 0), cfg.ResumeGrace.Milliseconds()) + s.pollGap = time.Duration(ms)*time.Millisecond + batchPollGapAllowance + } + } } // Register before the callback. The client's first poll can beat diff --git a/protocol.go b/protocol.go index 3e880a9..e62e276 100644 --- a/protocol.go +++ b/protocol.go @@ -89,6 +89,12 @@ const ( // never needs to match anything the client declares, so it stays an // unexported constant rather than a Limits field. defaultStreamReadGrace = 10 * time.Second + + // batchPollGapAllowance is how long, beyond its declared PollInterval, a + // resumable pure-batch session may sit between two polls before it counts + // as detached for MaxDetachedResumable: room for the response to drain, + // the client to turn it around, and the next request to arrive. + batchPollGapAllowance = 10 * time.Second ) // Client-side defaults. See Connector. @@ -184,6 +190,12 @@ type ConnectRequest struct { // Servers echo it only when resume is enabled for this session. Keeping it // separate protects older resumable clients that only understand streams. BatchResume bool `json:"batch_resume,omitempty"` + // PollIntervalMS is the client's idle pause between batch polls + // (Connector.PollInterval). A resumable pure-batch session has no request + // attached between polls, so the server uses this to avoid counting a + // healthy session against ServerConfig.MaxDetachedResumable. Clamped to the + // resume grace; ignored for every other transport. + PollIntervalMS int64 `json:"poll_interval_ms,omitempty"` } // ResumeRequest is the JSON body of POST {prefix}/{id}/resume, sent by a diff --git a/reliable.go b/reliable.go index f345e0c..cc834a7 100644 --- a/reliable.go +++ b/reliable.go @@ -54,7 +54,7 @@ type reliable struct { recvOffset uint64 // contiguous bytes written to in lastAck uint64 // recvOffset as of the last ack handed out by takeAck - ackEager int // interrupt out's waiter once this much is unacknowledged + ackEager int // interrupt out's waiter once this much is unacknowledged; 0 disables } // ackEagerBytes is how much newly received data prompts an immediate ack @@ -71,6 +71,14 @@ func newReliable(out, in *BufferedPipe, maxReplay int) *reliable { return &reliable{out: out, in: in, maxReplay: maxReplay, ackEager: ackEagerBytes} } +// disableEagerAck stops recvIn from waking the sending side to carry an ack. +// For a receive direction carried by batch requests or responses: each one +// already reports the cumulative ack, so an early wakeup only adds a request. +// Called before the layer is shared, never after. +func (r *reliable) disableEagerAck() { + r.ackEager = 0 +} + // nextOut returns the next chunk for the attached transport to send and the // offset of its first byte. Pending replay (bytes below sendOffset the // current transport has not sent yet) always goes first; only once that is @@ -136,7 +144,7 @@ func (r *reliable) recvIn(off uint64, p []byte) error { return err } r.recvOffset += uint64(len(p)) - wake := r.recvOffset-r.lastAck >= uint64(r.ackEager) + wake := r.ackEager > 0 && r.recvOffset-r.lastAck >= uint64(r.ackEager) r.mu.Unlock() if wake { diff --git a/reliable_test.go b/reliable_test.go index b5de47f..078af25 100644 --- a/reliable_test.go +++ b/reliable_test.go @@ -233,6 +233,17 @@ func TestReliableEagerAckInterruptsSender(t *testing.T) { } } +func TestReliableDisabledEagerAckLeavesSenderParked(t *testing.T) { + r := newTestReliable(1 << 20) + r.disableEagerAck() + if err := r.recvIn(0, bytes.Repeat([]byte("x"), 2*ackEagerBytes)); err != nil { + t.Fatal(err) + } + if _, _, err := r.nextOut(make([]byte, 64), 20*time.Millisecond, time.Millisecond); err != nil { + t.Fatalf("sender woke with %v, want a plain timeout", err) + } +} + // --- BufferedPipe.interrupt ---------------------------------------------------- func TestBufferedPipeInterruptCutsWaitShort(t *testing.T) { diff --git a/resumable_client.go b/resumable_client.go index a5c46ab..e13943f 100644 --- a/resumable_client.go +++ b/resumable_client.go @@ -792,6 +792,8 @@ func (c *Connector) connectResumable(ctx context.Context, base string, cr *Conne conn.pollClient = &http.Client{Transport: c.newTransport(dialTimeout, headerTimeout), CheckRedirect: noRedirect} if !conn.pollStream { conn.pollClient.Timeout = dialTimeout + headerTimeout + // Every poll request carries the downstream ack. + conn.rl.disableEagerAck() } if conn.uploadStream { conn.sendStreamClient = &http.Client{Transport: c.newTransport(dialTimeout, cr.Limits.StreamMaxDuration()+pollGrace), CheckRedirect: noRedirect} diff --git a/session.go b/session.go index f06cce9..2a1316e 100644 --- a/session.go +++ b/session.go @@ -82,6 +82,11 @@ type Session struct { rs *reliable att *attachments resumeGrace time.Duration + // pollGap is how long a resumable pure-batch session normally goes with + // nothing attached between two polls; zero for every other transport. + // Only a session detached longer than this counts toward the sweeper's + // MaxDetachedResumable cap. Set before publication, never mutated after. + pollGap time.Duration mu sync.Mutex lastActive time.Time @@ -156,6 +161,14 @@ func (s *Session) resumeExpiredLocked(now time.Time) bool { now.Sub(s.detachedAt) > s.resumeGrace } +// detachedBeyondPollGapLocked reports whether s has had nothing attached for +// longer than its transport's normal gap between requests, i.e. whether it is +// really waiting for a resume rather than between two batch polls. s.mu must +// be held. +func (s *Session) detachedBeyondPollGapLocked(now time.Time) bool { + return s.pollInFlight == 0 && now.Sub(s.detachedAt) > s.pollGap +} + // watchHighWater arms the high-water warning on both pipes. func (s *Session) watchHighWater(threshold int, logger *slog.Logger) { if threshold <= 0 || logger == nil { diff --git a/store.go b/store.go index 20c0ea9..54fad40 100644 --- a/store.go +++ b/store.go @@ -142,7 +142,9 @@ func (st *SessionStore) removeAndMarkClosed(s *Session, requireIdle bool) bool { // detached, measured against its own resumeGrace rather than timeout — a // resumable session that lost its transport is exactly the case the grace // exists for. Beyond that, maxDetachedResumable bounds how many such -// sessions may wait at once; the longest-detached are evicted first. +// sessions may wait at once; the longest-detached are evicted first. A +// pure-batch session is only counted once it has been detached longer than +// its normal gap between polls, so healthy clients are never the excess. func (st *SessionStore) sweep(timeout time.Duration, onEvict func(*Session)) { now := time.Now() var expired []*Session @@ -158,7 +160,7 @@ func (st *SessionStore) sweep(timeout time.Duration, onEvict func(*Session)) { s.closed = true delete(st.sessions, id) expired = append(expired, s) - } else { + } else if s.detachedBeyondPollGapLocked(now) { detached = append(detached, s) } case now.Sub(s.lastActive) > timeout: @@ -177,7 +179,7 @@ func (st *SessionStore) sweep(timeout time.Duration, onEvict func(*Session)) { sort.Slice(detached, func(i, j int) bool { return detached[i].detachedAt.Before(detached[j].detachedAt) }) for _, s := range detached[:len(detached)-max] { s.mu.Lock() - if !s.closed && s.pollInFlight == 0 { + if !s.closed && s.detachedBeyondPollGapLocked(now) { s.closed = true delete(st.sessions, s.ID) expired = append(expired, s) From 1e572223324f7c2f31077e087c4de0e505dcb521 Mon Sep 17 00:00:00 2001 From: MasterCoderK <8674856+DiamondGo@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:06:30 -0700 Subject: [PATCH 4/4] fix: abandon batch sessions whose responses can never finish arriving The batch poll's whole-request timeout also covers the body and is the client's only stall detector (yamux keepalive is off), so it stays fixed. But when a full batch cannot cross the link within that deadline, every resume replays the same batch and times out again. Each leg outlasts the fast-resume guard, and a truncated body is not progress, so the session resumed forever without delivering anything or signalling failure. doBatchPoll now reports a deadline hit while reading a 200 body as errBatchBodyTimeout. supervise abandons the session after three consecutive legs that end that way with no downstream bytes received; any delivered byte or any other failure resets the count. The README documents sizing poll_buffer_bytes for the slowest supported link. --- README.md | 4 ++- batch.go | 11 +++++++ batch_resume_test.go | 77 +++++++++++++++++++++++++++++++++++++++++++- resumable_client.go | 29 ++++++++++++++++- resume_test.go | 24 ++++++++++++++ 5 files changed, 142 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 95f35fc..05263b3 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,9 @@ HTTP uploads and downloads are independent requests to the poll endpoint: Uploads never wait for the downstream long poll. The default client poll interval is zero: waiting belongs inside the server's long poll, not an extra client sleep. A configured interval is applied after idle responses, not after data. -For **resumable** batch polls, the header timeout is `poll_timeout_ms + PollGrace`. A whole-request timeout of `DialTimeout + poll timeout + PollGrace` also bounds body consumption: receiving headers and then stalling halfway through a response is a transport failure, not an indefinitely healthy poll. Batch uploads use the client's send timeout. See [resumable batch wire behavior](#resumable-batch-wire-behavior) for offsets and replay. +For **resumable** batch polls, the header timeout is `poll_timeout_ms + PollGrace`. A whole-request timeout of `DialTimeout + poll timeout + PollGrace` also bounds body consumption: receiving headers and then stalling halfway through a response is a transport failure, not an indefinitely healthy poll. Batch uploads use the client's send timeout. + +**Size `poll_buffer_bytes` for the slowest link you support.** The whole-request timeout also covers the body transfer. Because yamux keepalive is disabled, it is the client's only stall detector for batch polls, so it deliberately does not stretch for slow bodies. Data that arrives near the end of a long poll leaves about `DialTimeout + PollGrace` to transfer a full batch. Keep `poll_buffer_bytes` within what the link carries in `PollGrace`, for example 256 KiB needs about 26 KB/s with the default 10 seconds. A batch that misses the deadline only costs a resume and a replay. But if a full batch cannot transfer within the whole deadline at all, every replay times out the same way. After three consecutive legs end with a response body timing out and no downstream bytes delivered, the client abandons the session and signals transport failure instead of resuming forever. See [resumable batch wire behavior](#resumable-batch-wire-behavior) for offsets and replay. ### Streamed HTTP downloads diff --git a/batch.go b/batch.go index 6fd4d45..db767b5 100644 --- a/batch.go +++ b/batch.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "net" "net/http" "strconv" "time" @@ -28,6 +29,12 @@ func batchOffset(h http.Header, name string) (uint64, error) { return n, nil } +// errBatchBodyTimeout is doBatchPoll's report that a 200 response started but +// its body did not finish within the poll deadline. Resuming replays the same +// batch, so on a link too slow for poll_buffer_bytes this repeats forever +// unless supervise gives up (see resumeStabilityGuard.recordBodyTimeout). +var errBatchBodyTimeout = errors.New("pollmux: batch poll response body did not finish within the poll deadline") + func setBatchOffset(h http.Header, name string, off uint64) { h.Set(name, strconv.FormatUint(off, 10)) } @@ -199,6 +206,10 @@ func (c *resumableConn) doBatchPoll(ctx context.Context) (bool, error) { } data, err := io.ReadAll(io.LimitReader(resp.Body, int64(c.maxFrame)+1)) if err != nil { + var ne net.Error + if resp.StatusCode == http.StatusOK && errors.As(err, &ne) && ne.Timeout() { + return false, fmt.Errorf("%w: %w", errBatchBodyTimeout, err) + } return false, fmt.Errorf("pollmux: reading batch response: %w", err) } if len(data) > c.maxFrame { diff --git a/batch_resume_test.go b/batch_resume_test.go index 31a72f7..0860a30 100644 --- a/batch_resume_test.go +++ b/batch_resume_test.go @@ -534,11 +534,86 @@ func TestBatchResumeClientBoundsStalledResponseBody(t *testing.T) { client := ts.Client() client.Timeout = 50 * time.Millisecond c := &resumableConn{rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), 1024), pollClient: client, pollURL: ts.URL, maxFrame: 16} - if _, err := c.doBatchPoll(context.Background()); err == nil || !errors.Is(err, context.DeadlineExceeded) { + if _, err := c.doBatchPoll(context.Background()); err == nil || !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, errBatchBodyTimeout) { t.Fatalf("stalled body error = %v", err) } } +// Only a deadline counts toward the body-timeout guard; a body cut short by +// the connection closing is an ordinary transport failure. +func TestBatchResumeClientTruncatedBodyIsNotABodyTimeout(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + setBatchOffset(w.Header(), HeaderRecvOffset, 0) + setBatchOffset(w.Header(), HeaderSendOffset, 0) + w.Header().Set("Content-Length", strconv.Itoa(10)) + w.WriteHeader(200) + io.WriteString(w, "abc") + })) + defer ts.Close() + client := ts.Client() + client.Timeout = 5 * time.Second + c := &resumableConn{rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), 1024), pollClient: client, pollURL: ts.URL, maxFrame: 16} + if _, err := c.doBatchPoll(context.Background()); err == nil || errors.Is(err, errBatchBodyTimeout) { + t.Fatalf("truncated body error = %v, want a non-timeout failure", err) + } +} + +type trickleWriter struct { + http.ResponseWriter +} + +func (w trickleWriter) Write(p []byte) (int, error) { + n := 0 + for len(p) > 0 { + k := min(len(p), 1<<10) + m, err := w.ResponseWriter.Write(p[:k]) + n += m + if err == nil { + err = http.NewResponseController(w.ResponseWriter).Flush() + } + if err != nil { + return n, err + } + p = p[k:] + time.Sleep(50 * time.Millisecond) + } + return n, nil +} + +func (w trickleWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +// A batch the link cannot carry within the poll deadline times out on every +// replay. Each leg outlasts resumableLegsMinStable, so only the body-timeout +// guard can end the loop instead of resuming forever. +func TestBatchResumeAbandonsSessionWhoseBatchesNeverFinish(t *testing.T) { + mw := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(HeaderReceiveOnly) == "true" { + w = trickleWriter{w} + } + next.ServeHTTP(w, r) + }) + } + e := newResumeE2E(t, PollModeBatch, nil, mw) + conn, sess := e.dial(t, func(c *Connector) { c.PollGrace = time.Second }) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + // Echoed back as about 64 KiB of downstream batches: 3 s or more each at + // the trickle rate, against a 2.5 s whole-request poll deadline. + go stream.Write(bytes.Repeat([]byte("x"), 64<<10)) + select { + case <-conn.TransportFailed(): + case <-time.After(30 * time.Second): + t.Fatalf("session kept resuming; resumes = %d", e.resumes.Load()) + } + if got := e.resumes.Load(); got != maxConsecutiveBatchBodyTimeouts-1 { + t.Fatalf("resumes before abandoning = %d, want %d", got, maxConsecutiveBatchBodyTimeouts-1) + } +} + func TestBatchResumeGraceExpiryEndsOriginalStreams(t *testing.T) { e := newResumeE2E(t, PollModeBatch, func(cfg *ServerConfig) { cfg.ResumeGrace = 300 * time.Millisecond }, nil) conn, sess := e.dial(t, nil) diff --git a/resumable_client.go b/resumable_client.go index e13943f..34586b0 100644 --- a/resumable_client.go +++ b/resumable_client.go @@ -196,10 +196,27 @@ const ( // maxConsecutiveFastResumes bounds the otherwise unthrottled case where // every resume handshake succeeds but its replacement legs fail at once. maxConsecutiveFastResumes = 5 + // maxConsecutiveBatchBodyTimeouts bounds the case the fast-resume guard + // cannot see: each leg lasts a whole poll deadline, but a batch response + // too large for the link never finishes, so nothing is ever delivered. + maxConsecutiveBatchBodyTimeouts = 3 ) type resumeStabilityGuard struct { - consecutiveFast int + consecutiveFast int + consecutiveBodyTimeouts int +} + +// recordBodyTimeout reports whether the session should be abandoned because +// batch responses keep timing out mid-body without delivering anything. Any +// downstream byte received, or a leg that ended for another reason, resets it. +func (g *resumeStabilityGuard) recordBodyTimeout(bodyTimedOut, received bool) bool { + if !bodyTimedOut || received { + g.consecutiveBodyTimeouts = 0 + return false + } + g.consecutiveBodyTimeouts++ + return g.consecutiveBodyTimeouts >= maxConsecutiveBatchBodyTimeouts } // record reports whether the session should be abandoned after a successful @@ -244,6 +261,16 @@ func (c *resumableConn) supervise() { c.fail() return } + if stability.recordBodyTimeout(errors.Is(err, errBatchBodyTimeout), c.rl.recvOffsetNow() != progressBefore.recv) { + c.logger.Warn("pollmux: batch poll responses keep timing out before they finish arriving, abandoning session; "+ + "poll_buffer_bytes is likely too large for this link's bandwidth", + "consecutive_body_timeouts", stability.consecutiveBodyTimeouts, + "poll_buffer_bytes", c.maxFrame, + "error", err, + ) + c.fail() + return + } c.logger.Warn("pollmux: transport failed, resuming the session", "error", err) if err := c.resume(); err != nil { diff --git a/resume_test.go b/resume_test.go index 61bfb45..6661a6f 100644 --- a/resume_test.go +++ b/resume_test.go @@ -586,6 +586,30 @@ func TestResumeStabilityGuardAbandonsConsecutiveFastLegs(t *testing.T) { } } +func TestResumeStabilityGuardBodyTimeouts(t *testing.T) { + var g resumeStabilityGuard + for i := 1; i < maxConsecutiveBatchBodyTimeouts; i++ { + if g.recordBodyTimeout(true, false) { + t.Fatalf("guard abandoned after %d body timeouts, want %d", i, maxConsecutiveBatchBodyTimeouts) + } + } + if g.recordBodyTimeout(true, true) { + t.Fatal("a body timeout after delivering bytes must reset, not trip, the guard") + } + for i := 1; i < maxConsecutiveBatchBodyTimeouts; i++ { + g.recordBodyTimeout(true, false) + } + if g.recordBodyTimeout(false, false) { + t.Fatal("a leg ending for another reason must reset, not trip, the guard") + } + for i := 1; i < maxConsecutiveBatchBodyTimeouts; i++ { + g.recordBodyTimeout(true, false) + } + if !g.recordBodyTimeout(true, false) { + t.Fatalf("guard did not abandon after %d consecutive unproductive body timeouts", maxConsecutiveBatchBodyTimeouts) + } +} + func TestResumeStabilityGuardStableOrProductiveLegResetsCounter(t *testing.T) { var g resumeStabilityGuard for i := 0; i < maxConsecutiveFastResumes-1; i++ {