# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

from ai.stigmer.agentic.workflowexecution.v1 import api_pb2 as ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2
from ai.stigmer.agentic.workflowexecution.v1 import io_pb2 as ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2


class WorkflowExecutionQueryControllerStub(object):
    """WorkflowExecutionQueryController handles read operations (Get, List, Subscribe) for WorkflowExecution resources.

    This service follows the Command-Query Separation (CQS) pattern:
    - CommandController: Write operations (create, update, delete)
    - QueryController: Read operations (get, list, search, subscribe)

    Authorization:
    - get: Standard authorization - user must have "get" permission on the specific WorkflowExecution
    - list: Custom authorization - filters results based on user's owner scope and permissions
    - list_by_workflow: Custom authorization - verifies user has access to the Workflow/WorkflowInstance
    - subscribe: Standard authorization - user must have "get" permission to subscribe to updates

    Service Options:
    - api_resource_kind: workflow_execution - Links this service to the WorkflowExecution resource
    """

    def __init__(self, channel):
        """Constructor.

        Args:
            channel: A grpc.Channel.
        """
        self.get = channel.unary_unary(
                '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/get',
                request_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionId.SerializeToString,
                response_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2.WorkflowExecution.FromString,
                _registered_method=True)
        self.list = channel.unary_unary(
                '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/list',
                request_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.ListWorkflowExecutionsRequest.SerializeToString,
                response_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionList.FromString,
                _registered_method=True)
        self.listByWorkflow = channel.unary_unary(
                '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/listByWorkflow',
                request_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.ListWorkflowExecutionsByWorkflowRequest.SerializeToString,
                response_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionList.FromString,
                _registered_method=True)
        self.subscribe = channel.unary_stream(
                '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/subscribe',
                request_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.SubscribeWorkflowExecutionRequest.SerializeToString,
                response_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2.WorkflowExecution.FromString,
                _registered_method=True)


