UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

180 lines (179 loc) • 5.34 kB
import { n as materializeErrorStack } from "../../error-graph-internal-DdjdM90N.mjs"; import { n as inspectPostgresGeneration, r as lockPostgresGeneration, t as fingerprintPostgresGeneration } from "../../postgres-generation-D3b-yckQ.mjs"; import { parentPort, workerData } from "node:worker_threads"; import pg from "pg"; //#region src/infra/postgres-sync/bridge.worker.ts const { host: serviceHost, peers } = workerData; function watchPeer({ port: e, signal: t }) { e.on("close", () => { const e = new Int32Array(t); Atomics.store(e, 1, 1); Atomics.notify(e, 1); }); } peers.forEach(watchPeer); parentPort?.on("message", (e) => watchPeer(e.watch)); function attachHost(e) { const t = /* @__PURE__ */ new Set(); e.on("message", (e) => { if ("host" in e) attachHost(e.host); else attachConnection(e.connection, t); }); e.on("close", () => { for (const e of t) e(); }); } function attachConnection(e, t) { const { port: n, signal: r, url: i, connectTimeoutMs: a, lockTimeoutMs: o, statementTimeoutMs: s } = e; let c = e.schema; const l = new Int32Array(r); let u; let d; const close = () => { t.delete(close); n.close(); u?.end().catch(() => {}); }; t.add(close); n.on("close", close); function send(e) { n.postMessage(e); Atomics.store(l, 0, e.id); Atomics.notify(l, 0); } async function connect(e) { const t = `"${e.replaceAll("\"", "\"\"")}"`; if (u) await u.end().catch(() => {}); d = void 0; u = new pg.Client({ connectionString: i, connectionTimeoutMillis: a, types: { getTypeParser: (e, t) => (e === pg.types.builtins.JSON || e === pg.types.builtins.JSONB) && t !== "binary" ? (e) => e : pg.types.getTypeParser(e, t) } }); u.on("error", (e) => { materializeErrorStack(e); d = e; }); await u.connect(); await u.query("SELECT set_config('lock_timeout', $1, false), set_config('statement_timeout', $2, false), set_config('search_path', $3, false)", [ `${o}ms`, `${s}ms`, t ]); c = e; } async function useSchema(e, t, n) { if (d) { if (!t || u.getTransactionStatus() !== "I") throw d; await connect(e); return; } if (c === e && !n) return; if (u.getTransactionStatus() !== "I") throw new Error("Cannot switch PostgreSQL schemas inside a transaction"); try { if (c === e) await u.query("SELECT 1"); else await u.query("SELECT set_config('search_path', $1, false)", [`"${e.replaceAll("\"", "\"\"")}"`]); c = e; } catch { await connect(e); } } async function handleRequest(e) { let t; try { if (e.operation === "connect") { await connect(e.schema); t = { id: e.id, result: { inTransaction: false, rows: [], rowCount: 0, fields: [] } }; } else if (e.operation === "close") { await u.end(); t = { id: e.id, result: { inTransaction: false, rows: [], rowCount: 0, fields: [] } }; } else if (e.operation === "release") { if (d) throw d; const n = u.getTransactionStatus() === "I"; if (!n) await u.end(); t = { id: e.id, reusable: n }; } else if (e.operation === "recovery-generation") { await useSchema(e.schema, e.reconnectIfIdle === true, e.validateIfIdle === true); if (e.lock) await lockPostgresGeneration(u, c); const n = { namespace: c, storeId: e.storeId }; const r = fingerprintPostgresGeneration(n, await inspectPostgresGeneration(u, n)); t = { id: e.id, generation: r, inTransaction: u.getTransactionStatus() !== "I" }; } else { await useSchema(e.schema, e.reconnectIfIdle === true, e.validateIfIdle === true); const n = await u.query(e.sql, [...e.parameters]); const r = Array.isArray(n) ? n.at(-1) : n; const i = (Array.isArray(n) ? n : [n]).map(({ command: e }) => e); const a = i.some((e) => /^(?:CREATE|ALTER|DROP|TRUNCATE|COMMENT|GRANT|REVOKE|COPY|CALL|DO|REFRESH)$/.test(e)) ? "unscoped" : i.some((e) => /^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(e)) ? "scoped" : void 0; t = { id: e.id, result: { inTransaction: u.getTransactionStatus() !== "I", command: r.command, mutation: a, rows: r.rows, rowCount: r.rowCount ?? 0, fields: r.fields.map(({ name: e, dataTypeID: t }) => ({ name: e, dataTypeID: t })) } }; } } catch (n) { const r = n instanceof Error ? n : new Error(String(n)); const i = e.operation === "connect" ? /* @__PURE__ */ new Error(`PostgreSQL connection failed: ${r.message}. Check database.postgres.connection, network, and credentials.`) : r; if (e.operation === "connect") i.name = "PostgresConnectionError"; const a = { name: i.name, message: i.message, stack: i.stack }; if (e.operation === "connect" && "code" in r && typeof r.code === "string") a.code = r.code; if (n instanceof pg.DatabaseError) Object.assign(a, { code: n.code, detail: n.detail, constraint: n.constraint, column: n.column }); t = { id: e.id, error: a }; } send(t); if (e.operation === "close" || e.operation === "connect" && "error" in t || "reusable" in t && !t.reusable) close(); } n.on("message", (e) => { handleRequest(e); }); } attachHost(serviceHost); parentPort?.postMessage({ poolReady: true }, []); //#endregion export {};