From 1f33d97289b0dedba356e897c528abd8fb18143d Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 19 Jul 2026 20:13:12 +0200 Subject: [PATCH] perf: cache server /versions to skip a blocking fetch on startup --- src/client/initMatrix.ts | 7 ++- src/client/versionsCache.ts | 91 +++++++++++++++++++++++++++++++++++++ src/types/matrix-sdk.ts | 2 + 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 src/client/versionsCache.ts diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 2687be11c..3f33cea53 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -29,6 +29,7 @@ import { scopeEphemeralExtensions, SlidingSyncManager } from './slidingSync'; import { PresenceSyncManager } from './presenceSync'; import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; import { hydrateRoomMember } from './roomMemberHydration'; +import { primeVersionsFromCache, revalidateVersionsCache, clearCachedVersions } from './versionsCache'; const log = createLogger('initMatrix'); const debugLog = createDebugLogger('initMatrix'); @@ -274,7 +275,10 @@ const initializeClient = async ( } const { mx, indexedDBStore } = builtClient; - void mx.getVersions().catch(() => undefined); + void primeVersionsFromCache(mx, session.baseUrl, session.userId).then((primed) => { + if (primed) void revalidateVersionsCache(mx, session.baseUrl, session.userId); + else void mx.getVersions().catch(() => undefined); + }); const syncStorePromise = measureStartupPhase('sync_store', () => indexedDBStore.startup()); const cryptoPromise = measureStartupPhase('rust_crypto', () => @@ -597,6 +601,7 @@ export const logoutClient = async (mx: MatrixClient, session?: Session) => { if (session) { SlidingSyncSidebarCache.clear(session.userId); + clearCachedVersions(session.baseUrl, session.userId); const storeName: SessionStoreName = getSessionStoreName(session); await mx.clearStores({ cryptoDatabasePrefix: storeName.rustCryptoPrefix }); await deleteDatabase(storeName.sync); diff --git a/src/client/versionsCache.ts b/src/client/versionsCache.ts new file mode 100644 index 000000000..ccdc0d731 --- /dev/null +++ b/src/client/versionsCache.ts @@ -0,0 +1,91 @@ +import type { MatrixClient } from '$types/matrix-sdk'; +import { buildFeatureSupportMap, Method } from '$types/matrix-sdk'; + +const TTL_MS = 24 * 60 * 60 * 1000; // 24 hours +const keyFor = (baseUrl: string, userId: string): string => + `sable.versionsCache.${baseUrl}|${userId}`; + +type CachedVersions = { + versions: unknown; + unstable_features: Record | undefined; + fetchedAt: number; +}; + +const readCache = (baseUrl: string, userId: string): CachedVersions | undefined => { + try { + const raw = localStorage.getItem(keyFor(baseUrl, userId)); + if (!raw) return undefined; + const parsed = JSON.parse(raw) as CachedVersions; + if (typeof parsed.fetchedAt !== 'number') return undefined; + if (Date.now() - parsed.fetchedAt > TTL_MS) return undefined; + return parsed; + } catch { + return undefined; + } +}; + +const writeCache = (baseUrl: string, userId: string, data: { versions: unknown; unstable_features: Record | undefined }): void => { + try { + const entry: CachedVersions = { ...data, fetchedAt: Date.now() }; + localStorage.setItem(keyFor(baseUrl, userId), JSON.stringify(entry)); + } catch { + // localStorage full or disabled — non-fatal, skip caching. + } +}; + +/** + * Seed mx.serverVersionsPromise AND mx.canSupport from a cached /versions payload. + * Seeding the promise alone leaves canSupport empty → semantic drift in + * redaction/relation checks. Both must be set before the first sync request. + */ +export const primeVersionsFromCache = async ( + mx: MatrixClient, + baseUrl: string, + userId: string +): Promise => { + const cached = readCache(baseUrl, userId); + if (!cached) return false; + const serverVersions = { versions: cached.versions, unstable_features: cached.unstable_features ?? {} }; + (mx as unknown as { serverVersionsPromise: Promise | undefined }).serverVersionsPromise = + Promise.resolve(serverVersions); + (mx as unknown as { canSupport: Map }).canSupport = + await buildFeatureSupportMap(serverVersions as Parameters[0]); + return true; +}; + +/** + * Fire-and-forget revalidation of the /versions cache. Updates both the cache + * and the in-memory promise/canSupport so the client stays current. + */ +export const revalidateVersionsCache = async ( + mx: MatrixClient, + baseUrl: string, + userId: string +): Promise => { + try { + const resp = await mx.http.authedRequest( + Method.Get, + '/_matrix/client/versions', + undefined, + undefined, + { prefix: '' } + ); + const data = resp as { versions: unknown; unstable_features?: Record }; + writeCache(baseUrl, userId, { versions: data.versions, unstable_features: data.unstable_features }); + (mx as unknown as { serverVersionsPromise: Promise | undefined }).serverVersionsPromise = + Promise.resolve(data); + (mx as unknown as { canSupport: Map }).canSupport = + await buildFeatureSupportMap(data as Parameters[0]); + } catch { + // Revalidation failed — cached values remain in effect. Non-fatal. + } +}; + +/** Clear the cached versions for a session (used on logout). */ +export const clearCachedVersions = (baseUrl: string, userId: string): void => { + try { + localStorage.removeItem(keyFor(baseUrl, userId)); + } catch { + // non-fatal + } +}; diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index 12f41e071..561941238 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -45,6 +45,8 @@ export * from 'matrix-js-sdk/lib/@types/read_receipts'; export * from 'matrix-js-sdk/lib/@types/membership'; export * from 'matrix-js-sdk/lib/@types/registration'; +export * from 'matrix-js-sdk/lib/feature'; + export * from 'matrix-js-sdk/lib/oidc'; // oidc-client-ts is a transitive dep (not resolvable here), so derive its type from the SDK.