class WorkflowExecutionQueryControllerServicer(object):
    """WorkflowExecutionQueryController handles read operations (Get, List, Subscribe) for WorkflowExecution resources.

    This service follows the Command-Query Separation (CQS) pattern:
    - CommandController: Write operations (create, update, delete)
    - QueryController: Read operations (get, list, search, subscribe)

    Authorization:
    - get: Standard authorization - user must have "get" permission on the specific WorkflowExecution
    - list: Custom authorization - filters results based on user's owner scope and permissions
    - list_by_workflow: Custom authorization - verifies user has access to the Workflow/WorkflowInstance
    - subscribe: Standard authorization - user must have "get" permission to subscribe to updates

    Service Options:
    - api_resource_kind: workflow_execution - Links this service to the WorkflowExecution resource
    """

    def get(self, request, context):
        """Get a single workflow execution by ID.

        Retrieves the complete WorkflowExecution resource including:
        - spec: User inputs (workflow_instance_id, trigger_message, etc.)
        - status: Current execution state (phase, tasks, progress_events, output/error)
        - metadata: Resource identification (id, name, labels, tags)

        Authorization:
        Standard authorization checks that user has "get" permission on the WorkflowExecution.
        Permission is granted if:
        - User created the execution (metadata.audit.created_by matches user)
        - User has organization-level "workflow_execution:get" permission
        - User has explicit permission via IamPolicy

        Use Cases:

        1. View Execution Details:
        - User clicks on an execution in the UI
        - UI calls get() to fetch full details
        - UI displays execution status, tasks, progress, output/error

        2. Poll for Completion:
        - Client triggers execution via create()
        - Client periodically calls get() to check if phase is terminal
        - Client retrieves output when phase == EXECUTION_COMPLETED

        3. Debug Failed Execution:
        - User sees execution failed
        - User calls get() to inspect status.error and status.tasks
        - User checks status.tasks[] for task-level execution details

        4. Retry Failed Execution:
        - User calls get() to retrieve failed execution's spec
        - User creates new execution with same spec values
        - New execution retries with identical inputs

        Error Cases:

        - NOT_FOUND:
        - No WorkflowExecution exists with the given ID

        - PERMISSION_DENIED:
        - User doesn't have "get" permission on this WorkflowExecution
        - WorkflowExecution belongs to different organization

        Example Request:
        {
        "value": "wfx-abc123xyz456"
        }

        Example Response:
        {
        "api_version": "agentic.stigmer.ai/v1",
        "kind": "WorkflowExecution",
        "metadata": {
        "id": "wfx-abc123xyz456",
        "name": "customer-onboarding-20250111-143022",
        "org": "acme"
        },
        "spec": {
        "workflow_instance_id": "wfi-customer-onboarding-prod",
        "trigger_message": "New signup: john.doe@example.com"
        },
        "status": {
        "phase": 2,  // EXECUTION_IN_PROGRESS
        "total_tasks": 3,
        "completed_tasks": 1,
        "tasks": [ ... ],
        "started_at": "2025-01-11T14:30:22Z"
        }
        }
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def list(self, request, context):
        """List workflow executions with pagination and optional filtering.

        Returns a paginated list of WorkflowExecution resources that the user has access to.
        Results are automatically filtered based on user's permissions and owner scope.

        Authorization:
        Custom authorization filters results to only include executions the user can access:
        - Organization users: Only executions in their organization
        - Users with cross-org access: Public executions from other orgs

        Pagination:
        - page_size: Maximum number of results to return (default: 50, max: 100)
        - page_token: Opaque token from previous response for next page
        - Returns total_pages count for UI pagination

        Filtering:
        - phase: Filter by execution phase (PENDING, IN_PROGRESS, COMPLETED, FAILED, CANCELLED)
        - tags: Filter by resource tags (AND logic - must match all tags)

        Sorting:
        Results are sorted by created_at descending (newest first).

        Use Cases:

        1. Execution History Dashboard:
        - UI displays list of all recent executions
        - User can filter by status (show only failed, show only in-progress)
        - User can page through historical executions

        2. Monitor Active Executions:
        - UI calls list(phase=EXECUTION_IN_PROGRESS) to show running executions
        - UI displays progress for each execution (completed_tasks / total_tasks)
        - UI refreshes list periodically to show updates

        3. Audit and Compliance:
        - Admin lists all executions for a time period
        - Admin filters by tags (environment, team, project)
        - Admin exports execution history for audit logs

        4. Debug and Troubleshooting:
        - Developer lists failed executions (phase=EXECUTION_FAILED)
        - Developer inspects error messages and retry patterns
        - Developer identifies systematic failures

        Error Cases:

        - INVALID_ARGUMENT:
        - page_size is negative or exceeds maximum
        - Invalid page_token (expired, corrupted)

        Example Request (Filter for failed executions):
        {
        "page_size": 20,
        "phase": 4,  // EXECUTION_FAILED
        "tags": ["environment:production"]
        }

        Example Response:
        {
        "total_pages": 3,
        "entries": [
        {
        "metadata": { "id": "wfx-failed-1", ... },
        "status": { "phase": 4, "error": "Task failed: API timeout", ... }
        },
        {
        "metadata": { "id": "wfx-failed-2", ... },
        "status": { "phase": 4, "error": "Task failed: Rate limit", ... }
        }
        ]
        }
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def listByWorkflow(self, request, context):
        """List all executions for a specific Workflow or WorkflowInstance.

        Returns executions filtered by a specific Workflow ID.
        This is useful for viewing execution history of a particular workflow.

        Authorization:
        Custom authorization verifies:
        1. User has access to the referenced Workflow or WorkflowInstance
        2. Results are filtered to only include executions user can access

        Pagination:
        - page_size: Maximum number of results to return (default: 50, max: 100)
        - page_token: Opaque token from previous response for next page

        Sorting:
        Results are sorted by created_at descending (newest first).

        Use Cases:

        1. Workflow Execution History:
        - User views a Workflow in the UI
        - UI calls listByWorkflow(workflow_id) to show all executions
        - UI displays timeline of executions with success/failure indicators

        2. Performance Analysis:
        - Developer wants to analyze workflow performance over time
        - Developer calls listByWorkflow() to get all executions
        - Developer calculates average duration, success rate, failure patterns

        3. Retry Analysis:
        - User sees failed execution
        - User calls listByWorkflow() to see if other executions also failed
        - User determines if failure is systematic or one-off

        4. Workflow Testing:
        - Developer tests a workflow with multiple executions
        - Developer calls listByWorkflow() to see all test runs
        - Developer compares outputs across executions

        Error Cases:

        - INVALID_ARGUMENT:
        - workflow_id is empty or invalid format
        - page_size is negative or exceeds maximum

        - PERMISSION_DENIED:
        - User doesn't have access to the referenced Workflow/WorkflowInstance

        - NOT_FOUND:
        - No Workflow or WorkflowInstance exists with the given ID

        Example Request:
        {
        "workflow_id": "wfi-customer-onboarding-prod",
        "page_size": 50
        }

        Example Response:
        {
        "total_pages": 5,
        "entries": [
        {
        "metadata": { "id": "wfx-latest", "created_at": "2025-01-11T14:30:22Z" },
        "status": { "phase": 3, ... }  // COMPLETED
        },
        {
        "metadata": { "id": "wfx-previous", "created_at": "2025-01-11T10:15:00Z" },
        "status": { "phase": 4, ... }  // FAILED
        }
        ]
        }
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def subscribe(self, request, context):
        """Subscribe to real-time updates for a specific workflow execution (server streaming).

        Opens a bidirectional stream that pushes WorkflowExecution updates as they occur.
        Client receives updates when:
        - Execution phase changes (PENDING → IN_PROGRESS → COMPLETED)
        - Tasks start or complete
        - Progress events are appended
        - Output or error fields are set

        Authorization:
        Standard authorization checks that user has "get" permission on the WorkflowExecution.
        This is the same permission check as get() RPC.

        Stream Lifecycle:
        1. Client sends SubscribeWorkflowExecutionRequest with execution_id
        2. Server validates authorization
        3. Server sends initial WorkflowExecution (current state)
        4. Server streams updates as execution progresses
        5. Server closes stream when execution reaches terminal state (COMPLETED/FAILED/CANCELLED)
        6. Client can close stream early (e.g., user navigates away from page)

        Update Frequency:
        - Updates are sent immediately when execution state changes
        - No polling necessary (server pushes updates)
        - Typical update latency: < 100ms

        Use Cases:

        1. Real-Time Progress Monitoring:
        - User triggers an execution from UI
        - UI subscribes to execution updates
        - UI displays live progress: tasks completing, progress bar updating
        - UI shows final output when execution completes

        2. Long-Running Workflow Monitoring:
        - Workflow takes hours to complete (e.g., data processing)
        - UI subscribes and shows live progress
        - User can leave page, come back, and reconnect to same execution

        3. Debugging with Live Updates:
        - Developer triggers test execution
        - Developer subscribes to watch execution progress
        - Developer sees exactly which task is running and when failures occur

        4. Multi-User Collaboration:
        - Multiple users watching same execution
        - All users receive same updates simultaneously
        - All users see consistent view of execution state

        Stream Message Format:
        Each message is a complete WorkflowExecution resource with updated status.

        Error Cases:

        - NOT_FOUND:
        - No WorkflowExecution exists with the given ID

        - PERMISSION_DENIED:
        - User doesn't have "get" permission on this WorkflowExecution

        - DEADLINE_EXCEEDED:
        - Client timeout (client should reconnect)

        - UNAVAILABLE:
        - Server unavailable (client should retry with backoff)

        Example Request:
        {
        "execution_id": "wfx-abc123xyz456"
        }

        Example Stream (sequence of messages):

        Message 1 (initial state):
        {
        "metadata": { "id": "wfx-abc123xyz456" },
        "status": {
        "phase": 1,  // EXECUTION_PENDING
        "total_tasks": 3,
        "completed_tasks": 0
        }
        }

        Message 2 (execution started):
        {
        "metadata": { "id": "wfx-abc123xyz456" },
        "status": {
        "phase": 2,  // EXECUTION_IN_PROGRESS
        "started_at": "2025-01-11T14:30:22Z"
        }
        }

        Message 3 (task 1 completed):
        {
        "metadata": { "id": "wfx-abc123xyz456" },
        "status": {
        "phase": 2,  // EXECUTION_IN_PROGRESS
        "completed_tasks": 1,
        "tasks": [
        { "task_id": "task-1", "status": 3, "output": { ... } }
        ]
        }
        }

        Message 4 (execution completed):
        {
        "metadata": { "id": "wfx-abc123xyz456" },
        "status": {
        "phase": 3,  // EXECUTION_COMPLETED
        "completed_tasks": 3,
        "output": { ... },
        "completed_at": "2025-01-11T14:35:47Z"
        }
        }
        [Stream closes]
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')


