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
176 changes: 125 additions & 51 deletions src/triggerdev/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

from __future__ import annotations

import asyncio
import logging
import os
import time
from typing import Any, TypeVar, cast, overload

import httpx2
Expand All @@ -25,10 +28,13 @@
TriggerDevError,
UnprocessableEntityError,
)
from triggerdev._retry import DEFAULT_MAX_RETRIES, calculate_retry_delay, should_retry_status

logger = logging.getLogger("triggerdev")

DEFAULT_BASE_URL = "https://api.trigger.dev"
DEFAULT_TIMEOUT = httpx2.Timeout(60.0)
DEFAULT_MAX_RETRIES = 0


_ModelT = TypeVar("_ModelT", bound=BaseModel)

Expand Down Expand Up @@ -134,8 +140,10 @@ def _request(
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
auth_required: bool = True,
max_retries: int | None = None,
) -> _ModelT | dict[str, Any] | None:
url = f"{self.base_url}{path}"
retries = max_retries if max_retries is not None else self.max_retries

headers: dict[str, str] = {
"accept": "application/json",
Expand All @@ -146,31 +154,63 @@ def _request(
if body is not None:
headers["content-type"] = "application/json"

try:
response = 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)
for attempt in range(retries + 1):
response: httpx2.Response | None = None
try:
response = self._client.request(
method,
url,
json=body,
params=params,
headers=headers,
)
except httpx2.TimeoutException as exc:
if attempt >= retries:
raise APITimeoutError(request=httpx2.Request(method, url)) from exc
logger.debug("Retry %d/%d after timeout on %s %s", attempt + 1, retries, method, path)
delay = calculate_retry_delay(attempt)
if delay is not None:
time.sleep(delay)
continue
except httpx2.TransportError as exc:
if attempt >= retries:
raise APIConnectionError(request=httpx2.Request(method, url)) from exc
logger.debug("Retry %d/%d after connection error on %s %s", attempt + 1, retries, method, path)
delay = calculate_retry_delay(attempt)
if delay is not None:
time.sleep(delay)
continue

if not response.is_success and should_retry_status(response.status_code) and attempt < retries:
retry_after = self._make_status_error(response).retry_after
delay = calculate_retry_delay(attempt, retry_after=retry_after)
if delay is None:
raise self._make_status_error(response)
logger.debug(
"Retry %d/%d after HTTP %d on %s %s",
attempt + 1,
retries,
response.status_code,
method,
path,
)
time.sleep(delay)
continue

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)

raise AssertionError("unreachable")

@staticmethod
def _make_status_error(response: httpx2.Response) -> APIStatusError:
Expand Down Expand Up @@ -312,8 +352,10 @@ async def _request(
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
auth_required: bool = True,
max_retries: int | None = None,
) -> _ModelT | dict[str, Any] | None:
url = f"{self.base_url}{path}"
retries = max_retries if max_retries is not None else self.max_retries

headers: dict[str, str] = {
"accept": "application/json",
Expand All @@ -324,31 +366,63 @@ async def _request(
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)
for attempt in range(retries + 1):
response: httpx2.Response | None = None
try:
response = await self._client.request(
method,
url,
json=body,
params=params,
headers=headers,
)
except httpx2.TimeoutException as exc:
if attempt >= retries:
raise APITimeoutError(request=httpx2.Request(method, url)) from exc
logger.debug("Retry %d/%d after timeout on %s %s", attempt + 1, retries, method, path)
delay = calculate_retry_delay(attempt)
if delay is not None:
await asyncio.sleep(delay)
continue
except httpx2.TransportError as exc:
if attempt >= retries:
raise APIConnectionError(request=httpx2.Request(method, url)) from exc
logger.debug("Retry %d/%d after connection error on %s %s", attempt + 1, retries, method, path)
delay = calculate_retry_delay(attempt)
if delay is not None:
await asyncio.sleep(delay)
continue

if not response.is_success and should_retry_status(response.status_code) and attempt < retries:
retry_after = self._make_status_error(response).retry_after
delay = calculate_retry_delay(attempt, retry_after=retry_after)
if delay is None:
raise self._make_status_error(response)
logger.debug(
"Retry %d/%d after HTTP %d on %s %s",
attempt + 1,
retries,
response.status_code,
method,
path,
)
await asyncio.sleep(delay)
continue

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)

raise AssertionError("unreachable")

@staticmethod
def _make_status_error(response: httpx2.Response) -> APIStatusError:
Expand Down
28 changes: 17 additions & 11 deletions src/triggerdev/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,23 @@ def __init__(
def __str__(self) -> str:
return f"{self.status_code} {self.message}"

@property
def retry_after(self) -> float | None:
"""Seconds to wait before retrying, or None if not specified."""
ms_header = self.response.headers.get("retry-after-ms")
if ms_header is not None:
try:
return max(0.0, float(ms_header) / 1000.0)
except ValueError:
pass
header = self.response.headers.get("retry-after")
if header is None:
return None
try:
return float(header)
except ValueError:
return None


class BadRequestError(APIStatusError):
"""The request was malformed or contained invalid parameters."""
Expand Down Expand Up @@ -92,17 +109,6 @@ class UnprocessableEntityError(APIStatusError):
class RateLimitError(APIStatusError):
"""Too many requests or concurrent operations."""

@property
def retry_after(self) -> float | None:
"""Seconds to wait before retrying, or None if not specified."""
header = self.response.headers.get("retry-after")
if header is None:
return None
try:
return float(header)
except ValueError:
return None


class InternalServerError(APIStatusError):
"""The API encountered an internal error."""
Expand Down
31 changes: 31 additions & 0 deletions src/triggerdev/_retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Retry logic for Trigger.dev API requests."""

from __future__ import annotations

import random

DEFAULT_MAX_RETRIES = 2
INITIAL_RETRY_DELAY = 0.5
MAX_RETRY_DELAY = 8.0
MAX_RETRY_AFTER = 60.0

_RETRYABLE_STATUS_CODES = {408, 429}


def should_retry_status(status_code: int) -> bool:
"""Return True if the HTTP status code is retryable."""
return status_code in _RETRYABLE_STATUS_CODES or status_code >= 500


def calculate_retry_delay(
attempt: int,
retry_after: float | None = None,
) -> float | None:
"""Return seconds to sleep, or None if the server-requested delay exceeds the cap."""
if retry_after is not None and retry_after > MAX_RETRY_AFTER:
return None
if retry_after is not None and retry_after > 0:
return retry_after
jitter = 1.0 - 0.25 * random.random()
delay: float = min(INITIAL_RETRY_DELAY * (2**attempt), MAX_RETRY_DELAY) * jitter
return delay
Loading