openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
66 lines (65 loc) • 2.86 kB
JavaScript
//#region src/shared/global-singleton.ts
/**
* Process-local singleton helpers for registries, caches, and SDK-visible shared state.
* Keys must be symbols so unrelated modules cannot collide on `globalThis` property names.
*/
const GLOBAL_SINGLETON_RESETS_KEY = Symbol.for("openclaw.globalSingletonLifecycleResets");
function resolveGlobalSingletonResetRegistry() {
const e = globalThis;
const t = e[GLOBAL_SINGLETON_RESETS_KEY];
if (t instanceof Map) return t;
const n = /* @__PURE__ */ new Map();
e[GLOBAL_SINGLETON_RESETS_KEY] = n;
return n;
}
/** Observe an existing owner's state without initializing it or registering cleanup. */
function readGlobalSingleton(e) {
const t = globalThis;
return Object.hasOwn(t, e) ? t[e] : void 0;
}
/** Resolves a process-local singleton for caches and registries that tolerate helper lookup. */
function resolveGlobalSingleton(e, t, n, r = "close-and-restart") {
const i = globalThis;
let a;
if (Object.hasOwn(i, e)) a = i[e];
else {
a = t();
i[e] = a;
}
if (n) resolveGlobalSingletonResetRegistry().set(e, {
lifecycle: r,
reset: () => n(a)
});
return a;
}
/** Resolves a process-local Map singleton for keyed caches backed by globalThis. */
function resolveGlobalMap(e, t, n) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Map(), typeof t === "string" ? (e) => e.clear() : t, typeof t === "string" ? t : n);
}
/** Resolves a lifecycle-owned process-local Set singleton. */
function resolveGlobalSet(e, t) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Set(), (e) => e.clear(), t);
}
/** Resets every opt-in singleton while preserving shared object identity for the next lifecycle. */
async function drainGlobalSingletonLifecycleState(e = "close", t = {}) {
const n = [...resolveGlobalSingletonResetRegistry().entries()].filter(([, { lifecycle: n }]) => {
if (e === "shared-state") return n === "shared-state";
if (n === "shared-state") return e !== "plugin-registry" && !t.retainSharedState;
if (e === "plugin-registry") return n === "plugin-registry";
if (n === "plugin-registry") return false;
return e === "close" || n === "close-and-restart";
}).map(([e, { reset: n }]) => {
const runReset = () => {
try {
return Promise.resolve(n());
} catch (e) {
return Promise.reject(e instanceof Error ? e : new Error("Global singleton reset failed", { cause: e }));
}
};
return t.measureReset ? t.measureReset(e.description ?? String(e), runReset) : runReset();
});
const r = (await Promise.allSettled(n)).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (r.length > 0) throw new AggregateError(r, "Failed to reset global singleton lifecycle state");
}
//#endregion
export { resolveGlobalSingleton as a, resolveGlobalSet as i, readGlobalSingleton as n, resolveGlobalMap as r, drainGlobalSingletonLifecycleState as t };