Skip to content
Merged
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
12 changes: 12 additions & 0 deletions packages/tanstack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,18 @@ rendering or hydration recovery instead.
and on the server, reuses a fetched manifest for 30 seconds (`maxAgeMs`), and
rejects when the manifest is unreachable or does not list the expose.

Remote manifest fetches throw `RemoteFetchError` from the `runtime` entry. Its
`code` distinguishes network, timeout, HTTP, response-size, and JSON parse
failures. HTTP failures preserve `status`, `statusText`, and a normalized
`bodyPreview` of at most 240 characters; `retryable` is true for network,
timeout, and transient HTTP failures.

A timeout used to reject with the raw `AbortError`. It now rejects with a
`RemoteFetchError` whose `code` is `TANSTACK-REMOTE-FETCH-TIMEOUT`, and the
`AbortError` is its `cause`. `RemoteEntryError.cause` is that `RemoteFetchError`
too when a server entry cannot be fetched, so check `code` instead of
`name === "AbortError"`.

## Remote server functions

A remote's exposed modules can call the remote's `createServerFn`
Expand Down
1 change: 1 addition & 0 deletions packages/tanstack/rslib.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { defineConfig } from "@rslib/core";
const entry = {
index: "./src/index.ts",
"node-entry-loader": "./src/node-entry-loader.ts",
"remote-errors": "./src/remote-errors.ts",
"remote-fetch": "./src/remote-fetch.ts",
rsbuild: "./src/rsbuild.ts",
runtime: "./src/runtime.ts",
Expand Down
72 changes: 59 additions & 13 deletions packages/tanstack/src/node-entry-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { tanstackStartSharedPackages } from "./shared";
import {
DEFAULT_REMOTE_FETCH_TIMEOUT_MS,
fetchRemoteText,
RemoteFetchError,
type RemoteFetchOptions,
} from "./remote-fetch";
import { REMOTE_ERROR_CODES, isRetryableHttpStatus, type RemoteErrorCode } from "./remote-errors";
export type { RemoteFetchOptions } from "./remote-fetch";

type LoadEntryArgs = Parameters<NonNullable<ModuleFederationRuntimePlugin["loadEntry"]>>[0];
Expand Down Expand Up @@ -32,21 +34,41 @@ export interface NodeEntryLoaderOptions extends RemoteFetchOptions {
strategy?: "temp-file" | "vm";
}

/** A remote's server entry failed to load. `phase` says which step failed; `cause` keeps the original error. */
/**
* A remote's server entry failed to load. `phase` says which step failed; `cause` keeps the
* original error, which is a `RemoteFetchError` whenever the entry's own fetch failed.
*/
export class RemoteEntryError extends Error {
readonly code: RemoteErrorCode;
readonly phase: "fetch" | "evaluate" | "loader";
readonly remote: string;
readonly url: string;
readonly retryable: boolean;

constructor(
message: string,
options: { cause?: unknown; phase: RemoteEntryError["phase"]; remote: string; url: string },
options: {
cause?: unknown;
code?: RemoteErrorCode;
phase: RemoteEntryError["phase"];
remote: string;
url: string;
retryable?: boolean;
},
) {
super(message, { cause: options.cause });
this.name = "RemoteEntryError";
this.code =
options.code ??
(options.phase === "fetch"
? REMOTE_ERROR_CODES.remoteFetchNetwork
: options.phase === "evaluate"
? REMOTE_ERROR_CODES.remoteEntryEvaluate
: REMOTE_ERROR_CODES.remoteEntryLoader);
this.phase = options.phase;
this.remote = options.remote;
this.url = options.url;
this.retryable = options.retryable ?? false;
}
}

Expand Down Expand Up @@ -172,6 +194,8 @@ async function loadCommonJsEntry(
`Could not fetch the server entry of remote "${name}" from ${entry}.`,
{
cause,
code: cause instanceof RemoteFetchError ? cause.code : undefined,
retryable: cause instanceof RemoteFetchError ? cause.retryable : undefined,
phase: "fetch",
remote: name,
url: entry,
Expand Down Expand Up @@ -242,7 +266,7 @@ type ViteSsrEntryLoaderModule = {
fetchMaxBytes?: number;
}) => ModuleFederationRuntimePlugin;
revalidate?: (remoteEntryUrl?: string) => void;
SsrEntryHttpError?: new (...args: never[]) => Error;
SsrEntryHttpError?: new (...args: never[]) => Error & { status?: number };
};

type ViteLoader = {
Expand Down Expand Up @@ -333,34 +357,56 @@ async function loadModuleEntry(args: LoadEntryArgs, options: NodeEntryLoaderOpti
: await viteLoader.plugin.loadEntry?.(args);
} catch (cause) {
const { httpError } = viteLoader;
const status = httpError && cause instanceof httpError ? cause.status : undefined;
throw new RemoteEntryError(
`Could not load the server entry of remote "${name}" from ${entry}.`,
{
cause,
phase: httpError && cause instanceof httpError ? "fetch" : "evaluate",
remote: name,
url: entry,
...(httpError && cause instanceof httpError
? typeof status === "number"
? { code: REMOTE_ERROR_CODES.remoteFetchHttp, retryable: isRetryableHttpStatus(status) }
: { code: REMOTE_ERROR_CODES.remoteFetchNetwork, retryable: true }
: {}),
},
);
}
// Without an entry the runtime would try its own Node loader, which cannot load ES
// modules without Node flags. Report the failure instead. The Vite loader returns
// nothing for an unreachable remote, so tell that case apart.
if (!remoteEntry) {
const reachable = await fetch(entry, {
// A status means the remote answered; an error means it never did.
const probe = await fetch(entry, {
method: "HEAD",
...requestOptions(options.fetchTimeoutMs),
}).then(
(response) => response.ok,
() => false,
);
throw new RemoteEntryError(
reachable
? `@module-federation/vite could not load the server entry of remote "${name}" ` +
`from ${entry}; its warnings have the cause.`
: `Could not reach remote "${name}" at ${entry}.`,
{ phase: reachable ? "loader" : "fetch", remote: name, url: entry },
(response) => ({ ok: response.ok, status: response.status }),
(cause: unknown) => ({ cause, ok: false, status: undefined }),
);
if (probe.ok) {
throw new RemoteEntryError(
`@module-federation/vite could not load the server entry of remote "${name}" ` +
`from ${entry}; its warnings have the cause.`,
{ phase: "loader", remote: name, url: entry },
);
}
const timedOut =
"cause" in probe && probe.cause instanceof Error && probe.cause.name === "TimeoutError";
throw new RemoteEntryError(`Could not reach remote "${name}" at ${entry}.`, {
cause: "cause" in probe ? probe.cause : undefined,
code:
probe.status !== undefined
? REMOTE_ERROR_CODES.remoteFetchHttp
: timedOut
? REMOTE_ERROR_CODES.remoteFetchTimeout
: REMOTE_ERROR_CODES.remoteFetchNetwork,
phase: "fetch",
remote: name,
url: entry,
retryable: probe.status === undefined || isRetryableHttpStatus(probe.status),
});
}
return remoteEntry;
}
Expand Down
30 changes: 30 additions & 0 deletions packages/tanstack/src/remote-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export const REMOTE_ERROR_CODES = {
remoteFetchNetwork: "TANSTACK-REMOTE-FETCH-NETWORK",
remoteFetchTimeout: "TANSTACK-REMOTE-FETCH-TIMEOUT",
remoteFetchHttp: "TANSTACK-REMOTE-FETCH-HTTP",
remoteFetchBodyTooLarge: "TANSTACK-REMOTE-FETCH-BODY-TOO-LARGE",
remoteFetchParse: "TANSTACK-REMOTE-FETCH-PARSE",
remoteEntryEvaluate: "TANSTACK-REMOTE-ENTRY-EVALUATE",
remoteEntryLoader: "TANSTACK-REMOTE-ENTRY-LOADER",
} as const;

export type RemoteErrorCode = (typeof REMOTE_ERROR_CODES)[keyof typeof REMOTE_ERROR_CODES];

export const REMOTE_ERROR_DESCRIPTIONS: Record<RemoteErrorCode, string> = {
[REMOTE_ERROR_CODES.remoteFetchNetwork]: "A remote resource could not be reached.",
[REMOTE_ERROR_CODES.remoteFetchTimeout]: "A remote request did not complete before the timeout.",
[REMOTE_ERROR_CODES.remoteFetchHttp]: "A remote resource returned an HTTP error.",
[REMOTE_ERROR_CODES.remoteFetchBodyTooLarge]:
"A remote response exceeded the configured size limit.",
[REMOTE_ERROR_CODES.remoteFetchParse]: "A remote response could not be parsed.",
[REMOTE_ERROR_CODES.remoteEntryEvaluate]: "A remote server entry could not be evaluated.",
[REMOTE_ERROR_CODES.remoteEntryLoader]: "A remote server entry loader could not load the entry.",
};

export function isRetryableHttpStatus(status: number): boolean {
return status === 408 || status === 425 || status === 429 || status >= 500;
}

export function errorMessage(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
153 changes: 147 additions & 6 deletions packages/tanstack/src/remote-fetch.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,50 @@
import {
REMOTE_ERROR_CODES,
errorMessage,
isRetryableHttpStatus,
type RemoteErrorCode,
} from "./remote-errors";

export type RemoteFetchOptions = {
/** Maximum time for the request and response body to complete. Defaults to 10 seconds. */
fetchTimeoutMs?: number;
/** Maximum response body size in bytes. Defaults to 10 MiB. Set to 0 to disable. */
fetchMaxBytes?: number;
};

export type { RemoteErrorCode } from "./remote-errors";

export class RemoteFetchError extends Error {
readonly code: RemoteErrorCode;
readonly url: string;
readonly status?: number;
readonly statusText?: string;
readonly bodyPreview?: string;
readonly retryable: boolean;

constructor(
message: string,
options: {
cause?: unknown;
code: RemoteErrorCode;
url: string;
status?: number;
statusText?: string;
bodyPreview?: string;
retryable: boolean;
},
) {
super(message, { cause: options.cause });
this.name = "RemoteFetchError";
this.code = options.code;
this.url = options.url;
this.status = options.status;
this.statusText = options.statusText;
this.bodyPreview = options.bodyPreview;
this.retryable = options.retryable;
}
}

export const DEFAULT_REMOTE_FETCH_TIMEOUT_MS = 10_000;
export const DEFAULT_REMOTE_FETCH_MAX_BYTES = 10 * 1024 * 1024;

Expand All @@ -16,18 +56,46 @@ export async function fetchRemoteText(
const timeoutMs = options.fetchTimeoutMs ?? DEFAULT_REMOTE_FETCH_TIMEOUT_MS;
const maxBytes = options.fetchMaxBytes ?? DEFAULT_REMOTE_FETCH_MAX_BYTES;
const controller = timeoutMs === 0 ? undefined : new AbortController();
const timeout = controller ? setTimeout(() => controller.abort(), timeoutMs) : undefined;
let timedOut = false;
const timeout = controller
? setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs)
: undefined;

try {
const response = await fetch(url, controller ? { signal: controller.signal } : undefined);
if (!response.ok) throw new Error(`${url} responded with HTTP ${response.status}.`);
let response: Response;
try {
response = await fetch(url, controller ? { signal: controller.signal } : undefined);
} catch (cause) {
throw fetchFailure(url, cause, timedOut ? timeoutMs : undefined);
}

if (!response.ok) {
// The status is already known, so a slow or stalled body must not delay or reclassify it.
const bodyPreview = await readBodyPreview(response);
throw new RemoteFetchError(`${url} responded with HTTP ${response.status}.`, {
bodyPreview,
code: REMOTE_ERROR_CODES.remoteFetchHttp,
retryable: isRetryableHttpStatus(response.status),
status: response.status,
statusText: response.statusText,
url,
});
}

const contentLength = response.headers.get("content-length");
if (maxBytes > 0 && contentLength && Number(contentLength) > maxBytes) {
await response.body?.cancel();
throw new Error(
throw new RemoteFetchError(
`${url} response exceeds the maximum size of ${maxBytes} bytes ` +
`(content-length: ${contentLength}).`,
{
code: REMOTE_ERROR_CODES.remoteFetchBodyTooLarge,
retryable: false,
url,
},
);
}

Expand Down Expand Up @@ -55,6 +123,9 @@ export async function fetchRemoteText(
await reader.cancel().catch(() => undefined);
throw error;
}
} catch (cause) {
if (cause instanceof RemoteFetchError) throw cause;
throw fetchFailure(url, cause, timedOut ? timeoutMs : undefined);
} finally {
if (timeout !== undefined) clearTimeout(timeout);
}
Expand All @@ -69,14 +140,84 @@ export async function fetchRemoteJson<T>(
try {
return JSON.parse(text) as T;
} catch (cause) {
throw new Error(`Could not parse the JSON response from ${url}.`, { cause });
throw new RemoteFetchError(`Could not parse the JSON response from ${url}.`, {
cause,
code: REMOTE_ERROR_CODES.remoteFetchParse,
retryable: false,
url,
});
}
}

function assertResponseSize(url: string, bytes: number, maxBytes: number) {
if (maxBytes > 0 && bytes > maxBytes) {
throw new Error(
throw new RemoteFetchError(
`${url} response exceeds the maximum size of ${maxBytes} bytes (received: ${bytes}).`,
{
code: REMOTE_ERROR_CODES.remoteFetchBodyTooLarge,
retryable: false,
url,
},
);
}
}

/** A request that failed without a usable response: it timed out, or the remote was unreachable. */
function fetchFailure(url: string, cause: unknown, timedOutAfterMs: number | undefined) {
return timedOutAfterMs === undefined
? new RemoteFetchError(`Could not reach ${url}: ${errorMessage(cause)}`, {
cause,
code: REMOTE_ERROR_CODES.remoteFetchNetwork,
retryable: true,
url,
})
: new RemoteFetchError(`${url} did not complete within ${timedOutAfterMs} ms.`, {
cause,
code: REMOTE_ERROR_CODES.remoteFetchTimeout,
retryable: true,
url,
});
}

const MAX_BODY_PREVIEW = 240;
// Whitespace is collapsed, so an indented error page needs more raw text than the preview keeps.
const MAX_BODY_PREVIEW_BYTES = 16 * 1024;
const BODY_PREVIEW_TIMEOUT_MS = 1_000;

/** Best effort: returns what arrived before the deadline and never rejects. */
async function readBodyPreview(response: Response): Promise<string | undefined> {
if (!response.body) return undefined;

const reader = response.body.getReader();
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
// Cancelling settles a pending read, so a body that stalls cannot hold the error back.
const deadline = setTimeout(() => {
void reader.cancel().catch(() => undefined);
}, BODY_PREVIEW_TIMEOUT_MS);
try {
while (bytes < MAX_BODY_PREVIEW_BYTES && previewCodePoints(text).length < MAX_BODY_PREVIEW) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
text += decoder.decode(value, { stream: true });
}
text += decoder.decode();
} catch {
// Keep whatever was read before the body failed or the request timed out.
} finally {
clearTimeout(deadline);
await reader.cancel().catch(() => undefined);
}
return normalizePreview(text);
}

/** Collapsed text by code point, so the limit never splits a surrogate pair. */
function previewCodePoints(text: string) {
return Array.from(text.replace(/\s+/g, " ").trim());
}

function normalizePreview(text: string): string | undefined {
return previewCodePoints(text).slice(0, MAX_BODY_PREVIEW).join("") || undefined;
}
Loading