mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-01 22:32:32 -08:00
fix: handle notification delivery across mobile providers
This commit is contained in:
16 files changed
+327
-52
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix push notification delivery across providers on Android and iOS.
|
||||
Generated
+1
-1
@@ -8325,7 +8325,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "tauri-plugin-notifications"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=758156fd9b1cbc99c83062194a2a59c411b5907f#758156fd9b1cbc99c83062194a2a59c411b5907f"
|
||||
source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=a837cd9bb87fe85ecb2a8061e6ec7e8933823dd0#a837cd9bb87fe85ecb2a8061e6ec7e8933823dd0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
|
||||
@@ -110,12 +110,12 @@ windows = { version = "0.62", features = [
|
||||
tauri-plugin-single-instance = { version = "2.4.3", features = ["deep-link"] }
|
||||
|
||||
[target.'cfg(any(windows, target_os = "linux"))'.dependencies]
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "758156fd9b1cbc99c83062194a2a59c411b5907f" }
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "a837cd9bb87fe85ecb2a8061e6ec7e8933823dd0" }
|
||||
|
||||
# default-features = false drops notify-rust so macOS uses the native
|
||||
# UNUserNotificationCenter backend (needs a signed .app to deliver).
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "758156fd9b1cbc99c83062194a2a59c411b5907f", default-features = false }
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "a837cd9bb87fe85ecb2a8061e6ec7e8933823dd0", default-features = false }
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-updater = { version = "2", optional = true }
|
||||
@@ -139,7 +139,7 @@ libloading = "0.9"
|
||||
zbus = "5"
|
||||
|
||||
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "758156fd9b1cbc99c83062194a2a59c411b5907f", features = [
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "a837cd9bb87fe85ecb2a8061e6ec7e8933823dd0", features = [
|
||||
"push-notifications",
|
||||
] }
|
||||
tauri-plugin-edge-to-edge = { git = "https://github.com/SableClient/tauri-plugin-edge-to-edge.git", rev = "33c6116c27be28c06df5a9d02231ecc5fdeb93c5" }
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
<array>
|
||||
<string>audio</string>
|
||||
<string>voip</string>
|
||||
<string>remote-notification</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -91,7 +91,7 @@ targets:
|
||||
properties:
|
||||
LSRequiresIPhoneOS: true
|
||||
UILaunchStoryboardName: LaunchScreen
|
||||
UIBackgroundModes: [audio, voip]
|
||||
UIBackgroundModes: [audio, voip, remote-notification]
|
||||
NSMicrophoneUsageDescription: Sable uses your microphone for calls.
|
||||
NSCameraUsageDescription: Sable uses your camera for video calls.
|
||||
UIRequiredDeviceCapabilities: [arm64, metal]
|
||||
@@ -119,6 +119,8 @@ targets:
|
||||
{{this.key}}: {{this.value}}{{/each}}
|
||||
entitlements:
|
||||
path: {{app.name}}_iOS/{{app.name}}_iOS.entitlements
|
||||
properties:
|
||||
aps-environment: development
|
||||
scheme:
|
||||
environmentVariables:
|
||||
RUST_BACKTRACE: full
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type DecryptPushParams = {
|
||||
userId: string;
|
||||
@@ -26,6 +26,7 @@ const event = {
|
||||
};
|
||||
|
||||
describe('decryptPushEventNatively', () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
isTauri.mockReturnValue(true);
|
||||
@@ -83,6 +84,18 @@ describe('decryptPushEventNatively', () => {
|
||||
await expect(decryptPushEventNatively('@me:example.org', 'DEVICE', event)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('lets SDK key recovery proceed when native decryption stalls', async () => {
|
||||
vi.useFakeTimers();
|
||||
engineDecryptPush.mockReturnValue(new Promise(() => {}));
|
||||
let result: unknown = 'pending';
|
||||
void decryptPushEventNatively('@me:example.org', 'DEVICE', event).then((value) => {
|
||||
result = value;
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
expect(result).toBeNull();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('returns null rather than throwing when isTauri itself throws', async () => {
|
||||
isTauri.mockImplementation(() => {
|
||||
throw new Error('not in a tauri context');
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { IContent } from '$types/matrix-sdk';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
|
||||
const pushDecryptLog = createDebugLogger('push-decrypt');
|
||||
const NATIVE_DECRYPT_TIMEOUT_MS = 2_000;
|
||||
|
||||
export type DecryptedPushEvent = {
|
||||
eventType: string;
|
||||
@@ -30,10 +31,11 @@ export const decryptPushEventNatively = async (
|
||||
): Promise<DecryptedPushEvent | null> => {
|
||||
if (!userId || !deviceId) return null;
|
||||
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
if (!isTauri()) return null;
|
||||
|
||||
const decrypted = await engineDecryptPush({
|
||||
const nativeDecryption = engineDecryptPush({
|
||||
userId,
|
||||
deviceId,
|
||||
roomId: event.roomId,
|
||||
@@ -47,6 +49,13 @@ export const decryptPushEventNatively = async (
|
||||
}),
|
||||
passphrase: null,
|
||||
});
|
||||
const decrypted = await Promise.race([
|
||||
nativeDecryption,
|
||||
new Promise<null>((resolve) => {
|
||||
timeoutId = setTimeout(() => resolve(null), NATIVE_DECRYPT_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
if (!decrypted) return null;
|
||||
|
||||
// `engine_decrypt_push` reports snake_case, and hands the clear event over as JSON text.
|
||||
const clearEvent = JSON.parse(decrypted.clear_event) as { content?: IContent };
|
||||
@@ -65,5 +74,7 @@ export const decryptPushEventNatively = async (
|
||||
{ reason: error instanceof Error ? error.message : String(error) }
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { iosApp } from '$utils/platform';
|
||||
import type { IPusherRequest, MatrixClient } from '$types/matrix-sdk';
|
||||
import type { ClientConfig } from '$hooks/useClientConfig';
|
||||
import { MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND } from '$unstable/prefixes';
|
||||
@@ -50,9 +51,10 @@ function clearStoredNativePushRegistration(): void {
|
||||
}
|
||||
|
||||
function getNativePushAppId(clientConfig: ClientConfig): string {
|
||||
const appId = clientConfig.pushNotificationDetails?.nativePushAppID;
|
||||
const field = iosApp() ? 'iosPushAppID' : 'nativePushAppID';
|
||||
const appId = clientConfig.pushNotificationDetails?.[field]?.trim();
|
||||
if (!appId) {
|
||||
throw new Error('Native push requires pushNotificationDetails.nativePushAppID in config.json.');
|
||||
throw new Error(`Native push requires pushNotificationDetails.${field} in config.json.`);
|
||||
}
|
||||
return appId;
|
||||
}
|
||||
@@ -274,6 +276,7 @@ export async function disableNativePush(
|
||||
const appIds = [
|
||||
clientConfig.pushNotificationDetails?.webPushAppID,
|
||||
clientConfig.pushNotificationDetails?.nativePushAppID,
|
||||
clientConfig.pushNotificationDetails?.iosPushAppID,
|
||||
].filter((appId): appId is string => Boolean(appId));
|
||||
await Promise.all(appIds.map((appId) => removeNativePushersForCurrentDevice(mx, appId)));
|
||||
}
|
||||
|
||||
@@ -43,4 +43,78 @@ describe('parseUnifiedPushMessage', () => {
|
||||
expect(parseUnifiedPushMessage({})).toBeNull();
|
||||
expect(parseUnifiedPushMessage({ message: 'not json' })).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['flat', 'object', 'string'])(
|
||||
'preserves gateway recipients in %s payloads',
|
||||
(wrapper) => {
|
||||
for (const recipient of ['notification', 'envelope', 'device', 'default_payload']) {
|
||||
const notification: Record<string, unknown> = { room_id: '!r:server', event_id: '$e' };
|
||||
const envelope: Record<string, unknown> = wrapper === 'flat' ? notification : {};
|
||||
if (recipient === 'notification') notification.user_id = '@a:server';
|
||||
else if (recipient === 'envelope') envelope.user_id = '@a:server';
|
||||
else
|
||||
notification.devices = [
|
||||
{
|
||||
data:
|
||||
recipient === 'device'
|
||||
? { user_id: '@a:server' }
|
||||
: { default_payload: { user_id: '@a:server' } },
|
||||
},
|
||||
];
|
||||
if (wrapper === 'object') envelope.notification = notification;
|
||||
if (wrapper === 'string') envelope.notification = JSON.stringify(notification);
|
||||
expect(parseUnifiedPushMessage({ message: JSON.stringify(envelope) })).toMatchObject({
|
||||
room_id: '!r:server',
|
||||
event_id: '$e',
|
||||
user_id: '@a:server',
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects conflicting account identities, including device defaults', () => {
|
||||
expect(
|
||||
parseUnifiedPushMessage({
|
||||
message: JSON.stringify({
|
||||
user_id: '@a:server',
|
||||
notification: { user_id: '@b:server' },
|
||||
}),
|
||||
})
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseUnifiedPushMessage({
|
||||
message: JSON.stringify({
|
||||
notification: {
|
||||
devices: ['@a:server', '@b:server'].map((user_id) => ({
|
||||
data: { default_payload: { user_id } },
|
||||
})),
|
||||
},
|
||||
}),
|
||||
})
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('accepts string-encoded notifications while preserving the envelope recipient', () => {
|
||||
expect(
|
||||
parseUnifiedPushMessage({
|
||||
message: JSON.stringify({
|
||||
user_id: '@a:server',
|
||||
notification: JSON.stringify({ room_id: '!r:server', event_id: '$e' }),
|
||||
}),
|
||||
})
|
||||
).toEqual({ room_id: '!r:server', event_id: '$e', user_id: '@a:server' });
|
||||
});
|
||||
|
||||
it('rejects non-object payloads and wrappers', () => {
|
||||
for (const payload of [
|
||||
[],
|
||||
null,
|
||||
1,
|
||||
{ notification: null },
|
||||
{ notification: [] },
|
||||
{ notification: 'invalid' },
|
||||
]) {
|
||||
expect(parseUnifiedPushMessage({ message: JSON.stringify(payload) })).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -20,11 +20,38 @@ export function parseUnifiedPushMessage(raw: unknown): Record<string, unknown> |
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if (!isRecord(payload)) return null;
|
||||
|
||||
const notification = (payload as { notification?: unknown }).notification;
|
||||
if (notification && typeof notification === 'object') {
|
||||
return notification as Record<string, unknown>;
|
||||
let notification = payload.notification === undefined ? payload : payload.notification;
|
||||
if (typeof notification === 'string') {
|
||||
try {
|
||||
notification = JSON.parse(notification);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return payload as Record<string, unknown>;
|
||||
if (!isRecord(notification)) return null;
|
||||
|
||||
const recipients = new Set<string>();
|
||||
const addRecipient = (value: unknown) => {
|
||||
if (typeof value === 'string' && value.trim()) recipients.add(value.trim());
|
||||
};
|
||||
addRecipient(payload.user_id);
|
||||
addRecipient(notification.user_id);
|
||||
if (Array.isArray(notification.devices)) {
|
||||
for (const device of notification.devices) {
|
||||
if (!isRecord(device) || !isRecord(device.data)) continue;
|
||||
addRecipient(device.data.user_id);
|
||||
if (isRecord(device.data.default_payload)) {
|
||||
addRecipient(device.data.default_payload.user_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (recipients.size > 1) return null;
|
||||
const [userId] = recipients;
|
||||
return userId ? { ...notification, user_id: userId } : notification;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
@@ -206,6 +206,50 @@ describe('UnifiedPushNotifications', () => {
|
||||
expect(matrixClient.getRoom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('delivers wrapped gateway pushes with the account on the envelope', async () => {
|
||||
await listenAndPush({
|
||||
notification: {
|
||||
type: 'm.room.message',
|
||||
room_id: '!room:example.com',
|
||||
event_id: '$wrapped',
|
||||
content: { body: 'gateway message' },
|
||||
},
|
||||
});
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(notificationsApi.sendNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: expect.stringContaining('gateway message') })
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
it('delivers ntfy Matrix gateway pushes whose account is in device default_payload', async () => {
|
||||
await listenForUnifiedPushMessages(() => makeSettings() as never);
|
||||
pushHandler({
|
||||
message: JSON.stringify({
|
||||
notification: {
|
||||
room_id: '!room:example.com',
|
||||
event_id: '$ntfy',
|
||||
type: 'm.room.message',
|
||||
content: { body: 'ntfy message' },
|
||||
devices: [
|
||||
{
|
||||
pushkey: 'https://ntfy.sh/up123?up=1',
|
||||
data: {
|
||||
default_payload: { user_id: '@user:example.com' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
});
|
||||
await vi.waitFor(() =>
|
||||
expect(notificationsApi.sendNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: expect.stringContaining('ntfy message') })
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
it('posts an encrypted baseline before a hanging local decryption completes', async () => {
|
||||
matrixClient.getRoom.mockReturnValue(makeRoom());
|
||||
let resolveDecryption!: (content: Record<string, unknown>) => void;
|
||||
@@ -765,6 +809,27 @@ describe('UnifiedPushNotifications', () => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('finishes registration even when gateway discovery never answers', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(() => new Promise<Response>(() => {}))
|
||||
);
|
||||
try {
|
||||
let result: unknown;
|
||||
void tryEnableUnifiedPush(matrixClient as never).then((value) => {
|
||||
result = value;
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(result).toMatchObject({
|
||||
status: 'registered',
|
||||
gatewayUrl: 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify',
|
||||
});
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the gateway webpush pusher when the homeserver does not support MSC4174', async () => {
|
||||
unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({
|
||||
status: 'registered',
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
resolveNotificationPreviewText,
|
||||
ENCRYPTED_MESSAGE_PREVIEW,
|
||||
} from '$utils/notificationStyle';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { getStateEvent } from '$utils/room/hierarchy';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
@@ -170,13 +171,27 @@ export async function discoverPushGateway(endpoint: string): Promise<string> {
|
||||
return UP_PUBLIC_GATEWAY;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const response = await fetch(candidate, { method: 'GET' });
|
||||
if (!response.ok) return UP_PUBLIC_GATEWAY;
|
||||
const body = (await response.json()) as { unifiedpush?: { gateway?: unknown } };
|
||||
if (body?.unifiedpush?.gateway === 'matrix') return candidate;
|
||||
return await Promise.race([
|
||||
(async () => {
|
||||
const response = await fetch(candidate, { method: 'GET', signal: controller.signal });
|
||||
if (!response.ok) return UP_PUBLIC_GATEWAY;
|
||||
const body = (await response.json()) as { unifiedpush?: { gateway?: unknown } };
|
||||
return body?.unifiedpush?.gateway === 'matrix' ? candidate : UP_PUBLIC_GATEWAY;
|
||||
})(),
|
||||
new Promise<string>((resolve) => {
|
||||
timeoutId = setTimeout(() => {
|
||||
resolve(UP_PUBLIC_GATEWAY);
|
||||
controller.abort();
|
||||
}, 5000);
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
// Unreachable or not JSON: the provider does not proxy.
|
||||
} finally {
|
||||
if (timeoutId !== undefined) clearTimeout(timeoutId);
|
||||
}
|
||||
return UP_PUBLIC_GATEWAY;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ export type ClientConfig = {
|
||||
vapidPublicKey?: string;
|
||||
webPushAppID?: string;
|
||||
nativePushAppID?: string;
|
||||
iosPushAppID?: string;
|
||||
unifiedPushAppID?: string;
|
||||
unifiedPushGatewayUrl?: string;
|
||||
};
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
IndexedDBStore,
|
||||
MatrixEventEvent,
|
||||
RoomEvent,
|
||||
SyncState,
|
||||
EventType,
|
||||
} from '$types/matrix-sdk';
|
||||
|
||||
@@ -45,11 +44,15 @@ import { startClient, stopClient } from '$client/initMatrix';
|
||||
import { createSessionTokenRefresher } from '$client/oidcTokenRefresher';
|
||||
import { hasServiceWorker, isDesktopTauri } from '$utils/platform';
|
||||
import { isMobileOrTablet } from '$utils/platform';
|
||||
import {
|
||||
BACKGROUND_SYNC_POLL_TIMEOUT_MS,
|
||||
isClientReadyForNotifications,
|
||||
waitForSync,
|
||||
} from './backgroundNotificationSync';
|
||||
|
||||
const log = createLogger('BackgroundNotifications');
|
||||
const debugLog = createDebugLogger('BackgroundNotifications');
|
||||
|
||||
const BACKGROUND_SYNC_POLL_TIMEOUT_MS = 60_000;
|
||||
const BACKGROUND_STAGGER_DELAY_MS = 5_000;
|
||||
|
||||
let desktopNotificationSeq = 1;
|
||||
@@ -59,9 +62,6 @@ const nextDesktopNotificationId = (): number => {
|
||||
return id;
|
||||
};
|
||||
|
||||
const isClientReadyForNotifications = (state: SyncState | string | null): boolean =>
|
||||
state === SyncState.Prepared || state === SyncState.Syncing || state === SyncState.Catchup;
|
||||
|
||||
const startBackgroundClient = async (session: Session): Promise<MatrixClient> => {
|
||||
const storeName = {
|
||||
sync: `bg-sync${session.userId}`,
|
||||
@@ -110,34 +110,6 @@ const startBackgroundClient = async (session: Session): Promise<MatrixClient> =>
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Wait for the background client to finish its initial sync so that
|
||||
* push rules and account data are available before processing events.
|
||||
* Rejects after 30 seconds so callers can handle a stalled client instead
|
||||
* of blocking indefinitely.
|
||||
*/
|
||||
const waitForSync = (mx: MatrixClient): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const state = mx.getSyncState();
|
||||
if (isClientReadyForNotifications(state)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const timer: { id: ReturnType<typeof setTimeout> | undefined } = { id: undefined };
|
||||
function onSync(newState: SyncState) {
|
||||
if (isClientReadyForNotifications(newState)) {
|
||||
if (timer.id !== undefined) clearTimeout(timer.id);
|
||||
mx.removeListener(ClientEvent.Sync, onSync);
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
mx.on(ClientEvent.Sync, onSync);
|
||||
timer.id = setTimeout(() => {
|
||||
mx.removeListener(ClientEvent.Sync, onSync);
|
||||
reject(new Error('background client sync timed out'));
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
export function BackgroundNotifications() {
|
||||
const sessions = useAtomValue(sessionsAtom);
|
||||
const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom);
|
||||
@@ -214,6 +186,7 @@ export function BackgroundNotifications() {
|
||||
|
||||
const { current } = clientsRef;
|
||||
let disposed = false;
|
||||
const syncAbort = new AbortController();
|
||||
const activeIds = new Set(inactiveSessions.map((s) => s.userId));
|
||||
const retryTimers: ReturnType<typeof setTimeout>[] = [];
|
||||
|
||||
@@ -310,7 +283,7 @@ export function BackgroundNotifications() {
|
||||
current.set(session.userId, mx);
|
||||
Sentry.metrics.gauge('sable.background.client_count', current.size);
|
||||
|
||||
await waitForSync(mx);
|
||||
await waitForSync(mx, syncAbort.signal);
|
||||
|
||||
if (disposed) return;
|
||||
if (current.get(session.userId) !== mx) {
|
||||
@@ -642,6 +615,7 @@ export function BackgroundNotifications() {
|
||||
const cleanupMap = clientCleanupRef.current;
|
||||
return () => {
|
||||
disposed = true;
|
||||
syncAbort.abort();
|
||||
staggerTimers.forEach(clearTimeout);
|
||||
retryTimers.forEach(clearTimeout);
|
||||
current.forEach((mx, userId) => {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { ClientEvent, SyncState, type MatrixClient } from '$types/matrix-sdk';
|
||||
import { waitForSync } from './backgroundNotificationSync';
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('allows a background sync poll to finish after thirty seconds', async () => {
|
||||
vi.useFakeTimers();
|
||||
const mx = Object.assign(new EventEmitter(), { getSyncState: () => null });
|
||||
const ready = waitForSync(mx as unknown as MatrixClient);
|
||||
const outcome = ready.then(
|
||||
() => 'ready',
|
||||
() => 'failed'
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(45_000);
|
||||
mx.emit(ClientEvent.Sync, SyncState.Prepared);
|
||||
await expect(outcome).resolves.toBe('ready');
|
||||
expect(mx.listenerCount(ClientEvent.Sync)).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('cancels an in-flight wait when its background client is disposed', async () => {
|
||||
vi.useFakeTimers();
|
||||
const mx = Object.assign(new EventEmitter(), { getSyncState: () => null });
|
||||
const controller = new AbortController();
|
||||
const ready = waitForSync(mx as unknown as MatrixClient, controller.signal);
|
||||
controller.abort();
|
||||
await expect(ready).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(mx.listenerCount(ClientEvent.Sync)).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('still times out a stalled client and releases its listener', async () => {
|
||||
vi.useFakeTimers();
|
||||
const mx = Object.assign(new EventEmitter(), { getSyncState: () => null });
|
||||
const result = waitForSync(mx as unknown as MatrixClient).catch((error) => error);
|
||||
await vi.advanceTimersByTimeAsync(90_000);
|
||||
expect(await result).toMatchObject({ message: 'background client sync timed out' });
|
||||
expect(mx.listenerCount(ClientEvent.Sync)).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { ClientEvent, SyncState, type MatrixClient } from '$types/matrix-sdk';
|
||||
|
||||
export const BACKGROUND_SYNC_POLL_TIMEOUT_MS = 60_000;
|
||||
const INITIAL_SYNC_TIMEOUT_MS = BACKGROUND_SYNC_POLL_TIMEOUT_MS + 30_000;
|
||||
|
||||
export const isClientReadyForNotifications = (state: SyncState | string | null): boolean =>
|
||||
state === SyncState.Prepared || state === SyncState.Syncing || state === SyncState.Catchup;
|
||||
|
||||
export const waitForSync = (mx: MatrixClient, signal?: AbortSignal): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
reject(signal.reason);
|
||||
return;
|
||||
}
|
||||
if (isClientReadyForNotifications(mx.getSyncState())) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
mx.removeListener(ClientEvent.Sync, onSync);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
};
|
||||
const onSync = (state: SyncState) => {
|
||||
if (!isClientReadyForNotifications(state)) return;
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const onAbort = () => {
|
||||
cleanup();
|
||||
reject(signal?.reason);
|
||||
};
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error('background client sync timed out'));
|
||||
}, INITIAL_SYNC_TIMEOUT_MS);
|
||||
mx.on(ClientEvent.Sync, onSync);
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
onSync(mx.getSyncState() as SyncState);
|
||||
});
|
||||
Reference in new issue
Block a user