Skip to content

Commit 641c2ff

Browse files
committed
introduce ThrottledOperations
1 parent cad8049 commit 641c2ff

5 files changed

Lines changed: 126 additions & 104 deletions

File tree

‎src/server/editorServices.ts‎

Lines changed: 43 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,6 @@ namespace ts.server {
108108
currentPath = parentPath;
109109
parentPath = getDirectoryPath(parentPath);
110110
}
111-
112111
}
113112
}
114113

@@ -139,21 +138,21 @@ namespace ts.server {
139138
/**
140139
* list of open files
141140
*/
142-
openFiles: ScriptInfo[] = [];
141+
readonly openFiles: ScriptInfo[] = [];
143142

144143
private readonly directoryWatchers: DirectoryWatchers;
144+
private readonly throttledOperations: ThrottledOperations;
145145

146146
private readonly hostConfiguration: HostConfiguration;
147147

148-
private timerForDetectingProjectFileListChanges: Map<any> = {};
149-
150148
constructor(public readonly host: ServerHost,
151149
public readonly logger: Logger,
152150
public readonly cancellationToken: HostCancellationToken,
153-
private readonly useOneInferredProject: boolean,
151+
private readonly useSingleInferredProject: boolean,
154152
private readonly eventHandler?: ProjectServiceEventHandler) {
155153

156154
this.directoryWatchers = new DirectoryWatchers(this);
155+
this.throttledOperations = new ThrottledOperations(host);
157156
// ts.disableIncrementalParsing = true;
158157

159158
this.hostConfiguration = {
@@ -243,14 +242,10 @@ namespace ts.server {
243242
}
244243

245244
this.log(`Detected source file changes: ${fileName}`);
246-
const timeoutId = this.timerForDetectingProjectFileListChanges[project.configFileName];
247-
if (timeoutId) {
248-
this.host.clearTimeout(timeoutId);
249-
}
250-
this.timerForDetectingProjectFileListChanges[project.configFileName] = this.host.setTimeout(
251-
() => this.handleChangeInSourceFileForConfiguredProject(project),
252-
250
253-
);
245+
this.throttledOperations.schedule(
246+
project.configFileName,
247+
250,
248+
() => this.handleChangeInSourceFileForConfiguredProject(project));
254249
}
255250

256251
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject) {
@@ -357,7 +352,7 @@ namespace ts.server {
357352
// create new inferred project p with the newly opened file as root
358353
// or add root to existing inferred project if 'useOneInferredProject' is true
359354
const inferredProject = this.createInferredProjectWithRootFileIfNecessary(info);
360-
if (!this.useOneInferredProject) {
355+
if (!this.useSingleInferredProject) {
361356

362357
// if useOneInferredProject is not set then try to fixup ownership of open files
363358
for (const f of this.openFiles) {
@@ -755,7 +750,7 @@ namespace ts.server {
755750
}
756751

757752
createInferredProjectWithRootFileIfNecessary(root: ScriptInfo) {
758-
const useExistingProject = this.useOneInferredProject && this.inferredProjects.length;
753+
const useExistingProject = this.useSingleInferredProject && this.inferredProjects.length;
759754
const project = useExistingProject
760755
? this.inferredProjects[0]
761756
: new InferredProject(this, this.documentRegistry, /*languageServiceEnabled*/ true);
@@ -1004,42 +999,42 @@ namespace ts.server {
1004999
// this.openFilesReferenced.push(rootFile);
10051000
// }
10061001
// }
1007-
// if (rootFile.containingProjects.some(p => p.projectKind !== ProjectKind.Inferred)) {
1008-
// // file was included in non-inferred project - drop old inferred project
1002+
// if (rootFile.containingProjects.some(p => p.projectKind !== ProjectKind.Inferred)) {
1003+
// // file was included in non-inferred project - drop old inferred project
10091004

1010-
// }
1011-
// else {
1012-
// openFileRoots.push(rootFile);
1013-
// }
1014-
// let inferredProjectsToRemove: Project[];
1015-
// for (const p of rootFile.containingProjects) {
1016-
// if (p.projectKind !== ProjectKind.Inferred) {
1017-
// // file was included in non-inferred project - drop old inferred project
1018-
// }
1019-
// }
1005+
// }
1006+
// else {
1007+
// openFileRoots.push(rootFile);
1008+
// }
1009+
// let inferredProjectsToRemove: Project[];
1010+
// for (const p of rootFile.containingProjects) {
1011+
// if (p.projectKind !== ProjectKind.Inferred) {
1012+
// // file was included in non-inferred project - drop old inferred project
1013+
// }
1014+
// }
10201015

1021-
// const rootedProject = rootFile.defaultProject;
1022-
// const referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
1016+
// const rootedProject = rootFile.defaultProject;
1017+
// const referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
10231018

1024-
// if (rootFile.defaultProject && rootFile.defaultProject.projectKind !== ProjectKind.Inferred) {
1025-
// // If the root file has already been added into a configured project,
1026-
// // meaning the original inferred project is gone already.
1027-
// if (rootedProject.projectKind === ProjectKind.Inferred) {
1028-
// this.removeProject(rootedProject);
1029-
// }
1030-
// this.openFileRootsConfigured.push(rootFile);
1031-
// }
1032-
// else {
1033-
// if (referencingProjects.length === 0) {
1034-
// rootFile.defaultProject = rootedProject;
1035-
// openFileRoots.push(rootFile);
1036-
// }
1037-
// else {
1038-
// // remove project from inferred projects list because root captured
1039-
// this.removeProject(rootedProject);
1040-
// this.openFilesReferenced.push(rootFile);
1041-
// }
1042-
// }
1019+
// if (rootFile.defaultProject && rootFile.defaultProject.projectKind !== ProjectKind.Inferred) {
1020+
// // If the root file has already been added into a configured project,
1021+
// // meaning the original inferred project is gone already.
1022+
// if (rootedProject.projectKind === ProjectKind.Inferred) {
1023+
// this.removeProject(rootedProject);
1024+
// }
1025+
// this.openFileRootsConfigured.push(rootFile);
1026+
// }
1027+
// else {
1028+
// if (referencingProjects.length === 0) {
1029+
// rootFile.defaultProject = rootedProject;
1030+
// openFileRoots.push(rootFile);
1031+
// }
1032+
// else {
1033+
// // remove project from inferred projects list because root captured
1034+
// this.removeProject(rootedProject);
1035+
// this.openFilesReferenced.push(rootFile);
1036+
// }
1037+
// }
10431038
// }
10441039
// this.openFileRoots = openFileRoots;
10451040

‎src/server/server.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,8 @@ namespace ts.server {
9191
}
9292

9393
class IOSession extends Session {
94-
constructor(host: ServerHost, cancellationToken: HostCancellationToken, useOneInferredProject: boolean, logger: ts.server.Logger) {
95-
super(host, cancellationToken, useOneInferredProject, Buffer.byteLength, process.hrtime, logger);
94+
constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, logger: ts.server.Logger) {
95+
super(host, cancellationToken, useSingleInferredProject, Buffer.byteLength, process.hrtime, logger);
9696
}
9797

9898
exit() {
@@ -304,8 +304,8 @@ namespace ts.server {
304304
};
305305
};
306306

307-
const useOneInferredProject = sys.args.some(arg => arg === "--useOneInferredProject");
308-
const ioSession = new IOSession(sys, cancellationToken, useOneInferredProject, logger);
307+
const useSingleInferredProject = sys.args.some(arg => arg === "--useSingleInferredProject");
308+
const ioSession = new IOSession(sys, cancellationToken, useSingleInferredProject, logger);
309309
process.on("uncaughtException", function(err: Error) {
310310
ioSession.logError(err, "unknown");
311311
});

‎src/server/session.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,12 @@ namespace ts.server {
179179
constructor(
180180
private host: ServerHost,
181181
cancellationToken: HostCancellationToken,
182-
useOneInferredProject: boolean,
182+
useSingleInferredProject: boolean,
183183
private byteLength: (buf: string, encoding?: string) => number,
184184
private hrtime: (start?: number[]) => number[],
185185
private logger: Logger) {
186186
this.projectService =
187-
new ProjectService(host, logger, cancellationToken, useOneInferredProject, (eventName, project, fileName) => {
187+
new ProjectService(host, logger, cancellationToken, useSingleInferredProject, (eventName, project, fileName) => {
188188
this.handleEvent(eventName, project, fileName);
189189
});
190190
}

‎src/server/utilities.ts‎

Lines changed: 62 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
/// <reference path="..\services\services.ts" />
22

3-
/* tslint:disable:no-null-keyword */
4-
53
namespace ts.server {
64
export interface Logger {
75
close(): void;
@@ -74,14 +72,16 @@ namespace ts.server {
7472
}
7573

7674
export interface NormalizedPathMap<T> {
77-
get (path: NormalizedPath): T;
78-
set (path: NormalizedPath, value: T): void;
75+
get(path: NormalizedPath): T;
76+
set(path: NormalizedPath, value: T): void;
7977
contains(path: NormalizedPath): boolean;
8078
remove(path: NormalizedPath): void;
8179
}
8280

8381
export function createNormalizedPathMap<T>(): NormalizedPathMap<T> {
82+
/* tslint:disable:no-null-keyword */
8483
const map: Map<T> = Object.create(null);
84+
/* tslint:enable:no-null-keyword */
8585
return {
8686
get(path) {
8787
return map[path];
@@ -97,48 +97,49 @@ namespace ts.server {
9797
}
9898
};
9999
}
100-
function throwLanguageServiceIsDisabledError() {;
100+
function throwLanguageServiceIsDisabledError() {
101+
;
101102
throw new Error("LanguageService is disabled");
102103
}
103104

104105
export const nullLanguageService: LanguageService = {
105-
cleanupSemanticCache: (): any => throwLanguageServiceIsDisabledError(),
106-
getSyntacticDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
107-
getSemanticDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
108-
getCompilerOptionsDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
109-
getSyntacticClassifications: (): any => throwLanguageServiceIsDisabledError(),
106+
cleanupSemanticCache: (): any => throwLanguageServiceIsDisabledError(),
107+
getSyntacticDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
108+
getSemanticDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
109+
getCompilerOptionsDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
110+
getSyntacticClassifications: (): any => throwLanguageServiceIsDisabledError(),
110111
getEncodedSyntacticClassifications: (): any => throwLanguageServiceIsDisabledError(),
111-
getSemanticClassifications: (): any => throwLanguageServiceIsDisabledError(),
112-
getEncodedSemanticClassifications: (): any => throwLanguageServiceIsDisabledError(),
113-
getCompletionsAtPosition: (): any => throwLanguageServiceIsDisabledError(),
114-
findReferences: (): any => throwLanguageServiceIsDisabledError(),
115-
getCompletionEntryDetails: (): any => throwLanguageServiceIsDisabledError(),
116-
getQuickInfoAtPosition: (): any => throwLanguageServiceIsDisabledError(),
117-
findRenameLocations: (): any => throwLanguageServiceIsDisabledError(),
118-
getNameOrDottedNameSpan: (): any => throwLanguageServiceIsDisabledError(),
119-
getBreakpointStatementAtPosition: (): any => throwLanguageServiceIsDisabledError(),
120-
getBraceMatchingAtPosition: (): any => throwLanguageServiceIsDisabledError(),
121-
getSignatureHelpItems: (): any => throwLanguageServiceIsDisabledError(),
122-
getDefinitionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
123-
getRenameInfo: (): any => throwLanguageServiceIsDisabledError(),
124-
getTypeDefinitionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
125-
getReferencesAtPosition: (): any => throwLanguageServiceIsDisabledError(),
126-
getDocumentHighlights: (): any => throwLanguageServiceIsDisabledError(),
127-
getOccurrencesAtPosition: (): any => throwLanguageServiceIsDisabledError(),
128-
getNavigateToItems: (): any => throwLanguageServiceIsDisabledError(),
129-
getNavigationBarItems: (): any => throwLanguageServiceIsDisabledError(),
130-
getOutliningSpans: (): any => throwLanguageServiceIsDisabledError(),
131-
getTodoComments: (): any => throwLanguageServiceIsDisabledError(),
132-
getIndentationAtPosition: (): any => throwLanguageServiceIsDisabledError(),
133-
getFormattingEditsForRange: (): any => throwLanguageServiceIsDisabledError(),
134-
getFormattingEditsForDocument: (): any => throwLanguageServiceIsDisabledError(),
135-
getFormattingEditsAfterKeystroke: (): any => throwLanguageServiceIsDisabledError(),
136-
getDocCommentTemplateAtPosition: (): any => throwLanguageServiceIsDisabledError(),
137-
isValidBraceCompletionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
138-
getEmitOutput: (): any => throwLanguageServiceIsDisabledError(),
139-
getProgram: (): any => throwLanguageServiceIsDisabledError(),
140-
getNonBoundSourceFile: (): any => throwLanguageServiceIsDisabledError(),
141-
dispose: (): any => throwLanguageServiceIsDisabledError(),
112+
getSemanticClassifications: (): any => throwLanguageServiceIsDisabledError(),
113+
getEncodedSemanticClassifications: (): any => throwLanguageServiceIsDisabledError(),
114+
getCompletionsAtPosition: (): any => throwLanguageServiceIsDisabledError(),
115+
findReferences: (): any => throwLanguageServiceIsDisabledError(),
116+
getCompletionEntryDetails: (): any => throwLanguageServiceIsDisabledError(),
117+
getQuickInfoAtPosition: (): any => throwLanguageServiceIsDisabledError(),
118+
findRenameLocations: (): any => throwLanguageServiceIsDisabledError(),
119+
getNameOrDottedNameSpan: (): any => throwLanguageServiceIsDisabledError(),
120+
getBreakpointStatementAtPosition: (): any => throwLanguageServiceIsDisabledError(),
121+
getBraceMatchingAtPosition: (): any => throwLanguageServiceIsDisabledError(),
122+
getSignatureHelpItems: (): any => throwLanguageServiceIsDisabledError(),
123+
getDefinitionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
124+
getRenameInfo: (): any => throwLanguageServiceIsDisabledError(),
125+
getTypeDefinitionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
126+
getReferencesAtPosition: (): any => throwLanguageServiceIsDisabledError(),
127+
getDocumentHighlights: (): any => throwLanguageServiceIsDisabledError(),
128+
getOccurrencesAtPosition: (): any => throwLanguageServiceIsDisabledError(),
129+
getNavigateToItems: (): any => throwLanguageServiceIsDisabledError(),
130+
getNavigationBarItems: (): any => throwLanguageServiceIsDisabledError(),
131+
getOutliningSpans: (): any => throwLanguageServiceIsDisabledError(),
132+
getTodoComments: (): any => throwLanguageServiceIsDisabledError(),
133+
getIndentationAtPosition: (): any => throwLanguageServiceIsDisabledError(),
134+
getFormattingEditsForRange: (): any => throwLanguageServiceIsDisabledError(),
135+
getFormattingEditsForDocument: (): any => throwLanguageServiceIsDisabledError(),
136+
getFormattingEditsAfterKeystroke: (): any => throwLanguageServiceIsDisabledError(),
137+
getDocCommentTemplateAtPosition: (): any => throwLanguageServiceIsDisabledError(),
138+
isValidBraceCompletionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
139+
getEmitOutput: (): any => throwLanguageServiceIsDisabledError(),
140+
getProgram: (): any => throwLanguageServiceIsDisabledError(),
141+
getNonBoundSourceFile: (): any => throwLanguageServiceIsDisabledError(),
142+
dispose: (): any => throwLanguageServiceIsDisabledError(),
142143
};
143144

144145
export interface ServerLanguageServiceHost {
@@ -172,4 +173,24 @@ namespace ts.server {
172173
export function makeInferredProjectName(counter: number) {
173174
return `/dev/null/inferredProject${counter}*`;
174175
}
176+
177+
export class ThrottledOperations {
178+
private pendingTimeouts: Map<any> = {};
179+
constructor(private readonly host: ServerHost) {
180+
}
181+
182+
public schedule(operationId: string, delay: number, cb: () => void) {
183+
if (hasProperty(this.pendingTimeouts, operationId)) {
184+
// another operation was already scheduled for this id - cancel it
185+
this.host.clearTimeout(this.pendingTimeouts[operationId]);
186+
}
187+
// schedule new operation, pass arguments
188+
this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb);
189+
}
190+
191+
private static run(self: ThrottledOperations, operationId: string, cb: () => void) {
192+
delete self.pendingTimeouts[operationId];
193+
cb();
194+
}
195+
}
175196
}

‎tests/cases/unittests/tsserverProjectSystem.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,10 @@ namespace ts {
145145
private fs: ts.FileMap<FSEntry>;
146146
private getCanonicalFileName: (s: string) => string;
147147
private toPath: (f: string) => Path;
148-
private callbackQueue: TimeOutCallback[] = [];
148+
149+
private nextTimeoutId = 0;
150+
private callbacks: { [n: number]: TimeOutCallback } = {};
151+
149152
readonly watchedDirectories: Map<{ cb: DirectoryWatcherCallback, recursive: boolean }[]> = {};
150153
readonly watchedFiles: Map<FileWatcherCallback[]> = {};
151154

@@ -283,25 +286,28 @@ namespace ts {
283286
}
284287

285288
// TOOD: record and invoke callbacks to simulate timer events
286-
readonly setTimeout = (callback: TimeOutCallback, time: number) => {
287-
this.callbackQueue.push(callback);
288-
return this.callbackQueue.length - 1;
289+
readonly setTimeout = (callback: TimeOutCallback, time: number, ...args: any[]) => {
290+
const timeoutId = this.nextTimeoutId;
291+
this.nextTimeoutId++;
292+
this.callbacks[timeoutId] = callback.bind(undefined, ...args);
293+
return timeoutId;
289294
};
290295
readonly clearTimeout = (timeoutId: any): void => {
291296
if (typeof timeoutId === "number") {
292-
this.callbackQueue.splice(timeoutId, 1);
297+
delete this.callbacks[timeoutId];
293298
}
294299
};
295300

296301
checkTimeoutQueueLength(expected: number) {
297-
assert.equal(this.callbackQueue.length, expected, `expected ${expected} timeout callbacks queued but found ${this.callbackQueue.length}.`);
302+
const callbacksCount = sizeOfMap(this.callbacks);
303+
assert.equal(callbacksCount, expected, `expected ${expected} timeout callbacks queued but found ${callbacksCount}.`);
298304
}
299305

300306
runQueuedTimeoutCallbacks() {
301-
for (const callback of this.callbackQueue) {
302-
callback();
307+
for (const id in this.callbacks) {
308+
this.callbacks[id]();
303309
}
304-
this.callbackQueue = [];
310+
this.callbacks = [];
305311
}
306312

307313
readonly readFile = (s: string) => (<File>this.fs.get(this.toPath(s))).content;

0 commit comments

Comments
 (0)