openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
79 lines (78 loc) • 2.89 kB
JavaScript
import { randomBytes } from "node:crypto";
import os from "node:os";
//#region src/infra/backup-retention.ts
function normalizeBackupRetention(e) {
const t = {};
for (const n of [
"keepDaily",
"keepWeekly",
"keepMonthly"
]) {
const r = e[n];
if (r === void 0) continue;
const i = typeof r === "string" && /^\d+$/.test(r) ? Number(r) : r;
if (typeof i !== "number" || !Number.isSafeInteger(i) || i < 0) throw new Error(`--${n.replace(/[A-Z]/g, (e) => `-${e.toLowerCase()}`)} must be a nonnegative integer.`);
t[n] = i;
}
return t;
}
function resolveBackupNamespace(e) {
const t = e ?? os.hostname().replace(/[^A-Za-z0-9._-]/g, "-");
if (!/^[A-Za-z0-9._-]{1,128}$/.test(t) || t === "." || t === "..") throw new Error("Backup namespace must be 1–128 letters, digits, dots, underscores or hyphens, and cannot be . or .. .");
return t;
}
function createRemoteBackupKey(e = Date.now()) {
return `${new Date(e).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z")}-${randomBytes(4).toString("hex")}.tar.gz`;
}
/** Only consumer-owned keys with real UTC timestamps participate in listing or deletion. */
function parseRemoteBackupTimestamp(e) {
const t = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z-[a-f0-9]{8}\.tar\.gz$/.exec(e);
if (!t) return;
const n = `${t[1]}-${t[2]}-${t[3]}T${t[4]}:${t[5]}:${t[6]}.000Z`;
const r = Date.parse(n);
return Number.isFinite(r) && new Date(r).toISOString() === n ? r : void 0;
}
/** Keep the newest snapshot in each selected nonempty UTC calendar bucket (Monday weeks). */
function selectBackupRetention(e, t) {
const n = [...new Set(e)].flatMap((e) => {
const t = parseRemoteBackupTimestamp(e);
return t === void 0 ? [] : [{
key: e,
timestamp: t
}];
}).toSorted((e, t) => t.timestamp - e.timestamp || t.key.localeCompare(e.key));
if (Object.values(t).every((e) => e === void 0)) return {
kept: n.map(({ key: e }) => e),
deleted: []
};
const r = new Set(n.slice(0, 1).map(({ key: e }) => e));
const i = {
keepDaily: /* @__PURE__ */ new Set(),
keepWeekly: /* @__PURE__ */ new Set(),
keepMonthly: /* @__PURE__ */ new Set()
};
for (const { key: e, timestamp: a } of n) {
const n = new Date(a);
const o = n.toISOString().slice(0, 10);
const s = o.slice(0, 7);
n.setUTCDate(n.getUTCDate() - (n.getUTCDay() + 6) % 7);
const c = n.toISOString().slice(0, 10);
for (const [n, a] of [
["keepDaily", o],
["keepWeekly", c],
["keepMonthly", s]
]) {
const o = i[n];
if (!o.has(a) && o.size < (t[n] ?? 0)) {
r.add(e);
o.add(a);
}
}
}
return {
kept: n.filter(({ key: e }) => r.has(e)).map(({ key: e }) => e),
deleted: n.filter(({ key: e }) => !r.has(e)).map(({ key: e }) => e)
};
}
//#endregion
export { selectBackupRetention as a, resolveBackupNamespace as i, normalizeBackupRetention as n, parseRemoteBackupTimestamp as r, createRemoteBackupKey as t };