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
2 changes: 2 additions & 0 deletions src/triggerdev/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""The first fully typed Python SDK for the Trigger.dev management API."""

from triggerdev._async_client import AsyncClient
from triggerdev._client import Client
from triggerdev._exceptions import (
APIConnectionError,
Expand All @@ -26,6 +27,7 @@
"APIError",
"APIStatusError",
"APITimeoutError",
"AsyncClient",
"AuthenticationError",
"BadRequestError",
"Client",
Expand Down
55 changes: 55 additions & 0 deletions src/triggerdev/_async_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Trigger.dev async client."""

from __future__ import annotations

from functools import cached_property
from typing import TYPE_CHECKING

from triggerdev._base_client import AsyncBaseClient
from triggerdev.resources.runs import AsyncRuns
from triggerdev.resources.schedules import AsyncSchedules
from triggerdev.resources.tasks import AsyncTasks

if TYPE_CHECKING:
import httpx2


class AsyncClient(AsyncBaseClient):
"""Async client for the Trigger.dev management API."""

def __init__(
self,
*,
api_key: str | None = None,
base_url: str | None = None,
timeout: float | httpx2.Timeout | None = None,
max_retries: int | None = None,
http_client: httpx2.AsyncClient | None = None,
default_headers: dict[str, str] | None = None,
) -> None:
super().__init__(
api_key=api_key,
base_url=base_url,
timeout=timeout,
max_retries=max_retries,
http_client=http_client,
default_headers=default_headers,
)

@cached_property
def tasks(self) -> AsyncTasks:
return AsyncTasks(self)

@cached_property
def runs(self) -> AsyncRuns:
return AsyncRuns(self)

@cached_property
def schedules(self) -> AsyncSchedules:
return AsyncSchedules(self)

async def __aenter__(self) -> AsyncClient:
return self

async def __aexit__(self, *_args: object) -> None:
await self.aclose()
210 changes: 210 additions & 0 deletions src/triggerdev/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,157 @@ def __exit__(self, *_args: object) -> None:
self.close()


class AsyncBaseClient:
"""Shared async HTTP client logic for the Trigger.dev API."""

api_key: str
base_url: str
timeout: httpx2.Timeout
max_retries: int

_client: httpx2.AsyncClient
_owns_client: bool

def __init__(
self,
*,
api_key: str | None = None,
base_url: str | None = None,
timeout: float | httpx2.Timeout | None = None,
max_retries: int | None = None,
http_client: httpx2.AsyncClient | None = None,
default_headers: dict[str, str] | None = None,
) -> None:
resolved_key = api_key or os.environ.get("TRIGGER_SECRET_KEY")
if not resolved_key:
raise TriggerDevError(
"The API key must be provided as the `api_key` argument or the TRIGGER_SECRET_KEY environment variable."
)
self.api_key = resolved_key

resolved_url = base_url or os.environ.get("TRIGGER_DEV_BASE_URL", DEFAULT_BASE_URL)
self.base_url = resolved_url.rstrip("/")

if timeout is None:
self.timeout = DEFAULT_TIMEOUT
elif isinstance(timeout, (int, float)):
self.timeout = httpx2.Timeout(float(timeout))
else:
self.timeout = timeout

self.max_retries = max_retries if max_retries is not None else DEFAULT_MAX_RETRIES

self._default_headers = default_headers or {}

if http_client is not None:
self._client = http_client
self._owns_client = False
else:
self._client = httpx2.AsyncClient(timeout=self.timeout)
self._owns_client = True

@overload
async def _request(
self,
method: str,
path: str,
*,
cast_to: type[_ModelT],
body: dict[str, Any] | None = ...,
params: dict[str, Any] | None = ...,
auth_required: bool = ...,
) -> _ModelT: ...

@overload
async def _request(
self,
method: str,
path: str,
*,
cast_to: None,
body: dict[str, Any] | None = ...,
params: dict[str, Any] | None = ...,
auth_required: bool = ...,
) -> None: ...

@overload
async def _request(
self,
method: str,
path: str,
*,
cast_to: _SentinelType,
body: dict[str, Any] | None = ...,
params: dict[str, Any] | None = ...,
auth_required: bool = ...,
) -> dict[str, Any]: ...

async def _request(
self,
method: str,
path: str,
*,
cast_to: type[_ModelT] | _SentinelType | None = None,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
auth_required: bool = True,
) -> _ModelT | dict[str, Any] | None:
url = f"{self.base_url}{path}"

headers: dict[str, str] = {
"accept": "application/json",
**self._default_headers,
}
if auth_required:
headers["authorization"] = f"Bearer {self.api_key}"
if body is not None:
headers["content-type"] = "application/json"

try:
response = await self._client.request(
method,
url,
json=body,
params=params,
headers=headers,
)
except httpx2.TimeoutException as exc:
raise APITimeoutError(request=httpx2.Request(method, url)) from exc
except httpx2.TransportError as exc:
raise APIConnectionError(request=httpx2.Request(method, url)) from exc

if not response.is_success:
raise self._make_status_error(response)

if cast_to is None:
return None

data: dict[str, Any] = response.json()

if isinstance(cast_to, _SentinelType):
return data

return cast_to.model_validate(data)

@staticmethod
def _make_status_error(response: httpx2.Response) -> APIStatusError:
return BaseClient._make_status_error(response) # pyright: ignore[reportPrivateUsage]

@property
def is_closed(self) -> bool:
return self._client.is_closed

async def aclose(self) -> None:
if self._owns_client:
await self._client.aclose()

async def __aenter__(self) -> AsyncBaseClient:
return self

async def __aexit__(self, *_args: object) -> None:
await self.aclose()


class SyncAPIResource:
"""Base for sync resource classes."""

Expand Down Expand Up @@ -275,3 +426,62 @@ def _request(
body=body,
params=params,
)


class AsyncAPIResource:
"""Base for async resource classes."""

_client: AsyncBaseClient

def __init__(self, client: AsyncBaseClient) -> None:
self._client = client

@overload
async def _request(
self,
method: str,
path: str,
*,
cast_to: type[_ModelT],
body: dict[str, Any] | None = ...,
params: dict[str, Any] | None = ...,
) -> _ModelT: ...

@overload
async def _request(
self,
method: str,
path: str,
*,
cast_to: None,
body: dict[str, Any] | None = ...,
params: dict[str, Any] | None = ...,
) -> None: ...

@overload
async def _request(
self,
method: str,
path: str,
*,
cast_to: _SentinelType,
body: dict[str, Any] | None = ...,
params: dict[str, Any] | None = ...,
) -> dict[str, Any]: ...

async def _request(
self,
method: str,
path: str,
*,
cast_to: type[_ModelT] | _SentinelType | None = None,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
) -> _ModelT | dict[str, Any] | None:
return await self._client._request( # pyright: ignore[reportPrivateUsage]
method,
path,
cast_to=cast_to,
body=body,
params=params,
)
9 changes: 6 additions & 3 deletions src/triggerdev/resources/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Trigger.dev API resource clients."""

from triggerdev.resources.runs import Runs
from triggerdev.resources.schedules import Schedules
from triggerdev.resources.tasks import Tasks
from triggerdev.resources.runs import AsyncRuns, Runs
from triggerdev.resources.schedules import AsyncSchedules, Schedules
from triggerdev.resources.tasks import AsyncTasks, Tasks

__all__ = [
"AsyncRuns",
"AsyncSchedules",
"AsyncTasks",
"Runs",
"Schedules",
"Tasks",
Expand Down
Loading