feat: 任务队列改为并发池并支持幂等复用与退避重试

This commit is contained in:
cat
2026-10-08 17:32:34 +08:00
parent 7c751bfc02
commit bf56c2bd46
10 changed files with 1296 additions and 123 deletions
+36 -1
View File
@@ -36,11 +36,40 @@ export class LlmError extends Error {
constructor(
message: string,
public readonly statusCode: number,
/**
* 服务端给出的建议重试等待(毫秒)。
*
* 来自 429/503 的 `Retry-After` 头;有值时退避重试应优先采用它,
* 而不是用自己的指数退避——服务商限流时自己的退避往往偏短。
*/
public readonly retryAfterMs?: number,
) {
super(message);
this.name = "LlmError";
}
}
/**
* 解析 `Retry-After` 头。
*
* 规范允许秒数或 HTTP 日期两种形式,两种都支持;解析不出来时返回 undefined。
*/
export function parseRetryAfter(value: string | null, now: number = Date.now()): number | undefined {
if (!value) return undefined;
const trimmed = value.trim();
if (trimmed.length === 0) return undefined;
// 纯数字:秒
if (/^\d+$/.test(trimmed)) {
return Number(trimmed) * 1000;
}
// HTTP 日期
const at = Date.parse(trimmed);
if (Number.isNaN(at)) return undefined;
return Math.max(0, at - now);
}
/**
* 非流式调用,返回完整文本
*/
@@ -75,7 +104,13 @@ export async function chat(
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new LlmError(`LLM 请求失败 (${response.status}): ${body.slice(0, 200)}`, 502);
const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
// 保留上游真实状态码:重试策略靠它区分 429/5xx(可重试)与 4xx(不可重试)
throw new LlmError(
`LLM 请求失败 (${response.status}): ${body.slice(0, 200)}`,
response.status,
retryAfterMs,
);
}
const data = (await response.json()) as {