openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2 lines • 5.91 kB
JavaScript
//!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)})}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.random??Math.random;const n=e.createFailure??(e=>toRetryError(e.at(-1)??/* @__PURE__ */ new Error(`Retry failed`)));return async function retryAsync(r,i=3,a=300){const o=[];const s=typeof i===`number`;const c=typeof i===`number`?{attempts:i}:i;const l=resolveRetryConfig(DEFAULT_RETRY_CONFIG,c);const u=l.attempts;const d=l.minDelayMs;const f=l.maxDelayMs>0?l.maxDelayMs:Number.POSITIVE_INFINITY;const p=c.retryAfterMaxDelayMs===void 0?f:Math.max(d,resolveRetryDelayMs(clampNumber(c.retryAfterMaxDelayMs,f,0)));const m=c.random??t;const h=c.sleep??defaultSleep;const g=c.shouldRetry??(()=>true);for(let t=1;t<=u;t+=1)try{return await r()}catch(n){o.push(n);if(t>=u||e.shouldRetry?.(n)===false||!g(n,t))break;if(s){await defaultSleep(resolveRetryDelayMs(a*2**(t-1)));continue}const r={attempt:t,maxAttempts:u,err:n,label:c.label};const i=c.retryAfterMs?.(n);const _=typeof i===`number`&&Number.isFinite(i);const v=typeof c.delayMs===`function`?c.delayMs(r):c.delayMs;const y=v===void 0?void 0:resolveRetryDelayMs(v);const b=_?Math.max(i,d):y===void 0?d*2**(t-1):Math.max(y,d);const x=_?p:f;let S=Math.min(b,x);const C=_&&(i??0)<=x;const w=l.jitter===`full`?!_||C:C;S=applyJitter(S,l.jitter,w?`positive`:`symmetric`,m);S=Math.min(Math.max(S,d),x);await c.onRetry?.({...r,delayMs:S});if(S>0)await h(S)}throw n(o)}}const retryAsync=createRetryRunner();export{raceWithTimeout as a,toRetryError as c,racePromiseWithAbortSignal as i,createAbortError as n,resolveSleepDelayMs as o,createRetryRunner as r,sleepWithAbort as s,RetrySupervisor as t};