Skip to content

feat(manager): drained reload (reload(runner, { drain })) - #92

Merged
pi0 merged 6 commits into
mainfrom
feat/drained-reload
Oct 24, 2026
Merged

pi0 merged 6 commits into
mainfrom
feat/drained-reload

Conversation

@pi0x

@pi0x pi0x commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #91.

RunnerManager.reload(next) closes the previous runner at the swap, so in-flight requests, streamed responses and WebSockets end with ECONNRESET. This adds a drain mode:

await manager.reload(next, { drain: true });                    // closes it after 60s at the latest
await manager.reload(next, { drain: { timeout: 600_000 } });    // custom limit
await manager.reload(next, { drain: { timeout: Infinity } });   // no limit
new EnvServer({ entry, watch: true, drain: true });             // default for its reloads (watch mode included)

New requests and upgrades go to the new runner right away. The previous runner keeps serving what it already accepted and is retired with shutdown() (so ipc.onClose runs) once that settles. At the timeout (default 60s, also for NaN; negative values are 0), it is closed with whatever is still open. A graceful shutdown there would wait on those same exchanges and overrun the limit. reload() resolves once the new runner is attached and doesn't wait for the drain.

How it works

  • RunnerManager counts exchanges per runner:
    • requests: from runner selection until the response body is read to the end, errors or is canceled. The runner is read and counted in the same tick, so a drained reload can't retire it as idle in between. The body is re-wrapped with srvx FastResponse. A runner's own FastResponse on Node (e.g. from self) is read with srvx's internal _toNodeResponse(), like its Node adapter does, so the content-type/content-length srvx derives for string/byte bodies are kept (reading .body would turn it into a native Response and drop them).
      • A HEAD request settles once its response arrives (its body may never be read). Node.js stream bodies settle with stream.finished().
      • Runner fetch() now passes a Request's signal to proxyFetch() (httpxy doesn't forward it), so a client that disconnects before the response aborts the worker request instead of holding the previous runner until the worker answers. When that signal aborted it, fetch() resolves with an empty 499 response instead of rejecting, which srvx would log as a fetch handler error. Deno's node:http ignores the signal, so there the request still runs to completion, as before.
      • On Node, runner fetch() passes srvx FastResponse as httpxy's Response option (httpxy 0.5.6), so worker bodies stay Node.js streams.
    • Node upgrades (manager.upgrade()): until the client socket closes
    • Bun/Deno bridge (wsSrvxPlugin()): new optional track callback on createRunnerWSProxyPlugin(), backed by crossws's onUpstreamConnect/onUpstreamClose lifecycle callbacks (exactly once each; crossws bumped to ^0.4.16, feat(proxy): lifecycle callbacks for proxied connections h3js/crossws#219). The target is synchronous when the runner is ready, so the dial happens in the tick the address is read; a dial resolved mid-reload to a runner swapped out meanwhile is refused (1011).
  • close()/shutdown() of the manager also retire draining runners. close() force-closes one already shutting down; a second shutdown() waits for the running one (no double ipc.onClose).
  • A draining runner that closes itself (crash) just leaves the drain. One attached again (swapping back) stops draining, and reload(activeRunner) keeps it. A runner's close() is wrapped once, so re-attaching doesn't report its close twice.
  • The drain timer is unref()'d.
  • A drained runner's shutdown()/close() that throws synchronously is logged, not thrown out of a socket close listener or timer.
  • Lazy invalidation is per runner: a draining runner's pending reloadModule() no longer clears the new runner's invalidation, and isn't shared with fetches to the new runner.

Trade-offs

  • Response tracking is always on, since a request must be counted before a reload is known. Responses through the manager are re-created with the same status/headers/body, which drops url/redirected and Response subclasses. A quick local benchmark (srvx → manager → node-worker) showed no difference from main beyond noise with FastResponse; with a native Response wrapper, 1 MiB streams looked a few percent slower.
  • On Bun/Deno hosts, a self runner's native Response with a string body is sent chunked through the manager (the runtime would otherwise derive content-length). Worker runners are unaffected, since their proxied responses carry the upstream content-length.
  • A custom runner whose shutdown() never settles isn't force-closed at the drain timeout (the timer is cleared once the shutdown starts). Built-in runners bound their own shutdown.
  • Not included: waiting for the new runner to be ready before the swap (requests arriving while it starts wait for it and can get a 503, while the old runner is still up); requests sent to runner.fetch() directly aren't counted; no CLI flag.

