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,373 @@
|
|
|
1
|
+
"""Source templates for finite, application-owned reference workflows."""
|
|
2
|
+
|
|
3
|
+
SERVICE_APP = '''"""Application-owned assembly of the accepted synthetic work-item service."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from compose_application.reference import reference_application
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@asynccontextmanager
|
|
13
|
+
async def open_application(database):
|
|
14
|
+
async with reference_application(Path(database)) as application:
|
|
15
|
+
yield application
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@asynccontextmanager
|
|
19
|
+
async def open_server(database, *, port=0):
|
|
20
|
+
from expose_api import serve
|
|
21
|
+
async with open_application(database) as application:
|
|
22
|
+
async with serve(application.app, port=port) as server:
|
|
23
|
+
yield server
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def serve(database, *, port=8000):
|
|
27
|
+
async with open_server(database, port=port) as server:
|
|
28
|
+
port = server.sockets[0].getsockname()[1]
|
|
29
|
+
print(f"Work items: http://127.0.0.1:{port}/work-items", flush=True)
|
|
30
|
+
await asyncio.Event().wait()
|
|
31
|
+
'''
|
|
32
|
+
|
|
33
|
+
COMMAND = '''"""Run the selected reference or its isolated temporary-data acceptance."""
|
|
34
|
+
|
|
35
|
+
import argparse
|
|
36
|
+
import asyncio
|
|
37
|
+
import json
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def main():
|
|
42
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
43
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
44
|
+
commands.add_parser("check", help="check temporary data across independent processes")
|
|
45
|
+
server = commands.add_parser("serve", help="start the loopback development reference")
|
|
46
|
+
server.add_argument("--database", required=True, type=Path)
|
|
47
|
+
server.add_argument("--port", type=int, default=8000)
|
|
48
|
+
arguments = parser.parse_args()
|
|
49
|
+
if arguments.command == "check":
|
|
50
|
+
from .checks import accept
|
|
51
|
+
print(json.dumps(asyncio.run(accept()), sort_keys=True))
|
|
52
|
+
else:
|
|
53
|
+
from .app import serve
|
|
54
|
+
try:
|
|
55
|
+
asyncio.run(serve(arguments.database, port=arguments.port))
|
|
56
|
+
except KeyboardInterrupt:
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
main()
|
|
62
|
+
'''
|
|
63
|
+
|
|
64
|
+
CHECK_RUNNER = '''"""Bounded acceptance using temporary data in independent processes."""
|
|
65
|
+
|
|
66
|
+
import asyncio
|
|
67
|
+
import json
|
|
68
|
+
from pathlib import Path
|
|
69
|
+
import sys
|
|
70
|
+
from tempfile import TemporaryDirectory
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def require(condition):
|
|
74
|
+
if not condition:
|
|
75
|
+
raise RuntimeError("Generated reference acceptance failed.")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
async def accept():
|
|
79
|
+
phases = []
|
|
80
|
+
code = "import asyncio,faulthandler,json,sys; from __PROJECT_MODULE__.checks import phase; faulthandler.dump_traceback_later(15); print(json.dumps(asyncio.run(phase(sys.argv[1],sys.argv[2])))); faulthandler.cancel_dump_traceback_later()"
|
|
81
|
+
with TemporaryDirectory(prefix="reference-project-check-") as directory:
|
|
82
|
+
for name in ("write", "reload"):
|
|
83
|
+
process = await asyncio.create_subprocess_exec(
|
|
84
|
+
sys.executable, "-I", "-W", "error::ResourceWarning", "-c", code,
|
|
85
|
+
str(Path(directory) / "check.sqlite3"), name,
|
|
86
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
|
87
|
+
communication = asyncio.create_task(process.communicate())
|
|
88
|
+
try:
|
|
89
|
+
try:
|
|
90
|
+
output, errors = await asyncio.wait_for(asyncio.shield(communication), 30)
|
|
91
|
+
except TimeoutError:
|
|
92
|
+
if process.returncode is None:
|
|
93
|
+
process.kill()
|
|
94
|
+
_, errors = await communication
|
|
95
|
+
raise RuntimeError("Generated check timed out during " + name + ": " + errors.decode("utf-8", errors="replace")[-8000:]) from None
|
|
96
|
+
if process.returncode:
|
|
97
|
+
raise RuntimeError("Generated check failed during " + name + ": " + errors.decode("utf-8", errors="replace")[-4000:])
|
|
98
|
+
phases.append(json.loads(output))
|
|
99
|
+
finally:
|
|
100
|
+
if process.returncode is None:
|
|
101
|
+
process.kill()
|
|
102
|
+
await communication
|
|
103
|
+
return {"profile": "__PROJECT_PROFILE__", "checks": sum(item["checks"] for item in phases),
|
|
104
|
+
"phases": phases, "process_restart": True, "passed": True}
|
|
105
|
+
'''
|
|
106
|
+
|
|
107
|
+
HTTP_CHECKS = '''
|
|
108
|
+
|
|
109
|
+
async def request(port, method, path, *, data=None, revision=None):
|
|
110
|
+
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
|
111
|
+
try:
|
|
112
|
+
body = b"" if data is None else json.dumps(data, allow_nan=False).encode()
|
|
113
|
+
headers = [f"{method} {path} HTTP/1.1", f"Host: 127.0.0.1:{port}",
|
|
114
|
+
"Connection: close", f"Content-Length: {len(body)}"]
|
|
115
|
+
if data is not None:
|
|
116
|
+
headers.append("Content-Type: application/json")
|
|
117
|
+
if revision is not None:
|
|
118
|
+
headers.append(f'If-Match: "{revision}"')
|
|
119
|
+
writer.write(("\\r\\n".join(headers) + "\\r\\n\\r\\n").encode("ascii") + body)
|
|
120
|
+
await writer.drain()
|
|
121
|
+
raw = await asyncio.wait_for(reader.readuntil(b"\\r\\n\\r\\n"), 5)
|
|
122
|
+
status, *fields = raw.decode("latin-1").strip().split("\\r\\n")
|
|
123
|
+
fields = dict(field.lower().split(": ", 1) for field in fields)
|
|
124
|
+
size = int(fields.get("content-length", "0"))
|
|
125
|
+
if not 0 <= size <= 65536:
|
|
126
|
+
raise RuntimeError("Acceptance response exceeded its bound.")
|
|
127
|
+
payload = await asyncio.wait_for(reader.readexactly(size), 5)
|
|
128
|
+
value = json.loads(payload) if payload and "application/json" in fields.get("content-type", "") else payload.decode("utf-8")
|
|
129
|
+
return int(status.split()[1]), fields, value
|
|
130
|
+
finally:
|
|
131
|
+
writer.close()
|
|
132
|
+
await writer.wait_closed()
|
|
133
|
+
'''
|
|
134
|
+
|
|
135
|
+
SERVICE_PHASE = '''
|
|
136
|
+
|
|
137
|
+
async def phase(database, name):
|
|
138
|
+
import threading
|
|
139
|
+
from .app import open_server
|
|
140
|
+
threads = {thread.ident for thread in threading.enumerate()}
|
|
141
|
+
async with open_server(database) as server:
|
|
142
|
+
port = server.sockets[0].getsockname()[1]
|
|
143
|
+
checks = 0
|
|
144
|
+
async def check(method, path, expected, **options):
|
|
145
|
+
nonlocal checks
|
|
146
|
+
status, headers, value = await request(port, method, path, **options)
|
|
147
|
+
require(status == expected)
|
|
148
|
+
checks += 1
|
|
149
|
+
return headers, value
|
|
150
|
+
if name == "write":
|
|
151
|
+
headers, value = await check("POST", "/work-items", 201, data={"key": "garden", "title": "Garden 🌱"})
|
|
152
|
+
require(headers.get("etag") == '\"1\"' and value["done"] is False)
|
|
153
|
+
await check("PATCH", "/work-items/garden", 422, revision="1", data={"done": 1})
|
|
154
|
+
headers, _ = await check("PATCH", "/work-items/garden", 200, revision="1", data={"title": "Water garden"})
|
|
155
|
+
require(headers.get("etag") == '\"2\"')
|
|
156
|
+
await check("PATCH", "/work-items/garden", 409, revision="1", data={"done": True})
|
|
157
|
+
await check("DELETE", "/work-items/garden", 428)
|
|
158
|
+
elif name == "reload":
|
|
159
|
+
headers, value = await check("GET", "/work-items/garden", 200)
|
|
160
|
+
require(headers.get("etag") == '\"2\"' and value["title"] == "Water garden" and value["done"] is False)
|
|
161
|
+
await check("DELETE", "/work-items/garden", 409, revision="1")
|
|
162
|
+
await check("DELETE", "/work-items/garden", 204, revision="2")
|
|
163
|
+
await check("GET", "/work-items/garden", 404)
|
|
164
|
+
else:
|
|
165
|
+
raise ValueError("Unknown acceptance phase.")
|
|
166
|
+
require({thread.ident for thread in threading.enumerate()} == threads)
|
|
167
|
+
return {"phase": name, "checks": checks, "closed": True}
|
|
168
|
+
'''
|
|
169
|
+
|
|
170
|
+
UI_APP = '''"""Application-owned loopback UI and persistent checked REST lifecycle."""
|
|
171
|
+
|
|
172
|
+
import asyncio
|
|
173
|
+
from contextlib import asynccontextmanager
|
|
174
|
+
from pathlib import Path
|
|
175
|
+
import threading
|
|
176
|
+
|
|
177
|
+
from compose_application.reference import reference_application
|
|
178
|
+
from compose_application.ui import make_ui, resource_client
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@asynccontextmanager
|
|
182
|
+
async def open_server(database, *, port=0):
|
|
183
|
+
from expose_api import serve
|
|
184
|
+
async with reference_application(Path(database)) as application:
|
|
185
|
+
async with serve(application.app, port=0) as api:
|
|
186
|
+
origin = f"http://127.0.0.1:{api.sockets[0].getsockname()[1]}"
|
|
187
|
+
with make_ui(origin).make_server(port) as ui:
|
|
188
|
+
thread = threading.Thread(target=ui.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)
|
|
189
|
+
thread.start()
|
|
190
|
+
try:
|
|
191
|
+
yield ui, resource_client(origin)
|
|
192
|
+
finally:
|
|
193
|
+
await asyncio.to_thread(ui.shutdown)
|
|
194
|
+
await asyncio.to_thread(thread.join, 5)
|
|
195
|
+
if thread.is_alive():
|
|
196
|
+
raise RuntimeError("UI server did not stop within its shutdown bound.")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
async def serve(database, *, port=8000):
|
|
200
|
+
async with open_server(database, port=port) as (ui, _):
|
|
201
|
+
print(f"Work items: http://127.0.0.1:{ui.server_port}", flush=True)
|
|
202
|
+
await asyncio.Event().wait()
|
|
203
|
+
'''
|
|
204
|
+
|
|
205
|
+
UI_PHASE = '''
|
|
206
|
+
|
|
207
|
+
async def phase(database, name):
|
|
208
|
+
import threading
|
|
209
|
+
from spatial_ui import Session
|
|
210
|
+
from spatial_ui.resource_form import ResourceForm
|
|
211
|
+
from .app import open_server
|
|
212
|
+
threads = {thread.ident for thread in threading.enumerate()}
|
|
213
|
+
checks = 0
|
|
214
|
+
def check(value):
|
|
215
|
+
nonlocal checks
|
|
216
|
+
require(value)
|
|
217
|
+
checks += 1
|
|
218
|
+
async with open_server(database) as (ui, client):
|
|
219
|
+
status, _, page = await request(ui.server_port, "GET", "/")
|
|
220
|
+
check(status == 200 and "Work items" in page)
|
|
221
|
+
first, second = Session(ResourceForm(client)), Session(ResourceForm(client))
|
|
222
|
+
async def submit(session, **values):
|
|
223
|
+
snapshot = session.render()
|
|
224
|
+
fields = {**session.component.binding.draft, "operation": "save", **values}
|
|
225
|
+
result = await asyncio.to_thread(session.dispatch, snapshot.event_ids[0], snapshot.version,
|
|
226
|
+
{"kind": "submit", "fields": fields})
|
|
227
|
+
return result.form_result.status
|
|
228
|
+
if name == "write":
|
|
229
|
+
check(await submit(first, key="garden", title="") == "invalid")
|
|
230
|
+
check(await submit(first, key="garden", title="Garden 🌱") == "saved")
|
|
231
|
+
check(await submit(second, key="garden", operation="load") == "loaded")
|
|
232
|
+
check(await submit(first, title="Water garden") == "saved")
|
|
233
|
+
check(await submit(second, title="Local merge") == "conflict")
|
|
234
|
+
check(second.component.binding.draft["title"] == "Local merge")
|
|
235
|
+
check(await submit(second, operation="load") == "loaded")
|
|
236
|
+
check(second.component.binding.draft["title"] == "Local merge" and second.component.binding.committed["title"] == "Water garden")
|
|
237
|
+
check(await submit(second) == "saved")
|
|
238
|
+
elif name == "reload":
|
|
239
|
+
check(await submit(first, key="garden", operation="load") == "loaded")
|
|
240
|
+
check(first.component.binding.committed["title"] == "Local merge" and first.component.binding.revision == "3")
|
|
241
|
+
check(await submit(first, operation="delete") == "deleted")
|
|
242
|
+
check(await asyncio.to_thread(client.list) == ())
|
|
243
|
+
else:
|
|
244
|
+
raise ValueError("Unknown acceptance phase.")
|
|
245
|
+
# The public form client uses asyncio's default executor; its caller owns
|
|
246
|
+
# that executor until asyncio.run exits. Native UI/storage workers must close.
|
|
247
|
+
remaining = {thread.ident for thread in threading.enumerate()
|
|
248
|
+
if not thread.name.startswith("asyncio")}
|
|
249
|
+
require(remaining <= threads)
|
|
250
|
+
return {"phase": name, "checks": checks, "closed": True}
|
|
251
|
+
'''
|
|
252
|
+
|
|
253
|
+
LIVE_APP = '''"""Application-owned protected live factory; the caller supplies its ASGI host."""
|
|
254
|
+
|
|
255
|
+
from pathlib import Path
|
|
256
|
+
from compose_application.live import LiveApplication, LiveConfig
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def create_application(*, database, origin, verify, credentials):
|
|
260
|
+
"""Construct without I/O; the caller owns credentials, exact origin and lifespan."""
|
|
261
|
+
return LiveApplication(LiveConfig(database=Path(database), origin=origin,
|
|
262
|
+
verify=verify, credentials=credentials))
|
|
263
|
+
'''
|
|
264
|
+
|
|
265
|
+
LIVE_COMMAND = '''"""Check the protected live factory with disposable data and runtime-only identities."""
|
|
266
|
+
|
|
267
|
+
import argparse
|
|
268
|
+
import asyncio
|
|
269
|
+
import json
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def main():
|
|
273
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
274
|
+
parser.add_argument("command", choices=("check",))
|
|
275
|
+
parser.parse_args()
|
|
276
|
+
from .checks import accept
|
|
277
|
+
print(json.dumps(asyncio.run(accept()), sort_keys=True))
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
if __name__ == "__main__":
|
|
281
|
+
main()
|
|
282
|
+
'''
|
|
283
|
+
|
|
284
|
+
LIVE_PHASE = '''
|
|
285
|
+
|
|
286
|
+
async def request(app, method="GET", path="/work-items", *, token=None, data=None, revision=None):
|
|
287
|
+
body = b"" if data is None else json.dumps(data, allow_nan=False).encode()
|
|
288
|
+
headers = [(b"host", b"reference.example")]
|
|
289
|
+
if token is not None:
|
|
290
|
+
headers.append((b"authorization", ("Bearer " + token).encode()))
|
|
291
|
+
if data is not None:
|
|
292
|
+
headers.append((b"content-type", b"application/json"))
|
|
293
|
+
if revision is not None:
|
|
294
|
+
headers.append((b"if-match", ('"' + revision + '"').encode()))
|
|
295
|
+
incoming, outgoing = asyncio.Queue(), []
|
|
296
|
+
await incoming.put({"type": "http.request", "body": body})
|
|
297
|
+
async def send(event):
|
|
298
|
+
outgoing.append(event)
|
|
299
|
+
await asyncio.wait_for(app({"type": "http", "method": method, "path": path,
|
|
300
|
+
"root_path": "", "query_string": b"", "headers": headers}, incoming.get, send), 5)
|
|
301
|
+
return outgoing[0]["status"], dict(outgoing[0]["headers"]), b"".join(event.get("body", b"") for event in outgoing[1:])
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
async def phase(database, name):
|
|
305
|
+
import secrets
|
|
306
|
+
import threading
|
|
307
|
+
from expose_api import Principal
|
|
308
|
+
from compose_application.live import Credential
|
|
309
|
+
from .app import create_application
|
|
310
|
+
alice = Principal("check-alice", scopes=frozenset({"work-items"}))
|
|
311
|
+
bob = Principal("check-bob", scopes=frozenset({"work-items"}))
|
|
312
|
+
first, second = secrets.token_urlsafe(24), secrets.token_urlsafe(24)
|
|
313
|
+
identities = {first: alice, second: bob}
|
|
314
|
+
threads = {thread.ident for thread in threading.enumerate()}
|
|
315
|
+
app = create_application(database=database, origin="https://reference.example", verify=identities.get,
|
|
316
|
+
credentials=(Credential(alice, first), Credential(bob, second)))
|
|
317
|
+
checks = 0
|
|
318
|
+
async def check(method, path, expected, **options):
|
|
319
|
+
nonlocal checks
|
|
320
|
+
result = await request(app, method, path, **options)
|
|
321
|
+
require(result[0] == expected)
|
|
322
|
+
checks += 1
|
|
323
|
+
return result
|
|
324
|
+
async with app:
|
|
325
|
+
await check("GET", "/work-items", 401)
|
|
326
|
+
if name == "write":
|
|
327
|
+
created = await check("POST", "/work-items", 201, token=first,
|
|
328
|
+
data={"key": "garden", "title": "Garden 🌱", "owner": alice.subject})
|
|
329
|
+
require(created[1].get(b"etag") == b'"1"' and "owner" not in json.loads(created[2]))
|
|
330
|
+
await check("GET", "/work-items/garden", 404, token=second)
|
|
331
|
+
await check("PATCH", "/work-items/garden", 404, token=second, revision="9", data={"done": True})
|
|
332
|
+
await check("PATCH", "/work-items/garden", 422, token=first, revision="1", data={"done": 1})
|
|
333
|
+
incoming, outgoing = asyncio.Queue(), asyncio.Queue()
|
|
334
|
+
scope = {"type": "websocket", "path": "/work-items/garden", "root_path": "", "query_string": b"",
|
|
335
|
+
"subprotocols": ["expose-api.events.v1"], "scheme": "wss", "headers": [
|
|
336
|
+
(b"host", b"reference.example"), (b"origin", b"https://reference.example"),
|
|
337
|
+
(b"cookie", ("work_identity=" + first).encode())]}
|
|
338
|
+
socket = asyncio.create_task(app(scope, incoming.get, outgoing.put))
|
|
339
|
+
try:
|
|
340
|
+
await incoming.put({"type": "websocket.connect"})
|
|
341
|
+
require((await asyncio.wait_for(outgoing.get(), 2))["type"] == "websocket.accept")
|
|
342
|
+
await incoming.put({"type": "websocket.receive", "text": '{"v":1,"type":"subscribe","cursor":null}'})
|
|
343
|
+
snapshot = json.loads((await asyncio.wait_for(outgoing.get(), 2))["text"])
|
|
344
|
+
require(snapshot["value"] == {"key": "garden", "title": "Garden 🌱", "done": False})
|
|
345
|
+
checks += 1
|
|
346
|
+
updated = await check("PATCH", "/work-items/garden", 200, token=first, revision="1", data={"done": True})
|
|
347
|
+
require(updated[1].get(b"etag") == b'"2"')
|
|
348
|
+
snapshot = json.loads((await asyncio.wait_for(outgoing.get(), 2))["text"])
|
|
349
|
+
require(snapshot["value"]["done"] is True and "owner" not in snapshot["value"])
|
|
350
|
+
checks += 1
|
|
351
|
+
finally:
|
|
352
|
+
await incoming.put({"type": "websocket.disconnect", "code": 1000})
|
|
353
|
+
try:
|
|
354
|
+
await asyncio.wait_for(socket, 5)
|
|
355
|
+
finally:
|
|
356
|
+
if not socket.done():
|
|
357
|
+
socket.cancel()
|
|
358
|
+
await asyncio.gather(socket, return_exceptions=True)
|
|
359
|
+
await check("PATCH", "/work-items/garden", 409, token=first, revision="1", data={"title": "Stale"})
|
|
360
|
+
identities.pop(first)
|
|
361
|
+
await check("GET", "/work-items/garden", 401, token=first)
|
|
362
|
+
elif name == "reload":
|
|
363
|
+
result = await check("GET", "/work-items/garden", 200, token=first)
|
|
364
|
+
require(result[1].get(b"etag") == b'"2"' and json.loads(result[2])["done"] is True)
|
|
365
|
+
await check("DELETE", "/work-items/garden", 404, token=second, revision="9")
|
|
366
|
+
await check("DELETE", "/work-items/garden", 409, token=first, revision="1")
|
|
367
|
+
await check("DELETE", "/work-items/garden", 204, token=first, revision="2")
|
|
368
|
+
else:
|
|
369
|
+
raise ValueError("Unknown acceptance phase.")
|
|
370
|
+
await app.aclose()
|
|
371
|
+
require({thread.ident for thread in threading.enumerate()} == threads)
|
|
372
|
+
return {"phase": name, "checks": checks, "closed": True}
|
|
373
|
+
'''
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Explicit selections for application-owned reference projects."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import keyword
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
from tempfile import TemporaryDirectory
|
|
12
|
+
|
|
13
|
+
from .terminal_templates import TerminalProjectSpec, render_terminal_project
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
REFERENCE_VERSION = "0.1.0a1"
|
|
17
|
+
REFERENCE_SOURCE = "pypi:compose-application==" + REFERENCE_VERSION
|
|
18
|
+
PROFILES = ("service", "ui", "live")
|
|
19
|
+
_RESERVED = set(sys.stdlib_module_names) | {
|
|
20
|
+
"compose_application", "expose_api", "backpack_store", "enforce_type", "spatial_ui",
|
|
21
|
+
"con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)),
|
|
22
|
+
*(f"lpt{i}" for i in range(1, 10)),
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class ProjectSpec:
|
|
28
|
+
"""A finite reference selection, with no imports, I/O or implicit profile."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
profile: str
|
|
32
|
+
source: str = REFERENCE_SOURCE
|
|
33
|
+
|
|
34
|
+
def __post_init__(self):
|
|
35
|
+
if type(self.name) is not str or not 1 <= len(self.name) <= 48 or not re.fullmatch(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*", self.name):
|
|
36
|
+
raise ValueError("Choose a lowercase project name of 1–48 letters, digits and single hyphens.")
|
|
37
|
+
if keyword.iskeyword(self.module) or self.module in _RESERVED:
|
|
38
|
+
raise ValueError("Choose a project name that does not shadow a platform or Python module.")
|
|
39
|
+
if type(self.profile) is not str or self.profile not in PROFILES:
|
|
40
|
+
raise ValueError("Select service, ui or live explicitly.")
|
|
41
|
+
if type(self.source) is not str or self.source != REFERENCE_SOURCE:
|
|
42
|
+
raise ValueError("Select the qualified released reference version.")
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def module(self):
|
|
46
|
+
return self.name.replace("-", "_")
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def dependency(self):
|
|
50
|
+
return f"compose-application[{self.profile}]=={REFERENCE_VERSION}"
|
|
51
|
+
|
|
52
|
+
def selection(self):
|
|
53
|
+
"""Return detached, non-secret generation metadata, independent of data schema."""
|
|
54
|
+
return {"format": "reference-project/1", "name": self.name,
|
|
55
|
+
"profile": self.profile, "source": self.source}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def render_project(spec: ProjectSpec):
|
|
59
|
+
"""Return detached UTF-8 source files without writing or installing anything."""
|
|
60
|
+
if type(spec) is TerminalProjectSpec:
|
|
61
|
+
return render_terminal_project(spec)
|
|
62
|
+
if type(spec) is not ProjectSpec:
|
|
63
|
+
raise TypeError("render_project() requires ProjectSpec.")
|
|
64
|
+
from .project_templates import (CHECK_RUNNER, COMMAND, HTTP_CHECKS, SERVICE_APP, SERVICE_PHASE,
|
|
65
|
+
UI_APP, UI_PHASE, LIVE_APP, LIVE_COMMAND, LIVE_PHASE)
|
|
66
|
+
app_source, phase_source, helpers, command = {
|
|
67
|
+
"service": (SERVICE_APP, SERVICE_PHASE, HTTP_CHECKS, COMMAND),
|
|
68
|
+
"ui": (UI_APP, UI_PHASE, HTTP_CHECKS, COMMAND),
|
|
69
|
+
"live": (LIVE_APP, LIVE_PHASE, "", LIVE_COMMAND),
|
|
70
|
+
}[spec.profile]
|
|
71
|
+
metadata = f'''[project]
|
|
72
|
+
name = "{spec.name}"
|
|
73
|
+
version = "0.1.0"
|
|
74
|
+
requires-python = ">=3.14"
|
|
75
|
+
dependencies = ["{spec.dependency}"]
|
|
76
|
+
|
|
77
|
+
[project.scripts]
|
|
78
|
+
{spec.name} = "{spec.module}.__main__:main"
|
|
79
|
+
|
|
80
|
+
[build-system]
|
|
81
|
+
requires = ["uv_build>=0.12.19,<0.13.0"]
|
|
82
|
+
build-backend = "uv_build"
|
|
83
|
+
'''
|
|
84
|
+
readme = f'''# {spec.name}
|
|
85
|
+
|
|
86
|
+
Application-owned `{spec.profile}` reference project for synthetic work items.
|
|
87
|
+
Composition source: `{spec.source}`. Python 3.14+ and uv are required.
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
uv sync
|
|
91
|
+
uv run {spec.name} check
|
|
92
|
+
uv run {spec.name} serve --database ./work-items.sqlite3
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The check uses a dedicated temporary database in two independent processes.
|
|
96
|
+
Serving uses a loopback development listener with public synthetic data and
|
|
97
|
+
checked REST revisions. Choose a private persistent local SQLite path explicitly.
|
|
98
|
+
Application assembly and checks live in `src/{spec.module}/`; these files and
|
|
99
|
+
the database belong to you. The selected reference owns its fixed work-item
|
|
100
|
+
schema. Domain/schema changes require their own implementation and migration.
|
|
101
|
+
Dependencies select the qualified package-index preview version.
|
|
102
|
+
Generation installs nothing and repeating the same request never updates files.
|
|
103
|
+
Publication and public hosting require separate setup.
|
|
104
|
+
'''
|
|
105
|
+
if spec.profile == "ui":
|
|
106
|
+
readme += "\nThe UI opens at the printed loopback address. Browser drafts are independent;\nSave uses checked revisions. Load refreshes the baseline while retaining edits\nfor an explicit merge; Discard replaces the draft with that baseline. Shutdown\nstops the UI listener/worker before closing REST and storage.\n"
|
|
107
|
+
if spec.profile == "live":
|
|
108
|
+
readme = f'''# {spec.name}
|
|
109
|
+
|
|
110
|
+
Application-owned protected `live` reference. Python 3.14+ and uv are required.
|
|
111
|
+
Composition source: `{spec.source}`. Install and check with:
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
uv sync
|
|
115
|
+
uv run {spec.name} check
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`src/{spec.module}/app.py` exposes `create_application` with required keyword
|
|
119
|
+
arguments: `database`, `origin`, `verify`, `credentials`. Supply a private local
|
|
120
|
+
SQLite path, an exact HTTPS origin (HTTP only on loopback), a bounded synchronous
|
|
121
|
+
current-credential verifier and 1–8 explicit `Credential(Principal(...), token)`
|
|
122
|
+
bindings. Principals need globally unique subjects and the `work-items` scope.
|
|
123
|
+
Import `Credential` from `compose_application.live` and `Principal` from
|
|
124
|
+
`expose_api`. The verifier returns the currently valid Principal or None.
|
|
125
|
+
|
|
126
|
+
Pass the returned application to your selected HTTP/WebSocket ASGI host with
|
|
127
|
+
lifespan enabled. Construction opens no database, listener or worker. The host
|
|
128
|
+
must preserve the exact Host, bound admission/headers/send deadlines and drain
|
|
129
|
+
listeners before shutdown. One process owns the native UI sessions. No login,
|
|
130
|
+
credential issuance, default credentials, external identity provider or host
|
|
131
|
+
package is installed by this project. Provision the `work_identity` cookie with
|
|
132
|
+
HttpOnly, SameSite=Strict, Path=/ and Secure for HTTPS. Never put tokens in
|
|
133
|
+
source, URLs, receipts or logs. Stop/reload after identity changes; token-binding
|
|
134
|
+
changes require a drained restart. Each callback/subscription checks current
|
|
135
|
+
access; owner fields stay hidden and denial precedes revision comparison.
|
|
136
|
+
|
|
137
|
+
The check creates runtime-only disposable identities, uses a temporary database
|
|
138
|
+
across independent processes and tests protected checked REST, native WebSocket
|
|
139
|
+
snapshots, revocation, durable reopen and cleanup. It does not start a listener
|
|
140
|
+
or use your credentials/data. The accepted reference owns its separate fixed
|
|
141
|
+
live table/journal. Every writer must use the same event-enabled profile;
|
|
142
|
+
stop writers and verify backups before upgrades or restoring compatible data.
|
|
143
|
+
Application source and data belong to you; repeated generation leaves them
|
|
144
|
+
untouched. Dependencies select the qualified package-index preview. Publication and public
|
|
145
|
+
hosting remain separate from project generation and native acceptance.
|
|
146
|
+
'''
|
|
147
|
+
checks = (CHECK_RUNNER + helpers + phase_source).replace("__PROJECT_MODULE__", spec.module).replace("__PROJECT_PROFILE__", spec.profile)
|
|
148
|
+
return {"pyproject.toml": metadata, "README.md": readme,
|
|
149
|
+
".gitignore": ".venv/\n__pycache__/\n*.py[cod]\n*.sqlite3*\n.env\n",
|
|
150
|
+
"reference-project.json": json.dumps(spec.selection(), indent=2, sort_keys=True) + "\n",
|
|
151
|
+
f"src/{spec.module}/__init__.py": '"""Application-owned reference project."""\n',
|
|
152
|
+
f"src/{spec.module}/app.py": app_source,
|
|
153
|
+
f"src/{spec.module}/__main__.py": command,
|
|
154
|
+
f"src/{spec.module}/checks.py": checks}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _existing_selection(destination, spec):
|
|
158
|
+
if destination.is_symlink():
|
|
159
|
+
raise FileExistsError("Project destination must not be a symbolic link.")
|
|
160
|
+
if not destination.exists():
|
|
161
|
+
return False
|
|
162
|
+
receipt = destination / "reference-project.json"
|
|
163
|
+
try:
|
|
164
|
+
if not destination.is_dir() or receipt.is_symlink() or not receipt.is_file() or receipt.stat().st_size > 4096:
|
|
165
|
+
raise ValueError
|
|
166
|
+
selected = json.loads(receipt.read_text(encoding="utf-8"))
|
|
167
|
+
if selected != spec.selection():
|
|
168
|
+
raise ValueError
|
|
169
|
+
except (OSError, ValueError):
|
|
170
|
+
raise FileExistsError("Destination exists without a matching project selection; no files were changed.") from None
|
|
171
|
+
return True
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def create_project(spec: ProjectSpec, destination):
|
|
175
|
+
"""Stage a new project and exclusively create its files; return True if created.
|
|
176
|
+
|
|
177
|
+
Matching repeat requests return False without examining or changing owned
|
|
178
|
+
source/data. The parent must exist. An incomplete project has no receipt.
|
|
179
|
+
"""
|
|
180
|
+
files = render_project(spec)
|
|
181
|
+
destination = Path(destination).absolute()
|
|
182
|
+
if _existing_selection(destination, spec):
|
|
183
|
+
return False
|
|
184
|
+
# All template paths are internal, relative and validated before any write.
|
|
185
|
+
for name in files:
|
|
186
|
+
path = Path(name)
|
|
187
|
+
if path.is_absolute() or ".." in path.parts:
|
|
188
|
+
raise ValueError("Project template contains an invalid path.")
|
|
189
|
+
with TemporaryDirectory(prefix=".reference-project-", dir=destination.parent) as directory:
|
|
190
|
+
stage = Path(directory)
|
|
191
|
+
for name, content in files.items():
|
|
192
|
+
path = stage / name
|
|
193
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
path.write_text(content, encoding="utf-8", newline="\n")
|
|
195
|
+
try:
|
|
196
|
+
destination.mkdir()
|
|
197
|
+
except FileExistsError:
|
|
198
|
+
if _existing_selection(destination, spec):
|
|
199
|
+
return False
|
|
200
|
+
raise
|
|
201
|
+
created, directories = [], []
|
|
202
|
+
try:
|
|
203
|
+
# Publish the receipt last, after all application files exist.
|
|
204
|
+
names = [name for name in files if name != "reference-project.json"] + ["reference-project.json"]
|
|
205
|
+
for name in names:
|
|
206
|
+
path = destination / name
|
|
207
|
+
for parent in reversed(path.relative_to(destination).parents):
|
|
208
|
+
if parent == Path("."):
|
|
209
|
+
continue
|
|
210
|
+
target = destination / parent
|
|
211
|
+
if target not in directories:
|
|
212
|
+
target.mkdir()
|
|
213
|
+
directories.append(target)
|
|
214
|
+
# Same-filesystem hard links publish complete files exclusively
|
|
215
|
+
# without a partial-write window or overwriting a raced file.
|
|
216
|
+
os.link(stage / name, path)
|
|
217
|
+
created.append(path)
|
|
218
|
+
except BaseException:
|
|
219
|
+
# Remove only our own unchanged files. Concurrent owner additions
|
|
220
|
+
# and edits survive; nonempty directories are never removed.
|
|
221
|
+
for path in reversed(created):
|
|
222
|
+
try:
|
|
223
|
+
expected = files[path.relative_to(destination).as_posix()]
|
|
224
|
+
if not path.is_symlink() and path.read_text(encoding="utf-8") == expected:
|
|
225
|
+
path.unlink()
|
|
226
|
+
except OSError:
|
|
227
|
+
pass
|
|
228
|
+
for path in [*reversed(directories), destination]:
|
|
229
|
+
try:
|
|
230
|
+
path.rmdir()
|
|
231
|
+
except OSError:
|
|
232
|
+
pass
|
|
233
|
+
raise
|
|
234
|
+
return True
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def main():
|
|
238
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
239
|
+
parser.add_argument("destination", type=Path)
|
|
240
|
+
parser.add_argument("--name", required=True)
|
|
241
|
+
parser.add_argument("--profile", choices=(*PROFILES, "terminal"), required=True)
|
|
242
|
+
arguments = parser.parse_args()
|
|
243
|
+
try:
|
|
244
|
+
spec = (TerminalProjectSpec(arguments.name) if arguments.profile == "terminal"
|
|
245
|
+
else ProjectSpec(arguments.name, arguments.profile))
|
|
246
|
+
created = create_project(spec, arguments.destination)
|
|
247
|
+
except (OSError, ValueError) as error:
|
|
248
|
+
parser.exit(2, f"Project creation refused: {error}\n")
|
|
249
|
+
print(json.dumps({"created": created, "selection": spec.selection()}, sort_keys=True))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
if __name__ == "__main__":
|
|
253
|
+
main()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|