Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(realtime): authenticate native GraphQL websocket and recover in place (#8030)

teo07e88a205137
diff --git a/apps/web/patches/[email protected] b/apps/web/patches/[email protected]
new file mode 100644
index 0000000000..4069cd0dec
--- /dev/null
+++ b/apps/web/patches/[email protected]
@@ -0,0 +1,32 @@
+diff --git a/dist/client.cjs b/dist/client.cjs
+index 631b9dc694859136f0f32e869ec6156d8dbc0877..fb1433fb0170f6fb38a94a6ed8889040e2a2a57b 100644
+--- a/dist/client.cjs
++++ b/dist/client.cjs
+@@ -251,7 +251,10 @@ function createClient(options) {
+ );
+ }
+ };
+- })()
++ })().catch((error) => {
++ connecting = void 0;
++ denied(error);
++ })
+ )));
+ if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose;
+ let release = () => {
+diff --git a/dist/client.js b/dist/client.js
+index 6cabb00d5d76261235626c41bf5bdd6204ae1da8..39e2d33f71f3027b878a251a4b5ac7bee6902bf5 100644
+--- a/dist/client.js
++++ b/dist/client.js
+@@ -250,7 +250,10 @@ function createClient(options) {
+ );
+ }
+ };
+- })()
++ })().catch((error) => {
++ connecting = void 0;
++ denied(error);
++ })
+ )));
+ if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose;
+ let release = () => {
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts
index 6b53147838..fe88f422ec 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts
@@ -1,10 +1,39 @@
-import { describe, expect, it, vi } from 'vitest';
+import { err, ok } from 'neverthrow';
+import { afterEach, describe, expect, it, vi } from 'vitest';
const toastFailure = vi.hoisted(() => vi.fn());
vi.mock('@core/component/Toast/Toast', () => ({
toast: { failure: toastFailure },
}));
+const nativeStatus = vi.hoisted(() => ({
+ listeners: new Set<(status: string) => void>(),
+}));
+vi.mock('@core/mobile/native-network-status', () => ({
+ subscribeNativeNetworkStatus: (listener: (status: string) => void) => {
+ nativeStatus.listeners.add(listener);
+ listener('online');
+ return () => nativeStatus.listeners.delete(listener);
+ },
+}));
+
+function setNativeStatus(status: string) {
+ for (const listener of [...nativeStatus.listeners]) listener(status);
+}
+
+function setVisibility(state: DocumentVisibilityState) {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => state,
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ setVisibility('visible');
+});
+
import {
ActivityUpdatesDocument,
NotificationUpdatesDocument,
@@ -14,9 +43,11 @@ import {
buildGraphqlSoupWebSocketUrl,
createGraphqlSoupSubscriptionsLifecycle,
createGraphqlSoupWebSocketUrlResolver,
+ GraphqlSoupWebSocketAuthUnavailableError,
SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
shouldRetryGraphqlSoupWebSocket,
subscribeToGraphqlNotificationPatches,
+ waitToRetryGraphqlSoupWebSocket,
} from './graphql-soup-websocket';
describe('GraphQL Soup websocket auth', () => {
@@ -32,7 +63,7 @@ describe('GraphQL Soup websocket auth', () => {
});
it('refreshes cookie auth before resolving each connection URL', async () => {
- const refreshCookieAuth = vi.fn().mockResolvedValue(undefined);
+ const refreshCookieAuth = vi.fn().mockResolvedValue(ok(undefined));
const getApiToken = vi.fn();
const resolveUrl = createGraphqlSoupWebSocketUrlResolver({
dssHost: 'https://gateway.macro.com/dss',
@@ -65,11 +96,35 @@ describe('GraphQL Soup websocket auth', () => {
await expect(resolveUrl()).resolves.toContain('macro-api-token=second');
expect(refreshCookieAuth).not.toHaveBeenCalled();
});
+
+ it('retries a cookie refresh lost to an outage but not a rejected session', async () => {
+ const resolverFor = (code: string) =>
+ createGraphqlSoupWebSocketUrlResolver({
+ dssHost: 'https://gateway.macro.com/dss',
+ bearerTokenAuth: false,
+ getApiToken: vi.fn(),
+ refreshCookieAuth: vi.fn().mockResolvedValue(err([{ code }])),
+ });
+
+ for (const code of ['NETWORK_ERROR', 'UNKNOWN_ERROR', 'HTTP_ERROR']) {
+ const error = await resolverFor(code)().catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(GraphqlSoupWebSocketAuthUnavailableError);
+ expect(shouldRetryGraphqlSoupWebSocket(error)).toBe(true);
+ }
+
+ const rejected = await resolverFor('UNAUTHORIZED')().catch(
+ (e: unknown) => e
+ );
+ expect(rejected).toBeInstanceOf(Error);
+ expect(shouldRetryGraphqlSoupWebSocket(rejected)).toBe(false);
+ });
});
describe('GraphQL Soup websocket retry policy', () => {
- it('bounds retries and accepts only transient failures', () => {
- expect(SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS).toBe(5);
+ it('keeps retrying transient failures but not auth or protocol failures', () => {
+ expect(SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS).toBe(
+ Number.POSITIVE_INFINITY
+ );
expect(shouldRetryGraphqlSoupWebSocket({ code: 1006 })).toBe(true);
expect(shouldRetryGraphqlSoupWebSocket({ code: 1013 })).toBe(true);
expect(shouldRetryGraphqlSoupWebSocket(new Event('error'))).toBe(true);
@@ -80,6 +135,46 @@ describe('GraphQL Soup websocket retry policy', () => {
false
);
});
+
+ it('caps the wait between attempts', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(1);
+ const resolved = vi.fn();
+ void waitToRetryGraphqlSoupWebSocket(30).then(resolved);
+
+ await vi.advanceTimersByTimeAsync(62_999);
+ expect(resolved).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(resolved).toHaveBeenCalledOnce();
+ vi.mocked(Math.random).mockRestore();
+ });
+
+ it.each([
+ ['the app returns to the foreground', () => setVisibility('visible')],
+ ['the browser comes online', () => dispatchEvent(new Event('online'))],
+ ['the native network path returns', () => setNativeStatus('online')],
+ ])('stops waiting when %s', async (_name, opportunity) => {
+ vi.useFakeTimers();
+ setVisibility('hidden');
+ setNativeStatus('offline');
+ const resolved = vi.fn();
+ void waitToRetryGraphqlSoupWebSocket(10).then(resolved);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(resolved).not.toHaveBeenCalled();
+
+ opportunity();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(resolved).toHaveBeenCalledOnce();
+ expect(nativeStatus.listeners.size).toBe(0);
+ });
+
+ it('does not treat the current native status as a reconnect opportunity', async () => {
+ vi.useFakeTimers();
+ const resolved = vi.fn();
+ void waitToRetryGraphqlSoupWebSocket(10).then(resolved);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(resolved).not.toHaveBeenCalled();
+ });
});
describe('GraphQL Soup subscription lifecycle', () => {
@@ -215,4 +310,76 @@ describe('GraphQL Soup subscription lifecycle', () => {
});
lifecycle.dispose();
});
+
+ it('reattaches an ended subscription set on the next foreground or online signal', () => {
+ toastFailure.mockClear();
+ const receive: Array<
+ (result: { error?: unknown; hasNext?: boolean }) => void
+ > = [];
+ const unsubscribes: Array<ReturnType<typeof vi.fn>> = [];
+ const client = {
+ subscription: vi.fn(() => ({
+ subscribe: vi.fn((next) => {
+ receive.push(next);
+ const unsubscribe = vi.fn();
+ unsubscribes.push(unsubscribe);
+ return { unsubscribe };
+ }),
+ })),
+ };
+ const lifecycle = createGraphqlSoupSubscriptionsLifecycle();
+ lifecycle.replace(client as never);
+ expect(client.subscription).toHaveBeenCalledTimes(2);
+
+ // Results that keep the stream open never reattach it.
+ receive[0]?.({ hasNext: true });
+ setVisibility('visible');
+ expect(client.subscription).toHaveBeenCalledTimes(2);
+
+ // A terminal result waits for an opportunity rather than a timer.
+ const failed = receive[0];
+ failed?.({ error: new Error('session rejected'), hasNext: false });
+ receive[1]?.({ error: new Error('session rejected'), hasNext: false });
+ expect(client.subscription).toHaveBeenCalledTimes(2);
+
+ setVisibility('visible');
+ expect(client.subscription).toHaveBeenCalledTimes(4);
+ for (const unsubscribe of unsubscribes.slice(0, 2))
+ expect(unsubscribe).toHaveBeenCalledOnce();
+
+ // Late results from the replaced set and repeated signals do not
+ // duplicate the healthy replacement.
+ failed?.({ error: new Error('stale'), hasNext: false });
+ setVisibility('visible');
+ dispatchEvent(new Event('online'));
+ expect(client.subscription).toHaveBeenCalledTimes(4);
+ expect(toastFailure).toHaveBeenCalledOnce();
+
+ receive[2]?.({ error: new Error('again'), hasNext: false });
+ lifecycle.dispose();
+ dispatchEvent(new Event('online'));
+ expect(client.subscription).toHaveBeenCalledTimes(4);
+ });
+
+ it('signals a new outage after a successful reconnection', () => {
+ toastFailure.mockClear();
+ const receive: Array<(result: { error?: unknown }) => void> = [];
+ const client = {
+ subscription: vi.fn(() => ({
+ subscribe: vi.fn((next) => {
+ receive.push(next);
+ return { unsubscribe: vi.fn() };
+ }),
+ })),
+ };
+ const lifecycle = createGraphqlSoupSubscriptionsLifecycle();
+ lifecycle.replace(client as never);
+
+ receive[0]?.({ error: new Error('first outage') });
+ lifecycle.connected();
+ receive[0]?.({ error: new Error('second outage') });
+
+ expect(toastFailure).toHaveBeenCalledTimes(2);
+ lifecycle.dispose();
+ });
});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts
index 3e140c14e9..71c9a787dd 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts
@@ -1,7 +1,9 @@
import { toast } from '@core/component/Toast/Toast';
+import { subscribeNativeNetworkStatus } from '@core/mobile/native-network-status';
import { normalizedCacheResultMetadata } from '@graphql-cache/exchange/normalized-cache-exchange';
import type { CacheHost } from '@graphql-cache/host/types';
import type { Client, OperationResult } from '@urql/core';
+import type { Result } from 'neverthrow';
import {
channelNotificationRefresh,
disposeChannelNotificationRefresh,
@@ -18,8 +20,22 @@ import { createChannelListUpdatesHandler } from './graphql-channel-list-updates'
const SOUP_GRAPHQL_WEBSOCKET_PATH = '/items/soup/graphql/ws';
-/** Maximum reconnect attempts for the Soup updates websocket. */
-export const SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS = 5;
+/**
+ * Transient failures retry without limit. graphql-ws never resets its retry
+ * count after giving up, so an exhausted client would wait `2^retries` seconds
+ * before every later attempt; the wait is capped instead (see
+ * `waitToRetryGraphqlSoupWebSocket`).
+ */
+export const SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS = Number.POSITIVE_INFINITY;
+
+const MAX_RETRY_DELAY_MS = 60_000;
+
+/** The cookie refresh failed for a transient reason, such as an outage. */
+export class GraphqlSoupWebSocketAuthUnavailableError extends Error {
+ constructor() {
+ super('Unable to refresh GraphQL websocket cookie');
+ }
+}
const RETRYABLE_WEBSOCKET_CLOSE_CODES = new Set([
1001, // endpoint is temporarily going away
@@ -41,11 +57,59 @@ export function shouldRetryGraphqlSoupWebSocket(error: unknown): boolean {
);
}
- // Browser websocket network failures arrive as Events. Errors thrown while
- // resolving auth or processing the protocol are not retryable.
+ if (error instanceof GraphqlSoupWebSocketAuthUnavailableError) return true;
+
+ // Browser websocket network failures arrive as Events. Other errors thrown
+ // while resolving auth or processing the protocol are not retryable.
return typeof Event !== 'undefined' && error instanceof Event;
}
+/**
+ * Calls `listener` when the app returns to the foreground or regains
+ * connectivity, when a waiting reconnect should stop waiting.
+ */
+function onReconnectOpportunity(listener: () => void): () => void {
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') listener();
+ };
+ let subscribed = false;
+ const unsubscribeNative = subscribeNativeNetworkStatus((status) => {
+ // The first call reports the current status, not a change.
+ if (subscribed && status === 'online') listener();
+ });
+ subscribed = true;
+ document.addEventListener('visibilitychange', onVisible);
+ addEventListener('online', listener);
+ return () => {
+ unsubscribeNative();
+ document.removeEventListener('visibilitychange', onVisible);
+ removeEventListener('online', listener);
+ };
+}
+
+/**
+ * Waits before reconnect attempt `retries`: graphql-ws's randomized
+ * exponential backoff, capped at a minute, and cut short when the app returns
+ * to the foreground or regains connectivity.
+ */
+export function waitToRetryGraphqlSoupWebSocket(
+ retries: number
+): Promise<void> {
+ const delay =
+ Math.min(1000 * 2 ** retries, MAX_RETRY_DELAY_MS) +
+ 300 +
+ Math.random() * 2_700;
+ return new Promise((resolve) => {
+ const finish = () => {
+ clearTimeout(timer);
+ stopListening();
+ resolve();
+ };
+ const timer = setTimeout(finish, delay);
+ const stopListening = onReconnectOpportunity(finish);
+ });
+}
+
/** Converts a DSS HTTP origin into its Soup GraphQL websocket endpoint. */
export function buildGraphqlSoupWebSocketUrl(
dssHost: string,
@@ -67,7 +131,7 @@ type GraphqlSoupWebSocketAuth = {
dssHost: string;
bearerTokenAuth: boolean;
getApiToken: () => Promise<string>;
- refreshCookieAuth: () => Promise<void>;
+ refreshCookieAuth: () => Promise<Result<void, { code: string }[]>>;
};
/** Creates the reconnect-safe URL resolver used by graphql-ws. */
@@ -84,8 +148,15 @@ export function createGraphqlSoupWebSocketUrlResolver({
return buildGraphqlSoupWebSocketUrl(dssHost, apiToken);
}
- // Browsers authenticate the websocket upgrade with the refreshed cookie.
- await refreshCookieAuth();
+ // The websocket upgrade authenticates with the refreshed cookie. Only a
+ // rejected session is final; a refresh lost to an outage retries.
+ const refreshed = await refreshCookieAuth();
+ if (refreshed.isErr()) {
+ if (refreshed.error.some((error) => error.code === 'UNAUTHORIZED')) {
+ throw new Error('GraphQL websocket session was rejected');
+ }
+ throw new GraphqlSoupWebSocketAuthUnavailableError();
+ }
return buildGraphqlSoupWebSocketUrl(dssHost);
};
}
@@ -144,8 +215,23 @@ export function createGraphqlSoupSubscriptionsLifecycle(
let unsubscribes: Array<() => void> = [];
let activity: ReturnType<typeof createActivityUpdatesHandler> | undefined;
let channels: ReturnType<typeof createChannelListUpdatesHandler> | undefined;
+ let generation = 0;
+ let signaledFailure = false;
+ let stopWatchingForReattach: (() => void) | undefined;
+
+ // graphql-ws retries transient failures itself and gives up only on ones a
+ // timer cannot fix (a rejected session, a protocol error). Reattach the set
+ // when the app returns to the foreground or regains connectivity instead.
+ const reattachOnNextOpportunity = () => {
+ stopWatchingForReattach ??= onReconnectOpportunity(() =>
+ lifecycle.replace(currentClient, currentHost)
+ );
+ };
const unsubscribeAll = () => {
+ generation += 1;
+ stopWatchingForReattach?.();
+ stopWatchingForReattach = undefined;
for (const unsubscribe of unsubscribes) unsubscribe();
unsubscribes = [];
activity?.dispose();
@@ -191,7 +277,7 @@ export function createGraphqlSoupSubscriptionsLifecycle(
: LIVE_UPDATE_SUBSCRIPTIONS.filter(
({ document }) => document !== SoupUpdatesDocument
);
- let signaledFailure = false;
+ const setGeneration = generation;
unsubscribes = subscriptions.map(({ document, errorMessage }) => {
const subscription = client
.subscription(document, {})
@@ -224,11 +310,16 @@ export function createGraphqlSoupSubscriptionsLifecycle(
});
}
}
+ // urql ends a subscription with a final `hasNext: false` result.
+ if (result.hasNext === false && setGeneration === generation) {
+ reattachOnNextOpportunity();
+ }
});
return () => subscription.unsubscribe();
});
},
connected: () => {
+ signaledFailure = false;
activity?.reconnect();
channels?.reconnect();
},
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index b819081f52..c6b7450d2c 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -324,6 +324,7 @@ vi.mock('./graphql/generated/graphql', () => ({
vi.mock('./graphql-soup-websocket', () => ({
SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS: 0,
shouldRetryGraphqlSoupWebSocket: () => false,
+ waitToRetryGraphqlSoupWebSocket: vi.fn(),
createGraphqlSoupWebSocketUrlResolver: () => () => 'ws://dss.test',
createGraphqlSoupSubscriptionsLifecycle: () => ({
replace: mocks.replaceSubscriptions,
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index 8c0b993df4..0fe910484f 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -31,6 +31,7 @@ import {
} from '@graphql-cache/protocol';
import { getBrowserTursoCacheRolloutDecision } from '@graphql-cache/rollout';
import { getOrCreateCacheScope } from '@graphql-cache/scope';
+import { TauriWebSocketWrapper } from '@macro-inc/collaboration/websocket/platform/tauri-websocket';
import { Telemetry } from '@macro-inc/observability';
import { notificationStateFromGraphql } from '@notifications/notification-state';
import { localDraftQueueLifecycle } from '@queries/email/local-drafts';
@@ -97,6 +98,7 @@ import {
createGraphqlSoupWebSocketUrlResolver,
SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
shouldRetryGraphqlSoupWebSocket,
+ waitToRetryGraphqlSoupWebSocket,
} from './graphql-soup-websocket';
const dssHost = SERVER_HOSTS['document-storage-service'];
@@ -370,16 +372,18 @@ function createGraphqlSoupWebSocketClient(
dssHost,
bearerTokenAuth: ENABLE_BEARER_TOKEN_AUTH,
getApiToken: getMacroApiToken,
- refreshCookieAuth: async () => {
- const result = await fetchToken();
- if (result.isErr()) {
- throw new Error('Unable to refresh GraphQL websocket cookie');
- }
- },
+ refreshCookieAuth: fetchToken,
});
return createGraphqlWsClient({
url: resolveWebSocketUrl,
+ // Session cookies live in the native HTTP client's jar, which the WebView's
+ // own WebSocket cannot send; the native socket forwards them.
+ webSocketImpl:
+ isTauri() && !ENABLE_BEARER_TOKEN_AUTH
+ ? TauriWebSocketWrapper
+ : undefined,
retryAttempts: SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
+ retryWait: waitToRetryGraphqlSoupWebSocket,
on: {
connected: () => {
onConnected();
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-ws-recovery.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-ws-recovery.test.ts
new file mode 100644
index 0000000000..3452fba927
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-ws-recovery.test.ts
@@ -0,0 +1,158 @@
+import { createClient } from 'graphql-ws';
+import { err, ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+type ReplayEnvelope = { seq: number; message: { type: string; data: unknown } };
+type ConnectArgs = {
+ url: string;
+ onMessage: { onmessage?: (envelope: ReplayEnvelope) => void };
+ config?: { headers: [string, string][] };
+};
+
+// A native websocket plugin that speaks graphql-transport-ws as the server.
+const plugin = vi.hoisted(() => ({
+ connects: [] as ConnectArgs[],
+ received: [] as Array<{ id: number; type: string; payload: unknown }>,
+}));
+
+vi.mock('@tauri-apps/api/core', () => ({
+ Channel: class {
+ onmessage?: (envelope: ReplayEnvelope) => void;
+ },
+ invoke: vi.fn(async (command: string, args: Record<string, unknown>) => {
+ if (command === 'plugin:websocket|connect') {
+ plugin.connects.push(args as ConnectArgs);
+ return plugin.connects.length;
+ }
+ if (command !== 'plugin:websocket|send') return;
+ const id = args.id as number;
+ const message = args.message as { type: string; data: unknown };
+ if (message.type !== 'Text') {
+ plugin.received.push({ id, type: message.type, payload: message.data });
+ return;
+ }
+ const frame = JSON.parse(message.data as string);
+ plugin.received.push({ id, type: frame.type, payload: frame.payload });
+ const channel = plugin.connects[id - 1]?.onMessage;
+ let seq = plugin.received.length;
+ const reply = (value: object) =>
+ queueMicrotask(() =>
+ channel?.onmessage?.({
+ seq: ++seq,
+ message: { type: 'Text', data: JSON.stringify(value) },
+ })
+ );
+ if (frame.type === 'connection_init') reply({ type: 'connection_ack' });
+ if (frame.type === 'subscribe') {
+ reply({ id: frame.id, type: 'next', payload: { data: { ping: id } } });
+ reply({ id: frame.id, type: 'complete' });
+ }
+ }),
+}));
+
+import { TauriWebSocketWrapper } from '@macro-inc/collaboration/websocket/platform/tauri-websocket';
+import {
+ createGraphqlSoupWebSocketUrlResolver,
+ SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
+ shouldRetryGraphqlSoupWebSocket,
+} from './graphql-soup-websocket';
+
+function subscribeOnce(client: ReturnType<typeof createClient>) {
+ return new Promise<unknown[]>((resolve, reject) => {
+ const values: unknown[] = [];
+ client.subscribe(
+ { query: 'subscription { ping }' },
+ {
+ next: (value) => values.push(value),
+ error: reject,
+ complete: () => resolve(values),
+ }
+ );
+ // An unhandled url rejection used to leave the subscription pending.
+ setTimeout(() => reject(new Error('subscription stayed pending')), 1_000);
+ });
+}
+
+function cookieClient(refreshCookieAuth: () => Promise<unknown>) {
+ return createClient({
+ url: createGraphqlSoupWebSocketUrlResolver({
+ dssHost: 'https://dss.test',
+ bearerTokenAuth: false,
+ getApiToken: vi.fn(),
+ refreshCookieAuth: refreshCookieAuth as never,
+ }),
+ webSocketImpl: TauriWebSocketWrapper,
+ retryAttempts: SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
+ retryWait: async () => {},
+ shouldRetry: shouldRetryGraphqlSoupWebSocket,
+ });
+}
+
+beforeEach(() => {
+ plugin.connects.length = 0;
+ plugin.received.length = 0;
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+
+describe('GraphQL websocket auth recovery', () => {
+ it('retries a cookie refresh that failed during an outage', async () => {
+ const refresh = vi
+ .fn()
+ .mockResolvedValueOnce(err([{ code: 'NETWORK_ERROR' }]))
+ .mockResolvedValue(ok(undefined));
+ const client = cookieClient(refresh);
+
+ await expect(subscribeOnce(client)).resolves.toEqual([
+ { data: { ping: 1 } },
+ ]);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ await client.dispose();
+ });
+
+ it('ends subscriptions when the session is rejected', async () => {
+ const client = cookieClient(
+ vi.fn().mockResolvedValue(err([{ code: 'UNAUTHORIZED' }]))
+ );
+
+ await expect(subscribeOnce(client)).rejects.toThrow(
+ 'GraphQL websocket session was rejected'
+ );
+ expect(plugin.connects).toHaveLength(0);
+ await client.dispose();
+ });
+});
+
+describe('GraphQL websocket over the native transport', () => {
+ it('negotiates graphql-transport-ws and runs a subscription', async () => {
+ const client = cookieClient(vi.fn().mockResolvedValue(ok(undefined)));
+
+ await expect(subscribeOnce(client)).resolves.toEqual([
+ { data: { ping: 1 } },
+ ]);
+ expect(plugin.connects[0]?.url).toBe(
+ 'wss://dss.test/items/soup/graphql/ws'
+ );
+ expect(plugin.connects[0]?.config).toEqual({
+ headers: [['Sec-WebSocket-Protocol', 'graphql-transport-ws']],
+ });
+ expect(plugin.received.map(({ type }) => type)).toEqual([
+ 'connection_init',
+ 'subscribe',
+ 'Close',
+ ]);
+ await client.dispose();
+ });
+
+ it('reconnects after the idle socket closes', async () => {
+ const client = cookieClient(vi.fn().mockResolvedValue(ok(undefined)));
+
+ await subscribeOnce(client);
+ // The lazy client closed its idle socket; the next subscription must
+ // open a new one rather than reuse the closed socket.
+ await expect(subscribeOnce(client)).resolves.toEqual([
+ { data: { ping: 2 } },
+ ]);
+ expect(plugin.connects).toHaveLength(2);
+ await client.dispose();
+ });
+});
diff --git a/bun.lock b/bun.lock
index 5861f97107..0c510b297c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -540,6 +540,7 @@
"[email protected]": "apps/web/patches/[email protected]",
"@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
+ "[email protected]": "apps/web/patches/[email protected]",
"@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index 6a1f660a01..31e5d42914 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
- "aarch64-darwin": "sha256-OD86QcxVQTz0qj222kCOqPnrtVQ5HQEO0KgaTlwuMv8=",
- "x86_64-linux": "sha256-k2OoP7TgU5bi3P09+F1BAaN+wiKpNkp+HR6gWibOZr8="
+ "aarch64-darwin": "sha256-XljXiI5DuwI7JGc5FhAq//qjhq1WCIu6VVD3uisQqCI=",
+ "x86_64-linux": "sha256-2Z6ketjBQxNrYVlCMyntHpQWaDiEV97RjLWPJeoF6yA="
}
}
diff --git a/package.json b/package.json
index 86f6f9fe6d..fe12efcc60 100644
--- a/package.json
+++ b/package.json
@@ -44,7 +44,8 @@
"[email protected]": "apps/web/patches/[email protected]",
"@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"@tauri-apps/[email protected]": "apps/web/patches/@tauri-apps%[email protected]",
- "@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]"
+ "@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]",
+ "[email protected]": "apps/web/patches/[email protected]"
},
"private": true,
"scripts": {
diff --git a/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts b/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
new file mode 100644
index 0000000000..de87fa4ba9
--- /dev/null
+++ b/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+type ReplayEnvelope = { seq: number; message: unknown };
+type ConnectArgs = {
+ url: string;
+ onMessage: { onmessage?: (envelope: ReplayEnvelope) => void };
+ config?: { headers: [string, string][] };
+};
+
+const plugin = vi.hoisted(() => ({
+ connects: [] as Array<{
+ args: ConnectArgs;
+ resolve: (id: number) => void;
+ reject: (error: unknown) => void;
+ }>,
+ sent: [] as Array<{ id: number; message: unknown }>,
+}));
+
+vi.mock('@tauri-apps/api/core', () => ({
+ Channel: class {
+ onmessage?: (envelope: ReplayEnvelope) => void;
+ },
+ invoke: vi.fn((command: string, args: unknown) => {
+ if (command === 'plugin:websocket|connect') {
+ return new Promise((resolve, reject) =>
+ plugin.connects.push({ args: args as ConnectArgs, resolve, reject })
+ );
+ }
+ if (command === 'plugin:websocket|send') {
+ plugin.sent.push(args as { id: number; message: unknown });
+ }
+ return Promise.resolve();
+ }),
+}));
+
+import { TauriWebSocketWrapper } from './tauri-websocket';
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+function track(socket: TauriWebSocketWrapper) {
+ const events: string[] = [];
+ socket.onopen = () => events.push('open');
+ socket.onerror = () => events.push('error');
+ socket.onclose = (event) => events.push(`close:${event.code}`);
+ return events;
+}
+
+beforeEach(() => {
+ plugin.connects.length = 0;
+ plugin.sent.length = 0;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('TauriWebSocketWrapper', () => {
+ it('can stand in for the WebSocket constructor', () => {
+ expect(TauriWebSocketWrapper.CONNECTING).toBe(0);
+ expect(TauriWebSocketWrapper.OPEN).toBe(1);
+ expect(TauriWebSocketWrapper.CLOSING).toBe(2);
+ expect(TauriWebSocketWrapper.CLOSED).toBe(3);
+ });
+
+ it('negotiates a single subprotocol through the handshake headers', async () => {
+ const socket = new TauriWebSocketWrapper(
+ 'wss://dss.test/ws',
+ 'graphql-transport-ws'
+ );
+ const events = track(socket);
+ expect(plugin.connects[0]?.args.config).toEqual({
+ headers: [['Sec-WebSocket-Protocol', 'graphql-transport-ws']],
+ });
+ expect(socket.protocol).toBe('');
+
+ plugin.connects[0]?.resolve(7);
+ await settle();
+
+ expect(events).toEqual(['open']);
+ expect(socket.protocol).toBe('graphql-transport-ws');
+ });
+
+ it('sends no handshake config without a subprotocol', () => {
+ new TauriWebSocketWrapper('wss://dss.test/ws');
+ expect(plugin.connects[0]?.args).not.toHaveProperty('config');
+ });
+
+ it('rejects several subprotocols it cannot tell apart', () => {
+ expect(
+ () => new TauriWebSocketWrapper('wss://dss.test/ws', ['one', 'two'])
+ ).toThrow(SyntaxError);
+ expect(plugin.connects).toHaveLength(0);
+ });
+
+ it('drops a connection that completes after close()', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+
+ socket.close();
+ expect(socket.readyState).toBe(socket.CLOSING);
+ await settle();
+ expect(events).toEqual(['close:1006']);
+ expect(socket.readyState).toBe(socket.CLOSED);
+
+ plugin.connects[0]?.resolve(7);
+ await settle();
+
+ expect(events).toEqual(['close:1006']);
+ expect(socket.readyState).toBe(socket.CLOSED);
+ expect(plugin.sent).toEqual([
+ {
+ id: 7,
+ message: {
+ type: 'Close',
+ data: { code: 1000, reason: 'Disconnected by client' },
+ },
+ },
+ ]);
+ });
+
+ it('reports one closure when a connect fails after close()', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+
+ socket.close();
+ plugin.connects[0]?.reject(new Error('unreachable'));
+ await settle();
+
+ expect(events).toEqual(['close:1006']);
+ });
+
+ it('closes with the requested code and reports it exactly once', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ plugin.connects[0]?.resolve(7);
+ await settle();
+
+ socket.close(4499, 'Terminated');
+ expect(socket.readyState).toBe(socket.CLOSING);
+ await settle();
+
+ expect(plugin.sent).toEqual([
+ {
+ id: 7,
+ message: { type: 'Close', data: { code: 4499, reason: 'Terminated' } },
+ },
+ ]);
+ expect(events).toEqual(['open', 'close:4499']);
+ expect(socket.readyState).toBe(socket.CLOSED);
+ });
+
+ it('does not report the echo of a local close a second time', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ plugin.connects[0]?.resolve(7);
+ await settle();
+
+ socket.close(1000, 'Normal Closure');
+ const echo = {
+ type: 'Close',
+ data: { code: 1000, reason: 'Normal Closure' },
+ };
+ plugin.connects[0]?.args.onMessage.onmessage?.({ seq: 1, message: echo });
+ await settle();
+ plugin.connects[0]?.args.onMessage.onmessage?.({ seq: 2, message: echo });
+
+ expect(events).toEqual(['open', 'close:1000']);
+ });
+
+ it('reports a server-initiated closure once', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ plugin.connects[0]?.resolve(7);
+ await settle();
+
+ const onMessage = plugin.connects[0]?.args.onMessage;
+ onMessage?.onmessage?.({
+ seq: 1,
+ message: { type: 'Close', data: { code: 1012, reason: 'restart' } },
+ });
+ socket.close();
+ await settle();
+
+ expect(events).toEqual(['open', 'close:1012']);
+ expect(plugin.sent).toEqual([]);
+ });
+});
diff --git a/packages/collaboration/src/websocket/platform/tauri-websocket.ts b/packages/collaboration/src/websocket/platform/tauri-websocket.ts
index e977cdfcad..123c930c3b 100644
--- a/packages/collaboration/src/websocket/platform/tauri-websocket.ts
+++ b/packages/collaboration/src/websocket/platform/tauri-websocket.ts
@@ -51,9 +51,16 @@ interface RecoverResponse {
}
/**
- * Tauri WebSocket wrapper that implements MinimalWebSocket interface
+ * Tauri WebSocket wrapper that implements MinimalWebSocket interface.
+ * The static state constants let it stand in for the `WebSocket` constructor
+ * (e.g. graphql-ws's `webSocketImpl`).
*/
-class TauriWebSocketWrapper implements MinimalWebSocket {
+export class TauriWebSocketWrapper implements MinimalWebSocket {
+ static readonly CONNECTING = 0;
+ static readonly OPEN = 1;
+ static readonly CLOSING = 2;
+ static readonly CLOSED = 3;
+
private socketId: number | null = null; // plugin connection id
private _readyState: number = 0; // CONNECTING
private _url: string;
@@ -61,6 +68,7 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
private _extensions: string = '';
private _binaryType: BinaryType = 'blob';
private _bufferedAmount: number = 0;
+ private closeReported = false;
// Event handlers
onclose: ((this: WebSocket, ev: CloseEvent) => any) | null = null;
@@ -85,20 +93,18 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
readonly CLOSED: 3 = 3;
constructor(url: string, protocols?: string | string[]) {
+ // The plugin does not report which of several offered subprotocols the
+ // server selected, so only a single one can be negotiated safely.
+ const offered = protocols === undefined ? [] : [protocols].flat();
+ if (offered.length > 1) {
+ throw new SyntaxError('Tauri WebSocket supports at most one subprotocol');
+ }
this._url = url;
- this.initializeWebSocket(url, protocols);
+ this.initializeWebSocket(url, offered[0]);
}
- private async initializeWebSocket(
- url: string,
- protocols?: string | string[]
- ) {
+ private async initializeWebSocket(url: string, protocol?: string) {
try {
- // The Tauri websocket plugin does not support subprotocol negotiation, so
- // we keep the shared factory signature for compatibility but do not
- // forward `protocols` to the plugin connect call.
- void protocols;
-
// We call invoke() directly and pre-register our handler BEFORE the
// connection is made, so messages sent by the server immediately after
// the handshake cannot be dropped (see module comment above).
@@ -118,7 +124,6 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
this.handleMessage(messageData);
})
.with({ type: 'Close' }, ({ data }) => {
- this._readyState = this.CLOSED;
const closeEvent = new CloseEvent('close', {
code: data?.code || 1000,
reason: data?.reason || '',
@@ -138,6 +143,9 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
// Register BEFORE invoke so any message that arrives during the handshake
// is dispatched to our handler rather than dropped into an empty Set.
listeners.add(handleMessage);
+ this.removeListener = () => {
+ listeners.delete(handleMessage);
+ };
// Unwrap the { seq, message } replay envelope, deduplicating messages
// that are delivered both live and via recover().
@@ -173,13 +181,22 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
const id = await invoke<number>('plugin:websocket|connect', {
url,
onMessage,
+ // The plugin's handshake fails unless the server selects this
+ // protocol, so a completed connect has negotiated it.
+ ...(protocol && {
+ config: { headers: [['Sec-WebSocket-Protocol', protocol]] },
+ }),
});
this.socketId = id;
- this.removeListener = () => {
- listeners.delete(handleMessage);
- };
+ if (this._readyState !== this.CONNECTING) {
+ // Closed while connecting: that closure is already reported, so drop
+ // the late connection instead of opening it.
+ this.disconnectSocket().catch(() => {});
+ return;
+ }
+ this._protocol = protocol ?? '';
this._readyState = this.OPEN;
// Recover messages received by the Rust side while the webview was
@@ -196,6 +213,8 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
const openEvent = new Event('open');
this.handleOpen(openEvent);
} catch (error) {
+ // A close() during the failed connect has already reported the closure.
+ if (this._readyState !== this.CONNECTING) return;
console.error(`Failed to initialize Tauri WebSocket to ${url}:`, error);
this._readyState = this.CLOSED;
const errorEvent = new Event('error');
@@ -227,6 +246,12 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
}
private handleClose(event: CloseEvent) {
+ // One closure can be observed more than once (a local close and the
+ // server's echoed close frame); report it once.
+ if (this.closeReported) return;
+ this.closeReported = true;
+ this._readyState = this.CLOSED;
+ this.removeListener?.();
this.teardownVisibilityListener();
if (this.onclose) {
this.onclose.call(this as any, event);
@@ -389,33 +414,37 @@ class TauriWebSocketWrapper implements MinimalWebSocket {
});
}
- /** Closes the plugin connection with a normal-closure frame. */
- private async disconnectSocket(): Promise<void> {
- await this.sendMessage({
- type: 'Close',
- data: {
- code: 1000,
- reason: 'Disconnected by client',
- },
- });
+ /** Closes the plugin connection with a close frame. */
+ private async disconnectSocket(
+ code = 1000,
+ reason = 'Disconnected by client'
+ ): Promise<void> {
+ await this.sendMessage({ type: 'Close', data: { code, reason } });
}
- close(_code?: number, _reason?: string): void {
- if (this.socketId !== null && this._readyState === this.OPEN) {
+ close(code = 1000, reason = ''): void {
+ if (this._readyState === this.CONNECTING) {
+ // Like a browser socket, abandoning the handshake reports an abnormal
+ // closure; the pending connect drops its connection if it completes.
this._readyState = this.CLOSING;
-
- // Tauri WebSocket disconnect doesn't take parameters, so we just disconnect
- this.disconnectSocket()
- .catch((error: any) => {
- console.error('Error closing Tauri WebSocket:', error);
- })
- .finally(() => {
- this._readyState = this.CLOSED;
- if (this.removeListener) {
- this.removeListener();
- }
- });
+ queueMicrotask(() =>
+ this.handleClose(
+ new CloseEvent('close', { code: 1006, reason, wasClean: false })
+ )
+ );
+ return;
}
+ if (this.socketId === null || this._readyState !== this.OPEN) return;
+ this._readyState = this.CLOSING;
+ this.disconnectSocket(code, reason)
+ .catch((error: any) => {
+ console.error('Error closing Tauri WebSocket:', error);
+ })
+ .finally(() => {
+ this.handleClose(
+ new CloseEvent('close', { code, reason, wasClean: true })
+ );
+ });
}
private handleSendRejection(error: unknown) {