From 57600ba1f92242bffb55bdd0647d8e7dfbec712d Mon Sep 17 00:00:00 2001 From: Jon Lazarowicz Date: Wed, 21 Oct 2026 08:42:03 -0400 Subject: [PATCH] feat(simulate): add session-replay endpoints (sessions, demo, quota, prepare, status) Adds rh.simulate with typed models for /v1/simulate/*. Removes the stale GET /v1/simulations pointer from the Simulation docstring and pins the ruff rule set so lint is green again on ruff 0.17. --- README.md | 13 ++++ pyproject.toml | 4 ++ racehooks/__init__.py | 11 ++++ racehooks/client.py | 66 +++++++++++++++++++ racehooks/models/__init__.py | 13 ++++ racehooks/models/resources.py | 5 +- racehooks/models/simulate.py | 99 +++++++++++++++++++++++++++++ tests/test_client.py | 116 ++++++++++++++++++++++++++++++++++ 8 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 racehooks/models/simulate.py diff --git a/README.md b/README.md index c4e11a5..cafd158 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,19 @@ if pits.fastest_stop: print(pits.fastest_stop.tla, pits.fastest_stop.pit_stop_time_sec, "s") ``` +### Session replay + +Replay a completed session as if it were live. List replayable sessions, warm +the recorded-playback artifact, then stream it from the simulate-stream service: + +```python +rh.simulate.sessions(year=2026, type="race") # replayable sessions (+ total, restricted_to_season) +rh.simulate.demo() # the curated demo session +art = rh.simulate.prepare("2026-great-britain_r") # generate the artifact if cold +rh.simulate.status("2026-great-britain_r") # status: ready | preparing | missing | unknown +rh.simulate.quota() # your tier's replay slots (-1 = unlimited) +``` + ### Core resources ```python diff --git a/pyproject.toml b/pyproject.toml index 4392250..b8d0ca0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,3 +72,7 @@ asyncio_mode = "auto" [tool.ruff] # Generated protobuf stubs are not linted/formatted. extend-exclude = ["racehooks/grpc/_gen"] + +[tool.ruff.lint] +# Pin the rule set (ruff's default set widened in 0.17 and broke CI on untouched files). +select = ["E4", "E7", "E9", "F"] diff --git a/racehooks/__init__.py b/racehooks/__init__.py index e21b473..bbd630f 100644 --- a/racehooks/__init__.py +++ b/racehooks/__init__.py @@ -25,6 +25,11 @@ RaceHooksError, ) from .models import ( + DemoSession, + ReplayQuota, + ReplayableSession, + ReplayableSessionList, + SimulateArtifact, AnalyticsBattle, AnalyticsChampionshipProbability, AnalyticsGapProjection, @@ -187,4 +192,10 @@ "FantasyScoreEntry", "RaceScores", "SessionScores", + # session replay + "DemoSession", + "ReplayQuota", + "ReplayableSession", + "ReplayableSessionList", + "SimulateArtifact", ] diff --git a/racehooks/client.py b/racehooks/client.py index a72ebd8..1475c88 100644 --- a/racehooks/client.py +++ b/racehooks/client.py @@ -13,6 +13,10 @@ events = rh.events.list(upcoming=True) ctx = rh.live.context() + # Session replay + rh.simulate.sessions(year=2026) + rh.simulate.prepare("2026-great-britain_r") + Authentication uses the OAuth 2 client-credentials flow: the client exchanges ``client_id`` + ``client_secret`` for a short-lived Bearer token on the first request and refreshes it automatically before expiry. Credentials come from the @@ -31,10 +35,14 @@ CreateWebhookResult, EventList, FeedList, + DemoSession, LiveContext, RaceScores, + ReplayableSessionList, + ReplayQuota, SessionPitTimes, SessionScores, + SimulateArtifact, Webhook, WebhookList, WebhookLogList, @@ -117,6 +125,7 @@ def __init__( self.feeds = FeedsNamespace(self) self.events = EventsNamespace(self) self.live = LiveNamespace(self) + self.simulate = SimulateNamespace(self) # ------------------------------------------------------------------ # Lifecycle @@ -461,6 +470,62 @@ def context(self) -> LiveContext: return LiveContext.model_validate(res["data"]) +class SimulateNamespace: + """Session replay: prepare a completed session's recorded-playback artifact. + + Playback itself streams from the simulate-stream service. Any authenticated + tier can list and prepare real sessions; tier controls the artifact profile + (``lite`` vs ``full``) and the replay quota. + """ + + def __init__(self, client: RaceHooks) -> None: + self._client = client + + def sessions( + self, + *, + year: Optional[int] = None, + type: Optional[str] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + ) -> ReplayableSessionList: + """List completed sessions available for replay. + + ``type`` is one of ``race``, ``qualifying``, ``sprint``, ``practice`` + (``GET /v1/simulate/sessions``). Self-serve tiers see the current + season plus the demo session; ``restricted_to_season`` reports the clamp. + """ + params = _pagination_params(limit, offset) + if year is not None: + params["year"] = year + if type is not None: + params["type"] = type + res = self._client._get("/simulate/sessions", params) + return ReplayableSessionList.model_validate(res["data"]) + + def demo(self) -> DemoSession: + """The curated demo session (``GET /v1/simulate/demo``).""" + res = self._client._get("/simulate/demo") + return DemoSession.model_validate(res["data"]) + + def quota(self) -> ReplayQuota: + """Distinct-session replay quota for your tier (``GET /v1/simulate/quota``).""" + res = self._client._get("/simulate/quota") + return ReplayQuota.model_validate(res["data"]) + + def prepare(self, session_id: str) -> SimulateArtifact: + """Ensure a session's artifact exists, triggering generation if cold + (``POST /v1/simulate/prepare``).""" + res = self._client._post("/simulate/prepare", {"sessionId": session_id}) + return SimulateArtifact.model_validate(res["data"]) + + def status(self, session_id: str) -> SimulateArtifact: + """Whether a session's artifact is ready to stream + (``GET /v1/simulate/status``).""" + res = self._client._get("/simulate/status", {"session": session_id}) + return SimulateArtifact.model_validate(res["data"]) + + __all__: List[str] = [ "RaceHooks", "RaceHooksError", @@ -471,5 +536,6 @@ def context(self) -> LiveContext: "FeedsNamespace", "EventsNamespace", "LiveNamespace", + "SimulateNamespace", "DEFAULT_BASE_URL", ] diff --git a/racehooks/models/__init__.py b/racehooks/models/__init__.py index 4c53d47..009bb19 100644 --- a/racehooks/models/__init__.py +++ b/racehooks/models/__init__.py @@ -51,6 +51,13 @@ SessionPitTimes, SessionScores, ) +from .simulate import ( + DemoSession, + ReplayableSession, + ReplayableSessionList, + ReplayQuota, + SimulateArtifact, +) from .resources import ( CreateWebhookResult, DeliveryLog, @@ -140,4 +147,10 @@ "FantasyScoreEntry", "RaceScores", "SessionScores", + # session replay + "DemoSession", + "ReplayQuota", + "ReplayableSession", + "ReplayableSessionList", + "SimulateArtifact", ] diff --git a/racehooks/models/resources.py b/racehooks/models/resources.py index bc1561c..de081ad 100644 --- a/racehooks/models/resources.py +++ b/racehooks/models/resources.py @@ -82,7 +82,10 @@ class Webhook(_Resource): class Simulation(_Resource): - """A Simulate historical-replay run (``GET /v1/simulations``).""" + """Deprecated: the retired per-request replay run. + + Use ``rh.simulate`` (sessions / prepare / status) instead. + """ simulation_id: Optional[str] = Field(default=None, alias="simulationId") client_id: Optional[str] = Field(default=None, alias="clientId") diff --git a/racehooks/models/simulate.py b/racehooks/models/simulate.py new file mode 100644 index 0000000..d987667 --- /dev/null +++ b/racehooks/models/simulate.py @@ -0,0 +1,99 @@ +"""Pydantic models for the session-replay REST endpoints (``/v1/simulate/*``). + +Wire format is camelCase and every model exposes snake_case attributes via +pydantic aliases, tolerating unknown fields (``extra="allow"``) so new fields +never break parsing. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel, ConfigDict, Field + + +class _Resource(BaseModel): + """Base for replay resource models — tolerant of unknown fields.""" + + model_config = ConfigDict(extra="allow", populate_by_name=True) + + +class ReplayableSession(_Resource): + """A completed session that can be replayed (``GET /v1/simulate/sessions``).""" + + session_id: str = Field(alias="sessionId") + session_name: Optional[str] = Field(default=None, alias="sessionName") + event_id: Optional[str] = Field(default=None, alias="eventId") + event_name: Optional[str] = Field(default=None, alias="eventName") + circuit_id: Optional[str] = Field(default=None, alias="circuitId") + circuit_outline: Optional[Dict[str, Any]] = Field( + default=None, alias="circuitOutline" + ) + year: Optional[int] = None + type: Optional[str] = None + start_date: Optional[str] = Field(default=None, alias="startDate") + #: Replaying this session delivers the full Analytics feeds on any plan + #: without using a replay slot. + analytics_preview: Optional[bool] = Field(default=None, alias="analyticsPreview") + + +class ReplayableSessionList(_Resource): + """Paginated replayable-session listing.""" + + sessions: List[ReplayableSession] = Field(default_factory=list) + total: int = 0 + limit: Optional[int] = None + offset: Optional[int] = None + #: The season the listing is clamped to when the tier limits the archive. + restricted_to_season: Optional[str] = Field( + default=None, alias="restrictedToSeason" + ) + + +class SimulateArtifact(_Resource): + """Recorded-playback artifact state for a session. + + ``status`` is ``"ready"`` (stream it now), ``"preparing"`` (generation was + triggered; poll ``status()``), ``"missing"`` (call ``prepare()``) or + ``"unknown"`` (no such session). ``profile`` is ``"lite"`` or ``"full"``. + """ + + session_id: str = Field(alias="sessionId") + session_name: Optional[str] = Field(default=None, alias="sessionName") + model_version: Optional[str] = Field(default=None, alias="modelVersion") + profile: Optional[str] = None + status: str + #: Served from a compatible prior format while the current one regenerates. + format_fallback: Optional[bool] = Field(default=None, alias="formatFallback") + + +class DemoSession(_Resource): + """The curated demo session (``GET /v1/simulate/demo``).""" + + session_id: str = Field(alias="sessionId") + session_name: Optional[str] = Field(default=None, alias="sessionName") + #: ``"ready"`` or ``"missing"``. + status: str + + +class ReplayQuota(_Resource): + """Distinct-session replay-delivery quota (``GET /v1/simulate/quota``). + + Watching is unlimited; ``-1`` means unlimited for ``limit``/``remaining``. + """ + + limit: int + used: int + remaining: int + #: Session ids already unlocked; re-running them is free. + unlocked: List[str] = Field(default_factory=list) + current_season_only: bool = Field(default=False, alias="currentSeasonOnly") + + +__all__ = [ + "ReplayableSession", + "ReplayableSessionList", + "SimulateArtifact", + "DemoSession", + "ReplayQuota", +] diff --git a/tests/test_client.py b/tests/test_client.py index 7f6ebe1..a675a0f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -284,3 +284,119 @@ def test_missing_credentials_raise_value_error() -> None: RaceHooks("", "secret") with pytest.raises(ValueError): RaceHooks("cid", "") + + +# --------------------------------------------------------------------------- +# Session replay (/v1/simulate/*) +# --------------------------------------------------------------------------- + + +def _replay_client(payload, seen: List[httpx.Request]) -> RaceHooks: + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/v1/oauth": + return _oauth_response() + seen.append(request) + return httpx.Response(200, json={"data": payload}) + + return _make_client(handler) + + +def test_simulate_sessions_query_and_models() -> None: + seen: List[httpx.Request] = [] + rh = _replay_client( + { + "sessions": [ + { + "sessionId": "2026-great-britain_r", + "sessionName": "Race", + "eventId": "e1", + "eventName": "British Grand Prix", + "circuitId": None, + "year": 2026, + "type": "r", + "startDate": "2026-07-05T14:00:00Z", + "analyticsPreview": True, + } + ], + "total": 1, + "limit": 20, + "offset": 0, + "restrictedToSeason": "2026", + }, + seen, + ) + res = rh.simulate.sessions(year=2026, type="race", limit=20, offset=0) + req = seen[0] + assert req.method == "GET" and req.url.path == "/v1/simulate/sessions" + assert dict(req.url.params) == { + "year": "2026", + "type": "race", + "limit": "20", + "offset": "0", + } + assert res.restricted_to_season == "2026" + assert res.sessions[0].session_id == "2026-great-britain_r" + assert res.sessions[0].analytics_preview is True + + +def test_simulate_sessions_no_filters_sends_no_query() -> None: + seen: List[httpx.Request] = [] + rh = _replay_client({"sessions": [], "total": 0}, seen) + assert rh.simulate.sessions().sessions == [] + assert str(seen[0].url.query, "ascii") == "" + + +def test_simulate_status_and_prepare() -> None: + art = { + "sessionId": "2026-great-britain_r", + "modelVersion": "v1", + "profile": "lite", + "status": "preparing", + "formatFallback": True, + } + seen: List[httpx.Request] = [] + rh = _replay_client(art, seen) + s = rh.simulate.status("2026-great-britain_r") + assert seen[0].method == "GET" and seen[0].url.path == "/v1/simulate/status" + assert seen[0].url.params["session"] == "2026-great-britain_r" + assert s.status == "preparing" and s.format_fallback is True + + p = rh.simulate.prepare("2026-great-britain_r") + assert seen[1].method == "POST" and seen[1].url.path == "/v1/simulate/prepare" + assert json.loads(seen[1].content) == {"sessionId": "2026-great-britain_r"} + assert p.profile == "lite" and p.model_version == "v1" + + +def test_simulate_demo_and_quota() -> None: + seen: List[httpx.Request] = [] + rh = _replay_client({"sessionId": "2026-demo_r", "status": "ready"}, seen) + demo = rh.simulate.demo() + assert seen[0].url.path == "/v1/simulate/demo" + assert demo.session_id == "2026-demo_r" and demo.status == "ready" + + seen2: List[httpx.Request] = [] + rh2 = _replay_client( + { + "limit": -1, + "used": 2, + "remaining": -1, + "unlocked": ["a", "b"], + "currentSeasonOnly": True, + }, + seen2, + ) + q = rh2.simulate.quota() + assert seen2[0].url.path == "/v1/simulate/quota" + assert q.limit == -1 and q.unlocked == ["a", "b"] and q.current_season_only + + +def test_simulate_error_raises_api_error() -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/v1/oauth": + return _oauth_response() + return httpx.Response(403, text="forbidden") + + rh = _make_client(handler) + with pytest.raises(RaceHooksAPIError) as ei: + rh.simulate.quota() + assert ei.value.status_code == 403