interlude-sdk 0.2.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.
interlude/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """
2
+ Interlude Python SDK.
3
+
4
+ Official Python client library for the Interlude BaaS platform.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from .account import AccountClient
10
+ from .client import Client, EndUserAuth, UserScope
11
+ from .errors import ClientError, InterludeError
12
+ from .models import (
13
+ Account,
14
+ EndUser,
15
+ Filter,
16
+ Page,
17
+ Row,
18
+ StorageObject,
19
+ Summary,
20
+ SummaryGroup,
21
+ )
22
+ from .storage import StorageClient
23
+ from .table import TableClient
24
+
25
+ __version__ = "0.2.0"
26
+
27
+ __all__ = [
28
+ "Account",
29
+ "AccountClient",
30
+ "Client",
31
+ "ClientError",
32
+ "EndUser",
33
+ "EndUserAuth",
34
+ "Filter",
35
+ "InterludeError",
36
+ "Page",
37
+ "Row",
38
+ "StorageClient",
39
+ "StorageObject",
40
+ "Summary",
41
+ "SummaryGroup",
42
+ "TableClient",
43
+ "UserScope",
44
+ ]
interlude/_http.py ADDED
@@ -0,0 +1,191 @@
1
+ """The one place the API's response envelope is unwrapped.
2
+
3
+ Every Interlude response is ``{"data": ..., "meta": ...}`` on success or
4
+ ``{"error": {"code", "message", "details"}}`` on failure. Nothing outside
5
+ this module needs to know that.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any, Optional, Protocol
12
+ from urllib.parse import quote
13
+
14
+ import httpx
15
+
16
+ from .errors import InterludeError
17
+
18
+
19
+ def segment(value: str) -> str:
20
+ """One path segment, encoded.
21
+
22
+ Table names, row IDs and object IDs come from the caller. An unencoded
23
+ ``/``, ``?``, ``#`` or ``../`` in one would send the request, credentials
24
+ and all, to a different endpoint than the method names.
25
+ """
26
+ return quote(value, safe="")
27
+
28
+
29
+ class TokenSource(Protocol):
30
+ """Where a request's bearer token comes from, and how to renew it."""
31
+
32
+ def get(self) -> Optional[str]:
33
+ """The token to send, renewed first if it is about to expire."""
34
+ ...
35
+
36
+ def renew(self, rejected: str) -> Optional[str]:
37
+ """Called after the API refused ``rejected``. Returns the token to
38
+ retry with, or ``None`` when there is nothing better to offer."""
39
+ ...
40
+
41
+
42
+ class StaticToken:
43
+ """A token the caller supplied and the SDK cannot renew."""
44
+
45
+ def __init__(self, token: str) -> None:
46
+ self._token = token
47
+
48
+ def get(self) -> Optional[str]:
49
+ return self._token
50
+
51
+ def renew(self, rejected: str) -> Optional[str]:
52
+ return None
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Credentials:
57
+ """What one request authenticates with. Each field is its own header:
58
+
59
+ * ``api_key``: ``X-API-Key``, the secret project key.
60
+ * ``publishable_key``: ``X-Publishable-Key``, which names the project and
61
+ authorises nothing on its own.
62
+ * ``tokens``: ``Authorization: Bearer``, an account or end-user JWT.
63
+ """
64
+
65
+ api_key: Optional[str] = None
66
+ publishable_key: Optional[str] = None
67
+ tokens: Optional[TokenSource] = None
68
+
69
+
70
+ class Transport:
71
+ """Sends requests to the API and unwraps the envelope."""
72
+
73
+ def __init__(self, base_url: str, http_client: httpx.Client) -> None:
74
+ # Without trailing slashes, so base + "/auth" cannot become "//auth",
75
+ # which the API does not route.
76
+ self.base_url = base_url.rstrip("/")
77
+ self.http = http_client
78
+
79
+ def send(
80
+ self,
81
+ method: str,
82
+ path: str,
83
+ *,
84
+ token: Optional[str] = None,
85
+ api_key: Optional[str] = None,
86
+ publishable_key: Optional[str] = None,
87
+ body: Optional[Any] = None,
88
+ params: Optional[list[tuple[str, str]]] = None,
89
+ ) -> tuple[Any, dict[str, Any]]:
90
+ """Sends one request. Returns ``(data, meta)``."""
91
+ headers = {"Content-Type": "application/json"}
92
+ if token:
93
+ headers["Authorization"] = f"Bearer {token}"
94
+ if api_key:
95
+ headers["X-API-Key"] = api_key
96
+ if publishable_key:
97
+ headers["X-Publishable-Key"] = publishable_key
98
+
99
+ try:
100
+ response = self.http.request(
101
+ method,
102
+ f"{self.base_url}{path}",
103
+ headers=headers,
104
+ json=body,
105
+ params=params or None,
106
+ )
107
+ except httpx.TransportError as exc:
108
+ raise InterludeError(
109
+ "network_error",
110
+ "could not reach the Interlude API; check your network "
111
+ "connection and base_url",
112
+ 0,
113
+ ) from exc
114
+
115
+ if response.status_code >= 400:
116
+ # A proxy in front of the API can answer with HTML or nothing at
117
+ # all, so the error body is read defensively.
118
+ error = _error_body(response)
119
+ raise InterludeError(
120
+ error.get("code") or "unknown_error",
121
+ error.get("message")
122
+ or f"request failed with status {response.status_code}",
123
+ response.status_code,
124
+ error.get("details"),
125
+ )
126
+
127
+ if response.status_code == 204:
128
+ return None, {}
129
+
130
+ try:
131
+ payload = response.json()
132
+ except ValueError as exc:
133
+ raise InterludeError(
134
+ "invalid_response",
135
+ "the API answered with a body that is not JSON",
136
+ response.status_code,
137
+ ) from exc
138
+ if not isinstance(payload, dict):
139
+ return None, {}
140
+ return payload.get("data"), payload.get("meta") or {}
141
+
142
+ def send_as(
143
+ self,
144
+ credentials: Credentials,
145
+ method: str,
146
+ path: str,
147
+ *,
148
+ body: Optional[Any] = None,
149
+ params: Optional[list[tuple[str, str]]] = None,
150
+ ) -> tuple[Any, dict[str, Any]]:
151
+ """Sends a request, and if the API refuses the bearer token, renews
152
+ it and sends the request once more.
153
+
154
+ A token can be revoked before its expiry, and the expiry is judged on
155
+ this machine. The retry is safe for writes: a 401 comes from the API's
156
+ middleware, before any handler ran. Exactly one retry, no loop.
157
+ """
158
+ tokens = credentials.tokens
159
+ token = tokens.get() if tokens else None
160
+
161
+ def attempt(bearer: Optional[str]) -> tuple[Any, dict[str, Any]]:
162
+ return self.send(
163
+ method,
164
+ path,
165
+ token=bearer,
166
+ api_key=credentials.api_key,
167
+ publishable_key=credentials.publishable_key,
168
+ body=body,
169
+ params=params,
170
+ )
171
+
172
+ try:
173
+ return attempt(token)
174
+ except InterludeError as exc:
175
+ if exc.status_code != 401 or not token or tokens is None:
176
+ raise
177
+ renewed = tokens.renew(token)
178
+ if not renewed or renewed == token:
179
+ raise
180
+ return attempt(renewed)
181
+
182
+
183
+ def _error_body(response: httpx.Response) -> dict[str, Any]:
184
+ try:
185
+ payload = response.json()
186
+ except ValueError:
187
+ return {}
188
+ if not isinstance(payload, dict):
189
+ return {}
190
+ error = payload.get("error")
191
+ return error if isinstance(error, dict) else {}
interlude/_parse.py ADDED
@@ -0,0 +1,85 @@
1
+ """Turning API JSON into models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime
7
+ from typing import Any, Optional
8
+
9
+ from .models import Account, APIKeyMetadata, EndUser, Project, StorageObject
10
+
11
+ # The API is written in Go, which emits RFC 3339 with up to nine fractional
12
+ # digits ("...T10:00:00.123456789Z"). datetime.fromisoformat accepts at most
13
+ # six before Python 3.11, and no "Z" before 3.11 either.
14
+ _FRACTION = re.compile(r"\.(\d{6})\d+")
15
+
16
+
17
+ def parse_datetime(value: str) -> datetime:
18
+ """Parses an RFC 3339 timestamp from the API."""
19
+ normalized = _FRACTION.sub(r".\1", value.replace("Z", "+00:00"))
20
+ return datetime.fromisoformat(normalized)
21
+
22
+
23
+ def optional_datetime(value: Optional[str]) -> Optional[datetime]:
24
+ return parse_datetime(value) if value else None
25
+
26
+
27
+ def project(data: dict[str, Any]) -> Project:
28
+ return Project(
29
+ id=data["id"],
30
+ name=data["name"],
31
+ slug=data["slug"],
32
+ region=data["region"],
33
+ created_at=parse_datetime(data["created_at"]),
34
+ updated_at=parse_datetime(data["updated_at"]),
35
+ )
36
+
37
+
38
+ def api_key_metadata(data: dict[str, Any]) -> APIKeyMetadata:
39
+ return APIKeyMetadata(
40
+ id=data["id"],
41
+ display_id=data["display_id"],
42
+ name=data["name"],
43
+ role=data["role"],
44
+ created_at=parse_datetime(data["created_at"]),
45
+ updated_at=parse_datetime(data["updated_at"]),
46
+ last_used_at=optional_datetime(data.get("last_used_at")),
47
+ revoked_at=optional_datetime(data.get("revoked_at")),
48
+ )
49
+
50
+
51
+ def account(data: dict[str, Any]) -> Account:
52
+ return Account(
53
+ account_id=data["account_id"],
54
+ email=data.get("email"),
55
+ display_name=data.get("display_name"),
56
+ avatar_url=data.get("avatar_url"),
57
+ )
58
+
59
+
60
+ def end_user(data: dict[str, Any]) -> EndUser:
61
+ return EndUser(
62
+ id=data["id"],
63
+ project_id=data["project_id"],
64
+ email=data.get("email"),
65
+ display_name=data.get("display_name"),
66
+ avatar_url=data.get("avatar_url"),
67
+ email_verified=bool(data.get("email_verified")),
68
+ last_sign_in_at=optional_datetime(data.get("last_sign_in_at")),
69
+ created_at=parse_datetime(data["created_at"]),
70
+ )
71
+
72
+
73
+ def storage_object(
74
+ data: dict[str, Any], download_url: Optional[str] = None
75
+ ) -> StorageObject:
76
+ return StorageObject(
77
+ id=data["id"],
78
+ project_id=data["project_id"],
79
+ provider=data["provider"],
80
+ file_name=data["file_name"],
81
+ content_type=data["content_type"],
82
+ size_bytes=data["size_bytes"],
83
+ created_at=parse_datetime(data["created_at"]),
84
+ download_url=download_url,
85
+ )
interlude/account.py ADDED
@@ -0,0 +1,162 @@
1
+ """The account plane: signing in to Interlude itself."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from typing import Any, Optional
8
+
9
+ from . import _parse
10
+ from ._http import Credentials, Transport
11
+ from .errors import InterludeError
12
+ from .models import Account
13
+
14
+ #: Renew this many seconds before the access token really expires, so a slow
15
+ #: request never races the token dying mid-flight.
16
+ REFRESH_SKEW_SECONDS = 60.0
17
+
18
+
19
+ class AccountClient:
20
+ """Signs in to an Interlude account, and keeps its token fresh.
21
+
22
+ For scripts, CLIs and provisioning jobs that manage projects and API keys.
23
+ Not for your application's users; that is :meth:`Client.as_user`.
24
+
25
+ A client starts with the ``access_token`` it was given, if any. That token
26
+ is used as is and is never renewed. After :meth:`sign_in` the client holds
27
+ a session instead: the access token is renewed shortly before it expires,
28
+ and once more if the API refuses it. The session lives in memory only.
29
+
30
+ Safe to share between threads. Concurrent callers that find the token
31
+ expiring wait for one refresh rather than each starting their own. The
32
+ server rotates refresh tokens on use, so two overlapping refreshes would
33
+ revoke each other's token.
34
+ """
35
+
36
+ def __init__(self, transport: Transport, access_token: Optional[str]) -> None:
37
+ self._transport = transport
38
+ self._static_token = access_token
39
+ self._lock = threading.Lock()
40
+ self._access_token: Optional[str] = None
41
+ self._refresh_token: Optional[str] = None
42
+ # time.monotonic(), not the wall clock: a clock that jumps cannot
43
+ # make a fresh token look expired or an expired one look fresh.
44
+ self._expires_at = 0.0
45
+
46
+ # -- sign-in -----------------------------------------------------------
47
+
48
+ def sign_in(self, *, email: str, password: str) -> Account:
49
+ """Signs in with email and password, and returns the account."""
50
+ data, _ = self._transport.send(
51
+ "POST", "/auth/login", body={"email": email, "password": password}
52
+ )
53
+ self._adopt(data)
54
+ return self.me()
55
+
56
+ def sign_up(
57
+ self, *, email: str, password: str, display_name: Optional[str] = None
58
+ ) -> Account:
59
+ """Creates an account, signs in to it, and returns it."""
60
+ body: dict[str, Any] = {"email": email, "password": password}
61
+ if display_name is not None:
62
+ body["display_name"] = display_name
63
+ data, _ = self._transport.send("POST", "/auth/register", body=body)
64
+ self._adopt(data)
65
+ return self.me()
66
+
67
+ def sign_out(self) -> None:
68
+ """Ends the session here and on the server.
69
+
70
+ The server call is best effort: the local session is gone whether or
71
+ not it succeeds. A client built with ``access_token`` falls back to
72
+ that token afterwards.
73
+ """
74
+ with self._lock:
75
+ refresh_token = self._refresh_token
76
+ self._clear()
77
+ if refresh_token:
78
+ try:
79
+ self._transport.send(
80
+ "POST", "/auth/logout", body={"refresh_token": refresh_token}
81
+ )
82
+ except InterludeError:
83
+ pass
84
+
85
+ def me(self) -> Account:
86
+ """The account the current token belongs to."""
87
+ self._require_token()
88
+ data, _ = self._transport.send_as(Credentials(tokens=self), "GET", "/auth/me")
89
+ return _parse.account(data)
90
+
91
+ @property
92
+ def signed_in(self) -> bool:
93
+ """Whether this client holds an account credential of either kind."""
94
+ with self._lock:
95
+ return bool(self._refresh_token or self._static_token)
96
+
97
+ # -- TokenSource -------------------------------------------------------
98
+
99
+ def get(self) -> Optional[str]:
100
+ """The account access token, renewed first if it is about to expire."""
101
+ with self._lock:
102
+ if self._refresh_token is None:
103
+ return self._static_token
104
+ if time.monotonic() < self._expires_at - REFRESH_SKEW_SECONDS:
105
+ return self._access_token
106
+ self._refresh_locked()
107
+ return self._access_token
108
+
109
+ def renew(self, rejected: str) -> Optional[str]:
110
+ """Renews the session after the API refused ``rejected``.
111
+
112
+ Another thread may already have renewed it; refreshing again would
113
+ rotate a perfectly good new pair for nothing.
114
+ """
115
+ with self._lock:
116
+ if self._refresh_token is None:
117
+ return None
118
+ if self._access_token == rejected:
119
+ self._refresh_locked()
120
+ return self._access_token
121
+
122
+ # -- internals ---------------------------------------------------------
123
+
124
+ def _require_token(self) -> None:
125
+ if not self.signed_in:
126
+ raise InterludeError(
127
+ "access_token_required",
128
+ "this call needs an Interlude account: pass access_token to "
129
+ "Client(), or call client.account.sign_in() first",
130
+ 0,
131
+ )
132
+
133
+ def _refresh_locked(self) -> None:
134
+ """Exchanges the refresh token for a new pair. Caller holds the lock.
135
+
136
+ Only a refresh token the server actually refused ends the session. A
137
+ network failure or a 5xx says nothing about the token, so it is
138
+ raised and the session stands for the next attempt.
139
+ """
140
+ try:
141
+ data, _ = self._transport.send(
142
+ "POST", "/auth/refresh", body={"refresh_token": self._refresh_token}
143
+ )
144
+ except InterludeError as exc:
145
+ if exc.status_code in (401, 403):
146
+ self._clear()
147
+ raise
148
+ self._adopt_locked(data)
149
+
150
+ def _adopt(self, data: dict[str, Any]) -> None:
151
+ with self._lock:
152
+ self._adopt_locked(data)
153
+
154
+ def _adopt_locked(self, data: dict[str, Any]) -> None:
155
+ self._access_token = data["access_token"]
156
+ self._refresh_token = data["refresh_token"]
157
+ self._expires_at = time.monotonic() + float(data["expires_in"])
158
+
159
+ def _clear(self) -> None:
160
+ self._access_token = None
161
+ self._refresh_token = None
162
+ self._expires_at = 0.0