Fix workout display service worker fetch fallbacks

This commit is contained in:
Ccjcarkbla
2026-10-14 10:10:10 -04:00
parent 636e7b506c
commit a084388322
2 changed files with 252 additions and 15 deletions
+80 -15
View File
@@ -1,11 +1,12 @@
/* VitFit Service Worker — shell-only caching for PWA install */
'use strict';
const CACHE_NAME = 'vitfit-v13';
const CACHE_NAME = 'vitfit-v14';
const SHELL_ASSETS = [
'/',
'/index.html',
'/dashboard.html',
'/workout-display.html',
'/styles/base.css',
'/styles/layout.css',
'/styles/components.css',
@@ -15,39 +16,103 @@ const SHELL_ASSETS = [
'/js/display.js',
'/manifest.json',
];
const SHELL_PATHS = new Set(SHELL_ASSETS);
async function readShell(pathname) {
try {
const cache = await caches.open(CACHE_NAME);
return await cache.match(pathname);
} catch {
// Safari can make cache storage unavailable; network access must still work.
return undefined;
}
}
async function storeShell(pathname, response) {
if (!SHELL_PATHS.has(pathname) || !response.ok || response.redirected) return;
try {
const cache = await caches.open(CACHE_NAME);
await cache.put(pathname, response.clone());
} catch {
// Cache/quota failures must not turn a successful fetch into a network error.
}
}
function unavailableResponse(isPage) {
return new Response(isPage ? `<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>VitFit connection unavailable</title></head>
<body style="background:#111;color:#fff;font:24px system-ui;padding:40px">
<h1>Unable to reach VitFit</h1><p>Check the connection and try again.</p>
<button style="font:inherit;padding:12px" onclick="location.reload()">Try again</button>
</body></html>` : 'VitFit resource unavailable. Please try again.', {
status: 503,
headers: {
'Content-Type': isPage ? 'text/html; charset=utf-8' : 'text/plain; charset=utf-8',
'Cache-Control': 'no-store',
'Retry-After': '30',
},
});
}
async function fetchPage(request, pathname) {
try {
const response = await fetch(request);
if (response.status >= 500) {
const cached = await readShell(pathname);
if (cached) return cached;
}
await storeShell(pathname, response);
return response;
} catch {
// Use the matching page shell, retaining the workout id in the browser URL.
// Never substitute the login page for a workout display.
return (await readShell(pathname)) || unavailableResponse(true);
}
}
async function fetchAsset(request, pathname) {
const cached = await readShell(pathname);
if (cached) return cached;
try {
const response = await fetch(request);
await storeShell(pathname, response);
return response;
} catch {
return unavailableResponse(false);
}
}
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(SHELL_ASSETS))
caches.open(CACHE_NAME)
.then(cache => cache.addAll(SHELL_ASSETS))
.then(() => self.skipWaiting())
);
self.skipWaiting();
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
)
Promise.all(keys.filter(k => k.startsWith('vitfit-') && k !== CACHE_NAME).map(k => caches.delete(k)))
).then(() => self.clients.claim())
);
self.clients.claim();
});
self.addEventListener('fetch', (e) => {
const url = new URL(e.request.url);
if (e.request.method !== 'GET' || url.origin !== self.location.origin) return;
// API and socket: always network
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/socket.io')) return;
// Navigation: network-first, fallback to cached index
if (e.request.mode === 'navigate') {
e.respondWith(
fetch(e.request).catch(() => caches.match('/index.html'))
);
// HTML can also be requested by fetch/prefetch, without mode="navigate".
if (e.request.mode === 'navigate' || e.request.destination === 'document' || url.pathname.endsWith('.html')) {
e.respondWith(fetchPage(e.request, url.pathname));
return;
}
// Static assets: cache-first
e.respondWith(
caches.match(e.request).then(cached => cached || fetch(e.request))
);
// Cache only the fixed shell list, never videos, API data or arbitrary URLs.
if (SHELL_PATHS.has(url.pathname)) e.respondWith(fetchAsset(e.request, url.pathname));
});
+172
View File
@@ -0,0 +1,172 @@
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
function setup(entries = {}) {
const handlers = new Map();
const stored = new Map(Object.entries(entries));
const cache = {
match: jest.fn(async key => stored.get(key)?.clone()),
put: jest.fn(async (key, response) => { stored.set(key, response); }),
addAll: jest.fn(async () => {}),
};
const caches = {
open: jest.fn(async () => cache),
keys: jest.fn(async () => ['vitfit-v13', 'vitfit-v14', 'another-app']),
delete: jest.fn(async () => true),
};
const self = {
location: { origin: 'https://vitfit.test' },
addEventListener: (name, callback) => handlers.set(name, callback),
skipWaiting: jest.fn(async () => {}),
clients: { claim: jest.fn(async () => {}) },
};
const fetch = jest.fn(async () => new Response('network response'));
vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../../public/sw.js'), 'utf8'), {
self, caches, fetch, URL, Response,
});
function request(pathname, options = {}) {
const event = {
request: {
url: new URL(pathname, self.location.origin).href,
method: 'GET', mode: 'cors', destination: '', ...options,
},
respondWith: jest.fn(promise => { event.response = promise; }),
};
handlers.get('fetch')(event);
return event;
}
async function lifecycle(name) {
const waits = [];
handlers.get(name)({ waitUntil: promise => waits.push(promise) });
await Promise.all(waits);
}
return { request, lifecycle, fetch, cache, caches, stored, self };
}
test.each(['navigate', 'cors'])('failed %s request for a workout returns its cached shell', async mode => {
const { request, fetch } = setup({
'/workout-display.html': new Response('workout shell'),
'/index.html': new Response('login shell'),
});
fetch.mockRejectedValue(new TypeError('Failed to fetch'));
for (const id of [89, 91]) {
const event = request(`/workout-display.html?id=${id}`, { mode });
const response = await event.response;
expect(response.status).toBe(200);
expect(await response.text()).toBe('workout shell');
expect(event.request.url).toContain(`id=${id}`);
}
});
test('a missing page cache produces an explicit offline response, preserving the requested page', async () => {
const { request, fetch } = setup({ '/index.html': new Response('login shell') });
fetch.mockRejectedValue(new TypeError('Failed to fetch'));
const response = await request('/workout-display.html?id=89', { mode: 'navigate' }).response;
expect(response.status).toBe(503);
expect(response.headers.get('Content-Type')).toContain('text/html');
expect(await response.text()).toContain('Unable to reach VitFit');
});
test('failed static asset requests resolve with a response instead of rejecting', async () => {
const { request, fetch } = setup();
fetch.mockRejectedValue(new TypeError('Failed to fetch'));
const response = await request('/js/display.js').response;
expect(response.status).toBe(503);
expect(response.headers.get('Cache-Control')).toBe('no-store');
});
test('HTML is network-first and stores one shell regardless of workout id', async () => {
const { request, fetch, stored } = setup({ '/workout-display.html': new Response('old shell') });
fetch.mockImplementation(async () => new Response('new shell'));
for (const id of [89, 91]) {
const response = await request(`/workout-display.html?id=${id}`).response;
expect(await response.text()).toBe('new shell');
}
expect([...stored.keys()]).toEqual(['/workout-display.html']);
});
test('cached static assets work offline and are read from the current cache only', async () => {
const { request, fetch, caches } = setup({ '/js/display.js': new Response('cached script') });
const response = await request('/js/display.js').response;
expect(await response.text()).toBe('cached script');
expect(fetch).not.toHaveBeenCalled();
expect(caches.open).toHaveBeenCalledWith('vitfit-v14');
});
test('newly fetched shell assets are cached', async () => {
const { request, stored } = setup();
await request('/js/display.js').response;
expect(stored.has('/js/display.js')).toBe(true);
});
test('a cache read failure does not prevent fetching a resource', async () => {
const { request, caches } = setup();
caches.open.mockRejectedValue(new Error('Cache storage unavailable'));
const response = await request('/js/display.js').response;
expect(await response.text()).toBe('network response');
});
test('cache write failures do not discard successful page responses', async () => {
const { request, cache } = setup();
cache.put.mockRejectedValue(new Error('Quota exceeded'));
const response = await request('/workout-display.html?id=89').response;
expect(response.status).toBe(200);
expect(await response.text()).toBe('network response');
});
test('network and cache failures together still yield a valid response', async () => {
const { request, caches, fetch } = setup();
caches.open.mockRejectedValue(new Error('Cache storage unavailable'));
fetch.mockRejectedValue(new TypeError('Failed to fetch'));
for (const pathname of ['/workout-display.html?id=89', '/js/display.js']) {
expect((await request(pathname).response).status).toBe(503);
}
});
test('server errors can use the matching cached shell, but 404s remain visible', async () => {
const { request, fetch } = setup({ '/workout-display.html': new Response('cached shell') });
fetch.mockResolvedValueOnce(new Response('Bad gateway', { status: 502 }));
expect(await (await request('/workout-display.html?id=89').response).text()).toBe('cached shell');
fetch.mockResolvedValueOnce(new Response('Not found', { status: 404 }));
expect((await request('/workout-display.html?id=89').response).status).toBe(404);
});
test.each([
['/api/v1/workouts/89', {}],
['/api/v1/videos/stream/clip.mp4?token=secret', {}],
['/socket.io/?transport=polling', {}],
['/uploads/clip.mp4', {}],
['/other-resource.png', {}],
['/index.html', { method: 'POST' }],
['https://other.test/index.html', {}],
])('leaves %s to the browser network stack', (pathname, options) => {
const { request, fetch, cache } = setup();
expect(request(pathname, options).respondWith).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
expect(cache.match).not.toHaveBeenCalled();
});
test('install caches the workout page before activating the new worker', async () => {
const { lifecycle, cache, self } = setup();
await lifecycle('install');
expect(cache.addAll.mock.calls[0][0]).toContain('/workout-display.html');
expect(cache.addAll.mock.invocationCallOrder[0]).toBeLessThan(self.skipWaiting.mock.invocationCallOrder[0]);
});
test('a failed installation leaves the previous worker in place', async () => {
const { lifecycle, cache, self } = setup();
cache.addAll.mockRejectedValue(new Error('Offline'));
await expect(lifecycle('install')).rejects.toThrow('Offline');
expect(self.skipWaiting).not.toHaveBeenCalled();
});
test('activation removes old VitFit caches and claims clients after cleanup', async () => {
const { lifecycle, caches, self } = setup();
await lifecycle('activate');
expect(caches.delete).toHaveBeenCalledTimes(1);
expect(caches.delete).toHaveBeenCalledWith('vitfit-v13');
expect(caches.delete.mock.invocationCallOrder[0]).toBeLessThan(self.clients.claim.mock.invocationCallOrder[0]);
});