def add_WorkflowExecutionQueryControllerServicer_to_server(servicer, server):
    rpc_method_handlers = {
            'get': grpc.unary_unary_rpc_method_handler(
                    servicer.get,
                    request_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionId.FromString,
                    response_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2.WorkflowExecution.SerializeToString,
            ),
            'list': grpc.unary_unary_rpc_method_handler(
                    servicer.list,
                    request_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.ListWorkflowExecutionsRequest.FromString,
                    response_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionList.SerializeToString,
            ),
            'listByWorkflow': grpc.unary_unary_rpc_method_handler(
                    servicer.listByWorkflow,
                    request_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.ListWorkflowExecutionsByWorkflowRequest.FromString,
                    response_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionList.SerializeToString,
            ),
            'subscribe': grpc.unary_stream_rpc_method_handler(
                    servicer.subscribe,
                    request_deserializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.SubscribeWorkflowExecutionRequest.FromString,
                    response_serializer=ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2.WorkflowExecution.SerializeToString,
            ),
    }
    generic_handler = grpc.method_handlers_generic_handler(
            'ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController', rpc_method_handlers)
    server.add_generic_rpc_handlers((generic_handler,))
    server.add_registered_method_handlers('ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController', rpc_method_handlers)


 # This class is part of an EXPERIMENTAL API.
