Repository navigation
feat(vercel): add vercel runner - #3
Conversation
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 9 minutes and 30 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAdds a new Vercel runner (runtime + worker), exposes it via package exports and src/index, extends loader/RunnerName to include "vercel", declares optional Changes
Sequence DiagramsequenceDiagram
actor Client
participant VercelEnvRunner as VercelEnvRunner
participant WorkerProcess as Worker Process
participant NodeWorkerImpl as Node Worker Impl
participant EntryModule as Entry Module
Client->>VercelEnvRunner: fetch(request)
VercelEnvRunner->>VercelEnvRunner: inject/merge Vercel & forwarding headers
VercelEnvRunner->>WorkerProcess: send proxied HTTP request to worker address
WorkerProcess->>NodeWorkerImpl: deliver request (worker runtime)
NodeWorkerImpl->>EntryModule: invoke exported fetch(handler)
EntryModule-->>NodeWorkerImpl: response
NodeWorkerImpl-->>WorkerProcess: proxied response
WorkerProcess-->>VercelEnvRunner: return response
VercelEnvRunner-->>Client: return response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/runners/vercel/runner.ts`:
- Around line 89-103: Replace the undefined _requestGracefulShutdown usage in
_closeRuntime with an inline graceful-shutdown flow: send shutdown with
this.#worker.postMessage({event:"shutdown"}), then await a Promise that attaches
this.#worker.on("message") and resolves when message.event === "exit", treats
any defined numeric this.#worker._exitCode as a finished state (check for typeof
this.#worker?._exitCode === "number" rather than Boolean(...) so 0 counts as
finished), and rejects/force-closes after a short timeout; ensure you remove the
call to _requestGracefulShutdown and clean up listeners and references to
this.#worker in the success and timeout branches.
- Around line 66-69: In the fetch override in runner.ts, when input is already a
Request you currently reconstruct it with only { headers }, which discards
caller-supplied init overrides (method, body, duplex, signal, etc.); change the
creation to merge init and headers (e.g. new Request(input, { ...init, headers
})) so the Request branch preserves init overrides the same way the string/URL
branch does—ensure you merge any existing header values appropriately if needed.
In `@src/runners/vercel/worker.ts`:
- Around line 10-26: The serve() call captures a snapshot of entry.middleware,
entry.plugins, entry.websocket and the initial presence of entry.upgrade so
after reloads fetch can point to new code while middleware/plugins/upgrade stay
stale; fix by making those integrations dynamic: keep the server.fetch as a thin
delegating wrapper that calls the latest entry.fetch at request time (reference
entry.fetch and server.fetch), replace the static middleware/plugins values with
delegating middleware/plugin implementations that consult entry.middleware,
entry.plugins and entry.websocket on each invocation (reference
entry.middleware, entry.plugins, entry.websocket and wsPlugin), and always
register a single persistent "upgrade" listener on
server.node?.server?.on("upgrade") that forwards to entry.upgrade if present
(reference entry.upgrade and the upgrade handler) so reloads see the current
module shape.
- Around line 36-42: The shutdown handler currently chains
Promise.resolve(entry.ipc?.onClose?.()).then(() => server.close()).then(() =>
parentPort?.postMessage({ event: "exit" })) so if entry.ipc.onClose() or
server.close() rejects the exit ack is never sent; update the handler in the
parentPort "message" listener to always post parentPort?.postMessage({ event:
"exit" }) in a finally path (or in both then and catch) after awaiting/handling
Promise.resolve(entry.ipc?.onClose?.()) and server.close() so the exit message
is emitted regardless of success or failure while preserving any error
logging/propagation from entry.ipc.onClose or server.close.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d08f4eba-6ee8-4f45-853e-9bc5fdf36265
📒 Files selected for processing (5)
package.jsonsrc/index.tssrc/loader.tssrc/runners/vercel/runner.tssrc/runners/vercel/worker.ts
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/runners/vercel/runner.ts (1)
66-69:⚠️ Potential issue | 🟠 Major
initoverrides lost wheninputis aRequest.Line 67 reconstructs the request with only
{ headers }, discarding any caller-suppliedinitproperties (method,body,signal,duplex, etc.). This is inconsistent with line 69, which correctly spreadsinitfor the string/URL branch.Suggested fix
if (input instanceof Request) { - return super.fetch(new Request(input, { headers })); + return super.fetch(new Request(input, { ...init, headers })); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/runners/vercel/runner.ts` around lines 66 - 69, The Request branch currently rebuilds the Request with only { headers } and drops caller-supplied init options; update the input instanceof Request path in the fetch override to preserve and merge init and headers instead of replacing them: when constructing the new Request from input, spread ...init into the options and merge headers (combine existing input.headers with the provided headers) so method/body/signal/duplex/etc. are preserved before calling super.fetch; reference the fetch override, input, init, headers, and the new Request construction to locate the change.
🧹 Nitpick comments (3)
src/runners/vercel/runner.ts (1)
89-98: Consider graceful shutdown before termination.The worker implementation (per
worker.tscontext snippet) supports graceful shutdown via{ event: "shutdown" }message, which allows cleanup (e.g., closing IPC, server) before sending{ event: "exit" }. The current implementation terminates abruptly without this handshake.This may be acceptable for dev/test scenarios, but could cause resource leaks or unclean state if the worker has pending operations.
Optional: Add graceful shutdown with timeout fallback
protected async _closeRuntime() { - if (!this.#worker) { + const worker = this.#worker; + if (!worker) { return; } - this.#worker.removeAllListeners(); - await this.#worker.terminate().catch((error) => { + + // Attempt graceful shutdown with timeout + await new Promise<void>((resolve) => { + const timeout = setTimeout(() => resolve(), 3000); + const onMessage = (msg: { event?: string }) => { + if (msg?.event === "exit") { + clearTimeout(timeout); + resolve(); + } + }; + worker.on("message", onMessage); + worker.postMessage({ event: "shutdown" }); + }); + + worker.removeAllListeners(); + await worker.terminate().catch((error) => { console.error(error); }); this.#worker = undefined; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/runners/vercel/runner.ts` around lines 89 - 98, The _closeRuntime method currently terminates this.#worker abruptly; modify it to send a graceful shutdown handshake to the worker (postMessage({ event: "shutdown" })) and await a response event of { event: "exit" } within a bounded timeout (e.g., 2–5s), only calling this.#worker.terminate() as a fallback if the timeout elapses or an error occurs; still removeAllListeners and clear this.#worker at the end, and handle any errors from the handshake so the code falls back to terminate() to avoid hanging.test/vercel.test.ts (2)
97-138: Consider adding test forinitoptions preservation withRequestinput.The preservation tests cover headers well, but there's no test verifying that
initoptions (e.g.,method,body) are preserved when passing aRequestobject. This would catch the bug flagged inrunner.tswhereinitis not spread for theRequestbranch.Example test case
it("preserves init options when input is a Request", async () => { runner = new VercelEnvRunner({ name: "test-init-preserve", data: { entry: appEntry } }); await waitForReady(runner); const request = new Request("http://localhost/", { method: "GET" }); const res = await runner.fetch(request, { method: "POST" }); // This test would fail with current implementation since init.method is ignored // Adjust assertion based on expected behavior });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/vercel.test.ts` around lines 97 - 138, The fetch implementation in runner.ts currently ignores the provided init when the first argument is a Request, so init options (method, body, headers) are lost; update VercelEnvRunner.fetch to merge/spread the provided init over the cloned Request (e.g., create a new Request(request, { ...requestInit, ...init })) or otherwise apply init values (method/body/headers) when input is a Request; ensure headers merging preserves existing request headers unless explicitly overridden and add a test similar to the suggested "preserves init options when input is a Request" using VercelEnvRunner.fetch to verify method/body are preserved.
11-25: Minor:onMessagelistener not cleaned up on success.The
waitForReadyhelper registers anonMessagelistener but only clears the timeout on success—it never removes the listener itself. While this won't cause test failures (the runner is closed inafterEach), it's a minor hygiene issue.Suggested improvement
function waitForReady(runner: EnvRunner, timeout = 5000): Promise<void> { return new Promise((resolve, reject) => { if (runner.ready) { resolve(); return; } const timer = setTimeout(() => reject(new Error("Runner did not become ready")), timeout); - runner.onMessage(() => { + const listener = () => { if (runner.ready) { clearTimeout(timer); + runner.offMessage(listener); resolve(); } - }); + }; + runner.onMessage(listener); }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/vercel.test.ts` around lines 11 - 25, The waitForReady helper registers a runner.onMessage listener but never removes it; change waitForReady to capture the handler (e.g., const handler = () => { ... }) and unregister it on both success and failure — either by using the unsubscribe returned from runner.onMessage (call unsubscribe()) or by calling runner.offMessage(handler) if that API exists; ensure you still clearTimeout(timer) on success and also remove the listener in the timeout rejection path so the handler is cleaned up in all outcomes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/runners/vercel/runner.ts`:
- Around line 66-69: The Request branch currently rebuilds the Request with only
{ headers } and drops caller-supplied init options; update the input instanceof
Request path in the fetch override to preserve and merge init and headers
instead of replacing them: when constructing the new Request from input, spread
...init into the options and merge headers (combine existing input.headers with
the provided headers) so method/body/signal/duplex/etc. are preserved before
calling super.fetch; reference the fetch override, input, init, headers, and the
new Request construction to locate the change.
---
Nitpick comments:
In `@src/runners/vercel/runner.ts`:
- Around line 89-98: The _closeRuntime method currently terminates this.#worker
abruptly; modify it to send a graceful shutdown handshake to the worker
(postMessage({ event: "shutdown" })) and await a response event of { event:
"exit" } within a bounded timeout (e.g., 2–5s), only calling
this.#worker.terminate() as a fallback if the timeout elapses or an error
occurs; still removeAllListeners and clear this.#worker at the end, and handle
any errors from the handshake so the code falls back to terminate() to avoid
hanging.
In `@test/vercel.test.ts`:
- Around line 97-138: The fetch implementation in runner.ts currently ignores
the provided init when the first argument is a Request, so init options (method,
body, headers) are lost; update VercelEnvRunner.fetch to merge/spread the
provided init over the cloned Request (e.g., create a new Request(request, {
...requestInit, ...init })) or otherwise apply init values (method/body/headers)
when input is a Request; ensure headers merging preserves existing request
headers unless explicitly overridden and add a test similar to the suggested
"preserves init options when input is a Request" using VercelEnvRunner.fetch to
verify method/body are preserved.
- Around line 11-25: The waitForReady helper registers a runner.onMessage
listener but never removes it; change waitForReady to capture the handler (e.g.,
const handler = () => { ... }) and unregister it on both success and failure —
either by using the unsubscribe returned from runner.onMessage (call
unsubscribe()) or by calling runner.offMessage(handler) if that API exists;
ensure you still clearTimeout(timer) on success and also remove the listener in
the timeout rejection path so the handler is cleaned up in all outcomes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c778b433-ee2b-4ca9-9f24-a3716dbfa2c4
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (5)
package.jsonsrc/runners/vercel/runner.tssrc/runners/vercel/worker.tstest/fixtures/app-headers.mjstest/vercel.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- package.json
- src/runners/vercel/worker.ts
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/runners/vercel/runner.ts (1)
29-29:⚠️ Potential issue | 🟠 MajorMerge
init.headersbefore rebuilding aRequest.When
inputis already aRequest, Line 29 seedsheadersfrominput.headersonly, and Line 67 then writes that merged object back intonew Request(...).method/bodyoverrides now survive, but caller header overrides frominit.headersstill get dropped.Suggested fix
- const headers = new Headers(input instanceof Request ? input.headers : init?.headers); + const headers = new Headers(input instanceof Request ? input.headers : init?.headers); + if (input instanceof Request && init?.headers) { + for (const [key, value] of new Headers(init.headers)) { + headers.set(key, value); + } + }MDN Request constructor: when `input` is a `Request` and `init.headers` is provided, are the original request headers merged with `init.headers`, or does `init.headers` replace them?Also applies to: 66-69
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/runners/vercel/runner.ts` at line 29, When rebuilding a Request you currently seed headers from input.headers only, which drops any caller-provided init.headers; update the logic that constructs the Headers instance (the variable named headers) so that if input is a Request and init?.headers exists you merge init.headers into input.headers (with init.headers taking precedence), and then pass that merged Headers into new Request(...) (same fix for the analogous block around the new Request at the other spot referenced by lines 66-69); ensure you reference the variables input, init, headers and the new Request(...) call when implementing the merge.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/runners/vercel/runner.ts`:
- Line 29: When rebuilding a Request you currently seed headers from
input.headers only, which drops any caller-provided init.headers; update the
logic that constructs the Headers instance (the variable named headers) so that
if input is a Request and init?.headers exists you merge init.headers into
input.headers (with init.headers taking precedence), and then pass that merged
Headers into new Request(...) (same fix for the analogous block around the new
Request at the other spot referenced by lines 66-69); ensure you reference the
variables input, init, headers and the new Request(...) call when implementing
the merge.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 59201ccc-2d2c-47ac-becb-d52e23781446
📒 Files selected for processing (1)
src/runners/vercel/runner.ts
Summary by CodeRabbit
New Features
Bug Fixes / Behavior
Tests