From 00e071e41335266df0aba974f93632b5ca10eab2 Mon Sep 17 00:00:00 2001 From: Daisuke <42408108+da1suk8@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:34:28 +0900 Subject: [PATCH] fix(ext/workers): settle UserWorker.fetch without waiting for the request body pipe --- .../main_retired_worker_fetch/index.ts | 156 ++++++++++++++++++ .../respond-with-late-body/index.ts | 14 ++ .../respond-without-reading-body/index.ts | 5 + crates/base/tests/integration_tests.rs | 149 +++++++++++++++++ ext/workers/user_workers.js | 41 +++-- 5 files changed, 353 insertions(+), 12 deletions(-) create mode 100644 crates/base/test_cases/main_retired_worker_fetch/index.ts create mode 100644 crates/base/test_cases/respond-with-late-body/index.ts create mode 100644 crates/base/test_cases/respond-without-reading-body/index.ts diff --git a/crates/base/test_cases/main_retired_worker_fetch/index.ts b/crates/base/test_cases/main_retired_worker_fetch/index.ts new file mode 100644 index 00000000..9be122d5 --- /dev/null +++ b/crates/base/test_cases/main_retired_worker_fetch/index.ts @@ -0,0 +1,156 @@ +// Exercises `UserWorker.fetch()` with request bodies that cannot be delivered: +// `/boot` + `/stale` dispatch to a worker that has already retired +// (supabase/edge-runtime#742), `/early-response` forwards a cloned upload to +// a worker that answers without reading it (supabase/edge-runtime#737), and +// `/late-response-body` forwards a request whose body has not arrived yet to a +// worker whose response body follows its head. +console.log("main function started"); + +type UserWorker = Awaited>; + +let worker: UserWorker | null = null; + +function createWorker(name: string, workerTimeoutMs: number) { + return EdgeRuntime.userWorkers.create({ + servicePath: `./test_cases/${name}`, + memoryLimitMb: 150, + workerTimeoutMs, + cpuTimeSoftLimitMs: 10 * 60 * 1000, + cpuTimeHardLimitMs: 10 * 60 * 1000, + noModuleCache: false, + envVars: [], + }); +} + +function settle( + promise: Promise, + timeoutMs: number, + readBody = false, +): Promise> { + return Promise.race([ + promise.then( + async (res) => { + if (readBody) { + try { + return { + kind: "response", + status: res.status, + body: await res.text(), + }; + } catch (err) { + return { kind: "body-error", message: String(err) }; + } + } + + // Release the response body so the user worker sees the request end. + await res.body?.cancel(); + return { kind: "response", status: res.status }; + }, + (err) => ({ + kind: "error", + name: err?.name ?? typeof err, + message: String(err), + }), + ), + new Promise>((resolve) => + setTimeout(() => resolve({ kind: "timeout" }), timeoutMs) + ), + ]); +} + +function intHeader(req: Request, key: string, fallback: number): number { + const parsed = parseInt(req.headers.get(key) ?? ""); + return Number.isNaN(parsed) ? fallback : parsed; +} + +Deno.serve(async (req: Request) => { + const url = new URL(req.url); + + if (url.pathname === "/boot") { + // The supervisor raises the retire flag at half of the wall clock limit + // and terminates the worker when the limit has fully elapsed. + worker = await createWorker( + "sleep-5000ms", + intHeader(req, "x-worker-timeout-ms", 4000), + ); + + // Keep an in-flight request on the worker so that it stays registered in + // the pool after it retires instead of being shut down right away. + const busy = new Request(url.origin + "/", { method: "GET" }); + EdgeRuntime.applySupabaseTag(req, busy); + worker.fetch(busy).catch(() => {}); + + return new Response("ok"); + } + + if (url.pathname === "/stale") { + if (worker === null) { + return new Response("boot first", { status: 400 }); + } + + const mode = req.headers.get("x-body-mode") ?? "none"; + const settleTimeoutMs = intHeader(req, "x-settle-timeout-ms", 2000); + + let target: Request; + switch (mode) { + case "none": { + target = new Request(url.origin + "/", { method: "GET" }); + EdgeRuntime.applySupabaseTag(req, target); + break; + } + case "passthrough": { + target = req; + break; + } + case "clone": { + target = new Request(new URL(req.url), req.clone()); + EdgeRuntime.applySupabaseTag(req, target); + break; + } + default: + return new Response(`unknown mode: ${mode}`, { status: 400 }); + } + + const start = performance.now(); + const outcome = await settle(worker.fetch(target), settleTimeoutMs); + + return Response.json({ + ...outcome, + elapsedMs: Math.round(performance.now() - start), + }); + } + + // Forwards a cloned request to a worker that responds without reading the + // request body, as a relay in front of a bounded upload endpoint would. + if (url.pathname === "/early-response") { + const settleTimeoutMs = intHeader(req, "x-settle-timeout-ms", 2000); + const fresh = await createWorker("respond-without-reading-body", 60_000); + const target = new Request(new URL(req.url), req.clone()); + EdgeRuntime.applySupabaseTag(req, target); + + const start = performance.now(); + const outcome = await settle(fresh.fetch(target), settleTimeoutMs); + + return Response.json({ + ...outcome, + elapsedMs: Math.round(performance.now() - start), + }); + } + + // Forwards the inbound request as it is to a worker that answers before the + // request body has arrived, and reads the response body to the end. + if (url.pathname === "/late-response-body") { + const settleTimeoutMs = intHeader(req, "x-settle-timeout-ms", 2000); + const fresh = await createWorker("respond-with-late-body", 60_000); + + const start = performance.now(); + const outcome = await settle(fresh.fetch(req), settleTimeoutMs, true); + + return Response.json({ + ...outcome, + elapsedMs: Math.round(performance.now() - start), + }); + } + + return new Response("not found", { status: 404 }); +}); diff --git a/crates/base/test_cases/respond-with-late-body/index.ts b/crates/base/test_cases/respond-with-late-body/index.ts new file mode 100644 index 00000000..464cb2f9 --- /dev/null +++ b/crates/base/test_cases/respond-with-late-body/index.ts @@ -0,0 +1,14 @@ +// Answers immediately without reading the request body. The response body +// follows a moment later, so it is still in flight when the response head +// reaches the caller. +Deno.serve(() => { + const body = new ReadableStream({ + async start(controller) { + await new Promise((resolve) => setTimeout(resolve, 100)); + controller.enqueue(new TextEncoder().encode("payload too large")); + controller.close(); + }, + }); + + return new Response(body, { status: 413 }); +}); diff --git a/crates/base/test_cases/respond-without-reading-body/index.ts b/crates/base/test_cases/respond-without-reading-body/index.ts new file mode 100644 index 00000000..38f625a7 --- /dev/null +++ b/crates/base/test_cases/respond-without-reading-body/index.ts @@ -0,0 +1,5 @@ +// Answers immediately and never touches the request body, like an endpoint +// that rejects an upload up front based on its headers. +Deno.serve(() => { + return new Response("payload too large", { status: 413 }); +}); diff --git a/crates/base/tests/integration_tests.rs b/crates/base/tests/integration_tests.rs index b46fe6bb..24966d4e 100644 --- a/crates/base/tests/integration_tests.rs +++ b/crates/base/tests/integration_tests.rs @@ -5119,3 +5119,152 @@ async fn test_websocket_handshake_user_agent_is_stamped_with_project_ref() { [deno::versions::user_agent(Some(PROJECT_REF))] ); } + +#[tokio::test] +#[serial] +async fn test_user_worker_fetch_settles_when_worker_already_retired() { + async fn dispatch_to_retired_worker( + tb: &TestBed, + body_mode: &'static str, + ) -> serde_json::Value { + // The retire flag is raised at half of the wall clock limit (2000ms) and + // the worker is terminated once the limit (4000ms) has elapsed. + let resp = tb + .request(|b| { + b.uri("/boot") + .header("x-worker-timeout-ms", HeaderValue::from_static("4000")) + .body(Body::empty()) + .context("can't make request") + }) + .await + .unwrap(); + + assert_eq!(resp.status().as_u16(), StatusCode::OK); + + sleep(Duration::from_millis(2500)).await; + + let mut resp = tb + .request(|b| { + b.uri("/stale") + .method(Method::POST) + .header("x-body-mode", HeaderValue::from_static(body_mode)) + .header("x-settle-timeout-ms", HeaderValue::from_static("1000")) + // The body arrives after the dispatch has been rejected. A body + // that is already buffered can be handed over before the rejection, + // in which case the cloned case settles even without the fix. + .body(Body::wrap_stream(futures_util::stream::once(async { + sleep(Duration::from_millis(300)).await; + Ok::<_, io::Error>("meow") + }))) + .context("can't make request") + }) + .await + .unwrap(); + + assert_eq!(resp.status().as_u16(), StatusCode::OK); + + let bytes = to_bytes(resp.body_mut()).await.unwrap(); + + serde_json::from_slice(&bytes).unwrap() + } + + let tb = TestBedBuilder::new("./test_cases/main_retired_worker_fetch") + .with_per_worker_policy(None) + .build() + .await; + + for body_mode in ["none", "passthrough", "clone"] { + let outcome = dispatch_to_retired_worker(&tb, body_mode).await; + + assert_eq!(outcome["kind"], "error", "mode={body_mode}: {outcome}"); + assert_eq!( + outcome["name"], "WorkerAlreadyRetired", + "mode={body_mode}: {outcome}" + ); + } + + tb.exit(Duration::from_secs(TESTBED_DEADLINE_SEC)).await; +} + +#[tokio::test] +#[serial] +async fn test_user_worker_fetch_settles_when_response_arrives_before_body_is_sent( +) { + let tb = TestBedBuilder::new("./test_cases/main_retired_worker_fetch") + .with_per_worker_policy(None) + .build() + .await; + + // The second chunk is only produced after the worker has already responded, + // so piping it to the user worker fails once the response is in hand. + let chunk = "x".repeat(16 * 1024); + let body = Body::wrap_stream( + futures_util::stream::iter([Ok::<_, std::io::Error>(chunk.clone())]).chain( + futures_util::stream::once(async move { + sleep(Duration::from_millis(500)).await; + Ok(chunk) + }), + ), + ); + + let mut resp = tb + .request(|b| { + b.uri("/early-response") + .method(Method::POST) + .header("x-settle-timeout-ms", HeaderValue::from_static("2000")) + .body(body) + .context("can't make request") + }) + .await + .unwrap(); + + assert_eq!(resp.status().as_u16(), StatusCode::OK); + + let bytes = to_bytes(resp.body_mut()).await.unwrap(); + let outcome = serde_json::from_slice::(&bytes).unwrap(); + + assert_eq!(outcome["kind"], "response", "{outcome}"); + assert_eq!(outcome["status"], 413, "{outcome}"); + + tb.exit(Duration::from_secs(TESTBED_DEADLINE_SEC)).await; +} + +#[tokio::test] +#[serial] +async fn test_user_worker_fetch_relays_response_body_that_follows_the_head() { + let tb = TestBedBuilder::new("./test_cases/main_retired_worker_fetch") + .with_per_worker_policy(None) + .build() + .await; + + // The request body has a declared length and only arrives after the settle + // deadline, so it is still outstanding when the worker's response body + // follows the response head. + let body = Body::wrap_stream(futures_util::stream::once(async { + sleep(Duration::from_millis(3000)).await; + Ok::<_, io::Error>("meow") + })); + + let mut resp = tb + .request(|b| { + b.uri("/late-response-body") + .method(Method::POST) + .header("content-length", HeaderValue::from_static("4")) + .header("x-settle-timeout-ms", HeaderValue::from_static("2000")) + .body(body) + .context("can't make request") + }) + .await + .unwrap(); + + assert_eq!(resp.status().as_u16(), StatusCode::OK); + + let bytes = to_bytes(resp.body_mut()).await.unwrap(); + let outcome = serde_json::from_slice::(&bytes).unwrap(); + + assert_eq!(outcome["kind"], "response", "{outcome}"); + assert_eq!(outcome["status"], 413, "{outcome}"); + assert_eq!(outcome["body"], "payload too large", "{outcome}"); + + tb.exit(Duration::from_secs(TESTBED_DEADLINE_SEC)).await; +} diff --git a/ext/workers/user_workers.js b/ext/workers/user_workers.js index ed38cdc8..c5eec821 100644 --- a/ext/workers/user_workers.js +++ b/ext/workers/user_workers.js @@ -12,7 +12,7 @@ import { const ops = core.ops; -const { TypeError } = primordials; +const { PromisePrototypeCatch, TypeError } = primordials; const { op_user_worker_fetch_send, @@ -82,21 +82,38 @@ class UserWorker { tag.watcherRid, ); - const [requestBodyPromiseResult, responsePromiseResult] = await Promise - .allSettled([ - requestBodyPromise, - responsePromise, - ]); - - if (requestBodyPromiseResult.status === "rejected") { - // console.warn(requestBodyPromiseResult.reason); + // The request body is streamed to the user worker in the background and + // its outcome is never exposed to the caller. It must not gate the + // response either: once the request has been answered or rejected, the + // body resource is cancelled and the pipe fails on its next write. + // + // Waiting for the pipe to settle can hang forever when `body` is a branch + // of a tee'd stream (e.g. `req.clone()`), because cancelling one branch + // does not resolve until the other branch is cancelled as well. + // See https://github.com/supabase/edge-runtime/issues/742 + if (requestBodyPromise !== null) { + PromisePrototypeCatch(requestBodyPromise, () => {}); } - if (responsePromiseResult.status === "rejected") { - throw responsePromiseResult.reason; + let result; + + try { + result = await responsePromise; + } catch (err) { + // No response is coming, so there is nothing left to deliver the body + // to. + // + // The resource is deliberately left open once the worker has answered: + // closing it ends the request body short of its declared length, which + // aborts the connection that the response body is still arriving on. + // The pipe closes it when it finishes or fails. + if (requestBodyRid !== null) { + core.tryClose(requestBodyRid); + } + + throw err; } - const result = responsePromiseResult.value; const response = { headers: result.headers, status: result.status,