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
43 changes: 32 additions & 11 deletions saturday/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@

from __future__ import annotations

import math
import re
import time
from typing import Any, Dict, List, Optional, Sequence, Union
from urllib.parse import quote
from urllib.parse import quote, urlparse

import httpx

Expand Down Expand Up @@ -96,7 +97,10 @@ def _retry_safe_on_server_error(method: str, path: str) -> bool:

def _seg(value: str) -> str:
"""Encode one path segment."""
return quote(str(value), safe="")
text = str(value)
if text in (".", ".."):
raise ValueError(f"Invalid path segment: {text!r}")
return quote(text, safe="")


def _params(**values: Any) -> Optional[Dict[str, Any]]:
Expand Down Expand Up @@ -135,6 +139,18 @@ def __init__(
max_retries: int = DEFAULT_MAX_RETRIES,
bearer_token: Optional[str] = None,
):
if not isinstance(api_key, str) or (not api_key and not bearer_token):
raise ValueError("api_key must be a non-empty string")
for name, value in (("api_key", api_key), ("bearer_token", bearer_token or "")):
if any(ord(c) < 32 or ord(c) == 127 for c in value):
raise ValueError(f"{name} must not contain control characters")
if timeout is not None:
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
raise ValueError("timeout must be a finite number above 0")
if not math.isfinite(float(timeout)) or float(timeout) <= 0:
raise ValueError("timeout must be a finite number above 0")
if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
raise ValueError("max_retries must be an integer of 0 or more")
self._api_key = api_key
self._base_url = base_url.rstrip("/")
self._timeout = DEFAULT_TIMEOUT if timeout is None else timeout
Expand Down Expand Up @@ -192,6 +208,10 @@ def request(
since the server may have done the write. Daily ceilings, blocks, waits over 30 seconds and
every other 4xx raise at once.
"""
method = method.upper()
parsed_path = urlparse(path)
if parsed_path.scheme or parsed_path.netloc:
raise ValueError("path must be a relative URL path, not an absolute URL")
last_error: Optional[SaturdayError] = None

for attempt in range(self._max_retries + 1):
Expand All @@ -210,7 +230,8 @@ def request(
try:
error_body = response.json()
except Exception:
error_body = {"error": {"type": "api_error", "code": "unknown", "message": response.text or f"HTTP {response.status_code}"}}
fallback_message = (response.text or f"HTTP {response.status_code}")[:200]
error_body = {"error": {"type": "api_error", "code": "unknown", "message": fallback_message}}
error = SaturdayError.from_response(response.status_code, error_body, response.headers.get("Retry-After"))
last_error = error

Expand All @@ -221,7 +242,7 @@ def request(
elif response.status_code >= 500 and _retry_safe_on_server_error(method, path):
if error.retry_after is not None and error.retry_after > MAX_RETRY_WAIT_SECONDS:
raise error
delay = error.retry_after if error.retry_after is not None else 2 ** attempt
delay = error.retry_after if error.retry_after is not None else min(2 ** attempt, MAX_RETRY_WAIT_SECONDS)
else:
raise error
if attempt < self._max_retries:
Expand Down Expand Up @@ -806,7 +827,7 @@ def fueling_rollup(
"""One athlete's in-window fueling rollup + concern summary (roster-confined)."""
return self._client.request(
"GET",
f"/v1/coach/athletes/{athlete_uid}/fueling-rollup",
f"/v1/coach/athletes/{_seg(athlete_uid)}/fueling-rollup",
params=_coach_read_params(window, focus),
)

Expand All @@ -823,7 +844,7 @@ def report(
if refresh:
params["refresh"] = "true"
return self._client.request(
"GET", f"/v1/coach/athletes/{athlete_uid}/report", params=params or None
"GET", f"/v1/coach/athletes/{_seg(athlete_uid)}/report", params=params or None
)

def report_pdf(
Expand All @@ -833,13 +854,13 @@ def report_pdf(
params = _coach_read_params(window, focus) or {}
params["format"] = "pdf"
return self._client.request(
"GET", f"/v1/coach/athletes/{athlete_uid}/report", params=params, raw=True
"GET", f"/v1/coach/athletes/{_seg(athlete_uid)}/report", params=params, raw=True
)

def session_detail(self, athlete_uid: str, activity_id: str) -> Dict[str, Any]:
"""Drill into one session by activity id (planned-vs-actual + markers)."""
return self._client.request(
"GET", f"/v1/coach/athletes/{athlete_uid}/sessions/{activity_id}"
"GET", f"/v1/coach/athletes/{_seg(athlete_uid)}/sessions/{_seg(activity_id)}"
)

# --- Config: alert rules ---
Expand Down Expand Up @@ -927,15 +948,15 @@ def register_webhook(self, url: str, *, events: Optional[List[str]] = None) -> D

def delete_webhook(self, webhook_id: str) -> Dict[str, Any]:
"""Delete a webhook endpoint by id."""
return self._client.request("DELETE", f"/v1/coach/webhooks/{webhook_id}")
return self._client.request("DELETE", f"/v1/coach/webhooks/{_seg(webhook_id)}")

def disable_webhook(self, webhook_id: str) -> Dict[str, Any]:
"""Disable a webhook endpoint (stops delivery without deleting it)."""
return self._client.request("POST", f"/v1/coach/webhooks/{webhook_id}/disable")
return self._client.request("POST", f"/v1/coach/webhooks/{_seg(webhook_id)}/disable")

def enable_webhook(self, webhook_id: str) -> Dict[str, Any]:
"""Re-enable a previously disabled webhook endpoint."""
return self._client.request("POST", f"/v1/coach/webhooks/{webhook_id}/enable")
return self._client.request("POST", f"/v1/coach/webhooks/{_seg(webhook_id)}/enable")

# --- Billing (read-only; the key must carry billing:read) ---

Expand Down
56 changes: 43 additions & 13 deletions saturday/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import re
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from typing import Any, Dict, Optional

# The 429 codes that reset at UTC midnight. Nothing they refuse succeeds before then.
Expand Down Expand Up @@ -51,26 +52,55 @@ def __init__(
self.retry_after = retry_after

@classmethod
def from_response(cls, status: int, error_body: Dict[str, Any], retry_after: Optional[str] = None) -> "SaturdayError":
def from_response(cls, status: int, error_body: Any, retry_after: Optional[str] = None) -> "SaturdayError":
"""The error subclass for an API error response."""
detail = error_body.get("error", error_body) if isinstance(error_body, dict) else {}
if isinstance(error_body, dict):
raw_detail = error_body.get("error", error_body)
detail = raw_detail if isinstance(raw_detail, dict) else {}
else:
detail = {}
message = detail.get("message")
if not isinstance(message, str) or not message:
message = f"HTTP {status}"
error_type = detail.get("type")
if not isinstance(error_type, str) or not error_type:
error_type = "api_error"
code = detail.get("code")
if not isinstance(code, str) or not code:
code = "unknown"
param = detail.get("param") if isinstance(detail.get("param"), str) else None
request_id = detail.get("request_id") if isinstance(detail.get("request_id"), str) else None
athlete_id = detail.get("athlete_id") if isinstance(detail.get("athlete_id"), str) else None
kwargs: Dict[str, Any] = {
"message": detail.get("message", f"HTTP {status}"),
"message": message,
"status": status,
"error_type": detail.get("type", "api_error"),
"code": detail.get("code", "unknown"),
"param": detail.get("param"),
"request_id": detail.get("request_id"),
"athlete_id": detail.get("athlete_id"),
"error_type": error_type,
"code": code,
"param": param,
"request_id": request_id,
"athlete_id": athlete_id,
}
seconds: Optional[float] = None
if retry_after is not None:
try:
seconds = max(0.0, float(retry_after))
except ValueError:
stripped = retry_after.strip() if isinstance(retry_after, str) else retry_after
if stripped is None or stripped == "":
seconds = None
if seconds is not None and seconds.is_integer():
seconds = int(seconds)
else:
try:
seconds = max(0.0, float(stripped)) # type: ignore[arg-type]
except (ValueError, TypeError):
try:
parsed = parsedate_to_datetime(stripped) # type: ignore[arg-type]
if parsed is None:
seconds = None
else:
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
seconds = max(0.0, (parsed - datetime.now(timezone.utc)).total_seconds())
except Exception:
seconds = None
if seconds is not None and float(seconds).is_integer():
seconds = int(seconds)
if status in (400, 422):
return ValidationError(**kwargs)
if status == 401:
Expand Down
42 changes: 42 additions & 0 deletions tests/test_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,45 @@ def test_shared_profile_carries_every_answer_and_unshared_carries_none():
for name in ("fueling_profile_off", "fueling_profile_not_linked"):
assert "profile" not in FIXTURES[name] and "updated_at" not in FIXTURES[name]
assert isinstance(FIXTURES[name]["message"], str)


@pytest.mark.parametrize("call, method, path, body", [
(lambda c: c.nutrition.extract(image_base64="AA=="),
"POST", "/v1/nutrition/extract", {"image_base64": "AA=="}),
(lambda c: c.infer.activity_type(activity_name="Morning Ride", tags=["bike"]),
"POST", "/v1/infer/activity-type", {"activity_name": "Morning Ride", "tags": ["bike"]}),
(lambda c: c.infer.brick_types(activity_name="Brick session"),
"POST", "/v1/infer/brick-types", {"activity_name": "Brick session"}),
(lambda c: c.integrations.disconnect("intervals_icu", "ath_1"),
"POST", "/v1/integrations/intervals_icu/disconnect", {"athlete_id": "ath_1"}),
(lambda c: c.organizations.update_subscription("org_1", "sub_1", seats=10),
"PATCH", "/v1/organizations/org_1/subscriptions/sub_1", {"seats": 10}),
(lambda c: c.organizations.add_licenses("org_1", "sub_1", [{"athlete_id": "ath_1"}]),
"POST", "/v1/organizations/org_1/subscriptions/sub_1/licenses",
{"licenses": [{"athlete_id": "ath_1"}]}),
(lambda c: c.organizations.list_licenses("org_1", "sub_1"),
"GET", "/v1/organizations/org_1/subscriptions/sub_1/licenses", None),
(lambda c: c.organizations.remove_license("org_1", "sub_1", "ath_1"),
"DELETE", "/v1/organizations/org_1/subscriptions/sub_1/licenses/ath_1", None),
(lambda c: c.knowledge.list_topics(), "GET", "/v1/knowledge/topics", None),
(lambda c: c.knowledge.get_article("art_1"), "GET", "/v1/knowledge/articles/art_1", None),
(lambda c: c.activities.get("ath_1", "act_1"),
"GET", "/v1/athletes/ath_1/activities/act_1", None),
(lambda c: c.organizations.get("org_1"), "GET", "/v1/organizations/org_1", None),
(lambda c: c.organizations.update("org_1", description="Weekend riders"),
"PATCH", "/v1/organizations/org_1", {"description": "Weekend riders"}),
(lambda c: c.organizations.get_offer("org_1"), "GET", "/v1/organizations/org_1/offer", None),
])
def test_untested_methods_send_the_documented_request(call, method, path, body):
def send(request):
assert request.method == method
assert request.url.path == path
assert (json.loads(request.content) if request.content else None) == body
return httpx.Response(200, json={"ok": True})

client = Saturday(api_key="sk_test_fixture", max_retries=0)
client._client.close()
client._client = httpx.Client(
base_url=client._base_url, transport=httpx.MockTransport(send))
with client:
call(client)
Loading
Loading