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/client.py ADDED
@@ -0,0 +1,353 @@
1
+ """The Interlude client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ import httpx
8
+
9
+ from . import _parse
10
+ from ._http import Credentials, StaticToken, Transport, segment
11
+ from .account import AccountClient
12
+ from .errors import InterludeError
13
+ from .models import (
14
+ APIKeyMetadata,
15
+ CreateAPIKeyRequest,
16
+ CreateAPIKeyResponse,
17
+ CreateProjectRequest,
18
+ EndUser,
19
+ Project,
20
+ RotateAPIKeyResponse,
21
+ )
22
+ from .storage import StorageClient
23
+ from .table import TableClient
24
+
25
+ DEFAULT_BASE_URL = "https://api.useinterlude.com"
26
+
27
+ # Key prefixes, used only to recognise a credential passed in the wrong place
28
+ # and say so. Only the server can tell whether a key is valid.
29
+ API_KEY_PREFIX = "il_sk_"
30
+ PUBLISHABLE_KEY_PREFIX = "il_pk_"
31
+
32
+
33
+ class Client:
34
+ """The Interlude client for servers, scripts and CLIs.
35
+
36
+ Credentials
37
+ -----------
38
+ Interlude has several credentials, and each reaches different routes.
39
+ Pass the ones your code needs:
40
+
41
+ * ``api_key`` (``il_sk_...``): the **secret project key**. Your server
42
+ acting as the project: ``client.table()`` and ``client.storage``. Keep
43
+ it out of anything that ships to a browser or phone.
44
+ * ``publishable_key`` (``il_pk_...``): names the project and authorises
45
+ nothing on its own. Needed to act as one of your app's users
46
+ (:meth:`as_user`) and to check their tokens (``client.auth``).
47
+ * ``access_token``: an **Interlude account** JWT, for managing projects
48
+ and API keys. Or call ``client.account.sign_in()`` instead, which also
49
+ keeps the token fresh.
50
+ * ``project_id``: which project ``table()``, ``storage`` and ``auth``
51
+ act on. Not a secret.
52
+
53
+ Missing configuration is reported when a feature is used, not here, so a
54
+ client built for one job does not need the credentials of another.
55
+
56
+ Usage::
57
+
58
+ client = Client(project_id="proj_123", api_key=os.environ["INTERLUDE_API_KEY"])
59
+ todo = client.table("todos").insert({"title": "Ship it"})
60
+
61
+ The client is safe to share between threads. Use it as a context manager,
62
+ or call :meth:`close`, to release its connections.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ access_token: Optional[str] = None,
68
+ *,
69
+ api_key: Optional[str] = None,
70
+ publishable_key: Optional[str] = None,
71
+ project_id: Optional[str] = None,
72
+ base_url: str = DEFAULT_BASE_URL,
73
+ http_client: Optional[httpx.Client] = None,
74
+ timeout: float = 30.0,
75
+ ) -> None:
76
+ _check_credential_types(access_token, api_key, publishable_key)
77
+
78
+ self._owns_http = http_client is None
79
+ self._transport = Transport(base_url, http_client or httpx.Client(timeout=timeout))
80
+ self._api_key = api_key
81
+ self._publishable_key = publishable_key
82
+ self._project_id = project_id
83
+
84
+ #: The Interlude account: sign-in, and the token for projects and keys.
85
+ self.account = AccountClient(self._transport, access_token)
86
+ #: Projects owned by the account. Needs an account credential.
87
+ self.projects = _ProjectsResource(self)
88
+ #: A project's API keys. Needs an account credential.
89
+ self.api_keys = _APIKeysResource(self)
90
+
91
+ # -- data plane --------------------------------------------------------
92
+
93
+ def table(self, name: str) -> TableClient:
94
+ """A table's rows, as your server.
95
+
96
+ Sent with the API key when there is one, otherwise with the account
97
+ credential. With neither, only the publishable key is sent, which
98
+ reaches tables marked public and nothing else.
99
+
100
+ To act as one of your app's users, within the table's access rules,
101
+ use :meth:`as_user` instead.
102
+ """
103
+ return TableClient(
104
+ self._transport, self._server_credentials, self._require_project_id("table()"), name
105
+ )
106
+
107
+ @property
108
+ def storage(self) -> StorageClient:
109
+ """The project's files. Needs the API key or an account credential."""
110
+ return StorageClient(
111
+ self._transport, self._server_credentials, self._require_project_id("storage")
112
+ )
113
+
114
+ # -- end users ---------------------------------------------------------
115
+
116
+ @property
117
+ def auth(self) -> "EndUserAuth":
118
+ """Your app's users: check who an access token belongs to."""
119
+ return EndUserAuth(self)
120
+
121
+ def as_user(self, access_token: str) -> "UserScope":
122
+ """Acts as one of your app's users, with the access token they sent
123
+ your server.
124
+
125
+ Requests carry their token and the publishable key, never the API
126
+ key, so the table's access rules apply exactly as they would to that
127
+ user's own app. Use this rather than the API key whenever a request is
128
+ made on a user's behalf.
129
+ """
130
+ if not access_token:
131
+ raise InterludeError("access_token_required", "an end-user access token is required", 0)
132
+ return UserScope(self, access_token)
133
+
134
+ # -- lifecycle ---------------------------------------------------------
135
+
136
+ def close(self) -> None:
137
+ """Closes the HTTP connections, unless an ``http_client`` was passed
138
+ in, in which case its owner closes it."""
139
+ if self._owns_http:
140
+ self._transport.http.close()
141
+
142
+ def __enter__(self) -> "Client":
143
+ return self
144
+
145
+ def __exit__(self, *exc: object) -> None:
146
+ self.close()
147
+
148
+ # -- internals ---------------------------------------------------------
149
+
150
+ def _server_credentials(self) -> Credentials:
151
+ """Who a server-side data request is, in order: the API key, then the
152
+ account, then the publishable key alone (anonymous).
153
+
154
+ The publishable key is never sent with the API key or an account
155
+ token. The API reads a publishable key with no end-user token as an
156
+ anonymous caller, so sending it alongside would quietly drop a server
157
+ to anonymous.
158
+ """
159
+ if self._api_key:
160
+ return Credentials(api_key=self._api_key)
161
+ if self.account.signed_in:
162
+ return Credentials(tokens=self.account)
163
+ return Credentials(publishable_key=self._publishable_key)
164
+
165
+ def _account_credentials(self) -> Credentials:
166
+ self.account._require_token()
167
+ return Credentials(tokens=self.account)
168
+
169
+ def _require_project_id(self, feature: str) -> str:
170
+ if not self._project_id:
171
+ raise InterludeError(
172
+ "project_id_required",
173
+ f"Client(project_id=...) is required to use {feature}",
174
+ 0,
175
+ )
176
+ return self._project_id
177
+
178
+ def _require_publishable_key(self, feature: str) -> str:
179
+ if not self._publishable_key:
180
+ raise InterludeError(
181
+ "publishable_key_required",
182
+ f"Client(publishable_key=...) is required to use {feature}; "
183
+ "find it on your project's API keys page",
184
+ 0,
185
+ )
186
+ return self._publishable_key
187
+
188
+
189
+ class EndUserAuth:
190
+ """Your app's users, as seen from your server."""
191
+
192
+ def __init__(self, client: Client) -> None:
193
+ self._client = client
194
+
195
+ def get_user(self, access_token: str) -> EndUser:
196
+ """The user an access token belongs to.
197
+
198
+ This is how your server learns who sent a request: the app sends its
199
+ user's token, and this asks Interlude whether the token is valid and
200
+ whose it is. An invalid or expired token raises
201
+ :class:`InterludeError` with ``status_code`` 401.
202
+ """
203
+ client = self._client
204
+ project_id = client._require_project_id("auth")
205
+ publishable_key = client._require_publishable_key("auth")
206
+ if not access_token:
207
+ raise InterludeError("access_token_required", "an end-user access token is required", 0)
208
+ data, _ = client._transport.send(
209
+ "GET",
210
+ f"/projects/{segment(project_id)}/auth/me",
211
+ token=access_token,
212
+ publishable_key=publishable_key,
213
+ )
214
+ return _parse.end_user(data)
215
+
216
+
217
+ class UserScope:
218
+ """The data plane as one of your app's users. From :meth:`Client.as_user`."""
219
+
220
+ def __init__(self, client: Client, access_token: str) -> None:
221
+ self._client = client
222
+ self._access_token = access_token
223
+
224
+ def table(self, name: str) -> TableClient:
225
+ """A table's rows, as this user, within the table's access rules."""
226
+ client = self._client
227
+ project_id = client._require_project_id("table()")
228
+ credentials = Credentials(
229
+ publishable_key=client._require_publishable_key("as_user()"),
230
+ # Not renewable: the token is the user's, and so is its refresh.
231
+ tokens=StaticToken(self._access_token),
232
+ )
233
+ return TableClient(client._transport, lambda: credentials, project_id, name)
234
+
235
+ def get_user(self) -> EndUser:
236
+ """Who this user is. Raises with ``status_code`` 401 if the token is
237
+ not valid."""
238
+ return self._client.auth.get_user(self._access_token)
239
+
240
+
241
+ class _ProjectsResource:
242
+ """Project management operations. Needs an account credential."""
243
+
244
+ def __init__(self, client: Client) -> None:
245
+ self._client = client
246
+
247
+ def _send(self, method: str, path: str, body: Optional[Any] = None) -> Any:
248
+ data, _ = self._client._transport.send_as(
249
+ self._client._account_credentials(), method, path, body=body
250
+ )
251
+ return data
252
+
253
+ def create(self, req: CreateProjectRequest) -> Project:
254
+ """Create a new project."""
255
+ data = self._send(
256
+ "POST", "/projects", {"name": req.name, "slug": req.slug, "region": req.region}
257
+ )
258
+ return _parse.project(data)
259
+
260
+ def list(self) -> list[Project]:
261
+ """List all projects for the signed-in account."""
262
+ return [_parse.project(p) for p in self._send("GET", "/projects") or []]
263
+
264
+ def get(self, project_id: str) -> Project:
265
+ """Get a project by ID."""
266
+ return _parse.project(self._send("GET", f"/projects/{segment(project_id)}"))
267
+
268
+ def delete(self, project_id: str) -> None:
269
+ """Delete a project by ID."""
270
+ self._send("DELETE", f"/projects/{segment(project_id)}")
271
+
272
+
273
+ class _APIKeysResource:
274
+ """API key management operations. Needs an account credential."""
275
+
276
+ def __init__(self, client: Client) -> None:
277
+ self._client = client
278
+
279
+ def _send(self, method: str, path: str, body: Optional[Any] = None) -> Any:
280
+ data, _ = self._client._transport.send_as(
281
+ self._client._account_credentials(), method, path, body=body
282
+ )
283
+ return data
284
+
285
+ @staticmethod
286
+ def _path(project_id: str, key_id: Optional[str] = None) -> str:
287
+ path = f"/projects/{segment(project_id)}/api-keys"
288
+ return f"{path}/{segment(key_id)}" if key_id else path
289
+
290
+ def create(self, project_id: str, req: CreateAPIKeyRequest) -> CreateAPIKeyResponse:
291
+ """Create a new API key. The raw key is returned only this once."""
292
+ data = self._send("POST", self._path(project_id), {"name": req.name, "role": req.role})
293
+ return CreateAPIKeyResponse(
294
+ id=data["id"],
295
+ name=data["name"],
296
+ role=data["role"],
297
+ key=data["key"],
298
+ created_at=_parse.parse_datetime(data["created_at"]),
299
+ )
300
+
301
+ def list(self, project_id: str) -> list[APIKeyMetadata]:
302
+ """List all API keys for the given project."""
303
+ return [_parse.api_key_metadata(k) for k in self._send("GET", self._path(project_id)) or []]
304
+
305
+ def get(self, project_id: str, key_id: str) -> APIKeyMetadata:
306
+ """Get an API key by ID within the given project."""
307
+ return _parse.api_key_metadata(self._send("GET", self._path(project_id, key_id)))
308
+
309
+ def revoke(self, project_id: str, key_id: str) -> None:
310
+ """Revoke an API key by ID within the given project."""
311
+ self._send("DELETE", self._path(project_id, key_id))
312
+
313
+ def rotate(self, project_id: str, key_id: str) -> RotateAPIKeyResponse:
314
+ """Rotate an API key. The new raw key is returned only this once."""
315
+ data = self._send("POST", f"{self._path(project_id, key_id)}/rotate")
316
+ return RotateAPIKeyResponse(
317
+ id=data["id"],
318
+ name=data["name"],
319
+ role=data["role"],
320
+ key=data["key"],
321
+ created_at=_parse.parse_datetime(data["created_at"]),
322
+ )
323
+
324
+
325
+ def _check_credential_types(
326
+ access_token: Optional[str], api_key: Optional[str], publishable_key: Optional[str]
327
+ ) -> None:
328
+ """Refuses a key passed where a different credential belongs.
329
+
330
+ Each mistake fails later as an opaque 401, or worse, works with the wrong
331
+ authority, so it is caught here with an explanation.
332
+ """
333
+ if access_token and access_token.startswith(API_KEY_PREFIX):
334
+ raise ValueError(
335
+ "interlude: a project API key was passed as access_token; pass it "
336
+ "as api_key=... instead. access_token is an Interlude account "
337
+ "token, for managing projects and API keys"
338
+ )
339
+ if access_token and access_token.startswith(PUBLISHABLE_KEY_PREFIX):
340
+ raise ValueError(
341
+ "interlude: a publishable key was passed as access_token; pass it "
342
+ "as publishable_key=... instead"
343
+ )
344
+ if api_key and api_key.startswith(PUBLISHABLE_KEY_PREFIX):
345
+ raise ValueError(
346
+ "interlude: a publishable key was passed as api_key; pass it as "
347
+ "publishable_key=... instead. api_key is the secret key (il_sk_...)"
348
+ )
349
+ if publishable_key and publishable_key.startswith(API_KEY_PREFIX):
350
+ raise ValueError(
351
+ "interlude: the secret API key was passed as publishable_key; pass "
352
+ "it as api_key=... instead, and keep it on your server"
353
+ )
interlude/errors.py ADDED
@@ -0,0 +1,41 @@
1
+ """The one exception type the SDK raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class InterludeError(Exception):
9
+ """Raised for every failure: the API's, and the SDK's own refusals.
10
+
11
+ ``status_code`` is the HTTP status when the API answered. It is ``0`` when
12
+ the SDK refused to send a request it already knew could not succeed (for
13
+ example ``project_id_required``), or when the API could not be reached
14
+ (``network_error``).
15
+
16
+ ``code`` is the API's own error code where one exists (``invalid_token``,
17
+ ``row_count_mismatch``, ...), so callers branch on one vocabulary across
18
+ the whole stack, and across the JavaScript, Python and Go SDKs.
19
+
20
+ ``details`` holds the extra facts the API attaches to a few errors, as it
21
+ sent them. For ``row_count_mismatch`` it is ``{"expected": n, "actual": m}``.
22
+ ``None`` for every other error.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ code: str,
28
+ message: str,
29
+ status_code: int,
30
+ details: Optional[Any] = None,
31
+ ) -> None:
32
+ self.code = code
33
+ self.message = message
34
+ self.status_code = status_code
35
+ self.details = details
36
+ super().__init__(f"[{code}] {message}")
37
+
38
+
39
+ # The name 0.1.0 shipped. Kept so `except ClientError` in existing code still
40
+ # catches everything; new code should use InterludeError.
41
+ ClientError = InterludeError
interlude/models.py ADDED
@@ -0,0 +1,218 @@
1
+ """Data models for the Interlude API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any, Literal, Optional, Union
8
+
9
+ from .errors import ClientError, InterludeError
10
+
11
+ __all__ = [
12
+ "Account",
13
+ "APIKeyMetadata",
14
+ "ClientError",
15
+ "CreateAPIKeyRequest",
16
+ "CreateAPIKeyResponse",
17
+ "CreateProjectRequest",
18
+ "EndUser",
19
+ "Filter",
20
+ "FilterOp",
21
+ "InterludeError",
22
+ "Measure",
23
+ "Page",
24
+ "Project",
25
+ "RotateAPIKeyResponse",
26
+ "Row",
27
+ "StorageObject",
28
+ "Summary",
29
+ "SummaryGroup",
30
+ ]
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Control plane: projects and API keys
34
+ # ---------------------------------------------------------------------------
35
+
36
+
37
+ @dataclass
38
+ class Project:
39
+ """Represents an Interlude project."""
40
+
41
+ id: str
42
+ name: str
43
+ slug: str
44
+ region: str
45
+ created_at: datetime
46
+ updated_at: datetime
47
+
48
+
49
+ @dataclass
50
+ class CreateProjectRequest:
51
+ """Payload for creating a project."""
52
+
53
+ name: str
54
+ slug: str
55
+ region: str = "eu-nuremberg-1"
56
+
57
+
58
+ @dataclass
59
+ class APIKeyMetadata:
60
+ """Safe representation of an API key (no raw key)."""
61
+
62
+ id: str
63
+ display_id: str
64
+ name: str
65
+ role: str
66
+ created_at: datetime
67
+ updated_at: datetime
68
+ last_used_at: Optional[datetime] = None
69
+ revoked_at: Optional[datetime] = None
70
+
71
+
72
+ @dataclass
73
+ class CreateAPIKeyRequest:
74
+ """Payload for creating an API key."""
75
+
76
+ name: str
77
+ role: str
78
+
79
+
80
+ @dataclass
81
+ class CreateAPIKeyResponse:
82
+ """Response for a successful key creation."""
83
+
84
+ id: str
85
+ name: str
86
+ role: str
87
+ key: str
88
+ created_at: datetime
89
+
90
+
91
+ @dataclass
92
+ class RotateAPIKeyResponse:
93
+ """Response for a successful key rotation."""
94
+
95
+ id: str
96
+ name: str
97
+ role: str
98
+ key: str
99
+ created_at: datetime
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # Identities
104
+ # ---------------------------------------------------------------------------
105
+
106
+
107
+ @dataclass
108
+ class Account:
109
+ """An Interlude account: the person who owns projects."""
110
+
111
+ account_id: str
112
+ email: Optional[str] = None
113
+ display_name: Optional[str] = None
114
+ avatar_url: Optional[str] = None
115
+
116
+
117
+ @dataclass
118
+ class EndUser:
119
+ """A user of *your* application, from one project's user pool.
120
+
121
+ Distinct from :class:`Account`. An end user exists only inside one
122
+ project and has no access to Interlude itself.
123
+ """
124
+
125
+ id: str
126
+ project_id: str
127
+ email: Optional[str]
128
+ display_name: Optional[str]
129
+ avatar_url: Optional[str]
130
+ email_verified: bool
131
+ last_sign_in_at: Optional[datetime]
132
+ created_at: datetime
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Data plane: rows
137
+ # ---------------------------------------------------------------------------
138
+
139
+ #: A row: free-form, since tables are developer-defined.
140
+ Row = dict[str, Any]
141
+
142
+ FilterOp = Literal["eq", "neq", "gt", "gte", "lt", "lte", "contains", "is"]
143
+ Measure = Literal["count", "sum", "avg", "min", "max"]
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class Filter:
148
+ """One condition on a column. Every filter in a list must hold (AND).
149
+
150
+ * ``eq``, ``neq``, ``gt``, ``gte``, ``lt``, ``lte``: compare with
151
+ ``value``, which the server converts to the column's type (``gt`` to
152
+ ``lte`` are not available on boolean, uuid or jsonb columns).
153
+ * ``contains``: case-insensitive substring match, text columns only.
154
+ * ``is``: ``value`` is ``"null"`` or ``"not_null"``.
155
+
156
+ Filters only narrow what the table's access rules already let the caller
157
+ read. A plain ``(column, op, value)`` tuple is accepted wherever a Filter
158
+ is.
159
+ """
160
+
161
+ column: str
162
+ op: FilterOp
163
+ value: Union[str, int, float, bool]
164
+
165
+
166
+ FilterLike = Union[Filter, tuple[str, str, Union[str, int, float, bool]]]
167
+
168
+
169
+ @dataclass
170
+ class Page:
171
+ """One page of rows, and whether another follows.
172
+
173
+ There is no total count by design; ask for the next page with ``offset``
174
+ until ``has_more`` is false.
175
+ """
176
+
177
+ rows: list[Row]
178
+ has_more: bool
179
+
180
+
181
+ @dataclass
182
+ class SummaryGroup:
183
+ """One result of a summary. ``key`` is ``None`` when ungrouped."""
184
+
185
+ key: Any
186
+ value: Union[int, float, str, None]
187
+
188
+
189
+ @dataclass
190
+ class Summary:
191
+ """The result of ``table.summarize()``.
192
+
193
+ One group when ungrouped; one per value of ``group_by`` otherwise, largest
194
+ first. ``truncated`` is true when there were more than 50 groups.
195
+ """
196
+
197
+ groups: list[SummaryGroup] = field(default_factory=list)
198
+ truncated: bool = False
199
+
200
+
201
+ # ---------------------------------------------------------------------------
202
+ # Data plane: storage
203
+ # ---------------------------------------------------------------------------
204
+
205
+
206
+ @dataclass
207
+ class StorageObject:
208
+ """A stored file's metadata. ``download_url`` is set only by
209
+ ``storage.get()``: a presigned link that expires."""
210
+
211
+ id: str
212
+ project_id: str
213
+ provider: str
214
+ file_name: str
215
+ content_type: str
216
+ size_bytes: int
217
+ created_at: datetime
218
+ download_url: Optional[str] = None