openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
254 lines (253 loc) • 7.34 kB
JavaScript
import { F as resolveNonNegativeIntegerOption, I as resolveOptionalIntegerOption } from "./number-coercion-D6u-4YD8.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { T as runWithGatewayIndependentRootWorkContinuation } from "./gateway-work-admission-79pid1hQ.mjs";
//#region src/auto-reply/inbound-debounce.ts
/** Resolve effective inbound debounce milliseconds from explicit, channel, and global config. */
function resolveInboundDebounceMs(e) {
const t = e.cfg.messages?.inbound;
return resolveOptionalIntegerOption(e.overrideMs, { min: 0 }) ?? t?.byChannel?.[e.channel] ?? t?.debounceMs ?? 0;
}
/**
* Start one flush and bind its admission signal to the turn lifecycle.
* Completion also releases admission for gated work that never enters a session lane.
*/
function createInboundDebounceFlush(e) {
let t = false;
const { promise: n, resolve: r } = createDeferredCore();
const markAdmitted = () => {
t = true;
r();
};
const i = e.lifecycle;
const a = {
abortSignal: i?.abortSignal ?? new AbortController().signal,
onAdopted: async () => {
await i?.onAdopted?.();
markAdmitted();
},
onDeferred: () => {
const e = i?.onDeferred?.();
if (e !== false) markAdmitted();
return e;
},
onDeferredHeartbeat: () => i?.onDeferredHeartbeat?.(),
deferredHeartbeatIntervalMs: i?.deferredHeartbeatIntervalMs,
onAdoptionFinalizing: () => i?.onAdoptionFinalizing?.(),
onFailed: i?.onFailed ? async (e) => {
try {
await i.onFailed?.(e);
} finally {
markAdmitted();
}
} : void 0,
onAbandoned: async () => i?.onAbandoned?.()
};
return {
admission: n,
completion: runWithGatewayIndependentRootWorkContinuation(async () => e.dispatch(a), "channel:inbound-dispatch").catch(async (e) => {
const n = toErrorObject(e, "Inbound debounce dispatch failed");
if (!t && a.onFailed) await Promise.allSettled([a.onFailed(n)]);
throw n;
}).finally(markAdmitted)
};
}
const DEFAULT_MAX_TRACKED_KEYS = 2048;
const MAX_DEBOUNCE_WINDOW_MULTIPLIER = 5;
/** Create a keyed debouncer with flush/cancel controls and same-key serialization. */
function createInboundDebouncer(e) {
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Set();
const o = resolveNonNegativeIntegerOption(e.debounceMs, 0);
const s = Math.max(1, Math.trunc(e.maxTrackedKeys ?? DEFAULT_MAX_TRACKED_KEYS));
const resolveDebounceMs = (t, n) => {
const r = e.resolveDebounceMs?.(t, n);
return resolveNonNegativeIntegerOption(r, o);
};
const resolvePending = (n, r) => {
const i = t.get(r);
return i && (e.canAppend?.(n, i.items) ?? true) ? i : void 0;
};
const shouldBuffer = (t) => {
const n = e.buildKey(t);
return Boolean(n && resolveDebounceMs(t, resolvePending(t, n)?.items) > 0 && (e.shouldDebounce?.(t) ?? true));
};
const notifyObserver = (e) => {
try {
e();
} catch {}
};
const reportFlushError = (t, n) => notifyObserver(() => e.onError?.(t, n));
const cancelItems = (t) => notifyObserver(() => e.onCancel?.(t));
const runFlush = async (t) => {
let n;
try {
const r = e.onFlush(t, createInboundDebounceFlush);
if ("then" in r) {
const e = Promise.resolve(r);
n = {
admission: e,
completion: e
};
} else n = r;
} catch (e) {
reportFlushError(e, t);
return;
}
let r = false;
const reportOnce = (e) => {
if (r) return;
r = true;
reportFlushError(e, t);
};
const i = n.admission.catch(reportOnce);
const o = n.completion.catch(reportOnce);
a.add(o);
o.then(() => a.delete(o));
await Promise.race([i, o]);
};
const untrackKeyTask = (e, t) => {
if (i.get(e) === t) i.delete(e);
};
const enqueueKeyTask = (e, t) => {
const n = i.get(e);
const r = n ? n.then(t) : t();
const a = r.catch(() => void 0);
i.set(e, a);
a.then(() => untrackKeyTask(e, a));
return r;
};
const enqueueImmediate = (e, t) => {
const n = [t];
const i = r.get(e) ?? /* @__PURE__ */ new Set();
i.add(n);
r.set(e, i);
return enqueueKeyTask(e, async () => {
i.delete(n);
if (i.size === 0) r.delete(e);
if (n.length > 0) await runFlush(n);
});
};
const detachBuffer = (e, n) => {
if (t.get(e) === n) t.delete(e);
if (n.timeout) {
clearTimeout(n.timeout);
n.timeout = null;
}
};
const flushBuffer = async (e, t) => {
detachBuffer(e, t);
t.releaseReady();
await t.task;
};
const flushKey = async (e) => {
const n = t.get(e);
if (!n) return;
await flushBuffer(e, n);
};
const cancelKey = (e) => {
const t = n.get(e);
if (!t?.size && !i.has(e)) return false;
for (const n of t ?? []) {
detachBuffer(e, n);
const t = n.items;
n.items = [];
cancelItems(t);
n.releaseReady();
}
for (const t of r.get(e) ?? []) if (t.length > 0) cancelItems(t.splice(0));
n.delete(e);
return true;
};
const settleQuietFlush = async (n, r) => {
if (!e.shouldHoldFlush || performance.now() >= r.flushDeadlineMs) {
await flushBuffer(n, r);
return;
}
r.timeout = setTimeout(() => {
flushBuffer(n, r);
}, Math.max(0, r.flushDeadlineMs - performance.now()));
r.timeout.unref?.();
let i;
try {
i = await e.shouldHoldFlush(r.items);
} catch {
i = false;
}
if (t.get(n) !== r) return;
if (i) scheduleFlush(n, r);
else await flushBuffer(n, r);
};
const scheduleFlush = (t, n) => {
if (n.timeout) clearTimeout(n.timeout);
const r = Math.min(n.debounceMs, Math.max(0, n.flushDeadlineMs - performance.now()));
n.timeout = setTimeout(() => {
if (e.shouldHoldFlush) settleQuietFlush(t, n);
else flushBuffer(t, n);
}, r);
n.timeout.unref?.();
};
const enqueue = async (r) => {
const a = e.buildKey(r);
const o = a ? resolvePending(r, a) : void 0;
const c = resolveDebounceMs(r, o?.items);
if (!(c > 0 && (e.shouldDebounce?.(r) ?? true)) || !a) {
if (a && (t.has(a) || i.has(a) || e.serializeImmediate)) {
flushKey(a);
await enqueueImmediate(a, r);
return;
}
await runFlush([r]);
return;
}
if (o) {
o.items.push(r);
o.debounceMs = c;
scheduleFlush(a, o);
return;
}
if (t.has(a)) flushKey(a);
if (!(i.has(a) || i.size < s)) {
await enqueueImmediate(a, r);
return;
}
const { promise: l, resolve: u } = createDeferredCore();
const d = enqueueKeyTask(a, async () => {
await l;
const e = n.get(a);
e?.delete(f);
if (e?.size === 0) n.delete(a);
if (f.items.length === 0) return;
await runFlush(f.items);
});
const f = {
items: [r],
timeout: null,
debounceMs: c,
flushDeadlineMs: performance.now() + Math.max(c, resolveNonNegativeIntegerOption(typeof e.maxWaitMs === "function" ? e.maxWaitMs(r) : e.maxWaitMs, c * MAX_DEBOUNCE_WINDOW_MULTIPLIER)),
releaseReady: u,
task: d
};
t.set(a, f);
const p = n.get(a) ?? /* @__PURE__ */ new Set();
p.add(f);
n.set(a, p);
scheduleFlush(a, f);
};
const drain = async () => {
while (i.size > 0 || a.size > 0) await Promise.all([...i.values(), ...a]);
};
return {
enqueue,
shouldBuffer,
flushKey,
cancelKey,
drain
};
}
//#endregion
export { resolveInboundDebounceMs as n, createInboundDebouncer as t };