|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * A declared `state_machine` judges every write from the record's STORED |
| 5 | + * state, and clearing the state field is itself a transition the machine must |
| 6 | + * admit — so no sequence of writes leaves a state the machine would refuse to |
| 7 | + * leave in one write. |
| 8 | + * |
| 9 | + * ## The rig |
| 10 | + * |
| 11 | + * The real `ObjectQL` engine over a store-backed driver (what is stored is |
| 12 | + * what a later read answers), one object whose state field is NOT required, so |
| 13 | + * the field validator never refuses an empty value on its own. Its machine: |
| 14 | + * `open → closed`, `closed` a declared dead-end (`[]`), and `paused`, which |
| 15 | + * lists the empty value `''` and so may be cleared. |
| 16 | + * |
| 17 | + * ## Pins |
| 18 | + * |
| 19 | + * - a clear from a declared state is refused with the transition refusal |
| 20 | + * (`VALIDATION_FAILED` / 400, field code `invalid_transition`, `from → ''`), |
| 21 | + * by id and through the bulk door, for an elevated caller too, written as |
| 22 | + * `null` or as `''`; nothing is written, so the next write is judged from |
| 23 | + * the state still stored; |
| 24 | + * - the direct illegal transition is still refused (control); |
| 25 | + * CONTROLS: a declared transition lands; a clear the machine lists lands; an |
| 26 | + * empty field written empty again, and a write that does not touch the state |
| 27 | + * field, are not judged. |
| 28 | + */ |
| 29 | + |
| 30 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 31 | +import { resolveThrownHttpError } from '@objectstack/types'; |
| 32 | +import { ObjectQL } from './engine.js'; |
| 33 | +import { ValidationError } from './validation/record-validator.js'; |
| 34 | + |
| 35 | +const OBJ = 'smss_ticket'; |
| 36 | + |
| 37 | +const TICKET = { |
| 38 | + name: OBJ, |
| 39 | + label: 'Ticket', |
| 40 | + fields: { |
| 41 | + title: { name: 'title', label: 'Title', type: 'text' }, |
| 42 | + status: { |
| 43 | + name: 'status', |
| 44 | + label: 'Status', |
| 45 | + type: 'select', |
| 46 | + options: [ |
| 47 | + { value: 'open', label: 'Open' }, |
| 48 | + { value: 'paused', label: 'Paused' }, |
| 49 | + { value: 'closed', label: 'Closed' }, |
| 50 | + ], |
| 51 | + }, |
| 52 | + }, |
| 53 | + validations: [{ |
| 54 | + type: 'state_machine', |
| 55 | + name: 'smss_flow', |
| 56 | + message: 'That status change is not allowed.', |
| 57 | + field: 'status', |
| 58 | + events: ['update'], |
| 59 | + transitions: { open: ['closed', 'paused'], paused: ['open', ''], closed: [] }, |
| 60 | + }], |
| 61 | +}; |
| 62 | + |
| 63 | +/** A store-backed driver: what is stored is what a later read answers. */ |
| 64 | +function makeStoreDriver() { |
| 65 | + const rows = new Map<string, Record<string, any>>(); |
| 66 | + const matches = (row: any, where: any): boolean => { |
| 67 | + if (!where || typeof where !== 'object') return true; |
| 68 | + return Object.entries(where).every(([k, v]: [string, any]) => { |
| 69 | + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); |
| 70 | + if (k.startsWith('$')) throw new Error(`store driver: unsupported combinator ${k}`); |
| 71 | + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { |
| 72 | + return Object.entries(v).every(([op, target]) => { |
| 73 | + if (op === '$eq') return row?.[k] === target; |
| 74 | + if (op === '$in') return Array.isArray(target) && target.includes(row?.[k]); |
| 75 | + throw new Error(`store driver: unsupported operator ${op}`); |
| 76 | + }); |
| 77 | + } |
| 78 | + return row?.[k] === v; |
| 79 | + }); |
| 80 | + }; |
| 81 | + let n = 0; |
| 82 | + const driver: any = { |
| 83 | + name: 'smss-store', version: '0.0.0', supports: {}, |
| 84 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, |
| 85 | + async syncSchema() {}, |
| 86 | + async find(_o: string, ast: any) { |
| 87 | + const hits = Array.from(rows.values()).filter((r) => matches(r, ast?.where)); |
| 88 | + return (typeof ast?.limit === 'number' ? hits.slice(0, ast.limit) : hits).map((r) => ({ ...r })); |
| 89 | + }, |
| 90 | + async findOne(_o: string, ast: any) { |
| 91 | + for (const r of rows.values()) if (matches(r, ast?.where)) return { ...r }; |
| 92 | + return null; |
| 93 | + }, |
| 94 | + async create(_o: string, data: Record<string, unknown>) { |
| 95 | + n += 1; |
| 96 | + const id = (data.id as string) ?? `rec_${n}`; |
| 97 | + const row = { ...data, id }; |
| 98 | + rows.set(id, row); |
| 99 | + return { ...row }; |
| 100 | + }, |
| 101 | + async update(_o: string, id: string, data: Record<string, unknown>) { |
| 102 | + const row = { ...rows.get(id), ...data, id }; |
| 103 | + rows.set(id, row); |
| 104 | + return { ...row }; |
| 105 | + }, |
| 106 | + async updateMany(_o: string, ast: any, data: Record<string, unknown>) { |
| 107 | + const hits = Array.from(rows.values()).filter((r) => matches(r, ast?.where)); |
| 108 | + for (const r of hits) rows.set(r.id, { ...r, ...data, id: r.id }); |
| 109 | + return hits.length; |
| 110 | + }, |
| 111 | + async delete(_o: string, id: string) { return rows.delete(id); }, |
| 112 | + async count(_o: string, ast: any) { |
| 113 | + return Array.from(rows.values()).filter((r) => matches(r, ast?.where)).length; |
| 114 | + }, |
| 115 | + }; |
| 116 | + return { driver, rows }; |
| 117 | +} |
| 118 | + |
| 119 | +type Envelope = { status: number; code: string; fields: Array<{ field: string; code: string; constraint?: unknown }> }; |
| 120 | + |
| 121 | +/** The refusal as every HTTP door reads it (ADR-0112), plus its field codes. */ |
| 122 | +function envelopeOf(err: unknown): Envelope { |
| 123 | + const thrown = resolveThrownHttpError(err); |
| 124 | + const fields = ((err as any)?.fields ?? []).map((f: any) => ({ field: f.field, code: f.code, constraint: f.constraint })); |
| 125 | + return { status: thrown.status, code: thrown.code, fields }; |
| 126 | +} |
| 127 | + |
| 128 | +async function refusalOf(run: () => Promise<unknown>): Promise<unknown> { |
| 129 | + try { |
| 130 | + await run(); |
| 131 | + } catch (e) { |
| 132 | + return e; |
| 133 | + } |
| 134 | + throw new Error('expected the write to be refused, but it succeeded'); |
| 135 | +} |
| 136 | + |
| 137 | +const transitionRefusal = (from: string, to: string): Envelope => ({ |
| 138 | + status: 400, code: 'VALIDATION_FAILED', fields: [{ field: 'status', code: 'invalid_transition', constraint: { from, to } }], |
| 139 | +}); |
| 140 | + |
| 141 | +const ALICE = { userId: 'alice' }; |
| 142 | +const SYSTEM = { isSystem: true, userId: 'alice' }; |
| 143 | + |
| 144 | +type Door = 'update by id' | 'bulk update'; |
| 145 | +const DOORS: Door[] = ['update by id', 'bulk update']; |
| 146 | + |
| 147 | +describe('a state machine judges every write from the stored state, a clear included', () => { |
| 148 | + let engine: ObjectQL; |
| 149 | + let rows: Map<string, Record<string, any>>; |
| 150 | + |
| 151 | + beforeEach(() => { |
| 152 | + const store = makeStoreDriver(); |
| 153 | + rows = store.rows; |
| 154 | + engine = new ObjectQL(); |
| 155 | + engine.registerDriver(store.driver, true); |
| 156 | + engine.registerApp({ id: 'smss', name: 'State machine stored state', objects: [TICKET] } as any); |
| 157 | + }); |
| 158 | + |
| 159 | + const seed = (status: string | null) => rows.set('t1', { id: 't1', title: 'stored', status }); |
| 160 | + const write = (door: Door, payload: Record<string, unknown>, context: Record<string, unknown> = ALICE) => { |
| 161 | + if (door === 'update by id') return engine.update(OBJ, payload, { where: { id: 't1' }, context } as any); |
| 162 | + return engine.update(OBJ, payload, { where: { id: { $in: ['t1'] } }, multi: true, context } as any); |
| 163 | + }; |
| 164 | + const stored = () => rows.get('t1')?.status; |
| 165 | + |
| 166 | + describe.each(DOORS)('%s', (door) => { |
| 167 | + it.each([['null', null], ['the empty string', '']] as const)( |
| 168 | + 'a clear (written as %s) from a declared dead-end is refused as a transition, and the state stays stored', |
| 169 | + async (_label, empty) => { |
| 170 | + seed('closed'); |
| 171 | + const err = await refusalOf(() => write(door, { status: empty })); |
| 172 | + expect(err).toBeInstanceOf(ValidationError); |
| 173 | + expect(envelopeOf(err)).toEqual(transitionRefusal('closed', '')); |
| 174 | + expect(stored()).toBe('closed'); |
| 175 | + // The next write is judged from the state still stored: leaving it is refused. |
| 176 | + expect(envelopeOf(await refusalOf(() => write(door, { status: 'open' })))).toEqual(transitionRefusal('closed', 'open')); |
| 177 | + expect(stored()).toBe('closed'); |
| 178 | + }, |
| 179 | + ); |
| 180 | + |
| 181 | + it('a clear from a state that does not list the empty value is refused', async () => { |
| 182 | + seed('open'); |
| 183 | + expect(envelopeOf(await refusalOf(() => write(door, { status: null })))).toEqual(transitionRefusal('open', '')); |
| 184 | + expect(stored()).toBe('open'); |
| 185 | + }); |
| 186 | + |
| 187 | + it('an elevated caller is judged the same way', async () => { |
| 188 | + seed('closed'); |
| 189 | + expect(envelopeOf(await refusalOf(() => write(door, { status: null }, SYSTEM)))).toEqual(transitionRefusal('closed', '')); |
| 190 | + expect(stored()).toBe('closed'); |
| 191 | + }); |
| 192 | + |
| 193 | + it('control: the direct illegal transition is still refused', async () => { |
| 194 | + seed('closed'); |
| 195 | + expect(envelopeOf(await refusalOf(() => write(door, { status: 'open' })))).toEqual(transitionRefusal('closed', 'open')); |
| 196 | + expect(stored()).toBe('closed'); |
| 197 | + }); |
| 198 | + |
| 199 | + it('control: a declared transition lands', async () => { |
| 200 | + seed('open'); |
| 201 | + await write(door, { status: 'closed' }); |
| 202 | + expect(stored()).toBe('closed'); |
| 203 | + }); |
| 204 | + |
| 205 | + it('control: a clear the machine lists lands', async () => { |
| 206 | + seed('paused'); |
| 207 | + await write(door, { status: null }); |
| 208 | + expect(stored() ?? null).toBeNull(); |
| 209 | + }); |
| 210 | + |
| 211 | + it('control: an empty field written empty again, and a write that leaves the state alone, are not judged', async () => { |
| 212 | + seed(null); |
| 213 | + await write(door, { status: null }); |
| 214 | + expect(stored() ?? null).toBeNull(); |
| 215 | + seed('closed'); |
| 216 | + await write(door, { title: 'renamed' }); |
| 217 | + expect(rows.get('t1')).toMatchObject({ title: 'renamed', status: 'closed' }); |
| 218 | + }); |
| 219 | + }); |
| 220 | +}); |
0 commit comments