techtools
Головна / proto / flow-old / server / data-flow.ts

data-flow.ts

TypeScript · 414 рядків

1import { backEdges, forwardIncoming } from '../shared/graph.ts'
2import { validateCondition } from '../shared/condition.ts'
3import { actionOutputSchema } from '../shared/action.ts'
4import { validateApiRequest } from '../shared/api-request.ts'
5import { deriveMappingSchema, validateMapping } from '../shared/mapping.ts'
6import { handlerContextModelId, taskContextModelId, validateTaskConfig } from '../shared/task.ts'
7import { validateFireEventConfig } from '../shared/fire-event.ts'
8import { validateWorkflowContract, workflowContract } from '../shared/workflow-contract.ts'
9import { EVENT_SYSTEM_FIELDS, nestAtPath, startEventData } from '../shared/schema-scopes.ts'
10import { decisionOutputSchema, validateDecisionPorts } from '../shared/decision.ts'
11import { validateScreen } from '../shared/screen.ts'
12
13const primitives = new Set(['string', 'number', 'integer', 'boolean', 'object', 'any', 'null'])
14const apiErrorSchema = {
15  error: {
16    type: 'string',
17    message: 'string',
18    status: 'number',
19    code: 'string',
20    details: 'object',
21    request: { method: 'string', url: 'string' }
22  }
23}
24
25function expand(schema, models, seen = new Set()) {
26  const result = {}
27  for (const [key, value] of Object.entries(schema || {})) {
28    if (typeof value === 'string') {
29      const array = value.endsWith('[]')
30      const type = array ? value.slice(0, -2) : value
31      const model = !primitives.has(type) && models.find(item => item.name === type)
32      if (model && !seen.has(model.id)) {
33        const nested = expand(model.schema, models, new Set([...seen, model.id]))
34        result[key] = array ? [nested] : nested
35      } else {
36        result[key] = value
37      }
38    } else if (value && typeof value === 'object') {
39      result[key] = expand(value, models, seen)
40    }
41  }
42  return result
43}
44
45function modelSchema(id, models) {
46  return expand(models.find(model => model.id === id)?.schema || {}, models)
47}
48
49function eventModelSchema(id, models) {
50  return { ...EVENT_SYSTEM_FIELDS, ...modelSchema(id, models) }
51}
52
53function merge(left, right, issues, path = 'data') {
54  const result = structuredClone(left || {})
55  for (const [key, value] of Object.entries(right || {})) {
56    if (key in result) {
57      if (typeof result[key] === 'object'
58        && typeof value === 'object'
59        && !Array.isArray(result[key])
60        && !Array.isArray(value)) {
61        result[key] = merge(result[key], value, issues, `${path}.${key}`)
62      } else if (result[key] !== value) {
63        issues.push(`${path}.${key}: type conflict (${result[key]} vs ${value})`)
64      }
65    } else {
66      result[key] = structuredClone(value)
67    }
68  }
69  return result
70}
71
72function routeObject(node) {
73  return Array.isArray(node.config?.routes)
74    ? Object.fromEntries(node.config.routes.map(route => [route.port, route.expression]))
75    : node.config?.routes
76}
77
78function validateRoutes(node, schema) {
79  const routes = routeObject(node)
80  const issues = []
81  if (!routes || typeof routes !== 'object' || Array.isArray(routes)) {
82    return [`${node.name}: ports must be a JSON object`]
83  }
84  const entries = Object.entries(routes)
85  if (!entries.length) issues.push(`${node.name}: at least one output port is required`)
86  if (entries.some(([name, value]) => !name.trim() || typeof value !== 'string')) {
87    issues.push(`${node.name}: every port needs a name and string condition`)
88  }
89  if (entries.filter(([, value]) => value === '').length > 1) {
90    issues.push(`${node.name}: only one empty fallback condition is allowed`)
91  }
92  if (entries.filter(([, value]) => value === '$error').length > 1) {
93    issues.push(`${node.name}: only one $error route is allowed`)
94  }
95  if (JSON.stringify(node.outputs?.map(port => port.id) || []) !== JSON.stringify(Object.keys(routes))) {
96    issues.push(`${node.name}: output ports must match config.routes keys`)
97  }
98  for (const [name, expression] of entries) {
99    if (!expression || expression === '$error') continue
100    for (const error of validateCondition(expression, schema).errors) {
101      issues.push(`${node.name} · ${name}: ${error}`)
102    }
103  }
104  return issues
105}
106
107export function validateWorkflowDataFlow(workflow, models, workflows = []) {
108  const issues = []
109  const memo = new Map()
110  const taskSchema = modelSchema('system-task', models)
111  for (const edge of backEdges(workflow)) issues.push(`Cycle detected at node ${edge.target}`)
112  const contextId = workflow.settings?.taskContextModelId
113  if (contextId && !models.some(model => model.id === contextId)) issues.push('Task context model not found')
114  if (workflow.settings?.errorScreen) {
115    // екран помилки за замовчуванням (P7): шаблон бачить data.error.{message, code, block}, task.*, event.*
116    const errorData = { error: { message: 'string', code: 'string', block: 'string' } }
117    const config = { kind: 'error', expect: 'button', tone: 'error', text: 'x', ...workflow.settings.errorScreen }
118    for (const error of validateScreen(config, { data: errorData, task: taskSchema, event: EVENT_SYSTEM_FIELDS })) {
119      issues.push(`TSD error screen: ${error}`)
120    }
121  }
122
123  function inheritedEventSchema(nodeId, seen = new Set()) {
124    if (seen.has(nodeId)) return {}
125    seen.add(nodeId)
126    let result = {}
127    for (const edge of forwardIncoming(workflow, nodeId)) {
128      const source = workflow.nodes.find(candidate => candidate.id === edge.source)
129      const sourceSchema = source?.type === 'EVENT'
130        ? eventModelSchema(source.config?.modelId, models)
131        : inheritedEventSchema(source?.id, new Set(seen))
132      result = merge(result, sourceSchema, issues, 'event')
133    }
134    return result
135  }
136
137  function output(nodeId, portId, stack = new Set()) {
138    const cache = `${nodeId}:${portId}`
139    if (memo.has(cache)) return memo.get(cache)
140    if (stack.has(nodeId)) {
141      issues.push(`Cycle detected at node ${nodeId}`)
142      return {}
143    }
144    stack.add(nodeId)
145
146    const node = workflow.nodes.find(item => item.id === nodeId)
147    if (!node) return {}
148
149    let inherited = {}
150    for (const edge of forwardIncoming(workflow, nodeId)) {
151      const incoming = output(edge.source, edge.sourcePort, new Set(stack))
152      inherited = merge(
153        inherited,
154        node.type === 'TASK_UPDATE' && edge.targetPort === 'task' ? { task: incoming } : incoming,
155        issues
156      )
157    }
158
159    const eventSchema = node.type === 'EVENT'
160      ? eventModelSchema(node.config?.modelId, models)
161      : inheritedEventSchema(node.id)
162    const taskContextSchema = node.type === 'EVENT' && node.config?.activation === 'TASK'
163      ? modelSchema(taskContextModelId(workflow, node), models)
164      : inherited
165    const scopeSchemas = { task: taskSchema, event: eventSchema }
166
167    if (node.type === 'EVENT') {
168      if (!node.config?.event?.trim()) issues.push(`${node.name}: event is required`)
169      if (!node.config?.modelId) issues.push(`${node.name}: model is required`)
170      if (!['START', 'TASK', undefined].includes(node.config?.activation)) {
171        issues.push(`${node.name}: activation must be START or TASK`)
172      }
173      const conditionSchema = {
174        data: taskContextSchema,
175        input: inherited,
176        model: eventSchema,
177        task: taskSchema,
178        event: eventSchema
179      }
180      for (const expression of node.config?.conditions || []) {
181        for (const error of validateCondition(expression, conditionSchema).errors) {
182          issues.push(`${node.name}: ${error}`)
183        }
184      }
185    }
186
187    if (node.type === 'CONDITION') {
188      issues.push(...validateRoutes(node, {
189        data: inherited,
190        task: taskSchema,
191        event: eventSchema
192      }))
193    }
194
195    if (node.type === 'DELAY') {
196      if (!Number.isFinite(Number(node.config?.seconds))
197        || Number(node.config.seconds) < 0
198        || Number(node.config.seconds) > 86400) {
199        issues.push(`${node.name}: seconds must be between 0 and 86400`)
200      }
201      if (['modelId', 'outputModelId', 'responseModelId', 'outputModels']
202        .some(key => key in (node.config || {}))) {
203        issues.push(`${node.name}: Delay does not support a data model`)
204      }
205    }
206
207    if (node.type === 'API_REQUEST') {
208      for (const error of validateApiRequest(node.config, inherited, scopeSchemas).errors) {
209        issues.push(`${node.name}: ${error}`)
210      }
211    }
212
213    if (node.type === 'FIRE_EVENT') {
214      for (const error of validateFireEventConfig(node.config, inherited, scopeSchemas).errors) {
215        issues.push(`${node.name}: ${error}`)
216      }
217    }
218
219    if (node.type === 'SCREEN') {
220      for (const error of validateScreen(node.config, { data: inherited, ...scopeSchemas })) issues.push(`${node.name}: ${error}`)
221      if (node.outputs?.length) issues.push(`${node.name}: SCREEN must be terminal`)
222    }
223
224    if (node.type === 'DECISION') {
225      for (const error of validateDecisionPorts(node)) issues.push(`${node.name}: ${error}`)
226      const decision = decisionOutputSchema(node.config, inherited, scopeSchemas)
227      for (const error of decision.errors) issues.push(`${node.name}: ${error}`)
228      memo.set(cache, decision.schema)
229      return decision.schema
230    }
231
232    if (node.type === 'CLIENT_RESPONSE') {
233      const status = Number(node.config?.status || 200)
234      if (!Number.isInteger(status) || status < 100 || status > 599) {
235        issues.push(`${node.name}: status must be an integer from 100 to 599`)
236      }
237      for (const error of validateMapping(
238        node.config?.mapping || { $copy: 'data' },
239        inherited,
240        scopeSchemas
241      ).errors) {
242        issues.push(`${node.name}: ${error}`)
243      }
244      if (node.outputs?.length) issues.push(`${node.name}: CLIENT_RESPONSE must be terminal`)
245    }
246
247    if (node.type === 'WORKFLOW_INPUT' && !node.config?.modelId) {
248      issues.push(`${node.name}: input contract model is required`)
249    }
250
251    if (node.type === 'WORKFLOW_OUTPUT') {
252      if (!node.config?.port?.trim()) issues.push(`${node.name}: output port name is required`)
253      if (['modelId', 'mapping', 'outputModelId'].some(key => key in (node.config || {}))) {
254        issues.push(`${node.name}: WORKFLOW_OUTPUT passes input data as-is and does not support model or mapping`)
255      }
256    }
257
258    if (node.type === 'WORKFLOW') {
259      const contract = workflowContract(
260        workflows.find(item => item.id === node.config?.workflowId),
261        models
262      )
263      for (const error of [
264        ...contract.errors,
265        ...validateWorkflowContract(inherited, contract.input).errors
266      ]) {
267        issues.push(`${node.name}: ${error}`)
268      }
269      if ('inputMapping' in (node.config || {})) {
270        issues.push(`${node.name}: WORKFLOW does not support inputMapping; use a MAPPING block`)
271      }
272      const result = contract.outputs[portId] || {}
273      memo.set(cache, result)
274      return result
275    }
276
277    if (['TASK', 'TASK_UPDATE'].includes(node.type)) {
278      const handlerContextId = node.type === 'TASK'
279        ? handlerContextModelId(workflow, workflows, node.config)
280        : null
281      if (handlerContextId && !models.some(model => model.id === handlerContextId)) {
282        issues.push(`${node.name}: handler task context model not found`)
283      }
284      for (const error of validateTaskConfig(
285        node.config,
286        inherited,
287        node.type === 'TASK_UPDATE',
288        scopeSchemas,
289        handlerContextId ? modelSchema(handlerContextId, models) : null,
290        models.find(model => model.id === handlerContextId)?.defaults || null
291      ).errors) {
292        issues.push(`${node.name}: ${error}`)
293      }
294      if (node.type === 'TASK' && node.config?.handlerWorkflowId) {
295        const reference = String(node.config.handlerWorkflowId).trim()
296        const idMatch = workflows.find(candidate => candidate.id === reference)
297        const nameMatches = workflows.filter(candidate => candidate.name === reference)
298        if (!idMatch && !nameMatches.length) {
299          issues.push(`${node.name}: handler workflow not found`)
300        } else if (!idMatch && nameMatches.length > 1) {
301          issues.push(`${node.name}: handler workflow name is ambiguous`)
302        }
303      }
304      if (node.type === 'TASK' && node.config?.itemsPath
305        && workflow.edges.some(edge =>
306          edge.source === node.id && edge.sourcePort === 'task'
307        )) {
308        issues.push(`${node.name}: batch TASK cannot connect the task output`)
309      }
310      const result = portId === 'task'
311        ? taskSchema
312        : merge(inherited, node.config?.itemsPath ? { tasks: [taskSchema] } : { task: taskSchema }, issues)
313      memo.set(cache, result)
314      return result
315    }
316
317    if (node.type === 'API_REQUEST' && portId === 'error') {
318      const result = merge(
319        inherited,
320        { error: modelSchema(node.config?.errorModelId || 'system-api-error', models) || apiErrorSchema.error },
321        issues
322      )
323      memo.set(cache, result)
324      return result
325    }
326
327    if (node.type === 'CONDITION' && routeObject(node)?.[portId] === '$error') {
328      const result = merge(
329        inherited,
330        { error: modelSchema('system-workflow-error', models) },
331        issues
332      )
333      memo.set(cache, result)
334      return result
335    }
336
337    if (node.type === 'ACTION') {
338      const action = actionOutputSchema(node.config, inherited, scopeSchemas)
339      for (const error of action.errors) issues.push(`${node.name} · ${error}`)
340      memo.set(cache, action.schema)
341      return action.schema
342    }
343
344    if (node.type === 'MAPPING') {
345      const mapping = node.config?.mapping || { $copy: 'data' }
346      const result = deriveMappingSchema(mapping, inherited, scopeSchemas)
347      for (const error of validateMapping(mapping, inherited, scopeSchemas).errors) {
348        issues.push(`${node.name}: ${error}`)
349      }
350      if ('outputModelId' in (node.config || {})) {
351        issues.push(`${node.name}: MAPPING does not support a data model`)
352      }
353      memo.set(cache, result)
354      return result
355    }
356
357    let result = inherited
358    if (node.type === 'EVENT') {
359      result = node.config?.activation === 'TASK'
360        ? taskContextSchema
361        : merge(inherited, startEventData(eventSchema), issues)
362    } else {
363      const modelId = node.config?.outputModels?.[portId]
364        || (node.type === 'WORKFLOW_INPUT' ? node.config?.modelId : null)
365        || (node.type === 'API_REQUEST'
366          ? node.config?.modelId || node.config?.responseModelId
367          : null)
368      const added = node.type === 'API_REQUEST'
369        ? nestAtPath(modelSchema(modelId, models), node.config?.resultPath)
370        : modelSchema(modelId, models)
371      result = merge(inherited, added, issues)
372    }
373
374    memo.set(cache, result)
375    return result
376  }
377
378  for (const node of workflow.nodes) {
379    if (['CLIENT_RESPONSE', 'SCREEN'].includes(node.type)) output(node.id, '')
380    for (const port of node.outputs || []) output(node.id, port.id)
381  }
382
383  // G3: умова на ребрі. З одного порту рушій іде першим ребром, чия умова істинна (згори вниз, як routes у CONDITION),
384  // інакше — ребром без умови (fallback). Двох ребер без умови з одного порту бути не може: друге ніколи не виконається.
385  const byPort = new Map()
386  for (const edge of workflow.edges || []) {
387    const key = JSON.stringify([edge.source, edge.sourcePort])
388    if (!byPort.has(key)) byPort.set(key, [])
389    byPort.get(key).push(edge)
390  }
391  for (const edges of byPort.values()) {
392    const source = workflow.nodes.find(node => node.id === edges[0].source)
393    if (!source) continue
394    const port = edges[0].sourcePort
395    const plain = edges.filter(edge => !String(edge.condition || '').trim())
396    if (plain.length > 1) {
397      issues.push(`${source.name}: port "${port}" has ${plain.length} connectors without a condition — only the first one runs; set a condition on every connector except one fallback, or chain the blocks`)
398    }
399    const conditioned = edges.filter(edge => String(edge.condition || '').trim())
400    if (!conditioned.length) continue
401    const schema = {
402      data: output(source.id, port),
403      task: taskSchema,
404      event: source.type === 'EVENT' ? eventModelSchema(source.config?.modelId, models) : inheritedEventSchema(source.id)
405    }
406    for (const edge of conditioned) {
407      for (const error of validateCondition(String(edge.condition).trim(), schema).errors) {
408        issues.push(`Connector ${edge.id}: condition: ${error}`)
409      }
410    }
411  }
412  return [...new Set(issues)]
413}
414