|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * A hook's own `ctx.api` write that raises the stale-roll-up refusal never |
| 5 | + * answers for the write the hook is bound to. |
| 6 | + * |
| 7 | + * `SummaryRecomputeError` (`ERR_SUMMARY_RECOMPUTE`) means "this write is |
| 8 | + * stored, only a parent's roll-up recompute failed". It carries the write's |
| 9 | + * result as `written`, and every answering surface turns it into that write's |
| 10 | + * own success. A hook that writes through `ctx.api` makes a write of its own. |
| 11 | + * When that write raised the refusal and the handler let it escape, the refusal |
| 12 | + * reached the OUTER write's caller unchanged. So the caller read the hook's |
| 13 | + * record as the result of its own write: measured through the REST data door |
| 14 | + * before this file, `POST /data/case` answered `201` with the id and record of |
| 15 | + * the row the hook wrote. Under an `after*` hook's unit (`inAfterAbortUnit`) the |
| 16 | + * unit then committed, because the refusal says "written". |
| 17 | + * |
| 18 | + * Pinned here, at the one seam a handler's error leaves through |
| 19 | + * (`triggerHooks`): |
| 20 | + * - an aborting `afterInsert` / `afterUpdate` / `afterDelete` hook: the outer |
| 21 | + * write refuses with an error that is NOT the stale-roll-up refusal (no |
| 22 | + * `code`, no `written`, the refusal kept as `cause`), leading with the outer |
| 23 | + * write, and its unit rolls both rows back; |
| 24 | + * - a code-registered hook (no unit opens): the same refusal, whose text says |
| 25 | + * what stays written, and both rows are stored; |
| 26 | + * - a `before*` hook: the same refusal, and the outer row was never written. |
| 27 | + * |
| 28 | + * Controls: a hook declared `onError: 'log'` does not fail the outer write; the |
| 29 | + * outer write's OWN refusal still answers `ERR_SUMMARY_RECOMPUTE` carrying its |
| 30 | + * own result (and its unit still commits); any other error a hook throws passes |
| 31 | + * through unchanged. |
| 32 | + * |
| 33 | + * The driver rolls back for real (a snapshot per transaction), and refuses |
| 34 | + * every write to `bucket` while `refuseBucket` is set: that is the roll-up |
| 35 | + * recompute's parent update, refused without a transient message, so no retry |
| 36 | + * runs. |
| 37 | + */ |
| 38 | + |
| 39 | +import { describe, it, expect } from 'vitest'; |
| 40 | +import type { Hook } from '@objectstack/spec/data'; |
| 41 | +import { ObjectQL } from './engine.js'; |
| 42 | +import { bindHooksToEngine } from './hook-binder.js'; |
| 43 | + |
| 44 | +type Row = Record<string, unknown>; |
| 45 | + |
| 46 | +function makeDriver() { |
| 47 | + let stores = new Map<string, Map<string, Row>>(); |
| 48 | + const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!); |
| 49 | + const matches = (row: Row, where: any) => |
| 50 | + !where || Object.entries(where).every(([k, v]) => k.startsWith('$') || row[k] === v); |
| 51 | + const begun: unknown[] = []; |
| 52 | + const committed: unknown[] = []; |
| 53 | + const rolledBack: unknown[] = []; |
| 54 | + const snapshots = new Map<unknown, typeof stores>(); |
| 55 | + const state = { refuseBucket: false }; |
| 56 | + let n = 0; |
| 57 | + const driver: any = { |
| 58 | + name: 'primary', version: '0.0.0', supports: {}, begun, committed, rolledBack, state, |
| 59 | + rowsOf: (o: string) => Array.from(storeFor(o).values()), |
| 60 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 61 | + async syncSchema() {}, |
| 62 | + async find(o: string, ast: any) { |
| 63 | + const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); |
| 64 | + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; |
| 65 | + }, |
| 66 | + async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; }, |
| 67 | + async create(o: string, data: Row) { |
| 68 | + const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` }; |
| 69 | + storeFor(o).set(String(row.id), row); |
| 70 | + return row; |
| 71 | + }, |
| 72 | + async update(o: string, id: string, data: Row) { |
| 73 | + if (state.refuseBucket && o === 'bucket') throw new Error('bucket store refused the write'); |
| 74 | + const row = { ...storeFor(o).get(String(id)), ...data, id }; |
| 75 | + storeFor(o).set(String(id), row); |
| 76 | + return row; |
| 77 | + }, |
| 78 | + async delete(o: string, id: string) { return storeFor(o).delete(String(id)); }, |
| 79 | + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, |
| 80 | + async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, |
| 81 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 82 | + async beginTransaction() { |
| 83 | + const handle = { trx: begun.length + 1 }; |
| 84 | + snapshots.set(handle, new Map(Array.from(stores, ([o, s]) => [o, new Map(Array.from(s, ([k, v]) => [k, { ...v }]))]))); |
| 85 | + begun.push(handle); |
| 86 | + return handle; |
| 87 | + }, |
| 88 | + async commit(h: unknown) { snapshots.delete(h); committed.push(h); }, |
| 89 | + async rollback(h: unknown) { stores = snapshots.get(h) ?? stores; rolledBack.push(h); }, |
| 90 | + }; |
| 91 | + return driver; |
| 92 | +} |
| 93 | + |
| 94 | +const text = (name: string) => ({ name, type: 'text' }); |
| 95 | +/** The hook's own write: a `line`, whose roll-up into `bucket` the driver refuses. */ |
| 96 | +const writeLine = (ctx: any) => ctx.api.object('line').insert({ name: `from-${ctx.event}`, bucket: 'b1' }); |
| 97 | +const hook = (events: string[], handler: (ctx: any) => unknown, extra: Partial<Hook> = {}) => |
| 98 | + ({ name: 'line_writer', object: 'case', events, handler, ...extra }) as unknown as Hook; |
| 99 | + |
| 100 | +async function makeEngine(hooks: Hook[]) { |
| 101 | + const log = () => {}; |
| 102 | + const engine = new ObjectQL({ logger: { debug: log, info: log, warn: log, error: log } } as any); |
| 103 | + (engine as any).summaryRetryOptions = { sleep: async () => {}, backoffBaseMs: 0 }; |
| 104 | + const driver = makeDriver(); |
| 105 | + engine.registerDriver(driver, true); |
| 106 | + await engine.init(); |
| 107 | + engine.registry.registerObject({ name: 'case', label: 'case', fields: { id: { ...text('id'), primaryKey: true }, name: text('name') } } as any, '__test__'); |
| 108 | + engine.registry.registerObject({ |
| 109 | + name: 'bucket', label: 'bucket', |
| 110 | + fields: { |
| 111 | + id: { ...text('id'), primaryKey: true }, name: text('name'), |
| 112 | + line_count: { name: 'line_count', type: 'summary', summaryOperations: { object: 'line', function: 'count' } }, |
| 113 | + }, |
| 114 | + } as any, '__test__'); |
| 115 | + engine.registry.registerObject({ |
| 116 | + name: 'line', label: 'line', |
| 117 | + fields: { id: { ...text('id'), primaryKey: true }, name: text('name'), bucket: { name: 'bucket', type: 'master_detail', reference: 'bucket' } }, |
| 118 | + } as any, '__test__'); |
| 119 | + await engine.insert('bucket', { id: 'b1', name: 'B' }); |
| 120 | + await engine.insert('case', { id: 'c0', name: 'existing' }); |
| 121 | + bindHooksToEngine(engine, hooks, { packageId: 'app:t' }); |
| 122 | + driver.begun.length = 0; |
| 123 | + driver.committed.length = 0; |
| 124 | + driver.rolledBack.length = 0; |
| 125 | + driver.state.refuseBucket = true; |
| 126 | + return { engine, driver }; |
| 127 | +} |
| 128 | + |
| 129 | +const refusal = (p: Promise<unknown>): Promise<any> => p.then(() => null, (e: unknown) => e); |
| 130 | +const names = (rows: Row[]) => rows.map((r) => r.name).sort(); |
| 131 | + |
| 132 | +/** The converted refusal: an internal error naming the OUTER write, the hook write's refusal kept as `cause`. */ |
| 133 | +function expectHookStopped(err: any, lead: string) { |
| 134 | + expect(err).toBeInstanceOf(Error); |
| 135 | + expect(err.code).toBeUndefined(); |
| 136 | + expect(err.written).toBeUndefined(); |
| 137 | + expect(err.failures).toBeUndefined(); |
| 138 | + expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE'); |
| 139 | + expect(err.cause?.written?.name).toMatch(/^from-/); |
| 140 | + expect(err.message.startsWith(lead), err.message).toBe(true); |
| 141 | + expect(err.message).toContain('bucket.line_count'); |
| 142 | +} |
| 143 | + |
| 144 | +describe('a hook\'s own ctx.api write that raises ERR_SUMMARY_RECOMPUTE never answers for the write it is bound to', () => { |
| 145 | + it('afterInsert (aborting, unit open): the insert refuses naming itself, and the unit rolls both rows back', async () => { |
| 146 | + const { engine, driver } = await makeEngine([hook(['afterInsert'], writeLine)]); |
| 147 | + const err = await refusal(engine.insert('case', { name: 'c-1' })); |
| 148 | + expectHookStopped(err, 'The insert of "case" did not complete: its afterInsert hook "line_writer" stopped.'); |
| 149 | + expect(driver.begun).toHaveLength(1); |
| 150 | + expect(driver.committed).toHaveLength(0); |
| 151 | + expect(driver.rolledBack).toHaveLength(1); |
| 152 | + expect(names(driver.rowsOf('case'))).toEqual(['existing']); |
| 153 | + expect(driver.rowsOf('line')).toHaveLength(0); |
| 154 | + }); |
| 155 | + |
| 156 | + it('afterUpdate and afterDelete (aborting, unit open): refused naming the outer write, the stored row unchanged', async () => { |
| 157 | + const upd = await makeEngine([hook(['afterUpdate'], writeLine)]); |
| 158 | + const updErr = await refusal(upd.engine.update('case', { id: 'c0', name: 'renamed' })); |
| 159 | + expectHookStopped(updErr, 'The update of "case" did not complete: its afterUpdate hook "line_writer" stopped.'); |
| 160 | + expect(upd.driver.rolledBack).toHaveLength(1); |
| 161 | + expect(names(upd.driver.rowsOf('case'))).toEqual(['existing']); |
| 162 | + expect(upd.driver.rowsOf('line')).toHaveLength(0); |
| 163 | + |
| 164 | + const del = await makeEngine([hook(['afterDelete'], writeLine)]); |
| 165 | + const delErr = await refusal(del.engine.delete('case', { where: { id: 'c0' } })); |
| 166 | + expectHookStopped(delErr, 'The delete of "case" did not complete: its afterDelete hook "line_writer" stopped.'); |
| 167 | + expect(del.driver.rolledBack).toHaveLength(1); |
| 168 | + expect(names(del.driver.rowsOf('case'))).toEqual(['existing']); |
| 169 | + expect(del.driver.rowsOf('line')).toHaveLength(0); |
| 170 | + }); |
| 171 | + |
| 172 | + it('a code-registered afterInsert (no unit opens): the same refusal, saying what stays written, and both rows stored', async () => { |
| 173 | + const { engine, driver } = await makeEngine([]); |
| 174 | + engine.registerHook('afterInsert', writeLine, { object: 'case', hookName: 'code_line_writer' }); |
| 175 | + const err = await refusal(engine.insert('case', { name: 'c-1' })); |
| 176 | + expectHookStopped(err, 'The insert of "case" did not complete: its afterInsert hook "code_line_writer" stopped.'); |
| 177 | + expect(err.message).toContain( |
| 178 | + 'Under a transaction that rolls back nothing was written; otherwise what was written before that point stays written.', |
| 179 | + ); |
| 180 | + expect(driver.begun).toHaveLength(0); |
| 181 | + expect(names(driver.rowsOf('case'))).toEqual(['c-1', 'existing']); |
| 182 | + expect(names(driver.rowsOf('line'))).toEqual(['from-afterInsert']); |
| 183 | + }); |
| 184 | + |
| 185 | + it('beforeInsert: the same refusal, and the outer row was never written', async () => { |
| 186 | + const { engine, driver } = await makeEngine([hook(['beforeInsert'], writeLine)]); |
| 187 | + const err = await refusal(engine.insert('case', { name: 'c-1' })); |
| 188 | + expectHookStopped(err, 'The insert of "case" did not complete: its beforeInsert hook "line_writer" stopped.'); |
| 189 | + expect(names(driver.rowsOf('case'))).toEqual(['existing']); |
| 190 | + // No unit opens for a before* hook, so the hook's own write stays, as the text says. |
| 191 | + expect(names(driver.rowsOf('line'))).toEqual(['from-beforeInsert']); |
| 192 | + }); |
| 193 | + |
| 194 | + it('CONTROL onError: \'log\': the hook\'s refusal is logged, and the outer insert answers its own row', async () => { |
| 195 | + const { engine, driver } = await makeEngine([hook(['afterInsert'], writeLine, { onError: 'log' })]); |
| 196 | + const row: any = await engine.insert('case', { name: 'c-1' }); |
| 197 | + expect(row?.name).toBe('c-1'); |
| 198 | + expect(names(driver.rowsOf('case'))).toEqual(['c-1', 'existing']); |
| 199 | + expect(names(driver.rowsOf('line'))).toEqual(['from-afterInsert']); |
| 200 | + }); |
| 201 | + |
| 202 | + it('CONTROL the outer write\'s OWN refusal still answers ERR_SUMMARY_RECOMPUTE with its own result, and its unit commits', async () => { |
| 203 | + const { engine, driver } = await makeEngine([ |
| 204 | + { name: 'observe', object: 'line', events: ['afterInsert'], handler: () => {} } as unknown as Hook, |
| 205 | + ]); |
| 206 | + const err = await refusal(engine.insert('line', { name: 'direct', bucket: 'b1' })); |
| 207 | + expect(err?.code).toBe('ERR_SUMMARY_RECOMPUTE'); |
| 208 | + expect(err.written?.name).toBe('direct'); |
| 209 | + expect(driver.begun).toHaveLength(1); |
| 210 | + expect(driver.committed).toHaveLength(1); |
| 211 | + expect(driver.rolledBack).toHaveLength(0); |
| 212 | + expect(names(driver.rowsOf('line'))).toEqual(['direct']); |
| 213 | + }); |
| 214 | + |
| 215 | + it('CONTROL any other error a hook throws passes through unchanged', async () => { |
| 216 | + const boom = new Error('refused by the hook'); |
| 217 | + const { engine } = await makeEngine([hook(['afterInsert'], () => { throw boom; })]); |
| 218 | + expect(await refusal(engine.insert('case', { name: 'c-1' }))).toBe(boom); |
| 219 | + }); |
| 220 | +}); |
0 commit comments