bootstrap.ts
TypeScript · 144 рядків
1// Порожня база PostgreSQL на старті: імпорт наявної SQLite-бази (.data/wms-flow.sqlite або SQLITE_PATH) без втрат,
2// інакше — демо (як SQLite-версія на першому запуску). Імпорт: визначення нормалізуються (normalize.ts); поточна версія
3// кожного workflow і всі його revisions стають опублікованими версіями, активна — поточна; виконання, журнал, задачі,
4// inbox (оброблені), стан товарів і журнал подій — як є.
5import { existsSync } from 'node:fs'
6import { resolve } from 'node:path'
7import { DatabaseSync } from 'node:sqlite'
8import { Catalog } from './catalog.ts'
9import type { Sql } from './db.ts'
10import { demoModels, demoWorkflow } from './demo.ts'
11import { normalizeWorkflows, syncSystemModels } from './normalize.ts'
12import { upsertModel } from './workflows.ts'
13
14type Json = any
15
16export async function isEmpty(sql: Sql): Promise<boolean> {
17 const [r] = await sql.query<{ n: number }>('SELECT (SELECT count(*) FROM workflows) + (SELECT count(*) FROM data_models) AS n')
18 return Number(r.n) === 0
19}
20
21export function sqlitePath(): string {
22 return resolve(process.env.SQLITE_PATH || '.data/wms-flow.sqlite')
23}
24
25export async function bootstrap(sql: Sql): Promise<string> {
26 if (!(await isEmpty(sql))) return 'existing'
27 const file = sqlitePath()
28 if (existsSync(file)) {
29 const n = await importSqlite(sql, file)
30 return `imported ${file}: ${JSON.stringify(n)}`
31 }
32 await seedDemo(sql)
33 return 'demo'
34}
35
36export async function seedDemo(sql: Sql): Promise<void> {
37 const models = demoModels()
38 for (const model of models) await upsertModel(sql, model)
39 const workflow = demoWorkflow()
40 normalizeWorkflows([workflow])
41 await insertWorkflow(sql, workflow, [])
42 await Catalog.bump(sql)
43}
44
45async function insertWorkflow(sql: Sql, workflow: Json, revisions: Json[]) {
46 const { revisions: _ignored, ...current } = workflow
47 void _ignored
48 const all = [...revisions.map((r) => ({ ...r, revisions: undefined })), current].filter((r) => r && Number(r.version) > 0)
49 const byVersion = new Map<number, Json>()
50 for (const r of all) byVersion.set(Number(r.version), r)
51 if (!byVersion.size) byVersion.set(1, { ...current, version: 1 })
52 const active = Math.max(...byVersion.keys())
53 await sql.query(`
54 INSERT INTO workflows (id, name, status, active_version, created_at, updated_at) VALUES (:id, :name, 'published', :active, :createdAt, :updatedAt)`,
55 { id: current.id, name: current.name || current.id, active, createdAt: current.createdAt || new Date().toISOString(), updatedAt: current.updatedAt || new Date().toISOString() })
56 for (const [version, definition] of [...byVersion].sort((a, b) => a[0] - b[0])) {
57 const { revisions: _r, ...clean } = definition
58 void _r
59 await sql.query('INSERT INTO workflow_versions (workflow_id, version, definition, published_at) VALUES (:id, :version, :definition, :at)', {
60 id: current.id, version, definition: JSON.stringify({ ...clean, id: current.id, version, status: 'published' }), at: clean.updatedAt || new Date().toISOString(),
61 })
62 }
63}
64
65/** Імпорт SQLite-бази SQLite-версії flow. Повертає кількості перенесених рядків. */
66export async function importSqlite(sql: Sql, file: string): Promise<Record<string, number>> {
67 const db = new DatabaseSync(file, { readOnly: true })
68 const has = (table: string) => !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)
69 const rows = (table: string, column = 'data'): Json[] => (has(table) ? db.prepare(`SELECT ${column} AS json FROM ${table} ORDER BY rowid`).all().map((r: Json) => JSON.parse(r.json)) : [])
70 const workflows = rows('workflows', 'definition')
71 const models = rows('data_models')
72 const counts: Record<string, number> = {}
73 try {
74 syncSystemModels(models)
75 for (const m of models) await upsertModel(sql, m)
76 counts.models = models.length
77
78 for (const w of workflows) {
79 const revisions = (w.revisions || []).filter(Boolean)
80 normalizeWorkflows([w, ...revisions])
81 await insertWorkflow(sql, w, revisions)
82 }
83 counts.workflows = workflows.length
84
85 const executions = rows('workflow_executions')
86 for (const e of executions) {
87 await sql.query(`
88 INSERT INTO workflow_executions (id, workflow_id, workflow_version, parent_execution_id, task_id, entity_type, entity_id, status, waiting_for, updated_at, data)
89 VALUES (:id, :workflowId, :version, :parentId, :taskId, :entityType, :entityId, :status, :waitingFor, :updatedAt, :data)`, {
90 id: e.id, workflowId: e.workflowId, version: e.workflowVersion ?? null, parentId: e.parentExecutionId ?? null, taskId: e.taskId ?? null,
91 entityType: String(e.entityType || 'warehouse_item'), entityId: String(e.entityId), status: e.status, waitingFor: e.waitingFor ?? null,
92 updatedAt: e.updatedAt || e.startedAt, data: JSON.stringify(e),
93 })
94 }
95 counts.executions = executions.length
96
97 const logs = rows('workflow_execution_logs')
98 for (const l of logs) {
99 await sql.query('INSERT INTO workflow_execution_logs (id, execution_id, created_at, data) VALUES (:id, :executionId, :createdAt, :data)',
100 { id: l.id, executionId: l.executionId, createdAt: l.createdAt, data: JSON.stringify(l) })
101 }
102 counts.logs = logs.length
103
104 const tasks = rows('workflow_tasks')
105 for (const t of tasks) {
106 await sql.query(`
107 INSERT INTO workflow_tasks (id, execution_id, entity_type, entity_id, type, handler_workflow_id, handler_workflow_version, status, updated_at, data)
108 VALUES (:id, :executionId, :entityType, :entityId, :type, :handlerId, :handlerVersion, :status, :updatedAt, :data)`, {
109 id: t.id, executionId: t.executionId ?? null, entityType: String(t.entityType || 'warehouse_item'), entityId: String(t.entityId), type: t.type || 'GENERAL',
110 handlerId: t.handlerWorkflowId ?? null, handlerVersion: t.handlerWorkflowVersion ?? null, status: t.status, updatedAt: t.updatedAt || t.createdAt, data: JSON.stringify(t),
111 })
112 }
113 counts.tasks = tasks.length
114
115 const inbox = rows('inbox_events')
116 for (const i of inbox) {
117 await sql.query(`
118 INSERT INTO inbox_events (event_id, event, entity_type, entity_id, status, payload, result, received_at, processed_at)
119 VALUES (:eventId, :event, :entityType, :entityId, :status, NULL, :result, :receivedAt, :processedAt)`, {
120 eventId: i.eventId, event: i.event, entityType: i.entityType || 'warehouse_item', entityId: i.entityId ?? null,
121 // accepted / processing без збереженої події не відтворити — фіксуємо як failed з поясненням
122 status: ['processed', 'failed'].includes(i.status) ? i.status : 'failed',
123 result: JSON.stringify(['processed', 'failed'].includes(i.status) ? i.result : { processed: 0, code: 'LOST_IN_SQLITE', error: `Event was ${i.status} in SQLite without stored payload` }),
124 receivedAt: i.receivedAt, processedAt: i.processedAt ?? i.receivedAt,
125 })
126 }
127 counts.inbox = inbox.length
128
129 for (const [table, target] of [['outbox_events', 'outbox_events'], ['warehouse_items', 'warehouse_items'], ['warehouse_item_events', 'warehouse_item_events']]) {
130 const list = rows(table)
131 for (const x of list) {
132 if (target === 'outbox_events') await sql.query('INSERT INTO outbox_events (id, event, created_at, data) VALUES (:id, :event, :createdAt, :data)', { id: x.id, event: x.event, createdAt: x.createdAt, data: JSON.stringify(x) })
133 else if (target === 'warehouse_items') await sql.query('INSERT INTO warehouse_items (id, data) VALUES (:id, :data)', { id: String(x.id), data: JSON.stringify(x) })
134 else await sql.query('INSERT INTO warehouse_item_events (id, created_at, data) VALUES (:id, :createdAt, :data)', { id: x.id, createdAt: x.createdAt ?? null, data: JSON.stringify(x) })
135 }
136 counts[table] = list.length
137 }
138 await Catalog.bump(sql)
139 return counts
140 } finally {
141 db.close()
142 }
143}
144