/
serverconnection.ts
355 lines (322 loc) · 9.77 KB
/
serverconnection.ts
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { PageConfig, URLExt } from '@jupyterlab/coreutils';
import { KernelMessage } from './kernel';
import { deserialize, serialize } from './kernel/serialize';
let WEBSOCKET: typeof WebSocket;
if (typeof window === 'undefined') {
// Mangle the require statements so it does not get picked up in the
// browser assets.
WEBSOCKET = require('ws');
} else {
WEBSOCKET = WebSocket;
}
interface ISerializer {
/**
* Serialize a kernel message for transport.
*/
serialize(
msg: KernelMessage.IMessage,
protocol?: string
): string | ArrayBuffer;
/**
* Deserialize and return the unpacked message.
*/
deserialize(data: ArrayBuffer, protocol?: string): KernelMessage.IMessage;
}
/**
* The namespace for ServerConnection functions.
*
* #### Notes
* This is only intended to manage communication with the Jupyter server.
*
* The default values can be used in a JupyterLab or Jupyter Notebook context.
*
* We use `token` authentication if available, falling back on an XSRF
* cookie if one has been provided on the `document`.
*
* A content type of `'application/json'` is added when using authentication
* and there is no body data to allow the server to prevent malicious forms.
*/
export namespace ServerConnection {
/**
* A Jupyter server settings object.
* Note that all of the settings are optional when passed to
* [[makeSettings]]. The default settings are given in [[defaultSettings]].
*/
export interface ISettings {
/**
* The base url of the server.
*/
readonly baseUrl: string;
/**
* The app url of the JupyterLab application.
*/
readonly appUrl: string;
/**
* The base ws url of the server.
*/
readonly wsUrl: string;
/**
* The default request init options.
*/
readonly init: RequestInit;
/**
* The authentication token for requests. Use an empty string to disable.
*/
readonly token: string;
/**
* Whether to append a token to a Websocket url. The default is `false` in the browser
* and `true` in node or jest.
*/
readonly appendToken: boolean;
/**
* The `fetch` method to use.
*/
readonly fetch: (
input: RequestInfo,
init?: RequestInit
) => Promise<Response>;
/**
* The `Request` object constructor.
*/
readonly Request: typeof Request;
/**
* The `Headers` object constructor.
*/
readonly Headers: typeof Headers;
/**
* The `WebSocket` object constructor.
*/
readonly WebSocket: typeof WebSocket;
/**
* Serializer used to serialize/deserialize kernel messages.
*/
readonly serializer: ISerializer;
}
/**
* Create a settings object given a subset of options.
*
* @param options - An optional partial set of options.
*
* @returns The full settings object.
*/
export function makeSettings(options?: Partial<ISettings>): ISettings {
return Private.makeSettings(options);
}
/**
* Make an request to the notebook server.
*
* @param url - The url for the request.
*
* @param init - The initialization options for the request.
*
* @param settings - The server settings to apply to the request.
*
* @returns a Promise that resolves with the response.
*
* @throws If the url of the request is not a notebook server url.
*
* #### Notes
* The `url` must start with `settings.baseUrl`. The `init` settings are
* merged with `settings.init`, with `init` taking precedence.
* The headers in the two objects are not merged.
* If there is no body data, we set the content type to `application/json`
* because it is required by the Notebook server.
*/
export function makeRequest(
url: string,
init: RequestInit,
settings: ISettings
): Promise<Response> {
return Private.handleRequest(url, init, settings);
}
/**
* A wrapped error for a fetch response.
*/
export class ResponseError extends Error {
/**
* Create a ResponseError from a response, handling the traceback and message
* as appropriate.
*
* @param response The response object.
*
* @returns A promise that resolves with a `ResponseError` object.
*/
static async create(response: Response): Promise<ResponseError> {
try {
const data = await response.json();
const { message, traceback } = data;
if (traceback) {
console.error(traceback);
}
return new ResponseError(
response,
message ?? ResponseError._defaultMessage(response),
traceback ?? ''
);
} catch (e) {
console.debug(e);
return new ResponseError(response);
}
}
/**
* Create a new response error.
*/
constructor(
response: Response,
message = ResponseError._defaultMessage(response),
traceback = ''
) {
super(message);
this.response = response;
this.traceback = traceback;
}
/**
* The response associated with the error.
*/
response: Response;
/**
* The traceback associated with the error.
*/
traceback: string;
private static _defaultMessage(response: Response): string {
return `Invalid response: ${response.status} ${response.statusText}`;
}
}
/**
* A wrapped error for a network error.
*/
export class NetworkError extends TypeError {
/**
* Create a new network error.
*/
constructor(original: TypeError) {
super(original.message);
this.stack = original.stack;
}
}
}
/**
* The namespace for module private data.
*/
namespace Private {
/**
* Handle the server connection settings, returning a new value.
*/
export function makeSettings(
options: Partial<ServerConnection.ISettings> = {}
): ServerConnection.ISettings {
const pageBaseUrl = PageConfig.getBaseUrl();
const pageWsUrl = PageConfig.getWsUrl();
const baseUrl = URLExt.normalize(options.baseUrl) || pageBaseUrl;
let wsUrl = options.wsUrl;
// Prefer the default wsUrl if we are using the default baseUrl.
if (!wsUrl && baseUrl === pageBaseUrl) {
wsUrl = pageWsUrl;
}
// Otherwise convert the baseUrl to a wsUrl if possible.
if (!wsUrl && baseUrl.indexOf('http') === 0) {
wsUrl = 'ws' + baseUrl.slice(4);
}
// Otherwise fall back on the default wsUrl.
wsUrl = wsUrl ?? pageWsUrl;
const appendTokenConfig = PageConfig.getOption('appendToken').toLowerCase();
let appendToken;
if (appendTokenConfig === '') {
appendToken =
typeof window === 'undefined' ||
(typeof process !== 'undefined' &&
process?.env?.JEST_WORKER_ID !== undefined) ||
URLExt.getHostName(pageBaseUrl) !== URLExt.getHostName(wsUrl);
} else {
appendToken = appendTokenConfig === 'true';
}
return {
init: { cache: 'no-store', credentials: 'same-origin' },
fetch,
Headers,
Request,
WebSocket: WEBSOCKET,
token: PageConfig.getToken(),
appUrl: PageConfig.getOption('appUrl'),
appendToken,
serializer: { serialize, deserialize },
...options,
baseUrl,
wsUrl
};
}
/**
* Handle a request.
*
* @param url - The url for the request.
*
* @param init - The overrides for the request init.
*
* @param settings - The settings object for the request.
*
* #### Notes
* The `url` must start with `settings.baseUrl`. The `init` settings
* take precedence over `settings.init`.
*/
export function handleRequest(
url: string,
init: RequestInit,
settings: ServerConnection.ISettings
): Promise<Response> {
// Handle notebook server requests.
if (url.indexOf(settings.baseUrl) !== 0) {
throw new Error('Can only be used for notebook server requests');
}
// Use explicit cache buster when `no-store` is set since
// not all browsers use it properly.
const cache = init.cache ?? settings.init.cache;
if (cache === 'no-store') {
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
}
const request = new settings.Request(url, { ...settings.init, ...init });
// Handle authentication. Authentication can be overdetermined by
// settings token and XSRF token.
let authenticated = false;
if (settings.token) {
authenticated = true;
request.headers.append('Authorization', `token ${settings.token}`);
}
if (typeof document !== 'undefined') {
const xsrfToken = getCookie('_xsrf');
if (xsrfToken !== undefined) {
authenticated = true;
request.headers.append('X-XSRFToken', xsrfToken);
}
}
// Set the content type if there is no given data and we are
// using an authenticated connection.
if (!request.headers.has('Content-Type') && authenticated) {
request.headers.set('Content-Type', 'application/json');
}
// Use `call` to avoid a `TypeError` in the browser.
return settings.fetch.call(null, request).catch((e: TypeError) => {
// Convert the TypeError into a more specific error.
throw new ServerConnection.NetworkError(e);
});
// TODO: *this* is probably where we need a system-wide connectionFailure
// signal we can hook into.
}
/**
* Get a cookie from the document.
*/
function getCookie(name: string): string | undefined {
// From http://www.tornadoweb.org/en/stable/guide/security.html
let cookie = '';
try {
cookie = document.cookie;
} catch (e) {
// e.g. SecurityError in case of CSP Sandbox
return;
}
const matches = cookie.match('\\b' + name + '=([^;]*)\\b');
return matches?.[1];
}
}