Files
Genarrative/apps/ai-game-creator-shell/src/services/clientHttp.ts
T
kdletters 97b0231afc
Project CI / Frontend tests (push) Successful in 4m33s
Project CI / Repository checks (push) Successful in 4m48s
Project CI / Backend tests (push) Successful in 8m38s
Project CI / Native shell tests (push) Successful in 18m37s
优化 AGC 会话恢复超时与 Runner 启动校验 (#253)
## 变更内容

- 增加启动会话恢复阶段、等待时间和可操作错误提示。
- 为客户端 HTTP 请求增加默认超时、AbortController 取消和可选长请求豁免。
- 会话恢复失败后提供重试,并隔离旧请求的迟到结果。
- 让 Runner 启动探测严格遵守剩余启动时间预算。
- 补充前端、HTTP、Runner 定向测试并同步技术方案。

## 验证

- npm run typecheck --workspace @genarrative/ai-game-creator-shell
- npm run check:encoding
- clientHttp 定向测试
- AuthenticatedClient 定向测试
- Runner 启动探测测试
- cargo fmt --check
- git diff --check

Reviewed-on: http://192.168.35.82/git/GenarrativeAI/Genarrative/pulls/253
Co-authored-by: kdletters <kdletters@qq.com>
Co-committed-by: kdletters <kdletters@qq.com>
2026-09-02 18:15:38 +08:00

302 lines
9.5 KiB
TypeScript

import { fetch as tauriHttpFetch } from '@tauri-apps/plugin-http';
export const AGC_DEVELOPMENT_API_BASE_URL = 'https://dev.genarrative.world';
export const AGC_RELEASE_API_BASE_URL = 'https://www.genarrative.world';
export const AGC_CLIENT_MARKER_HEADER = 'X-Genarrative-Client';
export const AGC_CLIENT_MARKER_VALUE = 'agc';
/**
* Upper bound for the initial network transaction (DNS/connect/response
* headers). Callers may override this for a request that legitimately needs
* more time; the default prevents auth/bootstrap requests from hanging
* forever when the selected server or proxy is unavailable.
*/
export const CLIENT_HTTP_DEFAULT_TIMEOUT_MS = 15_000;
export class ClientHttpTimeoutError extends Error {
readonly code = 'CLIENT_HTTP_TIMEOUT';
readonly timeoutMs: number;
readonly url: string;
constructor(url: string, timeoutMs: number) {
super(`请求超时(${timeoutMs} ms):${url}`);
this.name = 'ClientHttpTimeoutError';
this.timeoutMs = timeoutMs;
this.url = url;
}
}
export function isClientHttpTimeoutError(
error: unknown,
): error is ClientHttpTimeoutError {
return error instanceof ClientHttpTimeoutError;
}
export type ClientServerPreset = 'release' | 'dev' | 'custom';
export type ClientServerSelection = {
preset: ClientServerPreset;
customBaseUrl: string;
};
const CLIENT_SERVER_SELECTION_STORAGE_KEY =
'genarrative.client.server-selection.v1';
function defaultClientServerPreset(): Exclude<ClientServerPreset, 'custom'> {
return import.meta.env.DEV ? 'dev' : 'release';
}
function isClientServerPreset(value: unknown): value is ClientServerPreset {
return value === 'release' || value === 'dev' || value === 'custom';
}
export function normalizeClientServerBaseUrl(value: string) {
const normalized = value.trim().replace(/\/+$/u, '');
let parsed: URL;
try {
parsed = new URL(normalized);
} catch {
throw new Error('服务器地址无效');
}
if (
!['http:', 'https:'].includes(parsed.protocol) ||
parsed.username ||
parsed.password ||
parsed.pathname !== '/' ||
parsed.search ||
parsed.hash
) {
throw new Error('服务器地址必须是纯 HTTP(S) 地址');
}
const isLoopback = ['localhost', '127.0.0.1', '[::1]'].includes(
parsed.hostname,
);
if (parsed.protocol === 'http:' && !isLoopback) {
throw new Error('非本机服务器必须使用 HTTPS');
}
return normalized;
}
function readStoredClientServerSelection(): ClientServerSelection {
const fallback: ClientServerSelection = {
preset: defaultClientServerPreset(),
customBaseUrl: '',
};
if (typeof window === 'undefined') return fallback;
try {
const raw = window.localStorage.getItem(
CLIENT_SERVER_SELECTION_STORAGE_KEY,
);
if (!raw) return fallback;
const parsed = JSON.parse(raw) as {
preset?: unknown;
customBaseUrl?: unknown;
};
if (!isClientServerPreset(parsed.preset)) return fallback;
const customBaseUrl =
typeof parsed.customBaseUrl === 'string' ? parsed.customBaseUrl : '';
if (parsed.preset === 'custom') {
normalizeClientServerBaseUrl(customBaseUrl);
}
return { preset: parsed.preset, customBaseUrl };
} catch {
return fallback;
}
}
export function getClientServerSelection() {
return readStoredClientServerSelection();
}
export function setClientServerSelection(
selection: ClientServerSelection,
): ClientServerSelection {
const next: ClientServerSelection = {
preset: selection.preset,
customBaseUrl:
selection.preset === 'custom'
? normalizeClientServerBaseUrl(selection.customBaseUrl)
: selection.customBaseUrl.trim(),
};
if (typeof window !== 'undefined') {
window.localStorage.setItem(
CLIENT_SERVER_SELECTION_STORAGE_KEY,
JSON.stringify(next),
);
}
return next;
}
export function resetClientServerSelectionForTests() {
if (typeof window !== 'undefined') {
window.localStorage.removeItem(CLIENT_SERVER_SELECTION_STORAGE_KEY);
}
}
export function getClientServerBaseUrl(
selection: ClientServerSelection = getClientServerSelection(),
) {
if (selection.preset === 'release') return AGC_RELEASE_API_BASE_URL;
if (selection.preset === 'dev') return AGC_DEVELOPMENT_API_BASE_URL;
return normalizeClientServerBaseUrl(selection.customBaseUrl);
}
type ClientHttpContext = {
isDevelopment: boolean;
isTauri: boolean;
pageProtocol: string;
mode?: string;
serverBaseUrl?: string;
};
type ClientHttpTarget = {
transport: 'web' | 'tauri-http';
url: string;
};
function withAgcClientMarker(init: RequestInit): RequestInit {
const headers = new Headers(init.headers);
headers.set(AGC_CLIENT_MARKER_HEADER, AGC_CLIENT_MARKER_VALUE);
return { ...init, headers };
}
function currentClientHttpContext(): ClientHttpContext {
return {
isDevelopment: import.meta.env.DEV,
isTauri: typeof window !== 'undefined' && Boolean(window.__TAURI__),
pageProtocol: typeof window === 'undefined' ? '' : window.location.protocol,
mode: import.meta.env.MODE,
};
}
export function resolveClientHttpTarget(
url: string,
context: ClientHttpContext = currentClientHttpContext(),
): ClientHttpTarget {
// Existing unit fixtures omit mode; retain the Vite-relative transport for
// them while real development/release clients use the selected server.
if (
!context.serverBaseUrl &&
(context.mode === 'test' || (!context.mode && context.isDevelopment))
) {
return { transport: 'web', url };
}
const serverBaseUrl =
context.serverBaseUrl ?? getClientServerBaseUrl(getClientServerSelection());
const target = new URL(url, `${serverBaseUrl}/`);
if (target.origin !== serverBaseUrl) {
throw new Error('请求目标不在当前选择的服务器范围内');
}
if (!context.isTauri) {
return { transport: 'web', url: target.toString() };
}
return { transport: 'tauri-http', url: target.toString() };
}
export async function fetchClientHttp(
url: string,
init: RequestInit,
options: {
serverBaseUrl?: string;
/** Set to null to opt out for a long-running request. */
timeoutMs?: number | null;
} = {},
): Promise<Response> {
const currentContext = currentClientHttpContext();
const serverBaseUrl = options.serverBaseUrl
? normalizeClientServerBaseUrl(options.serverBaseUrl)
: undefined;
// Unit fixtures intentionally use the relative Vite transport. Real clients bind every
// auth transaction to the explicit origin captured before its first request.
const target = resolveClientHttpTarget(
url,
currentContext.mode === 'test'
? currentContext
: { ...currentContext, serverBaseUrl },
);
const markedInit = withAgcClientMarker(init);
// Always use a private controller so an internal timeout cannot mutate a
// caller-owned AbortSignal. The caller's signal is still propagated in
// both directions, preserving normal AbortError behaviour for user aborts.
const timeoutMs =
options.timeoutMs === undefined
? CLIENT_HTTP_DEFAULT_TIMEOUT_MS
: options.timeoutMs;
if (timeoutMs === null) {
if (target.transport === 'tauri-http') {
return tauriHttpFetch(target.url, markedInit);
}
return fetch(target.url, markedInit);
}
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new RangeError('请求超时时间必须是大于 0 的有限数值');
}
const controller = new AbortController();
let timedOut = false;
const callerSignal = markedInit.signal;
const forwardCallerAbort = () => {
// AbortSignal.reason is available in modern browsers/Tauri WebViews. The
// fallback keeps compatibility with older runtimes and test doubles.
const reason = callerSignal?.reason;
try {
controller.abort(reason);
} catch {
controller.abort();
}
};
if (callerSignal) {
if (callerSignal.aborted) {
forwardCallerAbort();
} else {
callerSignal.addEventListener('abort', forwardCallerAbort, {
once: true,
});
}
}
const requestInit = { ...markedInit, signal: controller.signal };
let request: Promise<Response>;
try {
// Keep invocation synchronous so an already-aborted caller signal is
// observed by transports that only subscribe to `abort` events.
const responsePromise =
target.transport === 'tauri-http'
? tauriHttpFetch(target.url, requestInit)
: fetch(target.url, requestInit);
request = Promise.resolve(responsePromise);
} catch (error) {
callerSignal?.removeEventListener('abort', forwardCallerAbort);
throw error;
}
// A timed-out request is intentionally not awaited after the race settles,
// but transports may still reject when the abort reaches them. Attach a
// sink to avoid an unhandled rejection while keeping the original promise
// in the race for normal errors.
void request.catch(() => undefined);
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timeoutHandle = setTimeout(() => {
timedOut = true;
controller.abort();
reject(new ClientHttpTimeoutError(target.url, timeoutMs));
}, timeoutMs);
});
try {
return await Promise.race([request, timeout]);
} catch (error) {
// Some transports reject with a generic error after AbortController.abort;
// expose a stable, actionable error to auth/bootstrap callers.
if (timedOut) {
throw new ClientHttpTimeoutError(target.url, timeoutMs);
}
throw error;
} finally {
if (timeoutHandle !== undefined) clearTimeout(timeoutHandle);
callerSignal?.removeEventListener('abort', forwardCallerAbort);
}
}