ovok-sdk 0.1.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.
Files changed (53) hide show
  1. ovok_sdk/__init__.py +75 -0
  2. ovok_sdk/auth/__init__.py +1 -0
  3. ovok_sdk/auth/access_token.py +31 -0
  4. ovok_sdk/auth/client_credentials.py +55 -0
  5. ovok_sdk/auth/credentials.py +28 -0
  6. ovok_sdk/auth/pkce.py +39 -0
  7. ovok_sdk/auth/session.py +85 -0
  8. ovok_sdk/auth/session_store.py +87 -0
  9. ovok_sdk/auth/single_flight.py +54 -0
  10. ovok_sdk/auth/token_endpoint.py +71 -0
  11. ovok_sdk/auth/user_session.py +121 -0
  12. ovok_sdk/clock.py +14 -0
  13. ovok_sdk/config.py +158 -0
  14. ovok_sdk/errors.py +142 -0
  15. ovok_sdk/http/__init__.py +1 -0
  16. ovok_sdk/http/client.py +137 -0
  17. ovok_sdk/http/error_response.py +256 -0
  18. ovok_sdk/http/request.py +26 -0
  19. ovok_sdk/http/retry.py +75 -0
  20. ovok_sdk/http/transport.py +141 -0
  21. ovok_sdk/http/url.py +65 -0
  22. ovok_sdk/ovok.py +151 -0
  23. ovok_sdk/paging.py +140 -0
  24. ovok_sdk/py.typed +0 -0
  25. ovok_sdk/resources/__init__.py +1 -0
  26. ovok_sdk/resources/ai.py +139 -0
  27. ovok_sdk/resources/auth.py +332 -0
  28. ovok_sdk/resources/auth_sessions.py +43 -0
  29. ovok_sdk/resources/bots.py +32 -0
  30. ovok_sdk/resources/cms.py +264 -0
  31. ovok_sdk/resources/consent.py +93 -0
  32. ovok_sdk/resources/content.py +143 -0
  33. ovok_sdk/resources/documents.py +108 -0
  34. ovok_sdk/resources/fhir.py +179 -0
  35. ovok_sdk/resources/health.py +33 -0
  36. ovok_sdk/resources/invites.py +85 -0
  37. ovok_sdk/resources/measurement_builder.py +728 -0
  38. ovok_sdk/resources/measurements.py +797 -0
  39. ovok_sdk/resources/patient.py +160 -0
  40. ovok_sdk/resources/platform.py +348 -0
  41. ovok_sdk/resources/questionnaires.py +106 -0
  42. ovok_sdk/resources/registration.py +100 -0
  43. ovok_sdk/resources/sharing.py +121 -0
  44. ovok_sdk/resources/signals.py +127 -0
  45. ovok_sdk/resources/slim.py +1055 -0
  46. ovok_sdk/resources/video_calls.py +170 -0
  47. ovok_sdk/resources/wearables.py +132 -0
  48. ovok_sdk/storage.py +40 -0
  49. ovok_sdk/values.py +12 -0
  50. ovok_sdk-0.1.0.dist-info/METADATA +292 -0
  51. ovok_sdk-0.1.0.dist-info/RECORD +53 -0
  52. ovok_sdk-0.1.0.dist-info/WHEEL +4 -0
  53. ovok_sdk-0.1.0.dist-info/licenses/LICENSE +661 -0
