openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 2.39 kB
JavaScript
import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{n as materializeErrorStack}from"./error-graph-internal-Bt2pFJBM.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";
//!src/shared/bounded-serial-queue.ts
const asyncLocalStorage=typeof process===`undefined`?void 0:process.getBuiltinModule(`node:async_hooks`).AsyncLocalStorage;var BoundedSerialQueue=class{constructor(e){this.options=e;this.pending=[];this.pendingWeight=0;this.active=false;this.sealed=false;this.overflowed=false;this.acceptedSequence=0;this.settledPrefix=Promise.resolve();if(!Number.isSafeInteger(e.maxPendingCount)||e.maxPendingCount<0)throw new Error(`maxPendingCount must be a non-negative safe integer`);if(!Number.isFinite(e.maxPendingWeight)||e.maxPendingWeight<0)throw new Error(`maxPendingWeight must be a non-negative finite number`)}get isIdle(){return!this.active&&this.pending.length===0}get didOverflow(){return this.overflowed}enqueue(e,t={}){if(this.sealed)return{accepted:false,reason:`sealed`};const n=t.weight??1;if(!Number.isFinite(n)||n<0)throw new Error(`queue task weight must be a non-negative finite number`);if(this.active&&(this.pending.length>=this.options.maxPendingCount||this.pendingWeight+n>this.options.maxPendingWeight)){if(t.sealOnOverflow===false)return{accepted:false,reason:`capacity`};this.sealed=true;this.overflowed=true;return{accepted:false,reason:`overflow`}}const{promise:r,resolve:i,reject:a}=createDeferredCore();const o={sequence:++this.acceptedSequence,weight:n,run:asyncLocalStorage?asyncLocalStorage.bind(e):e,resolve:e=>i(e),reject:a};this.settledPrefix=r.then(()=>void 0,()=>void 0);if(this.active){this.pending.push(o);this.pendingWeight+=n}else{this.active=true;runInDetachedAsyncContext(()=>void this.runTask(o))}return{accepted:true,completion:r}}seal(){this.sealed=true}flush(e={}){const t=this.settledPrefix;const n=this.acceptedSequence;if(e.requireSuccess!==true)return t;return t.then(()=>{if(this.firstFailure&&this.firstFailure.sequence<=n)throw this.firstFailure.error})}async runTask(e){try{e.resolve(await e.run())}catch(t){if(!this.firstFailure){materializeErrorStack(t);this.firstFailure={sequence:e.sequence,error:t}}e.reject(t)}finally{const e=this.pending.shift();if(e){this.pendingWeight-=e.weight;queueMicrotask(()=>void this.runTask(e))}else this.active=false}}};export{BoundedSerialQueue as t};