pg-repo.ts
TypeScript · 180 рядків
1// Сховище рушія на PostgreSQL — одна транзакція на подію (R-12.9). Створюється на транзакцію (flow.ts) і живе разом із нею.
2//
3// Інваріанти, які тримає SQL:
4// • задача сутності, рядки виконань і рядок inbox читаються FOR UPDATE — події однієї задачі / сутності йдуть по черзі;
5// • друга активна задача сутності — унікальний індекс; вставка під SAVEPOINT, тож конфлікт не обриває транзакцію,
6// а стає помилкою ENTITY_ALREADY_HAS_ACTIVE_TASK (як у SQLite-версії);
7// • рядок inbox вставляється до проходу; паралельний дубль чекає на ключі й отримує DuplicateEvent;
8// • FIRE_EVENT і async-подія — рядок inbox зі status = accepted у тій самій транзакції (довговічна черга, dispatch.ts);
9// • DELAY — рядок workflow_timers, виконання чекає (status waiting, waiting_for $timer).
10import type { Catalog } from './catalog.ts'
11import type { Sql } from './db.ts'
12import type { Json, Repo } from './repo.ts'
13
14export class DuplicateEvent extends Error {
15 eventId: string
16 constructor(eventId: string) {
17 super(`Event ${eventId} is already being processed`)
18 this.eventId = eventId
19 }
20}
21
22const iso = (v: Json) => (v ? new Date(v).toISOString() : null)
23
24export class PgRepo implements Repo {
25 readonly kind = 'pg' as const
26 readonly sql: Sql
27 readonly catalog: Catalog
28 /** Чи з'явились у транзакції нові accepted-події / таймери — flow.ts смикне диспетчер після коміту. */
29 kicked = false
30
31 constructor(sql: Sql, catalog: Catalog) {
32 this.sql = sql
33 this.catalog = catalog
34 }
35
36 workflow(id: string) { return this.catalog.workflow(id) }
37 workflowVersion(id: string, version: number | null) { return this.catalog.version(this.sql, id, version) }
38 workflows() { return this.catalog.workflows() }
39 model(id: string) { return this.catalog.model(id) }
40 models() { return this.catalog.models() }
41
42 async task(id: string) {
43 const [r] = await this.sql.query<{ data: Json }>('SELECT data FROM workflow_tasks WHERE id = :id FOR UPDATE', { id })
44 return r?.data ?? null
45 }
46
47 async activeTask(entityType: string, entityId: string) {
48 const [r] = await this.sql.query<{ data: Json }>(`
49 SELECT data FROM workflow_tasks WHERE entity_type = :entityType AND entity_id = :entityId AND status IN ('open', 'in_progress')
50 FOR UPDATE`, { entityType: String(entityType), entityId: String(entityId) })
51 return r?.data ?? null
52 }
53
54 async insertTask(task: Json) {
55 await this.sql.query('SAVEPOINT insert_task')
56 try {
57 await this.sql.query(`
58 INSERT INTO workflow_tasks (id, execution_id, entity_type, entity_id, type, handler_workflow_id, handler_workflow_version, status, updated_at, data)
59 VALUES (:id, :executionId, :entityType, :entityId, :type, :handlerId, :handlerVersion, :status, :updatedAt, :data)`, this.taskParams(task))
60 await this.sql.query('RELEASE SAVEPOINT insert_task')
61 return task
62 } catch (e) {
63 await this.sql.query('ROLLBACK TO SAVEPOINT insert_task')
64 if ((e as Json).code === '23505') {
65 const existing = await this.activeTask(task.entityType, task.entityId)
66 const error = new Error(`Entity ${task.entityType}:${task.entityId} already has active task ${existing?.id ?? ''}`.trim()) as Error & { code: string }
67 error.code = 'ENTITY_ALREADY_HAS_ACTIVE_TASK'
68 throw error
69 }
70 throw e
71 }
72 }
73
74 async saveTask(task: Json) {
75 await this.sql.query(`
76 UPDATE workflow_tasks SET status = :status, handler_workflow_id = :handlerId, handler_workflow_version = :handlerVersion, updated_at = :updatedAt, data = :data
77 WHERE id = :id`, this.taskParams(task))
78 }
79
80 private taskParams(task: Json) {
81 return {
82 id: task.id, executionId: task.executionId ?? null, entityType: String(task.entityType || 'warehouse_item'), entityId: String(task.entityId),
83 type: task.type, handlerId: task.handlerWorkflowId ?? null, handlerVersion: task.handlerWorkflowVersion ?? null, status: task.status,
84 updatedAt: iso(task.updatedAt || task.createdAt) ?? new Date().toISOString(), data: JSON.stringify(task),
85 }
86 }
87
88 insertExecution(execution: Json) { return this.saveExecution(execution) }
89
90 async saveExecution(execution: Json) {
91 await this.sql.query(`
92 INSERT INTO workflow_executions (id, workflow_id, workflow_version, parent_execution_id, task_id, entity_type, entity_id, status, waiting_for, updated_at, data)
93 VALUES (:id, :workflowId, :version, :parentId, :taskId, :entityType, :entityId, :status, :waitingFor, :updatedAt, :data)
94 ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, waiting_for = EXCLUDED.waiting_for, updated_at = EXCLUDED.updated_at, data = EXCLUDED.data`, {
95 id: execution.id, workflowId: execution.workflowId, version: execution.workflowVersion ?? null, parentId: execution.parentExecutionId ?? null,
96 taskId: execution.taskId ?? null, entityType: String(execution.entityType), entityId: String(execution.entityId), status: execution.status,
97 waitingFor: execution.waitingFor ?? null, updatedAt: iso(execution.updatedAt), data: JSON.stringify(execution),
98 })
99 }
100
101 async waitingExecutions(event: string, entityId: string | null) {
102 const rows = await this.sql.query<{ data: Json }>(`
103 SELECT data FROM workflow_executions WHERE status = 'waiting' AND waiting_for = :event AND (:entityId::text IS NULL OR entity_id = :entityId)
104 ORDER BY updated_at FOR UPDATE`, { event, entityId })
105 return rows.map((r) => r.data)
106 }
107
108 async insertLog(log: Json) {
109 await this.sql.query('INSERT INTO workflow_execution_logs (id, execution_id, created_at, data) VALUES (:id, :executionId, :createdAt, :data)',
110 { id: log.id, executionId: log.executionId, createdAt: log.createdAt, data: JSON.stringify(log) })
111 }
112
113 async inbox(eventId: string) {
114 const [r] = await this.sql.query<Json>('SELECT * FROM inbox_events WHERE event_id = :eventId FOR UPDATE', { eventId })
115 return r ? inboxRow(r) : null
116 }
117
118 async insertInbox(row: Json) {
119 const inserted = await this.sql.query(`
120 INSERT INTO inbox_events (event_id, event, entity_type, entity_id, status, payload, result, received_at, processed_at)
121 VALUES (:eventId, :event, :entityType, :entityId, :status, :payload, :result, :receivedAt, :processedAt)
122 ON CONFLICT (event_id) DO NOTHING RETURNING event_id`, inboxParams(row))
123 if (!inserted.length) throw new DuplicateEvent(row.eventId)
124 }
125
126 async saveInbox(row: Json) {
127 await this.sql.query('UPDATE inbox_events SET status = :status, result = :result, processed_at = :processedAt WHERE event_id = :eventId', inboxParams(row))
128 }
129
130 async enqueue(event: Json) {
131 const row = {
132 eventId: event.eventId, event: event.event, entityType: event.entityType, entityId: String(event.entityId ?? ''),
133 status: 'accepted', payload: event, result: null, receivedAt: new Date().toISOString(), processedAt: null,
134 }
135 const inserted = await this.sql.query(`
136 INSERT INTO inbox_events (event_id, event, entity_type, entity_id, status, payload, result, received_at, processed_at)
137 VALUES (:eventId, :event, :entityType, :entityId, :status, :payload, :result, :receivedAt, :processedAt)
138 ON CONFLICT (event_id) DO NOTHING RETURNING event_id`, inboxParams(row))
139 if (!inserted.length) {
140 const existing = await this.inbox(event.eventId)
141 return { eventId: event.eventId, status: existing?.status, result: existing?.result ?? null, duplicate: true }
142 }
143 this.kicked = true
144 return { eventId: event.eventId, status: 'accepted', duplicate: false }
145 }
146
147 async consumed(event: Json) {
148 const id = crypto.randomUUID()
149 const row = { id, event: String(event?.event || event?.name || ''), payload: event, processed: true, createdAt: new Date().toISOString() }
150 await this.sql.query('INSERT INTO outbox_events (id, event, created_at, data) VALUES (:id, :event, :createdAt, :data)', { ...row, data: JSON.stringify(row) })
151 }
152
153 async delay(execution: Json, node: Json, seconds: number) {
154 if (!(seconds > 0)) return 'continue' as const
155 await this.sql.query(`
156 INSERT INTO workflow_timers (execution_id, node_id, due_at) VALUES (:executionId, :nodeId, :dueAt)
157 ON CONFLICT (execution_id, node_id) DO UPDATE SET due_at = EXCLUDED.due_at, fired_at = NULL`,
158 { executionId: execution.id, nodeId: node.id, dueAt: new Date(Date.now() + seconds * 1000).toISOString() })
159 this.kicked = true
160 return 'suspend' as const
161 }
162
163 flush() {}
164}
165
166export function inboxRow(r: Json) {
167 return {
168 eventId: r.event_id, event: r.event, entityType: r.entity_type, entityId: r.entity_id, status: r.status,
169 result: r.result ?? null, receivedAt: iso(r.received_at), processedAt: iso(r.processed_at),
170 }
171}
172
173function inboxParams(row: Json) {
174 return {
175 eventId: row.eventId, event: row.event, entityType: row.entityType || 'warehouse_item', entityId: row.entityId ?? null, status: row.status,
176 payload: row.payload === undefined ? null : JSON.stringify(row.payload), result: row.result == null ? null : JSON.stringify(row.result),
177 receivedAt: row.receivedAt || new Date().toISOString(), processedAt: row.processedAt ?? null,
178 }
179}
180