Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/triggerdev/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
PermissionDeniedError,
RateLimitError,
ServiceUnavailableError,
SessionClosedError,
SessionExpiredError,
StreamingError,
TriggerDevError,
UnprocessableEntityError,
)
Expand All @@ -39,6 +42,9 @@
"PermissionDeniedError",
"RateLimitError",
"ServiceUnavailableError",
"SessionClosedError",
"SessionExpiredError",
"StreamingError",
"TriggerDevError",
"UnprocessableEntityError",
"__version__",
Expand Down
248 changes: 248 additions & 0 deletions src/triggerdev/_channels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
"""Channel client for Trigger.dev session .in/.out endpoints."""

from __future__ import annotations

from contextlib import contextmanager, suppress
from typing import TYPE_CHECKING, Any

from triggerdev._exceptions import (
SessionClosedError,
SessionExpiredError,
)
from triggerdev._streaming import AsyncStream, ServerSentEvent, Stream

if TYPE_CHECKING:
from collections.abc import Generator

import httpx2


class ChannelClient:
"""Sync client for session channel operations."""

_http_client: httpx2.Client
_base_url: str
_api_key: str

def __init__(
self,
*,
http_client: httpx2.Client,
base_url: str,
api_key: str,
) -> None:
self._http_client = http_client
self._base_url = base_url.rstrip("/")
self._api_key = api_key

def _url(self, path: str) -> str:
return f"{self._base_url}/realtime/v1{path}"

def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
headers: dict[str, str] = {"authorization": f"Bearer {self._api_key}"}
if extra:
headers.update(extra)
return headers

def send(
self,
session: str,
record: dict[str, Any],
*,
part_id: str | None = None,
) -> dict[str, Any]:
"""Append a record to the session's input channel."""
extra: dict[str, str] = {"content-type": "application/json"}
if part_id is not None:
extra["x-part-id"] = part_id

response = self._http_client.post(
self._url(f"/sessions/{session}/in/append"),
json=record,
headers=self._headers(extra),
)
self._raise_for_status(response)
result: dict[str, Any] = response.json()
return result

@contextmanager
def read(
self,
session: str,
*,
last_event_id: str | None = None,
) -> Generator[Stream[ServerSentEvent]]:
"""Read the session's output channel as an SSE stream."""
extra: dict[str, str] = {"accept": "text/event-stream"}
if last_event_id is not None:
extra["last-event-id"] = last_event_id

response = self._http_client.send(
self._http_client.build_request(
"GET",
self._url(f"/sessions/{session}/out"),
headers=self._headers(extra),
),
stream=True,
)
try:
self._raise_for_status(response)
stream: Stream[ServerSentEvent] = Stream(response)
yield stream
finally:
response.close()

def drain(
self,
session: str,
*,
after_event_id: str | None = None,
) -> list[dict[str, Any]]:
"""Retrieve all output records without streaming."""
params: dict[str, str] = {}
if after_event_id is not None:
params["afterEventId"] = after_event_id

response = self._http_client.get(
self._url(f"/sessions/{session}/out/records"),
params=params,
headers=self._headers(),
)
self._raise_for_status(response)
result: list[dict[str, Any]] = response.json()
return result

def _raise_for_status(self, response: httpx2.Response) -> None:
if response.is_success:
return
body: object = None
with suppress(Exception):
body = response.json()
if response.status_code == 409:
raise SessionClosedError(
"Session is closed.",
response=response,
body=body,
)
if response.status_code == 400:
raise SessionExpiredError(
"Session has expired.",
response=response,
body=body,
)
response.raise_for_status()


class AsyncChannelClient:
"""Async client for session channel operations."""

_http_client: httpx2.AsyncClient
_base_url: str
_api_key: str

def __init__(
self,
*,
http_client: httpx2.AsyncClient,
base_url: str,
api_key: str,
) -> None:
self._http_client = http_client
self._base_url = base_url.rstrip("/")
self._api_key = api_key

def _url(self, path: str) -> str:
return f"{self._base_url}/realtime/v1{path}"

def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
headers: dict[str, str] = {"authorization": f"Bearer {self._api_key}"}
if extra:
headers.update(extra)
return headers

async def send(
self,
session: str,
record: dict[str, Any],
*,
part_id: str | None = None,
) -> dict[str, Any]:
"""Append a record to the session's input channel."""
extra: dict[str, str] = {"content-type": "application/json"}
if part_id is not None:
extra["x-part-id"] = part_id

response = await self._http_client.post(
self._url(f"/sessions/{session}/in/append"),
json=record,
headers=self._headers(extra),
)
self._raise_for_status(response)
result: dict[str, Any] = response.json()
return result

async def read(
self,
session: str,
*,
last_event_id: str | None = None,
) -> AsyncStream[ServerSentEvent]:
"""Read the session's output channel as an async SSE stream."""
extra: dict[str, str] = {"accept": "text/event-stream"}
if last_event_id is not None:
extra["last-event-id"] = last_event_id

response = await self._http_client.send(
self._http_client.build_request(
"GET",
self._url(f"/sessions/{session}/out"),
headers=self._headers(extra),
),
stream=True,
)
try:
self._raise_for_status(response)
except Exception:
await response.aclose()
raise
return AsyncStream(response)

async def drain(
self,
session: str,
*,
after_event_id: str | None = None,
) -> list[dict[str, Any]]:
"""Retrieve all output records without streaming."""
params: dict[str, str] = {}
if after_event_id is not None:
params["afterEventId"] = after_event_id

response = await self._http_client.get(
self._url(f"/sessions/{session}/out/records"),
params=params,
headers=self._headers(),
)
self._raise_for_status(response)
result: list[dict[str, Any]] = response.json()
return result

def _raise_for_status(self, response: httpx2.Response) -> None:
if response.is_success:
return
body: object = None
with suppress(Exception):
body = response.json()
if response.status_code == 409:
raise SessionClosedError(
"Session is closed.",
response=response,
body=body,
)
if response.status_code == 400:
raise SessionExpiredError(
"Session has expired.",
response=response,
body=body,
)
response.raise_for_status()
15 changes: 15 additions & 0 deletions src/triggerdev/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,18 @@ def __init__(self, *, request: httpx2.Request) -> None:
self.message = "Request timed out."


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."""


__all__ = [
"APIConnectionError",
"APIError",
Expand All @@ -156,6 +168,9 @@ def __init__(self, *, request: httpx2.Request) -> None:
"PermissionDeniedError",
"RateLimitError",
"ServiceUnavailableError",
"SessionClosedError",
"SessionExpiredError",
"StreamingError",
"TriggerDevError",
"UnprocessableEntityError",
]
1 change: 1 addition & 0 deletions src/triggerdev/_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import random

DEFAULT_MAX_RETRIES = 2
DEFAULT_MAX_STREAM_RECONNECTS = 5
INITIAL_RETRY_DELAY = 0.5
MAX_RETRY_DELAY = 8.0
MAX_RETRY_AFTER = 60.0
Expand Down
Loading