Skip to content

feat(ws): add upgradeTimeout and resolve ws() on handled socket errors - #172

Merged
pi0 merged 2 commits into
unjs:mainfrom
DavidIlie:codex/ws-establishment-deadline
Oct 23, 2026
Merged

pi0 merged 2 commits into
unjs:mainfrom
DavidIlie:codex/ws-establishment-deadline

Conversation

@DavidIlie

@DavidIlie DavidIlie commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an optional upgradeTimeout to proxyUpgrade and ProxyServer.ws(), and makes ws() settle consistently on client socket errors.

upgradeTimeout

  • One deadline from connection setup until the upstream upgrade or final response headers arrive. 1xx responses and partial headers don't extend it.
  • Off by default. Omitted, non-positive and non-finite values disable it; values above 2147483647 ms are capped.
  • On expiry, both the upstream request and the client socket are destroyed (no HTTP 504 is written), and an error with code: "ERR_UPSTREAM_UPGRADE_TIMEOUT" and statusCode: 504 is reported.
  • It never limits an established tunnel or a non-upgrade response body.
  • While the deadline is active, a client disconnect also cancels the pending upstream request and is reported as ECONNRESET. This works even while a custom agent has no free socket.

ws() settlement (behavior change)

Previously, a client socket error during an upgrade always rejected ws(), even when an error listener had already received it. Now ws() follows the same rule as other errors: with an error listener, the error is emitted and the promise resolves; without one, it rejects. This holds whether or not upgradeTimeout is set. web() is unchanged.

Verification

  • pnpm test (lint + typecheck + full suite)
  • test/upgrade-timeout.test.ts runs every case against both APIs: silent upstream, queued agent requests (timeout, client close, client error), 1xx/partial headers, a tunnel that outlives the deadline, non-upgrade responses, early upstream errors, and disabled values.
  • test/server.test.ts: ws() settlement on a client socket error, with and without an error listener (fails without the fix).

🤖 Generated with AI assistant

@coderabbitai

coderabbitai Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: faf12e7e-683c-430a-b763-9f12f1e968e3

📥 Commits

Reviewing files that changed from the base of the PR and between 54e4263 and 60932bf.

📒 Files selected for processing (8)
  • AGENTS.md
  • README.md
  • src/_ws-timeout.ts
  • src/middleware/ws-incoming.ts
  • src/types.ts
  • src/ws.ts
  • test/types.test-d.ts
  • test/ws-timeout.test.ts

Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review.

📝 Walkthrough

The PR adds an optional establishmentTimeout to WebSocket proxy APIs. It enforces the deadline for upstream response headers or upgrades, cleans up timed-out connections, updates documentation and types, and adds coverage for timeout, cancellation, agent, response, and invalid-value behavior.

Changes: WebSocket establishment timeout

Layer / File(s) Summary
Timeout option and documented contract
src/types.ts, src/ws.ts, README.md, AGENTS.md, test/types.test-d.ts
Adds establishmentTimeout to both public option types and documents disabled values, the timeout cap, error details, cleanup, and cancellation behavior.
Timeout enforcement and error handling
src/_ws-timeout.ts, src/ws.ts, src/middleware/ws-incoming.ts
Adds the timeout helper and wires it into both proxy paths. The helper clears listeners after settlement and destroys timed-out requests and sockets.
Timeout behavior validation
test/ws-timeout.test.ts
Tests timeout expiry, cleanup, queued-agent handling, downstream cancellation, successful upgrades, non-upgrade responses, upstream errors, and invalid values.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Proxy
  participant TimeoutHelper
  participant Upstream
  Client->>Proxy: request WebSocket upgrade
  Proxy->>TimeoutHelper: setUpgradeTimeout
  TimeoutHelper->>Upstream: monitor upgrade request and socket
  Upstream-->>TimeoutHelper: response, upgrade, error, or close
  TimeoutHelper-->>Proxy: report timeout or socket failure
  Proxy-->>Client: close or complete connection
Loading

Suggested reviewers: pi0

Merge Risk: ⚪ Minimal · up to 60932

The opt-in WebSocket establishment timeout is typed, documented, enforced across both proxy paths, and covered for timeout, cleanup, cancellation, and successful establishment behavior.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title describes the WebSocket timeout and handled socket-error behavior, which are related to the changes. However, it names upgradeTimeout instead of the implemented establishmentTimeout, so …
Full details: Title check

Explanation

The title describes the WebSocket timeout and handled socket-error behavior, which are related to the changes. However, it names upgradeTimeout instead of the implemented establishmentTimeout, so it does not identify the primary option precisely.

Full details: Docstring Coverage

Explanation

Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@DavidIlie
DavidIlie marked this pull request as ready for review September 18, 2026 10:55
… handled socket errors

- rename `establishmentTimeout` to `upgradeTimeout` (and `_ws-timeout.ts` to `_upgrade-timeout.ts`)
- `ws()` no longer rejects on client socket errors when an `error` listener exists, regardless of `upgradeTimeout`
- trim README/AGENTS.md docs, use an options object in the test helper
@pi0x pi0x changed the title feat(ws): add an upgrade establishment timeout feat(ws): add upgradeTimeout and resolve ws() on handled socket errors Oct 23, 2026
@codecov

codecov Bot commented Oct 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.51%. Comparing base (54e4263) to head (85f8836).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #172      +/-   ##
==========================================
+ Coverage   95.03%   95.51%   +0.48%     
==========================================
  Files           8        9       +1     
  Lines         805      847      +42     
  Branches      331      336       +5     
==========================================
+ Hits          765      809      +44     
+ Misses         35       33       -2     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pi0
pi0 merged commit 49565ec into unjs:main Oct 23, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants