askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
multiuser_fixes.py · 5.7 KB · 123 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """What would pure-Python fixes buy for the multi-user cost, and are they exact? |
| 3 | |
| 4 | Experiment only: monkeypatches its OWN process, edits nothing in the server. |
| 5 | Seeds U users (default 1000), drives the real ASGI app in-process as a signed-in user, and times |
| 6 | GET /collections/notes/records?limit=20 under: |
| 7 | baseline | + rules narrowed once per (action, resource) | + session lookup cached by file mtime | both |
| 8 | and checks that the narrowed permission engine returns IDENTICAL decisions to the real one for |
| 9 | every note x several subjects x several actions. |
| 10 | |
| 11 | multiuser_fixes.py [USERS] |
| 12 | """ |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import asyncio |
| 16 | import dataclasses |
| 17 | import os |
| 18 | import sys |
| 19 | import tempfile |
| 20 | import time |
| 21 | from pathlib import Path |
| 22 | |
| 23 | REPO = Path(__file__).resolve().parents[3] |
| 24 | sys.path.insert(0, str(REPO)); sys.path.insert(0, str(REPO / "scripts/bench")) |
| 25 | import multiuser # noqa: E402 |
| 26 | |
| 27 | U = int(sys.argv[1]) if len(sys.argv) > 1 else 1000 |
| 28 | tmp = Path(tempfile.mkdtemp()); (tmp / "objects").mkdir() |
| 29 | tokens = multiuser.seed(tmp, U) |
| 30 | os.environ.update(DBBASIC_OBJECTS_DIR=str(tmp / "objects"), DBBASIC_ADMIN_TOKEN="x", DBBASIC_ENABLE_PERMISSION_ENFORCEMENT="true", |
| 31 | DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT="true", DBBASIC_MAX_CONCURRENT_REQUESTS="0", DBBASIC_MAX_CONCURRENT_EXECUTIONS="0") |
| 32 | import object_identity # noqa: E402 |
| 33 | import object_permissions as op # noqa: E402 |
| 34 | import object_server # noqa: E402 |
| 35 | |
| 36 | REAL_CHECK = op.check_permission |
| 37 | REAL_READ_SESSIONS = object_identity._read_sessions |
| 38 | |
| 39 | |
| 40 | async def one(i: int = 0) -> int: |
| 41 | sent = [] |
| 42 | async def receive(): return {"type": "http.request", "body": b"", "more_body": False} |
| 43 | async def send(m): sent.append(m) |
| 44 | scope = {"type": "http", "method": "GET", "path": "/collections/notes/records", "query_string": b"limit=20", |
| 45 | "headers": [(b"authorization", f"Bearer {tokens[i % len(tokens)]}".encode()), (b"accept", b"application/json"), (b"host", b"x")], |
| 46 | "client": ("127.0.0.1", 1)} |
| 47 | await object_server.app(scope, receive, send) |
| 48 | return sent[0]["status"] |
| 49 | |
| 50 | |
| 51 | def timed(label: str, n: int = 8) -> float: |
| 52 | asyncio.run(one()) # warm |
| 53 | t = time.perf_counter() |
| 54 | for k in range(n): |
| 55 | assert asyncio.run(one(k)) == 200 |
| 56 | ms = (time.perf_counter() - t) / n * 1000 |
| 57 | print(f" {label:<46} {ms:8.1f} ms / list request") |
| 58 | return ms |
| 59 | |
| 60 | |
| 61 | # ---- the two candidate fixes -------------------------------------------------------------------- |
| 62 | _narrow_cache: dict = {} |
| 63 | |
| 64 | |
| 65 | def narrowed_check(subject, action, *, policy=None, collection=None, object_id=None, record=None, now=None): |
| 66 | """Same result as check_permission; the rules that cannot depend on the ROW (active window, action, |
| 67 | resource) are filtered once per (policy, action, resource) instead of once per row per rule.""" |
| 68 | if policy is None or record is None: |
| 69 | return REAL_CHECK(subject, action, policy=policy, collection=collection, object_id=object_id, record=record, now=now) |
| 70 | key = (id(policy), action.lower(), collection, object_id) |
| 71 | narrow = _narrow_cache.get(key) |
| 72 | if narrow is None: |
| 73 | at = now or op.datetime.now(op.timezone.utc) |
| 74 | keep = tuple(r for r in policy.rules if op._rule_is_active(r, at) and op._action_matches(r, action.lower()) |
| 75 | and op._resource_matches(r, collection=collection, object_id=object_id)) |
| 76 | narrow = _narrow_cache[key] = (policy, dataclasses.replace(policy, rules=keep)) # hold `policy` so id() stays unique |
| 77 | return REAL_CHECK(subject, action, policy=narrow[1], collection=collection, object_id=object_id, record=record, now=now) |
| 78 | |
| 79 | |
| 80 | _sess_cache: dict = {} |
| 81 | |
| 82 | |
| 83 | def cached_read_sessions(path): |
| 84 | st = path.stat() |
| 85 | key = (str(path), st.st_mtime_ns, st.st_size) |
| 86 | hit = _sess_cache.get("k") |
| 87 | if hit and hit[0] == key: |
| 88 | return hit[1] |
| 89 | value = REAL_READ_SESSIONS(path) |
| 90 | _sess_cache["k"] = (key, value) |
| 91 | return value |
| 92 | |
| 93 | |
| 94 | print(f"{U} users, {U*10} notes, {U*3} sessions, enforcement on") |
| 95 | base = timed("baseline") |
| 96 | op.check_permission = narrowed_check |
| 97 | object_server.object_permissions.check_permission = narrowed_check |
| 98 | _narrow_cache.clear() |
| 99 | narrow = timed("+ rules narrowed once per request-kind") |
| 100 | object_identity._read_sessions = cached_read_sessions |
| 101 | both = timed("+ session file parsed once per change") |
| 102 | op.check_permission = REAL_CHECK; object_server.object_permissions.check_permission = REAL_CHECK |
| 103 | sess_only = timed("session cache alone (rules not narrowed)") |
| 104 | object_identity._read_sessions = REAL_READ_SESSIONS |
| 105 | print(f" -> {base/both:.1f}x faster with both; the rest is {both:.1f} ms") |
| 106 | |
| 107 | # ---- exactness: identical decisions for every row, subject and action ----------------------------- |
| 108 | import object_permission_store, object_records # noqa: E402 |
| 109 | policy = object_permission_store.load_policy(tmp / "data") |
| 110 | rows = object_records.read_collection_records("notes", base_dir=tmp / "data") |
| 111 | subjects = [op.PermissionSubject.anonymous(), op.PermissionSubject(user_id="u0", roles=()), op.PermissionSubject(user_id="u5", roles=("admin",)), |
| 112 | object_server._permission_identity({"authorization": f"Bearer {tokens[3]}"})[0]] |
| 113 | mismatch = checks = 0 |
| 114 | _narrow_cache.clear() |
| 115 | for subj in subjects: |
| 116 | for action in ("read", "update", "delete", "create"): |
| 117 | for row in rows[:4000]: |
| 118 | a = REAL_CHECK(subj, action, policy=policy, collection="notes", record=row) |
| 119 | b = narrowed_check(subj, action, policy=policy, collection="notes", record=row) |
| 120 | checks += 1 |
| 121 | if (a.allowed, a.reason, getattr(a, "row_filter", None)) != (b.allowed, b.reason, getattr(b, "row_filter", None)): |
| 122 | mismatch += 1 |
| 123 | print(f"exactness: {checks} decisions compared (4 subjects x 4 actions x {min(len(rows),4000)} rows): {'IDENTICAL' if mismatch == 0 else str(mismatch) + ' DIFFER'}") |