streamcom-scoreboard-client 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,173 @@
1
+ """The same client for ``asyncio``: every call awaitable, every walk an ``async for``.
2
+
3
+ Each request runs on a worker thread (:func:`asyncio.to_thread`), so the event loop never
4
+ blocks and the retries, errors and options are exactly the blocking client's.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ from datetime import datetime
11
+ from typing import Any, AsyncIterator, Callable, Iterable, List, Optional, TypeVar
12
+
13
+ from .client import (
14
+ ClubsApi,
15
+ CompetitionsApi,
16
+ CourtsApi,
17
+ MatchesApi,
18
+ MatchSync,
19
+ StreamcomClient,
20
+ )
21
+ from .stream import LiveStream
22
+ from .types import (
23
+ Club,
24
+ Competition,
25
+ CompetitionDetail,
26
+ Court,
27
+ CourtSnapshot,
28
+ Match,
29
+ MatchPage,
30
+ Timeline,
31
+ TimelineEvent,
32
+ )
33
+
34
+ T = TypeVar("T")
35
+
36
+
37
+ async def _walk(read: Callable[[Optional[str]], Any], items: str) -> AsyncIterator[Any]:
38
+ cursor: Optional[str] = None
39
+ while True:
40
+ page = await asyncio.to_thread(read, cursor)
41
+ for item in page[items]:
42
+ yield item
43
+ cursor = page["next_cursor"]
44
+ if cursor is None:
45
+ return
46
+
47
+
48
+ class AsyncMatchesApi:
49
+ """:class:`MatchesApi`, awaitable."""
50
+
51
+ def __init__(self, api: MatchesApi) -> None:
52
+ self._api = api
53
+
54
+ async def list(self, **filters: Any) -> MatchPage:
55
+ """One page; the filters of :meth:`MatchesApi.list`."""
56
+ return await asyncio.to_thread(self._api.list, **filters)
57
+
58
+ def all(self, **filters: Any) -> AsyncIterator[Match]:
59
+ """Every match the filters name, a page at a time::
60
+
61
+ async for match in streamcom.matches.all(competition="cp7k2pq9x"):
62
+ ...
63
+ """
64
+ return _walk(lambda cursor: self._api.list(**filters, cursor=cursor), "matches")
65
+
66
+ async def get(self, id: str) -> Match:
67
+ return await asyncio.to_thread(self._api.get, id)
68
+
69
+ async def timeline(
70
+ self, id: str, *, cursor: Optional[str] = None, limit: Optional[int] = None
71
+ ) -> Timeline:
72
+ return await asyncio.to_thread(self._api.timeline, id, cursor=cursor, limit=limit)
73
+
74
+ def events(self, id: str) -> AsyncIterator[TimelineEvent]:
75
+ """Every row of the timeline, a page at a time."""
76
+ return _walk(lambda cursor: self._api.timeline(id, cursor=cursor), "events")
77
+
78
+ async def sync(self, since: Optional[datetime] = None, **filters: Any) -> MatchSync:
79
+ """:meth:`MatchesApi.sync`."""
80
+ return await asyncio.to_thread(self._api.sync, since, **filters)
81
+
82
+
83
+ class AsyncCompetitionsApi:
84
+ """:class:`CompetitionsApi`, awaitable."""
85
+
86
+ def __init__(self, api: CompetitionsApi) -> None:
87
+ self._api = api
88
+
89
+ async def list(
90
+ self,
91
+ *,
92
+ season: Optional[str] = None,
93
+ series: Optional[str] = None,
94
+ federation: Optional[str] = None,
95
+ updated_since: Optional[datetime] = None,
96
+ ) -> List[Competition]:
97
+ return await asyncio.to_thread(
98
+ self._api.list,
99
+ season=season,
100
+ series=series,
101
+ federation=federation,
102
+ updated_since=updated_since,
103
+ )
104
+
105
+ async def get(self, id: str) -> CompetitionDetail:
106
+ return await asyncio.to_thread(self._api.get, id)
107
+
108
+
109
+ class AsyncClubsApi:
110
+ """:class:`ClubsApi`, awaitable."""
111
+
112
+ def __init__(self, api: ClubsApi) -> None:
113
+ self._api = api
114
+
115
+ async def get(self, id: str) -> Club:
116
+ return await asyncio.to_thread(self._api.get, id)
117
+
118
+ async def logo(self, logo_url: str) -> bytes:
119
+ return await asyncio.to_thread(self._api.logo, logo_url)
120
+
121
+
122
+ class AsyncCourtsApi:
123
+ """:class:`CourtsApi`, awaitable."""
124
+
125
+ def __init__(self, api: CourtsApi) -> None:
126
+ self._api = api
127
+
128
+ async def list(self) -> List[Court]:
129
+ return await asyncio.to_thread(self._api.list)
130
+
131
+ async def get(self, id: str) -> CourtSnapshot:
132
+ return await asyncio.to_thread(self._api.get, id)
133
+
134
+
135
+ class AsyncStreamcomClient:
136
+ """:class:`StreamcomClient` for ``asyncio``, with the same options::
137
+
138
+ streamcom = AsyncStreamcomClient(token=os.environ["STREAMCOM_TOKEN"])
139
+ match = await streamcom.matches.get("mt4n8w2qa")
140
+
141
+ stream = streamcom.stream(courts=["ct9w3d5ke"])
142
+ with stream:
143
+ async for event in stream.aevents():
144
+ ...
145
+ """
146
+
147
+ def __init__(self, token: Optional[str], **options: Any) -> None:
148
+ self.sync_client = StreamcomClient(token, **options)
149
+ """The blocking client underneath, for code that is not async."""
150
+ self.matches = AsyncMatchesApi(self.sync_client.matches)
151
+ self.competitions = AsyncCompetitionsApi(self.sync_client.competitions)
152
+ self.clubs = AsyncClubsApi(self.sync_client.clubs)
153
+ self.courts = AsyncCourtsApi(self.sync_client.courts)
154
+
155
+ def stream(
156
+ self,
157
+ courts: Optional[Iterable[str]] = None,
158
+ matches: Optional[Iterable[str]] = None,
159
+ competitions: Optional[Iterable[str]] = None,
160
+ **options: Any,
161
+ ) -> LiveStream:
162
+ """:meth:`StreamcomClient.stream`; iterate it with ``async for … in stream.aevents()``.
163
+ Its handlers run on the stream's own thread, not in the event loop."""
164
+ return self.sync_client.stream(courts, matches, competitions, **options)
165
+
166
+
167
+ __all__ = [
168
+ "AsyncClubsApi",
169
+ "AsyncCompetitionsApi",
170
+ "AsyncCourtsApi",
171
+ "AsyncMatchesApi",
172
+ "AsyncStreamcomClient",
173
+ ]
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ import random as _random
4
+ from dataclasses import dataclass
5
+ from typing import Callable
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Backoff:
10
+ """How long to wait before trying again: doubling from ``min`` to ``max`` seconds, jittered
11
+ by ``jitter`` either way. The stream redials on ``Backoff()`` (1 to 30 s, a fifth either
12
+ way), as the npm package and the Java SDK do.
13
+
14
+ Jittered because the platform deploys: clients that redial on the same schedule all arrive in
15
+ the same second. Attempt 0 waits too: a socket that closed the instant it opened will do so
16
+ again, and dialling straight back is a tight loop.
17
+ """
18
+
19
+ min: float = 1.0
20
+ max: float = 30.0
21
+ jitter: float = 0.2
22
+
23
+ def __post_init__(self) -> None:
24
+ if not 0 < self.min <= self.max:
25
+ raise ValueError("Backoff: 0 < min <= max, in seconds")
26
+ if not 0 <= self.jitter < 1:
27
+ raise ValueError("Backoff: jitter is a fraction from 0 up to 1")
28
+
29
+ def delay_ms(self, attempt: int, random: Callable[[], float] = _random.random) -> int:
30
+ """The delay before attempt ``attempt`` (zero-based), in ms."""
31
+ doubled = min(self.max * 1000, self.min * 1000 * 2.0 ** max(0, min(attempt, 30)))
32
+ return round(doubled * (1 - self.jitter + random() * self.jitter * 2))