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

9 downloads

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, 41 minutes ago History
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
4Experiment only: monkeypatches its OWN process, edits nothing in the server.
5Seeds U users (default 1000), drives the real ASGI app in-process as a signed-in user, and times
6GET /collections/notes/records?limit=20 under:
7 baseline | + rules narrowed once per (action, resource) | + session lookup cached by file mtime | both
8and checks that the narrowed permission engine returns IDENTICAL decisions to the real one for
9every note x several subjects x several actions.
10
11 multiuser_fixes.py [USERS]
12"""
13from __future__ import annotations
14
15import asyncio
16import dataclasses
17import os
18import sys
19import tempfile
20import time
21from pathlib import Path
22
23REPO = Path(__file__).resolve().parents[3]
24sys.path.insert(0, str(REPO)); sys.path.insert(0, str(REPO / "scripts/bench"))
25import multiuser # noqa: E402
26
27U = int(sys.argv[1]) if len(sys.argv) > 1 else 1000
28tmp = Path(tempfile.mkdtemp()); (tmp / "objects").mkdir()
29tokens = multiuser.seed(tmp, U)
30os.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")
32import object_identity # noqa: E402
33import object_permissions as op # noqa: E402
34import object_server # noqa: E402
35
36REAL_CHECK = op.check_permission
37REAL_READ_SESSIONS = object_identity._read_sessions
38
39
40async 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
51def 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
65def 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
83def 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
94print(f"{U} users, {U*10} notes, {U*3} sessions, enforcement on")
95base = timed("baseline")
96op.check_permission = narrowed_check
97object_server.object_permissions.check_permission = narrowed_check
98_narrow_cache.clear()
99narrow = timed("+ rules narrowed once per request-kind")
100object_identity._read_sessions = cached_read_sessions
101both = timed("+ session file parsed once per change")
102op.check_permission = REAL_CHECK; object_server.object_permissions.check_permission = REAL_CHECK
103sess_only = timed("session cache alone (rules not narrowed)")
104object_identity._read_sessions = REAL_READ_SESSIONS
105print(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 -----------------------------
108import object_permission_store, object_records # noqa: E402
109policy = object_permission_store.load_policy(tmp / "data")
110rows = object_records.read_collection_records("notes", base_dir=tmp / "data")
111subjects = [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]]
113mismatch = checks = 0
114_narrow_cache.clear()
115for 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
123print(f"exactness: {checks} decisions compared (4 subjects x 4 actions x {min(len(rows),4000)} rows): {'IDENTICAL' if mismatch == 0 else str(mismatch) + ' DIFFER'}")