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

task-routing.test.ts

TypeScript · 523 рядків

1// @ts-nocheck — тести перенесено з JS-версії без змін; типи фікстур не перевіряються
2import test from 'node:test'
3import assert from 'node:assert/strict'
4import { Engine } from '../server/engine.ts'
5import { demoModels } from '../server/demo.ts'
6import { validateWorkflowDataFlow } from '../server/data-flow.ts'
7
8function fixture() {
9  const data = {
10    workflows: [],
11    models: demoModels(),
12    executions: [],
13    logs: [],
14    tasks: [],
15    items: [],
16    entityEvents: [],
17    outbox: [],
18    inbox: []
19  }
20  const store = {
21    data,
22    workflow: id => data.workflows.find(workflow => workflow.id === id),
23    workflowVersion(id, version) {
24      const workflow = this.workflow(id)
25      if (!workflow) return null
26      if (!version || workflow.version === version) return workflow
27      return workflow.revisions?.find(revision => revision.version === version) || null
28    },
29    workflows: () => data.workflows,
30    model: id => data.models.find(model => model.id === id),
31    save() {},
32    push(collection, value) {
33      data[collection].push(value)
34      return value
35    }
36  }
37  return { data, engine: new Engine(store) }
38}
39
40function taskHandlerWorkflow() {
41  return {
42    id: 'workflow-unload',
43    name: 'UNLOAD',
44    version: 3,
45    nodes: [
46      {
47        id: 'scan-post1',
48        type: 'EVENT',
49        name: 'SCAN POST 1',
50        inputs: [],
51        outputs: [{ id: 'next', name: 'next' }],
52        config: {
53          event: 'SCAN_POST1',
54          activation: 'TASK',
55          modelId: 'demo-warehouse-event',
56          conditions: [
57            'task.type == "UNLOAD"',
58            'task.state == "created"',
59            'event.event == "SCAN_POST1"'
60          ]
61        }
62      },
63      {
64        id: 'mark-processed',
65        type: 'ACTION',
66        name: 'MARK PROCESSED',
67        inputs: [{ id: 'in', name: 'in' }],
68        outputs: [{ id: 'next', name: 'next' }],
69        config: { set: { processed: true } }
70      },
71      {
72        id: 'update-task',
73        type: 'TASK_UPDATE',
74        name: 'UPDATE TASK',
75        inputs: [
76          { id: 'data', name: 'data' },
77          { id: 'task', name: 'task' }
78        ],
79        outputs: [
80          { id: 'next', name: 'next' },
81          { id: 'task', name: 'task' }
82        ],
83        config: {
84          taskModelId: 'system-task',
85          state: 'post1_scanned',
86          progress: 'post 1 complete',
87          complete: false
88        }
89      },
90      {
91        id: 'response',
92        type: 'CLIENT_RESPONSE',
93        name: 'CLIENT RESPONSE',
94        inputs: [{ id: 'in', name: 'in' }],
95        outputs: [],
96        config: {
97          status: 200,
98          mapping: {
99            taskId: 'task.id',
100            state: 'task.state',
101            event: 'event.event'
102          }
103        }
104      }
105    ],
106    edges: [
107      {
108        source: 'scan-post1',
109        sourcePort: 'next',
110        target: 'mark-processed',
111        targetPort: 'in'
112      },
113      {
114        source: 'mark-processed',
115        sourcePort: 'next',
116        target: 'update-task',
117        targetPort: 'data'
118      },
119      {
120        source: 'update-task',
121        sourcePort: 'next',
122        target: 'response',
123        targetPort: 'in'
124      }
125    ]
126  }
127}
128
129function taskCreationWorkflow() {
130  return {
131    id: 'workflow-create-supply-tasks',
132    name: 'CREATE SUPPLY TASKS',
133    version: 1,
134    nodes: [
135      {
136        id: 'new-supply-order',
137        type: 'EVENT',
138        name: 'NEW SUPPLY ORDER',
139        inputs: [],
140        outputs: [{ id: 'next', name: 'next' }],
141        config: {
142          event: 'NEW_SUPPLY_ORDER',
143          activation: 'START',
144          modelId: 'supply-order-event'
145        }
146      },
147      {
148        id: 'create-unload-tasks',
149        type: 'TASK',
150        name: 'CREATE UNLOAD TASKS',
151        inputs: [{ id: 'data', name: 'data' }],
152        outputs: [
153          { id: 'next', name: 'next' },
154          { id: 'task', name: 'task' }
155        ],
156        config: {
157          taskModelId: 'system-task',
158          itemsPath: 'data.parts',
159          entityType: 'item',
160          entityIdPath: 'data.id',
161          orderId: 'data.orderId',
162          handlerWorkflowId: 'UNLOAD',
163          assigneeType: 'group',
164          assignee: 'warehouse_worker',
165          taskType: 'UNLOAD',
166          state: 'created',
167          title: 'Unload {{data.id}}',
168          description: 'Move {{data.id}} to {{data.targetShelfId}}',
169          priority: 'normal',
170          progress: 'waiting',
171          payloadMapping: { $copy: 'data' }
172        }
173      }
174    ],
175    edges: [
176      {
177        source: 'new-supply-order',
178        sourcePort: 'next',
179        target: 'create-unload-tasks',
180        targetPort: 'data'
181      }
182    ]
183  }
184}
185
186function activeTask() {
187  const now = new Date().toISOString()
188  return {
189    id: 'task-1',
190    executionId: 'creation-execution',
191    entityType: 'item',
192    entityId: '0000001',
193    parentTaskId: 'order-task-1',
194    orderId: 'order-1',
195    type: 'UNLOAD',
196    handlerWorkflowId: 'workflow-unload',
197    handlerWorkflowVersion: 3,
198    title: 'Unload part',
199    description: '',
200    priority: 'normal',
201    status: 'open',
202    state: 'created',
203    progress: 'waiting',
204    assignee: { type: 'group', id: 'warehouse_worker' },
205    context: { orderId: 'order-1', targetShelfId: 'shelf-22' },
206    payload: { orderId: 'order-1', targetShelfId: 'shelf-22' },
207    version: 1,
208    createdAt: now,
209    updatedAt: now,
210    completedAt: null
211  }
212}
213
214function supplyOrderEvent(parts) {
215  return {
216    event: 'NEW_SUPPLY_ORDER',
217    entityType: 'order',
218    entityId: 'order-1',
219    parts
220  }
221}
222
223function addSupplyOrderModels(data) {
224  data.models.push(
225    {
226      id: 'supply-part',
227      name: 'SupplyPart',
228      schema: {
229        id: 'string',
230        orderId: 'string',
231        targetShelfId: 'string'
232      }
233    },
234    {
235      id: 'supply-order-event',
236      name: 'SupplyOrderEvent',
237      schema: {
238        event: 'string',
239        entityId: 'string',
240        parts: 'SupplyPart[]'
241      }
242    }
243  )
244}
245
246test('task events route one active entity task without a waiting execution', async () => {
247  const { data, engine } = fixture()
248  const workflow = taskHandlerWorkflow()
249  data.workflows.push(workflow)
250  data.tasks.push(activeTask())
251
252  assert.deepEqual(validateWorkflowDataFlow(workflow, data.models, data.workflows), [])
253
254  const result = await engine.trigger({
255    eventId: 'scan-event-1',
256    event: 'SCAN_POST1',
257    entityType: 'item',
258    entityId: '0000001'
259  })
260
261  assert.equal(result.processed, 1)
262  assert.equal(result.executions[0].status, 'completed')
263  assert.equal(result.executions[0].waitingFor, null)
264  assert.equal(data.tasks[0].state, 'post1_scanned')
265  assert.equal(data.tasks[0].context.processed, true)
266  assert.equal(data.tasks[0].version, 2)
267  assert.deepEqual(result.response, {
268    status: 200,
269    body: {
270      taskId: 'task-1',
271      state: 'post1_scanned',
272      event: 'SCAN_POST1'
273    }
274  })
275})
276
277test('event IDs are idempotent and task conditions reject invalid later events', async () => {
278  const { data, engine } = fixture()
279  data.workflows.push(taskHandlerWorkflow())
280  data.tasks.push(activeTask())
281
282  const event = {
283    eventId: 'scan-event-1',
284    event: 'SCAN_POST1',
285    entityType: 'item',
286    entityId: '0000001'
287  }
288  const first = await engine.trigger(event)
289  const duplicate = await engine.trigger(event)
290  const rejected = await engine.trigger({ ...event, eventId: 'scan-event-2' })
291
292  assert.equal(first.processed, 1)
293  assert.equal(duplicate.duplicate, true)
294  assert.equal(data.executions.length, 1)
295  assert.equal(rejected.processed, 0)
296  assert.equal(rejected.code, 'EVENT_NOT_ALLOWED')
297})
298
299test('task event executes a task-less fallback flow with task false', async () => {
300  const { data, engine } = fixture()
301  data.workflows.push(taskHandlerWorkflow())
302  const fallbackWorkflow = {
303    id: 'workflow-no-task-fallback',
304    name: 'NO TASK FALLBACK',
305    version: 1,
306    nodes: [
307      {
308        id: 'scan-without-task',
309        type: 'EVENT',
310        name: 'SCAN WITHOUT TASK',
311        inputs: [],
312        outputs: [{ id: 'next', name: 'next' }],
313        config: {
314          event: 'SCAN_POST1',
315          activation: 'TASK',
316          modelId: 'demo-warehouse-event',
317          conditions: ['task == false']
318        }
319      },
320      {
321        id: 'mark-fallback',
322        type: 'ACTION',
323        name: 'MARK FALLBACK',
324        inputs: [{ id: 'in', name: 'in' }],
325        outputs: [],
326        config: { set: { fallback: true } }
327      }
328    ],
329    edges: [{
330      source: 'scan-without-task',
331      sourcePort: 'next',
332      target: 'mark-fallback',
333      targetPort: 'in'
334    }]
335  }
336  data.workflows.push(fallbackWorkflow)
337
338  assert.deepEqual(validateWorkflowDataFlow(fallbackWorkflow, data.models, data.workflows), [])
339
340  const result = await engine.trigger({
341    eventId: 'scan-without-task-1',
342    event: 'SCAN_POST1',
343    entityType: 'item',
344    entityId: 'missing-task-item'
345  })
346
347  assert.equal(result.code, 'PROCESSED')
348  assert.equal(result.processed, 1)
349  assert.equal(result.executions[0].invocationType, 'task_event')
350  assert.equal(result.executions[0].taskId, null)
351  assert.equal(result.executions[0].context.fallback, true)
352})
353test('one entity cannot receive a second active task', () => {
354  const { data, engine } = fixture()
355  const task = activeTask()
356  data.tasks.push(task)
357
358  assert.throws(
359    () => engine.createTask({ ...task, id: 'task-2' }),
360    error => error.code === 'ENTITY_ALREADY_HAS_ACTIVE_TASK'
361  )
362})
363
364test('batch TASK creates one pinned handler task per part without child executions', async () => {
365  const { data, engine } = fixture()
366  const creationWorkflow = taskCreationWorkflow()
367  const handlerWorkflow = taskHandlerWorkflow()
368  addSupplyOrderModels(data)
369  data.workflows.push(creationWorkflow, handlerWorkflow)
370
371  assert.deepEqual(
372    validateWorkflowDataFlow(creationWorkflow, data.models, data.workflows),
373    []
374  )
375
376  const execution = await engine.start(
377    creationWorkflow.id,
378    supplyOrderEvent([
379      { id: 'part-1', orderId: 'order-1', targetShelfId: 'shelf-11' },
380      { id: 'part-2', orderId: 'order-1', targetShelfId: 'shelf-22' }
381    ])
382  )
383
384  assert.equal(execution.status, 'completed')
385  assert.equal(data.executions.length, 1)
386  assert.equal(data.tasks.length, 2)
387  assert.deepEqual(data.tasks.map(task => task.entityId), ['part-1', 'part-2'])
388  assert.ok(data.tasks.every(task => task.handlerWorkflowId === handlerWorkflow.id))
389  assert.ok(data.tasks.every(task => task.handlerWorkflowVersion === 3))
390  assert.equal(data.tasks[1].context.targetShelfId, 'shelf-22')
391  assert.equal(execution.context.tasks.length, 2)
392})
393
394test('batch TASK preflights conflicts and does not leave partially created tasks', async () => {
395  const { data, engine } = fixture()
396  const creationWorkflow = taskCreationWorkflow()
397  addSupplyOrderModels(data)
398  data.workflows.push(creationWorkflow, taskHandlerWorkflow())
399
400  const execution = await engine.start(
401    creationWorkflow.id,
402    supplyOrderEvent([
403      { id: 'part-1', orderId: 'order-1', targetShelfId: 'shelf-11' },
404      { id: 'part-1', orderId: 'order-1', targetShelfId: 'shelf-22' }
405    ])
406  )
407
408  assert.equal(execution.status, 'failed')
409  assert.match(execution.error, /already has an active task/)
410  assert.equal(data.tasks.length, 0)
411})
412
413test('active tasks continue on their pinned workflow revision', async () => {
414  const { data, engine } = fixture()
415  const revision3 = taskHandlerWorkflow()
416  const current = structuredClone(revision3)
417  current.version = 4
418  current.revisions = [revision3]
419  current.nodes.find(node => node.id === 'mark-processed').config.set.processed = 'revision-4'
420  data.workflows.push(current)
421  data.tasks.push(activeTask())
422
423  const result = await engine.trigger({
424    eventId: 'scan-pinned-revision',
425    event: 'SCAN_POST1',
426    entityType: 'item',
427    entityId: '0000001'
428  })
429
430  assert.equal(result.processed, 1)
431  assert.equal(result.executions[0].workflowVersion, 3)
432  assert.equal(data.tasks[0].context.processed, true)
433})
434
435test('async enqueue durably accepts before running the same task router', async () => {
436  const { data, engine } = fixture()
437  data.workflows.push(taskHandlerWorkflow())
438  data.tasks.push(activeTask())
439
440  const accepted = engine.enqueue({
441    eventId: 'async-scan-event',
442    event: 'SCAN_POST1',
443    entityType: 'item',
444    entityId: '0000001'
445  })
446
447  assert.deepEqual(accepted, {
448    eventId: 'async-scan-event',
449    status: 'accepted',
450    duplicate: false
451  })
452  assert.equal(data.inbox[0].status, 'accepted')
453
454  await new Promise(resolve => setImmediate(resolve))
455
456  assert.equal(data.inbox[0].status, 'processed')
457  assert.equal(data.inbox[0].result.processed, 1)
458  assert.equal(data.tasks[0].state, 'post1_scanned')
459
460  const duplicate = engine.enqueue({
461    eventId: 'async-scan-event',
462    event: 'SCAN_POST1',
463    entityType: 'item',
464    entityId: '0000001'
465  })
466  assert.equal(duplicate.duplicate, true)
467  assert.equal(duplicate.status, 'processed')
468  assert.equal(duplicate.result.processed, 1)
469  assert.equal(data.executions.length, 1)
470})
471
472
473test('handler task context model types data.* in TASK events (G1)', () => {
474  const { data } = fixture()
475  addSupplyOrderModels(data)
476  const handler = taskHandlerWorkflow()
477  handler.nodes[0].config.conditions.push('data.targetShelfId != ""')
478
479  assert.ok(validateWorkflowDataFlow(handler, data.models, [handler])
480    .some(issue => issue.includes('Unknown field: data.targetShelfId')))
481
482  handler.settings = { taskContextModelId: 'supply-part' }
483  assert.deepEqual(validateWorkflowDataFlow(handler, data.models, [handler]), [])
484
485  handler.settings = { taskContextModelId: 'missing-model' }
486  assert.ok(validateWorkflowDataFlow(handler, data.models, [handler])
487    .includes('Task context model not found'))
488})
489
490test('TASK payloadMapping must provide the handler task context (G1)', () => {
491  const { data } = fixture()
492  addSupplyOrderModels(data)
493  const creation = taskCreationWorkflow()
494  const handler = taskHandlerWorkflow()
495  handler.settings = { taskContextModelId: 'supply-part' }
496  const workflows = [creation, handler]
497
498  assert.deepEqual(validateWorkflowDataFlow(creation, data.models, workflows), [])
499
500  creation.nodes[1].config.payloadMapping = { id: 'data.id', orderId: 'data.orderId' }
501  const issues = validateWorkflowDataFlow(creation, data.models, workflows)
502  assert.ok(issues.some(issue =>
503    issue.includes('payloadMapping → handler task context: Missing required field: data.targetShelfId')))
504})
505
506test('engine refuses to create a task whose context breaks the handler model (G1)', async () => {
507  const { data, engine } = fixture()
508  addSupplyOrderModels(data)
509  const creation = taskCreationWorkflow()
510  creation.nodes[1].config.payloadMapping = { id: 'data.id', orderId: 'data.orderId' }
511  const handler = taskHandlerWorkflow()
512  handler.settings = { taskContextModelId: 'supply-part' }
513  data.workflows.push(creation, handler)
514
515  const execution = await engine.start(creation.id, supplyOrderEvent([
516    { id: 'part-1', orderId: 'order-1', targetShelfId: 'shelf-11' }
517  ]))
518
519  assert.equal(execution.status, 'failed')
520  assert.match(execution.error, /Task context validation failed: payload\.targetShelfId is required/)
521  assert.equal(data.tasks.length, 0)
522})
523