openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
365 lines (364 loc) • 14.4 kB
JavaScript
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs";
import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { l as quoteSqliteIdentifier } from "./sqlite-schema-sql-CPyk_2Hd.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { n as openNodeSqliteDatabase, r as resolveExistingSqliteFileUri } from "./node-sqlite-CU4puofF.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { M as parseGatewayLockPayload, g as defaultPayload, j as describeGatewayLockHolder, t as acquireGatewayStateOwner } from "./gateway-state-owner-Bnv5owvG.mjs";
import { t as acquireFileLockSync } from "./file-lock-manager-DJ_fctTe.mjs";
import { r as prepareSqliteReadOnlyLocation } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { t as stateEngineInput } from "./openclaw-state-db-engine-input-Dy8v5WSG.mjs";
import { a as isStatePostgres, c as stateEngineSchema } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { S as releaseOpenClawStateLeaseInTransaction, f as GATEWAY_OWNER_LEASE_COLUMNS_SQL, h as gatewayOwnerKey, m as decodeGatewayOwnerLease, p as assertGatewayOwnerLeaseColumns, v as readOpenClawStateLease } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs";
import { d as resolveGatewayOwnerStatus, u as resolveGatewayLockPaths } from "./gateway-lock-IYOwJQai.mjs";
import { i as readEngineAnchorIdentity } from "./physical-store-inspection-C7yPt-uR.mjs";
import { i as withPostgresConnection, r as readPostgresStoreMetadata } from "./postgres-store-metadata-CcC14HrG.mjs";
import fs from "node:fs";
import { createHash } from "node:crypto";
//#region src/infra/gateway-lock-recovery-lease.ts
/** Recovery inspects a private snapshot without borrowing the unverified owner's authority. */
async function inspectGatewayRecoveryLease(e) {
if (!fs.existsSync(e)) return null;
const t = await prepareSqliteReadOnlyLocation(e, {
allowLiveOwner: true,
preserveSourceArtifacts: true
});
let n = null;
const r = [];
try {
const e = openNodeSqliteDatabase(t.location, { readOnly: true });
try {
n = tableExists(e, "state_leases") ? readOpenClawStateLease(e, gatewayOwnerKey) ?? null : null;
} finally {
e.close();
}
} catch (e) {
r.push(e);
}
try {
if (!await t.cleanupAsync()) r.push(/* @__PURE__ */ new Error("Gateway recovery inspection snapshot cleanup did not finish."));
} catch (e) {
r.push(e);
}
throwSqliteLifecycleErrors(r, "Gateway recovery inspection or cleanup failed.");
return n;
}
function assertGatewayRecoveryLeaseNotLive(e) {
if (e && decodeGatewayOwnerLease(e)?.state === "live") throw new Error("Gateway owner lease is still live; stop the holder before recovering its lock.");
}
/** CLI-only repair: physical custody and the exact reviewed row guard this deletion. */
function removeGatewayRecoveryLease(e, t, n) {
n.assertDatabaseAccess(e);
if (!fs.existsSync(e)) {
if (t) throw new Error("Gateway state database changed; inspect the lock again.");
return;
}
const r = openNodeSqliteDatabase(resolveExistingSqliteFileUri(e));
try {
runSqliteImmediateTransactionSync(r, () => {
n.assertDatabaseAccess(e);
const i = tableExists(r, "state_leases") ? readOpenClawStateLease(r, gatewayOwnerKey) ?? null : null;
if (JSON.stringify(i) !== JSON.stringify(t)) throw new Error("Gateway owner lease changed; inspect the lock again.");
assertGatewayRecoveryLeaseNotLive(i);
if (i) releaseOpenClawStateLeaseInTransaction(r, {
...gatewayOwnerKey,
owner: i.owner
});
}, {
databaseLabel: e,
operationLabel: "gateway.lock-recovery"
});
} finally {
r.close();
}
}
//#endregion
//#region src/infra/gateway-lock-recovery-postgres.ts
/** Lease inspection can outlive an application schema; destructive recovery cannot. */
function assertPostgresGatewayRecoveryMutationSupported(e) {
if (e.version !== stateEngineSchema.version) throw new Error(`PostgreSQL GLOBAL schema version ${e.version} is not supported for Gateway lock recovery by this binary (expected ${stateEngineSchema.version}); use the matching OpenClaw version.`);
}
function selectedPostgres() {
const e = stateEngineInput();
if (!e) throw new Error("PostgreSQL Gateway recovery selection changed");
return {
input: e,
connection: createHash("sha256").update(e.connection).digest("hex")
};
}
function leaseTimestamp(e) {
if (typeof e !== "string" || !/^-?\d+$/.test(e) || !Number.isSafeInteger(Number(e))) throw new Error("PostgreSQL Gateway owner lease has an invalid timestamp");
return Number(e);
}
async function readLease(e, t, n = false) {
const { rows: r } = await e.query(`SELECT row_to_json(lease)::text AS raw, owner, created_at::text,
expires_at::text, heartbeat_at::text, payload_json
FROM ${quoteSqliteIdentifier(t.namespace)}.state_leases AS lease
WHERE scope = 'gateway-owner' AND lease_key = 'global'${n ? " FOR UPDATE" : ""}`);
if (r.length > 1) throw new Error("PostgreSQL Gateway owner lease is ambiguous");
const i = r[0];
if (!i) return {
raw: null,
lease: null
};
const a = {
owner: i.owner,
createdAt: leaseTimestamp(i.created_at),
expiresAt: i.expires_at === null ? null : leaseTimestamp(i.expires_at),
heartbeatAt: i.heartbeat_at === null ? null : leaseTimestamp(i.heartbeat_at),
payloadJson: i.payload_json
};
if (typeof i.owner !== "string" || !i.owner || typeof i.raw !== "string" || !decodeGatewayOwnerLease(a)) throw new Error("PostgreSQL Gateway owner lease could not be verified");
return {
raw: i.raw,
lease: a
};
}
async function stateVersion(e, t) {
const n = await readPostgresStoreMetadata(e, t);
if (n.store !== "state" || n.version < 1) throw new Error("PostgreSQL Gateway recovery requires a verified state store");
assertGatewayOwnerLeaseColumns((await e.query(GATEWAY_OWNER_LEASE_COLUMNS_SQL, [t.namespace])).rows);
return n.version;
}
async function transaction(e, t, n, r) {
await e.query(t ? "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY" : "BEGIN");
try {
await e.query("SET LOCAL lock_timeout = '5000ms'");
await e.query("SET LOCAL statement_timeout = '5000ms'");
const i = await n();
r?.();
const a = await e.query(t ? "ROLLBACK" : "COMMIT");
if (!t && a.command !== "COMMIT") throw new Error("PostgreSQL Gateway recovery transaction did not commit");
return i;
} catch (t) {
try {
await e.query("ROLLBACK");
} catch (e) {
throw new AggregateError([t, e], "PostgreSQL Gateway recovery rollback failed", { cause: e });
}
throw t;
}
}
async function inspectPostgresGatewayRecovery(e) {
const { input: t, connection: n } = selectedPostgres();
const r = readDatabasePathIdentitySync(e);
const i = await prepareSqliteReadOnlyLocation(e, {
allowLiveOwner: true,
preserveSourceArtifacts: true,
requireCleanup: true
});
const cleanup = async (e) => {
if (!await i.cleanupAsync()) {
const t = /* @__PURE__ */ new Error("PostgreSQL Gateway recovery anchor inspection cleanup did not finish");
if (e !== void 0) throw new AggregateError([e, t], t.message, { cause: e });
throw t;
}
};
let a;
try {
try {
var o = _usingCtx();
const s = o.u(openNodeSqliteDatabase(i.location, { readOnly: true }));
const c = readEngineAnchorIdentity(s, e);
if (c.engine !== "postgres") throw new Error("PostgreSQL Gateway recovery requires its original anchor");
const l = await withPostgresConnection(t, (e) => transaction(e, true, async () => ({
version: await stateVersion(e, c),
...await readLease(e, c)
})), {
connectionTimeoutMillis: 1e4,
query_timeout: 1e4
});
if (JSON.stringify(readDatabasePathIdentitySync(e)) !== JSON.stringify(r) || selectedPostgres().connection !== n) throw new Error("PostgreSQL Gateway recovery anchor or selection changed during inspection");
a = {
anchor: c,
identity: r,
connection: n,
...l
};
} catch (e) {
o.e = e;
} finally {
o.d();
}
} catch (e) {
await cleanup(e);
throw e;
}
await cleanup();
return a;
}
async function recoverPostgresGatewayLease(e, t, n) {
const assertCurrent = () => n.run(() => {
try {
var r = _usingCtx();
n.assertDatabaseAccess(e);
if (selectedPostgres().connection !== t.connection || JSON.stringify(readDatabasePathIdentitySync(e)) !== JSON.stringify(t.identity)) throw new Error("PostgreSQL Gateway recovery anchor or selection changed");
const i = r.u(openNodeSqliteDatabase(e, { readOnly: true }));
if (JSON.stringify(readEngineAnchorIdentity(i, e)) !== JSON.stringify(t.anchor)) throw new Error("PostgreSQL Gateway recovery anchor changed");
} catch (e) {
r.e = e;
} finally {
r.d();
}
});
assertCurrent();
const { input: r } = selectedPostgres();
await withPostgresConnection(r, (e) => transaction(e, false, async () => {
assertCurrent();
const n = createHash("sha256").update(t.anchor.storeId).digest().readBigInt64BE().toString();
const r = await e.query("SELECT pg_try_advisory_xact_lock($1::bigint) AS acquired", [n]);
assertCurrent();
if (r.rows[0]?.acquired !== true) throw new Error("PostgreSQL Gateway recovery store is busy; inspect again after its operation settles");
if (await stateVersion(e, t.anchor) !== t.version) throw new Error("PostgreSQL Gateway recovery state metadata changed");
assertCurrent();
const i = await readLease(e, t.anchor, true);
assertCurrent();
if (i.raw !== t.raw) throw new Error("PostgreSQL Gateway owner lease changed; inspect the lock again");
assertGatewayRecoveryLeaseNotLive(i.lease);
if (i.lease) {
if ((await e.query(`DELETE FROM ${quoteSqliteIdentifier(t.anchor.namespace)}.state_leases AS lease
WHERE scope = 'gateway-owner' AND lease_key = 'global' AND owner = $1 AND row_to_json(lease)::text = $2`, [i.lease.owner, i.raw])).rowCount !== 1) throw new Error("PostgreSQL Gateway owner lease changed before recovery");
}
}, assertCurrent), {
connectionTimeoutMillis: 1e4,
query_timeout: 1e4
});
}
//#endregion
//#region src/infra/gateway-lock-recovery.ts
function readObservedFile(e) {
let t;
try {
t = fs.openSync(e, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
} catch (e) {
if (extractErrorCode(e) === "ENOENT") return null;
throw e;
}
try {
const n = fs.fstatSync(t, { bigint: true });
if (!n.isFile() || n.nlink !== 1n) throw new Error(`Gateway recovery requires a regular, single-link lock file: ${e}`);
const r = fs.readFileSync(t, "utf8");
return {
path: e,
raw: r,
identity: [
n.dev,
n.ino,
n.birthtimeNs,
n.ctimeNs,
n.mtimeNs,
n.size
].join(":"),
holder: parseGatewayLockPayload(r)
};
} finally {
fs.closeSync(t);
}
}
function sameObservation(e, t) {
return e?.identity === t?.identity && e?.raw === t?.raw;
}
async function inspectGatewayLockRecovery(e = {}) {
const t = e.env ?? process.env;
const n = resolveGatewayLockPaths(t);
const r = [
n.ownerLockPath,
n.stateLockPath,
n.configLockPath
].map((e) => ({
path: e,
observed: readObservedFile(e)
}));
const i = resolveOpenClawStateSqlitePath(t);
const a = isStatePostgres() ? await inspectPostgresGatewayRecovery(i) : void 0;
const o = a ? a.lease : await inspectGatewayRecoveryLease(i);
const s = createHash("sha256").update(JSON.stringify({
databasePath: i,
files: r,
lease: o,
postgres: a
})).digest("hex");
const c = r.flatMap(({ observed: e }) => e ? [`${e.path}: ${describeGatewayLockHolder(e.holder ?? {}, e.path, "unknown")}`] : []);
if (o) c.push(`${a ? "PostgreSQL" : "SQLite"} Gateway owner lease: ${describeGatewayLockHolder(decodeGatewayOwnerLease(o) ?? {}, void 0, "unknown")}`);
return {
databasePath: i,
files: r,
lease: o,
postgres: a,
confirmation: s,
holders: c,
present: c.length > 0
};
}
/** Explicit operator confirmation is bound to file identity, bytes, heartbeat and lease facts. */
async function recoverGatewayLock(e) {
const t = await inspectGatewayLockRecovery();
if (t.confirmation !== e.confirmation) throw new Error("Gateway lock or heartbeat changed since inspection; run `openclaw gateway recover-lock` again.");
if (t.postgres) assertPostgresGatewayRecoveryMutationSupported(t.postgres);
if (!t.present) return {
recovered: false,
removed: 0
};
assertGatewayRecoveryLeaseNotLive(t.lease);
for (const { observed: e } of t.files) {
if (!e?.holder) continue;
const t = await resolveGatewayOwnerStatus(e.holder.pid, e.holder, process.platform, { lockPath: e.path });
if (t === "alive" || t !== "dead" && process.platform === "win32" && e.holder.processNamespace === void 0) throw new Error(`Gateway holder ${e.holder.pid} ${t === "alive" ? "is still live" : "could not be verified dead"}; stop it before recovering its lock.`);
}
const n = defaultPayload(t.databasePath);
const r = [];
let i;
const a = [];
try {
for (const { path: e, observed: i } of t.files) {
const unchanged = () => {
if (!sameObservation(readObservedFile(e), i)) throw new Error(`Gateway lock changed at ${e}; inspect the lock again.`);
return true;
};
unchanged();
r.push(acquireFileLockSync(e, {
lockPath: e,
retry: { retries: 0 },
timeoutMs: 0,
staleRecovery: "remove-if-unchanged",
reentrantOwner: n.ownerId,
payload: () => n,
parsePayload: (e) => ({ raw: e }),
shouldReclaim: unchanged,
shouldRemoveStaleLock: ({ raw: e }) => {
unchanged();
return e === i?.raw;
}
}));
}
const e = acquireGatewayStateOwner({
databasePath: t.databasePath,
payload: n
});
i = e;
if (t.postgres) await recoverPostgresGatewayLease(t.databasePath, t.postgres, e);
else e.run(() => removeGatewayRecoveryLease(t.databasePath, t.lease, e));
} catch (e) {
a.push(e);
}
try {
i?.release();
} catch (e) {
a.push(e);
}
for (const e of r.toReversed()) try {
e.release();
} catch (e) {
a.push(e);
}
throwSqliteLifecycleErrors(a, "Gateway lock recovery or cleanup failed.");
return {
recovered: t.present,
removed: t.holders.length
};
}
//#endregion
export { inspectGatewayLockRecovery, recoverGatewayLock };