diff --git a/README.md b/README.md index df251ac..480a064 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,28 @@ WebSocket 是绕开这个问题的正确层:Cloudflare(以及几乎所有反 **依赖**:`go.mod` 新增 `github.com/coder/websocket`。选它是因为 API 是 context-native 的(`Read(ctx)`/`Write(ctx, ...)`),和这个库本身大量用 context 做超时/取消的风格一致;没有引入额外的传递依赖。 +### 六、跨重连会话恢复(`PreferResume` / `EnableResume`) + +前五节解决的都是"链路健康时怎么跑得快、跑得稳"。这一节解决另一类问题:**链路被外部按存活时间掐断时,隧道上的流为什么必死、以及怎么让它不死**。 + +默认模型下,底层传输(poll / send-stream / WebSocket)一断,客户端就丢弃整个 yamux 会话,下一轮 `Connect` 拿到的是一个全新 session id,旧会话里所有 stream(比如一条 SSH 的 TCP 流)随之被切断。生产上 consumer 与 provider 各有一条传输经过 Cloudflare/反向代理,任意一条被中间层的最大连接存活时间(观察到约一小时)掐断,SSH 就断一次。心跳、`StreamMaxDuration` 滚动这些秒级机制保护不了这件事——它们不是原因。 + +开启方式:服务端 `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。 + +**它做了什么**:在 yamux 与 pollmux 传输之间插了一层可靠续传层(`reliable.go`),两端共用同一份实现—— + +- 每方向给数据字节编累积序号(和 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` 一行不改,只加配置。 + +**什么时候会放弃恢复、退化成今天的"新建会话"**(客户端 `TransportFailed` 触发、`ReconnectLoop` 照旧转一圈):宽限期内没能完成 `/resume`(服务端回 404/410,或客户端按下发的 `resume_grace_ms` 重试用尽);服务端主动关闭了会话(410 / `frameGone`,比如对端离开、被 DELETE);任一方向重放缓冲超过 `MaxReplayBytes`(默认 16MB,两端各自独立配置,超过后会话继续在当前传输上工作但不再可恢复);offset 越界或出现空洞(这是 bug 信号,宁可重建也绝不错误重放);`UploadStreamPreference` 自动探测失败——上行退回离散 POST 就没法续传,客户端会删掉这个会话、不带 `PreferResume` 重连一次,调用方拿到的是一个普通连接。 + +**要注意的两件事**:一,**两跳都要开**。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 本身没有的能力,但前提是鉴权层没有漏掉它。 + +`/resume` 的状态码:200 恢复成功(响应体带服务端的 `recv_offset`);404 会话不存在、410 已关闭、409 不可恢复(未协商、已判定不可恢复、offset 超出可重放范围——客户端一律放弃并重建);426 协议版本;503 稍后重试(旧传输还没脱离干净,或另一个 resume 正在进行)。 + --- ## 协议与行为约定 diff --git a/client.go b/client.go index 9004390..0c5f111 100644 --- a/client.go +++ b/client.go @@ -139,6 +139,23 @@ type Connector struct { // WebSocket connection carries both directions, so there is no separate // upload leg to probe. PreferWebSocket bool + // 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. + PreferResume bool + // MaxReplayBytes caps how much unacknowledged data each direction of a + // resumable connection retains for replay; beyond it the connection + // stops being resumable and its next transport failure ends it like a + // non-resumable one. Defaults to DefaultMaxReplayBytes. + MaxReplayBytes int // Logger receives transport diagnostics. Nil disables logging. Logger *slog.Logger @@ -174,6 +191,13 @@ 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) +} + +// 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) { if c.BaseURL == "" { return nil, errors.New("pollmux: Connector.BaseURL is required") } @@ -202,7 +226,7 @@ func (c *Connector) Connect(ctx context.Context) (Conn, error) { CheckRedirect: noRedirect, } - cr, err := c.doConnect(ctx, connectClient, base) + cr, err := c.doConnect(ctx, connectClient, base, preferResume) if err != nil { return nil, err } @@ -211,6 +235,21 @@ func (c *Connector) Connect(ctx context.Context) (Conn, error) { return nil, err } + 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. + 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) { + 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) + } + } + // WebSocket is negotiated independently of, and takes priority over, the // PollMode/UploadStreamMode branch below: a session either attaches over // one WebSocket or it doesn't, and if it does none of the poll/ @@ -222,6 +261,9 @@ func (c *Connector) Connect(ctx context.Context) (Conn, error) { return nil, fmt.Errorf("pollmux: server negotiated websocket transport but sent non-positive heartbeat_interval_ms=%d", cr.Limits.HeartbeatIntervalMS) } + if cr.Resumable { + return c.connectResumable(ctx, base, cr, dialTimeout, sendTimeout, pollGrace, coalesce) + } return c.connectWebSocket(ctx, base, cr, dialTimeout, pollGrace) } @@ -264,6 +306,30 @@ func (c *Connector) Connect(ctx context.Context) (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 == "" { + 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", + "probe_timeout", probeTimeout) + c.deleteSession(base, cr.SessionID, connectClient) + return c.connect(ctx, false) + } + } + return c.connectResumable(ctx, base, cr, dialTimeout, sendTimeout, pollGrace, coalesce) + } + // Two clients, deliberately not shared. The poll client must tolerate a // response header withheld for the whole long-poll timeout; the send client // must not, or a stalled send would sit undetected for that same span. @@ -332,7 +398,7 @@ func (c *Connector) Connect(ctx context.Context) (Conn, error) { conn.uploadStreamMode = false default: // "" — auto-detect probeTimeout := orDuration(c.UploadProbeTimeout, DefaultUploadProbeTimeout) - conn.uploadStreamMode = conn.probeUploadStream(probeTimeout) + conn.uploadStreamMode = probeUploadStream(conn.ctx, conn.sendStreamClient, conn.pollURL, conn.authToken, probeTimeout) if !conn.uploadStreamMode { logger.Warn("pollmux: upload-stream probe did not pass within timeout, "+ "falling back to batch uploads for this connection — "+ @@ -392,13 +458,14 @@ 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) (*ConnectResponse, error) { +func (c *Connector) doConnect(ctx context.Context, client *http.Client, base string, preferResume bool) (*ConnectResponse, error) { body, err := json.Marshal(ConnectRequest{ ProtocolVersion: ProtocolVersion, Meta: c.Meta, PreferStreamMode: c.PreferStream, PreferStreamUpload: c.UploadStreamPreference != PollModeBatch, PreferWebSocket: c.PreferWebSocket, + PreferResume: preferResume, }) if err != nil { return nil, fmt.Errorf("pollmux: failed to encode connect request: %w", err) @@ -456,6 +523,24 @@ func (c *Connector) doConnect(ctx context.Context, client *http.Client, base str return &cr, nil } +// deleteSession sends a best-effort DELETE for a session Connect created but +// decided not to use. +func (c *Connector) deleteSession(base, id string, client *http.Client) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, fmt.Sprintf("%s/%s", base, id), nil) + if err != nil { + return + } + if c.AuthToken != "" { + req.Header.Set("Authorization", "Bearer "+c.AuthToken) + } + if resp, err := client.Do(req); err == nil { + io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) + resp.Body.Close() + } +} + // httpConn is the Conn implementation: a poll loop pulling data down, and a // flush loop pushing data up as separate requests. // @@ -984,9 +1069,11 @@ func (c *httpConn) doSend(chunk []byte) error { // The probe never touches writePipe or the real session: the server // recognizes HeaderSendStreamProbe and discards the frames instead of // writing them upstream, so this is safe to run before any real data is -// queued to send. -func (c *httpConn) probeUploadStream(timeout time.Duration) bool { - ctx, cancel := context.WithTimeout(c.ctx, timeout) +// queued to send. A package-level function rather than an httpConn method +// because a resumable connect (see Connector.connect) runs it before it has +// decided which Conn to build. +func probeUploadStream(parent context.Context, client *http.Client, pollURL, authToken string, timeout time.Duration) bool { + ctx, cancel := context.WithTimeout(parent, timeout) defer cancel() pr, pw := io.Pipe() @@ -1009,7 +1096,7 @@ func (c *httpConn) probeUploadStream(timeout time.Duration) bool { pw.Close() }() - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.pollURL, pr) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, pollURL, pr) if err != nil { pw.CloseWithError(err) return false @@ -1018,9 +1105,11 @@ func (c *httpConn) probeUploadStream(timeout time.Duration) bool { req.Header.Set(HeaderSendStream, "true") req.Header.Set(HeaderSendStreamProbe, "true") req.ContentLength = -1 - c.setAuth(req) + if authToken != "" { + req.Header.Set("Authorization", "Bearer "+authToken) + } - resp, err := c.sendStreamClient.Do(req) + resp, err := client.Do(req) if err != nil { // Includes context.DeadlineExceeded — the expected outcome on a path // that does not forward this request to the origin within timeout. diff --git a/frame.go b/frame.go index 37c0a7c..72582a1 100644 --- a/frame.go +++ b/frame.go @@ -24,8 +24,23 @@ const ( // the client must treat this the same as batch mode's 410 — surface // TransportFailed and let the caller reconnect with a fresh session. frameGone frameType = 0x04 + // frameAck and frameSeqData only ever appear on a session that + // negotiated ConnectResponse.Resumable (see reliable.go). frameAck's + // payload is one 8-byte big-endian cumulative offset: "I have every + // byte below this". frameSeqData replaces frameData on such a session: + // its payload is an 8-byte big-endian offset of the first data byte, + // followed by the data. Carrying the absolute offset on every data frame + // is what lets a receiver drop a replayed byte it already has and refuse + // a stream with a hole in it, instead of handing yamux a corrupted byte + // stream — see reliable.recvIn. + frameAck frameType = 0x05 + frameSeqData frameType = 0x06 ) +// seqHeaderLen is the size of the offset that prefixes a frameSeqData payload +// and that forms the whole of a frameAck payload. +const seqHeaderLen = 8 + // frameHeaderLen is 1 byte type + 4 byte big-endian length. Only frameData // gives the length field meaning; frameHeartbeat, frameEnd, and frameGone // always encode zero length and carry no payload. @@ -47,6 +62,47 @@ func writeFrame(w io.Writer, typ frameType, payload []byte) error { return err } +// writeSeqFrame writes one frameSeqData frame carrying payload at offset off, +// as three writes with no intermediate copy — a resumable session's data +// frames are the hot path, and payload can be a full PollBufferBytes. +func writeSeqFrame(w io.Writer, off uint64, payload []byte) error { + var hdr [frameHeaderLen + seqHeaderLen]byte + hdr[0] = byte(frameSeqData) + binary.BigEndian.PutUint32(hdr[1:], uint32(seqHeaderLen+len(payload))) + binary.BigEndian.PutUint64(hdr[frameHeaderLen:], off) + if _, err := w.Write(hdr[:]); err != nil { + return err + } + if len(payload) == 0 { + return nil + } + _, err := w.Write(payload) + return err +} + +// encodeOffset renders a frameAck payload (or a frameSeqData prefix). +func encodeOffset(n uint64) []byte { + var b [seqHeaderLen]byte + binary.BigEndian.PutUint64(b[:], n) + return b[:] +} + +// decodeAck parses a frameAck payload. +func decodeAck(payload []byte) (uint64, error) { + if len(payload) != seqHeaderLen { + return 0, fmt.Errorf("pollmux: ack frame payload is %d bytes, want %d", len(payload), seqHeaderLen) + } + return binary.BigEndian.Uint64(payload), nil +} + +// splitSeq separates a frameSeqData payload into its offset and data. +func splitSeq(payload []byte) (uint64, []byte, error) { + if len(payload) < seqHeaderLen { + return 0, nil, fmt.Errorf("pollmux: seq-data frame payload is %d bytes, shorter than its %d-byte offset", len(payload), seqHeaderLen) + } + return binary.BigEndian.Uint64(payload), payload[seqHeaderLen:], nil +} + // frameReader decodes stream frames, returning exactly one frame per call to // next and buffering nothing across the underlying io.Reader beyond what // io.ReadFull needs — HTTP chunked transfer gives no guarantee that a @@ -79,11 +135,21 @@ func (f *frameReader) next() (frameType, []byte, error) { } typ := frameType(f.hdr[0]) length := binary.BigEndian.Uint32(f.hdr[1:]) - if typ != frameData || length == 0 { + if length == 0 { return typ, nil, nil } - if int64(length) > int64(f.maxPayload) { - return 0, nil, fmt.Errorf("pollmux: stream frame length %d exceeds max %d", length, f.maxPayload) + // A frameSeqData payload is the data plus its offset prefix, so it may + // legitimately run seqHeaderLen past the negotiated data bound; a + // frameAck payload is exactly one offset, whatever the data bound is. + maxPayload := f.maxPayload + switch typ { + case frameSeqData: + maxPayload += seqHeaderLen + case frameAck: + maxPayload = seqHeaderLen + } + if int64(length) > int64(maxPayload) { + return 0, nil, fmt.Errorf("pollmux: stream frame length %d exceeds max %d", length, maxPayload) } payload := make([]byte, length) if _, err := io.ReadFull(f.r, payload); err != nil { diff --git a/handler.go b/handler.go index bc624cf..3517a28 100644 --- a/handler.go +++ b/handler.go @@ -100,6 +100,38 @@ type ServerConfig struct { // difference. EnableWebSocket bool + // 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 + // with this left false, is completely unaffected. Mount ResumeHandler + // when turning this on. + EnableResume bool + + // ResumeGrace is how long a resumable session survives with no + // transport attached, waiting to be resumed. Defaults to + // DefaultResumeGrace; capped at MaxResumeGrace (check panics above it). + // This replaces SessionTimeout as the eviction criterion for a + // resumable session that is detached; an attached one is never evicted, + // as today. + ResumeGrace time.Duration + + // MaxReplayBytes caps how much unacknowledged data each direction of a + // resumable session retains for replay. Beyond it the session stops + // being resumable (it keeps working over its current transport, and + // the next transport failure ends it like a non-resumable session + // would). Defaults to DefaultMaxReplayBytes. + MaxReplayBytes int + + // 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. + MaxDetachedResumable int + // Logger receives diagnostics. Nil disables logging. Logger *slog.Logger } @@ -129,6 +161,15 @@ func (cfg ServerConfig) withDefaults() ServerConfig { if cfg.StreamMaxDuration <= 0 { cfg.StreamMaxDuration = DefaultStreamMaxDuration } + if cfg.ResumeGrace <= 0 { + cfg.ResumeGrace = DefaultResumeGrace + } + if cfg.MaxReplayBytes <= 0 { + cfg.MaxReplayBytes = DefaultMaxReplayBytes + } + if cfg.MaxDetachedResumable == 0 { + cfg.MaxDetachedResumable = DefaultMaxDetachedResumable + } if cfg.SessionIDFunc == nil { cfg.SessionIDFunc = func(r *http.Request) string { return r.PathValue("id") } } @@ -161,11 +202,16 @@ func (cfg ServerConfig) check() { "the stream would barely open before being forced to end", cfg.StreamMaxDuration, 2*cfg.HeartbeatInterval)) } + if cfg.ResumeGrace > MaxResumeGrace { + panic(fmt.Sprintf("pollmux: ServerConfig.ResumeGrace=%v exceeds MaxResumeGrace=%v; "+ + "a detached resumable session holds its replay buffer for the whole grace", + cfg.ResumeGrace, MaxResumeGrace)) + } } // limits is what gets handed down to clients at connect time for the given // negotiated mode. -func (cfg ServerConfig) limits(mode string) Limits { +func (cfg ServerConfig) limits(mode string, resumable bool) Limits { l := Limits{ MaxSendBytes: cfg.MaxSendBytes, PollTimeoutMS: cfg.PollTimeout.Milliseconds(), @@ -176,6 +222,9 @@ func (cfg ServerConfig) limits(mode string) Limits { l.HeartbeatIntervalMS = cfg.HeartbeatInterval.Milliseconds() l.StreamMaxDurationMS = cfg.StreamMaxDuration.Milliseconds() } + if resumable { + l.ResumeGraceMS = cfg.ResumeGrace.Milliseconds() + } return l } @@ -300,6 +349,19 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { s.pollMode = negotiatedMode s.watchHighWater(cfg.HighWaterWarn, cfg.Logger) + // Decided here, before the session is published, because + // PollHandler/WebSocketHandler read s.rs without a lock — the same + // immutable-after-publish discipline pollMode and transport follow. + transport := "" + if cfg.EnableWebSocket && req.PreferWebSocket { + transport = TransportWebSocket + } + s.transport = transport + resumable := negotiateResume(cfg, req, transport, negotiatedMode, negotiatedUpload) + if resumable { + s.enableResume(cfg.MaxReplayBytes, cfg.ResumeGrace) + } + // Register before the callback. The client's first poll can beat // OnConnect to the server, and it must find the session waiting. st.add(s) @@ -314,7 +376,7 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { } } - cfg.Logger.Info("pollmux: session created", "session_id", id) + cfg.Logger.Info("pollmux: session created", "session_id", id, "resumable", resumable) uploadStreamMode := "" // limitsMode drives whether cfg.limits() includes the @@ -331,23 +393,19 @@ func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { // still rides limitsMode's Heartbeat field (WebSocketHandler uses it // for the app-level heartbeat cadence, see websocket.go) but never // needs StreamMaxDuration — see ServerConfig.StreamMaxDuration. - transport := "" - if cfg.EnableWebSocket && req.PreferWebSocket { - transport = TransportWebSocket - if limitsMode != PollModeStream { - limitsMode = PollModeStream - } + if transport == TransportWebSocket && limitsMode != PollModeStream { + limitsMode = PollModeStream } - s.transport = transport writeJSON(w, http.StatusOK, ConnectResponse{ ProtocolVersion: ProtocolVersion, SessionID: id, - Limits: cfg.limits(limitsMode), + Limits: cfg.limits(limitsMode, resumable), Meta: meta, PollMode: negotiatedMode, UploadStreamMode: uploadStreamMode, Transport: transport, + Resumable: resumable, }) }) } @@ -388,6 +446,20 @@ func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { 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") + return + } + pollStream(w, r, s, cfg) + return + } + body := http.MaxBytesReader(w, r.Body, int64(cfg.MaxSendBytes)) data, err := io.ReadAll(body) if err != nil { @@ -467,6 +539,27 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo // PollHandler owns the lifecycle attachment for this request. + // A resumable session additionally hands this handler exclusive + // ownership of the downstream direction, kicking any previous owner + // off first (see attachments). kick has to cover both places this loop + // can be blocked: the pipe wait (interrupt) and a write to a peer that + // stopped reading (a past write deadline fails it at once). + var att *attachment + if s.rs != nil { + rc := http.NewResponseController(w) + var err error + att, err = s.att.attach(attachDown, func() { + 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) + s.rs.resetAck() + } + // Headers must go out now, not on the first frame. The client's // ResponseHeaderTimeout for a stream-mode poll is short (it only needs // to cover connection setup, not a long-poll wait) — if this handler @@ -480,6 +573,11 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo buf := make([]byte, cfg.PollBufferSize) deadline := time.Now().Add(cfg.StreamMaxDuration) + if s.rs != nil { + pollStreamResumable(w, r, s, cfg, flusher, att, buf, deadline) + return + } + for { select { case <-r.Context().Done(): @@ -522,6 +620,68 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo } } +// pollStreamResumable is pollStream's loop for a resumable session. Same +// shape — wait, frame, flush, roll over at deadline — with three +// differences: bytes come from the reliable layer (pending replay first, +// then the pipe) and go out as frameSeqData carrying their offset; every +// write is preceded by an ack of what has arrived upstream since the last +// one; and an interrupted wait means either "you have been replaced" (leave +// quietly, a newer transport owns this direction now) or "an ack is due" +// (send just that, no heartbeat). +func pollStreamResumable(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerConfig, + flusher http.Flusher, att *attachment, buf []byte, deadline time.Time) { + for { + select { + case <-r.Context().Done(): + return + default: + } + + off, n, err := s.rs.nextOut(buf, cfg.HeartbeatInterval, cfg.CoalesceWindow) + interrupted := false + switch { + case errors.Is(err, io.EOF): + writeFrame(w, frameGone, nil) + flusher.Flush() + return + case errors.Is(err, errPipeInterrupted): + if !s.att.isCurrent(att) { + return + } + interrupted = true + } + + if ack, due := s.rs.takeAck(); due { + if err := writeFrame(w, frameAck, encodeOffset(ack)); err != nil { + cfg.Logger.Debug("pollmux: stream ack write failed, ending stream poll", + "session_id", s.ID, "error", err) + return + } + } + switch { + case n > 0: + if err := writeSeqFrame(w, off, buf[:n]); err != nil { + cfg.Logger.Debug("pollmux: stream write failed, ending stream poll", + "session_id", s.ID, "error", err) + return + } + case !interrupted: + if err := writeFrame(w, frameHeartbeat, nil); err != nil { + cfg.Logger.Debug("pollmux: stream heartbeat write failed, ending stream poll", + "session_id", s.ID, "error", err) + return + } + } + flusher.Flush() + + if time.Now().After(deadline) { + writeFrame(w, frameEnd, nil) + flusher.Flush() + return + } + } +} + // pollSendStream serves the upload-stream half of PollHandler: instead of // reading one discrete, bounded request body and answering at once, it reads // a sequence of frames off the (potentially long-lived) request body and @@ -546,6 +706,21 @@ func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg Serv } resetDeadline() + // A resumable session hands this handler exclusive ownership of the + // upstream direction (see attachments); a past read deadline is what + // gets a kicked reader out of fr.next() immediately. The probe never + // carries session data, so it needs no attachment. + probe := r.Header.Get(HeaderSendStreamProbe) == "true" + resumable := s.rs != nil && !probe + if resumable { + att, err := s.att.attach(attachUp, func() { rc.SetReadDeadline(time.Now()) }) + if err != nil { + writeError(w, http.StatusServiceUnavailable, "previous transport is still detaching, retry") + return + } + defer s.att.detach(att) + } + // A probe request (see Connector.UploadStreamPreference / // probeUploadStream) carries no real session data: its frames are // discarded instead of being written upstream. Otherwise it is handled @@ -554,7 +729,6 @@ func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg Serv // probe exercises the identical code path and timing as production // traffic rather than a bespoke fast-path that might behave differently // under a buffering proxy. - probe := r.Header.Get(HeaderSendStreamProbe) == "true" fr := newFrameReader(r.Body, cfg.MaxSendBytes) for { @@ -577,11 +751,16 @@ func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg Serv switch typ { case frameData: - if len(payload) == 0 { + if len(payload) == 0 || probe { continue } - if probe { - continue + if resumable { + // Plain data has no offset and would silently desync the + // upstream count; a resumable client never sends it. + cfg.Logger.Debug("pollmux: unnumbered data frame on a resumable session", "session_id", s.ID) + s.rs.markBroken() + writeError(w, http.StatusBadRequest, "resumable session requires seq-data frames") + return } if _, err := s.writeUpstream(payload); err != nil { cfg.Logger.Debug("pollmux: send-stream write failed, session is gone", @@ -589,6 +768,41 @@ func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg Serv writeError(w, http.StatusGone, "session closed") return } + case frameSeqData: + if !resumable { + cfg.Logger.Debug("pollmux: seq-data frame on a non-resumable session", "session_id", s.ID) + writeError(w, http.StatusBadRequest, "seq-data frames require a resumable session") + return + } + off, data, err := splitSeq(payload) + if err == nil { + err = s.rs.recvIn(off, data) + } + if err != nil { + if errors.Is(err, io.ErrClosedPipe) { + writeError(w, http.StatusGone, "session closed") + return + } + cfg.Logger.Warn("pollmux: send-stream data rejected, session is no longer resumable", + "session_id", s.ID, "error", err) + writeError(w, http.StatusBadRequest, err.Error()) + return + } + case frameAck: + if !resumable { + writeError(w, http.StatusBadRequest, "ack frames require a resumable session") + return + } + n, err := decodeAck(payload) + if err == nil { + err = s.rs.ack(n) + } + if err != nil { + cfg.Logger.Warn("pollmux: send-stream ack rejected, session is no longer resumable", + "session_id", s.ID, "error", err) + writeError(w, http.StatusBadRequest, err.Error()) + return + } case frameHeartbeat: // Nothing to do beyond the resetDeadline above. case frameEnd: @@ -650,6 +864,13 @@ func closeSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason // CloseSessionIfNoPollInFlight atomically closes s only when it is still the // current store entry and no poll or persistent transport is attached. It // returns true only when this call completed the removal and close. +// +// A resumable session (see ServerConfig.EnableResume) that is detached but +// still inside its ResumeGrace also counts as attached here: its client may +// be about to resume it. A periodic reaper that calls this after noticing a +// transport drop therefore needs no resume-specific logic — it simply keeps +// getting false until the grace has passed, and the sweeper evicts the +// session at that point anyway. Session.ResumeDeadline says when. func CloseSessionIfNoPollInFlight(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) bool { if !st.removeAndMarkClosed(s, true) { return false @@ -668,6 +889,10 @@ func StartSweeper(st *SessionStore, cfg ServerConfig, h Hooks) (stop func()) { cfg.check() cfg = cfg.withDefaults() + st.mu.Lock() + st.maxDetachedResumable = max(cfg.MaxDetachedResumable, 0) + st.mu.Unlock() + return st.StartSweeper(cfg.SweepInterval, cfg.SessionTimeout, func(s *Session) { cfg.Logger.Info("pollmux: evicting an idle session", "session_id", s.ID, "idle_for", time.Since(s.LastActive())) diff --git a/handler_test.go b/handler_test.go index 912e66f..11cd84b 100644 --- a/handler_test.go +++ b/handler_test.go @@ -711,7 +711,7 @@ func TestServerConfigDefaultsAreCoherent(t *testing.T) { if cfg.PollBufferSize != DefaultPollBufferSize { t.Fatalf("default PollBufferSize = %d, want %d", cfg.PollBufferSize, DefaultPollBufferSize) } - l := cfg.limits("") + l := cfg.limits("", false) if l.PollTimeoutMS != DefaultPollTimeout.Milliseconds() { t.Fatalf("limits poll_timeout_ms = %d, want %d", l.PollTimeoutMS, DefaultPollTimeout.Milliseconds()) } diff --git a/pipe.go b/pipe.go index ecbc09d..2b97baa 100644 --- a/pipe.go +++ b/pipe.go @@ -30,6 +30,15 @@ type BufferedPipe struct { warnThreshold int warned bool logger *slog.Logger + + // intr is a level-triggered interrupt flag for ReadAvailable, set by + // interrupt and consumed by the next ReadAvailable call. The resumable + // transport (see reliable.go) uses it for two things that both need to + // pull a parked writer out of its long wait early: kicking a stale + // attachment off a session so a replacement can attach, and nudging + // the writer to send an acknowledgement when enough data has arrived. + // Read is deliberately unaffected — it has no timeout to cut short. + intr bool } // NewBufferedPipe creates a new BufferedPipe ready for use. @@ -135,7 +144,14 @@ func (p *BufferedPipe) Read(dst []byte) (int, error) { // answers 204. Returns io.EOF if the pipe is closed and empty, which the caller // must distinguish from that timeout: it means the session is gone, and // answering 204 there would leave the client polling an empty session until its -// own timeout instead of reconnecting (A5). +// own timeout instead of reconnecting (A5). Returns (0, errPipeInterrupted) +// if interrupt was called; only the resumable transport ever does that, so +// every other caller keeps seeing exactly the three outcomes above. An +// interrupted return says nothing about the pipe's contents — data may +// well be buffered (an interrupt that lands during the coalesce window is +// reported on the *following* call, after that call's data has been +// returned) — so a caller must treat it purely as "re-check your state and +// call again", never as "the pipe is empty". func (p *BufferedPipe) ReadAvailable(dst []byte, timeout time.Duration, coalesceWindow time.Duration) (int, error) { if coalesceWindow <= 0 { coalesceWindow = DefaultCoalesceWindow @@ -144,12 +160,21 @@ func (p *BufferedPipe) ReadAvailable(dst []byte, timeout time.Duration, coalesce p.mu.Lock() defer p.mu.Unlock() + // A pending interrupt wins over everything, including data already + // buffered: the interrupter wants the caller back in its own loop now + // (to notice it has been detached, or to send an ack), and the data is + // still here for the next call. + if p.intr { + p.intr = false + return 0, errPipeInterrupted + } + if len(p.buf) == 0 { if p.closed { return 0, io.EOF } - // Phase 1: wait for the first byte (or timeout/close). + // Phase 1: wait for the first byte (or timeout/close/interrupt). timedOut := false timer := time.AfterFunc(timeout, func() { p.mu.Lock() @@ -157,7 +182,7 @@ func (p *BufferedPipe) ReadAvailable(dst []byte, timeout time.Duration, coalesce p.cond.Broadcast() p.mu.Unlock() }) - for len(p.buf) == 0 && !p.closed && !timedOut { + for len(p.buf) == 0 && !p.closed && !timedOut && !p.intr { p.cond.Wait() } timer.Stop() @@ -166,14 +191,20 @@ func (p *BufferedPipe) ReadAvailable(dst []byte, timeout time.Duration, coalesce if p.closed { return 0, io.EOF } + if p.intr { + p.intr = false + return 0, errPipeInterrupted + } return 0, nil // pure timeout, no data at all } } // Phase 2: at least one byte is available. Give it a brief window to // accumulate more before flushing, unless dst is already full or the pipe - // closed in the meantime. - if len(p.buf) < len(dst) && !p.closed { + // closed in the meantime. An interrupt cuts the window short but does not + // consume the flag — the data goes back first, and the very next call + // returns errPipeInterrupted, so the interrupt is still handled promptly. + if len(p.buf) < len(dst) && !p.closed && !p.intr { timedOut := false timer := time.AfterFunc(coalesceWindow, func() { p.mu.Lock() @@ -181,7 +212,7 @@ func (p *BufferedPipe) ReadAvailable(dst []byte, timeout time.Duration, coalesce p.cond.Broadcast() p.mu.Unlock() }) - for len(p.buf) < len(dst) && !p.closed && !timedOut { + for len(p.buf) < len(dst) && !p.closed && !timedOut && !p.intr { p.cond.Wait() } timer.Stop() @@ -192,6 +223,20 @@ func (p *BufferedPipe) ReadAvailable(dst []byte, timeout time.Duration, coalesce return n, nil } +// interrupt makes the current or next ReadAvailable call return +// errPipeInterrupted instead of waiting out its timeout. It is level- +// triggered: a call that lands while no reader is parked is remembered and +// consumed by the next ReadAvailable, so a writer that was busy between two +// calls still sees it promptly. A spurious interrupt is harmless to every +// caller in this package — each one re-checks its own state and simply calls +// ReadAvailable again — which is what makes the flag safe to leave pending. +func (p *BufferedPipe) interrupt() { + p.mu.Lock() + p.intr = true + p.cond.Broadcast() + p.mu.Unlock() +} + // Close closes the pipe, unblocking any waiting readers. Idempotent. func (p *BufferedPipe) Close() error { p.mu.Lock() diff --git a/protocol.go b/protocol.go index b849fa6..d916dbf 100644 --- a/protocol.go +++ b/protocol.go @@ -62,6 +62,20 @@ const ( // of it leaves no margin), not just under SessionTimeout. DefaultStreamMaxDuration = 45 * time.Second + // DefaultResumeGrace is how long a resumable session survives on the + // server with no transport attached, waiting for the client to resume it + // (see ServerConfig.ResumeGrace). It only needs to cover one reconnect — + // the client's detection time plus a few retries — not a long outage. + DefaultResumeGrace = 30 * time.Second + // MaxResumeGrace caps ServerConfig.ResumeGrace: a detached resumable + // session holds its replay buffer for the whole grace period, so an + // unbounded grace would be an unbounded memory hold. + MaxResumeGrace = 5 * time.Minute + // DefaultMaxDetachedResumable caps how many resumable sessions may sit + // detached (waiting to be resumed) at once; beyond it the sweeper evicts + // the longest-detached first. See ServerConfig.MaxDetachedResumable. + DefaultMaxDetachedResumable = 1024 + // defaultStreamReadGrace is the server's local safety margin for the // upload-stream read-idle watchdog (PollHandler's pollSendStream): if no // frame — data or heartbeat — arrives within HeartbeatInterval plus this @@ -82,6 +96,14 @@ const ( DefaultDialTimeout = 10 * time.Second DefaultMaxSendChunk = 512 << 10 + // DefaultMaxReplayBytes bounds each direction's replay buffer on a + // resumable connection (see Connector.MaxReplayBytes). yamux's flow + // control already keeps the buffer near MaxStreamWindowSize per active + // stream while the transport is down, so this is a hard ceiling for the + // pathological case — very many streams, or a peer that never + // acknowledges — not a number a healthy session should ever approach. + DefaultMaxReplayBytes = 16 << 20 + // DefaultUploadProbeTimeout bounds Connector's connect-time auto-detect // probe for upload streaming (see Connector.UploadStreamPreference). // Some intermediate proxies (observed with Cloudflare's standard tiers) @@ -111,10 +133,10 @@ const DefaultCoalesceWindow = 2 * time.Millisecond // Reconnect defaults. See ReconnectLoop. const ( - DefaultInitialBackoff = 1 * time.Second - DefaultMaxBackoff = 3 * time.Minute - DefaultPeerClosedPause = 500 * time.Millisecond - DefaultMinStableDuration = 5 * time.Second + DefaultInitialBackoff = 1 * time.Second + DefaultMaxBackoff = 3 * time.Minute + DefaultPeerClosedPause = 500 * time.Millisecond + DefaultMinStableDuration = 5 * time.Second ) // ConnectRequest is the JSON body of POST {prefix}/connect. @@ -145,6 +167,29 @@ type ConnectRequest struct { // ConnectResponse.Transport and the client falls back to whatever // PreferStreamMode/PreferStreamUpload negotiated, unchanged. 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. + PreferResume bool `json:"prefer_resume,omitempty"` +} + +// ResumeRequest is the JSON body of POST {prefix}/{id}/resume, sent by a +// resumable client after its transport failed (see ResumeHandler). +type ResumeRequest struct { + ProtocolVersion int `json:"protocol_version"` + // RecvOffset is the count of downstream bytes the client has received + // contiguously. The server replays everything from here on. + RecvOffset uint64 `json:"recv_offset"` +} + +// ResumeResponse is the JSON body of a successful resume. +type ResumeResponse struct { + Resumed bool `json:"resumed"` + // RecvOffset is the count of upstream bytes the server has received + // contiguously. The client replays everything from here on. + RecvOffset uint64 `json:"recv_offset"` } // Limits are the transport parameters the server hands down at connect time. @@ -166,6 +211,11 @@ type Limits struct { // in a batch-mode response, same as today. HeartbeatIntervalMS int64 `json:"heartbeat_interval_ms,omitempty"` StreamMaxDurationMS int64 `json:"stream_max_duration_ms,omitempty"` + // ResumeGraceMS is only set when this connect negotiated a resumable + // session (see ConnectResponse.Resumable): how long the server keeps a + // detached session waiting to be resumed. The client stops retrying + // resume after this long and falls back to a fresh session. + ResumeGraceMS int64 `json:"resume_grace_ms,omitempty"` } // PollTimeout returns PollTimeoutMS as a duration. @@ -188,6 +238,11 @@ func (l Limits) StreamMaxDuration() time.Duration { return time.Duration(l.StreamMaxDurationMS) * time.Millisecond } +// ResumeGrace returns ResumeGraceMS as a duration. +func (l Limits) ResumeGrace() time.Duration { + return time.Duration(l.ResumeGraceMS) * time.Millisecond +} + // Validate rejects limits that cannot be honoured, so a client fails at connect // time with an actionable message instead of misbehaving later. func (l Limits) Validate() error { @@ -230,6 +285,12 @@ type ConnectResponse struct { // UploadStreamMode as negotiated above", never as an error: this field is // purely additive over the existing negotiation. Transport string `json:"transport,omitempty"` + // Resumable is true when the server agreed to keep this session alive + // across transport failures (see ConnectRequest.PreferResume). The + // client then wraps the transport in the reliable layer (reliable.go) + // and reattaches through ResumeHandler instead of reconnecting. Empty + // from an older server; a client must treat that as false. + Resumable bool `json:"resumable,omitempty"` } // errorResponse is the JSON body of any non-2xx answer from the handlers. diff --git a/relay_topology_test.go b/relay_topology_test.go index 926c0a9..2235084 100644 --- a/relay_topology_test.go +++ b/relay_topology_test.go @@ -57,6 +57,13 @@ func newMiniBroker(t *testing.T, token string, tls bool) *miniBroker { // newMiniBrokerWithMode is newMiniBroker's poll-mode-aware counterpart, used // by the two topology tests parameterized over batch/stream. func newMiniBrokerWithMode(t *testing.T, token string, tls bool, mode string) *miniBroker { + return newMiniBrokerOpts(t, token, tls, mode, false) +} + +// newMiniBrokerOpts additionally lets the broker offer resumable sessions +// (ServerConfig.EnableResume plus ResumeHandler mounted), the shape +// HttpBroker takes once it turns the feature on. +func newMiniBrokerOpts(t *testing.T, token string, tls bool, mode string, resume bool) *miniBroker { t.Helper() b := &miniBroker{ @@ -87,6 +94,10 @@ func newMiniBrokerWithMode(t *testing.T, token string, tls bool, mode string) *m b.cfg.HeartbeatInterval = 100 * time.Millisecond b.cfg.StreamMaxDuration = 400 * time.Millisecond } + if resume { + b.cfg.EnableResume = true + b.cfg.ResumeGrace = 3 * time.Second + } b.hooks = Hooks{ Authenticate: func(_ *http.Request, req ConnectRequest) (map[string]string, error) { @@ -120,6 +131,9 @@ func newMiniBrokerWithMode(t *testing.T, token string, tls bool, mode string) *m mux.Handle("/tunnel/connect", wrap(ConnectHandler(b.store, b.cfg, b.hooks))) mux.Handle("/tunnel/{id}/poll", wrap(PollHandler(b.store, b.cfg, b.hooks))) mux.Handle("/tunnel/{id}", wrap(DeleteHandler(b.store, b.cfg, b.hooks))) + if resume { + mux.Handle("/tunnel/{id}/resume", wrap(ResumeHandler(b.store, b.cfg, b.hooks))) + } if tls { b.ts = httptest.NewTLSServer(mux) @@ -323,6 +337,14 @@ func runMiniProvider(t *testing.T, ctx context.Context, brokerURL, token, endpoi // runMiniProviderMode is runMiniProvider's poll-mode-aware counterpart. func runMiniProviderMode(t *testing.T, ctx context.Context, brokerURL, token, endpoint string, insecure, preferStream bool) *miniProvider { + return runMiniProviderOpts(t, ctx, brokerURL, token, endpoint, insecure, preferStream, false) +} + +// runMiniProviderOpts additionally lets the provider ask for a resumable +// session. Upload streaming is forced on (no probe) so the session actually +// qualifies for resume; a real deployment that needs the probe gets the +// same result one connect later (see Connector.PreferResume). +func runMiniProviderOpts(t *testing.T, ctx context.Context, brokerURL, token, endpoint string, insecure, preferStream, preferResume bool) *miniProvider { t.Helper() p := &miniProvider{ outcomes: make(chan Outcome, 8), @@ -338,6 +360,11 @@ func runMiniProviderMode(t *testing.T, ctx context.Context, brokerURL, token, en PollGrace: 2 * time.Second, InsecureSkipVerify: insecure, PreferStream: preferStream, + PreferResume: preferResume, + } + if preferResume { + c.UploadStreamPreference = PollModeStream + c.PollGrace = 500 * time.Millisecond } return c.Connect(ctx) }, @@ -404,6 +431,11 @@ func runMiniConsumer(t *testing.T, ctx context.Context, brokerURL, token, endpoi // runMiniConsumerMode is runMiniConsumer's poll-mode-aware counterpart. func runMiniConsumerMode(t *testing.T, ctx context.Context, brokerURL, token, endpoint string, insecure, preferStream bool) *miniConsumer { + return runMiniConsumerOpts(t, ctx, brokerURL, token, endpoint, insecure, preferStream, false) +} + +// runMiniConsumerOpts is runMiniProviderOpts' consumer counterpart. +func runMiniConsumerOpts(t *testing.T, ctx context.Context, brokerURL, token, endpoint string, insecure, preferStream, preferResume bool) *miniConsumer { t.Helper() c := &miniConsumer{ outcomes: make(chan Outcome, 8), @@ -420,6 +452,11 @@ func runMiniConsumerMode(t *testing.T, ctx context.Context, brokerURL, token, en PollGrace: 2 * time.Second, InsecureSkipVerify: insecure, PreferStream: preferStream, + PreferResume: preferResume, + } + if preferResume { + conn.UploadStreamPreference = PollModeStream + conn.PollGrace = 500 * time.Millisecond } return conn.Connect(ctx) }, diff --git a/reliable.go b/reliable.go new file mode 100644 index 0000000..8954cb2 --- /dev/null +++ b/reliable.go @@ -0,0 +1,260 @@ +package pollmux + +import ( + "errors" + "sync" + "time" +) + +// errPipeInterrupted is BufferedPipe.ReadAvailable's answer to interrupt: +// nothing was read, and the caller should re-check its own state (has it +// been detached? is an ack due?) before waiting again. +var errPipeInterrupted = errors.New("pollmux: pipe wait interrupted") + +// errReplayGap is reliable.recvIn's report that the peer sent data starting +// past the receiver's contiguous offset: a hole in the byte stream. There is +// no recovering from that — handing yamux a stream with bytes missing would +// desynchronise every frame after it — so the session must be abandoned. +var errReplayGap = errors.New("pollmux: resumable stream has a gap: peer skipped bytes") + +// errBadAck is reliable.ack's report that the peer acknowledged more than +// was ever sent, which no correct peer can do. +var errBadAck = errors.New("pollmux: peer acknowledged bytes that were never sent") + +// reliable is the resumable transport's byte layer, shared verbatim by both +// ends: on the server it sits between a Session's pipes and the poll/ +// WebSocket handlers, on the client between resumableConn's pipes and its +// legs. Each direction is a cumulative byte count, exactly as TCP does it: +// +// - Sending: bytes taken from out get consecutive offsets and are kept in +// replay until the peer acknowledges them. sentCursor is where the +// currently attached transport is up to; normally it tracks sendOffset, +// and a resume rewinds it to whatever the peer says it has, so the next +// transport replays the gap before taking anything new from out. +// - Receiving: recvIn writes into in only what extends recvOffset. Bytes +// below it are a replay the peer sent because it never saw our ack — +// dropped. Bytes above it are a hole — fatal. +// +// Nothing here ever blocks a sender on the peer: Write into out always +// returns at once, and the only thing acknowledgements control is how much +// memory replay holds. A replay buffer that outgrows maxReplay marks the +// layer broken — the session keeps working over its current transport, but +// it can no longer be resumed and stops retaining anything. +type reliable struct { + out *BufferedPipe // bytes the local application wants delivered to the peer + in *BufferedPipe // bytes received from the peer, for the local application + + mu sync.Mutex + sendOffset uint64 // every byte ever taken from out sits below this + ackedOffset uint64 // the peer has confirmed everything below this + sentCursor uint64 // the attached transport sends from here; ackedOffset <= sentCursor <= sendOffset + replay []byte // bytes [ackedOffset, sendOffset) + maxReplay int + broken bool + + 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 +} + +// ackEagerBytes is how much newly received data prompts an immediate ack +// (by interrupting the sending side's wait) rather than waiting for the next +// data frame or heartbeat to carry it. Half a stream window: yamux itself +// sends a window update at that point, so this matches the reverse-traffic +// cadence a bulk transfer already has. +const ackEagerBytes = MaxStreamWindowSize / 2 + +func newReliable(out, in *BufferedPipe, maxReplay int) *reliable { + if maxReplay <= 0 { + maxReplay = DefaultMaxReplayBytes + } + return &reliable{out: out, in: in, maxReplay: maxReplay, ackEager: ackEagerBytes} +} + +// 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 +// exhausted does it wait on out with ReadAvailable's usual semantics, so the +// error cases are ReadAvailable's: io.EOF when out is closed for good, +// errPipeInterrupted when interrupt was called, (0, nil) on a plain timeout. +// +// Only one transport may be attached per direction at a time — the caller +// (Session's attachment tracking on the server, resumableConn's supervisor +// on the client) guarantees it. Two concurrent callers would each pull bytes +// from out and then race to number them, which would reorder the stream. +func (r *reliable) nextOut(buf []byte, timeout, coalesce time.Duration) (off uint64, n int, err error) { + r.mu.Lock() + if !r.broken && r.sentCursor < r.sendOffset { + start := int(r.sentCursor - r.ackedOffset) + n = copy(buf, r.replay[start:]) + off = r.sentCursor + r.sentCursor += uint64(n) + r.mu.Unlock() + return off, n, nil + } + r.mu.Unlock() + + n, err = r.out.ReadAvailable(buf, timeout, coalesce) + if n == 0 { + return 0, 0, err + } + + r.mu.Lock() + defer r.mu.Unlock() + off = r.sendOffset + r.sendOffset += uint64(n) + r.sentCursor = r.sendOffset + if !r.broken { + r.replay = append(r.replay, buf[:n]...) + if len(r.replay) > r.maxReplay { + r.markBrokenLocked() + } + } + return off, n, nil +} + +// recvIn accepts a data frame from the peer: whatever part of it extends +// recvOffset is written to in, a full duplicate is dropped, a gap is fatal. +func (r *reliable) recvIn(off uint64, p []byte) error { + r.mu.Lock() + switch { + case off > r.recvOffset: + r.markBrokenLocked() + r.mu.Unlock() + return errReplayGap + case off+uint64(len(p)) <= r.recvOffset: + r.mu.Unlock() + return nil // already have all of it + default: + p = p[r.recvOffset-off:] + } + // Written under the lock so recvOffset never runs ahead of what is + // actually in the pipe. BufferedPipe.Write never blocks, so this holds + // r.mu only for a copy. + if _, err := r.in.Write(p); err != nil { + r.mu.Unlock() + return err + } + r.recvOffset += uint64(len(p)) + wake := r.recvOffset-r.lastAck >= uint64(r.ackEager) + r.mu.Unlock() + + if wake { + // Nudge the sending side to carry an ack now instead of at its next + // heartbeat, so the peer's replay buffer does not sit on half a + // window per stream for seconds at a time. + r.out.interrupt() + } + return nil +} + +// ack records the peer's cumulative acknowledgement and releases replay. +func (r *reliable) ack(n uint64) error { + r.mu.Lock() + defer r.mu.Unlock() + if n > r.sendOffset { + r.markBrokenLocked() + return errBadAck + } + if r.broken || n <= r.ackedOffset { + return nil + } + r.replay = r.replay[n-r.ackedOffset:] + if len(r.replay) == 0 { + r.replay = nil // let the old backing array go once it is fully acked + } + r.ackedOffset = n + if r.sentCursor < n { + r.sentCursor = n + } + return nil +} + +// takeAck returns the offset to acknowledge if recvOffset has moved since +// the last one was handed out. The caller commits to sending it; a lost ack +// is harmless because the next one is cumulative, and every fresh +// attachment starts by sending one (see resetAck). +func (r *reliable) takeAck() (uint64, bool) { + r.mu.Lock() + defer r.mu.Unlock() + if r.recvOffset == r.lastAck { + return 0, false + } + r.lastAck = r.recvOffset + return r.recvOffset, true +} + +// resetAck makes the next takeAck report the current recvOffset even if it +// was already acknowledged once, so a newly attached transport always opens +// with an ack the peer may have missed while the previous transport died. +func (r *reliable) resetAck() { + r.mu.Lock() + r.lastAck = 0 + r.mu.Unlock() +} + +// resumeOut rewinds the sending side to peerRecv, what the peer says it +// has: everything below is dropped from replay, everything from there to +// sendOffset will be replayed by the next attached transport. It refuses — +// and the caller must then abandon the session rather than guess — if the +// layer is broken or peerRecv is outside [ackedOffset, sendOffset]: below +// means the peer claims not to have bytes it already acknowledged, above +// means it claims bytes that were never sent. +func (r *reliable) resumeOut(peerRecv uint64) bool { + r.mu.Lock() + defer r.mu.Unlock() + if r.broken || peerRecv < r.ackedOffset || peerRecv > r.sendOffset { + return false + } + r.replay = r.replay[peerRecv-r.ackedOffset:] + if len(r.replay) == 0 { + r.replay = nil + } + r.ackedOffset = peerRecv + r.sentCursor = peerRecv + return true +} + +// recvOffsetNow is what this end reports in a resume handshake. +func (r *reliable) recvOffsetNow() uint64 { + r.mu.Lock() + defer r.mu.Unlock() + return r.recvOffset +} + +// unacked is how many sent bytes the peer has not acknowledged — the replay +// buffer's current size. +func (r *reliable) unacked() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.replay) +} + +func (r *reliable) isBroken() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.broken +} + +// markBroken gives up on resumability: the session keeps running over its +// current transport, but nothing is retained for replay any more and every +// resume attempt will be refused. +func (r *reliable) markBroken() { + r.mu.Lock() + r.markBrokenLocked() + r.mu.Unlock() +} + +func (r *reliable) markBrokenLocked() { + r.broken = true + r.replay = nil + r.ackedOffset = r.sendOffset + r.sentCursor = r.sendOffset +} + +// interruptOut pulls the attached sender out of its wait on out (see +// BufferedPipe.interrupt): used to detach a stale transport promptly and to +// stop a leg on shutdown. +func (r *reliable) interruptOut() { + r.out.interrupt() +} diff --git a/reliable_test.go b/reliable_test.go new file mode 100644 index 0000000..a47c632 --- /dev/null +++ b/reliable_test.go @@ -0,0 +1,375 @@ +package pollmux + +import ( + "bytes" + "errors" + "io" + "testing" + "time" +) + +// --- reliable --------------------------------------------------------------- + +func newTestReliable(maxReplay int) *reliable { + return newReliable(NewBufferedPipe(), NewBufferedPipe(), maxReplay) +} + +func mustNext(t *testing.T, r *reliable, n int) (uint64, []byte) { + t.Helper() + buf := make([]byte, n) + off, got, err := r.nextOut(buf, 50*time.Millisecond, time.Millisecond) + if err != nil { + t.Fatalf("nextOut: %v", err) + } + return off, buf[:got] +} + +func TestReliableNumbersRetainsAndReplays(t *testing.T) { + r := newTestReliable(1 << 20) + + r.out.Write([]byte("hello ")) + off, data := mustNext(t, r, 64) + if off != 0 || string(data) != "hello " { + t.Fatalf("first chunk = (%d, %q), want (0, %q)", off, data, "hello ") + } + r.out.Write([]byte("world")) + off, data = mustNext(t, r, 64) + if off != 6 || string(data) != "world" { + t.Fatalf("second chunk = (%d, %q), want (6, %q)", off, data, "world") + } + if r.unacked() != 11 { + t.Fatalf("unacked = %d, want 11 before any ack", r.unacked()) + } + + // A partial ack releases exactly that prefix. + if err := r.ack(4); err != nil { + t.Fatal(err) + } + if r.unacked() != 7 { + t.Fatalf("unacked = %d after ack(4), want 7", r.unacked()) + } + + // A resume to an offset inside the retained range rewinds the cursor: + // the next chunk is a replay starting exactly there, and only then does + // fresh data follow. + if !r.resumeOut(8) { + t.Fatal("resumeOut(8) refused an offset inside the retained range") + } + r.out.Write([]byte("!")) + off, data = mustNext(t, r, 64) + if off != 8 || string(data) != "rld" { + t.Fatalf("replay chunk = (%d, %q), want (8, %q)", off, data, "rld") + } + off, data = mustNext(t, r, 64) + if off != 11 || string(data) != "!" { + t.Fatalf("post-replay chunk = (%d, %q), want (11, %q)", off, data, "!") + } + + // Replay respects the caller's buffer size and picks up where it left. + if !r.resumeOut(8) { + t.Fatal("second resumeOut(8) refused") + } + off, data = mustNext(t, r, 2) + if off != 8 || string(data) != "rl" { + t.Fatalf("small replay chunk = (%d, %q), want (8, %q)", off, data, "rl") + } + off, data = mustNext(t, r, 2) + if off != 10 || string(data) != "d!" { + t.Fatalf("next small replay chunk = (%d, %q), want (10, %q)", off, data, "d!") + } + + // Out of range in either direction is refused, never guessed. + if r.resumeOut(7) { + t.Fatal("resumeOut below ackedOffset must be refused") + } + if r.resumeOut(13) { + t.Fatal("resumeOut above sendOffset must be refused") + } + if err := r.ack(99); !errors.Is(err, errBadAck) { + t.Fatalf("ack beyond sendOffset = %v, want errBadAck", err) + } +} + +func TestReliableRecvDedupsReplayAndRefusesGaps(t *testing.T) { + r := newTestReliable(1 << 20) + + if err := r.recvIn(0, []byte("abc")); err != nil { + t.Fatal(err) + } + // A replay overlapping what we have contributes only its tail. + if err := r.recvIn(1, []byte("bcdef")); err != nil { + t.Fatal(err) + } + // A replay entirely below recvOffset contributes nothing. + if err := r.recvIn(0, []byte("abcdef")); err != nil { + t.Fatal(err) + } + got := make([]byte, 16) + n, _ := r.in.Read(got) + if string(got[:n]) != "abcdef" { + t.Fatalf("in pipe holds %q, want %q", got[:n], "abcdef") + } + if r.recvOffsetNow() != 6 { + t.Fatalf("recvOffset = %d, want 6", r.recvOffsetNow()) + } + + // takeAck reports movement once, then stays quiet until more arrives or + // resetAck forces a repeat. + if ack, due := r.takeAck(); !due || ack != 6 { + t.Fatalf("takeAck = (%d, %v), want (6, true)", ack, due) + } + if _, due := r.takeAck(); due { + t.Fatal("takeAck reported an ack due with nothing new received") + } + r.resetAck() + if ack, due := r.takeAck(); !due || ack != 6 { + t.Fatalf("takeAck after resetAck = (%d, %v), want (6, true)", ack, due) + } + + if err := r.recvIn(10, []byte("x")); !errors.Is(err, errReplayGap) { + t.Fatalf("gap = %v, want errReplayGap", err) + } + if !r.isBroken() { + t.Fatal("a gap must mark the layer broken") + } +} + +func TestReliableOverflowBreaksAndStopsRetaining(t *testing.T) { + r := newTestReliable(8) + r.out.Write(bytes.Repeat([]byte("a"), 6)) + mustNext(t, r, 64) + if r.isBroken() { + t.Fatal("broken before exceeding maxReplay") + } + r.out.Write(bytes.Repeat([]byte("b"), 6)) + off, data := mustNext(t, r, 64) + if off != 6 || len(data) != 6 { + t.Fatalf("chunk after overflow = (%d, %d bytes), want (6, 6): data must still flow", off, len(data)) + } + if !r.isBroken() { + t.Fatal("exceeding maxReplay must mark the layer broken") + } + if r.unacked() != 0 { + t.Fatalf("unacked = %d after breaking, want 0: nothing should be retained any more", r.unacked()) + } + if r.resumeOut(6) { + t.Fatal("a broken layer must refuse to resume") + } + // Data keeps flowing over the current transport regardless. + r.out.Write([]byte("c")) + off, data = mustNext(t, r, 64) + if off != 12 || string(data) != "c" { + t.Fatalf("post-break chunk = (%d, %q), want (12, %q)", off, data, "c") + } +} + +func TestReliableEagerAckInterruptsSender(t *testing.T) { + r := newTestReliable(1 << 20) + r.ackEager = 4 + + done := make(chan error, 1) + go func() { + _, _, err := r.nextOut(make([]byte, 64), 5*time.Second, time.Millisecond) + done <- err + }() + time.Sleep(20 * time.Millisecond) // let the sender park + if err := r.recvIn(0, []byte("abcd")); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if !errors.Is(err, errPipeInterrupted) { + t.Fatalf("sender woke with %v, want errPipeInterrupted", err) + } + case <-time.After(2 * time.Second): + t.Fatal("receiving ackEager bytes did not wake the parked sender") + } + if ack, due := r.takeAck(); !due || ack != 4 { + t.Fatalf("takeAck after eager wake = (%d, %v), want (4, true)", ack, due) + } +} + +// --- BufferedPipe.interrupt ---------------------------------------------------- + +func TestBufferedPipeInterruptCutsWaitShort(t *testing.T) { + p := NewBufferedPipe() + done := make(chan error, 1) + go func() { + _, err := p.ReadAvailable(make([]byte, 8), 5*time.Second, time.Millisecond) + done <- err + }() + time.Sleep(20 * time.Millisecond) + p.interrupt() + select { + case err := <-done: + if !errors.Is(err, errPipeInterrupted) { + t.Fatalf("interrupted wait returned %v, want errPipeInterrupted", err) + } + case <-time.After(2 * time.Second): + t.Fatal("interrupt did not wake the parked reader") + } + + // The flag was consumed: the next wait is a normal one. + start := time.Now() + if n, err := p.ReadAvailable(make([]byte, 8), 30*time.Millisecond, time.Millisecond); n != 0 || err != nil { + t.Fatalf("plain wait = (%d, %v), want (0, nil) timeout", n, err) + } + if time.Since(start) < 25*time.Millisecond { + t.Fatal("a consumed interrupt must not shorten the following wait") + } +} + +func TestBufferedPipeInterruptIsLevelTriggered(t *testing.T) { + p := NewBufferedPipe() + p.interrupt() // nobody waiting + p.Write([]byte("data")) + + // A pending interrupt wins over buffered data, once. + if _, err := p.ReadAvailable(make([]byte, 8), time.Second, time.Millisecond); !errors.Is(err, errPipeInterrupted) { + t.Fatalf("pending interrupt not honoured: %v", err) + } + n, err := p.ReadAvailable(make([]byte, 8), time.Second, time.Millisecond) + if err != nil || n != 4 { + t.Fatalf("data after interrupt = (%d, %v), want (4, nil)", n, err) + } + + // Close still wins once the interrupt has been consumed. + p.Close() + if _, err := p.ReadAvailable(make([]byte, 8), time.Second, time.Millisecond); !errors.Is(err, io.EOF) { + t.Fatalf("closed pipe = %v, want io.EOF", err) + } +} + +// --- frame codec -------------------------------------------------------------- + +func TestSeqAndAckFramesRoundTrip(t *testing.T) { + var buf bytes.Buffer + if err := writeSeqFrame(&buf, 1<<40, []byte("payload")); err != nil { + t.Fatal(err) + } + if err := writeFrame(&buf, frameAck, encodeOffset(12345)); err != nil { + t.Fatal(err) + } + writeFrame(&buf, frameHeartbeat, nil) + + fr := newFrameReader(&buf, 7) + typ, payload, err := fr.next() + if err != nil || typ != frameSeqData { + t.Fatalf("first frame = (%v, %v), want frameSeqData", typ, err) + } + off, data, err := splitSeq(payload) + if err != nil || off != 1<<40 || string(data) != "payload" { + t.Fatalf("splitSeq = (%d, %q, %v)", off, data, err) + } + + typ, payload, err = fr.next() + if err != nil || typ != frameAck { + t.Fatalf("second frame = (%v, %v), want frameAck", typ, err) + } + if n, err := decodeAck(payload); err != nil || n != 12345 { + t.Fatalf("decodeAck = (%d, %v), want 12345", n, err) + } + + typ, _, err = fr.next() + if err != nil || typ != frameHeartbeat { + t.Fatalf("third frame = (%v, %v), want frameHeartbeat", typ, err) + } + if _, _, err := fr.next(); !errors.Is(err, io.EOF) { + t.Fatalf("end = %v, want io.EOF", err) + } +} + +func TestFrameReaderAllowsSeqOffsetOverDataBound(t *testing.T) { + // A seq-data frame carrying exactly maxPayload bytes of data is legal + // even though its payload is 8 bytes longer than a plain data frame + // could be; one byte more is not. + var ok bytes.Buffer + writeSeqFrame(&ok, 0, make([]byte, 16)) + if _, _, err := newFrameReader(&ok, 16).next(); err != nil { + t.Fatalf("seq frame at the bound rejected: %v", err) + } + var tooBig bytes.Buffer + writeSeqFrame(&tooBig, 0, make([]byte, 17)) + if _, _, err := newFrameReader(&tooBig, 16).next(); err == nil { + t.Fatal("seq frame over the bound accepted") + } + var plainTooBig bytes.Buffer + writeFrame(&plainTooBig, frameData, make([]byte, 17)) + if _, _, err := newFrameReader(&plainTooBig, 16).next(); err == nil { + t.Fatal("plain data frame over the bound accepted") + } + if _, err := decodeAck([]byte{1, 2, 3}); err == nil { + t.Fatal("short ack payload accepted") + } + if _, _, err := splitSeq([]byte{1, 2, 3}); err == nil { + t.Fatal("short seq payload accepted") + } +} + +// --- attachments -------------------------------------------------------------- + +func TestAttachmentsReplaceStaleOwnerAndTrackCurrent(t *testing.T) { + a := newAttachments() + + // The first owner's kick releases it, the way a real handler's deferred + // detach does once its blocked call fails. + var first *attachment + var err error + first, err = a.attach(attachDown, func() { a.detach(first) }) + if err != nil { + t.Fatal(err) + } + if !a.isCurrent(first) { + t.Fatal("fresh attachment is not current") + } + + second, err := a.attach(attachDown, func() {}) + if err != nil { + t.Fatalf("second attach: %v", err) + } + if a.isCurrent(first) || !a.isCurrent(second) { + t.Fatal("second attach did not displace the first") + } + select { + case <-first.done: + default: + t.Fatal("displaced attachment's done channel is still open") + } + + // An owner whose kick achieves nothing is waited out and reported. + start := time.Now() + if _, err := a.attach(attachDown, func() {}); !errors.Is(err, errStillAttached) { + t.Fatalf("attach over a stuck owner = %v, want errStillAttached", err) + } + if time.Since(start) < detachWait { + t.Fatal("attach gave up before detachWait") + } + a.detach(second) + if a.isCurrent(second) { + t.Fatal("detached attachment still current") + } + + // attachBoth claims both directions; kickAll clears them. + var both *attachment + both, err = a.attach(attachBoth, func() { a.detach(both) }) + if err != nil { + t.Fatal(err) + } + if a.down != both || a.up != both { + t.Fatal("attachBoth did not claim both directions") + } + if err := a.kickAll(); err != nil { + t.Fatal(err) + } + if a.down != nil || a.up != nil { + t.Fatal("kickAll left an owner in place") + } + + if !a.beginResume() || a.beginResume() { + t.Fatal("beginResume must be exclusive") + } + a.endResume() + if !a.beginResume() { + t.Fatal("beginResume after endResume must succeed") + } +} diff --git a/resumable_client.go b/resumable_client.go new file mode 100644 index 0000000..6ff92fe --- /dev/null +++ b/resumable_client.go @@ -0,0 +1,729 @@ +package pollmux + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "maps" + "math/rand/v2" + "net/http" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/coder/websocket" +) + +// resumableConn is Conn's implementation for a session that negotiated +// ConnectResponse.Resumable. Where httpConn and wsConn give up on the whole +// session the moment their transport fails, this one keeps the session — +// and the yamux session the caller built on top of it — alive across the +// failure: a supervisor goroutine tears down the dead legs, performs the +// resume handshake (see ResumeHandler), and brings up fresh legs on the same +// session id. yamux above sees a Read that took a while and a Write that +// returned at once, nothing else. +// +// The pieces: +// +// - rl, the reliable byte layer (reliable.go), numbers every byte yamux +// writes, retains it until the server acknowledges it, and drops +// anything the server replays that already arrived. It is the one part +// that persists across transports; everything below it is disposable. +// - Legs are the transport goroutines: a stream poll pulling frames down +// and a send-stream pushing frames up, or a WebSocket read loop and +// write loop. Each set lives exactly as long as one transport. +// - The supervisor (supervise) is the only goroutine that ever decides a +// transport is over, so there is never more than one set of legs, and +// the reliable layer's one-sender-per-direction rule holds. +// +// TransportFailed is only closed when resuming is impossible: the server +// refused (grace expired, offsets it cannot honour, session gone), the +// replay buffer overflowed, or the reconnect budget ran out. At that point +// the caller's ReconnectLoop does what it does today — a brand new session. +type resumableConn struct { + sessionGuard + sessionID string + limits Limits + meta map[string]string + logger *slog.Logger + + 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. + pollClient *http.Client + sendStreamClient *http.Client + httpClient *http.Client + + localHealth func() bool + heartbeat time.Duration + idleTimeout time.Duration + streamMaxDuration time.Duration + coalesceWindow time.Duration + sendTimeout time.Duration + dialTimeout time.Duration + maxFrame int + resumeGrace time.Duration + + // ws is the current WebSocket connection when transport is + // TransportWebSocket. Only the supervisor replaces it, between one set + // of legs ending and the next starting; Close reads it after waiting + // the supervisor out. Atomic anyway, so that safety does not hinge on + // a reader knowing that ordering. + ws atomic.Pointer[websocket.Conn] + + transportFailed chan struct{} + failOnce sync.Once + + closed atomic.Bool + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +func (c *resumableConn) SessionID() string { return c.sessionID } +func (c *resumableConn) Limits() Limits { return c.limits } +func (c *resumableConn) Meta() map[string]string { return maps.Clone(c.meta) } +func (c *resumableConn) TransportFailed() <-chan struct{} { return c.transportFailed } + +// Read returns data the server sent. It blocks through a transport failure +// and resume — the read pipe is only ever closed by Close or by giving up. +func (c *resumableConn) Read(p []byte) (int, error) { return c.rl.in.Read(p) } + +// Write queues data for delivery and returns at once, whether or not a +// transport is currently attached. That is what keeps yamux from ever +// blocking in a write during an outage (its ConnectionWriteTimeout would +// otherwise end the session for us); the bytes wait in the reliable layer, +// bounded by yamux's own flow control. +func (c *resumableConn) Write(p []byte) (int, error) { + if c.closed.Load() { + return 0, io.ErrClosedPipe + } + if len(p) == 0 { + return 0, nil + } + return c.rl.out.Write(p) +} + +// Close stops the supervisor and its legs and tells the server to drop the +// session. This is the only path that sends a DELETE: a resume never does, +// since that would kill the very session it is trying to keep. +func (c *resumableConn) Close() error { + if !c.closed.CompareAndSwap(false, true) { + return nil + } + + c.cancel() + // Closing out unblocks a sender parked in nextOut with io.EOF; the + // interrupt covers the case where out already has data queued and the + // sender would otherwise go on to try writing it to a dead leg. + c.rl.out.Close() + c.rl.interruptOut() + c.wg.Wait() + c.rl.in.Close() + if ws := c.ws.Load(); ws != nil { + ws.CloseNow() + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, c.deleteURL, nil) + if err == nil { + c.setAuth(req) + if resp, err := c.httpClient.Do(req); err == nil { + io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) + resp.Body.Close() + } + } + + c.httpClient.CloseIdleConnections() + if c.pollClient != nil { + c.pollClient.CloseIdleConnections() + } + if c.sendStreamClient != nil { + c.sendStreamClient.CloseIdleConnections() + } + return nil +} + +func (c *resumableConn) setAuth(req *http.Request) { + if c.authToken != "" { + req.Header.Set("Authorization", "Bearer "+c.authToken) + } +} + +// fail gives up on the session: signals transport failure once and unblocks +// anyone reading. +func (c *resumableConn) fail() { + c.failOnce.Do(func() { + close(c.transportFailed) + c.rl.in.Close() + }) +} + +func (c *resumableConn) onSessionClosed() { + if c.supersededByNewerConnect(c.logger) { + c.rl.in.Close() + return + } + c.fail() +} + +// supervise runs one set of legs after another until the connection is +// closed or the session cannot be kept. Between sets it decides, from why +// the previous set ended, whether resuming is even worth attempting: a +// server that closed the session (410, frameGone) will not have it back, +// and a reliable layer that caught an inconsistency (a gap, an impossible +// ack, an overflowed replay buffer) cannot vouch for the byte stream any +// more. Everything else is a transport problem, and transport problems are +// what resume is for. +func (c *resumableConn) supervise() { + defer c.wg.Done() + for { + err := c.runLegs() + if c.ctx.Err() != nil || c.closed.Load() { + return + } + if isSessionClosedErr(err) { + c.onSessionClosed() + return + } + if errors.Is(err, errReplayGap) || errors.Is(err, errBadAck) || c.rl.isBroken() { + c.logger.Warn("pollmux: resumable session is no longer consistent, giving up on it", "error", err) + c.fail() + return + } + + c.logger.Warn("pollmux: transport failed, resuming the session", "error", err) + if err := c.resume(); err != nil { + if c.ctx.Err() != nil || c.closed.Load() { + return + } + if isSessionClosedErr(err) { + c.onSessionClosed() + return + } + c.logger.Warn("pollmux: could not resume the session, falling back to a fresh one", "error", err) + c.fail() + return + } + c.logger.Info("pollmux: session resumed", + "recv_offset", c.rl.recvOffsetNow(), "unacked_bytes", c.rl.unacked()) + } +} + +// runLegs runs one transport's legs to completion. Whichever leg fails first +// decides the outcome; the other is cancelled and waited for, so by the time +// this returns nothing is touching the pipes and a resume may safely rewind +// the reliable layer. +func (c *resumableConn) runLegs() error { + legCtx, cancel := context.WithCancel(c.ctx) + defer cancel() + + errCh := make(chan error, 2) + ws := c.ws.Load() + if c.transport == TransportWebSocket { + 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) }() + } + + err := <-errCh + cancel() + // A sender parked in nextOut has no context to observe; this is what + // gets it back to check legCtx. + c.rl.interruptOut() + if ws != nil { + ws.CloseNow() + } + <-errCh + return err +} + +// resume performs the handshake with ResumeHandler and, for WebSocket +// transport, dials the replacement connection, retrying transient failures +// with jittered backoff until the server's grace period is spent. A +// definitive refusal (any 4xx, including the 409 for offsets the server +// cannot honour and the 410/404 for a session that is gone) ends it at +// once — retrying cannot change a server's mind about those. +// +// The jitter matters more here than for an ordinary reconnect: the failure +// this exists for — a CDN closing every connection that reached its +// maximum age — hits a whole fleet of clients within the same second, and +// without it they would all retry on the same beat. +func (c *resumableConn) resume() error { + deadline := time.Now().Add(c.resumeGrace) + backoff := 250 * time.Millisecond + var lastErr error + + for attempt := 1; ; attempt++ { + serverRecv, err := c.doResume() + switch { + case err == nil: + if !c.rl.resumeOut(serverRecv) { + return fmt.Errorf("pollmux: server's recv_offset %d is outside what this side can replay", serverRecv) + } + if c.transport != TransportWebSocket { + return nil + } + ws, err := c.dialWS() + if err == nil { + c.ws.Store(ws) + return nil + } + // A dial failure right after a successful handshake: the next + // attempt repeats the handshake, which is idempotent — nothing + // moved on either side in between. + lastErr = err + default: + var fatal *fatalPollError + if errors.As(err, &fatal) && fatal.status < http.StatusInternalServerError { + return err + } + lastErr = err + } + + if time.Now().After(deadline) { + return fmt.Errorf("pollmux: resume grace %v exhausted after %d attempts: %w", c.resumeGrace, attempt, lastErr) + } + wait := jitter(backoff) + c.logger.Debug("pollmux: resume attempt failed, retrying", "attempt", attempt, "error", lastErr, "retry_in", wait) + if !sleepOrDone(c.ctx, wait) { + return c.ctx.Err() + } + backoff = min(backoff*2, 2*time.Second) + } +} + +// jitter spreads d by ±20%, so clients that lost their transport at the +// same instant do not retry in lockstep. +func jitter(d time.Duration) time.Duration { + return time.Duration(float64(d) * (0.8 + 0.4*rand.Float64())) +} + +// doResume performs one POST {prefix}/{id}/resume exchange. +func (c *resumableConn) doResume() (uint64, error) { + body, err := json.Marshal(ResumeRequest{ + ProtocolVersion: ProtocolVersion, + RecvOffset: c.rl.recvOffsetNow(), + }) + if err != nil { + return 0, err + } + + ctx, cancel := context.WithTimeout(c.ctx, c.sendTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.resumeURL, bytes.NewReader(body)) + if err != nil { + return 0, err + } + req.Header.Set("Content-Type", "application/json") + c.setAuth(req) + + resp, err := c.httpClient.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + detail, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<10)) + return 0, &fatalPollError{status: resp.StatusCode, detail: strings.TrimSpace(string(detail))} + } + var rr ResumeResponse + if err := json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&rr); err != nil { + return 0, fmt.Errorf("pollmux: failed to parse resume response: %w", err) + } + if !rr.Resumed { + return 0, &fatalPollError{status: http.StatusConflict, detail: "server did not resume the session"} + } + return rr.RecvOffset, nil +} + +// ---- stream-mode legs ---- + +// downLoop is pollLoopStream's counterpart: one stream poll after another, +// reopening on a clean end, returning on anything else. +func (c *resumableConn) downLoop(ctx context.Context) error { + for { + err := c.doStreamPoll(ctx) + if errors.Is(err, errStreamEnd) { + if ctx.Err() != nil { + return ctx.Err() + } + continue + } + return err + } +} + +// doStreamPoll is httpConn.doStreamPoll for a resumable session: data +// arrives as frameSeqData and goes through the reliable layer, and frameAck +// releases replay. A plain frameData is a protocol error here — the server +// never sends one on a resumable session. +func (c *resumableConn) doStreamPoll(ctx context.Context) error { + reqCtx, cancelReq := context.WithCancel(ctx) + defer cancelReq() + + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.pollURL, nil) + if err != nil { + return err + } + req.Header.Set(HeaderReceiveOnly, "true") + 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 err + } + defer resp.Body.Close() + + switch resp.StatusCode { + case http.StatusOK: + case http.StatusGone: + return &fatalPollError{status: resp.StatusCode, detail: "session closed by server"} + default: + detail, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<10)) + return &fatalPollError{status: resp.StatusCode, detail: strings.TrimSpace(string(detail))} + } + + watchdog := time.AfterFunc(c.idleTimeout, cancelReq) + defer watchdog.Stop() + + fr := newFrameReader(resp.Body, c.maxFrame) + for { + typ, payload, err := fr.next() + if err != nil { + if errors.Is(err, io.EOF) { + return errStreamEnd + } + if reqCtx.Err() != nil && ctx.Err() == nil { + return fmt.Errorf("pollmux: stream idle watchdog fired after %v with no frame", c.idleTimeout) + } + return fmt.Errorf("reading stream frame: %w", err) + } + watchdog.Reset(c.idleTimeout) + + switch typ { + case frameSeqData: + off, data, err := splitSeq(payload) + if err == nil { + err = c.rl.recvIn(off, data) + } + if err != nil { + return err + } + case frameAck: + n, err := decodeAck(payload) + if err == nil { + err = c.rl.ack(n) + } + if err != nil { + return err + } + case frameHeartbeat: + case frameEnd: + return errStreamEnd + case frameGone: + return errSessionGone + case frameData: + return errors.New("pollmux: server sent an unnumbered data frame on a resumable session") + default: + return fmt.Errorf("pollmux: unknown stream frame type %#x", typ) + } + } +} + +// upLoop is sendLoopStream's counterpart: one send-stream request after +// another, reopening on a clean rollover. +func (c *resumableConn) upLoop(ctx context.Context) error { + for { + if err := c.doSendStream(ctx); err != nil { + return err + } + if ctx.Err() != nil { + return ctx.Err() + } + } +} + +// doSendStream is httpConn.doSendStream with the resumable feeder. +func (c *resumableConn) doSendStream(ctx context.Context) error { + pr, pw := io.Pipe() + feedErrCh := make(chan error, 1) + go func() { feedErrCh <- c.feedSendStream(ctx, pw) }() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.pollURL, pr) + if err != nil { + pw.CloseWithError(err) + <-feedErrCh + return err + } + req.Header.Set("Content-Type", "application/octet-stream") + req.Header.Set(HeaderSendStream, "true") + req.ContentLength = -1 + c.setAuth(req) + + resp, err := c.sendStreamClient.Do(req) + feedErr := <-feedErrCh + if err != nil { + return err + } + defer resp.Body.Close() + io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) + + switch resp.StatusCode { + case http.StatusOK: + return feedErr + case http.StatusGone: + return &fatalPollError{status: resp.StatusCode, detail: "session closed by server"} + default: + return &fatalPollError{status: resp.StatusCode} + } +} + +// feedSendStream is httpConn.feedSendStream for a resumable session: bytes +// come from the reliable layer (pending replay first) as frameSeqData, each +// write is preceded by any due ack, and an interrupted wait is either the +// leg being torn down (ctx done) or an ack being due. Every leg opens with +// an ack, so a server that missed one on the previous leg catches up. +func (c *resumableConn) feedSendStream(ctx context.Context, pw *io.PipeWriter) error { + buf := make([]byte, c.maxFrame) + deadline := time.Now().Add(c.streamMaxDuration) + c.rl.resetAck() + + for { + off, n, err := c.rl.nextOut(buf, c.heartbeat, c.coalesceWindow) + interrupted := false + switch { + case errors.Is(err, io.EOF): + // out closed: Close() was called. End this leg cleanly. + writeFrame(pw, frameEnd, nil) + pw.Close() + return nil + case errors.Is(err, errPipeInterrupted): + if ctx.Err() != nil { + pw.CloseWithError(ctx.Err()) + return ctx.Err() + } + interrupted = true + } + + if ack, due := c.rl.takeAck(); due { + if err := writeFrame(pw, frameAck, encodeOffset(ack)); err != nil { + pw.CloseWithError(err) + return err + } + } + switch { + case n > 0: + if err := writeSeqFrame(pw, off, buf[:n]); err != nil { + pw.CloseWithError(err) + return err + } + case !interrupted: + if err := writeFrame(pw, frameHeartbeat, nil); err != nil { + pw.CloseWithError(err) + return err + } + } + + if time.Now().After(deadline) { + writeFrame(pw, frameEnd, nil) + pw.Close() + return nil + } + } +} + +// ---- WebSocket legs ---- + +func (c *resumableConn) dialWS() (*websocket.Conn, error) { + header := http.Header{} + if c.authToken != "" { + header.Set("Authorization", "Bearer "+c.authToken) + } + dialCtx, cancel := context.WithTimeout(c.ctx, c.dialTimeout) + defer cancel() + ws, _, err := websocket.Dial(dialCtx, c.wsURL, &websocket.DialOptions{ + HTTPClient: c.httpClient, + HTTPHeader: header, + }) + if err != nil { + return nil, fmt.Errorf("pollmux: websocket dial failed: %w", err) + } + ws.SetReadLimit(int64(c.maxFrame) + 1 + seqHeaderLen) + return ws, nil +} + +// wsReadLoop is wsConn.readLoop through the reliable layer. +func (c *resumableConn) wsReadLoop(ctx context.Context, ws *websocket.Conn) error { + for { + rctx, cancel := context.WithTimeout(ctx, c.idleTimeout) + typ, msg, err := ws.Read(rctx) + cancel() + if err != nil { + return err + } + if typ != websocket.MessageBinary { + continue + } + ft, payload, err := wsDecode(msg) + if err != nil { + return err + } + switch ft { + case frameSeqData: + off, data, err := splitSeq(payload) + if err == nil { + err = c.rl.recvIn(off, data) + } + if err != nil { + return err + } + case frameAck: + n, err := decodeAck(payload) + if err == nil { + err = c.rl.ack(n) + } + if err != nil { + return err + } + case frameHeartbeat: + case frameData: + return errors.New("pollmux: server sent an unnumbered data frame on a resumable session") + default: + return fmt.Errorf("pollmux: unexpected websocket frame type %#x", ft) + } + } +} + +// wsWriteLoop is wsConn.writeLoop through the reliable layer; see +// feedSendStream for the shape. +func (c *resumableConn) wsWriteLoop(ctx context.Context, ws *websocket.Conn) error { + buf := make([]byte, c.maxFrame) + c.rl.resetAck() + + for { + off, n, err := c.rl.nextOut(buf, c.heartbeat, c.coalesceWindow) + interrupted := false + switch { + case errors.Is(err, io.EOF): + return io.EOF // Close() was called + case errors.Is(err, errPipeInterrupted): + if ctx.Err() != nil { + return ctx.Err() + } + interrupted = true + } + + wctx, cancel := context.WithTimeout(ctx, c.idleTimeout) + if ack, due := c.rl.takeAck(); due { + err = ws.Write(wctx, websocket.MessageBinary, wsEncode(frameAck, encodeOffset(ack))) + } + if err == nil { + switch { + case n > 0: + err = ws.Write(wctx, websocket.MessageBinary, wsEncodeSeq(off, buf[:n])) + case !interrupted: + err = ws.Write(wctx, websocket.MessageBinary, wsEncode(frameHeartbeat, nil)) + } + } + cancel() + if err != nil { + return err + } + } +} + +// connectResumable builds the Conn for a connect that negotiated Resumable. +// Called by Connector.connect once every transport-level validation has +// passed and, for stream mode with UploadStreamPreference left on auto, +// once the upload probe has passed too. +func (c *Connector) connectResumable(ctx context.Context, base string, cr *ConnectResponse, + dialTimeout, sendTimeout, pollGrace, coalesce time.Duration) (Conn, error) { + maxFrame := orInt(cr.Limits.PollBufferBytes, DefaultPollBufferSize) + logger := c.logger().With("session_id", cr.SessionID) + + connCtx, cancel := context.WithCancel(context.Background()) + conn := &resumableConn{ + sessionGuard: newSessionGuard(c, cr.SessionID, cancel), + sessionID: cr.SessionID, + limits: cr.Limits, + meta: cr.Meta, + logger: logger, + rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), c.MaxReplayBytes), + transport: cr.Transport, + 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), + wsURL: fmt.Sprintf("%s/%s/ws", base, cr.SessionID), + authToken: c.AuthToken, + httpClient: &http.Client{Timeout: sendTimeout, Transport: c.newTransport(dialTimeout, sendTimeout), CheckRedirect: noRedirect}, + localHealth: c.LocalHealth, + heartbeat: cr.Limits.HeartbeatInterval(), + idleTimeout: cr.Limits.HeartbeatInterval() + pollGrace, + streamMaxDuration: cr.Limits.StreamMaxDuration(), + coalesceWindow: coalesce, + sendTimeout: sendTimeout, + dialTimeout: dialTimeout, + maxFrame: maxFrame, + resumeGrace: cr.Limits.ResumeGrace(), + transportFailed: make(chan struct{}), + ctx: connCtx, + cancel: cancel, + } + + if cr.Transport == TransportWebSocket { + // The WebSocket dial reuses httpClient for the upgrade request + // itself, so its Timeout must not cut a long-lived connection + // short: coder/websocket only uses the client for the handshake. + conn.httpClient.Timeout = 0 + ws, err := conn.dialWS() + if err != nil { + cancel() + return nil, err + } + conn.ws.Store(ws) + } else { + 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} + } + + c.adoptSession(cr.SessionID) + + logger.Debug("pollmux: connected (resumable)", + "transport", conn.transport, + "resume_grace", conn.resumeGrace, + "poll_buffer_bytes", maxFrame, + ) + + conn.wg.Add(1) + go conn.supervise() + return conn, nil +} diff --git a/resume_server.go b/resume_server.go new file mode 100644 index 0000000..53f4ea4 --- /dev/null +++ b/resume_server.go @@ -0,0 +1,286 @@ +package pollmux + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sync" + "time" +) + +// attachKind names the direction a poll handler owns on a resumable +// session. Stream mode has two independent legs — the long poll carrying +// data down and the send-stream carrying data up — each attached and +// detached on its own; a WebSocket owns both at once. +type attachKind int + +const ( + attachDown attachKind = iota + attachUp + attachBoth +) + +// attachment is one handler's claim on a direction. kick must make that +// handler return promptly from wherever it is blocked — a parked pipe wait, +// a network write to a peer that is no longer reading — and done is closed +// when it has actually let go. +type attachment struct { + kick func() + done chan struct{} + doneOnce sync.Once +} + +// attachments enforces one transport per direction on a resumable session. +// The reliable layer numbers bytes as it takes them from the pipe, so two +// handlers draining the same direction would interleave the stream (see +// reliable.nextOut); and a resume must know that the previous transport has +// stopped for good before it trusts the offsets it is about to exchange. +// Both needs are met the same way: whoever wants a direction kicks the +// current owner and waits for it to leave. +type attachments struct { + mu sync.Mutex + down, up *attachment + resuming bool +} + +func newAttachments() *attachments { return &attachments{} } + +// errStillAttached is attach/kickAll's report that the previous owner did +// not let go within detachWait. It is transient: the handler is presumably +// stuck in a network write that will fail on its own shortly, so the client +// is told to retry (503) rather than to give up. +var errStillAttached = errors.New("pollmux: previous transport has not detached yet") + +// detachWait bounds how long a replacement waits for a kicked attachment to +// leave. The kick cancels every wait the old handler can be in, so this is +// a safety net rather than an expected delay. +const detachWait = 3 * time.Second + +func (a *attachments) slot(kind attachKind) **attachment { + if kind == attachUp { + return &a.up + } + return &a.down +} + +// attach claims kind for a new handler, kicking and waiting out any current +// owner first. attachBoth claims both directions (WebSocket). +func (a *attachments) attach(kind attachKind, kick func()) (*attachment, error) { + att := &attachment{kick: kick, done: make(chan struct{})} + kinds := []attachKind{kind} + if kind == attachBoth { + kinds = []attachKind{attachDown, attachUp} + } + for _, k := range kinds { + for { + a.mu.Lock() + slot := a.slot(k) + old := *slot + if old == nil { + *slot = att + a.mu.Unlock() + break + } + a.mu.Unlock() + if err := old.kickAndWait(); err != nil { + a.detach(att) // release whatever this call already claimed + return nil, err + } + } + } + return att, nil +} + +// detach releases every direction att owns and marks it done. Idempotent. +func (a *attachments) detach(att *attachment) { + a.mu.Lock() + if a.down == att { + a.down = nil + } + if a.up == att { + a.up = nil + } + a.mu.Unlock() + att.doneOnce.Do(func() { close(att.done) }) +} + +// isCurrent reports whether att still owns at least one direction — a +// handler woken by an interrupt uses it to tell "you have been replaced" +// from "an ack is due". +func (a *attachments) isCurrent(att *attachment) bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.down == att || a.up == att +} + +// kickAll detaches every current owner and waits for them to leave, so the +// caller (ResumeHandler) can read final offsets. +func (a *attachments) kickAll() error { + a.mu.Lock() + olds := []*attachment{a.down, a.up} + a.mu.Unlock() + for _, old := range olds { + if old == nil { + continue + } + if err := old.kickAndWait(); err != nil { + return err + } + } + return nil +} + +func (att *attachment) kickAndWait() error { + att.kick() + select { + case <-att.done: + return nil + case <-time.After(detachWait): + return errStillAttached + } +} + +// beginResume makes resume handshakes mutually exclusive. A client's own +// retry can overlap a slow first attempt; the second one is told to come +// back (503), never to give up. +func (a *attachments) beginResume() bool { + a.mu.Lock() + defer a.mu.Unlock() + if a.resuming { + return false + } + a.resuming = true + return true +} + +func (a *attachments) endResume() { + a.mu.Lock() + a.resuming = false + a.mu.Unlock() +} + +// ResumeHandler serves POST {prefix}/{id}/resume, the handshake a resumable +// client performs after its transport failed and before it attaches a new +// one. Register it alongside ConnectHandler/PollHandler/DeleteHandler (and +// WebSocketHandler); it only ever succeeds for a session ConnectHandler +// negotiated Resumable for (see ServerConfig.EnableResume). +// +// The exchange is symmetric: the client says how many downstream bytes it +// has received contiguously, the server rewinds its send side to exactly +// there and answers with the same number for the upstream direction. Both +// ends then replay from those offsets on the next transport, and neither +// yamux sees anything but a pause. +// +// Before trusting its own offsets the handler kicks whatever handler still +// owns either direction and waits for it to leave — a transport the client +// has already given up on may still look attached here for as long as it +// takes the server to notice. Any inconsistency (an offset outside what the +// replay buffer can honour, a session whose reliable layer already broke) +// is refused with 409, and the client falls back to a fresh session rather +// than resuming with the wrong bytes. +// +// An offset outside [acked, sent] does more than fail the request: it ends +// the session's resumability for good. Refusing alone would let a peer +// whose state has drifted try other offsets until one happens to land +// inside the range, and resuming from a guessed offset is exactly the +// silent corruption this whole layer exists to rule out. The honest peer +// loses nothing by this — after a 409 it abandons the session anyway. +// +// Authorization is the same as PollHandler, DeleteHandler and +// WebSocketHandler's: the 128-bit random session id in the path, plus +// whatever middleware the application puts in front of all of them. Mount +// this handler behind the very same middleware — a caller who can reach it +// unauthenticated could break a session's resumability, though note that +// the same caller could already DELETE the session outright, so the +// endpoint adds no capability the id did not already confer. +// +// Status codes: 200 resumed; 404 unknown session; 409 cannot be resumed +// (not negotiated, broken, or an offset out of range — give up); 410 closed; +// 426 protocol version; 503 try again shortly (a previous transport is +// still letting go, or another resume is in flight). +func ResumeHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { + cfg.check() + cfg = cfg.withDefaults() + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := cfg.SessionIDFunc(r) + s, ok := st.Get(id) + if !ok { + writeError(w, http.StatusNotFound, "session not found") + return + } + + var req ResumeRequest + body := http.MaxBytesReader(w, r.Body, 64<<10) + if err := json.NewDecoder(body).Decode(&req); err != nil && err != io.EOF { + writeError(w, http.StatusBadRequest, "malformed resume request: "+err.Error()) + return + } + if req.ProtocolVersion != ProtocolVersion { + writeError(w, http.StatusUpgradeRequired, + fmt.Sprintf("unsupported protocol_version %d, this server speaks %d", req.ProtocolVersion, ProtocolVersion)) + return + } + + if s.rs == nil { + writeError(w, http.StatusConflict, "session was not negotiated as resumable") + return + } + // Counting as an attached transport for the duration of the + // handshake is what keeps the sweeper and any conditional close + // from evicting the session between the offset exchange and the + // client's next attach; and endPoll restarts the grace clock. + if !s.beginPoll() { + writeError(w, http.StatusGone, "session closed") + return + } + defer s.endPoll() + s.touch() + + if s.rs.isBroken() { + writeError(w, http.StatusConflict, "session is no longer resumable") + return + } + if !s.att.beginResume() { + writeError(w, http.StatusServiceUnavailable, "another resume is in progress") + return + } + defer s.att.endResume() + + if err := s.att.kickAll(); err != nil { + cfg.Logger.Debug("pollmux: resume waited out its detach budget", "session_id", id, "error", err) + writeError(w, http.StatusServiceUnavailable, "previous transport is still detaching, retry") + return + } + + if !s.rs.resumeOut(req.RecvOffset) { + cfg.Logger.Warn("pollmux: refusing resume with an offset the replay buffer cannot honour", + "session_id", id, "client_recv_offset", req.RecvOffset) + s.rs.markBroken() + writeError(w, http.StatusConflict, "recv_offset is outside the replayable range") + return + } + + upRecv := s.rs.recvOffsetNow() + cfg.Logger.Info("pollmux: session resumed", + "session_id", id, "client_recv_offset", req.RecvOffset, "server_recv_offset", upRecv) + writeJSON(w, http.StatusOK, ResumeResponse{Resumed: true, RecvOffset: upRecv}) + }) +} + +// 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. +func negotiateResume(cfg ServerConfig, req ConnectRequest, transport, pollMode, uploadMode string) bool { + if !cfg.EnableResume || !req.PreferResume { + return false + } + if transport == TransportWebSocket { + return true + } + return pollMode == PollModeStream && uploadMode == PollModeStream +} diff --git a/resume_test.go b/resume_test.go new file mode 100644 index 0000000..5aa287c --- /dev/null +++ b/resume_test.go @@ -0,0 +1,1320 @@ +package pollmux + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/coder/websocket" + "github.com/hashicorp/yamux" +) + +// --------------------------------------------------------------------------- +// harness +// --------------------------------------------------------------------------- + +// testResumeServerConfig is testServerConfig with two-way stream mode, +// WebSocket, and resume all switched on, so one server can negotiate every +// shape ResumeHandler has to deal with. +func testResumeServerConfig() ServerConfig { + return ServerConfig{ + PollTimeout: 200 * time.Millisecond, + SessionTimeout: 400 * time.Millisecond, + SweepInterval: 20 * time.Millisecond, + CoalesceWindow: 5 * time.Millisecond, + PollBufferSize: 4 << 10, + MaxSendBytes: 1 << 16, + PollMode: PollModeStream, + HeartbeatInterval: 50 * time.Millisecond, + StreamMaxDuration: 2 * time.Second, + EnableWebSocket: true, + EnableResume: true, + ResumeGrace: time.Second, + } +} + +// newResumeTestServer mounts every handler, including ResumeHandler. +func newResumeTestServer(t *testing.T, cfg ServerConfig, h Hooks) (*httptest.Server, *SessionStore) { + t.Helper() + st := NewSessionStore() + mux := http.NewServeMux() + mux.Handle("POST /tunnel/connect", ConnectHandler(st, cfg, h)) + mux.Handle("POST /tunnel/{id}/poll", PollHandler(st, cfg, h)) + mux.Handle("POST /tunnel/{id}/resume", ResumeHandler(st, cfg, h)) + mux.Handle("DELETE /tunnel/{id}", DeleteHandler(st, cfg, h)) + mux.Handle("GET /tunnel/{id}/ws", WebSocketHandler(st, cfg, h)) + ts := httptest.NewServer(mux) + t.Cleanup(ts.Close) + return ts, st +} + +// connectResumableStream negotiates a two-way stream, resumable session. +func connectResumableStream(t *testing.T, ts *httptest.Server) ConnectResponse { + t.Helper() + resp, cr := postConnect(t, ts, ConnectRequest{ + ProtocolVersion: ProtocolVersion, PreferStreamMode: true, PreferStreamUpload: true, PreferResume: true, + }) + if resp.StatusCode != http.StatusOK { + t.Fatalf("connect status = %d, want 200", resp.StatusCode) + } + if !cr.Resumable { + t.Fatal("server did not negotiate a resumable session") + } + return cr +} + +// postResume performs the raw handshake. +func postResume(t *testing.T, ts *httptest.Server, id string, req ResumeRequest) (*http.Response, ResumeResponse) { + t.Helper() + body, _ := json.Marshal(req) + resp, err := ts.Client().Post(ts.URL+"/tunnel/"+id+"/resume", "application/json", bytes.NewReader(body)) + if err != nil { + t.Fatalf("resume request: %v", err) + } + var rr ResumeResponse + json.NewDecoder(resp.Body).Decode(&rr) + resp.Body.Close() + return resp, rr +} + +// openStreamPoll opens a raw receive-only stream poll and returns the frame +// reader over its body plus a cancel that drops the connection mid-stream — +// the client-side half of a seam failure. +func openStreamPoll(t *testing.T, ts *httptest.Server, id string) (*frameReader, context.CancelFunc) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, ts.URL+"/tunnel/"+id+"/poll", nil) + req.Header.Set(HeaderReceiveOnly, "true") + resp, err := ts.Client().Do(req) + if err != nil { + cancel() + t.Fatalf("stream poll: %v", err) + } + if resp.StatusCode != http.StatusOK { + cancel() + t.Fatalf("stream poll status = %d, want 200", resp.StatusCode) + } + t.Cleanup(func() { cancel(); resp.Body.Close() }) + return newFrameReader(resp.Body, 1<<20), cancel +} + +// nextSeqData reads frames until a seq-data frame arrives, skipping +// heartbeats and acks (which it returns through acks). +func nextSeqData(t *testing.T, fr *frameReader) (off uint64, data []byte, acks []uint64) { + t.Helper() + for { + typ, payload, err := fr.next() + if err != nil { + t.Fatalf("reading frame: %v", err) + } + switch typ { + case frameSeqData: + off, data, err = splitSeq(payload) + if err != nil { + t.Fatal(err) + } + return off, data, acks + case frameAck: + n, err := decodeAck(payload) + if err != nil { + t.Fatal(err) + } + acks = append(acks, n) + case frameHeartbeat: + case frameData: + t.Fatal("server sent an unnumbered data frame on a resumable session") + default: + t.Fatalf("unexpected frame %#x", typ) + } + } +} + +// rawSendStream posts one send-stream request carrying the given +// pre-encoded frames followed by frameEnd, returning the response. +func rawSendStream(t *testing.T, ts *httptest.Server, id string, frames ...[]byte) *http.Response { + t.Helper() + var body bytes.Buffer + for _, f := range frames { + body.Write(f) + } + writeFrame(&body, frameEnd, nil) + req, _ := http.NewRequest(http.MethodPost, ts.URL+"/tunnel/"+id+"/poll", &body) + req.Header.Set(HeaderSendStream, "true") + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatalf("send-stream: %v", err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + return resp +} + +func seqFrame(off uint64, data string) []byte { + var b bytes.Buffer + writeSeqFrame(&b, off, []byte(data)) + return b.Bytes() +} + +func ackFrame(n uint64) []byte { + var b bytes.Buffer + writeFrame(&b, frameAck, encodeOffset(n)) + return b.Bytes() +} + +// --------------------------------------------------------------------------- +// negotiation +// --------------------------------------------------------------------------- + +func TestConnectNegotiatesResumeOnlyForResumableTransports(t *testing.T) { + cases := []struct { + name string + cfg func(*ServerConfig) + req ConnectRequest + want bool + }{ + {"two-way stream", nil, ConnectRequest{PreferStreamMode: true, PreferStreamUpload: true, PreferResume: true}, true}, + {"websocket", nil, ConnectRequest{PreferWebSocket: true, PreferResume: true}, true}, + {"websocket without stream prefs", nil, ConnectRequest{PreferWebSocket: true, PreferResume: true}, true}, + {"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}, + {"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}, + {"websocket off falls back to stream and stays resumable", func(c *ServerConfig) { c.EnableWebSocket = false }, + ConnectRequest{PreferWebSocket: true, PreferStreamMode: true, PreferStreamUpload: true, PreferResume: true}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := testResumeServerConfig() + if tc.cfg != nil { + tc.cfg(&cfg) + } + ts, st := newResumeTestServer(t, cfg, Hooks{}) + tc.req.ProtocolVersion = ProtocolVersion + resp, cr := postConnect(t, ts, tc.req) + if resp.StatusCode != http.StatusOK { + t.Fatalf("connect status = %d", resp.StatusCode) + } + if cr.Resumable != tc.want { + t.Fatalf("Resumable = %v, want %v (transport=%q poll_mode=%q upload=%q)", + cr.Resumable, tc.want, cr.Transport, cr.PollMode, cr.UploadStreamMode) + } + if tc.want && cr.Limits.ResumeGrace() != cfg.ResumeGrace { + t.Fatalf("resume_grace_ms = %v, want %v", cr.Limits.ResumeGrace(), cfg.ResumeGrace) + } + if !tc.want && cr.Limits.ResumeGraceMS != 0 { + t.Fatalf("resume_grace_ms = %d on a non-resumable connect, want 0", cr.Limits.ResumeGraceMS) + } + s, _ := st.Get(cr.SessionID) + if s.Resumable() != tc.want { + t.Fatalf("Session.Resumable() = %v, want %v", s.Resumable(), tc.want) + } + }) + } +} + +func TestServerConfigRejectsExcessiveResumeGrace(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatal("check() accepted ResumeGrace above MaxResumeGrace") + } + }() + cfg := testResumeServerConfig() + cfg.ResumeGrace = MaxResumeGrace + time.Second + cfg.check() +} + +// --------------------------------------------------------------------------- +// ResumeHandler, driven directly +// --------------------------------------------------------------------------- + +func TestResumeHandlerStatuses(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + + if resp, _ := postResume(t, ts, "nope", ResumeRequest{ProtocolVersion: ProtocolVersion}); resp.StatusCode != http.StatusNotFound { + t.Fatalf("unknown session = %d, want 404", resp.StatusCode) + } + + plain := connectOK(t, ts) // batch: never resumable + if resp, _ := postResume(t, ts, plain.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}); resp.StatusCode != http.StatusConflict { + t.Fatalf("non-resumable session = %d, want 409", resp.StatusCode) + } + + cr := connectResumableStream(t, ts) + if resp, _ := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: 99}); resp.StatusCode != http.StatusUpgradeRequired { + t.Fatalf("bad version = %d, want 426", resp.StatusCode) + } + + // Nothing sent yet: only offset 0 is honourable. + resp, rr := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion, RecvOffset: 0}) + if resp.StatusCode != http.StatusOK || !rr.Resumed || rr.RecvOffset != 0 { + t.Fatalf("fresh resume = (%d, %+v), want 200 resumed at 0", resp.StatusCode, rr) + } + s, _ := st.Get(cr.SessionID) + resp, _ = postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion, RecvOffset: 5}) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("out-of-range offset = %d, want 409", resp.StatusCode) + } + if s.Resumable() { + t.Fatal("an impossible offset must end the session's resumability, never be guessed at") + } + if resp, _ := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}); resp.StatusCode != http.StatusConflict { + t.Fatalf("resume on a broken session = %d, want 409", resp.StatusCode) + } + + closed := connectResumableStream(t, ts) + cs, _ := st.Get(closed.SessionID) + cs.Close() // closed but still in the store: the 410 path + if resp, _ := postResume(t, ts, closed.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}); resp.StatusCode != http.StatusGone { + t.Fatalf("closed session = %d, want 410", resp.StatusCode) + } +} + +// ★ The seam. Downstream bytes that were drained from the pipe and written +// to a poll response the client never finished reading are the whole reason +// the reliable layer exists: after the resume they come back, from exactly +// the offset the client declared, and nothing else is lost or repeated. +func TestResumeReplaysDownstreamFromClientOffset(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableStream(t, ts) + s, _ := st.Get(cr.SessionID) + + fr, dropPoll := openStreamPoll(t, ts, cr.SessionID) + s.Write([]byte("hello world")) + off, data, _ := nextSeqData(t, fr) + if off != 0 || string(data) != "hello world" { + t.Fatalf("first frame = (%d, %q)", off, data) + } + // The client "received" only the first 5 bytes before the link died and + // never acknowledged anything. Meanwhile the server writes more, which + // goes into the replay buffer with no transport to send it on. + dropPoll() + waitFor(t, 2*time.Second, func() bool { return s.PollInFlight() == 0 }) + s.Write([]byte("!")) + + resp, rr := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion, RecvOffset: 5}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("resume = %d", resp.StatusCode) + } + if rr.RecvOffset != 0 { + t.Fatalf("server recv_offset = %d, want 0 (nothing was uploaded)", rr.RecvOffset) + } + + fr2, _ := openStreamPoll(t, ts, cr.SessionID) + off, data, _ = nextSeqData(t, fr2) + if off != 5 || string(data) != " world" { + t.Fatalf("replayed frame = (%d, %q), want (5, %q)", off, data, " world") + } + off, data, _ = nextSeqData(t, fr2) + if off != 11 || string(data) != "!" { + t.Fatalf("frame after replay = (%d, %q), want (11, %q)", off, data, "!") + } + if s.rs.unacked() != 7 { + t.Fatalf("unacked = %d, want 7 (offsets 5..12 retained until acked)", s.rs.unacked()) + } + + // An ack from the client releases the retained bytes. + if resp := rawSendStream(t, ts, cr.SessionID, ackFrame(12)); resp.StatusCode != http.StatusOK { + t.Fatalf("send-stream carrying ack = %d", resp.StatusCode) + } + waitFor(t, time.Second, func() bool { return s.rs.unacked() == 0 }) +} + +func TestResumeReportsUpstreamOffsetAndDedupsReplayedUploads(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableStream(t, ts) + s, _ := st.Get(cr.SessionID) + + if resp := rawSendStream(t, ts, cr.SessionID, seqFrame(0, "abc")); resp.StatusCode != http.StatusOK { + t.Fatalf("send-stream = %d", resp.StatusCode) + } + // The client's replay after a failed leg overlaps what already arrived. + if resp := rawSendStream(t, ts, cr.SessionID, seqFrame(1, "bcde")); resp.StatusCode != http.StatusOK { + t.Fatalf("overlapping send-stream = %d", resp.StatusCode) + } + got := make([]byte, 16) + total := 0 + for total < 5 { + n, err := s.Read(got[total:]) + if err != nil { + t.Fatal(err) + } + total += n + } + if string(got[:total]) != "abcde" { + t.Fatalf("session read %q, want %q", got[:total], "abcde") + } + + resp, rr := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusOK || rr.RecvOffset != 5 { + t.Fatalf("resume = (%d, recv_offset %d), want 200 with 5", resp.StatusCode, rr.RecvOffset) + } + + // A hole is fatal: refused, and the session stops being resumable. + if resp := rawSendStream(t, ts, cr.SessionID, seqFrame(9, "x")); resp.StatusCode != http.StatusBadRequest { + t.Fatalf("gap = %d, want 400", resp.StatusCode) + } + if s.Resumable() { + t.Fatal("a gap must end resumability") + } + // Unnumbered data is refused too on a resumable session. + fresh := connectResumableStream(t, ts) + var plain bytes.Buffer + writeFrame(&plain, frameData, []byte("raw")) + if resp := rawSendStream(t, ts, fresh.SessionID, plain.Bytes()); resp.StatusCode != http.StatusBadRequest { + t.Fatalf("plain data on resumable session = %d, want 400", resp.StatusCode) + } + // And a discrete send-only or batch poll is refused outright. + fresh2 := connectResumableStream(t, ts) + if resp := poll(t, ts, fresh2.SessionID, []byte("x"), map[string]string{HeaderSendOnly: "true"}); resp.StatusCode != http.StatusBadRequest { + t.Fatalf("send-only on resumable session = %d, want 400", resp.StatusCode) + } +} + +// A resume must not trust its offsets while a stale handler may still be +// draining the pipe. The handshake kicks the parked poll and waits for it to +// leave; the client that opened it sees its body end. +func TestResumeKicksParkedStreamPoll(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableStream(t, ts) + s, _ := st.Get(cr.SessionID) + + fr, _ := openStreamPoll(t, ts, cr.SessionID) + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 }) + + start := time.Now() + resp, _ := postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("resume = %d", resp.StatusCode) + } + if time.Since(start) > detachWait { + t.Fatal("resume waited out detachWait instead of kicking the parked poll") + } + // The kicked poll's body ends (without a frameGone: the session lives). + for { + typ, _, err := fr.next() + if err != nil { + break + } + if typ == frameGone { + t.Fatal("kicked poll got frameGone; the session must survive a resume") + } + } + if s.IsClosed() { + t.Fatal("session closed by resume") + } + + // The next attach works normally and starts with an ack. + fr2, _ := openStreamPoll(t, ts, cr.SessionID) + s.Write([]byte("after")) + off, data, _ := nextSeqData(t, fr2) + if off != 0 || string(data) != "after" { + t.Fatalf("post-resume frame = (%d, %q)", off, data) + } +} + +// Two stream polls on the same direction: the newer one displaces the +// older, exactly what happens when a client reopens after a rollover the +// server has not finished noticing. +func TestNewerStreamPollDisplacesOlderOnResumableSession(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + cr := connectResumableStream(t, ts) + s, _ := st.Get(cr.SessionID) + + old, _ := openStreamPoll(t, ts, cr.SessionID) + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 }) + fresh, _ := openStreamPoll(t, ts, cr.SessionID) + + // The old one ends; the new one is served. + for { + if _, _, err := old.next(); err != nil { + break + } + } + s.Write([]byte("to the newcomer")) + off, data, _ := nextSeqData(t, fresh) + if off != 0 || string(data) != "to the newcomer" { + t.Fatalf("newcomer frame = (%d, %q)", off, data) + } +} + +// --------------------------------------------------------------------------- +// lifecycle: grace, sweeper, conditional close, DELETE race +// --------------------------------------------------------------------------- + +func TestDetachedResumableSessionOutlivesSessionTimeoutUntilGrace(t *testing.T) { + cfg := testResumeServerConfig() + cfg.SessionTimeout = 400 * time.Millisecond + cfg.ResumeGrace = 900 * time.Millisecond + var mu sync.Mutex + var reasons []DisconnectReason + h := Hooks{OnDisconnect: func(_ *Session, r DisconnectReason) { mu.Lock(); reasons = append(reasons, r); mu.Unlock() }} + ts, st := newResumeTestServer(t, cfg, h) + stop := StartSweeper(st, cfg, h) + defer stop() + + cr := connectResumableStream(t, ts) // never attaches: detached from birth + s, _ := st.Get(cr.SessionID) + + time.Sleep(600 * time.Millisecond) // past SessionTimeout, inside grace + if _, ok := st.Get(cr.SessionID); !ok { + t.Fatal("detached resumable session was swept before its grace ran out") + } + if dl, ok := s.ResumeDeadline(); !ok || time.Until(dl) <= 0 || time.Until(dl) > cfg.ResumeGrace { + t.Fatalf("ResumeDeadline = (%v, %v)", dl, ok) + } + if CloseSessionIfNoPollInFlight(st, h, s, ReasonServerClose) { + t.Fatal("conditional close killed a resumable session inside its grace") + } + + waitFor(t, 2*time.Second, func() bool { _, ok := st.Get(cr.SessionID); return !ok }) + mu.Lock() + defer mu.Unlock() + if len(reasons) != 1 || reasons[0] != ReasonEvicted { + t.Fatalf("disconnects = %v, want exactly one eviction", reasons) + } + if _, ok := s.ResumeDeadline(); ok { + t.Fatal("ResumeDeadline reported on a closed session") + } +} + +func TestConditionalCloseSucceedsOnceGraceHasPassed(t *testing.T) { + st := NewSessionStore() + s := newSession("r", nil) + s.enableResume(1<<20, 50*time.Millisecond) + st.add(s) + + if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("closed inside grace") + } + s.mu.Lock() + s.detachedAt = time.Now().Add(-time.Second) + s.mu.Unlock() + if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("did not close after grace") + } + + // A broken (no longer resumable) session is judged like any other. + b := newSession("b", nil) + b.enableResume(1<<20, time.Hour) + st.add(b) + b.rs.markBroken() + if !CloseSessionIfNoPollInFlight(st, Hooks{}, b, ReasonServerClose) { + t.Fatal("conditional close spared a session that is no longer resumable") + } +} + +func TestSweeperEvictsLongestDetachedBeyondCap(t *testing.T) { + st := NewSessionStore() + st.maxDetachedResumable = 2 + var ids []string + for i, age := range []time.Duration{3 * time.Second, time.Second, 2 * time.Second} { + s := newSession(string(rune('a'+i)), nil) + s.enableResume(1<<20, time.Hour) + s.mu.Lock() + s.detachedAt = time.Now().Add(-age) + s.mu.Unlock() + st.add(s) + ids = append(ids, s.ID) + } + var evicted []string + st.sweep(time.Hour, func(s *Session) { evicted = append(evicted, s.ID) }) + if len(evicted) != 1 || evicted[0] != "a" { + t.Fatalf("evicted %v, want just the longest-detached %q", evicted, "a") + } + if st.Len() != 2 { + t.Fatalf("store has %d sessions, want 2", st.Len()) + } + _ = ids +} + +func TestResumeAfterDeleteFailsAndHookFiresOnce(t *testing.T) { + var calls atomic.Int32 + h := Hooks{OnDisconnect: func(*Session, DisconnectReason) { calls.Add(1) }} + ts, _ := newResumeTestServer(t, testResumeServerConfig(), h) + cr := connectResumableStream(t, ts) + + req, _ := http.NewRequest(http.MethodDelete, ts.URL+"/tunnel/"+cr.SessionID, nil) + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + + resp, _ = postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusNotFound && resp.StatusCode != http.StatusGone { + t.Fatalf("resume after delete = %d, want 404 or 410", resp.StatusCode) + } + if calls.Load() != 1 { + t.Fatalf("OnDisconnect fired %d times, want 1", calls.Load()) + } +} + +// --------------------------------------------------------------------------- +// end to end, through a proxy that breaks +// --------------------------------------------------------------------------- + +// faultProxy is a TCP relay in front of the server that can kill every +// connection through it at once (the client sees exactly what a CDN's +// max-connection-age cutoff looks like), refuse new ones, or swallow +// upstream bytes while keeping the connection up. +type faultProxy struct { + ln net.Listener + backend string + + mu sync.Mutex + conns map[net.Conn]struct{} + + refuse atomic.Bool // accept and close at once + dropUp atomic.Bool // discard client→backend bytes +} + +func newFaultProxy(t *testing.T, backendURL string) *faultProxy { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &faultProxy{ln: ln, backend: strings.TrimPrefix(backendURL, "http://"), conns: make(map[net.Conn]struct{})} + go p.serve() + t.Cleanup(func() { ln.Close(); p.killAll() }) + return p +} + +func (p *faultProxy) URL() string { return "http://" + p.ln.Addr().String() } + +func (p *faultProxy) serve() { + for { + c, err := p.ln.Accept() + if err != nil { + return + } + if p.refuse.Load() { + c.Close() + continue + } + go p.handle(c) + } +} + +func (p *faultProxy) handle(client net.Conn) { + backend, err := net.Dial("tcp", p.backend) + if err != nil { + client.Close() + return + } + p.mu.Lock() + p.conns[client] = struct{}{} + p.conns[backend] = struct{}{} + p.mu.Unlock() + defer func() { + p.mu.Lock() + delete(p.conns, client) + delete(p.conns, backend) + p.mu.Unlock() + client.Close() + backend.Close() + }() + + done := make(chan struct{}, 2) + go func() { + buf := make([]byte, 32<<10) + for { + n, err := client.Read(buf) + if n > 0 && !p.dropUp.Load() { + if _, werr := backend.Write(buf[:n]); werr != nil { + break + } + } + if err != nil { + break + } + } + done <- struct{}{} + }() + go func() { io.Copy(client, backend); done <- struct{}{} }() + <-done +} + +// connCount is how many relayed connections (both halves) are live. +func (p *faultProxy) connCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.conns) +} + +// killAll drops every connection currently relayed, both halves. +func (p *faultProxy) killAll() { + p.mu.Lock() + conns := make([]net.Conn, 0, len(p.conns)) + for c := range p.conns { + conns = append(conns, c) + } + p.mu.Unlock() + for _, c := range conns { + c.Close() + } +} + +// resumeE2E is the whole stack with resume on and a faultProxy between the +// Connector and the server. +type resumeE2E struct { + ts *httptest.Server + proxy *faultProxy + store *SessionStore + cfg ServerConfig + hooks Hooks + mode string + + mu sync.Mutex + disconnects []DisconnectReason + + resumes atomic.Int32 // POST .../resume requests seen by the server +} + +func newResumeE2E(t *testing.T, mode string, tweak func(*ServerConfig), middleware func(http.Handler) http.Handler) *resumeE2E { + t.Helper() + e := &resumeE2E{ + store: NewSessionStore(), + mode: mode, + cfg: ServerConfig{ + PollTimeout: 500 * time.Millisecond, + SessionTimeout: time.Second, + SweepInterval: 50 * time.Millisecond, + CoalesceWindow: 2 * time.Millisecond, + PollBufferSize: 64 << 10, + MaxSendBytes: 256 << 10, + PollMode: PollModeStream, + HeartbeatInterval: 200 * time.Millisecond, + StreamMaxDuration: 2 * time.Second, + EnableWebSocket: mode == TransportWebSocket, + EnableResume: true, + ResumeGrace: 3 * time.Second, + }, + } + if tweak != nil { + tweak(&e.cfg) + } + e.hooks = Hooks{ + OnConnect: func(s *Session, _ map[string]string) error { + go func() { + sess, err := ServerSession(s) + if err != nil { + return + } + defer sess.Close() + for { + stream, err := sess.Accept() + if err != nil { + return + } + go func() { + defer stream.Close() + io.Copy(stream, stream) + }() + } + }() + return nil + }, + OnDisconnect: func(_ *Session, reason DisconnectReason) { + e.mu.Lock() + e.disconnects = append(e.disconnects, reason) + e.mu.Unlock() + }, + } + mux := http.NewServeMux() + mux.Handle("POST /tunnel/connect", ConnectHandler(e.store, e.cfg, e.hooks)) + mux.Handle("POST /tunnel/{id}/poll", PollHandler(e.store, e.cfg, e.hooks)) + mux.Handle("POST /tunnel/{id}/resume", ResumeHandler(e.store, e.cfg, e.hooks)) + mux.Handle("DELETE /tunnel/{id}", DeleteHandler(e.store, e.cfg, e.hooks)) + mux.Handle("GET /tunnel/{id}/ws", WebSocketHandler(e.store, e.cfg, e.hooks)) + var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/resume") { + e.resumes.Add(1) + } + mux.ServeHTTP(w, r) + }) + if middleware != nil { + h = middleware(h) + } + e.ts = httptest.NewServer(h) + t.Cleanup(e.ts.Close) + stop := StartSweeper(e.store, e.cfg, e.hooks) + t.Cleanup(stop) + e.proxy = newFaultProxy(t, e.ts.URL) + return e +} + +func (e *resumeE2E) connector(tweak func(*Connector)) *Connector { + c := &Connector{ + BaseURL: e.proxy.URL(), + PollGrace: 300 * time.Millisecond, + SendTimeout: time.Second, + DialTimeout: time.Second, + PreferStream: true, + UploadStreamPreference: PollModeStream, + PreferWebSocket: e.mode == TransportWebSocket, + PreferResume: true, + } + if tweak != nil { + tweak(c) + } + return c +} + +func (e *resumeE2E) dial(t *testing.T, tweak func(*Connector)) (Conn, *yamux.Session) { + t.Helper() + conn, err := e.connector(tweak).Connect(context.Background()) + if err != nil { + t.Fatalf("Connect: %v", err) + } + sess, err := ClientSession(conn) + if err != nil { + conn.Close() + t.Fatalf("ClientSession: %v", err) + } + t.Cleanup(func() { + sess.Close() + conn.Close() + }) + return conn, sess +} + +func (e *resumeE2E) reasons() []DisconnectReason { + e.mu.Lock() + defer e.mu.Unlock() + return append([]DisconnectReason(nil), e.disconnects...) +} + +func isClosed(ch <-chan struct{}) bool { + select { + case <-ch: + return true + default: + return false + } +} + +// ★ Acceptance: the transport is killed repeatedly in the middle of a bulk +// transfer, and the yamux session, the stream, and every byte survive. +func TestE2EResumeSurvivesTransportKills_Stream(t *testing.T) { + testE2EResumeSurvivesTransportKills(t, PollModeStream) +} +func TestE2EResumeSurvivesTransportKills_WebSocket(t *testing.T) { + testE2EResumeSurvivesTransportKills(t, TransportWebSocket) +} + +func testE2EResumeSurvivesTransportKills(t *testing.T, mode string) { + e := newResumeE2E(t, mode, nil, nil) + conn, sess := e.dial(t, nil) + if _, ok := conn.(*resumableConn); !ok { + t.Fatalf("Connect returned %T, want *resumableConn", conn) + } + sessionID := conn.SessionID() + + stream, err := sess.Open() + if err != nil { + t.Fatalf("Open: %v", err) + } + defer stream.Close() + + const chunk = 32 << 10 + payload := make([]byte, 96*chunk) // 3MB + rand.Read(payload) + want := sha256.Sum256(payload) + + readDone := make(chan []byte, 1) + go func() { + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil { + readDone <- nil + return + } + readDone <- got + }() + + // Kill the link every dozen chunks — while data is in flight in both + // directions — for a handful of seams per transfer. + kills := 0 + for i := 0; i < len(payload); i += chunk { + if _, err := stream.Write(payload[i : i+chunk]); err != nil { + t.Fatalf("Write at %d: %v", i, err) + } + if i > 0 && (i/chunk)%12 == 0 { + e.proxy.killAll() + kills++ + } + } + + select { + case got := <-readDone: + if got == nil { + t.Fatal("the echo came back short") + } + if sha256.Sum256(got) != want { + t.Fatal("echoed bytes differ from what was sent") + } + case <-time.After(60 * time.Second): + t.Fatalf("echo did not complete across %d transport kills", kills) + } + + if kills < 3 { + t.Fatalf("only %d kills were injected", kills) + } + if e.resumes.Load() == 0 { + t.Fatal("no resume handshake happened: the kills did not exercise the seam") + } + if isClosed(conn.TransportFailed()) { + t.Fatal("TransportFailed fired: the session was not kept") + } + if sess.IsClosed() { + t.Fatal("yamux session closed across the kills") + } + if conn.SessionID() != sessionID || e.store.Len() != 1 { + t.Fatalf("session identity changed: id %q→%q, store has %d", sessionID, conn.SessionID(), e.store.Len()) + } + if r := e.reasons(); len(r) != 0 { + t.Fatalf("server saw disconnects %v; a resumed session must never disconnect", r) + } + + // And the session is fully healthy afterwards: a fresh stream works. + second, err := sess.Open() + if err != nil { + t.Fatalf("Open after kills: %v", err) + } + defer second.Close() + second.Write([]byte("still here")) + buf := make([]byte, 10) + if _, err := io.ReadFull(second, buf); err != nil || string(buf) != "still here" { + t.Fatalf("post-kill stream echo = (%q, %v)", buf, err) + } +} + +// The transport is killed while the session is idle — no data in flight — +// and the next write still goes through, on the same session. +func TestE2EResumeIdleKillIsInvisible_Stream(t *testing.T) { + testE2EResumeIdleKillIsInvisible(t, PollModeStream) +} +func TestE2EResumeIdleKillIsInvisible_WebSocket(t *testing.T) { + testE2EResumeIdleKillIsInvisible(t, TransportWebSocket) +} + +func testE2EResumeIdleKillIsInvisible(t *testing.T, mode string) { + e := newResumeE2E(t, mode, nil, nil) + conn, sess := e.dial(t, nil) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.Write([]byte("before")) + buf := make([]byte, 6) + if _, err := io.ReadFull(stream, buf); err != nil { + t.Fatal(err) + } + + e.proxy.killAll() + time.Sleep(300 * time.Millisecond) + e.proxy.killAll() // and once more while it may be mid-resume + + stream.Write([]byte("after!")) + stream.SetReadDeadline(time.Now().Add(15 * time.Second)) + if _, err := io.ReadFull(stream, buf); err != nil || string(buf) != "after!" { + t.Fatalf("post-kill echo = (%q, %v)", buf, err) + } + if isClosed(conn.TransportFailed()) || len(e.reasons()) != 0 { + t.Fatal("session did not survive an idle kill") + } + if e.resumes.Load() == 0 { + t.Fatal("no resume handshake happened") + } +} + +// Grace runs out: the server evicts, the client gives up, and the caller +// gets exactly today's signal — TransportFailed — to build a new session. +func TestE2EResumeGraceExpiryFallsBackToTransportFailed(t *testing.T) { + e := newResumeE2E(t, PollModeStream, func(c *ServerConfig) { c.ResumeGrace = 600 * 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(10 * time.Second): + t.Fatal("TransportFailed never fired after the grace ran out") + } + waitFor(t, 5*time.Second, func() bool { return e.store.Len() == 0 }) + if r := e.reasons(); len(r) != 1 || r[0] != ReasonEvicted { + t.Fatalf("disconnects = %v, want one eviction", r) + } + // yamux notices the read pipe closing and ends the session. + select { + case <-sess.CloseChan(): + case <-time.After(5 * time.Second): + t.Fatal("yamux session did not end after the connection gave up") + } +} + +// The server closed the session (DELETE from elsewhere, an eviction, a +// shutdown): not a transport failure, and not something to resume. +func TestE2EResumeDoesNotResurrectAServerClosedSession(t *testing.T) { + e := newResumeE2E(t, PollModeStream, 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(10 * time.Second): + t.Fatal("TransportFailed never fired for a server-closed session") + } + if e.store.Len() != 0 { + t.Fatal("a resume recreated the session") + } +} + +// Server has resume off: the client asked, got a plain session, and behaves +// exactly as today (a kill ends the session). +func TestE2EResumeDegradesWhenServerHasItOff(t *testing.T) { + e := newResumeE2E(t, PollModeStream, func(c *ServerConfig) { c.EnableResume = false }, nil) + conn, sess := e.dial(t, nil) + if _, ok := conn.(*resumableConn); ok { + t.Fatal("got a resumable conn from a server with resume off") + } + if conn.Limits().ResumeGraceMS != 0 { + t.Fatal("resume_grace_ms handed down without resume") + } + // A round trip first, so both legs' connections exist to be killed. + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + stream.Write([]byte("ping")) + buf := make([]byte, 4) + if _, err := io.ReadFull(stream, buf); err != nil { + t.Fatal(err) + } + e.proxy.killAll() + select { + case <-conn.TransportFailed(): + case <-time.After(10 * time.Second): + t.Fatal("non-resumable conn did not report the kill") + } + if e.resumes.Load() != 0 { + t.Fatal("a non-resumable conn attempted a resume") + } +} + +// Client did not ask: nothing changes for it either. +func TestE2EResumeStaysOffWhenClientDoesNotAsk(t *testing.T) { + e := newResumeE2E(t, PollModeStream, nil, nil) + conn, _ := e.dial(t, func(c *Connector) { c.PreferResume = false }) + if _, ok := conn.(*resumableConn); ok { + t.Fatal("got a resumable conn without asking") + } + s, _ := e.store.Get(conn.SessionID()) + if s.Resumable() { + t.Fatal("server made the session resumable without being asked") + } +} + +// 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. +func TestE2EResumeFallsBackWhenUploadProbeFails(t *testing.T) { + stall := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(HeaderSendStreamProbe) == "true" { + // A proxy that never forwards the body. Bounded rather than + // waiting on r.Context(): net/http does not notice a dropped + // connection while a request body sits unread, and + // httptest.Server.Close would wait on this handler forever. + select { + case <-r.Context().Done(): + case <-time.After(2 * time.Second): + } + return + } + next.ServeHTTP(w, r) + }) + } + e := newResumeE2E(t, PollModeStream, nil, stall) + conn, _ := 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) + } + 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") + } +} + +// A replay buffer that outgrows MaxReplayBytes ends resumability cleanly: +// the connection keeps working until its transport actually fails, then +// falls back to TransportFailed instead of resuming with bytes it dropped. +func TestE2EResumeReplayOverflowGivesUpCleanly(t *testing.T) { + e := newResumeE2E(t, PollModeStream, nil, nil) + conn, sess := e.dial(t, func(c *Connector) { c.MaxReplayBytes = 32 << 10 }) + rc := conn.(*resumableConn) + stream, err := sess.Open() + if err != nil { + t.Fatal(err) + } + defer stream.Close() + // A round trip first, so both legs' connections exist before anything + // is done to them. + stream.Write([]byte("ping")) + buf := make([]byte, 4) + if _, err := io.ReadFull(stream, buf); err != nil { + t.Fatal(err) + } + waitFor(t, 2*time.Second, func() bool { return e.proxy.connCount() >= 4 }) + + // Upstream bytes vanish in the proxy: sent, never acknowledged. The + // first 64KB chunk alone overflows a 32KB replay buffer. + e.proxy.dropUp.Store(true) + if _, err := stream.Write(make([]byte, 128<<10)); err != nil { + t.Fatal(err) + } + waitFor(t, 5*time.Second, func() bool { return rc.rl.isBroken() }) + if isClosed(conn.TransportFailed()) { + t.Fatal("overflow alone must not fail the transport while it is still up") + } + + e.proxy.dropUp.Store(false) + e.proxy.killAll() + select { + case <-conn.TransportFailed(): + case <-time.After(10 * time.Second): + t.Fatal("a broken reliable layer must fall back to TransportFailed on the next kill") + } +} + +// Raw WebSocket on a resumable session: the same framing rules as stream. +func TestWebSocketResumableSessionUsesSeqFramesAndAcks(t *testing.T) { + ts, st := newResumeTestServer(t, testResumeServerConfig(), Hooks{}) + resp, cr := postConnect(t, ts, ConnectRequest{ProtocolVersion: ProtocolVersion, PreferWebSocket: true, PreferResume: true}) + if resp.StatusCode != http.StatusOK || !cr.Resumable || cr.Transport != TransportWebSocket { + t.Fatalf("connect = %d resumable=%v transport=%q", resp.StatusCode, cr.Resumable, cr.Transport) + } + s, _ := st.Get(cr.SessionID) + + ws := dialWS(t, ts, cr.SessionID) + ctx := context.Background() + if err := ws.Write(ctx, websocket.MessageBinary, wsEncodeSeq(0, []byte("up"))); err != nil { + t.Fatal(err) + } + got := make([]byte, 8) + n, _ := s.Read(got) + if string(got[:n]) != "up" { + t.Fatalf("session read %q", got[:n]) + } + + s.Write([]byte("down")) + for { + _, msg, err := ws.Read(ctx) + if err != nil { + t.Fatal(err) + } + ft, payload, _ := wsDecode(msg) + if ft == frameSeqData { + off, data, _ := splitSeq(payload) + if off != 0 || string(data) != "down" { + t.Fatalf("ws seq frame = (%d, %q)", off, data) + } + break + } + if ft == frameData { + t.Fatal("server sent an unnumbered data frame on a resumable websocket") + } + } + if s.rs.unacked() != 4 { + t.Fatalf("unacked = %d, want 4", s.rs.unacked()) + } + if err := ws.Write(ctx, websocket.MessageBinary, wsEncode(frameAck, encodeOffset(4))); err != nil { + t.Fatal(err) + } + waitFor(t, time.Second, func() bool { return s.rs.unacked() == 0 }) + + // A second WebSocket displaces the first rather than getting 409. + ws2 := dialWS(t, ts, cr.SessionID) + if _, _, err := ws.Read(ctx); err == nil { + t.Fatal("displaced websocket still readable") + } + s.Write([]byte("to ws2")) + for { + _, msg, err := ws2.Read(ctx) + if err != nil { + t.Fatal(err) + } + if ft, payload, _ := wsDecode(msg); ft == frameSeqData { + off, data, _ := splitSeq(payload) + if off != 4 || string(data) != "to ws2" { + t.Fatalf("ws2 frame = (%d, %q)", off, data) + } + break + } + } +} + +// --------------------------------------------------------------------------- +// the two-hop relay, the deployment this feature exists for +// --------------------------------------------------------------------------- + +// ★ consumer → broker → provider, both hops behind a proxy that keeps +// killing connections, a tunnelled stream carrying a bulk transfer the whole +// time. With both hops resumable the stream never notices: no reconnect, no +// new session id on either side, every byte intact. This is the SSH-through- +// two-CDN-legs scenario from the design document. +func TestRelayStreamSurvivesKillsOnBothHopsWithResume(t *testing.T) { + const token = "broker-token" + b := newMiniBrokerOpts(t, token, false, PollModeStream, true) + providerProxy := newFaultProxy(t, b.ts.URL) + consumerProxy := newFaultProxy(t, b.ts.URL) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + p := runMiniProviderOpts(t, ctx, providerProxy.URL(), token, "home", false, true, true) + c := runMiniConsumerOpts(t, ctx, consumerProxy.URL(), token, "home", false, true, true) + c.waitReady(t) + consumerSession := <-c.sessions + providerSession := <-p.sessions + waitFor(t, 10*time.Second, func() bool { _, ok := b.providerYamux("home"); return ok }) + + target := echoTarget(t) + stream := c.dial(t, target) + defer stream.Close() + + const chunk = 16 << 10 + payload := make([]byte, 128*chunk) // 2MB + rand.Read(payload) + want := sha256.Sum256(payload) + + readDone := make(chan []byte, 1) + go func() { + got := make([]byte, len(payload)) + if _, err := io.ReadFull(stream, got); err != nil { + readDone <- nil + return + } + readDone <- got + }() + + for i := 0; i < len(payload); i += chunk { + if _, err := stream.Write(payload[i : i+chunk]); err != nil { + t.Fatalf("Write at %d: %v", i, err) + } + switch (i / chunk) % 20 { + case 7: + consumerProxy.killAll() + case 14: + providerProxy.killAll() + } + } + + select { + case got := <-readDone: + if got == nil { + t.Fatal("the tunnelled echo came back short") + } + if sha256.Sum256(got) != want { + t.Fatal("tunnelled bytes differ from what was sent") + } + case <-time.After(60 * time.Second): + t.Fatal("tunnelled echo did not complete across the kills") + } + + // Neither role reconnected: no outcome fired, no new session id, and the + // broker still holds exactly the two original sessions. + select { + case out := <-c.outcomes: + t.Fatalf("consumer's Serve ended with %v; a resumed session must not end", out) + case out := <-p.outcomes: + t.Fatalf("provider's Serve ended with %v; a resumed session must not end", out) + default: + } + select { + case id := <-c.sessions: + t.Fatalf("consumer got a new session %q (was %q)", id, consumerSession) + case id := <-p.sessions: + t.Fatalf("provider got a new session %q (was %q)", id, providerSession) + default: + } + if b.store.Len() != 2 { + t.Fatalf("broker holds %d sessions, want 2", b.store.Len()) + } + for _, s := range b.store.All() { + if !s.Resumable() { + t.Fatalf("broker session %s lost resumability", s.ID) + } + } +} + +// Same relay, resume off: the same kills end the stream and both roles +// reconnect with fresh sessions — today's behaviour, unchanged. +func TestRelayStreamDiesOnKillWithoutResume(t *testing.T) { + const token = "broker-token" + b := newMiniBrokerOpts(t, token, false, PollModeStream, false) + consumerProxy := newFaultProxy(t, b.ts.URL) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + runMiniProviderOpts(t, ctx, b.ts.URL, token, "home", false, true, false) + c := runMiniConsumerOpts(t, ctx, consumerProxy.URL(), token, "home", false, true, false) + c.waitReady(t) + first := <-c.sessions + waitFor(t, 10*time.Second, func() bool { _, ok := b.providerYamux("home"); return ok }) + + stream := c.dial(t, echoTarget(t)) + defer stream.Close() + stream.Write([]byte("ping")) + buf := make([]byte, 4) + if _, err := io.ReadFull(stream, buf); err != nil { + t.Fatal(err) + } + + consumerProxy.killAll() + select { + case out := <-c.outcomes: + if out != OutcomeTransportFailed { + t.Fatalf("outcome = %v, want transport failure", out) + } + case <-time.After(15 * time.Second): + t.Fatal("consumer never noticed the kill") + } + if second := waitForNewSession(t, c.sessions, first); second == first { + t.Fatal("consumer reused the dead session id") + } +} diff --git a/session.go b/session.go index 9123985..5521763 100644 --- a/session.go +++ b/session.go @@ -66,21 +66,82 @@ type Session struct { // detection instead of a session_timeout wait (A3). pollInFlight int32 + // rs and att are only set for a session that negotiated + // ConnectResponse.Resumable, by ConnectHandler before the session is + // published, and never mutated after (same discipline as pollMode). rs + // is the byte layer that numbers, retains, and replays each direction + // (see reliable.go); att tracks which poll/WebSocket handler currently + // owns each direction so a replacement can kick a stale one off before + // taking over (see resume_server.go). resumeGrace is how long the + // session may sit with no transport attached before the sweeper gives + // up on it. + rs *reliable + att *attachments + resumeGrace time.Duration + mu sync.Mutex lastActive time.Time closed bool + // detachedAt is when pollInFlight last dropped to zero — the moment a + // resumable session's grace period starts. Only meaningful when rs is + // set; starts at creation so a session whose client never attaches at + // all is still bounded by the grace. + detachedAt time.Time } // newSession creates a session with initialized pipes. meta is copied, so later // mutation by the caller cannot affect the session. func newSession(id string, meta map[string]string) *Session { + now := time.Now() return &Session{ ID: id, toServer: NewBufferedPipe(), toClient: NewBufferedPipe(), meta: maps.Clone(meta), - lastActive: time.Now(), + lastActive: now, + detachedAt: now, + } +} + +// enableResume arms the reliable layer on a freshly created session. Called +// by ConnectHandler before the session is published, never after. +func (s *Session) enableResume(maxReplay int, grace time.Duration) { + s.rs = newReliable(s.toClient, s.toServer, maxReplay) + s.att = newAttachments() + s.resumeGrace = grace +} + +// Resumable reports whether this session negotiated resumable transport and +// can still be resumed. It turns false for good once a direction's replay +// buffer overflowed or the peer broke the protocol — from then on the +// session behaves exactly like a non-resumable one. +func (s *Session) Resumable() bool { + return s.rs != nil && !s.rs.isBroken() +} + +// ResumeDeadline returns when a detached resumable session's grace period +// runs out, and true, if the session is resumable and currently has no +// transport attached. Otherwise it returns the zero time and false. A +// reaper that closes sessions whose transport dropped (see +// CloseSessionIfNoPollInFlight) can use this to leave a session alone +// while its client may still come back. +func (s *Session) ResumeDeadline() (time.Time, bool) { + if !s.Resumable() { + return time.Time{}, false } + s.mu.Lock() + defer s.mu.Unlock() + if s.pollInFlight != 0 || s.closed { + return time.Time{}, false + } + return s.detachedAt.Add(s.resumeGrace), true +} + +// inResumeGraceLocked reports whether s is a detached resumable session +// still inside its grace period. s.mu must be held. +func (s *Session) inResumeGraceLocked(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. @@ -154,9 +215,18 @@ func (s *Session) beginPoll() bool { func (s *Session) endPoll() { s.mu.Lock() s.pollInFlight-- + s.noteDetachedLocked() s.mu.Unlock() } +// noteDetachedLocked stamps detachedAt when the last transport leaves a +// resumable session. s.mu must be held. +func (s *Session) noteDetachedLocked() { + if s.rs != nil && s.pollInFlight == 0 { + s.detachedAt = time.Now() + } +} + func (s *Session) beginWebSocket() bool { s.mu.Lock() defer s.mu.Unlock() @@ -172,6 +242,7 @@ func (s *Session) endWebSocket() { s.mu.Lock() s.wsAttached = false s.pollInFlight-- + s.noteDetachedLocked() s.mu.Unlock() } diff --git a/store.go b/store.go index a45b046..20c0ea9 100644 --- a/store.go +++ b/store.go @@ -1,6 +1,7 @@ package pollmux import ( + "sort" "sync" "time" ) @@ -11,6 +12,11 @@ import ( type SessionStore struct { mu sync.RWMutex sessions map[string]*Session + + // maxDetachedResumable caps how many resumable sessions may sit + // detached at once; the sweeper evicts the longest-detached beyond it. + // Zero means no cap. Set by StartSweeper from ServerConfig. + maxDetachedResumable int } // NewSessionStore creates an empty store. @@ -104,7 +110,13 @@ func (st *SessionStore) StartSweeper(interval, timeout time.Duration, onEvict fu } // removeAndMarkClosed removes s only if it is still the store's current object. -// Lock order throughout lifecycle operations is SessionStore.mu -> Session.mu. +// Lock order throughout lifecycle operations is SessionStore.mu -> Session.mu +// (-> reliable.mu, for the resumable checks). +// +// With requireIdle, a resumable session that is merely detached and still +// inside its grace period counts as busy: its client may be about to resume +// it, and closing it now would turn a recoverable blip into a dropped +// session. func (st *SessionStore) removeAndMarkClosed(s *Session, requireIdle bool) bool { st.mu.Lock() defer st.mu.Unlock() @@ -113,7 +125,7 @@ func (st *SessionStore) removeAndMarkClosed(s *Session, requireIdle bool) bool { } s.mu.Lock() defer s.mu.Unlock() - if s.closed || (requireIdle && s.pollInFlight != 0) { + if s.closed || (requireIdle && (s.pollInFlight != 0 || s.inResumeGraceLocked(time.Now()))) { return false } s.closed = true @@ -124,20 +136,55 @@ func (st *SessionStore) removeAndMarkClosed(s *Session, requireIdle bool) bool { // sweep evicts every session that has gone quiet past timeout with no poll // parked on it. The final expiry and transport checks happen while holding both // lifecycle locks, so a poll cannot attach between checking and removal. +// +// A resumable session is judged differently: while it is still resumable +// (its reliable layer is not broken), what matters is how long it has been +// 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. func (st *SessionStore) sweep(timeout time.Duration, onEvict func(*Session)) { now := time.Now() var expired []*Session + var detached []*Session st.mu.Lock() for id, s := range st.sessions { s.mu.Lock() - if !s.closed && s.pollInFlight == 0 && now.Sub(s.lastActive) > timeout { - s.closed = true - delete(st.sessions, id) - expired = append(expired, s) + if !s.closed && s.pollInFlight == 0 { + switch { + case s.rs != nil && !s.rs.isBroken(): + if now.Sub(s.detachedAt) > s.resumeGrace { + s.closed = true + delete(st.sessions, id) + expired = append(expired, s) + } else { + detached = append(detached, s) + } + case now.Sub(s.lastActive) > timeout: + s.closed = true + delete(st.sessions, id) + expired = append(expired, s) + } } s.mu.Unlock() } + if max := st.maxDetachedResumable; max > 0 && len(detached) > max { + // detachedAt was read under s.mu above and only changes when a + // transport attaches or detaches, which needs s.mu; a stale value + // here just means a slightly unfair pick, never a wrong eviction — + // the recheck below is what decides. + 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 { + s.closed = true + delete(st.sessions, s.ID) + expired = append(expired, s) + } + s.mu.Unlock() + } + } st.mu.Unlock() // Pipe closing and application callbacks always happen outside locks. diff --git a/websocket.go b/websocket.go index 1a3ac5a..af0725e 100644 --- a/websocket.go +++ b/websocket.go @@ -2,6 +2,7 @@ package pollmux import ( "context" + "encoding/binary" "errors" "fmt" "io" @@ -32,6 +33,16 @@ func wsEncode(typ frameType, payload []byte) []byte { return msg } +// wsEncodeSeq is wsEncode for a frameSeqData message: type tag, 8-byte +// offset, data. +func wsEncodeSeq(off uint64, payload []byte) []byte { + msg := make([]byte, 1+seqHeaderLen+len(payload)) + msg[0] = byte(frameSeqData) + binary.BigEndian.PutUint64(msg[1:], off) + copy(msg[1+seqHeaderLen:], payload) + return msg +} + func wsDecode(msg []byte) (frameType, []byte, error) { if len(msg) == 0 { return 0, nil, errors.New("pollmux: empty websocket message") @@ -63,6 +74,33 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler writeError(w, http.StatusBadRequest, "session was not negotiated for websocket transport") return } + + // A resumable session lets a new WebSocket displace a stale one — + // the client only dials again after its previous connection died, + // and this server may not have noticed that yet — instead of + // answering 409 (see attachments). The claim is taken before + // beginWebSocket, and released after endWebSocket, so that by the + // time a kicked handler's done channel closes its wsAttached flag + // is already clear for the newcomer. The kick closes the + // connection (failing whichever pump is inside Read/Write) and + // interrupts the write pump's pipe wait. + var att *attachment + var wsRef atomic.Pointer[websocket.Conn] + if s.rs != nil { + var err error + att, err = s.att.attach(attachBoth, func() { + if c := wsRef.Load(); c != nil { + c.CloseNow() + } + s.rs.interruptOut() + }) + if err != nil { + writeError(w, http.StatusServiceUnavailable, "previous transport is still detaching, retry") + return + } + defer s.att.detach(att) + } + if !s.beginWebSocket() { if s.IsClosed() { writeError(w, http.StatusGone, "session closed") @@ -86,7 +124,18 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler // Accept already wrote the HTTP error response. return } - c.SetReadLimit(int64(cfg.MaxSendBytes) + 1) // +1 for wsEncode's type byte + c.SetReadLimit(int64(cfg.MaxSendBytes) + 1 + seqHeaderLen) // +1 for wsEncode's type byte, +8 for a seq-data offset + if s.rs != nil { + wsRef.Store(c) + // A kick that landed between attach and Accept found no + // connection to close; honour it now rather than sit in Read + // until the kicker gives up. + if !s.att.isCurrent(att) { + c.CloseNow() + return + } + s.rs.resetAck() + } // Not r.Context(): coder/websocket's Accept doc warns that using the // request context after Accept returns "may lead to unexpected @@ -108,7 +157,7 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler readErrCh := make(chan error, 1) writeErrCh := make(chan error, 1) go func() { defer wg.Done(); readErrCh <- wsReadPump(ctx, c, s, idle) }() - go func() { defer wg.Done(); writeErrCh <- wsWritePump(ctx, c, s, cfg, idle) }() + go func() { defer wg.Done(); writeErrCh <- wsWritePump(ctx, c, s, cfg, idle, att) }() // Whichever pump ends first decides the outcome and closing c below // is what unblocks whichever pump is still running — a read or @@ -162,11 +211,39 @@ func wsReadPump(ctx context.Context, c *websocket.Conn, s *Session, idle time.Du } switch ft { case frameData: + if s.rs != nil { + // Unnumbered data would silently desync the upstream + // count; a resumable client never sends it. + s.rs.markBroken() + return errors.New("pollmux: unnumbered data frame on a resumable session") + } if len(payload) > 0 { if _, err := s.writeUpstream(payload); err != nil { return err } } + case frameSeqData: + if s.rs == nil { + return errors.New("pollmux: seq-data frame on a non-resumable session") + } + off, data, err := splitSeq(payload) + if err == nil { + err = s.rs.recvIn(off, data) + } + if err != nil { + return err + } + case frameAck: + if s.rs == nil { + return errors.New("pollmux: ack frame on a non-resumable session") + } + n, err := decodeAck(payload) + if err == nil { + err = s.rs.ack(n) + } + if err != nil { + return err + } case frameHeartbeat: // Liveness only. default: @@ -181,7 +258,10 @@ func wsReadPump(ctx context.Context, c *websocket.Conn, s *Session, idle time.Du // "nothing to send" into a heartbeat frame on the same cadence pollStream // already uses, so the peer's read-idle watchdog never has reason to fire // while this session is merely quiet rather than dead. -func wsWritePump(ctx context.Context, c *websocket.Conn, s *Session, cfg ServerConfig, idle time.Duration) error { +func wsWritePump(ctx context.Context, c *websocket.Conn, s *Session, cfg ServerConfig, idle time.Duration, att *attachment) error { + if s.rs != nil { + return wsWritePumpResumable(ctx, c, s, cfg, idle, att) + } buf := make([]byte, cfg.PollBufferSize) for { n, err := s.toClient.ReadAvailable(buf, cfg.HeartbeatInterval, cfg.CoalesceWindow) @@ -202,6 +282,49 @@ func wsWritePump(ctx context.Context, c *websocket.Conn, s *Session, cfg ServerC } } +// errDetached is wsWritePumpResumable's report that a newer WebSocket took +// over the session while this one was parked: leave without touching the +// pipe again. +var errDetached = errors.New("pollmux: transport detached by a newer attachment") + +// wsWritePumpResumable is wsWritePump for a resumable session: the same +// three changes pollStreamResumable makes to pollStream — bytes come from +// the reliable layer as numbered frames, every write is preceded by any due +// ack, and an interrupted wait means either "replaced" or "ack now". +func wsWritePumpResumable(ctx context.Context, c *websocket.Conn, s *Session, cfg ServerConfig, idle time.Duration, att *attachment) error { + buf := make([]byte, cfg.PollBufferSize) + for { + off, n, err := s.rs.nextOut(buf, cfg.HeartbeatInterval, cfg.CoalesceWindow) + interrupted := false + switch { + case errors.Is(err, io.EOF): + return io.EOF + case errors.Is(err, errPipeInterrupted): + if !s.att.isCurrent(att) { + return errDetached + } + interrupted = true + } + + wctx, cancel := context.WithTimeout(ctx, idle) + if ack, due := s.rs.takeAck(); due { + err = c.Write(wctx, websocket.MessageBinary, wsEncode(frameAck, encodeOffset(ack))) + } + if err == nil { + switch { + case n > 0: + err = c.Write(wctx, websocket.MessageBinary, wsEncodeSeq(off, buf[:n])) + case !interrupted: + err = c.Write(wctx, websocket.MessageBinary, wsEncode(frameHeartbeat, nil)) + } + } + cancel() + if err != nil { + return err + } + } +} + // ---- Client side ---- // connectWebSocket dials {prefix}/{id}/ws and returns a Conn backed by it.