UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

227 lines (226 loc) • 9.6 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { a as pluginInstanceInvocation } from "./plugin-instance-invocation-Bq_toGDw.mjs"; import { _ as wrapCurrentPluginInstance, a as getPluginInstanceOwner, d as pluginInstanceState, p as resolvePluginInstanceOwner } from "./plugin-instance-scope-oezVdCr2.mjs"; import { x as isPluginRegistryRetired } from "./registry-lifecycle-CJjWnl-y.mjs"; import { D as getPluginHttpRouteViews, I as normalizePluginHttpPath, M as replacePluginHttpRoutes, N as respondPluginHttpRouteHandoff, O as isPluginHttpRouteVisible, k as notifyPluginHttpRoutesChanged, v as requireActivePluginRegistry } from "./runtime-ezCEpumg.mjs"; import { t as findPluginHttpRouteRegistrationConflicts } from "./http-route-overlap-xGPgAXgh.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/plugins/http-registry.ts const pluginHttpRouteRegistryScope = resolveGlobalSingleton(Symbol.for("openclaw.pluginHttpRouteRegistryScope"), () => new AsyncLocalStorage()); const routeOwners = resolveGlobalSingleton(Symbol.for("openclaw.pluginHttpRouteRetentionOwners"), () => /* @__PURE__ */ new WeakMap()); const leasedRoutes = resolveGlobalSingleton(Symbol.for("openclaw.pluginHttpRouteLeaseRetentions"), () => /* @__PURE__ */ new WeakMap()); const noopUnregister = () => {}; function removeOwnedRoute(e, t) { e.removeRoute(); for (const [n, r] of e.handoffs) { n.delete(e); if (t) { n.add(t); t.handoffs.set(n, r); } } e.handoffs.clear(); routeOwners.delete(e.entry); if (t) updateLegacyListeners(t); } function retireUnheldRoute(e) { if (e.holders.size > 0) return; if (e.handoffs.size === 0 || !isPluginHttpRouteVisible(e.entry)) removeOwnedRoute(e); else if (!e.entry.handoff) { const t = e.entry; e.entry = { ...t, handoff: true, handleUpgrade: void 0, handler: respondPluginHttpRouteHandoff }; e.removeRoute = replacePluginHttpRoutes(e.registry, e.entry, [t], true); routeOwners.delete(t); routeOwners.set(e.entry, e); } } /** Keep retired ingress retryable until a successor claims it or every replacement ends. */ function createPluginHttpRouteHandoff() { const e = /* @__PURE__ */ new Set(); return { park(t) { for (const { owner: n, legacyListener: r } of leasedRoutes.get(t) ?? []) if (isPluginHttpRouteVisible(n.entry)) { e.add(n); const t = n.handoffs.get(e) ?? []; n.handoffs.set(e, r && !t.includes(r) ? [...t, r] : t); } }, release() { for (const t of e) { t.handoffs.delete(e); updateLegacyListeners(t); retireUnheldRoute(t); } e.clear(); } }; } function updateLegacyListeners(e) { const t = new Map([...e.handoffs.values()].flat().map((e) => [`${e.host ?? "<unspecified>"}:${e.port}`, e])); const n = new Map(t); for (const r of e.holders.values()) if (r) { const e = `${r.host ?? "<unspecified>"}:${r.port}`; n.set(e, r); t.delete(e); } if (n.size) e.entry.legacyListeners = [...n.values()]; else delete e.entry.legacyListeners; if (t.size) e.entry.legacyListenerHandoffs = [...t.values()]; else delete e.entry.legacyListenerHandoffs; notifyPluginHttpRoutesChanged(); } function hasSameRouteOwner(e, t) { return e.auth === t.auth && normalizeOptionalString(e.pluginId) === normalizeOptionalString(t.pluginId) && normalizeOptionalString(e.source) === normalizeOptionalString(t.source); } function adoptPluginHttpRouteHandoffs(e, t) { if (e === t) return; const n = e.httpRoutes.flatMap((e) => { const n = routeOwners.get(e); if (!n || !e.handoff) return []; const r = findPluginHttpRouteRegistrationConflicts(t.httpRoutes, e); if (r.authOverlap || r.canonicalMatches.some((t) => !hasSameRouteOwner(t, e))) throw new Error(`plugin reload cannot replace HTTP route ownership at ${e.path}`); return [{ owner: n, replacement: r.canonicalMatches[0] }]; }); for (const { owner: e, replacement: r } of n) { if (r === e.entry) continue; if (r) removeOwnedRoute(e, routeOwners.get(r)); else { e.removeRoute(); e.registry = t; e.removeRoute = replacePluginHttpRoutes(t, e.entry); } } } function retainPluginHttpRoute(e) { const t = routeOwners.get(e.entry); if (!t) return noopUnregister; const n = { owner: t, legacyListener: e.legacyListener }; const r = []; const release = () => { if (!t.holders.delete(release)) return; for (const t of e.leases) leasedRoutes.get(t)?.delete(n); for (const e of r.splice(0)) e(); updateLegacyListeners(t); retireUnheldRoute(t); }; t.holders.set(release, e.legacyListener); updateLegacyListeners(t); for (const t of e.leases) { let e = leasedRoutes.get(t); if (!e) { e = /* @__PURE__ */ new Set(); leasedRoutes.set(t, e); } e.add(n); r.push(t.retain(release)); } return release; } function withPluginHttpRouteRegistry(e, t, n) { const r = pluginHttpRouteRegistryScope.getStore()?.leases ?? []; const i = n && !r.includes(n) ? [...r, n] : r; return pluginHttpRouteRegistryScope.run({ registry: new WeakRef(e), leases: i }, t); } function registerPluginHttpRoute(e) { const t = pluginHttpRouteRegistryScope.getStore(); const n = pluginInstanceInvocation.getStore()?.instance ?? pluginInstanceState.values.get(e.handler); let r = n ? getPluginInstanceOwner(n) : void 0; let i = r ? r.registry : e.registry ?? (t ? t.registry.deref() : requireActivePluginRegistry()); if (!n && i) { const t = i.plugins.find((t) => t.id === e.pluginId); r = t ? resolvePluginInstanceOwner(t, i) : void 0; if (r && !r.revoked) i = r.registry; } const a = e.accountId ? ` for account "${e.accountId}"` : ""; const rejectRegistration = (t) => { e.log?.(t); if (e.throwOnFailure) throw new Error(t); return noopUnregister; }; if (e.legacyListener && e.auth !== "plugin") return rejectRegistration("legacy webhook listeners require plugin authentication"); if (t?.leases.some((e) => !e.isActive())) return rejectRegistration("plugin runtime HTTP route lease is no longer active"); if (!i || r?.revoked || isPluginRegistryRetired(i)) return rejectRegistration("plugin HTTP route owner is no longer active"); const o = [...new Set(getPluginHttpRouteViews(i, e.pluginId, n).flatMap((e) => e.httpRoutes))]; const s = normalizePluginHttpPath(e.path, e.fallbackPath); if (!s) return rejectRegistration(`plugin: webhook path missing${a}`); const c = e.match ?? "exact"; const l = { path: s, match: c, auth: e.auth }; const { authOverlap: u, canonicalMatches: d } = findPluginHttpRouteRegistrationConflicts(o, l); if (u) return rejectRegistration(`plugin: route overlap denied at ${s} (${c}, ${e.auth})${a}; overlaps ${u.path} (${u.match}, ${u.auth}) owned by ${u.pluginId ?? "unknown-plugin"} (${u.source ?? "unknown-source"})`); const f = e.legacyListener; if (f) for (const t of o) { if (e.replaceExisting && d.includes(t)) continue; if (t.legacyListeners?.find((e) => e.port === f.port && e.host === f.host && !t.legacyListenerHandoffs?.includes(e) && (e.health?.path !== f.health?.path || e.health?.contentType !== f.health?.contentType || e.timeouts?.headers !== f.timeouts?.headers || e.timeouts?.request !== f.timeouts?.request || e.timeouts?.socket !== f.timeouts?.socket))) return rejectRegistration(`plugin: conflicting legacy webhook health or timeout profile at ${f.host ?? "<unspecified>"}:${f.port}${a}; registrations sharing a port must use the same profile`); } const p = { path: s, handler: wrapCurrentPluginInstance(e.handler), auth: e.auth, match: c, ...e.gatewayRuntimeScopeSurface ? { gatewayRuntimeScopeSurface: e.gatewayRuntimeScopeSurface } : {}, pluginId: e.pluginId, source: e.source }; const m = d[0]; if (m) { const n = normalizeOptionalString(e.pluginId); const r = normalizeOptionalString(e.source); const i = d.find((t) => !hasSameRouteOwner(t, e)); const o = e.replaceExisting || !i && d.every((e) => e.handoff); if (!o && e.reuseExistingSameOwner) { if (n !== void 0 && r !== void 0 && !i) { e.log?.(`plugin: reusing existing webhook path ${s} (${c}) (${n}/${r})`); return retainPluginHttpRoute({ entry: m, leases: t?.leases ?? [], legacyListener: e.legacyListener }); } const o = i ?? m; return rejectRegistration(`plugin: route reuse denied for ${s} (${c})${a}; owned by ${o.pluginId ?? "unknown-plugin"} (${o.source ?? "unknown-source"})`); } if (!o) return rejectRegistration(`plugin: route conflict at ${s} (${c})${a}; owned by ${m.pluginId ?? "unknown-plugin"} (${m.source ?? "unknown-source"})`); const l = d.find((e) => normalizeOptionalString(e.pluginId) !== n || n !== void 0 && normalizeOptionalString(e.source) !== r); if (l) return rejectRegistration(`plugin: route replacement denied for ${s} (${c})${a}; owned by ${l.pluginId ?? "unknown-plugin"} (${l.source ?? "unknown-source"})`); const u = e.pluginId ? ` (${e.pluginId})` : ""; e.log?.(`plugin: replacing stale webhook path ${s} (${c})${a}${u}`); } const h = { entry: p, registry: i, removeRoute: replacePluginHttpRoutes(i, p, d), holders: /* @__PURE__ */ new Map(), handoffs: /* @__PURE__ */ new Map() }; for (const e of d.toReversed()) { const t = routeOwners.get(e); if (t) removeOwnedRoute(t, h); } routeOwners.set(p, h); return retainPluginHttpRoute({ entry: p, leases: t?.leases ?? [], legacyListener: e.legacyListener }); } //#endregion export { withPluginHttpRouteRegistry as i, createPluginHttpRouteHandoff as n, registerPluginHttpRoute as r, adoptPluginHttpRouteHandoffs as t };