From 84faab372a74fe27df60f16aedee26db333b22ec Mon Sep 17 00:00:00 2001 From: Hampus Date: Wed, 11 Nov 2026 00:43:14 +0100 Subject: [PATCH] perf(web): serve critical assets from the service worker cache (#4016) --- fluxer_app/rspack.config.mjs | 3 +- .../scripts/build/utils/ServiceWorker.tsx | 45 ++++-- .../platform/service_worker/Worker.ts | 68 ++++---- .../platform/service_worker/WorkerAppShell.ts | 145 ++++++++++++------ .../service_worker/WorkerCacheCleanup.ts | 1 + .../service_worker/WorkerFetchRouting.ts | 47 +++++- .../service_worker/WorkerNavigation.ts | 13 +- 7 files changed, 224 insertions(+), 98 deletions(-) diff --git a/fluxer_app/rspack.config.mjs b/fluxer_app/rspack.config.mjs index 46d4b3a8b..122ab6b69 100644 --- a/fluxer_app/rspack.config.mjs +++ b/fluxer_app/rspack.config.mjs @@ -18,6 +18,7 @@ import {transformSync} from 'esbuild'; import {getLinguiSwcPluginConfig} from './scripts/build/rspack/lingui.mjs'; import {staticFilesPlugin} from './scripts/build/rspack/static-files.mjs'; import {moduleMapPlugin} from './scripts/module-map/index.ts'; +import {APP_SHELL_BUILD_META_NAME} from './src/features/platform/service_worker/WorkerCacheCleanup.ts'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -805,7 +806,7 @@ export default () => { inject: 'body', scriptLoading: 'module', excludeChunks: ['sw'], - ...(isDesktopRenderer ? {publicPath: '/'} : {}), + ...(isDesktopRenderer ? {publicPath: '/'} : {meta: {[APP_SHELL_BUILD_META_NAME]: buildInfo.version}}), }), new CopyRspackPlugin({ patterns: [ diff --git a/fluxer_app/scripts/build/utils/ServiceWorker.tsx b/fluxer_app/scripts/build/utils/ServiceWorker.tsx index 7ad0c2873..86ede95af 100644 --- a/fluxer_app/scripts/build/utils/ServiceWorker.tsx +++ b/fluxer_app/scripts/build/utils/ServiceWorker.tsx @@ -1,31 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later +import {createHash} from 'node:crypto'; import {promises as fs} from 'node:fs'; import * as path from 'node:path'; -import type {PrecacheEntry} from '@app/features/platform/service_worker/WorkerAppShell'; +import {type PrecacheEntry, readAppShellBuildId} from '@app/features/platform/service_worker/WorkerAppShell'; import {DIST_DIR, SRC_DIR} from '@app_scripts/build/Config'; import * as esbuild from 'esbuild'; const PRECACHE_ROOT_FILES = ['manifest.json', 'browserconfig.xml', 'robots.txt', 'version.json']; +const BUILD_ORIGIN = 'https://fluxer.invalid'; -async function fileRevision(filePath: string): Promise { - const stat = await fs.stat(filePath); - return `${stat.size}:${Math.trunc(stat.mtimeMs)}`; +function extractCriticalAssetUrls(html: string): Array { + const urls = new Set(); + for (const [, value] of html.matchAll(/["']([^"'\s<>]*\/assets\/[^"'\s<>]+)["']/gu)) { + const url = new URL(value.replaceAll('&', '&'), `${BUILD_ORIGIN}/`); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + continue; + } + url.hash = ''; + urls.add(url.origin === BUILD_ORIGIN ? `${url.pathname}${url.search}` : url.href); + } + return [...urls].sort(); } -async function collectPrecacheManifest(): Promise> { - const entries = new Map(); +async function collectPrecacheManifest(html: string): Promise> { + const entries: Array = await Promise.all( + extractCriticalAssetUrls(html).map(async (url) => { + const pathname = new URL(url, BUILD_ORIGIN).pathname; + const assetPath = pathname.slice(pathname.lastIndexOf('/assets/') + 1); + const bytes = await fs.readFile(path.join(DIST_DIR, assetPath)); + return {url, integrity: `sha384-${createHash('sha384').update(bytes).digest('base64')}`}; + }), + ); for (const file of PRECACHE_ROOT_FILES) { - const filePath = path.join(DIST_DIR, file); - try { - entries.set(`/${file}`, await fileRevision(filePath)); - } catch {} + await fs.access(path.join(DIST_DIR, file)); + entries.push({url: `/${file}`, integrity: null}); } - return Array.from(entries, ([url, revision]) => ({url, revision})); + return entries; } export async function buildServiceWorker(production: boolean): Promise { - const precacheManifest = await collectPrecacheManifest(); + const html = await fs.readFile(path.join(DIST_DIR, 'index.html'), 'utf8'); + const version = readAppShellBuildId(html); + if (!version) throw new Error('index.html has no fluxer-build meta'); + const precacheManifest = await collectPrecacheManifest(html); await esbuild.build({ entryPoints: [path.join(SRC_DIR, 'features', 'platform', 'service_worker', 'Worker.ts')], bundle: true, @@ -35,9 +53,8 @@ export async function buildServiceWorker(production: boolean): Promise { sourcemap: true, target: 'esnext', define: { - __WB_MANIFEST: '[]', __FLUXER_PRECACHE_MANIFEST__: JSON.stringify(precacheManifest), - __FLUXER_SW_VERSION__: JSON.stringify(String(Date.now())), + __FLUXER_SW_VERSION__: JSON.stringify(version), }, }); } diff --git a/fluxer_app/src/features/platform/service_worker/Worker.ts b/fluxer_app/src/features/platform/service_worker/Worker.ts index 89942eb54..a9a300c2c 100644 --- a/fluxer_app/src/features/platform/service_worker/Worker.ts +++ b/fluxer_app/src/features/platform/service_worker/Worker.ts @@ -7,7 +7,6 @@ import { import { type AppShellRuntime, fetchAppShellNavigation, - isCacheableResponse, type PrecacheEntry, precacheAssets, seedAppShell, @@ -17,7 +16,11 @@ import { WORKER_CACHE_PREFIX, WORKER_NAVIGATION_CACHE_PREFIX, } from '@app/features/platform/service_worker/WorkerCacheCleanup'; -import {getWorkerFetchRoute} from '@app/features/platform/service_worker/WorkerFetchRouting'; +import { + getWorkerFetchRoute, + getWorkerStaticRoutes, + type WorkerStaticRoute, +} from '@app/features/platform/service_worker/WorkerFetchRouting'; import { getBadgeCount, getPushNotificationClientState, @@ -40,7 +43,6 @@ type SwLogLevel = 'debug' | 'info' | 'warn' | 'error'; declare const self: ServiceWorkerGlobalScope & typeof globalThis & { skipWaiting(): void; - __WB_MANIFEST: unknown; console: Console; }; @@ -50,6 +52,11 @@ const workerNavigator = self.navigator as {readonly userAgent: string; readonly const ensureServiceWorkerReady: Promise = Promise.resolve(); const SERVICE_WORKER_VERSION = typeof __FLUXER_SW_VERSION__ === 'string' ? __FLUXER_SW_VERSION__ : 'dev'; const PRECACHE_MANIFEST = typeof __FLUXER_PRECACHE_MANIFEST__ === 'undefined' ? [] : __FLUXER_PRECACHE_MANIFEST__; +const CRITICAL_ASSET_URLS = new Set( + PRECACHE_MANIFEST.filter((entry) => entry.integrity !== null).map( + (entry) => new URL(entry.url, self.location.origin).href, + ), +); const PRECACHE_CACHE = `${WORKER_CACHE_PREFIX}-precache-${SERVICE_WORKER_VERSION}`; const NAVIGATION_CACHE = `${WORKER_NAVIGATION_CACHE_PREFIX}${SERVICE_WORKER_VERSION}`; const EXPECTED_CACHES = new Set([PRECACHE_CACHE, NAVIGATION_CACHE]); @@ -83,31 +90,16 @@ const appShellRuntime: AppShellRuntime = { caches: serviceWorkerCaches, fetch: (request) => fetch(request), origin: self.location.origin, + version: SERVICE_WORKER_VERSION, precacheName: PRECACHE_CACHE, navigationCacheName: NAVIGATION_CACHE, networkTimeoutMs: NAVIGATION_NETWORK_TIMEOUT_MS, + onBuildMismatch: () => self.registration.update(), onCacheWriteError: (error) => { void log('warn', 'app shell cache put failed', {error: describeError(error)}); }, }; -const cacheRequest = async (cacheName: string, request: Request | string, response: Response): Promise => { - if (!isCacheableResponse(response)) { - return; - } - try { - if (!serviceWorkerCaches) { - return; - } - const cache = await serviceWorkerCaches.open(cacheName); - await cache.put(request, response.clone()); - } catch (error) { - await log('warn', 'cache put failed', {cacheName, error: describeError(error)}); - } -}; const cleanupOldCaches = async (): Promise => { - if (!serviceWorkerCaches) { - return; - } const names = await serviceWorkerCaches.keys(); await Promise.all( names.map((name) => { @@ -120,11 +112,9 @@ const cleanupOldCaches = async (): Promise => { }; const fetchNetworkFirst = async (request: Request): Promise => { try { - const response = await fetch(request); - await cacheRequest(PRECACHE_CACHE, request, response); - return response; + return await fetch(request); } catch (error) { - const cached = await serviceWorkerCaches?.match(request); + const cached = await serviceWorkerCaches.match(request, {cacheName: PRECACHE_CACHE}); if (cached) { return cached; } @@ -134,19 +124,25 @@ const fetchNetworkFirst = async (request: Request): Promise => { const instanceManifestUrl = (): string => new URL('/manifest.json', self.location.origin).href; const instanceManifestSources: InstanceManifestSources = { - fetchManifest: async (signal) => { - const response = await fetch(instanceManifestUrl(), {signal}); - await cacheRequest(PRECACHE_CACHE, instanceManifestUrl(), response); - return response; - }, - readCachedManifest: async () => (await serviceWorkerCaches?.match(instanceManifestUrl())) ?? undefined, + fetchManifest: (signal) => fetch(instanceManifestUrl(), {signal}), + readCachedManifest: async () => + (await serviceWorkerCaches.match(instanceManifestUrl(), {cacheName: PRECACHE_CACHE})) ?? undefined, }; +interface StaticRoutingInstallEvent extends ExtendableEvent { + addRoutes?: (rules: ReadonlyArray) => Promise; +} + self.addEventListener('install', (event: ExtendableEvent) => { + const installEvent = event as StaticRoutingInstallEvent; event.waitUntil( (async () => { + await installEvent + .addRoutes?.(getWorkerStaticRoutes(CRITICAL_ASSET_URLS, self.location.origin, PRECACHE_CACHE)) + .catch((error: unknown) => log('warn', 'static routes were refused', error)); await ensureServiceWorkerReady; - await Promise.allSettled([precacheAssets(appShellRuntime, PRECACHE_MANIFEST), seedAppShell(appShellRuntime)]); + await precacheAssets(appShellRuntime, PRECACHE_MANIFEST); + await seedAppShell(appShellRuntime); await log('info', 'install'); self.skipWaiting(); })(), @@ -167,9 +163,15 @@ self.addEventListener('activate', (event: ExtendableEvent) => { self.addEventListener('fetch', (event: FetchEvent) => { const request = event.request; - const route = getWorkerFetchRoute(request, self.location.origin); + const route = getWorkerFetchRoute(request, self.location.origin, CRITICAL_ASSET_URLS); + if (route === 'asset') { + event.respondWith( + serviceWorkerCaches.match(request, {cacheName: PRECACHE_CACHE}).then((cached) => cached ?? fetch(request)), + ); + return; + } if (route === 'navigation') { - event.respondWith(fetchAppShellNavigation(appShellRuntime, request)); + event.respondWith(fetchAppShellNavigation(appShellRuntime, request, (work) => event.waitUntil(work))); return; } if (route === 'metadata') { diff --git a/fluxer_app/src/features/platform/service_worker/WorkerAppShell.ts b/fluxer_app/src/features/platform/service_worker/WorkerAppShell.ts index 45ab95cb8..00e83bdfd 100644 --- a/fluxer_app/src/features/platform/service_worker/WorkerAppShell.ts +++ b/fluxer_app/src/features/platform/service_worker/WorkerAppShell.ts @@ -1,99 +1,150 @@ // SPDX-License-Identifier: AGPL-3.0-or-later +import {APP_SHELL_BUILD_META_NAME, WORKER_CACHE_PREFIX} from '@app/features/platform/service_worker/WorkerCacheCleanup'; +import {servesSignedInShell} from '@app/features/platform/service_worker/WorkerNavigation'; + const APP_SHELL_CACHE_KEY = '/app-shell'; const APP_SHELL_SEED_PATH = '/app'; const APP_SHELL_MARKER_HEADER = 'x-fluxer-app-shell'; export interface PrecacheEntry { readonly url: string; - readonly revision: string; + readonly integrity: string | null; } export interface AppShellRuntime { - readonly caches: {open(name: string): Promise>} | undefined; + readonly caches: CacheStorage; readonly fetch: (request: Request) => Promise; readonly origin: string; + readonly version: string; readonly precacheName: string; readonly navigationCacheName: string; readonly networkTimeoutMs: number; + readonly onBuildMismatch: () => Promise; readonly onCacheWriteError: (error: unknown) => void; } -export function isCacheableResponse(response: Response): boolean { - return response.ok || response.type === 'opaque'; +export function readAppShellBuildId(html: string): string | null { + for (const [tag] of html.matchAll(/]*>/giu)) { + if (tag.match(/\bname=["']([^"']+)["']/iu)?.[1] === APP_SHELL_BUILD_META_NAME) { + return tag.match(/\bcontent=["']([^"']+)["']/iu)?.[1] ?? null; + } + } + return null; +} + +async function appShellBuildId(response: Response): Promise { + if (!response.ok || response.headers.get(APP_SHELL_MARKER_HEADER) !== '1') return null; + return readAppShellBuildId(await response.clone().text()); +} + +async function findCachedAsset(runtime: AppShellRuntime, request: Request): Promise { + const names = (await runtime.caches.keys()).filter((name) => name.startsWith(`${WORKER_CACHE_PREFIX}-`)); + for (const cacheName of names) { + const cached = await runtime.caches.match(request, {cacheName}); + if (cached?.ok && cached.type !== 'opaque') { + return cached; + } + } + return undefined; +} + +async function precacheEntry(runtime: AppShellRuntime, cache: Cache, entry: PrecacheEntry): Promise { + const request = new Request(new URL(entry.url, runtime.origin), { + mode: 'cors', + credentials: 'omit', + cache: entry.integrity ? 'default' : 'reload', + integrity: entry.integrity ?? '', + }); + const response = + (entry.integrity ? await findCachedAsset(runtime, request) : undefined) ?? (await runtime.fetch(request)); + if (!response.ok || response.type === 'opaque') { + throw new Error(`Precache failed: ${entry.url}`); + } + await cache.put(request, response); } export async function precacheAssets(runtime: AppShellRuntime, manifest: ReadonlyArray): Promise { - if (!runtime.caches) { - return; - } const cache = await runtime.caches.open(runtime.precacheName); - await Promise.allSettled( - manifest.map(async (entry) => { - const request = new Request(new URL(entry.url, runtime.origin).toString(), {cache: 'reload'}); - const response = await runtime.fetch(request); - if (isCacheableResponse(response)) { - await cache.put(entry.url, response); - } - }), - ); + const assets = manifest.filter((entry) => entry.integrity !== null); + const metadata = manifest.filter((entry) => entry.integrity === null); + await Promise.all([ + ...assets.map((entry) => precacheEntry(runtime, cache, entry)), + ...metadata.map((entry) => precacheEntry(runtime, cache, entry).catch(() => undefined)), + ]); } async function readAppShell(runtime: AppShellRuntime): Promise { - if (!runtime.caches) { - return undefined; - } - const cache = await runtime.caches.open(runtime.navigationCacheName); - return (await cache.match(APP_SHELL_CACHE_KEY)) ?? undefined; + return (await runtime.caches.match(APP_SHELL_CACHE_KEY, {cacheName: runtime.navigationCacheName})) ?? undefined; } async function storeAppShell(runtime: AppShellRuntime, response: Response): Promise { - if (!runtime.caches || !response.ok || response.headers.get(APP_SHELL_MARKER_HEADER) !== '1') { + const buildId = await appShellBuildId(response); + if (buildId !== runtime.version) { + if (buildId !== null) await runtime.onBuildMismatch(); return; } try { const cache = await runtime.caches.open(runtime.navigationCacheName); - await cache.put(APP_SHELL_CACHE_KEY, response.clone()); + await cache.put(APP_SHELL_CACHE_KEY, response); } catch (error) { runtime.onCacheWriteError(error); } } -export async function seedAppShell(runtime: AppShellRuntime): Promise { - if (!runtime.caches) { - return; - } - const request = new Request(new URL(APP_SHELL_SEED_PATH, runtime.origin).toString(), {cache: 'reload'}); - const response = await runtime.fetch(request); - await storeAppShell(runtime, response); +function shellRequest(runtime: AppShellRuntime, url: string, cache: RequestCache, priority: RequestPriority): Request { + return new Request(new URL(url, runtime.origin), {mode: 'cors', credentials: 'omit', cache, priority}); } -export async function fetchAppShellNavigation(runtime: AppShellRuntime, request: Request): Promise { +export async function seedAppShell(runtime: AppShellRuntime): Promise { + const response = await runtime.fetch(shellRequest(runtime, APP_SHELL_SEED_PATH, 'reload', 'auto')); + if ((await appShellBuildId(response)) !== runtime.version) throw new Error('Precache shell build mismatch'); + const cache = await runtime.caches.open(runtime.navigationCacheName); + await cache.put(APP_SHELL_CACHE_KEY, response); +} + +export async function fetchAppShellNavigation( + runtime: AppShellRuntime, + request: Request, + keepAlive: (work: Promise) => void, +): Promise { + const cached = servesSignedInShell(new URL(request.url).pathname) + ? await readAppShell(runtime).catch(() => undefined) + : undefined; + if (cached) { + keepAlive( + runtime + .fetch(shellRequest(runtime, APP_SHELL_SEED_PATH, 'no-cache', 'low')) + .then((response) => storeAppShell(runtime, response)) + .catch(() => undefined), + ); + return cached; + } + return fetchNetworkShell(runtime, request, keepAlive); +} + +async function fetchNetworkShell( + runtime: AppShellRuntime, + request: Request, + keepAlive: (work: Promise) => void, +): Promise { let timeoutId: ReturnType | undefined; - const timeout = new Promise((resolve) => { + const timeout = new Promise((resolve) => { timeoutId = setTimeout(() => resolve(undefined), runtime.networkTimeoutMs); }); + const network = runtime.fetch(request); + if (servesSignedInShell(new URL(request.url).pathname)) { + keepAlive(network.then((response) => storeAppShell(runtime, response.clone())).catch(() => undefined)); + } try { - const network = runtime.fetch(request).then(async (response) => { - await storeAppShell(runtime, response); - return response; - }); let networkResponse: Response | undefined; try { networkResponse = await Promise.race([network, timeout]); - if (networkResponse && isCacheableResponse(networkResponse)) { - return networkResponse; - } + if (networkResponse?.ok) return networkResponse; } catch {} const cached = await readAppShell(runtime); - if (cached) { - network.catch(() => undefined); - return cached; - } - if (networkResponse) { - return networkResponse; - } - return network; + if (cached) return cached; + return networkResponse ?? network; } finally { clearTimeout(timeoutId); } diff --git a/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.ts b/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.ts index 04657c131..dfad0ac13 100644 --- a/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.ts +++ b/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.ts @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later export const WORKER_CACHE_PREFIX = 'fluxer'; +export const APP_SHELL_BUILD_META_NAME = 'fluxer-build'; export const WORKER_NAVIGATION_CACHE_PREFIX = `${WORKER_CACHE_PREFIX}-navigation-`; export function shouldDeleteWorkerCache(cacheName: string, expectedCaches: ReadonlySet): boolean { diff --git a/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.ts b/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.ts index ef83d6036..c17cdbcad 100644 --- a/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.ts +++ b/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.ts @@ -2,7 +2,43 @@ import {isAppNavigationPath} from '@app/features/platform/service_worker/WorkerNavigation'; -export type WorkerFetchRoute = 'ignore' | 'metadata' | 'navigation'; +export type WorkerFetchRoute = 'ignore' | 'asset' | 'metadata' | 'navigation'; + +interface WorkerUrlPattern { + readonly protocol: string; + readonly hostname: string; + readonly port: string; + readonly pathname: string; +} + +export interface WorkerStaticRoute { + readonly condition: {readonly urlPattern: WorkerUrlPattern}; + readonly source: 'network' | {cacheName: string}; +} + +function urlPattern(url: URL, pathname: string): WorkerUrlPattern { + return {protocol: url.protocol.slice(0, -1), hostname: url.hostname, port: url.port, pathname}; +} + +export function getWorkerStaticRoutes( + assetUrls: ReadonlySet, + workerOrigin: string, + cacheName: string, +): Array { + const assetBases = new Set( + Array.from(assetUrls, (href) => { + const url = new URL(href); + return `${url.origin}${url.pathname.slice(0, url.pathname.lastIndexOf('/assets/'))}/assets/*`; + }), + ); + return [ + {condition: {urlPattern: urlPattern(new URL(workerOrigin), '/api/*')}, source: 'network'}, + ...Array.from(assetBases, (base): WorkerStaticRoute => { + const url = new URL(base); + return {condition: {urlPattern: urlPattern(url, url.pathname)}, source: {cacheName}}; + }), + ]; +} function isNavigationRequest(request: Request): boolean { if (request.mode === 'navigate') return true; @@ -10,11 +46,18 @@ function isNavigationRequest(request: Request): boolean { return request.destination === 'document' || accept.includes('text/html'); } -export function getWorkerFetchRoute(request: Request, workerOrigin: string): WorkerFetchRoute { +export function getWorkerFetchRoute( + request: Request, + workerOrigin: string, + assetUrls: ReadonlySet, +): WorkerFetchRoute { if (request.method !== 'GET') { return 'ignore'; } const url = new URL(request.url); + if (assetUrls.has(url.href) && request.cache !== 'reload') { + return 'asset'; + } if (url.origin !== workerOrigin) { return 'ignore'; } diff --git a/fluxer_app/src/features/platform/service_worker/WorkerNavigation.ts b/fluxer_app/src/features/platform/service_worker/WorkerNavigation.ts index 390e10f30..0220a52e2 100644 --- a/fluxer_app/src/features/platform/service_worker/WorkerNavigation.ts +++ b/fluxer_app/src/features/platform/service_worker/WorkerNavigation.ts @@ -28,10 +28,21 @@ const APP_NAVIGATION_EXACT_PATHS = new Set([ const APP_NAVIGATION_PREFIXES = ['/channels/', '/users/', '/invite/', '/gift/', '/theme/', '/migrate/']; +function normalizePathname(pathname: string): string { + return pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname; +} + export function isAppNavigationPath(pathname: string): boolean { - const normalizedPathname = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname; + const normalizedPathname = normalizePathname(pathname); if (APP_NAVIGATION_EXACT_PATHS.has(normalizedPathname)) { return true; } return APP_NAVIGATION_PREFIXES.some((prefix) => normalizedPathname.startsWith(prefix)); } + +const SIGNED_IN_SHELL_EXACT_PATHS = new Set(['/app', '/bookmarks', '/mentions', '/notifications', '/you']); + +export function servesSignedInShell(pathname: string): boolean { + const normalizedPathname = normalizePathname(pathname); + return SIGNED_IN_SHELL_EXACT_PATHS.has(normalizedPathname) || normalizedPathname.startsWith('/channels/'); +}