|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#26031] A database NOT NULL refusal on a column the object does NOT declare |
| 5 | + * (drift: the column stayed in the table after its field left the metadata) |
| 6 | + * answers one body on every door: `RestServer`'s, `400 VALIDATION_FAILED`, the |
| 7 | + * column named, and the drift `hint`. |
| 8 | + * |
| 9 | + * ## What was wrong |
| 10 | + * |
| 11 | + * #24768 (ruling A) moved a refusal on a DECLARED field into the engine, which |
| 12 | + * now refuses it as its own `ValidationError`. A column no field declares has |
| 13 | + * no field to name, so the engine lets the driver's error out, and each door |
| 14 | + * classified it its own way. Measured on the rig below, at `origin/main` |
| 15 | + * `40bba68c` (which carries #26026): |
| 16 | + * |
| 17 | + * - `RestServer` `POST /data/:object`: `mapDataError`'s NOT NULL arm, |
| 18 | + * `400 VALIDATION_FAILED` with the column sentence and the drift `hint`; |
| 19 | + * - the dispatcher's `POST /data/:object`: the raw `SqliteError` left |
| 20 | + * `dispatch()`, and the Hono exit (`declaredEnvelopeForThrow`) declined it, |
| 21 | + * so the door answered `500 INTERNAL_ERROR`; |
| 22 | + * - `POST /actions/:object/:action`, a handler whose engine insert leaves the |
| 23 | + * column out: `400 VALIDATION_ERROR`, the driver's text as the `message` |
| 24 | + * (the physical table and column) and `declaredCode: |
| 25 | + * 'SQLITE_CONSTRAINT_NOTNULL'`. |
| 26 | + * |
| 27 | + * Both dispatcher exits now ask the arm itself (`driverNotNullRefusalAnswer`, |
| 28 | + * `@objectstack/types`), so the body is `RestServer`'s, read off one |
| 29 | + * classification, in this transport's envelope: the sentence as `message`, the |
| 30 | + * code as `code`, and the arm's `fields`, `hint` and `object` in `details`. |
| 31 | + * |
| 32 | + * ## `PATCH` cannot reach the column |
| 33 | + * |
| 34 | + * A `PATCH` naming the dropped field is refused before any driver runs, as an |
| 35 | + * undeclared field (`400 INVALID_FIELD`), on both `/data` doors alike, and so |
| 36 | + * is a `beforeUpdate` hook writing it; an update that leaves the column alone |
| 37 | + * keeps the row's stored value, which is not null. So the `PATCH` case below is |
| 38 | + * the control: one answer on both doors, unchanged. |
| 39 | + * |
| 40 | + * ## The rig |
| 41 | + * |
| 42 | + * A REAL store: better-sqlite3 `:memory:` under `driver-sql`, the real |
| 43 | + * `ObjectQL` engine and protocol. The object is registered with the column, |
| 44 | + * the table is built, and the object is registered again without it: the |
| 45 | + * metadata the doors serve has drifted from the table. The dispatcher is |
| 46 | + * reached the way `@objectstack/hono`'s catch-all reaches it, `dispatch()` |
| 47 | + * over a real Fetch `Request`, with the identity step the one stubbed seam; a |
| 48 | + * throw out of `dispatch()` is rendered by the Hono exit's own recogniser. |
| 49 | + * `RestServer` is the same stack's REST door, its routes called directly. |
| 50 | + * |
| 51 | + * Every body is asserted whole. The `hint`'s words are `RestServer`'s, read |
| 52 | + * off its answer rather than spelled here. |
| 53 | + */ |
| 54 | + |
| 55 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 56 | +import { ObjectQL } from '@objectstack/objectql'; |
| 57 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 58 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 59 | +import { declaredEnvelopeForThrow } from '@objectstack/plugin-hono-server'; |
| 60 | +import { RestServer } from '@objectstack/rest'; |
| 61 | +import { HttpDispatcher } from './http-dispatcher.js'; |
| 62 | +import { installDefaultOrganization } from './default-organization.testkit.js'; |
| 63 | + |
| 64 | +const PREFIX = '/api/v1'; |
| 65 | +/** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ |
| 66 | +const TEST_PACKAGE_ID = 'objectstack-test'; |
| 67 | +const OBJECT = 'drift_line_26031'; |
| 68 | + |
| 69 | +/** The metadata the table was built from: `legacy_code` is a NOT NULL column. */ |
| 70 | +const BUILT = { |
| 71 | + name: OBJECT, |
| 72 | + label: 'Drift line', |
| 73 | + fields: { |
| 74 | + id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, |
| 75 | + name: { name: 'name', type: 'text' as const, label: 'Name' }, |
| 76 | + legacy_code: { name: 'legacy_code', type: 'text' as const, label: 'Legacy code', storage: { notNull: true } }, |
| 77 | + }, |
| 78 | + actions: [ |
| 79 | + { name: 'add_line', label: 'Add line', type: 'script', target: 'add_line' }, |
| 80 | + ], |
| 81 | +}; |
| 82 | + |
| 83 | +/** The metadata the doors serve afterwards: `legacy_code` is no longer declared. */ |
| 84 | +const SERVED = (() => { |
| 85 | + const { legacy_code: _dropped, ...fields } = BUILT.fields; |
| 86 | + return { ...BUILT, fields }; |
| 87 | +})(); |
| 88 | + |
| 89 | +const MEMBER = { userId: 'u_member', isSystem: false }; |
| 90 | + |
| 91 | +let engine: ObjectQL; |
| 92 | +let dispatcher: HttpDispatcher; |
| 93 | +let rest: RestServer; |
| 94 | + |
| 95 | +afterAll(async () => { |
| 96 | + try { await engine?.destroy(); } catch { /* noop */ } |
| 97 | +}); |
| 98 | + |
| 99 | +beforeAll(async () => { |
| 100 | + engine = new ObjectQL(); |
| 101 | + engine.registerDriver(new SqlDriver({ |
| 102 | + client: 'better-sqlite3', |
| 103 | + connection: { filename: ':memory:' }, |
| 104 | + useNullAsDefault: true, |
| 105 | + }), true); |
| 106 | + await engine.init(); |
| 107 | + engine.registry.registerObject(BUILT as any, TEST_PACKAGE_ID); |
| 108 | + await engine.syncSchemas(); |
| 109 | + // A real `single` install's Default Organization (ADR-0131 D9). |
| 110 | + await installDefaultOrganization(engine); |
| 111 | + await engine.insert(OBJECT, { id: 'e1', name: 'existing', legacy_code: 'L1' } as any); |
| 112 | + engine.registry.registerObject(SERVED as any, TEST_PACKAGE_ID); |
| 113 | + (engine as any).registerAction(OBJECT, 'add_line', async (ctx: any) => { |
| 114 | + await ctx.engine.insert(OBJECT, { id: 'a1', name: 'from the action' }); |
| 115 | + return { written: true }; |
| 116 | + }); |
| 117 | + |
| 118 | + const protocol = new ObjectStackProtocolImplementation(engine as any); |
| 119 | + const services: Record<string, unknown> = { objectql: engine, data: engine, protocol }; |
| 120 | + const get = (n: string) => services[n] ?? null; |
| 121 | + const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; |
| 122 | + dispatcher = new HttpDispatcher(kernel); |
| 123 | + (dispatcher as any).timedResolveExecutionContext = async () => ({ ...MEMBER }); |
| 124 | + |
| 125 | + const noop = () => {}; |
| 126 | + const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; |
| 127 | + rest = new RestServer(server as any, protocol as any, { api: { requireAuth: false } } as any); |
| 128 | + (rest as any).resolveExecCtx = async () => ({ userId: MEMBER.userId }); |
| 129 | + rest.registerRoutes(); |
| 130 | +}, 60_000); |
| 131 | + |
| 132 | +/** |
| 133 | + * A request as `@objectstack/hono`'s catch-all hands it to `dispatch()`: the |
| 134 | + * answer `dispatch()` returned, or, for a throw, what the Hono exit makes of it |
| 135 | + * (`undefined` there is its bare `500`). |
| 136 | + */ |
| 137 | +async function door(method: string, path: string, body: unknown) { |
| 138 | + const request = new Request(`http://localhost${PREFIX}${path}`, { |
| 139 | + method, |
| 140 | + headers: { 'content-type': 'application/json' }, |
| 141 | + body: JSON.stringify(body), |
| 142 | + }); |
| 143 | + try { |
| 144 | + const res: any = await dispatcher.dispatch(method, path, body, {}, { request } as any, PREFIX); |
| 145 | + return { returned: res?.response as { status: number; body: any } | undefined }; |
| 146 | + } catch (thrown) { |
| 147 | + return { thrown, hono: declaredEnvelopeForThrow(thrown) }; |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +/** A `RestServer` route, called as its host calls it. */ |
| 152 | +async function restDoor(method: string, path: string, body: unknown, params: Record<string, string>) { |
| 153 | + const route = rest.getRoutes().find((r: any) => r.method === method && r.path === path); |
| 154 | + expect(route, `${method} ${path}`).toBeDefined(); |
| 155 | + const res: any = { |
| 156 | + write: () => true, end: () => {}, |
| 157 | + header: () => res, |
| 158 | + status: (code: number) => { res._status = code; return res; }, |
| 159 | + json: (json: any) => { res._json = json; return res; }, |
| 160 | + }; |
| 161 | + await route!.handler({ params, body, query: {}, headers: {} } as any, res); |
| 162 | + return { status: res._status ?? 200, body: res._json }; |
| 163 | +} |
| 164 | + |
| 165 | +/** `RestServer`'s answer for the drifted column, asserted whole. */ |
| 166 | +async function restAnswer() { |
| 167 | + const answer = await restDoor('POST', `${PREFIX}/data/:object`, { id: 'r1', name: 'through rest' }, { object: OBJECT }); |
| 168 | + expect(answer.status, JSON.stringify(answer.body)).toBe(400); |
| 169 | + expect(answer.body).toEqual({ |
| 170 | + error: 'legacy_code is required', |
| 171 | + code: 'VALIDATION_FAILED', |
| 172 | + fields: [{ field: 'legacy_code', code: 'required', message: 'legacy_code is required' }], |
| 173 | + hint: expect.any(String), |
| 174 | + object: OBJECT, |
| 175 | + }); |
| 176 | + return answer.body as Record<string, unknown>; |
| 177 | +} |
| 178 | + |
| 179 | +/** The dispatcher envelope carrying `RestServer`'s body: the sentence, the code, the rest in `details`. */ |
| 180 | +function dispatcherEnvelopeOf(restBody: Record<string, unknown>) { |
| 181 | + const { error: message, code, ...details } = restBody; |
| 182 | + return { success: false, error: { code, message, httpStatus: 400, details } }; |
| 183 | +} |
| 184 | + |
| 185 | +function expectNoDriverText(body: unknown) { |
| 186 | + expect(JSON.stringify(body)).not.toMatch(/constraint failed|SQLITE_|insert into/); |
| 187 | +} |
| 188 | + |
| 189 | +const rowCount = async (id: string) => (await engine.find(OBJECT, { where: { id } })).length; |
| 190 | + |
| 191 | +describe('[#26031] a NOT NULL refusal on a drifted column answers RestServer\'s body on every door', () => { |
| 192 | + it('`RestServer` `POST /data/:object`: the arm\'s body, the reference', async () => { |
| 193 | + const body = await restAnswer(); |
| 194 | + expectNoDriverText(body); |
| 195 | + expect(await rowCount('r1')).toBe(0); |
| 196 | + }); |
| 197 | + |
| 198 | + it('the dispatcher `POST /data/:object`: the same body, returned, not a thrown 500', async () => { |
| 199 | + const reference = await restAnswer(); |
| 200 | + const answer = await door('POST', `/data/${OBJECT}`, { id: 'n1', name: 'through the dispatcher' }); |
| 201 | + expect(answer, JSON.stringify(answer)).toEqual({ |
| 202 | + returned: { status: 400, body: dispatcherEnvelopeOf(reference) }, |
| 203 | + }); |
| 204 | + expectNoDriverText(answer); |
| 205 | + expect(await rowCount('n1')).toBe(0); |
| 206 | + }); |
| 207 | + |
| 208 | + it('`POST /actions/:object/:action`, a handler whose insert leaves the column out: the same body', async () => { |
| 209 | + const reference = await restAnswer(); |
| 210 | + const answer = await door('POST', `/actions/${OBJECT}/add_line/e1`, {}); |
| 211 | + expect(answer, JSON.stringify(answer)).toEqual({ |
| 212 | + returned: { status: 400, body: dispatcherEnvelopeOf(reference) }, |
| 213 | + }); |
| 214 | + expectNoDriverText(answer); |
| 215 | + expect(await rowCount('a1')).toBe(0); |
| 216 | + }); |
| 217 | + |
| 218 | + it('the control: a `PATCH` naming the dropped field is refused before the driver, alike on both `/data` doors', async () => { |
| 219 | + const viaRest = await restDoor('PATCH', `${PREFIX}/data/:object/:id`, { legacy_code: null }, { object: OBJECT, id: 'e1' }); |
| 220 | + expect(viaRest).toEqual({ |
| 221 | + status: 400, |
| 222 | + body: { error: `Unknown field 'legacy_code' on object '${OBJECT}'`, code: 'INVALID_FIELD', field: 'legacy_code', object: OBJECT }, |
| 223 | + }); |
| 224 | + const viaDispatcher = await door('PATCH', `/data/${OBJECT}/e1`, { legacy_code: null }); |
| 225 | + expect((viaDispatcher as { hono?: unknown }).hono).toEqual({ |
| 226 | + status: 400, |
| 227 | + body: { |
| 228 | + success: false, |
| 229 | + error: { |
| 230 | + code: 'INVALID_FIELD', |
| 231 | + message: `Unknown field 'legacy_code' on object '${OBJECT}'`, |
| 232 | + details: { field: 'legacy_code', object: OBJECT }, |
| 233 | + }, |
| 234 | + }, |
| 235 | + }); |
| 236 | + const stored = await engine.findOne(OBJECT, { where: { id: 'e1' } }) as any; |
| 237 | + expect(stored?.name).toBe('existing'); |
| 238 | + }); |
| 239 | +}); |
0 commit comments