mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-27 12:26:29 -08:00
perf: cache server /versions to skip a blocking fetch on startup
This commit is contained in:
3 files changed
+99
-1
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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<string, boolean> | 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<string, boolean> | 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<boolean> => {
|
||||
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<unknown> | undefined }).serverVersionsPromise =
|
||||
Promise.resolve(serverVersions);
|
||||
(mx as unknown as { canSupport: Map<unknown, unknown> }).canSupport =
|
||||
await buildFeatureSupportMap(serverVersions as Parameters<typeof buildFeatureSupportMap>[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<void> => {
|
||||
try {
|
||||
const resp = await mx.http.authedRequest(
|
||||
Method.Get,
|
||||
'/_matrix/client/versions',
|
||||
undefined,
|
||||
undefined,
|
||||
{ prefix: '' }
|
||||
);
|
||||
const data = resp as { versions: unknown; unstable_features?: Record<string, boolean> };
|
||||
writeCache(baseUrl, userId, { versions: data.versions, unstable_features: data.unstable_features });
|
||||
(mx as unknown as { serverVersionsPromise: Promise<unknown> | undefined }).serverVersionsPromise =
|
||||
Promise.resolve(data);
|
||||
(mx as unknown as { canSupport: Map<unknown, unknown> }).canSupport =
|
||||
await buildFeatureSupportMap(data as Parameters<typeof buildFeatureSupportMap>[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
|
||||
}
|
||||
};
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user