fletbase-sdk 0.1.0a0__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.
fletbase/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ """FletBase — Python client SDK.
2
+
3
+ **One namespace per service** (ADR 002). This top level holds only project handles,
4
+ the error type, and wire versions. Each service's types and helpers live in its own
5
+ module, and that module is their only home:
6
+
7
+ fletbase.database Database, Collection, DocumentRef, transforms, ...
8
+ fletbase.observability HttpEvent, enable_debug_logging
9
+ fletbase.auth arrives with P9
10
+
11
+ The public surface lands incrementally, in the order the server can support it:
12
+
13
+ P3 server(), collections, documents, batches, transactions
14
+ P4 the query builder — DocumentModel, field(), ordering, cursors, aggregates
15
+ P7 on_snapshot realtime subscriptions
16
+ P9 project() for public clients, project.auth, OAuth
17
+ P10 file fields, upload
18
+ V2 database.local() and the offline cache
19
+
20
+ **The API is async, and only async.** An earlier design carried a sync facade over an
21
+ `anyio` portal alongside it; that is gone. One surface means one implementation and no
22
+ parity to keep honest — and it is what lets the same client run under Pyodide, where
23
+ the worker thread a sync facade needs does not exist. `flet build web` compiles to
24
+ Pyodide, so that is not a hypothetical target.
25
+
26
+ Getting started::
27
+
28
+ import asyncio
29
+ import fletbase
30
+ from fletbase import database
31
+
32
+ async def main():
33
+ async with fletbase.server(
34
+ base_url="https://api.flet.app",
35
+ project_id="prj_...",
36
+ service_key="fb_ak_...",
37
+ ) as project:
38
+ todos = project.database.collection("todos")
39
+ ref = await todos.add({"title": "Ship v1", "views": 0})
40
+ await ref.update({"views": database.increment(1)})
41
+ snap = await ref.get()
42
+ print(snap["title"], snap["views"])
43
+
44
+ asyncio.run(main())
45
+ """
46
+
47
+ from . import database
48
+ from .project import ServerProject, server
49
+ from .version import FILTER_AST_VERSION, PROTOCOL_VERSION, __version__
50
+ from .wire.errors import ERROR_CODES, FletBaseError
51
+
52
+ __all__ = [
53
+ "ERROR_CODES",
54
+ "FILTER_AST_VERSION",
55
+ "PROTOCOL_VERSION",
56
+ "FletBaseError",
57
+ "ServerProject",
58
+ "__version__",
59
+ "database",
60
+ "server",
61
+ ]
@@ -0,0 +1,6 @@
1
+ """Client-side authentication: PKCE, token storage, and the OAuth exchange flow.
2
+
3
+ Auth §11.3 is explicit about what may and may not live here: PKCE derivation and the
4
+ exchange protocol are cross-language contracts, while password hashing has **no**
5
+ client surface at all — the password travels over TLS and the Worker hashes it.
6
+ """
fletbase/auth/pkce.py ADDED
@@ -0,0 +1,80 @@
1
+ """PKCE — RFC 7636, required on every OAuth flow by Auth §6.1.
2
+
3
+ **PKCE on every flow, including web.** Public clients cannot hold a secret;
4
+ without PKCE, an intercepted ``fb_code`` would be redeemable.
5
+
6
+ Auth §11.3 names this as one of the few genuinely cross-language client obligations:
7
+ "PKCE ``S256`` derivation — SHA-256 of the verifier, base64url without padding.
8
+ **Must match byte for byte.**" A mismatch is not a subtle bug — the exchange simply
9
+ fails for every user of that client, so it is pinned by vectors.
10
+
11
+ The verifier never leaves process memory. That is what makes the 60-second
12
+ ``fb_code`` in Auth §6.1 worthless to an interceptor.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import base64
18
+ import hashlib
19
+ import re
20
+ import secrets
21
+ from typing import Final
22
+
23
+ from fletbase.wire.errors import ValidationError
24
+
25
+ #: RFC 7636 §4.1: 43-128 characters from the unreserved set.
26
+ _VERIFIER_PATTERN: Final = re.compile(r"^[A-Za-z0-9\-._~]{43,128}$")
27
+
28
+ CODE_CHALLENGE_METHOD: Final = "S256"
29
+
30
+
31
+ def _b64url(data: bytes) -> str:
32
+ """base64url without padding — RFC 4648 §5.
33
+
34
+ Padding is stripped because every consumer specifies the unpadded form, and a
35
+ stray ``=`` would fail a byte-for-byte comparison against the server.
36
+ """
37
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
38
+
39
+
40
+ def is_valid_code_verifier(verifier: str) -> bool:
41
+ return bool(_VERIFIER_PATTERN.match(verifier))
42
+
43
+
44
+ def assert_valid_code_verifier(verifier: str) -> None:
45
+ if not is_valid_code_verifier(verifier):
46
+ raise ValidationError(
47
+ "FB_FIELD_PATH_INVALID",
48
+ "A PKCE code verifier must be 43-128 characters of [A-Za-z0-9-._~].",
49
+ {"length": len(verifier)},
50
+ )
51
+
52
+
53
+ def derive_code_challenge(verifier: str) -> str:
54
+ """``S256`` challenge: base64url(SHA-256(ASCII(verifier))), unpadded.
55
+
56
+ The verifier is hashed as the **ASCII bytes of the string**, not as decoded
57
+ base64 — a natural mistake, since verifiers are usually produced by
58
+ base64url-encoding random bytes. RFC 7636 §4.2 is explicit that the input is the
59
+ verifier's own characters, and the vectors include the RFC's example so the
60
+ distinction cannot drift.
61
+ """
62
+ assert_valid_code_verifier(verifier)
63
+ return _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
64
+
65
+
66
+ def generate_code_verifier() -> str:
67
+ """A fresh verifier: 32 random bytes rendered base64url.
68
+
69
+ That is 43 characters — the RFC's minimum, and the most entropy that fits it.
70
+ """
71
+ return _b64url(secrets.token_bytes(32))
72
+
73
+
74
+ __all__ = [
75
+ "CODE_CHALLENGE_METHOD",
76
+ "assert_valid_code_verifier",
77
+ "derive_code_challenge",
78
+ "generate_code_verifier",
79
+ "is_valid_code_verifier",
80
+ ]
@@ -0,0 +1,47 @@
1
+ """The database service — the only home for its public names (ADR 002).
2
+
3
+ A cloud database comes from a project handle; this module holds its types and the
4
+ helpers that do not depend on which database they are used with::
5
+
6
+ import fletbase
7
+ from fletbase import database
8
+
9
+ async with fletbase.server(base_url=..., project_id=..., service_key=...) as project:
10
+ db = project.database
11
+ ref = await db.collection("todos").add({"title": "Ship", "views": 0})
12
+ await ref.update({"views": database.increment(1)})
13
+
14
+ Transforms are module functions rather than `Database` methods: they mean the same
15
+ thing against any database, so spelling them `db.increment` would invite a question
16
+ with no answer.
17
+
18
+ Arriving later, in this same module: the query builder and `DocumentModel` (P4), and
19
+ `local()` for local databases (V2 §3.2).
20
+ """
21
+
22
+ from fletbase.wire.sentinels import (
23
+ array_remove,
24
+ array_union,
25
+ delete_field,
26
+ increment,
27
+ server_timestamp,
28
+ )
29
+
30
+ from .batch import WriteBatch
31
+ from .database import Collection, Database, DocumentRef
32
+ from .snapshot import DocumentSnapshot
33
+ from .transaction import Transaction
34
+
35
+ __all__ = [
36
+ "Collection",
37
+ "Database",
38
+ "DocumentRef",
39
+ "DocumentSnapshot",
40
+ "Transaction",
41
+ "WriteBatch",
42
+ "array_remove",
43
+ "array_union",
44
+ "delete_field",
45
+ "increment",
46
+ "server_timestamp",
47
+ ]
@@ -0,0 +1,141 @@
1
+ """Batched writes — V1 §5.3.
2
+
3
+ > `db.batch()` collects unconditional writes and commits them atomically in one
4
+ > `transactionSync()` call inside the tenant Durable Object.
5
+
6
+ Atomic in both directions: every write passes or the batch rolls back (§8.3), and every
7
+ `server_timestamp()` in it receives the same value (§4.2) because the server chooses one
8
+ commit timestamp above the writes.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from fletbase.wire.errors import FletBaseError
16
+ from fletbase.wire.sentinels import split_transforms
17
+
18
+ if TYPE_CHECKING:
19
+ from .database import Database, DocumentRef
20
+
21
+
22
+ class WriteBuilder:
23
+ """Turns a ref plus a user dictionary into a wire write envelope.
24
+
25
+ Shared by single writes, batches, and transactions so all three produce byte-
26
+ identical envelopes — the SDK has one place where a write takes its shape.
27
+ """
28
+
29
+ @staticmethod
30
+ def _split(
31
+ data: dict[str, Any],
32
+ *,
33
+ replacing: bool,
34
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
35
+ return split_transforms(data, replacing=replacing)
36
+
37
+ @staticmethod
38
+ def create(ref: DocumentRef, data: dict[str, Any]) -> dict[str, Any]:
39
+ plain, transforms = WriteBuilder._split(data, replacing=True)
40
+ write: dict[str, Any] = {"op": "create", "path": ref.path, "data": plain}
41
+ if transforms:
42
+ write["transforms"] = transforms
43
+ return write
44
+
45
+ @staticmethod
46
+ def set(ref: DocumentRef, data: dict[str, Any], *, merge: bool) -> dict[str, Any]:
47
+ plain, transforms = WriteBuilder._split(data, replacing=not merge)
48
+ write: dict[str, Any] = {"op": "set", "path": ref.path, "data": plain}
49
+ if merge:
50
+ write["merge"] = True
51
+ if transforms:
52
+ write["transforms"] = transforms
53
+ return write
54
+
55
+ @staticmethod
56
+ def update(
57
+ ref: DocumentRef,
58
+ data: dict[str, Any],
59
+ *,
60
+ revision: int | None = None,
61
+ ) -> dict[str, Any]:
62
+ plain, transforms = WriteBuilder._split(data, replacing=False)
63
+ write: dict[str, Any] = {"op": "update", "path": ref.path, "data": plain}
64
+ if transforms:
65
+ write["transforms"] = transforms
66
+ if revision is not None:
67
+ write["precondition"] = {"revision": revision}
68
+ return write
69
+
70
+ @staticmethod
71
+ def delete(ref: DocumentRef, *, revision: int | None = None) -> dict[str, Any]:
72
+ write: dict[str, Any] = {"op": "delete", "path": ref.path}
73
+ if revision is not None:
74
+ write["precondition"] = {"revision": revision}
75
+ return write
76
+
77
+
78
+ class WriteBatch:
79
+ """Collects writes; sends them on `commit()`.
80
+
81
+ Write methods are ordinary calls rather than coroutines — nothing happens until the
82
+ commit, and making them awaitable would suggest otherwise.
83
+ """
84
+
85
+ def __init__(self, database: Database) -> None:
86
+ self._database = database
87
+ self._writes: list[dict[str, Any]] = []
88
+ self._committed = False
89
+
90
+ def __len__(self) -> int:
91
+ return len(self._writes)
92
+
93
+ def create(self, ref: DocumentRef, data: dict[str, Any]) -> WriteBatch:
94
+ return self._add(WriteBuilder.create(ref, data))
95
+
96
+ def set(self, ref: DocumentRef, data: dict[str, Any], *, merge: bool = False) -> WriteBatch:
97
+ return self._add(WriteBuilder.set(ref, data, merge=merge))
98
+
99
+ def update(
100
+ self,
101
+ ref: DocumentRef,
102
+ data: dict[str, Any],
103
+ *,
104
+ revision: int | None = None,
105
+ ) -> WriteBatch:
106
+ return self._add(WriteBuilder.update(ref, data, revision=revision))
107
+
108
+ def delete(self, ref: DocumentRef, *, revision: int | None = None) -> WriteBatch:
109
+ return self._add(WriteBuilder.delete(ref, revision=revision))
110
+
111
+ def _add(self, write: dict[str, Any]) -> WriteBatch:
112
+ if self._committed:
113
+ raise FletBaseError(
114
+ "FB_FIELD_PATH_INVALID",
115
+ "This batch was already committed. Build a new one with db.batch().",
116
+ {},
117
+ )
118
+ self._writes.append(write)
119
+ return self
120
+
121
+ async def commit(self) -> dict[str, Any]:
122
+ if not self._writes:
123
+ raise FletBaseError(
124
+ "FB_FIELD_PATH_INVALID", "A batch must contain at least one write.", {}
125
+ )
126
+ self._committed = True
127
+ # One mutation ID for the whole batch, fixed before the first attempt: that is
128
+ # what makes a transport retry of a lost batch return the original
129
+ # acknowledgement rather than applying every write a second time.
130
+ return await self._database._transport.request(
131
+ "POST",
132
+ "/batch",
133
+ json={
134
+ "writes": self._writes,
135
+ "mutation_id": self._database.new_mutation_id(),
136
+ "client_id": self._database.client_id,
137
+ },
138
+ )
139
+
140
+
141
+ __all__ = ["WriteBatch", "WriteBuilder"]
@@ -0,0 +1,192 @@
1
+ """The cloud database — V1 §5.1 and §5.3.
2
+
3
+ Async-only, deliberately. One surface means one implementation, no parity test to keep
4
+ honest, and — the reason it matters here — it works unchanged under Pyodide, where the
5
+ worker thread a sync facade would need does not exist.
6
+
7
+ A `Database` is not constructed directly. A project handle owns it, along with the
8
+ transport and credentials it uses (ADR 002), and closing the project is what releases
9
+ them; that is why there is no `close()` here.
10
+
11
+ Everything on this path is data-in, data-out: envelopes are built here, hashed and
12
+ committed by the server. No SQL, no query dialect, nothing but the versioned JSON the
13
+ server would accept from any surface (V1 §5.2, §9.3).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable, Coroutine
19
+ from typing import Any
20
+
21
+ from fletbase.transport.http import Transport
22
+ from fletbase.wire.errors import FletBaseError
23
+ from fletbase.wire.ids import prefixed_ulid, ulid
24
+ from fletbase.wire.names import canonicalize_collection_name
25
+
26
+ from .batch import WriteBatch, WriteBuilder
27
+ from .snapshot import DocumentSnapshot
28
+ from .transaction import Transaction, run_transaction
29
+
30
+ TransactionCallback = Callable[[Transaction], Coroutine[Any, Any, Any]]
31
+
32
+
33
+ class DocumentRef:
34
+ """A pointer to a document. Holds no data and performs no I/O until awaited."""
35
+
36
+ def __init__(self, database: Database, collection: str, doc_id: str) -> None:
37
+ self._database = database
38
+ self.collection = collection
39
+ self.id = doc_id
40
+
41
+ @property
42
+ def path(self) -> str:
43
+ return f"{self.collection}/{self.id}"
44
+
45
+ def __repr__(self) -> str:
46
+ return f"DocumentRef({self.path!r})"
47
+
48
+ async def get(self) -> DocumentSnapshot:
49
+ try:
50
+ body = await self._database._transport.request(
51
+ "GET", f"/collections/{self.collection}/documents/{self.id}"
52
+ )
53
+ except FletBaseError as exc:
54
+ # V1 §8.3: a denied point read is indistinguishable from a missing document,
55
+ # so both arrive as FB_PERMISSION_DENIED and both mean "you cannot see it".
56
+ # Reporting that as a non-existent snapshot rather than raising is what lets
57
+ # `if snap.exists` be the whole of a caller's error handling.
58
+ if exc.code == "FB_PERMISSION_DENIED":
59
+ return DocumentSnapshot.missing(self.path, self.id)
60
+ raise
61
+ return DocumentSnapshot.from_wire(body["document"])
62
+
63
+ async def set(self, data: dict[str, Any], *, merge: bool = False) -> DocumentSnapshot:
64
+ return await self._database._commit_single(
65
+ WriteBuilder.set(self, data, merge=merge), self.path
66
+ )
67
+
68
+ async def update(
69
+ self,
70
+ data: dict[str, Any],
71
+ *,
72
+ revision: int | None = None,
73
+ ) -> DocumentSnapshot:
74
+ """Update, optionally guarded by the revision the caller last saw.
75
+
76
+ `revision=` is the single-document form of an optimistic transaction: it fails
77
+ with FB_PRECONDITION_FAILED rather than clobbering a concurrent write.
78
+ """
79
+ return await self._database._commit_single(
80
+ WriteBuilder.update(self, data, revision=revision), self.path
81
+ )
82
+
83
+ async def delete(self, *, revision: int | None = None) -> None:
84
+ await self._database._commit_single(WriteBuilder.delete(self, revision=revision), self.path)
85
+
86
+
87
+ class Collection:
88
+ def __init__(self, database: Database, name: str) -> None:
89
+ self._database = database
90
+ # Canonicalized client-side so `doc.path` and the value echoed by the server
91
+ # agree, and the caller sees `Foo--Bar` become `foo_bar` before it is stored
92
+ # rather than discovering it on a later read (V1 §2.3).
93
+ self.name = canonicalize_collection_name(name)
94
+
95
+ def __repr__(self) -> str:
96
+ return f"Collection({self.name!r})"
97
+
98
+ def doc(self, doc_id: str | None = None) -> DocumentRef:
99
+ """A reference, allocating a ULID when none is given.
100
+
101
+ Allocating client-side is what lets an application build a graph of references
102
+ before any of them is written (V1 §3), and it is the same allocation V2 uses
103
+ offline.
104
+ """
105
+ return DocumentRef(self._database, self.name, doc_id or ulid())
106
+
107
+ async def add(self, data: dict[str, Any]) -> DocumentRef:
108
+ ref = self.doc()
109
+ await self._database._commit_single(WriteBuilder.create(ref, data), ref.path)
110
+ return ref
111
+
112
+
113
+ class Database:
114
+ """A project's cloud database. Obtained from `project.database`, never built directly."""
115
+
116
+ def __init__(self, transport: Transport, *, client_id: str) -> None:
117
+ self._transport = transport
118
+ # One client ID per project handle, mirroring "every SDK installation has a
119
+ # stable random client ID" (V1 §4.3). It scopes receipts, so two handles using
120
+ # the same mutation ID are correctly treated as two different mutations.
121
+ self.client_id = client_id
122
+
123
+ def __repr__(self) -> str:
124
+ return f"Database({self._transport.project_path!r})"
125
+
126
+ # --- surfaces ---------------------------------------------------------
127
+
128
+ def collection(self, name: str) -> Collection:
129
+ return Collection(self, name)
130
+
131
+ def batch(self) -> WriteBatch:
132
+ return WriteBatch(self)
133
+
134
+ async def run_transaction(
135
+ self,
136
+ callback: TransactionCallback,
137
+ *,
138
+ max_attempts: int = 5,
139
+ ) -> Any:
140
+ """Run an optimistic transaction — V1 §5.3.
141
+
142
+ The callback receives a transaction, reads through it, and queues writes. Reads
143
+ are recorded with the revision they saw; the commit succeeds only if every one
144
+ still holds, and otherwise the callback runs again against fresh data.
145
+
146
+ **The callback may run more than once, so it must not have external side
147
+ effects** — no emails, no logging that implies a commit, no mutation of state
148
+ outside the transaction.
149
+ """
150
+ return await run_transaction(self, callback, max_attempts=max_attempts)
151
+
152
+ # --- internals --------------------------------------------------------
153
+
154
+ def new_mutation_id(self) -> str:
155
+ return prefixed_ulid("mut")
156
+
157
+ async def _commit_single(self, write: dict[str, Any], path: str) -> DocumentSnapshot:
158
+ """Send one write as a one-element envelope.
159
+
160
+ The resource endpoints are ergonomic sugar: the server builds the same envelope
161
+ a batch would and calls the same `commit()`. Going through `/batch` here means
162
+ the SDK has exactly one write path too, so a single write and a batched one
163
+ cannot drift.
164
+ """
165
+ body = await self._transport.request(
166
+ "POST",
167
+ "/batch",
168
+ json={
169
+ "writes": [write],
170
+ "mutation_id": self.new_mutation_id(),
171
+ "client_id": self.client_id,
172
+ },
173
+ )
174
+ return _ack_to_snapshot(body, path)
175
+
176
+
177
+ def _ack_to_snapshot(body: dict[str, Any], path: str) -> DocumentSnapshot:
178
+ result = body["results"][0]
179
+ return DocumentSnapshot(
180
+ id=result["id"],
181
+ path=result["path"],
182
+ exists=not result["deleted"],
183
+ # A commit acknowledges; it does not read the document back. Callers who want
184
+ # the stored value re-read, which is one round trip they can decline to pay.
185
+ data={},
186
+ revision=result["revision"],
187
+ created_at=None,
188
+ updated_at=None,
189
+ )
190
+
191
+
192
+ __all__ = ["Collection", "Database", "DocumentRef"]
@@ -0,0 +1,76 @@
1
+ """What a read returns — V1 §3's document plus its `@` metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timedelta, timezone
7
+ from typing import Any
8
+
9
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
10
+
11
+
12
+ def _from_micros(value: int) -> datetime:
13
+ # Integer arithmetic, not `fromtimestamp(value / 1e6)`: a float has 53 bits, and
14
+ # today's microsecond timestamps already need 51 of them, so dividing first would
15
+ # round away exactly the precision `$date` exists to carry (V1 §4.1).
16
+ return _EPOCH + timedelta(microseconds=value)
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class DocumentSnapshot:
21
+ """A document as it was when read.
22
+
23
+ Metadata lives in its own namespace on the wire (`@id`, `@revision`, ...) so a user
24
+ field named `created_at` is never confused with the server-assigned timestamp. Here
25
+ it is unpacked into attributes, and `data` holds only user fields.
26
+
27
+ A snapshot for a document that does not exist has `exists is False` and empty
28
+ `data`, rather than being `None` — so `snap["title"]` fails with a clear message
29
+ instead of `AttributeError` on `None`.
30
+ """
31
+
32
+ id: str
33
+ path: str
34
+ exists: bool
35
+ data: dict[str, Any]
36
+ revision: int | None
37
+ created_at: datetime | None
38
+ updated_at: datetime | None
39
+
40
+ def __getitem__(self, key: str) -> Any:
41
+ return self.data[key]
42
+
43
+ def get(self, key: str, default: Any = None) -> Any:
44
+ return self.data.get(key, default)
45
+
46
+ def __contains__(self, key: str) -> bool:
47
+ return key in self.data
48
+
49
+ @staticmethod
50
+ def missing(path: str, doc_id: str) -> DocumentSnapshot:
51
+ return DocumentSnapshot(
52
+ id=doc_id,
53
+ path=path,
54
+ exists=False,
55
+ data={},
56
+ revision=None,
57
+ created_at=None,
58
+ updated_at=None,
59
+ )
60
+
61
+ @staticmethod
62
+ def from_wire(payload: dict[str, Any]) -> DocumentSnapshot:
63
+ created = payload.get("@created_at")
64
+ updated = payload.get("@updated_at")
65
+ return DocumentSnapshot(
66
+ id=payload["@id"],
67
+ path=payload["@path"],
68
+ exists=True,
69
+ data=payload.get("data", {}),
70
+ revision=payload.get("@revision"),
71
+ created_at=_from_micros(created["$date"]) if created else None,
72
+ updated_at=_from_micros(updated["$date"]) if updated else None,
73
+ )
74
+
75
+
76
+ __all__ = ["DocumentSnapshot"]