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.py · 9.8 KB · 197 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """How does the server stand up as the number of USERS grows? |
| 3 | |
| 4 | Seeds U users (3 sessions each, 2 projects each, 3 project grants each, 10 owned |
| 5 | notes each) into a throwaway data dir with the real app-notes package installed and |
| 6 | permission enforcement ON, then measures, as U grows: |
| 7 | |
| 8 | health no identity at all -- the server's own floor |
| 9 | list_notes GET /collections/notes?limit=20 as a signed-in user (row filter owner_id=$user) |
| 10 | create_note POST /collections/notes/records as a signed-in user |
| 11 | 8 users at once 8 different users, 4 connections each, for a few seconds (aggregate req/s) |
| 12 | identity() in-process cost of ONE identity resolution (session -> subject), no HTTP |
| 13 | |
| 14 | usage: multiuser.py [--users 10,100,1000,3000] [--python PY] [--seconds 6] |
| 15 | needs oha. Everything lives in temp dirs and is removed. |
| 16 | """ |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import argparse |
| 20 | import json |
| 21 | import os |
| 22 | import random |
| 23 | import shutil |
| 24 | import signal |
| 25 | import socket |
| 26 | import subprocess |
| 27 | import sys |
| 28 | import tempfile |
| 29 | import time |
| 30 | import urllib.request |
| 31 | from concurrent.futures import ThreadPoolExecutor |
| 32 | from datetime import datetime, timedelta, timezone |
| 33 | from pathlib import Path |
| 34 | |
| 35 | REPO = Path(__file__).resolve().parents[2] |
| 36 | sys.path.insert(0, str(REPO)) |
| 37 | |
| 38 | |
| 39 | def free_port() -> int: |
| 40 | s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close(); return p |
| 41 | |
| 42 | |
| 43 | def seed(tmp: Path, users: int) -> list[str]: |
| 44 | """Build the data dir; return one raw session token per user (first session).""" |
| 45 | os.environ["DBBASIC_DATA_DIR"] = str(tmp / "data") |
| 46 | import object_identity as oi |
| 47 | import object_packages |
| 48 | |
| 49 | for name in ("app-projects", "app-views", "app-notes"): |
| 50 | object_packages.install_package(name, root=REPO / "packages", base_dir=tmp / "data", object_roots=[tmp / "objects"]) |
| 51 | |
| 52 | now = datetime.now(timezone.utc).replace(microsecond=0) |
| 53 | stamp = oi._format_timestamp(now) |
| 54 | expires = oi._format_timestamp(now + timedelta(days=30)) |
| 55 | user_rows, sessions, tokens = [], [], [] |
| 56 | for i in range(users): |
| 57 | uid = f"u{i}" |
| 58 | user_rows.append(oi.IdentityUser(user_id=uid, account_id=None, email=f"{uid}@example.test", display_name=f"User {i}", |
| 59 | status="active", roles=(), subscriptions=(), created_at=stamp, updated_at=stamp)) |
| 60 | for d in range(3): # three devices -> three live sessions |
| 61 | token = f"tok-{i}-{d}" |
| 62 | sessions.append(oi.IdentitySession(session_id=oi._new_session_id(), token_hash=oi.hash_token(token), user_id=uid, account_id=None, |
| 63 | roles=(), subscriptions=(), label="", created_at=stamp, expires_at=expires)) |
| 64 | if d == 0: |
| 65 | tokens.append(token) |
| 66 | oi._write_users(oi.users_path(tmp / "data"), user_rows) |
| 67 | oi._write_sessions(oi.sessions_path(tmp / "data"), sessions) |
| 68 | |
| 69 | rng = random.Random(1) |
| 70 | coll = tmp / "data" / "collections" |
| 71 | with open(coll / "projects" / "records.tsv", "a") as f: |
| 72 | for i in range(users): |
| 73 | for p in range(2): |
| 74 | f.write(f"p{i}_{p}\tProject {i}.{p}\tseed\tactive\tu{i}\n") |
| 75 | with open(coll / "project_access" / "records.tsv", "a") as f: |
| 76 | for i in range(users): |
| 77 | for g in range(3): |
| 78 | other = (i + 1 + g) % users # deterministic: user i can read the next 3 users' first project |
| 79 | f.write(f"a{i}_{g}\tp{other}_0\tu{i}\tread\tu{other}\n") |
| 80 | with open(coll / "notes" / "records.tsv", "a") as f: |
| 81 | for i in range(users): |
| 82 | for n in range(10): |
| 83 | f.write(f"n{i}_{n}\tnote {n} of user {i}, some realistic length text\tp{i}_0\tfalse\tu{i}\n") |
| 84 | return tokens |
| 85 | |
| 86 | |
| 87 | def oha(args: list[str]) -> dict: |
| 88 | out = subprocess.run(["oha", "--no-tui", "--output-format", "json", *args], capture_output=True, text=True, check=True).stdout |
| 89 | return json.loads(out) |
| 90 | |
| 91 | |
| 92 | def p(d: dict, q: str) -> float: |
| 93 | v = d["latencyPercentiles"].get(q) # oha reports null when too few requests finished |
| 94 | return float("nan") if v is None else v * 1000 |
| 95 | |
| 96 | |
| 97 | def identity_cost(tmp: Path, token: str) -> tuple[float, float]: |
| 98 | """ms for one resolve_session_token and for one full _permission_identity().""" |
| 99 | code = f""" |
| 100 | import os, sys, time |
| 101 | sys.path.insert(0, {str(REPO)!r}) |
| 102 | os.environ['DBBASIC_DATA_DIR'] = {str(tmp / 'data')!r} |
| 103 | import object_identity, object_server |
| 104 | base = {str(tmp / 'data')!r} |
| 105 | def t(fn, n=30): |
| 106 | fn(); s = time.perf_counter() |
| 107 | for _ in range(n): fn() |
| 108 | return (time.perf_counter() - s) / n * 1000 |
| 109 | a = t(lambda: object_identity.resolve_session_token({token!r}, base_dir=base)) |
| 110 | h = {{'authorization': 'Bearer ' + {token!r}}} |
| 111 | b = t(lambda: object_server._permission_identity(h)) |
| 112 | print(a, b) |
| 113 | """ |
| 114 | out = subprocess.run([PY, "-c", code], capture_output=True, text=True, cwd=REPO) |
| 115 | if out.returncode: |
| 116 | sys.exit(out.stderr[-800:]) |
| 117 | a, b = out.stdout.split() |
| 118 | return float(a), float(b) |
| 119 | |
| 120 | |
| 121 | def run_one(users: int, seconds: int) -> dict: |
| 122 | tmp = Path(tempfile.mkdtemp()) |
| 123 | try: |
| 124 | (tmp / "objects").mkdir() |
| 125 | tokens = seed(tmp, users) |
| 126 | port = free_port(); base = f"http://127.0.0.1:{port}" |
| 127 | env = {k: v for k, v in os.environ.items() if k != "DBBASIC_RATE_LIMIT_REQUESTS"} |
| 128 | env.update(DBBASIC_OBJECTS_DIR=str(tmp / "objects"), DBBASIC_DATA_DIR=str(tmp / "data"), DBBASIC_ADMIN_TOKEN="admin-t", |
| 129 | DBBASIC_ENABLE_PERMISSION_ENFORCEMENT="true", DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT="true", |
| 130 | DBBASIC_MAX_CONCURRENT_REQUESTS="0", DBBASIC_MAX_CONCURRENT_EXECUTIONS="0", DBBASIC_COOKIE_SECURE="false") |
| 131 | log = open(tmp / "server.log", "w") |
| 132 | srv = subprocess.Popen([PY, "-m", "uvicorn", "object_server:app", "--host", "127.0.0.1", "--port", str(port), |
| 133 | "--log-level", "warning", "--no-access-log"], cwd=REPO, env=env, stdout=log, stderr=subprocess.STDOUT) |
| 134 | try: |
| 135 | for _ in range(80): |
| 136 | try: urllib.request.urlopen(base + "/health", timeout=1).read(); break |
| 137 | except Exception: time.sleep(0.5) |
| 138 | else: |
| 139 | sys.exit("server did not start: " + (tmp / "server.log").read_text()[-600:]) |
| 140 | |
| 141 | def auth(i: int) -> list[str]: |
| 142 | return ["-H", f"Authorization: Bearer {tokens[i % len(tokens)]}", "-H", "Accept: application/json"] |
| 143 | |
| 144 | # sanity: the user must see exactly their own 10 notes, enforcement on |
| 145 | req = urllib.request.Request(base + "/collections/notes/records?limit=200", headers={"Authorization": f"Bearer {tokens[0]}", "Accept": "application/json"}) |
| 146 | body = json.loads(urllib.request.urlopen(req, timeout=20).read()) |
| 147 | rows = body.get("records", body.get("items", [])) |
| 148 | expected = 10 + 10 * min(3, users - 1) # own notes + the notes of the projects shared with u0 |
| 149 | if len(rows) != expected or any(r.get("owner_id") != "u0" and r.get("project_id") not in {"p1_0", "p2_0", "p3_0"} for r in rows): |
| 150 | sys.exit(f"sanity failed: user u0 saw {len(rows)} notes, expected {expected}: {str(body)[:300]}") |
| 151 | |
| 152 | res: dict = {"users": users} |
| 153 | res["health_p50"] = p(oha(["-n", "1500", "-c", "1", base + "/health"]), "p50") |
| 154 | d = oha(["-n", "600", "-c", "1", *auth(0), base + "/collections/notes/records?limit=20"]) |
| 155 | if d["statusCodeDistribution"] != {"200": 600}: |
| 156 | sys.exit(f"list_notes did not succeed: {d['statusCodeDistribution']}") |
| 157 | res["list_p50"], res["list_rps"] = p(d, "p50"), d["summary"]["requestsPerSec"] |
| 158 | # The generated form sends owner_id; without it the write is refused (403) before the server would stamp it. |
| 159 | d = oha(["-n", "200", "-c", "1", "-m", "POST", "-T", "application/json", "-d", '{"content":"bench note","owner_id":"u1"}', *auth(1), base + "/collections/notes/records"]) |
| 160 | if d["statusCodeDistribution"] != {"201": 200}: |
| 161 | sys.exit(f"create_note did not succeed: {d['statusCodeDistribution']}") |
| 162 | res["create_p50"] = p(d, "p50") |
| 163 | with ThreadPoolExecutor(8) as ex: |
| 164 | futs = [ex.submit(oha, ["-z", f"{seconds}s", "-c", "4", *auth(i * 7 + 2), base + "/collections/notes/records?limit=20"]) for i in range(8)] |
| 165 | ds = [f.result() for f in futs] |
| 166 | res["x8_rps"] = sum(x["summary"]["requestsPerSec"] for x in ds) |
| 167 | res["x8_p99"] = max((p(x, "p99") for x in ds), default=float("nan")) |
| 168 | res["x8_err"] = sum(sum(v for k, v in x["statusCodeDistribution"].items() if k != "200") for x in ds) |
| 169 | res["session_ms"], res["identity_ms"] = identity_cost(tmp, tokens[0]) |
| 170 | return res |
| 171 | finally: |
| 172 | srv.send_signal(signal.SIGTERM) |
| 173 | try: srv.wait(10) |
| 174 | except subprocess.TimeoutExpired: srv.kill() |
| 175 | finally: |
| 176 | shutil.rmtree(tmp, ignore_errors=True) |
| 177 | |
| 178 | |
| 179 | def main() -> int: |
| 180 | global PY |
| 181 | ap = argparse.ArgumentParser() |
| 182 | ap.add_argument("--users", default="10,100,1000,3000") |
| 183 | ap.add_argument("--python", default=str(REPO / ".venv-jit/bin/python")) |
| 184 | ap.add_argument("--seconds", type=int, default=6) |
| 185 | a = ap.parse_args() |
| 186 | PY = a.python |
| 187 | print(f"{'users':>6} {'health':>8} {'list':>9} {'list rps':>9} {'create':>9} {'8 users x4 conns':>28} {'identity cost, in-process':>27}") |
| 188 | print(f"{'':>6} {'p50 ms':>8} {'p50 ms':>9} {'(1 conn)':>9} {'p50 ms':>9} {'agg req/s':>14} {'worst p99 ms':>12} {'err':>4} {'session ms':>12} {'whole ms':>10}") |
| 189 | for u in [int(x) for x in a.users.split(",")]: |
| 190 | r = run_one(u, a.seconds) |
| 191 | print(f"{r['users']:>6} {r['health_p50']:>8.2f} {r['list_p50']:>9.2f} {r['list_rps']:>9.0f} {r['create_p50']:>9.2f} " |
| 192 | f"{r['x8_rps']:>14.0f} {r['x8_p99']:>12.1f} {r['x8_err']:>4} {r['session_ms']:>12.2f} {r['identity_ms']:>10.2f}", flush=True) |
| 193 | return 0 |
| 194 | |
| 195 | |
| 196 | if __name__ == "__main__": |
| 197 | raise SystemExit(main()) |