techtools

index.ts

TypeScript · 219 рядків

1// HTTP API flow — ті самі маршрути й відповіді, що в SQLite-версії; дані — PostgreSQL (R-12.17), кожна подія — транзакція (flow.ts).
2// Нове: POST /api/workflows/:id/publish, DELETE /api/workflows/:id/draft, GET /api/workflows/:id/versions (G9);
3// GET /api/notifications (цикли LOOP_LIMIT, R-12.21); async-події й FIRE_EVENT переживають рестарт (dispatch.ts).
4//
5// Запуск: node server/index.ts [--port 3002]   (DATABASE_URL — інакше postgres://flow:flow@127.0.0.1:55434/flow; порт — --port, FLOW_API_PORT, PORT або 3002)
6import express from 'express'
7import cors from 'cors'
8import path from 'node:path'
9import { fileURLToPath } from 'node:url'
10import { parseArgs } from 'node:util'
11import type { Server } from 'node:http'
12import { Database } from './db.ts'
13import { DEFAULT_DATABASE_URL, ensureDatabase, migrate } from './migrate.ts'
14import { Flow } from './flow.ts'
15import { startDispatcher } from './dispatch.ts'
16import { bootstrap } from './bootstrap.ts'
17import { HttpError, deleteModel, deleteWorkflow, discardDraft, getEditor, listEditor, listModels, publish, saveDraft, saveModel, validateDraft, versions } from './workflows.ts'
18import { queryExternalTasks, queryTasks } from '../shared/task-list.ts'
19import { normalizeExternalEvent } from '../shared/external-event.ts'
20import { stubRouter } from './wms-stub.ts'
21import { services } from './engine.ts'
22
23type Json = any
24
25const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
26
27export function createApp(flow: Flow): express.Express {
28  const db = flow.db
29  const app = express()
30  app.use(cors())
31  app.use(express.json({ limit: '2mb' }))
32
33  /** Обробник з єдиною обробкою помилок HttpError і помилок бази. */
34  const route = (fn: (req: express.Request, res: express.Response) => Promise<unknown>) => async (req: express.Request, res: express.Response) => {
35    try {
36      await fn(req, res)
37    } catch (error) {
38      if (error instanceof HttpError) return void res.status(error.status).json(error.body)
39      console.error(error)
40      res.status(400).json({ error: (error as Error).message })
41    }
42  }
43  const tasks = async (): Promise<Json[]> => (await db.sql().query<{ data: Json }>('SELECT data FROM workflow_tasks ORDER BY updated_at')).map((r) => r.data)
44
45  app.get('/api/health', route(async (_, res) => {
46    await db.sql().query('SELECT 1')
47    res.json({ ok: true, storage: 'postgres', time: new Date().toISOString() })
48  }))
49
50  // ---------- workflows ----------
51  app.get('/api/workflows', route(async (_, res) => { res.json(await listEditor(db.sql())) }))
52  app.get('/api/workflows/:id', route(async (req, res) => {
53    const workflow = await getEditor(db.sql(), req.params.id as string)
54    if (workflow) res.json(workflow)
55    else res.status(404).json({ error: 'Not found' })
56  }))
57  app.post('/api/workflows/validate', route(async (req, res) => { res.json(await validateDraft(db.sql(), req.body)) }))
58  app.post('/api/workflows', route(async (req, res) => { res.status(201).json(await db.transaction((sql) => saveDraft(sql, req.body, null))) }))
59  app.put('/api/workflows/:id', route(async (req, res) => { res.json(await db.transaction((sql) => saveDraft(sql, req.body, req.params.id as string))) }))
60  app.post('/api/workflows/:id/publish', route(async (req, res) => { res.json(await db.transaction((sql) => publish(sql, req.params.id as string))) }))
61  app.delete('/api/workflows/:id/draft', route(async (req, res) => { res.json(await db.transaction((sql) => discardDraft(sql, req.params.id as string))) }))
62  app.get('/api/workflows/:id/versions', route(async (req, res) => { res.json(await versions(db.sql(), req.params.id as string)) }))
63  app.delete('/api/workflows/:id', route(async (req, res) => {
64    await db.transaction((sql) => deleteWorkflow(sql, req.params.id as string))
65    res.status(204).end()
66  }))
67
68  // ---------- models ----------
69  app.get('/api/models', route(async (_, res) => { res.json(await listModels(db.sql())) }))
70  app.get('/api/models/:id', route(async (req, res) => {
71    const model = (await listModels(db.sql())).find((item) => item.id === req.params.id)
72    if (model) res.json(model)
73    else res.status(404).json({ error: 'Model not found' })
74  }))
75  app.post('/api/models', route(async (req, res) => { res.status(201).json(await db.transaction((sql) => saveModel(sql, req.body, req.body?.id || null))) }))
76  app.put('/api/models/:id', route(async (req, res) => { res.json(await db.transaction((sql) => saveModel(sql, req.body, req.params.id as string))) }))
77  app.delete('/api/models/:id', route(async (req, res) => {
78    await db.transaction((sql) => deleteModel(sql, req.params.id as string))
79    res.status(204).end()
80  }))
81
82  // ---------- executions ----------
83  app.get('/api/executions', route(async (req, res) => {
84    const rows = await db.sql().query<{ data: Json }>(`
85      SELECT data FROM workflow_executions WHERE (:workflowId::text IS NULL OR workflow_id = :workflowId) ORDER BY updated_at DESC LIMIT 500`,
86    { workflowId: (req.query.workflowId as string) || null })
87    res.json(rows.map((r) => r.data))
88  }))
89  app.get('/api/executions/:id', route(async (req, res) => {
90    const [execution] = await db.sql().query<{ data: Json }>('SELECT data FROM workflow_executions WHERE id = :id', { id: req.params.id })
91    if (!execution) return void res.status(404).json({ error: 'Not found' })
92    const logs = await db.sql().query<{ data: Json }>('SELECT data FROM workflow_execution_logs WHERE execution_id = :id ORDER BY seq', { id: req.params.id })
93    res.json({ ...execution.data, logs: logs.map((l) => l.data) })
94  }))
95  app.post('/api/workflows/:id/execute', async (req, res) => {
96    try {
97      res.status(201).json(await flow.start(req.params.id, req.body))
98    } catch (error) {
99      res.status(400).json({ error: (error as Error).message, code: (error as Json).code })
100    }
101  })
102
103  // ---------- events ----------
104  async function fireEvent(req: express.Request, res: express.Response, external = false) {
105    try {
106      const responseMode = req.query.responseMode === 'sync' ? 'sync' : 'async'
107      if (responseMode === 'async') {
108        const accepted = await flow.enqueue(req.body)
109        return void res.status(202).json(external ? { status: accepted.status } : accepted)
110      }
111      const result = await flow.trigger(req.body)
112      if (result.response) return void res.status(result.response.status).json(result.response.body)
113      if (!result.processed) {
114        const status = result.code === 'NO_ACTIVE_TASK' ? 404 : 409
115        return void res.status(status).json({ code: result.code })
116      }
117      return void res.status(204).end()
118    } catch (error) {
119      const code = (error as Json).code
120      const status = code === 'ENTITY_ALREADY_HAS_ACTIVE_TASK' || code === 'LOOP_LIMIT' ? 409 : 400
121      return void res.status(status).json({ code: code || 'EVENT_PROCESSING_FAILED', error: (error as Error).message })
122    }
123  }
124  app.post('/api/events', (req, res) => fireEvent(req, res))
125  app.post('/api/external/v1/events', (req, res) => {
126    try {
127      req.body = normalizeExternalEvent(req.body)
128      return fireEvent(req, res, true)
129    } catch (error) {
130      return void res.status(400).json({ code: 'INVALID_EVENT', error: (error as Error).message })
131    }
132  })
133
134  // ---------- tasks ----------
135  app.get('/api/tasks', route(async (req, res) => {
136    res.json(queryTasks(await tasks(), { scope: req.query.scope, query: req.query.query, type: req.query.type, sort: req.query.sort, direction: req.query.direction }))
137  }))
138  app.get('/api/external/v1/tasks', route(async (req, res) => { res.json(queryExternalTasks(await tasks(), req.query)) }))
139  app.get('/api/external/v1/tasks/:taskId', route(async (req, res) => {
140    const task = queryExternalTasks(await tasks(), { taskId: req.params.taskId }).tasks[0]
141    if (!task) return void res.status(404).json({ code: 'TASK_NOT_FOUND', error: 'Task not found' })
142    res.json(task)
143  }))
144
145  // ---------- notifications (R-12.21) ----------
146  app.get('/api/notifications', route(async (req, res) => {
147    res.json(await db.sql().query(`
148      SELECT id, kind, workflow_id AS "workflowId", workflow_version AS "workflowVersion", task_id AS "taskId", event_id AS "eventId",
149             message, details, created_at AS "createdAt", delivered_at AS "deliveredAt"
150      FROM notifications WHERE (:workflowId::text IS NULL OR workflow_id = :workflowId) ORDER BY id DESC LIMIT 200`,
151    { workflowId: (req.query.workflowId as string) || null }))
152  }))
153  app.post('/api/notifications/ack', route(async (req, res) => {
154    const r = await db.sql().query('UPDATE notifications SET delivered_at = now() WHERE id <= :upTo AND delivered_at IS NULL RETURNING id', { upTo: Number(req.body?.upTo || 0) })
155    res.json({ acked: r.length })
156  }))
157
158  // ---------- docs & dashboard ----------
159  app.get('/openapi.yaml', (_, res) => { res.type('application/yaml').sendFile(path.join(root, 'openapi.yaml')) })
160  app.get(['/api-docs', '/api-docs/'], (_, res) => {
161    res.type('html').send(`<!doctype html>
162<html><head><title>FLOW External API</title>
163<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css"></head>
164<body><div id="swagger-ui"></div>
165<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
166<script>SwaggerUIBundle({url:'/openapi.yaml',dom_id:'#swagger-ui',deepLinking:true})</script>
167</body></html>`)
168  })
169  app.get('/api/dashboard', route(async (_, res) => {
170    const q = (text: string) => db.sql().query<{ data: Json }>(text).then((rows) => rows.map((r) => r.data))
171    res.json({
172      executions: await q('SELECT data FROM workflow_executions ORDER BY updated_at DESC LIMIT 500'),
173      tasks: await tasks(),
174      items: await q('SELECT data FROM warehouse_items'),
175      events: (await q('SELECT data FROM warehouse_item_events ORDER BY created_at DESC LIMIT 20')).reverse(),
176      outbox: (await q('SELECT data FROM outbox_events ORDER BY created_at DESC LIMIT 20')).reverse(),
177    })
178  }))
179
180  // заглушка WMS / ERP для прогону приймання (R-23 §9)
181  app.use('/stub', stubRouter(flow))
182
183  app.use('/api', (req, res) => { res.status(404).json({ error: `API endpoint not found: ${req.method} ${req.originalUrl}` }) })
184  app.use(express.static(path.join(root, 'dist')))
185  app.get('*path', (_, res) => { res.sendFile(path.join(root, 'dist', 'index.html')) })
186  return app
187}
188
189export interface StartOptions { databaseUrl?: string; database?: string | null; recreate?: boolean; port?: number; dispatch?: boolean; bootstrap?: boolean }
190
191/** База, міграції, початкове заповнення, сервер і диспетчер. */
192export async function startServer(o: StartOptions = {}) {
193  const url = await ensureDatabase(o.databaseUrl ?? process.env.DATABASE_URL ?? DEFAULT_DATABASE_URL, o.database ?? null, o.recreate ?? false)
194  const db = await Database.connect(url, 20)
195  const applied = await migrate(db.pool)
196  if (applied.length) console.log(`migrations: ${applied.join(', ')}`)
197  if (o.bootstrap !== false) {
198    const how = await db.transaction((sql) => bootstrap(sql))
199    if (how !== 'existing') console.log(`database: ${how}`)
200  }
201  const flow = new Flow(db)
202  const dispatcher = o.dispatch === false ? null : startDispatcher(flow)
203  const app = createApp(flow)
204  const server = await new Promise<Server>((resolve) => { const s = app.listen(o.port ?? 3002, () => resolve(s)) })
205  const port = (server.address() as Json).port
206  services.base = `http://127.0.0.1:${port}`
207  return {
208    flow, db, server, dispatcher, url: `http://127.0.0.1:${port}`,
209    stop: async () => { dispatcher?.stop(); await dispatcher?.idle(); await new Promise((r) => server.close(r)); await db.close() },
210  }
211}
212
213if (import.meta.main) {
214  // FLOW_API_PORT важливіший за PORT: у розробці його бачить і проксі Vite, навіть якщо середовище задає PORT для Vite
215  const { values } = parseArgs({ options: { port: { type: 'string' } } })
216  const { url } = await startServer({ port: Number(values.port ?? process.env.FLOW_API_PORT ?? process.env.PORT ?? 3002) })
217  console.log(`WMS Flow API ${url.replace('127.0.0.1', 'localhost')}`)
218}
219