Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 正在进行)。

---

## 协议与行为约定
Expand Down
107 changes: 98 additions & 9 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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
}
Expand All @@ -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/
Expand All @@ -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)
}

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 — "+
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
//
Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand All @@ -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.
Expand Down
72 changes: 69 additions & 3 deletions frame.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading