File size: 8,276 Bytes
ea3ef49 09f67be ea3ef49 52cd762 8628c98 52cd762 ea3ef49 52cd762 ea3ef49 52cd762 f2936a1 91b4202 f2936a1 52cd762 f2936a1 52cd762 ea3ef49 8628c98 ea3ef49 52cd762 ea3ef49 52cd762 ea3ef49 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | """
ALLI Lambda Function 4: Workflow Persistence (alli-workflows)
CRUD operations for workflow graphs in MongoDB Atlas, with resilient in-memory fallback and DynamoDB readiness.
"""
import json
from typing import Dict, Any, List, Optional
from database.mongo import workflow_repo
def validate_workflow_document_logic(data: Dict[str, Any]) -> Dict[str, Any]:
"""
Phase 3.8.5: Validates restored workflow document data integrity.
Verifies schema version, unique node IDs, valid edge references, deduplication, and viewport.
"""
errors: List[str] = []
warnings: List[str] = []
if not isinstance(data, dict):
return {"valid": False, "errors": ["Workflow document must be a JSON object."], "warnings": []}
name = data.get("name")
if not name or not str(name).strip():
errors.append("Workflow 'name' is required.")
schema_version = data.get("schema_version", "3.0.0")
supported_versions = {"1.0.0", "2.0.0", "2.1.0", "3.0.0"}
if schema_version not in supported_versions:
warnings.append(f"Unrecognized schema_version '{schema_version}'. Compatibility layer active.")
nodes = data.get("nodes") or []
if not isinstance(nodes, list):
errors.append("'nodes' must be a list.")
nodes = []
node_ids = set()
for idx, node in enumerate(nodes):
if not isinstance(node, dict):
errors.append(f"Node at index {idx} is malformed.")
continue
nid = node.get("id")
if not nid or not str(nid).strip():
errors.append(f"Node at index {idx} is missing a valid 'id'.")
elif nid in node_ids:
errors.append(f"Duplicate node ID detected: '{nid}'.")
else:
node_ids.add(nid)
edges = data.get("edges") or []
if not isinstance(edges, list):
errors.append("'edges' must be a list.")
edges = []
seen_connections = set()
sanitized_edges = []
for idx, edge in enumerate(edges):
if not isinstance(edge, dict):
warnings.append(f"Edge at index {idx} is malformed and was omitted.")
continue
src = edge.get("source") or edge.get("from_node")
tgt = edge.get("target") or edge.get("to_node")
src_h = edge.get("sourceHandle") or edge.get("source_handle") or "out"
tgt_h = edge.get("targetHandle") or edge.get("target_handle") or "in"
if not src or not tgt:
warnings.append(f"Edge '{edge.get('id', idx)}' is missing endpoints and was dropped.")
continue
if src not in node_ids:
warnings.append(f"Edge '{edge.get('id', idx)}' references non-existent source node '{src}' and was pruned.")
continue
if tgt not in node_ids:
warnings.append(f"Edge '{edge.get('id', idx)}' references non-existent target node '{tgt}' and was pruned.")
continue
if src == tgt:
warnings.append(f"Edge '{edge.get('id', idx)}' is a self-loop on node '{src}' and was pruned.")
continue
pair_key = (src, src_h, tgt, tgt_h)
if pair_key in seen_connections:
warnings.append(f"Duplicate edge [{src}:{src_h}] -> [{tgt}:{tgt_h}] was deduplicated.")
continue
seen_connections.add(pair_key)
sanitized_edges.append(edge)
viewport = data.get("viewport")
if viewport and isinstance(viewport, dict):
z = viewport.get("zoom", 1.0)
if not isinstance(z, (int, float)) or z <= 0:
warnings.append("Malformed viewport zoom reset to 1.0.")
return {
"valid": len(errors) == 0,
"errors": errors,
"warnings": warnings,
"schema_version": schema_version,
"node_count": len(node_ids),
"edge_count": len(sanitized_edges),
}
def save_workflow_logic(data: Dict[str, Any]) -> Dict[str, Any]:
validation = validate_workflow_document_logic(data)
if not validation["valid"]:
raise ValueError(f"Workflow schema validation failed: {'; '.join(validation['errors'])}")
wf_id = workflow_repo.save_workflow(data)
return {"id": wf_id, "status": "saved", "validation": validation}
def update_workflow_logic(workflow_id: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
existing = workflow_repo.get_workflow(workflow_id)
if not existing:
return None
merged = {**existing, **data, "id": workflow_id}
if not merged.get("created_at"):
merged["created_at"] = existing.get("created_at")
if not merged.get("source_template_id") and existing.get("source_template_id"):
merged["source_template_id"] = existing.get("source_template_id")
if not merged.get("user_id") and existing.get("user_id"):
merged["user_id"] = existing.get("user_id")
validation = validate_workflow_document_logic(merged)
if not validation["valid"]:
raise ValueError(f"Workflow schema validation failed: {'; '.join(validation['errors'])}")
workflow_repo.save_workflow(merged)
return workflow_repo.get_workflow(workflow_id)
def get_workflow_logic(workflow_id: str) -> Optional[Dict[str, Any]]:
return workflow_repo.get_workflow(workflow_id)
def list_workflows_logic(user_id: Optional[str] = None, org_id: Optional[str] = None) -> List[Dict[str, Any]]:
return workflow_repo.list_workflows(user_id=user_id, org_id=org_id)
def delete_workflow_logic(workflow_id: str) -> bool:
return workflow_repo.delete_workflow(workflow_id)
def handler(event: Dict[str, Any], context: Any = None) -> Dict[str, Any]:
"""Standalone AWS Lambda handler entrypoint for alli-workflows function."""
http_method = event.get("httpMethod") or event.get("requestContext", {}).get("http", {}).get("method", "GET")
path = event.get("path") or event.get("rawPath", "/workflows")
query_params = event.get("queryStringParameters") or {}
headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
}
try:
body_raw = event.get("body", "{}")
if isinstance(body_raw, str):
body = json.loads(body_raw) if body_raw else {}
else:
body = body_raw
# Extract workflow ID from path if present (e.g. /workflows/abc-123)
parts = [p for p in path.split("/") if p]
wf_id = parts[1] if len(parts) > 1 and parts[0] == "workflows" else None
if http_method == "POST":
res = save_workflow_logic(body)
return {"statusCode": 200, "headers": headers, "body": json.dumps(res)}
elif http_method in ("PUT", "PATCH") and wf_id:
res = update_workflow_logic(wf_id, body)
if not res:
return {"statusCode": 404, "headers": headers, "body": json.dumps({"error": "Workflow not found"})}
return {"statusCode": 200, "headers": headers, "body": json.dumps(res)}
elif http_method == "GET":
if wf_id:
doc = get_workflow_logic(wf_id)
if not doc:
return {"statusCode": 404, "headers": headers, "body": json.dumps({"error": "Workflow not found"})}
return {"statusCode": 200, "headers": headers, "body": json.dumps(doc)}
else:
user_id = query_params.get("user_id")
docs = list_workflows_logic(user_id=user_id)
return {"statusCode": 200, "headers": headers, "body": json.dumps(docs)}
elif http_method == "DELETE" and wf_id:
success = delete_workflow_logic(wf_id)
if not success:
return {"statusCode": 404, "headers": headers, "body": json.dumps({"error": "Workflow not found"})}
return {"statusCode": 200, "headers": headers, "body": json.dumps({"status": "deleted"})}
elif http_method == "OPTIONS":
return {"statusCode": 200, "headers": headers, "body": json.dumps({"status": "ok"})}
return {"statusCode": 405, "headers": headers, "body": json.dumps({"error": f"Method {http_method} not allowed"})}
except Exception as err:
return {"statusCode": 500, "headers": headers, "body": json.dumps({"error": str(err)})}
|