Tests

  • test/drain.test.ts: streamed response survives a drained reload (and is cut without drain), idle runner retires right away, canceled body, timeout closes on time (upper bound), 60s default and Infinity (fake timers), NaN/negative timeouts, manager close/shutdown during a drain, self-closing runner (not retired again), re-attaching a draining runner, reload(activeRunner), a throwing shutdown(), a request racing the reload, per-runner invalidation, FastResponse headers (GET/HEAD) and stream bodies (web and Node.js streams), WebSocket survives via wsSrvxPlugin(), EnvServer drain option. Through a srvx server with a real worker: a client disconnecting before the response and mid-stream, 204/304/HEAD/multiple set-cookie, and a HEAD body never read. Also an upgrade waiting for readiness, and the bridge's refusal of a swapped-out runner (track throws).
  • test/websocket.test.ts: on Bun/Deno hosts, a drained reload through a real RunnerManager.wsSrvxPlugin() retires the previous runner only once the bridged WebSocket closes, also for a WebSocket bridged while the runner was still starting (async target).

Upstream follow-ups

Docs: README ("Drained reload"), .agents/ARCHITECTURE.md, AGENTS.md.

🤖 Generated with AI assistant

Summary by CodeRabbit

  • New Features
    • Added optional drained reloads. When enabled, the previous runner continues serving accepted requests and WebSocket connections until they finish or the timeout expires, while new traffic goes to the replacement.
    • Added a server-level drain setting for reloads, including watch-mode reloads. The default drain timeout is 60 seconds; it can be customized or disabled.
  • Documentation
    • Added guidance and examples describing drained reload behavior, active requests and WebSockets, and timeout settings.

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 37 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f870296c-9a33-45ef-9083-97577fb4b8d2
📥 Commits

Reviewing files that changed from the base of the PR and between 751c28e and 5ba78f1.

📒 Files selected for processing: 6
  • .agents/ARCHITECTURE.md
  • README.md
  • src/common/base-runner.ts
  • src/manager.ts
  • test/drain.test.ts
  • test/fixtures/app-stream.mjs

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 64ea923b-2f48-4b13-bd13-4b33624c3496
📥 Commits

Reviewing files that changed from the base of the PR and between 5744a0b and 751c28e.

⛔ Files ignored due to path filters: 1
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing: 4
  • .agents/ARCHITECTURE.md
  • package.json
  • src/common/base-runner.ts
  • src/manager.ts
🚧 Files skipped from review as they are similar to previous changes: 2
  • .agents/ARCHITECTURE.md
  • src/manager.ts

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

RunnerManager now supports drained reloads. It can keep accepted fetches and WebSocket connections on the previous runner until they settle or a timeout expires. EnvServer can provide a default drain setting for reloads.

Changes: Drained reload

Layer / File(s) Summary
Reload options and orchestration
src/manager.ts, src/server.ts, src/index.ts
RunnerManager.reload() accepts drain options. EnvServer applies explicit reload options before its configured default, and RunnerReloadOptions is exported.
Fetch and WebSocket exchange tracking
src/manager.ts, src/common/ws-proxy.ts, src/common/base-runner.ts
RunnerManager tracks fetches and response-body completion, including Node FastResponse bodies, and tracks WebSocket connections until close. The Bun/Deno proxy reports bridged connection lifecycle events.
Runner retirement and validation
src/manager.ts, test/drain.test.ts, test/fixtures/app-stream.mjs
Draining runners shut down after exchanges settle or the timeout expires. Tests cover replacement, reattachment, shutdown, streams, WebSockets, and timeout handling.
Bridge coverage and documentation
test/fixtures/ws-bridge-server.mjs, test/websocket.test.ts, README.md, AGENTS.md, .agents/ARCHITECTURE.md, package.json
Bridge tests cover WebSockets opened before and during runner startup. Documentation describes drain settings and timeout behavior. Dependency ranges are updated for crossws, srvx, and httpxy.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature · Severity of issue fixed: Medium

Possibly related issues

  • unjs/env-runner#91 — The PR adds drain behavior for accepted requests and WebSockets during runner reloads.

Suggested reviewers: pi0

Merge Risk: ⚪ Minimal · up to 751c2

This change adds drained reloads so in-flight requests and WebSockets can finish on the previous runner before it retires. No concrete merge-blocking defect was found in the supplied evidence. Ordinary test and CI validation is still the right check before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 9 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "feat(manager): drained reload (reload(runner, { drain }))" names the main change. The PR adds optional draining to RunnerManager.reload() and an EnvServer drain option. The changed files …
Linked Issues check Passed Issue #91 requires drained reloads to route new traffic to the new runner, preserve accepted requests and upgrades, apply an optional upper bound, and retire the previous runner with shutdown(). The…
Out of Scope Changes check Passed The changes stay within issue #91. The manager and server APIs implement drained reloads. WebSocket lifecycle tracking, response handling, invalidation isolation, dependency updates, documentation, fi…
Full details: Title check

