2024-03-07 01:28:18 +08:00
|
|
|
import {
|
2024-04-03 00:31:43 +08:00
|
|
|
ApolloClient, ApolloProvider, InMemoryCache, NormalizedCacheObject, ApolloLink,
|
2024-03-07 01:28:18 +08:00
|
|
|
} from '@apollo/client';
|
2024-05-23 02:51:12 +08:00
|
|
|
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
|
|
|
|
import { createClient } from 'graphql-ws';
|
2024-06-11 04:20:41 +08:00
|
|
|
import { onError } from '@apollo/client/link/error';
|
|
|
|
import React, { useContext, useEffect, useRef } from 'react';
|
2024-03-07 01:28:18 +08:00
|
|
|
import { LoadingContext } from '/imports/ui/components/common/loading-screen/loading-screen-HOC/component';
|
2024-03-22 03:41:32 +08:00
|
|
|
import logger from '/imports/startup/client/logger';
|
2024-04-24 03:51:08 +08:00
|
|
|
import apolloContextHolder from '../../core/graphql/apolloContextHolder/apolloContextHolder';
|
2024-06-11 04:20:41 +08:00
|
|
|
import connectionStatus from '../../core/graphql/singletons/connectionStatus';
|
2024-05-30 04:43:17 +08:00
|
|
|
import deviceInfo from '/imports/utils/deviceInfo';
|
2024-07-19 22:27:48 +08:00
|
|
|
import BBBWeb from '/imports/api/bbb-web-api';
|
2024-09-14 04:14:09 +08:00
|
|
|
import useMeetingSettings from '/imports/ui/core/local-states/useMeetingSettings';
|
2024-03-07 01:28:18 +08:00
|
|
|
|
|
|
|
interface ConnectionManagerProps {
|
|
|
|
children: React.ReactNode;
|
|
|
|
}
|
|
|
|
|
2024-09-24 07:26:49 +08:00
|
|
|
interface WsError {
|
|
|
|
name: string;
|
|
|
|
message: string;
|
|
|
|
reason: string;
|
|
|
|
code: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
const isDetailedErrorObject = (error: unknown): error is WsError => {
|
|
|
|
const requiredKeys = ['name', 'message', 'reason', 'code'];
|
|
|
|
return (
|
|
|
|
error !== null
|
|
|
|
&& typeof error === 'object'
|
|
|
|
&& requiredKeys.every((key) => Object.hasOwn(error, key))
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2024-04-03 00:31:43 +08:00
|
|
|
const DEFAULT_MAX_MUTATION_PAYLOAD_SIZE = 10485760; // 10MB
|
|
|
|
const getMaxMutationPayloadSize = () => window.meetingClientSettings?.public?.app?.maxMutationPayloadSize
|
|
|
|
?? DEFAULT_MAX_MUTATION_PAYLOAD_SIZE;
|
|
|
|
|
|
|
|
const estimatePayloadSize = (variables: Record<string, unknown>) => {
|
|
|
|
const variablesAsString = JSON.stringify(variables);
|
|
|
|
const variablesAsBlob = new Blob([variablesAsString]);
|
|
|
|
return variablesAsBlob.size;
|
|
|
|
};
|
|
|
|
|
|
|
|
const payloadSizeCheckLink = new ApolloLink((operation, forward) => {
|
|
|
|
if (operation.query.definitions.some((def) => 'operation' in def && def.operation === 'mutation')) {
|
|
|
|
const size = estimatePayloadSize(operation.variables);
|
|
|
|
const maxPayloadSize = getMaxMutationPayloadSize();
|
|
|
|
|
|
|
|
if (size > maxPayloadSize) {
|
|
|
|
const errorMsg = `Mutation payload is too large: ${size} bytes. ${maxPayloadSize} maximum allowed.`;
|
|
|
|
logger.warn(errorMsg);
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-20 04:34:43 +08:00
|
|
|
// logger.debug(`Valid ${operation.operationName} payload. Following with the query.`);
|
2024-04-03 00:31:43 +08:00
|
|
|
return forward(operation);
|
|
|
|
});
|
|
|
|
|
2024-05-30 04:43:17 +08:00
|
|
|
const errorLink = onError(({ graphQLErrors, networkError }) => {
|
|
|
|
if (graphQLErrors) {
|
|
|
|
graphQLErrors.forEach(({ message }) => {
|
|
|
|
logger.error(`[GraphQL error]: Message: ${message}`);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (networkError) {
|
|
|
|
logger.error(`[Network error]: ${networkError}`);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-03-07 01:28:18 +08:00
|
|
|
const ConnectionManager: React.FC<ConnectionManagerProps> = ({ children }): React.ReactNode => {
|
|
|
|
const [graphqlUrlApolloClient, setApolloClient] = React.useState<ApolloClient<NormalizedCacheObject> | null>(null);
|
|
|
|
const [graphqlUrl, setGraphqlUrl] = React.useState<string>('');
|
|
|
|
const loadingContextInfo = useContext(LoadingContext);
|
2024-06-11 04:20:41 +08:00
|
|
|
const numberOfAttempts = useRef(20);
|
|
|
|
const [errorCounts, setErrorCounts] = React.useState(0);
|
2024-06-21 01:04:33 +08:00
|
|
|
const activeSocket = useRef<WebSocket>();
|
2024-07-05 04:26:09 +08:00
|
|
|
const tsLastMessageRef = useRef<number>(0);
|
|
|
|
const tsLastPingMessageRef = useRef<number>(0);
|
|
|
|
const boundary = useRef(15_000);
|
2024-06-21 01:04:33 +08:00
|
|
|
const [terminalError, setTerminalError] = React.useState<string>('');
|
2024-09-14 04:14:09 +08:00
|
|
|
const [MeetingSettings] = useMeetingSettings();
|
|
|
|
const enableDevTools = MeetingSettings.public.app.enableApolloDevTools;
|
|
|
|
|
2024-03-07 01:28:18 +08:00
|
|
|
useEffect(() => {
|
2024-07-19 22:27:48 +08:00
|
|
|
BBBWeb.index().then(({ data }) => {
|
|
|
|
setGraphqlUrl(data.graphqlWebsocketUrl);
|
2024-03-07 01:28:18 +08:00
|
|
|
}).catch((error) => {
|
|
|
|
loadingContextInfo.setLoading(false, '');
|
|
|
|
throw new Error('Error fetching GraphQL URL: '.concat(error.message || ''));
|
|
|
|
});
|
2024-03-22 03:41:32 +08:00
|
|
|
logger.info('Fetching GraphQL URL');
|
2024-07-16 21:40:13 +08:00
|
|
|
loadingContextInfo.setLoading(true, '1/2');
|
2024-03-07 01:28:18 +08:00
|
|
|
}, []);
|
|
|
|
|
2024-07-05 04:26:09 +08:00
|
|
|
useEffect(() => {
|
|
|
|
const interval = setInterval(() => {
|
|
|
|
const tsNow = Date.now();
|
|
|
|
|
|
|
|
if (tsLastMessageRef.current !== 0 && tsLastPingMessageRef.current !== 0) {
|
|
|
|
if ((tsNow - tsLastMessageRef.current > boundary.current) && connectionStatus.getServerIsResponding()) {
|
|
|
|
connectionStatus.setServerIsResponding(false);
|
|
|
|
} else if ((tsNow - tsLastPingMessageRef.current > boundary.current) && connectionStatus.getPingIsComing()) {
|
|
|
|
connectionStatus.setPingIsComing(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (tsNow - tsLastMessageRef.current < boundary.current && !connectionStatus.getServerIsResponding()) {
|
|
|
|
connectionStatus.setServerIsResponding(true);
|
|
|
|
} else if (tsNow - tsLastPingMessageRef.current < boundary.current && !connectionStatus.getPingIsComing()) {
|
|
|
|
connectionStatus.setPingIsComing(true);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, 5_000);
|
|
|
|
return () => clearInterval(interval);
|
|
|
|
}, []);
|
|
|
|
|
2024-06-11 04:20:41 +08:00
|
|
|
useEffect(() => {
|
|
|
|
if (errorCounts === numberOfAttempts.current) {
|
|
|
|
throw new Error('Error connecting to server, retrying attempts exceeded');
|
|
|
|
}
|
|
|
|
}, [errorCounts]);
|
|
|
|
|
2024-06-21 01:04:33 +08:00
|
|
|
useEffect(() => {
|
|
|
|
if (terminalError) {
|
|
|
|
throw new Error(terminalError);
|
|
|
|
}
|
|
|
|
}, [terminalError]);
|
|
|
|
|
2024-03-07 01:28:18 +08:00
|
|
|
useEffect(() => {
|
2024-03-22 03:41:32 +08:00
|
|
|
logger.info('Connecting to GraphQL server');
|
2024-07-16 21:40:13 +08:00
|
|
|
loadingContextInfo.setLoading(true, '2/2');
|
2024-03-07 01:28:18 +08:00
|
|
|
if (graphqlUrl) {
|
|
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
|
|
const sessionToken = urlParams.get('sessionToken');
|
|
|
|
if (!sessionToken) {
|
|
|
|
loadingContextInfo.setLoading(false, '');
|
|
|
|
throw new Error('Missing session token');
|
|
|
|
}
|
|
|
|
sessionStorage.setItem('sessionToken', sessionToken);
|
|
|
|
|
2024-05-30 04:43:17 +08:00
|
|
|
const clientSessionUUID = sessionStorage.getItem('clientSessionUUID');
|
|
|
|
const { isMobile } = deviceInfo;
|
|
|
|
|
2024-03-07 01:28:18 +08:00
|
|
|
let wsLink;
|
|
|
|
try {
|
2024-05-23 02:51:12 +08:00
|
|
|
const subscription = createClient({
|
|
|
|
url: graphqlUrl,
|
2024-06-11 04:20:41 +08:00
|
|
|
retryAttempts: numberOfAttempts.current,
|
2024-07-05 04:26:09 +08:00
|
|
|
keepAlive: 99999999999,
|
2024-06-11 04:20:41 +08:00
|
|
|
retryWait: async () => {
|
|
|
|
return new Promise((res) => {
|
|
|
|
setTimeout(() => {
|
|
|
|
res();
|
2024-06-21 01:04:33 +08:00
|
|
|
}, 10_000);
|
2024-06-11 04:20:41 +08:00
|
|
|
});
|
|
|
|
},
|
2024-06-21 01:04:33 +08:00
|
|
|
shouldRetry: (error) => {
|
2024-09-24 07:26:49 +08:00
|
|
|
const isDetailedError = isDetailedErrorObject(error);
|
|
|
|
const terminated = isDetailedError && error.code === 4499;
|
|
|
|
|
|
|
|
if (terminated) {
|
|
|
|
logger.info({
|
|
|
|
logCode: 'connection_terminated',
|
|
|
|
extraInfo: {
|
|
|
|
errorName: error.name,
|
|
|
|
errorMessage: error.message,
|
|
|
|
errorReason: error.reason,
|
|
|
|
},
|
|
|
|
}, 'Connection terminated (4499)');
|
|
|
|
} else if (isDetailedError) {
|
|
|
|
logger.error({
|
|
|
|
logCode: 'connection_error',
|
|
|
|
extraInfo: {
|
|
|
|
errorName: error.name,
|
|
|
|
errorMessage: error.message,
|
|
|
|
errorReason: error.reason,
|
|
|
|
},
|
|
|
|
}, `Connection error (${error.code})`);
|
|
|
|
} else {
|
|
|
|
logger.error({
|
|
|
|
logCode: 'connection_error',
|
|
|
|
extraInfo: {
|
|
|
|
errorName: 'Error',
|
|
|
|
errorMessage: JSON.stringify(error),
|
|
|
|
errorReason: 'Unknown',
|
|
|
|
},
|
|
|
|
}, `Connection error: ${JSON.stringify(error)}`);
|
|
|
|
}
|
|
|
|
|
2024-08-07 02:07:52 +08:00
|
|
|
if (error && typeof error === 'object' && 'code' in error && error.code === 4403) {
|
2024-06-21 01:04:33 +08:00
|
|
|
loadingContextInfo.setLoading(false, '');
|
2024-08-07 02:07:52 +08:00
|
|
|
setTerminalError('Server refused the connection');
|
2024-06-21 01:04:33 +08:00
|
|
|
return false;
|
|
|
|
}
|
2024-06-21 22:11:29 +08:00
|
|
|
|
2024-09-24 07:26:49 +08:00
|
|
|
return apolloContextHolder.getShouldRetry();
|
2024-06-21 01:04:33 +08:00
|
|
|
},
|
2024-03-07 01:28:18 +08:00
|
|
|
connectionParams: {
|
|
|
|
headers: {
|
|
|
|
'X-Session-Token': sessionToken,
|
2024-05-30 04:43:17 +08:00
|
|
|
'X-ClientSessionUUID': clientSessionUUID,
|
|
|
|
'X-ClientType': 'HTML5',
|
|
|
|
'X-ClientIsMobile': isMobile ? 'true' : 'false',
|
2024-03-07 01:28:18 +08:00
|
|
|
},
|
|
|
|
},
|
2024-05-23 02:51:12 +08:00
|
|
|
on: {
|
|
|
|
error: (error) => {
|
2024-08-07 02:07:52 +08:00
|
|
|
logger.error('Error: on subscription to server', error);
|
2024-05-23 02:51:12 +08:00
|
|
|
loadingContextInfo.setLoading(false, '');
|
2024-06-11 04:20:41 +08:00
|
|
|
connectionStatus.setConnectedStatus(false);
|
|
|
|
setErrorCounts((prev: number) => prev + 1);
|
|
|
|
},
|
2024-08-07 02:07:52 +08:00
|
|
|
closed: (e) => {
|
|
|
|
// Check if it's a CloseEvent (which includes HTTP errors during WebSocket handshake)
|
|
|
|
if (e instanceof CloseEvent) {
|
|
|
|
logger.error(`WebSocket closed with code ${e.code}: ${e.reason}`);
|
|
|
|
loadingContextInfo.setLoading(false, '');
|
|
|
|
setTerminalError('Server closed the connection');
|
|
|
|
}
|
2024-06-11 04:20:41 +08:00
|
|
|
connectionStatus.setConnectedStatus(false);
|
|
|
|
},
|
2024-06-21 01:04:33 +08:00
|
|
|
connected: (socket) => {
|
|
|
|
activeSocket.current = socket as WebSocket;
|
2024-06-11 04:20:41 +08:00
|
|
|
connectionStatus.setConnectedStatus(true);
|
|
|
|
},
|
|
|
|
connecting: () => {
|
|
|
|
connectionStatus.setConnectedStatus(false);
|
2024-05-23 02:51:12 +08:00
|
|
|
},
|
2024-07-05 04:26:09 +08:00
|
|
|
message: (message) => {
|
|
|
|
if (message.type === 'ping') {
|
|
|
|
tsLastPingMessageRef.current = Date.now();
|
2024-06-21 01:04:33 +08:00
|
|
|
}
|
2024-07-05 04:26:09 +08:00
|
|
|
tsLastMessageRef.current = Date.now();
|
2024-06-21 01:04:33 +08:00
|
|
|
},
|
2024-07-05 04:26:09 +08:00
|
|
|
|
2024-05-23 02:51:12 +08:00
|
|
|
},
|
2024-03-07 01:28:18 +08:00
|
|
|
});
|
2024-05-23 02:51:12 +08:00
|
|
|
const graphWsLink = new GraphQLWsLink(
|
2024-03-07 01:28:18 +08:00
|
|
|
subscription,
|
|
|
|
);
|
2024-05-30 04:43:17 +08:00
|
|
|
wsLink = ApolloLink.from([payloadSizeCheckLink, errorLink, graphWsLink]);
|
2024-03-07 01:28:18 +08:00
|
|
|
wsLink.setOnError((error) => {
|
|
|
|
loadingContextInfo.setLoading(false, '');
|
|
|
|
throw new Error('Error: on apollo connection'.concat(JSON.stringify(error) || ''));
|
|
|
|
});
|
2024-05-01 23:15:11 +08:00
|
|
|
apolloContextHolder.setLink(subscription);
|
2024-03-07 01:28:18 +08:00
|
|
|
} catch (error) {
|
|
|
|
loadingContextInfo.setLoading(false, '');
|
|
|
|
throw new Error('Error creating WebSocketLink: '.concat(JSON.stringify(error) || ''));
|
|
|
|
}
|
|
|
|
let client;
|
|
|
|
try {
|
|
|
|
client = new ApolloClient({
|
|
|
|
link: wsLink,
|
|
|
|
cache: new InMemoryCache(),
|
2024-09-14 04:14:09 +08:00
|
|
|
connectToDevTools: (process.env.NODE_ENV === 'development') || enableDevTools,
|
2024-03-07 01:28:18 +08:00
|
|
|
});
|
|
|
|
setApolloClient(client);
|
2024-04-24 03:51:08 +08:00
|
|
|
apolloContextHolder.setClient(client);
|
2024-03-07 01:28:18 +08:00
|
|
|
} catch (error) {
|
|
|
|
loadingContextInfo.setLoading(false, '');
|
|
|
|
throw new Error('Error creating Apollo Client: '.concat(JSON.stringify(error) || ''));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
[graphqlUrl]);
|
|
|
|
return (
|
|
|
|
graphqlUrlApolloClient
|
|
|
|
? (
|
|
|
|
<ApolloProvider
|
|
|
|
client={graphqlUrlApolloClient}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</ApolloProvider>
|
|
|
|
) : null
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default ConnectionManager;
|