|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `os migrate organization-ownership --apply`, column drops: a table the |
| 5 | + * booted composition declares no object for is answered `not-declared`, never |
| 6 | + * blamed on the release (ADR-0131 D10, fate 1). |
| 7 | + * |
| 8 | + * The ceremony drops a column only through the schema-drift ceremony, so only |
| 9 | + * for an object its boot declares, and its boot declares the composition it is |
| 10 | + * run in. `sys_flow_dispatch`'s provider (`service-automation`) is composed |
| 11 | + * only when that composition's `requires` names `automation`. So run in a |
| 12 | + * composition that does not, the v17 column is kept and the step says why |
| 13 | + * (`summary.notDeclared`, a blocker naming the table). The control is the same |
| 14 | + * database run in a composition that does: the column is dropped. |
| 15 | + * |
| 16 | + * The fixture is a database a served boot of this tree left behind, shaped |
| 17 | + * like v17: `organization_id` added to `sys_flow_dispatch`, and to |
| 18 | + * `sys_migration_journal`, whose provider is composed on every boot, as the |
| 19 | + * in-run control. |
| 20 | + */ |
| 21 | + |
| 22 | +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; |
| 23 | +import Database from 'better-sqlite3'; |
| 24 | +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 25 | +import { randomBytes } from 'node:crypto'; |
| 26 | +import { tmpdir } from 'node:os'; |
| 27 | +import { dirname, join, resolve } from 'node:path'; |
| 28 | +import { fileURLToPath } from 'node:url'; |
| 29 | +import { isExitSignal } from './format.js'; |
| 30 | +import MigrateOrganizationOwnership from '../commands/migrate/organization-ownership.js'; |
| 31 | + |
| 32 | +import '@objectstack/runtime'; |
| 33 | +import '@objectstack/objectql'; |
| 34 | +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; |
| 35 | +import { AutomationServicePlugin } from '@objectstack/service-automation'; |
| 36 | + |
| 37 | +const HERE = dirname(fileURLToPath(import.meta.url)); |
| 38 | +const CLI_ROOT = resolve(HERE, '..', '..'); |
| 39 | +const CASE_TIMEOUT_MS = 120_000; |
| 40 | + |
| 41 | +/** Env that would point the boot somewhere other than the fixture, or change what it composes. */ |
| 42 | +const OVERRIDING_ENV = [ |
| 43 | + 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', 'OS_ARTIFACT_PATH', |
| 44 | + 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', |
| 45 | +] as const; |
| 46 | + |
| 47 | +const OBJECT = { name: 'osnd_note', label: 'Note', fields: { body: { type: 'text', label: 'Body' } } }; |
| 48 | +const MANIFEST = { id: 'com.example.not-declared', name: 'Not Declared', version: '0.0.0', type: 'app' }; |
| 49 | + |
| 50 | +const FLOW_DISPATCH = 'sys_flow_dispatch'; |
| 51 | +const CONTROL = 'sys_migration_journal'; |
| 52 | + |
| 53 | +let dir: string; |
| 54 | +let templateDb: string; |
| 55 | +const savedEnv: Record<string, string | undefined> = {}; |
| 56 | +const savedCwd = process.cwd(); |
| 57 | + |
| 58 | +const hasOrganizationColumn = (dbFile: string, table: string): boolean => { |
| 59 | + const db = new Database(dbFile, { readonly: true }); |
| 60 | + try { |
| 61 | + return (db.prepare(`PRAGMA table_info("${table}")`).all() as Array<{ name: string }>).some((c) => c.name === 'organization_id'); |
| 62 | + } finally { |
| 63 | + db.close(); |
| 64 | + } |
| 65 | +}; |
| 66 | + |
| 67 | +/** A served boot of this tree over `dbFile`: every table these plugins declare. */ |
| 68 | +async function bootServed(projectDir: string, dbFile: string): Promise<void> { |
| 69 | + const { createStandaloneStack, Runtime } = await import('@objectstack/runtime'); |
| 70 | + const stack = await createStandaloneStack({ |
| 71 | + projectRoot: projectDir, |
| 72 | + databaseUrl: `file:${dbFile}`, |
| 73 | + skipSeedData: true, |
| 74 | + armLifecycleSweep: false, |
| 75 | + }); |
| 76 | + const runtime = new Runtime({ cluster: false }); |
| 77 | + const kernel = runtime.getKernel(); |
| 78 | + for (const plugin of stack.plugins) await kernel.use(plugin as any); |
| 79 | + await kernel.use(new PlatformObjectsPlugin() as any); |
| 80 | + // The default store, so `sys_flow_dispatch` is declared and created. |
| 81 | + await kernel.use(new AutomationServicePlugin({ armRuntime: false }) as any); |
| 82 | + await runtime.start(); |
| 83 | + await kernel.shutdown(); |
| 84 | +} |
| 85 | + |
| 86 | +/** A project directory whose config is `config` (no artifact). */ |
| 87 | +function projectFor(name: string, config: Record<string, unknown>): string { |
| 88 | + const projectDir = join(dir, 'projects', name); |
| 89 | + mkdirSync(projectDir, { recursive: true }); |
| 90 | + writeFileSync(join(projectDir, 'objectstack.config.mjs'), `export default ${JSON.stringify(config, null, 2)};\n`); |
| 91 | + return projectDir; |
| 92 | +} |
| 93 | + |
| 94 | +/** The real command, `--apply`, from `projectDir`, over a fresh copy of the fixture. */ |
| 95 | +async function applyIn(projectDir: string): Promise<{ dbFile: string; report: any; exitCode: number }> { |
| 96 | + const dbFile = join(projectDir, 'v17.db'); |
| 97 | + copyFileSync(templateDb, dbFile); |
| 98 | + const savedExit = process.exitCode; |
| 99 | + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { |
| 100 | + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; |
| 101 | + if (cb) cb(); |
| 102 | + return true; |
| 103 | + }) as typeof process.stdout.write; |
| 104 | + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); |
| 105 | + vi.spyOn(process.stderr, 'write').mockImplementation(swallow); |
| 106 | + vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 107 | + vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 108 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 109 | + process.chdir(projectDir); |
| 110 | + let exitCode: number | undefined; |
| 111 | + try { |
| 112 | + try { |
| 113 | + await MigrateOrganizationOwnership.run( |
| 114 | + ['--apply', '--backup-taken', '--out', join(projectDir, 'apply.json'), '--database-url', `file:${dbFile}`, '--json'], |
| 115 | + { root: CLI_ROOT }, |
| 116 | + ); |
| 117 | + } catch (error) { |
| 118 | + if (!isExitSignal(error)) throw error; |
| 119 | + exitCode = (error as { oclif?: { exit?: number } }).oclif?.exit; |
| 120 | + } |
| 121 | + const payload = JSON.parse(stdout.mock.calls.map((c) => String(c[0])).join('').trim()); |
| 122 | + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); |
| 123 | + return { dbFile, report: payload.report, exitCode: exitCode ?? (process.exitCode as number | undefined) ?? 0 }; |
| 124 | + } finally { |
| 125 | + process.chdir(savedCwd); |
| 126 | + process.exitCode = savedExit; |
| 127 | + vi.restoreAllMocks(); |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +const columnDrops = (report: any): { status: string; summary: Record<string, number>; blockers: string[] } => |
| 132 | + report.steps.find((s: { step: string }) => s.step === 'column-drops'); |
| 133 | +const blockersFor = (report: any, table: string): string[] => |
| 134 | + columnDrops(report).blockers.filter((b) => b.includes(`${table}.organization_id`)); |
| 135 | + |
| 136 | +beforeAll(async () => { |
| 137 | + for (const key of [...OVERRIDING_ENV, 'NODE_ENV', 'OS_SECRET_KEY'] as const) savedEnv[key] = process.env[key]; |
| 138 | + for (const key of OVERRIDING_ENV) delete process.env[key]; |
| 139 | + // The deployed posture: no telemetry sibling, and the crypto provider's key. |
| 140 | + process.env.NODE_ENV = 'production'; |
| 141 | + process.env.OS_SECRET_KEY = randomBytes(32).toString('hex'); |
| 142 | + |
| 143 | + dir = mkdtempSync(join(tmpdir(), 'os-ceremony-not-declared-')); |
| 144 | + const served = join(dir, 'served'); |
| 145 | + mkdirSync(served, { recursive: true }); |
| 146 | + templateDb = join(dir, 'template.db'); |
| 147 | + await bootServed(served, templateDb); |
| 148 | + // The v17 shape: the injected tenant column both objects carried before |
| 149 | + // they declared `systemFields: { tenant: false }`. |
| 150 | + const db = new Database(templateDb); |
| 151 | + try { |
| 152 | + for (const table of [FLOW_DISPATCH, CONTROL]) db.exec(`ALTER TABLE "${table}" ADD COLUMN "organization_id" varchar(255)`); |
| 153 | + } finally { |
| 154 | + db.close(); |
| 155 | + } |
| 156 | +}, CASE_TIMEOUT_MS); |
| 157 | + |
| 158 | +afterAll(() => { |
| 159 | + process.chdir(savedCwd); |
| 160 | + for (const [key, value] of Object.entries(savedEnv)) { |
| 161 | + if (value === undefined) delete process.env[key]; |
| 162 | + else process.env[key] = value; |
| 163 | + } |
| 164 | + rmSync(dir, { recursive: true, force: true }); |
| 165 | +}); |
| 166 | + |
| 167 | +describe('organization-ownership --apply: a column-drop table the booted composition does not declare', () => { |
| 168 | + it('(i) a config that requests no automation: sys_flow_dispatch is not-declared, kept, and named', async () => { |
| 169 | + const { dbFile, report, exitCode } = await applyIn(projectFor('no-automation', { manifest: MANIFEST, objects: [OBJECT] })); |
| 170 | + |
| 171 | + const step = columnDrops(report); |
| 172 | + expect(step.status).toBe('blocked'); |
| 173 | + expect(step.summary.notDeclared).toBe(1); |
| 174 | + expect(blockersFor(report, FLOW_DISPATCH)).toHaveLength(1); |
| 175 | + expect(hasOrganizationColumn(dbFile, FLOW_DISPATCH)).toBe(true); |
| 176 | + // The in-run control: a declared column-drop table is dropped by the same run. |
| 177 | + expect(blockersFor(report, CONTROL)).toEqual([]); |
| 178 | + expect(hasOrganizationColumn(dbFile, CONTROL)).toBe(false); |
| 179 | + expect(exitCode).toBe(1); |
| 180 | + }, CASE_TIMEOUT_MS); |
| 181 | + |
| 182 | + it('(ii) the control — a config with requires: [automation]: the same column is proposed and dropped', async () => { |
| 183 | + const { dbFile, report } = await applyIn( |
| 184 | + projectFor('automation', { manifest: MANIFEST, objects: [OBJECT], requires: ['automation'] }), |
| 185 | + ); |
| 186 | + |
| 187 | + expect(columnDrops(report).summary.notDeclared).toBe(0); |
| 188 | + expect(blockersFor(report, FLOW_DISPATCH)).toEqual([]); |
| 189 | + expect(report.tables.find((t: { object: string }) => t.object === FLOW_DISPATCH)).toMatchObject({ columnDropped: true }); |
| 190 | + expect(hasOrganizationColumn(dbFile, FLOW_DISPATCH)).toBe(false); |
| 191 | + }, CASE_TIMEOUT_MS); |
| 192 | +}); |
0 commit comments