You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
chajia/hooks/use-quote-polling.ts

90 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import type { QuoteDetail } from "@/lib/frontend/types";
import {
POLL_INTERVAL_MS,
POLL_TIMEOUT_MS,
} from "@/lib/frontend/constants";
import { formatQuoteErrorMessage } from "@/modules/quote/quote-error-messages";
export type PollFetchQuote = () => Promise<{
ok: boolean;
data?: QuoteDetail;
errorMessage?: string;
}>;
export type PollResult =
| { type: "done"; quote: QuoteDetail }
| { type: "timeout" }
| { type: "error"; message: string };
const BASE_BACKOFF_MS = 500;
/** 轮询超过该时长后缩短间隔,加快感知 RPA 完成 */
const POLL_FAST_AFTER_MS = 10_000;
const POLL_FAST_INTERVAL_MS = 800;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function pollIntervalMs(elapsedMs: number): number {
if (elapsedMs >= POLL_FAST_AFTER_MS) {
return Math.min(POLL_FAST_INTERVAL_MS, POLL_INTERVAL_MS);
}
return POLL_INTERVAL_MS;
}
/** 按 wall-clock 轮询至 timeoutMs默认与 POLL_TIMEOUT_MS 一致) */
export async function pollQuoteUntilDone(
fetchQuote: PollFetchQuote,
options?: { timeoutMs?: number },
): Promise<PollResult> {
let networkFailures = 0;
const startedAt = Date.now();
const timeoutMs = options?.timeoutMs ?? POLL_TIMEOUT_MS;
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const result = await fetchQuote();
if (!result.ok) {
networkFailures += 1;
const backoff = Math.min(
BASE_BACKOFF_MS * 2 ** (networkFailures - 1),
POLL_INTERVAL_MS,
);
const remaining = deadline - Date.now();
if (remaining <= 0) {
break;
}
await sleep(Math.min(backoff, remaining));
continue;
}
networkFailures = 0;
const quote = result.data!;
if (quote.status === "processing") {
const remaining = deadline - Date.now();
if (remaining <= 0) {
break;
}
const interval = pollIntervalMs(Date.now() - startedAt);
await sleep(Math.min(interval, remaining));
continue;
}
if (quote.status === "failed") {
return {
type: "error",
message: formatQuoteErrorMessage(
quote.error_code,
quote.error_message,
),
};
}
return { type: "done", quote };
}
return { type: "timeout" };
}