perf(web): serve critical assets from the service worker cache (#4016)

This commit is contained in:
Hampus authored and GitHub committed 2026-11-11 00:43:14 +01:00
1 parent b47e248b14
commit 84faab372a
7 files changed
+224 -98

No files matched your search

+2 -1
View File
@@ -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: [
@@ -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<string> {
const stat = await fs.stat(filePath);
return `${stat.size}:${Math.trunc(stat.mtimeMs)}`;
function extractCriticalAssetUrls(html: string): Array<string> {
const urls = new Set<string>();
for (const [, value] of html.matchAll(/["']([^"'\s<>]*\/assets\/[^"'\s<>]+)["']/gu)) {
const url = new URL(value.replaceAll('&amp;', '&'), `${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<Array<PrecacheEntry>> {
const entries = new Map<string, string>();
async function collectPrecacheManifest(html: string): Promise<Array<PrecacheEntry>> {
const entries: Array<PrecacheEntry> = 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<void> {
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<void> {
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),
},
});
}
@@ -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<void> = 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<void> => {
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<void> => {
if (!serviceWorkerCaches) {
return;
}
const names = await serviceWorkerCaches.keys();
await Promise.all(
names.map((name) => {
@@ -120,11 +112,9 @@ const cleanupOldCaches = async (): Promise<void> => {
};
const fetchNetworkFirst = async (request: Request): Promise<Response> => {
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<Response> => {
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<WorkerStaticRoute>) => Promise<void>;
}
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') {
@@ -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<Pick<Cache, 'match' | 'put'>>} | undefined;
readonly caches: CacheStorage;
readonly fetch: (request: Request) => Promise<Response>;
readonly origin: string;
readonly version: string;
readonly precacheName: string;
readonly navigationCacheName: string;
readonly networkTimeoutMs: number;
readonly onBuildMismatch: () => Promise<unknown>;
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(/<meta\b[^>]*>/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<string | null> {
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<Response | undefined> {
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<void> {
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<PrecacheEntry>): Promise<void> {
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<Response | undefined> {
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<void> {
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<void> {
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<Response> {
export async function seedAppShell(runtime: AppShellRuntime): Promise<void> {
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<unknown>) => void,
): Promise<Response> {
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<unknown>) => void,
): Promise<Response> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<Response | undefined>((resolve) => {
const timeout = new Promise<undefined>((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);
}
@@ -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<string>): boolean {
@@ -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<string>,
workerOrigin: string,
cacheName: string,
): Array<WorkerStaticRoute> {
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<string>,
): 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';
}
@@ -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/');
}