Elffuss BraidHub

utopia-ia/elffuss-code public

main · 12.1 KiBRawPermalink
1// Elffuss Runtime · almacén de modelos en OPFS (persistente, en disco).
2// ─────────────────────────────────────────────────────────────────────────────
3// Sustituye a Cache Storage para los PESOS del modelo. Motivo real (bug de móvil):
4// Cache Storage se desaloja en iOS/Android → el modelo se re-descargaba en CADA
5// visita. OPFS (Origin Private File System) + navigator.storage.persist() aguanta
6// entre sesiones y se lee como File respaldado por DISCO (no vuelca todo a RAM).
7//
8// Además es la capa de almacenamiento del loader por shards: el motor leerá los
9// pesos por rangos desde el File sin cargar los gigabytes enteros en memoria.
10//
11// Licencia: código propio (Apache-2.0). Sin dependencias externas.
12
13const DIR = 'elffuss-models';
14
15// Nombre de fichero estable y seguro a partir de la URL (sin barras ni query).
16function keyFor(url) {
17 return String(url).replace(/[?#].*$/, '').replace(/[^\w.\-]+/g, '_').slice(-180);
18}
19
20async function requestPersist() {
21 try {
22 if (navigator.storage?.persist) {
23 const already = navigator.storage.persisted ? await navigator.storage.persisted() : false;
24 return already || await navigator.storage.persist();
25 }
26 } catch { /* no bloquea */ }
27 return false;
28}
29
30async function dirHandle() {
31 const root = await navigator.storage.getDirectory(); // lanza si no hay OPFS
32 return await root.getDirectoryHandle(DIR, { create: true });
33}
34
35// ¿Hay soporte para escribir en OPFS de forma útil en este navegador?
36// Chrome/escritorio: createWritable (stream a disco). iOS Safari: solo
37// createSyncAccessHandle (en worker) → en este primer incremento, si no hay
38// createWritable en el hilo principal, devolvemos null y el llamador cae a Cache.
39async function opfsWritableSupported(dir) {
40 try {
41 const test = await dir.getFileHandle('.probe', { create: true });
42 if (typeof test.createWritable !== 'function') { await dir.removeEntry('.probe').catch(() => {}); return false; }
43 const w = await test.createWritable();
44 await w.close();
45 await dir.removeEntry('.probe').catch(() => {});
46 return true;
47 } catch { return false; }
48}
49
50// Devuelve un File (respaldado en disco) del modelo. Descarga por chunks a OPFS
51// la primera vez (con progreso real), lo sirve desde disco a partir de entonces.
52// Un marcador «<key>.done» evita servir una descarga cortada a medias.
53// Devuelve null si OPFS no está disponible/escribible → el llamador usa su
54// respaldo (Cache Storage) sin romperse.
55export async function getModelFile(url, onProgress = () => {}) {
56 // 1) Caché COMPARTIDA (broker en origen Elffuss): un modelo bajado en CUALQUIER
57 // web de Elffuss se reutiliza aquí sin re-descargar. Fast-fail por sesión si
58 // el broker no está disponible → caemos a la OPFS local de este origen.
59 let brokerDown = false;
60 try { brokerDown = sessionStorage.getItem('elffuss.broker.down') === '1'; } catch { /* — */ }
61 if (!brokerDown) {
62 try {
63 const { getSharedModel } = await import('./model-broker.js');
64 const blob = await getSharedModel(url, onProgress);
65 if (blob && blob.size) return blob;
66 } catch { try { sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* — */ } }
67 }
68
69 if (!navigator.storage?.getDirectory) return null;
70 let dir;
71 try { dir = await dirHandle(); } catch { return null; }
72 await requestPersist();
73
74 const key = keyFor(url);
75 const doneName = key + '.done';
76
77 // ¿ya está entero en disco?
78 try {
79 await dir.getFileHandle(doneName); // lanza si no existe
80 const f = await (await dir.getFileHandle(key)).getFile();
81 if (f.size > 0) { onProgress('Cargando el modelo desde disco (OPFS, sin descargar)…'); return f; }
82 } catch { /* no está o incompleto: se descarga */ }
83
84 if (!(await opfsWritableSupported(dir))) return null; // iOS main-thread: que decida el llamador
85
86 // ── Descarga REANUDABLE ────────────────────────────────────────────────
87 // Antes, un corte borraba lo bajado y la vez siguiente empezaba de cero. Con
88 // un modelo de gigas eso convierte un tropiezo de red —o que el equipo se
89 // duerma— en media hora perdida, y el usuario lo vive como «vuelve a
90 // descargar el modelo». Ahora lo ya escrito se conserva y se pide el resto
91 // con `Range`.
92 //
93 // El peligro de reanudar es empalmar dos ficheros DISTINTOS si el de origen
94 // cambió: saldría un modelo corrupto que carga y devuelve basura, que es
95 // peor que volver a bajarlo. Por eso se guarda la huella del origen (ETag o
96 // Last-Modified) junto a los bytes, y si no coincide se empieza de nuevo.
97 const parteName = key + '.parte'; // huella del intento
98 let ya = 0, huellaPrevia = null;
99 try {
100 huellaPrevia = JSON.parse(await (await (await dir.getFileHandle(parteName)).getFile()).text());
101 ya = (await (await dir.getFileHandle(key)).getFile()).size;
102 } catch { ya = 0; huellaPrevia = null; }
103
104 // Se pregunta primero POR LA CABECERA qué hay al otro lado: es una petición
105 // de un byte, y decide si lo que tenemos sirve.
106 let huella = null, total = 0, aceptaRangos = false;
107 try {
108 const cab = await fetch(url, { headers: { Range: 'bytes=0-0' } });
109 aceptaRangos = cab.status === 206;
110 huella = cab.headers.get('etag') || cab.headers.get('last-modified') || null;
111 const cr = cab.headers.get('content-range');
112 total = cr ? +cr.split('/')[1] : (+cab.headers.get('content-length') || 0);
113 try { await cab.arrayBuffer(); } catch { /* — */ }
114 } catch { /* sin cabecera: se baja entero */ }
115
116 // La huella preferida es el ETag, pero CORS solo expone Content-Range,
117 // Accept-Ranges y Content-Length: desde el navegador `etag` sale NULL y una
118 // reanudación que dependiera de él no se activaría jamás. Se cae al TAMAÑO
119 // TOTAL, que Content-Range sí deja leer y que el registro del motor fija al
120 // byte — si el fichero de origen cambiara, cambiaría de tamaño y la
121 // reanudación se descarta sola. Es más débil que un ETag y suficiente aquí.
122 const mismaHuella = huellaPrevia && (
123 (huella && huellaPrevia.huella === huella) ||
124 (!huella && !huellaPrevia.huella && huellaPrevia.total === total));
125 const puedeReanudar = ya > 0 && aceptaRangos && total > 0 && ya < total && mismaHuella;
126 if (ya > 0 && !puedeReanudar) {
127 // Lo guardado no sirve (otro fichero, o el servidor no da rangos).
128 await dir.removeEntry(key).catch(() => {});
129 ya = 0;
130 }
131
132 const net = await fetch(url, puedeReanudar ? { headers: { Range: `bytes=${ya}-` } } : undefined);
133 const okEstado = puedeReanudar ? net.status === 206 : net.ok;
134 if (!okEstado || !net.body) throw new Error('descarga del modelo falló: HTTP ' + net.status);
135 if (!total) total = (+net.headers.get('content-length') || 0) + ya;
136
137 await dir.removeEntry(doneName).catch(() => {});
138 const fh = await dir.getFileHandle(key, { create: true });
139 // `keepExistingData` conserva lo ya escrito; sin él, createWritable() TRUNCA
140 // el fichero a cero y la reanudación sería una forma cara de empezar de nuevo.
141 // Se confirma POR TRAMOS. `createWritable()` es atómico: lo escrito no existe
142 // en el fichero hasta el `close()`, así que un corte tira TODO aunque nadie
143 // borre nada — que es exactamente lo que medía el banco de reanudación
144 // fallando. Cerrando y reabriendo cada tramo, lo confirmado sobrevive al
145 // corte y la próxima vez se continúa desde ahí.
146 // Proporcional al fichero, no fijo: con un tramo de 64 MB un fichero de 3 MB
147 // no llegaba a confirmar NUNCA y la reanudación no existía para él —lo
148 // destapó el banco, que usa un fichero pequeño a propósito—. Así se confirma
149 // una quincena de veces sea cual sea el tamaño, con suelo para no castigar a
150 // los diminutos y techo para no confirmar cada dos por tres en los de gigas.
151 const TRAMO = Math.max(512 * 1024, Math.min(64 * 1024 * 1024, Math.floor((total || 0) / 16) || (64 * 1024 * 1024)));
152 const anota = async () => {
153 try {
154 const ph = await dir.getFileHandle(parteName, { create: true });
155 const pw = await ph.createWritable();
156 await pw.write(new TextEncoder().encode(JSON.stringify({ huella, total })));
157 await pw.close();
158 } catch { /* sin anotación se pierde la reanudación, no los datos */ }
159 };
160 let writable = await fh.createWritable({ keepExistingData: puedeReanudar });
161 if (puedeReanudar) await writable.seek(ya);
162 const t0 = performance.now();
163 let loaded = ya;
164 if (puedeReanudar) onProgress(`Reanudando la descarga desde ${(ya / 1e9).toFixed(1)} GB…`);
165 await anota();
166 try {
167 const reader = net.body.getReader();
168 let enTramo = 0;
169 for (;;) {
170 const { done, value } = await reader.read();
171 if (done) break;
172 await writable.write(value);
173 loaded += value.byteLength;
174 enTramo += value.byteLength;
175 if (enTramo >= TRAMO) {
176 enTramo = 0;
177 await writable.close(); // confirma lo del tramo
178 writable = await fh.createWritable({ keepExistingData: true });
179 await writable.seek(loaded);
180 }
181 onProgress(fmt(loaded, total, t0));
182 }
183 await writable.close();
184 } catch (e) {
185 // Se cierra para CONFIRMAR lo del tramo en curso. `abort()` lo descartaría,
186 // que es justo lo contrario de lo que se quiere al reanudar.
187 try { await writable.close(); } catch { /* lo confirmado en tramos ya está */ }
188 throw e;
189 }
190 // Completado: fuera la marca de intento a medias.
191 await dir.removeEntry(parteName).catch(() => {});
192
193 // marcar completado (con el tamaño esperado, para validar en el futuro)
194 const dh = await dir.getFileHandle(doneName, { create: true });
195 const dw = await dh.createWritable();
196 await dw.write(new TextEncoder().encode(JSON.stringify({ size: loaded, total })));
197 await dw.close();
198
199 return await (await dir.getFileHandle(key)).getFile();
200}
201
202// Abre un handle de lectura por rangos (para el loader por shards del motor):
203// devuelve una función slice(offset, length) → Promise<ArrayBuffer> que lee del
204// disco sin cargar el fichero entero. File.slice() es perezoso en disco.
205export async function openRanged(url) {
206 const file = await getModelFile(url);
207 if (!file) return null;
208 return {
209 size: file.size,
210 async slice(offset, length) { return await file.slice(offset, offset + length).arrayBuffer(); },
211 };
212}
213
214// Borrar un modelo cacheado (para el «liberar espacio» de la UI).
215export async function removeModel(url) {
216 try {
217 const dir = await dirHandle();
218 const key = keyFor(url);
219 await dir.removeEntry(key).catch(() => {});
220 await dir.removeEntry(key + '.done').catch(() => {});
221 return true;
222 } catch { return false; }
223}
224
225// Borra TODOS los modelos guardados en OPFS.
226// Existe porque el botón «liberar espacio» de Ajustes solo vaciaba Cache
227// Storage: un modelo descargado por este almacén se quedaba ocupando disco sin
228// forma de borrarlo desde la interfaz. Y como navigator.storage.estimate() SÍ
229// lo cuenta, el usuario veía gigas que el botón no bajaba nunca.
230export async function clearAll() {
231 try {
232 const root = await navigator.storage.getDirectory();
233 await root.removeEntry(DIR, { recursive: true });
234 return true;
235 } catch { return false; } // no existe o no hay OPFS: nada que borrar
236}
237
238// Bytes ocupados por los modelos en OPFS (aprox, para diagnóstico).
239export async function usage() {
240 try {
241 const est = await navigator.storage.estimate();
242 return { usage: est.usage || 0, quota: est.quota || 0 };
243 } catch { return { usage: 0, quota: 0 }; }
244}
245
246function fmt(loaded, total, t0) {
247 const mb = n => (n / 1048576).toFixed(0);
248 const secs = (performance.now() - t0) / 1000;
249 const spd = secs > 0 ? (loaded / 1048576 / secs).toFixed(1) : '0';
250 // Incluir el % cuando se conoce el total: el escaparate lo extrae para llenar
251 // la barra, y el texto queda corto (no envuelve en móvil).
252 return total
253 ? `Descargando el cerebro · ${mb(loaded)}/${mb(total)} MB · ${Math.round(loaded / total * 100)}%`
254 : `Descargando el cerebro · ${mb(loaded)} MB · ${spd} MB/s`;
255}