From d790c3d95d210b314b5867de5ca30c7024918668 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 4 Nov 2026 16:39:59 +0100 Subject: [PATCH] fix(sw): network-first y no cachear errores (#5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El service worker servía primero la caché (los cambios de /data y del código llegaban con una carga de retraso, y JS nuevo podía mezclarse con JS viejo), guardaba cualquier respuesta incluidos 404/500, y silenciaba los fallos del precache. Además, sin red la app no llegaba a arrancar. - Mismo origen: network-first con timeout de 4 s; tras un timeout, 15 s sirviendo de caché directamente para no sumar un timeout por nivel (HTML → JS → JSON). Un error del servidor con copia en caché sirve la copia; sin copia, el error llega a la app. - Otros orígenes (Google Fonts): cache-first. - Solo se cachean respuestas ok (u opacas de otros orígenes). - Precache fichero a fichero con console.warn del que falle. - CACHE_NAME → v4 para purgar las cachés con 404 guardados. tests/sw.test.mjs comprueba que ASSETS existe, cubre todo js/, el CSS, los HTML, el manifest y sus iconos. Documentado en README (publicar cambios) y CONTRIBUTING (cuándo subir CACHE_NAME). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++ CONTRIBUTING.md | 13 +++++ README.md | 12 +++++ service-worker.js | 119 ++++++++++++++++++++++++++++++++++++---------- tests/sw.test.mjs | 40 ++++++++++++++++ 5 files changed, 169 insertions(+), 24 deletions(-) create mode 100644 tests/sw.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index d7d8376..51bdd93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,16 @@ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). (`tests/data.test.mjs`: JSON válido, ids únicos, recetas sin ingredientes inexistentes, categorías con tope, `visualStyle` conocido) (#3). +### Cambiado +- Service worker: *network-first* (con timeout de 4 s) para todo lo del + propio sitio en vez de servir primero la caché, así los cambios en `/data` + y en el código se ven en la siguiente carga sin tocar `CACHE_NAME`. Sin red + o con red lenta, arranca desde caché (#5). + ### Corregido +- El service worker ya no guarda en caché respuestas de error (404/500), y + la app vuelve a arrancar sin conexión. El precache avisa en consola de qué + fichero falló en vez de silenciarlo (#5). - La ronda 2 ya no se queda en "Cargando…" si falla la carga del tipo de cena elegido: muestra el error con el fichero que falló y permite reintentar (sin perder la ronda 1) o volver al inicio (#19). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f9a80d7..2fb4d05 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,6 +68,19 @@ Ver `README.md` sección "Añadir un tipo de cena nuevo" — resumen: crea `admin.html`) y añade la entrada en `data/dish-types.json`. No hace falta tocar `service-worker.js` ni el código JS. +## Service worker y caché +`service-worker.js` sirve todo lo del propio sitio con *network-first* +(con conexión siempre llega lo último publicado; la caché es solo para +offline o red lenta) y nunca cachea respuestas de error. Por eso: +- **Cambiar `/data` o el código no requiere tocar el service worker.** +- **Sube `CACHE_NAME`** (`dinner-match-v4` → `v5`...) solo si quieres purgar + la caché de todos los clientes: al renombrar o borrar ficheros del shell, + o si cambias la estrategia de caché. +- Si añades un fichero al shell (un HTML, CSS o módulo de `js/` nuevo), + añádelo a `ASSETS` para que funcione offline desde la primera visita. + `tests/sw.test.mjs` falla si falta alguno o si una ruta de `ASSETS` no + existe. + ## Añadir una tarea al backlog Añádela a `backlog/issues.json` (con `title`, `body`, `labels`, `milestone`) y luego créala en GitHub con: diff --git a/README.md b/README.md index 8401e0d..575e668 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,18 @@ Cualquier hosting estático con HTTPS sirve, por ejemplo: Una vez desplegado, entra desde el móvil y usa "Añadir a pantalla de inicio" (o el banner de instalación que aparece solo en Chrome/Edge Android). +### Publicar cambios de contenido o de código + +No hay que hacer nada especial: haz commit de los JSON de `/data` (o del +código) y despliega. El service worker usa *network-first* para todo lo del +propio sitio, así que quien abra la app con conexión ve la versión nueva en +esa misma carga, también con la PWA instalada. Sin conexión (o si la red +tarda más de 4 s) se usa la última versión guardada en el móvil, y se +actualiza sola la próxima vez que haya red. + +No hace falta cambiar `CACHE_NAME` en `service-worker.js` para publicar +cambios; ver `CONTRIBUTING.md` para los casos en que sí. + ## Estructura ``` diff --git a/service-worker.js b/service-worker.js index 63de23e..4d09c3e 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,8 +1,27 @@ -const CACHE_NAME = "dinner-match-v3"; -// Precache solo el "shell" de la app y el catálogo de tipos: los datos de -// cada tipo (data/types//*.json) se cachean en runtime la primera vez -// que se piden (ver el handler de "fetch" más abajo), así añadir un tipo -// nuevo en /data no requiere tocar este fichero. +// Estrategia de caché: +// - Mismo origen (HTML, JS, CSS, iconos y /data): network-first. Con +// conexión siempre se sirve lo último publicado (contenido de /data y +// código siempre coherentes entre sí); la caché solo se usa sin red o si +// la red tarda más de NETWORK_TIMEOUT_MS. Por eso publicar cambios en /data +// o en el código NO requiere tocar este fichero. +// - Otros orígenes (Google Fonts): cache-first, no cambian. +// - Solo se guardan respuestas válidas: un 404/500 nunca se cachea. +// +// CACHE_NAME solo hay que cambiarlo si se quiere purgar la caché de todos +// los clientes (p. ej. al renombrar o borrar ficheros del shell). Ver +// CONTRIBUTING.md. +const CACHE_NAME = "dinner-match-v4"; +const NETWORK_TIMEOUT_MS = 4000; +// Tras un timeout, durante este tiempo se sirve directamente de caché (sin +// esperar otra vez a la red) para que la cadena HTML → JS → JSON no sume un +// timeout por nivel. La red se sigue consultando en segundo plano. +const SLOW_NETWORK_GRACE_MS = 15000; +let slowNetworkUntil = 0; + +// Shell precacheado para que la app arranque offline desde la primera +// visita. Los datos de cada tipo (data/types//*.json) se cachean en +// runtime la primera vez que se piden. tests/sw.test.mjs comprueba que +// todas estas rutas existen. const ASSETS = [ "./", "./index.html", @@ -21,30 +40,82 @@ const ASSETS = [ ]; self.addEventListener("install", (event) => { - event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)).catch(() => {}) - ); + event.waitUntil((async () => { + const cache = await caches.open(CACHE_NAME); + // Uno a uno en vez de addAll: si falla un fichero se avisa de cuál y el + // resto sí queda precacheado (addAll es todo o nada). + const results = await Promise.allSettled(ASSETS.map((url) => cache.add(new Request(url, { cache: "reload" })))); + results.forEach((r, i) => { + if (r.status === "rejected") console.warn(`[sw] No se pudo precachear ${ASSETS[i]}:`, r.reason); + }); + })()); self.skipWaiting(); }); self.addEventListener("activate", (event) => { - event.waitUntil( - caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))) - ); - self.clients.claim(); + event.waitUntil((async () => { + const keys = await caches.keys(); + await Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))); + await self.clients.claim(); + })()); }); self.addEventListener("fetch", (event) => { - if (event.request.method !== "GET") return; - event.respondWith( - caches.match(event.request).then((cached) => { - const fetchPromise = fetch(event.request) - .then((networkResponse) => { - caches.open(CACHE_NAME).then((cache) => cache.put(event.request, networkResponse.clone())); - return networkResponse; - }) - .catch(() => cached); - return cached || fetchPromise; - }) - ); + const { request } = event; + if (request.method !== "GET") return; + const url = new URL(request.url); + if (url.protocol !== "http:" && url.protocol !== "https:") return; + event.respondWith(url.origin === self.location.origin ? networkFirst(event) : cacheFirst(event)); }); + +function cacheable(response) { + // Las respuestas opacas (CSS/fuentes de Google cargadas sin CORS) no + // exponen su status; se aceptan solo para otros orígenes. + return response && (response.ok || response.type === "opaque"); +} + +function store(event, response) { + if (!cacheable(response)) return; + const copy = response.clone(); + event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy))); +} + +async function networkFirst(event) { + const { request } = event; + const network = fetch(request).then((response) => { + if (response.ok) store(event, response); + return response; + }); + // Evita un unhandled rejection si gana el timeout y luego falla la red. + network.catch(() => {}); + + const cached = await caches.match(request); + if (!cached) return network; // sin copia local: lo que diga la red, errores incluidos + if (Date.now() < slowNetworkUntil) return cached; + + let timer; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => { + slowNetworkUntil = Date.now() + SLOW_NETWORK_GRACE_MS; + resolve(cached); + }, NETWORK_TIMEOUT_MS); + }); + try { + const response = await Promise.race([network, timeout]); + // Si el servidor responde con error pero hay copia válida, mejor la copia + // que romper la app (p. ej. un 5xx puntual del hosting). + return response.ok || response === cached ? response : cached; + } catch { + return cached; // sin red + } finally { + clearTimeout(timer); + } +} + +async function cacheFirst(event) { + const cached = await caches.match(event.request); + if (cached) return cached; + const response = await fetch(event.request); + store(event, response); + return response; +} diff --git a/tests/sw.test.mjs b/tests/sw.test.mjs new file mode 100644 index 0000000..e5f6b0b --- /dev/null +++ b/tests/sw.test.mjs @@ -0,0 +1,40 @@ +// Coherencia entre service-worker.js y los ficheros del repo: si una ruta del +// precache no existe, ese fichero no estará disponible offline; si un módulo +// de js/ no está precacheado, la app no arranca offline en la primera visita. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, readdirSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = fileURLToPath(new URL("..", import.meta.url)); +const sw = readFileSync(join(ROOT, "service-worker.js"), "utf8"); +const block = sw.match(/const ASSETS = \[([\s\S]*?)\];/); +const assets = block ? [...block[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]) : []; + +test("service-worker.js declara ASSETS", () => { + assert.ok(assets.length > 0, "no se encontró const ASSETS = [...] en service-worker.js"); +}); + +test("todas las rutas precacheadas existen", () => { + const missing = assets + .filter((a) => a !== "./") + .filter((a) => !existsSync(join(ROOT, a))); + assert.deepEqual(missing, []); +}); + +test("el shell completo está precacheado (HTML, CSS, módulos JS, manifest, datos globales)", () => { + const required = [ + "./index.html", "./admin.html", "./manifest.json", "./css/style.css", + "./data/dish-types.json", "./data/game-config.json", + ...readdirSync(join(ROOT, "js")).filter((f) => f.endsWith(".js")).map((f) => `./js/${f}`), + ]; + assert.deepEqual(required.filter((r) => !assets.includes(r)), []); +}); + +test("los iconos del manifest están precacheados", () => { + const manifest = JSON.parse(readFileSync(join(ROOT, "manifest.json"), "utf8")); + const icons = manifest.icons.map((i) => `./${i.src.replace(/^\.\//, "")}`); + assert.deepEqual(icons.filter((i) => !assets.includes(i)), []); +});