UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

81 lines (80 loc) • 2.42 kB
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { a as captureAsyncWorkTracker, o as getAsyncWorkSignal, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/shared/async-work-resources.ts function createContextualCancellationRelay(e) { const t = new AbortController(); const n = AsyncLocalStorage.snapshot(); const abort = () => n(() => t.abort(e.reason)); e.addEventListener("abort", abort, { once: true }); if (e.aborted) abort(); return { signal: t.signal, release: () => e.removeEventListener("abort", abort) }; } /** Preserves cancellation context until cooperating work ends, without delaying its result. */ async function runWithTrackedCancellation(e, t) { if (!getAsyncWorkSignal()) return await t(e); return await runWithAsyncWorkResources(async (n) => { const r = createContextualCancellationRelay(e); n({ release: r.release }); return t(r.signal); }); } /** Returns the logical result while retaining resources through owned cleanup. */ async function runWithAsyncWorkResources(e, t) { let n = createDeferredCore(); const r = n.promise; let i = e; const a = captureAsyncWorkTracker(); const o = getAsyncWorkSignal(); a(async () => { const e = new AsyncWorkScope(); let r; let a = e.run(() => AsyncLocalStorage.snapshot()); const closeFromParent = () => a(() => e.beginClose(o?.reason)); o?.addEventListener("abort", closeFromParent, { once: true }); if (o?.aborted) closeFromParent(); try { let t = await e.track(() => { const e = i; i = void 0; return e((e) => { r = e; }, () => { a = AsyncLocalStorage.snapshot(); }); }); if (r?.releaseBeforeResultWhenIdle && !e.hasPendingWork) { const t = r; r = void 0; await a(() => e.drain()); await t.release(); } n?.resolve(t); n = void 0; t = void 0; } catch (r) { if (t?.cancelOnError) { a(() => e.beginClose(r)); await a(() => e.drain()); } n?.reject(r); n = void 0; } finally { try { await AsyncWorkScope.runWhenAllIdle(() => [e], () => a(() => e.drain())); } finally { o?.removeEventListener("abort", closeFromParent); await r?.release(); } } }).catch((e) => { n?.reject(e); n = void 0; }); return await r; } //#endregion export { runWithTrackedCancellation as n, runWithAsyncWorkResources as t };