-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathextension.service.ts
More file actions
883 lines (745 loc) · 29.6 KB
/
Copy pathextension.service.ts
File metadata and controls
883 lines (745 loc) · 29.6 KB
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
import debounce from 'lodash/debounce';
import { Autowired, INJECTOR_TOKEN, Injectable, Injector } from '@opensumi/di';
import { WSChannelHandler } from '@opensumi/ide-connection/lib/browser';
import { RPCServiceChannelPath } from '@opensumi/ide-connection/lib/common/server-handler';
import {
AppConfig,
CommandRegistry,
CorePreferences,
Deferred,
Disposable,
ExtensionActivateEvent,
IClientApp,
ILogger,
PreferenceService,
} from '@opensumi/ide-core-browser';
import { IProgressService } from '@opensumi/ide-core-browser/lib/progress';
import {
CancelablePromise,
CancellationToken,
ExtensionActivatedEvent,
ExtensionDidContributes,
GeneralSettingsId,
MayCancelablePromise,
OnEvent,
ProgressLocation,
URI,
WithEventBus,
createCancelablePromise,
getLanguageId,
localize,
sleep,
} from '@opensumi/ide-core-common';
import { DebugConfigurationsReadyEvent } from '@opensumi/ide-debug';
import { IExtensionStoragePathServer, IExtensionStorageService } from '@opensumi/ide-extension-storage';
import { FileSearchServicePath, IFileSearchService } from '@opensumi/ide-file-search/lib/common';
import { IFileServiceClient } from '@opensumi/ide-file-service';
import { IDialogService, IMessageService } from '@opensumi/ide-overlay';
import { IWorkspaceService } from '@opensumi/ide-workspace';
import {
ERestartPolicy,
ExtensionHostType,
ExtensionNodeServiceServerPath,
ExtensionService,
IExtCommandManagement,
IExtensionMetaData,
IExtensionNodeClientService,
LANGUAGE_BUNDLE_FIELD,
} from '../common';
import { ActivatedExtension } from '../common/activator';
import {
AbstractNodeExtProcessService,
AbstractViewExtProcessService,
AbstractWorkerExtProcessService,
} from '../common/extension.service';
import { MainThreadAPIIdentifier } from '../common/vscode';
import { ActivationEventServiceImpl } from './activation.service';
import { Extension } from './extension';
import { SumiContributionsService, SumiContributionsServiceToken } from './sumi/contributes';
import {
AbstractExtInstanceManagementService,
ExtensionApiReadyEvent,
ExtensionBeforeActivateEvent,
ExtensionDidEnabledEvent,
ExtensionDidUninstalledEvent,
ExtensionsInitializedEvent,
IActivationEventService,
} from './types';
import { VSCodeContributesService, VSCodeContributesServiceToken } from './vscode/contributes';
@Injectable()
export class ExtensionServiceImpl extends WithEventBus implements ExtensionService {
static extraMetadata = {
[LANGUAGE_BUNDLE_FIELD]: './package.nls.json',
};
@Autowired(ExtensionNodeServiceServerPath)
private readonly extensionNodeClient: IExtensionNodeClientService;
@Autowired(AppConfig)
private readonly appConfig: AppConfig;
@Autowired(CommandRegistry)
private readonly commandRegistry: CommandRegistry;
@Autowired(IActivationEventService)
private readonly activationEventService: ActivationEventServiceImpl;
@Autowired(IWorkspaceService)
private readonly workspaceService: IWorkspaceService;
@Autowired(IExtensionStorageService)
private readonly extensionStorageService: IExtensionStorageService;
@Autowired(IProgressService)
private readonly progressService: IProgressService;
@Autowired(IDialogService)
private readonly dialogService: IDialogService;
@Autowired(IClientApp)
private readonly clientApp: IClientApp;
@Autowired(ILogger)
private readonly logger: ILogger;
@Autowired(IMessageService)
private readonly messageService: IMessageService;
@Autowired(CorePreferences)
private readonly corePreferences: CorePreferences;
@Autowired(AbstractWorkerExtProcessService)
private readonly workerExtensionService: AbstractWorkerExtProcessService;
@Autowired(AbstractNodeExtProcessService)
private readonly nodeExtensionService: AbstractNodeExtProcessService;
@Autowired(AbstractViewExtProcessService)
private readonly viewExtensionService: AbstractViewExtProcessService;
@Autowired(IExtCommandManagement)
private readonly extensionCommandManager: IExtCommandManagement;
@Autowired(AbstractExtInstanceManagementService)
private readonly extensionInstanceManageService: AbstractExtInstanceManagementService;
@Autowired(FileSearchServicePath)
private readonly fileSearchService: IFileSearchService;
@Autowired(VSCodeContributesServiceToken)
private readonly contributesService: VSCodeContributesService;
@Autowired(SumiContributionsServiceToken)
private readonly sumiContributesService: SumiContributionsService;
@Autowired(PreferenceService)
private readonly preferenceService: PreferenceService;
@Autowired(IExtensionStoragePathServer)
private readonly extensionStoragePathServer: IExtensionStoragePathServer;
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(IFileServiceClient)
protected fileServiceClient: IFileServiceClient;
constructor() {
super();
this.addDispose(
this.fileServiceClient.onWillActivateFileSystemProvider(async () => {
if (!this.extensionMetaDataArr) {
await this.initExtensionMetaData();
}
return this.activationEventService.getTopicsData('onFileSystem');
}),
);
}
/**
* 这里的 ready 是区分环境,将 node/worker 区分开使用
*/
private ready = new Map<string, Deferred<void>>();
// 存储 extension 的 meta 数据
private extensionMetaDataArr: IExtensionMetaData[];
// 插件进程是否正在重启中
private isExtProcessRestarting = false;
// 插件进程是否正在等待重启,页面不可见的时候被设置
private isExtProcessWaitingForRestart: ERestartPolicy | undefined;
private pCrashMessageModel: MayCancelablePromise<string | undefined> | undefined;
// 是否正在显示插件重启的 loading 状态
private isProgressShowing = false;
// 针对 activationEvents 为 * 的插件
public eagerExtensionsActivated: Deferred<void> = new Deferred();
@Autowired(WSChannelHandler)
private readonly channelHandler: WSChannelHandler;
/**
* @internal 提供获取所有运行中的插件的列表数据
*/
async getActivatedExtensions(): Promise<{ [key in ExtensionHostType]?: ActivatedExtension[] }> {
const activated = {};
if (this.nodeExtensionService.protocol) {
activated['node'] = await this.nodeExtensionService.getActivatedExtensions();
}
if (this.workerExtensionService.protocol) {
activated['worker'] = await this.workerExtensionService.getActivatedExtensions();
}
return activated;
}
/**
* 插件目录
* 主要为插件的读取目录
*/
private extensionScanDir = new Set<string>();
/**
* 补充的插件列表
* 主要为插件的读取路径
*/
private extensionCandidatePath = new Set<string>();
@OnEvent(ExtensionActivateEvent)
protected async onActivateExtension(e: ExtensionActivateEvent) {
await this.activationEventService.fireEvent(e.payload.topic, e.payload.data);
}
/**
* 插件激活后需更新插件进程数据
*/
@OnEvent(ExtensionDidEnabledEvent)
protected async onExtensionEnabled(e: ExtensionDidEnabledEvent) {
const extension = e.payload;
await this.updateExtHostData();
await this.fireActivationEventsIfNeed(extension.packageJSON.activationEvents);
}
/**
* 插件卸载后需更新插件进程数据
*/
@OnEvent(ExtensionDidUninstalledEvent)
protected async onExtensionUninstalled() {
await this.updateExtHostData();
}
public async activate(): Promise<void> {
await this.initExtensionMetaData();
await this.initExtensionInstanceData();
await this.runEagerExtensionsContributes();
// update nls config by extensions
await this.setupExtensionNLSConfig();
this.doActivate();
// 监听页面展示状态,当页面状态变为可见且插件进程待重启的时候执行
const onPageVisibilitychange = () => {
this.logger.log(
'[ext-restart]: page visibility change, current:',
document.visibilityState,
'is waiting:',
this.isExtProcessWaitingForRestart,
'is restarting:',
this.isExtProcessRestarting,
);
if (
document.visibilityState === 'visible' &&
this.isExtProcessWaitingForRestart &&
!this.isExtProcessRestarting
) {
this.extProcessRestartHandler(this.isExtProcessWaitingForRestart);
}
};
document.addEventListener('visibilitychange', onPageVisibilitychange, false);
this.addDispose(
Disposable.create(() => {
document.removeEventListener('visibilitychange', onPageVisibilitychange);
}),
);
}
private async setupExtensionNLSConfig() {
const storagePath = (await this.extensionStoragePathServer.getLastStoragePath()) || '';
const currentLanguage: string = this.preferenceService.get(GeneralSettingsId.Language) || getLanguageId();
await this.extensionNodeClient.setupNLSConfig(currentLanguage, storagePath);
}
/**
* 初始化插件列表数据
* 包括插件目录和插件 Candidate
* 以及 ExtensionMetaData
*/
private async initExtensionMetaData() {
const { extensionDir, extensionCandidate } = this.appConfig;
if (extensionDir) {
this.extensionScanDir.add(extensionDir);
}
if (extensionCandidate) {
extensionCandidate.forEach((extension) => {
this.extensionCandidatePath.add(extension.path);
});
}
await this.getExtensionsMetaData(Array.from(this.extensionScanDir), Array.from(this.extensionCandidatePath));
}
/**
* 初始化插件实例数据
*/
private async initExtensionInstanceData() {
for (const extensionMetaData of this.extensionMetaDataArr) {
const isBuiltin = this.extensionInstanceManageService.checkIsBuiltin(extensionMetaData);
const isDevelopment = this.extensionInstanceManageService.checkIsDevelopment(extensionMetaData);
const extension = await this.extensionInstanceManageService.createExtensionInstance(
extensionMetaData,
isBuiltin,
isDevelopment,
);
if (extension) {
this.extensionInstanceManageService.addExtensionInstance(extension);
}
if (extension?.contributes && extension.enabled) {
this.contributesService.register(extension.id, extension.contributes);
this.sumiContributesService.register(extension.id, extension.packageJSON.sumiContributes || {});
}
}
this.eventBus.fire(new ExtensionsInitializedEvent(this.extensionInstanceManageService.getExtensionInstances()));
this.eventBus.fire(new DebugConfigurationsReadyEvent(undefined));
const extensionInstanceList = this.extensionInstanceManageService.getExtensionInstances();
this.nodeExtensionService.updateExtensionData(extensionInstanceList);
this.workerExtensionService.updateExtensionData(extensionInstanceList);
this.viewExtensionService.initExtension(extensionInstanceList);
}
private async doActivate() {
await this.workspaceService.whenReady;
await this.extensionStorageService.whenReady;
await this.viewExtensionService.activate();
// 启动插件进程
await this.startExtProcess(true);
try {
await this.eventBus.fireAndAwait(new ExtensionBeforeActivateEvent());
await this.activationEventService.fireEvent('*');
} catch (err) {
this.logger.error(`[Extension Activate Error], \n ${err.message || err}`);
} finally {
// 表示 * 的插件全部激活完了
this.eagerExtensionsActivated.resolve();
this.activationEventService.fireEvent('onStartupFinished');
// 表示 * 的插件可以调了
this.eventBus.fire(new ExtensionApiReadyEvent());
}
}
/**
* 重启插件进程
*/
public async restartExtProcess(restartPolicy: ERestartPolicy = ERestartPolicy.Always) {
/**
* 只有在页面可见的情况下才执行插件进程重启操作
* 如果当前页面不可见,那么 chrome 会对 socket 进行限流,导致进程重启的 rpc 调用得不到返回从而卡住
*/
if (document.visibilityState === 'visible') {
this.extProcessRestartHandler(restartPolicy);
} else {
this.logger.log('[ext-restart]: page is not visible, waiting for restart, policy:', restartPolicy);
this.isExtProcessWaitingForRestart = restartPolicy;
}
}
private extProcessRestartPromise: CancelablePromise<void> | undefined;
private disposeAllOverlayWindow() {
if (this.pCrashMessageModel) {
// crash message model is still open, close it
this.pCrashMessageModel.cancel?.();
this.pCrashMessageModel = undefined;
}
}
restartProgress = async (restartPolicy: ERestartPolicy = ERestartPolicy.Always) => {
const doRestart = async (token: CancellationToken) => {
this.disposeAllOverlayWindow();
token.onCancellationRequested(() => {
this.logger.log('[ext-restart]: ext process restart canceled');
this.isExtProcessRestarting = false;
this.isExtProcessWaitingForRestart = undefined;
this.isProgressShowing = false;
});
try {
await this.startExtProcess(false);
} catch (err) {
this.logger.error(`[ext-restart]: ext-host restart failure, error: ${err}`);
}
this.isExtProcessRestarting = false;
this.isExtProcessWaitingForRestart = undefined;
this.isProgressShowing = false;
this.disposeAllOverlayWindow();
};
await this.channelHandler.awaitChannelReady(RPCServiceChannelPath);
const policy = this.isExtProcessWaitingForRestart || restartPolicy;
this.logger.log('[ext-restart]: restart ext process, restart policy:', policy);
switch (policy) {
// @ts-expect-error Need fall-through
case ERestartPolicy.WhenExit:
// if we can get the pid, then the process is still running, no need to restart.
// if pid is null, it means the process is exited, then we need to start it.
if (await this.getExtProcessPID()) {
this.logger.log('[ext-restart]: ext process is still running, skip');
break;
}
case ERestartPolicy.Always:
if (this.isProgressShowing) {
this.logger.log('[ext-restart]: progress is already showing, skip');
return;
}
this.isProgressShowing = true;
await this.progressService.withProgress(
{
location: ProgressLocation.Notification,
title: localize('extension.exthostRestarting.content'),
buttons: [
{
id: 'extension.reload',
label: localize('preference.general.language.change.refresh.now'),
primary: true,
run: async () => {
this.clientApp.fireOnReload();
},
dispose: () => {},
},
],
},
async () => {
// doRestart 存在严重的副作用且不可 Cancel,因此单次重启只允许执行一次
this.extProcessRestartPromise = createCancelablePromise(doRestart);
await this.extProcessRestartPromise;
},
);
break;
}
this.isExtProcessRestarting = false;
};
restartDebounced = debounce(async () => {
await this.restartProgress();
}, 500);
private async extProcessRestartHandler(restartPolicy: ERestartPolicy = ERestartPolicy.Always) {
if (this.isExtProcessRestarting && restartPolicy !== ERestartPolicy.Always) {
this.logger.log('[ext-restart]: ext process is restarting, skip');
return;
}
this.isExtProcessRestarting = true;
if (this.isExtProcessWaitingForRestart) {
/**
* 只有当页面不可见的时候被通知执行重启操作,isExtProcessWaitingForRestart 才会为 true
* 目前观察到页面从不可见恢复至可见状态后,可能出现 socket 堆积的现象,因此延迟 1000ms 后再进行重启操作
* 这里延时并不能保证一定能够正确重启,只是降低失败的可能性。在解决了 socket 堆积的情况后,可以直接去掉
*/
this.restartDebounced();
} else {
this.restartProgress(restartPolicy);
}
}
private async getExtProcessPID(): Promise<number | null> {
return await Promise.race([
this.extensionNodeClient.pid().catch(async (err) => {
this.logger.error(`[ext-restart]: get ext process pid error, ${err}`);
await sleep(200);
return null;
}),
sleep(1000).then(() => null),
]);
}
private async startExtProcess(init: boolean) {
/**
* 重启插件进程步骤:
* 1、重置所有插件实例的状态至未激活
* 2、dispose 掉所有被激活且在 contributes 里申明过 browserView 的 sumi 插件
* 3、将负责前后端通信的 main.thread 全部 dispose 掉
* 4、杀掉后端插件进程
* 5、走正常激活插件流程,重新激活对应插件进程
* 6、将之前已经激活的插件重新激活一遍
*/
if (!init) {
this.resetExtensionInstances();
this.disposeSumiViewExtension();
await this.disposeExtProcess();
}
// set ready for node/worker
await Promise.all([this.startNodeExtHost(init), this.startWorkerExtHost(init)]);
if (!init) {
// 重启场景下需要将申明过 browserView 的 sumi 插件的 contributes 重新跑一遍
await this.rerunSumiViewExtensionContributes();
// 重启场景下把 ActivationEvent 再发一次
if (this.activationEventService.activatedEventSet.size) {
const activatedEventArr = Array.from(this.activationEventService.activatedEventSet);
this.activationEventService.activatedEventSet.clear();
await Promise.allSettled(
activatedEventArr.map((event) => {
const { topic, data } = JSON.parse(event);
this.logger.verbose('fireEvent', 'event.topic', topic, 'event.data', data);
return this.activationEventService.fireEvent(topic, data);
}),
);
}
}
}
private async startNodeExtHost(init: boolean) {
if (this.appConfig.noExtHost) {
return;
}
// 激活 node 插件进程
const protocol = await this.nodeExtensionService.activate();
this.extensionCommandManager.registerProxyCommandExecutor(
'node',
protocol.get(MainThreadAPIIdentifier.MainThreadCommands),
);
if (init) {
this.ready.set('node', this.nodeExtensionService.ready);
}
}
private async startWorkerExtHost(init: boolean) {
// 激活 worker 插件进程
if (!this.appConfig.extWorkerHost) {
return;
}
try {
const protocol = await this.workerExtensionService.activate(this.appConfig.ignoreWorkerHostCors);
this.extensionCommandManager.registerProxyCommandExecutor(
'worker',
protocol.get(MainThreadAPIIdentifier.MainThreadCommands),
);
if (init) {
this.ready.set('worker', this.workerExtensionService.ready);
}
} catch (err) {
this.logger.error(`Worker host activate fail, \n ${err.message}`);
}
}
/**
* 更新插件进程中插件的数据
*/
private async updateExtHostData() {
const extensions = this.extensionInstanceManageService.getExtensionInstances();
if (!this.appConfig.noExtHost) {
await this.nodeExtensionService.updateExtensionData(extensions);
}
if (this.appConfig.extWorkerHost) {
await this.workerExtensionService.updateExtensionData(extensions);
}
}
/**
* 发送 ActivationEvents
*/
private async fireActivationEventsIfNeed(activationEvents: string[]) {
if (!Array.isArray(activationEvents) || !activationEvents.length) {
return;
}
const startUpActivationEvents = ['*', 'onStartupFinished'];
const _activationEvents = activationEvents.filter((event) => event !== '*');
const shouldFireEvents = Array.from(this.activationEventService.activatedEventSet)
.map((event) => JSON.parse(event))
.filter(({ topic, data }) => _activationEvents.find((_event) => _event === `${topic}:${data}`));
for (const event of startUpActivationEvents) {
if (activationEvents.includes(event)) {
this.logger.verbose(`Fire activation event ${event}`);
this.activationEventService.fireEvent(event);
}
}
for (const event of shouldFireEvents) {
const { topic, data } = event;
this.logger.verbose(`Fire activation event ${topic}:${data}`);
this.activationEventService.fireEvent(topic, data);
}
await this.activateByWorkspaceContains(activationEvents);
}
private async activateByWorkspaceContains(activationEvents: string[]) {
if (!Array.isArray(activationEvents) || !activationEvents.length) {
return;
}
const paths: string[] = [];
const includePatterns: string[] = [];
for (const activationEvent of activationEvents) {
if (/^workspaceContains:/.test(activationEvent)) {
const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
includePatterns.push(fileNameOrGlob);
} else {
paths.push(fileNameOrGlob);
}
}
}
const promises: Promise<boolean>[] = [];
if (paths.length) {
promises.push(this.workspaceService.containsSome(paths));
}
if (includePatterns.length) {
promises.push(
(async () => {
try {
const result = await this.fileSearchService.find('', {
rootUris: this.workspaceService.tryGetRoots().map((stat) => new URI(stat.uri).codeUri.fsPath),
includePatterns,
limit: 1,
});
return result.length > 0;
} catch (e) {
this.logger.error(e);
return false;
}
})(),
);
}
if (promises.length && (await Promise.all(promises).then((exists) => exists.some((v) => v)))) {
this.activationEventService.fireEvent('workspaceContains', [...paths, ...includePatterns][0]);
}
}
/**
* 将插件的目录位置和文件位置,通过后端读取并缓存
* 返回所有插件的 meta data
*/
private async getExtensionsMetaData(
extensionScanDir: string[],
extensionCandidatePath: string[],
): Promise<IExtensionMetaData[]> {
if (!this.extensionMetaDataArr) {
const extensions = await this.extensionNodeClient.getAllExtensions(
extensionScanDir,
extensionCandidatePath,
getLanguageId(),
ExtensionServiceImpl.extraMetadata,
);
this.extensionMetaDataArr = extensions;
}
this.logger.log('extensions count:', this.extensionMetaDataArr.length);
return this.extensionMetaDataArr;
}
private async runEagerExtensionsContributes() {
await Promise.all([this.contributesService.initialize(), this.sumiContributesService.initialize()]);
this.commandRegistry.beforeExecuteCommand(async (command, args) => {
await this.activationEventService.fireEvent('onCommand', command);
return args;
});
this.eventBus.fire(new ExtensionDidContributes());
}
/**
* 激活插件的 Contributes
*/
public async runExtensionContributes() {
const extensions = Array.from(this.extensionInstanceManageService.getExtensionInstances() as Extension[]);
// try fire workspaceContains activateEvent ,这里不要 await
Promise.all(
extensions.map((extension) => this.activateByWorkspaceContains(extension.packageJSON.activationEvents)),
).catch((error) => this.logger.error(error));
}
/**
* 判断是否是 web 插件
* 这里会多增加一个判断:是否启动了 node-ext-host
* https://code.visualstudio.com/api/extension-guides/web-extensions#web-extension-enablement
*/
private whetherWebExtension({ packageJSON }: Extension): boolean {
const { browser, main } = packageJSON || {};
const noExtHost = Boolean(this.appConfig.noExtHost);
// 如果只包含 browser 入口
if (browser && !main) {
return true;
}
// 如果同时包含两个入口,那么判断是否启动了node插件进程
if (browser && main) {
return noExtHost;
}
// 只包含 main 入
if (!browser && main) {
return false;
}
/**
* 都不包含的情况下:
* 如果contributes中含有'debuggers', 'terminal', 'typescriptServerPlugins'三个之一,那么不作为web插件启动
* 如果不包含,那么判断是否启动了node插件进程
*/
if (typeof packageJSON.contributes !== 'undefined') {
for (const id of ['debuggers', 'terminal', 'typescriptServerPlugins']) {
if (packageJSON.contributes.hasOwnProperty(id)) {
return false;
}
}
}
return noExtHost;
}
/**
* 给 Extension 使用 | 激活插件
*/
public async activeExtension(extension: Extension) {
const isWebExtension = this.whetherWebExtension(extension);
if (isWebExtension && !this.appConfig.extWorkerHost) {
this.logger.error('[extension.service]: has no ext worker host');
}
// 优先激活 Node 和 Worker 进程中的插件
// 这个时序下,不允许存在 Node/Worker 互相依赖的情况
// 插件 Browser 中可以依赖 Node/Worker
await Promise.all([
this.nodeExtensionService.activeExtension(extension, isWebExtension),
this.workerExtensionService.activeExtension(extension, isWebExtension),
]);
await this.viewExtensionService.activeExtension(extension, this.nodeExtensionService.protocol);
this.eventBus.fire(new ExtensionActivatedEvent({ topic: 'onExtensionActivated', data: { id: extension.id } }));
}
private resetExtensionInstances() {
this.extensionInstanceManageService.resetExtensionInstances();
this.nodeExtensionService.disposeApiFactory();
this.workerExtensionService.disposeApiFactory();
}
/**
* 每次激活 sumi 插件的时候,都会尝试去激活 sumiContributes 中的 browserView,会导致 browserView 重复注册
* 因此重启场景下需要先将这部分被激活的插件 dispose 掉
*/
private disposeSumiViewExtension() {
const paths = Array.from(this.viewExtensionService.activatedViewExtensionMap.keys());
this.extensionInstanceManageService.disposeExtensionInstancesByPath(paths);
}
private async rerunSumiViewExtensionContributes() {
const { activatedViewExtensionMap } = this.viewExtensionService;
const extensionPaths = Array.from(activatedViewExtensionMap.keys());
await Promise.all(
extensionPaths.map((path) => {
const extension = this.extensionInstanceManageService.getExtensionInstanceByPath(path);
if (extension) {
extension.initialize();
this.sumiContributesService.register(extension.id, extension.packageJSON.sumiContributes || {});
}
}),
);
activatedViewExtensionMap.clear();
await Promise.all([this.contributesService.initialize(), this.sumiContributesService.initialize()]);
}
async disposeExtProcess() {
await this.nodeExtensionService.disposeProcess();
await this.workerExtensionService.disposeProcess();
}
public async disposeExtensions() {
// 重置掉插件实例
this.extensionInstanceManageService.disposeExtensionInstances();
}
// 给 contributes#command 注册 command executor 使用
public async executeExtensionCommand(command: string, args: any[]): Promise<void> {
const targetEnv = this.extensionCommandManager.getExtensionCommandEnv(command);
if (!targetEnv) {
throw new Error('No Command with id "' + command + '" is declared by extensions');
}
// 需要等待对应插件进程启动完成再执行指令
await this.ready.get(targetEnv)?.promise;
// 这里相比之前有个变化,之前是先找 command 存不存在,然后等 ready 再执行
// 现在是先等 ready 再去找 command 再去执行
return this.extensionCommandManager.executeExtensionCommand(targetEnv, command, args);
}
// 暴露给后端调用前端时使用,用来处理插件进程不存在和 crash/restart 时的弹窗
private get invalidReloadStrategy() {
// 获取corePreferences配置判断是否弹出确认框
return this.corePreferences['application.invalidExthostReload'];
}
// RPC call from node
public async $restartExtProcess() {
this.logger.log('[ext-restart]: receive the command from the node side to restart the process');
await this.restartExtProcess(ERestartPolicy.Always);
}
public async $processNotExist() {
// if browser receive the message, means the connection is keep alive
// so we still need to restart the ext process
this.logger.log('[ext-restart]: receive the command from the node side that the process does not exist');
this.$restartExtProcess();
return 'ok';
}
public async showReloadWindow() {
const okText = localize('extension.invalidExthostReload.confirm.ok');
const options = [okText];
const ifRequiredReload = this.invalidReloadStrategy === 'ifRequired';
if (ifRequiredReload) {
options.unshift(localize('extension.invalidExthostReload.confirm.cancel'));
}
const msg = await this.dialogService.info(
localize('extension.invalidExthostReload.confirm.content'),
options,
!!ifRequiredReload,
);
if (msg === okText) {
this.clientApp.fireOnReload();
}
}
public async $processCrashRestart() {
if (this.pCrashMessageModel) {
this.pCrashMessageModel.cancel?.();
}
const okText = localize('common.yes');
const options = [okText];
const ifRequiredReload = this.invalidReloadStrategy === 'ifRequired';
if (ifRequiredReload) {
options.unshift(localize('common.no'));
}
this.pCrashMessageModel = this.messageService.info(
localize('extension.crashedExthostReload.confirm'),
options,
!!ifRequiredReload,
);
const msg = await this.pCrashMessageModel;
this.pCrashMessageModel = undefined;
if (msg === okText) {
await this.restartExtProcess(ERestartPolicy.Always);
}
}
}