Elffuss BraidHub

utopia-ia/elffuss-code public

a173c6d98b7c · 3.5 KiBRawPermalink
1// Verifica la caché de modelos por service worker: descarga una vez, se sirve
2// desde Cache Storage (incluso OFFLINE) y soporta range requests. Usa un fixture
3// .litertlm determinista (byte[i] = i%256) para no bajar los GB reales.
4import { chromium } from 'playwright';
5import { CHROME_ARGS } from './chrome-args.mjs';
6import { writeFileSync, rmSync } from 'node:fs';
7import { fileURLToPath } from 'node:url';
8import { dirname, join } from 'node:path';
9const BASE = process.env.BASE || 'http://localhost:8799';
10const FIX = BASE + '/__test_fixture.litertlm';
11const SIZE = 100000;
12let fails = 0;
13const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
14
15// fixture determinista (byte[i]=i%256) en web/, autolimpiado al terminar
16const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web');
17const FIXPATH = join(WEB, '__test_fixture.litertlm');
18writeFileSync(FIXPATH, Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256)));
19const cleanup = () => { try { rmSync(FIXPATH); } catch {} };
20process.on('exit', cleanup);
21
22const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', ...CHROME_ARGS] });
23const ctx = await b.newContext();
24await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
25const p = await ctx.newPage({ viewport: { width: 1200, height: 800 } });
26await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
27
28// esperar a que el SW controle la página
29const controlled = await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller != null, null, { timeout: 10000 }).then(() => true).catch(() => false);
30ok('el service worker controla la página', controlled);
31
32const fetchInfo = (u, opts) => p.evaluate(async ({ u, opts }) => {
33 const r = await fetch(u, opts);
34 const buf = new Uint8Array(await r.arrayBuffer());
35 return { status: r.status, len: buf.length, cr: r.headers.get('content-range'), first: [...buf.slice(0, 4)], sample: [...buf.slice(0, 12)] };
36}, { u, opts });
37
38// 1) primera descarga (el SW baja el fichero completo y lo cachea)
39const r1 = await fetchInfo(FIX);
40ok('primera petición devuelve el fichero completo', r1.status === 200 && r1.len === SIZE, `status ${r1.status}, ${r1.len}B`);
41
42// 2) OFFLINE: si está cacheado, se sigue sirviendo sin red
43await ctx.setOffline(true);
44const r2 = await fetchInfo(FIX).catch(e => ({ status: 0, err: String(e) }));
45ok('OFFLINE se sirve desde la caché (prueba de que quedó cacheado)', r2.status === 200 && r2.len === SIZE, `status ${r2.status}, ${r2.len}B`);
46
47// 3) range request servido desde el blob cacheado (bytes 10..19)
48const r3 = await fetchInfo(FIX, { headers: { Range: 'bytes=10-19' } });
49const expected = Array.from({ length: 10 }, (_, i) => (10 + i) % 256);
50ok('range request → 206 con los bytes correctos', r3.status === 206 && r3.len === 10 && JSON.stringify(r3.sample.slice(0, 10)) === JSON.stringify(expected), `status ${r3.status}, cr=${r3.cr}, bytes=${r3.sample}`);
51await ctx.setOffline(false);
52
53// 4) el estimate reporta uso (>0) tras cachear
54const est = await p.evaluate(() => navigator.storage.estimate().then(e => ({ usage: e.usage, persisted: null })).catch(() => ({ usage: 0 })));
55ok('storage.estimate refleja el uso cacheado', est.usage > 0, `${(est.usage / 1024 / 1024).toFixed(1)} MB`);
56
57console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — descarga 1 vez, persiste y sirve offline + ranges');
58await b.close();
59process.exit(fails ? 1 : 0);