class WorkflowExecutionQueryController(object):
    """WorkflowExecutionQueryController handles read operations (Get, List, Subscribe) for WorkflowExecution resources.

    This service follows the Command-Query Separation (CQS) pattern:
    - CommandController: Write operations (create, update, delete)
    - QueryController: Read operations (get, list, search, subscribe)

    Authorization:
    - get: Standard authorization - user must have "get" permission on the specific WorkflowExecution
    - list: Custom authorization - filters results based on user's owner scope and permissions
    - list_by_workflow: Custom authorization - verifies user has access to the Workflow/WorkflowInstance
    - subscribe: Standard authorization - user must have "get" permission to subscribe to updates

    Service Options:
    - api_resource_kind: workflow_execution - Links this service to the WorkflowExecution resource
    """

    @staticmethod
    def get(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(
            request,
            target,
            '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/get',
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionId.SerializeToString,
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2.WorkflowExecution.FromString,
            options,
            channel_credentials,
            insecure,
            call_credentials,
            compression,
            wait_for_ready,
            timeout,
            metadata,
            _registered_method=True)

    @staticmethod
    def list(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(
            request,
            target,
            '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/list',
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.ListWorkflowExecutionsRequest.SerializeToString,
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionList.FromString,
            options,
            channel_credentials,
            insecure,
            call_credentials,
            compression,
            wait_for_ready,
            timeout,
            metadata,
            _registered_method=True)

    @staticmethod
    def listByWorkflow(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(
            request,
            target,
            '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/listByWorkflow',
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.ListWorkflowExecutionsByWorkflowRequest.SerializeToString,
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.WorkflowExecutionList.FromString,
            options,
            channel_credentials,
            insecure,
            call_credentials,
            compression,
            wait_for_ready,
            timeout,
            metadata,
            _registered_method=True)

    @staticmethod
    def subscribe(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_stream(
            request,
            target,
            '/ai.stigmer.agentic.workflowexecution.v1.WorkflowExecutionQueryController/subscribe',
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_io__pb2.SubscribeWorkflowExecutionRequest.SerializeToString,
            ai_dot_stigmer_dot_agentic_dot_workflowexecution_dot_v1_dot_api__pb2.WorkflowExecution.FromString,
            options,
            channel_credentials,
            insecure,
            call_credentials,
            compression,
            wait_for_ready,
            timeout,
            metadata,
            _registered_method=True)
