openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
182 lines (181 loc) • 7.12 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { r as readFiniteSqliteNumber } from "./sqlite-number-D8n3srri.mjs";
import { n as formatDiskSpaceBytes, r as tryReadDiskSpace } from "./disk-space-B5Tl0OOd.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { n as openSqliteReadOnlyDatabase } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { a as resolveSqliteDatabaseFilePaths } from "./sqlite-files-rWisKj_V.mjs";
import { n as assertOpenClawStateDatabaseForMaintenance } from "./openclaw-state-db-maintenance-Dvr7ztmv.mjs";
import { n as assertOpenClawStateWriteAllowed } from "./openclaw-state-ownership-Wv4JBQVJ.mjs";
import "./openclaw-state-db-ARhwdPJg.mjs";
import { t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs";
import { l as invalidateOpenClawAgentDatabaseIntegrityBeforeMutation } from "./openclaw-agent-db-lease-BZhGt_sk.mjs";
import { i as readEngineAnchorIdentity } from "./physical-store-inspection-C7yPt-uR.mjs";
import { t as assertOpenClawAgentDatabaseForMaintenance } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs";
import { n as assertDoctorSqliteMaintenancePathsNotAliased } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs";
import { n as compactDoctorSqliteFile, t as DoctorSqliteCompactionDeferredError } from "./doctor-sqlite-compact-D8iufPYc.mjs";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { setImmediate } from "node:timers/promises";
//#region src/commands/doctor-sqlite-reclamation.ts
var ReclamationDeferred = class extends Error {};
function pragmaNumber(e, t) {
const n = readFiniteSqliteNumber(e.prepare(`PRAGMA ${t}`).get()?.[t]);
if (n === void 0 || n < 0) throw new Error(`SQLite PRAGMA ${t} returned an invalid result.`);
return n;
}
/** VACUUM may place its temporary database on a different volume from its WAL. */
function assertVacuumSpace(e, t, n) {
const r = path.dirname(e);
const i = /* @__PURE__ */ new Set([
r,
...[
n.SQLITE_TMPDIR,
n.TMPDIR,
n.TMP,
n.TEMP,
os.tmpdir()
].filter((e) => Boolean(e?.trim())),
...process.platform === "win32" ? [] : [
"/var/tmp",
"/usr/tmp",
"/tmp",
process.cwd()
]
]);
const a = /* @__PURE__ */ new Set();
const o = t * 2 + 67108864;
for (const e of i) {
let t;
try {
t = fs.statSync(e, { bigint: true });
if (!t.isDirectory()) continue;
fs.accessSync(e, fs.constants.W_OK | fs.constants.X_OK);
} catch (t) {
if (e === r) throw new ReclamationDeferred("the database directory is not writable", { cause: t });
continue;
}
if (t.dev > 0n && a.has(t.dev)) continue;
const n = tryReadDiskSpace(e);
if (!n || n.availableBytes < o) throw new ReclamationDeferred(`${formatDiskSpaceBytes(o)} of temporary space is needed near ${e}; ${n ? `${formatDiskSpaceBytes(n.availableBytes)} available` : "free space could not be measured"}`);
a.add(t.dev);
}
if (a.size === 0) throw new ReclamationDeferred("database and SQLite temporary storage could not be verified");
}
/** The existing Doctor owner calls this only after its readers and writers have drained. */
async function enableDoctorSqliteReclamation(e) {
const t = [{
path: resolveOpenClawStateSqlitePath(e.env),
agentId: void 0
}, ...e.agents.map((e) => ({
path: e.path,
agentId: e.agentId
}))];
const n = [];
const r = /* @__PURE__ */ new Set();
const assertAdmission = () => {
e.signal.throwIfAborted();
e.assertCurrent();
};
for (const i of t) {
await setImmediate();
assertAdmission();
const t = path.resolve(i.path);
if (r.has(t)) continue;
r.add(t);
const a = fs.lstatSync(t, {
bigint: true,
throwIfNoEntry: false
});
if (!a) continue;
const assertIdentity = () => {
const e = fs.lstatSync(t, {
bigint: true,
throwIfNoEntry: false
});
if (!e?.isFile() || e.dev !== a.dev || e.ino !== a.ino) throw new ReclamationDeferred("the database file identity changed");
try {
assertDoctorSqliteMaintenancePathsNotAliased("automatic SQLite reclamation", resolveSqliteDatabaseFilePaths(t), [path.parse(t).root]);
} catch (e) {
throw new ReclamationDeferred(formatErrorMessage(e), { cause: e });
}
};
const validate = (n) => {
assertAdmission();
assertIdentity();
if (i.agentId === void 0) {
assertOpenClawStateWriteAllowed({
database: n,
databasePath: t,
env: e.env
});
assertOpenClawStateDatabaseForMaintenance(n, { pathname: t });
} else assertOpenClawAgentDatabaseForMaintenance(n, {
pathname: t,
agentId: i.agentId
});
};
let o = false;
let s = false;
try {
assertIdentity();
const n = withArtifactPreservingStateReads(() => {
const n = openSqliteReadOnlyDatabase(t);
try {
if (readEngineAnchorIdentity(n, t).engine === "postgres") return false;
const r = pragmaNumber(n, "auto_vacuum") === 0;
if (r) {
validate(n);
const r = Math.max(Number(a.size), pragmaNumber(n, "page_count") * pragmaNumber(n, "page_size"));
assertVacuumSpace(t, r, e.env);
}
return r;
} finally {
n.close();
}
}, { agentDatabases: true });
assertAdmission();
assertIdentity();
if (!n) continue;
if (i.agentId !== void 0) invalidateOpenClawAgentDatabaseIntegrityBeforeMutation(t);
e.log(`Enabling incremental SQLite reclamation once: ${t}`);
const r = compactDoctorSqliteFile({
sqlitePath: t,
requireExisting: true,
busyTimeoutMs: 0,
validateBeforeMutation(e) {
validate(e);
o = true;
},
afterSuccess: assertIdentity
});
if (r.after.autoVacuum !== 2) throw new Error("SQLite compaction did not enable incremental reclamation.");
s = true;
e.assertCurrent();
e.log(`Enabled incremental SQLite reclamation: ${t}; reclaimed ${formatDiskSpaceBytes(r.reclaimedBytes)}; integrity verified.`);
} catch (e) {
if (o && !s && !(e instanceof DoctorSqliteCompactionDeferredError)) {
let n = e;
try {
assertAdmission();
} catch (t) {
n = new AggregateError([e, t], "SQLite reclamation failed during interruption.");
}
throw new DoctorMaintenanceRefusalError(`SQLite reclamation did not finish verified for ${t}: ${formatErrorMessage(e)}. Inspect this database before restarting the Gateway.`, {
kind: "data-at-risk",
reason: "incomplete-migration"
}, { cause: n });
}
assertAdmission();
if (!(e instanceof ReclamationDeferred) && !(e instanceof DoctorSqliteCompactionDeferredError)) throw e;
const r = i.agentId === void 0 ? "openclaw doctor --state-sqlite compact" : "openclaw doctor --session-sqlite compact --session-sqlite-all-agents";
n.push(`Automatic SQLite reclamation deferred for ${t}: ${e.message}. The update can continue; after resolving this condition, run ${r} while the Gateway is stopped.`);
}
}
await setImmediate();
assertAdmission();
return { warnings: n };
}
//#endregion
export { enableDoctorSqliteReclamation };