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,130 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from datetime import datetime, timezone
5
+ from email.utils import parsedate_to_datetime
6
+ from enum import StrEnum
7
+ from typing import Any, Optional
8
+
9
+
10
+ class ApiErrorCode(StrEnum):
11
+ """The stable part of a refusal, spelled as the API writes it: ``"not_found"``."""
12
+
13
+ UNAUTHORIZED = "unauthorized"
14
+ """No token, a malformed one, or one unknown, revoked or expired (401)."""
15
+ NOT_FOUND = "not_found"
16
+ """It does not exist *or is not in this key's reach*: one answer on purpose (404). There is
17
+ no 403."""
18
+ INVALID_REQUEST = "invalid_request"
19
+ """A filter, a bound, a cursor or a limit is wrong (400, 422)."""
20
+ RATE_LIMITED = "rate_limited"
21
+ """60 requests a minute per key, v1 and v2 together (429). ``retry_after_ms`` says when."""
22
+ INTERNAL_ERROR = "internal_error"
23
+ """On Streamcom's side; retry with backoff (5xx)."""
24
+ NETWORK = "network"
25
+ """No answer at all, or an answer that could not be read."""
26
+
27
+
28
+ class ApiError(Exception):
29
+ """A refused request, with the stable part (``code``) apart from the part for a human
30
+ (``str(error)``).
31
+
32
+ ::
33
+
34
+ try:
35
+ match = streamcom.matches.get(match_id)
36
+ except ApiError as e:
37
+ if e.code == ApiErrorCode.NOT_FOUND:
38
+ ...
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ code: ApiErrorCode,
44
+ message: str,
45
+ status: Optional[int] = None,
46
+ retry_after_ms: Optional[int] = None,
47
+ ) -> None:
48
+ super().__init__(message)
49
+ self.code = code
50
+ self.status = status
51
+ """The HTTP status, or ``None`` when no answer arrived."""
52
+ self.retry_after_ms = retry_after_ms
53
+ """From ``Retry-After`` on a 429, in ms; otherwise ``None``."""
54
+
55
+ @property
56
+ def message(self) -> str:
57
+ return str(self)
58
+
59
+
60
+ def _by_status(status: int) -> ApiErrorCode:
61
+ if status == 401:
62
+ return ApiErrorCode.UNAUTHORIZED
63
+ if status == 404:
64
+ return ApiErrorCode.NOT_FOUND
65
+ if status in (400, 422):
66
+ return ApiErrorCode.INVALID_REQUEST
67
+ if status == 429:
68
+ return ApiErrorCode.RATE_LIMITED
69
+ return ApiErrorCode.INTERNAL_ERROR
70
+
71
+
72
+ _WIRE_CODES = {code.value: code for code in ApiErrorCode if code is not ApiErrorCode.NETWORK}
73
+
74
+
75
+ def refusal(
76
+ status: int, body: Any, path: str, retry_after: Optional[str], now: datetime
77
+ ) -> ApiError:
78
+ """The refusal body ``{"error": {"code", "message"}}`` as an error."""
79
+ error = body.get("error") if isinstance(body, dict) else None
80
+ wire_code = error.get("code") if isinstance(error, dict) else None
81
+ wire_message = error.get("message") if isinstance(error, dict) else None
82
+
83
+ known = _WIRE_CODES.get(wire_code) if isinstance(wire_code, str) else None
84
+ code = known or _by_status(status)
85
+ said = wire_message if isinstance(wire_message, str) else f"answered {status}"
86
+ hint = ""
87
+ if code == ApiErrorCode.UNAUTHORIZED:
88
+ hint = (
89
+ " Use a current API key from the portal's Data feed page, passed as `token` on its own."
90
+ )
91
+ elif code == ApiErrorCode.RATE_LIMITED:
92
+ hint = (
93
+ " A key may make 60 requests a minute over v1 and v2 together;"
94
+ " follow the stream instead of polling."
95
+ )
96
+ wait = parse_retry_after(retry_after, now) if status == 429 else None
97
+ return ApiError(code, f"GET {path}: {said}.{hint}", status, wait)
98
+
99
+
100
+ def network(message: str, status: Optional[int] = None) -> ApiError:
101
+ return ApiError(ApiErrorCode.NETWORK, message, status)
102
+
103
+
104
+ def parse_retry_after(value: Optional[str], now: datetime) -> Optional[int]:
105
+ """``Retry-After`` (seconds, or an HTTP date) in ms from ``now``, never below zero; ``None``
106
+ for absent or unreadable."""
107
+ if value is None or not value.strip():
108
+ return None
109
+ text = value.strip()
110
+ try:
111
+ seconds = float(text)
112
+ if math.isfinite(seconds):
113
+ return max(0, math.floor(seconds * 1000 + 0.5))
114
+ except ValueError:
115
+ pass # An HTTP date, perhaps.
116
+ at = _date(text)
117
+ if at is None:
118
+ return None
119
+ return max(0, round((at - now).total_seconds() * 1000))
120
+
121
+
122
+ def _date(text: str) -> Optional[datetime]:
123
+ try:
124
+ at = parsedate_to_datetime(text)
125
+ except (TypeError, ValueError):
126
+ try:
127
+ at = datetime.fromisoformat(text)
128
+ except ValueError:
129
+ return None
130
+ return at if at.tzinfo else at.replace(tzinfo=timezone.utc)
File without changes