mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 00:42:49 +08:00
Stop the service worker from stranding clients
Between48f5e35(07.09., registerType: 'autoUpdate') and5b5f4ca(10.09., switched to 'prompt') every client that cached the app froze: the new worker sits in `waiting` and the only code that could release it - the update toast - lives in the build behind that worker. Their next update never arrives, and Pages deletes the hashed assets they still run from, so the bundle they serve does not exist on the server any more. That is how the feedback form went missing on client.webspeak3.de. - Back to 'autoUpdate', with skipWaiting/clientsClaim spelled out: the plugin only sets them when it also injects registerSW.js, so with injectRegister: false the generated worker was byte-identical to the 'prompt' one. Verified in dist/sw.js. - onNeedReload instead of onNeedRefresh: the worker takes over on its own, the toast only decides *when* to reload, so nobody is thrown out of a running connection. - version.json plus a __BUILD_ID__ baked into the bundle, checked every 30 min and on tab focus, deliberately routed around the worker (not in globPatterns, so never precached). If the server is on another build and no new worker turns up, the worker is wedged and the button clears registrations and caches instead of reloading into the same cache. - Dismissing the toast snoozes for 30 min rather than for good. Verified in headless Chromium against simulated deploys: a client stuck on the old worker lands on the new bundle at the first plain F5. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
1 parent
06f38b4582
commit
2ee6d1f0b5
3 files changed
+183
-17
No files matched your search
+118
-9
@@ -1897,32 +1897,141 @@ function StreamSettingsDialog({
|
||||
);
|
||||
}
|
||||
|
||||
const SW_UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;
|
||||
const VERSION_CHECK_INTERVAL_MS = 30 * 60 * 1000;
|
||||
/** Floor between two version.json fetches, so tab-switching doesn't poll. */
|
||||
const VERSION_CHECK_MIN_GAP_MS = 5 * 60 * 1000;
|
||||
const UPDATE_TOAST_SNOOZE_MS = 30 * 60 * 1000;
|
||||
|
||||
/** What the server actually has right now. Deliberately routed around the
|
||||
* service worker: version.json is not in Workbox's globPatterns, so it is
|
||||
* never precached, and the cache-busting query plus `no-store` keeps any
|
||||
* intermediate cache out of the answer too. */
|
||||
async function fetchServerBuildId(): Promise<string | null> {
|
||||
try {
|
||||
const res = await fetch(`${import.meta.env.BASE_URL}version.json?t=${Date.now()}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data: unknown = await res.json();
|
||||
const id = (data as { buildId?: unknown }).buildId;
|
||||
return typeof id === "string" ? id : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Throw away the worker and everything it cached, then reload from the
|
||||
* network. Only for a client that is provably stale but isn't being handed
|
||||
* an update — see `stranded` below. */
|
||||
async function resetServiceWorkerAndReload() {
|
||||
try {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map((registration) => registration.unregister()));
|
||||
const cacheKeys = await caches.keys();
|
||||
await Promise.all(cacheKeys.map((key) => caches.delete(key)));
|
||||
} catch {
|
||||
// Reloading without the cleanup is still better than staying stale.
|
||||
}
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
function UpdatePrompt() {
|
||||
const t = useT();
|
||||
const {
|
||||
needRefresh: [needRefresh, setNeedRefresh],
|
||||
updateServiceWorker,
|
||||
} = useRegisterSW({
|
||||
const [visible, setVisible] = useState(false);
|
||||
/** An update is waiting to be applied, whether or not the toast is showing. */
|
||||
const pending = useRef(false);
|
||||
/** Set when the server is on a different build than we are *and* no new
|
||||
* service worker turned up to deliver it. Then the worker is wedged and a
|
||||
* plain reload would just serve the same cached shell again, so the button
|
||||
* has to clear it out instead. */
|
||||
const stranded = useRef(false);
|
||||
const snoozeTimer = useRef<number | null>(null);
|
||||
const lastVersionCheck = useRef(0);
|
||||
|
||||
const announce = (isStranded: boolean) => {
|
||||
if (isStranded) stranded.current = true;
|
||||
pending.current = true;
|
||||
// While snoozed the timer owns the toast; don't pop it back up early.
|
||||
if (snoozeTimer.current === null) setVisible(true);
|
||||
};
|
||||
|
||||
const snooze = () => {
|
||||
setVisible(false);
|
||||
// Never a permanent dismissal: a client that misses the prompt for good is
|
||||
// exactly how clients ended up stranded on a bundle the server no longer
|
||||
// even serves.
|
||||
snoozeTimer.current = window.setTimeout(() => {
|
||||
snoozeTimer.current = null;
|
||||
if (pending.current) setVisible(true);
|
||||
}, UPDATE_TOAST_SNOOZE_MS);
|
||||
};
|
||||
|
||||
useRegisterSW({
|
||||
onNeedReload() {
|
||||
// autoUpdate: the new worker has already taken over, we only choose the
|
||||
// moment to reload — mid-call is the user's decision, not ours.
|
||||
announce(false);
|
||||
},
|
||||
onRegisteredSW(_url, registration) {
|
||||
// Poll for a new service worker in the background — otherwise an app
|
||||
// left open for hours/days only checks for updates on next full load.
|
||||
if (!registration) return;
|
||||
const CHECK_INTERVAL_MS = 60 * 60 * 1000;
|
||||
window.setInterval(() => {
|
||||
registration.update().catch(() => {});
|
||||
}, CHECK_INTERVAL_MS);
|
||||
}, SW_UPDATE_CHECK_INTERVAL_MS);
|
||||
},
|
||||
});
|
||||
|
||||
if (!needRefresh) return null;
|
||||
useEffect(() => {
|
||||
const checkVersion = async () => {
|
||||
const now = Date.now();
|
||||
if (now - lastVersionCheck.current < VERSION_CHECK_MIN_GAP_MS) return;
|
||||
lastVersionCheck.current = now;
|
||||
|
||||
const serverBuildId = await fetchServerBuildId();
|
||||
if (!serverBuildId || serverBuildId === __BUILD_ID__) return;
|
||||
|
||||
// We are demonstrably behind. Give the service worker the first shot at
|
||||
// fixing it; only if it produces no new worker at all is it wedged.
|
||||
let registration: ServiceWorkerRegistration | undefined;
|
||||
try {
|
||||
registration = await navigator.serviceWorker?.getRegistration();
|
||||
await registration?.update();
|
||||
} catch {
|
||||
// An update check that throws is itself a sign of a wedged worker.
|
||||
}
|
||||
announce(!registration?.installing && !registration?.waiting);
|
||||
};
|
||||
|
||||
void checkVersion();
|
||||
const interval = window.setInterval(() => void checkVersion(), VERSION_CHECK_INTERVAL_MS);
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") void checkVersion();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
return () => {
|
||||
window.clearInterval(interval);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
return (
|
||||
<div className="ts-update-toast">
|
||||
<span>{t("pwa.updateAvailable")}</span>
|
||||
<button type="button" onClick={() => updateServiceWorker(true)}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (stranded.current) void resetServiceWorkerAndReload();
|
||||
else window.location.reload();
|
||||
}}
|
||||
>
|
||||
{t("pwa.reload")}
|
||||
</button>
|
||||
<button type="button" className="ts-update-toast-dismiss" onClick={() => setNeedRefresh(false)}>
|
||||
<button type="button" className="ts-update-toast-dismiss" onClick={snooze}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
Vendored
+3
@@ -1,3 +1,6 @@
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
/// <reference types="vite-plugin-pwa/react" />
|
||||
|
||||
/** Injected by vite.config.ts; matches the `buildId` in version.json. */
|
||||
declare const __BUILD_ID__: string
|
||||
+62
-8
@@ -1,19 +1,65 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { execSync } from 'node:child_process'
|
||||
import { defineConfig, type Plugin } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { VitePWA } from 'vite-plugin-pwa'
|
||||
|
||||
// Identifies the build a bundle came from. Only has to differ between two
|
||||
// builds — the client compares its own baked-in value against version.json to
|
||||
// notice when it is running something the server no longer serves.
|
||||
function resolveBuildId(): string {
|
||||
const fromCi = process.env.CF_PAGES_COMMIT_SHA || process.env.GITHUB_SHA
|
||||
if (fromCi) return fromCi.slice(0, 12)
|
||||
try {
|
||||
return execSync('git rev-parse --short=12 HEAD', { stdio: ['ignore', 'pipe', 'ignore'] })
|
||||
.toString()
|
||||
.trim()
|
||||
} catch {
|
||||
// No git checkout (the Docker build copies sources in without .git).
|
||||
return String(Date.now())
|
||||
}
|
||||
}
|
||||
|
||||
const buildId = resolveBuildId()
|
||||
|
||||
// version.json must never be precached, or a stuck client would ask the very
|
||||
// cache it is stuck in what the server has. `.json` is not in globPatterns
|
||||
// below, so Workbox leaves it alone and the fetch always hits the network.
|
||||
function versionManifest(): Plugin {
|
||||
return {
|
||||
name: 'webspeak3-version-manifest',
|
||||
apply: 'build',
|
||||
generateBundle() {
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'version.json',
|
||||
source: `${JSON.stringify({ buildId })}\n`,
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
define: {
|
||||
__BUILD_ID__: JSON.stringify(buildId),
|
||||
},
|
||||
plugins: [
|
||||
react(),
|
||||
versionManifest(),
|
||||
VitePWA({
|
||||
registerType: 'prompt',
|
||||
// We register the service worker ourselves (see useSwUpdatePrompt in
|
||||
// App.tsx) via the virtual:pwa-register/react module so we can show a
|
||||
// "new version available" toast instead of updating silently — a
|
||||
// stale-cache tab would otherwise keep running old JS/CSS until the
|
||||
// user manually reloads (or worse, clears storage), which bit us
|
||||
// repeatedly while verifying deploys.
|
||||
// The generated worker takes over as soon as it has installed
|
||||
// (skipWaiting + clientsClaim). It must NOT wait for the page to ask it
|
||||
// to: between 2026-09-07 and 2026-09-10 this was `prompt`, and every
|
||||
// client cached in that window froze — the new worker sat in `waiting`
|
||||
// forever because the only code that could have released it (the update
|
||||
// toast) lived in the version behind that worker. Deciding *when* to
|
||||
// reload is a UI concern and stays one: `onNeedReload` in App.tsx shows
|
||||
// the toast instead of pulling the page out from under an active
|
||||
// connection.
|
||||
registerType: 'autoUpdate',
|
||||
// We register from inside the app (virtual:pwa-register/react) rather
|
||||
// than through an injected registerSW.js, because that script would
|
||||
// reload the page on its own the moment a new worker activates.
|
||||
injectRegister: false,
|
||||
// Dev-time Workbox would sit in front of Vite's own HMR/WS traffic and
|
||||
// stale-cache the app shell while iterating — only ever ship the SW in
|
||||
@@ -35,6 +81,14 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
workbox: {
|
||||
// Both are what `registerType: 'autoUpdate'` is supposed to imply, but
|
||||
// the plugin only sets them when it also injects registerSW.js (see
|
||||
// resolveOptions: `injectRegister === 'auto' || injectRegister == null`)
|
||||
// — with injectRegister: false they have to be spelled out, or the
|
||||
// generated worker is byte-identical to the `prompt` one and strands
|
||||
// clients all over again. Verified in dist/sw.js after building.
|
||||
skipWaiting: true,
|
||||
clientsClaim: true,
|
||||
// Precache the built app shell (JS/CSS/HTML/icons) only. The gateway's
|
||||
// /ws endpoint and any file-transfer/API traffic must never be
|
||||
// intercepted or cached — Workbox's default fetch handler already
|
||||
|
||||
Reference in new issue
Block a user