-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathsessioncontext.tsx
1932 lines (1746 loc) · 50.7 KB
/
sessioncontext.tsx
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 { IChangedArgs, PathExt } from '@jupyterlab/coreutils';
import {
Kernel,
KernelMessage,
KernelSpec,
ServerConnection,
Session
} from '@jupyterlab/services';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import {
ITranslator,
nullTranslator,
TranslationBundle
} from '@jupyterlab/translation';
import { find } from '@lumino/algorithm';
import { JSONExt, PromiseDelegate, UUID } from '@lumino/coreutils';
import { IDisposable, IObservableDisposable } from '@lumino/disposable';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget } from '@lumino/widgets';
import * as React from 'react';
import { Dialog, showDialog } from './dialog';
/**
* A context object to manage a widget's kernel session connection.
*
* #### Notes
* The current session connection is `.session`, the current session's kernel
* connection is `.session.kernel`. For convenience, we proxy several kernel
* connection and session connection signals up to the session context so
* that you do not have to manage slots as sessions and kernels change. For
* example, to act on whatever the current kernel's iopubMessage signal is
* producing, connect to the session context `.iopubMessage` signal.
*
*/
export interface ISessionContext extends IObservableDisposable {
/**
* The current session connection.
*/
session: Session.ISessionConnection | null;
/**
* Initialize the session context.
*
* @returns A promise that resolves with whether to ask the user to select a kernel.
*
* #### Notes
* This includes starting up an initial kernel if needed.
*/
initialize(): Promise<boolean>;
/**
* Whether the session context is ready.
*/
readonly isReady: boolean;
/**
* Whether the session context is terminating.
*/
readonly isTerminating: boolean;
/**
* Whether the session context is restarting.
*/
readonly isRestarting: boolean;
/**
* A promise that is fulfilled when the session context is ready.
*/
readonly ready: Promise<void>;
/**
* A signal emitted when the session connection changes.
*/
readonly sessionChanged: ISignal<
this,
IChangedArgs<
Session.ISessionConnection | null,
Session.ISessionConnection | null,
'session'
>
>;
// Signals proxied from the session connection for convenience.
/**
* A signal emitted when the kernel changes, proxied from the session connection.
*/
readonly kernelChanged: ISignal<
this,
IChangedArgs<
Kernel.IKernelConnection | null,
Kernel.IKernelConnection | null,
'kernel'
>
>;
/**
* Signal emitted if the kernel preference changes.
*/
readonly kernelPreferenceChanged: ISignal<
this,
IChangedArgs<ISessionContext.IKernelPreference>
>;
/**
* A signal emitted when the kernel status changes, proxied from the session connection.
*/
readonly statusChanged: ISignal<this, Kernel.Status>;
/**
* A signal emitted when the kernel connection status changes, proxied from the session connection.
*/
readonly connectionStatusChanged: ISignal<this, Kernel.ConnectionStatus>;
/**
* A flag indicating if session is has pending input, proxied from the session connection.
*/
readonly pendingInput: boolean;
/**
* A signal emitted for a kernel messages, proxied from the session connection.
*/
readonly iopubMessage: ISignal<this, KernelMessage.IMessage>;
/**
* A signal emitted for an unhandled kernel message, proxied from the session connection.
*/
readonly unhandledMessage: ISignal<this, KernelMessage.IMessage>;
/**
* A signal emitted when a session property changes, proxied from the session connection.
*/
readonly propertyChanged: ISignal<this, 'path' | 'name' | 'type'>;
/**
* The kernel preference for starting new kernels.
*/
kernelPreference: ISessionContext.IKernelPreference;
/**
* Whether the kernel is "No Kernel" or not.
*
* #### Notes
* As the displayed name is translated, this can be used directly.
*/
readonly hasNoKernel: boolean;
/**
* The sensible display name for the kernel, or translated "No Kernel"
*
* #### Notes
* This is at this level since the underlying kernel connection does not
* have access to the kernel spec manager.
*/
readonly kernelDisplayName: string;
/**
* A sensible status to display
*
* #### Notes
* This combines the status and connection status into a single status for the user.
*/
readonly kernelDisplayStatus: ISessionContext.KernelDisplayStatus;
/**
* The session path.
*
* #### Notes
* Typically `.session.path` should be used. This attribute is useful if
* there is no current session.
*/
readonly path: string;
/**
* The session type.
*
* #### Notes
* Typically `.session.type` should be used. This attribute is useful if
* there is no current session.
*/
readonly type: string;
/**
* The session name.
*
* #### Notes
* Typically `.session.name` should be used. This attribute is useful if
* there is no current session.
*/
readonly name: string;
/**
* The previous kernel name.
*/
readonly prevKernelName: string;
/**
* The kernel manager
*
* #### Notes
* In the next major version of this interface, a kernel manager is required.
*/
readonly kernelManager?: Kernel.IManager;
/**
* The session manager used by the session.
*/
readonly sessionManager: Session.IManager;
/**
* The kernel spec manager
*/
readonly specsManager: KernelSpec.IManager;
/**
* Starts new Kernel.
*
* @returns Whether to ask the user to pick a kernel.
*/
startKernel(): Promise<boolean>;
/**
* Restart the current Kernel.
*
* @returns A promise that resolves when the kernel is restarted.
*/
restartKernel(): Promise<void>;
/**
* Kill the kernel and shutdown the session.
*
* @returns A promise that resolves when the session is shut down.
*/
shutdown(): Promise<void>;
/**
* Change the kernel associated with the session.
*
* @param options The optional kernel model parameters to use for the new kernel.
*
* @returns A promise that resolves with the new kernel connection.
*/
changeKernel(
options?: Partial<Kernel.IModel>
): Promise<Kernel.IKernelConnection | null>;
}
/**
* The namespace for session context related interfaces.
*/
export namespace ISessionContext {
/**
* A kernel preference.
*
* #### Notes
* Preferences for a kernel are considered in the order `id`, `name`,
* `language`. If no matching kernels can be found and `autoStartDefault` is
* `true`, then the default kernel for the server is preferred.
*/
export interface IKernelPreference {
/**
* The name of the kernel.
*/
readonly name?: string;
/**
* The preferred kernel language.
*/
readonly language?: string;
/**
* The id of an existing kernel.
*/
readonly id?: string;
/**
* A kernel should be started automatically (default `true`).
*/
readonly shouldStart?: boolean;
/**
* A kernel can be started (default `true`).
*/
readonly canStart?: boolean;
/**
* Shut down the session when session context is disposed (default `false`).
*/
readonly shutdownOnDispose?: boolean;
/**
* Automatically start the default kernel if no other matching kernel is
* found (default `false`).
*/
readonly autoStartDefault?: boolean;
/**
* Skip showing the kernel restart dialog if checked (default `false`).
*/
readonly skipKernelRestartDialog?: boolean;
}
export type KernelDisplayStatus =
| Kernel.Status
| Kernel.ConnectionStatus
| 'initializing'
| '';
/**
* An interface for a session context dialog provider.
*/
export interface IDialogs {
/**
* Select a kernel for the session.
*/
selectKernel(session: ISessionContext): Promise<void>;
/**
* Restart the session context.
*
* @returns A promise that resolves with whether the kernel has restarted.
*
* #### Notes
* If there is a running kernel, present a dialog.
* If there is no kernel, we start a kernel with the last run
* kernel name and resolves with `true`. If no kernel has been started,
* this is a no-op, and resolves with `false`.
*/
restart(session: ISessionContext): Promise<boolean>;
}
/**
* Session context dialog options
*/
export interface IDialogsOptions {
/**
* Application translator object
*/
translator?: ITranslator;
/**
* Optional setting registry used to access restart dialog preference.
*/
settingRegistry?: ISettingRegistry | null;
}
}
/**
* The default implementation for a session context object.
*/
export class SessionContext implements ISessionContext {
/**
* Construct a new session context.
*/
constructor(options: SessionContext.IOptions) {
this.kernelManager = options.kernelManager;
this.sessionManager = options.sessionManager;
this.specsManager = options.specsManager;
this.translator = options.translator || nullTranslator;
this._trans = this.translator.load('jupyterlab');
this._path = options.path ?? UUID.uuid4();
this._type = options.type ?? '';
this._name = options.name ?? '';
this._setBusy = options.setBusy;
this._kernelPreference = options.kernelPreference ?? {};
}
/**
* The current session connection.
*/
get session(): Session.ISessionConnection | null {
return this._session ?? null;
}
/**
* The session path.
*
* #### Notes
* Typically `.session.path` should be used. This attribute is useful if
* there is no current session.
*/
get path(): string {
return this._path;
}
/**
* The session type.
*
* #### Notes
* Typically `.session.type` should be used. This attribute is useful if
* there is no current session.
*/
get type(): string {
return this._type;
}
/**
* The session name.
*
* #### Notes
* Typically `.session.name` should be used. This attribute is useful if
* there is no current session.
*/
get name(): string {
return this._name;
}
/**
* A signal emitted when the kernel connection changes, proxied from the session connection.
*/
get kernelChanged(): ISignal<
this,
Session.ISessionConnection.IKernelChangedArgs
> {
return this._kernelChanged;
}
/**
* A signal emitted when the session connection changes.
*/
get sessionChanged(): ISignal<
this,
IChangedArgs<
Session.ISessionConnection | null,
Session.ISessionConnection | null,
'session'
>
> {
return this._sessionChanged;
}
/**
* A signal emitted when the kernel status changes, proxied from the kernel.
*/
get statusChanged(): ISignal<this, Kernel.Status> {
return this._statusChanged;
}
/**
* A flag indicating if the session has pending input, proxied from the kernel.
*/
get pendingInput(): boolean {
return this._pendingInput;
}
/**
* A signal emitted when the kernel status changes, proxied from the kernel.
*/
get connectionStatusChanged(): ISignal<this, Kernel.ConnectionStatus> {
return this._connectionStatusChanged;
}
/**
* A signal emitted for iopub kernel messages, proxied from the kernel.
*/
get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {
return this._iopubMessage;
}
/**
* A signal emitted for an unhandled kernel message, proxied from the kernel.
*/
get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {
return this._unhandledMessage;
}
/**
* A signal emitted when a session property changes, proxied from the current session.
*/
get propertyChanged(): ISignal<this, 'path' | 'name' | 'type'> {
return this._propertyChanged;
}
/**
* The kernel preference of this client session.
*
* This is used when selecting a new kernel, and should reflect the sort of
* kernel the activity prefers.
*/
get kernelPreference(): ISessionContext.IKernelPreference {
return this._kernelPreference;
}
set kernelPreference(value: ISessionContext.IKernelPreference) {
if (!JSONExt.deepEqual(value as any, this._kernelPreference as any)) {
const oldValue = this._kernelPreference;
this._kernelPreference = value;
this._preferenceChanged.emit({
name: 'kernelPreference',
oldValue,
newValue: JSONExt.deepCopy(value as any)
});
}
}
/**
* Signal emitted if the kernel preference changes.
*/
get kernelPreferenceChanged(): ISignal<
this,
IChangedArgs<ISessionContext.IKernelPreference>
> {
return this._preferenceChanged;
}
/**
* Whether the context is ready.
*/
get isReady(): boolean {
return this._isReady;
}
/**
* A promise that is fulfilled when the context is ready.
*/
get ready(): Promise<void> {
return this._ready.promise;
}
/**
* Whether the context is terminating.
*/
get isTerminating(): boolean {
return this._isTerminating;
}
/**
* Whether the context is restarting.
*/
get isRestarting(): boolean {
return this._isRestarting;
}
/**
* The kernel manager
*/
readonly kernelManager?: Kernel.IManager;
/**
* The session manager used by the session.
*/
readonly sessionManager: Session.IManager;
/**
* The kernel spec manager
*/
readonly specsManager: KernelSpec.IManager;
/**
* Whether the kernel is "No Kernel" or not.
*
* #### Notes
* As the displayed name is translated, this can be used directly.
*/
get hasNoKernel(): boolean {
return this.kernelDisplayName === this.noKernelName;
}
/**
* The display name of the current kernel, or a sensible alternative.
*
* #### Notes
* This is a convenience function to have a consistent sensible name for the
* kernel.
*/
get kernelDisplayName(): string {
const kernel = this.session?.kernel;
if (this._pendingKernelName === this.noKernelName) {
return this.noKernelName;
}
if (this._pendingKernelName) {
return (
this.specsManager.specs?.kernelspecs[this._pendingKernelName]
?.display_name ?? this._pendingKernelName
);
}
if (!kernel) {
return this.noKernelName;
}
return (
this.specsManager.specs?.kernelspecs[kernel.name]?.display_name ??
kernel.name
);
}
/**
* A sensible status to display
*
* #### Notes
* This combines the status and connection status into a single status for
* the user.
*/
get kernelDisplayStatus(): ISessionContext.KernelDisplayStatus {
const kernel = this.session?.kernel;
if (this._isTerminating) {
return 'terminating';
}
if (this._isRestarting) {
return 'restarting';
}
if (this._pendingKernelName === this.noKernelName) {
return 'unknown';
}
if (!kernel && this._pendingKernelName) {
return 'initializing';
}
if (
!kernel &&
!this.isReady &&
this.kernelPreference.canStart !== false &&
this.kernelPreference.shouldStart !== false
) {
return 'initializing';
}
return (
(kernel?.connectionStatus === 'connected'
? kernel?.status
: kernel?.connectionStatus) ?? 'unknown'
);
}
/**
* The name of the previously started kernel.
*/
get prevKernelName(): string {
return this._prevKernelName;
}
/**
* Test whether the context is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* A signal emitted when the poll is disposed.
*/
get disposed(): ISignal<this, void> {
return this._disposed;
}
/**
* Get the constant displayed name for "No Kernel"
*/
protected get noKernelName(): string {
return this._trans.__('No Kernel');
}
/**
* Dispose of the resources held by the context.
*/
dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
this._disposed.emit();
if (this._session) {
if (this.kernelPreference.shutdownOnDispose) {
// Fire and forget the session shutdown request
this.sessionManager.shutdown(this._session.id).catch(reason => {
console.error(`Kernel not shut down ${reason}`);
});
}
// Dispose the session connection
this._session.dispose();
this._session = null;
}
if (this._dialog) {
this._dialog.dispose();
}
if (this._busyDisposable) {
this._busyDisposable.dispose();
this._busyDisposable = null;
}
Signal.clearData(this);
}
/**
* Starts new Kernel.
*
* @returns Whether to ask the user to pick a kernel.
*/
async startKernel(): Promise<boolean> {
const preference = this.kernelPreference;
if (!preference.autoStartDefault && preference.shouldStart === false) {
return true;
}
let options: Partial<Kernel.IModel> | undefined;
if (preference.id) {
options = { id: preference.id };
} else {
const name = Private.getDefaultKernel({
specs: this.specsManager.specs,
sessions: this.sessionManager.running(),
preference
});
if (name) {
options = { name };
}
}
if (options) {
try {
await this._changeKernel(options);
return false;
} catch (err) {
/* no-op */
}
}
// Always fall back to selecting a kernel
return true;
}
/**
* Restart the current Kernel.
*
* @returns A promise that resolves when the kernel is restarted.
*/
async restartKernel(): Promise<void> {
const kernel = this.session?.kernel || null;
if (this._isRestarting) {
return;
}
this._isRestarting = true;
this._isReady = false;
this._statusChanged.emit('restarting');
try {
await this.session?.kernel?.restart();
this._isReady = true;
} catch (e) {
console.error(e);
}
this._isRestarting = false;
this._statusChanged.emit(this.session?.kernel?.status || 'unknown');
this._kernelChanged.emit({
name: 'kernel',
oldValue: kernel,
newValue: this.session?.kernel || null
});
}
/**
* Change the current kernel associated with the session.
*/
async changeKernel(
options: Partial<Kernel.IModel> = {}
): Promise<Kernel.IKernelConnection | null> {
if (this.isDisposed) {
throw new Error('Disposed');
}
// Wait for the initialization method to try
// and start its kernel first to ensure consistent
// ordering.
await this._initStarted.promise;
return this._changeKernel(options);
}
/**
* Kill the kernel and shutdown the session.
*
* @returns A promise that resolves when the session is shut down.
*/
async shutdown(): Promise<void> {
if (this.isDisposed || !this._initializing) {
return;
}
await this._initStarted.promise;
this._pendingSessionRequest = '';
this._pendingKernelName = this.noKernelName;
return this._shutdownSession();
}
/**
* Initialize the session context
*
* @returns A promise that resolves with whether to ask the user to select a kernel.
*
* #### Notes
* If a server session exists on the current path, we will connect to it.
* If preferences include disabling `canStart` or `shouldStart`, no
* server session will be started.
* If a kernel id is given, we attempt to start a session with that id.
* If a default kernel is available, we connect to it.
* Otherwise we ask the user to select a kernel.
*/
async initialize(): Promise<boolean> {
if (this._initializing) {
return this._initPromise.promise;
}
this._initializing = true;
const needsSelection = await this._initialize();
if (!needsSelection) {
this._isReady = true;
this._ready.resolve(undefined);
}
if (!this._pendingSessionRequest) {
this._initStarted.resolve(void 0);
}
this._initPromise.resolve(needsSelection);
return needsSelection;
}
/**
* Inner initialize function that doesn't handle promises.
* This makes it easier to consolidate promise handling logic.
*/
async _initialize(): Promise<boolean> {
const manager = this.sessionManager;
await manager.ready;
await manager.refreshRunning();
const model = find(manager.running(), item => {
return item.path === this._path;
});
if (model) {
try {
const session = manager.connectTo({ model });
this._handleNewSession(session);
} catch (err) {
void this._handleSessionError(err);
return Promise.reject(err);
}
}
return await this._startIfNecessary();
}
/**
* Shut down the current session.
*/
private async _shutdownSession(): Promise<void> {
const session = this._session;
// Capture starting values in case an error is raised.
const isTerminating = this._isTerminating;
const isReady = this._isReady;
this._isTerminating = true;
this._isReady = false;
this._statusChanged.emit('terminating');
try {
await session?.shutdown();
this._isTerminating = false;
session?.dispose();
this._session = null;
const kernel = session?.kernel || null;
this._statusChanged.emit('unknown');
this._kernelChanged.emit({
name: 'kernel',
oldValue: kernel,
newValue: null
});
this._sessionChanged.emit({
name: 'session',
oldValue: session,
newValue: null
});
} catch (err) {
this._isTerminating = isTerminating;
this._isReady = isReady;
const status = session?.kernel?.status;
if (status === undefined) {
this._statusChanged.emit('unknown');
} else {
this._statusChanged.emit(status);
}
throw err;
}
return;
}
/**
* Start the session if necessary.
*
* @returns Whether to ask the user to pick a kernel.
*/
private async _startIfNecessary(): Promise<boolean> {
const preference = this.kernelPreference;
if (
this.isDisposed ||
this.session?.kernel ||
preference.shouldStart === false ||
preference.canStart === false
) {
// Not necessary to start a kernel
return false;
}
return this.startKernel();
}
/**
* Change the kernel.
*/
private async _changeKernel(
model: Partial<Kernel.IModel> = {}
): Promise<Kernel.IKernelConnection | null> {
if (model.name) {
this._pendingKernelName = model.name;
}
if (!this._session) {
this._kernelChanged.emit({
name: 'kernel',
oldValue: null,
newValue: null
});
}
// Guarantee that the initialized kernel
// will be started first.
if (!this._pendingSessionRequest) {
this._initStarted.resolve(void 0);
}
// If we already have a session, just change the kernel.
if (this._session && !this._isTerminating) {
try {
await this._session.changeKernel(model);
return this._session.kernel;
} catch (err) {
void this._handleSessionError(err);
throw err;
}
}
// Use a UUID for the path to overcome a race condition on the server
// where it will re-use a session for a given path but only after
// the kernel finishes starting.
// We later switch to the real path below.
// Use the correct directory so the kernel will be started in that directory.
const dirName = PathExt.dirname(this._path);
const requestId = (this._pendingSessionRequest = PathExt.join(
dirName,
UUID.uuid4()
));
try {
this._statusChanged.emit('starting');
const session = await this.sessionManager.startNew({
path: requestId,
type: this._type,
name: this._name,
kernel: model
});
// Handle a preempt.
if (this._pendingSessionRequest !== session.path) {
await session.shutdown();
session.dispose();
return null;
}
// Change to the real path.
await session.setPath(this._path);
// Update the name in case it has changed since we launched the session.
await session.setName(this._name);
if (this._session && !this._isTerminating) {
await this._shutdownSession();
}
return this._handleNewSession(session);
} catch (err) {
void this._handleSessionError(err);
throw err;
}
}
/**
* Handle a new session object.
*/
private _handleNewSession(
session: Session.ISessionConnection | null
): Kernel.IKernelConnection | null {
if (this.isDisposed) {
throw Error('Disposed');
}
if (!this._isReady) {
this._isReady = true;
this._ready.resolve(undefined);
}
if (this._session) {
this._session.dispose();
}
this._session = session;
this._pendingKernelName = '';
if (session) {
this._prevKernelName = session.kernel?.name ?? '';