|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ADR-0142 D1] A stack that declares `queues` and `assignmentRules` boots |
| 5 | + * through the migrate path, and `os migrate summary-nulls` fills its new |
| 6 | + * roll-ups on that stack. |
| 7 | + * |
| 8 | + * The engine refuses, at `kernel:ready`, a stack declaring either key with no |
| 9 | + * `ownership-queue` service registered. `os serve` registers it (`sharing` is |
| 10 | + * on its always-on slate); every one-shot `bootSchemaStack` boot whose plugin |
| 11 | + * set carried no sharing provider refused instead, so a queue-using app could |
| 12 | + * run no data migration at all. `bootSchemaStack` now registers the service |
| 13 | + * `os serve`'s provider registers, and nothing else of it, whenever the boot |
| 14 | + * lacks that provider (`../../utils/migrate-ownership-queue.ts`). |
| 15 | + * |
| 16 | + * ## The fixture |
| 17 | + * |
| 18 | + * One app object owning two roll-ups (`count`, `sum`) over a master-detail |
| 19 | + * child, one declared queue and one declared assignment rule routing the |
| 20 | + * child into it. The parent and child rows are written through the DRIVER, |
| 21 | + * below the engine's door, which is how rows stored before the roll-ups were |
| 22 | + * declared hold them: `NULL`, never recomputed. |
| 23 | + * |
| 24 | + * Pinned: |
| 25 | + * 1. `os migrate summary-nulls` — dry run, then `--apply` — runs on that |
| 26 | + * stack: the dry run counts the `NULL` values and writes none, the apply |
| 27 | + * fills each with its real aggregate, a re-run reads zero. |
| 28 | + * 2. Each composition a migrate subcommand boots with registers the |
| 29 | + * service: the plain data stack (`account-issuer`, `duplicates`, |
| 30 | + * `multi-value-columns`), a data-migration plugin set |
| 31 | + * (`buildDataMigrationPlugins`, the rest of the data family), the host |
| 32 | + * composition (`packageless-overlays`, `security-catalog-overlays`) and |
| 33 | + * the served-platform composition (`plan`, `apply`, `unmapped-columns`, |
| 34 | + * `organization-ownership`), which already mounts the provider and is |
| 35 | + * given no second registration (the kernel refuses one under the same |
| 36 | + * name, so that boot would throw). |
| 37 | + * 3. Nothing else of sharing comes with it: no `sharing` service, and no |
| 38 | + * sharing object in the registry, so the one-shot boot examines the |
| 39 | + * tables it always did. |
| 40 | + */ |
| 41 | + |
| 42 | +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; |
| 43 | +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 44 | +import { tmpdir } from 'node:os'; |
| 45 | +import { dirname, join, resolve } from 'node:path'; |
| 46 | +import { fileURLToPath } from 'node:url'; |
| 47 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 48 | +import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts'; |
| 49 | +import { OwnershipQueueService } from '@objectstack/plugin-sharing'; |
| 50 | +import { isExitSignal } from '../../utils/format.js'; |
| 51 | +import { bootSchemaStack } from '../../utils/schema-migrate.js'; |
| 52 | +import { buildDataMigrationPlugins } from '../../utils/data-migration-plugins.js'; |
| 53 | +import MigrateSummaryNulls from './summary-nulls.js'; |
| 54 | +// [#10126] Pay the first transform of the dist-resolved workspace deps the |
| 55 | +// boot reaches through dynamic `import()`s at MODULE LOAD, not inside a |
| 56 | +// clocked case (`scripts/check-test-source-alias.mjs`). |
| 57 | +import '@objectstack/runtime'; |
| 58 | +import '@objectstack/objectql'; |
| 59 | +import '@objectstack/plugin-audit'; |
| 60 | +import '@objectstack/platform-objects/plugin'; |
| 61 | +import '@objectstack/cloud-connection'; |
| 62 | +import '@objectstack/driver-turso'; |
| 63 | +import '@objectstack/metadata'; |
| 64 | +import '@objectstack/metadata-protocol'; |
| 65 | +import '@objectstack/plugin-hono-server'; |
| 66 | +import '@objectstack/plugin-security'; |
| 67 | +import '@objectstack/rest'; |
| 68 | +import '@objectstack/service-automation'; |
| 69 | +import '@objectstack/service-datasource'; |
| 70 | +import '@objectstack/service-settings'; |
| 71 | +import '@objectstack/service-storage'; |
| 72 | + |
| 73 | +const HERE = dirname(fileURLToPath(import.meta.url)); |
| 74 | +const CLI_ROOT = resolve(HERE, '..', '..', '..'); |
| 75 | +const CASE_TIMEOUT_MS = 120_000; |
| 76 | +const ORG = 'org_sqn'; |
| 77 | + |
| 78 | +const ARTIFACT = { |
| 79 | + manifest: { id: 'com.example.summary-queue', name: 'Summary Queue', version: '0.0.0', type: 'app' }, |
| 80 | + objects: [ |
| 81 | + { |
| 82 | + name: 'sqn_account', |
| 83 | + fields: { |
| 84 | + name: { type: 'text' }, |
| 85 | + contract_count: { type: 'summary', summaryOperations: { object: 'sqn_contract', field: 'id', function: 'count' } }, |
| 86 | + contract_total: { type: 'summary', summaryOperations: { object: 'sqn_contract', field: 'amount', function: 'sum' } }, |
| 87 | + }, |
| 88 | + }, |
| 89 | + { |
| 90 | + name: 'sqn_contract', |
| 91 | + fields: { |
| 92 | + title: { type: 'text' }, |
| 93 | + amount: { type: 'number' }, |
| 94 | + account: { type: 'master_detail', reference: 'sqn_account' }, |
| 95 | + }, |
| 96 | + }, |
| 97 | + ], |
| 98 | + queues: [{ name: 'sqn_intake', label: 'Contract intake', members: [] }], |
| 99 | + assignmentRules: [{ |
| 100 | + name: 'sqn_contract_intake', |
| 101 | + label: 'Contract intake', |
| 102 | + object: 'sqn_contract', |
| 103 | + active: true, |
| 104 | + entries: [{ name: 'all', assignTo: { type: 'queue', value: 'sqn_intake' } }], |
| 105 | + }], |
| 106 | +}; |
| 107 | + |
| 108 | +/** Env that would point a boot somewhere other than the fixture. */ |
| 109 | +const OVERRIDING_ENV = ['OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_ARTIFACT_PATH'] as const; |
| 110 | +const savedEnv: Record<string, string | undefined> = {}; |
| 111 | +const savedCwd = process.cwd(); |
| 112 | +let dir: string; |
| 113 | +let dbFile: string; |
| 114 | + |
| 115 | +function probe(): SqlDriver { |
| 116 | + return new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); |
| 117 | +} |
| 118 | + |
| 119 | +async function accounts(): Promise<Array<{ id: string; contract_count: unknown; contract_total: unknown }>> { |
| 120 | + const driver = probe(); |
| 121 | + try { |
| 122 | + return await (driver as any).knex('sqn_account').select('id', 'contract_count', 'contract_total').orderBy('id'); |
| 123 | + } finally { |
| 124 | + await driver.disconnect(); |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/** One command run through oclif, its `--json` document captured. */ |
| 129 | +async function runJson(argv: string[]): Promise<{ payload: any; exitCode: number }> { |
| 130 | + const savedExit = process.exitCode; |
| 131 | + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { |
| 132 | + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; |
| 133 | + if (cb) cb(); |
| 134 | + return true; |
| 135 | + }) as typeof process.stdout.write; |
| 136 | + // Installed before the boot: a `--json` boot reserves stdout and keeps |
| 137 | + // whatever `process.stdout.write` is at that moment. |
| 138 | + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); |
| 139 | + vi.spyOn(process.stderr, 'write').mockImplementation(swallow); |
| 140 | + vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 141 | + vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 142 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 143 | + let exitCode = 0; |
| 144 | + try { |
| 145 | + try { |
| 146 | + await MigrateSummaryNulls.run(argv, { root: CLI_ROOT }); |
| 147 | + } catch (error) { |
| 148 | + if (!isExitSignal(error)) throw error; |
| 149 | + exitCode = (error as { oclif?: { exit?: number } }).oclif?.exit ?? 1; |
| 150 | + } |
| 151 | + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); |
| 152 | + let payload: any; |
| 153 | + try { payload = JSON.parse(out); } catch { payload = { unparsed: out.slice(-600) }; } |
| 154 | + return { payload, exitCode: exitCode || ((process.exitCode as number | undefined) ?? 0) }; |
| 155 | + } finally { |
| 156 | + process.exitCode = savedExit; |
| 157 | + vi.restoreAllMocks(); |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +beforeAll(async () => { |
| 162 | + for (const key of [...OVERRIDING_ENV, 'NODE_ENV'] as const) savedEnv[key] = process.env[key]; |
| 163 | + for (const key of OVERRIDING_ENV) delete process.env[key]; |
| 164 | + process.env.NODE_ENV = 'test'; |
| 165 | + dir = mkdtempSync(join(tmpdir(), 'os-summary-queue-')); |
| 166 | + mkdirSync(join(dir, 'dist'), { recursive: true }); |
| 167 | + // The standalone stack reads `OS_ARTIFACT_PATH`, else `<cwd>/dist/objectstack.json`. |
| 168 | + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); |
| 169 | + writeFileSync(process.env.OS_ARTIFACT_PATH, JSON.stringify(ARTIFACT)); |
| 170 | + dbFile = join(dir, 'app.db'); |
| 171 | + |
| 172 | + // The tables, from a plain one-shot boot of this stack — itself the |
| 173 | + // composition `account-issuer` / `duplicates` boot with. |
| 174 | + const stack = await bootSchemaStack({ jsonOutput: false, databaseUrl: `file:${dbFile}`, projectRoot: dir }); |
| 175 | + await stack.shutdown(); |
| 176 | + |
| 177 | + // The before-state, below the engine's door: no recompute ever ran. |
| 178 | + const driver = probe(); |
| 179 | + try { |
| 180 | + const k = (driver as any).knex; |
| 181 | + await k('sqn_account').insert([ |
| 182 | + { id: 'a_busy', name: 'Busy', organization_id: ORG }, |
| 183 | + { id: 'a_quiet', name: 'Quiet', organization_id: ORG }, |
| 184 | + ]); |
| 185 | + await k('sqn_contract').insert([ |
| 186 | + { id: 'c1', title: 'C1', amount: 10, account: 'a_busy', organization_id: ORG }, |
| 187 | + { id: 'c2', title: 'C2', amount: 32, account: 'a_busy', organization_id: ORG }, |
| 188 | + ]); |
| 189 | + } finally { |
| 190 | + await driver.disconnect(); |
| 191 | + } |
| 192 | +}, 180_000); |
| 193 | + |
| 194 | +afterAll(() => { |
| 195 | + process.chdir(savedCwd); |
| 196 | + for (const [key, value] of Object.entries(savedEnv)) { |
| 197 | + if (value === undefined) delete process.env[key]; |
| 198 | + else process.env[key] = value; |
| 199 | + } |
| 200 | + try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ } |
| 201 | +}); |
| 202 | + |
| 203 | +// The command takes `process.cwd()` as the project root, as a real invocation does. |
| 204 | +beforeEach(() => { process.chdir(dir); }); |
| 205 | +afterEach(() => { process.chdir(savedCwd); }); |
| 206 | + |
| 207 | +describe('os migrate summary-nulls on a stack declaring queues and assignmentRules', () => { |
| 208 | + it('the dry run boots, counts the NULL roll-ups and writes none; --apply fills them; a re-run reads zero', async () => { |
| 209 | + expect(await accounts()).toEqual([ |
| 210 | + { id: 'a_busy', contract_count: null, contract_total: null }, |
| 211 | + { id: 'a_quiet', contract_count: null, contract_total: null }, |
| 212 | + ]); |
| 213 | + |
| 214 | + const preview = await runJson(['--database-url', `file:${dbFile}`, '--json']); |
| 215 | + expect(preview.payload?.error, JSON.stringify(preview.payload).slice(0, 600)).toBeUndefined(); |
| 216 | + expect(preview.exitCode).toBe(0); |
| 217 | + expect(preview.payload.apply).toBe(false); |
| 218 | + expect(preview.payload.report.nullRows).toBe(4); |
| 219 | + expect(preview.payload.report.filled).toBe(0); |
| 220 | + expect((await accounts()).every((a) => a.contract_count === null && a.contract_total === null)).toBe(true); |
| 221 | + |
| 222 | + const applied = await runJson(['--apply', '--yes', '--database-url', `file:${dbFile}`, '--json']); |
| 223 | + expect(applied.payload?.error, JSON.stringify(applied.payload).slice(0, 600)).toBeUndefined(); |
| 224 | + expect(applied.exitCode).toBe(0); |
| 225 | + expect(applied.payload.report.failures).toEqual([]); |
| 226 | + expect(applied.payload.report.filled).toBe(4); |
| 227 | + expect(await accounts()).toEqual([ |
| 228 | + { id: 'a_busy', contract_count: 2, contract_total: 42 }, |
| 229 | + { id: 'a_quiet', contract_count: 0, contract_total: 0 }, |
| 230 | + ]); |
| 231 | + |
| 232 | + const again = await runJson(['--database-url', `file:${dbFile}`, '--json']); |
| 233 | + expect(again.payload?.error).toBeUndefined(); |
| 234 | + expect(again.payload.report.nullRows).toBe(0); |
| 235 | + }, CASE_TIMEOUT_MS); |
| 236 | +}); |
| 237 | + |
| 238 | +describe('every composition an os migrate subcommand boots with registers the ownership-queue service', () => { |
| 239 | + const COMPOSITIONS: Array<{ label: string; servedPlatform?: true; options: () => Promise<Record<string, unknown>> }> = [ |
| 240 | + { label: 'the plain data stack (account-issuer, duplicates, multi-value-columns)', options: async () => ({}) }, |
| 241 | + { |
| 242 | + label: 'a data-migration plugin set (buildDataMigrationPlugins, the rest of the data family)', |
| 243 | + options: async () => ({ extraPlugins: await buildDataMigrationPlugins({ audit: true }) }), |
| 244 | + }, |
| 245 | + { label: 'the host composition (packageless-overlays, security-catalog-overlays)', options: async () => ({ composeHostStack: true }) }, |
| 246 | + { |
| 247 | + label: 'the served-platform composition (plan, apply, unmapped-columns, organization-ownership)', |
| 248 | + servedPlatform: true, |
| 249 | + options: async () => ({ composeHostStack: true, composeServedPlatform: true }), |
| 250 | + }, |
| 251 | + ]; |
| 252 | + |
| 253 | + for (const composition of COMPOSITIONS) { |
| 254 | + it(composition.label, async () => { |
| 255 | + const stack = await bootSchemaStack({ |
| 256 | + jsonOutput: false, |
| 257 | + databaseUrl: `file:${dbFile}`, |
| 258 | + projectRoot: dir, |
| 259 | + deferSchemaDdl: true, |
| 260 | + readOnlyProbe: true, |
| 261 | + ...(await composition.options()), |
| 262 | + }); |
| 263 | + try { |
| 264 | + expect(stack.kernel.getService(OWNERSHIP_QUEUE_SERVICE)).toBeInstanceOf(OwnershipQueueService); |
| 265 | + expect(() => stack.kernel.getService('sharing')).toThrow(/not found/); |
| 266 | + const engine = stack.kernel.getService('objectql') as { getConfigs(): Record<string, unknown> }; |
| 267 | + // The served platform's composition declares the sharing objects itself; no other one does. |
| 268 | + expect('sys_queue' in engine.getConfigs()).toBe(composition.servedPlatform === true); |
| 269 | + } finally { |
| 270 | + await stack.shutdown(); |
| 271 | + } |
| 272 | + }, CASE_TIMEOUT_MS); |
| 273 | + } |
| 274 | +}); |
0 commit comments