diff --git a/docs/decisions/ADR-004-streaming-sse-design.md b/docs/decisions/ADR-004-streaming-sse-design.md new file mode 100644 index 0000000..48fc1a3 --- /dev/null +++ b/docs/decisions/ADR-004-streaming-sse-design.md @@ -0,0 +1,196 @@ +# ADR-004: Streaming/SSE Client Design + +**Status:** Accepted +**Date:** 2026-12-01 + +## Context + +The Trigger.dev session channel API uses Server-Sent Events (SSE) for reading output (`.out`) and REST POST for sending input (`.in`). These endpoints live at `/realtime/v1/sessions/{session}/{io}`, a separate base path from the management API (`/api/v1/`), and are not in the OpenAPI spec (see Item 17 investigation for full details). + +The SDK needs a streaming client that: + +1. Parses SSE streams from `.out` channels with reconnection support +2. Sends records to `.in` channels via REST POST +3. Exposes both sync and async surfaces (matching the existing Client/AsyncClient pattern) +4. Handles Trigger.dev-specific event types and control records +5. Integrates with the existing error hierarchy and retry infrastructure + +Three SSE parsing approaches were evaluated: + +1. **httpx-sse** (third-party library, v0.4.3) +2. **Inline parser** (self-contained module in the SDK) +3. **Manual line-by-line parsing** (no abstraction, inline in each method) + +## Decision + +**Use an inline SSE parser module, matching the pattern established by anthropic-sdk-python and openai-python.** + +### Evidence + +Both reference SDKs (anthropic-sdk-python, openai-python) initially adopted httpx-sse, then replaced it with inline parsers (~100 lines each). Their reasons apply to us: + +| Factor | httpx-sse | Inline parser | +|---|---|---| +| httpx2 compatibility | Unconfirmed (targets httpx, not httpx2) | Guaranteed (we control it) | +| Reconnection support | Not built-in (single-stream only) | We add `Last-Event-ID` resume directly | +| Dependency count | +1 runtime dependency | Zero new dependencies | +| Control over edge cases | Limited to library's choices | Full control (Trigger.dev-specific events) | +| Maintenance | External maintainer | Internal (SSE spec is stable, no churn) | + +The SSE wire format (W3C EventSource spec) is simple: UTF-8 text, line-delimited fields (`event:`, `data:`, `id:`, `retry:`, comments via `:`), with CR/LF/CRLF line endings. A complete parser fits in ~100 lines. + +### Module layout + +``` +src/triggerdev/ + _streaming.py # SSE parser, event types, stream wrappers + _channels.py # Channel client (sync + async) for .in/.out + resources/ + sessions.py # Session CRUD (from Tier 2, Item 21) +``` + +`_streaming.py` owns the wire format; `_channels.py` owns the HTTP transport and reconnection. This separation means the SSE parser is testable without network calls, and the channel client is testable with mock SSE data. + +### SSE parser design (`_streaming.py`) + +**Event model:** + +```python +@dataclasses.dataclass(frozen=True, slots=True) +class ServerSentEvent: + event: str # Event type ("batch", "ping", empty string for default) + data: str # Payload (multi-line data joined with "\n") + id: str # Last-Event-ID (for reconnection cursor) + retry: int | None # Server-suggested reconnect interval (ms) +``` + +**Parser:** An `SSEDecoder` class that accepts lines and yields `ServerSentEvent` objects. Handles: +- Multi-line `data:` fields (joined with `\n`) +- Comment lines (`:` prefix, discarded) +- Empty lines as event boundaries +- BOM stripping on first line +- CR, LF, and CRLF line endings + +**Stream wrappers:** + +```python +class Stream(Generic[_EventT]): + """Sync SSE stream with iteration and context manager support.""" + def __iter__(self) -> Iterator[_EventT]: ... + def __enter__(self) -> Self: ... + def __exit__(self, ...) -> None: ... + def close(self) -> None: ... + +class AsyncStream(Generic[_EventT]): + """Async SSE stream with iteration and context manager support.""" + def __aiter__(self) -> AsyncIterator[_EventT]: ... + async def __aenter__(self) -> Self: ... + async def __aexit__(self, ...) -> None: ... + async def close(self) -> None: ... +``` + +Both wrappers accept a raw `httpx2.Response` (sync) or streaming async response, feed lines through the `SSEDecoder`, and yield typed events. The generic parameter `_EventT` allows callers to receive either raw `ServerSentEvent` or Pydantic-parsed channel records. + +### Channel client design (`_channels.py`) + +**Typed channel events:** + +Trigger.dev channels emit three SSE event types plus control records: + +| SSE event type | Meaning | Python type | +|---|---|---| +| `batch` | Data records | `ChannelRecord` (Pydantic model, Tier 2) | +| `ping` | Keepalive | Skipped (not yielded to caller) | +| `[DONE]` | Stream complete (may be an SSE `event:` type or a sentinel `data:` value; verify against live API) | Closes the iterator | + +Control records are distinguished by a `trigger-control` field in the record payload (the Trigger.dev docs describe this as a "header" but it arrives as a property within the SSE event's JSON data, since SSE has no per-event headers). Subtypes: `turn-complete`, `upgrade-required`, `session-closed`, `pending-version`. These are surfaced as typed `ControlEvent` dataclasses, separate from data records. The channel client inspects each `batch` event's parsed JSON for the `trigger-control` field and routes accordingly. + +**Reconnection strategy:** + +The `.out` SSE endpoint supports cursor-based resume via the `Last-Event-ID` request header. The reconnection loop: + +1. Open SSE connection with `Last-Event-ID` set to the last received event ID (empty on first connect) +2. On connection drop or timeout: calculate delay using `_retry.calculate_retry_delay(attempt)`, honoring the SSE `retry:` field if present +3. Reconnect with the last seen event ID +4. On 409 (`session_closed`): raise `SessionClosedError` (new exception, extends `ConflictError`) +5. On 400 (expired session): raise `SessionExpiredError` (new exception, extends `BadRequestError`) +6. On other HTTP errors: apply the standard retry logic from `_retry.should_retry_status()` +7. Maximum reconnection attempts: configurable, defaults to `DEFAULT_MAX_STREAM_RECONNECTS` (5). This is intentionally higher than request retries (`DEFAULT_MAX_RETRIES = 2`) because long-lived streams are expected to encounter transient network disruptions more frequently than individual requests + +The `Timeout-Seconds` request header (1-600) controls server-side idle timeout. The client sets this to match its own timeout configuration. + +**Input channel (`.in/append`):** + +A simple POST wrapper, no streaming involved: + +```python +def send(self, session: str, record: dict[str, Any], *, part_id: str | None = None) -> SendResult: + """Append a record to the session's input channel.""" +``` + +The `X-Part-Id` header enables deduplication. Returns `{ok, seq}`. Uses the standard `_request` path with retry support. + +**Auth model:** + +The channel client accepts either: +- A secret API key (from `Client.api_key`): full access to both `.in` and `.out` +- A public access token: restricted to `.in/append` and `.out` read + +The auth mode is passed via the `Authorization: Bearer {token}` header, identical to the management API. The channel client does NOT create a separate httpx2 client; it reuses the parent client's connection pool by accepting the `httpx2.Client` / `httpx2.AsyncClient` instance. + +**Base URL handling:** + +Channel endpoints use a different base path (`/realtime/v1/`) than the management API (`/api/v1/`). The channel client constructs URLs from the same `base_url` (e.g., `https://api.trigger.dev`) but substitutes the path prefix. This ensures custom base URLs (self-hosted instances) work without additional configuration. + +### Error hierarchy additions + +Two new exception classes for channel-specific errors: + +```python +class StreamingError(TriggerDevError): + """Error during SSE stream processing.""" + +class SessionClosedError(ConflictError): + """The session is closed and no longer accepts records.""" + +class SessionExpiredError(BadRequestError): + """The session has expired.""" +``` + +`StreamingError` was already planned in the Phase 1 exception hierarchy (deferred to Phase 2). It covers SSE parse errors, unexpected stream termination, and reconnection failures. + +### Non-streaming drain + +The `.out/records?afterEventId=N` endpoint returns all records as a single JSON response. This is a standard REST call, handled through the existing `_request` path, exposed as: + +```python +def drain(self, session: str, *, after_event_id: str | None = None) -> list[ChannelRecord]: + """Retrieve all output records without streaming.""" +``` + +## Consequences + +### Positive + +- Zero new runtime dependencies (inline parser, no httpx-sse). +- Full control over reconnection, which is critical for Trigger.dev's `Last-Event-ID` resume pattern. +- Matches the established pattern from both reference SDKs (anthropic, openai). +- Reuses existing retry infrastructure (`_retry.py`) for reconnection backoff. +- Reuses existing httpx2 client for connection pooling. +- Clear module separation: wire format (`_streaming.py`) vs transport (`_channels.py`). + +### Negative + +- ~100 lines of SSE parsing code to maintain. Mitigated by the SSE spec being stable (W3C, unchanged since 2015). +- Reconnection logic adds complexity beyond what reference SDKs implement. Justified by Trigger.dev's explicit support for `Last-Event-ID` resume. + +### Neutral + +- The `_streaming.py` module is reusable if Trigger.dev adds other SSE endpoints in the future (e.g., run-state streaming via ElectricSQL). +- Control record handling (`trigger-control` payload field) may need adjustment once verified against the live API (naming discrepancy between docs pages noted in Item 17). + +## Related Decisions + +- **ADR-001**: API selection (identified streaming as a key SDK feature). +- **ADR-003**: Schema-driven generation (Tier 2 `ChannelRecord` models will follow the same pipeline). +- **Item 17 investigation**: Determined channel transport is SSE + REST POST (the input to this ADR).