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, 31 minutes ago History
ws_check.py · 11.5 KB · 246 lines
1#!/usr/bin/env python3
2"""Does /ws (realtime push) behave the same under a given server?
3
4Starts the app on a throwaway data dir under uvicorn or granian, then checks the
5protocol docs/http-api-contract.md promises, plus the things that usually break
6at a server boundary: rejected anonymous sockets, abrupt disconnects, fan-out,
7and shutting down cleanly with sockets still open.
8
9 python ws_check.py --server uvicorn|granian [--python PATH] [--threads N] [--workers N]
10
11Prints one PASS/FAIL line per check and a delivery-latency summary; exit 1 on any FAIL.
12"""
13from __future__ import annotations
14
15import argparse
16import asyncio
17import json
18import os
19import signal
20import socket
21import statistics
22import subprocess
23import sys
24import tempfile
25import time
26import urllib.request
27from pathlib import Path
28
29HERE = Path(__file__).resolve().parent
30REPO = HERE.parents[1]
31TOKEN = "benchtoken"
32AUTH = {"Authorization": f"Token {TOKEN}"}
33
34try:
35 from websockets.asyncio.client import connect
36 from websockets.exceptions import ConnectionClosed, InvalidStatus
37except ImportError: # pragma: no cover
38 sys.exit("needs the `websockets` package (it is in the project venv)")
39
40
41def free_port() -> int:
42 s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close(); return p
43
44
45def http(method: str, url: str, body: dict | None = None) -> tuple[int, dict]:
46 req = urllib.request.Request(url, method=method, data=json.dumps(body).encode() if body is not None else None,
47 headers={**AUTH, "Content-Type": "application/json", "Accept": "application/json"})
48 try:
49 with urllib.request.urlopen(req, timeout=20) as r:
50 return r.status, json.loads(r.read() or b"{}")
51 except urllib.error.HTTPError as e:
52 return e.code, {}
53
54
55async def ahttp(*a, **k):
56 return await asyncio.to_thread(http, *a, **k)
57
58
59class Server:
60 def __init__(self, kind: str, python: str, workers: int, threads: int | None):
61 self.kind, self.python, self.workers, self.threads = kind, python, workers, threads
62 self.tmp = Path(tempfile.mkdtemp()); self.port = free_port(); self.proc = None
63
64 @property
65 def base(self) -> str: return f"http://127.0.0.1:{self.port}"
66
67 def start(self) -> None:
68 subprocess.run([self.python, str(HERE / "seed_tsv.py"), str(self.tmp / "data"), str(self.tmp / "urls"),
69 self.base, "200"], check=True)
70 (self.tmp / "objects").mkdir()
71 if self.kind == "uvicorn":
72 cmd = [self.python, "-m", "uvicorn", "object_server:app", "--host", "127.0.0.1", "--port", str(self.port),
73 "--workers", str(self.workers), "--log-level", "warning", "--no-access-log"]
74 else:
75 cmd = [self.python, "-m", "granian", "--interface", "asgi", "--host", "127.0.0.1", "--port", str(self.port),
76 "--workers", str(self.workers), "--log-level", "warning"]
77 if self.threads:
78 cmd += ["--runtime-threads", str(self.threads), "--blocking-threads", str(self.threads)]
79 cmd += ["object_server:app"]
80 env = {k: v for k, v in os.environ.items() if k != "DBBASIC_RATE_LIMIT_REQUESTS"}
81 env.update(DBBASIC_OBJECTS_DIR=str(self.tmp / "objects"), DBBASIC_DATA_DIR=str(self.tmp / "data"),
82 DBBASIC_ADMIN_TOKEN=TOKEN, DBBASIC_COOKIE_SECURE="false")
83 self.log = open(self.tmp / "server.log", "w")
84 self.proc = subprocess.Popen(cmd, cwd=REPO, env=env, stdout=self.log, stderr=subprocess.STDOUT)
85 for _ in range(80):
86 if self.proc.poll() is not None:
87 sys.exit(f"server exited during startup:\n{(self.tmp / 'server.log').read_text()[-1500:]}")
88 try:
89 urllib.request.urlopen(self.base + "/health", timeout=1).read(); return
90 except Exception:
91 time.sleep(0.5)
92 sys.exit("server did not become ready")
93
94 def stop_timed(self) -> float | None:
95 """SIGTERM and time how long the server takes to exit."""
96 t = time.perf_counter(); self.proc.send_signal(signal.SIGTERM)
97 try:
98 self.proc.wait(timeout=20); return time.perf_counter() - t
99 except subprocess.TimeoutExpired:
100 self.proc.kill(); self.proc.wait(); return None
101
102 def kill(self) -> None:
103 if self.proc and self.proc.poll() is None:
104 self.proc.kill(); self.proc.wait()
105
106
107results: list[tuple[str, bool, str]] = []
108
109
110def check(name: str, ok: bool, detail: str = "") -> None:
111 results.append((name, ok, detail)); print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail else ""), flush=True)
112
113
114async def recv_json(ws, timeout=3.0):
115 return json.loads(await asyncio.wait_for(ws.recv(), timeout))
116
117
118async def recv_record(ws, record_id, action, timeout=3.0):
119 end = time.perf_counter() + timeout
120 while time.perf_counter() < end:
121 m = await recv_json(ws, max(0.05, end - time.perf_counter()))
122 if m.get("type") == "record" and m.get("record_id") == record_id and m.get("action") == action:
123 return m
124 raise asyncio.TimeoutError
125
126
127async def run_checks(srv: Server) -> None:
128 uri = f"ws://127.0.0.1:{srv.port}/ws"
129 coll = "bench_log"
130
131 # 1. anonymous sockets are refused or closed
132 try:
133 async with connect(uri) as ws:
134 try:
135 await asyncio.wait_for(ws.recv(), 3); check("anonymous connection is refused", False, "got a message")
136 except ConnectionClosed as e:
137 check("anonymous connection is refused", True, f"closed {e.rcvd.code if e.rcvd else '?'}")
138 except (InvalidStatus, ConnectionClosed, OSError) as e:
139 check("anonymous connection is refused", True, type(e).__name__)
140
141 # 2-4. welcome, subscribe, ping
142 async with connect(uri, additional_headers=AUTH) as ws:
143 m = await recv_json(ws); check("welcome frame after connect", m.get("type") == "welcome", str(m))
144 await ws.send(json.dumps({"action": "subscribe", "collections": [coll, "not a valid name!"]}))
145 m = await recv_json(ws); check("subscribe is acknowledged, invalid names dropped", m == {"type": "subscribed", "collections": [coll]}, str(m))
146 await ws.send(json.dumps({"action": "ping"}))
147 m = await recv_json(ws); check("ping gets pong", m.get("type") == "pong", str(m))
148 await ws.send("this is not json"); await ws.send(json.dumps([1, 2]))
149 await ws.send(json.dumps({"action": "ping"}))
150 m = await recv_json(ws); check("garbage frames are ignored, socket stays usable", m.get("type") == "pong", str(m))
151
152 # 5-7. created / updated / deleted signals; signal carries no body
153 st, body = await ahttp("POST", f"{srv.base}/collections/{coll}/records", {"title": "ws-test", "note": "SECRET-BODY"})
154 rid = body.get("record", {}).get("id")
155 check("HTTP create succeeds", st == 201 and rid, f"status {st}")
156 try:
157 m = await recv_record(ws, rid, "create")
158 check("create signal arrives", True)
159 check("signal never carries the record body", "SECRET-BODY" not in json.dumps(m) and set(m) <= {"type", "collection", "record_id", "action"}, str(m))
160 except asyncio.TimeoutError:
161 check("create signal arrives", False, "timeout")
162 await ahttp("PUT", f"{srv.base}/collections/{coll}/records/{rid}", {"title": "changed"})
163 try: await recv_record(ws, rid, "update"); check("update signal arrives", True)
164 except asyncio.TimeoutError: check("update signal arrives", False, "timeout")
165 await ahttp("DELETE", f"{srv.base}/collections/{coll}/records/{rid}")
166 try: await recv_record(ws, rid, "delete"); check("delete signal arrives", True)
167 except asyncio.TimeoutError: check("delete signal arrives", False, "timeout")
168
169 # 8. unsubscribe stops delivery
170 await ws.send(json.dumps({"action": "unsubscribe", "collections": [coll]}))
171 await recv_json(ws)
172 _, body = await ahttp("POST", f"{srv.base}/collections/{coll}/records", {"title": "after-unsub"})
173 try:
174 await recv_record(ws, body["record"]["id"], "create", timeout=1.0); check("no signals after unsubscribe", False, "still delivered")
175 except asyncio.TimeoutError:
176 check("no signals after unsubscribe", True)
177
178 # 9. fan-out to many clients, each exactly once
179 n = 25
180 sockets = [await connect(uri, additional_headers=AUTH).__aenter__() for _ in range(n)]
181 try:
182 for ws in sockets:
183 await recv_json(ws); await ws.send(json.dumps({"action": "subscribe", "collections": [coll]})); await recv_json(ws)
184 _, body = await ahttp("POST", f"{srv.base}/collections/{coll}/records", {"title": "fanout"})
185 rid = body["record"]["id"]
186 got = await asyncio.gather(*[recv_record(ws, rid, "create") for ws in sockets], return_exceptions=True)
187 check(f"fan-out reaches all {n} clients", all(not isinstance(g, Exception) for g in got), f"{sum(not isinstance(g, Exception) for g in got)}/{n}")
188
189 # 10. abrupt disconnects don't hurt the others or the server
190 for ws in sockets[: n // 2]:
191 ws.transport.abort()
192 await asyncio.sleep(0.3)
193 _, body = await ahttp("POST", f"{srv.base}/collections/{coll}/records", {"title": "after-abort"})
194 rid = body["record"]["id"]
195 live = await asyncio.gather(*[recv_record(ws, rid, "create") for ws in sockets[n // 2:]], return_exceptions=True)
196 check("survivors still get signals after half the clients vanish", all(not isinstance(g, Exception) for g in live))
197 st, _ = await ahttp("GET", f"{srv.base}/health")
198 check("server healthy after abrupt disconnects", st == 200)
199
200 # 11. delivery latency (sequential creates, one subscriber)
201 ws = sockets[-1]
202 lat = []
203 for i in range(60):
204 t = time.perf_counter()
205 _, body = await ahttp("POST", f"{srv.base}/collections/{coll}/records", {"title": f"lat{i}"})
206 await recv_record(ws, body["record"]["id"], "create")
207 lat.append((time.perf_counter() - t) * 1000)
208 lat.sort()
209 print(f" create->signal latency over 60 creates: median {statistics.median(lat):.1f} ms, p95 {lat[int(len(lat)*.95)-1]:.1f} ms")
210 check("latency measured", True)
211 finally:
212 for ws in sockets:
213 try: await ws.close()
214 except Exception: pass
215
216 # 12. shutdown with sockets still open
217 held = [await connect(uri, additional_headers=AUTH).__aenter__() for _ in range(3)]
218 for ws in held: await recv_json(ws)
219 secs = await asyncio.to_thread(srv.stop_timed)
220 check("clean shutdown with 3 sockets open", secs is not None and secs < 10, "did not exit in 20s" if secs is None else f"exited in {secs:.1f}s")
221 for ws in held:
222 try: await ws.close()
223 except Exception: pass
224
225
226def main() -> int:
227 ap = argparse.ArgumentParser()
228 ap.add_argument("--server", choices=["uvicorn", "granian"], required=True)
229 ap.add_argument("--python", default=str(REPO / ".venv-jit/bin/python"))
230 ap.add_argument("--workers", type=int, default=1)
231 ap.add_argument("--threads", type=int, default=None, help="granian runtime/blocking threads")
232 args = ap.parse_args()
233 srv = Server(args.server, args.python, args.workers, args.threads)
234 print(f"== /ws under {args.server} (workers={args.workers}, threads={args.threads}) with {args.python}")
235 srv.start()
236 try:
237 asyncio.run(run_checks(srv))
238 finally:
239 srv.kill()
240 bad = [r for r in results if not r[1]]
241 print(f"== {len(results) - len(bad)} passed, {len(bad)} failed")
242 return 1 if bad else 0
243
244
245if __name__ == "__main__":
246 raise SystemExit(main())