-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathruntimeSession.ts
2211 lines (1947 loc) · 87.5 KB
/
runtimeSession.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) 2024-2025 Posit Software, PBC. All rights reserved.
* Licensed under the Elastic License 2.0. See LICENSE.txt for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from '../../../../nls.js';
import { DeferredPromise, disposableTimeout } from '../../../../base/common/async.js';
import { Emitter } from '../../../../base/common/event.js';
import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js';
import { URI } from '../../../../base/common/uri.js';
import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js';
import { ILogService } from '../../../../platform/log/common/log.js';
import { IOpener, IOpenerService, OpenExternalOptions, OpenInternalOptions } from '../../../../platform/opener/common/opener.js';
import { ILanguageRuntimeMetadata, ILanguageRuntimeService, LanguageRuntimeSessionLocation, LanguageRuntimeSessionMode, LanguageRuntimeStartupBehavior, RuntimeExitReason, RuntimeState, LanguageStartupBehavior, formatLanguageRuntimeMetadata, formatLanguageRuntimeSession } from '../../languageRuntime/common/languageRuntimeService.js';
import { ILanguageRuntimeGlobalEvent, ILanguageRuntimeSession, ILanguageRuntimeSessionManager, ILanguageRuntimeSessionStateEvent, INotebookSessionUriChangedEvent, IRuntimeSessionMetadata, IRuntimeSessionService, IRuntimeSessionWillStartEvent, RuntimeStartMode } from './runtimeSessionService.js';
import { IWorkspaceTrustManagementService } from '../../../../platform/workspace/common/workspaceTrust.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js';
import { IModalDialogPromptInstance, IPositronModalDialogsService } from '../../positronModalDialogs/common/positronModalDialogs.js';
import { ILanguageService } from '../../../../editor/common/languages/language.js';
import { ResourceMap } from '../../../../base/common/map.js';
import { IExtensionService } from '../../extensions/common/extensions.js';
import { IStorageService, StorageScope } from '../../../../platform/storage/common/storage.js';
import { ICommandService } from '../../../../platform/commands/common/commands.js';
import { ActiveRuntimeSession } from './activeRuntimeSession.js';
import { IUpdateService } from '../../../../platform/update/common/update.js';
import { multipleConsoleSessionsFeatureEnabled } from './positronMultipleConsoleSessionsFeatureFlag.js';
import { INotificationService, Severity } from '../../../../platform/notification/common/notification.js';
import { localize } from '../../../../nls.js';
/**
* The maximum number of active sessions a user can have running at a time.
* This value is arbitrary and a limit to use for sanity purposes for the
* multiple console sessions feature. This should be removed in the future
* or made a setting if limiting concurrent active sessions is required.
*
* Only to be used with `console.multipleConsoleSessions` feaeture flag.
*/
const MAX_CONCURRENT_SESSIONS = 15;
/**
* Get a map key corresponding to a session.
*
* @returns A composite of the session mode, runtime ID, and notebook URI - assuming that there
* is at most one session for this combination at any given time.
*/
function getSessionMapKey(sessionMode: LanguageRuntimeSessionMode,
runtimeId: string,
notebookUri: URI | undefined): string {
return JSON.stringify([sessionMode, runtimeId, notebookUri?.toString()]);
}
/**
* The implementation of IRuntimeSessionService.
*/
export class RuntimeSessionService extends Disposable implements IRuntimeSessionService, IOpener {
// Needed for service branding in dependency injector.
declare readonly _serviceBrand: undefined;
// The session managers.
private _sessionManagers: Array<ILanguageRuntimeSessionManager> = [];
// The set of encountered languages. This is keyed by the languageId and is
// used to orchestrate implicit runtime startup.
private readonly _encounteredLanguagesByLanguageId = new Set<string>();
/**
* The foreground session. This is the session that is currently active in
* the Console view.
*/
private _foregroundSession?: ILanguageRuntimeSession;
// A map of the currently active sessions. This is keyed by the session ID.
private readonly _activeSessionsBySessionId = new Map<string, ActiveRuntimeSession>();
// A map of the starting consoles. This is keyed by the languageId
// (metadata.languageId) of the runtime owning the session.
private readonly _startingConsolesByLanguageId = new Map<string, ILanguageRuntimeMetadata>();
// A map of the starting consoles. This is keyed by the runtimeId
// (metadata.runtimeId) of the runtime owning the session.
// This is the replacement for _startingConsolesByLanguageId for multiple console sessions
private readonly _startingConsolesByRuntimeId = new Map<string, ILanguageRuntimeMetadata>();
// A map of the starting notebooks. This is keyed by the notebook URI
// owning the session.
private readonly _startingNotebooksByNotebookUri = new ResourceMap<ILanguageRuntimeMetadata>();
// A map of sessions currently starting to promises that resolve when the session
// is ready to use. This is keyed by the composition of the session mode, runtime ID,
// and notebook URI. This map limits the number of sessions that can be started at once
// per runtime due to the nature of the session key.
private readonly _startingSessionsBySessionMapKey = new Map<string, DeferredPromise<string>>();
// A map of sessions currently shutting down to promises that resolve when the session
// has shut down. This is keyed by the session ID.
private readonly _shuttingDownRuntimesBySessionId = new Map<string, Promise<void>>();
/** A map of notebooks currently shutting down to promises that resolve when the notebook
* has exited, keyed by notebook URI. */
private readonly _shuttingDownNotebooksByNotebookUri = new ResourceMap<DeferredPromise<void>>();
// A map of the currently active console sessions. Since we can currently
// only have one console session per language, this is keyed by the
// languageId (metadata.languageId) of the session.
private readonly _consoleSessionsByLanguageId = new Map<string, ILanguageRuntimeSession>();
// A map of the currently active console sessions. Since we can
// have multiple console sessions per runtime, this map is keyed by
// the runtimeId (metadata.runtimeId) of the session.
private readonly _consoleSessionsByRuntimeId = new Map<string, ILanguageRuntimeSession[]>();
// A map of the number of sessions created per runtime ID. This is used to
// make each session name unique.
private readonly _consoleSessionCounterByRuntimeId = new Map<string, number>();
// A map of the last active console session per langauge.
// We can have multiple console sessions per language,
// and this map provides access to the session that was
// last active per language.
private readonly _lastActiveConsoleSessionByLanguageId = new Map<string, ILanguageRuntimeSession>();
// A map of the currently active notebook sessions. This is keyed by the notebook URI
// owning the session.
private readonly _notebookSessionsByNotebookUri = new ResourceMap<ILanguageRuntimeSession>();
// An map of sessions that have been disconnected from the extension host,
// from sessionId to session. We keep these around so we can reconnect them when
// the extension host comes back online.
private readonly _disconnectedSessions = new Map<string, ILanguageRuntimeSession>();
// The event emitter for the onWillStartRuntime event.
private readonly _onWillStartRuntimeEmitter =
this._register(new Emitter<IRuntimeSessionWillStartEvent>);
// The event emitter for the onDidStartRuntime event.
private readonly _onDidStartRuntimeEmitter =
this._register(new Emitter<ILanguageRuntimeSession>);
// The event emitter for the onDidFailStartRuntime event.
private readonly _onDidFailStartRuntimeEmitter =
this._register(new Emitter<ILanguageRuntimeSession>);
// The event emitter for the onDidChangeRuntimeState event.
private readonly _onDidChangeRuntimeStateEmitter =
this._register(new Emitter<ILanguageRuntimeSessionStateEvent>());
// The event emitter for the onDidReceiveRuntimeEvent event.
private readonly _onDidReceiveRuntimeEventEmitter =
this._register(new Emitter<ILanguageRuntimeGlobalEvent>());
// The event emitter for the onDidChangeForegroundSession event.
private readonly _onDidChangeForegroundSessionEmitter =
this._register(new Emitter<ILanguageRuntimeSession | undefined>);
// The event emitter for the onDidDeleteRuntime event.
private readonly _onDidDeleteRuntimeSessionEmitter =
this._register(new Emitter<string>);
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@ILanguageService private readonly _languageService: ILanguageService,
@ILanguageRuntimeService private readonly _languageRuntimeService: ILanguageRuntimeService,
@ILogService private readonly _logService: ILogService,
@INotificationService private readonly _notificationService: INotificationService,
@IOpenerService private readonly _openerService: IOpenerService,
@IPositronModalDialogsService private readonly _positronModalDialogsService: IPositronModalDialogsService,
@IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService,
@IExtensionService private readonly _extensionService: IExtensionService,
@IStorageService private readonly _storageService: IStorageService,
@IUpdateService private readonly _updateService: IUpdateService
) {
super();
// Register as an opener in the opener service.
this._openerService.registerOpener(this);
// Add the onDidEncounterLanguage event handler.
this._register(this._languageService.onDidRequestRichLanguageFeatures(languageId => {
// Add the language to the set of encountered languages.
this._encounteredLanguagesByLanguageId.add(languageId);
// If a runtime for the language is already starting or running,
// there is no need to check for implicit startup below.
if (this.hasStartingOrRunningConsole(languageId)) {
return;
}
// Find the registered runtimes for the language that have implicit
// startup behavior. If there aren't any, return.
const languageRuntimeInfos = this._languageRuntimeService.registeredRuntimes
.filter(
metadata =>
metadata.languageId === languageId &&
metadata.startupBehavior === LanguageRuntimeStartupBehavior.Implicit);
if (!languageRuntimeInfos.length) {
return;
}
// Start the first runtime that was found. This isn't random; the
// runtimes are sorted by priority when registered by the extension
// so they will be in the right order so the first one is the right
// one to start.
this._logService.trace(`Language runtime ${formatLanguageRuntimeMetadata(languageRuntimeInfos[0])} automatically starting`);
this.autoStartRuntime(languageRuntimeInfos[0],
`A file with the language ID ${languageId} was opened.`,
true);
}));
// When an extension activates, check to see if we have any disconnected
// sessions owned by that extension. If we do, try to reconnect them.
this._register(this._extensionService.onDidChangeExtensionsStatus((e) => {
for (const extensionId of e) {
for (const session of this._disconnectedSessions.values()) {
if (session.runtimeMetadata.extensionId.value === extensionId.value) {
// Remove the session from the disconnected sessions so we don't
// try to reconnect it again (no matter the outcome below)
this._disconnectedSessions.delete(session.sessionId);
// Attempt to reconnect the session.
this._logService.debug(`Extension ${extensionId.value} has been reloaded; ` +
`attempting to reconnect session ${session.sessionId}`);
this.restoreRuntimeSession(session.runtimeMetadata, session.metadata, false);
}
}
}
}));
// Changing the application storage scope causes disconnected sessions
// to become unusable, since the information needed to reconnect to them
// is stored in the old scope.
this._register(this._storageService.onDidChangeTarget((e) => {
if (e.scope === StorageScope.APPLICATION && this._disconnectedSessions.size > 0) {
this._logService.debug(`Application storage scope changed; ` +
`discarding ${this._disconnectedSessions.size} disconnected sessions`);
// Clear map and fire deletion events to update
// console session service consumers.
this._disconnectedSessions.forEach(value => {
this._onDidDeleteRuntimeSessionEmitter.fire(value.sessionId);
});
this._disconnectedSessions.clear();
}
}));
this.scheduleUpdateActiveLanguages(25 * 1000);
}
//#region ILanguageRuntimeService Implementation
// An event that fires when a runtime is about to start.
readonly onWillStartSession = this._onWillStartRuntimeEmitter.event;
// An event that fires when a runtime successfully starts.
readonly onDidStartRuntime = this._onDidStartRuntimeEmitter.event;
// An event that fires when a runtime fails to start.
readonly onDidFailStartRuntime = this._onDidFailStartRuntimeEmitter.event;
// An event that fires when a runtime changes state.
readonly onDidChangeRuntimeState = this._onDidChangeRuntimeStateEmitter.event;
// An event that fires when a runtime receives a global event.
readonly onDidReceiveRuntimeEvent = this._onDidReceiveRuntimeEventEmitter.event;
// An event that fires when the active runtime changes.
readonly onDidChangeForegroundSession = this._onDidChangeForegroundSessionEmitter.event;
// An event that fires when a runtime is deleted.
readonly onDidDeleteRuntimeSession = this._onDidDeleteRuntimeSessionEmitter.event;
// The event emitter for the onDidUpdateNotebookSessionUri event.
private readonly _onDidUpdateNotebookSessionUriEmitter =
this._register(new Emitter<INotebookSessionUriChangedEvent>());
// An event that fires when a notebook session's URI is updated.
readonly onDidUpdateNotebookSessionUri = this._onDidUpdateNotebookSessionUriEmitter.event;
/**
* Registers a session manager with the service.
*
* @param manager The session manager to register
* @returns A Disposable that can be used to unregister the session manager.
*/
registerSessionManager(manager: ILanguageRuntimeSessionManager): IDisposable {
this._sessionManagers.push(manager);
return toDisposable(() => {
const index = this._sessionManagers.indexOf(manager);
if (index !== -1) {
this._sessionManagers.splice(index, 1);
}
});
}
/**
* Gets the console session for a runtime, if one exists.
* Used to associated a session with a runtime.
*
* @param runtimeId The runtime identifier of the session to retrieve.
* @param includeExited Whether to include exited sessions in the search. (default false, optional)
* @returns The console session with the given runtime identifier, or undefined if
* no console session with the given runtime identifier exists.
*/
getConsoleSessionForRuntime(runtimeId: string, includeExited: boolean = false): ILanguageRuntimeSession | undefined {
// It's possible that there are multiple consoles for the same runtime.
// In that case, we return the most recently created.
return Array.from(this._activeSessionsBySessionId.values())
.map((info, index) => ({ info, index }))
.sort((a, b) =>
b.info.session.metadata.createdTimestamp - a.info.session.metadata.createdTimestamp
// If the timestamps are the same, prefer the session that was inserted last.
|| b.index - a.index)
.find(({ info }) =>
info.session.runtimeMetadata.runtimeId === runtimeId &&
info.session.metadata.sessionMode === LanguageRuntimeSessionMode.Console &&
(includeExited || info.state !== RuntimeState.Exited)
)
?.info.session;
}
/**
* Gets the console session for a language, if one exists.
*
* @param languageId The language identifier of the session to retrieve.
* @returns The console session with the given language identifier, or undefined if
* no console session with the given language identifier exists.
*/
getConsoleSessionForLanguage(languageId: string): ILanguageRuntimeSession | undefined {
const multiSessionsEnabled = multipleConsoleSessionsFeatureEnabled(this._configurationService);
if (multiSessionsEnabled) {
// Return the foreground session if the languageId matches
if (this._foregroundSession?.runtimeMetadata.languageId === languageId) {
return this.foregroundSession;
}
// Otherwise, return the last active session for the languageId if there is one
return this._lastActiveConsoleSessionByLanguageId.get(languageId);
} else {
return this._consoleSessionsByLanguageId.get(languageId);
}
}
/**
* Gets the notebook session for a notebook URI, if one exists.
*
* @param notebookUri The notebook URI of the session to retrieve.
* @returns The notebook session with the given notebook URI, or undefined if
* no notebook session with the given notebook URI exists.
*/
getNotebookSessionForNotebookUri(notebookUri: URI): ILanguageRuntimeSession | undefined {
const session = this._notebookSessionsByNotebookUri.get(notebookUri);
this._logService.info(`Lookup notebook session for notebook URI ${notebookUri.toString()}: ${session ? session.metadata.sessionId : 'not found'}`);
return session;
}
/**
* List all active runtime sessions.
*
* @returns The active sessions.
*/
getActiveSessions(): ActiveRuntimeSession[] {
return Array.from(this._activeSessionsBySessionId.values());
}
/**
* Selects and starts a new runtime session, after shutting down any currently active
* sessions for the console or notebook.
*
* If `console.multipleConsoleSessions` is enabled this function works as decribed below:
*
* Select a session for the provided runtime.
*
* For console sessions, if there is an active console session for the runtime, set it as
* the foreground session and return. If there is no active console session for the runtime,
* start a new session for the runtime. If there are multiple sessions for the runtime,
* the most recently created session is set as the foreground session.
*
* For notebooks, only one runtime session for a notebook URI is allowed. Starts a session for the
* new runtime after shutting down the session for the previous runtime. Do nothing if the runtime
* matches the active runtime for the notebook session.
*
* @param runtimeId The ID of the runtime to select
* @param source The source of the selection
* @param notebookUri The URI of the notebook selecting the runtime, if any
*
* @returns A promise that resolves to the session ID if a runtime session was started
*/
async selectRuntime(runtimeId: string, source: string, notebookUri?: URI): Promise<void> {
const multiSessionsEnabled = multipleConsoleSessionsFeatureEnabled(this._configurationService);
const runtime = this._languageRuntimeService.getRegisteredRuntime(runtimeId);
if (!runtime) {
throw new Error(`No language runtime with id '${runtimeId}' was found.`);
}
// Determine some session metadata values based off the session type (console vs notebook)
const sessionMode = notebookUri
? LanguageRuntimeSessionMode.Notebook
: LanguageRuntimeSessionMode.Console;
const startMode = notebookUri
? RuntimeStartMode.Switching
: multiSessionsEnabled ? RuntimeStartMode.Starting : RuntimeStartMode.Switching;
// If a start request is already in progress, wait for it to complete.
const startingPromise = this._startingSessionsBySessionMapKey.get(
getSessionMapKey(sessionMode, runtimeId, notebookUri));
if (startingPromise && !startingPromise.isSettled) {
await startingPromise.p;
}
if (notebookUri) {
// If a session is already shutting down for this notebook, wait for it to complete.
const shuttingDownPromise = this._shuttingDownNotebooksByNotebookUri.get(notebookUri);
if (shuttingDownPromise && !shuttingDownPromise.isSettled) {
try {
await shuttingDownPromise.p;
} catch (error) {
// Continue anyway; we assume the error is handled elsewhere.
}
}
// Shut down any other sessions for the notebook.
const activeSession =
this.getNotebookSessionForNotebookUri(notebookUri);
if (activeSession) {
// If the active session is for the same runtime, we don't need to do anything.
if (activeSession.runtimeMetadata.runtimeId === runtime.runtimeId) {
return;
}
await this.shutdownRuntimeSession(activeSession, RuntimeExitReason.SwitchRuntime);
}
} else {
if (multiSessionsEnabled) {
// Check if there is a console session for this runtime already
const existingSession = this.getConsoleSessionForRuntime(runtimeId, true);
if (existingSession) {
// Set it as the foreground session and return.
if (existingSession.runtimeMetadata.runtimeId !== this.foregroundSession?.runtimeMetadata.runtimeId) {
this.foregroundSession = existingSession;
}
return;
}
} else {
// Shut down any other runtime consoles for the language.
const activeSession =
this.getConsoleSessionForLanguage(runtime.languageId);
if (activeSession) {
// Is this, by chance, the runtime that's already running?
if (activeSession.runtimeMetadata.runtimeId === runtime.runtimeId) {
// Set it as the foreground session and return.
this.foregroundSession = activeSession;
return;
}
await this.shutdownRuntimeSession(activeSession, RuntimeExitReason.SwitchRuntime);
}
}
}
// Wait for the selected runtime to start.
await this.startNewRuntimeSession(
runtime.runtimeId,
runtime.runtimeName,
sessionMode,
notebookUri,
source,
startMode,
true
);
}
/**
* Shutdown a runtime session.
*
* @param session The session to shutdown.
* @param exitReason The reason for shutting down the session.
* @returns Promise that resolves when the session has been shutdown.
*/
private async shutdownRuntimeSession(
session: ILanguageRuntimeSession, exitReason: RuntimeExitReason): Promise<void> {
// See if we are already shutting down this session. If we
// are, return the promise that resolves when the runtime is shut down.
// This makes it possible for multiple requests to shut down the same
// session to be coalesced.
const sessionId = session.metadata.sessionId;
const shuttingDownPromise = this._shuttingDownRuntimesBySessionId.get(sessionId);
if (shuttingDownPromise) {
return shuttingDownPromise;
}
const shutdownPromise = this.doShutdownRuntimeSession(session, exitReason)
.finally(() => this._shuttingDownRuntimesBySessionId.delete(sessionId));
this._shuttingDownRuntimesBySessionId.set(sessionId, shutdownPromise);
return shutdownPromise;
}
private async doShutdownRuntimeSession(
session: ILanguageRuntimeSession, exitReason: RuntimeExitReason): Promise<void> {
const activeSession = this._activeSessionsBySessionId.get(session.sessionId);
if (!activeSession) {
throw new Error(`No active session '${session.sessionId}'`);
}
// We wait for `onDidEndSession()` rather than `RuntimeState.Exited`, because the former
// generates some Console output that must finish before starting up a new runtime:
const disposables = activeSession.register(new DisposableStore());
const promise = new Promise<void>((resolve, reject) => {
disposables.add(session.onDidEndSession((exit) => {
disposables.dispose();
resolve();
}));
disposables.add(disposableTimeout(() => {
disposables.dispose();
reject(new Error(`Timed out waiting for runtime ` +
`${formatLanguageRuntimeSession(session)} to finish exiting.`));
}, 5000));
});
// Ask the runtime to shut down.
try {
await session.shutdown(exitReason);
} catch (error) {
disposables.dispose();
throw error;
}
// Wait for the runtime onDidEndSession to resolve, or for the timeout to expire
// (whichever comes first)
await promise;
}
/**
* Starts a new runtime session.
*
* @param runtimeId The runtime identifier of the runtime.
* @param sessionName A human readable name for the session.
* @param sessionMode The mode of the new session.
* @param notebookUri The notebook URI to attach to the session, if any.
* @param source The source of the request to start the runtime.
* @param startMode The mode in which to start the runtime.
* @param activate Whether to activate/focus the session after it is started.
*/
async startNewRuntimeSession(runtimeId: string,
sessionName: string,
sessionMode: LanguageRuntimeSessionMode,
notebookUri: URI | undefined,
source: string,
startMode = RuntimeStartMode.Starting,
activate: boolean): Promise<string> {
// See if we are already starting the requested session. If we
// are, return the promise that resolves when the session is ready to
// use. This makes it possible for multiple requests to start the same
// session to be coalesced.
const sessionMapKey = getSessionMapKey(sessionMode, runtimeId, notebookUri);
const startingRuntimePromise = this._startingSessionsBySessionMapKey.get(sessionMapKey);
if (startingRuntimePromise && !startingRuntimePromise.isSettled) {
return startingRuntimePromise.p;
}
// Get the runtime. Throw an error, if it could not be found.
const languageRuntime = this._languageRuntimeService.getRegisteredRuntime(runtimeId);
if (!languageRuntime) {
throw new Error(`No language runtime with id '${runtimeId}' was found.`);
}
const runningSessionId = this.validateRuntimeSessionStart(sessionMode, languageRuntime, notebookUri, source);
if (runningSessionId) {
return runningSessionId;
}
// If the workspace is not trusted, defer starting the runtime until the
// workspace is trusted.
if (!this._workspaceTrustManagementService.isWorkspaceTrusted()) {
if (sessionMode === LanguageRuntimeSessionMode.Console) {
return this.autoStartRuntime(languageRuntime, source, activate);
} else {
throw new Error(`Cannot start a ${sessionMode} session in an untrusted workspace.`);
}
}
// Start the runtime.
this._logService.info(
`Starting session for language runtime ` +
`${formatLanguageRuntimeMetadata(languageRuntime)} (Source: ${source})`);
return this.doCreateRuntimeSession(languageRuntime, sessionName, sessionMode, source, startMode, activate, notebookUri);
}
/**
* Validates that a runtime session can be restored.
*
* @param runtimeMetadata
* @param sessionId
*/
async validateRuntimeSession(
runtimeMetadata: ILanguageRuntimeMetadata,
sessionId: string): Promise<boolean> {
// Get the runtime's manager.
let sessionManager: ILanguageRuntimeSessionManager;
try {
sessionManager = await this.getManagerForRuntime(runtimeMetadata);
} catch (err) {
// This shouldn't happen, but could in unusual circumstances, e.g.
// the extension that supplies the runtime was uninstalled and this
// is a stale session that it owned the last time we were running.
this._logService.error(`Error getting manager for runtime ${formatLanguageRuntimeMetadata(runtimeMetadata)}: ${err}`);
// Treat the session as invalid if we can't get the manager.
return false;
}
return sessionManager.validateSession(runtimeMetadata, sessionId);
}
/**
* Restores (reconnects to) a runtime session that was previously started.
*
* @param runtimeMetadata The metadata of the runtime to start.
* @param sessionMetadata The metadata of the session to start.
* @param activate Whether to activate/focus the session after it is
* reconnected.
*/
async restoreRuntimeSession(
runtimeMetadata: ILanguageRuntimeMetadata,
sessionMetadata: IRuntimeSessionMetadata,
activate: boolean): Promise<void> {
const multisessionEnabled = multipleConsoleSessionsFeatureEnabled(this._configurationService);
// See if we are already starting the requested session. If we
// are, return the promise that resolves when the session is ready to
// use. This makes it possible for multiple requests to start the same
// session to be coalesced.
const sessionMapKey = getSessionMapKey(
sessionMetadata.sessionMode, runtimeMetadata.runtimeId, sessionMetadata.notebookUri);
if (!multisessionEnabled || sessionMetadata.sessionMode === LanguageRuntimeSessionMode.Notebook) {
const startingRuntimePromise = this._startingSessionsBySessionMapKey.get(sessionMapKey);
if (startingRuntimePromise && !startingRuntimePromise.isSettled) {
return startingRuntimePromise.p.then(() => { });
}
}
// Ensure that the runtime is registered.
const languageRuntime = this._languageRuntimeService.getRegisteredRuntime(
runtimeMetadata.runtimeId);
if (!languageRuntime) {
this._logService.debug(`[Reconnect ${sessionMetadata.sessionId}]: ` +
`Registering runtime ${runtimeMetadata.runtimeName}`);
this._languageRuntimeService.registerRuntime(runtimeMetadata);
}
const runningSessionId = this.validateRuntimeSessionStart(
sessionMetadata.sessionMode, runtimeMetadata, sessionMetadata.notebookUri);
if (runningSessionId) {
return;
}
const startPromise = new DeferredPromise<string>();
if (!multisessionEnabled || sessionMetadata.sessionMode === LanguageRuntimeSessionMode.Notebook) {
// Create a promise that resolves when the runtime is ready to use.
this._startingSessionsBySessionMapKey.set(sessionMapKey, startPromise);
// It's possible that startPromise is never awaited, so we log any errors here
// at the debug level since we still expect the error to be handled/logged elsewhere.
startPromise.p.catch((err) => this._logService.debug(`Error starting session: ${err}`));
this.setStartingSessionMaps(
sessionMetadata.sessionMode, runtimeMetadata, sessionMetadata.notebookUri);
}
// We should already have a session manager registered, since we can't
// get here until the extension host has been activated.
if (this._sessionManagers.length === 0) {
throw new Error(`No session manager has been registered.`);
}
// Get the runtime's manager.
let sessionManager: ILanguageRuntimeSessionManager;
try {
sessionManager = await this.getManagerForRuntime(runtimeMetadata);
} catch (err) {
startPromise.error(err);
if (!multisessionEnabled || sessionMetadata.sessionMode === LanguageRuntimeSessionMode.Notebook) {
this.clearStartingSessionMaps(
sessionMetadata.sessionMode, runtimeMetadata, sessionMetadata.notebookUri);
}
throw err;
}
// Restore the session. This can take some time; it may involve waiting
// for the extension to finish activating and the network to attempt to
// reconnect, etc.
let session: ILanguageRuntimeSession;
try {
session = await sessionManager.restoreSession(runtimeMetadata, sessionMetadata);
} catch (err) {
this._logService.error(
`Reconnecting to session '${sessionMetadata.sessionId}' for language runtime ` +
`${formatLanguageRuntimeMetadata(runtimeMetadata)} failed. Reason: ${err}`);
startPromise.error(err);
if (!multisessionEnabled || sessionMetadata.sessionMode === LanguageRuntimeSessionMode.Notebook) {
this.clearStartingSessionMaps(
sessionMetadata.sessionMode, runtimeMetadata, sessionMetadata.notebookUri);
}
throw err;
}
// Actually reconnect the session.
try {
await this.doStartRuntimeSession(session, sessionManager, RuntimeStartMode.Reconnecting, activate);
startPromise.complete(sessionMetadata.sessionId);
} catch (err) {
startPromise.error(err);
}
return startPromise.p.then(() => { });
}
/**
* Sets the foreground session.
*/
set foregroundSession(session: ILanguageRuntimeSession | undefined) {
// If there's nothing to do, return.
if (!session && !this._foregroundSession) {
return;
}
this._foregroundSession = session;
if (session) {
// Update the map of active console sessions per language
this._lastActiveConsoleSessionByLanguageId.set(session.runtimeMetadata.languageId, session);
}
// Fire the onDidChangeForegroundSession event.
this._onDidChangeForegroundSessionEmitter.fire(this._foregroundSession);
}
/**
* Gets a single session, given its session ID.
*
* @param sessionId The session ID to retrieve.
* @returns The session with the given session ID, or undefined if no
* session with the given session ID exists.
*/
getSession(sessionId: string): ILanguageRuntimeSession | undefined {
return this._activeSessionsBySessionId.get(sessionId)?.session;
}
/**
* Gets a single active session, given its session ID.
*
* @param sessionId The session ID to retrieve.
* @returns The session with the given session ID, or undefined if no
* session with the given session ID exists.
*/
getActiveSession(sessionId: string): ActiveRuntimeSession | undefined {
return this._activeSessionsBySessionId.get(sessionId);
}
/**
* Gets the running runtimes.
*/
get activeSessions(): ILanguageRuntimeSession[] {
return Array.from(this._activeSessionsBySessionId.values()).map(info => info.session);
}
/**
* Gets the foreground session.
*/
get foregroundSession(): ILanguageRuntimeSession | undefined {
return this._foregroundSession;
}
/**
* Restarts a runtime session.
*
* @param sessionId The session ID of the runtime to restart.
* @param source The source of the request to restart the runtime.
*/
async restartSession(sessionId: string, source: string): Promise<void> {
const session = this.getSession(sessionId);
if (!session) {
throw new Error(`No session with ID '${sessionId}' was found.`);
}
this._logService.info(
`Restarting session '` +
`${formatLanguageRuntimeSession(session)}' (Source: ${source})`);
const state = session.getRuntimeState();
if (state === RuntimeState.Busy ||
state === RuntimeState.Idle ||
state === RuntimeState.Ready) {
// The runtime looks like it could handle a restart request, so send
// one over.
return this.doRestartRuntime(session);
} else if (state === RuntimeState.Uninitialized ||
state === RuntimeState.Exited) {
// The runtime has never been started, or is no longer running. Just
// tell it to start.
await this.startNewRuntimeSession(session.runtimeMetadata.runtimeId,
session.metadata.sessionName,
session.metadata.sessionMode,
session.metadata.notebookUri,
`'Restart Interpreter' command invoked`,
RuntimeStartMode.Starting,
true);
return;
} else if (state === RuntimeState.Starting ||
state === RuntimeState.Restarting) {
// The runtime is already starting or restarting. We could show an
// error, but this is probably just the result of a user mashing the
// restart when we already have one in flight.
return;
} else {
// The runtime is not in a state where it can be restarted.
throw new Error(`The ${session.runtimeMetadata.languageName} session is '${state}' ` +
`and cannot be restarted.`);
}
}
/**
* Internal method to restart a runtime session.
*
* @param session The runtime to restart.
*/
private async doRestartRuntime(session: ILanguageRuntimeSession): Promise<void> {
// If there is already a runtime starting for the session, return its promise.
const sessionMapKey = getSessionMapKey(
session.metadata.sessionMode, session.runtimeMetadata.runtimeId, session.metadata.notebookUri);
const startingRuntimePromise = this._startingSessionsBySessionMapKey.get(sessionMapKey);
if (startingRuntimePromise && !startingRuntimePromise.isSettled) {
return startingRuntimePromise.p.then(() => { });
}
const activeSession = this._activeSessionsBySessionId.get(session.sessionId);
if (!activeSession) {
throw new Error(`No active session '${session.sessionId}'`);
}
// Create a promise that resolves when the runtime is ready to use.
const startPromise = new DeferredPromise<string>();
this._startingSessionsBySessionMapKey.set(sessionMapKey, startPromise);
// Mark the session as starting.
this.setStartingSessionMaps(
session.metadata.sessionMode, session.runtimeMetadata, session.metadata.notebookUri);
// Mark the session as ready when it reaches the ready state,
// or after a timeout.
awaitStateChange(activeSession, [RuntimeState.Ready], 10)
.then(() => {
this.clearStartingSessionMaps(
session.metadata.sessionMode, session.runtimeMetadata, session.metadata.notebookUri);
startPromise.complete(session.sessionId);
})
.catch((err) => {
startPromise.error(err);
this.clearStartingSessionMaps(
session.metadata.sessionMode, session.runtimeMetadata, session.metadata.notebookUri);
});
// Ask the runtime to restart.
try {
// Restart the working directory in the same directory as the session.
await session.restart(activeSession.workingDirectory);
} catch (err) {
startPromise.error(err);
this.clearStartingSessionMaps(
session.metadata.sessionMode, session.runtimeMetadata, session.metadata.notebookUri);
}
return startPromise.p.then(() => { });
}
/**
* Shutdown a runtime session for a notebook.
*
* @param notebookUri The notebook's URI.
* @param exitReason The reason for exiting.
* @param source The source of the request to shutdown the session, for debugging purposes.
* @returns A promise that resolves when the session has exited.
*/
async shutdownNotebookSession(notebookUri: URI, exitReason: RuntimeExitReason, source: string): Promise<void> {
this._logService.info(`Shutting down notebook ${notebookUri.toString()}. Source: ${source}`);
// If there is a pending shutdown request for this notebook, return the existing promise.
const shuttingDownPromise = this._shuttingDownNotebooksByNotebookUri.get(notebookUri);
if (shuttingDownPromise && !shuttingDownPromise.isSettled) {
this._logService.debug(`Notebook ${notebookUri.toString()} is already shutting down. Returning existing promise`);
return shuttingDownPromise.p;
}
// Create a promise that resolves when the runtime has exited.
const shutdownPromise = new DeferredPromise<void>();
this._shuttingDownNotebooksByNotebookUri.set(notebookUri, shutdownPromise);
// Remove the promise from the map of shutting down notebooks when it completes.
shutdownPromise.p.finally(() => {
if (this._shuttingDownNotebooksByNotebookUri.get(notebookUri) === shutdownPromise) {
this._shuttingDownNotebooksByNotebookUri.delete(notebookUri);
}
});
// Get the session to shutdown.
const session = await this.getActiveOrStartingNotebook(notebookUri);
if (!session) {
this._logService.debug(
`Aborting shutdown request for notebook ${notebookUri.toString()}. ` +
`No active session found`
);
shutdownPromise.complete();
return;
}
// Actually shutdown the session.
try {
await this.shutdownRuntimeSession(session, exitReason);
shutdownPromise.complete();
this._logService.debug(`Notebook ${notebookUri.toString()} has been shut down`);
} catch (error) {
this._logService.error(`Failed to shutdown notebook ${notebookUri.toString()}. Reason: ${error}`);
shutdownPromise.error(error);
}
return shutdownPromise.p;
}
/**
* Shutdown a runtime session if active, and delete it.
* Cleans up the session and removes it from the active sessions list.
* @param sessionId The session ID of the runtime to delete.
*/
async deleteSession(sessionId: string): Promise<void> {
// If the session is disconnected, we preserve the console session
// in the case that the extension host comes back online.
if (this._disconnectedSessions.has(sessionId)) {
throw new Error(`Cannot delete session because it is disconnected.`);
}
const session = this.getSession(sessionId);
if (!session) {
throw new Error(`Cannot delete session because its runtime was not found.`);
}
const runtimeState = session.getRuntimeState();
if (runtimeState !== RuntimeState.Exited) {
if (runtimeState === RuntimeState.Busy ||
runtimeState === RuntimeState.Idle ||
runtimeState === RuntimeState.Ready) {
// If the runtime is in a state where it can be shut down, do so.
await this.shutdownRuntimeSession(session, RuntimeExitReason.Shutdown);
} else {
// Otherwise throw error.
throw new Error(`Cannot delete session because it is in state '${runtimeState}'`);
}
}
if (this._activeSessionsBySessionId.delete(sessionId)) {
// Clean up if necessary (should already by done once the runtime is exited).
this._consoleSessionsByLanguageId.delete(session.runtimeMetadata.languageId);
// Dispose of the session.
session.dispose();
// Fire the onDidDeleteRuntime event only if the session was actually deleted.
this._onDidDeleteRuntimeSessionEmitter.fire(sessionId);
}
}
/**
* Helper to get an active or starting session for a notebook URI. Returns undefined if there is
* no active session or if an error was encountered while the session was starting.
*/
private async getActiveOrStartingNotebook(notebookUri: URI): Promise<ILanguageRuntimeSession | undefined> {
// Check if there is an active session for the notebook.
const session = this._notebookSessionsByNotebookUri.get(notebookUri);
if (session) {
this._logService.debug(`Found an active session for notebook ${notebookUri.toString()}`);
return session;
}
// Check if there is a starting session for the notebook.
const startingRuntime = this._startingNotebooksByNotebookUri.get(notebookUri);
if (!startingRuntime) {
this._logService.debug(`No starting session for notebook ${notebookUri.toString()}`);
return undefined;
}
// Get the starting promise.
const sessionMapKey = getSessionMapKey(
LanguageRuntimeSessionMode.Notebook, startingRuntime.runtimeId, notebookUri);
const startingPromise = this._startingSessionsBySessionMapKey.get(sessionMapKey);
if (!startingPromise) {
this._logService.debug(`No starting session for notebook ${notebookUri.toString()}`);