compose-application 0.1.0a1__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.
@@ -0,0 +1,8 @@
1
+ """Optional composition of typed storage, APIs and spatial interfaces.
2
+
3
+ Application assembly APIs are developed through the Cohesion Block A roadmap.
4
+ """
5
+
6
+ from .service import ProfileError, Service, ServiceConfig, application
7
+
8
+ __all__ = ["ProfileError", "Service", "ServiceConfig", "application"]
@@ -0,0 +1,79 @@
1
+ """Explicit in-process Headless Spreadsheets/Backpack table assembly."""
2
+
3
+ import argparse
4
+ from contextlib import contextmanager
5
+ import json
6
+ from pathlib import Path
7
+ from tempfile import TemporaryDirectory
8
+
9
+ from .tabular import TableItem
10
+
11
+
12
+ @contextmanager
13
+ def headless_application(database):
14
+ """The application owns registration, initialization and connection close."""
15
+ from backpack_store import ApplicationStore, DataclassCodec
16
+ from headless_spreadsheets import SourceColumn
17
+ from headless_spreadsheets.backpack import BackpackSource
18
+ with ApplicationStore.open(database) as store:
19
+ model = store.register(DataclassCodec(TableItem, type_key="reference.table_item"), namespace="tabular",
20
+ table="app_tabular_items", primary_key="key", columns={name: name for name in TableItem.__dataclass_fields__})
21
+ store.initialize("tabular")
22
+ source = BackpackSource(model, model_type=TableItem, key_field="key", table_id="work_items", schema_version="1", columns=[
23
+ SourceColumn("key", "Key", "text", False),
24
+ SourceColumn("title", "Title", "text", False, searchable=True, writable=True),
25
+ SourceColumn("done", "Done", "boolean", False, writable=True),
26
+ SourceColumn("rank", "Rank", "integer", True, writable=True),
27
+ SourceColumn("score", "Score", "number", False, writable=True)])
28
+ try:
29
+ yield source, model
30
+ finally:
31
+ source.close()
32
+
33
+
34
+ def accept_headless():
35
+ from backpack_store import RevisionConflictError, TransactionError
36
+ checks = 0
37
+ def check(condition):
38
+ nonlocal checks
39
+ if not condition:
40
+ raise RuntimeError("Headless persistence acceptance failed.")
41
+ checks += 1
42
+ with TemporaryDirectory(prefix="headless-table-") as directory:
43
+ path = Path(directory) / "items.sqlite"
44
+ with headless_application(path) as (source, model):
45
+ model.create(TableItem("a", "Zulu", "alice", rank=2))
46
+ model.create(TableItem("b", "Alpha", "alice", rank=1))
47
+ row = source.query(columns=["title", "key"], order=[("title", False)], search=dict(fields=["title"], term="Alpha")).rows[0]
48
+ check((row.key, row.revision, row.source_addresses) == ("b", "1", ("title", "key")))
49
+ result = source.edit(row.key, "title", "Headless saved", expected_revision=row.revision)
50
+ check((result.key, result.revision) == ("b", "2"))
51
+ check(model.get("a").value.title == "Zulu" and model.get("b").value.owner == "alice")
52
+ with headless_application(path) as (other, _):
53
+ try:
54
+ other.edit("b", "done", True, expected_revision="1")
55
+ except RevisionConflictError:
56
+ check(True)
57
+ else:
58
+ check(False)
59
+ check(other.get("b") == result)
60
+ try:
61
+ source.edit("b", "title", "", expected_revision="2")
62
+ except TransactionError:
63
+ check(source.get("b") == result)
64
+ else:
65
+ check(False)
66
+ with headless_application(path) as (reopened, _):
67
+ check(reopened.get("b") == result)
68
+ return dict(profile="cpython-tabular/1", consumer="headless-backpack", checks=checks, independent_reopen=True, passed=True)
69
+
70
+
71
+ def main():
72
+ parser = argparse.ArgumentParser(description=__doc__)
73
+ parser.add_argument("command", choices=("check",))
74
+ parser.parse_args()
75
+ print(json.dumps(accept_headless(), sort_keys=True))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
@@ -0,0 +1,361 @@
1
+ """Protected, single-origin native live composition with explicit credentials."""
2
+
3
+ import asyncio
4
+ from contextlib import AsyncExitStack, asynccontextmanager
5
+ from contextvars import ContextVar
6
+ from dataclasses import dataclass, field
7
+ import hmac
8
+ from importlib import metadata
9
+ import inspect
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import re
14
+
15
+ from .reference import WorkItem
16
+ from .service import ProfileError
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class OwnedWorkItem:
21
+ key: str
22
+ title: str
23
+ done: bool = False
24
+ owner: str = field(default="", metadata={"expose_api": {"write_only": True}})
25
+
26
+ def __post_init__(self):
27
+ WorkItem(self.key, self.title, self.done)
28
+ if type(self.owner) is not str or len(self.owner) > 256:
29
+ raise ValueError("Select a bounded owner identifier.")
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Credential:
34
+ principal: object
35
+ token: str = field(repr=False)
36
+
37
+ def __post_init__(self):
38
+ if type(self.token) is not str or not re.fullmatch(r"[A-Za-z0-9._~-]{16,256}", self.token):
39
+ raise ValueError("Select an explicit bounded application credential.")
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class LiveConfig:
44
+ database: Path
45
+ origin: str
46
+ verify: object = field(repr=False)
47
+ credentials: tuple[Credential, ...] = field(repr=False)
48
+ cookie_name: str = "work_identity"
49
+ retention: int = 64
50
+
51
+ def __post_init__(self):
52
+ if str(self.database) == ":memory:":
53
+ raise ValueError("Select a persistent local database.")
54
+ object.__setattr__(self, "database", Path(self.database))
55
+ object.__setattr__(self, "credentials", tuple(self.credentials))
56
+ if not callable(self.verify) or inspect.iscoroutinefunction(self.verify):
57
+ raise ValueError("Select a bounded synchronous credential verifier.")
58
+ if not 1 <= len(self.credentials) <= 8 or any(type(value) is not Credential for value in self.credentials):
59
+ raise ValueError("Select between one and eight explicit principal/credential bindings.")
60
+ if len({value.token for value in self.credentials}) != len(self.credentials):
61
+ raise ValueError("Application credentials must be unique.")
62
+ if type(self.cookie_name) is not str or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]{0,63}", self.cookie_name):
63
+ raise ValueError("Select one application-owned identity cookie name.")
64
+ if type(self.retention) is not int or not 1 <= self.retention <= 4096:
65
+ raise ValueError("Select a bounded journal retention.")
66
+
67
+
68
+ def _dependencies():
69
+ try:
70
+ for package in ("spatial-ui", "expose-api", "backpack-store", "enforce-type"):
71
+ if metadata.version(package) != ("0.1.1" if package == "spatial-ui" else "0.2.0"):
72
+ raise ProfileError("Installed packages do not match the selected live profile.")
73
+ import expose_api as api
74
+ from expose_api.backpack import BackpackStore
75
+ from spatial_ui import ASGIApp
76
+ from spatial_ui.live import LiveConfig as BrowserLiveConfig
77
+ if "predicate" not in inspect.signature(BackpackStore.update_checked).parameters:
78
+ raise ImportError
79
+ except (ImportError, metadata.PackageNotFoundError):
80
+ raise ProfileError("Install compose-application[live] with its qualified published versions.") from None
81
+ return api, BackpackStore, ASGIApp, BrowserLiveConfig
82
+
83
+
84
+ @asynccontextmanager
85
+ async def _api_lifespan(app):
86
+ incoming, outgoing = asyncio.Queue(), asyncio.Queue()
87
+ task = asyncio.create_task(app({"type": "lifespan"}, incoming.get, outgoing.put))
88
+ try:
89
+ await incoming.put({"type": "lifespan.startup"})
90
+ result = await outgoing.get()
91
+ if result["type"] != "lifespan.startup.complete":
92
+ await task
93
+ raise ProfileError("Live API startup failed.")
94
+ except BaseException:
95
+ task.cancel()
96
+ await asyncio.gather(task, return_exceptions=True)
97
+ raise
98
+ try:
99
+ yield
100
+ finally:
101
+ await incoming.put({"type": "lifespan.shutdown"})
102
+ result = await outgoing.get()
103
+ await task
104
+ if result["type"] != "lifespan.shutdown.complete":
105
+ raise ProfileError("Live API shutdown failed.")
106
+
107
+
108
+ class _BridgeTransport:
109
+ def __init__(self, origin, credential):
110
+ from spatial_ui.rest import HTTPTransport
111
+ self.transport = HTTPTransport(origin, headers=(("Authorization", "Bearer " + credential.token),))
112
+ self.owner = credential.principal.subject
113
+
114
+ def request(self, method, path, *, data=None, revision=None):
115
+ if method == "POST":
116
+ data = {**data, "owner": self.owner}
117
+ return self.transport.request(method, path, data=data, revision=revision)
118
+
119
+
120
+ class LiveApplication:
121
+ """One process/event loop; caller supplies the ASGI host and credentials.
122
+
123
+ Constructing configuration opens no storage or worker. Use host lifespan,
124
+ or an explicit async context for embedding, and drain the host on shutdown.
125
+ """
126
+
127
+ max_body_size = 65536
128
+
129
+ def __init__(self, config: LiveConfig):
130
+ if not isinstance(config, LiveConfig):
131
+ raise TypeError("LiveApplication requires LiveConfig.")
132
+ self.config = config
133
+ self.state = {"profile": "cpython-live/1"}
134
+ self.store = self.resource = self.api = None
135
+ self.adapters = {}
136
+ self._stack = self._close_task = self._idle = None
137
+ self._requests = set()
138
+ self._closing = False
139
+ self._opening = False
140
+ self._loop = self._pid = None
141
+
142
+ def _credential(self, scope, *, bearer=True):
143
+ headers = scope.get("headers", ())
144
+ authorization = [value for name, value in headers if name.lower() == b"authorization"]
145
+ cookies = [value for name, value in headers if name.lower() == b"cookie"]
146
+ if len(authorization) > 1 or len(cookies) > 1:
147
+ return None
148
+ token = None
149
+ if authorization:
150
+ if not bearer or cookies:
151
+ return None
152
+ match = re.fullmatch(rb"Bearer ([A-Za-z0-9._~-]{16,256})", authorization[0])
153
+ if match:
154
+ token = match[1].decode("ascii")
155
+ elif cookies:
156
+ if len(cookies[0]) > 8192:
157
+ return None
158
+ matches = [part.strip().partition(b"=")[2] for part in cookies[0].split(b";")
159
+ if part.strip().partition(b"=")[0] == self.config.cookie_name.encode("ascii")]
160
+ if len(matches) == 1 and re.fullmatch(rb"[A-Za-z0-9._~-]{16,256}", matches[0]):
161
+ token = matches[0].decode("ascii")
162
+ if token is None:
163
+ return None
164
+ binding = next((value for value in self.config.credentials if hmac.compare_digest(value.token, token)), None)
165
+ if binding is None:
166
+ return None
167
+ try:
168
+ principal = self.config.verify(token)
169
+ if inspect.isawaitable(principal):
170
+ if inspect.iscoroutine(principal):
171
+ principal.close()
172
+ return None
173
+ return binding if type(principal) is type(binding.principal) and principal == binding.principal else None
174
+ except Exception:
175
+ return None
176
+
177
+ async def __aenter__(self):
178
+ if self._stack is not None or self._opening:
179
+ raise RuntimeError("Live application is already open.")
180
+ self._opening = True
181
+ try:
182
+ return await self._open()
183
+ finally:
184
+ self._opening = False
185
+
186
+ async def _open(self):
187
+ api, adapter, ASGIApp, BrowserLiveConfig = _dependencies()
188
+ from spatial_ui.rest import ResourceClient
189
+ from .ui import make_ui, resource_client
190
+ if any(type(item.principal) is not api.Principal for item in self.config.credentials):
191
+ raise ValueError("Bind explicit immutable API principals.")
192
+ if len({item.principal.subject for item in self.config.credentials}) != len(self.config.credentials):
193
+ raise ValueError("Select one credential binding per globally unique subject.")
194
+ expected, returned, current = (ContextVar(name, default=None) for name in ("expected", "returned", "principal"))
195
+ self._expected, self._returned, self._current = expected, returned, current
196
+ def policy(principal, operation, value):
197
+ return principal is not None and "work-items" in principal.scopes and principal.subject == value.owner
198
+ class CheckedStore(adapter):
199
+ async def create(self, key, value):
200
+ result = await super().create(key, value)
201
+ returned.set("1")
202
+ return result
203
+ async def get(self, key):
204
+ row = await self.get_row(key)
205
+ returned.set(row.revision)
206
+ return row.value
207
+ async def update(self, key, transform):
208
+ principal = current.get()
209
+ row = await self.update_checked(key, expected_revision=expected.get(), transform=transform,
210
+ predicate=(lambda value: policy(principal, "update", value)) if principal is not None else None)
211
+ returned.set(row.revision)
212
+ return row.value
213
+ async def delete_where(self, key, predicate):
214
+ await super().delete_where(key, predicate, expected_revision=expected.get())
215
+ # Validate native origin/configuration before opening persistent storage.
216
+ adapters = {}
217
+ for credential in self.config.credentials:
218
+ client = ResourceClient(_BridgeTransport(self.config.origin, credential), resource_client(self.config.origin).spec)
219
+ adapters[credential.principal] = ASGIApp(make_ui(self.config.origin, client=client,
220
+ live=BrowserLiveConfig("/work-items")), origin=self.config.origin)
221
+ stack = AsyncExitStack()
222
+ try:
223
+ store = await CheckedStore.open(OwnedWorkItem, self.config.database, namespace="live_work_items",
224
+ table="app_live_work_items", type_key="example.live_work_item", id_field="key",
225
+ events=self.config.retention, event_namespace="live_work_item_events")
226
+ await stack.enter_async_context(store)
227
+ application = api.App(authenticate=lambda request: (binding.principal if (binding := self._credential(request.scope)) else None), auth_challenge="Custom")
228
+ def authorize(request):
229
+ current.set(request.principal)
230
+ return "work-items" in request.principal.scopes
231
+ resource = application.include(OwnedWorkItem, store=store, path="/work-items", id_field="key",
232
+ authorize=authorize, record_policy=policy)
233
+ application.subscribe(resource, origins=(self.config.origin,),
234
+ hosts=(self.config.origin.split("://", 1)[1],), connections=64,
235
+ max_message_bytes=65536, poll_interval=0.05)
236
+ await stack.enter_async_context(_api_lifespan(application))
237
+ for ui in adapters.values():
238
+ await stack.enter_async_context(ui)
239
+ except BaseException:
240
+ await stack.aclose()
241
+ raise
242
+ self._stack, self.store, self.api, self.resource, self.adapters = stack, store, application, resource, adapters
243
+ self._idle = asyncio.Event()
244
+ self._idle.set()
245
+ self._closing, self._close_task = False, None
246
+ self._loop, self._pid = asyncio.get_running_loop(), os.getpid()
247
+ return self
248
+
249
+ async def __aexit__(self, *_):
250
+ await self.aclose()
251
+
252
+ async def aclose(self):
253
+ if self._opening:
254
+ raise RuntimeError("Live application startup is still running.")
255
+ if self._stack is None:
256
+ return
257
+ self._owner()
258
+ if self._close_task is None:
259
+ self._closing = True
260
+ self._close_task = asyncio.create_task(self._drain())
261
+ task = self._close_task
262
+ cancelled = False
263
+ while not task.done():
264
+ try:
265
+ await asyncio.shield(task)
266
+ except asyncio.CancelledError:
267
+ cancelled = True
268
+ task.result()
269
+ if cancelled:
270
+ raise asyncio.CancelledError
271
+
272
+ async def _drain(self):
273
+ await asyncio.gather(*(adapter.aclose() for adapter in self.adapters.values()))
274
+ await self._idle.wait()
275
+ await self._stack.aclose()
276
+ self._stack = None
277
+ self._loop = self._pid = None
278
+
279
+ def _owner(self):
280
+ if self._loop is not asyncio.get_running_loop() or self._pid != os.getpid():
281
+ raise RuntimeError("Live application must stay in its opening process and event loop.")
282
+
283
+ async def _error(self, scope, send, status):
284
+ if scope["type"] == "websocket":
285
+ await send({"type": "websocket.close", "code": 1008 if status != 503 else 1001})
286
+ return
287
+ body = json.dumps({"error": "Live application unavailable."}).encode()
288
+ await send({"type": "http.response.start", "status": status, "headers": [
289
+ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode()), (b"cache-control", b"no-store")]})
290
+ await send({"type": "http.response.body", "body": b"" if scope["method"] == "HEAD" else body})
291
+
292
+ async def __call__(self, scope, receive, send):
293
+ if scope["type"] == "lifespan":
294
+ return await self._lifespan(receive, send)
295
+ if self._stack is None or self._closing:
296
+ return await self._error(scope, send, 503)
297
+ self._owner()
298
+ headers = scope.get("headers", ())
299
+ hosts = [value for name, value in headers if name.lower() == b"host"]
300
+ if hosts != [self.config.origin.split("://", 1)[1].encode("ascii")] or scope.get("root_path"):
301
+ return await self._error(scope, send, 421)
302
+ if scope["type"] == "websocket":
303
+ return await self.api(scope, receive, send)
304
+ if scope["type"] != "http":
305
+ raise RuntimeError("Unsupported live application scope.")
306
+ if len(self._requests) >= 64:
307
+ return await self._error(scope, send, 503)
308
+ marker = object()
309
+ self._requests.add(marker)
310
+ self._idle.clear()
311
+ try:
312
+ if scope["path"] == "/work-items" or scope["path"].startswith("/work-items/"):
313
+ return await self._http_api(scope, receive, send)
314
+ binding = self._credential(scope, bearer=False)
315
+ if binding is None:
316
+ return await self._error(scope, send, 401)
317
+ await self.adapters[binding.principal](scope, receive, send)
318
+ finally:
319
+ self._requests.remove(marker)
320
+ if not self._requests:
321
+ self._idle.set()
322
+
323
+ async def _http_api(self, scope, receive, send):
324
+ headers = scope.get("headers", ())
325
+ if scope["method"] in ("POST", "PATCH", "DELETE"):
326
+ origins = [value for name, value in headers if name.lower() == b"origin"]
327
+ bearer = any(name.lower() == b"authorization" for name, value in headers)
328
+ if not bearer and origins != [self.config.origin.encode("ascii")]:
329
+ return await self._error(scope, send, 403)
330
+ expected = None
331
+ if scope["method"] in ("PATCH", "DELETE"):
332
+ revisions = [value for name, value in headers if name.lower() == b"if-match"]
333
+ match = re.fullmatch(rb'"([1-9][0-9]{0,18})"', revisions[0]) if len(revisions) == 1 else None
334
+ if match is None or int(match[1]) > 2**63 - 1:
335
+ return await self._error(scope, send, 428 if not revisions else 400)
336
+ expected = match[1].decode("ascii")
337
+ tokens = self._expected.set(expected), self._returned.set(None), self._current.set(None)
338
+ async def response(event):
339
+ if event["type"] == "http.response.start" and 200 <= event["status"] < 300 and self._returned.get() is not None:
340
+ event = {**event, "headers": [*event["headers"], (b"etag", ('"'+self._returned.get()+'"').encode("ascii"))]}
341
+ await send(event)
342
+ try:
343
+ await self.api(scope, receive, response)
344
+ finally:
345
+ self._expected.reset(tokens[0]); self._returned.reset(tokens[1]); self._current.reset(tokens[2])
346
+
347
+ async def _lifespan(self, receive, send):
348
+ if (await receive())["type"] != "lifespan.startup":
349
+ raise RuntimeError("Expected lifespan.startup.")
350
+ try:
351
+ await self.__aenter__()
352
+ except Exception:
353
+ await send({"type": "lifespan.startup.failed", "message": "Live application startup failed."})
354
+ return
355
+ try:
356
+ await send({"type": "lifespan.startup.complete"})
357
+ if (await receive())["type"] != "lifespan.shutdown":
358
+ raise RuntimeError("Expected lifespan.shutdown.")
359
+ finally:
360
+ await self.aclose()
361
+ await send({"type": "lifespan.shutdown.complete"})