forked from deephaven/web-client-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionBootstrap.tsx
More file actions
244 lines (222 loc) · 7.02 KB
/
ConnectionBootstrap.tsx
File metadata and controls
244 lines (222 loc) · 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
BasicModal,
DebouncedModal,
InfoModal,
LoadingOverlay,
LoadingSpinner,
} from '@deephaven/components';
import {
ObjectFetcherContext,
type ObjectFetchManager,
ObjectFetchManagerContext,
sanitizeVariableDescriptor,
type UriVariableDescriptor,
useApi,
useClient,
} from '@deephaven/jsapi-bootstrap';
import type { dh } from '@deephaven/jsapi-types';
import Log from '@deephaven/log';
import { assertNotNull } from '@deephaven/utils';
import { vsDebugDisconnect } from '@deephaven/icons';
import ConnectionContext from './ConnectionContext';
const log = Log.module('@deephaven/app-utils.ConnectionBootstrap');
export type ConnectionBootstrapProps = {
/**
* The children to render wrapped with the ConnectionContext.
* Will not render children until the connection is created.
*/
children: React.ReactNode;
};
/**
* ConnectionBootstrap component. Handles initializing the connection.
*/
export function ConnectionBootstrap({
children,
}: ConnectionBootstrapProps): JSX.Element {
const api = useApi();
const client = useClient();
const [error, setError] = useState<unknown>();
const [connection, setConnection] = useState<dh.IdeConnection>();
const [connectionState, setConnectionState] = useState<
| 'not_connecting'
| 'connecting'
| 'connected'
| 'reconnecting'
| 'failed'
| 'shutdown'
>('connecting');
const isAuthFailed = connectionState === 'failed';
const isShutdown = connectionState === 'shutdown';
const isReconnecting = connectionState === 'reconnecting';
const isNotConnecting = connectionState === 'not_connecting';
useEffect(
function initConnection() {
let isCanceled = false;
async function loadConnection(): Promise<void> {
try {
const newConnection = await client.getAsIdeConnection();
if (isCanceled) {
return;
}
setConnection(newConnection);
setConnectionState('connected');
} catch (e) {
if (isCanceled) {
return;
}
setError(e);
setConnectionState('not_connecting');
}
}
loadConnection();
return () => {
isCanceled = true;
};
},
[api, client]
);
useEffect(
function listenForDisconnect() {
if (connection == null || isShutdown) return;
// handles the disconnect event
function handleDisconnect(event: dh.Event<unknown>): void {
const { detail } = event;
log.info('Disconnect', `${JSON.stringify(detail)}`);
setConnectionState('reconnecting');
}
const removerFn = connection.addEventListener(
api.IdeConnection.EVENT_DISCONNECT,
handleDisconnect
);
return removerFn;
},
[api, connection, isShutdown]
);
useEffect(
function listenForReconnect() {
if (connection == null || isShutdown) return;
// handles the reconnect event
function handleReconnect(event: dh.Event<unknown>): void {
const { detail } = event;
log.info('Reconnect', `${JSON.stringify(detail)}`);
setConnectionState('connected');
}
const removerFn = connection.addEventListener(
api.CoreClient.EVENT_RECONNECT,
handleReconnect
);
return removerFn;
},
[api, connection, isShutdown]
);
useEffect(
function listenForShutdown() {
if (connection == null) return;
// handles the shutdown event
function handleShutdown(event: dh.Event<unknown>): void {
const { detail } = event;
log.info('Shutdown', `${JSON.stringify(detail)}`);
setError(`Server shutdown: ${detail ?? 'Unknown reason'}`);
setConnectionState('shutdown');
}
const removerFn = connection.addEventListener(
api.IdeConnection.EVENT_SHUTDOWN,
handleShutdown
);
return removerFn;
},
[api, connection]
);
useEffect(
function listenForAuthFailed() {
if (connection == null || isShutdown) return;
// handles the auth failed event
function handleAuthFailed(event: dh.Event<unknown>): void {
const { detail } = event;
log.warn(
'Reconnect authentication failed',
`${JSON.stringify(detail)}`
);
setError(
`Reconnect authentication failed: ${detail ?? 'Unknown reason'}`
);
setConnectionState('failed');
}
const removerFn = connection.addEventListener(
api.CoreClient.EVENT_RECONNECT_AUTH_FAILED,
handleAuthFailed
);
return removerFn;
},
[api, connection, isShutdown]
);
const objectFetcher = useCallback(
async (descriptor: dh.ide.VariableDescriptor | UriVariableDescriptor) => {
assertNotNull(connection, 'No connection available to fetch object with');
if (typeof descriptor === 'string') {
throw new Error('No URI resolvers available in Core');
}
return connection.getObject(sanitizeVariableDescriptor(descriptor));
},
[connection]
);
/** We don't really need to do anything fancy in Core to manage an object, just fetch it */
const objectManager: ObjectFetchManager = useMemo(
() => ({
subscribe: (descriptor, onUpdate) => {
// We send an update with the fetch right away
onUpdate({
fetch: () => objectFetcher(descriptor),
status: 'ready',
});
return () => {
// no-op
// For Core, if the server dies then we can't reconnect anyway, so no need to bother listening for subscription or cleaning up
};
},
}),
[objectFetcher]
);
function handleRefresh(): void {
log.info('Refreshing application');
window.location.reload();
}
if (isShutdown || connectionState === 'connecting' || isNotConnecting) {
return (
<LoadingOverlay
data-testid="connection-bootstrap-loading"
isLoading={error == null}
errorMessage={error != null ? `${error}` : undefined}
/>
);
}
return (
<ConnectionContext.Provider value={connection ?? null}>
<ObjectFetcherContext.Provider value={objectFetcher}>
<ObjectFetchManagerContext.Provider value={objectManager}>
{children}
<DebouncedModal isOpen={isReconnecting} debounceMs={1000}>
<InfoModal
icon={vsDebugDisconnect}
title={
<>
<LoadingSpinner /> Attempting to reconnect...
</>
}
subtitle="Please check your network connection."
/>
</DebouncedModal>
<BasicModal
confirmButtonText="Refresh"
onConfirm={handleRefresh}
isOpen={isAuthFailed}
headerText="Authentication failed"
bodyText="Credentials are invalid. Please refresh your browser to try and reconnect."
/>
</ObjectFetchManagerContext.Provider>
</ObjectFetcherContext.Provider>
</ConnectionContext.Provider>
);
}
export default ConnectionBootstrap;