|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #34579 — a record hook refuses the step AFTER an approval decision. |
| 5 | + * |
| 6 | + * ## The reported case |
| 7 | + * |
| 8 | + * A special-approval flow parks at an `approval` node; on `approve` an |
| 9 | + * `update_record` moves the plan to `approved`. The plan's `beforeUpdate` hook |
| 10 | + * re-checks capacity and refuses with a declared refusal. The approver's |
| 11 | + * `POST …/approve` then answered `500 RESUME_FAILED`, the decision stood, the |
| 12 | + * run stranded, and the approver could not read WHY: the engine reported the |
| 13 | + * refusal (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on |
| 14 | + * #24914), and the approvals door dropped it before building the envelope. |
| 15 | + * |
| 16 | + * ## What is pinned, within the rulings on file |
| 17 | + * |
| 18 | + * ⛔ The status code does not move and the decision is not rolled back or made |
| 19 | + * atomic: #13807 B keeps the 500 and the #13937 shape-4 ruling excludes undoing |
| 20 | + * a human decision. So the card is pinned on its fallback route: |
| 21 | + * |
| 22 | + * 1. NO fault edge: the `RESUME_FAILED` envelope carries the refusal the step |
| 23 | + * met — `innerRefusal` in the engine's own shape and the hook's marked |
| 24 | + * `userMessage` — beside the four #13807 facts, which are unchanged. |
| 25 | + * 2. A declared FAULT edge on that step: the hook refusal is routed down it, |
| 26 | + * like any run-time failure (`dag-traversal.ts`; only guard refusals are |
| 27 | + * not routed). The decision answers normally, `resumed: true`, and the run |
| 28 | + * completes through the author's handler. A flow author can bounce the |
| 29 | + * record back without an administrator. |
| 30 | + * 3. Reverse control: a step that FAULTS (a throw that declares no HTTP |
| 31 | + * answer) met no refusal, so the envelope carries neither member — nothing |
| 32 | + * is synthesised from the prose. |
| 33 | + */ |
| 34 | + |
| 35 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 36 | +import { AutomationEngine, InMemorySuspendedRunStore, registerCrudNodes } from '@objectstack/service-automation'; |
| 37 | +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; |
| 38 | +import { strandedDecisionDetails } from '@objectstack/types'; |
| 39 | +import { ApprovalService } from './approval-service.js'; |
| 40 | +import { registerApprovalNode } from './approval-node.js'; |
| 41 | + |
| 42 | +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as any; |
| 43 | +const noopLogger: any = { info() {}, warn() {}, error() {}, debug() {} }; |
| 44 | +noopLogger.child = () => noopLogger; |
| 45 | + |
| 46 | +/** The hook's declared sentence, in the caller's locale — what the approver should read. */ |
| 47 | +const HOOK_USER_TEXT = '产能已被其他订单占用,该方案无法按当前产能通过。'; |
| 48 | + |
| 49 | +/** |
| 50 | + * A declared hook refusal as the runtime answers one |
| 51 | + * (`resolveHookRefusal`, `runtime/src/sandbox/hook-refusal-catalogue.ts`): |
| 52 | + * the diagnostic message names the hook, the declared code and status ride |
| 53 | + * the error, and the declared sentence is both the caller-facing message and |
| 54 | + * the marked `userMessage`. |
| 55 | + */ |
| 56 | +const hookRefusal = () => Object.assign( |
| 57 | + new Error("hook 'alloc_plan_capacity_recheck' threw: Error: over_capacity"), |
| 58 | + { name: 'SandboxError', innerMessage: HOOK_USER_TEXT, code: 'VALIDATION_FAILED', status: 400, userMessage: HOOK_USER_TEXT }, |
| 59 | +); |
| 60 | + |
| 61 | +/** In-memory ObjectQL stand-in: approvals tables plus the plan the flow writes. */ |
| 62 | +function makeFakeEngine(refuseUpdateOf: string, refusal: () => unknown) { |
| 63 | + const tables = new Map<string, any[]>(); |
| 64 | + const rows = (o: string) => (tables.get(o) ?? (tables.set(o, []), tables.get(o)!)); |
| 65 | + const matches = (row: any, where: any) => Object.entries(where ?? {}).every(([k, v]) => { |
| 66 | + if (k.startsWith('$')) throw new Error(`fake engine: unsupported filter operator ${k}`); |
| 67 | + if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]); |
| 68 | + if (v && typeof v === 'object' && '$ne' in (v as any)) return row[k] !== (v as any).$ne; |
| 69 | + return row[k] === v; |
| 70 | + }); |
| 71 | + return { |
| 72 | + tables, |
| 73 | + async find(object: string, opts: any = {}) { |
| 74 | + const where = opts.where ?? opts.filter ?? {}; |
| 75 | + const out = rows(object).filter(r => matches(r, where)); |
| 76 | + const start = opts.offset ?? 0; |
| 77 | + const page = typeof opts.limit === 'number' ? out.slice(start, start + opts.limit) : out.slice(start); |
| 78 | + return page.map(r => ({ ...r })); |
| 79 | + }, |
| 80 | + async insert(object: string, data: any) { rows(object).push({ ...data }); return { ...data }; }, |
| 81 | + async update(object: string, data: any, options?: any) { |
| 82 | + const dispatch = assertEngineUpdateDispatch(data, options); |
| 83 | + // The record hook: accepts the call the way ObjectQL does, then refuses. |
| 84 | + if (object === refuseUpdateOf) throw refusal(); |
| 85 | + const table = rows(object); |
| 86 | + if (dispatch.kind === 'multi') { |
| 87 | + let n = 0; |
| 88 | + for (let i = 0; i < table.length; i++) { |
| 89 | + if (matches(table[i], options?.where)) { table[i] = { ...table[i], ...data }; n++; } |
| 90 | + } |
| 91 | + return { updated: n }; |
| 92 | + } |
| 93 | + const i = table.findIndex(r => r.id === dispatch.id); |
| 94 | + if (i >= 0) table[i] = { ...table[i], ...data }; |
| 95 | + return i >= 0 ? { ...table[i] } : null; |
| 96 | + }, |
| 97 | + async delete(object: string, options?: any) { |
| 98 | + const dispatch = assertEngineDeleteDispatch(options); |
| 99 | + const table = rows(object); |
| 100 | + const i = table.findIndex(r => r.id === (dispatch as any).id); |
| 101 | + if (i >= 0) table.splice(i, 1); |
| 102 | + return { id: (dispatch as any).id }; |
| 103 | + }, |
| 104 | + }; |
| 105 | +} |
| 106 | + |
| 107 | +/** start → approval → (approve) adopt the plan → end; (reject) → end. */ |
| 108 | +function specialApprovalFlow(withFaultEdge: boolean) { |
| 109 | + return { |
| 110 | + name: 'plan_special_approval', |
| 111 | + label: 'Plan Special Approval', |
| 112 | + type: 'autolaunched', |
| 113 | + nodes: [ |
| 114 | + { id: 'start', type: 'start', label: 'Start' }, |
| 115 | + { |
| 116 | + id: 'director', type: 'approval', label: 'Director Approval', |
| 117 | + config: { approvers: [{ type: 'user', value: 'director' }] }, |
| 118 | + }, |
| 119 | + { |
| 120 | + id: 'adopt_plan', type: 'update_record', label: 'Adopt Plan', |
| 121 | + config: { objectName: 'alloc_plan', filter: { id: 'p1' }, fields: { status: 'approved' } }, |
| 122 | + }, |
| 123 | + { id: 'bounce_back', type: 'mark', label: 'Bounce back to the rep' }, |
| 124 | + { id: 'end', type: 'end', label: 'End' }, |
| 125 | + ], |
| 126 | + edges: [ |
| 127 | + { id: 'e1', source: 'start', target: 'director' }, |
| 128 | + { id: 'e2', source: 'director', target: 'adopt_plan', label: 'approve' }, |
| 129 | + { id: 'e3', source: 'director', target: 'end', label: 'reject' }, |
| 130 | + { id: 'e4', source: 'adopt_plan', target: 'end' }, |
| 131 | + ...(withFaultEdge |
| 132 | + ? [ |
| 133 | + { id: 'ef', source: 'adopt_plan', target: 'bounce_back', type: 'fault' }, |
| 134 | + { id: 'e5', source: 'bounce_back', target: 'end' }, |
| 135 | + ] |
| 136 | + : []), |
| 137 | + ], |
| 138 | + }; |
| 139 | +} |
| 140 | + |
| 141 | +describe('#34579 — a hook refusal on the step after an approval decision', () => { |
| 142 | + let marks: string[]; |
| 143 | + |
| 144 | + beforeEach(() => { marks = []; }); |
| 145 | + |
| 146 | + /** One live process: real engine, real CRUD + approval nodes, real approvals service. */ |
| 147 | + function boot(opts: { withFaultEdge: boolean; refusal?: () => unknown }) { |
| 148 | + const data = makeFakeEngine('alloc_plan', opts.refusal ?? hookRefusal); |
| 149 | + data.tables.set('alloc_plan', [{ id: 'p1', status: 'submitted' }]); |
| 150 | + const service = new ApprovalService({ engine: data as any, logger: noopLogger }); |
| 151 | + const automation = new AutomationEngine(noopLogger, new InMemorySuspendedRunStore()); |
| 152 | + registerCrudNodes(automation, { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as any); |
| 153 | + registerApprovalNode(automation, service, noopLogger); |
| 154 | + automation.registerNodeExecutor({ |
| 155 | + type: 'mark', |
| 156 | + async execute(node: any) { marks.push(node.id); return { success: true }; }, |
| 157 | + } as never); |
| 158 | + automation.registerFlow('plan_special_approval', specialApprovalFlow(opts.withFaultEdge) as never); |
| 159 | + service.attachAutomation(automation); |
| 160 | + return { data, service, automation }; |
| 161 | + } |
| 162 | + |
| 163 | + async function park(env: ReturnType<typeof boot>) { |
| 164 | + const started = await env.automation.execute('plan_special_approval', { |
| 165 | + object: 'alloc_plan', record: { id: 'p1', status: 'submitted' }, userId: 'rep', |
| 166 | + } as never); |
| 167 | + expect(started.status, 'the run must park at the approval node').toBe('paused'); |
| 168 | + const req = (await env.data.find('sys_approval_request', { where: { status: 'pending' } }))[0]; |
| 169 | + expect(req?.flow_run_id, 'the request must name the run it gates').toBeTruthy(); |
| 170 | + return req; |
| 171 | + } |
| 172 | + |
| 173 | + it('NO fault edge: still 500 RESUME_FAILED, and the envelope now carries the refusal the step met', async () => { |
| 174 | + const env = boot({ withFaultEdge: false }); |
| 175 | + const req = await park(env); |
| 176 | + const runId = req.flow_run_id; |
| 177 | + |
| 178 | + const err = await env.service |
| 179 | + .decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX) |
| 180 | + .then(() => null, (e: Error) => e); |
| 181 | + |
| 182 | + // #13807 B, unchanged: the door still throws, and the prose still names the run. |
| 183 | + expect(err, '⛔ not "return 200" — the status code does not move').toBeTruthy(); |
| 184 | + expect(err?.message).toMatch(/^RESUME_FAILED: the approve decision was recorded on request /); |
| 185 | + expect(err?.message).toMatch(/could not be resumed and is now stranded/); |
| 186 | + |
| 187 | + // The decision is durable and the plan did not move: the reported state. |
| 188 | + const row = (await env.data.find('sys_approval_request', { where: { id: req.id } }))[0]; |
| 189 | + expect(row.status).toBe('approved'); |
| 190 | + expect((await env.data.find('alloc_plan', { where: { id: 'p1' } }))[0].status).toBe('submitted'); |
| 191 | + |
| 192 | + // ⭐ The card's deliverable: the refusal, structured, beside the four facts. |
| 193 | + expect(strandedDecisionDetails(err)).toEqual({ |
| 194 | + finalized: true, |
| 195 | + decision: 'approve', |
| 196 | + runId, |
| 197 | + repairable: true, |
| 198 | + innerRefusal: { code: 'VALIDATION_FAILED', message: hookRefusal().message }, |
| 199 | + userMessage: HOOK_USER_TEXT, |
| 200 | + }); |
| 201 | + }); |
| 202 | + |
| 203 | + it('a declared FAULT edge on that step routes the hook refusal to the handler — the decision answers normally and the run does not strand', async () => { |
| 204 | + const env = boot({ withFaultEdge: true }); |
| 205 | + const req = await park(env); |
| 206 | + const runId = req.flow_run_id; |
| 207 | + |
| 208 | + const out = await env.service.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX); |
| 209 | + |
| 210 | + expect(out.finalized).toBe(true); |
| 211 | + expect(out.decision).toBe('approve'); |
| 212 | + expect(out.resumed, 'the run advanced through the fault edge').toBe(true); |
| 213 | + expect(out.resumeError).toBeUndefined(); |
| 214 | + expect(marks, "the author's handler ran").toEqual(['bounce_back']); |
| 215 | + // Nothing left parked and nothing to repair: the run ended. |
| 216 | + expect(await env.automation.hasSuspendedRun(runId)).toBe(false); |
| 217 | + expect(strandedDecisionDetails(out as unknown)).toBeUndefined(); |
| 218 | + }); |
| 219 | + |
| 220 | + it('reverse control: a step that FAULTS met no refusal — the envelope carries neither member', async () => { |
| 221 | + const env = boot({ withFaultEdge: false, refusal: () => new Error('ECONNREFUSED: could not reach the store') }); |
| 222 | + const req = await park(env); |
| 223 | + |
| 224 | + const err = await env.service |
| 225 | + .decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX) |
| 226 | + .then(() => null, (e: Error) => e); |
| 227 | + |
| 228 | + const details = strandedDecisionDetails(err); |
| 229 | + expect(details).toEqual({ finalized: true, decision: 'approve', runId: req.flow_run_id, repairable: true }); |
| 230 | + expect(details && 'innerRefusal' in details).toBe(false); |
| 231 | + expect(details && 'userMessage' in details).toBe(false); |
| 232 | + }); |
| 233 | +}); |
0 commit comments