|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #23033 — a metadata write that names its author stores that author on the |
| 5 | + * `sys_metadata` row, read back from the row the REAL engine stored. |
| 6 | + * |
| 7 | + * ## The defect |
| 8 | + * |
| 9 | + * `SysMetadataRepository`'s header maps `actor → updated_by`, and its read |
| 10 | + * side (`rowToItem`'s `authoredBy`, `listDrafts`' `updatedBy`) reads |
| 11 | + * `updated_by ?? created_by`. But `put()` built the parent row with neither |
| 12 | + * column and wrote it under `isSystem`, whose context carries no user, so the |
| 13 | + * engine's own audit stamp (`sys_stamp_audit_insert` / `_update`, which stamp |
| 14 | + * the `*_by` pair only from `session.userId`) had nobody to write either. |
| 15 | + * Every metadata row read `created_by` / `updated_by` null; the actor reached |
| 16 | + * only the history row's `recorded_by`. |
| 17 | + * |
| 18 | + * ## Why this file is here and not beside the repository |
| 19 | + * |
| 20 | + * The repository suite (`sys-metadata-repository.recorded-by.test.ts`) can only |
| 21 | + * prove the repository HANDS the engine the pair — its engine is a fake that |
| 22 | + * stores what it is given. What this card owes on top is that the pair |
| 23 | + * SURVIVES the engine: `created_by` is `readonly: true` on `sys_metadata`, the |
| 24 | + * static-readonly strip runs inside `engine.insert` / `engine.update` after the |
| 25 | + * `before*` hooks, and the audit hooks rewrite the `*_by` pair whenever a |
| 26 | + * session user is present. So the write goes through a real kernel — |
| 27 | + * `ObjectQLPlugin` binds the real audit hooks and assembles the real protocol |
| 28 | + * and `sys_metadata` declaration — and every pin reads the stored row out of |
| 29 | + * the driver, never the payload. `metadata-protocol` cannot host this: it must |
| 30 | + * not depend on `objectql`, even as a devDependency (the same reason |
| 31 | + * `plugin.authoring-channel.test.ts` lives here). |
| 32 | + * |
| 33 | + * ## The pins (the triage direction's) |
| 34 | + * |
| 35 | + * - a first write with actor A stores `created_by` A and `updated_by` A; |
| 36 | + * - a second write with actor B stores `created_by` A and `updated_by` B; |
| 37 | + * - CONTROL: a write with no actor stores both null — no placeholder user; |
| 38 | + * - history's `recorded_by` is unchanged: each history row names its own |
| 39 | + * write's actor, exactly as before; |
| 40 | + * - the door's read-back: `listDrafts` answers `updatedBy` from the row. |
| 41 | + */ |
| 42 | + |
| 43 | +import { randomUUID } from 'node:crypto'; |
| 44 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 45 | +import { ObjectKernel } from '@objectstack/core'; |
| 46 | +import { ObjectQL } from './engine.js'; |
| 47 | +import { ObjectQLPlugin } from './plugin.js'; |
| 48 | + |
| 49 | +type Stores = Map<string, Map<string, Record<string, unknown>>>; |
| 50 | + |
| 51 | +/** In-memory driver, copied from `environment-overlay-email-locale-restart.test.ts`; equality-only WHERE. */ |
| 52 | +function makeMemoryDriver(stores: Stores) { |
| 53 | + const storeFor = (obj: string) => { |
| 54 | + let s = stores.get(obj); |
| 55 | + if (!s) { s = new Map(); stores.set(obj, s); } |
| 56 | + return s; |
| 57 | + }; |
| 58 | + // `$and` / `$or` are conjoined WITH their sibling keys, the way a real |
| 59 | + // driver ANDs them. |
| 60 | + const matchesWhere = (row: Record<string, unknown>, where: any): boolean => { |
| 61 | + if (!where || typeof where !== 'object') return true; |
| 62 | + for (const [k, v] of Object.entries(where)) { |
| 63 | + if (k === '$and' && Array.isArray(v)) { |
| 64 | + if (!v.every((w: any) => matchesWhere(row, w))) return false; |
| 65 | + continue; |
| 66 | + } |
| 67 | + if (k === '$or' && Array.isArray(v)) { |
| 68 | + if (!v.some((w: any) => matchesWhere(row, w))) return false; |
| 69 | + continue; |
| 70 | + } |
| 71 | + if (k.startsWith('$')) continue; |
| 72 | + const rowVal = row[k]; |
| 73 | + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; |
| 74 | + const a = rowVal === undefined ? null : rowVal; |
| 75 | + const b = expected === undefined ? null : expected; |
| 76 | + if (a !== b) return false; |
| 77 | + } |
| 78 | + return true; |
| 79 | + }; |
| 80 | + const driver: any = { |
| 81 | + name: 'memory', version: '0.0.0', supports: {} as any, |
| 82 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, |
| 83 | + async execute() { return null; }, |
| 84 | + async find(object: string, ast: any) { |
| 85 | + const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); |
| 86 | + // The caller's bound, after the filter, by presence (`check:objectql-double-limit`). |
| 87 | + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; |
| 88 | + }, |
| 89 | + async findOne(object: string, ast: any) { |
| 90 | + for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; |
| 91 | + return null; |
| 92 | + }, |
| 93 | + async create(object: string, data: Record<string, unknown>) { |
| 94 | + const id = (data.id as string) ?? `r_${randomUUID()}`; |
| 95 | + const row = { ...data, id }; |
| 96 | + storeFor(object).set(id, row); |
| 97 | + return row; |
| 98 | + }, |
| 99 | + async update(object: string, id: string, data: Record<string, unknown>) { |
| 100 | + const s = storeFor(object); |
| 101 | + const cur = s.get(id); |
| 102 | + if (!cur) throw new Error(`not found: ${object}/${id}`); |
| 103 | + const updated = { ...cur, ...data, id }; |
| 104 | + s.set(id, updated); |
| 105 | + return updated; |
| 106 | + }, |
| 107 | + async upsert(object: string, data: Record<string, unknown>) { |
| 108 | + const id = data.id as string | undefined; |
| 109 | + if (id && storeFor(object).has(id)) return this.update(object, id, data); |
| 110 | + return this.create(object, data); |
| 111 | + }, |
| 112 | + async delete(object: string, id: string) { return storeFor(object).delete(id); }, |
| 113 | + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, |
| 114 | + async bulkCreate(object: string, rows: Record<string, unknown>[]) { |
| 115 | + return Promise.all(rows.map((r) => this.create(object, r))); |
| 116 | + }, |
| 117 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 118 | + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, |
| 119 | + async commit() {}, async rollback() {}, |
| 120 | + }; |
| 121 | + return driver; |
| 122 | +} |
| 123 | + |
| 124 | +const ALICE = 'usr_alice'; |
| 125 | +const BOB = 'usr_bob'; |
| 126 | +const NAME = 'case_grid'; |
| 127 | + |
| 128 | +// [#21470] `name` is the row's: a body `name` that is not its row's is refused by the write doors. |
| 129 | +const viewBody = (label: string) => ({ name: NAME, type: 'grid', label, columns: ['id'], object: 'case', viewKind: 'list' }); |
| 130 | + |
| 131 | +describe('#23033 — the sys_metadata row records who created it and who last changed it', () => { |
| 132 | + let kernel: ObjectKernel; |
| 133 | + let stores: Stores; |
| 134 | + let protocol: any; |
| 135 | + |
| 136 | + beforeEach(async () => { |
| 137 | + // `logger.level` is the real config key, and gracefulShutdown:false keeps |
| 138 | + // process signal handlers out of vitest's fork workers (#4250). |
| 139 | + kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); |
| 140 | + stores = new Map(); |
| 141 | + const engine = new ObjectQL(); |
| 142 | + engine.registerDriver(makeMemoryDriver(stores), true); |
| 143 | + await kernel.use(new ObjectQLPlugin({ ql: engine })); |
| 144 | + await kernel.bootstrap(); |
| 145 | + protocol = kernel.getService('protocol'); |
| 146 | + }); |
| 147 | + afterEach(async () => { |
| 148 | + if (kernel.getState() === 'running') await kernel.shutdown(); |
| 149 | + }); |
| 150 | + |
| 151 | + /** The stored `sys_metadata` rows for the view, as the driver holds them. */ |
| 152 | + const parentRows = (state: 'active' | 'draft' = 'active') => |
| 153 | + Array.from(stores.get('sys_metadata')?.values() ?? []) |
| 154 | + .filter((r) => r.type === 'view' && r.name === NAME && r.state === state); |
| 155 | + const parentRow = (state: 'active' | 'draft' = 'active') => { |
| 156 | + const rows = parentRows(state); |
| 157 | + expect(rows, `exactly one ${state} row for view/${NAME}`).toHaveLength(1); |
| 158 | + return rows[0]!; |
| 159 | + }; |
| 160 | + /** `recorded_by` per history row, in write order. */ |
| 161 | + const recordedBy = () => |
| 162 | + Array.from(stores.get('sys_metadata_history')?.values() ?? []) |
| 163 | + .filter((h) => h.type === 'view' && h.name === NAME) |
| 164 | + .sort((a, b) => Number(a.version) - Number(b.version)) |
| 165 | + .map((h) => h.recorded_by ?? null); |
| 166 | + |
| 167 | + it('a first write with actor A stores created_by A and updated_by A', async () => { |
| 168 | + await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A'), actor: ALICE }); |
| 169 | + |
| 170 | + const row = parentRow(); |
| 171 | + expect(row.created_by).toBe(ALICE); |
| 172 | + expect(row.updated_by).toBe(ALICE); |
| 173 | + expect(recordedBy()).toEqual([ALICE]); |
| 174 | + }); |
| 175 | + |
| 176 | + it('a second write with actor B keeps created_by A and moves updated_by to B', async () => { |
| 177 | + await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A'), actor: ALICE }); |
| 178 | + await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('B'), actor: BOB }); |
| 179 | + |
| 180 | + const row = parentRow(); |
| 181 | + expect(row.created_by, 'created_by never changes after the insert').toBe(ALICE); |
| 182 | + expect(row.updated_by, 'updated_by names the latest writer').toBe(BOB); |
| 183 | + // History is unchanged: each row still names its own write's actor. |
| 184 | + expect(recordedBy()).toEqual([ALICE, BOB]); |
| 185 | + }); |
| 186 | + |
| 187 | + it('CONTROL: a write with no actor stores both columns null — no placeholder user', async () => { |
| 188 | + await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A') }); |
| 189 | + |
| 190 | + const row = parentRow(); |
| 191 | + expect(row.created_by ?? null).toBeNull(); |
| 192 | + expect(row.updated_by ?? null).toBeNull(); |
| 193 | + expect(recordedBy()).toEqual([null]); |
| 194 | + }); |
| 195 | + |
| 196 | + it('the door reads the row back: listDrafts answers updatedBy from the draft row', async () => { |
| 197 | + await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A'), actor: ALICE, mode: 'draft' }); |
| 198 | + await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('B'), actor: BOB, mode: 'draft' }); |
| 199 | + |
| 200 | + const row = parentRow('draft'); |
| 201 | + expect(row.created_by).toBe(ALICE); |
| 202 | + expect(row.updated_by).toBe(BOB); |
| 203 | + const { drafts } = await protocol.listDrafts({ type: 'view' }); |
| 204 | + expect(drafts.map((d: any) => [d.name, d.updatedBy])).toEqual([[NAME, BOB]]); |
| 205 | + }); |
| 206 | +}); |
0 commit comments