openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
278 lines (277 loc) • 9.95 kB
JavaScript
import { o as writeRuntimeJson } from "./runtime-B-SLYP-m.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { Fn as object, Jn as string, Pn as number, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs";
import "./config-CMA-J084.mjs";
import { i as loadOrCreateProcessDeviceIdentityAsync } from "./device-identity-async-B1EfjFkw.mjs";
import { t as ExpectedCliError } from "./failure-output-DVVDqwuu.mjs";
import { n as finishBackupScratch, r as maintainBackupScratch, t as createBackupScratchDirectory } from "./backup-scratch-DYV2vJfy.mjs";
import { a as selectBackupRetention, i as resolveBackupNamespace, n as normalizeBackupRetention, r as parseRemoteBackupTimestamp, t as createRemoteBackupKey } from "./backup-retention-D-I6jsEu.mjs";
import { r as openStorageLocation } from "./locations-DIktuiRP.mjs";
import { createReadStream, createWriteStream } from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import os from "node:os";
import { pipeline } from "node:stream/promises";
//#region src/commands/backup-namespace.ts
const OWNER_KEY = "owner.json";
const ownerSchema = object({
version: literal(1),
deviceId: string().min(1),
hostname: string().min(1),
claimedAt: number().int().nonnegative()
});
async function readNamespaceOwner(e) {
const t = await e.getObject(OWNER_KEY);
if (!t) return;
const n = [];
let r = 0;
for await (const e of t) {
r += e.byteLength;
if (r > 4096) throw new Error("Backup namespace owner exceeds 4096 bytes.");
n.push(Buffer.from(e));
}
try {
return ownerSchema.parse(JSON.parse(Buffer.concat(n).toString("utf8")));
} catch {
throw new Error("Invalid backup namespace owner.json.");
}
}
function namespaceRefusal(e, ...t) {
const n = String.raw({ raw: e }, ...t);
return new ExpectedCliError({
message: n,
machineOutput: n,
humanOutput: terminalText(e, ...t)
});
}
function assertOwner(e, t, n, r) {
const i = e.describe().name;
if (!r) throw namespaceRefusal`Backup namespace "${t}" in ${i} lost its ownership claim. Retry the backup.`;
if (r.deviceId !== n) throw namespaceRefusal`Backup namespace "${t}" in ${i} belongs to another OpenClaw installation (${r.hostname}, device ${r.deviceId.slice(0, 12)}). Pass --namespace <name> to use a separate namespace, or --claim-namespace to take it over deliberately (for example after moving to new hardware).`;
}
async function claimBackupNamespace(e, t, n, r) {
if (r) await e.delete(OWNER_KEY);
let i = await readNamespaceOwner(e);
if (!i) {
const t = Buffer.from(JSON.stringify({
version: 1,
deviceId: n,
hostname: os.hostname(),
claimedAt: Date.now()
}));
try {
await e.putObject(OWNER_KEY, (async function* () {
yield t;
})(), { sizeBytes: t.length });
} catch (t) {
i = await readNamespaceOwner(e);
if (!i) throw t;
}
i ??= await readNamespaceOwner(e);
}
assertOwner(e, t, n, i);
}
async function assertBackupNamespaceOwner(e, t, n) {
assertOwner(e, t, n, await readNamespaceOwner(e));
}
/** Discovery is read-only and incomplete claim metadata must never prevent recovery. */
async function listBackupNamespaces(e) {
const t = /* @__PURE__ */ new Set();
for await (const n of e.list(void 0, { acceptKey: (e) => {
const [n, r, i] = e.split("/");
if (!n || !r || i !== void 0 || r !== OWNER_KEY && parseRemoteBackupTimestamp(r) === void 0) return false;
try {
resolveBackupNamespace(n);
} catch {
return false;
}
t.add(n);
return r !== OWNER_KEY;
} })) t.add(n.key.slice(0, n.key.indexOf("/")));
const n = [];
for (const r of [...t].toSorted()) {
const t = await readNamespaceOwner(e.scope(r)).catch(() => void 0);
n.push({
namespace: r,
...t ? { hostname: t.hostname } : {}
});
}
return n;
}
//#endregion
//#region src/commands/backup-remote.ts
async function openBackupLocation(e, t) {
const n = await openStorageLocation({
name: e,
config: await captureRuntimeConfigAsyncReader()()
});
try {
const r = await n.probe();
if (r.state !== "ok") throw new Error(r.message ?? `Storage location ${e}: ${r.state}. Run \`openclaw storage test ${e}\`.`);
return n.scope(t === void 0 ? "backups" : `backups/${t}`);
} catch (e) {
await n.close();
throw e;
}
}
async function listBackupObjects(e) {
const t = [];
for await (const n of e.list(void 0, { acceptKey: (e) => parseRemoteBackupTimestamp(e) !== void 0 })) t.push(n);
return t.toSorted((e, t) => t.key.localeCompare(e.key));
}
async function createOffsiteBackupArchive(e) {
const t = resolveBackupNamespace(e.namespace);
const n = normalizeBackupRetention(e);
const r = await openBackupLocation(e.to, t);
let i;
let a;
let o = [];
try {
const { chooseBackupTempRoot: s, createBackupArchive: c } = await import("./backup-create-w7ogQxy8.mjs");
if (e.dryRun) return await c(e);
const { deviceId: l } = await loadOrCreateProcessDeviceIdentityAsync();
await claimBackupNamespace(r, t, l, e.claimNamespace === true);
if (!e.output) {
const { resolveBackupPlanFromDisk: t } = await import("./backup-shared-Cc-RMGcx.mjs");
const n = Boolean(e.onlyConfig);
const r = await s({ assets: (await t({
includeWorkspace: n ? false : e.includeWorkspace ?? true,
onlyConfig: n,
nowMs: e.nowMs
})).included });
const a = await maintainBackupScratch({
roots: [r],
repair: true,
log: e.log
});
o = a.warnings;
for (const t of a.reclaimed) e.log?.(`Removed abandoned backup scratch: ${t}`);
i = await createBackupScratchDirectory(r);
}
const u = await c({
...e,
output: i ? path.join(i.directory, "archive.tar.gz") : e.output
});
if (o.length) u.warnings = [...o, ...u.warnings ?? []];
const { verifyBackupArchive: d } = await import("./backup-verify-CyW6XuB4.mjs");
await d(u.archivePath);
u.verified = true;
const f = (await fs$1.stat(u.archivePath)).size;
const p = createRemoteBackupKey(Date.parse(u.createdAt));
await assertBackupNamespaceOwner(r, t, l);
const m = await r.putObject(p, createReadStream(u.archivePath), {
sizeBytes: f,
precondition: () => assertBackupNamespaceOwner(r, t, l)
});
const h = await r.stat(p);
if (!h || h.sizeBytes !== f || h.storedBytes !== m.storedBytes) throw new Error(`Stored backup size could not be confirmed for ${e.to}/${t}/${p}. Run \`openclaw storage test ${e.to}\`.`);
const g = r.describe();
a = {
...u,
archivePath: e.output ? u.archivePath : `storage://${e.to}/backups/${t}/${p}`,
localArchiveRetained: Boolean(e.output),
location: {
name: g.name,
provider: g.provider,
locationId: g.locationId,
key: p,
namespace: t,
plaintextBytes: f,
storedBytes: h.storedBytes
}
};
if (Object.values(n).some((e) => e !== void 0)) {
const e = selectBackupRetention((await listBackupObjects(r)).map((e) => e.key), n);
for (const n of e.deleted) await r.delete(n, { precondition: () => assertBackupNamespaceOwner(r, t, l) });
a.retention = {
kept: e.kept.length,
deleted: e.deleted.length
};
}
return a;
} finally {
try {
if (i) {
const t = await finishBackupScratch(i, e.log);
if (t && a) a.warnings = [...a.warnings ?? [], t];
}
} finally {
await r.close();
}
}
}
async function backupListCommand(e, t) {
const n = resolveBackupNamespace(t.namespace);
const r = await openBackupLocation(t.from);
const i = r.scope(n);
try {
const a = t.namespace === void 0 ? await listBackupNamespaces(r) : void 0;
const o = (await listBackupObjects(i)).map((e) => ({
key: e.key,
sizeBytes: e.sizeBytes,
storedBytes: e.storedBytes,
createdAt: new Date(parseRemoteBackupTimestamp(e.key)).toISOString()
}));
const s = {
location: i.describe(),
namespace: n,
backups: o,
...a ? { namespaces: a } : {}
};
if (t.json) writeRuntimeJson(e, s);
else {
if (a) e.log(a.length ? terminalText`Available namespaces in ${t.from}:\n` + a.map((e) => terminalText`${e.namespace}${e.hostname ? ` (${e.hostname})` : ""}`).join("\n") : terminalText`No backup namespaces in ${t.from}.`);
e.log(o.length ? o.map((e) => terminalText`${e.key} ${e.sizeBytes} bytes (${e.storedBytes} stored)`).join("\n") : terminalText`No backups in ${t.from}/${n}.`);
}
return s;
} finally {
await i.close();
}
}
async function withDownloadedBackup(e, t, n) {
const r = resolveBackupNamespace(t.namespace);
if (t.archive !== "latest" && parseRemoteBackupTimestamp(t.archive) === void 0) throw new Error("Expected a backup key from `openclaw backup list --from <location>` or latest.");
const i = await openBackupLocation(t.from, r);
let a;
try {
const e = t.archive === "latest" ? (await listBackupObjects(i))[0]?.key : t.archive;
if (!e) throw new Error(`No backups in ${t.from}/${r}.`);
const o = await i.getObject(e);
if (!o) throw new Error(`Backup ${e} was not found in ${t.from}/${r}.`);
a = await createBackupScratchDirectory(os.tmpdir());
const s = path.join(a.directory, "archive.tar.gz");
await pipeline(o, createWriteStream(s, {
flags: "wx",
mode: 384
}));
return await n(s);
} finally {
try {
if (a) await finishBackupScratch(a, (t) => e.error(terminalText`${t}`));
} finally {
await i.close();
}
}
}
async function backupRemoteVerifyCommand(e, t) {
return await withDownloadedBackup(e, t, async (n) => {
const { backupVerifyCommand: r } = await import("./backup-verify-CyW6XuB4.mjs");
return await r(e, {
archive: n,
json: t.json
});
});
}
async function backupRemoteRestoreCommand(e, t) {
return await withDownloadedBackup(e, t, async (n) => {
const { backupRestoreCommand: r } = await import("./backup-restore-scxS7l78.mjs");
return await r(e, {
archive: n,
target: t.target,
json: t.json
});
});
}
//#endregion
export { backupListCommand, backupRemoteRestoreCommand, backupRemoteVerifyCommand, createOffsiteBackupArchive };