Skip to content

fix: restore Cloudflare Worker routes after the v3.0.0 startup crash - #248

Merged
jaredwray merged 1 commit into
mainfrom
cursor/fix-worker-startup-eval-b4c3
Oct 20, 2026
Merged

jaredwray merged 1 commit into
mainfrom
cursor/fix-worker-startup-eval-b4c3

Conversation

@jaredwray

Copy link
Copy Markdown
Owner

Please check if the PR fulfills these requirements

  • Followed the Contributing and Code of Conduct guidelines.
  • Tests for the changes have been added (for bug fixes/features) with 100% code coverage.

What kind of change does this PR introduce?

Bug fix. After v3.0.0 (deploy-site run 39346805553, commit 266157b, Worker version cdaa6cb9) every Worker route on mockhttp.org returned Cloudflare error 1101.

Root cause

PR #247 moved listenWorkerApp(await createWorkerApp(env)) from module load into the first fetch, so it could read env.MONGODB_URI. Fastify compiles routes with new Function() (HandlerStorage._compileCreateParamsObject → Router.all → _setNotFoundHandler). workerd allows that only while the isolate is starting. On the first request it throws:

Uncaught EvalError: Code generation from strings disallowed for this context

That uncaught exception is Cloudflare 1101. Static assets never enter the Worker, so they kept loading.

Fix

  • Start Fastify again at module load. import { env } from "cloudflare:workers" supplies MONGODB_URI during startup.
  • Do not construct @keyv/mongo until the first bin operation. Its constructor calls MongoClient.connect(), and workerd rejects that network I/O outside a request. With no URI, bins stay in memory as before.
  • Bin URLs no longer trust request.protocol / x-forwarded-proto. The Node server inside the Worker is plain HTTP, and the bridge rewrites x-forwarded-proto to that socket. The Worker stamps x-mockhttp-forwarded-proto from the request URL, and POST /bins uses that for the public capture URL.

http vs https

http:// in the local experiment was the wrangler dev listener, not a wrong host. Default wrangler dev is HTTP, the Worker request URL is http://mockhttp.org/..., and the bin URL correctly follows that (http://mockhttp.org/b/<id>, not http://127.0.0.1:3000).

An HTTPS edge is different. With wrangler's HTTPS dev listener, and without this stamp, POST /bins still returned http://mockhttp.org/b/<id> because Fastify only saw the plain Node socket. With the stamp, the same request returns https://mockhttp.org/b/<id>. Production Workers receive https://mockhttp.org/... as request.url, so hosted bin URLs are https.

Verification

Reproduced the 1101 class of failure under wrangler 4.127.0 / workerd before the change: GET /get returned 500 with the EvalError above.

After the change, pnpm test passed: 45 files, 536 tests, 100% lines. The new workerd test (test/worker-runtime.test.ts) covers /get, /ip, GET /bins, POST /bins, and POST /b/<id>.

Atlas itself was not exercised. This environment has no MONGODB_URI and no MongoDB server. Under workerd, MONGODB_URI=mongodb://127.0.0.1:1/mockhttp (nothing listening) still serves GET /get with 200, and POST /bins returns 500 from the failed connect rather than EvalError. That shows the client stays closed during startup and connects on the bin write. A successful Atlas round trip still needs a real cluster.

Open in Web Open in Cursor 

Fastify compiles routes with new Function(), which workerd only allows
while the isolate is starting. v3.0.0 moved listen() into the first
fetch so it could read MONGODB_URI, and every route then crashed with
EvalError (Cloudflare 1101). Read the URI from cloudflare:workers at
module load, and construct the Mongo client on the first bin operation
because @keyv/mongo connects from its constructor.

Bin capture URLs followed the plain Node socket, so an https edge
request produced an http:// URL. Stamp the Worker request scheme and
use it when building the public bin URL.

Co-authored-by: Jared Wray <me@jaredwray.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T00:56:32.820180Z 6405a3c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@socket-security

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedwrangler@​4.127.0981009296100

View full report

Comment thread test/worker-runtime.test.ts Dismissed
@codecov

codecov Bot commented Oct 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (266157b) to head (6405a3c).

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #248   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         1404      1436   +32     
  Branches       287       300   +13     
=========================================
+ Hits          1404      1436   +32     

☔ 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.

@jaredwray
jaredwray merged commit 234ae0e into main Oct 20, 2026
13 checks passed
@jaredwray
jaredwray deleted the cursor/fix-worker-startup-eval-b4c3 branch October 20, 2026 00:53

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6405a3c7fa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

});

it("builds a capture URL from the forwarded protocol chain", () => {
expect(binCaptureUrl("http, https", "http", "mockhttp.org", "abc")).toBe(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exercise bin URL cases through POST /bins

Remove this direct helper test. Cover its cases through POST /bins. No production caller uses the binCaptureUrl export.

AGENTS.md reference: AGENTS.md:L66-L73

Useful? React with 👍 / 👎.

Comment thread test/worker.test.ts
createWorkerApp,
handleWorkerFetch,
listenWorkerApp,
requestWithPublicProtocol,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Test the protocol marker through the Worker boundary

Remove these direct helper tests. Cover these cases through the Worker fetch boundary. No production caller uses the requestWithPublicProtocol export.

AGENTS.md reference: AGENTS.md:L66-L73

Useful? React with 👍 / 👎.

Comment thread worker/index.ts
await listening;
}
// Fastify compiles routes with `new Function()`. workerd allows that only
// while the isolate is starting, so the server has to listen at module load.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use the simple present in this new comment

Replace is starting with a simple-present phrase. The repository prohibits this verb form in new comments.

AGENTS.md reference: AGENTS.md:L51-L52

Useful? React with 👍 / 👎.

const raw = Array.isArray(forwardedProto)
? forwardedProto.join(",")
: forwardedProto;
const forwarded = raw?.split(",").at(-1)?.trim().toLowerCase();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the client protocol from the proxy chain

When an HTTPS edge appends an internal HTTP hop as https, http, .at(-1) selects http. POST /bins then returns the wrong public scheme. Read the first client protocol entry instead.

Useful? React with 👍 / 👎.

Comment thread worker/app.ts
}

const headers = new Headers(request.headers);
headers.set(PUBLIC_PROTOCOL_HEADER, protocol);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the internal protocol marker out of echoed headers

For each Worker call, this marker enters Fastify's request.headers; headersRoute and the HTTP method routes return that map. Their responses report a header that the client did not send. Carry the scheme outside the echoed header map.

Useful? React with 👍 / 👎.

import { type Unstable_DevWorker, unstable_dev } from "wrangler";

// wrangler's HTTPS dev listener uses a self-signed certificate.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore TLS verification after the Worker test

If Vitest runs another file in this process, this module-level assignment leaves TLS verification off after this suite ends. That file can accept an invalid certificate. Restore the prior value in afterAll.

Useful? React with 👍 / 👎.

});
const body = await created.text();
expect(created.status, body).toBe(500);
expect(body).not.toContain("Code generation from strings");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Assert the Mongo failure at an observable boundary

Replace this assertion. MockHttpBins.save() wraps every adapter failure with a fixed message, so Fastify does not put the cause in this response. This check also passes for the prohibited EvalError. Assert the error at a boundary that exposes it.

AGENTS.md reference: AGENTS.md:L75-L77

Useful? React with 👍 / 👎.

@jaredwray jaredwray mentioned this pull request Oct 28, 2026
4 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.

3 participants