openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
209 lines (208 loc) • 7.8 kB
JavaScript
import { t as formatErrorMessage } from "../errors-BKzCeTYb.mjs";
import { i as sqliteWalChecksum, n as SQLITE_WAL_MAGIC_LE, r as readUint32, t as SQLITE_WAL_MAGIC_BE } from "../sqlite-wal-checksum-Zkd3__fm.mjs";
import path from "node:path";
import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import { endianness } from "node:os";
import { FsSafeError } from "@openclaw/fs-safe/errors";
import { openLocalFileSafely } from "@openclaw/fs-safe/root";
import { text } from "node:stream/consumers";
//#region src/infra/state-migrations.snapshot.worker.ts
const SQLITE_FILE_HEADER = Buffer.from("SQLite format 3\0", "utf8");
const SQLITE_SHM_REGION_BYTES = 32768;
const SQLITE_WAL_INDEX_HEADER_COPY_BYTES = 48;
const SQLITE_WAL_INDEX_HEADER_BYTES = 96;
const SQLITE_WAL_INDEX_VERSION = 3007e3;
const SQLITE_WAL_HEADER_BYTES = 32;
const SQLITE_SHM_VOLATILE_RANGES = [[96, 120], [128, 132]];
const SNAPSHOT_HASH_BUFFER_BYTES = 1048576;
async function digestFile(e, t = "") {
const n = await fs.lstat(e);
if (!n.isFile()) throw new Error(`Snapshot path is not a regular file: ${e}`);
if (n.nlink !== 1) throw new Error(`Snapshot path has unbound hard links: ${e}`);
const r = await openSnapshotRegularFile(e);
if (!r) throw new Error(`Snapshot path is not a regular file: ${e}`);
return `sha256:${await digestSnapshotFileHandle(e, r, n, [], t)}`;
}
async function openSnapshotRegularFile(e) {
try {
return (await openLocalFileSafely({ filePath: e })).handle;
} catch (t) {
if (t instanceof FsSafeError) {
if (t.code === "not-found" || t.code === "not-file" || t.code === "symlink") return;
if (t.code === "path-mismatch") throw new Error(`Snapshot file changed while opening: ${e}`, { cause: t });
}
throw t;
}
}
async function openSqliteSharedMemoryEntry(e, t) {
if (!t.endsWith("-shm")) return;
const n = path.join(e, t.slice(0, -4));
const r = path.join(e, t);
let i;
try {
i = await openSnapshotRegularFile(n);
if (!i) return;
const e = Buffer.alloc(SQLITE_FILE_HEADER.length);
const { bytesRead: t } = await i.read(e, 0, e.length, 0);
if (t !== e.length || !e.equals(SQLITE_FILE_HEADER)) return;
} catch (e) {
if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return;
throw e;
} finally {
await i?.close();
}
let a;
try {
a = await fs.lstat(r);
} catch (e) {
if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return;
throw e;
}
if (!a.isFile() || a.size === 0 || a.size % SQLITE_SHM_REGION_BYTES !== 0) return;
let o;
let s;
try {
o = await openSnapshotRegularFile(r);
if (!o) return;
const e = Buffer.alloc(SQLITE_WAL_INDEX_HEADER_BYTES);
const { bytesRead: t } = await o.read(e, 0, e.length, 0);
if (t !== e.length) return;
const i = e.subarray(0, SQLITE_WAL_INDEX_HEADER_COPY_BYTES);
const a = e.subarray(SQLITE_WAL_INDEX_HEADER_COPY_BYTES);
const c = endianness();
const [l, u] = sqliteWalChecksum(i.subarray(0, 40), c);
if (readUint32(i, 0, c) !== SQLITE_WAL_INDEX_VERSION || readUint32(i, 4, c) !== 0 || i[12] !== 1 || readUint32(i, 40, c) !== l || readUint32(i, 44, c) !== u || !i.equals(a)) return;
s = await openSnapshotRegularFile(`${n}-wal`);
if (!s) return;
const d = Buffer.alloc(SQLITE_WAL_HEADER_BYTES);
if ((await s.read(d, 0, d.length, 0)).bytesRead !== d.length) return;
const f = d.readUInt32BE(0);
const p = f === 931071618 ? "LE" : "BE";
if (f !== 931071618 && f !== 931071619 || d.readUInt32BE(4) !== SQLITE_WAL_INDEX_VERSION) return;
const [m, h] = sqliteWalChecksum(d.subarray(0, 24), p);
if (d.readUInt32BE(24) === m && d.readUInt32BE(28) === h && i.subarray(32, 40).equals(d.subarray(16, 24))) {
const e = o;
o = void 0;
return e;
}
return;
} catch (e) {
if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return;
throw e;
} finally {
await o?.close();
await s?.close();
}
}
async function digestSnapshotFileHandle(e, t, n, r = [], i = "") {
const a = createHash("sha256").update(i);
const o = Buffer.alloc(SNAPSHOT_HASH_BUFFER_BYTES);
let s = 0;
const assertUnchanged = (t, r) => {
if ([
"dev",
"ino",
"size",
"mtimeMs"
].some((e) => n[e] !== t[e])) throw new Error(`Snapshot file changed ${r} hashing: ${e}`);
};
try {
assertUnchanged(await t.stat(), "before");
for (;;) {
const { bytesRead: e } = await t.read(o, 0, o.length, s);
if (e === 0) break;
const n = Buffer.from(o.subarray(0, e));
for (const [t, i] of r) {
const r = Math.max(s, t);
const a = Math.min(s + e, i);
if (r < a) n.fill(0, r - s, a - s);
}
a.update(n);
s += e;
}
assertUnchanged(await t.stat(), "while");
} finally {
await t.close();
}
return a.digest("hex");
}
async function digestDirectory(e) {
if (!(await fs.lstat(e)).isDirectory()) throw new Error(`Snapshot state path is not a directory: ${e}`);
const t = createHash("sha256");
const n = /* @__PURE__ */ new Map();
const visit = async (e, r) => {
const i = await fs.lstat(e);
if (i.isSymbolicLink()) throw new Error(`Snapshot tree contains a symbolic link: ${e}`);
const a = r.split(path.sep).join("/");
if (i.isFile()) {
const r = `${i.dev}:${i.ino}`;
const o = n.get(r);
if (o) {
if (o.expected !== i.nlink) throw new Error(`Snapshot hard-link count changed while hashing: ${e}`);
o.observed += 1;
t.update("hardlink\0").update(a).update("\0").update(o.firstRelative).update("\0");
return;
}
n.set(r, {
firstPath: e,
firstRelative: a,
observed: 1,
expected: i.nlink
});
const s = await openSqliteSharedMemoryEntry(path.dirname(e), path.basename(e));
const c = s ?? await openSnapshotRegularFile(e);
if (!c) throw new Error(`Snapshot file changed before hashing: ${e}`);
const l = await digestSnapshotFileHandle(e, c, i, s ? SQLITE_SHM_VOLATILE_RANGES : []);
t.update("file\0").update(a).update("\0").update(l).update("\0");
return;
}
if (!i.isDirectory()) throw new Error(`Snapshot tree contains a non-file entry: ${e}`);
t.update("directory\0").update(a).update("\0");
const o = (await fs.readdir(e)).toSorted();
for (const t of o) await visit(path.join(e, t), path.join(r, t));
};
await visit(e, "");
for (const e of n.values()) if (e.observed !== e.expected) throw new Error(`Snapshot file has links outside copied state: ${e.firstPath}`);
return `sha256:${t.digest("hex")}`;
}
async function captureLegacyStateSnapshotIdentityInProcess(e) {
const t = [];
const capture = async (e, n, r) => {
try {
return await r();
} catch (r) {
const i = r instanceof Error ? r.message : String(r);
t.push(`Could not bind copied ${e} at ${n}: ${i}`);
return;
}
};
const n = path.resolve(e.configPath);
const r = path.resolve(e.stateDir);
const i = await capture("config", n, async () => {
const t = await digestFile(n);
if (e.configInputHashes) {
if (t !== `sha256:${e.configInputHashes.root}`) throw new Error(`Snapshot config changed while planning: ${n}`);
for (const t of e.configInputHashes.includes) if (await digestFile(t.path, "present\0") !== `sha256:${t.hash}`) throw new Error(`Snapshot config input changed while planning: ${t.path}`);
}
return t;
});
const a = await capture("state", r, () => digestDirectory(r));
return {
...i ? { configDigest: i } : {},
...a ? { stateDigest: a } : {},
warnings: t
};
}
async function runSnapshotWorker() {
try {
const e = JSON.parse(await text(process.stdin));
process.stdout.write(JSON.stringify(await captureLegacyStateSnapshotIdentityInProcess(e)));
} catch (e) {
process.exitCode = 1;
process.stderr.write(formatErrorMessage(e));
}
}
if (process.argv[2] === "--openclaw-state-snapshot") runSnapshotWorker();
//#endregion
export { captureLegacyStateSnapshotIdentityInProcess };