Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions crates/base/test_cases/main_retired_worker_fetch/index.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof EdgeRuntime.userWorkers.create>>;

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<Response>,
timeoutMs: number,
readBody = false,
): Promise<Record<string, unknown>> {
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<Record<string, unknown>>((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 });
});
14 changes: 14 additions & 0 deletions crates/base/test_cases/respond-with-late-body/index.ts
Original file line number Diff line number Diff line change
@@ -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<Uint8Array>({
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 });
});
5 changes: 5 additions & 0 deletions crates/base/test_cases/respond-without-reading-body/index.ts
Original file line number Diff line number Diff line change
@@ -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 });
});
149 changes: 149 additions & 0 deletions crates/base/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<serde_json::Value>(&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::<serde_json::Value>(&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;
}
41 changes: 29 additions & 12 deletions ext/workers/user_workers.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {

const ops = core.ops;

const { TypeError } = primordials;
const { PromisePrototypeCatch, TypeError } = primordials;

const {
op_user_worker_fetch_send,
Expand Down Expand Up @@ -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,
Expand Down
Loading