|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// [#24535] The by-name read's EXECUTION face (`getMetaItemForExecution`) is |
| 4 | +// the served face (`getMetaItem`) minus the serving decorations, and nothing |
| 5 | +// else. |
| 6 | +// |
| 7 | +// Both faces are one body (`readMetaItemFace` → `readMetaItem`); the face |
| 8 | +// decides only what happens at the read's exits. So the parity this file pins |
| 9 | +// is exact, not "close enough": |
| 10 | +// |
| 11 | +// - THE ITEM: decorating the execution face's item reproduces the served |
| 12 | +// face's item, `toEqual` — `decorateMetadataItem` is the served exit's |
| 13 | +// decoration (`_diagnostics` computed on the raw body, then the type's |
| 14 | +// credential redaction), so this one equality says "the served item minus |
| 15 | +// `_diagnostics` and redaction", for a redacting type as for a plain one. |
| 16 | +// - THE ENVELOPE: every other key (`lock`, `editable`, `version`, `packageId`, |
| 17 | +// …) is equal, save `registration`, which the served face alone carries, |
| 18 | +// as the list read's served face alone carries `registrations`. |
| 19 | +// - THE REFUSALS: a disabled package's object and a missing draft are refused |
| 20 | +// with the same code on both faces. |
| 21 | +// - THE CACHE: an environment-overlay item's active rows are read through ONE |
| 22 | +// overlay-cache entry for both faces, retired by a write for both. |
| 23 | +// |
| 24 | +// Every parity row also asserts the served item IS decorated, so the equality |
| 25 | +// cannot hold by both faces skipping the decoration. |
| 26 | +// |
| 27 | +// Test-path resolution: every subject is imported by relative specifier, so |
| 28 | +// vitest resolves it from this package's source. |
| 29 | + |
| 30 | +import { describe, it, expect } from 'vitest'; |
| 31 | +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; |
| 32 | +import { ObjectStackProtocolImplementation } from './protocol.js'; |
| 33 | +import { decorateMetadataItem } from './metadata-diagnostics.js'; |
| 34 | +import { metaOverlayCacheEntryCount } from './meta-overlay-cache.js'; |
| 35 | + |
| 36 | +type Row = Record<string, unknown>; |
| 37 | + |
| 38 | +const matches = (row: Row, where: Row = {}): boolean => Object.entries(where).every(([k, v]) => { |
| 39 | + if (k.startsWith('$')) throw new Error(`store double: unsupported combinator ${k}`); |
| 40 | + if (v !== null && typeof v === 'object') { |
| 41 | + const set = (v as { $in?: unknown }).$in; |
| 42 | + if (!Array.isArray(set)) throw new Error(`store double: unsupported operator in ${JSON.stringify(v)}`); |
| 43 | + return set.includes(row[k] ?? null); |
| 44 | + } |
| 45 | + return v === undefined || (row[k] ?? null) === (v ?? null); |
| 46 | +}); |
| 47 | + |
| 48 | +/** A code-registered object: the registry's item, no stored row. */ |
| 49 | +const CODE_OBJECT = { |
| 50 | + name: 'code_widget', |
| 51 | + label: 'Code Widget', |
| 52 | + fields: { title: { name: 'title', label: 'Title', type: 'text' } }, |
| 53 | + enable: { apiMethods: ['get', 'list'] }, |
| 54 | +}; |
| 55 | + |
| 56 | +const objectRow = (name: string, state: 'active' | 'draft', body: Row): Row => ({ |
| 57 | + id: `r_${name}_${state}`, type: 'object', name, state, package_id: null, |
| 58 | + metadata: JSON.stringify({ name, fields: {}, ...body }), |
| 59 | +}); |
| 60 | + |
| 61 | +/** A `datasource` row holding an inline credential — the type with a registered redactor. */ |
| 62 | +const DATASOURCE_ROW: Row = { |
| 63 | + id: 'r_warehouse', type: 'datasource', name: 'warehouse', state: 'active', package_id: null, |
| 64 | + metadata: JSON.stringify({ |
| 65 | + name: 'warehouse', label: 'Warehouse', driver: 'postgres', |
| 66 | + config: { host: 'db.internal', database: 'warehouse', username: 'reporting', password: 'hunter2' }, |
| 67 | + }), |
| 68 | +}; |
| 69 | + |
| 70 | +const FLOW_ROW: Row = { |
| 71 | + id: 'r_flow', type: 'flow', name: 'notify_owner', state: 'active', package_id: null, |
| 72 | + metadata: JSON.stringify({ |
| 73 | + name: 'notify_owner', label: 'Notify Owner', type: 'autolaunched', |
| 74 | + nodes: [{ id: 'start', type: 'start', label: 'Start' }, { id: 'end', type: 'end', label: 'End' }], |
| 75 | + edges: [{ id: 'e1', source: 'start', target: 'end' }], |
| 76 | + }), |
| 77 | +}; |
| 78 | + |
| 79 | +function harness(rows: Row[], opts: { disabledObjects?: string[]; automation?: boolean } = {}) { |
| 80 | + const reads: Row[] = []; |
| 81 | + let epoch = 0; |
| 82 | + const seam = { |
| 83 | + get current() { return epoch; }, |
| 84 | + bump(): number { epoch += 1; return epoch; }, |
| 85 | + subscribe(): () => void { return () => {}; }, |
| 86 | + }; |
| 87 | + const disabled = new Set(opts.disabledObjects ?? []); |
| 88 | + const engine: Record<string, unknown> = { |
| 89 | + registry: { |
| 90 | + getItem: (type: string, name: string) => |
| 91 | + (type === 'object' || type === 'objects') && name === CODE_OBJECT.name |
| 92 | + ? structuredClone(CODE_OBJECT) |
| 93 | + : undefined, |
| 94 | + getObject: () => undefined, |
| 95 | + listItems: () => [], |
| 96 | + getPackage: () => undefined, |
| 97 | + getArtifactItem: () => undefined, |
| 98 | + isPackageDisabled: () => false, |
| 99 | + isObjectPackageDisabled: (name: string) => disabled.has(name), |
| 100 | + registerItem: () => undefined, |
| 101 | + registerObject: () => undefined, |
| 102 | + applyNavContributions: (app: unknown) => app, |
| 103 | + }, |
| 104 | + writeEpoch: seam, |
| 105 | + find: async (table: string, q: { where?: Row; limit?: number } = {}) => { |
| 106 | + if (table !== 'sys_metadata') return []; |
| 107 | + reads.push(structuredClone(q.where ?? {})); |
| 108 | + const hits = rows.filter((r) => matches(r, q.where)); |
| 109 | + return typeof q.limit === 'number' ? hits.slice(0, q.limit) : hits; |
| 110 | + }, |
| 111 | + findOne: async (table: string, q: { where?: Row } = {}) => { |
| 112 | + assertEngineFindOnePredicate(table, q as never); |
| 113 | + if (table !== 'sys_metadata') return null; |
| 114 | + reads.push(structuredClone(q.where ?? {})); |
| 115 | + return rows.find((r) => matches(r, q.where)) ?? null; |
| 116 | + }, |
| 117 | + }; |
| 118 | + type Middleware = (ctx: { object: string; operation: string }, next: () => Promise<void>) => Promise<void>; |
| 119 | + const middlewares: Middleware[] = []; |
| 120 | + engine.registerMiddleware = (fn: Middleware) => { |
| 121 | + middlewares.push(fn); |
| 122 | + }; |
| 123 | + /** A `sys_metadata` write as the engine makes one: the epoch first, then the chain around the row. */ |
| 124 | + const write = async (apply: () => void) => { |
| 125 | + seam.bump(); |
| 126 | + const chain = [...middlewares]; |
| 127 | + let i = 0; |
| 128 | + const next = async (): Promise<void> => { |
| 129 | + if (i < chain.length) return chain[i++]!({ object: 'sys_metadata', operation: 'update' }, next); |
| 130 | + apply(); |
| 131 | + }; |
| 132 | + await next(); |
| 133 | + }; |
| 134 | + const services = new Map<string, unknown>(); |
| 135 | + if (opts.automation) { |
| 136 | + services.set('automation', { getFlowRegistration: () => ({ state: 'registered' }) }); |
| 137 | + } |
| 138 | + const protocol = new ObjectStackProtocolImplementation(engine as never, () => services as Map<string, never>) as any; |
| 139 | + return { protocol, engine, reads, write }; |
| 140 | +} |
| 141 | + |
| 142 | +/** Read one request on both faces. */ |
| 143 | +async function bothFaces(h: ReturnType<typeof harness>, request: Row) { |
| 144 | + const served = await h.protocol.getMetaItem(structuredClone(request)); |
| 145 | + const execution = await h.protocol.getMetaItemForExecution(structuredClone(request)); |
| 146 | + return { served, execution }; |
| 147 | +} |
| 148 | + |
| 149 | +/** |
| 150 | + * THE parity: the served item is the execution item decorated, every other |
| 151 | + * envelope key is equal, and the served item really is decorated. |
| 152 | + */ |
| 153 | +function expectParity(type: string, served: any, execution: any) { |
| 154 | + expect(served.item, 'the served face found an item').toBeTruthy(); |
| 155 | + expect(served.item._diagnostics, 'the served item is decorated (anti-vacuity)').toBeDefined(); |
| 156 | + expect(Object.prototype.hasOwnProperty.call(execution.item, '_diagnostics')).toBe(false); |
| 157 | + expect(served.item).toEqual(decorateMetadataItem(type, execution.item)); |
| 158 | + const { item: _servedItem, registration: _servedOnly, ...servedEnvelope } = served; |
| 159 | + const { item: _executionItem, ...executionEnvelope } = execution; |
| 160 | + expect(executionEnvelope).toEqual(servedEnvelope); |
| 161 | +} |
| 162 | + |
| 163 | +const byNameReads = (reads: Row[], name: string) => |
| 164 | + reads.filter((w) => w.name === name && JSON.stringify(w.type) === JSON.stringify({ $in: ['object', 'objects'] })); |
| 165 | + |
| 166 | +describe('[#24535] the by-name execution read is the served read minus the serving decorations', () => { |
| 167 | + it('a CODE item: the registry\'s object, no stored row', async () => { |
| 168 | + const h = harness([]); |
| 169 | + const { served, execution } = await bothFaces(h, { type: 'object', name: CODE_OBJECT.name }); |
| 170 | + expectParity('object', served, execution); |
| 171 | + expect(execution.item.enable).toEqual(CODE_OBJECT.enable); |
| 172 | + expect(execution.version).toBeNull(); |
| 173 | + }); |
| 174 | + |
| 175 | + it('an ENVIRONMENT-OVERLAY item: the stored row, read through ONE overlay-cache entry for both faces', async () => { |
| 176 | + const rows = [objectRow('stored_widget', 'active', { label: 'Stored', enable: { apiMethods: ['get'] } })]; |
| 177 | + const h = harness(rows); |
| 178 | + const served = await h.protocol.getMetaItem({ type: 'object', name: 'stored_widget' }); |
| 179 | + expect(byNameReads(h.reads, 'stored_widget')).toHaveLength(1); |
| 180 | + // The execution face is served by the entry the served face filled. |
| 181 | + const execution = await h.protocol.getMetaItemForExecution({ type: 'object', name: 'stored_widget' }); |
| 182 | + expect(byNameReads(h.reads, 'stored_widget')).toHaveLength(1); |
| 183 | + expect(metaOverlayCacheEntryCount(h.engine)).toBe(1); |
| 184 | + expectParity('object', served, execution); |
| 185 | + expect(execution.item.enable).toEqual({ apiMethods: ['get'] }); |
| 186 | + |
| 187 | + // A write retires the entry for BOTH faces: the execution face reads |
| 188 | + // the store and serves the new row, and the served face is then |
| 189 | + // answered from the entry the execution face filled. |
| 190 | + await h.write(() => { |
| 191 | + rows[0] = objectRow('stored_widget', 'active', { label: 'Stored', enable: { apiMethods: ['get', 'list'] } }); |
| 192 | + }); |
| 193 | + const executionAfter = await h.protocol.getMetaItemForExecution({ type: 'object', name: 'stored_widget' }); |
| 194 | + expect(executionAfter.item.enable).toEqual({ apiMethods: ['get', 'list'] }); |
| 195 | + expect(byNameReads(h.reads, 'stored_widget')).toHaveLength(2); |
| 196 | + const servedAfter = await h.protocol.getMetaItem({ type: 'object', name: 'stored_widget' }); |
| 197 | + expect(byNameReads(h.reads, 'stored_widget')).toHaveLength(2); |
| 198 | + expectParity('object', servedAfter, executionAfter); |
| 199 | + }); |
| 200 | + |
| 201 | + it('a REDACTING type: the execution item is the stored body, the served one its projection', async () => { |
| 202 | + const h = harness([DATASOURCE_ROW]); |
| 203 | + const { served, execution } = await bothFaces(h, { type: 'datasource', name: 'warehouse' }); |
| 204 | + expectParity('datasource', served, execution); |
| 205 | + expect(execution.item.config.password).toBe('hunter2'); |
| 206 | + expect(served.item.config.password).toBeUndefined(); |
| 207 | + }); |
| 208 | + |
| 209 | + it('the STRICT DRAFT read: the draft row, undecorated, with the same version token', async () => { |
| 210 | + const rows = [ |
| 211 | + objectRow('stored_widget', 'active', { label: 'Active' }), |
| 212 | + objectRow('stored_widget', 'draft', { label: 'Draft', enable: { apiMethods: ['get'] } }), |
| 213 | + ]; |
| 214 | + const h = harness(rows); |
| 215 | + const { served, execution } = await bothFaces(h, { type: 'object', name: 'stored_widget', state: 'draft' }); |
| 216 | + expectParity('object', served, execution); |
| 217 | + expect(execution.item.label).toBe('Draft'); |
| 218 | + }); |
| 219 | + |
| 220 | + it('the DRAFT-PREVIEW read: the draft where one exists, the active item where none does', async () => { |
| 221 | + const withDraft = harness([ |
| 222 | + objectRow('stored_widget', 'active', { label: 'Active' }), |
| 223 | + objectRow('stored_widget', 'draft', { label: 'Draft' }), |
| 224 | + ]); |
| 225 | + const preview = await bothFaces(withDraft, { type: 'object', name: 'stored_widget', previewDrafts: true }); |
| 226 | + expectParity('object', preview.served, preview.execution); |
| 227 | + expect(preview.execution.item).toMatchObject({ label: 'Draft', _draft: true }); |
| 228 | + |
| 229 | + const withoutDraft = harness([objectRow('stored_widget', 'active', { label: 'Active' })]); |
| 230 | + const fallback = await bothFaces(withoutDraft, { type: 'object', name: 'stored_widget', previewDrafts: true }); |
| 231 | + expectParity('object', fallback.served, fallback.execution); |
| 232 | + expect(fallback.execution.item.label).toBe('Active'); |
| 233 | + }); |
| 234 | + |
| 235 | + it('a missing draft is refused `NO_DRAFT` on both faces', async () => { |
| 236 | + const h = harness([objectRow('stored_widget', 'active', { label: 'Active' })]); |
| 237 | + const request = { type: 'object', name: 'stored_widget', state: 'draft' }; |
| 238 | + await expect(h.protocol.getMetaItem({ ...request })).rejects.toMatchObject({ code: 'NO_DRAFT', status: 404 }); |
| 239 | + await expect(h.protocol.getMetaItemForExecution({ ...request })).rejects.toMatchObject({ code: 'NO_DRAFT', status: 404 }); |
| 240 | + }); |
| 241 | + |
| 242 | + it('an object of a DISABLED package is refused `OBJECT_PACKAGE_DISABLED` on both faces', async () => { |
| 243 | + const h = harness([], { disabledObjects: [CODE_OBJECT.name] }); |
| 244 | + const request = { type: 'object', name: CODE_OBJECT.name }; |
| 245 | + const servedRefusal = await h.protocol.getMetaItem({ ...request }).catch((e: unknown) => e); |
| 246 | + const executionRefusal = await h.protocol.getMetaItemForExecution({ ...request }).catch((e: unknown) => e); |
| 247 | + expect(servedRefusal).toMatchObject({ code: 'OBJECT_PACKAGE_DISABLED', status: 404 }); |
| 248 | + expect(executionRefusal).toMatchObject({ code: 'OBJECT_PACKAGE_DISABLED', status: 404 }); |
| 249 | + expect((executionRefusal as Error).message).toBe((servedRefusal as Error).message); |
| 250 | + }); |
| 251 | + |
| 252 | + it('a name with nothing behind it answers no item on both faces', async () => { |
| 253 | + const h = harness([]); |
| 254 | + const { served, execution } = await bothFaces(h, { type: 'object', name: 'no_such_object' }); |
| 255 | + expect(served.item).toBeUndefined(); |
| 256 | + expect(execution).toEqual(served); |
| 257 | + }); |
| 258 | + |
| 259 | + it('`registration` is the served face\'s alone, as the list read\'s `registrations` are', async () => { |
| 260 | + const h = harness([FLOW_ROW], { automation: true }); |
| 261 | + const { served, execution } = await bothFaces(h, { type: 'flow', name: 'notify_owner' }); |
| 262 | + expect(served.registration).toEqual({ state: 'registered' }); |
| 263 | + expect(Object.prototype.hasOwnProperty.call(execution, 'registration')).toBe(false); |
| 264 | + expectParity('flow', served, execution); |
| 265 | + }); |
| 266 | +}); |
0 commit comments