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.
- compose_application/__init__.py +8 -0
- compose_application/headless_tabular.py +79 -0
- compose_application/live.py +361 -0
- compose_application/project_templates.py +373 -0
- compose_application/projects.py +253 -0
- compose_application/py.typed +1 -0
- compose_application/reference.py +215 -0
- compose_application/service.py +124 -0
- compose_application/tabular.py +233 -0
- compose_application/tabular_edits.py +93 -0
- compose_application/terminal_templates.py +191 -0
- compose_application/ui.py +178 -0
- compose_application-0.1.0a1.dist-info/METADATA +161 -0
- compose_application-0.1.0a1.dist-info/RECORD +16 -0
- compose_application-0.1.0a1.dist-info/WHEEL +4 -0
- compose_application-0.1.0a1.dist-info/licenses/LICENSE.md +21 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Synthetic local work-item REST application and offline acceptance command."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from contextvars import ContextVar
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import sys
|
|
12
|
+
from tempfile import TemporaryDirectory
|
|
13
|
+
|
|
14
|
+
from .service import ServiceConfig, _dependencies, _validation_profile, application
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class WorkItem:
|
|
19
|
+
key: str
|
|
20
|
+
title: str
|
|
21
|
+
done: bool = False
|
|
22
|
+
|
|
23
|
+
def __post_init__(self):
|
|
24
|
+
if type(self.key) is not str or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}", self.key):
|
|
25
|
+
raise ValueError("Invalid work item key.")
|
|
26
|
+
if type(self.title) is not str or not 1 <= len(self.title) <= 200 or type(self.done) is not bool:
|
|
27
|
+
raise ValueError("Invalid work item fields.")
|
|
28
|
+
try:
|
|
29
|
+
self.title.encode("utf-8")
|
|
30
|
+
except UnicodeError:
|
|
31
|
+
raise ValueError("Invalid work item text.") from None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _RevisionApp:
|
|
35
|
+
def __init__(self, app, expected, returned):
|
|
36
|
+
self.app, self.state, self.expected, self.returned = app, app.state, expected, returned
|
|
37
|
+
self.max_body_size = app.max_body_size
|
|
38
|
+
|
|
39
|
+
async def __call__(self, scope, receive, send):
|
|
40
|
+
if scope["type"] != "http":
|
|
41
|
+
return await self.app(scope, receive, send)
|
|
42
|
+
expected_token, returned_token = self.expected.set(None), self.returned.set(None)
|
|
43
|
+
try:
|
|
44
|
+
path, root = scope["path"], scope.get("root_path", "").rstrip("/")
|
|
45
|
+
if root and path.startswith(root + "/"):
|
|
46
|
+
path = path[len(root):]
|
|
47
|
+
if scope["method"] in ("PATCH", "DELETE") and path.startswith("/work-items/") and "/" not in path[len("/work-items/"):] and path != "/work-items/":
|
|
48
|
+
headers = [value for key, value in scope.get("headers", ()) if key.lower() == b"if-match"]
|
|
49
|
+
match = re.fullmatch(rb'"([1-9][0-9]{0,18})"', headers[0]) if len(headers) == 1 else None
|
|
50
|
+
if match is None or int(match[1]) > 9223372036854775807:
|
|
51
|
+
status, code = (428, "precondition_required") if not headers else (400, "precondition")
|
|
52
|
+
body = json.dumps({"error": {"code": code, "message": "Supply one canonical revision in If-Match.", "details": []}}).encode()
|
|
53
|
+
await send({"type": "http.response.start", "status": status, "headers": [
|
|
54
|
+
(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]})
|
|
55
|
+
await send({"type": "http.response.body", "body": body})
|
|
56
|
+
return
|
|
57
|
+
self.expected.set(match[1].decode("ascii"))
|
|
58
|
+
async def response(event):
|
|
59
|
+
if event["type"] == "http.response.start" and 200 <= event["status"] < 300 and self.returned.get() is not None:
|
|
60
|
+
event = {**event, "headers": [*event["headers"], (b"etag", ('"' + self.returned.get() + '"').encode("ascii"))]}
|
|
61
|
+
await send(event)
|
|
62
|
+
await self.app(scope, receive, response)
|
|
63
|
+
finally:
|
|
64
|
+
self.expected.reset(expected_token)
|
|
65
|
+
self.returned.reset(returned_token)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@asynccontextmanager
|
|
69
|
+
async def reference_application(database, *, validation="builtin"):
|
|
70
|
+
"""Open the public synthetic work-item example; caller owns local HTTP serving."""
|
|
71
|
+
profile = _validation_profile(validation)
|
|
72
|
+
api, adapter = _dependencies(extra="validation" if validation == "enforce-type" else "service")
|
|
73
|
+
expected, returned = ContextVar("expected_revision", default=None), ContextVar("returned_revision", default=None)
|
|
74
|
+
def revision():
|
|
75
|
+
value = expected.get()
|
|
76
|
+
if value is None:
|
|
77
|
+
raise api.ValidationError(api.Issue(("revision",), "required"))
|
|
78
|
+
return value
|
|
79
|
+
class CheckedStore(adapter):
|
|
80
|
+
async def create(self, key, value):
|
|
81
|
+
result = await super().create(key, value)
|
|
82
|
+
returned.set("1")
|
|
83
|
+
return result
|
|
84
|
+
async def get(self, key):
|
|
85
|
+
row = await self.get_row(key)
|
|
86
|
+
returned.set(row.revision)
|
|
87
|
+
return row.value
|
|
88
|
+
async def update(self, key, transform):
|
|
89
|
+
row = await self.update_checked(key, transform=transform, expected_revision=revision())
|
|
90
|
+
returned.set(row.revision)
|
|
91
|
+
return row.value
|
|
92
|
+
async def delete(self, key):
|
|
93
|
+
await self.delete_checked(key, expected_revision=revision())
|
|
94
|
+
config = ServiceConfig(WorkItem, Path(database), namespace="work_items", table="app_work_items",
|
|
95
|
+
type_key="example.work_item", id_field="key", resource_path="/work-items", public=True,
|
|
96
|
+
profile=profile)
|
|
97
|
+
async with application(config, store_type=CheckedStore) as service:
|
|
98
|
+
service.app = _RevisionApp(service.app, expected, returned)
|
|
99
|
+
yield service
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def _exchange(port, method, path, *, data=None, revision=None, headers=()):
|
|
103
|
+
"""Bounded real loopback HTTP exchange used by the synthetic acceptance."""
|
|
104
|
+
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
|
105
|
+
try:
|
|
106
|
+
body = b"" if data is None else json.dumps(data, ensure_ascii=False, allow_nan=False).encode()
|
|
107
|
+
lines = [f"{method} {path} HTTP/1.1", f"Host: 127.0.0.1:{port}", "Connection: close", f"Content-Length: {len(body)}"]
|
|
108
|
+
if data is not None:
|
|
109
|
+
lines.append("Content-Type: application/json")
|
|
110
|
+
if revision is not None:
|
|
111
|
+
lines.append(f'If-Match: "{revision}"')
|
|
112
|
+
lines.extend(headers)
|
|
113
|
+
writer.write(("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + body)
|
|
114
|
+
await writer.drain()
|
|
115
|
+
raw = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 5)
|
|
116
|
+
status_line, *response_headers = raw.decode("latin-1").strip().split("\r\n")
|
|
117
|
+
values = dict(line.lower().split(": ", 1) for line in response_headers)
|
|
118
|
+
size = int(values.get("content-length", "0"))
|
|
119
|
+
if not 0 <= size <= 65536:
|
|
120
|
+
raise RuntimeError("Acceptance response exceeded its bound.")
|
|
121
|
+
payload = await asyncio.wait_for(reader.readexactly(size), 5)
|
|
122
|
+
return int(status_line.split()[1]), values, json.loads(payload) if payload else None
|
|
123
|
+
finally:
|
|
124
|
+
writer.close()
|
|
125
|
+
await writer.wait_closed()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def _accept_phase(database, phase, validation="builtin"):
|
|
129
|
+
from expose_api import serve
|
|
130
|
+
async with reference_application(database, validation=validation) as service:
|
|
131
|
+
async with serve(service.app, port=0) as server:
|
|
132
|
+
port, checks = server.sockets[0].getsockname()[1], 0
|
|
133
|
+
async def check(method, path, status, *, data=None, revision=None, etag=None, code=None):
|
|
134
|
+
nonlocal checks
|
|
135
|
+
actual, headers, result = await _exchange(port, method, path, data=data, revision=revision)
|
|
136
|
+
if actual != status or etag is not None and headers.get("etag") != etag or code is not None and result["error"]["code"] != code:
|
|
137
|
+
raise RuntimeError(f"Reference {phase} acceptance failed: {method} expected status {status}, received {actual}.")
|
|
138
|
+
checks += 1
|
|
139
|
+
return result
|
|
140
|
+
if phase == "write":
|
|
141
|
+
await check("POST", "/work-items", 201, data={"key": "item-001", "title": "Garden 🌱"}, etag='"1"')
|
|
142
|
+
await check("PATCH", "/work-items/item-001", 422, revision="1", data={"done": 1})
|
|
143
|
+
await check("GET", "/work-items/item-001", 200, etag='"1"')
|
|
144
|
+
await check("PATCH", "/work-items/item-001", 200, revision="1", data={"title": "Changed locally"}, etag='"2"')
|
|
145
|
+
await check("PATCH", "/work-items/item-001", 409, revision="1", data={"done": True}, code="revision_conflict")
|
|
146
|
+
await check("DELETE", "/work-items/item-001", 428, code="precondition_required")
|
|
147
|
+
await check("POST", "/work-items", 201, data={"key": "item-002", "title": "Second"})
|
|
148
|
+
page = await check("GET", "/work-items?offset=1&limit=1", 200)
|
|
149
|
+
if [item["key"] for item in page] != ["item-002"]:
|
|
150
|
+
raise RuntimeError("Reference pagination returned an unexpected page.")
|
|
151
|
+
await check("GET", "/work-items?offset=10001", 422)
|
|
152
|
+
await check("DELETE", "/work-items/item-002", 204, revision="1")
|
|
153
|
+
elif phase == "reload":
|
|
154
|
+
item = await check("GET", "/work-items/item-001", 200, etag='"2"')
|
|
155
|
+
if item != {"key": "item-001", "title": "Changed locally", "done": False}:
|
|
156
|
+
raise RuntimeError("Reference restart did not retain the committed value.")
|
|
157
|
+
await check("PATCH", "/work-items/item-001", 422, revision="2", data={"key": "changed"})
|
|
158
|
+
await check("DELETE", "/work-items/item-001", 409, revision="1", code="revision_conflict")
|
|
159
|
+
await check("DELETE", "/work-items/item-001", 204, revision="2")
|
|
160
|
+
await check("GET", "/work-items/item-001", 404)
|
|
161
|
+
await check("POST", "/work-items", 409, data={"key": "item-001", "title": "Reused key"})
|
|
162
|
+
else:
|
|
163
|
+
raise ValueError("Unknown acceptance phase.")
|
|
164
|
+
return {"phase": phase, "checks": checks, "passed": True}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def accept_reference(*, validation="builtin"):
|
|
168
|
+
"""Run real HTTP in two independent processes over a dedicated temporary DB."""
|
|
169
|
+
profile = _validation_profile(validation)
|
|
170
|
+
_dependencies(extra="validation" if validation == "enforce-type" else "service")
|
|
171
|
+
receipts = []
|
|
172
|
+
code = "import asyncio,json,sys; from compose_application.reference import _accept_phase; print(json.dumps(asyncio.run(_accept_phase(sys.argv[1],sys.argv[2],sys.argv[3]))))"
|
|
173
|
+
with TemporaryDirectory(prefix="work-item-acceptance-") as directory:
|
|
174
|
+
for phase in ("write", "reload"):
|
|
175
|
+
process = await asyncio.create_subprocess_exec(sys.executable, "-I", "-c", code, str(Path(directory) / "work-items.sqlite3"), phase, validation,
|
|
176
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
|
177
|
+
try:
|
|
178
|
+
output, errors = await asyncio.wait_for(process.communicate(), 30)
|
|
179
|
+
if process.returncode:
|
|
180
|
+
raise RuntimeError(f"Reference acceptance process failed during {phase}: " + errors.decode("utf-8", errors="replace")[-4000:])
|
|
181
|
+
receipts.append(json.loads(output))
|
|
182
|
+
finally:
|
|
183
|
+
if process.returncode is None:
|
|
184
|
+
process.kill()
|
|
185
|
+
await process.communicate()
|
|
186
|
+
return {"profile": profile, "phases": receipts, "checks": sum(item["checks"] for item in receipts), "process_restart": True}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def main():
|
|
190
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
191
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
192
|
+
check = commands.add_parser("check", help="exercise a dedicated temporary database across real processes")
|
|
193
|
+
server = commands.add_parser("serve", help="serve synthetic work items on loopback")
|
|
194
|
+
server.add_argument("--database", required=True, type=Path)
|
|
195
|
+
server.add_argument("--port", type=int, default=8000)
|
|
196
|
+
for command in (check, server):
|
|
197
|
+
command.add_argument("--validation", choices=("builtin", "enforce-type"), default="builtin")
|
|
198
|
+
arguments = parser.parse_args()
|
|
199
|
+
async def run():
|
|
200
|
+
if arguments.command == "check":
|
|
201
|
+
print(json.dumps(await accept_reference(validation=arguments.validation), sort_keys=True))
|
|
202
|
+
else:
|
|
203
|
+
from expose_api import serve
|
|
204
|
+
async with reference_application(arguments.database, validation=arguments.validation) as service:
|
|
205
|
+
async with serve(service.app, port=arguments.port):
|
|
206
|
+
print(f"Synthetic work items: http://127.0.0.1:{arguments.port}/work-items", flush=True)
|
|
207
|
+
await asyncio.Event().wait()
|
|
208
|
+
try:
|
|
209
|
+
asyncio.run(run())
|
|
210
|
+
except KeyboardInterrupt:
|
|
211
|
+
pass
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
if __name__ == "__main__":
|
|
215
|
+
main()
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Explicit CPython service configuration and asynchronous resource ownership."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from contextlib import asynccontextmanager
|
|
5
|
+
from dataclasses import dataclass, is_dataclass
|
|
6
|
+
from importlib import import_module, metadata
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ProfileError(RuntimeError):
|
|
12
|
+
"""A selected application profile is unavailable or incompatible."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class ServiceConfig:
|
|
17
|
+
model: type
|
|
18
|
+
database: Path
|
|
19
|
+
namespace: str
|
|
20
|
+
table: str
|
|
21
|
+
type_key: str
|
|
22
|
+
id_field: str = "id"
|
|
23
|
+
resource_path: str = "/items"
|
|
24
|
+
public: bool = False
|
|
25
|
+
authorize: object = None
|
|
26
|
+
profile: str = "cpython-service/1"
|
|
27
|
+
timeout: float = 5.0
|
|
28
|
+
queue_limit: int = 64
|
|
29
|
+
max_body_size: int = 65536
|
|
30
|
+
|
|
31
|
+
def __post_init__(self):
|
|
32
|
+
if self.profile not in ("cpython-service/1", "cpython-service-enforce-type/1"):
|
|
33
|
+
raise ProfileError("Select cpython-service/1 or cpython-service-enforce-type/1 explicitly.")
|
|
34
|
+
if not isinstance(self.model, type) or not is_dataclass(self.model):
|
|
35
|
+
raise ValueError("Select an explicit trusted dataclass model.")
|
|
36
|
+
if str(self.database) == ":memory:":
|
|
37
|
+
raise ValueError("The service profile requires a persistent local database path.")
|
|
38
|
+
object.__setattr__(self, "database", Path(self.database))
|
|
39
|
+
if type(self.public) is not bool or (self.public and self.authorize is not None) or (not self.public and not callable(self.authorize)):
|
|
40
|
+
raise ValueError("Choose public=True or an explicit authorization callback.")
|
|
41
|
+
if type(self.queue_limit) is not int or not 1 <= self.queue_limit <= 1024:
|
|
42
|
+
raise ValueError("Queue capacity must be between 1 and 1024.")
|
|
43
|
+
if type(self.max_body_size) is not int or not 1 <= self.max_body_size <= 65536:
|
|
44
|
+
raise ValueError("Body size must be between 1 and 65536 bytes.")
|
|
45
|
+
if type(self.resource_path) is not str or not re.fullmatch(r"/[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*", self.resource_path):
|
|
46
|
+
raise ValueError("Choose an explicit static resource path.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _dependencies(*, extra="service"):
|
|
50
|
+
try:
|
|
51
|
+
for name in ("expose-api", "backpack-store", "enforce-type"):
|
|
52
|
+
if metadata.version(name) != "0.2.0":
|
|
53
|
+
raise ProfileError("Installed package versions do not match the qualified service profile.")
|
|
54
|
+
api = import_module("expose_api")
|
|
55
|
+
adapter = import_module("expose_api.backpack").BackpackStore
|
|
56
|
+
except (ImportError, metadata.PackageNotFoundError):
|
|
57
|
+
raise ProfileError(f"Install compose-application[{extra}] with the qualified published dependencies.") from None
|
|
58
|
+
if not all(callable(getattr(adapter, name, None)) for name in ("open", "get_row", "update_checked", "delete_checked", "aclose")):
|
|
59
|
+
raise ProfileError("The installed storage adapter does not implement the selected profile.")
|
|
60
|
+
return api, adapter
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _validation_profile(validation):
|
|
64
|
+
if type(validation) is not str or validation not in ("builtin", "enforce-type"):
|
|
65
|
+
raise ValueError("Select builtin or enforce-type validation explicitly.")
|
|
66
|
+
return "cpython-service/1" if validation == "builtin" else "cpython-service-enforce-type/1"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Service:
|
|
70
|
+
"""Opened storage, typed resource and API; the caller owns HTTP admission."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, config, store, resource, app):
|
|
73
|
+
self.config, self.store, self.resource, self.app = config, store, resource, app
|
|
74
|
+
self._close_task = None
|
|
75
|
+
|
|
76
|
+
async def aclose(self):
|
|
77
|
+
"""Drain storage cleanup before propagating cancellation; safe to repeat."""
|
|
78
|
+
if self._close_task is None:
|
|
79
|
+
self._close_task = asyncio.create_task(self.store.aclose())
|
|
80
|
+
cancelled = False
|
|
81
|
+
while not self._close_task.done():
|
|
82
|
+
try:
|
|
83
|
+
await asyncio.shield(self._close_task)
|
|
84
|
+
except asyncio.CancelledError:
|
|
85
|
+
cancelled = True
|
|
86
|
+
self._close_task.result()
|
|
87
|
+
if cancelled:
|
|
88
|
+
raise asyncio.CancelledError
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@asynccontextmanager
|
|
92
|
+
async def application(config: ServiceConfig, *, store_type=None):
|
|
93
|
+
"""Open the selected profile, unwind failed startup and close after serving.
|
|
94
|
+
|
|
95
|
+
An explicit store subclass can add application-owned checked-write behavior;
|
|
96
|
+
it must preserve the qualified adapter's public ownership contract.
|
|
97
|
+
"""
|
|
98
|
+
if not isinstance(config, ServiceConfig):
|
|
99
|
+
raise TypeError("application() requires ServiceConfig.")
|
|
100
|
+
api, adapter = _dependencies(extra="validation" if config.profile == "cpython-service-enforce-type/1" else "service")
|
|
101
|
+
if store_type is not None:
|
|
102
|
+
if not isinstance(store_type, type) or not issubclass(store_type, adapter):
|
|
103
|
+
raise ProfileError("Custom stores must extend the qualified Backpack adapter.")
|
|
104
|
+
adapter = store_type
|
|
105
|
+
schema_options = {}
|
|
106
|
+
if config.profile == "cpython-service-enforce-type/1":
|
|
107
|
+
try:
|
|
108
|
+
schema_type = import_module("expose_api.enforce_type").EnforceTypeSchema
|
|
109
|
+
except ImportError:
|
|
110
|
+
raise ProfileError("Install compose-application[validation] with the qualified adapter source.") from None
|
|
111
|
+
schema_options["schema"] = schema_type(config.model, id_field=config.id_field)
|
|
112
|
+
store = await adapter.open(config.model, config.database, namespace=config.namespace,
|
|
113
|
+
table=config.table, type_key=config.type_key, id_field=config.id_field,
|
|
114
|
+
timeout=config.timeout, queue_limit=config.queue_limit)
|
|
115
|
+
service = Service(config, store, None, None)
|
|
116
|
+
try:
|
|
117
|
+
app = api.App(max_body_size=config.max_body_size)
|
|
118
|
+
resource = app.include(config.model, store=store, path=config.resource_path,
|
|
119
|
+
id_field=config.id_field, public=config.public, authorize=config.authorize, **schema_options)
|
|
120
|
+
app.state["profile"] = config.profile
|
|
121
|
+
service.app, service.resource = app, resource
|
|
122
|
+
yield service
|
|
123
|
+
finally:
|
|
124
|
+
await service.aclose()
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Optional persisted read-only/editable tables over synthetic loopback records."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import sys
|
|
11
|
+
from tempfile import TemporaryDirectory
|
|
12
|
+
import threading
|
|
13
|
+
|
|
14
|
+
from .service import ProfileError, Service
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class TableItem:
|
|
19
|
+
key: str
|
|
20
|
+
title: str
|
|
21
|
+
owner: str = field(metadata={"expose_api": {"write_only": True}})
|
|
22
|
+
done: bool = False
|
|
23
|
+
rank: int | None = None
|
|
24
|
+
score: float = 0.0
|
|
25
|
+
|
|
26
|
+
def __post_init__(self):
|
|
27
|
+
if not self.title.strip() or self.rank is not None and self.rank < 0:
|
|
28
|
+
raise ValueError("A nonblank title and nonnegative nullable rank are required.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def dependencies():
|
|
32
|
+
try:
|
|
33
|
+
import expose_api as api
|
|
34
|
+
from expose_api.backpack import BackpackStore
|
|
35
|
+
from spatial_ui import App, HTTPTableClient, TableBrowser
|
|
36
|
+
from headless_spreadsheets import TableSource
|
|
37
|
+
if not callable(getattr(api.App, "tabular", None)) or not callable(getattr(BackpackStore, "tabular_page", None)):
|
|
38
|
+
raise ImportError
|
|
39
|
+
except ImportError:
|
|
40
|
+
raise ProfileError("Install compose-application[tabular] with its qualified source profile.") from None
|
|
41
|
+
return api, BackpackStore
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@asynccontextmanager
|
|
45
|
+
async def tabular_application(database, *, seed=True, editable=False):
|
|
46
|
+
"""Own a local worker and an explicitly protected synthetic table API."""
|
|
47
|
+
api, adapter = dependencies()
|
|
48
|
+
if str(database) == ":memory:" or type(seed) is not bool or type(editable) is not bool:
|
|
49
|
+
raise ValueError("Select a persistent database and explicit seed behavior.")
|
|
50
|
+
store = await adapter.open(TableItem, Path(database), namespace="tabular", table="app_tabular_items", type_key="reference.table_item", id_field="key")
|
|
51
|
+
service = Service(Path(database), store, None, None)
|
|
52
|
+
try:
|
|
53
|
+
if seed:
|
|
54
|
+
for index in range(120):
|
|
55
|
+
key = f"item-{index:03}"
|
|
56
|
+
try:
|
|
57
|
+
await store.get_row(key)
|
|
58
|
+
except api.NotFoundError:
|
|
59
|
+
title = "Café %_ Needle" if index == 55 else f"Item {index:03}"
|
|
60
|
+
value = TableItem(key, title, "bob" if index < 40 else "alice", index % 2 == 0, None if index % 7 == 0 else index % 5, index / 10)
|
|
61
|
+
try:
|
|
62
|
+
await store.create(key, value)
|
|
63
|
+
except api.ConflictError:
|
|
64
|
+
# Another explicitly selected local reference can seed concurrently.
|
|
65
|
+
await store.get_row(key)
|
|
66
|
+
def verify(token):
|
|
67
|
+
return api.Principal(token[7:]) if token in {"reader-alice", "reader-bob"} else None
|
|
68
|
+
app = api.App(authenticate=api.BearerAuth(verify), auth_challenge="Bearer", max_body_size=65536)
|
|
69
|
+
resource = app.include(TableItem, store=store, id_field="key", path="/work-items", operations=("list", "get", "update") if editable else ("list", "get"),
|
|
70
|
+
authorize=lambda request: request.principal is not None,
|
|
71
|
+
record_policy=lambda principal, operation, value: value.owner == principal.subject and value.title != "policy-denied")
|
|
72
|
+
app.tabular(resource, table_id="work_items", schema_version="1", application_scope="tabular-reference-v1", columns=[
|
|
73
|
+
api.TableColumn("title", "title", "Title", sortable=True, searchable=True, writable=editable),
|
|
74
|
+
api.TableColumn("done", "done", "Done", sortable=True, writable=editable),
|
|
75
|
+
api.TableColumn("rank", "rank", "Rank", sortable=True, writable=editable),
|
|
76
|
+
api.TableColumn("score", "score", "Score", sortable=True, writable=editable),
|
|
77
|
+
*([api.TableColumn("key", "key", "Key", sortable=True)] if editable else [])])
|
|
78
|
+
service.resource, service.app = resource, app
|
|
79
|
+
yield service
|
|
80
|
+
finally:
|
|
81
|
+
await service.aclose()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def transport(origin, principal="alice"):
|
|
85
|
+
from spatial_ui.rest import HTTPTransport
|
|
86
|
+
if principal not in {"alice", "bob"}:
|
|
87
|
+
raise ValueError("Select a synthetic reference principal.")
|
|
88
|
+
return HTTPTransport(origin, headers=(("Authorization", f"Bearer reader-{principal}"),), max_response_body=4194304)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def make_ui(client, *, editable=False):
|
|
92
|
+
from spatial_ui import App, TableBrowser
|
|
93
|
+
from .ui import STYLESHEET
|
|
94
|
+
return App(lambda: TableBrowser(client, title="Persistent work items", page_size=50, editable=editable),
|
|
95
|
+
title="Editable work items" if editable else "Read-only work items", stylesheet=STYLESHEET)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def fingerprint(store):
|
|
99
|
+
values = await store.list(limit=1000)
|
|
100
|
+
rows = [await store.get_row(value.key) for value in values]
|
|
101
|
+
raw = [[row.key, row.revision, asdict(row.value)] for row in rows]
|
|
102
|
+
return hashlib.sha256(json.dumps(raw, sort_keys=True, ensure_ascii=True).encode()).hexdigest()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def accept_phase(database, phase, continuation=None):
|
|
106
|
+
from expose_api import serve
|
|
107
|
+
from spatial_ui import HTTPTableClient
|
|
108
|
+
api, _ = dependencies()
|
|
109
|
+
checks = 0
|
|
110
|
+
def check(value):
|
|
111
|
+
nonlocal checks
|
|
112
|
+
if not value:
|
|
113
|
+
raise RuntimeError("Tabular reference acceptance failed.")
|
|
114
|
+
checks += 1
|
|
115
|
+
async with tabular_application(database, seed=phase == "seed") as service:
|
|
116
|
+
async with serve(service.app, port=0) as server:
|
|
117
|
+
origin = f"http://127.0.0.1:{server.sockets[0].getsockname()[1]}"
|
|
118
|
+
alice, bob = transport(origin), transport(origin, "bob")
|
|
119
|
+
client = await asyncio.to_thread(HTTPTableClient.open, alice, "/work-items")
|
|
120
|
+
before = await fingerprint(service.store)
|
|
121
|
+
def descriptor(**values):
|
|
122
|
+
return dict(generation=1, columns=[c.id for c in client.columns], order=[], search=None, cursor=None, limit=50, **values)
|
|
123
|
+
def query(**values):
|
|
124
|
+
data = descriptor()
|
|
125
|
+
data.update(values)
|
|
126
|
+
return alice.request("POST", "/work-items/_table/query", data=data)
|
|
127
|
+
if phase == "seed":
|
|
128
|
+
first = await asyncio.to_thread(query)
|
|
129
|
+
check(first.status == 200 and len(first.data["rows"]) == 50 and first.data["rows"][0]["key"] == "item-040")
|
|
130
|
+
continuation = first.data["next_cursor"]
|
|
131
|
+
check(type(continuation) is str and all(row["revision"] == "1" for row in first.data["rows"]))
|
|
132
|
+
second = await asyncio.to_thread(query, cursor=continuation)
|
|
133
|
+
check(second.status == 200 and len(second.data["rows"]) == 30 and second.data["next_cursor"] is None)
|
|
134
|
+
literal = await asyncio.to_thread(query, search={"fields": ["title"], "term": "%_"})
|
|
135
|
+
check(literal.status == 200 and [row["key"] for row in literal.data["rows"]] == ["item-055"])
|
|
136
|
+
sorted_page = await asyncio.to_thread(query, order=[{"column_id": "rank", "descending": True}])
|
|
137
|
+
check(sorted_page.status == 200 and sorted_page.data["rows"][0]["key"] == "item-044")
|
|
138
|
+
projected = await asyncio.to_thread(query, columns=["score", "title"])
|
|
139
|
+
check(projected.status == 200 and set(projected.data["rows"][0]["values"]) == {"score", "title"})
|
|
140
|
+
hidden = await asyncio.to_thread(query, search={"fields": ["owner"], "term": "alice"})
|
|
141
|
+
check(hidden.status == 400 and "alice" not in json.dumps(hidden.data))
|
|
142
|
+
changed = await asyncio.to_thread(query, cursor=continuation, search={"fields": ["title"], "term": "Item"})
|
|
143
|
+
check(changed.status == 400 and changed.data["error"]["code"] == "invalid_cursor")
|
|
144
|
+
other = await asyncio.to_thread(bob.request, "POST", "/work-items/_table/query", data=descriptor())
|
|
145
|
+
check(other.status == 200 and len(other.data["rows"]) == 40 and all(row["key"] < "item-040" for row in other.data["rows"]))
|
|
146
|
+
replay = await asyncio.to_thread(bob.request, "POST", "/work-items/_table/query", data={**descriptor(), "cursor": continuation})
|
|
147
|
+
check(replay.status == 400 and replay.data["error"]["code"] == "invalid_cursor")
|
|
148
|
+
check(await fingerprint(service.store) == before)
|
|
149
|
+
await service.store.update_checked("item-095", expected_revision="1", transform=lambda value: replace(value, title="Changed between pages"))
|
|
150
|
+
moved = await asyncio.to_thread(query, cursor=continuation)
|
|
151
|
+
check(next(row for row in moved.data["rows"] if row["key"] == "item-095")["revision"] == "2")
|
|
152
|
+
elif phase == "reopen":
|
|
153
|
+
second = await asyncio.to_thread(query, cursor=continuation)
|
|
154
|
+
row = next(row for row in second.data["rows"] if row["key"] == "item-095")
|
|
155
|
+
check(second.status == 200 and row["revision"] == "2" and row["values"]["title"] == "Changed between pages")
|
|
156
|
+
check(await fingerprint(service.store) == before)
|
|
157
|
+
denied = await asyncio.to_thread(alice.request, "GET", "/work-items/item-000")
|
|
158
|
+
check(denied.status == 404)
|
|
159
|
+
writes = await asyncio.to_thread(alice.request, "POST", "/work-items/_table/cell", data={})
|
|
160
|
+
check(writes.status == 404)
|
|
161
|
+
else:
|
|
162
|
+
raise ValueError("Unknown table acceptance phase.")
|
|
163
|
+
check(not service.store._backend._thread.is_alive())
|
|
164
|
+
return dict(phase=phase, checks=checks, passed=True, continuation=continuation)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def accept_tabular():
|
|
168
|
+
dependencies()
|
|
169
|
+
receipts, continuation = [], None
|
|
170
|
+
code = "import asyncio,json,sys; from compose_application.tabular import accept_phase; print(json.dumps(asyncio.run(accept_phase(sys.argv[1],sys.argv[2],None if sys.argv[3]=='-' else sys.argv[3]))))"
|
|
171
|
+
with TemporaryDirectory(prefix="tabular-reference-") as directory:
|
|
172
|
+
for phase in ("seed", "reopen"):
|
|
173
|
+
process = await asyncio.create_subprocess_exec(sys.executable, "-I", "-c", code,
|
|
174
|
+
str(Path(directory) / "table.sqlite"), phase, continuation or "-", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
|
175
|
+
try:
|
|
176
|
+
output, errors = await asyncio.wait_for(process.communicate(), 30)
|
|
177
|
+
if process.returncode:
|
|
178
|
+
raise RuntimeError("Tabular acceptance process failed: " + errors.decode(errors="replace")[-2000:])
|
|
179
|
+
receipt = json.loads(output)
|
|
180
|
+
continuation = receipt.pop("continuation")
|
|
181
|
+
receipts.append(receipt)
|
|
182
|
+
finally:
|
|
183
|
+
if process.returncode is None:
|
|
184
|
+
process.kill()
|
|
185
|
+
await process.communicate()
|
|
186
|
+
return dict(profile="cpython-tabular/1", checks=sum(receipt["checks"] for receipt in receipts), phases=receipts, process_restart=True)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def main():
|
|
190
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
191
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
192
|
+
commands.add_parser("check")
|
|
193
|
+
commands.add_parser("check-edits")
|
|
194
|
+
serve = commands.add_parser("serve")
|
|
195
|
+
serve.add_argument("--database", type=Path, required=True)
|
|
196
|
+
serve.add_argument("--port", type=int, default=8000)
|
|
197
|
+
serve.add_argument("--principal", choices=("alice", "bob"), default="alice")
|
|
198
|
+
serve.add_argument("--editable", action="store_true")
|
|
199
|
+
args = parser.parse_args()
|
|
200
|
+
async def run():
|
|
201
|
+
if args.command == "check":
|
|
202
|
+
print(json.dumps(await accept_tabular(), sort_keys=True))
|
|
203
|
+
return
|
|
204
|
+
if args.command == "check-edits":
|
|
205
|
+
from .tabular_edits import accept_edits
|
|
206
|
+
print(json.dumps(await accept_edits(), sort_keys=True))
|
|
207
|
+
return
|
|
208
|
+
dependencies()
|
|
209
|
+
from expose_api import serve
|
|
210
|
+
from spatial_ui import HTTPTableClient
|
|
211
|
+
async with tabular_application(args.database, editable=args.editable) as service:
|
|
212
|
+
async with serve(service.app, port=0) as server:
|
|
213
|
+
origin = f"http://127.0.0.1:{server.sockets[0].getsockname()[1]}"
|
|
214
|
+
client = await asyncio.to_thread(HTTPTableClient.open, transport(origin, args.principal), "/work-items", key_column="key" if args.editable else None)
|
|
215
|
+
with make_ui(client, editable=args.editable).make_server(args.port) as ui:
|
|
216
|
+
thread = threading.Thread(target=ui.serve_forever, kwargs={"poll_interval": .02}, daemon=True)
|
|
217
|
+
thread.start()
|
|
218
|
+
try:
|
|
219
|
+
print(f"Table reference: http://127.0.0.1:{ui.server_port}", flush=True)
|
|
220
|
+
await asyncio.Event().wait()
|
|
221
|
+
finally:
|
|
222
|
+
await asyncio.to_thread(ui.shutdown)
|
|
223
|
+
thread.join(5)
|
|
224
|
+
await asyncio.to_thread(ui.server_close)
|
|
225
|
+
print("Table reference closed.", flush=True)
|
|
226
|
+
try:
|
|
227
|
+
asyncio.run(run())
|
|
228
|
+
except KeyboardInterrupt:
|
|
229
|
+
pass
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
if __name__ == "__main__":
|
|
233
|
+
main()
|