| 1 | // Caché de modelos: se baja UNA vez a disco y después se sirve sin red. |
| 2 | // |
| 3 | // Era la prueba del service worker que guardaba los modelos en Cache Storage. |
| 4 | // Ese service worker es inerte desde 75adafc (rompía la carga de ONNX) y los |
| 5 | // pesos se guardan ahora en el almacén de modelos (runtime/model-store.js): la |
| 6 | // caché compartida del broker y, si no está, la OPFS de este origen. Esto prueba |
| 7 | // ese camino con la OPFS: descarga una vez, sirve desde disco sin tocar la red, |
| 8 | // los bytes son los del original, se lee por rangos y no deja la marca de |
| 9 | // «completo» hasta que lo está. |
| 10 | // |
| 11 | // El fichero es de mentira (page.route, byte[i] = i % 251) y el broker se da por |
| 12 | // caído, así que no sale nada a la red. |
| 13 | // |
| 14 | // BASE=http://localhost:8799 node tests/modelcache.mjs |
| 15 | import { chromium } from 'playwright'; |
| 16 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 17 | const FIX = BASE + '/__modelcache_fixture.litertlm'; |
| 18 | const SIZE = 300000; |
| 19 | let fails = 0; |
| 20 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 21 | |
| 22 | const DATOS = Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 251)); |
| 23 | const peticiones = []; |
| 24 | const b = await chromium.launch(); |
| 25 | const ctx = await b.newContext(); |
| 26 | await ctx.addInitScript(() => { |
| 27 | try { localStorage.setItem('elffusscode.model', 'rules'); sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ } |
| 28 | }); |
| 29 | const p = await ctx.newPage({ viewport: { width: 1200, height: 800 } }); |
| 30 | await p.route('**/__modelcache_fixture.litertlm', route => { |
| 31 | const rango = route.request().headers().range || ''; |
| 32 | peticiones.push(rango || 'entero'); |
| 33 | const m = /bytes=(\d+)-(\d*)/.exec(rango); |
| 34 | if (!m) return route.fulfill({ status: 200, body: DATOS, headers: { 'content-type': 'application/octet-stream', 'accept-ranges': 'bytes' } }); |
| 35 | const desde = +m[1], hasta = m[2] ? +m[2] : SIZE - 1; |
| 36 | return route.fulfill({ status: 206, body: DATOS.subarray(desde, hasta + 1), |
| 37 | headers: { 'content-type': 'application/octet-stream', 'accept-ranges': 'bytes', 'content-range': `bytes ${desde}-${hasta}/${SIZE}` } }); |
| 38 | }); |
| 39 | await p.goto(BASE + '/manifest.json'); |
| 40 | |
| 41 | const baja = () => p.evaluate(async u => { |
| 42 | const m = await import('/js/runtime/model-store.js'); |
| 43 | const msgs = []; |
| 44 | const f = await m.getModelFile(u, s => msgs.push(typeof s === 'string' ? s : JSON.stringify(s))); |
| 45 | if (!f) return { nulo: true, msgs }; |
| 46 | const buf = new Uint8Array(await f.arrayBuffer()); |
| 47 | let malos = 0; for (let i = 0; i < buf.length; i++) if (buf[i] !== i % 251) malos++; |
| 48 | return { size: f.size, malos, primero: msgs[0] || '', ultimo: msgs.at(-1) || '' }; |
| 49 | }, FIX); |
| 50 | |
| 51 | // 1) primera vez: se baja y queda en disco, entero y marcado como completo |
| 52 | const r1 = await baja(); |
| 53 | ok('primera vez: devuelve el modelo entero', r1.size === SIZE && r1.malos === 0, JSON.stringify(r1)); |
| 54 | const enDisco = await p.evaluate(async () => { |
| 55 | const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); |
| 56 | const out = []; |
| 57 | for await (const [n, h] of dir.entries()) out.push(n + ':' + (h.kind === 'file' ? (await h.getFile()).size : 'dir')); |
| 58 | return out; |
| 59 | }); |
| 60 | ok('queda en la OPFS del origen, con su marca de completo', enDisco.some(x => x.endsWith('.litertlm:' + SIZE)) && enDisco.some(x => /\.done:/.test(x)), JSON.stringify(enDisco)); |
| 61 | ok(' …y la descarga sí pasó por la red', peticiones.length > 0, JSON.stringify(peticiones)); |
| 62 | |
| 63 | // 2) segunda vez SIN RED: sale del disco y no hace ninguna petición |
| 64 | peticiones.length = 0; |
| 65 | await ctx.setOffline(true); |
| 66 | const r2 = await baja(); |
| 67 | await ctx.setOffline(false); |
| 68 | ok('segunda vez sin red: sale del disco, con los mismos bytes', r2.size === SIZE && r2.malos === 0, JSON.stringify(r2)); |
| 69 | ok(' …sin una sola petición', peticiones.length === 0, JSON.stringify(peticiones)); |
| 70 | ok(' …y lo dice («desde disco, sin descargar»)', /desde disco/.test(r2.primero), r2.primero); |
| 71 | |
| 72 | // 3) lectura por rangos desde el disco (la usa el motor por trozos) |
| 73 | const trozo = await p.evaluate(async u => { |
| 74 | const m = await import('/js/runtime/model-store.js'); |
| 75 | const r = await m.openRanged(u); |
| 76 | return { size: r.size, bytes: [...new Uint8Array(await r.slice(1000, 8))] }; |
| 77 | }, FIX); |
| 78 | const esperado = Array.from({ length: 8 }, (_, i) => (1000 + i) % 251); |
| 79 | ok('lectura por rangos desde el disco: los bytes justos', trozo.size === SIZE && JSON.stringify(trozo.bytes) === JSON.stringify(esperado), JSON.stringify(trozo)); |
| 80 | |
| 81 | // 4) una descarga cortada no deja la marca de completo: no se sirve a medias |
| 82 | await p.evaluate(async () => (await import('/js/runtime/model-store.js')).clearAll()); |
| 83 | await p.unroute('**/__modelcache_fixture.litertlm'); |
| 84 | await p.route('**/__modelcache_fixture.litertlm', route => { |
| 85 | const rango = route.request().headers().range || ''; |
| 86 | if (/bytes=0-0$/.test(rango)) return route.fulfill({ status: 206, body: DATOS.subarray(0, 1), headers: { 'content-range': `bytes 0-0/${SIZE}`, 'accept-ranges': 'bytes' } }); |
| 87 | return route.abort('failed'); |
| 88 | }); |
| 89 | const r4 = await p.evaluate(async u => { |
| 90 | const m = await import('/js/runtime/model-store.js'); |
| 91 | let err = null; try { await m.getModelFile(u); } catch (e) { err = String(e.message || e); } |
| 92 | const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); |
| 93 | const nombres = []; for await (const [n] of dir.entries()) nombres.push(n); |
| 94 | return { err, completo: nombres.some(n => n.endsWith('.done')) }; |
| 95 | }, FIX); |
| 96 | ok('una descarga cortada falla y NO queda marcada como completa', !!r4.err && !r4.completo, JSON.stringify(r4)); |
| 97 | |
| 98 | // 5) el uso de almacenamiento lo refleja |
| 99 | const est = await p.evaluate(() => navigator.storage.estimate().then(e => e.usage || 0).catch(() => 0)); |
| 100 | ok('storage.estimate refleja lo guardado', est > 0, est > 0 ? 'hay uso' : 'sin uso'); |
| 101 | |
| 102 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — se baja una vez a disco, se sirve sin red y por rangos'); |
| 103 | await b.close(); |
| 104 | process.exit(fails ? 1 : 0); |