Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/differential_driver.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
differential_driver.py · 35.1 KB · 629 lines
1#!/usr/bin/env python3
2"""Drive one scripted session through the real ASGI app and record every response.
3
4Not a test: tests/test_platform_differential.py runs this twice, once against
5the platform modules of a baseline commit and once against the working tree,
6and compares the two recordings. It only uses surfaces both trees have: the
7HTTP API, `object_packages.install_package`, the identity file writers, and
8plain file writes into the data and objects directories.
9
10The session is built to catch a cache that goes stale. Every change to what is
11on disk (a schema, the policy, an object file, a records file, a package) is
12made the instant after the requests that would have warmed a cache, with no
13sleep, both through the API and by writing the file directly as an operator or
14another process would, and the same probe requests are then repeated. The
15baseline tree re-reads everything on every request, so it is the oracle.
16
17usage: differential_driver.py --tree DIR --packages DIR --work DIR --out FILE
18"""
19from __future__ import annotations
20
21import argparse
22import asyncio
23import hashlib
24import json
25import os
26import shutil
27import sys
28from datetime import datetime, timedelta, timezone
29from pathlib import Path
30
31USERS = 6
32ADMIN = "admin-t"
33CORE = ["app-views", "app-projects", "app-notes", "app-orders", "app-invoices", "app-payments",
34 "app-contacts", "app-tasks", "app-timers", "app-catalog", "app-shipping"]
35LATE_PACKAGE = "hello-world"
36
37
38_URANDOM = {"key": b"", "n": 0}
39
40
41def deterministic_urandom() -> None:
42 """Generated ids and tokens come out the same in both runs.
43
44 Each request draws from its own stream (reseed_urandom, keyed by the
45 request's label and how many times that label was issued before), so a
46 request that one tree answers differently -- drawing more or fewer bytes,
47 or making the driver issue a follow-up request the other run does not --
48 cannot shift the ids and correlation ids of every request after it. An
49 intended difference then shows up where it is, not everywhere."""
50 import random
51
52 state = _URANDOM
53
54 def urandom(size: int) -> bytes:
55 out = b""
56 while len(out) < size:
57 state["n"] += 1
58 out += hashlib.sha256(b"differential-%s%d" % (state["key"], state["n"])).digest()
59 return out[:size]
60
61 os.urandom = urandom
62 random._urandom = urandom
63
64
65def reseed_urandom(key: str) -> None:
66 _URANDOM["key"] = hashlib.sha256(key.encode()).hexdigest().encode() + b"-"
67 _URANDOM["n"] = 0
68
69
70def configure_env(work: Path, packages: Path) -> None:
71 os.environ.update(
72 DBBASIC_DATA_DIR=str(work / "data"),
73 DBBASIC_OBJECTS_DIR=str(work / "objects"),
74 DBBASIC_PACKAGES_DIR=str(packages),
75 DBBASIC_ADMIN_TOKEN=ADMIN,
76 DBBASIC_ENABLE_PERMISSION_ENFORCEMENT="true",
77 DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT="true",
78 DBBASIC_ENABLE_PERMISSION_AUDIT="true",
79 DBBASIC_MAX_CONCURRENT_REQUESTS="0",
80 DBBASIC_MAX_CONCURRENT_EXECUTIONS="0",
81 DBBASIC_ENABLE_SITE_ROUTES="true",
82 DBBASIC_ENABLE_EVENT_HANDLERS="true",
83 DBBASIC_ENABLE_RECORD_EVENTS="true",
84 DBBASIC_ENABLE_REALTIME="true",
85 DBBASIC_ENABLE_SOURCE_WRITES="true",
86 DBBASIC_ENABLE_PACKAGE_INSTALLS="true",
87 DBBASIC_COOKIE_SECURE="false",
88 )
89 for name in ("DBBASIC_RATE_LIMIT_REQUESTS", "DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_OVERRIDES_DIR",
90 "DBBASIC_PRIVATE_PACKAGES_DIR"):
91 os.environ.pop(name, None)
92
93
94def package_order(root: Path, which: str) -> list[str]:
95 deps: dict[str, list] = {}
96 for manifest in sorted(root.glob("*/dbbasic-package.json")):
97 payload = json.loads(manifest.read_text())
98 deps[payload["id"]] = list(payload.get("dependencies") or [])
99 want = CORE if which == "core" else [p for p in deps if p not in ("admin-write-probe", LATE_PACKAGE)]
100 order: list[str] = []
101 seen: set[str] = set()
102
103 def visit(name) -> None:
104 name = name["id"] if isinstance(name, dict) else name
105 if name in seen or name not in deps:
106 return
107 seen.add(name)
108 for dep in deps[name]:
109 visit(dep)
110 order.append(name)
111
112 for name in want:
113 visit(name)
114 return order
115
116
117def append_rows(work: Path, collection: str, rows: list[dict]) -> None:
118 path = work / "data" / "collections" / collection / "records.tsv"
119 if not path.exists():
120 return
121 header = path.read_text().split("\n", 1)[0].split("\t")
122 with open(path, "a") as handle:
123 for row in rows:
124 handle.write("\t".join(str(row.get(name, "")) for name in header) + "\n")
125
126
127def seed(work: Path, packages: Path, which: str) -> list[str]:
128 import object_identity as oi
129 import object_packages
130
131 (work / "objects").mkdir(parents=True, exist_ok=True)
132 for name in package_order(packages, which):
133 object_packages.install_package(name, root=packages, base_dir=work / "data",
134 object_roots=[work / "objects"])
135
136 now = datetime.now(timezone.utc).replace(microsecond=0)
137 stamp = oi._format_timestamp(now)
138 expires = oi._format_timestamp(now + timedelta(days=30))
139 users, sessions, tokens = [], [], []
140 for i in range(USERS):
141 uid = f"u{i}"
142 users.append(oi.IdentityUser(user_id=uid, account_id=None, email=f"{uid}@example.test",
143 display_name=f"User {i}", status="active", roles=(), subscriptions=(),
144 created_at=stamp, updated_at=stamp))
145 token = f"tok-{i}"
146 sessions.append(oi.IdentitySession(session_id=oi._new_session_id(), token_hash=oi.hash_token(token),
147 user_id=uid, account_id=None, roles=(), subscriptions=(), label="",
148 created_at=stamp, expires_at=expires))
149 tokens.append(token)
150 oi._write_users(oi.users_path(work / "data"), users)
151 oi._write_sessions(oi.sessions_path(work / "data"), sessions)
152
153 rng = range(USERS)
154 append_rows(work, "projects", [dict(id=f"p{i}_{p}", name=f"Project {i}.{p}", description="seed", status="active",
155 owner_id=f"u{i}") for i in rng for p in range(2)])
156 append_rows(work, "project_access", [dict(id=f"a{i}_{g}", project_id=f"p{(i + 1 + g) % USERS}_0", user_id=f"u{i}",
157 permission="read", granted_by=f"u{(i + 1 + g) % USERS}")
158 for i in rng for g in range(2)])
159 append_rows(work, "notes", [dict(id=f"n{i}_{n}", content=f"note {n} of user {i}, some realistic length text",
160 project_id=f"p{i}_0", is_public="true" if (i == 0 and n < 3) else "false",
161 owner_id=f"u{i}") for i in rng for n in range(10)])
162 append_rows(work, "orders", [dict(id=f"o{i}_{o}", doc_type="sale", number=f"SO-{i}-{o}", customer_name=f"Customer {i}",
163 currency="USD", status="draft", subtotal_cents="3000", tax_cents="0",
164 total_cents="3000", fulfillment_source="stock", fulfillment_method="shipping",
165 owner_id=f"u{i}", created_at="2026-01-01T00:00:00") for i in rng for o in range(2)])
166 append_rows(work, "order_lines", [dict(id=f"ol{i}_{o}_{n}", order_id=f"o{i}_{o}", description=f"line {n}", quantity="1",
167 unit_price_cents="1000", line_total_cents="1000", line_tax_cents="0",
168 owner_id=f"u{i}", created_at="2026-01-01T00:00:00")
169 for i in rng for o in range(2) for n in range(3)])
170 append_rows(work, "invoices", [dict(id=f"inv{i}", doc_type="invoice", number=f"INV-{i}", customer_name=f"Customer {i}",
171 currency="USD", status="draft", subtotal_cents="2000", tax_cents="0",
172 total_cents="2000", owner_id=f"u{i}", created_at="2026-01-01T00:00:00") for i in rng])
173 append_rows(work, "invoice_lines", [dict(id=f"il{i}_{n}", invoice_id=f"inv{i}", description=f"iline {n}", quantity="1",
174 unit_price_cents="1000", line_total_cents="1000", line_tax_cents="0",
175 owner_id=f"u{i}", created_at="2026-01-01T00:00:00")
176 for i in rng for n in range(2)])
177 append_rows(work, "contacts", [dict(id=f"c{i}_{c}", first_name=f"First{c}", last_name=f"Last{i}",
178 full_name=f"First{c} Last{i}", email=f"c{i}_{c}@example.test", project_id=f"p{i}_0",
179 lead_status="warm", owner_id=f"u{i}", created_at="2026-01-01T00:00:00")
180 for i in rng for c in range(3)])
181 append_rows(work, "tasks", [dict(id=f"t{i}_{t}", title=f"Task {t} of user {i}", description="seed", task_type="STANDARD",
182 project_id=f"p{i}_0", status="open", urgency="normal", assigned_to=f"u{i}",
183 owner_id=f"u{i}", created_at="2026-01-01T00:00:00") for i in rng for t in range(3)])
184 return tokens
185
186
187class Session:
188 def __init__(self, tokens: list[str]):
189 import object_server
190
191 self.app = object_server.app
192 self.tokens = tokens
193 self.loop = asyncio.new_event_loop()
194 asyncio.set_event_loop(self.loop)
195 self.log: list[list] = []
196 self.issued: dict[str, int] = {}
197
198 def call(self, label: str, method: str, path: str, *, query: str = "", body=None, user: int | None = 0,
199 token: str | None = None, accept: str = "application/json", host: str = "bench.test",
200 headers: list | None = None):
201 hdrs = [(b"accept", accept.encode()), (b"host", host.encode())]
202 if token is None and user is not None:
203 token = self.tokens[user % len(self.tokens)]
204 if token:
205 hdrs.append((b"authorization", f"Bearer {token}".encode()))
206 raw = b""
207 if body is not None:
208 raw = body if isinstance(body, bytes) else json.dumps(body).encode()
209 hdrs.append((b"content-type", b"application/json"))
210 hdrs += headers or []
211 scope = {"type": "http", "method": method, "path": path, "query_string": query.encode(), "headers": hdrs,
212 "client": ("127.0.0.1", 1), "scheme": "http", "http_version": "1.1"}
213 sent: list[dict] = []
214 state = {"done": False}
215
216 async def receive():
217 if state["done"]:
218 return {"type": "http.disconnect"}
219 state["done"] = True
220 return {"type": "http.request", "body": raw, "more_body": False}
221
222 async def send(message):
223 sent.append(message)
224
225 full_label = f"{label} :: {method} {path}{'?' + query if query else ''}"
226 self.issued[full_label] = self.issued.get(full_label, 0) + 1
227 reseed_urandom(f"{full_label}#{self.issued[full_label]}")
228 try:
229 self.loop.run_until_complete(self.app(scope, receive, send))
230 except Exception as exc: # noqa: BLE001 -- an escaped exception is an outcome to compare, too
231 self.log.append([full_label, -1, [], f"{type(exc).__name__}: {exc}"])
232 return -1, {}, b""
233 status = sent[0]["status"]
234 out_headers = sorted((k.decode("latin-1").lower(), v.decode("latin-1")) for k, v in sent[0].get("headers", []))
235 data = b"".join(m.get("body", b"") for m in sent[1:])
236 self.log.append([full_label, status, out_headers, data.decode("latin-1")])
237 return status, dict(out_headers), data
238
239 def admin(self, label: str, method: str, path: str, **kw):
240 return self.call(label, method, path, user=None, token=ADMIN, **kw)
241
242
243def discard_refused_probe(content: str) -> None:
244 """A probe note whose create was answered as refused must not be there.
245 Trees before the fix for "a write lands but is reported refused when an
246 unrelated schema file does not parse" (bug report 2026-11-29 11:07) wrote
247 it anyway at m06, and the driver, seeing no 201, never deleted it: one
248 step's intended difference became a different notes list in every step
249 after it. Removed through storage, not over HTTP, so neither recording
250 gains a request; when nothing landed (every refusal on a fixed tree)
251 there is nothing to remove."""
252 import object_records
253
254 data = Path(os.environ["DBBASIC_DATA_DIR"])
255 for row in object_records.read_collection_records("notes", base_dir=data):
256 if row.get("content") == content:
257 try:
258 object_records.delete_collection_record("notes", row["id"], base_dir=data,
259 actor="differential")
260 except Exception: # noqa: BLE001 -- that bug raises again after this delete lands
261 pass
262
263
264def probes(s: Session, tag: str) -> None:
265 """The requests whose answers depend on schemas, the policy, object files and records files."""
266 c = lambda name, *a, **k: s.call(f"{tag}/{name}", *a, **k) # noqa: E731
267 c("list", "GET", "/collections/notes/records", query="limit=20", user=1)
268 c("get", "GET", "/collections/notes/records/n1_3", user=1)
269 c("get-foreign", "GET", "/collections/notes/records/n2_3", user=1)
270 c("anon-rows", "GET", "/collections/notes/records", query="limit=20", user=None)
271 status, _, data = c("create", "POST", "/collections/notes/records",
272 body={"content": f"probe {tag}", "project_id": "p1_0", "owner_id": "u1"}, user=1)
273 if status == 201:
274 rid = json.loads(data)["record"]["id"]
275 c("update", "PUT", f"/collections/notes/records/{rid}", body={"content": f"probe {tag} edited"}, user=1)
276 c("delete", "DELETE", f"/collections/notes/records/{rid}", user=1)
277 else:
278 discard_refused_probe(f"probe {tag}")
279 c("orderline-create", "POST", "/collections/order_lines/records",
280 body={"order_id": "o1_0", "owner_id": "u1", "description": tag, "quantity": 2, "unit_price_cents": 500}, user=1)
281 c("order-after", "GET", "/collections/orders/records/o1_0", user=1)
282 c("page", "GET", "/notes", user=1, accept="text/html")
283 c("page-anon", "GET", "/notes", user=None, accept="text/html")
284 c("asset-style", "GET", "/style", user=1, accept="*/*")
285 c("asset-list", "GET", "/list", user=None, accept="*/*")
286 c("search", "GET", "/api/search", query="q=note", user=1)
287 c("schema-meta-notes", "GET", "/api/schema/notes", user=1)
288 for name in ("site_hosts", "site_routes", "site", "action", "brandnew", "ghost_coll", "loose_coll",
289 "scratch_things", "record_shares", "nope_nothing"):
290 c(f"schema-meta-{name}", "GET", f"/api/schema/{name}", user=1)
291 s.admin(f"{tag}/schema-admin-{name}", "GET", f"/schemas/{name}")
292 c("rows-ghost", "GET", "/collections/ghost_coll/records", user=1)
293 c("rows-loose", "GET", "/collections/loose_coll/records", user=1)
294 s.admin(f"{tag}/rows-loose-admin", "GET", "/collections/loose_coll/records")
295 c("rows-scratch", "GET", "/collections/scratch_things/records", user=1)
296 s.admin(f"{tag}/schemas", "GET", "/schemas")
297 s.admin(f"{tag}/collections", "GET", "/collections")
298 s.admin(f"{tag}/collection-notes", "GET", "/collections/notes")
299 s.admin(f"{tag}/collection-site", "GET", "/collections/site")
300 s.admin(f"{tag}/objects", "GET", "/objects")
301 s.admin(f"{tag}/policy", "GET", "/permissions/policy")
302 s.admin(f"{tag}/permissions-status", "GET", "/permissions/status")
303 c("identity", "GET", "/identity", user=1)
304 c("nav", "GET", "/objects/action_nav_entries", user=1)
305 c("views", "GET", "/collections/views/records", query="limit=200", user=1)
306 for path in ("/hello_diff", "/api_made", "/hello", "/no-such-page", "/orders/o1_0"):
307 c(f"site{path}", "GET", path, user=1, accept="text/html")
308 c(f"site-anon{path}", "GET", path, user=None, accept="text/html")
309 c("site-other-host", "GET", "/", user=None, accept="text/html", host="other.test")
310 c("object-hello-diff", "GET", "/objects/site_hello_diff", user=1)
311 c("object-brandnew", "GET", "/objects/brandnew_thing", user=None)
312 c("object-hello-world", "GET", "/objects/hello_world", user=1)
313 s.admin(f"{tag}/object-hello-world-admin", "GET", "/objects/hello_world")
314 s.admin(f"{tag}/permissions-audit", "GET", "/permissions/audit", query="limit=5")
315 s.admin(f"{tag}/permissions-audit-denied", "GET", "/permissions/audit", query="limit=3&allowed=false")
316
317
318def base_requests(s: Session) -> None:
319 """What the request profiler issues, for several users, plus error paths."""
320 c = s.call
321 c("health", "GET", "/health", user=None)
322 for u in (0, 3):
323 c(f"u{u} list", "GET", "/collections/notes/records", query="limit=20", user=u)
324 c(f"u{u} list-500", "GET", "/collections/notes/records", query="limit=500", user=u)
325 c(f"u{u} projects", "GET", "/collections/projects/records", query="limit=500", user=u)
326 c(f"u{u} get", "GET", f"/collections/notes/records/n{u}_4", user=u)
327 c(f"u{u} view-record", "GET", "/collections/views/records/view_notes", user=u)
328 c(f"u{u} views", "GET", "/collections/views/records", query="limit=200", user=u)
329 c(f"u{u} entities", "GET", "/collections/entities/records", query="limit=200", user=u)
330 c(f"u{u} notifications", "GET", "/collections/notifications/records", query="limit=50", user=u)
331 c(f"u{u} prefs", "GET", "/prefs", user=u)
332 c(f"u{u} nav", "GET", "/objects/action_nav_entries", user=u)
333 c(f"u{u} page", "GET", "/notes", user=u, accept="text/html")
334 c(f"u{u} search", "GET", "/api/search", query="q=note", user=u)
335 for asset in ("style", "markdown", "list", "form", "detail", "thread", "attachments", "share", "nav"):
336 c(f"u{u} asset", "GET", f"/{asset}", user=u, accept="*/*")
337 c("anon rows", "GET", "/collections/notes/records", query="limit=20", user=None)
338 c("anon page", "GET", "/notes", user=None, accept="text/html")
339 c("schema meta", "GET", "/api/schema/notes", user=2)
340
341 lifecycles = [
342 ("notes", lambda u: {"content": "bench note", "project_id": f"p{u}_0", "owner_id": f"u{u}"},
343 {"content": "bench note edited"}),
344 ("order_lines", lambda u: {"order_id": f"o{u}_1", "owner_id": f"u{u}", "description": "bench", "quantity": 2,
345 "unit_price_cents": 500}, {"quantity": 3}),
346 ("payments", lambda u: {"invoice_id": f"inv{u}", "owner_id": f"u{u}", "amount_cents": 1,
347 "received_on": "2026-01-02", "method": "cash"}, {"amount_cents": 2}),
348 ("contacts", lambda u: {"first_name": "Ann", "last_name": "Bench", "owner_id": f"u{u}"},
349 {"last_name": "Edited"}),
350 ]
351 for coll, make, change in lifecycles:
352 for u in (2, 4):
353 status, _, data = c(f"u{u} create", "POST", f"/collections/{coll}/records", body=make(u), user=u)
354 if status != 201:
355 continue
356 rid = json.loads(data)["record"]["id"]
357 c(f"u{u} get-created", "GET", f"/collections/{coll}/records/{rid}", user=u)
358 c(f"u{u} update", "PUT", f"/collections/{coll}/records/{rid}", body=change, user=u)
359 c("other user update", "PUT", f"/collections/{coll}/records/{rid}", body=change, user=u + 1)
360 c("anon delete", "DELETE", f"/collections/{coll}/records/{rid}", user=None)
361 c(f"u{u} changes", "GET", f"/collections/{coll}/records/{rid}/changes", user=u)
362 c(f"u{u} delete", "DELETE", f"/collections/{coll}/records/{rid}", user=u)
363 c(f"u{u} get-deleted", "GET", f"/collections/{coll}/records/{rid}", user=u)
364 c("order after lines", "GET", "/collections/orders/records/o2_1", user=2)
365 c("invoice after payments", "GET", "/collections/invoices/records/inv2", user=2)
366
367 # error paths
368 c("err unknown collection", "GET", "/collections/no_such_thing/records", user=1)
369 c("err unknown collection write", "POST", "/collections/no_such_thing/records", body={"a": 1}, user=1)
370 c("err bad collection name", "GET", "/collections/bad!name/records", user=1)
371 c("err bad record id", "GET", "/collections/notes/records/..%2Fx", user=1)
372 c("err missing record", "GET", "/collections/notes/records/zzz", user=1)
373 c("err foreign record", "GET", "/collections/notes/records/n5_1", user=1)
374 c("err foreign update", "PUT", "/collections/notes/records/n5_1", body={"content": "x"}, user=1)
375 c("err foreign delete", "DELETE", "/collections/notes/records/n5_1", user=1)
376 c("err bad json", "POST", "/collections/notes/records", body=b"{not json", user=1)
377 c("err no owner", "POST", "/collections/notes/records", body={"content": "no owner"}, user=1)
378 c("err unknown field", "POST", "/collections/notes/records", body={"content": "x", "owner_id": "u1", "zz": 1}, user=1)
379 c("err negative payment", "POST", "/collections/payments/records",
380 body={"invoice_id": "inv1", "owner_id": "u1", "amount_cents": -5, "received_on": "2026-01-02", "method": "cash"}, user=1)
381 c("err bad token", "GET", "/collections/notes/records", token="not-a-session", user=None)
382 c("err method", "PATCH", "/collections/notes/records", user=1)
383 c("err schema meta bad name", "GET", "/api/schema/bad!name", user=1)
384 c("err schema admin as user", "GET", "/schemas/notes", user=1)
385 c("err schemas anon", "GET", "/schemas", user=None)
386 c("err collections as user", "GET", "/collections", user=1)
387 c("err policy as user", "GET", "/permissions/policy", user=1)
388 c("err unknown object", "GET", "/objects/no_such_object", user=1)
389 c("err bad object id", "GET", "/objects/bad!id", user=1)
390 c("err search empty", "GET", "/api/search", query="q=", user=1)
391 c("err search anon", "GET", "/api/search", query="q=note", user=None)
392 c("err unknown route", "GET", "/definitely/not/a/route", user=1)
393 c("err site post", "POST", "/no-such-page", body={"a": 1}, user=1)
394 c("err changes foreign", "GET", "/collections/notes/records/n5_1/changes", user=1)
395 c("err collection changes", "GET", "/collections/notes/changes", user=1)
396
397
398def write_text(path: Path, text: str) -> None:
399 path.parent.mkdir(parents=True, exist_ok=True)
400 path.write_text(text)
401
402
403def mutations(s: Session, work: Path) -> None:
404 data, objects = work / "data", work / "objects"
405 probes(s, "m00 start")
406
407 # --- rules for the names the later steps create, added to the policy file by hand ----------------
408 policy_file = data / "permissions" / "policy.json"
409 stored = json.loads(policy_file.read_text())
410 stored["rules"] += [
411 {"effect": "allow", "principal": "public", "actions": ["execute"], "object_id": object_id,
412 "reason": "differential"}
413 for object_id in ("site_hello_diff", "site_api_made", "brandnew_thing")
414 ] + [
415 {"effect": "allow", "principal": "registered", "actions": ["read", "create", "update", "delete"],
416 "collection": collection, "reason": "differential"}
417 for collection in ("loose_coll", "scratch_things")
418 ]
419 policy_file.write_text(json.dumps(stored, indent=2, sort_keys=True) + "\n")
420 probes(s, "m00b rules added by hand")
421
422 # --- schema, through the API ------------------------------------------------------------
423 _, _, raw = s.admin("m01 read schema", "GET", "/schemas/notes")
424 schema = json.loads(raw)["schema"]
425 edited = dict(schema)
426 edited["fields"] = list(schema["fields"]) + [{"name": "diff_flag", "type": "text"}]
427 s.admin("m01 put schema", "PUT", "/schemas/notes", body={"schema": edited})
428 s.call("m01 create with new field", "POST", "/collections/notes/records",
429 body={"content": "has flag", "owner_id": "u1", "diff_flag": "yes"}, user=1)
430 probes(s, "m01 schema via api")
431
432 # --- schema, by hand: same size, same instant -----------------------------------------------
433 path = data / "schemas" / "notes.json"
434 text = path.read_text()
435 assert "diff_flag" in text
436 path.write_text(text.replace("diff_flag", "diff_flug"))
437 s.call("m02 create with old field", "POST", "/collections/notes/records",
438 body={"content": "old flag", "owner_id": "u1", "diff_flag": "yes"}, user=1)
439 s.call("m02 create with renamed field", "POST", "/collections/notes/records",
440 body={"content": "new flag", "owner_id": "u1", "diff_flug": "yes"}, user=1)
441 probes(s, "m02 schema by hand")
442 path.write_text(json.dumps(schema, indent=2, sort_keys=True) + "\n")
443 probes(s, "m03 schema restored by hand")
444
445 # --- a schema file appears, gains a rollup onto notes, is broken, then disappears ---------------
446 scratch = data / "schemas" / "scratch_things.json"
447 write_text(scratch, json.dumps({"fields": [{"name": "id"}, {"name": "title"}, {"name": "owner_id"}]}))
448 probes(s, "m04 new schema file")
449 write_text(scratch, json.dumps({"fields": [
450 {"name": "id"}, {"name": "title"}, {"name": "owner_id"},
451 {"name": "note_count", "type": "computed",
452 "rollup": {"collection": "notes", "fk_field": "project_id", "op": "count"}}]}))
453 s.admin("m05 scratch row", "POST", "/collections/scratch_things/records", body={"id": "p1_0", "title": "t", "owner_id": "u1"})
454 s.call("m05 note that the new rollup must count", "POST", "/collections/notes/records",
455 body={"content": "counted", "project_id": "p1_0", "owner_id": "u1"}, user=1)
456 s.admin("m05 scratch row counted", "GET", "/collections/scratch_things/records/p1_0")
457 probes(s, "m05 schema gains rollup")
458 s.admin("m05 scratch row after", "GET", "/collections/scratch_things/records/p1_0")
459 write_text(scratch, "{ this is not json")
460 probes(s, "m06 schema file broken")
461 scratch.unlink()
462 probes(s, "m07 schema file removed")
463 shutil.rmtree(data / "collections" / "scratch_things", ignore_errors=True)
464 probes(s, "m08 scratch records removed")
465
466 # --- policy, through the API ---------------------------------------------------------------
467 _, _, raw = s.admin("m09 read policy", "GET", "/permissions/policy")
468 policy = json.loads(raw)["policy"]
469 denied = dict(policy)
470 denied["rules"] = [{"effect": "deny", "principal": "registered", "actions": ["read", "create"],
471 "collection": "notes", "reason": "differential"}] + list(policy["rules"])
472 s.admin("m09 put policy", "PUT", "/permissions/policy", body={"policy": denied})
473 probes(s, "m09 policy deny via api")
474 s.admin("m10 put policy back", "PUT", "/permissions/policy", body={"policy": policy})
475 probes(s, "m10 policy restored via api")
476
477 # --- policy, by hand: deny, then a rule naming a collection nothing else knows, then broken ----
478 original_text = policy_file.read_text()
479 policy_file.write_text(json.dumps(denied, indent=2, sort_keys=True) + "\n")
480 probes(s, "m11 policy deny by hand")
481 ghost = dict(policy)
482 ghost["rules"] = list(policy["rules"]) + [{"effect": "allow", "principal": "registered", "actions": ["read"],
483 "collection": "ghost_coll", "reason": "differential"}]
484 policy_file.write_text(json.dumps(ghost, indent=2, sort_keys=True) + "\n")
485 probes(s, "m12 policy names ghost collection")
486 policy_file.write_text("{ broken")
487 probes(s, "m13 policy file broken")
488 policy_file.write_text(original_text)
489 probes(s, "m14 policy restored by hand")
490 policy_file.unlink()
491 probes(s, "m15 policy file removed")
492 policy_file.write_text(original_text)
493 probes(s, "m16 policy file back")
494
495 # --- object files, by hand and through the API -------------------------------------------------
496 page = ("def GET(request):\n"
497 " return {'status': 'ok', 'said': 'hello %s'}\n")
498 write_text(objects / "site" / "hello_diff.py", page % "one")
499 probes(s, "m17 object file created by hand")
500 write_text(objects / "site" / "hello_diff.py", page % "two")
501 probes(s, "m18 object file edited by hand")
502 (objects / "site" / "hello_diff.py").unlink()
503 probes(s, "m19 object file deleted by hand")
504 write_text(objects / "brandnew" / "thing.py", page % "new category")
505 s.call("m20 new category object", "GET", "/objects/brandnew_thing", user=1)
506 probes(s, "m20 object in a new directory")
507 shutil.rmtree(objects / "brandnew")
508 s.call("m21 new category object gone", "GET", "/objects/brandnew_thing", user=1)
509 probes(s, "m21 new directory removed")
510 s.admin("m22 create object via api", "POST", "/objects", body={"object_id": "site_api_made", "code": page % "api"})
511 probes(s, "m22 object created via api")
512 s.admin("m23 update object via api", "PUT", "/objects/site_api_made", body={"code": page % "api v2"},
513 query="source=true")
514 probes(s, "m23 object updated via api")
515 (objects / "site" / "api_made.py").unlink()
516 probes(s, "m24 api object deleted by hand")
517
518 # --- a records file for a collection with no schema, and site_hosts ---------------------------
519 write_text(data / "collections" / "loose_coll" / "records.tsv", "id\ttitle\towner_id\nl1\tone\tu1\n")
520 probes(s, "m25 loose records file")
521 write_text(data / "collections" / "site_hosts" / "records.tsv",
522 "id\thost\tprefix\thome_object\nh1\tother.test\tsite\tsite_view_render\n")
523 probes(s, "m26 site_hosts records")
524 shutil.rmtree(data / "collections" / "site_hosts")
525 shutil.rmtree(data / "collections" / "loose_coll")
526 probes(s, "m27 loose and site_hosts removed")
527
528 # --- a package installed through the API, then taken out by hand -------------------------------
529 before = {p for p in objects.rglob("*.py")}
530 s.admin("m28 install package", "POST", f"/packages/{LATE_PACKAGE}/install", body={})
531 s.admin("m28 package status", "GET", f"/packages/{LATE_PACKAGE}")
532 probes(s, "m28 package installed via api")
533 for added in sorted({p for p in objects.rglob("*.py")} - before):
534 added.unlink()
535 probes(s, "m29 package objects removed by hand")
536
537 # --- identity: a grant, a share and a session that change between requests ---------------------
538 s.call("m30 foreign project note before grant", "GET", "/collections/notes/records/n4_2", user=1)
539 append_rows(work, "project_access", [dict(id="a_diff", project_id="p4_0", user_id="u1", permission="read",
540 granted_by="u4")])
541 s.call("m30 foreign project note after grant", "GET", "/collections/notes/records/n4_2", user=1)
542 s.call("m30 list after grant", "GET", "/collections/notes/records", query="limit=500", user=1)
543 access = data / "collections" / "project_access" / "records.tsv"
544 access.write_text("".join(line for line in access.read_text().splitlines(True) if not line.startswith("a_diff\t")))
545 s.call("m31 foreign project note after revoke", "GET", "/collections/notes/records/n4_2", user=1)
546 s.call("m31 list after revoke", "GET", "/collections/notes/records", query="limit=500", user=1)
547
548 # a project created and deleted through the API: ownership must follow at once
549 status, _, raw = s.call("m31b create project", "POST", "/collections/projects/records",
550 body={"name": "Differential", "status": "active", "owner_id": "u1"}, user=1)
551 if status == 201:
552 pid = json.loads(raw)["record"]["id"]
553 s.call("m31b note in the new project", "POST", "/collections/notes/records",
554 body={"content": "in new project", "project_id": pid, "owner_id": "u1"}, user=1)
555 s.call("m31b other user note in the new project", "POST", "/collections/notes/records",
556 body={"content": "not mine", "project_id": pid, "owner_id": "u2"}, user=2)
557 s.call("m31b share the new project", "POST", "/collections/project_access/records",
558 body={"project_id": pid, "user_id": "u2", "permission": "write", "granted_by": "u1"}, user=1)
559 s.call("m31b other user note after the share", "POST", "/collections/notes/records",
560 body={"content": "shared in", "project_id": pid, "owner_id": "u2"}, user=2)
561 s.call("m31b other user list after the share", "GET", "/collections/notes/records", query="limit=500", user=2)
562 s.call("m31b delete project", "DELETE", f"/collections/projects/records/{pid}", user=1)
563 s.call("m31b note in the deleted project", "POST", "/collections/notes/records",
564 body={"content": "orphan", "project_id": pid, "owner_id": "u1"}, user=1)
565 s.call("m31b list after the delete", "GET", "/collections/notes/records", query="limit=500", user=1)
566
567 # a record share written by hand, then removed
568 shares = data / "collections" / "record_shares" / "records.tsv"
569 share_fields = [f["name"] for f in json.loads((data / "schemas" / "record_shares.json").read_text())["fields"]] \
570 if (data / "schemas" / "record_shares.json").exists() else []
571 if share_fields:
572 had_file = shares.exists()
573 kept_shares = shares.read_text() if had_file else "\t".join(share_fields) + "\n"
574 row = dict(id="s_diff", collection="notes", record_id="n4_3", user_id="u1", permission="write", owner_id="u4",
575 granted_by="u4")
576 s.call("m31c shared note before the share", "GET", "/collections/notes/records/n4_3", user=1)
577 write_text(shares, kept_shares + "\t".join(row.get(name, "") for name in share_fields) + "\n")
578 s.call("m31c shared note after the share", "GET", "/collections/notes/records/n4_3", user=1)
579 s.call("m31c update shared note", "PUT", "/collections/notes/records/n4_3", body={"content": "edited by u1"}, user=1)
580 s.call("m31c identity", "GET", "/identity", user=1)
581 if had_file:
582 shares.write_text(kept_shares)
583 else:
584 shares.unlink()
585 s.call("m31c shared note after the unshare", "GET", "/collections/notes/records/n4_3", user=1)
586 s.call("m31c update after the unshare", "PUT", "/collections/notes/records/n4_3", body={"content": "again"}, user=1)
587
588 sessions = data / "identity" / "sessions.tsv"
589 if sessions.exists():
590 kept = sessions.read_text()
591 sessions.write_text("".join(line for i, line in enumerate(kept.splitlines(True)) if i != 2))
592 s.call("m32 session row removed", "GET", "/collections/notes/records", query="limit=5", user=1)
593 s.call("m32 identity", "GET", "/identity", user=1)
594 sessions.write_text(kept)
595 s.call("m33 session row back", "GET", "/collections/notes/records", query="limit=5", user=1)
596 probes(s, "m34 end")
597
598
599def main() -> int:
600 ap = argparse.ArgumentParser()
601 ap.add_argument("--tree", required=True)
602 ap.add_argument("--packages", required=True)
603 ap.add_argument("--work", required=True)
604 ap.add_argument("--out", required=True)
605 ap.add_argument("--set", default="core", choices=["core", "full"])
606 a = ap.parse_args()
607
608 tree, work, packages = Path(a.tree).resolve(), Path(a.work), Path(a.packages).resolve()
609 here = str(Path(__file__).resolve().parent)
610 sys.path[:] = [str(tree)] + [p for p in sys.path if p not in ("", here, str(tree))]
611 deterministic_urandom()
612 configure_env(work, packages)
613
614 import object_server
615
616 loaded = Path(object_server.__file__).resolve()
617 assert loaded.parent == tree, f"platform modules came from {loaded.parent}, not {tree}"
618
619 tokens = seed(work, packages, a.set)
620 session = Session(tokens)
621 base_requests(session)
622 mutations(session, work)
623 Path(a.out).write_text(json.dumps(session.log))
624 print(f"{len(session.log)} responses recorded from {tree}")
625 return 0
626
627
628if __name__ == "__main__":
629 raise SystemExit(main())