Explanation

The title "feat(manager): drained reload (reload(runner, { drain }))" names the main change. The PR adds optional draining to RunnerManager.reload() and an EnvServer drain option. The changed files match this: src/manager.ts adds RunnerReloadOptions and drain handling, src/server.ts adds the drain option, and tests and docs cover drained reloads. The title uses a conventional commit prefix and a specific API signature, so a teammate scanning history can identify the primary change.

Full details: Linked Issues check

Explanation

Issue #91 requires drained reloads to route new traffic to the new runner, preserve accepted requests and upgrades, apply an optional upper bound, and retire the previous runner with shutdown(). The changes implement per-runner tracking for responses, Node upgrades, and Bun/Deno WebSockets. They implement default, custom, infinite, NaN, and negative timeout behavior. They also add EnvServer support and tests for streaming, cancellation, timeout, shutdown, reload races, and WebSocket draining.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #91. The manager and server APIs implement drained reloads. WebSocket lifecycle tracking, response handling, invalidation isolation, dependency updates, documentation, fixtures, and tests support that behavior. No unrelated change is demonstrated.

Full details: Docstring Coverage

Explanation

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

Resolution

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

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@pkg-pr-new

pkg-pr-new Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/env-runner@92

commit: 5ba78f1

pi0 added 2 commits October 23, 2026 05:18
… counting

- close the previous runner at the drain timeout instead of a graceful
  shutdown that overran it; default 60s, `Infinity` for no limit
- read and count the active runner in the same tick in `fetch()`/`upgrade()`
- keep lazy invalidation per runner, so a draining runner's module reload
  can't clear the new runner's
- re-wrap tracked bodies with srvx `FastResponse`
- Bun/Deno bridge test goes through `RunnerManager.wsSrvxPlugin()`
- keep srvx `FastResponse` headers (`content-type`/`content-length`) by
  reading it like srvx's Node adapter, instead of via `.body`
- stop draining a runner that is attached again; `reload(activeRunner)`
  keeps it; wrap a runner's `close()` once
- `NaN` drain timeout uses the default, negative values are 0
- log a drained runner's synchronously throwing `shutdown()`/`close()`
pi0 added 2 commits October 23, 2026 06:46
…allbacks

crossws 0.4.16 (h3js/crossws#219) reports proxied connections with
`onUpstreamConnect`/`onUpstreamClose`, exactly once each, so the bridge no
longer wraps the proxy's `open`/`close`/`error` hooks. The target is
synchronous when the runner is ready (dialed in the same tick), and the
manager refuses a dial to a runner swapped out meanwhile.
Pass srvx's `FastResponse` as httpxy's `proxyFetch()` `Response` option
(httpxy 0.5.6), so a proxied response keeps the upstream Node.js stream and
srvx pipes it without web stream conversions. Also bumps srvx to 1.0.7
(keeps the derived content-length when `FastResponse` materializes).
From the final review:
- runner `fetch()` passes a `Request`'s signal to `proxyFetch()` (httpxy
  doesn't forward it), so a client disconnect aborts the worker request; it
  resolves with an empty 499 response when that signal aborted it
- a HEAD request settles once its response arrives
- Node.js stream bodies settle with `stream.finished()` (no `autoDestroy` needed)
- the drain timer is `unref()`'d
- tests: client disconnects, proxied 204/304/HEAD/set-cookie, an upgrade
  waiting for readiness, and the bridge refusing a swapped-out runner
@pi0
pi0 merged commit 15dff2c into main Oct 24, 2026
11 checks passed
@pi0
pi0 deleted the feat/drained-reload branch October 24, 2026 01:28
pi0x pushed a commit to pi0/eve that referenced this pull request Oct 30, 2026
Move eve's vendored env-runner to 0.3.10, the version the Nitro RC uses.
Its worker now closes the server before running `ipc.onClose`, and
`shutdown()` waits for the worker's exit before terminating it, so eve no
longer patches the worker or manages worker exit itself.

The development runner's `close()` now terminates right away and
`shutdown()` is the graceful path; the drained dev server retires workers
with `shutdown()` and drops client connections before shutting workers
down on close, so an open stream doesn't hold up exit.

Draining stays in eve for now; a TODO tracks moving it to env-runner's
`RunnerManager` drained reload (unjs/env-runner#92).

Signed-off-by: pi0x <[email protected]>
@pi0 pi0 mentioned this pull request Oct 30, 2026
3 tasks done
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.

RunnerManager.reload() terminates the previous runner immediately, resetting in-flight requests

2 participants