diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index e3109e39d..78a7ea43a 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -61,6 +61,21 @@ const log = createLogger('ClientRoot'); const isClientReady = (syncState: string | null): boolean => syncState === 'PREPARED' || syncState === 'SYNCING' || syncState === 'CATCHUP'; +const resolveLocalRoomId = ( + mx: MatrixClient, + encodedRoomIdOrAlias?: string +): string | undefined => { + if (!encodedRoomIdOrAlias) return undefined; + try { + const roomIdOrAlias = decodeURIComponent(encodedRoomIdOrAlias); + if (isRoomId(roomIdOrAlias)) return roomIdOrAlias; + if (isRoomAlias(roomIdOrAlias)) return getCanonicalAliasRoomId(mx, roomIdOrAlias); + } catch { + // Ignore malformed route values and let the normal router handle them. + } + return undefined; +}; + function ClientRootLoading() { const sessions = useAtomValue(sessionsAtom); const activeSessionId = useAtomValue(activeSessionIdAtom); @@ -273,23 +288,13 @@ export function ClientRoot({ children }: ClientRootProps) { const [startState, startMatrix] = useAsyncCallback( useCallback( (m) => { - let initialRoomId: string | undefined; - if (encodedInitialRoomIdOrAlias) { - try { - const roomIdOrAlias = decodeURIComponent(encodedInitialRoomIdOrAlias); - if (isRoomId(roomIdOrAlias)) initialRoomId = roomIdOrAlias; - else if (isRoomAlias(roomIdOrAlias)) { - initialRoomId = getCanonicalAliasRoomId(m, roomIdOrAlias); - } - } catch { - // Ignore malformed route values and let the normal router handle them. - } - } + const initialRoomId = resolveLocalRoomId(m, encodedInitialRoomIdOrAlias); return startClient(m, { baseUrl: activeSession?.baseUrl, sessionSlidingSyncOptIn: activeSession?.slidingSyncOptIn, initialRoomIds: initialRoomId ? [initialRoomId] : undefined, + onCachedRoomsLoaded: () => setSyncReadyClient(m), }); }, [activeSession?.baseUrl, activeSession?.slidingSyncOptIn, encodedInitialRoomIdOrAlias] diff --git a/src/app/utils/sort.test.ts b/src/app/utils/sort.test.ts index 8f9a41388..a232ea8e5 100644 --- a/src/app/utils/sort.test.ts +++ b/src/app/utils/sort.test.ts @@ -14,14 +14,18 @@ import { } from './sort'; // Minimal stub that satisfies the MatrixClient shape needed by these sort functions. -function makeClient(rooms: Record): MatrixClient { +function makeClient( + rooms: Record +): MatrixClient { return { getRoom: (id: string) => { const r = rooms[id]; if (!r) return null; - return { name: r.name, getLastActiveTimestamp: () => r.ts } as unknown as ReturnType< - MatrixClient['getRoom'] - >; + return { + name: r.name, + getLastActiveTimestamp: () => r.ts, + getBumpStamp: () => r.bumpStamp, + } as unknown as ReturnType; }, } as unknown as MatrixClient; } @@ -63,6 +67,15 @@ describe('factoryRoomIdByActivity', () => { const sort = factoryRoomIdByActivity(mx); expect(['!unknown:h', '!known:h'].toSorted(sort)).toEqual(['!known:h', '!unknown:h']); }); + + it('uses sliding-sync bump stamps when no timeline event is loaded', () => { + const mx = makeClient({ + '!old:h': { name: 'Old', ts: Number.MIN_SAFE_INTEGER, bumpStamp: 1000 }, + '!new:h': { name: 'New', ts: Number.MIN_SAFE_INTEGER, bumpStamp: 9000 }, + }); + const sort = factoryRoomIdByActivity(mx); + expect(['!old:h', '!new:h'].toSorted(sort)).toEqual(['!new:h', '!old:h']); + }); }); describe('factoryRoomIdByAtoZ', () => { diff --git a/src/app/utils/sort.ts b/src/app/utils/sort.ts index 454521df6..0de221b28 100644 --- a/src/app/utils/sort.ts +++ b/src/app/utils/sort.ts @@ -2,16 +2,19 @@ import type { MatrixClient } from '$types/matrix-sdk'; export type SortFunc = (a: T, b: T) => number; +const getRoomActivity = (mx: MatrixClient, roomId: string): number => { + const room = mx.getRoom(roomId); + if (!room) return Number.MIN_SAFE_INTEGER; + const timelineTimestamp = room.getLastActiveTimestamp(); + return timelineTimestamp === Number.MIN_SAFE_INTEGER + ? (room.getBumpStamp() ?? Number.MIN_SAFE_INTEGER) + : timelineTimestamp; +}; + export const factoryRoomIdByActivity = (mx: MatrixClient): SortFunc => (a, b) => { - const room1 = mx.getRoom(a); - const room2 = mx.getRoom(b); - - return ( - (room2?.getLastActiveTimestamp() ?? Number.MIN_SAFE_INTEGER) - - (room1?.getLastActiveTimestamp() ?? Number.MIN_SAFE_INTEGER) - ); + return getRoomActivity(mx, b) - getRoomActivity(mx, a); }; export const factoryRoomIdByAtoZ = diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 815c55471..c73a58a8d 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -24,6 +24,7 @@ import { cryptoCallbacks } from './secretStorageKeys'; import type { SlidingSyncDiagnostics } from './slidingSync'; import { SlidingSyncManager } from './slidingSync'; import { PresenceSyncManager } from './presenceSync'; +import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; const log = createLogger('initMatrix'); const debugLog = createDebugLogger('initMatrix'); @@ -484,6 +485,7 @@ export type StartClientConfig = { pollTimeoutMs?: number; timelineLimit?: number; initialRoomIds?: Iterable; + onCachedRoomsLoaded?: () => void; }; export type ClientSyncDiagnostics = { @@ -539,6 +541,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): installSlidingSyncConnId(mx); manager.attach(); + manager.prepareSidebarCacheHydration(); slidingSyncByClient.set(mx, manager); } @@ -553,6 +556,9 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): }), { transport: useSliding ? 'sliding' : 'classic' } ); + if (manager && (await manager.waitForSidebarCacheHydration())) { + config?.onCachedRoomsLoaded?.(); + } } catch (err) { debugLog.error('network', 'Failed to start client with sliding sync', { error: err instanceof Error ? err.message : String(err), @@ -582,6 +588,7 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { log.log('clearCacheAndReload', mx.getUserId()); stopClient(mx); clearNavToActivePathStore(mx.getSafeUserId()); + SlidingSyncSidebarCache.clear(mx.getSafeUserId()); await mx.store.deleteAllData(); window.location.reload(); }; @@ -616,6 +623,7 @@ export const logoutClient = async (mx: MatrixClient, session?: Session) => { } if (session) { + SlidingSyncSidebarCache.clear(session.userId); const storeName: SessionStoreName = getSessionStoreName(session); await mx.clearStores({ cryptoDatabasePrefix: storeName.rustCryptoPrefix }); await deleteDatabase(storeName.sync); diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 63d99cad1..839aa4537 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -74,6 +74,7 @@ function makeManager(mx: ReturnType): SlidingSyncManager { beforeEach(() => { vi.clearAllMocks(); + localStorage.clear(); mocks.slidingSyncInstance.getListData.mockReset().mockReturnValue(null); mocks.slidingSyncInstance.getListParams.mockReset().mockReturnValue(null); mocks.slidingSyncInstance.setListRanges.mockReset(); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 442a1c08f..9f6069841 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -1,5 +1,6 @@ import type { MatrixClient, + MatrixEvent, MSC3575List, MSC3575RoomData, MSC3575RoomSubscription, @@ -15,11 +16,14 @@ import { MSC3575_STATE_KEY_LAZY, MSC3575_STATE_KEY_ME, EventType, + EventEmitterEvents, + ClientEvent, } from '$types/matrix-sdk'; import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; import { CustomStateEvent } from '$types/matrix/room'; import * as Sentry from '@sentry/react'; +import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; const log = createLogger('slidingSync'); const debugLog = createDebugLogger('slidingSync'); @@ -184,6 +188,22 @@ export class SlidingSyncManager { private readonly roomTimelineLimit: number; + private readonly sidebarCache: SlidingSyncSidebarCache; + + private cacheHydrationPromise: Promise = Promise.resolve(false); + + private cacheHydrationNewListener: + | ((eventName: string | symbol, listener: (...args: unknown[]) => void) => void) + | undefined; + + private cacheHydrationResolve: ((hydrated: boolean) => void) | undefined; + + private hydratingSidebarCache = false; + + private readonly onCacheRoomData: (roomId: string, data: MSC3575RoomData) => void; + + private readonly onCacheAccountData: (event: MatrixEvent) => void; + private readonly onLifecycle: ( state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, @@ -243,6 +263,7 @@ export class SlidingSyncManager { const roomTimelineLimit = clampPositive(options.timelineLimit, ACTIVE_ROOM_TIMELINE_LIMIT); this.roomTimelineLimit = roomTimelineLimit; + this.sidebarCache = new SlidingSyncSidebarCache(mx.getSafeUserId()); const defaultSubscription = buildEncryptedSubscription(roomTimelineLimit); const lists = buildLists(); @@ -385,10 +406,14 @@ export class SlidingSyncManager { if (member.userId !== this.mx.getUserId()) return; if (member.membership !== KnownMembership.Leave && member.membership !== KnownMembership.Ban) return; + this.sidebarCache.removeRoom(member.roomId); if (!this.activeRoomSubscriptions.has(member.roomId)) return; this.unsubscribeFromRoom(member.roomId); }; + this.onCacheRoomData = (roomId, data) => this.sidebarCache.cacheRoom(roomId, data); + this.onCacheAccountData = (event) => this.sidebarCache.cacheAccountData(event); + for (const roomId of options.initialRoomIds ?? []) { this.subscribeToRoom(roomId); } @@ -409,7 +434,9 @@ export class SlidingSyncManager { }); this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle); + this.slidingSync.on(SlidingSyncEvent.RoomData, this.onCacheRoomData); this.mx.on(RoomMemberEvent.Membership, this.onMembershipLeave); + this.mx.on(ClientEvent.AccountData, this.onCacheAccountData); debugLog.info('sync', 'Sliding sync listeners attached successfully'); } @@ -432,7 +459,19 @@ export class SlidingSyncManager { this.disposed = true; this.slidingSync.stop(); this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle); + this.slidingSync.removeListener(SlidingSyncEvent.RoomData, this.onCacheRoomData); + if (this.cacheHydrationNewListener) { + this.slidingSync.removeListener( + EventEmitterEvents.NewListener, + this.cacheHydrationNewListener as never + ); + this.cacheHydrationNewListener = undefined; + } + this.cacheHydrationResolve?.(false); + this.cacheHydrationResolve = undefined; this.mx.removeListener(RoomMemberEvent.Membership, this.onMembershipLeave); + this.mx.removeListener(ClientEvent.AccountData, this.onCacheAccountData); + this.sidebarCache.dispose(); debugLog.info('sync', 'Sliding sync disposed successfully', { totalSyncCycles: this.syncCount, @@ -455,6 +494,41 @@ export class SlidingSyncManager { }; } + public prepareSidebarCacheHydration(): void { + if (this.disposed || this.cacheHydrationNewListener) return; + + this.cacheHydrationPromise = new Promise((resolve) => { + this.cacheHydrationResolve = resolve; + }); + + this.cacheHydrationNewListener = (eventName) => { + if (eventName !== SlidingSyncEvent.RoomData) return; + const listener = this.cacheHydrationNewListener; + if (listener) { + this.slidingSync.removeListener(EventEmitterEvents.NewListener, listener as never); + } + this.cacheHydrationNewListener = undefined; + + globalThis.queueMicrotask(() => { + this.hydratingSidebarCache = true; + void this.sidebarCache + .hydrate(this.mx, this.slidingSync) + .then((hydrated) => this.cacheHydrationResolve?.(hydrated)) + .catch(() => this.cacheHydrationResolve?.(false)) + .finally(() => { + this.hydratingSidebarCache = false; + this.cacheHydrationResolve = undefined; + }); + }); + }; + + this.slidingSync.on(EventEmitterEvents.NewListener, this.cacheHydrationNewListener as never); + } + + public waitForSidebarCacheHydration(): Promise { + return this.cacheHydrationPromise; + } + private expandListsByPage(): void { if (!this.initialSyncCompleted) return; @@ -759,6 +833,7 @@ export class SlidingSyncManager { const subscribeMs = performance.now(); const onFirstRoomData = (dataRoomId: string) => { if (dataRoomId !== roomId) return; + if (this.hydratingSidebarCache) return; const latencyMs = Math.round(performance.now() - subscribeMs); const subscribedRoom = this.mx.getRoom(roomId); const eventCount = subscribedRoom?.getLiveTimeline().getEvents().length ?? 0; diff --git a/src/client/slidingSyncSidebarCache.test.ts b/src/client/slidingSyncSidebarCache.test.ts new file mode 100644 index 000000000..f288a87f0 --- /dev/null +++ b/src/client/slidingSyncSidebarCache.test.ts @@ -0,0 +1,132 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, MSC3575RoomData, SlidingSync } from '$types/matrix-sdk'; +import { EventType, MatrixEvent, SlidingSyncEvent } from '$types/matrix-sdk'; +import { CustomAccountDataEvent } from '$types/matrix/accountData'; +import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; + +const userId = '@user:example.com'; + +const stateEvent = (type: string, stateKey: string, content: Record = {}) => ({ + type, + state_key: stateKey, + content, + event_id: `$${type}-${stateKey}`, + sender: userId, + origin_server_ts: 1, +}); + +beforeEach(() => { + localStorage.clear(); +}); + +describe('SlidingSyncSidebarCache', () => { + it('restores sidebar state without caching timelines or bulk members', async () => { + const cache = new SlidingSyncSidebarCache(userId); + cache.cacheRoom('!room:example.com', { + name: 'Cached Room', + initial: true, + bump_stamp: 42, + required_state: [ + stateEvent(EventType.RoomName, '', { name: 'Cached Room' }), + stateEvent(EventType.SpaceChild, '!child:example.com', { via: ['example.com'] }), + stateEvent(EventType.RoomMember, userId, { membership: 'join' }), + stateEvent(EventType.RoomMember, '@other:example.com', { membership: 'join' }), + ], + timeline: [ + { + type: EventType.RoomMessage, + content: { body: 'do not cache me' }, + event_id: '$message', + sender: '@other:example.com', + origin_server_ts: 2, + }, + ], + } as MSC3575RoomData); + cache.cacheAccountData( + new MatrixEvent({ type: EventType.Direct, content: { '@other:example.com': ['!room'] } }) + ); + cache.cacheAccountData( + new MatrixEvent({ + type: CustomAccountDataEvent.CinnySpaces, + content: { categories: ['!room:example.com'] }, + }) + ); + cache.dispose(); + + const emitPromised = vi + .fn<(event: SlidingSyncEvent, roomId: string, data: MSC3575RoomData) => Promise>() + .mockResolvedValue(true); + const storeAccountDataEvents = vi.fn<(events: MatrixEvent[]) => void>(); + const restored = new SlidingSyncSidebarCache(userId); + const hydrated = await restored.hydrate( + { store: { storeAccountDataEvents } } as unknown as MatrixClient, + { emitPromised } as unknown as SlidingSync + ); + + expect(hydrated).toBe(true); + expect(emitPromised).toHaveBeenCalledWith( + SlidingSyncEvent.RoomData, + '!room:example.com', + expect.objectContaining({ + name: 'Cached Room', + timeline: [], + initial: true, + bump_stamp: 42, + }) + ); + const hydratedRoom = emitPromised.mock.calls[0]?.[2] as MSC3575RoomData; + expect(hydratedRoom.required_state).toHaveLength(3); + expect(hydratedRoom.required_state).toContainEqual( + expect.objectContaining({ + type: EventType.SpaceChild, + state_key: '!child:example.com', + }) + ); + expect(hydratedRoom.required_state).not.toContainEqual( + expect.objectContaining({ state_key: '@other:example.com' }) + ); + expect(storeAccountDataEvents).toHaveBeenCalledWith( + expect.arrayContaining([ + expect.objectContaining({ event: expect.objectContaining({ type: EventType.Direct }) }), + expect.objectContaining({ + event: expect.objectContaining({ type: CustomAccountDataEvent.CinnySpaces }), + }), + ]) + ); + }); + + it('merges later state into the existing cached room snapshot', async () => { + const cache = new SlidingSyncSidebarCache(userId); + cache.cacheRoom('!room:example.com', { + name: 'Before', + required_state: [stateEvent(EventType.RoomName, '', { name: 'Before' })], + timeline: [], + }); + cache.cacheRoom('!room:example.com', { + name: 'After', + required_state: [stateEvent(EventType.RoomAvatar, '', { url: 'mxc://example/avatar' })], + timeline: [], + }); + cache.dispose(); + + const emitPromised = vi + .fn<(event: SlidingSyncEvent, roomId: string, data: MSC3575RoomData) => Promise>() + .mockResolvedValue(true); + const restored = new SlidingSyncSidebarCache(userId); + await restored.hydrate( + { + store: { storeAccountDataEvents: vi.fn<(events: MatrixEvent[]) => void>() }, + } as unknown as MatrixClient, + { emitPromised } as unknown as SlidingSync + ); + + const hydratedRoom = emitPromised.mock.calls[0]?.[2] as MSC3575RoomData; + expect(hydratedRoom.name).toBe('After'); + expect(hydratedRoom.required_state).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: EventType.RoomName }), + expect.objectContaining({ type: EventType.RoomAvatar }), + ]) + ); + }); +}); diff --git a/src/client/slidingSyncSidebarCache.ts b/src/client/slidingSyncSidebarCache.ts new file mode 100644 index 000000000..d45afd842 --- /dev/null +++ b/src/client/slidingSyncSidebarCache.ts @@ -0,0 +1,212 @@ +import type { MatrixClient, MSC3575RoomData, SlidingSync } from '$types/matrix-sdk'; +import { EventType, MatrixEvent, SlidingSyncEvent } from '$types/matrix-sdk'; +import { CustomAccountDataEvent } from '$types/matrix/accountData'; + +const CACHE_VERSION = 1; +const CACHE_KEY_PREFIX = 'sable.slidingSyncSidebarCache.'; +const CACHE_WRITE_DELAY_MS = 500; +const MAX_CACHED_ROOMS = 2000; +const HYDRATION_BATCH_SIZE = 50; + +type StateEvent = MSC3575RoomData['required_state'][number]; + +type SidebarCacheData = { + version: number; + rooms: Record; + accountData: Record>; +}; + +const CACHED_ACCOUNT_DATA_TYPES = new Set([ + EventType.Direct, + CustomAccountDataEvent.CinnySpaces, +]); + +const CACHED_STATE_TYPES = new Set([ + EventType.RoomCreate, + EventType.RoomName, + EventType.RoomTopic, + EventType.RoomAvatar, + EventType.RoomCanonicalAlias, + EventType.RoomJoinRules, + EventType.RoomHistoryVisibility, + EventType.RoomGuestAccess, + EventType.RoomEncryption, + EventType.RoomTombstone, + EventType.RoomPowerLevels, + EventType.RoomPinnedEvents, + EventType.RoomServerAcl, + EventType.SpaceChild, + EventType.SpaceParent, +]); + +const emptyCache = (): SidebarCacheData => ({ + version: CACHE_VERSION, + rooms: {}, + accountData: {}, +}); + +const stateEventKey = (event: StateEvent): string => `${event.type}\u0000${event.state_key}`; + +const mergeStateEvents = ( + previous: StateEvent[] | undefined, + incoming: StateEvent[] | undefined, + userId: string +): StateEvent[] => { + const merged = new Map(); + previous?.forEach((event) => merged.set(stateEventKey(event), event)); + incoming?.forEach((event) => { + const cacheMember = event.type === 'm.room.member' && event.state_key === userId; + if (cacheMember || CACHED_STATE_TYPES.has(event.type)) { + merged.set(stateEventKey(event), event); + } + }); + return [...merged.values()]; +}; + +const mergeRoomData = ( + previous: MSC3575RoomData | undefined, + incoming: MSC3575RoomData, + userId: string +): MSC3575RoomData => ({ + ...previous, + ...incoming, + name: incoming.name ?? previous?.name ?? '', + heroes: incoming.heroes ?? previous?.heroes, + notification_count: incoming.notification_count ?? previous?.notification_count, + highlight_count: incoming.highlight_count ?? previous?.highlight_count, + joined_count: incoming.joined_count ?? previous?.joined_count, + invited_count: incoming.invited_count ?? previous?.invited_count, + is_dm: incoming.is_dm ?? previous?.is_dm, + bump_stamp: incoming.bump_stamp ?? previous?.bump_stamp, + required_state: mergeStateEvents(previous?.required_state, incoming.required_state, userId), + invite_state: incoming.invite_state + ? mergeStateEvents(previous?.invite_state, incoming.invite_state, userId) + : previous?.invite_state, + timeline: [], + initial: true, + limited: false, + num_live: 0, + prev_batch: undefined, +}); + +const parseCache = (value: string | null): SidebarCacheData => { + if (!value) return emptyCache(); + try { + const parsed = JSON.parse(value) as Partial; + if (parsed.version !== CACHE_VERSION || !parsed.rooms || !parsed.accountData) { + return emptyCache(); + } + return parsed as SidebarCacheData; + } catch { + return emptyCache(); + } +}; + +const hydrateRoomBatch = async ( + slidingSync: SlidingSync, + rooms: [string, MSC3575RoomData][], + startIndex = 0 +): Promise => { + const batch = rooms.slice(startIndex, startIndex + HYDRATION_BATCH_SIZE); + await Promise.all( + batch.map(([roomId, roomData]) => + slidingSync.emitPromised(SlidingSyncEvent.RoomData, roomId, roomData) + ) + ); + if (startIndex + HYDRATION_BATCH_SIZE < rooms.length) { + await hydrateRoomBatch(slidingSync, rooms, startIndex + HYDRATION_BATCH_SIZE); + } +}; + +export class SlidingSyncSidebarCache { + public static clear(userId: string): void { + try { + globalThis.localStorage?.removeItem(`${CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`); + } catch { + // Storage can be disabled for this origin. + } + } + + private readonly storageKey: string; + + private data: SidebarCacheData; + + private writeTimer: ReturnType | undefined; + + public constructor(private readonly userId: string) { + this.storageKey = `${CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`; + let stored: string | null = null; + try { + stored = globalThis.localStorage?.getItem(this.storageKey) ?? null; + } catch { + // Storage can be disabled for this origin. + } + this.data = parseCache(stored); + } + + public cacheRoom(roomId: string, roomData: MSC3575RoomData): void { + this.data.rooms[roomId] = mergeRoomData(this.data.rooms[roomId], roomData, this.userId); + this.scheduleWrite(); + } + + public removeRoom(roomId: string): void { + if (!this.data.rooms[roomId]) return; + delete this.data.rooms[roomId]; + this.scheduleWrite(); + } + + public cacheAccountData(event: MatrixEvent): void { + if (!CACHED_ACCOUNT_DATA_TYPES.has(event.getType())) return; + this.data.accountData[event.getType()] = event.getContent>(); + this.scheduleWrite(); + } + + public async hydrate(mx: MatrixClient, slidingSync: SlidingSync): Promise { + const rooms = Object.entries(this.data.rooms); + const accountData = Object.entries(this.data.accountData); + if (rooms.length === 0 && accountData.length === 0) return false; + + if (accountData.length > 0) { + mx.store.storeAccountDataEvents( + accountData.map(([type, content]) => new MatrixEvent({ type, content })) + ); + } + + await hydrateRoomBatch(slidingSync, rooms); + return rooms.length > 0; + } + + public dispose(): void { + if (this.writeTimer !== undefined) { + globalThis.clearTimeout(this.writeTimer); + this.writeTimer = undefined; + this.write(); + } + } + + private scheduleWrite(): void { + if (this.writeTimer !== undefined) return; + this.writeTimer = globalThis.setTimeout(() => { + this.writeTimer = undefined; + this.write(); + }, CACHE_WRITE_DELAY_MS); + } + + private write(): void { + let rooms = Object.entries(this.data.rooms) + .toSorted(([, a], [, b]) => (b.bump_stamp ?? 0) - (a.bump_stamp ?? 0)) + .slice(0, MAX_CACHED_ROOMS); + + while (true) { + const nextData = { ...this.data, rooms: Object.fromEntries(rooms) }; + try { + globalThis.localStorage?.setItem(this.storageKey, JSON.stringify(nextData)); + this.data = nextData; + return; + } catch { + if (rooms.length <= 1) return; + rooms = rooms.slice(0, Math.floor(rooms.length / 2)); + } + } + } +} diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index d05073f2e..2fb2709b5 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -22,6 +22,7 @@ export * from 'matrix-js-sdk/lib/models/user'; export * from 'matrix-js-sdk/lib/models/search-result'; export * from 'matrix-js-sdk/lib/models/event-timeline'; export * from 'matrix-js-sdk/lib/models/event-timeline-set'; +export { EventEmitterEvents } from 'matrix-js-sdk/lib/models/typed-event-emitter'; export { Relations, RelationsEvent } from 'matrix-js-sdk/lib/models/relations'; export * from 'matrix-js-sdk/lib/store/indexeddb';