forked from enisdenjo/graphql-ws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
588 lines (547 loc) · 18.1 KB
/
server.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/**
*
* server
*
*/
import * as http from 'http';
import * as WebSocket from 'ws';
import {
OperationTypeNode,
GraphQLSchema,
ValidationRule,
ExecutionResult,
ExecutionArgs,
parse,
validate,
getOperationAST,
GraphQLError,
SubscriptionArgs,
} from 'graphql';
import { Disposable } from './types';
import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from './protocol';
import {
Message,
MessageType,
parseMessage,
SubscribeMessage,
CompleteMessage,
stringifyMessage,
} from './message';
import {
Optional,
isObject,
isAsyncIterable,
hasOwnObjectProperty,
hasOwnStringProperty,
} from './utils';
import { ID } from './types';
export type ExecutionResultFormatter = (
ctx: Context,
result: ExecutionResult,
) => Promise<ExecutionResult> | ExecutionResult;
export interface ServerOptions {
/**
* The GraphQL schema on which the operations
* will be executed and validated against. If
* the schema is left undefined, one must be
* provided by in the resulting `ExecutionArgs`
* from the `onSubscribe` callback.
*/
schema?: GraphQLSchema;
/**
* A value which is provided to every resolver and holds
* important contextual information like the currently
* logged in user, or access to a database.
* Related operation context value will be injected to the
* `ExecutionArgs` BEFORE the `onSubscribe` callback.
*/
context?: SubscriptionArgs['contextValue'];
/**
* The GraphQL root fields or resolvers to go
* alongside the schema. Learn more about them
* here: https://graphql.org/learn/execution/#root-fields-resolvers.
* Related operation root value will be injected to the
* `ExecutionArgs` BEFORE the `onSubscribe` callback.
*/
roots?: {
[operation in OperationTypeNode]?: Record<
string,
NonNullable<SubscriptionArgs['rootValue']>
>;
};
/**
* Is the `execute` function from GraphQL which is
* used to execute the query/mutation operation.
*/
execute: (
args: ExecutionArgs,
) =>
| Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult>
| AsyncIterableIterator<ExecutionResult>
| ExecutionResult;
/**
* Is the `subscribe` function from GraphQL which is
* used to execute the subscription operation.
*/
subscribe: (
args: ExecutionArgs,
) => Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult>;
/**
* Is the connection callback called when the
* client requests the connection initialisation
* through the message `ConnectionInit`. The message
* payload (`connectionParams` on the client) is
* present in the `Context.connectionParams`.
*
* - Returning `true` from the callback will
* allow the client to connect.
*
* - Returning `false` from the callback will
* terminate the socket by dispatching the
* close event `4403: Forbidden`.
*
* - Throwing an error from the callback will
* terminate the socket by dispatching the
* close event `4400: <error-message>`, where
* the `<error-message>` is the message of the
* thrown `Error`.
*/
onConnect?: (ctx: Context) => Promise<boolean> | boolean;
/**
* @default 3 * 1000 (3 seconds)
*
* The amount of time for which the
* server will wait for `ConnectionInit` message.
*
* Set the value to `Infinity`, '', 0, null or undefined to skip waiting.
*
* If the wait timeout has passed and the client
* has not sent the `ConnectionInit` message,
* the server will terminate the socket by
* dispatching a close event `4408: Connection initialisation timeout`
*/
connectionInitWaitTimeout?: number;
/**
* Custom validation rules overriding all
* validation rules defined by the GraphQL spec.
*/
validationRules?: readonly ValidationRule[];
/**
* Format the operation execution results
* if the implementation requires an adjusted
* result. This formatter is run BEFORE the
* `onConnect` scoped formatter.
*/
formatExecutionResult?: ExecutionResultFormatter;
/**
* The subscribe callback executed before
* the actual operation execution. Useful
* for manipulating the execution arguments
* before the doing the operation. As a second
* item in the array, you can pass in a scoped
* execution result formatter. This formatter
* is run AFTER the root `formatExecutionResult`.
*/
onSubscribe?: (
ctx: Context,
message: SubscribeMessage,
args: Optional<ExecutionArgs, 'schema'>,
) =>
| Promise<[ExecutionArgs, ExecutionResultFormatter?]>
| [ExecutionArgs, ExecutionResultFormatter?];
/**
* The complete callback is executed after the
* operation has completed or the subscription
* has been closed.
*/
onComplete?: (ctx: Context, message: CompleteMessage) => void;
/**
* The timout between dispatched keep-alive messages. Internally the lib
* uses the [WebSocket Ping and Pongs]((https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Pings_and_Pongs_The_Heartbeat_of_WebSockets)) to check that the link between
* the clients and the server is operating and to prevent the link from being broken due to idling.
* Set to nullish value to disable.
*
* @default 12 * 1000 (12 seconds)
*/
keepAlive?: number;
}
export interface Context {
/**
* The actual WebSocket connection between the server and the client.
*/
readonly socket: WebSocket;
/**
* The initial HTTP request before the actual
* socket and connection is established.
*/
readonly request: http.IncomingMessage;
/**
* Indicates that the `ConnectionInit` message
* has been received by the server. If this is
* `true`, the client wont be kicked off after
* the wait timeout has passed.
*/
connectionInitReceived: boolean;
/**
* Indicates that the connection was acknowledged
* by having dispatched the `ConnectionAck` message
* to the related client.
*/
acknowledged: boolean;
/** The parameters passed during the connection initialisation. */
connectionParams?: Readonly<Record<string, unknown>>;
/**
* Holds the active subscriptions for this context.
* Subscriptions are for `subscription` operations **only**,
* other operations (`query`/`mutation`) are resolved immediately.
*/
subscriptions: Record<ID, AsyncIterator<unknown>>;
}
export interface Server extends Disposable {
webSocketServer: WebSocket.Server;
}
// for documentation gen only
type WebSocketServerOptions = WebSocket.ServerOptions;
type WebSocketServer = WebSocket.Server;
/**
* Creates a protocol complient WebSocket GraphQL
* subscription server. Read more about the protocol
* in the PROTOCOL.md documentation file.
*/
export function createServer(
options: ServerOptions,
websocketOptionsOrServer: WebSocketServerOptions | WebSocketServer,
): Server {
const isProd = process.env.NODE_ENV === 'production';
const {
schema,
context,
roots,
execute,
subscribe,
onConnect,
connectionInitWaitTimeout = 3 * 1000, // 3 seconds
validationRules,
formatExecutionResult,
onSubscribe,
onComplete,
keepAlive = 12 * 1000, // 12 seconds
} = options;
const webSocketServer = isWebSocketServer(websocketOptionsOrServer)
? websocketOptionsOrServer
: new WebSocket.Server(websocketOptionsOrServer);
function handleConnection(socket: WebSocket, request: http.IncomingMessage) {
if (
socket.protocol === undefined ||
socket.protocol !== GRAPHQL_TRANSPORT_WS_PROTOCOL ||
(Array.isArray(socket.protocol) &&
socket.protocol.indexOf(GRAPHQL_TRANSPORT_WS_PROTOCOL) === -1)
) {
socket.close(1002, 'Protocol Error');
return;
}
const ctxRef: { current: Context } = {
current: {
socket,
request,
connectionInitReceived: false,
acknowledged: false,
subscriptions: {},
},
};
// kick the client off (close socket) if the connection has
// not been initialised after the specified wait timeout
const connectionInitWait =
connectionInitWaitTimeout && // even 0 disables it
connectionInitWaitTimeout !== Infinity &&
setTimeout(() => {
if (!ctxRef.current.connectionInitReceived) {
ctxRef.current.socket.close(
4408,
'Connection initialisation timeout',
);
}
}, connectionInitWaitTimeout);
// keep alive through ping-pong messages
// read more about the websocket heartbeat here: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Pings_and_Pongs_The_Heartbeat_of_WebSockets
let pongWait: NodeJS.Timeout | null;
const pingInterval =
keepAlive && // even 0 disables it
keepAlive !== Infinity &&
setInterval(() => {
// ping pong on open sockets only
if (socket.readyState === WebSocket.OPEN) {
// terminate the connection after pong wait has passed because the client is idle
pongWait = setTimeout(() => {
socket.terminate();
}, keepAlive);
// listen for client's pong and stop socket termination
socket.once('pong', () => {
if (pongWait) {
clearTimeout(pongWait);
pongWait = null;
}
});
// issue a ping to the client
socket.ping();
}
}, keepAlive);
function errorOrCloseHandler(
errorOrClose: WebSocket.ErrorEvent | WebSocket.CloseEvent,
) {
if (connectionInitWait) {
clearTimeout(connectionInitWait);
}
if (pongWait) {
clearTimeout(pongWait);
}
if (pingInterval) {
clearInterval(pingInterval);
}
if (isErrorEvent(errorOrClose)) {
ctxRef.current.socket.close(
1011,
isProd ? 'Internal Error' : errorOrClose.message,
);
}
Object.entries(ctxRef.current.subscriptions).forEach(
([, subscription]) => {
subscription.return?.();
},
);
}
socket.onerror = errorOrCloseHandler;
socket.onclose = errorOrCloseHandler;
socket.onmessage = makeOnMessage(ctxRef.current);
}
webSocketServer.on('connection', handleConnection);
webSocketServer.on('error', (err) => {
for (const client of webSocketServer.clients) {
// report server errors by erroring out all clients with the same error
client.emit('error', err);
}
});
// Sends through a message only if the socket is open.
function sendMessage<T extends MessageType>(
ctx: Context,
message: Message<T>,
callback?: (err?: Error) => void,
) {
return new Promise((resolve, reject) => {
if (ctx.socket.readyState === WebSocket.OPEN) {
try {
ctx.socket.send(stringifyMessage<T>(message), (err) => {
if (callback) callback(err);
if (err) {
return reject(err);
}
return resolve();
});
} catch (err) {
reject(err);
}
} else {
if (callback) callback();
resolve();
}
});
}
function makeOnMessage(ctx: Context) {
return async function (event: WebSocket.MessageEvent) {
try {
const message = parseMessage(event.data);
switch (message.type) {
case MessageType.ConnectionInit: {
if (ctx.connectionInitReceived) {
return ctx.socket.close(4429, 'Too many initialisation requests');
}
ctx.connectionInitReceived = true;
if (isObject(message.payload)) {
ctx.connectionParams = message.payload;
}
if (onConnect) {
const permitted = await onConnect(ctx);
if (!permitted) {
return ctx.socket.close(4403, 'Forbidden');
}
}
await sendMessage<MessageType.ConnectionAck>(ctx, {
type: MessageType.ConnectionAck,
});
ctx.acknowledged = true;
break;
}
case MessageType.Subscribe: {
if (!ctx.acknowledged) {
return ctx.socket.close(4401, 'Unauthorized');
}
const operation = message.payload;
const document =
typeof operation.query === 'string'
? parse(operation.query)
: operation.query;
const operationAST = getOperationAST(
document,
operation.operationName,
);
if (!operationAST) {
throw new Error('Unable to get operation AST');
}
let execArgsMaybeSchema: Optional<ExecutionArgs, 'schema'> = {
contextValue: context,
schema,
operationName: operation.operationName,
document,
variableValues: operation.variables,
};
// if roots are provided, inject the coresponding operation root
if (roots) {
execArgsMaybeSchema.rootValue = roots[operationAST.operation];
}
let onSubscribeFormatter: ExecutionResultFormatter | undefined;
if (onSubscribe) {
[execArgsMaybeSchema, onSubscribeFormatter] = await onSubscribe(
ctx,
message,
execArgsMaybeSchema,
);
}
if (!execArgsMaybeSchema.schema) {
// not providing a schema is a fatal server error
return webSocketServer.emit(
'error',
new Error('The GraphQL schema is not provided'),
);
}
// the execution arguments should be complete now
const execArgs = execArgsMaybeSchema as ExecutionArgs;
// validate
const validationErrors = validate(
execArgs.schema,
execArgs.document,
validationRules,
);
if (validationErrors.length > 0) {
return await sendMessage<MessageType.Error>(ctx, {
id: message.id,
type: MessageType.Error,
payload: validationErrors,
});
}
// formats the incoming result and emits it to the subscriber
const emitResult = async (result: ExecutionResult) => {
// use the root formater first
if (formatExecutionResult) {
result = await formatExecutionResult(ctx, result);
}
// then use the subscription specific formatter
if (onSubscribeFormatter) {
result = await onSubscribeFormatter(ctx, result);
}
await sendMessage<MessageType.Next>(ctx, {
id: message.id,
type: MessageType.Next,
payload: result,
});
};
// perform
let iterableOrResult;
if (operationAST.operation === 'subscription') {
iterableOrResult = await subscribe(execArgs);
} else {
// operationAST.operation === 'query' || 'mutation'
iterableOrResult = await execute(execArgs);
}
if (isAsyncIterable(iterableOrResult)) {
/** multiple emitted results */
// iterable subscriptions are distinct on ID
if (ctx.subscriptions[message.id]) {
return ctx.socket.close(
4409,
`Subscriber for ${message.id} already exists`,
);
}
ctx.subscriptions[message.id] = iterableOrResult;
try {
for await (const result of iterableOrResult) {
await emitResult(result);
}
// source stream completed
const completeMessage: CompleteMessage = {
id: message.id,
type: MessageType.Complete,
};
await sendMessage<MessageType.Complete>(ctx, completeMessage);
if (onComplete) {
onComplete(ctx, completeMessage);
}
} catch (err) {
await sendMessage<MessageType.Error>(ctx, {
id: message.id,
type: MessageType.Error,
payload: [
new GraphQLError(
err instanceof Error
? err.message
: new Error(err).message,
),
],
});
} finally {
delete ctx.subscriptions[message.id];
}
} else {
/** single emitted result */
await emitResult(iterableOrResult);
// resolved
const completeMessage: CompleteMessage = {
id: message.id,
type: MessageType.Complete,
};
await sendMessage<MessageType.Complete>(ctx, completeMessage);
if (onComplete) {
onComplete(ctx, completeMessage);
}
}
break;
}
case MessageType.Complete: {
if (ctx.subscriptions[message.id]) {
await ctx.subscriptions[message.id].return?.();
}
break;
}
default:
throw new Error(
`Unexpected message of type ${message.type} received`,
);
}
} catch (err) {
ctx.socket.close(4400, err.message);
}
};
}
return {
webSocketServer,
dispose: async () => {
for (const client of webSocketServer.clients) {
client.close(1001, 'Going away');
}
webSocketServer.removeAllListeners();
await new Promise((resolve, reject) =>
webSocketServer.close((err) => (err ? reject(err) : resolve())),
);
},
};
}
function isErrorEvent(obj: unknown): obj is WebSocket.ErrorEvent {
return (
isObject(obj) &&
hasOwnObjectProperty(obj, 'error') &&
hasOwnStringProperty(obj, 'message') &&
hasOwnStringProperty(obj, 'type')
);
}
function isWebSocketServer(obj: unknown): obj is WebSocketServer {
return isObject(obj) && typeof obj.on === 'function';
}