| 1 | // ¿Se reanuda de verdad una descarga cortada, o solo lo parece? |
| 2 | // |
| 3 | // Antes, un corte borraba lo ya escrito y la vez siguiente empezaba de cero. |
| 4 | // Con un modelo de gigas eso convierte un tropiezo de red en media hora |
| 5 | // perdida, y el usuario lo vive como «vuelve a descargar el modelo». |
| 6 | // |
| 7 | // La prueba corta la descarga A PROPÓSITO a mitad y vuelve a pedirla. Lo que se |
| 8 | // comprueba no es que «funcione» sino las dos cosas que pueden ir mal: |
| 9 | // · que la segunda vez pida sólo el RESTO (si no, no hay reanudación); |
| 10 | // · que el fichero final sea BYTE A BYTE el original (si no, la reanudación |
| 11 | // ha empalmado mal y tendríamos un modelo corrupto que carga y da basura, |
| 12 | // que es peor que volver a bajarlo). |
| 13 | // |
| 14 | // Se usa un fichero pequeño servido en local, no el modelo de 7 GB: lo que se |
| 15 | // prueba es la lógica de reanudación, y para eso da igual el tamaño. |
| 16 | import { createServer } from 'node:http'; |
| 17 | import { existsSync, readFileSync, mkdtempSync } from 'node:fs'; |
| 18 | import { join, dirname } from 'node:path'; |
| 19 | import { tmpdir } from 'node:os'; |
| 20 | import { fileURLToPath } from 'node:url'; |
| 21 | import { createHash } from 'node:crypto'; |
| 22 | import { chromium } from 'playwright'; |
| 23 | |
| 24 | let fails = 0; |
| 25 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 26 | |
| 27 | // ── Un servidor que habla rangos y que puede CORTAR a mitad ──────────────── |
| 28 | const TAM = 3 * 1024 * 1024; |
| 29 | const DATOS = Buffer.alloc(TAM); |
| 30 | for (let i = 0; i < TAM; i++) DATOS[i] = (i * 7 + 13) & 0xff; // patrón, no ceros: |
| 31 | // con ceros, un empalme mal hecho seguiría dando el mismo hash y pasaría. |
| 32 | const SHA = createHash('sha256').update(DATOS).digest('hex'); |
| 33 | |
| 34 | let cortar = false; // cuando está puesto, el servidor corta a la mitad |
| 35 | const peticiones = []; |
| 36 | const srv = createServer((req, res) => { |
| 37 | const rango = req.headers.range; |
| 38 | const m = rango && /bytes=(\d+)-/.exec(rango); |
| 39 | const desde = m ? +m[1] : 0; |
| 40 | peticiones.push({ rango: rango || null, desde }); |
| 41 | // El sondeo de un byte se responde BIEN aunque estemos simulando un corte: una |
| 42 | // red que se cae a mitad de una descarga de gigas no impide hacer una |
| 43 | // petición de un byte. La primera versión cortaba también el sondeo, así que |
| 44 | // la descarga moría a nivel de red antes de escribir nada y no había nada que |
| 45 | // reanudar — el banco marcaba en rojo por culpa del banco. |
| 46 | const sondeo = /bytes=0-0$/.test(rango || ''); |
| 47 | const hasta = sondeo ? 0 : TAM - 1; |
| 48 | const cuerpo = DATOS.subarray(desde, hasta + 1); |
| 49 | res.setHeader('Accept-Ranges', 'bytes'); |
| 50 | res.setHeader('Access-Control-Allow-Origin', '*'); |
| 51 | res.setHeader('Access-Control-Expose-Headers', 'Content-Range, Accept-Ranges, Content-Length'); |
| 52 | if (m) { |
| 53 | res.statusCode = 206; |
| 54 | res.setHeader('Content-Range', `bytes ${desde}-${hasta}/${TAM}`); |
| 55 | } |
| 56 | res.setHeader('Content-Length', String(cuerpo.length)); |
| 57 | if (cortar && !sondeo && cuerpo.length > 1024) { |
| 58 | // Se manda la mitad, se deja que LLEGUE, y entonces se corta. Destruir el |
| 59 | // socket en el mismo tick hacía que Chrome invalidara la respuesta entera y |
| 60 | // rechazara el `fetch`: no llegaba un solo byte a la aplicación, y entonces |
| 61 | // no hay nada que reanudar. Una red que se cae de verdad entrega lo que ya |
| 62 | // iba en camino y corta después; esto reproduce eso. |
| 63 | res.write(cuerpo.subarray(0, Math.floor(cuerpo.length / 2))); |
| 64 | setTimeout(() => { try { res.destroy(); } catch { /* — */ } }, 400); |
| 65 | return; |
| 66 | } |
| 67 | res.end(cuerpo); |
| 68 | }); |
| 69 | await new Promise(r => srv.listen(0, '127.0.0.1', r)); |
| 70 | const PUERTO = srv.address().port; |
| 71 | const BASE = `http://127.0.0.1:${PUERTO}`; |
| 72 | |
| 73 | // La página tiene que servirse por HTTP para tener OPFS: se sirve desde el |
| 74 | // mismo servidor una página mínima que importa el almacén de verdad — el de |
| 75 | // ESTE árbol. Antes se servía una ruta fija a otra copia del repo, así que la |
| 76 | // prueba no probaba el model-store.js que tenía al lado. |
| 77 | const RAIZ = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); |
| 78 | const srv2 = createServer((req, res) => { |
| 79 | const ruta = req.url.split('?')[0]; |
| 80 | if (ruta === '/') { |
| 81 | res.setHeader('Content-Type', 'text/html'); |
| 82 | return res.end('<!doctype html><meta charset=utf-8><title>reanuda</title>'); |
| 83 | } |
| 84 | const f = join(RAIZ, ruta); |
| 85 | if (!existsSync(f)) { res.statusCode = 404; return res.end('no'); } |
| 86 | res.setHeader('Content-Type', ruta.endsWith('.js') ? 'text/javascript' : 'text/plain'); |
| 87 | res.end(readFileSync(f)); |
| 88 | }); |
| 89 | await new Promise(r => srv2.listen(0, '127.0.0.1', r)); |
| 90 | const APP = `http://127.0.0.1:${srv2.address().port}`; |
| 91 | |
| 92 | // Playwright y su navegador, los de estas pruebas (antes se buscaban en otros |
| 93 | // proyectos y se lanzaba el Chrome instalado). |
| 94 | const perfil = mkdtempSync(join(tmpdir(), 'reanuda-')); |
| 95 | const ctx = await chromium.launchPersistentContext(perfil, {}); |
| 96 | const p = await ctx.newPage(); |
| 97 | p.on('pageerror', e => console.log('· PAGEERROR: ' + e.message.slice(0, 120))); |
| 98 | |
| 99 | try { |
| 100 | await p.goto(APP + '/', { waitUntil: 'domcontentloaded' }); |
| 101 | |
| 102 | const baja = async (url) => p.evaluate(async (u) => { |
| 103 | const m = await import('/js/runtime/model-store.js'); |
| 104 | try { |
| 105 | const f = await m.getModelFile(u, () => {}); |
| 106 | if (!f) return { err: 'sin fichero' }; |
| 107 | const buf = new Uint8Array(await f.arrayBuffer()); |
| 108 | let h = 0; const cr = await crypto.subtle.digest('SHA-256', buf); |
| 109 | void h; |
| 110 | return { size: f.size, sha: [...new Uint8Array(cr)].map(b => b.toString(16).padStart(2, '0')).join('') }; |
| 111 | } catch (e) { return { err: String(e.message || e), pila: String(e.stack || '').split('\n').slice(0, 4).join(' | ') }; } |
| 112 | }, url); |
| 113 | |
| 114 | const url = BASE + '/modelo.bin'; |
| 115 | |
| 116 | // 1) Primer intento CORTADO a la mitad. |
| 117 | cortar = true; |
| 118 | const a = await baja(url); |
| 119 | ok('el primer intento falla (la red se corta)', !!a.err, (a.err || '') + ' :: ' + (a.pila || '')); |
| 120 | |
| 121 | // Qué quedó en disco tras el corte: es lo que decide si hay reanudación. |
| 122 | const estado = await p.evaluate(async () => { |
| 123 | const out = { ficheros: [] }; |
| 124 | try { |
| 125 | const root = await navigator.storage.getDirectory(); |
| 126 | const dir = await root.getDirectoryHandle('elffuss-models', { create: true }); |
| 127 | for await (const [n, h] of dir.entries()) { |
| 128 | const f = await h.getFile(); |
| 129 | out.ficheros.push({ n, size: f.size, txt: f.size < 200 ? await f.text() : '' }); |
| 130 | } |
| 131 | } catch (e) { out.err = String(e.message || e); } |
| 132 | return out; |
| 133 | }); |
| 134 | console.log('· en disco tras el corte: ' + (estado.err || JSON.stringify(estado.ficheros))); |
| 135 | |
| 136 | // 2) Segundo intento, servidor sano: tiene que pedir el RESTO, no todo. |
| 137 | cortar = false; |
| 138 | peticiones.length = 0; |
| 139 | const b = await baja(url); |
| 140 | const conRango = peticiones.filter(x => x.desde > 0); |
| 141 | ok('la segunda vez pide sólo el resto', conRango.length > 0, |
| 142 | peticiones.map(x => x.rango || 'sin rango').join(' · ')); |
| 143 | ok('el fichero queda completo', b.size === TAM, `${b.size} de ${TAM}`); |
| 144 | // Lo que de verdad importa: que no se haya empalmado mal. |
| 145 | ok('el contenido es byte a byte el original', b.sha === SHA, |
| 146 | b.sha ? `${b.sha.slice(0, 16)}… contra ${SHA.slice(0, 16)}…` : JSON.stringify(b)); |
| 147 | } finally { |
| 148 | await ctx.close(); srv.close(); srv2.close(); |
| 149 | } |
| 150 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ REANUDA OK — un corte ya no cuesta la descarga entera'); |
| 151 | process.exit(fails ? 1 : 0); |