|
| 1 | +"""Batch-status SSE route. |
| 2 | +
|
| 3 | +GET /api/batch/status/stream — Server-Sent Events stream of the pending |
| 4 | +attune-author maintenance batch (queued → in-progress → terminal). |
| 5 | +
|
| 6 | +Observe-only: the dashboard watches a batch kicked off from the CLI; it |
| 7 | +does not trigger one (that is a separate spec, ``gui-batch-trigger``). |
| 8 | +Backed by ``attune_author.maintenance_batch.status_maintenance_batch``, |
| 9 | +which is synchronous and does network I/O, so every poll runs in a |
| 10 | +worker thread to keep the single-process event loop responsive. |
| 11 | +
|
| 12 | +See ``specs/gui-batch-status-sse/`` for the design. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import asyncio |
| 18 | +import json |
| 19 | +import logging |
| 20 | +import os |
| 21 | +from pathlib import Path |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +from fastapi import APIRouter, Request |
| 25 | +from fastapi.responses import StreamingResponse |
| 26 | + |
| 27 | +from attune_gui.workspace import get_workspace |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | +router = APIRouter(prefix="/api/batch", tags=["batch"]) |
| 32 | + |
| 33 | +#: ``processing_status`` values (and the presence of ``ended_at``) that mean |
| 34 | +#: the batch has stopped; the stream emits a final frame and closes. |
| 35 | +_TERMINAL = {"ended", "canceled", "expired"} |
| 36 | + |
| 37 | +_DEFAULT_POLL_SECS = 30 |
| 38 | + |
| 39 | + |
| 40 | +def _poll_secs() -> int: |
| 41 | + """Resolve the poll cadence from ``ATTUNE_GUI_BATCH_POLL_SECS`` (default 30).""" |
| 42 | + raw = os.getenv("ATTUNE_GUI_BATCH_POLL_SECS", str(_DEFAULT_POLL_SECS)) |
| 43 | + try: |
| 44 | + return max(1, int(raw)) |
| 45 | + except ValueError: |
| 46 | + return _DEFAULT_POLL_SECS |
| 47 | + |
| 48 | + |
| 49 | +def _get_help_dir() -> Path: |
| 50 | + """The ``.help`` directory under the configured workspace. |
| 51 | +
|
| 52 | + Mirrors the living-docs routes' resolver: configured workspace, or the |
| 53 | + process cwd as a fallback. |
| 54 | + """ |
| 55 | + root = get_workspace() or Path.cwd() |
| 56 | + return root / ".help" |
| 57 | + |
| 58 | + |
| 59 | +def _sse(payload: dict[str, Any]) -> str: |
| 60 | + """Format one dict as an SSE ``data:`` frame.""" |
| 61 | + return f"data: {json.dumps(payload)}\n\n" |
| 62 | + |
| 63 | + |
| 64 | +def _status_once(help_dir: Path) -> dict[str, Any]: |
| 65 | + """One status query. Synchronous; run via ``asyncio.to_thread``. |
| 66 | +
|
| 67 | + Returns a frame dict with a ``state`` discriminator: |
| 68 | + - ``pending`` + the full ``status_maintenance_batch`` payload, or |
| 69 | + - ``none`` when there is no (or an expired) pending batch. |
| 70 | + Raises on unexpected errors — the caller renders an ``error`` frame. |
| 71 | + """ |
| 72 | + from attune_author.maintenance_batch import ( # noqa: PLC0415 |
| 73 | + BatchStateError, |
| 74 | + status_maintenance_batch, |
| 75 | + ) |
| 76 | + |
| 77 | + try: |
| 78 | + status = status_maintenance_batch(help_dir) |
| 79 | + except BatchStateError: |
| 80 | + # No pending batch, or the local state expired. CLI shows |
| 81 | + # "no pending batch"; the dashboard mirrors that as ``none``. |
| 82 | + return {"state": "none"} |
| 83 | + return {"state": "pending", **status} |
| 84 | + |
| 85 | + |
| 86 | +async def _events(request: Request, help_dir: Path): |
| 87 | + """SSE generator: poll until disconnect, terminal status, or none/error.""" |
| 88 | + while True: |
| 89 | + if await request.is_disconnected(): |
| 90 | + return |
| 91 | + try: |
| 92 | + frame = await asyncio.to_thread(_status_once, help_dir) |
| 93 | + except Exception as e: # noqa: BLE001 - surface, then close |
| 94 | + logger.warning("batch status poll failed: %s", e) |
| 95 | + yield _sse({"state": "error", "detail": str(e)}) |
| 96 | + return |
| 97 | + |
| 98 | + yield _sse(frame) |
| 99 | + |
| 100 | + if frame["state"] != "pending": |
| 101 | + return # ``none`` — one frame, then close. |
| 102 | + status = frame |
| 103 | + if status.get("processing_status") in _TERMINAL or status.get("ended_at"): |
| 104 | + return # terminal — final frame already sent, then close. |
| 105 | + |
| 106 | + await asyncio.sleep(_poll_secs()) |
| 107 | + |
| 108 | + |
| 109 | +@router.get("/status/stream") |
| 110 | +async def stream_status(request: Request) -> StreamingResponse: |
| 111 | + """Stream the pending batch's status as Server-Sent Events. |
| 112 | +
|
| 113 | + Emits one ``data:`` frame per poll. Closes after a ``none``/``error`` |
| 114 | + frame or once the batch reaches a terminal state. Read-only GET — the |
| 115 | + app-wide origin guard applies; no client token is required (matching |
| 116 | + the other read endpoints). |
| 117 | + """ |
| 118 | + help_dir = _get_help_dir() |
| 119 | + return StreamingResponse( |
| 120 | + _events(request, help_dir), |
| 121 | + media_type="text/event-stream", |
| 122 | + headers={ |
| 123 | + "Cache-Control": "no-cache", |
| 124 | + "X-Accel-Buffering": "no", # disable proxy buffering for SSE |
| 125 | + }, |
| 126 | + ) |
0 commit comments