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

9 downloads

dbbasic-object-server/tests/test_worker_pool_real_pages.py
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, 19 minutes ago History
test_worker_pool_real_pages.py · 10.8 KB · 287 lines
1"""Pool vs in-process equivalence for REAL packaged objects.
2
3docs recommend DBBASIC_OBJECT_TIMEOUT_SECONDS=5, which makes every HTTP-invoked
4object run out of process. DBBASIC_WORKER_POOL_SIZE keeps warm workers instead
5of spawning an interpreter per call. These tests run the same requests through
6(a) default in-process execution and (b) timeout=5 + pool size 2 and require
7identical observable behaviour. Real packages (app-projects, app-views,
8app-notes) are installed into tmp_path, as scripts/bench/experiments/
9real_page_modes.sh does.
10"""
11import asyncio
12import json
13import re
14from pathlib import Path
15
16import pytest
17
18import object_packages
19import object_server
20import object_worker_pool
21
22PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
23TOKEN = "unit-test-only-admin-token"
24IN_PROCESS = "in_process"
25POOLED = "pooled"
26
27
28def configure(monkeypatch, tmp_path, mode, *, timeout="5"):
29 data_dir = tmp_path / "data"
30 root = tmp_path / "objects"
31 root.mkdir(parents=True, exist_ok=True)
32 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
33 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
34 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TOKEN)
35 monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true")
36 monkeypatch.delenv(object_server.TRUSTED_IN_PROCESS_OBJECTS_ENV, raising=False)
37 if mode == POOLED:
38 monkeypatch.setenv(object_server.OBJECT_TIMEOUT_SECONDS_ENV, timeout)
39 monkeypatch.setenv(object_worker_pool.WORKER_POOL_SIZE_ENV, "2")
40 else:
41 monkeypatch.delenv(object_server.OBJECT_TIMEOUT_SECONDS_ENV, raising=False)
42 monkeypatch.delenv(object_worker_pool.WORKER_POOL_SIZE_ENV, raising=False)
43 return data_dir, root
44
45
46def install_real_packages(data_dir, root):
47 for name in ("app-projects", "app-views", "app-notes"):
48 object_packages.install_package(
49 name, root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[root]
50 )
51
52
53async def raw_request(path, method="GET", body=b"", headers=None, accept="text/html"):
54 messages = []
55
56 async def receive():
57 return {"type": "http.request", "body": body, "more_body": False}
58
59 async def send(message):
60 messages.append(message)
61
62 scope_headers = [(b"accept", accept.encode())]
63 for name, value in headers or []:
64 scope_headers.append((name.encode("latin-1"), value.encode("latin-1")))
65 scope = {
66 "type": "http",
67 "method": method,
68 "path": path,
69 "query_string": b"",
70 "headers": scope_headers,
71 "client": ("127.0.0.1", 12345),
72 }
73 await object_server.app(scope, receive, send)
74 start = next(m for m in messages if m["type"] == "http.response.start")
75 payload = b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body")
76 hdrs = {k.decode().lower(): v.decode() for k, v in start["headers"]}
77 return start["status"], hdrs, payload
78
79
80def run(coro_factory):
81 """One event loop for the whole scenario; always shut the pool down on it."""
82
83 async def wrapper():
84 try:
85 return await coro_factory()
86 finally:
87 await object_server._shutdown_worker_pool()
88
89 return asyncio.run(wrapper())
90
91
92ADMIN = [("authorization", f"Token {TOKEN}")]
93
94# Per-request values that legitimately differ between two runs.
95_VOLATILE = [
96 (re.compile(rb"corr_[0-9a-zA-Z_-]+"), b"CORR"),
97 (re.compile(rb"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"), b"UUID"),
98 (re.compile(rb"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z?"), b"TS"),
99 (re.compile(rb'nonce="[^"]*"'), b'nonce="N"'),
100]
101
102
103def normalise(body):
104 for pattern, repl in _VOLATILE:
105 body = pattern.sub(repl, body)
106 return body
107
108
109def stable_headers(hdrs):
110 return {k: v for k, v in hdrs.items()
111 if k in ("content-type", "cache-control", "location", "www-authenticate")}
112
113
114async def notes_scenario():
115 return {
116 "anon": await raw_request("/notes"),
117 "admin": await raw_request("/notes", headers=ADMIN),
118 "admin_missing": await raw_request("/notes/not-a-real-note", headers=ADMIN),
119 }
120
121
122def collect_notes_page(monkeypatch, tmp_path, mode):
123 data_dir, root = configure(monkeypatch, tmp_path / mode, mode)
124 install_real_packages(data_dir, root)
125 return run(notes_scenario)
126
127
128def test_real_notes_page_same_response_in_both_modes(monkeypatch, tmp_path):
129 inproc = collect_notes_page(monkeypatch, tmp_path, IN_PROCESS)
130 pooled = collect_notes_page(monkeypatch, tmp_path, POOLED)
131
132 # Sanity: the admin page is a real rendered page, not an error in both modes.
133 status, hdrs, body = inproc["admin"]
134 assert status == 200, body[:300]
135 assert "text/html" in hdrs["content-type"]
136 assert len(body) > 1000
137
138 for key in inproc:
139 i_status, i_hdrs, i_body = inproc[key]
140 p_status, p_hdrs, p_body = pooled[key]
141 assert p_status == i_status, key
142 assert stable_headers(p_hdrs) == stable_headers(i_hdrs), key
143 assert normalise(p_body) == normalise(i_body), key
144
145
146def test_anonymous_and_admin_differ_the_same_way_in_both_modes(monkeypatch, tmp_path):
147 inproc = collect_notes_page(monkeypatch, tmp_path, IN_PROCESS)
148 pooled = collect_notes_page(monkeypatch, tmp_path, POOLED)
149 # Whatever anonymous gets (redirect/denial/page), it must be what in-process gives,
150 # and it must not be the admin response in either mode.
151 assert pooled["anon"][0] == inproc["anon"][0]
152 assert (pooled["anon"][0], normalise(pooled["anon"][2])) != (
153 pooled["admin"][0], normalise(pooled["admin"][2])
154 ) or inproc["anon"][0] == inproc["admin"][0]
155
156
157ECHO_SOURCE = """
158def GET(request):
159 return {"identity": request.get("_identity"), "keys": sorted(request.keys())}
160"""
161
162
163def collect_identity(monkeypatch, tmp_path, mode):
164 data_dir, root = configure(monkeypatch, tmp_path / mode, mode)
165 install_real_packages(data_dir, root)
166 (root / "basics").mkdir(parents=True, exist_ok=True)
167 (root / "basics" / "echo.py").write_text(ECHO_SOURCE)
168
169 async def scenario():
170 out = {}
171 out["anon"] = await raw_request("/objects/basics_echo", accept="application/json")
172 out["admin"] = await raw_request(
173 "/objects/basics_echo", headers=ADMIN, accept="application/json"
174 )
175 return out
176
177 return run(scenario)
178
179
180def test_identity_payload_is_the_same_in_both_modes(monkeypatch, tmp_path):
181 inproc = collect_identity(monkeypatch, tmp_path, IN_PROCESS)
182 pooled = collect_identity(monkeypatch, tmp_path, POOLED)
183 for key in ("anon", "admin"):
184 assert pooled[key][0] == inproc[key][0], key
185 if inproc[key][0] == 200:
186 i = json.loads(inproc[key][2])
187 p = json.loads(pooled[key][2])
188 assert p == i, key
189 admin = json.loads(pooled["admin"][2])
190 assert admin["identity"]["auth_method"]
191 if inproc["anon"][0] == 200:
192 assert json.loads(pooled["anon"][2])["identity"] != admin["identity"]
193
194
195def test_pool_picks_up_source_edit_of_real_page_object(monkeypatch, tmp_path):
196 """Live edit on a packaged object (site_view_render) between two requests."""
197 results = {}
198 for mode in (IN_PROCESS, POOLED):
199 data_dir, root = configure(monkeypatch, tmp_path / mode, mode)
200 install_real_packages(data_dir, root)
201 source = next(root.rglob("view_render.py"))
202 marker = "<!-- live-edit-marker -->"
203
204 async def scenario(source=source, marker=marker):
205 first = await raw_request("/notes", headers=ADMIN)
206 text = source.read_text()
207 source.write_text(text + f"\n\n_LIVE_EDIT = {marker!r}\n" + _patch_tail(marker))
208 second = await raw_request("/notes", headers=ADMIN)
209 return first, second, marker
210
211 first, second, marker = run(scenario)
212 results[mode] = (first, second, marker)
213
214 for mode, (first, second, marker) in results.items():
215 assert first[0] == 200 and second[0] == 200, mode
216 assert marker.encode() not in first[2], mode
217 assert marker.encode() in second[2], f"{mode}: source edit not picked up"
218
219
220def _patch_tail(marker):
221 # Wrap the module's GET so the rendered HTML carries the marker.
222 return (
223 "_orig_GET = GET\n"
224 "def GET(request):\n"
225 " result = _orig_GET(request)\n"
226 " if isinstance(result, dict):\n"
227 " for key in ('html', 'body', 'content'):\n"
228 " if isinstance(result.get(key), str):\n"
229 " result[key] = result[key] + _LIVE_EDIT\n"
230 " break\n"
231 " elif isinstance(result, str):\n"
232 " result = result + _LIVE_EDIT\n"
233 " return result\n"
234 )
235
236
237def test_raising_object_returns_same_error_shape(monkeypatch, tmp_path):
238 out = {}
239 for mode in (IN_PROCESS, POOLED):
240 data_dir, root = configure(monkeypatch, tmp_path / mode, mode)
241 (root / "basics").mkdir(parents=True, exist_ok=True)
242 (root / "basics" / "broken.py").write_text(
243 "def GET(request):\n raise RuntimeError('boom')\n"
244 )
245
246 async def scenario():
247 return await raw_request("/objects/basics_broken", accept="application/json")
248
249 status, hdrs, body = run(scenario)
250 payload = json.loads(body)
251 # The traceback embeds the (per-mode) tmp path; everything else must match.
252 payload["error"] = payload["error"].replace(str(tmp_path / mode), "<ROOT>")
253 out[mode] = (status, hdrs["content-type"], payload)
254
255 i, p = out[IN_PROCESS], out[POOLED]
256 assert p[0] == i[0] == 500
257 assert p[1] == i[1]
258 assert set(p[2]) == set(i[2])
259 assert p[2]["status"] == i[2]["status"] == "error"
260 assert "RuntimeError: boom" in p[2]["error"]
261 assert "RuntimeError: boom" in i[2]["error"]
262 assert p[2]["error"] == i[2]["error"]
263
264
265def test_timeout_returns_504_and_pool_keeps_serving(monkeypatch, tmp_path):
266 data_dir, root = configure(monkeypatch, tmp_path, POOLED, timeout="0.5")
267 install_real_packages(data_dir, root)
268 (root / "basics").mkdir(parents=True, exist_ok=True)
269 (root / "basics" / "slow.py").write_text(
270 "import time\n\ndef GET(request):\n time.sleep(5)\n return {'ok': True}\n"
271 )
272 (root / "basics" / "fast.py").write_text("def GET(request):\n return {'ok': True}\n")
273
274 async def scenario():
275 slow = await raw_request("/objects/basics_slow", accept="application/json")
276 slow_again = await raw_request("/objects/basics_slow", accept="application/json")
277 fast = await raw_request("/objects/basics_fast", accept="application/json")
278 page = await raw_request("/notes", headers=ADMIN)
279 return slow, slow_again, fast, page
280
281 slow, slow_again, fast, page = run(scenario)
282 assert slow[0] == 504 and slow_again[0] == 504
283 assert json.loads(slow[2])["error"] == (
284 "Execution failed: GET timed out for object basics_slow after 0.5 seconds"
285 )
286 assert fast[0] == 200 and json.loads(fast[2]) == {"ok": True}
287 assert page[0] == 200 and b"<" in page[2]