Spaces:
Runtime error
Runtime error
| """Temporal client helpers for starting report generation workflows.""" | |
| from __future__ import annotations | |
| import logging | |
| from typing import Any | |
| from app.config import settings | |
| from app.workflows.models import ReportWorkflowRequest | |
| logger = logging.getLogger(__name__) | |
| _client: Any = None | |
| async def get_temporal_client() -> Any: | |
| global _client | |
| if _client is not None: | |
| return _client | |
| try: | |
| from temporalio.client import Client | |
| except ImportError as exc: # pragma: no cover | |
| raise RuntimeError("temporalio is not installed; pip install 'report-genius-ai[temporal]'") from exc | |
| _client = await Client.connect( | |
| settings.temporal_host, | |
| namespace=settings.temporal_namespace, | |
| ) | |
| return _client | |
| async def start_report_generation_workflow(request: ReportWorkflowRequest) -> str: | |
| """Start ``ReportGenerationWorkflow``; returns workflow id.""" | |
| from app.workflows.report_workflow import ReportGenerationWorkflow | |
| client = await get_temporal_client() | |
| import uuid | |
| wf_id = f"report-gen-{request.report_id}-{uuid.uuid4().hex[:12]}" | |
| handle = await client.start_workflow( | |
| ReportGenerationWorkflow.run, | |
| request, | |
| id=wf_id, | |
| task_queue=settings.temporal_task_queue, | |
| ) | |
| return str(handle.id) | |
| async def try_start_report_generation_workflow( | |
| request: ReportWorkflowRequest, | |
| ) -> str | None: | |
| """Return Temporal workflow id when start succeeded, else ``None`` (caller uses in-process task).""" | |
| if not settings.enable_temporal_workflow: | |
| return None | |
| try: | |
| from app.workflows.report_activities import temporal_activities_enabled | |
| if not temporal_activities_enabled(): | |
| logger.warning( | |
| "Temporal enabled but temporalio unavailable — falling back to in-process " | |
| "generation report=%s", | |
| request.report_id, | |
| ) | |
| return None | |
| return await start_report_generation_workflow(request) | |
| except Exception: # noqa: BLE001 | |
| logger.exception( | |
| "Temporal workflow start failed report=%s — falling back to in-process task", | |
| request.report_id, | |
| ) | |
| return None | |