openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
148 lines (147 loc) • 7.71 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as resolveConfigDir } from "./config-dir-DMqvtq2W.mjs";
import { _ as sql, a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { S as jsonValid, g as jsonPickObject } from "./json-values-DVAB74RK.mjs";
import { r as getSqliteWorkerCronDefaultStoreKey } from "./sqlite-worker-state-context-CR8h__Vh.mjs";
import path from "node:path";
//#region src/state/openclaw-state-db-cron-identity-migration.ts
const CRON_DEFAULT_STORE_KEY_STATE_KEY = "cron.defaultStoreKey";
const CRON_DEFAULT_STORE_IDENTITY_SCHEMA_VERSION = 34;
/** Capture the old selector before moving state; this value is never a path to open. */
function resolveLegacyCronDefaultStoreKey(e) {
return path.resolve(resolveConfigDir(e), "cron", "jobs.json");
}
function resolveCronIdentityMigrationDefaultStoreKey(e) {
return getSqliteWorkerCronDefaultStoreKey() ?? resolveLegacyCronDefaultStoreKey(e);
}
function readBindingRow(e, t) {
if (!(t?.has("config_machine_state") ?? tableExists(e, "config_machine_state"))) return;
return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("config_machine_state").select("value_json").where("state_key", "=", CRON_DEFAULT_STORE_KEY_STATE_KEY));
}
function readCronDefaultStoreBindingInDatabase(e) {
const t = readBindingRow(e);
if (!t) return { status: "absent" };
if (typeof t.value_json !== "string") return { status: "invalid" };
try {
const e = JSON.parse(t.value_json);
return typeof e === "string" && e.length > 0 ? {
status: "ready",
storeKey: e
} : { status: "invalid" };
} catch {
return { status: "invalid" };
}
}
/** A malformed binding stays unresolved, so unrelated Gateway functions remain available. */
function readCronDefaultStoreKeyInDatabase(e) {
const t = readCronDefaultStoreBindingInDatabase(e);
return t.status === "ready" ? t.storeKey : void 0;
}
/** Only a matching original selector or an empty inventory proves a legacy default. */
function resolveUnboundCronDefaultStoreKey(e, t) {
return e.length === 0 || e.some((e) => e.storeKey === t) ? t : void 0;
}
const keyedTables = [
["cron_jobs", "jobs"],
["cron_job_scratch", "scratch"],
["cron_run_receipts", "receipts"]
];
const quarantinePrefix = "cron.quarantine:";
const proactivePrefix = "automation-default:";
/** Offline migration/Doctor inventory; ordinary ready selectors only read the binding. */
function readCronStorePartitionInventoryInDatabase(e, t) {
const n = /* @__PURE__ */ new Map();
const add = (e, t, r) => {
if (typeof e !== "string" || e.length === 0) return;
let i = n.get(e);
if (!i) {
i = {
storeKey: e,
jobs: 0,
scratch: 0,
receipts: 0,
history: 0,
quarantine: 0,
proactiveReceipts: 0
};
n.set(e, i);
}
i[t] += r;
};
for (const [n, r] of keyedTables) if (t?.has(n) ?? tableExists(e, n)) {
const t = getNodeSqliteKysely(e).selectFrom(n).select("store_key").select((e) => e.fn.countAll().as("count")).groupBy("store_key");
for (const n of executeSqliteQuerySync(e, t).rows) add(n.store_key, r, Number(n.count));
}
if (t?.has("cron_run_logs") ?? tableExists(e, "cron_run_logs")) {
const t = getNodeSqliteKysely(e).selectFrom("cron_run_logs").select("store_key").select((e) => e.fn.countAll().as("count")).groupBy("store_key");
for (const n of executeSqliteQuerySync(e, t).rows) add(n.store_key, "history", Number(n.count));
}
if (t?.has("task_runs") ?? tableExists(e, "task_runs")) {
const t = getNodeSqliteKysely(e).selectFrom("task_runs").select((t) => [sql`CASE WHEN ${jsonValid(e, t.ref("detail_json"))}
THEN ${jsonPickObject(e, t.ref("detail_json"), ["storeKey"])} END`.as("detail_json")]).where("runtime", "=", "cron");
for (const n of executeSqliteQuerySync(e, t).rows) {
if (typeof n.detail_json !== "string") continue;
try {
const e = JSON.parse(n.detail_json);
if (isRecord(e)) add(e.storeKey, "history", 1);
} catch {}
}
}
if (t?.has("diagnostic_events") ?? tableExists(e, "diagnostic_events")) {
const t = getNodeSqliteKysely(e).selectFrom("diagnostic_events").select("scope").select((e) => e.fn.countAll().as("count")).where("scope", "like", `${quarantinePrefix}%`).groupBy("scope");
for (const n of executeSqliteQuerySync(e, t).rows) if (typeof n.scope === "string") add(n.scope.slice(16), "quarantine", Number(n.count));
}
if (t?.has("config_machine_state") ?? tableExists(e, "config_machine_state")) {
const t = getNodeSqliteKysely(e).selectFrom("config_machine_state").select("state_key").where("state_key", "like", `${proactivePrefix}%`);
for (const n of executeSqliteQuerySync(e, t).rows) add(n.state_key.slice(19, n.state_key.lastIndexOf(":")), "proactiveReceipts", 1);
}
return [...n.values()].toSorted((e, t) => e.storeKey < t.storeKey ? -1 : e.storeKey > t.storeKey ? 1 : 0);
}
const stateCronIdentityMigration = {
version: 34,
tables: ["config_machine_state"],
columns: [],
migrate: (e, t, n) => migrateCronDefaultStoreIdentity(e, {
previousVersion: t,
legacyDefaultStoreKey: n.legacyCronDefaultStoreKey ?? resolveCronIdentityMigrationDefaultStoreKey(n.env)
}),
applied: "Introduced durable default cron partition selection (v34)"
};
/** Doctor owns the prompt and offline transaction; this owner validates and binds its choice. */
function selectCronDefaultStoreIdentityInDatabase(e, t, n = Date.now()) {
const r = readCronDefaultStoreKeyInDatabase(e);
if (r === t) return;
if (r !== void 0) throw new Error("The default cron partition is already bound; preserve its existing identity.");
const i = readCronStorePartitionInventoryInDatabase(e);
if (t.length === 0 || i.length > 0 && !i.some((e) => e.storeKey === t)) throw new Error("The selected cron partition is not in the persisted inventory; inspect it again before repairing.");
executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("config_machine_state").values({
state_key: CRON_DEFAULT_STORE_KEY_STATE_KEY,
value_json: JSON.stringify(t),
updated_at_ms: n
}).onConflict((e) => e.column("state_key").doUpdateSet({
value_json: JSON.stringify(t),
updated_at_ms: n
})));
}
/** Runs within the state owner's existing schema transaction, on both engines. */
function migrateCronDefaultStoreIdentity(e, t) {
if (t.previousVersion >= 34 || readBindingRow(e, t.sourceTables)) return false;
let n = t.fresh ? t.legacyDefaultStoreKey : void 0;
if (!t.fresh) {
if (keyedTables.some(([n]) => (t.sourceTables?.has(n) ?? tableExists(e, n)) && executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom(n).select("store_key").where("store_key", "=", t.legacyDefaultStoreKey).limit(1)))) n = t.legacyDefaultStoreKey;
else {
const r = readCronStorePartitionInventoryInDatabase(e, t.sourceTables);
n = resolveUnboundCronDefaultStoreKey(r, t.legacyDefaultStoreKey) ?? (r.length === 1 ? r[0]?.storeKey : void 0);
}
}
if (n === void 0) return false;
executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("config_machine_state").values({
state_key: CRON_DEFAULT_STORE_KEY_STATE_KEY,
value_json: JSON.stringify(n),
updated_at_ms: t.nowMs ?? Date.now()
}));
return true;
}
//#endregion
export { resolveCronIdentityMigrationDefaultStoreKey as a, selectCronDefaultStoreIdentityInDatabase as c, readCronStorePartitionInventoryInDatabase as i, stateCronIdentityMigration as l, readCronDefaultStoreBindingInDatabase as n, resolveLegacyCronDefaultStoreKey as o, readCronDefaultStoreKeyInDatabase as r, resolveUnboundCronDefaultStoreKey as s, migrateCronDefaultStoreIdentity as t };