forked from jupyterlab/jupyterlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.ts
1754 lines (1632 loc) · 50.7 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 } from '@phosphor/coreutils';
import { ArrayExt, each, find } from '@phosphor/algorithm';
import { JSONExt, JSONObject, PromiseDelegate } from '@phosphor/coreutils';
import { ISignal, Signal } from '@phosphor/signaling';
import { ServerConnection } from '..';
import { CommHandler } from './comm';
import { Kernel } from './kernel';
import { KernelMessage } from './messages';
import { KernelFutureHandler } from './future';
import * as serialize from './serialize';
import * as validate from './validate';
/**
* The url for the kernel service.
*/
const KERNEL_SERVICE_URL = 'api/kernels';
/**
* The url for the kernelspec service.
*/
const KERNELSPEC_SERVICE_URL = 'api/kernelspecs';
// 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 DefaultKernel implements Kernel.IKernel {
/**
* Construct a kernel object.
*/
constructor(options: Kernel.IOptions, id: string) {
this._name = options.name;
this._id = id;
this.serverSettings =
options.serverSettings || ServerConnection.makeSettings();
this._clientId = options.clientId || UUID.uuid4();
this._username = options.username || '';
void this._readyPromise.promise.then(() => {
this._sendPending();
});
this._createSocket();
Private.runningKernels.push(this);
}
/**
* A signal emitted when the kernel is shut down.
*/
get terminated(): ISignal<this, void> {
return this._terminated;
}
/**
* The server settings for the kernel.
*/
readonly serverSettings: ServerConnection.ISettings;
/**
* A signal emitted when the kernel status changes.
*/
get statusChanged(): ISignal<this, Kernel.Status> {
return this._statusChanged;
}
/**
* 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;
}
/**
* A signal emitted for any kernel message.
*
* #### Notes
* This signal is emitted when a message is received, before it is handled
* asynchronously.
*
* The behavior is undefined if the message is modified during message
* handling. As such, the message should be treated as read-only.
*/
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;
}
/**
* Get the model associated with the kernel.
*/
get model(): Kernel.IModel {
return { name: this.name, id: this.id };
}
/**
* 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(): Kernel.Status {
return this._status;
}
/**
* Test whether the kernel has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* The cached kernel info.
*
* #### Notes
* This value will be null until the kernel is ready.
*/
get info(): KernelMessage.IInfoReply | null {
return this._info;
}
/**
* Test whether the kernel is ready.
*/
get isReady(): boolean {
return this._isReady;
}
/**
* A promise that is fulfilled when the kernel is ready.
*/
get ready(): Promise<void> {
return this._readyPromise.promise;
}
/**
* Get the kernel spec.
*
* @returns A promise that resolves with the kernel spec.
*/
getSpec(): Promise<Kernel.ISpecModel> {
if (this._specPromise) {
return this._specPromise;
}
this._specPromise = Private.findSpecs(this.serverSettings).then(specs => {
return specs.kernelspecs[this._name];
});
return this._specPromise;
}
/**
* Clone the current kernel with a new clientId.
*/
clone(): Kernel.IKernel {
return new DefaultKernel(
{
name: this._name,
username: this._username,
serverSettings: this.serverSettings
},
this._id
);
}
/**
* Dispose of the resources held by the kernel.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
this._terminated.emit();
this._status = 'dead';
// Trigger the async _clearState, but do not wait for it.
void this._clearState();
this._clearSocket();
this._kernelSession = '';
this._msgChain = null;
ArrayExt.removeFirstOf(Private.runningKernels, this);
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.IFuture<KernelMessage.IShellMessage<T>> {
if (this.status === 'dead') {
throw new Error('Kernel is dead');
}
if (!this._isReady || !this._ws) {
this._pendingMessages.push(msg);
} else {
this._ws.send(serialize.serialize(msg));
}
this._anyMessage.emit({ msg, direction: 'send' });
let future = new KernelFutureHandler(
() => {
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;
}
/**
* 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.
*/
interrupt(): Promise<void> {
return Private.interruptKernel(this, this.serverSettings);
}
/**
* Restart 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) and validates the response model.
*
* Any existing Future or Comm objects are cleared.
*
* 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 request fails or the response is
* invalid.
*/
restart(): Promise<void> {
return Private.restartKernel(this, this.serverSettings);
}
/**
* Handle a restart on the kernel. This is not part of the `IKernel`
* interface.
*/
async handleRestart(): Promise<void> {
await this._clearState();
this._updateStatus('restarting');
}
/**
* Reconnect to a disconnected kernel.
*
* #### Notes
* Used when the websocket connection to the kernel is lost.
*/
reconnect(): Promise<void> {
this._clearSocket();
this._updateStatus('reconnecting');
this._createSocket();
return this._readyPromise.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, closes the websocket and disposes of the kernel
* object, and fulfills the promise.
*
* If the kernel is already `dead`, it closes the websocket and returns
* without a server request.
*/
async shutdown(): Promise<void> {
if (this.status === 'dead') {
this._clearSocket();
await this._clearState();
return;
}
await Private.shutdownKernel(this.id, this.serverSettings);
await this._clearState();
this._clearSocket();
}
/**
* 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> {
let msg = KernelMessage.createMessage({
msgType: 'kernel_info_request',
channel: 'shell',
username: this._username,
session: this._clientId,
content: {}
});
let reply = (await Private.handleShellMessage(
this,
msg
)) as KernelMessage.IInfoReplyMsg;
if (this.isDisposed) {
throw new Error('Disposed kernel');
}
if (reply.content.status !== 'ok') {
throw new Error('Kernel info reply errored');
}
this._info = 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.IFuture<
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 }
});
return this.sendShellMessage(msg, true, disposeOnDone) as Kernel.IFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
>;
}
/**
* 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 {
if (this.status === 'dead') {
throw new Error('Kernel is dead');
}
let msg = KernelMessage.createMessage({
msgType: 'input_reply',
channel: 'stdin',
username: this._username,
session: this._clientId,
content
});
if (!this._isReady || !this._ws) {
this._pendingMessages.push(msg);
} else {
this._ws.send(serialize.serialize(msg));
}
this._anyMessage.emit({ msg, direction: 'send' });
}
/**
* Connect to a comm, or create a new one.
*
* #### Notes
* If a client-side comm already exists with the given commId, it is returned.
*/
connectToComm(
targetName: string,
commId: string = UUID.uuid4()
): Kernel.IComm {
if (this._comms.has(commId)) {
return this._comms.get(commId);
}
let comm = new CommHandler(targetName, commId, this, () => {
this._unregisterComm(commId);
});
this._comms.set(commId, comm);
return comm;
}
/**
* 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 {
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 the callback argument matches.
*/
removeCommTarget(
targetName: string,
callback: (
comm: Kernel.IComm,
msg: KernelMessage.ICommOpenMsg
) => void | PromiseLike<void>
): void {
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 && 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 && 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;
}
/**
* Clear the socket state.
*
* #### Notes
* When calling this, you should also set the status to something like
* 'reconnecting' to reset the kernel ready state.
*/
private _clearSocket(): void {
this._wsStopped = true;
if (this._ws !== null) {
// Clear the websocket event handlers and the socket itself.
this._ws.onopen = this._noOp;
this._ws.onclose = this._noOp;
this._ws.onerror = this._noOp;
this._ws.onmessage = this._noOp;
this._ws.close();
this._ws = null;
}
}
/**
* Handle status iopub messages from the kernel.
*/
private _updateStatus(status: Kernel.Status): void {
switch (status) {
case 'idle':
case 'busy':
if (!this._isReady && this._initialized) {
this._isReady = true;
this._readyPromise.resolve();
}
break;
case 'restarting':
// Send a kernel_info_request to get to a known kernel state.
void this.requestKernelInfo().catch(this._noOp);
break;
case 'starting':
case 'autorestarting':
// 'starting' can happen at initialization or 'restarting'.
// 'autorestarting' is always preceded by 'restarting'. In either case,
// the 'restarting' handler above is fine, so we do nothing here.
/* no-op */
break;
case 'connected':
// requestKernelInfo is sent by the onWSOpen
break;
case 'reconnecting':
if (this._isReady) {
this._isReady = false;
this._readyPromise = new PromiseDelegate();
void this._readyPromise.promise.then(() => {
// when we are ready again, send any pending messages.
this._sendPending();
});
}
break;
case 'dead':
if (this._isReady) {
this._isReady = false;
this._readyPromise = new PromiseDelegate();
}
void this._readyPromise.promise.catch(this._noOp);
this._readyPromise.reject('Kernel is dead');
break;
default:
console.error('invalid kernel status:', status);
return;
}
if (status !== this._status) {
this._status = status;
Private.logKernelStatus(this);
this._statusChanged.emit(status);
if (status === 'dead') {
this.dispose();
}
}
}
/**
* Send pending messages to the kernel.
*/
private _sendPending(): void {
// We shift the message off the queue
// after the message is sent so that if there is an exception,
// the message is still pending.
while (this._ws && this._pendingMessages.length > 0) {
let msg = serialize.serialize(this._pendingMessages[0]);
this._ws.send(msg);
this._pendingMessages.shift();
}
}
/**
* Clear the internal state.
*/
private async _clearState(): Promise<void> {
this._pendingMessages = [];
const futuresResolved: Promise<void>[] = [];
this._futures.forEach(future => {
futuresResolved.push(future.done.then(this._noOp, this._noOp));
future.dispose();
});
this._comms.forEach(comm => {
comm.dispose();
});
this._msgChain = Promise.resolve();
this._kernelSession = '';
this._futures = new Map<string, KernelFutureHandler>();
this._comms = new Map<string, Kernel.IComm>();
this._displayIdToParentIds.clear();
this._msgIdToDisplayIds.clear();
await Promise.all(futuresResolved);
}
/**
* Check to make sure it is okay to proceed to handle a message.
*
* #### Notes
* Because we handle messages asynchronously, before a message is handled the
* kernel might be disposed or restarted (and have a different session id).
* This function throws an error in each of these cases. This is meant to be
* called at the start of an asynchronous message handler to cancel message
* processing if the message no longer is valid.
*/
private _assertCurrentMessage(msg: KernelMessage.IMessage) {
if (this.isDisposed) {
throw new Error('Kernel object is disposed');
}
if (msg.header.session !== this._kernelSession) {
throw new Error(
`Canceling handling of old message: ${msg.header.msg_type}`
);
}
}
/**
* Handle a `comm_open` kernel message.
*/
private async _handleCommOpen(
msg: KernelMessage.ICommOpenMsg
): Promise<void> {
this._assertCurrentMessage(msg);
let content = msg.content;
let comm = new CommHandler(
content.target_name,
content.comm_id,
this,
() => {
this._unregisterComm(content.comm_id);
}
);
this._comms.set(content.comm_id, comm);
try {
let target = await Private.loadObject(
content.target_name,
content.target_module,
this._targetRegistry
);
await target(comm, msg);
} catch (e) {
// Close the comm asynchronously. We cannot block message processing on
// kernel messages to wait for another kernel message.
comm.close();
console.error('Exception opening new comm');
throw e;
}
}
/**
* Handle 'comm_close' kernel message.
*/
private async _handleCommClose(
msg: KernelMessage.ICommCloseMsg
): Promise<void> {
this._assertCurrentMessage(msg);
let content = msg.content;
let comm = this._comms.get(content.comm_id);
if (!comm) {
console.error('Comm not found for comm id ' + content.comm_id);
return;
}
this._unregisterComm(comm.commId);
let onClose = comm.onClose;
if (onClose) {
// tslint:disable-next-line:await-promise
await onClose(msg);
}
(comm as CommHandler).dispose();
}
/**
* Handle a 'comm_msg' kernel message.
*/
private async _handleCommMsg(msg: KernelMessage.ICommMsgMsg): Promise<void> {
this._assertCurrentMessage(msg);
let content = msg.content;
let comm = this._comms.get(content.comm_id);
if (!comm) {
return;
}
let onMsg = comm.onMsg;
if (onMsg) {
// tslint:disable-next-line:await-promise