openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
207 lines (206 loc) • 6.92 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runWithAsyncStore } from "./async-store-C6naia_Y.mjs";
import "./detached-async-context-D_mi-wUl.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/shared/async-work-scope.ts
const currentWorkScope = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScope"), () => new AsyncLocalStorage());
const currentWorkScopeAncestry = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScopeAncestry"), () => new AsyncLocalStorage());
const AsyncWorkScopeClosedError = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScopeClosedError"), () => class ClosedError extends Error {
constructor() {
super("Async work scope is closed");
this.name = "AsyncWorkScopeClosedError";
}
});
/** Joins cooperating descendants even when their caller returns a cached value first. */
var AsyncWorkScope = class AsyncWorkScope {
constructor(e) {
this.failures = e;
this.pending = /* @__PURE__ */ new Set();
this.controller = new AbortController();
this.phase = "open";
}
get signal() {
return this.controller.signal;
}
get hasPendingWork() {
return this.pending.size > 0;
}
get isClosing() {
return this.phase !== "open";
}
enter(e) {
const t = currentWorkScope.getStore();
if (t === this) return e();
const n = currentWorkScopeAncestry.getStore();
const r = t ? n?.scope === t ? n : { scope: t } : void 0;
return runWithAsyncStore(currentWorkScope, this, () => {
currentWorkScopeAncestry.enterWith({
scope: this,
parent: r
});
return e();
});
}
/** Enters synchronous work without inspecting or assimilating its return value. */
run(e) {
if (this.phase === "closed") throw new AsyncWorkScopeClosedError();
if (this.pending.size > 0) return this.enter(e);
const t = createDeferredCore();
this.pending.add(t.promise);
try {
return this.enter(e);
} finally {
t.resolve();
this.pending.delete(t.promise);
}
}
track(e) {
if (this.phase === "closed") return Promise.reject(new AsyncWorkScopeClosedError());
const t = createDeferredCore();
this.pending.add(t.promise);
t.promise.then(() => this.pending.delete(t.promise), (e) => {
this.pending.delete(t.promise);
if (this.failures) {
materializeErrorStack(e);
this.failures.add(e);
}
});
try {
t.resolve(this.enter(e));
} catch (e) {
t.reject(e);
}
return t.promise;
}
beginClose(e) {
if (this.phase !== "open") return;
this.phase = "closing";
this.controller.abort(e);
materializeErrorStack(this.controller.signal.reason);
}
/** Starts the next phase in the same continuation that observes settled pending work. */
runWhenIdle(e) {
return AsyncWorkScope.runWhenAllIdle(() => [this], () => this.track(e));
}
/** Reselects owners so work admitted into a later phase is not mistaken for earlier work. */
static async runWhenAllIdle(e, t) {
let n = e();
while (n.some((e) => e.pending.size > 0)) {
await Promise.allSettled(n.flatMap((e) => Array.from(e.pending)));
n = e();
}
return t();
}
async drain() {
this.beginClose();
while (this.pending.size > 0) await Promise.allSettled(this.pending);
this.phase = "closed";
}
};
const GatewayRetainedWorkTimeoutError = resolveGlobalSingleton(Symbol.for("openclaw.gatewayRetainedWorkTimeoutError"), () => class RetainedWorkTimeoutError extends Error {
constructor() {
super("Retained Gateway work did not settle after abort; resources remain retained");
}
});
/** Retains accepted work across Gateway close handles and successor scope generations. */
var GatewayRetainedWorkScope = class {
constructor(e, t) {
this.assertSettled = e;
this.escalation = t;
this.work = new AsyncWorkScope();
this.scopes = /* @__PURE__ */ new Set([this.work]);
this.gateways = 0;
this.closing = false;
}
get scope() {
return this.work;
}
get isClosing() {
return this.closing;
}
get hasGateways() {
return this.gateways > 0;
}
reopen() {
this.work = new AsyncWorkScope();
this.scopes.add(this.work);
this.closing = false;
}
async drain(e) {
const t = AsyncWorkScope.runWhenAllIdle(() => [e], async () => {
await e.drain();
this.assertSettled?.();
this.scopes.delete(e);
});
if (!this.escalation) return t;
const n = this.escalation.abortPendingAfterMs();
if (await settlesWithin(t, n)) return;
if (!e.isClosing) {
console.warn(this.escalation.reason);
e.beginClose(new Error(this.escalation.reason));
}
if (!await settlesWithin(t, n)) throw new GatewayRetainedWorkTimeoutError();
}
beginDrainAll() {
this.closing = true;
return Promise.all([...this.scopes].map((e) => this.drain(e)));
}
retainGateway() {
if (this.closing) this.reopen();
this.gateways += 1;
let e = false;
let t;
const beginClose = () => {
if (!e) {
e = true;
if (--this.gateways === 0) {
this.closing = true;
t = this.drain(this.work);
t.catch(() => {});
}
}
};
return {
beginClose,
drain: () => {
beginClose();
return t ?? Promise.resolve();
}
};
}
};
/** Inspect retained scopes by identity, including instances created by a released runtime. */
function isAsyncWorkScopeActiveHere(e) {
const t = currentWorkScope.getStore();
if (t === e) return true;
const n = currentWorkScopeAncestry.getStore();
if (!t || n?.scope !== t) return false;
for (let t = n; t; t = t.parent) if (t.scope === e) return true;
return false;
}
/** Outside a managed scope, the returned promise remains the caller's responsibility. */
async function trackAsyncWork(e) {
const t = currentWorkScope.getStore();
return await (t ? t.track(e) : e());
}
/** Captures only work ownership, never the caller's authorization or other async context. */
function captureAsyncWorkTracker() {
const e = currentWorkScope.getStore();
return async (t) => await (e ? e.track(t) : runOutsideAsyncWorkScope(t));
}
/** Starts work its caller does not own, so the caller's scope neither waits for it nor closes under it. */
function runOutsideAsyncWorkScope(e) {
if (currentWorkScope.getStore() === void 0) return currentWorkScopeAncestry.getStore() === void 0 ? e() : currentWorkScopeAncestry.exit(e);
return runWithAsyncStore(currentWorkScope, void 0, () => {
currentWorkScopeAncestry.enterWith(void 0);
return e();
});
}
function getAsyncWorkSignal() {
return currentWorkScope.getStore()?.signal;
}
//#endregion
export { captureAsyncWorkTracker as a, runOutsideAsyncWorkScope as c, GatewayRetainedWorkTimeoutError as i, trackAsyncWork as l, AsyncWorkScopeClosedError as n, getAsyncWorkSignal as o, GatewayRetainedWorkScope as r, isAsyncWorkScopeActiveHere as s, AsyncWorkScope as t };