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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
11 changes: 11 additions & 0 deletions racehooks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
RaceHooksError,
)
from .models import (
DemoSession,
ReplayQuota,
ReplayableSession,
ReplayableSessionList,
SimulateArtifact,
AnalyticsBattle,
AnalyticsChampionshipProbability,
AnalyticsGapProjection,
Expand Down Expand Up @@ -187,4 +192,10 @@
"FantasyScoreEntry",
"RaceScores",
"SessionScores",
# session replay
"DemoSession",
"ReplayQuota",
"ReplayableSession",
"ReplayableSessionList",
"SimulateArtifact",
]
66 changes: 66 additions & 0 deletions racehooks/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -31,10 +35,14 @@
CreateWebhookResult,
EventList,
FeedList,
DemoSession,
LiveContext,
RaceScores,
ReplayableSessionList,
ReplayQuota,
SessionPitTimes,
SessionScores,
SimulateArtifact,
Webhook,
WebhookList,
WebhookLogList,
Expand Down Expand Up @@ -117,6 +125,7 @@ def __init__(
self.feeds = FeedsNamespace(self)
self.events = EventsNamespace(self)
self.live = LiveNamespace(self)
self.simulate = SimulateNamespace(self)

# ------------------------------------------------------------------
# Lifecycle
Expand Down Expand Up @@ -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",
Expand All @@ -471,5 +536,6 @@ def context(self) -> LiveContext:
"FeedsNamespace",
"EventsNamespace",
"LiveNamespace",
"SimulateNamespace",
"DEFAULT_BASE_URL",
]
13 changes: 13 additions & 0 deletions racehooks/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@
SessionPitTimes,
SessionScores,
)
from .simulate import (
DemoSession,
ReplayableSession,
ReplayableSessionList,
ReplayQuota,
SimulateArtifact,
)
from .resources import (
CreateWebhookResult,
DeliveryLog,
Expand Down Expand Up @@ -140,4 +147,10 @@
"FantasyScoreEntry",
"RaceScores",
"SessionScores",
# session replay
"DemoSession",
"ReplayQuota",
"ReplayableSession",
"ReplayableSessionList",
"SimulateArtifact",
]
5 changes: 4 additions & 1 deletion racehooks/models/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
99 changes: 99 additions & 0 deletions racehooks/models/simulate.py
Original file line number Diff line number Diff line change
@@ -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",
]
Loading
Loading