1 #!/usr/bin/env python3
2 """Prove the store bundle answers the page through the stdlib framework.
3 4 Serves the built bundle directory (store.wasm, the emitted $runtime/, the app's
5 store-bridge.mjs), loads a page that starts it with startBundle, and speaks the
6 store's own JSON-array protocol: a KV put, a KV get, a KV get-all. Both
7 directions have to work - the page must receive the module's SR_* replies, and
8 the module must receive the page's requests - so a bundle that boots but cannot
9 be talked to fails here rather than looking healthy.
10 11 Usage: store-bundle-test.py [--dir DIR]
12 """
13 import functools, http.server, json, pathlib, socketserver, sys, threading
14 15 try:
16 from playwright.sync_api import sync_playwright
17 except ImportError:
18 print("playwright is required: pip install playwright")
19 sys.exit(2)
20 21 DIR = pathlib.Path(sys.argv[sys.argv.index("--dir") + 1]) if "--dir" in sys.argv else pathlib.Path("/tmp/smesh-store-proof")
22 23 PAGE = """<!DOCTYPE html><html><body><script type="module">
24 const { startBundle } = await import('./$runtime/host.mjs');
25 const b = startBundle('./store.wasm', { appBridge: './store-bridge.mjs' });
26 const waits = new Map();
27 const seen = [];
28 const items = [];
29 let getAllResolve = null;
30 const getAllDone = new Promise((r) => { getAllResolve = r; });
31 let readyResolve = null;
32 const readyReply = new Promise((r) => { readyResolve = r; });
33 b.port.onmessage = (e) => {
34 const msg = JSON.parse(String(e.data));
35 seen.push(msg[0]);
36 if (msg[0] === 'SR_READY' && readyResolve) readyResolve();
37 if (msg[0] === 'SR_KV_GETALL_ITEM') items.push([msg[2], msg[3]]);
38 if (msg[0] === 'SR_KV_GETALL_DONE' && getAllResolve) getAllResolve();
39 if (waits.has(msg[1])) { waits.get(msg[1])(msg); waits.delete(msg[1]); }
40 };
41 const request = (arr, rid) => new Promise((res) => {
42 waits.set(rid, res);
43 b.port.postMessage(JSON.stringify(arr));
44 setTimeout(() => { if (waits.delete(rid)) res(null); }, 8000);
45 });
46 const out = { replies: seen };
47 try {
48 await b.ready;
49 // SR_READY is the store's own ready signal: the module posts it once its
50 // IndexedDB connection is open, which is later than b.ready (that resolves
51 // when main returns, before the open completes). Sending before it would be
52 // racing the app's own contract - and the first version of this test did
53 // exactly that, which is why the put vanished.
54 await Promise.race([readyReply, new Promise((r) => setTimeout(r, 8000))]);
55 b.port.postMessage(JSON.stringify(['S_KV_PUT', 'settings', 'probe', 'hello-from-page']));
56 const got = await request(['S_KV_GET', 1, 'settings', 'probe'], 1);
57 out.kv = got ? got[2] : null;
58 // The walk pushes items and ends with a done reply, so the page collects them
59 // in the message handler instead of re-awaiting a promise that has already
60 // resolved - which is what the first version did, looping forever on the same
61 // item and freezing the page.
62 b.port.postMessage(JSON.stringify(['S_KV_GETALL', 2, 'settings']));
63 await Promise.race([getAllDone, new Promise(r => setTimeout(r, 5000))]);
64 out.kvAll = items;
65 out.replies = seen;
66 out.ok = true;
67 } catch (e) {
68 out.error = String((e && e.stack) || e);
69 }
70 window.__store = out;
71 window.__done = true;
72 </script></body></html>"""
73 74 75 class Handler(http.server.SimpleHTTPRequestHandler):
76 def do_GET(self):
77 if self.path in ("/", "/index.html"):
78 body = PAGE.encode()
79 self.send_response(200)
80 self.send_header("Content-Type", "text/html")
81 self.send_header("Content-Length", str(len(body)))
82 self.end_headers()
83 self.wfile.write(body)
84 return
85 super().do_GET()
86 87 def end_headers(self):
88 self.send_header("Cross-Origin-Opener-Policy", "same-origin")
89 self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
90 super().end_headers()
91 92 def log_message(self, *a):
93 pass
94 95 96 def main():
97 if not (DIR / "store.wasm").exists():
98 print(f"no store.wasm in {DIR}")
99 return 1
100 srv = socketserver.TCPServer(("127.0.0.1", 0), functools.partial(Handler, directory=str(DIR)))
101 srv.allow_reuse_address = True
102 port = srv.server_address[1]
103 threading.Thread(target=srv.serve_forever, daemon=True).start()
104 with sync_playwright() as pw:
105 browser = pw.chromium.launch()
106 page = browser.new_page()
107 page.on("console", lambda m: print(" console: " + m.text))
108 page.goto(f"http://127.0.0.1:{port}/", wait_until="load")
109 page.wait_for_function("window.__done === true", timeout=30000)
110 out = page.evaluate("() => window.__store")
111 browser.close()
112 srv.shutdown()
113 print(" store bundle said: " + json.dumps(out))
114 if not out or not out.get("ok"):
115 print("FAIL: the store bundle did not complete the exchange")
116 return 1
117 if out.get("kv") != "hello-from-page":
118 print("FAIL: KVGet did not return what KVPut stored")
119 return 1
120 if ["probe", "hello-from-page"] not in (out.get("kvAll") or []):
121 print("FAIL: KVGetAll did not walk the store")
122 return 1
123 if "SR_READY" not in (out.get("replies") or []):
124 print("FAIL: the page never received the worker's ready reply")
125 return 1
126 print("PASS: the store bundle answers the page through the stdlib framework")
127 return 0
128 129 130 if __name__ == "__main__":
131 sys.exit(main())
132