Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

3.0 KB
Raw Blame
import type { DeferredFetch } from "@reactive-resume/utils/deferred-request";
import { t } from "@lingui/core/macro";
import { getAccountId } from "@/libs/auth/account-scope";

let stagingUnavailable = false;

/** Large RPC bodies bypass the hosting ingress limit while retaining their original wire format. */
export async function rpcFetch(
	input: RequestInfo | URL,
	init?: RequestInit,
	options?: { context: { defer?: DeferredFetch; aiDestination?: string } },
): Promise<Response> {
	const defer = options?.context.defer;
	const request = new Request(input, { ...init, credentials: "include" });
	request.headers.set("x-client-timezone", Intl.DateTimeFormat().resolvedOptions().timeZone);
	// A call-bound account (captured when the procedure was invoked) wins; a direct fetch gets the live scope.
	if (!request.headers.has("x-account-id")) {
		const accountId = getAccountId();
		if (accountId) request.headers.set("x-account-id", accountId);
	}
	if (request.method !== "POST") return fetch(request);
	// Buffer as bytes: a teed stream needs duplex mode, and a Blob body is not visible to DevTools/CDP.
	const body = await request.arrayBuffer();
	const sendDirect = () => {
		if (defer && request.headers.get("x-account-id") !== getAccountId()) throw new DOMException("", "AbortError");
		return fetch(request.url, {
			method: "POST",
			headers: request.headers,
			body,
			// Cancel must disconnect AI work; ordinary small writes still survive leaving the page.
			keepalive: !options?.context.aiDestination && body.byteLength <= 60 * 1024,
			credentials: "include",
			signal: request.signal,
		});
	};
	if (defer) {
		if (body.byteLength > 60 * 1024) throw new Error("Request exceeds the Undo dispatch limit");
		return defer(sendDirect);
	}
	if (stagingUnavailable || body.byteLength < 3 * 1024 * 1024) return sendDirect();

	const url = new URL(request.url);
	const prepared = await fetch("/api/storage/stage", {
		method: "POST",
		credentials: "include",
		signal: request.signal,
		headers: { "content-type": "application/json" },
		body: JSON.stringify({
			path: `${url.pathname}${url.search}`,
			contentType: request.headers.get("content-type"),
			size: body.byteLength,
		}),
	});
	// Docker has no staging endpoint; send large bodies directly from now on.
	if (prepared.status === 404) {
		stagingUnavailable = true;
		return sendDirect();
	}
	if (!prepared.ok) throw new Error(t`Couldn't prepare the upload (${prepared.status}). Try again.`);
	const stage = (await prepared.json()) as { id: string; url: string };
	const uploaded = await fetch(stage.url, {
		method: "PUT",
		body,
		headers: { "content-type": "application/octet-stream" },
		signal: request.signal,
	});
	if (!uploaded.ok) throw new Error(t`The upload didn't finish (${uploaded.status}). Try again.`);
	const headers = new Headers(request.headers);
	headers.set("x-resume-staged-body", stage.id);
	headers.delete("content-length");
	return fetch(request.url, { method: request.method, headers, credentials: "include", signal: request.signal });
}