ovok_sdk/__init__.py ADDED
@@ -0,0 +1,75 @@
1
+ """Python SDK for Ovok Core: FHIR R4 and platform APIs through one tenant-scoped client."""
2
+
3
+ from ovok_sdk.auth.session import OvokReference, Session
4
+ from ovok_sdk.config import UnauthenticatedReason
5
+ from ovok_sdk.errors import (
6
+ FieldError,
7
+ OvokAuthenticationError,
8
+ OvokConfigError,
9
+ OvokConflictError,
10
+ OvokConnectionError,
11
+ OvokError,
12
+ OvokErrorDetails,
13
+ OvokNotFoundError,
14
+ OvokPermissionError,
15
+ OvokRateLimitError,
16
+ OvokServiceError,
17
+ OvokValidationError,
18
+ )
19
+ from ovok_sdk.http.transport import (
20
+ OvokRequest,
21
+ OvokResponse,
22
+ Transport,
23
+ UrllibTransport,
24
+ )
25
+ from ovok_sdk.ovok import Ovok
26
+ from ovok_sdk.paging import Page
27
+ from ovok_sdk.resources.auth import (
28
+ LoginResult,
29
+ MfaChallenge,
30
+ MfaRequired,
31
+ RegisterResult,
32
+ SignedIn,
33
+ )
34
+ from ovok_sdk.resources.measurement_builder import MeasurementTypeKey
35
+ from ovok_sdk.resources.registration import (
36
+ ClinicianInvite,
37
+ PatientRegistration,
38
+ Registration,
39
+ )
40
+ from ovok_sdk.storage import MemoryStorage, OvokStorage
41
+
42
+ __all__ = [
43
+ "ClinicianInvite",
44
+ "FieldError",
45
+ "LoginResult",
46
+ "MeasurementTypeKey",
47
+ "MemoryStorage",
48
+ "MfaChallenge",
49
+ "MfaRequired",
50
+ "Ovok",
51
+ "OvokAuthenticationError",
52
+ "OvokConfigError",
53
+ "OvokConflictError",
54
+ "OvokConnectionError",
55
+ "OvokError",
56
+ "OvokErrorDetails",
57
+ "OvokNotFoundError",
58
+ "OvokPermissionError",
59
+ "OvokRateLimitError",
60
+ "OvokReference",
61
+ "OvokRequest",
62
+ "OvokResponse",
63
+ "OvokServiceError",
64
+ "OvokStorage",
65
+ "OvokValidationError",
66
+ "Page",
67
+ "PatientRegistration",
68
+ "RegisterResult",
69
+ "Registration",
70
+ "Session",
71
+ "SignedIn",
72
+ "Transport",
73
+ "UnauthenticatedReason",
74
+ "UrllibTransport",
75
+ ]
@@ -0,0 +1 @@
1
+ """Sessions, tokens and the credentials that sign requests."""
@@ -0,0 +1,31 @@
1
+ """OAuth access tokens and their expiry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from ovok_sdk.clock import MS_PER_SECOND
8
+
9
+ REFRESH_MARGIN_MS = 60_000
10
+
11
+
12
+ def expires_at_for(expires_in_seconds: float, now_ms: int) -> int:
13
+ """Return the epoch-millisecond expiry of a token that lives `expires_in_seconds` from `now_ms`."""
14
+ return now_ms + round(expires_in_seconds * MS_PER_SECOND)
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class AccessToken:
19
+ """A bearer token and when it expires.
20
+
21
+ Attributes:
22
+ value: The token; never shown in `repr`.
23
+ expires_at_ms: Expiry in epoch milliseconds.
24
+ """
25
+
26
+ value: str = field(repr=False)
27
+ expires_at_ms: int
28
+
29
+ def is_stale_at(self, now_ms: int) -> bool:
30
+ """Stale a minute early, so a token never expires between the check and the request."""
31
+ return now_ms >= self.expires_at_ms - REFRESH_MARGIN_MS
@@ -0,0 +1,55 @@
1
+ """Machine-client authentication with the OAuth client-credentials grant."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ovok_sdk.auth.access_token import AccessToken, expires_at_for
6
+ from ovok_sdk.auth.single_flight import SingleFlight
7
+ from ovok_sdk.auth.token_endpoint import TokenEndpoint
8
+ from ovok_sdk.clock import Clock, epoch_ms
9
+ from ovok_sdk.config import MachineClient
10
+
11
+ CLIENT_CREDENTIALS_GRANT = "client_credentials"
12
+
13
+
14
+ class ClientCredentials:
15
+ """A machine client's own token, fetched from the OAuth endpoint and renewed before it expires.
16
+
17
+ Args:
18
+ endpoint: The OAuth token endpoint.
19
+ client: The machine client's credentials.
20
+ clock: Current time in epoch milliseconds.
21
+ """
22
+
23
+ def __init__(self, endpoint: TokenEndpoint, client: MachineClient, clock: Clock = epoch_ms) -> None:
24
+ self._endpoint = endpoint
25
+ self._client = client
26
+ self._clock = clock
27
+ self._token: AccessToken | None = None
28
+ self._flight: SingleFlight[AccessToken] = SingleFlight()
29
+
30
+ def access_token(self) -> str:
31
+ """Return a fresh access token, requesting a new one when the current one is stale."""
32
+ token = self._token
33
+ if token is None or token.is_stale_at(self._clock()):
34
+ token = self._flight.run(self._request_token)
35
+ return token.value
36
+
37
+ def refresh(self) -> bool:
38
+ """Request a new token.
39
+
40
+ Returns:
41
+ Always True; a failed request raises instead.
42
+ """
43
+ self._flight.run(self._request_token)
44
+ return True
45
+
46
+ def _request_token(self) -> AccessToken:
47
+ response = self._endpoint.request(
48
+ {
49
+ "grant_type": CLIENT_CREDENTIALS_GRANT,
50
+ "client_id": self._client.client_id,
51
+ "client_secret": self._client.client_secret,
52
+ }
53
+ )
54
+ self._token = AccessToken(response.access_token, expires_at_for(response.expires_in, self._clock()))
55
+ return self._token
@@ -0,0 +1,28 @@
1
+ """The interface that supplies bearer tokens to requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol
6
+
7
+
8
+ class Credentials(Protocol):
9
+ """Supplies the bearer token for each request and renews it on demand."""
10
+
11
+ def access_token(self) -> str | None:
12
+ """Return the current access token, or None when there is none."""
13
+ ...
14
+
15
+ def refresh(self) -> bool:
16
+ """Renew the token; return whether a new one is available."""
17
+ ...
18
+
19
+
20
+ class _NoCredentials:
21
+ def access_token(self) -> None:
22
+ return None
23
+
24
+ def refresh(self) -> bool:
25
+ return False
26
+
27
+
28
+ NO_CREDENTIALS: Credentials = _NoCredentials()
ovok_sdk/auth/pkce.py ADDED
@@ -0,0 +1,39 @@
1
+ """PKCE (RFC 7636) verifier and challenge generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import secrets
8
+ import string
9
+ from dataclasses import dataclass, field
10
+
11
+ VERIFIER_LENGTH = 128
12
+ UNRESERVED_CHARACTERS = string.ascii_letters + string.digits + "-._~"
13
+ ASCII = "ascii"
14
+ BASE64_PADDING = "="
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class PkcePair:
19
+ """A PKCE code verifier and its S256 challenge.
20
+
21
+ Attributes:
22
+ code_verifier: Random secret; never shown in `repr`.
23
+ code_challenge: Base64url SHA-256 of the verifier, without padding.
24
+ """
25
+
26
+ code_verifier: str = field(repr=False)
27
+ code_challenge: str
28
+
29
+
30
+ def generate_pkce_pair() -> PkcePair:
31
+ """Return a new random verifier of 128 unreserved characters and its challenge."""
32
+ verifier = "".join(secrets.choice(UNRESERVED_CHARACTERS) for _ in range(VERIFIER_LENGTH))
33
+ return PkcePair(verifier, code_challenge_for(verifier))
34
+
35
+
36
+ def code_challenge_for(verifier: str) -> str:
37
+ """Return the S256 code challenge for `verifier`."""
38
+ digest = hashlib.sha256(verifier.encode(ASCII)).digest()
39
+ return base64.urlsafe_b64encode(digest).decode(ASCII).rstrip(BASE64_PADDING)
@@ -0,0 +1,85 @@
1
+ """The signed-in user's session and its JSON conversions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field, replace
7
+ from typing import Any
8
+
9
+ from ovok_sdk.auth.access_token import AccessToken, expires_at_for
10
+ from ovok_sdk.auth.token_endpoint import TokenResponse
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class OvokReference:
15
+ """A FHIR reference to a resource.
16
+
17
+ Attributes:
18
+ reference: Relative reference, such as `Patient/123`.
19
+ display: Human-readable label, when the API sends one.
20
+ """
21
+
22
+ reference: str
23
+ display: str | None = None
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Session:
28
+ """The signed-in user's tokens, project and profile.
29
+
30
+ Attributes:
31
+ access_token: Bearer token; never shown in `repr`.
32
+ refresh_token: Token that renews the session, if any; never shown in `repr`.
33
+ expires_at_ms: Access-token expiry in epoch milliseconds.
34
+ project: The project the user signed in to.
35
+ profile: The user's profile resource, such as a Patient or Practitioner.
36
+ """
37
+
38
+ access_token: str = field(repr=False)
39
+ refresh_token: str | None = field(repr=False)
40
+ expires_at_ms: int
41
+ project: OvokReference
42
+ profile: OvokReference
43
+
44
+ def is_stale_at(self, now_ms: int) -> bool:
45
+ """Whether the access token is within a minute of expiring at `now_ms`."""
46
+ return AccessToken(self.access_token, self.expires_at_ms).is_stale_at(now_ms)
47
+
48
+
49
+ def session_from_login(tokens: Mapping[str, Any], now_ms: int) -> Session:
50
+ """Build a session from a sign-in response.
51
+
52
+ Args:
53
+ tokens: The camelCase body every Ovok sign-in route answers with.
54
+ now_ms: Current time in epoch milliseconds.
55
+
56
+ Returns:
57
+ The new session.
58
+ """
59
+ return Session(
60
+ access_token=tokens["accessToken"],
61
+ refresh_token=tokens.get("refreshToken"),
62
+ expires_at_ms=expires_at_for(tokens["expiresIn"], now_ms),
63
+ project=reference_from_json(tokens["project"]),
64
+ profile=reference_from_json(tokens["profile"]),
65
+ )
66
+
67
+
68
+ def session_after_refresh(session: Session, response: TokenResponse, now_ms: int) -> Session:
69
+ """Return `session` with the tokens from a refresh, keeping the old refresh token if none came back."""
70
+ return replace(
71
+ session,
72
+ access_token=response.access_token,
73
+ refresh_token=response.refresh_token or session.refresh_token,
74
+ expires_at_ms=expires_at_for(response.expires_in, now_ms),
75
+ )
76
+
77
+
78
+ def reference_from_json(value: Mapping[str, Any]) -> OvokReference:
79
+ """Read a reference from its FHIR JSON shape."""
80
+ return OvokReference(value["reference"], value.get("display"))
81
+
82
+
83
+ def reference_to_json(reference: OvokReference) -> dict[str, Any]:
84
+ """Write a reference in its FHIR JSON shape."""
85
+ return {"reference": reference.reference, "display": reference.display}
@@ -0,0 +1,87 @@
1
+ """Persistence of the user session in `OvokStorage`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from ovok_sdk.auth.session import Session, reference_from_json, reference_to_json
9
+ from ovok_sdk.storage import OvokStorage
10
+ from ovok_sdk.values import finite_number
11
+
12
+ SESSION_KEY = "ovok:{tenant_code}:session"
13
+
14
+
15
+ class SessionStore:
16
+ """Keeps the session as JSON in the TypeScript SDK's shape, so stores are interchangeable.
17
+
18
+ Args:
19
+ storage: Where the session is kept.
20
+ key: Storage key of the session.
21
+ """
22
+
23
+ def __init__(self, storage: OvokStorage, key: str) -> None:
24
+ self._storage = storage
25
+ self._key = key
26
+
27
+ @classmethod
28
+ def for_tenant(cls, storage: OvokStorage, tenant_code: str) -> SessionStore:
29
+ """One key per tenant, so clearing a session never touches anything else in shared storage."""
30
+ return cls(storage, SESSION_KEY.format(tenant_code=tenant_code))
31
+
32
+ def load(self) -> Session | None:
33
+ """Return the stored session, or None when none is stored or it is unreadable."""
34
+ raw = self._storage.get_item(self._key)
35
+ return None if raw is None else _session_from_json(raw)
36
+
37
+ def save(self, session: Session) -> None:
38
+ """Store `session`, replacing any earlier one."""
39
+ self._storage.set_item(self._key, _session_to_json(session))
40
+
41
+ def clear(self) -> None:
42
+ """Delete the stored session."""
43
+ self._storage.remove_item(self._key)
44
+
45
+
46
+ def _session_to_json(session: Session) -> str:
47
+ return json.dumps(
48
+ {
49
+ "accessToken": session.access_token,
50
+ "refreshToken": session.refresh_token,
51
+ "expiresAt": session.expires_at_ms,
52
+ "project": reference_to_json(session.project),
53
+ "profile": reference_to_json(session.profile),
54
+ }
55
+ )
56
+
57
+
58
+ def _session_from_json(raw: str) -> Session | None:
59
+ try:
60
+ value = json.loads(raw)
61
+ except ValueError:
62
+ return None
63
+ return _session_from(value) if _is_complete(value) else None
64
+
65
+
66
+ def _session_from(value: dict[str, Any]) -> Session:
67
+ return Session(
68
+ access_token=value["accessToken"],
69
+ refresh_token=value.get("refreshToken"),
70
+ expires_at_ms=value["expiresAt"],
71
+ project=reference_from_json(value["project"]),
72
+ profile=reference_from_json(value["profile"]),
73
+ )
74
+
75
+
76
+ def _is_complete(value: Any) -> bool:
77
+ return (
78
+ isinstance(value, dict)
79
+ and isinstance(value.get("accessToken"), str)
80
+ and finite_number(value.get("expiresAt")) is not None
81
+ and _is_reference(value.get("project"))
82
+ and _is_reference(value.get("profile"))
83
+ )
84
+
85
+
86
+ def _is_reference(value: Any) -> bool:
87
+ return isinstance(value, dict) and isinstance(value.get("reference"), str)
@@ -0,0 +1,54 @@
1
+ """Deduplication of concurrent calls, such as token refreshes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from collections.abc import Callable
7
+ from functools import partial
8
+ from typing import Generic, NoReturn, TypeVar
9
+
10
+ T = TypeVar("T")
11
+
12
+ Settled = Callable[[], T]
13
+
14
+
15
+ class SingleFlight(Generic[T]):
16
+ """Runs one call at a time; callers who arrive while it runs share its outcome instead of repeating it."""
17
+
18
+ def __init__(self) -> None:
19
+ self._lock = threading.Lock()
20
+ self._finished_calls = 0
21
+ self._latest: Settled[T] = _nothing_ran
22
+
23
+ def run(self, call: Callable[[], T]) -> T:
24
+ """Run `call`, or wait for the run in progress and share its outcome.
25
+
26
+ Returns:
27
+ The call's result.
28
+
29
+ Raises:
30
+ Exception: Whatever the shared call raised.
31
+ """
32
+ calls_seen = self._finished_calls
33
+ with self._lock:
34
+ if self._finished_calls == calls_seen:
35
+ self._latest = _settle(call)
36
+ self._finished_calls += 1
37
+ latest = self._latest
38
+ return latest()
39
+
40
+
41
+ def _settle(call: Callable[[], T]) -> Settled[T]:
42
+ try:
43
+ value = call()
44
+ except Exception as error:
45
+ return partial(_reraise, error)
46
+ return lambda: value
47
+
48
+
49
+ def _reraise(error: Exception) -> NoReturn:
50
+ raise error
51
+
52
+
53
+ def _nothing_ran() -> NoReturn:
54
+ raise RuntimeError("SingleFlight has run nothing yet.")
@@ -0,0 +1,71 @@
1
+ """The OAuth token endpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+ from urllib.parse import urlencode
9
+
10
+ from ovok_sdk.config import OvokSettings
11
+ from ovok_sdk.http.error_response import error_from_response
12
+ from ovok_sdk.http.transport import OvokRequest
13
+
14
+ TOKEN_PATH = "oauth2/token"
15
+ FORM_HEADERS = {"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"}
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class TokenResponse:
20
+ """A successful token endpoint response.
21
+
22
+ Attributes:
23
+ access_token: The new bearer token; never shown in `repr`.
24
+ expires_in: Lifetime of the access token in seconds.
25
+ refresh_token: A new refresh token, when the endpoint issues one.
26
+ """
27
+
28
+ access_token: str = field(repr=False)
29
+ expires_in: float
30
+ refresh_token: str | None = field(default=None, repr=False)
31
+
32
+ @classmethod
33
+ def from_json(cls, body: Mapping[str, Any]) -> TokenResponse:
34
+ """Read the snake_case OAuth response body."""
35
+ return cls(body["access_token"], body["expires_in"], body.get("refresh_token"))
36
+
37
+
38
+ class TokenEndpoint:
39
+ """Ovok's OAuth token endpoint: one plain form POST, without retries or credentials.
40
+
41
+ Args:
42
+ settings: The client's settings.
43
+ """
44
+
45
+ def __init__(self, settings: OvokSettings) -> None:
46
+ self._settings = settings
47
+
48
+ def request(self, form: Mapping[str, str]) -> TokenResponse:
49
+ """Post `form` to the token endpoint.
50
+
51
+ Args:
52
+ form: OAuth form fields, such as `grant_type`.
53
+
54
+ Returns:
55
+ The issued tokens.
56
+
57
+ Raises:
58
+ OvokError: The endpoint answered with an error.
59
+ """
60
+ response = self._settings.transport(
61
+ OvokRequest(
62
+ method="POST",
63
+ url=f"{self._settings.base_url}{TOKEN_PATH}",
64
+ headers=FORM_HEADERS,
65
+ body=urlencode(form),
66
+ timeout=self._settings.timeout,
67
+ )
68
+ )
69
+ if response.is_success:
70
+ return TokenResponse.from_json(response.json())
71
+ raise error_from_response(response)
@@ -0,0 +1,121 @@
1
+ """The signed-in user's session and its token refresh."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from typing import Any
7
+
8
+ from ovok_sdk.auth.session import Session, session_after_refresh, session_from_login
9
+ from ovok_sdk.auth.session_store import SessionStore
10
+ from ovok_sdk.auth.single_flight import SingleFlight
11
+ from ovok_sdk.auth.token_endpoint import TokenEndpoint
12
+ from ovok_sdk.clock import Clock, epoch_ms
13
+ from ovok_sdk.config import OvokSettings, UnauthenticatedReason
14
+ from ovok_sdk.errors import OvokError
15
+
16
+ REFRESH_TOKEN_GRANT = "refresh_token"
17
+ REJECTED_REFRESH_STATUSES = frozenset({400, 401, 403})
18
+
19
+
20
+ class UserSession:
21
+ """The signed-in user's tokens, kept in storage and refreshed a minute before they expire.
22
+
23
+ Args:
24
+ store: Where the session is kept.
25
+ endpoint: The OAuth token endpoint used to refresh.
26
+ settings: The client's settings.
27
+ clock: Current time in epoch milliseconds.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ store: SessionStore,
33
+ endpoint: TokenEndpoint,
34
+ settings: OvokSettings,
35
+ clock: Clock = epoch_ms,
36
+ ) -> None:
37
+ self._store = store
38
+ self._endpoint = endpoint
39
+ self._settings = settings
40
+ self._clock = clock
41
+ self._flight: SingleFlight[bool] = SingleFlight()
42
+ self._listeners: list[Callable[[], None]] = []
43
+
44
+ def current(self) -> Session | None:
45
+ """Return the stored session, or None when no one is signed in."""
46
+ return self._store.load()
47
+
48
+ def begin(self, tokens: Mapping[str, Any]) -> Session:
49
+ """Start a session from a sign-in response and notify listeners.
50
+
51
+ Args:
52
+ tokens: The camelCase body of an Ovok sign-in route.
53
+
54
+ Returns:
55
+ The new session.
56
+ """
57
+ session = session_from_login(tokens, self._clock())
58
+ self._store.save(session)
59
+ self._notify_change()
60
+ return session
61
+
62
+ def end(self) -> None:
63
+ """Delete the session and notify listeners."""
64
+ self._store.clear()
65
+ self._notify_change()
66
+
67
+ def on_change(self, listener: Callable[[], None]) -> None:
68
+ """Call `listener` whenever the session starts, refreshes or ends."""
69
+ self._listeners.append(listener)
70
+
71
+ def access_token(self) -> str | None:
72
+ """Return the access token, refreshing it first when it is stale; None when signed out."""
73
+ if self._needs_refresh(self.current()):
74
+ self.refresh()
75
+ session = self.current()
76
+ return None if session is None else session.access_token
77
+
78
+ def refresh(self) -> bool:
79
+ """Exchange the refresh token for new tokens.
80
+
81
+ A refused refresh signs the user out and calls `on_unauthenticated`.
82
+
83
+ Returns:
84
+ True when the session was refreshed; False when there is nothing to refresh
85
+ or the refresh was refused.
86
+
87
+ Raises:
88
+ OvokError: The refresh failed for another reason, such as an outage.
89
+ """
90
+ return self._flight.run(self._exchange_refresh_token)
91
+
92
+ def _needs_refresh(self, session: Session | None) -> bool:
93
+ return session is not None and session.refresh_token is not None and session.is_stale_at(self._clock())
94
+
95
+ def _exchange_refresh_token(self) -> bool:
96
+ session = self.current()
97
+ if session is None or session.refresh_token is None:
98
+ return False
99
+ try:
100
+ response = self._endpoint.request(self._refresh_form(session.refresh_token))
101
+ except OvokError as error:
102
+ return self._sign_out_if_rejected(error)
103
+ self._store.save(session_after_refresh(session, response, self._clock()))
104
+ self._notify_change()
105
+ return True
106
+
107
+ def _notify_change(self) -> None:
108
+ for listener in tuple(self._listeners):
109
+ listener()
110
+
111
+ def _sign_out_if_rejected(self, error: OvokError) -> bool:
112
+ """Only a refused refresh token signs the user out; an outage keeps the session for a later retry."""
113
+ if error.status in REJECTED_REFRESH_STATUSES:
114
+ self.end()
115
+ self._settings.on_unauthenticated(UnauthenticatedReason(status=error.status))
116
+ return False
117
+ raise error
118
+
119
+ def _refresh_form(self, refresh_token: str) -> dict[str, str]:
120
+ client = {} if self._settings.client_id is None else {"client_id": self._settings.client_id}
121
+ return {"grant_type": REFRESH_TOKEN_GRANT, "refresh_token": refresh_token, **client}
ovok_sdk/clock.py ADDED
@@ -0,0 +1,14 @@
1
+ """Wall-clock time in epoch milliseconds."""
2
+
3
+ import time
4
+ from collections.abc import Callable
5
+
6
+ MS_PER_SECOND = 1000
7
+ NS_PER_MS = 1_000_000
8
+
9
+ Clock = Callable[[], int]
10
+
11
+
12
+ def epoch_ms() -> int:
13
+ """Return the current time in milliseconds since the Unix epoch."""
14
+ return time.time_ns() // NS_PER_MS