fix(pwa): an upgrade counts as applied once the new build has taken over

After a server upgrade the app wrote the new version into its marker
before the service worker had fetched the new build. When that fetch
failed, when the new precache broke off halfway, or when the browser had
already swapped workers before the version check answered, the page kept
the old bundle, and every later launch took the marker at its word and
never tried again. An installed PWA went on showing the previous UI.

The marker now moves only once the handover is done or turned out to be
unnecessary, so a failed attempt is simply retried on the next launch. A
failure no longer reloads into the shell the old worker serves again, a
worker that took over before the check answered still gets its reload,
and no path reloads more than once per version and session. Caches and
workers are still never deleted.
This commit is contained in:
Maurice
2026-09-22 21:01:30 +02:00
parent bb515ac3cc
commit 615e74aff6
5 changed files with 782 additions and 51 deletions
+328
View File
@@ -0,0 +1,328 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
/*
* reconcileAppVersion notes the worker that served the page when its module
* loads, so every test installs its fake service-worker container first and
* then loads a fresh copy of the module.
*/
class FakeWorker extends EventTarget {
state: string
constructor(state: string) {
super()
this.state = state
}
become(state: string) {
this.state = state
this.dispatchEvent(new Event('statechange'))
}
}
class FakeRegistration {
installing: FakeWorker | null = null
waiting: FakeWorker | null = null
update = vi.fn(async () => this)
}
class FakeContainer extends EventTarget {
controller: FakeWorker | null
getRegistration = vi.fn()
constructor(controller: FakeWorker | null) {
super()
this.controller = controller
}
/** The browser activates a new worker and hands it this page. */
takeOver() {
this.controller = new FakeWorker('activated')
this.dispatchEvent(new Event('controllerchange'))
}
}
function installWorker(controller: FakeWorker | null = new FakeWorker('activated')) {
const registration = new FakeRegistration()
const container = new FakeContainer(controller)
container.getRegistration.mockResolvedValue(registration)
Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: container })
return { container, registration }
}
/** update() finds a new sw.js and leaves the new worker installing. */
function updateInstalls(registration: FakeRegistration) {
const incoming = new FakeWorker('installing')
registration.update.mockImplementation(async () => {
registration.installing = incoming
return registration
})
return incoming
}
async function loadModule() {
vi.resetModules()
return import('./versionHandover')
}
/** Lets one kind of storage throw while the other keeps working. */
function breakStorage(method: 'getItem' | 'setItem', broken: () => Storage) {
const original = Storage.prototype[method] as (...args: string[]) => unknown
vi.spyOn(Storage.prototype, method).mockImplementation(function (this: Storage, ...args: string[]) {
if (this === broken()) throw new DOMException('The operation is insecure.', 'SecurityError')
return original.apply(this, args)
} as never)
}
const marker = () => localStorage.getItem('trek_app_version')
let reload: ReturnType<typeof vi.fn>
beforeEach(() => {
reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
})
afterEach(() => {
vi.restoreAllMocks()
delete (navigator as { serviceWorker?: unknown }).serviceWorker
})
describe('reconcileAppVersion: when nothing needs to happen', () => {
it.each([
['nothing at all', undefined],
['a number', 431],
['an empty string', ''],
['markup', '<script>alert(1)</script>'],
['an overlong value', '4'.repeat(65)],
])('FE-UTIL-VERSION-001: ignores %s as the reported version', async (_label, reported) => {
const { container } = installWorker()
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion(reported)
expect(marker()).toBe('4.3.0')
expect(container.getRegistration).not.toHaveBeenCalled()
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-002: the first launch on a device only records the version', async () => {
const { container } = installWorker()
const { reconcileAppVersion } = await loadModule()
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.1')
expect(container.getRegistration).not.toHaveBeenCalled()
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-003: the version this device already runs changes nothing', async () => {
const { container } = installWorker()
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.1')
await reconcileAppVersion('4.3.1')
expect(container.getRegistration).not.toHaveBeenCalled()
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-004: unreadable storage leaves the worker alone', async () => {
const { container } = installWorker()
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
breakStorage('getItem', () => localStorage)
await expect(reconcileAppVersion('4.3.1')).resolves.toBeUndefined()
expect(container.getRegistration).not.toHaveBeenCalled()
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-005: a browser that throws on the service worker itself still loads the app', async () => {
Object.defineProperty(navigator, 'serviceWorker', {
configurable: true,
get() { throw new DOMException('The operation is insecure.', 'SecurityError') },
})
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
// Nothing could be asked, so the next launch asks again.
expect(marker()).toBe('4.3.0')
expect(reload).not.toHaveBeenCalled()
})
})
describe('reconcileAppVersion: a new version without a handover to wait for', () => {
it('FE-UTIL-VERSION-010: without service worker support it records the version and reloads once', async () => {
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.1')
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-011: without a registration it records the version and reloads once', async () => {
const { container } = installWorker(null)
container.getRegistration.mockResolvedValue(undefined)
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.1')
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-012: a worker the browser swapped in since the page loaded gets one reload and no update', async () => {
const { container, registration } = installWorker()
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
// The browser's own check on navigation got there before the server answered.
container.takeOver()
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.1')
expect(reload).toHaveBeenCalledTimes(1)
expect(registration.update).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-013: a worker claiming a page it did not serve is no takeover', async () => {
const { container, registration } = installWorker(null)
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
container.controller = new FakeWorker('activated')
await reconcileAppVersion('4.3.1')
expect(registration.update).toHaveBeenCalledTimes(1)
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-014: an unchanged sw.js leaves nothing to hand over', async () => {
const { container, registration } = installWorker()
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(registration.update).toHaveBeenCalledTimes(1)
expect(marker()).toBe('4.3.1')
expect(reload).not.toHaveBeenCalled()
// A takeover later in the session is not this launch's business.
container.takeOver()
expect(reload).not.toHaveBeenCalled()
})
})
describe('reconcileAppVersion: handing over to the new build', () => {
it('FE-UTIL-VERSION-020: reloads once the new worker has taken over, and only then records the version', async () => {
const { container, registration } = installWorker()
const incoming = updateInstalls(registration)
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.0')
expect(reload).not.toHaveBeenCalled()
incoming.become('activated')
container.takeOver()
expect(marker()).toBe('4.3.1')
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-021: a worker already installed and waiting counts as the incoming one', async () => {
const { container, registration } = installWorker()
registration.waiting = new FakeWorker('installed')
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.0')
container.takeOver()
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-022: an update that fails is left for the next launch, without a reload', async () => {
const { container, registration } = installWorker()
registration.update.mockRejectedValue(new TypeError('Failed to update a ServiceWorker: network error'))
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.0')
expect(reload).not.toHaveBeenCalled()
container.takeOver()
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-023: an install that goes redundant is left for the next launch', async () => {
const { container, registration } = installWorker()
const incoming = updateInstalls(registration)
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
incoming.become('redundant')
expect(marker()).toBe('4.3.0')
container.takeOver()
expect(reload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-024: a registration lookup that throws is left for the next launch', async () => {
const { container } = installWorker()
container.getRegistration.mockRejectedValue(new Error('no worker'))
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.0')
expect(reload).not.toHaveBeenCalled()
})
})
describe('reconcileAppVersion: the reload guard', () => {
it('FE-UTIL-VERSION-030: a marker that cannot be written does not turn into a reload loop', async () => {
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
breakStorage('setItem', () => localStorage)
// Every load of this session sees the new version again.
await reconcileAppVersion('4.3.1')
await reconcileAppVersion('4.3.1')
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.0')
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-031: the next release in the same session still gets its reload', async () => {
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
await reconcileAppVersion('4.3.1')
await reconcileAppVersion('4.3.2')
expect(marker()).toBe('4.3.2')
expect(reload).toHaveBeenCalledTimes(2)
})
it('FE-UTIL-VERSION-032: without session storage there is no guard, so there is no reload either', async () => {
const { reconcileAppVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.0')
breakStorage('getItem', () => sessionStorage)
await reconcileAppVersion('4.3.1')
expect(marker()).toBe('4.3.1')
expect(reload).not.toHaveBeenCalled()
})
})
+142
View File
@@ -0,0 +1,142 @@
/**
* Bringing an installed app onto the build the server runs now.
*
* Every launch asks the server for its version and compares it with a marker
* this device keeps. A different version means a release was deployed while
* this page may still run the previous bundle, answered from the service
* worker's precache. The worker is asked to fetch the new build; Workbox
* ('autoUpdate' with skipWaiting and clientsClaim) installs the new precache
* and only then drops the old one, and the page reloads once the new worker
* has taken over.
*
* The marker only moves once that handover is done or turned out to be
* unnecessary. A handover that failed (sw.js unreachable, a precache install
* that broke off on a flaky connection) is simply tried again on the next
* launch. That retry cannot loop: a failure never reloads, since the same old
* worker would answer the reload, and every reload here is limited to one per
* version and session.
*/
const VERSION_KEY = 'trek_app_version'
const RELOAD_KEY = 'trek_app_version_reload'
/** The worker controlling this page, or null. Reading it can throw where site data is blocked. */
function currentController(): ServiceWorker | null {
try {
return 'serviceWorker' in navigator ? navigator.serviceWorker.controller : null
} catch {
return null
}
}
// The worker that served this page, noted when the app loads. The browser checks
// sw.js on every navigation by itself, and when that check installs the new build
// before the server has told us its version, the takeover is over before anyone
// listens for it. A controller other than this one means the new shell is only a
// reload away. A page served without a worker came from the network, so a worker
// claiming it later is no takeover.
const servedBy = currentController()
function markApplied(version: string): void {
try { localStorage.setItem(VERSION_KEY, version) } catch { /* site data blocked */ }
}
/**
* One reload per server version and session. When the marker cannot be written,
* every load sees the new version again, and a page without a worker would
* otherwise reload forever. Without session storage there is no such guard, so
* the page stays as it is rather than risking the loop.
*/
function reloadOnce(version: string): void {
try {
if (sessionStorage.getItem(RELOAD_KEY) === version) return
sessionStorage.setItem(RELOAD_KEY, version)
} catch {
return
}
window.location.reload()
}
async function handOver(reg: ServiceWorkerRegistration, version: string): Promise<void> {
// Listening before asking for the update, so a quick takeover is not missed.
// Giving up disarms the listener: the reload belongs to this launch, and one
// arriving later in the session would hit the user in the middle of an edit.
let armed = true
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (!armed) return
markApplied(version)
reloadOnce(version)
}, { once: true })
try {
await reg.update()
} catch {
armed = false
return
}
const incoming = reg.installing ?? reg.waiting
if (!incoming) {
// sw.js is unchanged, so the release changed nothing the precache holds and
// the bundle this page runs is the current one.
armed = false
if (currentController() === servedBy) markApplied(version)
return
}
// Precaching is all or nothing: one failed request out of several hundred and
// the new worker is thrown away while the old one stays in charge. The marker
// has not moved, so the next launch comes back here.
incoming.addEventListener('statechange', () => {
if (incoming.state === 'redundant') armed = false
})
}
/**
* Compares the version the server reports with the one this device last ran
* and, when they differ, moves the app onto the new build. It never deletes a
* cache or unregisters a worker. That used to leave the device without an app
* shell until a fresh ~22 MB precache finished, so anyone who closed the app or
* lost signal in that window could no longer start it offline, and it threw
* away the map tiles and files the user had downloaded on purpose.
*/
export async function reconcileAppVersion(reported: unknown): Promise<void> {
// A version is a short release tag and nothing else. It arrives over the
// wire and is written to this device's storage, so only a value made of
// the characters a tag may contain is taken, as the match itself. Anything
// else is ignored, which also keeps a malformed value from being compared
// against the stored marker and starting an update on every launch.
const releaseTag = /^[\w.+-]{1,64}$/.exec(typeof reported === 'string' ? reported : '')
if (!releaseTag) return
const version = releaseTag[0]
let storedVersion: string | null
try {
storedVersion = localStorage.getItem(VERSION_KEY)
} catch {
return
}
if (!storedVersion) {
// The first launch on this device runs whatever the server just served.
markApplied(version)
return
}
if (storedVersion === version) return
let reg: ServiceWorkerRegistration | undefined
try {
reg = 'serviceWorker' in navigator ? await navigator.serviceWorker.getRegistration() : undefined
} catch {
// Left for the next launch. A reload now would only reach the old worker again.
return
}
// Without a worker the page came from the network and runs the new bundle
// already, so the reload only confirms it. A controller other than the one
// that served the page means the browser finished the handover by itself,
// and the reload is what shows the new build.
if (!reg || (servedBy && currentController() !== servedBy)) {
markApplied(version)
reloadOnce(version)
return
}
await handOver(reg, version)
}