techtools
Головна / proto / flow-old / test / postgres.test.ts

postgres.test.ts

TypeScript · 202 рядків

1// Ядро на PostgreSQL (R-12 §11, етап 1): транзакція на подію, дублікати, черга accepted-подій, FIRE_EVENT,
2// довговічний DELAY, лічильник циклів (R-12.21), чернетка → публікація, продовження legacy-очікувань через /api/events.
3import test, { after, before } from 'node:test'
4import assert from 'node:assert/strict'
5import { edge, node, publishWorkflow, reopen, testServer } from './helpers.ts'
6
7let t: Awaited<ReturnType<typeof testServer>>
8before(async () => { t = await testServer('core') })
9after(async () => { await t?.stop() })
10
11/** Задача з обробником: подія SCAN → ACTION → TASK_UPDATE → CLIENT_RESPONSE. */
12async function taskHandler() {
13  return publishWorkflow(t.call, {
14    name: 'UNLOAD',
15    nodes: [
16      node('scan', 'EVENT', { event: 'SCAN', activation: 'TASK', modelId: 'demo-warehouse-event', conditions: ['task.type == "UNLOAD"'] }, ['next'], []),
17      node('mark', 'ACTION', { set: { processed: true } }),
18      node('update', 'TASK_UPDATE', { taskModelId: 'system-task', state: 'scanned', progress: 'scanned', complete: false }, ['next', 'task'], ['data', 'task']),
19      node('reply', 'CLIENT_RESPONSE', { status: 200, mapping: { taskId: 'task.id', state: 'task.state' } }, []),
20    ],
21    edges: [edge('scan', 'next', 'mark'), edge('mark', 'next', 'update', 'data'), edge('update', 'next', 'reply')],
22  })
23}
24
25async function createTask(handler: any, entityId: string) {
26  return publishWorkflow(t.call, {
27    name: `CREATE ${entityId}`,
28    nodes: [
29      node('order', 'EVENT', { event: `ORDER_${entityId}`, activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []),
30      node('task', 'TASK', {
31        taskModelId: 'system-task', assigneeType: 'group', assignee: 'worker', taskType: 'UNLOAD', entityType: 'item', entityIdPath: 'data.entityId',
32        handlerWorkflowId: handler.id, state: 'created', title: 'Unload {{data.entityId}}', description: '', priority: 'normal', progress: 'waiting', payloadMapping: { $copy: 'data' },
33      }, ['next', 'task'], ['data']),
34    ],
35    edges: [edge('order', 'next', 'task', 'data')],
36  })
37}
38
39test('task event: one transaction, response, idempotent eventId, concurrent duplicates run once', async () => {
40  const handler = await taskHandler()
41  await createTask(handler, 'P1')
42  assert.equal((await t.call('POST', '/api/events?responseMode=sync', { eventId: 'o1', event: 'ORDER_P1', entityType: 'order', entityId: 'P1' })).status, 204)
43  const [task] = (await t.sql.query("SELECT data FROM workflow_tasks WHERE entity_id = 'P1'")).map((r) => r.data)
44  assert.equal(task.handlerWorkflowVersion, 1)
45
46  const body = { eventId: 'scan-1', event: 'SCAN', entityType: 'item', entityId: 'P1' }
47  const first = await t.call('POST', '/api/events?responseMode=sync', body)
48  assert.deepEqual(first, { status: 200, body: { taskId: task.id, state: 'scanned' } })
49  const again = await t.call('POST', '/api/events?responseMode=sync', body)
50  assert.deepEqual(again.body, first.body)
51
52  const parallel = await Promise.all([...Array(6)].map(() => t.call('POST', '/api/events?responseMode=sync', { ...body, eventId: 'scan-2' })))
53  assert.ok(parallel.every((r) => r.status === 200))
54  const runs = await t.sql.query("SELECT count(*)::int AS n FROM workflow_executions WHERE data->>'eventId' = 'scan-2'")
55  assert.equal(runs[0].n, 1)
56  const [{ data }] = await t.sql.query('SELECT data FROM workflow_tasks WHERE id = :id', { id: task.id })
57  assert.equal(data.context.processed, true)
58  assert.equal(data.version, 3)
59})
60
61test('async events and FIRE_EVENT are durable: accepted rows survive a restart and are processed by the dispatcher', async () => {
62  const target = await publishWorkflow(t.call, {
63    name: 'TARGET',
64    nodes: [node('ready', 'EVENT', { event: 'READY', activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []), node('done', 'ACTION', { set: { reached: true } }, [])],
65    edges: [edge('ready', 'next', 'done')],
66  })
67  await publishWorkflow(t.call, {
68    name: 'SOURCE',
69    nodes: [
70      node('go', 'EVENT', { event: 'GO', activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []),
71      node('fire', 'FIRE_EVENT', { event: 'READY', entityType: 'warehouse_item', entityId: 'data.entityId', userId: 7, payloadMapping: { $copy: 'data' } }),
72      node('after', 'ACTION', { set: { continued: true } }, []),
73    ],
74    edges: [edge('go', 'next', 'fire'), edge('fire', 'next', 'after')],
75  })
76  const accepted = await t.call('POST', '/api/events', { eventId: 'go-1', event: 'GO', entityId: 'X1' })
77  assert.deepEqual(accepted.body, { eventId: 'go-1', status: 'accepted', duplicate: false })
78
79  // сервер «падає» до обробки; новий процес дообробляє чергу
80  await t.stop()
81  const second = await reopen('core', { dispatch: true })
82  try {
83    for (let i = 0; i < 100; i++) {
84      const rows = await second.db.sql().query("SELECT count(*)::int AS n FROM inbox_events WHERE status = 'accepted'")
85      if (!rows[0].n) break
86      await new Promise((r) => setTimeout(r, 50))
87    }
88    await second.dispatcher.idle()
89    const reached = await second.db.sql().query("SELECT data FROM workflow_executions WHERE workflow_id = :id", { id: target.id })
90    assert.equal(reached.length, 1)
91    assert.equal(reached[0].data.context.reached, true)
92    const statuses = await second.db.sql().query("SELECT status, count(*)::int AS n FROM inbox_events WHERE event IN ('GO', 'READY') GROUP BY 1")
93    assert.deepEqual(statuses, [{ status: 'processed', n: 2 }])
94  } finally {
95    await second.stop()
96    t = await testServer('core-2')
97  }
98})
99
100test('DELAY waits durably on a timer instead of sleeping in the process', async () => {
101  const workflow = await publishWorkflow(t.call, {
102    name: 'DELAYED',
103    nodes: [node('start', 'EVENT', { event: 'WAIT_A_BIT', activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []), node('delay', 'DELAY', { seconds: 3600 }), node('done', 'ACTION', { set: { done: true } }, [])],
104    edges: [edge('start', 'next', 'delay'), edge('delay', 'next', 'done')],
105  })
106  const started = Date.now()
107  const execution = (await t.call('POST', `/api/workflows/${workflow.id}/execute`, { event: 'WAIT_A_BIT', entityId: 'D1' })).body
108  assert.ok(Date.now() - started < 2000)
109  assert.equal(execution.status, 'waiting')
110  assert.equal(execution.waitingFor, '$timer')
111  assert.equal(await t.flow.fireTimer(new Date().toISOString()), false)
112  assert.equal(await t.flow.fireTimer(new Date(Date.now() + 3601_000).toISOString()), true)
113  const resumed = (await t.call('GET', `/api/executions/${execution.id}`)).body
114  assert.equal(resumed.status, 'completed')
115  assert.equal(resumed.context.done, true)
116})
117
118test('loops are allowed (warning), but a runaway pass stops with LOOP_LIMIT, rolls back and notifies', async () => {
119  const definition = {
120    name: 'LOOPING',
121    settings: { loopLimits: { steps: 50, nodeVisits: 10 } },
122    nodes: [
123      node('start', 'EVENT', { event: 'SPIN', activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []),
124      node('tick', 'ACTION', { set: { spinning: true } }),
125      node('check', 'CONDITION', { routes: { again: 'data.event == "SPIN"', stop: '' } }, ['again', 'stop']),
126      node('end', 'ACTION', { set: { stopped: true } }, []),
127    ],
128    edges: [edge('start', 'next', 'tick'), edge('tick', 'next', 'check'), edge('check', 'again', 'tick'), edge('check', 'stop', 'end')],
129  }
130  const saved = (await t.call('POST', '/api/workflows', definition)).body
131  const warnings = saved.validation.issues.filter((i) => i.severity === 'warning')
132  assert.ok(warnings.length >= 1, JSON.stringify(saved.validation))
133  assert.equal(saved.validation.issues.filter((i) => i.severity !== 'warning').length, 0)
134  assert.equal((await t.call('POST', `/api/workflows/${saved.id}/publish`)).status, 200)
135
136  const result = await t.call('POST', '/api/events?responseMode=sync', { eventId: 'spin-1', event: 'SPIN', entityId: 'L1' })
137  assert.equal(result.status, 409)
138  assert.equal(result.body.code, 'LOOP_LIMIT')
139  assert.equal((await t.sql.query('SELECT count(*)::int AS n FROM workflow_executions WHERE workflow_id = :id', { id: saved.id }))[0].n, 0)
140  const [inbox] = await t.sql.query("SELECT status, result FROM inbox_events WHERE event_id = 'spin-1'")
141  assert.equal(inbox.status, 'failed')
142  assert.equal(inbox.result.code, 'LOOP_LIMIT')
143  const [note] = (await t.call('GET', `/api/notifications?workflowId=${saved.id}`)).body
144  assert.equal(note.kind, 'LOOP_LIMIT')
145  assert.deepEqual(note.details.loopNodes.map((n) => n.nodeId).sort(), ['check', 'tick'])
146  assert.equal(note.details.limits.nodeVisits, 10)
147})
148
149test('drafts do not affect running processes until published; publishing with errors is blocked', async () => {
150  const workflow = await publishWorkflow(t.call, {
151    name: 'VERSIONED',
152    nodes: [node('start', 'EVENT', { event: 'VERSIONED', activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []), node('mark', 'ACTION', { set: { label: 'v1' } }, [])],
153    edges: [edge('start', 'next', 'mark')],
154  })
155  const draft = structuredClone(workflow)
156  draft.nodes[1].config.set.label = 'v2'
157  draft.nodes.push(node('broken', 'MAPPING', { mapping: { x: 'data.missing.field' } }, ['next']))
158  draft.edges.push(edge('mark', 'next', 'broken'))
159  const saved = (await t.call('PUT', `/api/workflows/${workflow.id}`, draft)).body
160  assert.equal(saved.hasDraft, true)
161  assert.ok(saved.validation.issues.length > 0)
162  assert.equal((await t.call('POST', `/api/workflows/${workflow.id}/publish`)).status, 422)
163
164  const run = (await t.call('POST', `/api/workflows/${workflow.id}/execute`, { event: 'VERSIONED', entityId: 'V1' })).body
165  assert.equal(run.context.label, 'v1')
166  assert.equal(run.workflowVersion, 1)
167
168  draft.nodes = draft.nodes.filter((n) => n.id !== 'broken')
169  draft.edges = draft.edges.filter((e) => e.target !== 'broken')
170  await t.call('PUT', `/api/workflows/${workflow.id}`, draft)
171  assert.equal((await t.call('POST', `/api/workflows/${workflow.id}/publish`)).body.version, 2)
172  assert.equal((await t.call('POST', `/api/workflows/${workflow.id}/execute`, { event: 'VERSIONED', entityId: 'V2' })).body.context.label, 'v2')
173})
174
175test('legacy waiting executions resume from /api/events (demo putaway simulator)', async () => {
176  const started = (await t.call('POST', '/api/workflows/demo-putaway/execute', { event: 'ITEM_SCANNED', entityType: 'warehouse_item', entityId: 'W1', product: { id: 1 }, warehouse: { id: 1 } })).body
177  assert.equal(started.status, 'waiting')
178  assert.equal(started.waitingFor, 'ITEM_IN_CART')
179  await t.call('POST', '/api/events?responseMode=sync', { event: 'ITEM_IN_CART', entityId: 'W1' })
180  assert.equal((await t.call('GET', `/api/executions/${started.id}`)).body.waitingFor, 'LOCATION_SCANNED')
181  await t.call('POST', '/api/events?responseMode=sync', { event: 'LOCATION_SCANNED', entityId: 'W1', locationId: 100 })
182  await t.call('POST', '/api/events?responseMode=sync', { event: 'LOCATION_SCANNED', entityId: 'W1', locationId: 8812 })
183  const done = (await t.call('GET', `/api/executions/${started.id}`)).body
184  assert.equal(done.status, 'completed')
185  assert.equal(done.context.putaway.completed, true)
186})
187
188test('CONDITION routes keep their order after storage (json, not jsonb)', async () => {
189  const workflow = await publishWorkflow(t.call, {
190    name: 'ORDERED',
191    nodes: [
192      node('start', 'EVENT', { event: 'ORDERED', activation: 'START', modelId: 'demo-warehouse-event' }, ['next'], []),
193      node('route', 'CONDITION', { routes: { firstMatch: 'data.event == "ORDERED"', b: 'data.event == "ORDERED"', other: '' } }, ['firstMatch', 'b', 'other']),
194      node('one', 'ACTION', { set: { picked: 'firstMatch' } }, []),
195      node('two', 'ACTION', { set: { picked: 'b' } }, []),
196    ],
197    edges: [edge('start', 'next', 'route'), edge('route', 'firstMatch', 'one'), edge('route', 'b', 'two')],
198  })
199  assert.deepEqual(Object.keys((await t.call('GET', `/api/workflows/${workflow.id}`)).body.nodes[1].config.routes), ['firstMatch', 'b', 'other'])
200  assert.equal((await t.call('POST', `/api/workflows/${workflow.id}/execute`, { event: 'ORDERED', entityId: 'R1' })).body.context.picked, 'firstMatch')
201})
202