Add initial sliding sync support
This commit is contained in:
1 parent
4288d772df
commit
e1b7844ff8
10 files changed
+477
-16
No files matched your search
@@ -13,6 +13,10 @@
|
||||
"webPushAppID": "cc.cinny.web"
|
||||
},
|
||||
|
||||
"slidingSync": {
|
||||
"enabled": false
|
||||
},
|
||||
|
||||
"featuredCommunities": {
|
||||
"openAsDefault": false,
|
||||
"spaces": [
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AccountDataEditor, AccountDataSubmitCallback } from '$components/Accoun
|
||||
import { copyToClipboard } from '$utils/dom';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
import { AccountData } from './AccountData';
|
||||
import { SyncDiagnostics } from './SyncDiagnostics';
|
||||
|
||||
type DeveloperToolsProps = {
|
||||
requestClose: () => void;
|
||||
@@ -111,6 +112,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
||||
</SequenceCard>
|
||||
)}
|
||||
</Box>
|
||||
{developerTools && <SyncDiagnostics />}
|
||||
{developerTools && (
|
||||
<AccountData
|
||||
expand={expand}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Box, Text } from 'folds';
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { getClientSyncDiagnostics } from '$client/initMatrix';
|
||||
import { Direction, Room } from '$types/matrix-sdk';
|
||||
import { Membership } from '$types/matrix/room';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
|
||||
type RoomRenderingDiagnostics = {
|
||||
totalRooms: number;
|
||||
joinedRooms: number;
|
||||
inviteRooms: number;
|
||||
roomsMissingName: number;
|
||||
roomsMissingAvatar: number;
|
||||
roomsWithoutLiveEvents: number;
|
||||
roomsWithBackPagination: number;
|
||||
};
|
||||
|
||||
const getRoomRenderingDiagnostics = (rooms: Room[]): RoomRenderingDiagnostics => {
|
||||
let joinedRooms = 0;
|
||||
let inviteRooms = 0;
|
||||
let roomsMissingName = 0;
|
||||
let roomsMissingAvatar = 0;
|
||||
let roomsWithoutLiveEvents = 0;
|
||||
let roomsWithBackPagination = 0;
|
||||
|
||||
rooms.forEach((room) => {
|
||||
const membership = room.getMyMembership();
|
||||
if (membership === Membership.Join) joinedRooms += 1;
|
||||
if (membership === Membership.Invite) inviteRooms += 1;
|
||||
|
||||
if (!room.name || room.name.trim().length === 0) roomsMissingName += 1;
|
||||
|
||||
const roomAvatar = room.getMxcAvatarUrl();
|
||||
const fallbackAvatar = room.getAvatarFallbackMember()?.getMxcAvatarUrl();
|
||||
if (!roomAvatar && !fallbackAvatar) roomsMissingAvatar += 1;
|
||||
|
||||
const liveTimeline = room.getLiveTimeline();
|
||||
if (liveTimeline.getEvents().length === 0) roomsWithoutLiveEvents += 1;
|
||||
if (liveTimeline.getPaginationToken(Direction.Backward)) roomsWithBackPagination += 1;
|
||||
});
|
||||
|
||||
return {
|
||||
totalRooms: rooms.length,
|
||||
joinedRooms,
|
||||
inviteRooms,
|
||||
roomsMissingName,
|
||||
roomsMissingAvatar,
|
||||
roomsWithoutLiveEvents,
|
||||
roomsWithBackPagination,
|
||||
};
|
||||
};
|
||||
|
||||
const formatListCoverage = (knownCount: number, rangeEnd: number): string => {
|
||||
if (knownCount <= 0) return '0/0';
|
||||
const loadedCount = Math.max(0, Math.min(knownCount, rangeEnd + 1));
|
||||
return `${loadedCount}/${knownCount}`;
|
||||
};
|
||||
|
||||
export function SyncDiagnostics() {
|
||||
const mx = useMatrixClient();
|
||||
const clientConfig = useClientConfig();
|
||||
const [, setTick] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = window.setInterval(() => setTick((v) => v + 1), 1000);
|
||||
return () => window.clearInterval(intervalId);
|
||||
}, []);
|
||||
|
||||
const diagnostics = getClientSyncDiagnostics(mx);
|
||||
const roomDiagnostics = getRoomRenderingDiagnostics(mx.getRooms());
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Sync Diagnostics</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<Box direction="Column" gap="100" style={{ padding: '12px' }}>
|
||||
<Text size="T300">
|
||||
Transport: {diagnostics.transport}
|
||||
{diagnostics.fallbackFromSliding ? ' (fallback)' : ''}
|
||||
</Text>
|
||||
<Text size="T300">State: {diagnostics.syncState ?? 'null'}</Text>
|
||||
<Text size="T300">
|
||||
Sliding configured: {clientConfig.slidingSync?.enabled ? 'yes' : 'no'}
|
||||
</Text>
|
||||
<Text size="T300">
|
||||
Room counts: {roomDiagnostics.totalRooms} total, {roomDiagnostics.joinedRooms} joined,{' '}
|
||||
{roomDiagnostics.inviteRooms} invites
|
||||
</Text>
|
||||
<Text size="T300">Rooms missing name: {roomDiagnostics.roomsMissingName}</Text>
|
||||
<Text size="T300">Rooms missing avatar: {roomDiagnostics.roomsMissingAvatar}</Text>
|
||||
<Text size="T300">
|
||||
Rooms without live events: {roomDiagnostics.roomsWithoutLiveEvents}
|
||||
</Text>
|
||||
<Text size="T300">
|
||||
Rooms with more history to paginate: {roomDiagnostics.roomsWithBackPagination}
|
||||
</Text>
|
||||
|
||||
{diagnostics.sliding && (
|
||||
<>
|
||||
<Text size="T300">Sliding proxy: {diagnostics.sliding.proxyBaseUrl}</Text>
|
||||
{diagnostics.sliding.lists.map((list) => (
|
||||
<Text size="T300" key={list.key}>
|
||||
List `{list.key}` coverage: {formatListCoverage(list.knownCount, list.rangeEnd)}
|
||||
</Text>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,17 @@ export type ClientConfig = {
|
||||
webPushAppID?: string;
|
||||
};
|
||||
|
||||
slidingSync?: {
|
||||
enabled?: boolean;
|
||||
proxyBaseUrl?: string;
|
||||
listPageSize?: number;
|
||||
timelineLimit?: number;
|
||||
pollTimeoutMs?: number;
|
||||
maxRooms?: number;
|
||||
includeInviteList?: boolean;
|
||||
probeTimeoutMs?: number;
|
||||
};
|
||||
|
||||
featuredCommunities?: {
|
||||
openAsDefault?: boolean;
|
||||
spaces?: string[];
|
||||
|
||||
@@ -27,10 +27,15 @@ import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { buildRoomMessageNotification } from '$utils/notificationStyle';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { startClient, stopClient } from '$client/initMatrix';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
|
||||
const log = createLogger('BackgroundNotifications');
|
||||
|
||||
const startBackgroundClient = async (session: Session): Promise<MatrixClient> => {
|
||||
const startBackgroundClient = async (
|
||||
session: Session,
|
||||
slidingSyncConfig: ReturnType<typeof useClientConfig>['slidingSync']
|
||||
): Promise<MatrixClient> => {
|
||||
const mx = createClient({
|
||||
baseUrl: session.baseUrl,
|
||||
accessToken: session.accessToken,
|
||||
@@ -38,7 +43,10 @@ const startBackgroundClient = async (session: Session): Promise<MatrixClient> =>
|
||||
deviceId: session.deviceId,
|
||||
timelineSupport: false,
|
||||
});
|
||||
await mx.startClient({ lazyLoadMembers: true, initialSyncLimit: 0 });
|
||||
await startClient(mx, {
|
||||
baseUrl: session.baseUrl,
|
||||
slidingSync: slidingSyncConfig,
|
||||
});
|
||||
return mx;
|
||||
};
|
||||
|
||||
@@ -63,6 +71,7 @@ const waitForSync = (mx: MatrixClient): Promise<void> =>
|
||||
});
|
||||
|
||||
export function BackgroundNotifications() {
|
||||
const clientConfig = useClientConfig();
|
||||
const sessions = useAtomValue(sessionsAtom);
|
||||
const activeSessionId = useAtomValue(activeSessionIdAtom);
|
||||
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
|
||||
@@ -128,7 +137,7 @@ export function BackgroundNotifications() {
|
||||
current.forEach((mx, userId) => {
|
||||
if (!activeIds.has(userId)) {
|
||||
log.log('stopping background client for', userId);
|
||||
mx.stopClient();
|
||||
stopClient(mx);
|
||||
current.delete(userId);
|
||||
}
|
||||
});
|
||||
@@ -137,7 +146,7 @@ export function BackgroundNotifications() {
|
||||
if (current.has(session.userId)) return;
|
||||
|
||||
log.log('starting background client for', session.userId);
|
||||
startBackgroundClient(session)
|
||||
startBackgroundClient(session, clientConfig.slidingSync)
|
||||
.then(async (mx) => {
|
||||
current.set(session.userId, mx);
|
||||
|
||||
@@ -229,10 +238,11 @@ export function BackgroundNotifications() {
|
||||
});
|
||||
|
||||
return () => {
|
||||
current.forEach((mx) => mx.stopClient());
|
||||
current.forEach((mx) => stopClient(mx));
|
||||
current.clear();
|
||||
};
|
||||
}, [
|
||||
clientConfig.slidingSync,
|
||||
inactiveSessions,
|
||||
forcePushOnMobile,
|
||||
showNotifications,
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
initClient,
|
||||
logoutClient,
|
||||
startClient,
|
||||
stopClient,
|
||||
} from '$client/initMatrix';
|
||||
import { SplashScreen } from '$components/splash-screen';
|
||||
import { ServerConfigsLoader } from '$components/ServerConfigsLoader';
|
||||
@@ -40,6 +41,7 @@ import { createLogger } from '$utils/debug';
|
||||
import { useSyncNicknames } from '$hooks/useNickname';
|
||||
import { useAppVisibility } from '$hooks/useAppVisibility';
|
||||
import { getHomePath } from '$pages/pathUtils';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { pushSessionToSW } from '../../../sw-session';
|
||||
import { SyncStatus } from './SyncStatus';
|
||||
import { SpecVersions } from './SpecVersions';
|
||||
@@ -139,7 +141,7 @@ function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) {
|
||||
const useLogoutListener = (mx?: MatrixClient) => {
|
||||
useEffect(() => {
|
||||
const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => {
|
||||
mx?.stopClient();
|
||||
if (mx) stopClient(mx);
|
||||
await mx?.clearStores();
|
||||
window.localStorage.clear();
|
||||
window.location.reload();
|
||||
@@ -158,6 +160,7 @@ type ClientRootProps = {
|
||||
export function ClientRoot({ children }: ClientRootProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const navigate = useNavigate();
|
||||
const clientConfig = useClientConfig();
|
||||
const sessions = useAtomValue(sessionsAtom);
|
||||
const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom);
|
||||
const setSessions = useSetAtom(sessionsAtom);
|
||||
@@ -189,7 +192,14 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
);
|
||||
const mx = loadState.status === AsyncStatus.Success ? loadState.data : undefined;
|
||||
const [startState, startMatrix] = useAsyncCallback<void, Error, [MatrixClient]>(
|
||||
useCallback((m) => startClient(m), [])
|
||||
useCallback(
|
||||
(m) =>
|
||||
startClient(m, {
|
||||
baseUrl: activeSession?.baseUrl,
|
||||
slidingSync: clientConfig.slidingSync,
|
||||
}),
|
||||
[activeSession?.baseUrl, clientConfig.slidingSync]
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -205,7 +215,7 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
// Update the SW immediately so media requests use the new account's token
|
||||
pushSessionToSW(activeSession.baseUrl, activeSession.accessToken);
|
||||
if (mx?.clientRunning) {
|
||||
mx.stopClient();
|
||||
stopClient(mx);
|
||||
}
|
||||
setLoading(true);
|
||||
loadedUserIdRef.current = undefined;
|
||||
@@ -231,7 +241,7 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
() => () => {
|
||||
if (mx?.clientRunning) {
|
||||
log.log('ClientRoot unmounting — stopping client', mx.getUserId());
|
||||
mx.stopClient();
|
||||
stopClient(mx);
|
||||
}
|
||||
},
|
||||
[mx]
|
||||
|
||||
@@ -24,7 +24,7 @@ import { nameInitials } from '$utils/common';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { getHomePath, getLoginPath, withSearchParam } from '$pages/pathUtils';
|
||||
import { logoutClient, initClient } from '$client/initMatrix';
|
||||
import { logoutClient, initClient, stopClient } from '$client/initMatrix';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useUserProfile } from '$hooks/useUserProfile';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
@@ -201,7 +201,7 @@ export function AccountSwitcherTab() {
|
||||
const handleAddAccount = () => {
|
||||
const url = withSearchParam(getLoginPath(), { addAccount: '1' });
|
||||
setMenuAnchor(undefined);
|
||||
mx.stopClient();
|
||||
stopClient(mx);
|
||||
setTimeout(() => window.location.assign(url), 100);
|
||||
};
|
||||
|
||||
|
||||
+100
-5
@@ -17,8 +17,17 @@ import { getLocalStorageItem } from '$state/utils/atomWithLocalStorage';
|
||||
import { createLogger } from '$utils/debug';
|
||||
import { pushSessionToSW } from '../sw-session';
|
||||
import { cryptoCallbacks } from './secretStorageKeys';
|
||||
import { SlidingSyncConfig, SlidingSyncDiagnostics, SlidingSyncManager } from './slidingSync';
|
||||
|
||||
const log = createLogger('initMatrix');
|
||||
const slidingSyncByClient = new WeakMap<MatrixClient, SlidingSyncManager>();
|
||||
type SyncTransport = 'classic' | 'sliding';
|
||||
type SyncTransportMeta = {
|
||||
transport: SyncTransport;
|
||||
slidingConfigured: boolean;
|
||||
fallbackFromSliding: boolean;
|
||||
};
|
||||
const syncTransportByClient = new WeakMap<MatrixClient, SyncTransportMeta>();
|
||||
|
||||
const deleteDatabase = (name: string): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
@@ -244,21 +253,107 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
return mx;
|
||||
};
|
||||
|
||||
export const startClient = async (mx: MatrixClient) => {
|
||||
export type StartClientConfig = {
|
||||
baseUrl?: string;
|
||||
slidingSync?: SlidingSyncConfig;
|
||||
};
|
||||
|
||||
export type ClientSyncDiagnostics = SyncTransportMeta & {
|
||||
syncState: string | null;
|
||||
sliding?: SlidingSyncDiagnostics;
|
||||
};
|
||||
|
||||
const disposeSlidingSync = (mx: MatrixClient): void => {
|
||||
const manager = slidingSyncByClient.get(mx);
|
||||
if (!manager) return;
|
||||
manager.dispose();
|
||||
slidingSyncByClient.delete(mx);
|
||||
};
|
||||
|
||||
export const stopClient = (mx: MatrixClient): void => {
|
||||
disposeSlidingSync(mx);
|
||||
mx.stopClient();
|
||||
};
|
||||
|
||||
export const startClient = async (mx: MatrixClient, config?: StartClientConfig) => {
|
||||
log.log('startClient', mx.getUserId());
|
||||
await mx.startClient({
|
||||
lazyLoadMembers: true,
|
||||
disposeSlidingSync(mx);
|
||||
const slidingConfig = config?.slidingSync;
|
||||
const proxyBaseUrl = slidingConfig?.proxyBaseUrl ?? config?.baseUrl;
|
||||
const canUseSliding = slidingConfig?.enabled === true && typeof proxyBaseUrl === 'string';
|
||||
syncTransportByClient.set(mx, {
|
||||
transport: 'classic',
|
||||
slidingConfigured: slidingConfig?.enabled === true,
|
||||
fallbackFromSliding: false,
|
||||
});
|
||||
|
||||
if (!canUseSliding) {
|
||||
await mx.startClient({
|
||||
lazyLoadMembers: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const resolvedProxyBaseUrl = proxyBaseUrl;
|
||||
const manager = new SlidingSyncManager(mx, resolvedProxyBaseUrl, slidingConfig);
|
||||
const supported = await SlidingSyncManager.probe(
|
||||
mx,
|
||||
resolvedProxyBaseUrl,
|
||||
manager.probeTimeoutMs
|
||||
);
|
||||
if (!supported) {
|
||||
syncTransportByClient.set(mx, {
|
||||
transport: 'classic',
|
||||
slidingConfigured: true,
|
||||
fallbackFromSliding: true,
|
||||
});
|
||||
log.warn('Sliding Sync unavailable, falling back to classic sync for', mx.getUserId());
|
||||
await mx.startClient({
|
||||
lazyLoadMembers: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
manager.attach();
|
||||
slidingSyncByClient.set(mx, manager);
|
||||
syncTransportByClient.set(mx, {
|
||||
transport: 'sliding',
|
||||
slidingConfigured: true,
|
||||
fallbackFromSliding: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await mx.startClient({
|
||||
lazyLoadMembers: true,
|
||||
slidingSync: manager.slidingSync,
|
||||
});
|
||||
} catch (err) {
|
||||
disposeSlidingSync(mx);
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const clearCacheAndReload = async (mx: MatrixClient) => {
|
||||
log.log('clearCacheAndReload', mx.getUserId());
|
||||
mx.stopClient();
|
||||
stopClient(mx);
|
||||
clearNavToActivePathStore(mx.getSafeUserId());
|
||||
await mx.store.deleteAllData();
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
export const getClientSyncDiagnostics = (mx: MatrixClient): ClientSyncDiagnostics => {
|
||||
const meta = syncTransportByClient.get(mx) ?? {
|
||||
transport: 'classic',
|
||||
slidingConfigured: false,
|
||||
fallbackFromSliding: false,
|
||||
};
|
||||
return {
|
||||
...meta,
|
||||
syncState: mx.getSyncState(),
|
||||
sliding: slidingSyncByClient.get(mx)?.getDiagnostics(),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Logs out a Matrix client and cleans up its SDK stores + IndexedDB databases.
|
||||
* Does NOT touch the Jotai sessions atom — callers must do that themselves
|
||||
@@ -267,7 +362,7 @@ export const clearCacheAndReload = async (mx: MatrixClient) => {
|
||||
export const logoutClient = async (mx: MatrixClient, session?: Session) => {
|
||||
log.log('logoutClient', { userId: mx.getUserId(), sessionUserId: session?.userId });
|
||||
pushSessionToSW();
|
||||
mx.stopClient();
|
||||
stopClient(mx);
|
||||
try {
|
||||
await mx.logout();
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
MatrixClient,
|
||||
MSC3575List,
|
||||
MSC3575RoomSubscription,
|
||||
SlidingSync,
|
||||
SlidingSyncEvent,
|
||||
SlidingSyncState,
|
||||
MSC3575_STATE_KEY_LAZY,
|
||||
MSC3575_STATE_KEY_ME,
|
||||
EventType,
|
||||
} from '$types/matrix-sdk';
|
||||
import { createLogger } from '$utils/debug';
|
||||
|
||||
const log = createLogger('slidingSync');
|
||||
|
||||
const LIST_JOINED = 'joined';
|
||||
const LIST_INVITES = 'invites';
|
||||
const DEFAULT_LIST_PAGE_SIZE = 50;
|
||||
const DEFAULT_TIMELINE_LIMIT = 30;
|
||||
const DEFAULT_POLL_TIMEOUT_MS = 30000;
|
||||
const DEFAULT_MAX_ROOMS = 5000;
|
||||
|
||||
export type SlidingSyncConfig = {
|
||||
enabled?: boolean;
|
||||
proxyBaseUrl?: string;
|
||||
listPageSize?: number;
|
||||
timelineLimit?: number;
|
||||
pollTimeoutMs?: number;
|
||||
maxRooms?: number;
|
||||
includeInviteList?: boolean;
|
||||
probeTimeoutMs?: number;
|
||||
};
|
||||
|
||||
export type SlidingSyncListDiagnostics = {
|
||||
key: string;
|
||||
knownCount: number;
|
||||
rangeEnd: number;
|
||||
};
|
||||
|
||||
export type SlidingSyncDiagnostics = {
|
||||
proxyBaseUrl: string;
|
||||
lists: SlidingSyncListDiagnostics[];
|
||||
};
|
||||
|
||||
const clampPositive = (value: number | undefined, fallback: number): number => {
|
||||
if (typeof value !== 'number' || Number.isNaN(value) || value <= 0) return fallback;
|
||||
return Math.round(value);
|
||||
};
|
||||
|
||||
const buildDefaultSubscription = (timelineLimit: number): MSC3575RoomSubscription => ({
|
||||
timeline_limit: timelineLimit,
|
||||
required_state: [
|
||||
[EventType.RoomMember, MSC3575_STATE_KEY_ME],
|
||||
[EventType.RoomMember, MSC3575_STATE_KEY_LAZY],
|
||||
[EventType.RoomCreate, ''],
|
||||
[EventType.RoomName, ''],
|
||||
[EventType.RoomAvatar, ''],
|
||||
[EventType.RoomCanonicalAlias, ''],
|
||||
[EventType.RoomEncryption, ''],
|
||||
[EventType.RoomTombstone, ''],
|
||||
[EventType.RoomJoinRules, ''],
|
||||
[EventType.RoomHistoryVisibility, ''],
|
||||
[EventType.SpaceChild, '*'],
|
||||
[EventType.SpaceParent, '*'],
|
||||
],
|
||||
});
|
||||
|
||||
const buildLists = (
|
||||
pageSize: number,
|
||||
timelineLimit: number,
|
||||
includeInviteList: boolean
|
||||
): Map<string, MSC3575List> => {
|
||||
const lists = new Map<string, MSC3575List>();
|
||||
lists.set(LIST_JOINED, {
|
||||
ranges: [[0, Math.max(0, pageSize - 1)]],
|
||||
timeline_limit: timelineLimit,
|
||||
slow_get_all_rooms: true,
|
||||
filters: {
|
||||
is_invite: false,
|
||||
},
|
||||
});
|
||||
|
||||
if (includeInviteList) {
|
||||
lists.set(LIST_INVITES, {
|
||||
ranges: [[0, Math.max(0, pageSize - 1)]],
|
||||
timeline_limit: timelineLimit,
|
||||
slow_get_all_rooms: true,
|
||||
filters: {
|
||||
is_invite: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return lists;
|
||||
};
|
||||
|
||||
const getListEndIndex = (list: MSC3575List | null): number => {
|
||||
if (!list?.ranges?.length) return -1;
|
||||
return list.ranges.reduce((max, range) => Math.max(max, range[1] ?? -1), -1);
|
||||
};
|
||||
|
||||
export class SlidingSyncManager {
|
||||
private disposed = false;
|
||||
|
||||
private readonly maxRooms: number;
|
||||
|
||||
private readonly listKeys: string[];
|
||||
|
||||
private readonly onLifecycle: (state: SlidingSyncState, resp: unknown, err?: Error) => void;
|
||||
|
||||
public readonly slidingSync: SlidingSync;
|
||||
|
||||
public readonly probeTimeoutMs: number;
|
||||
|
||||
public constructor(
|
||||
private readonly mx: MatrixClient,
|
||||
private readonly proxyBaseUrl: string,
|
||||
config: SlidingSyncConfig
|
||||
) {
|
||||
const listPageSize = clampPositive(config.listPageSize, DEFAULT_LIST_PAGE_SIZE);
|
||||
const timelineLimit = clampPositive(config.timelineLimit, DEFAULT_TIMELINE_LIMIT);
|
||||
const pollTimeoutMs = clampPositive(config.pollTimeoutMs, DEFAULT_POLL_TIMEOUT_MS);
|
||||
this.probeTimeoutMs = clampPositive(config.probeTimeoutMs, 5000);
|
||||
this.maxRooms = clampPositive(config.maxRooms, DEFAULT_MAX_ROOMS);
|
||||
const includeInviteList = config.includeInviteList !== false;
|
||||
|
||||
const subscription = buildDefaultSubscription(timelineLimit);
|
||||
const lists = buildLists(listPageSize, timelineLimit, includeInviteList);
|
||||
this.listKeys = Array.from(lists.keys());
|
||||
this.slidingSync = new SlidingSync(proxyBaseUrl, lists, subscription, mx, pollTimeoutMs);
|
||||
|
||||
this.onLifecycle = (state, resp, err) => {
|
||||
if (this.disposed || err || !resp || state !== SlidingSyncState.Complete) return;
|
||||
this.expandListsToKnownCount();
|
||||
};
|
||||
}
|
||||
|
||||
public attach(): void {
|
||||
this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle);
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle);
|
||||
}
|
||||
|
||||
public getDiagnostics(): SlidingSyncDiagnostics {
|
||||
return {
|
||||
proxyBaseUrl: this.proxyBaseUrl,
|
||||
lists: this.listKeys.map((key) => {
|
||||
const listData = this.slidingSync.getListData(key);
|
||||
const params = this.slidingSync.getListParams(key);
|
||||
return {
|
||||
key,
|
||||
knownCount: listData?.joinedCount ?? 0,
|
||||
rangeEnd: getListEndIndex(params),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private expandListsToKnownCount(): void {
|
||||
this.listKeys.forEach((key) => {
|
||||
const listData = this.slidingSync.getListData(key);
|
||||
const knownCount = listData?.joinedCount ?? 0;
|
||||
if (knownCount <= 0) return;
|
||||
|
||||
const desiredEnd = Math.min(knownCount, this.maxRooms) - 1;
|
||||
const existing = this.slidingSync.getListParams(key);
|
||||
const currentEnd = getListEndIndex(existing);
|
||||
if (desiredEnd === currentEnd) return;
|
||||
|
||||
this.slidingSync.setListRanges(key, [[0, desiredEnd]]);
|
||||
if (knownCount > this.maxRooms) {
|
||||
log.warn(
|
||||
`Sliding Sync list "${key}" capped at ${this.maxRooms}/${knownCount} rooms for ${this.mx.getUserId()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static async probe(
|
||||
mx: MatrixClient,
|
||||
proxyBaseUrl: string,
|
||||
probeTimeoutMs: number
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const response = await mx.slidingSync(
|
||||
{
|
||||
lists: {
|
||||
probe: {
|
||||
ranges: [[0, 0]],
|
||||
timeline_limit: 1,
|
||||
},
|
||||
},
|
||||
timeout: 0,
|
||||
clientTimeout: probeTimeoutMs,
|
||||
},
|
||||
proxyBaseUrl
|
||||
);
|
||||
|
||||
return typeof response.pos === 'string' && response.pos.length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export * from 'matrix-js-sdk/lib/interactive-auth';
|
||||
export * from 'matrix-js-sdk/lib/content-repo';
|
||||
export * from 'matrix-js-sdk/lib/sync';
|
||||
export * from 'matrix-js-sdk/lib/sync-accumulator';
|
||||
export * from 'matrix-js-sdk/lib/sliding-sync';
|
||||
export { createClient } from 'matrix-js-sdk/lib/matrix';
|
||||
|
||||
export * from 'matrix-js-sdk/lib/models/event';
|
||||
|
||||
Reference in new issue
Block a user