|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { Command, Flags } from '@oclif/core'; |
| 4 | +import chalk from 'chalk'; |
| 5 | +import { createInterface } from 'node:readline'; |
| 6 | +import { |
| 7 | + runMigrationJournal, |
| 8 | + MigrationJournalRefusal, |
| 9 | + type MigrationPlanProvider, |
| 10 | +} from '@objectstack/core'; |
| 11 | +import { |
| 12 | + createRecordedBySentinelPlan, |
| 13 | + findSentinelHistoryRows, |
| 14 | + RECORDED_BY_SENTINEL, |
| 15 | + RECORDED_BY_SENTINEL_PLAN_ID, |
| 16 | +} from '@objectstack/metadata-protocol'; |
| 17 | +import type { IObjectQLEngine } from '@objectstack/spec/contracts'; |
| 18 | +import { |
| 19 | + printHeader, |
| 20 | + printSuccess, |
| 21 | + printWarning, |
| 22 | + printError, |
| 23 | + printInfo, |
| 24 | + printStep, |
| 25 | + createTimer, |
| 26 | + emitJson, |
| 27 | +} from '../../utils/format.js'; |
| 28 | +import { bootSchemaStack } from '../../utils/schema-migrate.js'; |
| 29 | +import { buildDataMigrationPlugins } from '../../utils/data-migration-plugins.js'; |
| 30 | + |
| 31 | +async function confirm(question: string): Promise<boolean> { |
| 32 | + if (!process.stdin.isTTY) return false; // non-interactive → require --yes |
| 33 | + const rl = createInterface({ input: process.stdin, output: process.stdout }); |
| 34 | + try { |
| 35 | + const answer: string = await new Promise((resolve) => rl.question(question, resolve)); |
| 36 | + return /^y(es)?$/i.test(answer.trim()); |
| 37 | + } finally { |
| 38 | + rl.close(); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * `os migrate recorded-by` — rewrite the `'system'` sentinel in |
| 44 | + * `sys_metadata_history.recorded_by` to `NULL` (#4556). |
| 45 | + * |
| 46 | + * `recorded_by` is a `lookup('sys_user')` that used to receive the STRING |
| 47 | + * `'system'` on every actor-less metadata write. That string is not any |
| 48 | + * user's id, so the column declared a foreign key and stored something no |
| 49 | + * join could resolve. The runtime no longer writes it (the write path stores |
| 50 | + * `NULL`); this command converts the rows already on disk. |
| 51 | + * |
| 52 | + * The conversion is semantically equivalent, not a reinterpretation: the |
| 53 | + * column has only ever held that one sentinel, written by one expression, and |
| 54 | + * both spellings mean "no actor" — only `NULL` is expressible in the declared |
| 55 | + * type. |
| 56 | + * |
| 57 | + * Dry run by default, like every other `os migrate` subcommand (#2186): a |
| 58 | + * bare invocation reports how many rows still carry the sentinel and writes |
| 59 | + * nothing. `--apply` runs the conversion through the ADR-0119 D2 migration |
| 60 | + * journal, so each chunk is one transaction and an interrupted run is |
| 61 | + * recoverable via `os migrate resume`. |
| 62 | + * |
| 63 | + * Safe to re-run: the plan selects only rows still holding the sentinel, so a |
| 64 | + * second `--apply` finds none and commits zero chunks. |
| 65 | + */ |
| 66 | +export default class MigrateRecordedBy extends Command { |
| 67 | + static override description = |
| 68 | + "Rewrite the legacy 'system' sentinel in sys_metadata_history.recorded_by to NULL (#4556). " + |
| 69 | + 'Dry-run by default; --apply runs the conversion through the migration journal.'; |
| 70 | + |
| 71 | + static override examples = [ |
| 72 | + '$ os migrate recorded-by', |
| 73 | + '$ os migrate recorded-by --json', |
| 74 | + '$ os migrate recorded-by --apply --yes', |
| 75 | + ]; |
| 76 | + |
| 77 | + static override flags = { |
| 78 | + 'database-url': Flags.string({ |
| 79 | + description: 'Database URL to inspect (defaults to $OS_DATABASE_URL / the project DB)', |
| 80 | + env: 'OS_DATABASE_URL', |
| 81 | + }), |
| 82 | + apply: Flags.boolean({ description: 'Perform the conversion (default is a read-only report)', default: false }), |
| 83 | + yes: Flags.boolean({ char: 'y', description: 'Skip the confirmation prompt', default: false }), |
| 84 | + 'chunk-size': Flags.integer({ description: 'Rows per journal chunk', default: 200 }), |
| 85 | + json: Flags.boolean({ description: 'Machine-readable output', default: false }), |
| 86 | + }; |
| 87 | + |
| 88 | + async run(): Promise<void> { |
| 89 | + const { flags } = await this.parse(MigrateRecordedBy); |
| 90 | + const timer = createTimer(); |
| 91 | + |
| 92 | + if (!flags.json) printHeader('Migrate · recorded-by sentinel → NULL'); |
| 93 | + if (!flags.json) printStep(flags.apply ? 'Booting data stack…' : 'Booting data stack (read-only)…'); |
| 94 | + |
| 95 | + let stack; |
| 96 | + try { |
| 97 | + stack = await bootSchemaStack({ |
| 98 | + databaseUrl: flags['database-url'], |
| 99 | + extraPlugins: await buildDataMigrationPlugins(), |
| 100 | + }); |
| 101 | + } catch (error: any) { |
| 102 | + if (flags.json) { await emitJson({ error: error.message }, 0, { compact: true }); this.exit(1); } |
| 103 | + printError(error.message || String(error)); |
| 104 | + this.exit(1); |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + try { |
| 109 | + const engine: IObjectQLEngine = stack.kernel.getService('objectql'); |
| 110 | + if (typeof engine?.find !== 'function') { |
| 111 | + throw new Error('No ObjectQL engine on this stack — cannot read sys_metadata_history.'); |
| 112 | + } |
| 113 | + |
| 114 | + const plan = createRecordedBySentinelPlan({ chunkSize: flags['chunk-size'] }); |
| 115 | + |
| 116 | + // Register the plan so an interrupted run is resumable in THIS process |
| 117 | + // too — `os migrate resume` looks plans up by id, and a run whose plan |
| 118 | + // nothing registers is reported unresumable. |
| 119 | + try { |
| 120 | + const plans = stack.kernel.getService('migration-plans') as MigrationPlanProvider; |
| 121 | + plans?.register?.(plan); |
| 122 | + } catch { /* no registry composed — resume reports it, this run still works */ } |
| 123 | + |
| 124 | + const pending = await findSentinelHistoryRows(engine); |
| 125 | + |
| 126 | + // ── dry run (default): read-only ───────────────────────────────── |
| 127 | + if (!flags.apply) { |
| 128 | + if (flags.json) { |
| 129 | + await emitJson({ planId: RECORDED_BY_SENTINEL_PLAN_ID, sentinel: RECORDED_BY_SENTINEL, pending: pending.length, applied: false }, timer.elapsed()); |
| 130 | + return; |
| 131 | + } |
| 132 | + if (pending.length === 0) { |
| 133 | + printSuccess(`No sys_metadata_history row holds the '${RECORDED_BY_SENTINEL}' sentinel — nothing to convert.`); |
| 134 | + return; |
| 135 | + } |
| 136 | + printWarning(`${pending.length} sys_metadata_history row(s) hold recorded_by = '${RECORDED_BY_SENTINEL}'.`); |
| 137 | + printInfo("Nothing was changed. Re-run with --apply to rewrite them to NULL."); |
| 138 | + return; |
| 139 | + } |
| 140 | + |
| 141 | + // ── apply ──────────────────────────────────────────────────────── |
| 142 | + if (pending.length === 0) { |
| 143 | + const msg = `No sys_metadata_history row holds the '${RECORDED_BY_SENTINEL}' sentinel — nothing to convert.`; |
| 144 | + if (flags.json) { await emitJson({ planId: RECORDED_BY_SENTINEL_PLAN_ID, pending: 0, applied: true, status: 'completed', chunksCommitted: 0 }, timer.elapsed()); return; } |
| 145 | + printSuccess(msg); |
| 146 | + return; |
| 147 | + } |
| 148 | + |
| 149 | + if (!flags.yes) { |
| 150 | + const summary = `Rewrite recorded_by '${RECORDED_BY_SENTINEL}' → NULL on ${pending.length} row(s)`; |
| 151 | + if (flags.json || !process.stdin.isTTY) { |
| 152 | + if (flags.json) { await emitJson({ error: 'confirmation_required', hint: 'pass --yes', summary }, timer.elapsed(), { compact: true }); this.exit(1); return; } |
| 153 | + printWarning(`Confirmation required: ${summary}. Re-run with --yes.`); |
| 154 | + this.exit(1); |
| 155 | + return; |
| 156 | + } |
| 157 | + const ok = await confirm(chalk.bold(`\n${summary}? [y/N] `)); |
| 158 | + if (!ok) { printInfo('Aborted — nothing changed.'); return; } |
| 159 | + } |
| 160 | + |
| 161 | + if (!flags.json) printStep('Converting…'); |
| 162 | + const result = await runMigrationJournal(engine, plan); |
| 163 | + |
| 164 | + if (flags.json) { |
| 165 | + await emitJson({ ...result, pending: pending.length, applied: true, error: result.error ? String(result.error) : undefined }, timer.elapsed()); |
| 166 | + this.exit(result.status === 'completed' ? 0 : 1); |
| 167 | + return; |
| 168 | + } |
| 169 | + |
| 170 | + if (result.status === 'completed') { |
| 171 | + printSuccess( |
| 172 | + `Converted ${pending.length} row(s) — run '${result.runId}', ${result.chunksCommitted}/${result.chunksTotal} chunk(s) committed.`, |
| 173 | + ); |
| 174 | + } else if (result.status === 'compensated') { |
| 175 | + printWarning( |
| 176 | + `Run '${result.runId}' failed and was unwound — ${result.chunksCompensated} chunk(s) compensated. ` + |
| 177 | + `The sentinel rows are back as they were; nothing is half-converted.`, |
| 178 | + ); |
| 179 | + this.exit(1); |
| 180 | + } else { |
| 181 | + printError( |
| 182 | + `Run '${result.runId}' FAILED and its compensation did not finish. ` + |
| 183 | + `Inspect sys_migration_journal for run '${result.runId}' — this needs a decision, not a retry.`, |
| 184 | + ); |
| 185 | + this.exit(1); |
| 186 | + } |
| 187 | + } catch (error: any) { |
| 188 | + const msg = error instanceof MigrationJournalRefusal |
| 189 | + ? `Refused (${error.code}): ${error.message}` |
| 190 | + : (error?.message || String(error)); |
| 191 | + if (flags.json) { await emitJson({ error: msg }, timer.elapsed(), { compact: true }); this.exit(1); return; } |
| 192 | + printError(msg); |
| 193 | + this.exit(1); |
| 194 | + } finally { |
| 195 | + try { await stack.shutdown?.(); } catch { /* best effort */ } |
| 196 | + } |
| 197 | + } |
| 198 | +} |
0 commit comments