openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
228 lines (227 loc) • 7.27 kB
JavaScript
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { r as runWithMainThreadTask } from "./main-thread-stall-BhUfYJnA.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { c as runOutsideAsyncWorkScope, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as runWithSessionControllerCleanup } from "./session-controller.cleanup-context-DsmTHS1X.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/infra/gateway-scheduler.ts
const log = createSubsystemLogger("gateway/scheduler");
const hostClock = {
now: () => Date.now(),
monotonicNow: () => performance.now(),
arm: (e, t) => {
const n = setTimeout(() => {
runWithMainThreadTask("scheduler:wake", () => {
e();
});
}, t);
n.unref();
return () => clearTimeout(n);
}
};
/** Next maintenance slot after a run, skipping missed slots without replay. */
function nextMaintenanceSlot(e, t, n) {
return e + (Math.floor(Math.max(0, t - e) / n) + 1) * n;
}
/** Owns Gateway wakeups; stores and execution owners retain their deadlines and authority. */
var GatewayScheduler = class {
constructor(e = {}) {
this.jobs = /* @__PURE__ */ new Map();
this.pending = /* @__PURE__ */ new Set();
this.dispatching = false;
this.fenced = false;
this.controller = new AbortController();
this.clock = e.clock ?? hostClock;
}
get signal() {
return this.controller.signal;
}
now() {
return this.clock.now();
}
get nextWakeAtMs() {
const e = this.now();
const t = this.clock.monotonicNow();
let n = null;
for (const r of this.jobs.values()) {
if (r.running) continue;
const i = e + this.remaining(r, e, t);
n = n === null ? i : Math.min(n, i);
}
return n;
}
/** Closes one owner's timers without retiring siblings or losing in-flight joins. */
scope() {
const e = new AbortController();
const t = {
signal: AbortSignal.any([this.signal, e.signal]),
jobs: /* @__PURE__ */ new Set()
};
const beginClose = () => {
e.abort();
materializeErrorStack(e.signal.reason);
materializeErrorStack(t.signal.reason);
for (const e of t.jobs) this.cancel(e);
};
const close = () => {
beginClose();
const e = [...t.jobs].flatMap((e) => e.running ?? []);
return e.length > 0 ? Promise.all(e).then(() => void 0) : void 0;
};
return {
signal: t.signal,
now: () => this.now(),
schedule: (e) => this.scheduleOwned(e, t),
beginClose,
close,
stop: async () => {
await close();
}
};
}
schedule(e) {
return this.scheduleOwned(e);
}
scheduleOwned(e, t) {
const n = "delayMs" in e;
const r = this.now();
const i = n ? r + e.delayMs : e.atMs;
const a = e.phase === "maintenance" ? Math.max(r, Math.floor(i / 1e4) * 1e4) : i;
if (!Number.isFinite(a) || e.everyMs !== void 0 && (!Number.isFinite(e.everyMs) || e.everyMs <= 0)) throw new Error(`Invalid Gateway schedule: ${e.id}`);
const o = this.fenced || t?.signal.aborted === true;
const s = o ? void 0 : this.jobs.get(e.id);
const c = {
id: e.id,
diagnosticName: `scheduler:${e.id.startsWith("maintenance:") ? e.id.split(":").slice(0, 3).join(":") : e.id.split(/[:/]/u, 1)[0]}`,
run: e.run,
everyMs: e.everyMs,
phase: e.phase,
atMs: a,
elapsedAtMs: e.phase !== "maintenance" && (n || e.everyMs !== void 0) ? this.clock.monotonicNow() + Math.max(0, a - r) : void 0,
context: runOutsideAsyncWorkScope(() => runWithSessionControllerCleanup(() => AsyncLocalStorage.snapshot())),
cancelled: o,
owner: t
};
if (e.mode === "earliest" && s && !s.running) {
c.atMs = Math.min(c.atMs, s.atMs);
if (e.phase !== "maintenance" && s.elapsedAtMs !== void 0) c.elapsedAtMs = c.elapsedAtMs === void 0 ? s.elapsedAtMs : Math.min(c.elapsedAtMs, s.elapsedAtMs);
}
const cancel = () => this.cancel(c);
if (!o) {
t?.jobs.add(c);
this.jobs.set(c.id, c);
if (s) this.cancel(s);
this.arm();
}
return {
get atMs() {
return c.atMs;
},
cancel,
stop: async () => {
cancel();
await c.running;
}
};
}
cancel(e) {
e.cancelled = true;
if (!e.running) e.owner?.jobs.delete(e);
if (this.jobs.get(e.id) === e) {
this.jobs.delete(e.id);
this.arm();
}
}
/** Stop wakeups and admission without retiring authority held by accepted work. */
fence() {
this.fenced = true;
this.cancelTimer?.();
this.cancelTimer = void 0;
for (const e of this.jobs.values()) this.cancel(e);
this.jobs.clear();
}
beginClose() {
this.fence();
this.controller.abort();
materializeErrorStack(this.controller.signal.reason);
}
async stop() {
this.beginClose();
await Promise.all(this.pending);
}
remaining(e, t, n) {
const r = e.atMs - t;
return e.elapsedAtMs === void 0 ? r : Math.min(r, e.elapsedAtMs - n);
}
arm() {
if (this.fenced || this.dispatching) return;
this.cancelTimer?.();
this.cancelTimer = void 0;
const e = this.nextWakeAtMs;
if (e !== null) {
const t = this.now();
const n = Math.min(2147483647, Math.max(0, Math.ceil(e - t)));
this.cancelTimer = runInDetachedAsyncContext(() => this.clock.arm(() => this.wake(t + n), n));
}
}
wake(e) {
this.cancelTimer = void 0;
if (this.fenced) return;
const t = this.now();
const n = this.clock.monotonicNow();
const r = [...this.jobs.values()].filter((e) => !e.running && this.remaining(e, t, n) <= 0).toSorted((e, r) => this.remaining(e, t, n) - this.remaining(r, t, n));
let i;
if (t - e > 6e4) log.debug(`late wake by ${t - e}ms; coalescing ${r.length} due jobs`);
this.dispatching = true;
try {
for (const e of r) {
if (this.fenced || e.cancelled || e.owner?.signal.aborted || this.jobs.get(e.id) !== e) continue;
if (e.everyMs === void 0) this.jobs.delete(e.id);
const t = this.run(e);
if (t) (i ??= []).push(t);
}
} finally {
this.dispatching = false;
this.arm();
}
return i ? Promise.all(i).then(() => void 0) : void 0;
}
run(e) {
log[e.everyMs === void 0 ? "debug" : "trace"](`running ${e.id}`);
const t = createDeferredCore();
const n = new AsyncWorkScope();
e.running = t.promise;
this.pending.add(t.promise);
const finish = () => {
e.running = void 0;
this.pending.delete(t.promise);
if (e.everyMs !== void 0 && !e.cancelled && !this.fenced) {
if (e.phase === "maintenance") {
e.atMs = Math.floor(e.atMs / 1e4) * 1e4;
e.atMs = nextMaintenanceSlot(e.atMs, this.now(), e.everyMs);
} else {
e.atMs = this.now() + e.everyMs;
e.elapsedAtMs = this.clock.monotonicNow() + e.everyMs;
}
} else e.owner?.jobs.delete(e);
t.resolve();
this.arm();
};
let r = void 0;
try {
r = e.context(() => runWithMainThreadTask(e.diagnosticName, () => n.run(e.run)));
} catch (t) {
log.error(`${e.id} failed: ${String(t)}`);
}
if (!r && !n.hasPendingWork) {
finish();
return;
}
Promise.resolve(r).catch((t) => log.error(`${e.id} failed: ${String(t)}`)).then(() => AsyncWorkScope.runWhenAllIdle(() => [n], () => n.drain())).finally(finish);
return t.promise;
}
};
//#endregion
export { GatewayScheduler as t };