UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

224 lines (223 loc) • 8.1 kB
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { Et as _enum, Jn as string, Nt as array, Pn as number, Yt as discriminatedUnion, lr as uuid, qn as strictObject, xn as literal } from "./schemas-Cy6abvsu.mjs"; import fs from "node:fs"; import path from "node:path"; import { randomUUID } from "node:crypto"; //#region src/infra/database-port-recovery.ts const count = number().int().nonnegative(); const hash$1 = string().regex(/^[a-f0-9]{64}$/); const absolutePath = string().refine((e) => path.isAbsolute(e) && !e.includes("://")); const databasePortArtifactSchema = strictObject({ path: absolutePath, sha256: hash$1, size: count }); const location = discriminatedUnion("engine", [strictObject({ engine: literal("sqlite"), path: absolutePath }), strictObject({ engine: literal("postgres"), anchorPath: absolutePath, namespace: string().regex(/^[a-z_][a-z0-9_-]*$/) })]); const target = strictObject({ storeId: uuid(), sourceSchemaVersion: count, targetSchemaVersion: count, descriptorHash: hash$1, original: location, intended: location, originalCapture: databasePortArtifactSchema, verification: strictObject({ contentHash: hash$1, catalogHash: hash$1, allocationHash: hash$1, rowCount: count, ownerAdmitted: literal(true) }).nullable() }); const manifestSchema = strictObject({ version: literal(1), operationId: uuid(), revision: number().int().positive(), state: _enum([ "preparing", "publishing", "complete" ]), outcome: _enum(["ported", "rolled-back"]).optional(), root: strictObject({ stateDir: absolutePath, dev: string().regex(/^\d+$/), ino: string().regex(/^\d+$/) }), direction: strictObject({ from: _enum(["sqlite", "postgres"]), to: _enum(["sqlite", "postgres"]) }), originalConfig: array(databasePortArtifactSchema).min(1), artifacts: array(databasePortArtifactSchema), targets: array(target).min(1) }).superRefine((e, t) => { if (e.direction.from === e.direction.to || new Set(e.targets.map((e) => e.storeId)).size !== e.targets.length || e.targets.some((t) => t.original.engine !== e.direction.from || t.intended.engine !== e.direction.to || e.state !== "preparing" && e.outcome !== "rolled-back" && !t.verification) || e.state === "complete" !== Boolean(e.outcome)) t.addIssue({ code: "custom", message: "Invalid database port manifest state" }); }); /** Port recovery requires durable directories and atomic replacement of existing SQLite files. */ function assertDatabasePortPlatformSupported() { if (process.platform === "win32") throw new Error("Native Windows does not support SQLite ↔ PostgreSQL database port yet. Existing data and engine selection stay unchanged. Start with a fresh PostgreSQL setup on Windows, or run the port on Linux or macOS."); } function databasePortManifestPath(e) { return path.join(e, "recovery", "database-port", "manifest.json"); } var DatabasePortRecoveryError = class extends Error {}; function refusal(e) { const t = databasePortManifestPath(e); const n = `'${t.replaceAll("'", "'\\''")}'`; return new DatabasePortRecoveryError(`Database port recovery required at ${t}. Run openclaw database port --resume ${n} or openclaw database port --rollback ${n}.`); } function readManifest(e) { let t; try { t = fs.readFileSync(databasePortManifestPath(e), { encoding: "utf8", flag: fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW }); } catch (t) { if (hasErrnoCode(t, "ENOENT")) return; throw refusal(e); } try { return manifestSchema.parse(JSON.parse(t)); } catch { throw refusal(e); } } function assertDatabasePortStartupAllowed(e) { const t = readManifest(e); if (t && (t.state !== "complete" || t.root.stateDir !== e)) throw refusal(e); } function assertPrivate(e, t) { const n = fs.lstatSync(e); if ((t ? !n.isDirectory() : !n.isFile() || n.nlink !== 1) || (n.mode & 511) !== (t ? 448 : 384) || process.getuid && n.uid !== process.getuid()) throw new Error(`Database port recovery path must be privately owned: ${e}`); } function assertRoot(e, t) { const n = fs.lstatSync(e, { bigint: true }); const r = { stateDir: e, dev: String(n.dev), ino: String(n.ino) }; if (!n.isDirectory() || JSON.stringify(t.root) !== JSON.stringify(r)) throw refusal(e); } /** Called only after physical custody has been acquired. */ function assertDatabasePortRecoveryAllowed(e, t) { const n = databasePortManifestPath(e); const r = readManifest(e); if (t.manifestPath !== n || !r || r.operationId !== t.operationId || r.state === "complete" && t.action !== "resume" || t.action !== "resume" && t.action !== "rollback") throw refusal(e); assertRoot(e, r); assertPrivate(path.dirname(path.dirname(n)), true); assertPrivate(path.dirname(n), true); assertPrivate(n, false); return r; } function syncDatabasePortPath(e) { const t = fs.openSync(e, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); try { fs.fsyncSync(t); } finally { fs.closeSync(t); } } function ensurePrivateDirectory(e) { try { fs.mkdirSync(e, { mode: 448 }); syncDatabasePortPath(path.dirname(e)); } catch (e) { if (!hasErrnoCode(e, "EEXIST")) throw e; } assertPrivate(e, true); } /** Private recovery artifacts and manifest revisions share one durable publication primitive. */ function writeDatabasePortArtifact(e, t, n, r = false) { const i = path.join(path.dirname(e), `.manifest-${randomUUID()}.tmp`); const a = fs.openSync(i, "wx", 384); try { try { fs.writeFileSync(a, t); fs.fsyncSync(a); } finally { fs.closeSync(a); } n(); if (r) fs.renameSync(i, e); else { fs.linkSync(i, e); fs.unlinkSync(i); } syncDatabasePortPath(path.dirname(e)); } finally { fs.rmSync(i, { force: true }); } } function prepareDatabasePortDirectory(e, t) { const n = path.dirname(databasePortManifestPath(e)); const r = path.join(n, uuid().parse(t)); for (const e of [ path.dirname(n), n, r ]) ensurePrivateDirectory(e); return r; } function writeAtomic(e, t, n) { writeDatabasePortArtifact(e, `${JSON.stringify(t)}\n`, n, true); } /** The caller holds offline custody; every revision is durable before returning. */ function writeDatabasePortManifest(e, t, n) { const r = manifestSchema.parse(t); n(); assertRoot(e, r); const i = databasePortManifestPath(e); ensurePrivateDirectory(path.dirname(path.dirname(i))); ensurePrivateDirectory(path.dirname(i)); const a = readManifest(e); if (a) { assertPrivate(i, false); const immutable = (e) => JSON.stringify({ operationId: e.operationId, root: e.root, direction: e.direction, originalConfig: e.originalConfig, targets: e.targets.map(({ verification: e, ...t }) => t) }); const t = [ "preparing", "publishing", "complete" ]; if (immutable(a) !== immutable(r) || r.revision !== a.revision + 1 || a.state === "complete" || t.indexOf(r.state) < t.indexOf(a.state) || t.indexOf(r.state) > t.indexOf(a.state) + 1 && !(a.state === "preparing" && r.outcome === "rolled-back") || a.artifacts.some((e) => !r.artifacts.some((t) => JSON.stringify(t) === JSON.stringify(e)))) throw refusal(e); } else if (r.state !== "preparing" || r.revision !== 1) throw refusal(e); writeAtomic(i, r, n); } function archiveDatabasePortManifest(e, t, n) { n(); const r = readManifest(e); if (!r || r.state !== "complete" || r.operationId !== t) throw refusal(e); assertRoot(e, r); const i = databasePortManifestPath(e); assertPrivate(path.dirname(path.dirname(i)), true); assertPrivate(path.dirname(i), true); assertPrivate(i, false); const a = path.join(path.dirname(i), t); ensurePrivateDirectory(a); const o = path.join(a, "manifest.json"); writeAtomic(o, r, n); n(); fs.unlinkSync(i); syncDatabasePortPath(path.dirname(i)); return o; } //#endregion export { assertDatabasePortStartupAllowed as a, prepareDatabasePortDirectory as c, writeDatabasePortManifest as d, assertDatabasePortRecoveryAllowed as i, syncDatabasePortPath as l, archiveDatabasePortManifest as n, databasePortArtifactSchema as o, assertDatabasePortPlatformSupported as r, databasePortManifestPath as s, DatabasePortRecoveryError as t, writeDatabasePortArtifact as u };