fix(infra): clamp provider usage timeout

This commit is contained in:
Peter Steinberger
2026-05-30 17:19:48 -04:00
parent aa42905354
commit cdab5fc16a
2 changed files with 16 additions and 1 deletions

View File

@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { MAX_TIMER_TIMEOUT_MS } from "../shared/number-coercion.js";
import { clampPercent, resolveUsageProviderId, withTimeout } from "./provider-usage.shared.js";
describe("provider-usage.shared", () => {
@@ -65,6 +66,18 @@ describe("provider-usage.shared", () => {
await expect(result).resolves.toBe("fallback");
});
it("clamps oversized timeout delays before scheduling", async () => {
vi.useFakeTimers();
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
const result = withTimeout(new Promise<string>(() => {}), Number.MAX_SAFE_INTEGER, "fallback");
expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), MAX_TIMER_TIMEOUT_MS);
await vi.advanceTimersByTimeAsync(MAX_TIMER_TIMEOUT_MS);
await expect(result).resolves.toBe("fallback");
});
it("clears the timeout after successful work", async () => {
const clearTimeoutSpy = vi.spyOn(globalThis, "clearTimeout");

View File

@@ -1,4 +1,5 @@
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
import { resolveTimerTimeoutMs } from "../shared/number-coercion.js";
import type { UsageProviderId } from "./provider-usage.types.js";
export const DEFAULT_TIMEOUT_MS = 5000;
@@ -71,11 +72,12 @@ export const clampPercent = (value: number) =>
export const withTimeout = async <T>(work: Promise<T>, ms: number, fallback: T): Promise<T> => {
let timeout: NodeJS.Timeout | undefined;
const timeoutMs = resolveTimerTimeoutMs(ms, 1);
try {
return await Promise.race([
work,
new Promise<T>((resolve) => {
timeout = setTimeout(() => resolve(fallback), ms);
timeout = setTimeout(() => resolve(fallback), timeoutMs);
}),
]);
} finally {