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.

Service worker: a slow network no longer cuts a chunk or a language off mid-download, and iOS 15 keeps its offline start (#274)

Duarte Santos5842f2891ca2
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index b3599d72d..8e71c5952 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -108,6 +108,9 @@ self.addEventListener('pushsubscriptionchange', e => {
// the API's own `Cache-Control: no-store`, so the worker has to know to stay out of the way.
const API = (() => { try { return new URL('api/', location.href).pathname } catch { return '/api/' } })()
+// How long a request for the app itself waits on the network before a cached copy answers it.
+const NET_WAIT_MS = 3000
+
self.addEventListener('fetch', e => {
const url = new URL(e.request.url)
if (e.request.method !== 'GET' || url.origin !== location.origin) return
@@ -125,12 +128,25 @@ self.addEventListener('fetch', e => {
// is why the shell never used to survive an offline reload.
// A dead radio does not reject fetch() quickly — it just never settles — so a cold-launch of
// the installed app with no network stayed on a blank screen forever, with the cache fallback
- // below never getting a chance to run (issue #274). Bounding the request with an abortable
- // timeout gives it up and falls back to the cached shell instead.
- e.respondWith(fetch(e.request, { signal: AbortSignal.timeout(3000) }).then(res => {
- if (res.ok) { const copy = res.clone(); caches.open(CACHE).then(c => c.put(e.request, copy)).catch(() => {}) }
- return res
- }).catch(() => caches.match(e.request, { ignoreSearch: true }).then(hit =>
- hit || (e.request.mode === 'navigate' ? caches.match('index.html') : undefined)
- )))
+ // never getting a chance to run (issue #274). So a request the network has not answered within
+ // NET_WAIT_MS is answered from the cache, when the cache has it. Nothing is aborted: an abort
+ // that fires once the headers are in errors the body the page is still reading, and on a slow
+ // connection a locale pack or a chunk that was on its way failed outright, every start again,
+ // since a body that never finishes is never cached either (and AbortSignal.timeout, which the
+ // abort used, does not exist before iOS 16: the handler threw before it answered at all, the
+ // cache fallback with it). A request the cache cannot answer keeps waiting for the network, as
+ // it always did; and the network's answer, whenever it comes, still refreshes the cache.
+ const fromCache = () => caches.match(e.request, { ignoreSearch: true }).then(hit =>
+ hit || (e.request.mode === 'navigate' ? caches.match('index.html') : undefined))
+ e.respondWith(new Promise(resolve => {
+ const slow = setTimeout(() => fromCache().then(hit => { if (hit) resolve(hit) }, () => {}), NET_WAIT_MS)
+ fetch(e.request).then(res => {
+ clearTimeout(slow)
+ if (res.ok) { const copy = res.clone(); caches.open(CACHE).then(c => c.put(e.request, copy)).catch(() => {}) }
+ resolve(res)
+ }, () => {
+ clearTimeout(slow)
+ resolve(fromCache())
+ })
+ }))
})
diff --git a/frontend/src/lib/sw-offline-launch.test.js b/frontend/src/lib/sw-offline-launch.test.js
index d5015c6e4..3b6a57884 100644
--- a/frontend/src/lib/sw-offline-launch.test.js
+++ b/frontend/src/lib/sw-offline-launch.test.js
@@ -3,18 +3,45 @@
// network-first fetch handler — a dead radio does not reject fetch() quickly, it just never
// settles, so the .catch() that falls back to the cached shell never runs.
//
+// The first fix aborted every request after 3 s. An abort that fires once the headers are in
+// errors the body the page is still reading, so on a slow connection a locale pack or a chunk
+// that was on its way failed outright; and AbortSignal.timeout does not exist before iOS 16,
+// where the handler threw before it answered at all. The worker now answers from the cache once
+// the network has kept a request waiting 3 s, and aborts nothing.
+//
// This loads the real production file (public/sw.js) into a sandboxed context and drives its
// actual 'fetch' listener, rather than re-implementing the logic here — the thing under test is
-// the shipped worker, not a description of it.
-import { describe, it, expect, vi } from 'vitest'
+// the shipped worker, not a description of it. Time is a clock the test moves by hand; the
+// sandbox's AbortSignal.timeout runs on it too, and the network stub errors a body it is still
+// sending when its request is aborted, the way fetch does.
+import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import vm from 'node:vm'
const swSource = readFileSync(fileURLToPath(new URL('../../public/sw.js', import.meta.url)), 'utf8')
+const settle = () => new Promise(r => setImmediate(r))
+
+function manualClock() {
+ let now = 0
+ let id = 0
+ const timers = new Map()
+ return {
+ setTimeout: (fn, ms) => { timers.set(++id, { at: now + (ms || 0), fn }); return id },
+ clearTimeout: t => { timers.delete(t) },
+ async advance(ms) {
+ now += ms
+ for (const [k, t] of [...timers].sort((a, b) => a[1].at - b[1].at)) {
+ if (t.at <= now && timers.has(k)) { timers.delete(k); t.fn() }
+ }
+ await settle()
+ },
+ }
+}
+
/** Run the real sw.js source in a sandbox and hand back what it registered. */
-function loadServiceWorker({ fetchImpl, timeoutImpl }) {
+function loadServiceWorker({ fetchImpl, abortSignal = true }) {
const listeners = {}
const cacheStore = new Map()
const cache = {
@@ -28,18 +55,28 @@ function loadServiceWorker({ fetchImpl, timeoutImpl }) {
clients: { claim: () => Promise.resolve() },
registration: {}
}
+ const clock = manualClock()
const context = {
self,
caches: { open: () => Promise.resolve(cache), keys: () => Promise.resolve([]), delete: () => Promise.resolve(true), match: cache.match },
fetch: fetchImpl,
location: { origin: 'https://gym.example' },
URL,
- AbortSignal: { timeout: timeoutImpl },
+ setTimeout: clock.setTimeout,
+ clearTimeout: clock.clearTimeout,
console
}
+ // iOS before 16 has AbortSignal but not AbortSignal.timeout.
+ context.AbortSignal = !abortSignal ? {} : {
+ timeout: ms => {
+ const c = new AbortController()
+ clock.setTimeout(() => c.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError')), ms)
+ return c.signal
+ }
+ }
vm.createContext(context)
vm.runInContext(swSource, context)
- return { listeners, cache }
+ return { listeners, cache, clock }
}
function makeFetchEvent(url, mode = 'navigate') {
@@ -51,43 +88,98 @@ function makeFetchEvent(url, mode = 'navigate') {
}
}
-describe('service worker offline cold-launch (issue #274)', () => {
- it('wires an abortable timeout onto the navigation fetch instead of waiting on it forever', async () => {
- let timeoutCalls = 0
- let controller
- // Stands in for the real AbortSignal.timeout: returns a signal the test can fire on demand,
- // instead of waiting out a real multi-second timer.
- const timeoutImpl = () => {
- timeoutCalls++
- controller = new AbortController()
- return controller.signal
- }
- // A dead radio: the request never resolves or rejects on its own, exactly like a real
- // offline navigation attempt — only an abort ends it.
- const hungFetch = vi.fn((req, opts) => new Promise((resolve, reject) => {
- opts?.signal?.addEventListener('abort', () => reject(new Error('The operation was aborted.')))
- }))
+// A dead radio: the request never resolves or rejects on its own — only an abort ends it.
+const deadRadio = (req, opts) => new Promise((resolve, reject) => {
+ opts?.signal?.addEventListener('abort', () => reject(opts.signal.reason))
+})
- const { listeners, cache } = loadServiceWorker({ fetchImpl: hungFetch, timeoutImpl })
+// Headers at once, the body in two parts: the second when the test calls `finish()`. An abort
+// before then errors the body, as fetch does.
+function slowBody(first, rest) {
+ const enc = new TextEncoder()
+ const net = {}
+ net.fetch = (req, opts) => {
+ const body = new ReadableStream({ start(c) { net.stream = c; c.enqueue(enc.encode(first)) } })
+ opts?.signal?.addEventListener('abort', () => net.stream.error(opts.signal.reason))
+ return Promise.resolve(new Response(body, { status: 200, headers: { 'content-type': 'text/javascript' } }))
+ }
+ net.finish = () => { net.stream.enqueue(enc.encode(rest)); net.stream.close() }
+ return net
+}
+
+// A server that takes its time before it answers at all: the test hands the answer over.
+function lateAnswer() {
+ const net = {}
+ net.fetch = (req, opts) => new Promise((resolve, reject) => {
+ net.answer = body => resolve(new Response(body, { status: 200 }))
+ opts?.signal?.addEventListener('abort', () => reject(opts.signal.reason))
+ })
+ return net
+}
+
+describe('service worker offline cold-launch (issue #274)', () => {
+ it('a navigation the network never answers is answered from the cached shell after 3 s, not before', async () => {
+ const { listeners, cache, clock } = loadServiceWorker({ fetchImpl: deadRadio })
await cache.put('index.html', new Response('cached-shell'))
const e = makeFetchEvent('https://gym.example/')
listeners.fetch(e)
-
- // A real timeout must actually be attached to the request - without one, this whole
- // recovery path is unreachable no matter how long the app is left running.
- expect(timeoutCalls).toBeGreaterThan(0)
-
- // Flushing a few microtask turns must not resolve it early on its own.
- const early = await Promise.race([
- e.response.then(() => 'settled'),
- Promise.resolve().then(() => {}).then(() => {}).then(() => 'still-pending')
- ])
+ await clock.advance(2999)
+ const early = await Promise.race([e.response.then(() => 'settled'), settle().then(() => 'still-pending')])
expect(early).toBe('still-pending')
- // Once the timeout fires, the app must recover from cache instead of staying blank.
- controller.abort()
+ await clock.advance(1)
const res = await e.response
expect(await res.text()).toBe('cached-shell')
})
+
+ it('a script whose body is still arriving after 3 s reaches the page whole, and is cached', async () => {
+ const net = slowBody('export const pack = {', ' hello: "Hallo" }')
+ const { listeners, cache, clock } = loadServiceWorker({ fetchImpl: net.fetch })
+ await cache.put('https://gym.example/assets/de-abc.js', new Response('the copy from the last build'))
+
+ const e = makeFetchEvent('https://gym.example/assets/de-abc.js', 'cors')
+ listeners.fetch(e)
+ const res = await e.response
+ await clock.advance(3000)
+ net.finish()
+
+ expect(await res.text()).toBe('export const pack = { hello: "Hallo" }')
+ await settle()
+ expect(await (await cache.match('https://gym.example/assets/de-abc.js')).text()).toBe('export const pack = { hello: "Hallo" }')
+ })
+
+ it('a request the cache cannot answer waits for a slow network past 3 s instead of failing', async () => {
+ const net = lateAnswer()
+ const { listeners, clock } = loadServiceWorker({ fetchImpl: net.fetch })
+
+ const e = makeFetchEvent('https://gym.example/assets/hi-new.js', 'cors')
+ listeners.fetch(e)
+ await clock.advance(10000)
+ net.answer('export default {}')
+
+ const res = await e.response
+ expect(res).toBeTruthy()
+ expect(await res.text()).toBe('export default {}')
+ })
+
+ it('a network that fails outright falls back to the cache at once', async () => {
+ const { listeners, cache } = loadServiceWorker({ fetchImpl: () => Promise.reject(new TypeError('Failed to fetch')) })
+ await cache.put('index.html', new Response('cached-shell'))
+
+ const e = makeFetchEvent('https://gym.example/')
+ listeners.fetch(e)
+ expect(await (await e.response).text()).toBe('cached-shell')
+ })
+
+ it('works where AbortSignal.timeout does not exist (iOS before 16)', async () => {
+ const { listeners, cache, clock } = loadServiceWorker({ fetchImpl: deadRadio, abortSignal: false })
+ await cache.put('index.html', new Response('cached-shell'))
+
+ const e = makeFetchEvent('https://gym.example/')
+ expect(() => listeners.fetch(e)).not.toThrow()
+ expect(e.response).toBeTruthy()
+ await clock.advance(3000)
+ expect(await (await e.response).text()).toBe('cached-shell')
+ })
})