Skip to content

Commit dba2284

Browse files
committed
refactor(doctor): consolidate shipped state migration ownership
1 parent a1b41d5 commit dba2284

20 files changed

Lines changed: 1558 additions & 1917 deletions

‎src/infra/state-migrations.apns.ts‎

Lines changed: 31 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
11
// Doctor-only import for the retired APNs registration JSON store.
2-
import { createHash } from "node:crypto";
32
import path from "node:path";
43
import { root, type Root } from "@openclaw/fs-safe";
54
import { isRecord } from "@openclaw/normalization-core/record-coerce";
65
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
7-
import {
8-
openOpenClawStateDatabase,
9-
runOpenClawStateWriteTransaction,
10-
} from "../state/openclaw-state-db.js";
6+
import { runOpenClawStateWriteTransaction } from "../state/openclaw-state-db.js";
117
import {
128
executeSqliteQuerySync,
139
executeSqliteQueryTakeFirstSync,
@@ -24,6 +20,14 @@ import {
2420
type ApnsRegistration,
2521
} from "./push-apns-store.js";
2622
import { withLegacyMigrationStateLock } from "./state-migrations.lock.js";
23+
import {
24+
markLegacyMigrationSourceRemoved,
25+
readLegacyMigrationReceipt,
26+
readLegacyMigrationReceiptFromDatabase,
27+
recordLegacyMigrationReceipt,
28+
resolveLegacyMigrationSourceKey,
29+
type LegacyMigrationReceipt,
30+
} from "./state-migrations.receipts.js";
2731
import {
2832
legacyMigrationSourceOrClaimMayExist,
2933
legacyMigrationSourceSnapshotsMatch as snapshotsMatch,
@@ -62,19 +66,14 @@ const RELAY_REGISTRATION_KEYS = new Set([
6266

6367
type ApnsMigrationDatabase = Pick<
6468
OpenClawStateKyselyDatabase,
65-
"apns_registrations" | "apns_registration_tombstones" | "migration_runs" | "migration_sources"
69+
"apns_registrations" | "apns_registration_tombstones"
6670
>;
6771

6872
type LegacySourceSnapshot = Pick<
6973
LegacyMigrationSourceSnapshot,
7074
"sourcePath" | "dev" | "ino" | "mtimeMs" | "sha256" | "size"
7175
>;
7276

73-
type MigrationReceipt = {
74-
sourceKey: string;
75-
removedSource: boolean;
76-
};
77-
7877
function resolveLegacyApnsPath(stateDir: string): string {
7978
return path.join(stateDir, LEGACY_APNS_REGISTRATION_PATH);
8079
}
@@ -181,23 +180,6 @@ function parseLegacyApnsRegistration(
181180
return [normalizedNodeId, registration];
182181
}
183182

184-
function receiptSourceKey(sourcePath: string): string {
185-
return `apns-json:${createHash("sha256").update(path.resolve(sourcePath)).digest("hex")}`;
186-
}
187-
188-
function readMigrationReceipt(sourcePath: string, env: NodeJS.ProcessEnv): MigrationReceipt | null {
189-
const sourceKey = receiptSourceKey(sourcePath);
190-
const { db } = openOpenClawStateDatabase({ env });
191-
const row = executeSqliteQueryTakeFirstSync(
192-
db,
193-
getNodeSqliteKysely<ApnsMigrationDatabase>(db)
194-
.selectFrom("migration_sources")
195-
.select("removed_source")
196-
.where("source_key", "=", sourceKey),
197-
);
198-
return row ? { sourceKey, removedSource: row.removed_source === 1 } : null;
199-
}
200-
201183
function importAndRecordReceipt(params: {
202184
env: NodeJS.ProcessEnv;
203185
sourcePath: string;
@@ -210,19 +192,13 @@ function importAndRecordReceipt(params: {
210192
suppressed: number;
211193
receiptAuthoritative: boolean;
212194
} {
213-
const sourceKey = receiptSourceKey(params.sourcePath);
195+
const sourceKey = resolveLegacyMigrationSourceKey("apns-json", params.sourcePath);
214196
const runId = `${sourceKey}:${params.snapshot.sha256.slice(0, 16)}`;
215197
const now = Date.now();
216198
return runOpenClawStateWriteTransaction(
217199
({ db }) => {
218200
const stateDb = getNodeSqliteKysely<ApnsMigrationDatabase>(db);
219-
const existingReceipt = executeSqliteQueryTakeFirstSync(
220-
db,
221-
stateDb
222-
.selectFrom("migration_sources")
223-
.select("source_key")
224-
.where("source_key", "=", sourceKey),
225-
);
201+
const existingReceipt = readLegacyMigrationReceiptFromDatabase(db, sourceKey);
226202
if (existingReceipt) {
227203
return {
228204
sourceKey,
@@ -290,54 +266,24 @@ function importAndRecordReceipt(params: {
290266
preservedSqliteRecordCount: preserved,
291267
suppressedDeletedRecordCount: suppressed,
292268
});
293-
executeSqliteQuerySync(
294-
db,
295-
stateDb.insertInto("migration_runs").values({
296-
id: runId,
297-
started_at: now,
298-
finished_at: now,
299-
status: "completed",
300-
report_json: reportJson,
301-
}),
302-
);
303-
executeSqliteQuerySync(
304-
db,
305-
stateDb.insertInto("migration_sources").values({
306-
source_key: sourceKey,
307-
migration_kind: MIGRATION_KIND,
308-
source_path: params.sourcePath,
309-
target_table: "apns_registrations",
310-
source_sha256: params.snapshot.sha256,
311-
source_size_bytes: params.snapshot.size,
312-
source_record_count: params.registrations.size,
313-
last_run_id: runId,
314-
status: "completed",
315-
imported_at: now,
316-
removed_source: 0,
317-
report_json: reportJson,
318-
}),
319-
);
269+
recordLegacyMigrationReceipt(db, {
270+
sourceKey,
271+
migrationKind: MIGRATION_KIND,
272+
sourcePath: params.sourcePath,
273+
targetTable: "apns_registrations",
274+
sourceSha256: params.snapshot.sha256,
275+
sourceSizeBytes: params.snapshot.size,
276+
sourceRecordCount: params.registrations.size,
277+
runId,
278+
now,
279+
reportJson,
280+
});
320281
return { sourceKey, imported, preserved, suppressed, receiptAuthoritative: false };
321282
},
322283
{ env: params.env },
323284
);
324285
}
325286

326-
function markSourceRemoved(sourceKey: string, env: NodeJS.ProcessEnv): void {
327-
runOpenClawStateWriteTransaction(
328-
({ db }) => {
329-
executeSqliteQuerySync(
330-
db,
331-
getNodeSqliteKysely<ApnsMigrationDatabase>(db)
332-
.updateTable("migration_sources")
333-
.set({ removed_source: 1 })
334-
.where("source_key", "=", sourceKey),
335-
);
336-
},
337-
{ env },
338-
);
339-
}
340-
341287
async function removePath(params: {
342288
stateRoot: Root;
343289
stateDir: string;
@@ -355,7 +301,7 @@ async function cleanupReceiptAuthoritativeSources(params: {
355301
stateRoot: Root;
356302
stateDir: string;
357303
sourcePath: string;
358-
receipt: MigrationReceipt;
304+
receipt: LegacyMigrationReceipt;
359305
env: NodeJS.ProcessEnv;
360306
removeSource?: (sourcePath: string) => Promise<void> | void;
361307
}): Promise<number> {
@@ -370,7 +316,7 @@ async function cleanupReceiptAuthoritativeSources(params: {
370316
removed += 1;
371317
}
372318
if (!params.receipt.removedSource || removed > 0) {
373-
markSourceRemoved(params.receipt.sourceKey, params.env);
319+
markLegacyMigrationSourceRemoved(params.receipt.sourceKey, params.env);
374320
}
375321
return removed;
376322
}
@@ -413,7 +359,10 @@ async function migrateWithExclusiveStateOwnership(params: {
413359
return { changes, warnings };
414360
}
415361

416-
const receipt = readMigrationReceipt(params.detected.sourcePath, params.env);
362+
const receipt = readLegacyMigrationReceipt(
363+
resolveLegacyMigrationSourceKey("apns-json", params.detected.sourcePath),
364+
params.env,
365+
);
417366
if (receipt) {
418367
try {
419368
const removed = await cleanupReceiptAuthoritativeSources({
@@ -519,7 +468,7 @@ async function migrateWithExclusiveStateOwnership(params: {
519468
throw new Error("legacy APNs source reappeared during import");
520469
}
521470
await removePath({ ...params, sourcePath: claimPath });
522-
markSourceRemoved(result.sourceKey, params.env);
471+
markLegacyMigrationSourceRemoved(result.sourceKey, params.env);
523472
} catch (error) {
524473
warnings.push(`APNs state is in SQLite, but legacy cleanup failed: ${String(error)}`);
525474
return { changes, warnings };

‎src/infra/state-migrations.config-machine-state.ts‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Imports machine-owned openclaw.json values into the shared SQLite state store.
2+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
23
import type { OpenClawConfig } from "../config/types.openclaw.js";
34
import { compareOpenClawVersions } from "../config/version.js";
45
import {
@@ -14,21 +15,15 @@ import {
1415

1516
const BUNDLED_DISCOVERY_STATE_CUTOVER_VERSION = "2026.7.2";
1617

17-
function record(value: unknown): Record<string, unknown> | undefined {
18-
return value !== null && typeof value === "object" && !Array.isArray(value)
19-
? (value as Record<string, unknown>)
20-
: undefined;
21-
}
22-
2318
/** Preserve retired machine-owned config fields before Doctor strips them. */
2419
export function migrateLegacyConfigMachineState(params: {
2520
config: OpenClawConfig;
2621
env: NodeJS.ProcessEnv;
2722
}): { changes: string[]; warnings: string[] } {
2823
const raw = params.config as Record<string, unknown>;
2924
const entries: Array<readonly [string, unknown]> = [];
30-
const controlUi = record(record(raw.gateway)?.controlUi);
31-
const meta = record(raw.meta);
25+
const controlUi = asOptionalRecord(asOptionalRecord(raw.gateway)?.controlUi);
26+
const meta = asOptionalRecord(raw.meta);
3227
if (
3328
isLegacyControlUiDeviceAuthMigrationInput({
3429
disabledDeviceAuth: controlUi?.dangerouslyDisableDeviceAuth === true,
@@ -46,9 +41,11 @@ export function migrateLegacyConfigMachineState(params: {
4641
if (meta && Object.hasOwn(meta, "lastTouchedAt")) {
4742
entries.push(["config.lastTouchedAt", meta.lastTouchedAt]);
4843
}
49-
const installs = record(record(record(raw.hooks)?.internal)?.installs);
44+
const installs = asOptionalRecord(
45+
asOptionalRecord(asOptionalRecord(raw.hooks)?.internal)?.installs,
46+
);
5047
const hasInstalls = Boolean(installs && Object.keys(installs).length > 0);
51-
const plugins = record(raw.plugins);
48+
const plugins = asOptionalRecord(raw.plugins);
5249
if (plugins && Object.hasOwn(plugins, "bundledDiscovery")) {
5350
entries.push(["plugins.bundledDiscovery", plugins.bundledDiscovery]);
5451
} else if (
@@ -75,11 +72,11 @@ export function migrateLegacyConfigMachineState(params: {
7572
entries.push(["plugins.bundledDiscovery", "compat"]);
7673
}
7774
}
78-
const tts = record(raw.tts);
75+
const tts = asOptionalRecord(raw.tts);
7976
if (tts && Object.hasOwn(tts, "prefsPath")) {
8077
entries.push(["tts.prefsPath", tts.prefsPath]);
8178
}
82-
const cron = record(raw.cron);
79+
const cron = asOptionalRecord(raw.cron);
8380
if (cron && Object.hasOwn(cron, "store")) {
8481
entries.push(["cron.store", cron.store]);
8582
}

0 commit comments

Comments
 (0)