flow.ts
TypeScript · 141 рядків
1// Сервіс рушія на PostgreSQL: кожна подія, запуск і таймер — окрема транзакція з власним Engine (R-12.9).
2//
3// trigger(event) — sync-режим POST /api/events: рядок inbox першим, прохід, коміт; дубль — збережений результат;
4// enqueue(event) — async-режим: лише accepted-рядок inbox, обробка — диспетчер (переживає рестарт);
5// start(id, body) — POST /api/workflows/:id/execute;
6// processAccepted / fireTimers — для dispatch.ts.
7// Помилка, що вийшла з проходу (AMBIGUOUS, LOOP_LIMIT …), відкочує транзакцію; потім окремою транзакцією записується
8// failed-рядок inbox, а для циклу — повідомлення (notifications) з блоками циклу й лічильниками (R-12.21).
9import { Catalog } from './catalog.ts'
10import type { Database, Sql } from './db.ts'
11import { Engine, LoopLimitError } from './engine.ts'
12import { DuplicateEvent, PgRepo, inboxRow } from './pg-repo.ts'
13
14type Json = any
15
16export class Flow {
17 readonly db: Database
18 readonly catalog: Catalog
19 /** Смикнути диспетчер після коміту (встановлює dispatch.ts). */
20 onKick: () => void = () => {}
21
22 constructor(db: Database, catalog = new Catalog()) {
23 this.db = db
24 this.catalog = catalog
25 }
26
27 /** Транзакція з рушієм. */
28 async inTx<T>(fn: (engine: Engine, repo: PgRepo, sql: Sql) => Promise<T>): Promise<T> {
29 let kicked = false
30 const result = await this.db.transaction(async (sql) => {
31 await this.catalog.ensure(sql)
32 const repo = new PgRepo(sql, this.catalog)
33 const value = await fn(new Engine(repo), repo, sql)
34 kicked = repo.kicked
35 return value
36 })
37 if (kicked) this.onKick()
38 return result
39 }
40
41 normalize(event: Json) {
42 return { ...event, eventId: event.eventId || crypto.randomUUID() }
43 }
44
45 async trigger(raw: Json): Promise<Json> {
46 const event = this.normalize(raw)
47 try {
48 return await this.inTx((engine) => engine.trigger(event))
49 } catch (error) {
50 if (error instanceof DuplicateEvent) return { ...(await this.stored(event.eventId))?.result, duplicate: true }
51 await this.recordFailure(event, error)
52 throw error
53 }
54 }
55
56 async enqueue(raw: Json): Promise<Json> {
57 const event = this.normalize(raw)
58 return this.inTx((engine) => engine.enqueue(event))
59 }
60
61 async start(workflowId: string, body: Json): Promise<Json> {
62 try {
63 return await this.inTx((engine) => engine.start(workflowId, body))
64 } catch (error) {
65 if (error instanceof LoopLimitError) await this.recordFailure(this.normalize(body), error)
66 throw error
67 }
68 }
69
70 async stored(eventId: string) {
71 const [r] = await this.db.sql().query<Json>('SELECT * FROM inbox_events WHERE event_id = :eventId', { eventId })
72 return r ? inboxRow(r) : null
73 }
74
75 /** Збій поза проходом — окремою транзакцією: failed-рядок inbox і (для циклу) повідомлення. */
76 async recordFailure(event: Json, error: Json) {
77 const result = { processed: 0, code: error?.code || 'EVENT_PROCESSING_FAILED', error: error?.message ?? String(error) }
78 await this.db.transaction(async (sql) => {
79 await sql.query(`
80 INSERT INTO inbox_events (event_id, event, entity_type, entity_id, status, payload, result, received_at, processed_at)
81 VALUES (:eventId, :event, :entityType, :entityId, 'failed', :payload, :result, now(), now())
82 ON CONFLICT (event_id) DO UPDATE SET status = 'failed', result = EXCLUDED.result, processed_at = now()`, {
83 eventId: event.eventId, event: String(event.event || event.name || ''), entityType: String(event.entityType || 'warehouse_item'),
84 entityId: event.entityId === undefined ? null : String(event.entityId), payload: JSON.stringify(event), result: JSON.stringify(result),
85 })
86 if (error instanceof LoopLimitError) {
87 const d = error.details
88 await sql.query(`
89 INSERT INTO notifications (kind, workflow_id, workflow_version, task_id, event_id, message, details)
90 VALUES ('LOOP_LIMIT', :workflowId, :version, :taskId, :eventId, :message, :details)`, {
91 workflowId: d.workflowId, version: d.workflowVersion ?? null, taskId: d.taskId, eventId: event.eventId, message: error.message,
92 details: JSON.stringify({ ...d, event: event.event }),
93 })
94 }
95 })
96 }
97
98 /** Наступна accepted-подія (async, FIRE_EVENT) — обробити; false — черга порожня. */
99 async processAccepted(): Promise<boolean> {
100 let event: Json = null
101 try {
102 return await this.inTx(async (engine, _repo, sql) => {
103 const [row] = await sql.query<{ payload: Json }>(`
104 SELECT payload FROM inbox_events WHERE status = 'accepted' ORDER BY received_at, event_id LIMIT 1 FOR UPDATE SKIP LOCKED`)
105 if (!row) return false
106 event = row.payload
107 await engine.trigger(event, { resumeAccepted: true })
108 return true
109 })
110 } catch (error) {
111 if (!event) throw error
112 await this.recordFailure(event, error)
113 return true
114 }
115 }
116
117 /** Таймер DELAY, що настав, — продовжити виконання; false — немає. */
118 async fireTimer(now = new Date().toISOString()): Promise<boolean> {
119 let timer: Json = null
120 try {
121 return await this.inTx(async (engine, repo, sql) => {
122 const [t] = await sql.query<Json>(`
123 SELECT execution_id, node_id FROM workflow_timers WHERE fired_at IS NULL AND due_at <= :now
124 ORDER BY due_at LIMIT 1 FOR UPDATE SKIP LOCKED`, { now })
125 if (!t) return false
126 timer = t
127 await sql.query('UPDATE workflow_timers SET fired_at = now() WHERE execution_id = :e AND node_id = :n', { e: t.execution_id, n: t.node_id })
128 const [ex] = await sql.query<{ data: Json }>(`SELECT data FROM workflow_executions WHERE id = :id AND status = 'waiting' FOR UPDATE`, { id: t.execution_id })
129 if (ex && ex.data.waitingFor === '$timer' && ex.data.currentNodeId === t.node_id) await engine.resumeAfterDelay(ex.data, t.node_id)
130 void repo
131 return true
132 })
133 } catch (error) {
134 if (!timer) throw error
135 await this.recordFailure({ eventId: `timer:${timer.execution_id}:${timer.node_id}`, event: '$timer', entityId: null }, error)
136 await this.db.sql().query('UPDATE workflow_timers SET fired_at = now() WHERE execution_id = :e AND node_id = :n', { e: timer.execution_id, n: timer.node_id })
137 return true
138 }
139 }
140}
141