rsnarsna
feat(alli-backend): Wave-1 standardization, standalone sys.env node & vault crypto, and DEC-014 security hardening
8628c98 Download lambdas/workflows_handler.py from Rsnarsna/auto: direct link, hf CLI and curl.
- Browser
- Download file 8.28 kB
-
https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/workflows_handler.py
- Command line
-
hf download hf://spaces/Rsnarsna/auto/lambdas/workflows_handler.py
-
curl -L -o workflows_handler.py https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/workflows_handler.py
8.28 kB
| """ | |
| 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)})} | |