bakbak-python 1.0.0rc2__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.
bakbak/_types.py ADDED
@@ -0,0 +1,79 @@
1
+ """Client option types: the NOT_GIVEN sentinel and Timeout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import Final, Literal, TypeAlias
8
+
9
+ from typing_extensions import override
10
+
11
+ from ._constants import DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT
12
+
13
+ __all__ = ["NOT_GIVEN", "NotGiven", "Timeout", "TimeoutLike"]
14
+
15
+
16
+ class NotGiven:
17
+ """Marks an option the caller did not pass, as distinct from ``None``.
18
+
19
+ ``timeout=None`` disables timeouts, while leaving ``timeout`` out keeps the
20
+ client's default. ``NOT_GIVEN`` is the value of the latter.
21
+ """
22
+
23
+ __slots__ = ()
24
+
25
+ def __bool__(self) -> Literal[False]:
26
+ return False
27
+
28
+ @override
29
+ def __repr__(self) -> str:
30
+ return "NOT_GIVEN"
31
+
32
+
33
+ NOT_GIVEN: Final = NotGiven()
34
+
35
+
36
+ @dataclass(slots=True, frozen=True)
37
+ class Timeout:
38
+ """Timeouts in seconds (BEHAVIOR.md §4.4). ``None`` disables one.
39
+
40
+ Attributes:
41
+ connect: TCP and TLS setup, plus the upgrade for a WebSocket.
42
+ read: the longest wait for the next byte of a response, or for the next
43
+ message of a WebSocket context that has unfinished requests. It
44
+ includes the time to first audio.
45
+ total: an optional limit on a whole HTTP call, retries and backoff
46
+ included. It is checked between reads, and caps each read.
47
+ """
48
+
49
+ connect: float | None = DEFAULT_CONNECT_TIMEOUT
50
+ read: float | None = DEFAULT_READ_TIMEOUT
51
+ total: float | None = None
52
+
53
+ def __post_init__(self) -> None:
54
+ for name in ("connect", "read", "total"):
55
+ value = getattr(self, name)
56
+ if value is not None and (
57
+ isinstance(value, bool)
58
+ or not isinstance(value, (int, float))
59
+ or math.isnan(value)
60
+ or value <= 0
61
+ ):
62
+ raise ValueError(f"Timeout.{name} must be a positive number of seconds or None")
63
+
64
+
65
+ TimeoutLike: TypeAlias = float | Timeout | None
66
+ """A ``Timeout``; a number, which sets the read timeout (and caps the connect
67
+ timeout at that value); or ``None`` for no timeouts at all."""
68
+
69
+
70
+ def coerce_timeout(value: TimeoutLike) -> Timeout:
71
+ """Normalise the accepted timeout forms into a ``Timeout``."""
72
+ if isinstance(value, Timeout):
73
+ return value
74
+ if value is None:
75
+ return Timeout(connect=None, read=None, total=None)
76
+ if isinstance(value, bool) or not isinstance(value, (int, float)): # pyright: ignore[reportUnnecessaryIsInstance]
77
+ raise TypeError("timeout must be a number of seconds, a bakbak.Timeout, or None")
78
+ seconds = float(value)
79
+ return Timeout(connect=min(DEFAULT_CONNECT_TIMEOUT, seconds), read=seconds, total=None)
bakbak/_utils.py ADDED
@@ -0,0 +1,62 @@
1
+ """Identity headers, logging and URL helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ import re
8
+ import sys
9
+ from collections.abc import Mapping
10
+ from typing import cast
11
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
12
+
13
+ from ._constants import PACKAGE_NAME
14
+ from ._version import __version__
15
+
16
+ __all__ = ["as_mapping", "client_header", "logger", "redact_url", "user_agent", "websocket_url"]
17
+
18
+ logger = logging.getLogger("bakbak")
19
+ """The SDK's logger. It logs at DEBUG only, and never the API key or any text."""
20
+
21
+ _SECRET_QUERY_KEYS = frozenset({"x-api-key", "api_key", "apikey", "key", "token"})
22
+
23
+
24
+ def redact_url(url: str) -> str:
25
+ """``url`` with any credential in the query string replaced by ``***``."""
26
+ parts = urlsplit(url)
27
+ if not parts.query:
28
+ return url
29
+ query = [
30
+ (k, "***" if k.lower() in _SECRET_QUERY_KEYS else v)
31
+ for k, v in parse_qsl(parts.query, keep_blank_values=True)
32
+ ]
33
+ return urlunsplit(parts._replace(query=urlencode(query, safe="*")))
34
+
35
+
36
+ def user_agent() -> str:
37
+ """``bakbak-python/<version> python/<version> <os>/<arch>`` (BEHAVIOR.md §8)."""
38
+ python = ".".join(str(p) for p in sys.version_info[:3])
39
+ system = platform.system().lower() or "unknown"
40
+ machine = platform.machine().lower() or "unknown"
41
+ return f"{PACKAGE_NAME}/{__version__} python/{python} {system}/{machine}"
42
+
43
+
44
+ def client_header() -> str:
45
+ """The ``X-Bakbak-Client`` value."""
46
+ return f"{PACKAGE_NAME}/{__version__}"
47
+
48
+
49
+ _SCHEME = re.compile(r"^http", re.IGNORECASE)
50
+
51
+
52
+ def websocket_url(base_url: str, path: str) -> str:
53
+ """The WebSocket URL for ``path``: the base URL with https -> wss (or
54
+ http -> ws), plus the path."""
55
+ parts = urlsplit(base_url)
56
+ scheme = _SCHEME.sub("ws", parts.scheme)
57
+ return urlunsplit((scheme, parts.netloc, parts.path.rstrip("/") + path, "", ""))
58
+
59
+
60
+ def as_mapping(value: object) -> Mapping[str, object] | None:
61
+ """``value`` as a JSON object, or ``None`` if it is not one."""
62
+ return cast("Mapping[str, object]", value) if isinstance(value, Mapping) else None
bakbak/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ __title__ = "bakbak-python"
2
+ # release-please writes "1.0.0-rc.N"; PEP 440 reads it as 1.0.0rcN.
3
+ __version__ = "1.0.0-rc.2" # x-release-please-version
bakbak/_ws/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """The WebSocket client (BEHAVIOR.md §6); the public names are in ``bakbak.websocket``."""