Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

sw: an install that lost a chunk fails instead of sweeping the build that worked

Boris 'B' Kurktchiev829a98435e51
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index 332969158..18d892261 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -18,10 +18,29 @@ async function precache() {
// on this device, and its cache, in place; a returned-quietly install activates and sweeps.
if (!res.ok || res.redirected) throw new Error('precache: index.html ' + res.status + (res.redirected ? ' redirected' : ''))
const html = await res.text()
+ const refs = [...new Set([...html.matchAll(/(?:src|href)="([^"]+)"/g)].map(m => m[1])
+ .filter(u => /\.(?:js|css|png|svg|webmanifest|json)(?:\?|$)/.test(u) && !/^(?:https?:)?\/\//.test(u)))]
+ // The scripts and the stylesheets ARE the app. Every sub-resource used to be best-effort, so an
+ // install that got index.html and lost one chunk to a flaky connection still activated, still
+ // swept the build this device came from, and the next offline open was a shell with no code:
+ // a blank page. A chunk that will not cache fails the install instead, which keeps the working
+ // build and its cache exactly where they are. Images, icons and the manifest stay best-effort —
+ // a missing icon is not a broken app.
+ const code = refs.filter(u => /\.(?:js|css)(?:\?|$)/.test(u))
+ // Fetched by hand rather than with `cache.add`, for the same reason index.html is: `add` takes
+ // a REDIRECT for an answer, and an auth proxy in front answers every request with its login
+ // page once the session there expires. A 200 of HTML stored under the main bundle's URL is
+ // worse than nothing cached at all —
+ // the install would report success and then sweep the build that still worked.
+ await Promise.all(code.map(async u => {
+ const r = await fetch(u, { cache: 'no-cache' }).catch(e => { throw new Error('precache: ' + u + ' — ' + (e?.message || e)) })
+ if (!r.ok || r.redirected) throw new Error('precache: ' + u + ' ' + r.status + (r.redirected ? ' redirected' : ''))
+ await c.put(u, r)
+ }))
+ await Promise.all(refs.filter(u => !code.includes(u)).map(u => c.add(u).catch(() => {})))
+ // The shell goes in last, so activate's guard — an index.html in THIS build's cache — means the
+ // whole shell is there rather than just its first file.
await c.put('index.html', new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } }))
- const refs = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map(m => m[1])
- .filter(u => /\.(?:js|css|png|svg|webmanifest|json)(?:\?|$)/.test(u) && !/^(?:https?:)?\/\//.test(u))
- await Promise.all([...new Set(refs)].map(u => c.add(u).catch(() => {})))
}
self.addEventListener('install', e => {
diff --git a/frontend/src/lib/sw.test.js b/frontend/src/lib/sw.test.js
index 080aec542..4af538343 100644
--- a/frontend/src/lib/sw.test.js
+++ b/frontend/src/lib/sw.test.js
@@ -91,6 +91,59 @@ describe('sw.js install and activate', () => {
expect(await globalThis.caches.keys()).toContain('opengym-rt-oldbuild')
})
+ it('a chunk that will not cache fails the install, so the build on the device stays', async () => {
+ await loadSW()
+ const old = await previousBuild()
+ globalThis.fetch = async u => (String(u) === 'index.html'
+ ? { ok: true, status: 200, redirected: false, text: async () => shellHtml }
+ : { ok: false, status: 404 })
+
+ await expect(fire('install')).rejects.toThrow(/index-new\.js/)
+ expect(skipWaiting).toBe(0)
+ // The shell is written after its code, so a half-filled cache cannot read as this build.
+ expect((await globalThis.caches.open(CACHE)).keys()).not.toContain('index.html')
+
+ await fire('activate')
+ expect(await globalThis.caches.keys()).toContain('opengym-rt-oldbuild')
+ expect(await old.match('index.html')).toBeTruthy()
+ })
+
+ it('a chunk answered by a redirect to a login page fails the install too', async () => {
+ // An auth proxy in front answers every request with its login page — 200, and `cache.add`
+ // would have stored that HTML under the main bundle's URL.
+ await loadSW()
+ const old = await previousBuild()
+ globalThis.fetch = async u => (String(u) === 'index.html'
+ ? { ok: true, status: 200, redirected: false, text: async () => shellHtml }
+ : { ok: true, status: 200, redirected: true, text: async () => '<html>sign in</html>' })
+
+ await expect(fire('install')).rejects.toThrow(/index-new\.js.*redirected/)
+ expect(skipWaiting).toBe(0)
+ expect((await globalThis.caches.open(CACHE)).keys()).toEqual([])
+
+ await fire('activate')
+ expect(await globalThis.caches.keys()).toContain('opengym-rt-oldbuild')
+ expect(await old.match('index.html')).toBeTruthy()
+ })
+
+ it('an icon that will not cache is not worth failing an install over', async () => {
+ await loadSW()
+ await previousBuild()
+ const withIcon = '<html><head><script src="./assets/index-new.js"></script>'
+ + '<link rel="stylesheet" href="./assets/index-new.css"><link rel="icon" href="./icon-512.png"></head></html>'
+ globalThis.fetch = async u => (String(u) === 'index.html'
+ ? { ok: true, status: 200, redirected: false, text: async () => withIcon }
+ : String(u).endsWith('.png') ? { ok: false, status: 404 } : { ok: true, status: 200, clone: () => ({}) })
+
+ await fire('install')
+ expect(skipWaiting).toBe(1)
+ await fire('activate')
+
+ expect(await globalThis.caches.keys()).toEqual([CACHE])
+ const c = await globalThis.caches.open(CACHE)
+ expect(c.keys()).toEqual(expect.arrayContaining(['./assets/index-new.js', './assets/index-new.css', 'index.html']))
+ })
+
it('an install that got the shell takes over and drops the previous build', async () => {
await loadSW()
await previousBuild()