Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop,mobile): 端点清单启动失败前先自动重试,并保留网络错误码 (#520)

Lizicb1cd146c865
diff --git a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
index fb3e473e9f..e9d675700f 100644
--- a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
+++ b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
@@ -4,6 +4,8 @@
* 校验语义(缺省字段归一/协议白名单/allowHttp)在 @cindy/maker-shared 侧已覆盖;
* 这里只测 desktop 宿主层:清单来源解析(resolveEndpointSource 表驱动)、
* 阻断式重试循环(失败 → prompt → 重试/退出,无静默降级、无烘焙合并)、
+ * 弹框前的网络层自动重试(mac 首装瞬时失败自愈;配置事故不消耗预算)、
+ * 失败 reason 带错误码、
* file 模式的 allowHttp 放行、init 前 getter 抛错(启动时序守卫)、sendSync IPC 形状。
*/
import path from 'node:path';
@@ -32,6 +34,7 @@ import {
resolveClientEndpointsBlocking,
resolveEndpointSource,
CLIENT_ENDPOINTS_SYNC_CHANNEL,
+ type BlockingResolveDeps,
} from '../clientEndpointsService';
afterEach(() => {
@@ -116,11 +119,17 @@ describe('resolveEndpointSource(清单来源三选一)', () => {
});
});
+/** 自动重试预算关掉的公共 deps 片段(测"一轮一次尝试"的原语义)。 */
+const NO_AUTO_RETRY = { autoRetryDelaysMs: [] as readonly number[] };
+
+const okFetch = (text: string) => async () => ({ ok: true as const, text });
+const failFetch = (detail: string) => async () => ({ ok: false as const, detail });
+
describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)', () => {
it('首次成功:不进 prompt,所有值来自清单', async () => {
const promptRetry = vi.fn();
const result = await resolveClientEndpointsBlocking({
- fetchManifestText: async () => FULL_MANIFEST,
+ fetchManifest: okFetch(FULL_MANIFEST),
promptRetry,
exitApp: vi.fn(),
});
@@ -130,20 +139,21 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'
});
it('失败 → prompt 选重试 → 第二次成功(无静默降级)', async () => {
- const fetchManifestText = vi
- .fn<(timeoutMs: number) => Promise<string | null>>()
- .mockResolvedValueOnce(null)
- .mockResolvedValueOnce(FULL_MANIFEST);
+ const fetchManifest = vi
+ .fn<BlockingResolveDeps['fetchManifest']>()
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_CONNECTION_REFUSED' })
+ .mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });
const promptRetry = vi.fn().mockReturnValue('retry');
const exitApp = vi.fn();
const result = await resolveClientEndpointsBlocking({
- fetchManifestText,
+ fetchManifest,
promptRetry,
exitApp,
+ ...NO_AUTO_RETRY,
});
expect(promptRetry).toHaveBeenCalledTimes(1);
- expect(promptRetry).toHaveBeenCalledWith('fetch-failed');
- expect(fetchManifestText).toHaveBeenCalledTimes(2);
+ expect(promptRetry).toHaveBeenCalledWith('fetch-failed:ERR_CONNECTION_REFUSED');
+ expect(fetchManifest).toHaveBeenCalledTimes(2);
expect(result?.authApiBaseUrl).toBe('https://auth.remote.example.com');
expect(exitApp).not.toHaveBeenCalled();
});
@@ -158,7 +168,7 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'
const promptRetry = vi.fn();
const exitApp = vi.fn();
const result = await resolveClientEndpointsBlocking({
- fetchManifestText: async () => JSON.stringify(manifest),
+ fetchManifest: okFetch(JSON.stringify(manifest)),
promptRetry,
exitApp,
});
@@ -167,30 +177,43 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'
expect(exitApp).not.toHaveBeenCalled();
});
- it('fetch 抛错视同失败进 prompt,选退出返回 null', async () => {
+ it('fetch 抛错视同失败进 prompt(reason 抽出 ERR_ 码),选退出返回 null', async () => {
const promptRetry = vi.fn().mockReturnValue('exit');
const exitApp = vi.fn();
const result = await resolveClientEndpointsBlocking({
- fetchManifestText: async () => {
- throw new Error('boom');
+ fetchManifest: async () => {
+ throw new Error('net::ERR_NAME_NOT_RESOLVED');
},
promptRetry,
exitApp,
+ ...NO_AUTO_RETRY,
});
expect(result).toBeNull();
+ expect(promptRetry).toHaveBeenCalledWith('fetch-failed:ERR_NAME_NOT_RESOLVED');
expect(exitApp).toHaveBeenCalledTimes(1);
});
+ it('detail 为空时 reason 退回裸 fetch-failed', async () => {
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ await resolveClientEndpointsBlocking({
+ fetchManifest: failFetch(' '),
+ promptRetry,
+ exitApp: vi.fn(),
+ ...NO_AUTO_RETRY,
+ });
+ expect(promptRetry).toHaveBeenCalledWith('fetch-failed');
+ });
+
it('localhost http 清单:默认拒绝(CDN 路径零放松),allowHttp(file 模式)放行', async () => {
const rejected = await resolveClientEndpointsBlocking({
- fetchManifestText: async () => LOCAL_MANIFEST,
+ fetchManifest: okFetch(LOCAL_MANIFEST),
promptRetry: vi.fn().mockReturnValue('exit'),
exitApp: vi.fn(),
});
expect(rejected).toBeNull();
const accepted = await resolveClientEndpointsBlocking({
- fetchManifestText: async () => LOCAL_MANIFEST,
+ fetchManifest: okFetch(LOCAL_MANIFEST),
promptRetry: vi.fn(),
exitApp: vi.fn(),
allowHttp: true,
@@ -198,16 +221,181 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'
expect(accepted?.authApiBaseUrl).toBe('http://localhost:3344');
});
- it('文件缺失(读取返回 null)进同一条阻断链路', async () => {
+ it('文件缺失(读取失败带 errno)进同一条阻断链路', async () => {
const promptRetry = vi.fn().mockReturnValue('exit');
const result = await resolveClientEndpointsBlocking({
- fetchManifestText: async () => null, // file 模式读不到文件即返回 null
+ fetchManifest: failFetch('ENOENT'), // file 模式读不到文件
promptRetry,
exitApp: vi.fn(),
allowHttp: true,
+ ...NO_AUTO_RETRY,
});
expect(result).toBeNull();
- expect(promptRetry).toHaveBeenCalledWith('fetch-failed');
+ expect(promptRetry).toHaveBeenCalledWith('fetch-failed:ENOENT');
+ });
+});
+
+describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {
+ it('网络失败后自动重试成功:用户完全看不到阻断框', async () => {
+ const fetchManifest = vi
+ .fn<BlockingResolveDeps['fetchManifest']>()
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_NAME_NOT_RESOLVED' })
+ .mockResolvedValueOnce({ ok: false, detail: 'timeout-15000ms' })
+ .mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });
+ const promptRetry = vi.fn();
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(result?.authApiBaseUrl).toBe('https://auth.remote.example.com');
+ expect(fetchManifest).toHaveBeenCalledTimes(3);
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([10, 20]);
+ expect(promptRetry).not.toHaveBeenCalled();
+ });
+
+ it('预算用尽才弹框,reason 是最后一次的错误码', async () => {
+ const fetchManifest = vi
+ .fn<BlockingResolveDeps['fetchManifest']>()
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_NAME_NOT_RESOLVED' })
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_PROXY_CONNECTION_FAILED' })
+ .mockResolvedValue({ ok: false, detail: 'timeout-15000ms' });
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ const exitApp = vi.fn();
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp,
+ autoRetryDelaysMs: [10, 20],
+ sleep: async () => {},
+ });
+
+ expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
+ expect(promptRetry).toHaveBeenCalledTimes(1);
+ expect(promptRetry).toHaveBeenCalledWith('fetch-failed:timeout-15000ms');
+ expect(result).toBeNull();
+ expect(exitApp).toHaveBeenCalledTimes(1);
+ });
+
+ it('用户点重试开的新一轮同样带完整预算', async () => {
+ const fetchManifest = vi
+ .fn<BlockingResolveDeps['fetchManifest']>()
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_FAILED' }) // 轮 1 首发
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_FAILED' }) // 轮 1 自动重试
+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_FAILED' }) // 轮 2 首发
+ .mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST }); // 轮 2 自动重试
+ const promptRetry = vi.fn().mockReturnValue('retry');
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10],
+ sleep: async () => {},
+ });
+
+ expect(promptRetry).toHaveBeenCalledTimes(1);
+ expect(fetchManifest).toHaveBeenCalledTimes(4);
+ expect(result?.authApiBaseUrl).toBe('https://auth.remote.example.com');
+ });
+
+ it.each([
+ ['JSON 非法', 'not json at all'],
+ ['schema 版本非法', JSON.stringify({ schemaVersion: 0 })],
+ ['非空值非法', JSON.stringify({ ...(JSON.parse(FULL_MANIFEST) as object), cdnBaseUrl: 'ftp://x.example.com' })],
+ ])('%s(配置事故)不消耗重试预算,立刻弹框', async (_label, text) => {
+ const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
+ ok: true,
+ text,
+ });
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ expect(promptRetry).toHaveBeenCalledTimes(1);
+ expect(promptRetry.mock.calls[0][0]).not.toMatch(/^fetch-failed/);
+ expect(result).toBeNull();
+ });
+
+ it('missing-manifest-base-url(打包配置事故)不消耗重试预算,立刻弹框', async () => {
+ const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
+ ok: false,
+ detail: 'missing-manifest-base-url',
+ });
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ expect(promptRetry).toHaveBeenCalledTimes(1);
+ expect(result).toBeNull();
+ });
+
+ it.each([403, 404, 301])('HTTP %d(永久性错误)不消耗重试预算,立刻弹框', async (status) => {
+ const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
+ ok: false,
+ detail: `http-${status}`,
+ });
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ expect(promptRetry).toHaveBeenCalledTimes(1);
+ expect(result).toBeNull();
+ });
+
+ it('HTTP 502(瞬时服务端错误)仍消耗重试预算', async () => {
+ const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
+ ok: false,
+ detail: 'http-502',
+ });
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry,
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
+ expect(sleep).toHaveBeenCalledTimes(2);
+ expect(promptRetry).toHaveBeenCalledTimes(1);
+ expect(result).toBeNull();
});
});
diff --git a/apps/desktop/src/main/clientEndpointsService.ts b/apps/desktop/src/main/clientEndpointsService.ts
index 8b54c9dfd9..985a6294b1 100644
--- a/apps/desktop/src/main/clientEndpointsService.ts
+++ b/apps/desktop/src/main/clientEndpointsService.ts
@@ -9,6 +9,9 @@
* 时才弹系统错误框(重试 / 退出),用户不重试成功就不放行启动。
* **没有缓存回退、没有超时后静默继续、没有逐字段烘焙回退**——生效的端点
* (含更新链 CDN base)全部来自清单,非空值配置非法会在启动时立刻暴露。
+ * 唯一的柔性是弹框**之前**的网络层自动重试(AUTO_RETRY_DELAYS_MS,只对
+ * 拉取失败生效、不对解析/校验失败生效),用于自愈首启瞬时抖动;重试用尽
+ * 仍失败照样阻断,所以严格语义不变。
*
* 清单来源按运行形态三选一(resolveEndpointSource,纯函数可单测):
* - packaged / dev + --endpoints-cdn:从烘焙自举基址 ENDPOINT_MANIFEST_BASE_URL
@@ -46,6 +49,25 @@ const MANIFEST_FILE_NAME = 'endpoint.json';
/** 单次请求的网络超时——只用于触发错误框,不是静默降级。 */
const ATTEMPT_TIMEOUT_MS = 15_000;
+/**
+ * 弹阻断框**之前**的自动重试节奏(ms);长度 = 额外尝试次数,总尝试 = 1 + 长度。
+ *
+ * 背景(2026-07,mac 首次安装启动的现场反馈):本函数是 app.ready 的第一枪,而
+ * "首次安装后的第一次启动"恰好是网络栈最冷的时刻——userData / Chromium profile
+ * 与 network context 尚未建立、Gatekeeper 公证校验与 XProtect 还在扫整个 bundle、
+ * 系统代理(macOS SystemConfiguration / PAC)与 DNS 全无缓存。原实现单次失败即
+ * 弹阻断框,用户重启一次或点一下「重试」就正常 = 典型瞬时失败,却被呈现成
+ * "无法获取服务器配置"。
+ *
+ * 这里补的只是"瞬时抖动自愈",不是静默降级:预算用尽仍失败照样弹框阻断,
+ * 依然没有缓存回退、没有烘焙兜底。**只有网络层失败(fetch 未拿到正文)消耗
+ * 预算**;JSON / schema / 非法值这类配置事故重试同一份内容没有意义,立刻弹框。
+ *
+ * 时长权衡:真断网时 DNS 立即失败,约 3.2s 就会弹框;最坏情况(三次都卡到
+ * 15s 超时)约 48s 才弹框——此时网络确实不通,慢比误报好。
+ */
+const AUTO_RETRY_DELAYS_MS: readonly number[] = [800, 2400];
+
export const CLIENT_ENDPOINTS_SYNC_CHANNEL = 'client-endpoints:get-sync';
// ── 清单来源解析(纯函数,规则 14:内存 harness 可测) ─────────────────────
@@ -83,49 +105,81 @@ export function resolveEndpointSource(input: ResolveEndpointSourceInput): Endpoi
// ── IO:CDN 拉取 / 本地文件读取 ─────────────────────────────────────────────
-/** net.request 拉清单原文;任何失败(非 200 / 超时 / 异常)返回 null。 */
-function fetchTextViaNet(url: string, timeoutMs: number): Promise<string | null> {
+/**
+ * 一次清单取原文的结果。失败携带 `detail`(错误码级别的短标识)——原实现把
+ * error 对象整个丢掉、统一折叠成 `fetch-failed`,现场只能看到一句
+ * "fetch-failed",日志里也无从区分 DNS / 代理 / TLS / 超时,排查全靠猜。
+ */
+export type ManifestFetchResult =
+ | { ok: true; text: string }
+ | { ok: false; detail: string };
+
+/** 归一为单行并截断:避免多行栈把弹框 detail 与日志行撑爆。 */
+function normalizeDetail(detail: string): string {
+ return detail.replace(/\s+/g, ' ').trim().slice(0, 120);
+}
+
+/**
+ * 错误细节 → 简短错误码。Electron net 的 error.message 形如
+ * `net::ERR_NAME_NOT_RESOLVED`,优先抽 `ERR_*` 码;抽不出时退回消息原文。
+ */
+function describeFetchError(err: unknown): string {
+ const message = err instanceof Error ? err.message : String(err);
+ const code = /\b(ERR_[A-Z0-9_]+)\b/.exec(message)?.[1];
+ return normalizeDetail(code ?? message);
+}
+
+/** 失败 detail → 阻断循环用的 reason(保持 maker-shared 的 `fetch-failed` 前缀语义)。 */
+function fetchFailedReason(detail: string): string {
+ const normalized = normalizeDetail(detail);
+ return normalized ? `fetch-failed:${normalized}` : 'fetch-failed';
+}
+
+/** net.request 拉清单原文;任何失败(非 200 / 超时 / 异常)带错误码返回。 */
+function fetchTextViaNet(url: string, timeoutMs: number): Promise<ManifestFetchResult> {
return new Promise((resolve) => {
try {
const request = net.request(url);
let body = '';
let settled = false;
- const finish = (value: string | null) => {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ const finish = (value: ManifestFetchResult) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
+ if (!value.ok) log.debug('fetch failed (%s) for %s', value.detail, url);
resolve(value);
};
- const timeout = setTimeout(() => {
+ timeout = setTimeout(() => {
request.abort();
- finish(null);
+ finish({ ok: false, detail: `timeout-${timeoutMs}ms` });
}, timeoutMs);
request.on('response', (response) => {
if (response.statusCode !== 200) {
- log.info('HTTP %d for %s', response.statusCode, url);
- finish(null);
+ response.on('data', () => {});
+ finish({ ok: false, detail: `http-${response.statusCode}` });
return;
}
response.on('data', (chunk) => {
body += chunk.toString();
});
- response.on('end', () => finish(body));
- response.on('error', () => finish(null));
+ response.on('end', () => finish({ ok: true, text: body }));
+ response.on('error', (err) => finish({ ok: false, detail: describeFetchError(err) }));
});
- request.on('error', () => finish(null));
+ request.on('error', (err) => finish({ ok: false, detail: describeFetchError(err) }));
request.end();
- } catch {
- resolve(null);
+ } catch (err) {
+ resolve({ ok: false, detail: describeFetchError(err) });
}
});
}
-function fetchManifestTextViaCdn(timeoutMs: number): Promise<string | null> {
+function fetchManifestViaCdn(timeoutMs: number): Promise<ManifestFetchResult> {
if (!ENDPOINT_MANIFEST_BASE_URL) {
- // 烘焙基址缺失属打包/构建配置事故,同样走阻断暴露(fetch-failed → 弹框)。
+ // 烘焙基址缺失属打包/构建配置事故,同样走阻断暴露(→ 弹框)。
log.error('ENDPOINT_MANIFEST_BASE_URL is empty (build misconfiguration)');
- return Promise.resolve(null);
+ return Promise.resolve({ ok: false, detail: 'missing-manifest-base-url' });
}
// cache-bust:防 Chromium / CDN 复用陈旧清单。
return fetchTextViaNet(
@@ -134,49 +188,94 @@ function fetchManifestTextViaCdn(timeoutMs: number): Promise<string | null> {
);
}
-/** dev 本地清单文件读取;缺失 / 读失败返回 null(→ 同一条阻断弹框链路)。 */
-function readManifestTextFromFile(filePath: string): string | null {
+/** dev 本地清单文件读取;缺失 / 读失败带 errno 返回(→ 同一条阻断弹框链路)。 */
+function readManifestFromFile(filePath: string): ManifestFetchResult {
try {
- return fs.readFileSync(filePath, 'utf8');
+ return { ok: true, text: fs.readFileSync(filePath, 'utf8') };
} catch (err) {
log.warn('failed to read local endpoint manifest %s: %s', filePath, String(err));
- return null;
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return { ok: false, detail: code ?? describeFetchError(err) };
}
}
// ── 阻断式解析循环 ──────────────────────────────────────────────────────────
+function defaultSleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
/** 阻断循环的依赖注入面(规则 14:测试用内存 harness 驱动,不起 Electron)。 */
export interface BlockingResolveDeps {
- fetchManifestText(timeoutMs: number): Promise<string | null>;
+ fetchManifest(timeoutMs: number): Promise<ManifestFetchResult>;
/** 拉取/校验失败时问用户;生产实现是系统模态错误框。 */
promptRetry(reason: string): 'retry' | 'exit';
exitApp(): void;
timeoutMs?: number;
/** 仅 dev 本地文件路径为 true(localhost http);CDN 路径一律不传。 */
allowHttp?: boolean;
+ /**
+ * 弹框前的自动重试节奏,默认 AUTO_RETRY_DELAYS_MS。file 模式传 `[]` 关闭:
+ * 本地文件读不到 / 内容非法都是配置事故,重读同一路径没有意义,只会白等。
+ */
+ autoRetryDelaysMs?: readonly number[];
+ /** 仅测试注入(默认 setTimeout);让重试节奏在内存 harness 里零等待可测。 */
+ sleep?(ms: number): Promise<void>;
}
/**
* 阻断式解析循环:成功返回完整端点 map;用户选择退出返回 null(调用方不再继续启动)。
- * 失败 → promptRetry → 'retry' 无限重试;没有任何静默降级路径。
+ *
+ * 每一轮 = 一次首发尝试 + 若干次自动重试(仅网络层失败消耗预算,见
+ * AUTO_RETRY_DELAYS_MS);一轮全败才 promptRetry,用户选 'retry' 则重新开一轮
+ * (同样带完整自动重试预算)。没有任何静默降级路径。
*/
export async function resolveClientEndpointsBlocking(
deps: BlockingResolveDeps,
): Promise<ClientEndpointMap | null> {
const timeoutMs = deps.timeoutMs ?? ATTEMPT_TIMEOUT_MS;
const options = deps.allowHttp ? { allowHttp: true } : undefined;
+ const retryDelays = deps.autoRetryDelaysMs ?? AUTO_RETRY_DELAYS_MS;
+ const sleep = deps.sleep ?? defaultSleep;
+
for (;;) {
- let rawText: string | null = null;
- try {
- rawText = await deps.fetchManifestText(timeoutMs);
- } catch {
- rawText = null;
+ let reason = 'fetch-failed';
+ for (let attempt = 0; ; attempt += 1) {
+ let fetched: ManifestFetchResult;
+ try {
+ fetched = await deps.fetchManifest(timeoutMs);
+ } catch (err) {
+ fetched = { ok: false, detail: describeFetchError(err) };
+ }
+
+ if (fetched.ok) {
+ const parsed = resolveClientEndpointsStrict(fetched.text, options);
+ if (parsed.ok) return parsed.endpoints;
+ // 拿到了正文但解析/校验不过 = 配置事故:重试同一份内容没有意义,直接弹框。
+ reason = parsed.reason;
+ break;
+ }
+
+ reason = fetchFailedReason(fetched.detail);
+ // 构建/打包配置事故(基址为空)重试不会改变结果,立即跳出。
+ if (fetched.detail === 'missing-manifest-base-url') break;
+ // HTTP 3xx/4xx 是永久性错误(路径/权限/配置),重试同一 URL 不会自愈;仅 5xx 可能是瞬时故障。
+ const httpStatus = /^http-(\d+)$/.exec(fetched.detail)?.[1];
+ if (httpStatus && Number(httpStatus) < 500) break;
+ const delay = retryDelays[attempt];
+ if (delay === undefined) break; // 预算用尽 → 阻断弹框
+ log.warn(
+ 'manifest fetch failed (%s); auto-retry %d/%d in %dms',
+ reason,
+ attempt + 1,
+ retryDelays.length,
+ delay,
+ );
+ await sleep(delay);
}
- const result = resolveClientEndpointsStrict(rawText, options);
- if (result.ok) return result.endpoints;
- log.warn(`client endpoints manifest unavailable (${result.reason}), prompting user`);
- if (deps.promptRetry(result.reason) === 'exit') {
+
+ log.warn(`client endpoints manifest unavailable (${reason}), prompting user`);
+ if (deps.promptRetry(reason) === 'exit') {
deps.exitApp();
return null;
}
@@ -227,13 +326,15 @@ export async function initClientEndpoints(): Promise<boolean> {
? `${ENDPOINT_MANIFEST_BASE_URL}/${MANIFEST_FILE_NAME}`
: source.filePath;
const endpoints = await resolveClientEndpointsBlocking({
- fetchManifestText:
+ fetchManifest:
source.kind === 'cdn'
- ? fetchManifestTextViaCdn
- : () => Promise.resolve(readManifestTextFromFile(source.filePath)),
+ ? fetchManifestViaCdn
+ : () => Promise.resolve(readManifestFromFile(source.filePath)),
promptRetry: (reason) => promptRetryDialog(reason, sourceLabel),
exitApp: () => app.exit(1),
allowHttp: source.kind === 'file',
+ // dev 本地文件:读不到就是路径/内容配置错,不自动重试(见 BlockingResolveDeps)。
+ autoRetryDelaysMs: source.kind === 'cdn' ? undefined : [],
});
if (endpoints === null) return false; // 用户选择退出,app.exit 已调用
resolvedEndpoints = endpoints;
diff --git a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
index 008a1242d9..e88b3a5fbd 100644
--- a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
+++ b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
@@ -8,6 +8,10 @@
*/
import { describe, expect, it, vi } from 'vitest';
+import type { ManifestFetchResult } from '@/config/clientEndpointStartup';
+
+type FetchManifest = (timeoutMs: number) => Promise<ManifestFetchResult>;
+
async function freshModules() {
vi.resetModules();
const env = await import('@/config/env');
@@ -36,13 +40,18 @@ const FULL_MANIFEST_OBJECT = {
};
const FULL_MANIFEST = JSON.stringify(FULL_MANIFEST_OBJECT);
+const okFetch = (text: string) => async () => ({ ok: true as const, text });
+const failFetch = (detail: string) => async () => ({ ok: false as const, detail });
+/** 关掉自动重试预算,测"单次尝试"原语义(不然失败路径会白等真实 backoff)。 */
+const NO_AUTO_RETRY = { autoRetryDelaysMs: [] as readonly number[] };
+
describe('runStartupEndpointResolve(CDN 解析)', () => {
it('拉取成功:全量采用 CDN 清单,回写 env live binding,跨模块可见', async () => {
const { env, startup } = await freshModules();
expect(env.DEVICE_LINK_API_BASE_URL).toBe('https://relay.example.invalid');
const outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () => FULL_MANIFEST,
+ fetchManifest: okFetch(FULL_MANIFEST),
});
expect(outcome).toEqual({ ok: true, source: 'cdn' });
@@ -70,15 +79,17 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(env.REVIEW_MODE).toBe(false);
let outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () =>
+ fetchManifest: okFetch(
JSON.stringify({ ...FULL_MANIFEST_OBJECT, review: '9.9.8' }),
+ ),
});
expect(outcome).toEqual({ ok: true, source: 'cdn' });
expect(env.REVIEW_MODE).toBe(false);
outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () =>
+ fetchManifest: okFetch(
JSON.stringify({ ...FULL_MANIFEST_OBJECT, review: '9.9.9' }),
+ ),
resolveIsTestFlight: async () => false,
});
expect(outcome).toEqual({ ok: true, source: 'cdn' });
@@ -86,8 +97,9 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(env.IS_TESTFLIGHT_BUILD).toBe(false);
outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () =>
+ fetchManifest: okFetch(
JSON.stringify({ ...FULL_MANIFEST_OBJECT, review: '9.9.9' }),
+ ),
resolveIsTestFlight: async () => true,
});
expect(outcome).toEqual({ ok: true, source: 'cdn' });
@@ -95,8 +107,9 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(env.IS_TESTFLIGHT_BUILD).toBe(true);
outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () =>
+ fetchManifest: okFetch(
JSON.stringify({ ...FULL_MANIFEST_OBJECT, review: '' }),
+ ),
});
expect(outcome).toEqual({ ok: true, source: 'cdn' });
expect(env.REVIEW_MODE).toBe(false);
@@ -123,7 +136,7 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
const { startup } = await freshModules();
const apply = vi.fn();
const outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () => text,
+ fetchManifest: okFetch(text),
apply,
});
@@ -147,7 +160,7 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
await expect(
startup.runStartupEndpointResolve({
- fetchManifestText: async () => JSON.stringify(manifest),
+ fetchManifest: okFetch(JSON.stringify(manifest)),
}),
).resolves.toEqual({ ok: true, source: 'cdn' });
expect(env.AUTH_API_BASE_URL).toBe('');
@@ -171,12 +184,11 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
'unsupported-schema-version:999',
],
['非 JSON', 'not-json{', 'invalid-json'],
- ['拉取失败', null, 'fetch-failed'],
] as const)('%s → 直接阻断,不回写任何端点', async (_label, text, reason) => {
const { env, startup } = await freshModules();
const apply = vi.fn();
const outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () => text,
+ fetchManifest: okFetch(text),
apply,
});
@@ -185,24 +197,37 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(env.DEVICE_LINK_API_BASE_URL).toBe('https://relay.example.invalid');
});
- it('fetch 抛错视同拉取失败并阻断;下一次重试成功后才回写', async () => {
+ it('拉取失败 → 阻断且 reason 带错误码,不回写任何端点', async () => {
+ const { env, startup } = await freshModules();
+ const apply = vi.fn();
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest: failFetch('timeout-10000ms'),
+ apply,
+ ...NO_AUTO_RETRY,
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:timeout-10000ms' });
+ expect(apply).not.toHaveBeenCalled();
+ expect(env.DEVICE_LINK_API_BASE_URL).toBe('https://relay.example.invalid');
+ });
+
+ it('fetch 抛错视同拉取失败并阻断(reason 带 name);下一次重试成功后才回写', async () => {
const { env, startup } = await freshModules();
const initialAuthApiBaseUrl = env.AUTH_API_BASE_URL;
- const fetchManifestText = vi
- .fn<(timeoutMs: number) => Promise<string | null>>()
- .mockRejectedValueOnce(new Error('boom'))
- .mockResolvedValueOnce(FULL_MANIFEST);
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockRejectedValueOnce(new TypeError('Network request failed'))
+ .mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });
await expect(
- startup.runStartupEndpointResolve({ fetchManifestText }),
+ startup.runStartupEndpointResolve({ fetchManifest, ...NO_AUTO_RETRY }),
).resolves.toEqual({
ok: false,
- reason: 'fetch-failed',
+ reason: 'fetch-failed:TypeError:Network request failed',
});
expect(env.AUTH_API_BASE_URL).toBe(initialAuthApiBaseUrl);
await expect(
- startup.runStartupEndpointResolve({ fetchManifestText }),
+ startup.runStartupEndpointResolve({ fetchManifest, ...NO_AUTO_RETRY }),
).resolves.toEqual({
ok: true,
source: 'cdn',
@@ -210,13 +235,119 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(env.AUTH_API_BASE_URL).toBe('https://auth-next.example.com');
});
+ describe('返回失败前的自动重试(首装瞬时失败自愈)', () => {
+ it('拉取失败后自动重试成功:闸门不进错误屏', async () => {
+ const { env, startup } = await freshModules();
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockResolvedValueOnce({ ok: false, detail: 'timeout-10000ms' })
+ .mockResolvedValueOnce({ ok: false, detail: 'TypeError:Network request failed' })
+ .mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(outcome).toEqual({ ok: true, source: 'cdn' });
+ expect(fetchManifest).toHaveBeenCalledTimes(3);
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([10, 20]);
+ expect(env.AUTH_API_BASE_URL).toBe('https://auth-next.example.com');
+ });
+
+ it('预算用尽才阻断,reason 是最后一次的错误码', async () => {
+ const { startup } = await freshModules();
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockResolvedValueOnce({ ok: false, detail: 'AbortError:Aborted' })
+ .mockResolvedValue({ ok: false, detail: 'timeout-10000ms' });
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep: async () => {},
+ });
+
+ expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
+ expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:timeout-10000ms' });
+ });
+
+ it('清单非法(配置事故)不消耗重试预算', async () => {
+ const { startup } = await freshModules();
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockResolvedValue({ ok: true, text: 'not-json{' });
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'invalid-json' });
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ });
+
+ it('missing-manifest-base-url(打包配置事故)不消耗重试预算', async () => {
+ const { startup } = await freshModules();
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockResolvedValue({ ok: false, detail: 'missing-manifest-base-url' });
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:missing-manifest-base-url' });
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ });
+
+ it.each([403, 404, 301])('HTTP %d(永久性错误)不消耗重试预算', async (status) => {
+ const { startup } = await freshModules();
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockResolvedValue({ ok: false, detail: `http-${status}` });
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: `fetch-failed:http-${status}` });
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ });
+
+ it('HTTP 502(瞬时服务端错误)仍消耗重试预算', async () => {
+ const { startup } = await freshModules();
+ const fetchManifest = vi.fn<FetchManifest>()
+ .mockResolvedValue({ ok: false, detail: 'http-502' });
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:http-502' });
+ expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
+ expect(sleep).toHaveBeenCalledTimes(2);
+ });
+ });
+
it('自建变体(IS_OTA_SELFHOST=1):mobileUpdateBaseUrl 只能在 CDN 清单校验通过后生效', async () => {
process.env.EXPO_PUBLIC_XDT_OTA_SELFHOST = '1';
try {
const { env, startup } = await freshModules();
expect(env.OTA_SERVER_BASE_URL).toBe('');
const outcome = await startup.runStartupEndpointResolve({
- fetchManifestText: async () => FULL_MANIFEST,
+ fetchManifest: okFetch(FULL_MANIFEST),
});
expect(outcome).toEqual({ ok: true, source: 'cdn' });
expect(env.OTA_SERVER_BASE_URL).toBe(
@@ -229,7 +360,7 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
});
await expect(
startup.runStartupEndpointResolve({
- fetchManifestText: async () => blankUpdateManifest,
+ fetchManifest: okFetch(blankUpdateManifest),
}),
).resolves.toEqual({ ok: true, source: 'cdn' });
expect(env.OTA_SERVER_BASE_URL).toBe('');
diff --git a/apps/mobile/src/config/clientEndpointStartup.ts b/apps/mobile/src/config/clientEndpointStartup.ts
index 54ca06b24f..b17c0d82f4 100644
--- a/apps/mobile/src/config/clientEndpointStartup.ts
+++ b/apps/mobile/src/config/clientEndpointStartup.ts
@@ -11,6 +11,11 @@
* 共享逻辑(schema / 校验)在 @cindy/maker-shared/client-endpoints;本文件负责
* mobile 侧 IO(全局 fetch + AbortController)与启动阻断;成功后经
* env.applyResolvedClientEndpoints 回写 live binding。
+ *
+ * 唯一的柔性是**返回失败前**的网络层自动重试(AUTO_RETRY_DELAYS_MS):首次
+ * 安装后的第一次启动网络栈最冷(DNS / 代理无缓存、系统仍在校验安装包),
+ * 单次失败就把用户推到错误屏是把瞬时抖动当成故障。只对拉取失败生效,
+ * 不对解析 / 校验失败生效;预算用尽仍失败照样阻断,严格语义不变。
*/
import {
@@ -23,21 +28,63 @@ import { ENDPOINT_MANIFEST_BASE_URL, applyResolvedClientEndpoints } from './env'
const MANIFEST_RELATIVE_PATH = '/endpoint.json';
/** 单次请求的网络超时——超时即阻断启动,不是无限等待。 */
const ATTEMPT_TIMEOUT_MS = 10_000;
+/**
+ * 返回失败前的自动重试节奏(ms);长度 = 额外尝试次数。与 desktop
+ * clientEndpointsService 同语义,节奏按 mobile 的 10s 单次超时略收紧。
+ */
+const AUTO_RETRY_DELAYS_MS: readonly number[] = [700, 2000];
+
+/**
+ * 一次取清单原文的结果。失败带 `detail`(错误码级别短标识):原实现 `catch {}`
+ * 把错误整个吞掉、reason 恒为 `fetch-failed`,错误屏与用户反馈里都分不清
+ * 超时 / DNS / HTTP 状态码,排查全靠猜。
+ */
+export type ManifestFetchResult =
+ | { ok: true; text: string }
+ | { ok: false; detail: string };
+
+/** 归一为单行并截断,避免长栈把错误屏文案撑爆。 */
+function normalizeDetail(detail: string): string {
+ return detail.replace(/\s+/g, ' ').trim().slice(0, 120);
+}
+
+/** RN fetch 失败 → 简短标识(AbortError / TypeError: Network request failed 等)。 */
+function describeFetchFailure(err: unknown): string {
+ if (err instanceof Error) {
+ return normalizeDetail(err.message ? `${err.name}:${err.message}` : err.name);
+ }
+ return normalizeDetail(String(err));
+}
+
+/** 失败 detail → 闸门 reason(保持 maker-shared 的 `fetch-failed` 前缀语义)。 */
+function fetchFailedReason(detail: string): string {
+ const normalized = normalizeDetail(detail);
+ return normalized ? `fetch-failed:${normalized}` : 'fetch-failed';
+}
+
+function defaultSleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
-async function fetchManifestTextViaCdn(timeoutMs: number): Promise<string | null> {
+async function fetchManifestViaCdn(timeoutMs: number): Promise<ManifestFetchResult> {
// 构建缺自举基址属打包配置事故:CDN 级不可用,交给启动闸门阻断。
- if (!ENDPOINT_MANIFEST_BASE_URL) return null;
+ if (!ENDPOINT_MANIFEST_BASE_URL) return { ok: false, detail: 'missing-manifest-base-url' };
const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
try {
const response = await fetch(
`${ENDPOINT_MANIFEST_BASE_URL}${MANIFEST_RELATIVE_PATH}?t=${Date.now()}`,
{ signal: controller.signal },
);
- if (!response.ok) return null;
- return await response.text();
- } catch {
- return null;
+ if (!response.ok) return { ok: false, detail: `http-${response.status}` };
+ return { ok: true, text: await response.text() };
+ } catch (err) {
+ // abort 与网络错在 RN 下都落到这里:自己记的 timedOut 比 err.name 可靠。
+ return { ok: false, detail: timedOut ? `timeout-${timeoutMs}ms` : describeFetchFailure(err) };
} finally {
clearTimeout(timer);
}
@@ -45,7 +92,7 @@ async function fetchManifestTextViaCdn(timeoutMs: number): Promise<string | null
/** 测试注入点;生产走默认实现。 */
export interface StartupEndpointResolveDeps {
- fetchManifestText?: (timeoutMs: number) => Promise<string | null>;
+ fetchManifest?: (timeoutMs: number) => Promise<ManifestFetchResult>;
/** iOS 在端点闸门放行前读取 StoreKit 分发环境;其它平台返回 false。 */
resolveIsTestFlight?: () => Promise<boolean>;
apply?: (resolved: ClientEndpointMap & {
@@ -53,6 +100,39 @@ export interface StartupEndpointResolveDeps {
isTestFlight: boolean;
}) => void;
timeoutMs?: number;
+ /** 自动重试节奏,默认 AUTO_RETRY_DELAYS_MS;传 `[]` 关闭(单次尝试)。 */
+ autoRetryDelaysMs?: readonly number[];
+ /** 仅测试注入(默认 setTimeout);让重试节奏零等待可测。 */
+ sleep?: (ms: number) => Promise<void>;
+}
+
+/**
+ * 首发尝试 + 自动重试,返回最后一次结果。只有拉取失败消耗预算;
+ * 拿到正文即刻返回(是否合法由调用方解析判定,失败不重试)。
+ */
+async function fetchManifestWithRetry(args: {
+ fetchManifest: (timeoutMs: number) => Promise<ManifestFetchResult>;
+ timeoutMs: number;
+ retryDelays: readonly number[];
+ sleep: (ms: number) => Promise<void>;
+}): Promise<ManifestFetchResult> {
+ for (let attempt = 0; ; attempt += 1) {
+ let fetched: ManifestFetchResult;
+ try {
+ fetched = await args.fetchManifest(args.timeoutMs);
+ } catch (err) {
+ fetched = { ok: false, detail: describeFetchFailure(err) };
+ }
+ if (fetched.ok) return fetched;
+ // 构建/打包配置事故(基址为空)重试不会改变结果,立即退出。
+ if (fetched.detail === 'missing-manifest-base-url') return fetched;
+ // HTTP 3xx/4xx 是永久性错误,重试同一 URL 不会自愈;仅 5xx 可能是瞬时故障。
+ const httpStatus = /^http-(\d+)$/.exec(fetched.detail)?.[1];
+ if (httpStatus && Number(httpStatus) < 500) return fetched;
+ const delay = args.retryDelays[attempt];
+ if (delay === undefined) return fetched; // 预算用尽 → 交调用方阻断
+ await args.sleep(delay);
+ }
}
export type StartupEndpointResolveOutcome =
@@ -64,23 +144,32 @@ export type StartupEndpointResolveOutcome =
| { ok: false; reason: string };
/**
- * 单次严格解析:成功 → 回写 env live binding;失败 → 返回 reason,
- * 由闸门渲染错误屏,重试 = 再调一次本函数。本函数自身永不 reject。
+ * 严格解析:成功 → 回写 env live binding;失败 → 返回 reason,由闸门渲染错误屏,
+ * 用户点重试 = 再调一次本函数。本函数自身永不 reject。
+ *
+ * 一次调用 = 首发尝试 + 若干次自动重试(仅拉取失败消耗预算,见
+ * AUTO_RETRY_DELAYS_MS);拿到正文后解析 / 校验不过是配置事故,不重试。
*/
export async function runStartupEndpointResolve(
deps: StartupEndpointResolveDeps = {},
): Promise<StartupEndpointResolveOutcome> {
try {
- const fetchManifestText = deps.fetchManifestText ?? fetchManifestTextViaCdn;
+ const fetchManifest = deps.fetchManifest ?? fetchManifestViaCdn;
const apply = deps.apply ?? applyResolvedClientEndpoints;
- let rawText: string | null = null;
- try {
- rawText = await fetchManifestText(deps.timeoutMs ?? ATTEMPT_TIMEOUT_MS);
- } catch {
- rawText = null;
- }
+ const timeoutMs = deps.timeoutMs ?? ATTEMPT_TIMEOUT_MS;
+ const retryDelays = deps.autoRetryDelaysMs ?? AUTO_RETRY_DELAYS_MS;
+ const sleep = deps.sleep ?? defaultSleep;
+
+ const fetched = await fetchManifestWithRetry({
+ fetchManifest,
+ timeoutMs,
+ retryDelays,
+ sleep,
+ });
+ if (!fetched.ok) return { ok: false, reason: fetchFailedReason(fetched.detail) };
- const result = resolveClientEndpointsStrict(rawText);
+ // 拿到正文:解析/校验不过 = 线上清单配置错,重试同一份内容没有意义,直接阻断。
+ const result = resolveClientEndpointsStrict(fetched.text);
if (!result.ok) return { ok: false, reason: result.reason };
// 分发环境识别失败不能把 endpoint 闸门变成启动故障;降级为非 TestFlight,