from django.db import models, transaction from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from .models import FlowDefinition, FlowExecutionLog from .serializers import FlowDefinitionSerializer, FlowExecutionLogSerializer from .engine import execute_flow_dag from openforce.permissions import ScopedOwnerAccessPermission class FlowDefinitionViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission] queryset = FlowDefinition.objects.all() serializer_class = FlowDefinitionSerializer def get_queryset(self): qs = super().get_queryset() user = self.request.user if not user or not user.is_authenticated: return qs.none() if user.is_superuser or user.is_staff: return qs if hasattr(FlowDefinition, 'created_by'): return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True)) return qs def perform_create(self, serializer): kwargs = {} if hasattr(FlowDefinition, 'created_by'): kwargs['created_by'] = self.request.user serializer.save(**kwargs) @action(detail=True, methods=['post'], url_path='execute') def execute(self, request, pk=None): flow = self.get_object() initial_context = request.data.get('context', {}) idempotency_key = request.data.get('idempotency_key') user = request.user if request.user and request.user.is_authenticated else None # Check existing idempotency key before attempting new execution if idempotency_key: existing_log = FlowExecutionLog.objects.filter(flow=flow, idempotency_key=idempotency_key).first() if existing_log: if existing_log.status == 'failed': return Response( { 'status': 'failed', 'error': existing_log.error_message, 'log': FlowExecutionLogSerializer(existing_log).data }, status=status.HTTP_400_BAD_REQUEST ) data = FlowExecutionLogSerializer(existing_log).data data['context_data'] = existing_log.context_data data['status'] = existing_log.status return Response(data, status=status.HTTP_200_OK) # Allocate distinct execution log for this attempt outside the mutation savepoint current_log = FlowExecutionLog.objects.create( flow=flow, status='running', context_data=initial_context or {}, idempotency_key=idempotency_key ) sid = transaction.savepoint() try: execution_log = execute_flow_dag( flow, initial_context=initial_context, idempotency_key=idempotency_key, user=user, execution_log=current_log ) if execution_log and execution_log.status == 'failed': transaction.savepoint_rollback(sid) current_log.status = 'failed' current_log.error_message = execution_log.error_message current_log.save() return Response( { 'status': 'failed', 'error': current_log.error_message, 'log': FlowExecutionLogSerializer(current_log).data }, status=status.HTTP_400_BAD_REQUEST ) transaction.savepoint_commit(sid) except Exception as e: transaction.savepoint_rollback(sid) current_log.status = 'failed' current_log.error_message = str(e) current_log.save() return Response( { 'status': 'failed', 'error': str(e), 'log': FlowExecutionLogSerializer(current_log).data }, status=status.HTTP_400_BAD_REQUEST ) # Refetch completed log state current_log.refresh_from_db() data = FlowExecutionLogSerializer(current_log).data data['context_data'] = current_log.context_data data['status'] = current_log.status return Response( data, status=status.HTTP_200_OK ) class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAuthenticated] queryset = FlowExecutionLog.objects.all() serializer_class = FlowExecutionLogSerializer def get_queryset(self): qs = super().get_queryset() user = self.request.user if not user or not user.is_authenticated: return qs if user.is_superuser or user.is_staff: return qs if hasattr(FlowDefinition, 'created_by'): return qs.filter(flow__created_by=user) return qs