e3682fd06f
Project CI / AI game creator shell Rust shard 4/4 (push) Successful in 7m31s
Project CI / AI game creator shell Rust shard 1/4 (push) Successful in 7m32s
Project CI / AI game creator shell Rust shard 3/4 (push) Successful in 7m33s
Project CI / AI game creator shell Rust shard 2/4 (push) Successful in 7m40s
Project CI / AI game creator shell Rust smoke (push) Successful in 2m21s
Project CI / AI game creator shell Rust crates (push) Successful in 3m11s
Project CI / Native shell tests (push) Successful in 16m15s
Project CI / Frontend tests (push) Successful in 14m57s
Project CI / Repository checks (push) Successful in 14m48s
Project CI / Backend tests (push) Successful in 20m7s
Project CI / AI game creator shell web tests (push) Successful in 6m20s
移除服务器选择并按来源隔离登录凭据 新增官网客户端下载入口和匿名平台聚合接口 根据发布清单自动展示Windows与macOS首装包 补齐Mac首装元数据和上传顺序校验 同步定向测试与下载发布规范
239 lines
7.5 KiB
TypeScript
239 lines
7.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_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 platform service 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;
|
|
}
|
|
|
|
/**
|
|
* Read a response body with the same bounded lifetime as the request that
|
|
* produced it. Some transports resolve fetch() after headers arrive while
|
|
* leaving body consumption pending indefinitely.
|
|
*/
|
|
export async function readClientHttpResponseText(
|
|
response: Response,
|
|
options: { timeoutMs?: number | null; url?: string } = {},
|
|
) {
|
|
const timeoutMs =
|
|
options.timeoutMs === undefined
|
|
? CLIENT_HTTP_DEFAULT_TIMEOUT_MS
|
|
: options.timeoutMs;
|
|
if (timeoutMs === null) {
|
|
return response.text();
|
|
}
|
|
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
throw new RangeError('响应体超时时间必须是大于 0 的有限数值');
|
|
}
|
|
|
|
let timedOut = false;
|
|
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
|
|
const bodyPromise = response.text();
|
|
// A transport may reject after cancel() unblocks the stream. The race owns
|
|
// the observable result, so keep the late rejection out of the global queue.
|
|
void bodyPromise.catch(() => undefined);
|
|
const timeout = new Promise<never>((_, reject) => {
|
|
timeoutHandle = setTimeout(() => {
|
|
timedOut = true;
|
|
try {
|
|
void response.body?.cancel().catch(() => undefined);
|
|
} catch {
|
|
// Response doubles and older WebViews may not expose cancel().
|
|
}
|
|
reject(
|
|
new ClientHttpTimeoutError(options.url ?? 'response body', timeoutMs),
|
|
);
|
|
}, timeoutMs);
|
|
});
|
|
try {
|
|
return await Promise.race([bodyPromise, timeout]);
|
|
} catch (error) {
|
|
if (timedOut) {
|
|
throw new ClientHttpTimeoutError(
|
|
options.url ?? 'response body',
|
|
timeoutMs,
|
|
);
|
|
}
|
|
throw error;
|
|
} finally {
|
|
if (timeoutHandle !== undefined) clearTimeout(timeoutHandle);
|
|
}
|
|
}
|
|
|
|
export function getClientServerBaseUrl() {
|
|
return AGC_DEVELOPMENT_API_BASE_URL;
|
|
}
|
|
|
|
type ClientHttpContext = {
|
|
isTauri: boolean;
|
|
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 {
|
|
isTauri: typeof window !== 'undefined' && Boolean(window.__TAURI__),
|
|
mode: import.meta.env.MODE,
|
|
};
|
|
}
|
|
|
|
export function resolveClientHttpTarget(
|
|
url: string,
|
|
context: ClientHttpContext = currentClientHttpContext(),
|
|
): ClientHttpTarget {
|
|
const serverBaseUrl = getClientServerBaseUrl();
|
|
const target = new URL(url, `${serverBaseUrl}/`);
|
|
if (
|
|
(context.serverBaseUrl && context.serverBaseUrl !== serverBaseUrl) ||
|
|
target.origin !== serverBaseUrl ||
|
|
target.username ||
|
|
target.password
|
|
) {
|
|
throw new Error('请求目标不在客户端固定的 dev 服务范围内');
|
|
}
|
|
|
|
// Unit fixtures use relative requests after the same origin validation.
|
|
if (context.mode === 'test') {
|
|
return { transport: 'web', url };
|
|
}
|
|
|
|
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 target = resolveClientHttpTarget(url, {
|
|
...currentContext,
|
|
serverBaseUrl: options.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);
|
|
}
|
|
}
|