aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests/harness/playlist_store_probe.py
blob: 83c00adc64218c3d76a02df1bcf5730024feac37 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#!/usr/bin/env python3
"""
The playlist store, driven in a real browser against a fake node.

`playlist-merge.js` and `playlist-crypto.js` are pure and are executed by their
own tests. `playlists.js` is neither: it is IndexedDB, WebCrypto and a
transport, and node has no IndexedDB at all. So this runs the shipped module in
Chrome, with a node stubbed to record what it was handed — which is also the
only way to check that what leaves the browser is sealed.

    playlist_store_probe.py

Prints JSON: one entry per step.
"""
import http.server
import json
import socketserver
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path

STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static"
PORT = 8753
RECORDS = []
socketserver.TCPServer.allow_reuse_address = True

FRAME = r"""<!doctype html><html><head><meta charset=utf-8></head><body>
<div id="root"></div>
<script type="module">
import { session } from '/hub-client.js';
import * as P from '/playlists.js';
import { open, seal, derivePlaylistKey } from '/playlist-crypto.js';
import { MANIFEST_KIND, bodyKind } from '/playlist-merge.js';

const LOGS = [];
addEventListener('error', (e) => LOGS.push('error: ' + (e.message || e)));
addEventListener('unhandledrejection',
  (e) => LOGS.push('rejection: ' + ((e.reason && (e.reason.stack || e.reason.message)) || e.reason)));

const USER = 'user-1';
const steps = [];

// A track as the views hand it over, live junk and all: the Search page
// attaches a transport and a CryptoKey to every entry it renders.
const track = (n, group) => ({
  id: 'hash-' + n, name: `${n} - Titre.flac`, display_title: `Titre ${n}`,
  path: 'Artiste/Album', size: 1000 + n, type: 'audio', duration: 200 + n,
  artist: 'Artiste', album: 'Album', track_no: n, hash_version: 1,
  groupId: group || 'g1',
  _tRef: { live: 'transport' }, _gRef: { key: true }, _origPath: 'elsewhere',
});

// The node: records everything, answers with whatever it has been given.
function fakeNode() {
  const rows = new Map();
  return {
    connected: true,
    rows,
    stored: [],
    async fetchUserBlob(kind) {
      const r = rows.get(kind);
      return r ? { rev: r.rev, blob_enc: r.blob } : { rev: null, blob_enc: null };
    },
    async storeUserBlob(kind, rev, blob) {
      rows.set(kind, { rev, blob });
      this.stored.push({ kind, rev, bytes: blob.length });
      return { type: 'ack' };
    },
    async listUserBlobs() {
      return [...rows.entries()].map(([kind, r]) => ({ kind, rev: r.rev }));
    },
    async deleteUserBlob(kind) { rows.delete(kind); return { type: 'ack' }; },
  };
}

(async () => {
  const fail = (why) => parent.postMessage({ error: why, logs: LOGS.slice(0, 10) }, '*');
  try {
    // A real HKDF handle over fixed bytes, as `deriveBundleKeys` would produce
    // — the point is that playlists.js gets its key the way it really does.
    const raw = new Uint8Array(32).fill(5);
    session.bundleKey = {
      v2: await crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false,
                                        ['encrypt', 'decrypt']),
      v2hkdf: await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']),
    };
    const key = await derivePlaylistKey(session.bundleKey.v2hkdf);

    // ── local editing ──────────────────────────────────────────────────────
    const eveningId = await P.createPlaylist(USER, 'Soirée');
    await P.addTracks(USER, eveningId, [track(1), track(2)], 'g1');
    await P.addTracks(USER, P.FAVORITES_ID, [track(9)], 'g1', 'Favoris');

    steps.push({ step: 'after editing',
                 list: (await P.listPlaylists(USER)).map((p) => ({ id: p.id, name: p.name, count: p.count })) });

    steps.push({ step: 'tracks read back',
                 tracks: (await P.getPlaylistTracks(USER, eveningId)).map((t) => ({
                   id: t.id, name: t.name, size: t.size, groupId: t.groupId,
                   title: t.display_title })) });

    // Favourites is a toggle, not an append.
    const again = await P.addTracks(USER, P.FAVORITES_ID, [track(9)], 'g1');
    const favTwice = await P.getPlaylistTracks(USER, P.FAVORITES_ID);
    steps.push({ step: 'favourites is idempotent', added: again, count: favTwice.length });

    // An ordinary playlist takes the same track twice, because real ones do.
    await P.addTracks(USER, eveningId, [track(1)], 'g1');
    steps.push({ step: 'an ordinary playlist takes duplicates',
                 count: (await P.getPlaylistTracks(USER, eveningId)).length });

    let dup = null;
    try { await P.createPlaylist(USER, 'soiree'); } catch (e) { dup = e.message; }
    steps.push({ step: 'a folded duplicate name is refused', why: dup });

    let fav = null;
    try { await P.deletePlaylist(USER, P.FAVORITES_ID); } catch (e) { fav = e.message; }
    steps.push({ step: 'favourites cannot be deleted', why: fav });

    // ── sync ───────────────────────────────────────────────────────────────
    const node = fakeNode();
    const r1 = await P.syncWith(node, USER);
    steps.push({ step: 'first sync', result: r1,
                 kinds: node.stored.map((s) => s.kind).sort() });

    // What actually left the browser: sealed, and openable only with the key.
    const manifestRow = node.rows.get(MANIFEST_KIND);
    const hay = new TextDecoder('latin1').decode(manifestRow.blob);
    const opened = await open(manifestRow.blob, MANIFEST_KIND, USER, key);
    steps.push({
      step: 'what the node holds',
      leaks: ['Soirée', 'Favoris', 'playlists', 'Titre'].filter((s) => hay.includes(s)),
      names: Object.values(opened.playlists).map((p) => p.name).sort(),
    });

    // Syncing again with nothing changed must not rewrite anything.
    node.stored.length = 0;
    const r2 = await P.syncWith(node, USER);
    steps.push({ step: 'second sync is quiet', result: r2,
                 wrote: node.stored.length });

    // ── a node that went away and came back with an older copy ─────────────
    //
    // The rollback case: the local copy is one of the merge inputs, so a stale
    // node can only lose. It must never lower what this browser holds.
    const stale = fakeNode();
    const oldManifest = { v: 1, rev: 1, playlists: {
      [eveningId]: { name: 'Soirée', rev: 1, body_rev: 1, count: 1,
                     device: 'other', updated_at: 99, deleted: false } } };
    stale.rows.set(MANIFEST_KIND, {
      rev: 1, blob: await seal(oldManifest, MANIFEST_KIND, USER, key) });
    await P.syncWith(stale, USER);
    steps.push({
      step: 'a stale node cannot lower anything',
      list: (await P.listPlaylists(USER)).map((p) => ({ id: p.id, count: p.count })),
      tracks: (await P.getPlaylistTracks(USER, eveningId)).length,
    });

    // ── a node with an edit this browser has not seen ──────────────────────
    const ahead = fakeNode();
    const driveId = 'drive-from-elsewhere';
    const newer = { v: 1, rev: 9, playlists: {
      ...JSON.parse(JSON.stringify(oldManifest.playlists)),
      [driveId]: { name: 'Route', rev: 4, body_rev: 2, count: 3,
                   device: 'aaa-other-device', updated_at: 5, deleted: false } } };
    ahead.rows.set(MANIFEST_KIND, {
      rev: 9, blob: await seal(newer, MANIFEST_KIND, USER, key) });
    ahead.rows.set(bodyKind(driveId), { rev: 2, blob: await seal(
      { v: 1, id: driveId, rev: 2, device: 'aaa-other-device',
        tracks: [{ id: 'r1', g: 'g2', hv: 1, n: 'a.flac', s: 5, p: 'X',
                   t: 'Route 1', a: 'A', b: 'B', d: 100, tn: 1 }] },
      bodyKind(driveId), USER, key) });
    await P.syncWith(ahead, USER);
    steps.push({
      step: 'an edit made elsewhere arrives',
      list: (await P.listPlaylists(USER)).map((p) => p.name).sort(),
      routeTracks: (await P.getPlaylistTracks(USER, driveId)).map((t) => t.display_title),
    });

    // ── deletion survives a node that still has it ─────────────────────────
    await P.deletePlaylist(USER, eveningId);
    const resurrector = fakeNode();
    resurrector.rows.set(MANIFEST_KIND, {
      rev: 2, blob: await seal(oldManifest, MANIFEST_KIND, USER, key) });
    await P.syncWith(resurrector, USER);
    steps.push({
      step: 'a deletion is not resurrected',
      list: (await P.listPlaylists(USER)).map((p) => p.name).sort(),
    });

    // And the body it left behind is reclaimed, on every node as it is
    // reached — otherwise the account's quota fills up with graves.
    const holder = fakeNode();
    holder.rows.set(bodyKind(eveningId), { rev: 3, blob: new Uint8Array([1, 2, 3]) });
    holder.rows.set(MANIFEST_KIND, {
      rev: 1, blob: await seal({ v: 1, rev: 1, playlists: {} }, MANIFEST_KIND, USER, key) });
    await P.syncWith(holder, USER);
    steps.push({
      step: 'a deleted body is reclaimed',
      stillThere: holder.rows.has(bodyKind(eveningId)),
    });

    // ── every mutation reaches a node, not just the one that used to ──────
    //
    // The defect this exists for: `syncWith` was called from exactly one place
    // in the interface, so creating a playlist, deleting one, removing a track
    // and saving the queue all wrote to IndexedDB and stopped there. A second
    // device saw nothing — which is the one thing playlists are for. Found in
    // the node's own audit log: two events, ever.
    const auto = fakeNode();
    P.setPlaylistTransport(async () => auto);
    const seen = () => auto.stored.map((s) => s.kind).sort();
    const wait = () => new Promise((r) => setTimeout(r, 2300));  // > the debounce

    const p1 = await P.createPlaylist(USER, 'Depuis le menu');
    await wait();
    steps.push({ step: 'create pushes', kinds: seen() });

    auto.stored.length = 0;
    await P.addTracks(USER, p1, [track(21)], 'g1');
    await wait();
    steps.push({ step: 'add pushes', kinds: seen() });

    auto.stored.length = 0;
    await P.removeTrackAt(USER, p1, 0);
    await wait();
    steps.push({ step: 'remove pushes', kinds: seen() });

    auto.stored.length = 0;
    const p2 = await P.saveQueueAsPlaylist(USER, 'Depuis la file', [track(31), track(32)]);
    await wait();
    steps.push({ step: 'save-queue pushes', kinds: seen() });

    auto.stored.length = 0;
    await P.deletePlaylist(USER, p2);
    await wait();
    steps.push({ step: 'delete pushes', kinds: seen(),
                 bodyGone: !auto.rows.has(bodyKind(p2)) });

    // A burst is one push, not one per write.
    auto.stored.length = 0;
    for (let i = 0; i < 5; i++) await P.addTracks(USER, p1, [track(40 + i)], 'g1');
    await wait();
    steps.push({ step: 'a burst is coalesced', writes: auto.stored.length });

    // ── a push that does not land is retried, once ────────────────────────
    //
    // Shortened from twenty seconds: a retry nobody can wait for is a retry
    // nobody has checked, and this feature has already shipped one whole path
    // that no test ever called.
    P.setPushTimings({ debounceMs: 100, retryMs: 400 });
    let refuse = true;
    const flaky = fakeNode();
    const flakyStore = flaky.storeUserBlob.bind(flaky);
    flaky.storeUserBlob = async (...a) => {
      if (refuse) throw new Error('Server busy, retry shortly');
      return flakyStore(...a);
    };
    // Sync *passes*, not store calls: one pass writes a body per playlist plus
    // the manifest, so counting writes says nothing about how many times the
    // push was attempted — which is the whole question for "does it loop".
    // Every pass begins with exactly one listing.
    let passes = 0;
    const flakyList = flaky.listUserBlobs.bind(flaky);
    flaky.listUserBlobs = async (...a) => { passes++; return flakyList(...a); };
    P.setPlaylistTransport(async () => flaky);

    await P.addTracks(USER, p1, [track(50)], 'g1');
    await new Promise((r) => setTimeout(r, 250));
    const afterFirst = { stored: flaky.stored.length, last: P.lastSync() };
    refuse = false;                       // the node comes back
    await new Promise((r) => setTimeout(r, 900));
    steps.push({ step: 'a failed push is retried once',
                 afterFirstTry: afterFirst.stored,
                 firstReason: afterFirst.last.reason,
                 afterRetry: flaky.stored.length,
                 ok: P.lastSync().ok });

    // ── and only once ─────────────────────────────────────────────────────
    refuse = true;
    flaky.stored.length = 0;
    passes = 0;
    await P.addTracks(USER, p1, [track(51)], 'g1');
    await new Promise((r) => setTimeout(r, 2000));   // room for four retries
    steps.push({ step: 'a retry does not loop',
                 stored: flaky.stored.length, passes });

    // ── closing the page sends what is pending ────────────────────────────
    refuse = false;
    P.setPushTimings({ debounceMs: 60000, retryMs: 60000 });   // never on its own
    flaky.stored.length = 0;
    await P.addTracks(USER, p1, [track(52)], 'g1');
    const beforeFlush = flaky.stored.length;
    await P.flushPush();
    steps.push({ step: 'flush sends a pending push',
                 beforeFlush, afterFlush: flaky.stored.length });
    P.setPushTimings({ debounceMs: 100, retryMs: 400 });

    // ── a fresh device finds them ─────────────────────────────────────────
    //
    // What the phone did not do. `auto` now holds this account's playlists; a
    // browser that has never seen them must end up with them.
    P.setPlaylistTransport(async () => auto);
    const before = (await P.listPlaylists(USER)).length;
    await P.forgetLocal(USER);
    const emptied = (await P.listPlaylists(USER)).length;
    const pulled = await P.pullOnce(USER);
    steps.push({ step: 'a fresh device pulls once',
                 before, emptied, result: pulled,
                 lists: (await P.listPlaylists(USER)).map((p) => p.name).sort() });

    // A device that already holds playlists must pull too. Bounding this to an
    // empty device left out the ordinary case — nine playlists here, a tenth
    // made somewhere else — which would then have waited for a Music tab.
    const elsewhere = fakeNode();
    const mani = { v: 1, rev: 50, playlists: {
      'made-elsewhere': { name: 'Faite ailleurs', rev: 9, body_rev: 1, count: 1,
                          device: 'aaa', updated_at: 1, deleted: false } } };
    elsewhere.rows.set(MANIFEST_KIND, {
      rev: 50, blob: await seal(mani, MANIFEST_KIND, USER, key) });
    elsewhere.rows.set(bodyKind('made-elsewhere'), { rev: 1, blob: await seal(
      { v: 1, id: 'made-elsewhere', rev: 1, device: 'aaa',
        tracks: [{ id: 'z1', g: 'g9', hv: 1, n: 'z.flac', s: 1, p: 'P',
                   t: 'Ailleurs', a: 'A', b: 'B', d: 1, tn: 1 }] },
      bodyKind('made-elsewhere'), USER, key) });
    P.setPlaylistTransport(async () => elsewhere);
    const held = (await P.listPlaylists(USER)).length;
    const pulled2 = await P.pullOnce(USER);
    steps.push({ step: 'a device that already has playlists pulls too',
                 held, result: pulled2,
                 found: (await P.listPlaylists(USER)).map((p) => p.name).sort() });
    P.setPlaylistTransport(async () => auto);

    // ── a node holding something this browser cannot read ─────────────────
    //
    // The defect that made the phone report land: `open()` throwing on the
    // node's manifest was treated as a fetch failure and returned before the
    // push. The first write landed because the node was empty; every sync
    // after it took that path and pushed nothing, for ever. Unreadable is an
    // absence, not an error — the client is the authority.
    const junkKey = await crypto.subtle.importKey(
      'raw', new Uint8Array(32).fill(200), { name: 'AES-GCM' }, false,
      ['encrypt', 'decrypt']);
    const wedged = fakeNode();
    wedged.rows.set(MANIFEST_KIND, {
      rev: 1,
      blob: await seal({ v: 1, rev: 1, playlists: {} },
                       MANIFEST_KIND, USER, junkKey) });
    const wedgedResult = await P.syncWith(wedged, USER);
    let readBack = null;
    try {
      readBack = await open(wedged.rows.get(MANIFEST_KIND).blob,
                            MANIFEST_KIND, USER, key);
    } catch { /* still unreadable means it was not overwritten */ }
    steps.push({
      step: 'an unreadable manifest does not wedge the sync',
      result: wedgedResult,
      overwritten: !!readBack,
      names: readBack ? Object.values(readBack.playlists).map((p) => p.name).sort() : [],
    });

    // ── what a playlist costs, sealed ─────────────────────────────────────
    //
    // The cap below is in bytes, but the only number a reader can act on is a
    // number of tracks — so it is measured here rather than quoted from the
    // design doc. (Quoting it is how "225 tracks" got written down: §4's
    // figure is ~270 bytes a track *raw* and ~60 *sealed*, and the raw one was
    // read for the sealed one.)
    //
    // Varied metadata on purpose. A fixture where every track shares an artist
    // and an album measures deflate's opinion of its own regularity: the first
    // attempt at this, 400 tracks differing only by id, sealed to 41 bytes a
    // track and would have let the case below pass while testing nothing.
    const WORDS = ['aube', 'ciel', 'verre', 'nord', 'ombre', 'pluie', 'fer',
                   'sel', 'onze', 'rive', 'brume', 'cendre', 'axe', 'lune'];
    const hex = (n) => [...crypto.getRandomValues(new Uint8Array(n))]
      .map((b) => b.toString(16).padStart(2, '0')).join('');
    const word = () => WORDS[Math.floor(Math.random() * WORDS.length)];
    const storedTrack = (i) => {
      const artist = `${word()} ${word()}`;
      const album = `${word()} ${word()} ${1970 + (i % 50)}`;
      const title = `${word()} ${word()} ${word()}`;
      return { id: hex(16), g: 'g1', hv: 1, n: `${i % 20} - ${title}.flac`,
               s: 30000000 + i, p: `${artist}/${album}`, t: title, a: artist,
               b: album, d: 180 + (i % 300), tn: (i % 20) + 1 };
    };
    const sizes = {};
    for (const n of [100, 500, 1000]) {
      const tracks = [];
      for (let i = 0; i < n; i++) tracks.push(storedTrack(i));
      const sealed = await seal({ v: 1, id: 'measure', rev: 1, device: 'aaa', tracks },
                                bodyKind('measure'), USER, key);
      sizes[n] = sealed.length;
    }
    steps.push({ step: 'what a playlist costs sealed', sizes });

    // ── a playlist too large for one frame is named, not swallowed ────────
    //
    // A DataChannel `send()` throws above the max-message-size the far end
    // advertised, which for the node's aiortc is 65536 — so the node's 1 MB
    // body cap is unreachable and the real limit is a count of tracks
    // (docs/playlists.md §15.3). The push used to swallow every per-body
    // failure in one bare `catch {}`: the playlist stopped leaving the browser
    // and nothing anywhere said so, which is the silent loss this design
    // exists to prevent.
    const bigNode = fakeNode();
    const longId = await P.createPlaylist(USER, 'Trop longue');
    const many = [];
    for (let i = 0; i < 1500; i++) {
      const st = storedTrack(i);
      many.push({ ...track(i), id: st.id, name: st.n, display_title: st.t,
                  path: st.p, artist: st.a, album: st.b, duration: st.d });
    }
    await P.addTracks(USER, longId, many, 'g1');
    const bigResult = await P.syncWith(bigNode, USER);
    steps.push({ step: 'a playlist too large for one frame',
                 result: bigResult,
                 bigKind: bodyKind(longId),
                 // Everything else must still have gone: one oversized
                 // playlist is not a broken sync.
                 stored: bigNode.stored.map((e) => ({ kind: e.kind, bytes: e.bytes })) });

    // ── a session with no HKDF handle degrades rather than failing ─────────
    P.setPlaylistTransport(null);
    P.forgetPlaylistKey();
    session.bundleKey = { v2: session.bundleKey.v2 };   // pre-change session
    const r3 = await P.syncWith(fakeNode(), USER);
    steps.push({ step: 'a session from before the HKDF handle', result: r3 });

    parent.postMessage({ steps, logs: LOGS.slice(0, 8) }, '*');
  } catch (err) {
    fail(String((err && err.stack) || err));
  }
})();
</script></body></html>"""

PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head>
<body style="margin:0"><div id="frames"></div><script>
addEventListener('message', (e) => {
  fetch('/log', { method: 'POST', body: JSON.stringify(e.data) });
});
const f = document.createElement('iframe');
f.src = '/case';
f.style.cssText = 'width:900px;height:600px;border:0;display:block';
document.getElementById('frames').appendChild(f);
</script></body></html>"""


class H(http.server.BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def do_POST(self):
        length = int(self.headers.get("Content-Length") or 0)
        if self.path == "/log":
            RECORDS.append(json.loads(self.rfile.read(length).decode()))
        else:
            self.rfile.read(length)
        self.send_response(204)
        self.end_headers()

    def _send(self, body: bytes, ctype: str) -> None:
        self.send_response(200)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path = self.path.split("?")[0]
        if path == "/":
            self._send(PAGE.encode(), "text/html; charset=utf-8")
        elif path == "/case":
            self._send(FRAME.encode(), "text/html; charset=utf-8")
        else:
            asset = (STATIC / path.lstrip("/")).resolve()
            if not str(asset).startswith(str(STATIC)) or not asset.is_file():
                self.send_response(404)
                self.end_headers()
                return
            self._send(asset.read_bytes(),
                       "text/css" if asset.suffix == ".css"
                       else "text/javascript" if asset.suffix == ".js"
                       else "application/octet-stream")


def main() -> int:
    with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv:
        threading.Thread(target=srv.serve_forever, daemon=True).start()
        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile:
            proc = subprocess.Popen(
                ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox",
                 f"--user-data-dir={profile}", "--window-size=900,700",
                 f"http://127.0.0.1:{PORT}/"],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            for _ in range(400):
                if RECORDS:
                    break
                time.sleep(0.1)
            proc.terminate()
            try:
                proc.wait(timeout=10)
            except subprocess.TimeoutExpired:
                proc.kill()
                proc.wait()
    if not RECORDS:
        print(json.dumps({"error": "no measurement"}), file=sys.stderr)
        return 1
    print(json.dumps(RECORDS[0], indent=1))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())