forked from jupyterlab/jupyterlab
/
default.ts
1576 lines (1444 loc) · 46 KB
/
default.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { URLExt } from '@jupyterlab/coreutils';
import { UUID, JSONExt, JSONObject, PromiseDelegate } from '@lumino/coreutils';
import { ISignal, Signal } from '@lumino/signaling';
import { ServerConnection } from '..';
import { CommHandler } from './comm';
import * as Kernel from './kernel';
import * as KernelMessage from './messages';
import {
KernelFutureHandler,
KernelShellFutureHandler,
KernelControlFutureHandler
} from './future';
import * as serialize from './serialize';
import * as validate from './validate';
import { KernelSpec, KernelSpecAPI } from '../kernelspec';
import * as restapi from './restapi';
// Stub for requirejs.
declare var requirejs: any;
/**
* Implementation of the Kernel object.
*
* #### Notes
* Messages from the server are handled in the order they were received and
* asynchronously. Any message handler can return a promise, and message
* handling will pause until the promise is fulfilled.
*/
export class KernelConnection implements Kernel.IKernelConnection {
/**
* Construct a kernel object.
*/
constructor(options: Kernel.IKernelConnection.IOptions) {
this._name = options.model.name;
this._id = options.model.id;
this.serverSettings =
options.serverSettings ?? ServerConnection.makeSettings();
this._clientId = options.clientId ?? UUID.uuid4();
this._username = options.username ?? '';
this.handleComms = options.handleComms ?? true;
this._createSocket();
// Immediately queue up a request for initial kernel info.
void this.requestKernelInfo();
}
get disposed(): ISignal<this, void> {
return this._disposed;
}
/**
* The server settings for the kernel.
*/
readonly serverSettings: ServerConnection.ISettings;
/**
* Handle comm messages
*
* #### Notes
* The comm message protocol currently has implicit assumptions that only
* one kernel connection is handling comm messages. This option allows a
* kernel connection to opt out of handling comms.
*
* See https://github.com/jupyter/jupyter_client/issues/263
*/
readonly handleComms: boolean;
/**
* A signal emitted when the kernel status changes.
*/
get statusChanged(): ISignal<this, KernelMessage.Status> {
return this._statusChanged;
}
/**
* A signal emitted when the kernel status changes.
*/
get connectionStatusChanged(): ISignal<this, Kernel.ConnectionStatus> {
return this._connectionStatusChanged;
}
/**
* A signal emitted for iopub kernel messages.
*
* #### Notes
* This signal is emitted after the iopub message is handled asynchronously.
*/
get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {
return this._iopubMessage;
}
/**
* A signal emitted for unhandled kernel message.
*
* #### Notes
* This signal is emitted for a message that was not handled. It is emitted
* during the asynchronous message handling code.
*/
get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {
return this._unhandledMessage;
}
/**
* The kernel model
*/
get model(): Kernel.IModel {
return {
id: this.id,
name: this.name
};
}
/**
* A signal emitted for any kernel message.
*
* #### Notes
* This signal is emitted when a message is received, before it is handled
* asynchronously.
*
* This message is emitted when a message is queued for sending (either in
* the websocket buffer, or our own pending message buffer). The message may
* actually be sent across the wire at a later time.
*
* The message emitted in this signal should not be modified in any way.
*/
get anyMessage(): ISignal<this, Kernel.IAnyMessageArgs> {
return this._anyMessage;
}
/**
* The id of the server-side kernel.
*/
get id(): string {
return this._id;
}
/**
* The name of the server-side kernel.
*/
get name(): string {
return this._name;
}
/**
* The client username.
*/
get username(): string {
return this._username;
}
/**
* The client unique id.
*/
get clientId(): string {
return this._clientId;
}
/**
* The current status of the kernel.
*/
get status(): KernelMessage.Status {
return this._status;
}
/**
* The current connection status of the kernel connection.
*/
get connectionStatus(): Kernel.ConnectionStatus {
return this._connectionStatus;
}
/**
* Test whether the kernel has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* The cached kernel info.
*
* @returns A promise that resolves to the kernel info.
*/
get info(): Promise<KernelMessage.IInfoReply> {
return this._info.promise;
}
/**
* The kernel spec.
*
* @returns A promise that resolves to the kernel spec.
*/
get spec(): Promise<KernelSpec.ISpecModel | undefined> {
if (this._specPromise) {
return this._specPromise;
}
this._specPromise = KernelSpecAPI.getSpecs(this.serverSettings).then(
specs => {
return specs.kernelspecs[this._name];
}
);
return this._specPromise;
}
/**
* Clone the current kernel with a new clientId.
*/
clone(
options: Pick<
Kernel.IKernelConnection.IOptions,
'clientId' | 'username' | 'handleComms'
> = {}
): Kernel.IKernelConnection {
return new KernelConnection({
model: this.model,
username: this.username,
serverSettings: this.serverSettings,
// handleComms defaults to false since that is safer
handleComms: false,
...options
});
}
/**
* Dispose of the resources held by the kernel.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
this._disposed.emit();
this._updateConnectionStatus('disconnected');
this._clearKernelState();
this._clearSocket();
// Clear Lumino signals
Signal.clearData(this);
}
/**
* Send a shell message to the kernel.
*
* #### Notes
* Send a message to the kernel's shell channel, yielding a future object
* for accepting replies.
*
* If `expectReply` is given and `true`, the future is disposed when both a
* shell reply and an idle status message are received. If `expectReply`
* is not given or is `false`, the future is resolved when an idle status
* message is received.
* If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
* If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
*
* All replies are validated as valid kernel messages.
*
* If the kernel status is `dead`, this will throw an error.
*/
sendShellMessage<T extends KernelMessage.ShellMessageType>(
msg: KernelMessage.IShellMessage<T>,
expectReply = false,
disposeOnDone = true
): Kernel.IShellFuture<KernelMessage.IShellMessage<T>> {
return this._sendKernelShellControl(
KernelShellFutureHandler,
msg,
expectReply,
disposeOnDone
) as Kernel.IShellFuture<KernelMessage.IShellMessage<T>>;
}
/**
* Send a control message to the kernel.
*
* #### Notes
* Send a message to the kernel's control channel, yielding a future object
* for accepting replies.
*
* If `expectReply` is given and `true`, the future is disposed when both a
* control reply and an idle status message are received. If `expectReply`
* is not given or is `false`, the future is resolved when an idle status
* message is received.
* If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
* If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
*
* All replies are validated as valid kernel messages.
*
* If the kernel status is `dead`, this will throw an error.
*/
sendControlMessage<T extends KernelMessage.ControlMessageType>(
msg: KernelMessage.IControlMessage<T>,
expectReply = false,
disposeOnDone = true
): Kernel.IControlFuture<KernelMessage.IControlMessage<T>> {
return this._sendKernelShellControl(
KernelControlFutureHandler,
msg,
expectReply,
disposeOnDone
) as Kernel.IControlFuture<KernelMessage.IControlMessage<T>>;
}
private _sendKernelShellControl<
REQUEST extends KernelMessage.IShellControlMessage,
REPLY extends KernelMessage.IShellControlMessage,
KFH extends new (...params: any[]) => KernelFutureHandler<REQUEST, REPLY>,
T extends KernelMessage.IMessage
>(
ctor: KFH,
msg: T,
expectReply = false,
disposeOnDone = true
): Kernel.IFuture<
KernelMessage.IShellControlMessage,
KernelMessage.IShellControlMessage
> {
this._sendMessage(msg);
this._anyMessage.emit({ msg, direction: 'send' });
let future = new ctor(
() => {
let msgId = msg.header.msg_id;
this._futures.delete(msgId);
// Remove stored display id information.
let displayIds = this._msgIdToDisplayIds.get(msgId);
if (!displayIds) {
return;
}
displayIds.forEach(displayId => {
let msgIds = this._displayIdToParentIds.get(displayId);
if (msgIds) {
let idx = msgIds.indexOf(msgId);
if (idx === -1) {
return;
}
if (msgIds.length === 1) {
this._displayIdToParentIds.delete(displayId);
} else {
msgIds.splice(idx, 1);
this._displayIdToParentIds.set(displayId, msgIds);
}
}
});
this._msgIdToDisplayIds.delete(msgId);
},
msg,
expectReply,
disposeOnDone,
this
);
this._futures.set(msg.header.msg_id, future);
return future;
}
/**
* Send a message on the websocket.
*
* If queue is true, queue the message for later sending if we cannot send
* now. Otherwise throw an error.
*/
private _sendMessage(msg: KernelMessage.IMessage, queue = true) {
if (this.status === 'dead') {
throw new Error('Kernel is dead');
}
// Send if the ws allows it, otherwise buffer the message.
if (this.connectionStatus === 'connected') {
this._ws!.send(serialize.serialize(msg));
} else if (queue) {
this._pendingMessages.push(msg);
} else {
throw new Error('Could not send message');
}
}
/**
* Interrupt a kernel.
*
* #### Notes
* Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
*
* The promise is fulfilled on a valid response and rejected otherwise.
*
* It is assumed that the API call does not mutate the kernel id or name.
*
* The promise will be rejected if the kernel status is `Dead` or if the
* request fails or the response is invalid.
*/
async interrupt(): Promise<void> {
if (this.status === 'dead') {
throw new Error('Kernel is dead');
}
return restapi.interruptKernel(this.id, this.serverSettings);
}
/**
* Request a kernel restart.
*
* #### Notes
* Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels)
* and validates the response model.
*
* Any existing Future or Comm objects are cleared once the kernel has
* actually be restarted.
*
* The promise is fulfilled on a valid server response (after the kernel restarts)
* and rejected otherwise.
*
* It is assumed that the API call does not mutate the kernel id or name.
*
* The promise will be rejected if the request fails or the response is
* invalid.
*/
async restart(): Promise<void> {
if (this.status === 'dead') {
throw new Error('Kernel is dead');
}
await restapi.restartKernel(this.id, this.serverSettings);
await this._handleRestart();
}
/**
* Reconnect to a kernel.
*
* #### Notes
* This may try multiple times to reconnect to a kernel, and will sever any
* existing connection.
*/
reconnect(): Promise<void> {
this._errorIfDisposed();
let result = new PromiseDelegate<void>();
// Set up a listener for the connection status changing, which accepts or
// rejects after the retries are done.
let fulfill = (sender: this, status: Kernel.ConnectionStatus) => {
if (status === 'connected') {
result.resolve();
this.connectionStatusChanged.disconnect(fulfill, this);
} else if (status === 'disconnected') {
result.reject(new Error('Kernel connection disconnected'));
this.connectionStatusChanged.disconnect(fulfill, this);
}
};
this.connectionStatusChanged.connect(fulfill, this);
// Reset the reconnect limit so we start the connection attempts fresh
this._reconnectAttempt = 0;
// Start the reconnection process, which will also clear any existing
// connection.
this._reconnect();
// Return the promise that should resolve on connection or reject if the
// retries don't work.
return result.promise;
}
/**
* Shutdown a kernel.
*
* #### Notes
* Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
*
* The promise is fulfilled on a valid response and rejected otherwise.
*
* On a valid response, disposes this kernel connection.
*
* If the kernel is already `dead`, disposes this kernel connection without
* a server request.
*/
async shutdown(): Promise<void> {
if (this.status !== 'dead') {
await restapi.shutdownKernel(this.id, this.serverSettings);
}
this.handleShutdown();
}
/**
* Handles a kernel shutdown.
*
* #### Notes
* This method should be called if we know from outside information that a
* kernel is dead (for example, we cannot find the kernel model on the
* server).
*/
handleShutdown(): void {
this._updateStatus('dead');
this.dispose();
}
/**
* Send a `kernel_info_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).
*
* Fulfills with the `kernel_info_response` content when the shell reply is
* received and validated.
*/
async requestKernelInfo(): Promise<KernelMessage.IInfoReplyMsg | undefined> {
let msg = KernelMessage.createMessage({
msgType: 'kernel_info_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content: {}
});
let reply: KernelMessage.IInfoReplyMsg | undefined;
try {
reply = (await Private.handleShellMessage(this, msg)) as
| KernelMessage.IInfoReplyMsg
| undefined;
} catch (e) {
// If we rejected because the future was disposed, ignore and return.
if (this.isDisposed) {
return;
} else {
throw e;
}
}
this._errorIfDisposed();
if (!reply) {
return;
}
// Kernels sometimes do not include a status field on kernel_info_reply
// messages, so set a default for now.
// See https://github.com/jupyterlab/jupyterlab/issues/6760
if (reply.content.status === undefined) {
(reply.content as any).status = 'ok';
}
if (reply.content.status !== 'ok') {
throw new Error('Kernel info reply errored');
}
this._info.resolve(reply.content);
return reply;
}
/**
* Send a `complete_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).
*
* Fulfills with the `complete_reply` content when the shell reply is
* received and validated.
*/
requestComplete(
content: KernelMessage.ICompleteRequestMsg['content']
): Promise<KernelMessage.ICompleteReplyMsg> {
let msg = KernelMessage.createMessage({
msgType: 'complete_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content
});
return Private.handleShellMessage(this, msg) as Promise<
KernelMessage.ICompleteReplyMsg
>;
}
/**
* Send an `inspect_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).
*
* Fulfills with the `inspect_reply` content when the shell reply is
* received and validated.
*/
requestInspect(
content: KernelMessage.IInspectRequestMsg['content']
): Promise<KernelMessage.IInspectReplyMsg> {
let msg = KernelMessage.createMessage({
msgType: 'inspect_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content: content
});
return Private.handleShellMessage(this, msg) as Promise<
KernelMessage.IInspectReplyMsg
>;
}
/**
* Send a `history_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).
*
* Fulfills with the `history_reply` content when the shell reply is
* received and validated.
*/
requestHistory(
content: KernelMessage.IHistoryRequestMsg['content']
): Promise<KernelMessage.IHistoryReplyMsg> {
let msg = KernelMessage.createMessage({
msgType: 'history_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content
});
return Private.handleShellMessage(this, msg) as Promise<
KernelMessage.IHistoryReplyMsg
>;
}
/**
* Send an `execute_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).
*
* Future `onReply` is called with the `execute_reply` content when the
* shell reply is received and validated. The future will resolve when
* this message is received and the `idle` iopub status is received.
* The future will also be disposed at this point unless `disposeOnDone`
* is specified and `false`, in which case it is up to the caller to dispose
* of the future.
*
* **See also:** [[IExecuteReply]]
*/
requestExecute(
content: KernelMessage.IExecuteRequestMsg['content'],
disposeOnDone: boolean = true,
metadata?: JSONObject
): Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
> {
let defaults: JSONObject = {
silent: false,
store_history: true,
user_expressions: {},
allow_stdin: true,
stop_on_error: false
};
let msg = KernelMessage.createMessage({
msgType: 'execute_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content: { ...defaults, ...content },
metadata
});
return this.sendShellMessage(
msg,
true,
disposeOnDone
) as Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
>;
}
/**
* Send an experimental `debug_request` message.
*
* @hidden
*
* #### Notes
* Debug messages are experimental messages that are not in the official
* kernel message specification. As such, this function is *NOT* considered
* part of the public API, and may change without notice.
*/
requestDebug(
content: KernelMessage.IDebugRequestMsg['content'],
disposeOnDone: boolean = true
): Kernel.IControlFuture<
KernelMessage.IDebugRequestMsg,
KernelMessage.IDebugReplyMsg
> {
let msg = KernelMessage.createMessage({
msgType: 'debug_request',
channel: 'control',
username: this._username,
session: this._clientId,
content
});
return this.sendControlMessage(
msg,
true,
disposeOnDone
) as Kernel.IControlFuture<
KernelMessage.IDebugRequestMsg,
KernelMessage.IDebugReplyMsg
>;
}
/**
* Send an `is_complete_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).
*
* Fulfills with the `is_complete_response` content when the shell reply is
* received and validated.
*/
requestIsComplete(
content: KernelMessage.IIsCompleteRequestMsg['content']
): Promise<KernelMessage.IIsCompleteReplyMsg> {
let msg = KernelMessage.createMessage({
msgType: 'is_complete_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content
});
return Private.handleShellMessage(this, msg) as Promise<
KernelMessage.IIsCompleteReplyMsg
>;
}
/**
* Send a `comm_info_request` message.
*
* #### Notes
* Fulfills with the `comm_info_reply` content when the shell reply is
* received and validated.
*/
requestCommInfo(
content: KernelMessage.ICommInfoRequestMsg['content']
): Promise<KernelMessage.ICommInfoReplyMsg> {
let msg = KernelMessage.createMessage({
msgType: 'comm_info_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content
});
return Private.handleShellMessage(this, msg) as Promise<
KernelMessage.ICommInfoReplyMsg
>;
}
/**
* Send an `input_reply` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).
*/
sendInputReply(content: KernelMessage.IInputReplyMsg['content']): void {
let msg = KernelMessage.createMessage({
msgType: 'input_reply',
channel: 'stdin',
username: this._username,
session: this._clientId,
content
});
this._sendMessage(msg);
this._anyMessage.emit({ msg, direction: 'send' });
}
/**
* Create a new comm.
*
* #### Notes
* If a client-side comm already exists with the given commId, an error is thrown.
* If the kernel does not handle comms, an error is thrown.
*/
createComm(targetName: string, commId: string = UUID.uuid4()): Kernel.IComm {
if (!this.handleComms) {
throw new Error('Comms are disabled on this kernel connection');
}
if (this._comms.has(commId)) {
throw new Error('Comm is already created');
}
let comm = new CommHandler(targetName, commId, this, () => {
this._unregisterComm(commId);
});
this._comms.set(commId, comm);
return comm;
}
/**
* Check if a comm exists.
*/
hasComm(commId: string): boolean {
return this._comms.has(commId);
}
/**
* Register a comm target handler.
*
* @param targetName - The name of the comm target.
*
* @param callback - The callback invoked for a comm open message.
*
* @returns A disposable used to unregister the comm target.
*
* #### Notes
* Only one comm target can be registered to a target name at a time, an
* existing callback for the same target name will be overridden. A registered
* comm target handler will take precedence over a comm which specifies a
* `target_module`.
*
* If the callback returns a promise, kernel message processing will pause
* until the returned promise is fulfilled.
*/
registerCommTarget(
targetName: string,
callback: (
comm: Kernel.IComm,
msg: KernelMessage.ICommOpenMsg
) => void | PromiseLike<void>
): void {
if (!this.handleComms) {
return;
}
this._targetRegistry[targetName] = callback;
}
/**
* Remove a comm target handler.
*
* @param targetName - The name of the comm target to remove.
*
* @param callback - The callback to remove.
*
* #### Notes
* The comm target is only removed if the callback argument matches.
*/
removeCommTarget(
targetName: string,
callback: (
comm: Kernel.IComm,
msg: KernelMessage.ICommOpenMsg
) => void | PromiseLike<void>
): void {
if (!this.handleComms) {
return;
}
if (!this.isDisposed && this._targetRegistry[targetName] === callback) {
delete this._targetRegistry[targetName];
}
}
/**
* Register an IOPub message hook.
*
* @param msg_id - The parent_header message id the hook will intercept.
*
* @param hook - The callback invoked for the message.
*
* #### Notes
* The IOPub hook system allows you to preempt the handlers for IOPub
* messages that are responses to a given message id.
*
* The most recently registered hook is run first. A hook can return a
* boolean or a promise to a boolean, in which case all kernel message
* processing pauses until the promise is fulfilled. If a hook return value
* resolves to false, any later hooks will not run and the function will
* return a promise resolving to false. If a hook throws an error, the error
* is logged to the console and the next hook is run. If a hook is
* registered during the hook processing, it will not run until the next
* message. If a hook is removed during the hook processing, it will be
* deactivated immediately.
*
* See also [[IFuture.registerMessageHook]].
*/
registerMessageHook(
msgId: string,
hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>
): void {
let future = this._futures?.get(msgId);
if (future) {
future.registerMessageHook(hook);
}
}
/**
* Remove an IOPub message hook.
*
* @param msg_id - The parent_header message id the hook intercepted.
*
* @param hook - The callback invoked for the message.
*
*/
removeMessageHook(
msgId: string,
hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>
): void {
let future = this._futures?.get(msgId);
if (future) {
future.removeMessageHook(hook);
}
}
/**
* Handle a message with a display id.
*
* @returns Whether the message was handled.
*/
private async _handleDisplayId(
displayId: string,
msg: KernelMessage.IMessage
): Promise<boolean> {
let msgId = (msg.parent_header as KernelMessage.IHeader).msg_id;
let parentIds = this._displayIdToParentIds.get(displayId);
if (parentIds) {
// We've seen it before, update existing outputs with same display_id
// by handling display_data as update_display_data.
let updateMsg: KernelMessage.IMessage = {
header: (JSONExt.deepCopy(
(msg.header as unknown) as JSONObject
) as unknown) as KernelMessage.IHeader,
parent_header: (JSONExt.deepCopy(
(msg.parent_header as unknown) as JSONObject
) as unknown) as KernelMessage.IHeader,
metadata: JSONExt.deepCopy(msg.metadata),
content: JSONExt.deepCopy(msg.content as JSONObject),
channel: msg.channel,
buffers: msg.buffers ? msg.buffers.slice() : []
};
(updateMsg.header as any).msg_type = 'update_display_data';
await Promise.all(
parentIds.map(async parentId => {
let future = this._futures && this._futures.get(parentId);
if (future) {
await future.handleMsg(updateMsg);
}
})
);
}
// We're done here if it's update_display.
if (msg.header.msg_type === 'update_display_data') {
// It's an update, don't proceed to the normal display.
return true;
}
// Regular display_data with id, record it for future updating
// in _displayIdToParentIds for future lookup.
parentIds = this._displayIdToParentIds.get(displayId) ?? [];
if (parentIds.indexOf(msgId) === -1) {
parentIds.push(msgId);
}
this._displayIdToParentIds.set(displayId, parentIds);
// Add to our map of display ids for this message.
let displayIds = this._msgIdToDisplayIds.get(msgId) ?? [];
if (displayIds.indexOf(msgId) === -1) {
displayIds.push(msgId);
}
this._msgIdToDisplayIds.set(msgId, displayIds);
// Let the message propagate to the intended recipient.
return false;
}
/**
* Handle a restart on the kernel. This is not part of the `IKernel`
* interface.
*/
private async _handleRestart(): Promise<void> {
this._clearKernelState();
this._updateStatus('restarting');
// Kick off an async kernel request to eventually reset the kernel status.
// We do this with a setTimeout so that it comes after the microtask
// logic in _handleMessage for restarting/autostarting status updates.
setTimeout(() => {
void this.requestKernelInfo();
}, 0);
}
/**
* Forcefully clear the socket state.
*
* #### Notes
* This will clear all socket state without calling any handlers and will
* not update the connection status. If you call this method, you are
* responsible for updating the connection status as needed and recreating
* the socket if you plan to reconnect.