151 lines
4.3 KiB
Python
151 lines
4.3 KiB
Python
from collections import deque
|
|
from django.utils import timezone
|
|
from django.core.exceptions import ValidationError
|
|
from .models import FlowExecutionLog
|
|
|
|
|
|
def validate_flow_dag(graph):
|
|
"""
|
|
Validates that the Vue Flow graph has no cycles and forms a valid DAG using Kahn's algorithm.
|
|
Also validates that all edges point to real node IDs.
|
|
"""
|
|
nodes = graph.get('nodes', [])
|
|
edges = graph.get('edges', [])
|
|
|
|
if not nodes:
|
|
return True
|
|
|
|
node_ids = {n['id'] for n in nodes if 'id' in n}
|
|
|
|
# Build adjacency and in-degree map
|
|
in_degree = {nid: 0 for nid in node_ids}
|
|
adj = {nid: [] for nid in node_ids}
|
|
|
|
for edge in edges:
|
|
src = edge.get('source')
|
|
tgt = edge.get('target')
|
|
|
|
# Dangling edge validation
|
|
if src not in node_ids or tgt not in node_ids:
|
|
raise ValidationError(f"Edge references non-existent node: {src} -> {tgt}")
|
|
|
|
adj[src].append(tgt)
|
|
in_degree[tgt] += 1
|
|
|
|
# Kahn's algorithm
|
|
queue = deque([nid for nid in node_ids if in_degree[nid] == 0])
|
|
visited_count = 0
|
|
|
|
while queue:
|
|
curr = queue.popleft()
|
|
visited_count += 1
|
|
|
|
for neighbor in adj[curr]:
|
|
in_degree[neighbor] -= 1
|
|
if in_degree[neighbor] == 0:
|
|
queue.append(neighbor)
|
|
|
|
if visited_count != len(node_ids):
|
|
raise ValidationError("Workflow graph contains cycles or self-referencing loops.")
|
|
|
|
return True
|
|
|
|
|
|
def topological_sort(graph):
|
|
"""
|
|
Returns ordered list of node IDs to execute in topological DAG sequence.
|
|
"""
|
|
validate_flow_dag(graph)
|
|
|
|
nodes = graph.get('nodes', [])
|
|
edges = graph.get('edges', [])
|
|
node_ids = [n['id'] for n in nodes if 'id' in n]
|
|
|
|
in_degree = {nid: 0 for nid in node_ids}
|
|
adj = {nid: [] for nid in node_ids}
|
|
|
|
for edge in edges:
|
|
src = edge.get('source')
|
|
tgt = edge.get('target')
|
|
adj[src].append(tgt)
|
|
in_degree[tgt] += 1
|
|
|
|
queue = deque([nid for nid in node_ids if in_degree[nid] == 0])
|
|
execution_order = []
|
|
|
|
while queue:
|
|
curr = queue.popleft()
|
|
execution_order.append(curr)
|
|
|
|
for neighbor in adj[curr]:
|
|
in_degree[neighbor] -= 1
|
|
if in_degree[neighbor] == 0:
|
|
queue.append(neighbor)
|
|
|
|
return execution_order
|
|
|
|
|
|
get_topological_execution_order = topological_sort
|
|
|
|
|
|
def execute_flow_dag(flow_def, initial_context=None, idempotency_key=None):
|
|
"""
|
|
Executes a FlowDefinition DAG given context data.
|
|
"""
|
|
if idempotency_key:
|
|
existing = FlowExecutionLog.objects.filter(idempotency_key=idempotency_key).first()
|
|
if existing:
|
|
return existing
|
|
|
|
log = FlowExecutionLog.objects.create(
|
|
flow=flow_def,
|
|
status='running',
|
|
context_data=initial_context or {},
|
|
idempotency_key=idempotency_key
|
|
)
|
|
|
|
try:
|
|
execution_order = topological_sort(flow_def.graph)
|
|
node_map = {n['id']: n for n in flow_def.graph.get('nodes', [])}
|
|
|
|
steps = []
|
|
context = dict(initial_context or {})
|
|
|
|
for node_id in execution_order:
|
|
node = node_map.get(node_id, {})
|
|
node_type = node.get('type')
|
|
node_data = node.get('data', {})
|
|
|
|
step_record = {
|
|
'node_id': node_id,
|
|
'type': node_type,
|
|
'status': 'success'
|
|
}
|
|
|
|
if node_type == 'action':
|
|
action_name = node_data.get('action')
|
|
if action_name == 'update_record':
|
|
field = node_data.get('field')
|
|
val = node_data.get('value')
|
|
context.setdefault('record_data', {})[field] = val
|
|
elif action_name == 'set_stage':
|
|
context['stage'] = node_data.get('stage')
|
|
elif action_name == 'increment_score':
|
|
pts = node_data.get('points', 0)
|
|
context['score'] = context.get('score', 0) + pts
|
|
|
|
steps.append(step_record)
|
|
|
|
log.status = 'completed'
|
|
log.steps_executed = steps
|
|
log.context_data = context
|
|
log.completed_at = timezone.now()
|
|
log.save()
|
|
return log
|
|
|
|
except Exception as e:
|
|
log.status = 'failed'
|
|
log.error_message = str(e)
|
|
log.completed_at = timezone.now()
|
|
log.save()
|
|
raise
|