-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathtypingInstallerAdapter.ts
255 lines (234 loc) · 10.4 KB
/
typingInstallerAdapter.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
import {
ApplyCodeActionCommandResult,
assertType,
createQueue,
Debug,
JsTyping,
MapLike,
server,
SortedReadonlyArray,
TypeAcquisition,
} from "./_namespaces/ts.js";
import {
ActionInvalidate,
ActionPackageInstalled,
ActionSet,
ActionWatchTypingLocations,
BeginInstallTypes,
createInstallTypingsRequest,
DiscoverTypings,
EndInstallTypes,
Event,
EventBeginInstallTypes,
EventEndInstallTypes,
EventInitializationFailed,
EventTypesRegistry,
InitializationFailedResponse,
InstallPackageOptionsWithProject,
InstallPackageRequest,
InvalidateCachedTypings,
ITypingsInstaller,
Logger,
LogLevel,
PackageInstalledResponse,
Project,
ProjectService,
protocol,
ServerHost,
SetTypings,
stringifyIndented,
TypesRegistryResponse,
TypingInstallerRequestUnion,
} from "./_namespaces/ts.server.js";
/** @internal */
export interface TypingsInstallerWorkerProcess {
send<T extends TypingInstallerRequestUnion>(rq: T): void;
}
interface PackageInstallPromise {
resolve(value: ApplyCodeActionCommandResult): void;
reject(reason: unknown): void;
}
/** @internal */
export abstract class TypingsInstallerAdapter implements ITypingsInstaller {
protected installer!: TypingsInstallerWorkerProcess;
private projectService!: ProjectService;
protected activeRequestCount = 0;
private requestQueue = createQueue<DiscoverTypings>();
private requestMap = new Map<string, DiscoverTypings>(); // Maps project name to newest requestQueue entry for that project
/** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */
private requestedRegistry = false;
private typesRegistryCache: Map<string, MapLike<string>> | undefined;
// This number is essentially arbitrary. Processing more than one typings request
// at a time makes sense, but having too many in the pipe results in a hang
// (see https://github.com/nodejs/node/issues/7657).
// It would be preferable to base our limit on the amount of space left in the
// buffer, but we have yet to find a way to retrieve that value.
private static readonly requestDelayMillis = 100;
private packageInstalledPromise: Map<number, PackageInstallPromise> | undefined;
private packageInstallId = 0;
constructor(
protected readonly telemetryEnabled: boolean,
protected readonly logger: Logger,
protected readonly host: ServerHost,
readonly globalTypingsCacheLocation: string,
protected event: Event,
private readonly maxActiveRequestCount: number,
) {
}
isKnownTypesPackageName(name: string): boolean {
// We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package.
const validationResult = JsTyping.validatePackageName(name);
if (validationResult !== JsTyping.NameValidationResult.Ok) {
return false;
}
if (!this.requestedRegistry) {
this.requestedRegistry = true;
this.installer.send({ kind: "typesRegistry" });
}
return !!this.typesRegistryCache?.has(name);
}
installPackage(options: InstallPackageOptionsWithProject): Promise<ApplyCodeActionCommandResult> {
this.packageInstallId++;
const request: InstallPackageRequest = { kind: "installPackage", ...options, id: this.packageInstallId };
const promise = new Promise<ApplyCodeActionCommandResult>((resolve, reject) => {
(this.packageInstalledPromise ??= new Map()).set(this.packageInstallId, { resolve, reject });
});
this.installer.send(request);
return promise;
}
attach(projectService: ProjectService): void {
this.projectService = projectService;
this.installer = this.createInstallerProcess();
}
onProjectClosed(p: Project): void {
this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" });
}
enqueueInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>): void {
const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`TIAdapter:: Scheduling throttled operation:${stringifyIndented(request)}`);
}
if (this.activeRequestCount < this.maxActiveRequestCount) {
this.scheduleRequest(request);
}
else {
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`TIAdapter:: Deferring request for: ${request.projectName}`);
}
this.requestQueue.enqueue(request);
this.requestMap.set(request.projectName, request);
}
}
handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse | server.WatchTypingLocations): void {
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`TIAdapter:: Received response:${stringifyIndented(response)}`);
}
switch (response.kind) {
case EventTypesRegistry:
this.typesRegistryCache = new Map(Object.entries(response.typesRegistry));
break;
case ActionPackageInstalled: {
const promise = this.packageInstalledPromise?.get(response.id);
Debug.assertIsDefined(promise, "Should find the promise for package install");
this.packageInstalledPromise?.delete(response.id);
if (response.success) {
promise.resolve({ successMessage: response.message });
}
else {
promise.reject(response.message);
}
this.projectService.updateTypingsForProject(response);
// The behavior is the same as for setTypings, so send the same event.
this.event(response, "setTypings");
break;
}
case EventInitializationFailed: {
const body: protocol.TypesInstallerInitializationFailedEventBody = {
message: response.message,
};
const eventName: protocol.TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed";
this.event(body, eventName);
break;
}
case EventBeginInstallTypes: {
const body: protocol.BeginInstallTypesEventBody = {
eventId: response.eventId,
packages: response.packagesToInstall,
};
const eventName: protocol.BeginInstallTypesEventName = "beginInstallTypes";
this.event(body, eventName);
break;
}
case EventEndInstallTypes: {
if (this.telemetryEnabled) {
const body: protocol.TypingsInstalledTelemetryEventBody = {
telemetryEventName: "typingsInstalled",
payload: {
installedPackages: response.packagesToInstall.join(","),
installSuccess: response.installSuccess,
typingsInstallerVersion: response.typingsInstallerVersion,
},
};
const eventName: protocol.TelemetryEventName = "telemetry";
this.event(body, eventName);
}
const body: protocol.EndInstallTypesEventBody = {
eventId: response.eventId,
packages: response.packagesToInstall,
success: response.installSuccess,
};
const eventName: protocol.EndInstallTypesEventName = "endInstallTypes";
this.event(body, eventName);
break;
}
case ActionInvalidate: {
this.projectService.updateTypingsForProject(response);
break;
}
case ActionSet: {
if (this.activeRequestCount > 0) {
this.activeRequestCount--;
}
else {
Debug.fail("TIAdapter:: Received too many responses");
}
while (!this.requestQueue.isEmpty()) {
const queuedRequest = this.requestQueue.dequeue();
if (this.requestMap.get(queuedRequest.projectName) === queuedRequest) {
this.requestMap.delete(queuedRequest.projectName);
this.scheduleRequest(queuedRequest);
break;
}
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`TIAdapter:: Skipping defunct request for: ${queuedRequest.projectName}`);
}
}
this.projectService.updateTypingsForProject(response);
this.event(response, "setTypings");
break;
}
case ActionWatchTypingLocations:
this.projectService.watchTypingLocations(response);
break;
default:
assertType<never>(response);
}
}
scheduleRequest(request: DiscoverTypings): void {
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`TIAdapter:: Scheduling request for: ${request.projectName}`);
}
this.activeRequestCount++;
this.host.setTimeout(
() => {
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`TIAdapter:: Sending request:${stringifyIndented(request)}`);
}
this.installer.send(request);
},
TypingsInstallerAdapter.requestDelayMillis,
`${request.projectName}::${request.kind}`,
);
}
protected abstract createInstallerProcess(): TypingsInstallerWorkerProcess;
}