forked from jupyterlab/jupyterlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.ts
1527 lines (1418 loc) · 44.6 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, uuid
} from '@jupyterlab/coreutils';
import {
ArrayExt, each, find, toArray
} from '@phosphor/algorithm';
import {
JSONExt, JSONObject, PromiseDelegate
} from '@phosphor/coreutils';
import {
DisposableDelegate, IDisposable
} from '@phosphor/disposable';
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
*/
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();
this._username = options.username || '';
this._futures = new Map<string, KernelFutureHandler>();
this._commPromises = new Map<string, Promise<Kernel.IComm>>();
this._comms = new Map<string, Kernel.IComm>();
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.
*/
get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {
return this._iopubMessage;
}
/**
* A signal emitted for unhandled kernel message.
*/
get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {
return this._unhandledMessage;
}
/**
* 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._connectionPromise.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(void 0);
this._status = 'dead';
this._clearSocket();
this._futures.forEach((future, key) => {
future.dispose();
});
this._comms.forEach((comm, key) => {
comm.dispose();
});
this._displayIdToParentIds.clear();
this._msgIdToDisplayIds.clear();
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(msg: KernelMessage.IShellMessage, expectReply=false, disposeOnDone=true): Kernel.IFuture {
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));
}
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.
*/
handleRestart(): void {
this._clearState();
this._updateStatus('restarting');
this._clearSocket();
}
/**
* 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._connectionPromise.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.
*
* The promise will be rejected if the kernel status is `Dead` or if the
* request fails or the response is invalid.
*/
shutdown(): Promise<void> {
if (this.status === 'dead') {
return Promise.reject(new Error('Kernel is dead'));
}
return Private.shutdownKernel(this.id, this.serverSettings).then(() => {
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.
*/
requestKernelInfo(): Promise<KernelMessage.IInfoReplyMsg> {
let options: KernelMessage.IOptions = {
msgType: 'kernel_info_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createShellMessage(options);
return Private.handleShellMessage(this, msg).then(reply => {
this._info = (reply as KernelMessage.IInfoReplyMsg).content;
return reply as KernelMessage.IInfoReplyMsg;
});
}
/**
* 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.ICompleteRequest): Promise<KernelMessage.ICompleteReplyMsg> {
let options: KernelMessage.IOptions = {
msgType: 'complete_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createShellMessage(options, 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.IInspectRequest): Promise<KernelMessage.IInspectReplyMsg> {
let options: KernelMessage.IOptions = {
msgType: 'inspect_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createShellMessage(options, 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.IHistoryRequest): Promise<KernelMessage.IHistoryReplyMsg> {
let options: KernelMessage.IOptions = {
msgType: 'history_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createShellMessage(options, 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.IExecuteRequest, disposeOnDone: boolean = true): Kernel.IFuture {
let options: KernelMessage.IOptions = {
msgType: 'execute_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let defaults: JSONObject = {
silent : false,
store_history : true,
user_expressions : {},
allow_stdin : true,
stop_on_error : false
};
content = { ...defaults, ...content };
let msg = KernelMessage.createShellMessage(options, content);
return this.sendShellMessage(msg, true, disposeOnDone);
}
/**
* 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.IIsCompleteRequest): Promise<KernelMessage.IIsCompleteReplyMsg> {
let options: KernelMessage.IOptions = {
msgType: 'is_complete_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createShellMessage(options, 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.ICommInfoRequest): Promise<KernelMessage.ICommInfoReplyMsg> {
let options: KernelMessage.IOptions = {
msgType: 'comm_info_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createShellMessage(options, 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.IInputReply): void {
if (this.status === 'dead') {
throw new Error('Kernel is dead');
}
let options: KernelMessage.IOptions = {
msgType: 'input_reply',
channel: 'stdin',
username: this._username,
session: this._clientId
};
let msg = KernelMessage.createMessage(options, content);
if (!this._isReady || !this._ws) {
this._pendingMessages.push(msg);
} else {
this._ws.send(serialize.serialize(msg));
}
}
/**
* 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.
*
* @returns A disposable used to unregister the message hook.
*
* #### Notes
* The IOPub hook system allows you to preempt the handlers for IOPub messages with a
* given parent_header message id. The most recently registered hook is run first.
* If the hook returns false, any later hooks and the future's onIOPub handler will not run.
* 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 won't run until the next message.
* If a hook is disposed during the hook processing, it will be deactivated immediately.
*
* See also [[IFuture.registerMessageHook]].
*/
registerMessageHook(msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean): IDisposable {
let future = this._futures && this._futures.get(msgId);
if (future) {
future.registerMessageHook(hook);
}
return new DisposableDelegate(() => {
future = this._futures && this._futures.get(msgId);
if (future) {
future.removeMessageHook(hook);
}
});
}
/**
* 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 at a time, an existing
* callback will be overidden. A registered comm target handler will take
* precedence over a comm which specifies a `target_module`.
*/
registerCommTarget(targetName: string, callback: (comm: Kernel.IComm, msg: KernelMessage.ICommOpenMsg) => void): IDisposable {
this._targetRegistry[targetName] = callback;
return new DisposableDelegate(() => {
if (!this.isDisposed) {
delete this._targetRegistry[targetName];
}
});
}
/**
* Connect to a comm, or create a new one.
*
* #### Notes
* If a client-side comm already exists, it is returned.
*/
connectToComm(targetName: string, commId?: string): Kernel.IComm {
let id = commId || uuid();
let comm = this._comms.get(id) || new CommHandler(
targetName,
id,
this,
() => { this._unregisterComm(id); }
);
this._comms.set(id, comm);
return comm;
}
/**
* Handle a message with a display id.
*
* @returns Whether the message was handled.
*/
private _handleDisplayId(displayId: string, msg: KernelMessage.IMessage): 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 KernelMessage.IHeader,
parent_header: JSONExt.deepCopy(msg.parent_header) as KernelMessage.IHeader,
metadata: JSONExt.deepCopy(msg.metadata),
content: JSONExt.deepCopy(msg.content),
channel: msg.channel,
buffers: msg.buffers ? msg.buffers.slice() : []
};
(updateMsg.header as any).msg_type = 'update_display_data';
parentIds.map((parentId) => {
let future = this._futures && this._futures.get(parentId);
if (future) {
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 it propagate to the intended recipient.
return false;
}
/**
* Clear the socket state.
*/
private _clearSocket(): void {
this._wsStopped = true;
this._isReady = false;
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 'starting':
case 'idle':
case 'busy':
case 'connected':
this._isReady = true;
break;
case 'restarting':
case 'reconnecting':
case 'dead':
this._isReady = false;
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();
}
}
if (this._isReady) {
this._sendPending();
}
}
/**
* 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 _clearState(): void {
this._isReady = false;
this._pendingMessages = [];
this._futures.forEach((future, key) => {
future.dispose();
});
this._comms.forEach((comm, key) => {
comm.dispose();
});
this._futures = new Map<string, KernelFutureHandler>();
this._commPromises = new Map<string, Promise<Kernel.IComm>>();
this._comms = new Map<string, Kernel.IComm>();
this._displayIdToParentIds.clear();
this._msgIdToDisplayIds.clear();
}
/**
* Handle a `comm_open` kernel message.
*/
private _handleCommOpen(msg: KernelMessage.ICommOpenMsg): void {
let content = msg.content;
if (this.isDisposed) {
return;
}
let promise = Private.loadObject(content.target_name, content.target_module,
this._targetRegistry).then(target => {
let comm = new CommHandler(
content.target_name,
content.comm_id,
this,
() => { this._unregisterComm(content.comm_id); }
);
let response : any;
try {
response = target(comm, msg);
} catch (e) {
comm.close();
console.error('Exception opening new comm');
throw(e);
}
return Promise.resolve(response).then(() => {
if (this.isDisposed) {
return;
}
this._commPromises.delete(comm.commId);
this._comms.set(comm.commId, comm);
return comm;
});
});
this._commPromises.set(content.comm_id, promise);
}
/**
* Handle 'comm_close' kernel message.
*/
private _handleCommClose(msg: KernelMessage.ICommCloseMsg): void {
let content = msg.content;
let promise = this._commPromises.get(content.comm_id);
if (!promise) {
let comm = this._comms.get(content.comm_id);
if (!comm) {
console.error('Comm not found for comm id ' + content.comm_id);
return;
}
promise = Promise.resolve(comm);
}
promise.then((comm) => {
if (!comm) {
return;
}
this._unregisterComm(comm.commId);
try {
let onClose = comm.onClose;
if (onClose) {
onClose(msg);
}
(comm as CommHandler).dispose();
} catch (e) {
console.error('Exception closing comm: ', e, e.stack, msg);
}
});
}
/**
* Handle a 'comm_msg' kernel message.
*/
private _handleCommMsg(msg: KernelMessage.ICommMsgMsg): void {
let content = msg.content;
let promise = this._commPromises.get(content.comm_id);
if (!promise) {
let comm = this._comms.get(content.comm_id);
if (!comm) {
// We do have a registered comm for this comm id, ignore.
return;
} else {
let onMsg = comm.onMsg;
if (onMsg) {
onMsg(msg);
}
}
} else {
promise.then((comm) => {
if (!comm) {
return;
}
try {
let onMsg = comm.onMsg;
if (onMsg) {
onMsg(msg);
}
} catch (e) {
console.error('Exception handling comm msg: ', e, e.stack, msg);
}
});
}
}
/**
* Unregister a comm instance.
*/
private _unregisterComm(commId: string) {
this._comms.delete(commId);
this._commPromises.delete(commId);
}
/**
* Create the kernel websocket connection and add socket status handlers.
*/
private _createSocket = () => {
let settings = this.serverSettings;
let partialUrl = URLExt.join(settings.wsUrl, KERNEL_SERVICE_URL,
encodeURIComponent(this._id));
// Strip any authentication from the display string.
let display = partialUrl.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/, '$1');
console.log('Starting WebSocket:', display);
let url = URLExt.join(
partialUrl,
'channels?session_id=' + encodeURIComponent(this._clientId)
);
// If token authentication is in use.
let token = settings.token;
if (token !== '') {
url = url + `&token=${encodeURIComponent(token)}`;
}
this._connectionPromise = new PromiseDelegate<void>();
this._wsStopped = false;
this._ws = new settings.WebSocket(url);
// Ensure incoming binary messages are not Blobs
this._ws.binaryType = 'arraybuffer';
this._ws.onmessage = this._onWSMessage;
this._ws.onopen = this._onWSOpen;
this._ws.onclose = this._onWSClose;
this._ws.onerror = this._onWSClose;
}
/**
* Handle a websocket open event.
*/
private _onWSOpen = (evt: Event) => {
this._reconnectAttempt = 0;
// Allow the message to get through.
this._isReady = true;
// Update our status to connected.
this._updateStatus('connected');
// Get the kernel info, signaling that the kernel is ready.
this.requestKernelInfo().then(() => {
this._connectionPromise.resolve(void 0);
}).catch(err => {
this._connectionPromise.reject(err);
});
this._isReady = false;
}
/**
* Handle a websocket message, validating and routing appropriately.
*/
private _onWSMessage = (evt: MessageEvent) => {
if (this._wsStopped) {
// If the socket is being closed, ignore any messages
return;
}
let msg = serialize.deserialize(evt.data);
try {
validate.validateMessage(msg);
} catch (error) {
console.error(`Invalid message: ${error.message}`);
return;
}
let handled = false;
if (msg.parent_header && msg.channel === 'iopub') {
switch (msg.header.msg_type) {
case 'display_data':
case 'update_display_data':
case 'execute_result':
// display_data messages may re-route based on their display_id.
let transient = (msg.content.transient || {}) as JSONObject;
let displayId = transient['display_id'] as string;
if (displayId) {
handled = this._handleDisplayId(displayId, msg);
}
break;
default:
break;
}
}
if (!handled && msg.parent_header) {
let parentHeader = msg.parent_header as KernelMessage.IHeader;
let future = this._futures && this._futures.get(parentHeader.msg_id);
if (future) {
future.handleMsg(msg);
} else {
// If the message was sent by us and was not iopub, it is orphaned.
let owned = parentHeader.session === this.clientId;
if (msg.channel !== 'iopub' && owned) {
this._unhandledMessage.emit(msg);
}
}
}
if (msg.channel === 'iopub') {
switch (msg.header.msg_type) {
case 'status':
this._updateStatus((msg as KernelMessage.IStatusMsg).content.execution_state);
break;
case 'comm_open':
this._handleCommOpen(msg as KernelMessage.ICommOpenMsg);
break;
case 'comm_msg':
this._handleCommMsg(msg as KernelMessage.ICommMsgMsg);
break;
case 'comm_close':
this._handleCommClose(msg as KernelMessage.ICommCloseMsg);
break;
default:
break;
}
this._iopubMessage.emit(msg as KernelMessage.IIOPubMessage);
}
}
/**