From e746f60f8c1465cee3e6396064b927815a564ba6 Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Mon, 19 Oct 2026 16:48:57 +0300 Subject: [PATCH 1/2] fix: the first load after upgrading to 1.0 no longer fails Reproduced with the published 0.10.0 + runtime 0.2.5 files replaced by 1.0.0 under the same URLs, in a profile that had played packages: - The demo and every embed site kept /frame-assets/ (and the embed's /libraries/) for an hour plus a day stale, under names that stay the same between versions: runtime 0.2.5's boot script ran under the new worker and every play failed. Now no-cache, a 304 when unchanged. - The element waited 3 s for the updated worker and then went ahead with the old one, which a worker of another major cannot survive: the load stayed in `indexing`. Across a major it now waits up to 30 s. - A page from before the upgrade, still open, registers loads naming main.bundle.js; the worker wrote that document without the boot route, and the 1.0 boot script at the same URL stopped with "older than this runtime". Every document names the route now; 0.2 ignores it. Closes #49. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 24 +++++++-- README.md | 4 +- docs/single-worker.md | 3 +- packages/embed/README.md | 3 +- packages/embed/lib/build.mjs | 10 +++- packages/embed/tests/build.test.ts | 6 ++- packages/player/src/h5p-offline-player.ts | 26 +++++++--- packages/player/src/shared/constants.ts | 9 ++++ packages/player/src/sw/frame-document.ts | 7 ++- packages/player/tests/browser/runtime.test.ts | 17 +++++++ .../tests/browser/worker-update.test.ts | 50 ++++++++++++++++++- .../player/tests/unit/frame-document.test.ts | 4 +- packages/player/vite.plugins.ts | 11 ++-- vercel.json | 2 +- 14 files changed, 148 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a7c66386..0348bde1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1128,9 +1128,13 @@ element, and the element acts. That relay is why `frame-document.ts` has a `mess `unversioned-pack.h5p` with `pack.test.ts` pins it; the walk tries each library both ways. **Across versions**: a record that names `mainJs` came from an element paired with the runtime up to 0.2, and the worker still writes that document — the loader, the upgrade list in the - config — so an element from before keeps playing against an updated worker; a later boot script - given a document without the `boot` URL, a worker from before, says to update the player and - `h5p-sw.js` together. An element of this player with a runtime up to 0.2 through `assets-base` + config — so an element from before keeps playing against an updated worker. It names the + `boot` route in that document too (#49): a page from before an upgrade, still open, registers + its loads naming the loader, and on a host that serves the runtime at one path — the demo, an + embed site, any copy of `dist/` — the boot script at that path is 1.0's by then, which boots + from the route and leaves the loader's 404 alone; without the route it stopped every such load. + A later boot script given a document without the `boot` URL, a worker from before, says to + update the player and `h5p-sw.js` together. An element of this player with a runtime up to 0.2 through `assets-base` cannot work and does not try: the peer range says which runtime it plays with. - **A 404 from the virtual server is load-bearing.** A library's `library.json` is looked for under the versioned folder name and then the bare one, and the first 404 is what sends the @@ -1274,6 +1278,12 @@ element, and the element acts. That relay is why `frame-document.ts` has a `mess the control channel, and on a difference calls `registration.update()` and waits for the new worker, all bounded by `WORKER_UPDATE_TIMEOUT_MS`; offline or past it, the load goes ahead with the worker it has. Same bytes after the update is a host's stale `h5p-sw.js`, still a warning. + Going ahead is right within a major, whose older worker serves the element, and not across + one, which it cannot: from 0.10 to 1.0, measured with the published files under the same URLs + and `h5p-sw.js` answered after four seconds, the load went ahead with the 0.10 worker, the new + one took over halfway through, and it stayed in `indexing` (#49). So for a worker of another + major the wait is `WORKER_MAJOR_UPDATE_TIMEOUT_MS`, thirty seconds; the new worker's activation, + which deletes the old major's caches, took about a second of it with four caches or 124. `activated()` waits for the newest worker — installing, then waiting, then active — since a changed script URL (a bundler's hash) installs a new worker beside the old active one; that wait is bounded by the same timeout whenever an activated worker can serve, because a host's @@ -2361,8 +2371,12 @@ SPA-fallback trap described above cannot happen there. longest prefix of the page's — so a page names no current link. The footers stay in the pages: each lists its own links. The per-page metadata — title, description, Open Graph and Twitter tags, each written two or three times — is the obvious next candidate and has not been done. -- **Caching.** Hashed files under `/assets/` are immutable; `h5p-sw.js` is `no-cache`; - `frame-assets/` and `fixtures/` revalidate hourly. Fixtures also carry permissive CORS with +- **Caching.** Hashed files under `/assets/` are immutable; `h5p-sw.js` and `frame-assets/` are + `no-cache`; `fixtures/` revalidate hourly. `frame-assets/` was hourly, with a day of + `stale-while-revalidate`, until #49: its file names stay the same from one runtime to the next, + and after the 1.0 deploy a returning browser ran runtime 0.2.5's boot script, kept from before, + under the new worker — "Cannot read properties of undefined (reading 'H5P')" on every play for + that hour. The embed command's headers changed the same way, for `/libraries/` as well. Fixtures also carry permissive CORS with `Range` allowed and `Content-Range` exposed, so another player instance can be pointed at them. - **The demo plays real content; the fixtures never ship.** The player's `public/fixtures/` is the test suite's stub library saying "Served from the archive, never extracted to disk", which is right diff --git a/README.md b/README.md index 04eb3065..15502bbb 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,9 @@ cp -r node_modules/@missing-elements/h5p-libraries/parts public/h5p-libraries cp node_modules/@missing-elements/h5p-libraries/libraries.txt public/h5p-libraries/ ``` -To upgrade, delete the folders and copy them again. +To upgrade, delete the folders and copy them again. Serve them with `Cache-Control: no-cache`, or +with no caching header at all: the file names stay the same from one version to the next, so a +copy a browser kept from before an upgrade would run against the new Service Worker. Or load the element and the runtime from jsDelivr, and copy only the Service Worker: diff --git a/docs/single-worker.md b/docs/single-worker.md index ff43e73d..de7da789 100644 --- a/docs/single-worker.md +++ b/docs/single-worker.md @@ -17,7 +17,8 @@ Routes then live under `h5p/`, and the element uses them instead of r ## Upgrading - Cache names include the package major version; minor and patch updates reuse cached packages, and a worker update never invalidates them. A major starts the cache afresh, and each package is downloaded once more; saved state is kept. -- After an upgrade, the element updates its own worker before the first load (waiting up to three seconds). +- After an upgrade, the element updates its own worker before the first load, waiting up to three seconds, or up to thirty when the worker is from another major version, which cannot serve it. +- Serve the runtime's folder and a copy of the library pack revalidated (`Cache-Control: no-cache`), or under a path with the version in it, as jsDelivr's addresses are. Their file names stay the same from one version to the next, and a copy the browser kept from before an upgrade runs against the new worker: from 0.10 to 1.0, kept for an hour, it failed every play for that hour. - Installed without a build step: re-download `h5p-sw.js` after upgrading. The element logs a warning when versions differ. - Single-worker hosts update their own worker; offer a reload on `controllerchange`, as the demo's app does. diff --git a/packages/embed/README.md b/packages/embed/README.md index d31c94d8..8b0af638 100644 --- a/packages/embed/README.md +++ b/packages/embed/README.md @@ -65,7 +65,8 @@ The headers themselves, for a host not listed: |---|---| | every path | `Content-Security-Policy` (the policy the command prints, with `frame-ancestors` from `--ancestors`), `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin` | | `/h5p-sw.js` | `Cache-Control: no-cache`, so an update reaches learners on their next visit | -| `/frame-assets/*`, `/resizer.js`, `/libraries/*` | `Cache-Control: public, max-age=3600, stale-while-revalidate=86400` | +| `/frame-assets/*`, `/libraries/*` | `Cache-Control: no-cache`: the runtime and the library pack keep their file names between versions, so a copy from before an update must not be used after it | +| `/resizer.js` | `Cache-Control: public, max-age=3600, stale-while-revalidate=86400` | To update, run the command again with `--force` and redeploy. diff --git a/packages/embed/lib/build.mjs b/packages/embed/lib/build.mjs index 261711d8..26cb08ea 100644 --- a/packages/embed/lib/build.mjs +++ b/packages/embed/lib/build.mjs @@ -137,6 +137,12 @@ export function contentSecurityPolicy({ packages = null, ancestors = null, meta /** Header rules, one set for every host format: the policy everywhere, and the caching that matters. */ function headerRules(csp) { const revalidate = 'public, max-age=3600, stale-while-revalidate=86400' + // Asked again on every load, a 304 when nothing changed. The runtime and the pack keep their + // file names from one version to the next, and the worker's version decides which files it + // needs: kept for an hour, the runtime of the version before ran under the new worker after an + // update, and every play failed until the hour was out (0.10 to 1.0, measured, #49); a part + // kept from the pack before fails its hash against the new index. + const current = 'no-cache' return [ { path: '/*', @@ -148,9 +154,9 @@ function headerRules(csp) { }, // The worker is checked on every load, so an update reaches learners on their next visit. { path: '/h5p-sw.js', headers: { 'Cache-Control': 'no-cache' } }, - { path: '/frame-assets/*', headers: { 'Cache-Control': revalidate } }, + { path: '/frame-assets/*', headers: { 'Cache-Control': current } }, { path: '/resizer.js', headers: { 'Cache-Control': revalidate } }, - { path: '/libraries/*', headers: { 'Cache-Control': revalidate } } + { path: '/libraries/*', headers: { 'Cache-Control': current } } ] } diff --git a/packages/embed/tests/build.test.ts b/packages/embed/tests/build.test.ts index 1880be53..f310e29f 100644 --- a/packages/embed/tests/build.test.ts +++ b/packages/embed/tests/build.test.ts @@ -103,13 +103,17 @@ describe('the site', () => { const vercel = JSON.parse(await readFile(join(out, 'vercel.json'), 'utf8')) expect(vercel.headers[0]).toEqual({ source: '/(.*)', headers: expect.arrayContaining([{ key: 'Content-Security-Policy', value: site.csp }]) }) expect(vercel.headers).toContainEqual({ source: '/h5p-sw.js', headers: [{ key: 'Cache-Control', value: 'no-cache' }] }) + // The runtime and the pack keep their names between versions, so neither is kept unasked (#49). + for (const folder of ['/frame-assets/', '/libraries/']) { + expect(vercel.headers.find((rule: { source: string }) => rule.source.startsWith(folder)).headers).toEqual([{ key: 'Cache-Control', value: 'no-cache' }]) + } expect(await readFile(join(out, 'config.js'), 'utf8')).toContain('{"libraries":true,"packages":["https://cdn.example.org"],"defaultLibraries":null}') // The three server formats say the same as the two host files, each in its own syntax. const caddy = await readFile(join(out, 'Caddyfile'), 'utf8') expect(caddy).toContain(`\theader Content-Security-Policy "${site.csp}"`) expect(caddy).toContain('\theader /h5p-sw.js Cache-Control "no-cache"') - expect(caddy).toContain('\theader /frame-assets/* Cache-Control "public, max-age=3600') + expect(caddy).toContain('\theader /frame-assets/* Cache-Control "no-cache"') const nginx = await readFile(join(out, 'nginx.conf'), 'utf8') expect(nginx).toContain(`add_header Content-Security-Policy "${site.csp}" always;`) expect(nginx).toContain('location = /h5p-sw.js {') diff --git a/packages/player/src/h5p-offline-player.ts b/packages/player/src/h5p-offline-player.ts index 1d8ae661..56417f19 100644 --- a/packages/player/src/h5p-offline-player.ts +++ b/packages/player/src/h5p-offline-player.ts @@ -9,11 +9,13 @@ import { packLibrariesIn } from './shared/pack' import { CONTROL_TIMEOUT_MS, LIBRARY_PACK_BASE, + MAJOR_VERSION, PACK_INDEX_CACHE, SAVE_INTERVAL_S, SILENT_ANSWER_TIMEOUT_MS, VERSION, WARM_ENTRY, + WORKER_MAJOR_UPDATE_TIMEOUT_MS, WORKER_UPDATE_TIMEOUT_MS } from './shared/constants' import { @@ -1450,13 +1452,16 @@ export class H5PPlayerElement extends HTMLElement { * into the boot, under a frame document the old version wrote. So a version that differs asks * for the update itself and waits for it, bounded: offline, or on a slow host, the load goes * ahead with the worker it has. A script that is still old after the update is the host's copy, - * which only the host can replace; that stays a warning. + * which only the host can replace; that stays a warning. A worker of another major cannot serve + * this element at all, so for one the load waits as long as the update takes, within + * `WORKER_MAJOR_UPDATE_TIMEOUT_MS`. */ private async ensureCurrentWorker(registration: ServiceWorkerRegistration): Promise { const before = await this.workerVersion() if (before === null || before === VERSION) return - await withTimeout(updateWorker(registration), WORKER_UPDATE_TIMEOUT_MS, undefined) + const wait = majorOf(before) === MAJOR_VERSION ? WORKER_UPDATE_TIMEOUT_MS : WORKER_MAJOR_UPDATE_TIMEOUT_MS + await withTimeout(updateWorker(registration, wait), wait, undefined) // Asked again rather than trusting what the update reported: with `skipWaiting`, a new // worker can be active before `update()` has resolved, leaving nothing in `installing`. warnIfDifferent((await this.workerVersion()) ?? before) @@ -2052,7 +2057,7 @@ async function stillRegistered(registration: ServiceWorkerRegistration): Promise * wait with it. A newest worker that turns redundant falls back to the one running for the same * reason. */ -function activated(registration: ServiceWorkerRegistration): Promise { +function activated(registration: ServiceWorkerRegistration, wait = WORKER_UPDATE_TIMEOUT_MS): Promise { const running = registration.active?.state === 'activated' ? registration.active : null const worker = registration.installing ?? registration.waiting ?? registration.active if (!worker) return Promise.reject(new PlayerError('no-worker', 'The registration has no worker')) @@ -2071,18 +2076,18 @@ function activated(registration: ServiceWorkerRegistration): Promise { +async function updateWorker(registration: ServiceWorkerRegistration, wait: number): Promise { try { await registration.update() - if (registration.installing || registration.waiting) await activated(registration) + if (registration.installing || registration.waiting) await activated(registration, wait) } catch { // Offline, a refused script, a worker that failed to install: the running one serves. } @@ -2096,6 +2101,11 @@ function withTimeout(promise: Promise, ms: number, fallback: T): Promise clearTimeout(timer)) } +/** A version's major, `0` of `0.10.0`; `NaN` for what is not a version, which matches no major. */ +function majorOf(version: string): number { + return Number(/^(\d+)\./.exec(version)?.[1] ?? NaN) +} + function warnIfDifferent(workerVersion: string | undefined): void { if (workerVersion && workerVersion !== VERSION) { console.warn( diff --git a/packages/player/src/shared/constants.ts b/packages/player/src/shared/constants.ts index f3742f06..88f87ada 100644 --- a/packages/player/src/shared/constants.ts +++ b/packages/player/src/shared/constants.ts @@ -205,6 +205,15 @@ export const SAVE_INTERVAL_S = 10 */ export const WORKER_UPDATE_TIMEOUT_MS = 3_000 +/** + * The same, when the running worker is of another major. Within a major an older worker serves the + * element (docs/compatibility.md), so the load need not wait long; across one it cannot, and going + * ahead failed the load: from 0.10 to 1.0, measured with the script answered after four seconds, + * the load went ahead with the old worker, the new one took over halfway through, and it never + * left `indexing`. The new worker's activation deletes the old major's caches, about a second more. + */ +export const WORKER_MAJOR_UPDATE_TIMEOUT_MS = 30_000 + /** How long the element waits for the Service Worker to answer on the control channel. */ export const CONTROL_TIMEOUT_MS = 30_000 /** diff --git a/packages/player/src/sw/frame-document.ts b/packages/player/src/sw/frame-document.ts index 03c5fcd9..1a261959 100644 --- a/packages/player/src/sw/frame-document.ts +++ b/packages/player/src/sw/frame-document.ts @@ -373,7 +373,10 @@ export function buildFrameDocument(options: FrameDocumentOptions): string { // A runtime up to 0.2 boots through h5p-standalone's `main.bundle.js`, which the document loads // ahead of the boot script, and takes the upgrade list from here; a later one has no such file - // and asks the `boot` route for what to load. + // and asks the `boot` route for what to load. The route is named in every document, the older + // kind too: a page from before an upgrade, still open, registers its loads naming the loader, + // and on a host that serves the runtime at one path the boot script there is the new one by now, + // which boots from the route and leaves the loader's 404 alone. A 0.2 boot script ignores it. const loader = assets.mainJs // A JSON block, not a script: it is data, so it needs no nonce, and the boot script proper — @@ -382,7 +385,7 @@ export function buildFrameDocument(options: FrameDocumentOptions): string { const bootConfig = JSON.stringify({ pkgId, h5pJsonPath: virtualRoot, - boot: loader ? undefined : options.bootUrl, + boot: options.bootUrl, frameJs: assets.frameJs, frameCss: assets.frameCss, title: options.title, diff --git a/packages/player/tests/browser/runtime.test.ts b/packages/player/tests/browser/runtime.test.ts index 9c0d1081..205638a1 100644 --- a/packages/player/tests/browser/runtime.test.ts +++ b/packages/player/tests/browser/runtime.test.ts @@ -34,6 +34,23 @@ describe('the runtime property', () => { expect(frameDocument(player).querySelector('style')?.textContent).toContain(runtime.fonts[0].url) }) + it('plays a load that names the loader of runtime 0.2, on a host that has since upgraded', async () => { + // A page from before an upgrade, still open: its element registers its loads naming + // h5p-standalone's `main.bundle.js`, which the upgraded host no longer has, and the boot script + // at the URL it names is this runtime's by now. The worker writes the old kind of document for + // such a load, the route in it too, and this boot script boots from the route; without the + // route it stopped with "older than this runtime" (#49). + const player = createPlayer() + player.runtime = { ...runtime, mainJs: `${base}main.bundle.js` } as typeof runtime + const settled = waitForSettled(player) + player.setAttribute('src', FIXTURES.basic) + + const result = await settled + if (!result.ok) expect.fail(`${result.detail.code} — ${result.detail.message}`) + const scripts = [...frameDocument(player).querySelectorAll('script[src]')].map((script) => script.getAttribute('src')) + expect(scripts).toContain(`${base}main.bundle.js`) + }) + it('refuses a value missing one of the three files, since that frame would never boot', () => { const player = createPlayer() player.runtime = { frameJs: 'b', frameCss: 'c' } as never diff --git a/packages/player/tests/browser/worker-update.test.ts b/packages/player/tests/browser/worker-update.test.ts index afe48fd4..5da6706a 100644 --- a/packages/player/tests/browser/worker-update.test.ts +++ b/packages/player/tests/browser/worker-update.test.ts @@ -1,6 +1,6 @@ import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' import '../../src/h5p-offline-player' -import { VERSION } from '../../src/shared/constants' +import { MAJOR_VERSION, VERSION } from '../../src/shared/constants' import { FIXTURES, frameFetch, play } from './utils' /** @@ -13,7 +13,24 @@ import { FIXTURES, frameFetch, play } from './utils' const SW = '/versioned/h5p-sw.js' const SCOPE = new URL('/versioned/h5p/', location.href).href -const serveVersion = (version: string) => fetch(`/versioned/__version?v=${encodeURIComponent(version)}`) +/** What `/versioned/h5p-sw.js` says it is from now on, and how late it is answered. */ +const serveVersion = (version: string, delay = 0) => fetch(`/versioned/__version?v=${encodeURIComponent(version)}&delay=${delay}`) + +/** The worker the scope runs brought to `version`, as an earlier visit would have left it. */ +async function installVersion(version: string) { + await serveVersion(version) + // Registered here when no test before has, so that each test stands on its own. + const registration = (await navigator.serviceWorker.getRegistration(SCOPE)) ?? (await navigator.serviceWorker.register(SW, { scope: SCOPE })) + await registration.update() + await activatedNewest(registration) +} + +/** Resolves once nothing is installing or waiting in the scope. */ +async function activatedNewest(registration: ServiceWorkerRegistration) { + const worker = registration.installing ?? registration.waiting + if (!worker) return + await new Promise((done) => worker.addEventListener('statechange', () => worker.state === 'activated' && done())) +} /** The version the worker controlling the frame reports, over its own `_ping` route. */ async function frameWorkerVersion(player: Parameters[0]): Promise { @@ -59,4 +76,33 @@ describe('a player update', () => { expect(replaced).toBe(false) expect(registration?.installing ?? registration?.waiting ?? null).toBeNull() }) + + it('waits for the update however slow the script, when the worker running is of another major', async () => { + // A worker of the major before cannot serve this element: from 0.10 to 1.0, a load that went + // ahead with it after three seconds never left `indexing` (#49). + await installVersion(`${MAJOR_VERSION - 1}.99.0`) + await serveVersion('', 4_000) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const started = performance.now() + const player = await play(FIXTURES.basic, { sw: SW }) + + expect(performance.now() - started).toBeGreaterThan(4_000) + expect(await frameWorkerVersion(player)).toBe(VERSION) + }, 60_000) + + it('goes ahead after three seconds within a major, where the worker running serves the element', async () => { + const older = `${MAJOR_VERSION}.0.0-older` + await installVersion(older) + // Slower than the wait, by a margin the load cannot use up before it is ready. + await serveVersion('', 8_000) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const player = await play(FIXTURES.basic, { sw: SW }) + + expect(await frameWorkerVersion(player)).toBe(older) + expect(warn.mock.calls.some(([line]) => String(line).includes(`Service Worker is ${older}`))).toBe(true) + // The update it gave up waiting for still lands, for the next load. + await activatedNewest((await navigator.serviceWorker.getRegistration(SCOPE))!) + }, 60_000) }) diff --git a/packages/player/tests/unit/frame-document.test.ts b/packages/player/tests/unit/frame-document.test.ts index cd7a7db6..ae5e5d65 100644 --- a/packages/player/tests/unit/frame-document.test.ts +++ b/packages/player/tests/unit/frame-document.test.ts @@ -242,7 +242,9 @@ describe('buildFrameDocument', () => { expect(html).toContain('') expect(html.indexOf('main.bundle.js')).toBeLessThan(html.indexOf('frame-boot.js')) expect(html).toContain('"upgrades":["H5P.QuestionSet-1.21","H5P.Summary-1.10"]') - expect(bootConfigOf(html).boot).toBeUndefined() + // The route too: on a host that serves the runtime at one path, the boot script named there is + // the new one once the host has upgraded, under a page from before still open. + expect(bootConfigOf(html).boot).toBe(options.bootUrl) expect(buildFrameDocument(legacy)).not.toContain('"upgrades"') expect(buildContentSecurityPolicy({ ...legacy, untrusted: true })).toContain(legacy.assets.mainJs) }) diff --git a/packages/player/vite.plugins.ts b/packages/player/vite.plugins.ts index 0162806b..05de5833 100644 --- a/packages/player/vite.plugins.ts +++ b/packages/player/vite.plugins.ts @@ -74,8 +74,10 @@ export function devServiceWorkerPlugin(): Plugin { // `/versioned/h5p-sw.js` is the worker as an older release would answer: the same script with // the version it reports replaced by the last `/versioned/__version?v=`, unset meaning the // real one. One URL with changing bytes is what a player update looks like to the browser, - // which is what `tests/browser/worker-update.test.ts` needs. + // which is what `tests/browser/worker-update.test.ts` needs. `&delay=` answers it that many + // milliseconds late, as a slow host does. let versionedAs: string | null = null + let versionedDelay = 0 // The worker's `VERSION` constant, which a release keeps equal to the package's own. const { version } = JSON.parse(readFileSync(resolve(rootDir, 'package.json'), 'utf8')) as { version: string } @@ -85,7 +87,9 @@ export function devServiceWorkerPlugin(): Plugin { server.middlewares.use((req, res, next) => { const url = req.url?.split('?')[0] if (url === '/versioned/__version') { - versionedAs = new URL(req.url ?? '', 'http://dev').searchParams.get('v') || null + const params = new URL(req.url ?? '', 'http://dev').searchParams + versionedAs = params.get('v') || null + versionedDelay = Number(params.get('delay')) || 0 res.setHeader('cache-control', 'no-store') res.end(versionedAs ?? '') return @@ -96,7 +100,8 @@ export function devServiceWorkerPlugin(): Plugin { if (!entry) return next() const as = url === '/versioned/h5p-sw.js' ? versionedAs : null - void bundleWorker(entry, false).then( + const late = url === '/versioned/h5p-sw.js' ? versionedDelay : 0 + void new Promise((resolve) => setTimeout(resolve, late)).then(() => bundleWorker(entry, false)).then( (bundled) => { // By value, not by name: esbuild renames the constant (`VERSION2`) when names collide. const source = as ? bundled.replaceAll(JSON.stringify(version), JSON.stringify(as)) : bundled diff --git a/vercel.json b/vercel.json index ecfeeb4c..bf002307 100644 --- a/vercel.json +++ b/vercel.json @@ -25,7 +25,7 @@ }, { "source": "/frame-assets/(.*)", - "headers": [{ "key": "Cache-Control", "value": "public, max-age=3600, stale-while-revalidate=86400" }] + "headers": [{ "key": "Cache-Control", "value": "no-cache" }] }, { "source": "/demo/content/(.*)", From f67f74b2230679a6cc6a34152c4cb43aae990c47 Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Mon, 19 Oct 2026 17:04:47 +0300 Subject: [PATCH 2/2] fix: a load that starts during the worker update waits on it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The element keeps its routes before it asks the worker's version, so a load that began during the wait — up to thirty seconds across a major — took them as kept and went ahead with the worker of the major before, the failure of #49 by another door. `ensureWorker` now holds one setup at a time, and every load meanwhile waits on it. Also: the last worker-update test now sees the update it gave up on land; the embed's header comment no longer says a part is kept in the HTTP cache, which the element never does. Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 5 ++- packages/embed/lib/build.mjs | 11 ++++--- packages/player/src/h5p-offline-player.ts | 19 ++++++++++-- .../tests/browser/worker-update.test.ts | 31 +++++++++++++++++-- 4 files changed, 55 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0348bde1..9d948bf1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1283,7 +1283,10 @@ element, and the element acts. That relay is why `frame-document.ts` has a `mess and `h5p-sw.js` answered after four seconds, the load went ahead with the 0.10 worker, the new one took over halfway through, and it stayed in `indexing` (#49). So for a worker of another major the wait is `WORKER_MAJOR_UPDATE_TIMEOUT_MS`, thirty seconds; the new worker's activation, - which deletes the old major's caches, took about a second of it with four caches or 124. + which deletes the old major's caches, took about a second of it with four caches or 124. One + setup at a time (`workerSetup`): the element keeps its routes before it asks the version, and a + load that began during the wait — a visitor choosing another package while the first still + loads — took them as kept and went ahead with the old worker; found reviewing the fix. `activated()` waits for the newest worker — installing, then waiting, then active — since a changed script URL (a bundler's hash) installs a new worker beside the old active one; that wait is bounded by the same timeout whenever an activated worker can serve, because a host's diff --git a/packages/embed/lib/build.mjs b/packages/embed/lib/build.mjs index 26cb08ea..04988033 100644 --- a/packages/embed/lib/build.mjs +++ b/packages/embed/lib/build.mjs @@ -137,11 +137,12 @@ export function contentSecurityPolicy({ packages = null, ancestors = null, meta /** Header rules, one set for every host format: the policy everywhere, and the caching that matters. */ function headerRules(csp) { const revalidate = 'public, max-age=3600, stale-while-revalidate=86400' - // Asked again on every load, a 304 when nothing changed. The runtime and the pack keep their - // file names from one version to the next, and the worker's version decides which files it - // needs: kept for an hour, the runtime of the version before ran under the new worker after an - // update, and every play failed until the hour was out (0.10 to 1.0, measured, #49); a part - // kept from the pack before fails its hash against the new index. + // Asked again on every load, a 304 when nothing changed. The runtime's files keep their names + // from one version to the next, and the worker's version decides which it needs: kept for an + // hour, the runtime of the version before ran under the new worker after an update, and every + // play failed until the hour was out (0.10 to 1.0, measured, #49). The pack the same way, for + // whatever reads it with the browser's defaults: the element itself asks for its index + // revalidated and for its parts past the HTTP cache, so for it the header changes nothing. const current = 'no-cache' return [ { diff --git a/packages/player/src/h5p-offline-player.ts b/packages/player/src/h5p-offline-player.ts index 56417f19..bbb5cb25 100644 --- a/packages/player/src/h5p-offline-player.ts +++ b/packages/player/src/h5p-offline-player.ts @@ -308,6 +308,8 @@ export class H5PPlayerElement extends HTMLElement { private jobs: JobsWorkerHandle | null = null private routes: Routes | null = null private registration: ServiceWorkerRegistration | null = null + /** The worker being found or brought up to date, while it is: every load meanwhile waits on it. */ + private workerSetup: Promise | null = null private currentFile: File | null = null private currentSource: SourceDescriptor | null = null private load: AbortController | null = null @@ -1368,9 +1370,22 @@ export class H5PPlayerElement extends HTMLElement { /** * Finds the routes, registering our own worker unless a host has already mounted the handlers * into theirs. Registration uses an explicit `h5p/` sub-scope, so a host worker living in the - * same directory — or at `/`, for a root-placed `h5p-sw.js` — is never displaced. + * same directory — or at `/`, for a root-placed `h5p-sw.js` — is never displaced. One setup at + * a time: a load that starts while an earlier one is still bringing the worker up to the + * element's version — up to thirty seconds across a major, on a slow host — waits on that setup. + * The routes are kept before the version is asked, and a load that began meanwhile took them as + * kept and went ahead with the worker of the major before (#49, found in review). */ - private async ensureWorker(): Promise { + private ensureWorker(): Promise { + if (!this.workerSetup) { + this.workerSetup = this.setUpWorker().finally(() => { + this.workerSetup = null + }) + } + return this.workerSetup + } + + private async setUpWorker(): Promise { if (this.routes && this.registration) { if (await stillRegistered(this.registration)) return this.routes diff --git a/packages/player/tests/browser/worker-update.test.ts b/packages/player/tests/browser/worker-update.test.ts index 5da6706a..69163ae6 100644 --- a/packages/player/tests/browser/worker-update.test.ts +++ b/packages/player/tests/browser/worker-update.test.ts @@ -1,7 +1,7 @@ import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' import '../../src/h5p-offline-player' import { MAJOR_VERSION, VERSION } from '../../src/shared/constants' -import { FIXTURES, frameFetch, play } from './utils' +import { FIXTURES, createPlayer, frameFetch, play, waitForSettled } from './utils' /** * The first load after a player update. Registering again with an unchanged script URL returns @@ -91,6 +91,25 @@ describe('a player update', () => { expect(await frameWorkerVersion(player)).toBe(VERSION) }, 60_000) + it('holds a load that starts while the update is still on its way', async () => { + // The element keeps its routes before it asks the worker's version, and a load that began + // during the wait — a visitor choosing another package while the first still loads — took + // them as kept and went ahead with the worker of the major before. + await installVersion(`${MAJOR_VERSION - 1}.99.0`) + await serveVersion('', 4_000) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const player = createPlayer({ sw: SW }) + player.setAttribute('src', FIXTURES.basic) + await new Promise((resolve) => setTimeout(resolve, 1_000)) + const settled = waitForSettled(player) + player.setAttribute('src', FIXTURES.streamed) + + const result = await settled + if (!result.ok) expect.fail(`${result.detail.code} — ${result.detail.message}`) + expect(await frameWorkerVersion(player)).toBe(VERSION) + }, 60_000) + it('goes ahead after three seconds within a major, where the worker running serves the element', async () => { const older = `${MAJOR_VERSION}.0.0-older` await installVersion(older) @@ -102,7 +121,13 @@ describe('a player update', () => { expect(await frameWorkerVersion(player)).toBe(older) expect(warn.mock.calls.some(([line]) => String(line).includes(`Service Worker is ${older}`))).toBe(true) - // The update it gave up waiting for still lands, for the next load. - await activatedNewest((await navigator.serviceWorker.getRegistration(SCOPE))!) + + // The update it gave up waiting for still lands, and takes the frame over. + const registration = (await navigator.serviceWorker.getRegistration(SCOPE))! + if (!registration.installing && !registration.waiting) { + await new Promise((found) => registration.addEventListener('updatefound', found, { once: true })) + } + await activatedNewest(registration) + expect(await frameWorkerVersion(player)).toBe(VERSION) }, 60_000) })