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, 30 minutes ago History
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
4Seeds U users (3 sessions each, 2 projects each, 3 project grants each, 10 owned
5notes each) into a throwaway data dir with the real app-notes package installed and
6permission 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
14usage: multiuser.py [--users 10,100,1000,3000] [--python PY] [--seconds 6]
15needs oha. Everything lives in temp dirs and is removed.
16"""
17from __future__ import annotations
18
19import argparse
20import json
21import os
22import random
23import shutil
24import signal
25import socket
26import subprocess
27import sys
28import tempfile
29import time
30import urllib.request
31from concurrent.futures import ThreadPoolExecutor
32from datetime import datetime, timedelta, timezone
33from pathlib import Path
34
35REPO = Path(__file__).resolve().parents[2]
36sys.path.insert(0, str(REPO))
37
38
39def free_port() -> int:
40 s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close(); return p
41
42
43def 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
87def 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
92def 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
97def 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"""
100import os, sys, time
101sys.path.insert(0, {str(REPO)!r})
102os.environ['DBBASIC_DATA_DIR'] = {str(tmp / 'data')!r}
103import object_identity, object_server
104base = {str(tmp / 'data')!r}
105def t(fn, n=30):
106 fn(); s = time.perf_counter()
107 for _ in range(n): fn()
108 return (time.perf_counter() - s) / n * 1000
109a = t(lambda: object_identity.resolve_session_token({token!r}, base_dir=base))
110h = {{'authorization': 'Bearer ' + {token!r}}}
111b = t(lambda: object_server._permission_identity(h))
112print(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
121def 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
179def 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
196if __name__ == "__main__":
197 raise SystemExit(main())