repo.ts
TypeScript · 174 рядків
1// Сховище рушія (R-12 §11, N1–N2). Рушій (engine.ts) не знає, де лежать дані: працює через Repo.
2//
3// PgRepo (pg-repo.ts) — робота: одна подія = одна транзакція PostgreSQL; рядки читаються з блокуванням,
4// змінене записується явно (saveTask / saveExecution), FIRE_EVENT і DELAY — через outbox / таймери.
5// MemoryRepo (цей файл) — тести й старі фікстури: масиви data.* у пам'яті, мутації «на місці», як у SQLite-версії.
6//
7// Методи можуть бути синхронними (пам'ять) або асинхронними (PostgreSQL): рушій завжди робить await.
8// insertTask у пам'яті кидає помилку синхронно — це зберігає поведінку engine.createTask, яку перевіряють тести.
9
10export type Json = any
11
12export interface Repo {
13 readonly kind: 'memory' | 'pg'
14 // визначення
15 workflow(id: string): Json | null | Promise<Json | null>
16 workflowVersion(id: string, version: number | null): Json | null | Promise<Json | null>
17 workflows(): Json[] | Promise<Json[]>
18 model(id: string): Json | null | Promise<Json | null>
19 models(): Json[] | Promise<Json[]>
20 // задачі
21 task(id: string): Json | null | Promise<Json | null>
22 activeTask(entityType: string, entityId: string): Json | null | Promise<Json | null>
23 insertTask(task: Json): Json | Promise<Json>
24 saveTask(task: Json): void | Promise<void>
25 // виконання й журнал
26 insertExecution(execution: Json): void | Promise<void>
27 saveExecution(execution: Json): void | Promise<void>
28 waitingExecutions(event: string, entityId: string | null): Json[] | Promise<Json[]>
29 insertLog(log: Json): void | Promise<void>
30 // події
31 inbox(eventId: string): Json | null | Promise<Json | null>
32 insertInbox(row: Json): void | Promise<void>
33 saveInbox(row: Json): void | Promise<void>
34 /** Подія з FIRE_EVENT / async — пам'ять: inbox + setImmediate; PostgreSQL: outbox у тій самій транзакції. */
35 enqueue(event: Json, engine: { trigger(event: Json, options?: Json): Promise<Json> }): Json | Promise<Json>
36 /** Запис про спожиту подію (старий outbox_events) — лише журнал. */
37 consumed(event: Json): void | Promise<void>
38 /** DELAY: пам'ять — чекає й повертає 'continue'; PostgreSQL — таймер і 'suspend' (виконання чекає таймера). */
39 delay(execution: Json, node: Json, seconds: number): 'continue' | 'suspend' | Promise<'continue' | 'suspend'>
40 /** Межа збереження (у пам'яті — store.save старого коду). */
41 flush(): void | Promise<void>
42}
43
44const ACTIVE = new Set(['open', 'in_progress'])
45
46/** Старе сховище тестів: { data, workflow(), workflowVersion?(), workflows?(), model(), activeTask?(), createTask?(), save(), push() }. */
47export interface LegacyStore {
48 data: Json
49 workflow?(id: string): Json
50 workflowVersion?(id: string, version: number | null): Json
51 workflows?(): Json[]
52 model?(id: string): Json
53 activeTask?(entityType: string, entityId: string): Json
54 createTask?(task: Json): Json
55 save?(): void
56 push?(collection: string, value: Json): Json
57}
58
59export class MemoryRepo implements Repo {
60 readonly kind = 'memory' as const
61 readonly store: LegacyStore
62 readonly data: Json
63
64 constructor(store: LegacyStore) {
65 this.store = store
66 this.data = store.data
67 for (const key of ['workflows', 'models', 'executions', 'logs', 'tasks', 'inbox', 'outbox']) this.data[key] ||= []
68 }
69
70 workflow(id: string) {
71 return this.store.workflow ? this.store.workflow(id) : this.data.workflows.find((w: Json) => w.id === id) || null
72 }
73
74 workflowVersion(id: string, version: number | null) {
75 if (this.store.workflowVersion) return this.store.workflowVersion(id, version)
76 const workflow = this.workflow(id)
77 if (!workflow) return null
78 if (!version || workflow.version === version) return workflow
79 return workflow.revisions?.find((r: Json) => r.version === version) || null
80 }
81
82 workflows() {
83 return this.store.workflows ? this.store.workflows() : this.data.workflows
84 }
85
86 model(id: string) {
87 return this.store.model ? this.store.model(id) : this.data.models.find((m: Json) => m.id === id) || null
88 }
89
90 models() {
91 return this.data.models
92 }
93
94 task(id: string) {
95 return this.data.tasks.find((t: Json) => t.id === id) || null
96 }
97
98 activeTask(entityType: string, entityId: string) {
99 if (this.store.activeTask) return this.store.activeTask(entityType, entityId) || null
100 return this.data.tasks.find((t: Json) =>
101 String(t.entityType || 'warehouse_item') === String(entityType) && String(t.entityId) === String(entityId) && ACTIVE.has(t.status)) || null
102 }
103
104 insertTask(task: Json) {
105 const existing = this.activeTask(task.entityType, task.entityId)
106 if (existing) {
107 const error = new Error(`Entity ${task.entityType}:${task.entityId} already has active task ${existing.id}`) as Error & { code: string }
108 error.code = 'ENTITY_ALREADY_HAS_ACTIVE_TASK'
109 throw error
110 }
111 if (this.store.createTask) return this.store.createTask(task)
112 this.data.tasks.push(task)
113 return task
114 }
115
116 saveTask() {}
117
118 insertExecution(execution: Json) {
119 this.data.executions.push(execution)
120 }
121
122 saveExecution() {}
123
124 waitingExecutions(event: string, entityId: string | null) {
125 return this.data.executions.filter((e: Json) => e.status === 'waiting' && e.waitingFor === event && (!entityId || String(entityId) === e.entityId))
126 }
127
128 insertLog(log: Json) {
129 this.data.logs.push(log)
130 }
131
132 inbox(eventId: string) {
133 return this.data.inbox.find((i: Json) => i.eventId === eventId) || null
134 }
135
136 insertInbox(row: Json) {
137 this.data.inbox.push(row)
138 }
139
140 saveInbox() {}
141
142 enqueue(event: Json, engine: { trigger(event: Json, options?: Json): Promise<Json> }) {
143 const existing = this.inbox(event.eventId)
144 if (existing) return { eventId: event.eventId, status: existing.status, result: structuredClone(existing.result), duplicate: true }
145 this.insertInbox({
146 eventId: event.eventId, event: event.event, entityType: event.entityType, entityId: String(event.entityId ?? ''),
147 status: 'accepted', result: null, receivedAt: new Date().toISOString(), processedAt: null,
148 })
149 this.flush()
150 setImmediate(() => { engine.trigger(event, { resumeAccepted: true }).catch(() => {}) })
151 return { eventId: event.eventId, status: 'accepted', duplicate: false }
152 }
153
154 consumed(event: Json) {
155 const row = { id: crypto.randomUUID(), event: String(event?.event || event?.name || ''), payload: event, processed: true, createdAt: new Date().toISOString() }
156 if (this.store.push) this.store.push('outbox', row)
157 else this.data.outbox.push(row)
158 }
159
160 async delay(_execution: Json, _node: Json, seconds: number): Promise<'continue'> {
161 await new Promise((resolve) => setTimeout(resolve, seconds * 1000))
162 return 'continue'
163 }
164
165 flush() {
166 this.store.save?.()
167 }
168}
169
170/** Рушій приймає Repo або старе сховище тестів. */
171export function asRepo(store: Repo | LegacyStore): Repo {
172 return (store as Repo).kind === 'memory' || (store as Repo).kind === 'pg' ? store as Repo : new MemoryRepo(store as LegacyStore)
173}
174