diff --git a/.changeset/verify-managed-datasource-stand-in.md b/.changeset/verify-managed-datasource-stand-in.md new file mode 100644 index 00000000000..d1f3daa99c7 --- /dev/null +++ b/.changeset/verify-managed-datasource-stand-in.md @@ -0,0 +1,8 @@ +--- +'@objectstack/verify': patch +--- + +Clause-②: no +Metadata-protocol: none + +`os verify` no longer writes test rows into a declared managed datasource's real database. A datasource the app declares with `schemaMode: 'managed'` (or none) is now built as a fresh in-memory store of the same kind as verify's own default store, so its objects are still exercised (CRUD, reference shapes, delete behaviours, unique scopes) and nothing reaches the database the datasource names. A managed datasource whose engine has no faithful in-memory stand-in (`mongodb`, or a driver a plugin supplies) keeps its real driver, and verify leaves its objects out, reported as `managed datasource "NAME" (driver "DRIVER"): not exercised`. An object that requires a reference to a withheld object (external, or one of those) is now reported as withheld on purpose with the target's reason, instead of "required relational target X is not synthesizable". diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 924516134d4..24353cb54c4 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -3029,9 +3029,16 @@ os verify --flow notify_on_new_case --flow-record '{"subject":"Printer jam"}' object): every stage reports it as not exercised, and the CRUD stage lists it `skipped` as `external datasource "NAME" (writes allowed)` or `(read-only)`, which does not fail the run. An object that requires a - reference to it is skipped too. A write the app itself makes there, its seed - or a hook or flow that a stage's write fires, goes where the app sends it, - as under `os dev`. With `--rls`, a second fresh boot proves the + reference to it is skipped too, and its reason says the target was withheld + on purpose. A write the app itself makes there, its seed or a hook or flow + that a stage's write fires, goes where the app sends it, as under `os dev`. + A declared managed datasource (`schemaMode: 'managed'`, or none declared) is + not connected to the database it names: verify runs it on a fresh in-memory + store, as it runs its own default one, so every write to its objects stays + in memory and they are still exercised. One whose engine has no in-memory + stand-in (`mongodb`, or a driver a plugin supplies) keeps its real driver, + and its objects are `skipped` as `managed datasource "NAME" (driver + "DRIVER"): not exercised`. With `--rls`, a second fresh boot proves the cross-owner invariant — a member must not write what it cannot read — for a probe persona and for one persona per declared position, and a hole fails the run. With `--reference-shapes`, another fresh boot proves that every diff --git a/packages/verify/README.md b/packages/verify/README.md index 4371f8dfbfe..6146529000d 100644 --- a/packages/verify/README.md +++ b/packages/verify/README.md @@ -75,13 +75,19 @@ don't exercise, silently breaks at runtime." Point this at *your* app. > datasource: every derived write family leaves it out, even one whose write > gate is open (`external.allowWrites` and the object's `external.writable`), > and reports it `skipped` as `external datasource "" (writes allowed | -> read-only): not exercised`. An object bound to a declared MANAGED datasource -> (or one that declares no `schemaMode`) is written through that datasource, -> as under `objectstack dev`. A write the app itself makes to an external -> object (its seed, or a hook or flow -> that one of verify's writes fires) goes where the app sends it, as under -> `objectstack dev`; only the `--flow` run refuses every write routed away -> from the in-memory database. +> read-only): not exercised`; an object that requires a reference to it is +> skipped as withheld on purpose, with the target's reason. A write the app +> itself makes to an external object (its seed, or a hook or flow that one of +> verify's writes fires) goes where the app sends it, as under +> `objectstack dev`. A declared MANAGED datasource (or one that declares no +> `schemaMode`) is never connected to the database it names: verify builds it +> as a fresh in-memory store of the same kind as its own default store, so its +> objects are still exercised and every write to them, the app's included, +> stays in memory. A managed datasource whose engine has no faithful in-memory +> stand-in (`mongodb`, or a driver a plugin supplies) keeps its real driver, +> and every derived write family leaves its objects out as `managed datasource +> "" (driver ""): not exercised`. Only the `--flow` run refuses +> every write routed away from the in-memory default database. ## CLI (zero-config) diff --git a/packages/verify/src/derive.test.ts b/packages/verify/src/derive.test.ts index 3cabb5bb1a6..19e12f8234e 100644 --- a/packages/verify/src/derive.test.ts +++ b/packages/verify/src/derive.test.ts @@ -49,6 +49,21 @@ describe('deriveCrudCases — objects on an external datasource are not exercise expect(c?.blocked).toContain('external datasource "wh" (read-only): not exercised'); }); + // One reader with verify's driver factory (`isManagedDatasource`): a mode + // spelled only inside `config` or `external` gets the real driver at boot, so + // derive must withhold its objects too, or verify's rows reach that database. + it.each([ + ['config', { driver: 'postgres', config: { host: 'wh.internal', schemaMode: 'external' } }], + ['external', { driver: 'postgres', config: { host: 'wh.internal' }, external: { schemaMode: 'validate-only' } }], + ])('withholds an object whose datasource spells schemaMode only inside `%s`', (_where, ds) => { + const c = deriveCrudCases({ + datasources: [{ name: 'wh', ...ds }], + objects: [{ name: 'wh_order', datasource: 'wh', fields: { amount: { type: 'number' } } }], + }).find((x) => x.object === 'wh_order'); + expect(c?.blocked).toContain('external datasource "wh" (read-only): not exercised'); + expect(c?.body).toBeUndefined(); + }); + it('a required relation to an external object is blocked too, so nothing is written for it', () => { const config = external({ allowWrites: true }, { remoteName: 'orders', writable: true }); config.objects.push({ @@ -60,6 +75,35 @@ describe('deriveCrudCases — objects on an external datasource are not exercise ); }); + it('a managed object requiring a withheld target says it was withheld on purpose, and why', () => { + const config = external({ allowWrites: false }, { remoteName: 'orders' }); + config.objects.push( + { name: 'wh_note', fields: { order: { type: 'lookup', reference: 'wh_order', required: true } } } as any, + { name: 'wh_reply', fields: { note: { type: 'lookup', reference: 'wh_note', required: true } } } as any, + ); + const cases = deriveCrudCases(config); + const note = cases.find((x) => x.object === 'wh_note')?.blocked; + expect(note).toBe( + 'required relational target "wh_order" is withheld on purpose — external datasource "wh" (read-only): ' + + 'not exercised — verify writes only to its ephemeral store', + ); + expect(note).not.toContain('not synthesizable'); + // Transitively too: the dependent of a dependent is not called unsynthesizable. + const reply = cases.find((x) => x.object === 'wh_reply')?.blocked; + expect(reply).toContain('required relational target "wh_note" is withheld on purpose'); + expect(reply).not.toContain('not synthesizable'); + }); + + it('a required target blocked for a field shape keeps the generic sentence', () => { + const cases = deriveCrudCases({ + objects: [ + { name: 'p', fields: { blob: { type: 'composite', required: true } } }, + { name: 'c', fields: { parent: { type: 'lookup', reference: 'p', required: true } } }, + ], + }); + expect(cases.find((x) => x.object === 'c')?.blocked).toBe('required relational target "p" is not synthesizable'); + }); + it('leaves managed objects unaffected, including one on a declared managed datasource', () => { const config = { datasources: [{ name: 'side', schemaMode: 'managed' }], @@ -72,6 +116,38 @@ describe('deriveCrudCases — objects on an external datasource are not exercise expect(cases.find((x) => x.object === 'task')?.blocked).toBeFalsy(); expect(cases.find((x) => x.object === 'side_task')?.blocked).toBeFalsy(); }); + + // A managed SQL or memory datasource runs on verify's stand-in, so its + // objects are exercised (`verify.managed-datasource-stand-in.test.ts`). One + // whose engine has no stand-in keeps its real driver, so verify withholds + // its objects instead of writing through. + it('exercises an object on a managed SQL datasource, and withholds one on an engine with no stand-in', () => { + const config = { + datasources: [ + { name: 'pg', driver: 'postgres', schemaMode: 'managed' }, + { name: 'docs', driver: 'mongodb' }, + { name: 'plug', driver: 'acme-plugin-driver', schemaMode: 'managed' }, + ], + objects: [ + { name: 'pg_task', datasource: 'pg', fields: { title: { type: 'text' } } }, + { name: 'doc_task', datasource: 'docs', fields: { title: { type: 'text' } } }, + { name: 'plug_task', datasource: 'plug', fields: { title: { type: 'text' } } }, + { name: 'doc_note', fields: { doc: { type: 'lookup', reference: 'doc_task', required: true } } }, + ], + }; + const cases = deriveCrudCases(config); + expect(cases.find((x) => x.object === 'pg_task')?.blocked).toBeFalsy(); + expect(cases.find((x) => x.object === 'doc_task')?.blocked).toBe( + 'managed datasource "docs" (driver "mongodb"): not exercised — verify has no ephemeral stand-in for ' + + 'this engine and never writes through to the real one', + ); + expect(cases.find((x) => x.object === 'plug_task')?.blocked).toContain( + 'managed datasource "plug" (driver "acme-plugin-driver"): not exercised', + ); + expect(cases.find((x) => x.object === 'doc_note')?.blocked).toContain( + 'required relational target "doc_task" is withheld on purpose — managed datasource "docs"', + ); + }); }); /** diff --git a/packages/verify/src/derive.ts b/packages/verify/src/derive.ts index d29f750356b..17ddde7de72 100644 --- a/packages/verify/src/derive.ts +++ b/packages/verify/src/derive.ts @@ -21,6 +21,7 @@ import { isMultiValueField, referenceCarrierOf } from '@objectstack/spec/data'; import { declaredCollection } from './artifact-collections.js'; +import { hasManagedStandIn, isManagedDatasource } from './managed-datasource-stand-in.js'; const COMPUTED = new Set(['formula', 'summary', 'autonumber', 'rollup', 'vector']); const RELATIONAL = new Set(['lookup', 'master_detail', 'master-detail', 'masterdetail', 'tree']); @@ -197,6 +198,8 @@ interface Draft { relationalRefs: RelationalRef[]; requiredTargets: string[]; // referenced objects that MUST exist + be ordered-before blocked?: string; + /** Blocked on purpose: verify withholds writes from it (or from a required target of it). */ + withheld?: boolean; } /** @@ -207,6 +210,8 @@ interface Draft { * in. Only genuinely unsatisfiable shapes are `blocked`: * - an object on an external datasource (never written: verify writes only to * its ephemeral store), or + * - an object on a declared managed datasource whose engine verify has no + * ephemeral stand-in for (never written through), or * - a required relation whose target is missing from the app config (external), or * - a required-reference cycle (incl. a required self-reference), or * - a required relation whose target is itself blocked (cascade), or @@ -244,16 +249,37 @@ export function deriveCrudCases(config: any): CrudCase[] { // Every write family (CRUD, RLS, reference shapes, delete behaviours, // unique scopes, parent write reach, dashboard windows) builds its records // from this case, so one blocked case keeps all of them off the object. - // The datasource counts as external the way the engine's write gate counts - // it: a declared `schemaMode` other than `managed`, or an object carrying - // an `external` block. The reason names the gate's state, so the report - // says when a write was possible and was withheld. + // Two triggers count the object as external. A datasource that is not + // managed is the half the engine's write gate reads too — read here by + // `isManagedDatasource`, the same reader verify's driver factory decides + // stand-in-or-real on, so a datasource the boot connects for real is never + // one whose objects verify writes (`./managed-datasource-stand-in.ts`). + // That reader also takes a `schemaMode` spelled inside `external` or + // `config`, which the engine's gate does not read. An object carrying an + // `external` block is verify's own trigger: the engine does not gate on + // it, verify withholds the object anyway. The reason names the gate's + // state, so the report says when a write was possible and was withheld. const ds = obj.datasource ? dsByName.get(obj.datasource) : undefined; - if (obj.external || (typeof ds?.schemaMode === 'string' && ds.schemaMode !== 'managed')) { + if (obj.external || (ds && !isManagedDatasource(ds))) { const writable = ds?.external?.allowWrites === true && obj.external?.writable === true; d.blocked = `external datasource "${obj.datasource ?? 'default'}" (${writable ? 'writes allowed' : 'read-only'}): ` + 'not exercised — verify writes only to its ephemeral store'; + d.withheld = true; + drafts.set(obj.name, d); + continue; + } + + // An object on a declared MANAGED datasource runs on the ephemeral store + // verify builds in that datasource's place (`./managed-datasource-stand-in.ts`), + // unless its engine has no faithful stand-in: then the boot keeps the real + // driver, and verify withholds the object rather than write through to it. + // `default` is verify's own store whatever the app declares under that name. + if (ds && obj.datasource !== 'default' && typeof ds.driver === 'string' && !hasManagedStandIn(ds.driver)) { + d.blocked = + `managed datasource "${obj.datasource}" (driver "${ds.driver}"): not exercised — verify has no ` + + 'ephemeral stand-in for this engine and never writes through to the real one'; + d.withheld = true; drafts.set(obj.name, d); continue; } @@ -325,6 +351,14 @@ export function deriveCrudCases(config: any): CrudCase[] { if (d.blocked) continue; for (const t of d.requiredTargets) { const td = drafts.get(t); + if (td?.withheld) { + // Say the target was left out on purpose, and why: "not + // synthesizable" would send the reader after a field shape. + d.blocked = `required relational target "${t}" is withheld on purpose — ${td.blocked}`; + d.withheld = true; + changed = true; + break; + } if (!td || td.blocked) { d.blocked = `required relational target "${t}" is ${!td ? 'missing' : 'not synthesizable'}`; changed = true; diff --git a/packages/verify/src/harness.ts b/packages/verify/src/harness.ts index 63ca59a28d4..cebd9256503 100644 --- a/packages/verify/src/harness.ts +++ b/packages/verify/src/harness.ts @@ -29,11 +29,22 @@ // writes such an object when one of verify's writes fires it. Verify's own // writes never reach an object on an EXTERNAL datasource: every derived write // family leaves it out and reports it "not exercised", whatever its write gate -// says (`deriveCrudCases`, `derive.ts`). An object bound to a declared MANAGED -// datasource (or one that declares no `schemaMode`) is written through that -// datasource, as under `objectstack dev`; only the local flow run refuses a -// write to any object routed away from this database (`flow-run.ts`). -// `verify.external-datasource-no-writes.test.ts` pins the external half. +// says (`deriveCrudCases`, `derive.ts`). +// +// A declared MANAGED datasource (or one that declares no `schemaMode`) is NOT +// connected to the database it names. Ruling A of the composition rule +// (`bootStack`, #22301) already swaps the app's own default store for an +// ephemeral one; the same swap now covers every declared managed store: +// verify's driver factory builds it as a fresh in-memory store of the default +// store's engine (`managed-datasource-stand-in.ts`), so every write that +// reaches it — verify's derived writes, a REST create, the app's seed — lands +// in memory and dies with the kernel. A managed datasource whose engine has no +// faithful stand-in (`mongodb`, or a driver a plugin supplies) keeps its real +// driver, and every derived write family leaves its objects out and names +// them, as for an external one. Only the local flow run refuses a write to any +// object routed away from the default store (`flow-run.ts`). +// `verify.external-datasource-no-writes.test.ts` pins the external half and +// `verify.managed-datasource-stand-in.test.ts` the managed one. import { randomBytes } from 'node:crypto'; import { resolve as resolvePath } from 'node:path'; @@ -61,6 +72,7 @@ import { MetadataPlugin } from '@objectstack/metadata'; import { createHostImporter, hostImportFailureKind } from '@objectstack/types/node'; import { materializeStackPlugin, resolveCapabilityArgument } from '@objectstack/core'; import { createHandle, type VerifyHandle } from './handle.js'; +import { createVerifyDatasourceDriverFactory } from './managed-datasource-stand-in.js'; import { constructServedProviders } from './required-providers.js'; import { registryLevelFor, resolveBootLogLevel, scopeRegistryLogLevel } from './boot-log-level.js'; @@ -1168,7 +1180,16 @@ async function bootClaimed( const { DatasourceAdminServicePlugin, createDefaultDatasourceDriverFactory } = await import( '@objectstack/service-datasource' ); - await kernel.use(new DatasourceAdminServicePlugin({ driverFactory: createDefaultDatasourceDriverFactory() })); + // Verify's own factory over the one `objectstack dev` uses: a declared + // MANAGED datasource is built as an ephemeral store of the default + // store's engine instead of its real connection, the same swap ruling A + // makes for `default` (`./managed-datasource-stand-in.ts`). + await kernel.use(new DatasourceAdminServicePlugin({ + driverFactory: createVerifyDatasourceDriverFactory({ + real: createDefaultDatasourceDriverFactory(), + defaultStore: databaseDriver, + }), + })); } } diff --git a/packages/verify/src/managed-datasource-stand-in.ts b/packages/verify/src/managed-datasource-stand-in.ts new file mode 100644 index 00000000000..89bce80247c --- /dev/null +++ b/packages/verify/src/managed-datasource-stand-in.ts @@ -0,0 +1,131 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// @objectstack/verify — the driver factory `bootStack` hands the datasource +// connection service (ADR-0062 D1/D2). +// +// Verify writes only to stores it creates. Its own `default` store is an +// ephemeral one that stands in for whatever database the app runs on (the +// harness header, and ruling A of the composition rule in `bootStack`). This +// module extends the same swap to every datasource the app DECLARES whose +// schema ObjectStack manages: such a datasource is built as a fresh in-memory +// store of the kind verify's own default store is, never as its real +// connection, so a write verify derives for an object bound to it — or any +// other write that reaches it during the run — lands in memory and dies with +// the kernel. +// +// A datasource ObjectStack does not own (`schemaMode` `external` or +// `validate-only`) keeps its real driver: reads reach it, and `deriveCrudCases` +// (`./derive.ts`) keeps every derived write off its objects. +// +// A managed datasource whose engine has no faithful in-memory stand-in (a +// non-SQL kind such as `mongodb`, or a driver a plugin supplies, which this +// factory never builds) keeps its real driver too, and `deriveCrudCases` +// withholds its objects the way it withholds external ones, naming why. Verify +// never writes through to it. +// +// ## One reading of "is this datasource managed" +// +// {@link isManagedDatasource} is the ONE reader, and both deciders call it: this +// factory (stand-in or real driver) and `deriveCrudCases` (withhold as external +// or exercise). It is `resolveDatasourceSchemaMode` — the read the real factory +// hands the driver, `spec.schemaMode`, then `external.schemaMode`, then +// `config.schemaMode` — with no mode read as managed. Two readers drifting is +// the hazard: a datasource that spells `schemaMode` only inside `config` would +// get its real connection here (the factory's reading) while derive (the +// declared key alone, as the engine's write gate reads it) kept its objects in +// every write family, so verify's rows would land in the real database. With +// one reader, any datasource this factory keeps real is withheld by derive. + +import { resolveDriverId } from '@objectstack/spec/data'; +import { resolveDatasourceSchemaMode } from '@objectstack/service-datasource'; +import type { + DatasourceConnectionSpec, + DatasourceDriverHandle, + IDatasourceDriverFactory, +} from '@objectstack/service-datasource'; + +/** The engine verify's own default store runs on (`BootOptions.databaseDriver`). */ +export type VerifyStoreEngine = 'sqlite-wasm' | 'memory'; + +/** The SQL engines an in-memory SQLite store stands in for, as the default store does. */ +const SQL_ENGINES: ReadonlySet = new Set(['sqlite', 'sqlite-wasm', 'postgres', 'mysql', 'turso']); + +/** + * The in-memory engine verify builds in place of a MANAGED datasource on + * `driver`, or `undefined` when it has none that is faithful. + * + * A SQL engine gets the default store's engine, as verify's own `default` + * does. A `memory` datasource gets a fresh memory store with no persistence. + * Everything else — `mongodb`, the federation-only SQL engines (which a managed + * datasource cannot name), and a driver id the platform ships no contract for + * (a plugin's) — has none. + */ +export function managedStandInEngine( + driver: unknown, + defaultStore: VerifyStoreEngine, +): VerifyStoreEngine | undefined { + const kind = resolveDriverId(driver); + if (kind === 'memory') return 'memory'; + if (kind !== undefined && SQL_ENGINES.has(kind)) return defaultStore; + return undefined; +} + +/** + * Whether verify reads a declared datasource (an authored definition, or the + * connection spec built from one) as MANAGED — the one reader both this + * factory and `deriveCrudCases` decide on (see this file's header). + */ +export function isManagedDatasource(ds: { + schemaMode?: unknown; + external?: unknown; + config?: unknown; +}): boolean { + const spec = { + ...ds, + config: ds.config && typeof ds.config === 'object' ? (ds.config as Record) : {}, + } as DatasourceConnectionSpec; + return (resolveDatasourceSchemaMode(spec) ?? 'managed') === 'managed'; +} + +/** True when a managed datasource on `driver` is run on a verify stand-in rather than withheld. */ +export function hasManagedStandIn(driver: unknown): boolean { + return managedStandInEngine(driver, 'sqlite-wasm') !== undefined; +} + +export interface VerifyDatasourceDriverFactoryOptions { + /** The factory `objectstack dev` builds declared datasources with. */ + real: IDatasourceDriverFactory; + /** The engine of verify's own default store. */ + defaultStore: VerifyStoreEngine; +} + +/** + * Verify's driver factory: the real one, except that a managed datasource with + * a stand-in is built as an ephemeral in-memory store (see this file's header). + * + * The stand-in is built by the real factory from a spec of verify's own — the + * datasource's name, the stand-in engine and an in-memory config — so it goes + * through the same construction verify's default store does. Nothing of the + * declared connection (url, credentials, pool, persistence) reaches it. + */ +export function createVerifyDatasourceDriverFactory( + opts: VerifyDatasourceDriverFactoryOptions, +): IDatasourceDriverFactory { + return { + supports(driverId: string): boolean { + return opts.real.supports(driverId); + }, + create(spec: DatasourceConnectionSpec): Promise | DatasourceDriverHandle { + // The one reader derive decides on too: what this keeps real, derive withholds. + if (!isManagedDatasource(spec)) return opts.real.create(spec); + const engine = managedStandInEngine(spec.driver, opts.defaultStore); + if (engine === undefined) return opts.real.create(spec); + return opts.real.create({ + ...(spec.name !== undefined ? { name: spec.name } : {}), + driver: engine, + schemaMode: 'managed', + config: engine === 'memory' ? {} : { filename: ':memory:' }, + }); + }, + }; +} diff --git a/packages/verify/src/verify.managed-datasource-stand-in.test.ts b/packages/verify/src/verify.managed-datasource-stand-in.test.ts new file mode 100644 index 00000000000..8339bec71e2 --- /dev/null +++ b/packages/verify/src/verify.managed-datasource-stand-in.test.ts @@ -0,0 +1,253 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Verify writes only to stores it creates: a declared MANAGED datasource runs + * on an ephemeral stand-in, never on the database it names. + * + * The fixture declares a managed secondary datasource on a real, file-backed + * SQLite database — the kind `objectstack dev` opens and writes. That file is + * this suite's recording driver: whatever reaches the real datasource lands in + * it. The derived write families run over an object bound to it on one boot + * (the CRUD round trip, reference shapes, delete behaviours and unique + * scopes), plus a REST create. The pins: + * + * - nothing reached the real database: the file was never created, so no + * table and no row reached it; + * - coverage is kept: the object's CRUD case ran and was verified, against + * the stand-in, and the REST create answered and read back; + * - CONTROL: the factory `objectstack dev` builds declared datasources with + * opens that very file for the same declaration and writes a row into it, + * so the silence above is verify's stand-in and not an unreachable file. + * + * A second describe pins the factory itself, without a boot, against a + * recording real factory: which declarations it stands in for and which keep + * their real driver. + * + * ⚠️ This suite resolves `@objectstack/runtime` and the service packages + * through their BUILT `dist/`. Rebuild them before trusting a run of this file. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { defineStack } from '@objectstack/spec'; +import { + createDefaultDatasourceDriverFactory, + type DatasourceConnectionSpec, + type IDatasourceDriverFactory, +} from '@objectstack/service-datasource'; + +import { bootStack, type VerifyStack } from './harness.js'; +import { runCrudVerification, formatReport, type VerifyReport } from './verify.js'; +import { runReferenceShapeProofs, formatReferenceShapeReport } from './reference-shape.js'; +import { runDeleteBehaviorProofs, formatDeleteBehaviorReport } from './delete-behavior.js'; +import { runUniqueScopeProofs, formatUniqueScopeReport } from './unique-scope.js'; +import { createVerifyDatasourceDriverFactory } from './managed-datasource-stand-in.js'; +import { deriveCrudCases } from './derive.js'; +import { warmUpBoot } from './boot-warm-up.testkit.js'; + +// Paid at collection: the harness's boot loads these lazily (check:test-source-alias). +import '@objectstack/service-automation'; + +await warmUpBoot(); + +// Booting the full in-process stack runs well past vitest's 5s default. +const BOOT_TIMEOUT = 120_000; + +const SIDE_DS = 'vms_side_ds'; +const SIDE = 'vms_side'; +const LOCAL = 'vms_local'; + +const dir = mkdtempSync(join(tmpdir(), 'verify-managed-ds-')); +const realDatabase = join(dir, 'side.db'); + +const sideDatasource = { + name: SIDE_DS, + label: 'Managed side store (real file)', + driver: 'sqlite-wasm', + schemaMode: 'managed', + config: { filename: realDatabase }, +} as const; + +const fixtureStack = defineStack({ + manifest: { + id: 'com.objectstack.verify.managed-stand-in', + namespace: 'vms', + version: '0.0.0', + type: 'app', + name: 'Managed Stand-in Fixture', + description: 'An app declaring a managed secondary datasource on a real database file.', + }, + datasources: [sideDatasource], + objects: [ + { + name: LOCAL, + label: 'Local', + pluralLabel: 'Locals', + sharingModel: 'public_read_write', + fields: { name: { type: 'text', label: 'Name' } }, + }, + { + name: SIDE, + label: 'Side', + pluralLabel: 'Sides', + datasource: SIDE_DS, + sharingModel: 'public_read_write', + fields: { + // In each family's population: a unique field, and a reference with a delete behaviour. + serial: { type: 'text', label: 'Serial', unique: true }, + local_ref: { type: 'lookup', reference: LOCAL, label: 'Local', deleteBehavior: 'set_null' }, + }, + }, + ], +} as never); + +const CONTROL_TABLE = 'vms_control'; + +/** Rows of `table` in the real database file, read through the factory `objectstack dev` uses. */ +async function rowsIn(table: string): Promise { + const handle = await createDefaultDatasourceDriverFactory().create({ + ...sideDatasource, + config: { ...sideDatasource.config }, + } as DatasourceConnectionSpec); + await handle.connect?.(); + try { + return ((await (handle.driver as any).find(table, {})) as unknown[]).length; + } catch { + return 0; // no such table + } finally { + await handle.disconnect?.(); + } +} + +/** Whether the real database file exists, and how many fixture rows it holds. */ +async function realDatabaseState(): Promise<{ exists: boolean; rows: number }> { + if (!existsSync(realDatabase)) return { exists: false, rows: 0 }; + return { exists: true, rows: await rowsIn(SIDE) }; +} + +describe('os verify runs a declared managed datasource on an ephemeral stand-in, never on its real database', () => { + let stack: VerifyStack | undefined; + let crud: VerifyReport; + const reports: Record = {}; + let restCreate: { status: number; readBack: number; body: string }; + + beforeAll(async () => { + stack = await bootStack(fixtureStack as never, {}); + const token = await stack.signIn(); + crud = await runCrudVerification(stack, token, fixtureStack); + reports.crud = formatReport(crud); + reports.referenceShapes = formatReferenceShapeReport(await runReferenceShapeProofs(stack, token, fixtureStack)); + reports.deleteBehaviors = formatDeleteBehaviorReport(await runDeleteBehaviorProofs(stack, token, fixtureStack)); + reports.uniqueScopes = formatUniqueScopeReport(await runUniqueScopeProofs(stack, token, fixtureStack)); + // A write outside verify's derived families reaches the same datasource. + const created = await stack.apiAs(token, 'POST', `/data/${SIDE}`, { serial: 'rest-create' }); + const body = await created.text(); + const id = (JSON.parse(body) as { data?: { id?: string }; id?: string }).data?.id + ?? (JSON.parse(body) as { id?: string }).id; + const read = await stack.apiAs(token, 'GET', `/data/${SIDE}/${id}`); + restCreate = { status: created.status, readBack: read.status, body }; + await stack.stop(); + stack = undefined; + }, BOOT_TIMEOUT * 2); + + afterAll(async () => { + await stack?.stop().catch(() => undefined); + rmSync(dir, { recursive: true, force: true }); + }); + + it('nothing reached the real database: its file was never created', async () => { + expect(await realDatabaseState(), Object.values(reports).join('\n')).toEqual({ exists: false, rows: 0 }); + }); + + it("the object's CRUD case still ran, and passed against the stand-in", () => { + const side = crud.results.find((r) => r.object === SIDE); + expect(side?.status, reports.crud).toBe('verified'); + }); + + it('a REST create to the object answers and reads back, from the stand-in', () => { + expect(restCreate.status, restCreate.body).toBe(201); + expect(restCreate.readBack, restCreate.body).toBe(200); + }); + + it("CONTROL: the factory `objectstack dev` uses opens that file for the same declaration and writes into it", async () => { + const handle = await createDefaultDatasourceDriverFactory().create({ + ...sideDatasource, + config: { ...sideDatasource.config }, + } as DatasourceConnectionSpec); + const driver = handle.driver as any; + await handle.connect?.(); + // A table of the control's own, so this write does not depend on what the + // run before it left in the file. + await driver.syncSchema(CONTROL_TABLE, { name: CONTROL_TABLE, fields: { serial: { type: 'text' } } }); + await driver.create(CONTROL_TABLE, { id: 'control_1', serial: 'control' }); + await handle.disconnect?.(); + expect(existsSync(realDatabase)).toBe(true); + expect(await rowsIn(CONTROL_TABLE)).toBe(1); + }); +}); + +describe('createVerifyDatasourceDriverFactory — which declarations get a stand-in', () => { + const built: DatasourceConnectionSpec[] = []; + const real: IDatasourceDriverFactory = { + supports: () => true, + create(spec) { + built.push(spec); + return { driver: {} } as never; + }, + }; + const factory = createVerifyDatasourceDriverFactory({ real, defaultStore: 'sqlite-wasm' }); + const buildOne = async (spec: DatasourceConnectionSpec) => { + built.length = 0; + await factory.create(spec); + return built[0]; + }; + + it('a managed SQL datasource is built as an in-memory store of the default store engine', async () => { + const spec = await buildOne({ + name: 'pg', driver: 'postgres', schemaMode: 'managed', config: { host: 'db.internal' }, secret: 's3cret', + }); + expect(spec).toEqual({ name: 'pg', driver: 'sqlite-wasm', schemaMode: 'managed', config: { filename: ':memory:' } }); + }); + + it('a datasource that declares no schemaMode counts as managed', async () => { + const spec = await buildOne({ name: 'lite', driver: 'sqlite', config: { filename: './data/app.db' } }); + expect(spec).toEqual({ name: 'lite', driver: 'sqlite-wasm', schemaMode: 'managed', config: { filename: ':memory:' } }); + }); + + it('a managed memory datasource gets a fresh memory store without its persistence', async () => { + const spec = await buildOne({ + name: 'mem', driver: 'memory', schemaMode: 'managed', config: { persistence: { type: 'file', path: './m.json' } }, + }); + expect(spec).toEqual({ name: 'mem', driver: 'memory', schemaMode: 'managed', config: {} }); + }); + + it('an external datasource keeps its real driver', async () => { + const declared: DatasourceConnectionSpec = { + name: 'wh', driver: 'postgres', schemaMode: 'external', config: { host: 'wh.internal' }, external: {}, + }; + expect(await buildOne(declared)).toBe(declared); + }); + + it('a datasource that spells schemaMode only inside config keeps its real driver, and derive withholds its objects', async () => { + const declared: DatasourceConnectionSpec = { + name: 'wh', driver: 'postgres', config: { host: 'wh.internal', schemaMode: 'external' }, + }; + expect(await buildOne(declared)).toBe(declared); + // The same reader decides derive's side: what the factory keeps real is withheld. + const c = deriveCrudCases({ + datasources: [declared], + objects: [{ name: 'wh_order', datasource: 'wh', fields: { amount: { type: 'number' } } }], + }).find((x) => x.object === 'wh_order'); + expect(c?.blocked).toContain('external datasource "wh" (read-only): not exercised'); + }); + + it('a managed datasource with no faithful stand-in (mongodb) keeps its real driver; derive withholds its objects', async () => { + const declared: DatasourceConnectionSpec = { + name: 'docs', driver: 'mongodb', schemaMode: 'managed', config: { url: 'mongodb://docs.internal' }, + }; + expect(await buildOne(declared)).toBe(declared); + }); +});