openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
242 lines (241 loc) • 7.41 kB
JavaScript
//#region packages/retry/src/index.ts
const MAX_TIMER_TIMEOUT_MS = 2147e6;
function createAbortError(e, t) {
const n = new Error(e, t);
n.name = "AbortError";
return n;
}
function racePromiseWithAbortSignal(e, t, n = (e) => createAbortError("Operation aborted", { cause: e.reason })) {
const run = () => {
try {
return typeof e === "function" ? e() : e;
} catch (e) {
return Promise.reject(e);
}
};
if (!t) return run();
const abortError = () => n(t);
if (t.aborted) {
const t = Promise.reject(abortError());
return typeof e === "function" ? t : Promise.race([t, e]);
}
let onAbort;
const r = new Promise((e, n) => {
onAbort = () => n(abortError());
t.addEventListener("abort", onAbort, { once: true });
});
return Promise.race([run(), r]).finally(() => {
t.removeEventListener("abort", onAbort);
});
}
/** Bounds observation without cancelling work; a factory starts only after the timer is armed. */
async function raceWithTimeout(e, t, n, r = {}) {
let i;
let onAbort;
try {
const a = new Promise((e, a) => {
const settle = (t) => {
try {
e(t());
} catch (e) {
a(e);
}
};
i = setTimeout(() => settle(n), t);
if (r.ref === false) i.unref?.();
const o = r.signal;
if (o) {
onAbort = () => settle(() => {
if (r.onAbort) return r.onAbort(o);
throw createAbortError("Operation aborted", { cause: o.reason });
});
o.addEventListener("abort", onAbort, { once: true });
if (o.aborted) onAbort();
}
});
let o;
try {
o = typeof e === "function" ? e() : e;
} catch (e) {
a.catch(() => {});
throw e;
}
return await Promise.race([o, a]);
} finally {
clearTimeout(i);
if (onAbort) r.signal?.removeEventListener("abort", onAbort);
}
}
function computeBackoff(e, t) {
const n = Math.min(e.maxMs, e.initialMs * e.factor ** Math.max(t - 1, 0));
const r = n * e.jitter * Math.random();
return Math.min(e.maxMs, Math.round(n + r));
}
function resolveSleepDelayMs(e) {
return Number.isFinite(e) && e > 0 ? Math.min(Math.max(Math.floor(e), 1), MAX_TIMER_TIMEOUT_MS) : 0;
}
async function sleepWithAbort(e, t, n = {}) {
const r = resolveSleepDelayMs(e);
if (r === 0) return;
await new Promise((e, i) => {
const cleanup = () => t?.removeEventListener("abort", onAbort);
const a = setTimeout(() => {
cleanup();
e();
}, r);
const onAbort = () => {
clearTimeout(a);
cleanup();
i(createAbortError("aborted", { cause: t?.reason ?? /* @__PURE__ */ new Error("aborted") }));
};
t?.addEventListener("abort", onAbort, { once: true });
if (t?.aborted) {
onAbort();
return;
}
if (n.ref === false) a.unref?.();
});
}
var RetrySupervisor = class {
constructor(e, t = Number.POSITIVE_INFINITY) {
this.policy = e;
this.maxAttempts = t;
this.attempts = 0;
this.initialMs = e.initialMs;
}
reset(e = this.policy.initialMs) {
this.cancel();
this.attempts = 0;
this.initialMs = e;
this.nextDelayOverrideMs = void 0;
}
cancel(e = /* @__PURE__ */ new Error("retry cancelled")) {
this.pendingAbort?.abort(e);
this.pendingAbort = void 0;
}
next(e) {
const t = this.nextDelayOverrideMs;
this.nextDelayOverrideMs = void 0;
if (t === void 0 && ++this.attempts > Math.ceil(this.maxAttempts)) return;
const n = Math.max(this.attempts, 1);
const r = t ?? computeBackoff({
...this.policy,
initialMs: this.initialMs
}, n);
this.cancel();
const i = new AbortController();
this.pendingAbort = i;
return {
attempt: n,
delayMs: r,
signal: e ? AbortSignal.any([i.signal, e]) : i.signal
};
}
};
const DEFAULT_RETRY_CONFIG = {
attempts: 3,
minDelayMs: 300,
maxDelayMs: 3e4,
jitter: 0
};
const defaultSleep = async (e) => {
let t = e;
do {
const e = Math.min(t, MAX_TIMER_TIMEOUT_MS);
await new Promise((t) => {
setTimeout(t, e);
});
t -= e;
} while (t > 0);
};
function clampNumber(e, t, n, r) {
if (typeof e !== "number" || !Number.isFinite(e)) return t;
return Math.min(Math.max(e, n ?? Number.NEGATIVE_INFINITY), r ?? Number.POSITIVE_INFINITY);
}
function resolveRetryDelayMs(e) {
return Math.min(Math.max(Math.round(e === Number.POSITIVE_INFINITY ? MAX_TIMER_TIMEOUT_MS : Number.isFinite(e) ? e : 0), 0), MAX_TIMER_TIMEOUT_MS);
}
function resolveRetryConfig(e = DEFAULT_RETRY_CONFIG, t) {
const n = Math.max(1, Math.round(clampNumber(t?.attempts, e.attempts)));
const r = resolveRetryDelayMs(clampNumber(t?.minDelayMs, e.minDelayMs, 0));
const i = Math.max(r, resolveRetryDelayMs(clampNumber(t?.maxDelayMs, e.maxDelayMs, 0)));
const a = t?.jitter;
const o = e.jitter;
return {
attempts: n,
minDelayMs: r,
maxDelayMs: i,
jitter: a === "full" ? a : typeof a === "number" && Number.isFinite(a) ? Math.min(Math.max(a, 0), 1) : o
};
}
function applyJitter(e, t, n, r) {
if (t === "full") {
if (n === "symmetric") return Math.max(0, Math.round(e * (.5 + r() * .5)));
return Math.max(0, Math.ceil(e * (1 + r())));
}
if (t <= 0) return n === "positive" ? Math.ceil(e) : e;
const i = r();
const a = e * (1 + (n === "positive" ? i * t : (i * 2 - 1) * t));
return Math.max(0, n === "positive" ? Math.ceil(a) : Math.round(a));
}
function toRetryError(e, t = "Non-Error thrown") {
if (e instanceof Error) return e;
if (typeof e === "string") return new Error(e);
const n = new Error(t, { cause: e });
if (typeof e === "object" && e !== null || typeof e === "function") Object.assign(n, e);
return n;
}
function createRetryRunner(e = {}) {
const t = e.sleep ?? defaultSleep;
const n = e.random ?? Math.random;
const r = e.createFailure ?? ((e) => toRetryError(e.at(-1) ?? /* @__PURE__ */ new Error("Retry failed")));
return async function retryAsync(i, a = 3, o = 300) {
const s = [];
const c = typeof a === "number";
const l = typeof a === "number" ? { attempts: a } : a;
const u = resolveRetryConfig(DEFAULT_RETRY_CONFIG, l);
const d = u.attempts;
const f = u.minDelayMs;
const p = u.maxDelayMs > 0 ? u.maxDelayMs : Number.POSITIVE_INFINITY;
const m = l.retryAfterMaxDelayMs === void 0 ? p : Math.max(f, resolveRetryDelayMs(clampNumber(l.retryAfterMaxDelayMs, p, 0)));
const h = l.random ?? n;
const g = l.sleep ?? t;
const _ = l.shouldRetry ?? (() => true);
for (let n = 1; n <= d; n += 1) try {
return await i();
} catch (r) {
s.push(r);
if (n >= d || e.shouldRetry?.(r) === false || !_(r, n)) break;
if (c) {
await t(resolveRetryDelayMs(o * 2 ** (n - 1)));
continue;
}
const i = {
attempt: n,
maxAttempts: d,
err: r,
label: l.label
};
const a = l.retryAfterMs?.(r);
const v = typeof a === "number" && Number.isFinite(a);
const y = typeof l.delayMs === "function" ? l.delayMs(i) : l.delayMs;
const b = y === void 0 ? void 0 : resolveRetryDelayMs(y);
const x = v ? Math.max(a, f) : b === void 0 ? f * 2 ** (n - 1) : Math.max(b, f);
const S = v ? m : p;
let C = Math.min(x, S);
const w = v && (a ?? 0) <= S;
const T = u.jitter === "full" ? !v || w : w;
C = applyJitter(C, u.jitter, T ? "positive" : "symmetric", h);
C = Math.min(Math.max(C, f), S);
await l.onRetry?.({
...i,
delayMs: C
});
if (C > 0) await g(C);
}
throw r(s);
};
}
const retryAsync = createRetryRunner();
//#endregion
export { resolveSleepDelayMs as a, raceWithTimeout as i, createAbortError as n, sleepWithAbort as o, racePromiseWithAbortSignal as r, RetrySupervisor as t };