engine.ts
TypeScript · 976 рядків
1// Рушій workflow. Логіка блоків — як у SQLite-версії; дані — через Repo (repo.ts): у пам'яті (тести) або
2// PostgreSQL (одна подія — одна транзакція, pg-repo.ts + flow.ts).
3//
4// Лічильник циклів (R-12.21): цикли в графі дозволені, але за один прохід рушій рахує кроки й відвідування кожного
5// блока. Перевищення ліміту (workflow.settings.loopLimits, за замовчуванням 1000 кроків / 100 відвідувань блока) —
6// помилка LOOP_LIMIT, яка НЕ перетворюється на «failed execution», а виходить нагору: транзакція відкочується,
7// flow.ts записує збій і повідомлення про цикл.
8import { validateData } from './models.ts'
9import { evaluateCondition } from '../shared/condition.ts'
10import { buildRequestBody, resolveApiUrl } from '../shared/api-request.ts'
11import { buildMappedData } from '../shared/mapping.ts'
12import { buildFireEvent } from '../shared/fire-event.ts'
13import { applyAction } from '../shared/action.ts'
14import { runDecision } from '../shared/decision.ts'
15import { screenBody } from '../shared/screen.ts'
16import { stageById, stageContextModelId, stageOf } from '../shared/stages.ts'
17import {
18 readRuntimePath,
19 readTaskPath,
20 renderTaskTemplate,
21 resolveTaskValue,
22 taskContextModelId,
23 taskPayload,
24 withDefaults
25} from '../shared/task.ts'
26import { asRepo, type Json, type LegacyStore, type Repo } from './repo.ts'
27
28export const DEFAULT_LOOP_LIMITS = { steps: 1000, nodeVisits: 100 }
29
30export const DEFAULT_ERROR_SCREEN = {
31 kind: 'error',
32 text: 'Operation failed: {{data.error.message}}. Repeat the action or call the supervisor',
33 expect: 'button',
34 tone: 'error',
35 buttons: ['OK']
36}
37
38/** Адреса сервісів для відносних URL у API_REQUEST (`/stub/wms/...`): сервер встановлює свою адресу на старті. */
39export const services = { base: '' }
40
41export class LoopLimitError extends Error {
42 code = 'LOOP_LIMIT'
43 details: Json
44 constructor(message: string, details: Json) {
45 super(message)
46 this.details = details
47 }
48}
49
50function coded(message: string, code: string): Error & { code: string } {
51 const error = new Error(message) as Error & { code: string }
52 error.code = code
53 return error
54}
55
56function clone(value) {
57 return value === undefined ? undefined : structuredClone(value)
58}
59
60function set(object, path, value) {
61 const keys = path.split('.')
62 const last = keys.pop()
63 const target = keys.reduce((current, key) => current[key] ??= {}, object)
64 target[last] = value
65}
66
67function eventName(event) {
68 return String(event?.event || event?.name || '')
69}
70
71function eventEntityType(event) {
72 return String(event?.entityType || 'warehouse_item')
73}
74
75function initialEventData(event) {
76 if (event?.data && typeof event.data === 'object' && !Array.isArray(event.data)) {
77 return clone(event.data)
78 }
79 return clone(event || {})
80}
81
82interface Pass { steps: number; visits: Map<string, number>; limits: { steps: number; nodeVisits: number } }
83
84export class Engine {
85 repo: Repo
86 /** Задачі, прочитані в цьому рушії (у PostgreSQL рушій живе одну транзакцію). */
87 private tasks = new Map<string, Json>()
88 private passes = new Map<string, Pass>()
89
90 constructor(store: Repo | LegacyStore) {
91 this.repo = asRepo(store)
92 }
93
94 /** Сумісність зі старими викликами (engine.store.data у тестах і демо). */
95 get store() {
96 return (this.repo as Json).store ?? this.repo
97 }
98
99 async log(execution, node, event, input = {}, output = {}, error = null) {
100 const log = {
101 id: crypto.randomUUID(),
102 executionId: execution.id,
103 nodeId: node?.id,
104 nodeName: node?.name,
105 event,
106 input,
107 output,
108 error,
109 createdAt: new Date().toISOString()
110 }
111 await this.repo.insertLog(log)
112 execution.history.push({
113 nodeId: node?.id,
114 status: error ? 'failed' : event === 'WAITING' ? 'waiting' : 'completed',
115 at: log.createdAt
116 })
117 return log
118 }
119
120 async taskFor(execution) {
121 if (!execution.taskId) return execution.invocationType === 'task_event' ? false : null
122 let task = this.tasks.get(execution.taskId)
123 if (!task) {
124 task = await this.repo.task(execution.taskId)
125 if (task) this.tasks.set(task.id, task)
126 }
127 return task || null
128 }
129
130 async workflowForExecution(execution) {
131 return (await this.repo.workflowVersion(execution.workflowId, execution.workflowVersion))
132 || await this.repo.workflow(execution.workflowId)
133 }
134
135 async scopes(execution, event) {
136 return {
137 data: execution.context,
138 task: await this.taskFor(execution),
139 event,
140 input: execution.context,
141 model: event
142 }
143 }
144
145 activeTask(entityType, entityId) {
146 return this.repo.activeTask(entityType, entityId)
147 }
148
149 async resolveHandlerWorkflow(reference) {
150 const value = String(reference || '').trim()
151 if (!value) return null
152
153 const workflowById = await this.repo.workflow(value)
154 if (workflowById) return workflowById
155
156 const matches = (await this.repo.workflows()).filter(workflow => workflow.name === value)
157 if (matches.length === 1) return matches[0]
158
159 throw coded(
160 matches.length ? `Task handler workflow name is ambiguous: ${value}` : `Task handler workflow not found: ${value}`,
161 matches.length ? 'TASK_WORKFLOW_AMBIGUOUS' : 'TASK_WORKFLOW_NOT_FOUND'
162 )
163 }
164
165 /** У пам'яті кидає синхронно (тести), у PostgreSQL — повертає Promise. */
166 createTask(task) {
167 const created = this.repo.insertTask(task)
168 if (created && typeof (created as Json).then === 'function') {
169 return (created as Promise<Json>).then(value => { this.tasks.set(value.id, value); return value })
170 }
171 this.tasks.set((created as Json).id, created)
172 return created
173 }
174
175 findStartNode(workflow, event, requestedNodeId = null) {
176 if (requestedNodeId) return workflow.nodes.find(node => node.id === requestedNodeId)
177 const incoming = new Set(workflow.edges.map(edge => edge.target))
178 return workflow.nodes.find(node =>
179 node.type === 'EVENT'
180 && node.config?.activation !== 'TASK'
181 && (!incoming.has(node.id) || node.config?.activation === 'START')
182 && (!node.config?.event || node.config.event === eventName(event))
183 ) || workflow.nodes[0]
184 }
185
186 async createExecution(workflow, start, event, options: Json = {}) {
187 const now = new Date().toISOString()
188 const task = options.task || null
189 const context = event.__subflow
190 ? clone(event.data)
191 : task
192 ? clone(task.context || task.payload || {})
193 : initialEventData(event)
194
195 if (!event.__subflow && !task) {
196 context.entity ??= {
197 type: eventEntityType(event),
198 id: event.entityId
199 }
200 }
201
202 const execution: Json = {
203 id: crypto.randomUUID(),
204 parentExecutionId: event.parentExecutionId || null,
205 parentNodeId: event.parentNodeId || null,
206 invocationType: event.__subflow ? 'subflow' : task || options.taskMissing ? 'task_event' : 'event',
207 workflowId: workflow.id,
208 workflowVersion: task?.handlerWorkflowVersion || workflow.version || 1,
209 taskId: task?.id || null,
210 eventId: event.eventId || null,
211 entityType: eventEntityType(event),
212 entityId: String(event.entityId || task?.entityId || crypto.randomUUID()),
213 status: 'running',
214 currentNodeId: start.id,
215 context,
216 waitingFor: null,
217 response: null,
218 history: [],
219 startedAt: now,
220 updatedAt: now,
221 completedAt: null
222 }
223 await this.repo.insertExecution(execution)
224 return execution
225 }
226
227 /** Новий прохід виконання: лічильники циклів з нуля. */
228 beginPass(execution, workflow) {
229 const limits = { ...DEFAULT_LOOP_LIMITS, ...(workflow?.settings?.loopLimits || {}) }
230 this.passes.set(execution.id, { steps: 0, visits: new Map(), limits })
231 }
232
233 async start(workflowId, event, options: Json = {}) {
234 const workflow = options.workflow || await this.repo.workflow(workflowId)
235 if (!workflow) throw new Error('Workflow not found')
236
237 const start = event.__subflow
238 ? workflow.nodes.find(node => node.type === 'WORKFLOW_INPUT')
239 : this.findStartNode(workflow, event, options.startNodeId)
240 if (!start) throw new Error('Workflow has no matching start node')
241
242 const execution = await this.createExecution(workflow, start, event, options)
243 if (options.task) this.tasks.set(options.task.id, options.task)
244 this.beginPass(execution, workflow)
245 await this.run(execution, start.id, event, true)
246 await this.persistTaskContext(execution)
247 await this.repo.saveExecution(execution)
248 await this.repo.flush()
249 return execution
250 }
251
252 async taskEventNodes(workflow, event, task) {
253 const context = task ? task.context || task.payload || {} : initialEventData(event)
254 const result = []
255 for (const node of workflow.nodes) {
256 if (node.type !== 'EVENT' || node.config?.activation !== 'TASK') continue
257 if (node.config?.event !== eventName(event)) continue
258 if (await this.eventMatches(node, context, event, task || false)) result.push(node)
259 }
260 return result
261 }
262
263 startEventNodes(workflow, event) {
264 const incoming = new Set(workflow.edges.map(edge => edge.target))
265 return workflow.nodes.filter(node =>
266 node.type === 'EVENT'
267 && node.config?.activation !== 'TASK'
268 && (!incoming.has(node.id) || node.config?.activation === 'START')
269 && node.config?.event === eventName(event)
270 )
271 }
272
273 normalizeEvent(event) {
274 return {
275 ...event,
276 event: eventName(event),
277 eventId: event.eventId || crypto.randomUUID(),
278 entityType: eventEntityType(event)
279 }
280 }
281
282 enqueue(rawEvent) {
283 return this.repo.enqueue(this.normalizeEvent(rawEvent), this)
284 }
285
286 async trigger(rawEvent, options: Json = {}) {
287 const event = this.normalizeEvent(rawEvent)
288 const existing = await this.repo.inbox(event.eventId)
289 if (existing && !options.resumeAccepted) {
290 return { ...clone(existing.result), duplicate: true }
291 }
292
293 const inbox = existing || {
294 eventId: event.eventId,
295 event: event.event,
296 entityType: event.entityType,
297 entityId: String(event.entityId ?? ''),
298 status: 'accepted',
299 result: null,
300 receivedAt: new Date().toISOString(),
301 processedAt: null
302 }
303 inbox.status = 'processing'
304 if (!existing) await this.repo.insertInbox(inbox)
305
306 try {
307 const executions = []
308 // виконання, що чекають цю подію (legacy WAIT, демо-симулятор), — спершу вони, як у consume
309 const waiting = event.entityId === undefined ? [] : await this.repo.waitingExecutions(event.event, String(event.entityId))
310 const task = waiting.length || event.entityId === undefined
311 ? null
312 : await this.activeTask(event.entityType, event.entityId)
313
314 if (waiting.length) {
315 for (const execution of waiting) {
316 execution.status = 'running'
317 execution.waitingFor = null
318 this.beginPass(execution, await this.workflowForExecution(execution))
319 await this.run(execution, execution.currentNodeId, event, true)
320 await this.persistTaskContext(execution)
321 await this.repo.saveExecution(execution)
322 executions.push(execution)
323 }
324 } else if (task) {
325 this.tasks.set(task.id, task)
326 const workflow = await this.repo.workflowVersion(task.handlerWorkflowId, task.handlerWorkflowVersion)
327 if (!workflow) {
328 throw coded(`Task handler workflow not found: ${task.handlerWorkflowId || 'empty id'}`, 'TASK_WORKFLOW_NOT_FOUND')
329 }
330 // задача етапу борду (R-30.12): подію приймають лише TASK-події в області цього етапу
331 const nodes = (await this.taskEventNodes(workflow, event, task))
332 .filter(node => !task.handlerStageId || stageOf(workflow, node)?.id === task.handlerStageId)
333 if (nodes.length > 1) {
334 throw coded(`Event ${event.event} matches multiple task entry nodes`, 'AMBIGUOUS_TASK_EVENT')
335 }
336 if (nodes.length === 1) {
337 executions.push(await this.start(workflow.id, event, {
338 workflow,
339 task,
340 startNodeId: nodes[0].id
341 }))
342 }
343 } else {
344 for (const workflow of await this.repo.workflows()) {
345 for (const node of this.startEventNodes(workflow, event)) {
346 executions.push(await this.start(workflow.id, event, { workflow, startNodeId: node.id }))
347 }
348 for (const node of await this.taskEventNodes(workflow, event, false)) {
349 executions.push(await this.start(workflow.id, event, {
350 workflow,
351 startNodeId: node.id,
352 taskMissing: true
353 }))
354 }
355 }
356 }
357
358 const responseExecution = executions.find(execution => execution.response)
359 const result = {
360 processed: executions.length,
361 code: executions.length ? 'PROCESSED' : task ? 'EVENT_NOT_ALLOWED' : 'NO_ACTIVE_TASK',
362 executions,
363 response: responseExecution?.response || await this.errorScreen(executions, event)
364 }
365 inbox.status = 'processed'
366 inbox.result = clone(result)
367 inbox.processedAt = new Date().toISOString()
368 await this.repo.saveInbox(inbox)
369 await this.repo.flush()
370 return result
371 } catch (error) {
372 inbox.status = 'failed'
373 inbox.result = { processed: 0, code: error.code || 'EVENT_PROCESSING_FAILED', error: error.message }
374 inbox.processedAt = new Date().toISOString()
375 await this.repo.saveInbox(inbox)
376 await this.repo.flush()
377 throw error
378 }
379 }
380
381 /**
382 * Екран помилки за замовчуванням (P7, R-23 §11): прохід процесу, що відповідає на ТСД блоками SCREEN, упав
383 * (сервіс відмовив, вихід error не з'єднано) і екрана не дав — ТСД отримує екран помилки замість порожньої відповіді.
384 * Текст — workflow.settings.errorScreen (шаблон з {{data.error.message}}, {{data.error.block}}), інакше стандартний.
385 * Стан задачі не змінюється (контекст невдалого проходу не зберігається) — дію можна повторити.
386 */
387 async errorScreen(executions, event) {
388 for (const execution of executions.filter(item => item.status === 'failed')) {
389 const workflow = await this.workflowForExecution(execution)
390 if (!workflow?.nodes?.some(node => node.type === 'SCREEN')) continue
391 const block = workflow.nodes.find(node => node.id === execution.errorNodeId)?.name || ''
392 const error = { message: execution.error || '', code: execution.errorCode || 'NODE_FAILED', block }
393 const config = { ...DEFAULT_ERROR_SCREEN, ...(workflow.settings?.errorScreen || {}) }
394 try {
395 const body: Json = screenBody(config, { data: { ...execution.context, error }, task: await this.taskFor(execution), event })
396 return { status: 200, body: { ...body, error } }
397 } catch {
398 // шаблон налаштування посилається на поле, якого немає, — стандартний текст
399 return { status: 200, body: { ...screenBody(DEFAULT_ERROR_SCREEN, { data: { error }, event }), error } }
400 }
401 }
402 return null
403 }
404
405 async consume(event) {
406 const candidates = await this.repo.waitingExecutions(eventName(event), event.entityId ? String(event.entityId) : null)
407
408 if (candidates.length) {
409 for (const execution of candidates) {
410 execution.status = 'running'
411 execution.waitingFor = null
412 this.beginPass(execution, await this.workflowForExecution(execution))
413 await this.run(execution, execution.currentNodeId, event, true)
414 await this.persistTaskContext(execution)
415 await this.repo.saveExecution(execution)
416 }
417 await this.repo.consumed(event)
418 await this.repo.flush()
419 return candidates
420 }
421
422 const result = await this.trigger(event)
423 return result.executions
424 }
425
426 /** Продовжити виконання після таймера DELAY (PostgreSQL). */
427 async resumeAfterDelay(execution, nodeId) {
428 const workflow = await this.workflowForExecution(execution)
429 const node = workflow.nodes.find(candidate => candidate.id === nodeId)
430 execution.status = 'running'
431 execution.waitingFor = null
432 this.beginPass(execution, workflow)
433 const edge = node ? await this.nextEdge(execution, workflow, node, node.outputs?.[0]?.id, { event: '$timer', nodeId }) : null
434 if (!edge) await this.complete(execution)
435 else await this.run(execution, edge.target, { event: '$timer', nodeId }, false, 0, edge.targetPort)
436 await this.persistTaskContext(execution)
437 await this.repo.saveExecution(execution)
438 await this.repo.flush()
439 return execution
440 }
441
442 /** Лічильник циклів (R-12.21). */
443 countStep(execution, workflow, node) {
444 let pass = this.passes.get(execution.id)
445 if (!pass) { this.beginPass(execution, workflow); pass = this.passes.get(execution.id) }
446 pass.steps += 1
447 const visits = (pass.visits.get(node.id) || 0) + 1
448 pass.visits.set(node.id, visits)
449 if (pass.steps > pass.limits.steps || visits > pass.limits.nodeVisits) {
450 const hot = [...pass.visits].filter(([, count]) => count > 1).sort((a, b) => b[1] - a[1])
451 throw new LoopLimitError(
452 `Loop detected in workflow ${workflow.name || workflow.id}: ${pass.steps} steps, block "${node.name || node.id}" visited ${visits} times`,
453 {
454 workflowId: workflow.id,
455 workflowName: workflow.name || null,
456 workflowVersion: execution.workflowVersion,
457 executionId: execution.id,
458 taskId: execution.taskId || null,
459 eventId: execution.eventId || null,
460 nodeId: node.id,
461 steps: pass.steps,
462 limits: pass.limits,
463 loopNodes: hot.map(([nodeId, count]) => ({ nodeId, name: workflow.nodes.find(n => n.id === nodeId)?.name || nodeId, visits: count }))
464 }
465 )
466 }
467 }
468
469 async run(execution, nodeId, event, resume = false, depth = 0, inputPort = null) {
470 const workflow = await this.workflowForExecution(execution)
471 const node = workflow.nodes.find(candidate => candidate.id === nodeId)
472 if (!node) return this.complete(execution)
473 this.countStep(execution, workflow, node)
474
475 execution.currentNodeId = node.id
476 execution.updatedAt = new Date().toISOString()
477
478 try {
479 const port = await this.executeNode(execution, node, event, resume, inputPort)
480 if (port === '__wait__') {
481 execution.status = 'waiting'
482 execution.waitingFor = node.config.event
483 await this.log(execution, node, 'WAITING', { event }, { waitingFor: execution.waitingFor })
484 return
485 }
486 if (port === '__delay__') {
487 execution.status = 'waiting'
488 execution.waitingFor = '$timer'
489 await this.log(execution, node, 'WAITING', { event }, { waitingFor: '$timer', seconds: Number(node.config?.seconds) })
490 return
491 }
492 if (port === '__filtered__') {
493 await this.log(execution, node, 'CONDITION_NOT_MATCHED', { event }, {
494 conditions: node.config?.conditions || []
495 })
496 return this.complete(execution)
497 }
498 if (port === '__workflow_output__') {
499 await this.log(execution, node, node.type, { event }, {
500 port: execution.returnPort,
501 context: execution.context
502 })
503 return this.complete(execution)
504 }
505 if (port === '__client_response__') {
506 await this.log(execution, node, node.type, { event }, { response: execution.response })
507 return this.complete(execution)
508 }
509
510 await this.log(execution, node, node.type, { event }, {
511 port,
512 context: execution.context
513 })
514
515 if (Array.isArray(port)) {
516 const connected = []
517 for (const id of port) {
518 const edge = await this.nextEdge(execution, workflow, node, id, event)
519 if (edge) connected.push({ id, edge })
520 }
521
522 for (const branch of connected.filter(item => item.id === 'task')) {
523 const now = new Date().toISOString()
524 const child: Json = {
525 id: crypto.randomUUID(),
526 parentExecutionId: execution.id,
527 workflowId: execution.workflowId,
528 workflowVersion: execution.workflowVersion,
529 taskId: null,
530 eventId: execution.eventId,
531 entityType: execution.entityType,
532 entityId: execution.entityId,
533 status: 'running',
534 currentNodeId: branch.edge.target,
535 context: clone(execution.context.task),
536 waitingFor: null,
537 response: null,
538 history: [],
539 startedAt: now,
540 updatedAt: now,
541 completedAt: null
542 }
543 await this.repo.insertExecution(child)
544 this.beginPass(child, workflow)
545 await this.run(child, branch.edge.target, event, false, depth + 1, branch.edge.targetPort)
546 await this.repo.saveExecution(child)
547 }
548
549 const next = connected.find(item => item.id === 'next')
550 if (next) {
551 return this.run(execution, next.edge.target, event, false, depth + 1, next.edge.targetPort)
552 }
553 return this.complete(execution)
554 }
555
556 const edge = await this.nextEdge(execution, workflow, node, port, event)
557 if (!edge) return this.complete(execution)
558 return this.run(execution, edge.target, event, false, depth + 1, edge.targetPort)
559 } catch (error) {
560 if (error instanceof LoopLimitError) throw error
561 execution.status = 'failed'
562 execution.error = error.message
563 execution.errorCode = error.code || 'NODE_FAILED'
564 execution.errorNodeId = node.id
565 await this.log(execution, node, 'ERROR', { event }, {}, error.message)
566 }
567 }
568
569 /**
570 * Ребро, яким іти з порту (G3): перше згори, чия умова істинна; якщо жодна — ребро без умови (fallback);
571 * якщо й його немає — шлях закінчується. Умова — та сама мова, що в CONDITION (data / task / event).
572 */
573 async nextEdge(execution, workflow, node, port, event) {
574 const edges = workflow.edges.filter(edge => edge.source === node.id && edge.sourcePort === port)
575 const conditioned = edges.filter(edge => String(edge.condition || '').trim())
576 if (conditioned.length) {
577 const scopes = await this.scopes(execution, event)
578 for (const edge of conditioned) {
579 if (this.condition(String(edge.condition).trim(), scopes)) return edge
580 }
581 }
582 return edges.find(edge => !String(edge.condition || '').trim()) || null
583 }
584
585 async executeNode(execution, node, event, resume, inputPort = null) {
586 const context = execution.context
587 const config = node.config || {}
588 const task = await this.taskFor(execution)
589 const runtimeScopes = { task, event }
590
591 if (node.type === 'EVENT') {
592 const workflow = await this.workflowForExecution(execution)
593 const activation = config.activation
594 || (workflow.edges.some(edge => edge.target === node.id)
595 ? 'LEGACY_WAIT'
596 : 'START')
597 if (!resume && activation === 'LEGACY_WAIT') return '__wait__'
598 return await this.acceptEvent(context, event, node, task, activation)
599 ? node.outputs[0]?.id
600 : activation === 'LEGACY_WAIT' ? '__wait__' : '__filtered__'
601 }
602
603 if (node.type === 'ACTION') {
604 applyAction(config, context, { task, event, model: event })
605 return node.outputs[0]?.id
606 }
607
608 if (node.type === 'DELAY') {
609 const mode = await this.repo.delay(execution, node, Number(config.seconds))
610 return mode === 'suspend' ? '__delay__' : node.outputs[0]?.id
611 }
612
613 if (node.type === 'CONDITION') {
614 const routes = Array.isArray(config.routes)
615 ? Object.fromEntries(config.routes.map(route => [route.port, route.expression]))
616 : config.routes || {}
617 const fallback = Object.entries(routes).find(([, expression]) => expression === '')?.[0]
618 const errorPort = Object.entries(routes).find(([, expression]) => expression === '$error')?.[0]
619 try {
620 const scopes = await this.scopes(execution, event)
621 for (const [port, expression] of Object.entries(routes) as [string, string][]) {
622 if (expression && expression !== '$error'
623 && this.condition(expression, scopes)) {
624 return port
625 }
626 }
627 return fallback
628 } catch (error) {
629 if (errorPort) {
630 context.error = {
631 type: 'CONDITION_ERROR',
632 message: error.message,
633 code: 'CONDITION_EVALUATION_FAILED',
634 details: {},
635 nodeId: node.id,
636 blockType: node.type
637 }
638 return errorPort
639 }
640 throw error
641 }
642 }
643
644 if (node.type === 'API_REQUEST') {
645 const method = String(config.method || 'GET').toUpperCase()
646 const resolved = resolveApiUrl(config.url, context, runtimeScopes)
647 const url = resolved.startsWith('/') && services.base ? services.base + resolved : resolved
648 const successPort = node.outputs.find(port => port.id !== 'error')?.id || node.outputs[0]?.id
649 try {
650 let result = config.mockResponse
651 if (!result && url) {
652 // ключ ідемпотентності (R-12.8, G8): подія + блок + номер відвідування блока в цьому проході — повтор тієї самої
653 // події дає той самий ключ, тож сервіс не виконає команду двічі; інженеру ключ у мапінгу не потрібен
654 const visit = this.passes.get(execution.id)?.visits.get(node.id) || 1
655 const response = await fetch(url, {
656 method,
657 headers: { 'content-type': 'application/json', 'idempotency-key': `${event?.eventId || execution.eventId}:${node.id}:${visit}` },
658 body: method === 'GET'
659 ? undefined
660 : JSON.stringify(buildRequestBody(config.requestMapping, context, runtimeScopes))
661 })
662 if (!response.ok) {
663 // причина відмови від сервісу ({ error } або { message }) — у повідомленні: її бачать екран помилки й журнал
664 let reason = ''
665 try {
666 const body = await response.json()
667 reason = String(body?.error || body?.message || '')
668 } catch {
669 // тіло не JSON або його немає — лише код
670 }
671 const failure = coded(`API ${response.status}${reason ? `: ${reason}` : ''}`, `HTTP_${response.status}`) as Error & { code: string; status?: number }
672 failure.status = response.status
673 throw failure
674 }
675 try {
676 result = await response.json()
677 } catch {
678 throw coded('API response is not valid JSON', 'INVALID_RESPONSE')
679 }
680 }
681
682 const responseModelId = config.modelId || config.responseModelId
683 if (responseModelId) {
684 try {
685 await this.validatePayload(result, await this.repo.model(responseModelId), 'API response')
686 } catch (error) {
687 error.code = 'INVALID_RESPONSE'
688 throw error
689 }
690 }
691 set(context, config.resultPath || 'apiResult', result || {})
692 delete context.error
693 return successPort
694 } catch (error) {
695 const errorPort = node.outputs.find(port => port.id === 'error')?.id
696 const workflow = await this.workflowForExecution(execution)
697 const connected = errorPort && workflow.edges.some(edge =>
698 edge.source === node.id && edge.sourcePort === errorPort
699 )
700 if (!connected) throw error
701 context.error = {
702 type: error.status
703 ? 'HTTP_ERROR'
704 : error.code === 'INVALID_RESPONSE' ? 'INVALID_RESPONSE' : 'NETWORK_ERROR',
705 message: error.message,
706 status: error.status || 0,
707 code: error.code || 'REQUEST_FAILED',
708 details: {},
709 nodeId: node.id,
710 blockType: node.type,
711 request: { method, url }
712 }
713 await this.validatePayload(
714 context.error,
715 await this.repo.model(config.errorModelId || 'system-api-error'),
716 'API error'
717 )
718 return errorPort
719 }
720 }
721
722 if (node.type === 'MAPPING') {
723 execution.context = buildMappedData(
724 config.mapping || { $copy: 'data' },
725 context,
726 runtimeScopes
727 )
728 return node.outputs[0]?.id
729 }
730
731 if (node.type === 'FIRE_EVENT') {
732 const fired = buildFireEvent(config, context, runtimeScopes)
733 await this.enqueue({ ...fired, data: fired.payload })
734 return node.outputs[0]?.id
735 }
736
737 if (node.type === 'WORKFLOW_INPUT') {
738 await this.validatePayload(context, await this.repo.model(config.modelId), 'Workflow input')
739 return node.outputs[0]?.id
740 }
741
742 if (node.type === 'WORKFLOW_OUTPUT') {
743 execution.returnPort = config.port
744 return '__workflow_output__'
745 }
746
747 if (node.type === 'TASK') {
748 const collection = config.itemsPath
749 ? readRuntimePath({ data: context, ...runtimeScopes }, config.itemsPath)
750 : null
751 if (config.itemsPath && !Array.isArray(collection)) {
752 throw new Error(`Task itemsPath must reference an array: ${config.itemsPath}`)
753 }
754 const sources = config.itemsPath ? collection : [context]
755 const candidates = []
756 for (const source of sources) candidates.push(await this.buildTask(execution, config, source, event, false))
757
758 if (config.itemsPath) {
759 const entityKeys = new Set()
760 for (const candidate of candidates) {
761 const entityKey = `${candidate.entityType}:${candidate.entityId}`
762 if (entityKeys.has(entityKey) || await this.activeTask(candidate.entityType, candidate.entityId)) {
763 throw coded(`Entity ${entityKey} already has an active task`, 'ENTITY_ALREADY_HAS_ACTIVE_TASK')
764 }
765 entityKeys.add(entityKey)
766 }
767 }
768
769 const created = []
770 for (const candidate of candidates) created.push(await this.createTask(candidate))
771 if (config.itemsPath) {
772 context.tasks = created.map(clone)
773 return ['next']
774 }
775 context.task = clone(created[0])
776 return ['next', 'task']
777 }
778
779 if (node.type === 'TASK_UPDATE') {
780 const base = inputPort === 'task' ? { task: context } : context
781 const currentTask = task || null
782 const taskId = currentTask?.id
783 || (inputPort === 'task'
784 ? context.id
785 : readTaskPath(base, config.taskIdPath || 'data.task.id'))
786 const updatedTask = taskId ? (this.tasks.get(taskId) || await this.repo.task(taskId)) : null
787 if (!updatedTask) throw new Error(`Task not found: ${taskId || 'empty id'}`)
788 this.tasks.set(updatedTask.id, updatedTask)
789
790 if (config.status) updatedTask.status = renderTaskTemplate(config.status, base, runtimeScopes)
791 if (config.state) updatedTask.state = renderTaskTemplate(config.state, base, runtimeScopes)
792 if (config.progress) updatedTask.progress = renderTaskTemplate(config.progress, base, runtimeScopes)
793 if (config.complete) {
794 updatedTask.status = 'completed'
795 updatedTask.completedAt = new Date().toISOString()
796 }
797 if (!currentTask) {
798 updatedTask.version = Number(updatedTask.version || 0) + 1
799 }
800 updatedTask.updatedAt = new Date().toISOString()
801 await this.repo.saveTask(updatedTask)
802 if (currentTask) {
803 execution.context = base
804 } else {
805 base.task = clone(updatedTask)
806 execution.context = base
807 }
808 return ['next', 'task']
809 }
810
811 if (node.type === 'DECISION') {
812 // який рядок спрацював — у data.<resultPath>.rule (журнал проходу зберігає його разом із контекстом)
813 return runDecision(config, context, { task, event, model: event }).port
814 }
815
816 if (node.type === 'SCREEN') {
817 execution.response = { status: 200, body: screenBody(config, { data: context, task, event }) }
818 return '__client_response__'
819 }
820
821 if (node.type === 'CLIENT_RESPONSE') {
822 const status = Number(config.status || 200)
823 if (!Number.isInteger(status) || status < 100 || status > 599) {
824 throw new Error('CLIENT_RESPONSE status must be an integer from 100 to 599')
825 }
826 execution.response = {
827 status,
828 body: buildMappedData(config.mapping || { $copy: 'data' }, context, runtimeScopes)
829 }
830 return '__client_response__'
831 }
832
833 if (node.type === 'WORKFLOW') {
834 const child = await this.start(config.workflowId, {
835 __subflow: true,
836 data: context,
837 entityType: execution.entityType,
838 entityId: execution.entityId,
839 parentExecutionId: execution.id,
840 parentNodeId: node.id
841 })
842 if (child.status !== 'completed' || !child.returnPort) {
843 throw new Error('Child workflow did not reach WORKFLOW_OUTPUT')
844 }
845 execution.context = clone(child.context)
846 return child.returnPort
847 }
848
849 return node.outputs[0]?.id
850 }
851
852 async buildTask(execution, config, sourceData, event, persist = true) {
853 const now = new Date().toISOString()
854 // пакетна задача (P5): data — елемент масиву, parent — дані процесу навколо нього
855 const scopes = { task: await this.taskFor(execution), event, ...(config.itemsPath ? { parent: execution.context } : {}) }
856 const entityType = String(resolveTaskValue(config.entityType || execution.entityType, sourceData, scopes))
857 const entityId = String(resolveTaskValue(
858 config.entityIdPath || 'data.entityId',
859 sourceData,
860 scopes
861 ) ?? execution.entityId)
862 // обробник — етап цього борду (R-30.12, закріплена версія борду) або окремий workflow
863 let handlerWorkflow = null, handlerStage = null
864 if (String(config.handlerStageId || '').trim()) {
865 handlerWorkflow = await this.workflowForExecution(execution)
866 handlerStage = stageById(handlerWorkflow, config.handlerStageId)
867 if (!handlerStage) throw coded(`Task handler stage not found: ${config.handlerStageId}`, 'TASK_STAGE_NOT_FOUND')
868 } else {
869 handlerWorkflow = await this.resolveHandlerWorkflow(config.handlerWorkflowId)
870 }
871
872 // контракт контексту задачі обробника (G1): задача не створюється з даними, яких обробник не чекає;
873 // поля, яких мапінг не дав, — зі значень за замовчуванням моделі (P4)
874 const contextModelId = handlerStage ? stageContextModelId(handlerWorkflow, handlerStage) : taskContextModelId(handlerWorkflow)
875 const contextModel = contextModelId ? await this.repo.model(contextModelId) : null
876 const payload = withDefaults(taskPayload(
877 config.payloadMapping || { $copy: 'data' },
878 sourceData,
879 scopes
880 ), contextModel?.defaults)
881 if (contextModelId) await this.validatePayload(payload, contextModel, 'Task context')
882 const task = {
883 id: crypto.randomUUID(),
884 executionId: execution.id,
885 entityType,
886 entityId,
887 parentTaskId: resolveTaskValue(config.parentTaskId || null, sourceData, scopes) || null,
888 orderId: resolveTaskValue(config.orderId || null, sourceData, scopes) || null,
889 type: config.taskType || 'GENERAL',
890 handlerWorkflowId: handlerWorkflow?.id || null,
891 handlerWorkflowVersion: handlerStage
892 ? execution.workflowVersion || handlerWorkflow?.version || null
893 : handlerWorkflow?.version || null,
894 handlerStageId: handlerStage?.id || null,
895 title: renderTaskTemplate(config.title || 'New task', sourceData, scopes),
896 description: renderTaskTemplate(config.description || '', sourceData, scopes),
897 // пріоритет, як і виконавець, може прийти з даних (наприклад, з таблиці рішень)
898 priority: String(resolveTaskValue(config.priority || 'normal', sourceData, scopes) || 'normal'),
899 status: 'open',
900 state: config.state || 'created',
901 progress: renderTaskTemplate(config.progress || 'waiting', sourceData, scopes),
902 assignee: {
903 type: config.assigneeType || 'group',
904 id: String(resolveTaskValue(config.assignee, sourceData, scopes) || '')
905 },
906 context: clone(payload),
907 payload: clone(payload),
908 version: 1,
909 createdAt: now,
910 updatedAt: now,
911 completedAt: null
912 }
913 await this.validatePayload(task, await this.repo.model('system-task'), 'Task')
914 return persist ? await this.createTask(task) : task
915 }
916
917 async eventMatches(node, context, event, task = null) {
918 const modelId = node.config?.modelId
919 if (modelId) await this.validatePayload(event, await this.repo.model(modelId), 'Event payload')
920 return this.conditionsMatch(node, {
921 data: context,
922 input: context,
923 model: event,
924 task,
925 event
926 })
927 }
928
929 async acceptEvent(context, event, node, task = null, activation = 'START') {
930 if (!await this.eventMatches(node, context, event, task)) return false
931 if (activation !== 'TASK') {
932 if (event.data && typeof event.data === 'object' && !Array.isArray(event.data)) {
933 Object.assign(context, event.data)
934 } else {
935 Object.assign(context, event)
936 }
937 }
938 return true
939 }
940
941 condition(expression, scopes) {
942 if (!expression) return true
943 const normalized = expression.replace(/\bcontext\./g, 'data.')
944 return evaluateCondition(normalized, scopes)
945 }
946
947 conditionsMatch(node, scopes) {
948 return (node.config?.conditions || [])
949 .every(expression => this.condition(expression, scopes))
950 }
951
952 async validatePayload(payload, model, label = 'Payload') {
953 if (!model) throw new Error(`${label} model not found`)
954 const result = validateData(payload, model, await this.repo.models())
955 if (!result.valid) {
956 throw new Error(`${label} validation failed: ${result.errors.join('; ')}`)
957 }
958 }
959
960 async persistTaskContext(execution) {
961 const task = await this.taskFor(execution)
962 if (!task || execution.status === 'failed') return
963 task.context = clone(execution.context)
964 task.payload = clone(execution.context)
965 task.version = Number(task.version || 0) + 1
966 task.updatedAt = new Date().toISOString()
967 await this.repo.saveTask(task)
968 }
969
970 complete(execution) {
971 execution.status = 'completed'
972 execution.currentNodeId = null
973 execution.completedAt = execution.updatedAt = new Date().toISOString()
974 }
975}
976