|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#24358] The engine's two relationship hydrations outside the one-hop loader |
| 5 | + * never read the stored-metadata-body family (`STORED_METADATA_BODY_OBJECTS`): |
| 6 | + * |
| 7 | + * - `expand` (`expandRelatedRecords`) — the REST read of a carrying object |
| 8 | + * with `expand` / `$expand`, its `findOne`, the nested AST form, and a hook |
| 9 | + * body's `ctx.api` read, which all reach the same loop through `find` / |
| 10 | + * `findOne`; |
| 11 | + * - the master-detail `parent` root (`resolveMasterDetailParent` / |
| 12 | + * `resolveMasterDetailParents`) — a field rule's `requiredWhen` / |
| 13 | + * `readonlyWhen` on insert and update, and the `validate()` preview, which |
| 14 | + * binds through the same batch read. |
| 15 | + * |
| 16 | + * The family's projection runs at its doors, and only for the object a request |
| 17 | + * names, so either hydration would hand the caller (or a `parent.*` verdict) |
| 18 | + * the stored body and its content hash unprojected. Each case below asserts |
| 19 | + * that no family value is served, that no family read asks for more than the |
| 20 | + * `id` column, and that the answer is the one a reference the caller may not |
| 21 | + * hydrate already gets: the stored id for `expand`, an unbound `parent` for a |
| 22 | + * rule, identical whatever the header holds. A hydration into an ordinary |
| 23 | + * object, on the same objects, is still served. |
| 24 | + */ |
| 25 | +import { beforeEach, describe, expect, it } from 'vitest'; |
| 26 | +import { STORED_METADATA_BODY_OBJECTS } from '@objectstack/spec/kernel'; |
| 27 | +import { ObjectQL } from './engine.js'; |
| 28 | + |
| 29 | +type Rec = Record<string, unknown>; |
| 30 | + |
| 31 | +const silentLogger: any = { |
| 32 | + trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, |
| 33 | + child() { return silentLogger; }, |
| 34 | +}; |
| 35 | + |
| 36 | +function makeDriver() { |
| 37 | + const stores = new Map<string, Map<string, Rec>>(); |
| 38 | + const storeFor = (o: string) => { |
| 39 | + let s = stores.get(o); |
| 40 | + if (!s) { s = new Map(); stores.set(o, s); } |
| 41 | + return s; |
| 42 | + }; |
| 43 | + const matches = (row: Rec, where: any): boolean => { |
| 44 | + if (!where || typeof where !== 'object') return true; |
| 45 | + return Object.entries(where).every(([k, v]: [string, any]) => { |
| 46 | + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); |
| 47 | + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); |
| 48 | + if (v && typeof v === 'object' && !Array.isArray(v)) { |
| 49 | + if ('$in' in v) return Array.isArray(v.$in) && v.$in.includes(row?.[k]); |
| 50 | + if ('$eq' in v) return row?.[k] === v.$eq; |
| 51 | + } |
| 52 | + return row?.[k] === v; |
| 53 | + }); |
| 54 | + }; |
| 55 | + const project = (r: Rec, fields: string[] | undefined): Rec => { |
| 56 | + if (!fields) return { ...r }; |
| 57 | + const out: Rec = {}; |
| 58 | + for (const f of fields) if (r[f] !== undefined) out[f] = r[f]; |
| 59 | + return out; |
| 60 | + }; |
| 61 | + const calls: Array<{ object: string; ast: any }> = []; |
| 62 | + let n = 0; |
| 63 | + const driver: any = { |
| 64 | + name: 'memory', version: '0.0.0', supports: {}, |
| 65 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 66 | + async find(object: string, ast: any) { |
| 67 | + calls.push({ object, ast }); |
| 68 | + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); |
| 69 | + const offset = typeof ast?.offset === 'number' ? ast.offset : 0; |
| 70 | + const paged = typeof ast?.limit === 'number' ? rows.slice(offset, offset + ast.limit) : rows.slice(offset); |
| 71 | + return paged.map((r) => project(r, ast?.fields)); |
| 72 | + }, |
| 73 | + async findOne(object: string, ast: any) { |
| 74 | + calls.push({ object, ast }); |
| 75 | + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return project(r, ast?.fields); |
| 76 | + return null; |
| 77 | + }, |
| 78 | + async create(object: string, data: Rec) { |
| 79 | + n += 1; |
| 80 | + const id = (data.id as string) ?? `r_${n}`; |
| 81 | + const row = { ...data, id }; |
| 82 | + storeFor(object).set(id, row); |
| 83 | + return { ...row }; |
| 84 | + }, |
| 85 | + async update(object: string, id: string, data: Rec) { |
| 86 | + const s = storeFor(object); |
| 87 | + const row = { ...s.get(id), ...data, id }; |
| 88 | + s.set(id, row); |
| 89 | + return { ...row }; |
| 90 | + }, |
| 91 | + async updateMany() { return 0; }, |
| 92 | + async delete(object: string, id: string) { return storeFor(object).delete(id); }, |
| 93 | + async count() { return 0; }, |
| 94 | + async bulkCreate(object: string, rows: Rec[]) { return Promise.all(rows.map((r) => this.create(object, r))); }, |
| 95 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 96 | + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, |
| 97 | + async commit() {}, async rollback() {}, |
| 98 | + }; |
| 99 | + return { driver, storeFor, calls }; |
| 100 | +} |
| 101 | + |
| 102 | +/** A synthetic stored datasource body with placeholder credential material, and a control body without it. */ |
| 103 | +const SECRET = 'PLACEHOLDER-SECRET'; |
| 104 | +const STORED_BODY = JSON.stringify({ name: 'ds', driver: 'turso', config: { url: 'libsql://x.invalid', encryptionKey: SECRET } }); |
| 105 | +const CONTROL_BODY = JSON.stringify({ name: 'ds2', driver: 'turso', config: { url: 'libsql://y.invalid' } }); |
| 106 | +const MEMBER = { userId: 'u1', tenantId: 'org_1', positions: ['member'] } as any; |
| 107 | +const SYSTEM = { isSystem: true } as any; |
| 108 | +const servesNothing = (value: unknown) => { |
| 109 | + const text = JSON.stringify(value) ?? ''; |
| 110 | + expect(text).not.toContain(SECRET); |
| 111 | + expect(text).not.toContain('PLACEHOLDER-HASH'); |
| 112 | +}; |
| 113 | +const failure = (p: Promise<unknown>) => p.then(() => undefined, (e: any) => ({ code: e?.code, message: String(e?.message) })); |
| 114 | + |
| 115 | +for (const family of STORED_METADATA_BODY_OBJECTS) { |
| 116 | + describe(`[#24358] '${family}' is never hydrated`, () => { |
| 117 | + let engine: ObjectQL; |
| 118 | + let d: ReturnType<typeof makeDriver>; |
| 119 | + /** Every family read, and whether one asked for anything beyond the `id` column. */ |
| 120 | + const familyReads = () => d.calls.filter((c) => c.object === family); |
| 121 | + const familyBodyReads = () => familyReads().filter((c) => !(Array.isArray(c.ast?.fields) && c.ast.fields.length === 1 && c.ast.fields[0] === 'id')); |
| 122 | + |
| 123 | + beforeEach(async () => { |
| 124 | + engine = new ObjectQL({ logger: silentLogger }); |
| 125 | + d = makeDriver(); |
| 126 | + engine.registerDriver(d.driver, true); |
| 127 | + await engine.init(); |
| 128 | + engine.registry.registerObject({ |
| 129 | + name: family, |
| 130 | + fields: { type: { type: 'text' }, name: { type: 'text' }, metadata: { type: 'textarea' }, checksum: { type: 'text' } }, |
| 131 | + } as any, 'test-package'); |
| 132 | + engine.registry.registerObject({ |
| 133 | + name: 'probe_other', |
| 134 | + fields: { name: { type: 'text' }, meta: { type: 'lookup', reference: family } }, |
| 135 | + } as any, 'test-package'); |
| 136 | + engine.registry.registerObject({ |
| 137 | + name: 'probe_carrier', |
| 138 | + fields: { |
| 139 | + meta: { type: 'lookup', reference: family }, |
| 140 | + metas: { type: 'lookup', reference: family, multiple: true }, |
| 141 | + other: { type: 'lookup', reference: 'probe_other' }, |
| 142 | + }, |
| 143 | + } as any, 'test-package'); |
| 144 | + engine.registry.registerObject({ |
| 145 | + name: 'probe_detail', |
| 146 | + fields: { |
| 147 | + hdr: { type: 'master_detail', reference: family }, |
| 148 | + note: { type: 'text', requiredWhen: `parent.metadata.contains('${SECRET}')` }, |
| 149 | + note2: { type: 'text', readonlyWhen: "parent.checksum.startsWith('sha256:')" }, |
| 150 | + }, |
| 151 | + } as any, 'test-package'); |
| 152 | + engine.registry.registerObject({ |
| 153 | + name: 'probe_ordinary_detail', |
| 154 | + fields: { |
| 155 | + hdr: { type: 'master_detail', reference: 'probe_other' }, |
| 156 | + note: { type: 'text', requiredWhen: "parent.name == 'Other'" }, |
| 157 | + }, |
| 158 | + } as any, 'test-package'); |
| 159 | + d.storeFor(family).set('m1', { id: 'm1', type: 'datasource', name: 'ds', metadata: STORED_BODY, checksum: 'sha256:PLACEHOLDER-HASH' }); |
| 160 | + d.storeFor(family).set('m2', { id: 'm2', type: 'datasource', name: 'ds2', metadata: CONTROL_BODY, checksum: 'md5:PLACEHOLDER-HASH' }); |
| 161 | + d.storeFor('probe_other').set('o1', { id: 'o1', name: 'Other', meta: 'm1' }); |
| 162 | + d.storeFor('probe_carrier').set('c1', { id: 'c1', meta: 'm1', metas: ['m1', 'm2'], other: 'o1' }); |
| 163 | + d.storeFor('probe_detail').set('dt1', { id: 'dt1', hdr: 'm1', note: 'n' }); |
| 164 | + d.storeFor('probe_detail').set('dt2', { id: 'dt2', hdr: 'm2', note: 'n' }); |
| 165 | + d.calls.length = 0; |
| 166 | + }); |
| 167 | + |
| 168 | + for (const [who, context] of [['a member', MEMBER], ['SYSTEM', SYSTEM]] as const) { |
| 169 | + it(`expand as ${who}: a reference into the family keeps its stored id, single and multiple, and is never read`, async () => { |
| 170 | + const rows = await engine.find('probe_carrier', { expand: { meta: {}, metas: {}, other: {} } as any, context }); |
| 171 | + expect(rows).toHaveLength(1); |
| 172 | + expect(rows[0]).toMatchObject({ meta: 'm1', metas: ['m1', 'm2'], other: { id: 'o1', name: 'Other' } }); |
| 173 | + servesNothing(rows); |
| 174 | + expect(familyReads()).toHaveLength(0); |
| 175 | + }); |
| 176 | + |
| 177 | + it(`expand as ${who}: a nested expansion into the family, and findOne, keep the stored id`, async () => { |
| 178 | + const nested = await engine.find('probe_carrier', { expand: { other: { expand: { meta: {} } } } as any, context }); |
| 179 | + expect(nested[0]).toMatchObject({ other: { id: 'o1', name: 'Other', meta: 'm1' } }); |
| 180 | + const one = await engine.findOne('probe_carrier', { where: { id: 'c1' }, expand: { meta: { fields: ['metadata', 'checksum'] } } as any, context }); |
| 181 | + expect(one).toMatchObject({ meta: 'm1' }); |
| 182 | + servesNothing([nested, one]); |
| 183 | + expect(familyReads()).toHaveLength(0); |
| 184 | + }); |
| 185 | + |
| 186 | + it(`parent as ${who}: a requiredWhen over a family header has no verdict, the same refusal whatever the header holds`, async () => { |
| 187 | + const holding = await failure(engine.insert('probe_detail', { hdr: 'm1' }, { context })); |
| 188 | + const control = await failure(engine.insert('probe_detail', { hdr: 'm2' }, { context })); |
| 189 | + expect(holding).toMatchObject({ code: 'VALIDATION_FAILED' }); |
| 190 | + expect(holding?.message).toContain("reads 'parent'"); |
| 191 | + // The verdict does not depend on the row: the bit the body would decide is not served. |
| 192 | + expect(control).toEqual(holding); |
| 193 | + servesNothing([holding, control]); |
| 194 | + expect(familyBodyReads()).toHaveLength(0); |
| 195 | + }); |
| 196 | + |
| 197 | + it(`parent as ${who}: a readonlyWhen over a family header answers the same whatever the header holds`, async () => { |
| 198 | + const answers: unknown[] = []; |
| 199 | + for (const id of ['dt1', 'dt2']) { |
| 200 | + answers.push(await engine.update('probe_detail', { id, note: 'n', note2: 'x' }, { context } as any) |
| 201 | + .then((r: any) => ({ note2: r?.note2 ?? null }), (e: any) => ({ code: e?.code }))); |
| 202 | + } |
| 203 | + expect(answers[1]).toEqual(answers[0]); |
| 204 | + servesNothing(answers); |
| 205 | + expect(familyBodyReads()).toHaveLength(0); |
| 206 | + }); |
| 207 | + |
| 208 | + it(`parent as ${who}: the validate() preview judges a family header the same whatever it holds`, async () => { |
| 209 | + const holding = await engine.validate('probe_detail', { hdr: 'm1' }, { context }); |
| 210 | + const control = await engine.validate('probe_detail', { hdr: 'm2' }, { context }); |
| 211 | + expect(JSON.stringify(control)).toBe(JSON.stringify(holding).replaceAll('m1', 'm2')); |
| 212 | + servesNothing([holding, control]); |
| 213 | + expect(familyBodyReads()).toHaveLength(0); |
| 214 | + }); |
| 215 | + } |
| 216 | + |
| 217 | + it('an ordinary master still binds parent: its requiredWhen is judged on the header', async () => { |
| 218 | + const err = await failure(engine.insert('probe_ordinary_detail', { hdr: 'o1' }, { context: SYSTEM })); |
| 219 | + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); |
| 220 | + expect(err?.message).not.toContain("reads 'parent'"); |
| 221 | + await expect(engine.insert('probe_ordinary_detail', { hdr: 'o1', note: 'n' }, { context: SYSTEM })).resolves.toMatchObject({ hdr: 'o1' }); |
| 222 | + }); |
| 223 | + }); |
| 224 | +} |
0 commit comments