diff --git a/Extension/src/LanguageServer/client.ts b/Extension/src/LanguageServer/client.ts index b370188f7..2eb7cb3ae 100644 --- a/Extension/src/LanguageServer/client.ts +++ b/Extension/src/LanguageServer/client.ts @@ -64,8 +64,10 @@ import { RequestCancelled, ServerCancelled, createProtocolFilter } from './proto import * as refs from './references'; import { CppSettings, OtherSettings, SettingsParams, WorkspaceFolderSettingsParams } from './settings'; import { SettingsTracker } from './settingsTracker'; +import { StuckInitializationNotice } from './stuckInitializationNotice'; import { ConfigurationType, LanguageStatusUI, getUI } from './ui'; import { handleChangedFromCppToC, makeLspRange, makeVscodeLocation, makeVscodeRange, withCancellation } from './utils'; +import { CrashAction, maxConsecutiveInitializationCrashes, stuckInitializingNoticeDelayMs, WorkspaceInitializationMonitor } from './workspaceInitializationMonitor'; import minimatch = require("minimatch"); function deepCopy(obj: any) { @@ -90,7 +92,23 @@ const languageClient: LanguageClient = new LanguageClient(); let firstClientStarted: Promise<{ wasShutdown: boolean }>; let languageClientHasCrashed: boolean = false; let languageClientCrashedNeedsRestart: boolean = false; -const languageClientCrashTimes: number[] = []; +// The key is not shared with the excessive files warning: dismissing one message says nothing about the other. +const showStuckInitializationNoticeKey: string = 'CPP.showStuckInitializationNotice'; +const stuckInitializationNotice: StuckInitializationNotice = new StuckInitializationNotice({ + appendLine: (message: string) => getOutputChannelLogger().appendLine(message), + showInformationMessage: (message: string, ...items: string[]) => vscode.window.showInformationMessage(message, ...items), + openLearnMore: () => void vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://go.microsoft.com/fwlink/?linkid=2333292')), + isSuppressed: () => !new PersistentWorkspaceState(showStuckInitializationNoticeKey, true).Value, + suppress: () => { new PersistentWorkspaceState(showStuckInitializationNoticeKey, true).Value = false; } +}); +const workspaceInitializationMonitor: WorkspaceInitializationMonitor = new WorkspaceInitializationMonitor(() => { + void stuckInitializationNotice.notify( + localize('workspace.initialization.stuck', + 'The C/C++ extension has been initializing this workspace for more than {0} minutes. If the workspace is very large or contains symbolic links that lead back into it, excluding folders with the "C_Cpp.files.exclude" setting may help.', + stuckInitializingNoticeDelayMs / 60000), + localize('learn.more', 'Learn More'), + localize('dont.show.again', 'Don\'t Show Again')).catch(logAndReturn.undefined); +}); let compilerDefaults: configs.CompilerDefaults | undefined; let diagnosticsCollectionIntelliSense: vscode.DiagnosticCollection; let diagnosticsCollectionRefactor: vscode.DiagnosticCollection; @@ -1730,21 +1748,10 @@ export class DefaultClient implements Client { error: (_error, _message, _count) => ({ action: ErrorAction.Continue }), closed: () => { languageClientHasCrashed = true; - languageClientCrashTimes.push(Date.now()); languageClientCrashedNeedsRestart = true; - let restart: boolean = true; - if (languageClientCrashTimes.length < 5) { - void clients.recreateClients(); - } else { - const elapsed: number = languageClientCrashTimes[languageClientCrashTimes.length - 1] - languageClientCrashTimes[0]; - if (elapsed <= 3 * 60 * 1000) { - void clients.recreateClients(true); - restart = false; - } else { - languageClientCrashTimes.shift(); - void clients.recreateClients(); - } - } + const crashAction: CrashAction = workspaceInitializationMonitor.serverCrashed(Date.now()); + const restart: boolean = crashAction === CrashAction.Restart; + void clients.recreateClients(!restart); // Wait 1 second to allow time for the file watcher to signal a crash call stack write has occurred. setTimeout(() => { @@ -1767,7 +1774,10 @@ export class DefaultClient implements Client { }, 1000); const message: string = restart ? localize('server.crashed.restart', 'The language server crashed. Restarting...') - : localize('server.crashed2', 'The language server crashed 5 times in the last 3 minutes. It will not be restarted.'); + : crashAction === CrashAction.StopCrashedTooOften ? localize('server.crashed2', 'The language server crashed 5 times in the last 3 minutes. It will not be restarted.') + : localize('server.crashed3', + 'The language server crashed {0} times in a row while initializing the workspace. It will not be restarted. If the workspace is very large or contains symbolic links that lead back into it, excluding folders with the "C_Cpp.files.exclude" setting may help.', + maxConsecutiveInitializationCrashes); // We manually restart the language server so tell the LanguageClient not to do it automatically for us. return { action: CloseAction.DoNotRestart, message }; @@ -1784,6 +1794,7 @@ export class DefaultClient implements Client { }; // Reset all UI state to default, in case this is a restart after a crash. + workspaceInitializationMonitor.serverStarted(); this.model.isIndexingWorkspace.Value = false; this.model.isParsingWorkspace.Value = false; this.model.isParsingWorkspacePaused.Value = false; @@ -2912,6 +2923,7 @@ export class DefaultClient implements Client { testHook.updateStatus(status); } else if (message.endsWith("Parsing")) { this.model.isParsingWorkspace.Value = true; + workspaceInitializationMonitor.setParsingWorkspace(true); this.model.isInitializingWorkspace.Value = false; this.model.isIndexingWorkspace.Value = false; const status: IntelliSenseStatus = { status: Status.TagParsingBegun }; @@ -2920,14 +2932,17 @@ export class DefaultClient implements Client { this.model.isInitializingWorkspace.Value = true; this.model.isIndexingWorkspace.Value = false; this.model.isParsingWorkspace.Value = false; + workspaceInitializationMonitor.setParsingWorkspace(false); } else if (message.endsWith("Indexing")) { this.model.isIndexingWorkspace.Value = true; this.model.isInitializingWorkspace.Value = false; this.model.isParsingWorkspace.Value = false; + workspaceInitializationMonitor.setParsingWorkspace(false); } else if (message.endsWith("Failed")) { this.model.isInitializingWorkspace.Value = false; this.model.isIndexingWorkspace.Value = false; this.model.isParsingWorkspace.Value = false; + workspaceInitializationMonitor.setParsingWorkspace(false); this.model.isParsingFiles.Value = false; } else if (message.endsWith("files")) { this.model.isParsingFiles.Value = true; @@ -2943,6 +2958,7 @@ export class DefaultClient implements Client { testHook.updateStatus(status); } else if (message.endsWith("Parsing done")) { // Tag Parser Ready this.model.isParsingWorkspace.Value = false; + workspaceInitializationMonitor.workspaceParsingDone(); const status: IntelliSenseStatus = { status: Status.TagParsingDone }; testHook.updateStatus(status); util.setProgress(util.getProgressParseRootSuccess()); @@ -2970,6 +2986,7 @@ export class DefaultClient implements Client { } private updateTagParseStatus(tagParseStatus: TagParseStatus): void { + workspaceInitializationMonitor.tagParseStatusChanged(tagParseStatus.localizeStringParams.text, tagParseStatus.isPaused); this.model.parsingWorkspaceStatus.Value = getLocalizedString(tagParseStatus.localizeStringParams); this.model.isParsingWorkspacePaused.Value = tagParseStatus.isPaused; } @@ -3315,10 +3332,12 @@ export class DefaultClient implements Client { } public async pauseParsing(): Promise { + workspaceInitializationMonitor.pauseRequested(); return this.languageClient.sendNotification(PauseParsingNotification); } public async resumeParsing(): Promise { + workspaceInitializationMonitor.resumeRequested(); return this.languageClient.sendNotification(ResumeParsingNotification); } @@ -4402,6 +4421,7 @@ export class DefaultClient implements Client { } public static stopLanguageClient(): Thenable { + workspaceInitializationMonitor.serverStopped(); return languageClient ? languageClient.stop() : Promise.resolve(); } diff --git a/Extension/src/LanguageServer/stuckInitializationNotice.ts b/Extension/src/LanguageServer/stuckInitializationNotice.ts new file mode 100644 index 000000000..772d114d1 --- /dev/null +++ b/Extension/src/LanguageServer/stuckInitializationNotice.ts @@ -0,0 +1,41 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; + +/** What the notice needs from VS Code. It is passed in so that the notice can be tested without it. */ +export interface StuckInitializationNoticeHost { + /** Writes a line to the C/C++ output channel. */ + appendLine(message: string): void; + showInformationMessage(message: string, ...items: string[]): Thenable; + openLearnMore(): void; + /** Whether the user chose not to see the message in this workspace again. */ + isSuppressed(): boolean; + suppress(): void; +} + +/** + * Tells the user that the language server has been initializing the workspace for a long time. + * Every occurrence is logged. The message is shown once per session, because a language server that is + * restarted after a crash usually gets into the same state again. + */ +export class StuckInitializationNotice { + private shown: boolean = false; + + constructor(private readonly host: StuckInitializationNoticeHost) { } + + public async notify(message: string, learnMore: string, dontShowAgain: string): Promise { + this.host.appendLine(message); + if (this.shown || this.host.isSuppressed()) { + return; + } + this.shown = true; + const response: string | undefined = await this.host.showInformationMessage(message, learnMore, dontShowAgain); + if (response === dontShowAgain) { + this.host.suppress(); + } else if (response === learnMore) { + this.host.openLearnMore(); + } + } +} diff --git a/Extension/src/LanguageServer/workspaceInitializationMonitor.ts b/Extension/src/LanguageServer/workspaceInitializationMonitor.ts new file mode 100644 index 000000000..57c27e292 --- /dev/null +++ b/Extension/src/LanguageServer/workspaceInitializationMonitor.ts @@ -0,0 +1,232 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; + +/** + * How long the language server may stay in the workspace initialization phase before `onStuck` is called. + * Other tag parser statuses that last less than `initializationStatusGraceMs` do not interrupt the phase. + */ +export const stuckInitializingNoticeDelayMs: number = 2 * 60 * 1000; + +/** + * How many crashes in a row in the workspace initialization phase stop the language server from being restarted. + * A crash outside the phase, or a server that finishes parsing the workspace, starts the count again. + */ +export const maxConsecutiveInitializationCrashes: number = 3; + +/** How long another tag parser status has to last before the workspace initialization phase is considered left. */ +export const initializationStatusGraceMs: number = 2000; + +const maxCrashesInCrashWindow: number = 5; +const crashWindowMs: number = 3 * 60 * 1000; + +export enum CrashAction { + /** Start a new language server. */ + Restart, + /** The language server crashed 5 times in 3 minutes. */ + StopCrashedTooOften, + /** The language server crashed `maxConsecutiveInitializationCrashes` times in a row while initializing the workspace. */ + StopInitializationCrashLoop +} + +// The unformatted English text of the tag parser statuses that a language server reports while it enumerates the +// files of the workspace after it started (see "status_initializing*" in nativeStrings.json). +// The "Initializing projects" statuses are deliberately not listed. After a start they are reported for a short time +// once the enumeration is over. A running server also reports them when it enumerates the workspace again, for +// example after a setting changed; that case is not covered here. +const workspaceInitializationStatuses: ReadonlySet = new Set([ + 'Initializing', + 'Initializing ({0} of {1})', + 'Initializing ({0} of {1}): {2}', + 'Initializing {0}' +]); + +/** + * @param text The `text` of the LocalizeStringParams of a tag parse status notification, not the localized string that is shown in the UI. + */ +export function isWorkspaceInitializationStatus(text: string): boolean { + return workspaceInitializationStatuses.has(text); +} + +/** + * Keeps track of whether the language server is in the phase in which it enumerates the files of the workspace, + * and decides whether the language server is restarted after a crash. + * + * A language server that never gets out of this phase (for example because of symbolic links that make it visit + * the same folders over and over) grows until the OS terminates it, which can take much longer than the 3 minutes + * in which 5 crashes stop the restarts. Without the additional rule here it would be restarted forever. + * + * There is one language server process for all workspace folders, so there is one monitor for all clients. + */ +export class WorkspaceInitializationMonitor { + private serverRunning: boolean = false; + private parsingWorkspace: boolean = false; + private initializationStatusReceived: boolean = false; + private pauseWasRequested: boolean = false; + private serverReportedPaused: boolean = false; + private stuckReported: boolean = false; + private stuckTimer: NodeJS.Timeout | undefined; + private otherStatusTimer: NodeJS.Timeout | undefined; + private readonly crashTimes: number[] = []; + private consecutiveInitializationCrashes: number = 0; + + /** + * @param onStuck Called at most once per language server process, when it has been in the workspace initialization + * phase for `stuckInitializingNoticeDelayMs`. + */ + constructor(private readonly onStuck: () => void) { } + + /** + * True while workspace parsing is in progress, the last tag parse status of this parsing cycle is one of the + * workspace initialization statuses (or another status has not lasted for `initializationStatusGraceMs` yet), + * and parsing is neither paused nor requested to be paused. Tag parse statuses only count while a language + * server is running. + */ + public get isInitializingWorkspace(): boolean { + return this.parsingWorkspace && this.initializationStatusReceived && !this.pauseWasRequested && !this.serverReportedPaused; + } + + /** A new language server process is about to be started. The crash history is kept. */ + public serverStarted(): void { + this.resetPhase(); + this.stuckReported = false; + this.serverRunning = true; + } + + /** + * The language server process is being stopped on purpose. Notifications that it still sends while + * it shuts down are ignored. + */ + public serverStopped(): void { + this.serverRunning = false; + this.resetPhase(); + } + + /** Mirrors `isParsingWorkspace` of the client model. */ + public setParsingWorkspace(value: boolean): void { + this.parsingWorkspace = value; + if (!value) { + // A tag parse status says nothing about the next parsing cycle. It is forgotten when a cycle ends and + // not when one starts, because the language server reports the start of workspace parsing and its + // first tag parse status at almost the same time, and the two can arrive in either order. + // The price is that a status which arrives after its cycle ended counts for the next cycle until + // another status of that cycle has lasted for `initializationStatusGraceMs`. + this.forgetInitializationStatus(); + } + this.update(); + } + + /** + * The language server reported that it finished parsing the workspace. A crash during a later initialization + * does not continue the series of crashes from before: the server got through in between. + */ + public workspaceParsingDone(): void { + if (this.serverRunning) { + this.consecutiveInitializationCrashes = 0; + } + this.setParsingWorkspace(false); + } + + /** + * A status other than an initialization status ends the phase only when it lasts for `initializationStatusGraceMs`: + * when files change, the language server reports "Parsing files" for a moment and then goes on initializing. + * Until then the phase counts as not left, also for a crash. + * @param text The `text` of the LocalizeStringParams of the notification. + */ + public tagParseStatusChanged(text: string, isPaused: boolean): void { + if (!this.serverRunning) { + // A language server that is shutting down still sends notifications. + return; + } + this.serverReportedPaused = isPaused; + if (isWorkspaceInitializationStatus(text)) { + this.forgetInitializationStatus(); + this.initializationStatusReceived = true; + } else if (this.initializationStatusReceived && this.otherStatusTimer === undefined) { + this.otherStatusTimer = setTimeout(() => { + this.forgetInitializationStatus(); + this.update(); + }, initializationStatusGraceMs); + } + this.update(); + } + + /** The extension is about to ask the language server to pause parsing. */ + public pauseRequested(): void { + this.pauseWasRequested = true; + this.update(); + } + + /** The extension is about to ask the language server to resume parsing. */ + public resumeRequested(): void { + this.pauseWasRequested = false; + this.update(); + } + + /** + * The language server process went away unexpectedly. + * @param now The time of the crash, in milliseconds. + */ + public serverCrashed(now: number): CrashAction { + const crashedDuringInitialization: boolean = this.isInitializingWorkspace; + this.serverRunning = false; + this.resetPhase(); + + let crashedTooOften: boolean = false; + this.crashTimes.push(now); + if (this.crashTimes.length >= maxCrashesInCrashWindow) { + const elapsed: number = this.crashTimes[this.crashTimes.length - 1] - this.crashTimes[0]; + if (elapsed <= crashWindowMs) { + crashedTooOften = true; + } else { + this.crashTimes.shift(); + } + } + + this.consecutiveInitializationCrashes = crashedDuringInitialization ? this.consecutiveInitializationCrashes + 1 : 0; + + if (crashedTooOften) { + return CrashAction.StopCrashedTooOften; + } + if (this.consecutiveInitializationCrashes >= maxConsecutiveInitializationCrashes) { + return CrashAction.StopInitializationCrashLoop; + } + return CrashAction.Restart; + } + + private forgetInitializationStatus(): void { + this.initializationStatusReceived = false; + if (this.otherStatusTimer !== undefined) { + clearTimeout(this.otherStatusTimer); + this.otherStatusTimer = undefined; + } + } + + private resetPhase(): void { + this.parsingWorkspace = false; + this.forgetInitializationStatus(); + this.pauseWasRequested = false; + this.serverReportedPaused = false; + this.update(); + } + + private update(): void { + if (!this.isInitializingWorkspace) { + if (this.stuckTimer !== undefined) { + clearTimeout(this.stuckTimer); + this.stuckTimer = undefined; + } + } else if (this.stuckTimer === undefined && !this.stuckReported) { + // Progress within the phase does not restart the timer: it measures the time spent in the phase. + this.stuckTimer = setTimeout(() => { + this.stuckTimer = undefined; + if (this.isInitializingWorkspace && !this.stuckReported) { + this.stuckReported = true; + this.onStuck(); + } + }, stuckInitializingNoticeDelayMs); + } + } +} diff --git a/Extension/test/unit/stuckInitializationNotice.test.ts b/Extension/test/unit/stuckInitializationNotice.test.ts new file mode 100644 index 000000000..611ad48b1 --- /dev/null +++ b/Extension/test/unit/stuckInitializationNotice.test.ts @@ -0,0 +1,115 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { describe, it } from 'mocha'; +import { deepStrictEqual, strictEqual } from 'node:assert'; +import { StuckInitializationNotice, StuckInitializationNoticeHost } from '../../src/LanguageServer/stuckInitializationNotice'; + +const message: string = 'The C/C++ extension has been initializing this workspace for more than 2 minutes.'; +const learnMore: string = 'Learn More'; +const dontShowAgain: string = 'Don\'t Show Again'; + +class FakeHost implements StuckInitializationNoticeHost { + public readonly lines: string[] = []; + public readonly shown: string[][] = []; + public learnMoreOpened: number = 0; + public suppressed: boolean = false; + /** What the user clicks; `undefined` means that the message is dismissed. */ + public response: string | undefined; + /** When set, the message stays open until `answer` is called. */ + public keepOpen: boolean = false; + private pending: ((value: string | undefined) => void)[] = []; + + public appendLine(line: string): void { + this.lines.push(line); + } + + public showInformationMessage(text: string, ...items: string[]): Thenable { + this.shown.push([text, ...items]); + if (this.keepOpen) { + return new Promise(resolve => this.pending.push(resolve)); + } + return Promise.resolve(this.response); + } + + public answer(response: string | undefined): void { + this.pending.splice(0).forEach(resolve => resolve(response)); + } + + public openLearnMore(): void { + this.learnMoreOpened++; + } + + public isSuppressed(): boolean { + return this.suppressed; + } + + public suppress(): void { + this.suppressed = true; + } +} + +describe('stuck initialization notice', () => { + it('writes to the output channel and shows the message with both actions', async () => { + const host: FakeHost = new FakeHost(); + await new StuckInitializationNotice(host).notify(message, learnMore, dontShowAgain); + deepStrictEqual(host.lines, [message]); + deepStrictEqual(host.shown, [[message, learnMore, dontShowAgain]]); + strictEqual(host.learnMoreOpened, 0); + strictEqual(host.suppressed, false); + }); + + it('shows the message once per session, but logs every time', async () => { + const host: FakeHost = new FakeHost(); + const notice: StuckInitializationNotice = new StuckInitializationNotice(host); + await notice.notify(message, learnMore, dontShowAgain); + // A replacement language server gets stuck again. + await notice.notify(message, learnMore, dontShowAgain); + await notice.notify(message, learnMore, dontShowAgain); + strictEqual(host.shown.length, 1); + deepStrictEqual(host.lines, [message, message, message]); + }); + + it('does not show a second message while the first one is still open', async () => { + const host: FakeHost = new FakeHost(); + host.keepOpen = true; + const notice: StuckInitializationNotice = new StuckInitializationNotice(host); + const first: Promise = notice.notify(message, learnMore, dontShowAgain); + const second: Promise = notice.notify(message, learnMore, dontShowAgain); + strictEqual(host.shown.length, 1); + host.answer(undefined); + await Promise.all([first, second]); + strictEqual(host.shown.length, 1); + }); + + it('remembers "Don\'t Show Again" and still logs afterwards', async () => { + const host: FakeHost = new FakeHost(); + host.response = dontShowAgain; + await new StuckInitializationNotice(host).notify(message, learnMore, dontShowAgain); + strictEqual(host.suppressed, true); + strictEqual(host.learnMoreOpened, 0); + + // The next session uses a new notice with the same persisted state. + await new StuckInitializationNotice(host).notify(message, learnMore, dontShowAgain); + strictEqual(host.shown.length, 1); + deepStrictEqual(host.lines, [message, message]); + }); + + it('opens the documentation for "Learn More" without suppressing the message', async () => { + const host: FakeHost = new FakeHost(); + host.response = learnMore; + await new StuckInitializationNotice(host).notify(message, learnMore, dontShowAgain); + strictEqual(host.learnMoreOpened, 1); + strictEqual(host.suppressed, false); + }); + + it('does nothing more when the message is dismissed', async () => { + const host: FakeHost = new FakeHost(); + host.response = undefined; + await new StuckInitializationNotice(host).notify(message, learnMore, dontShowAgain); + strictEqual(host.learnMoreOpened, 0); + strictEqual(host.suppressed, false); + }); +}); diff --git a/Extension/test/unit/workspaceInitializationMonitor.test.ts b/Extension/test/unit/workspaceInitializationMonitor.test.ts new file mode 100644 index 000000000..58fcea646 --- /dev/null +++ b/Extension/test/unit/workspaceInitializationMonitor.test.ts @@ -0,0 +1,857 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { afterEach, beforeEach, describe, it } from 'mocha'; +import { deepStrictEqual, strictEqual } from 'node:assert'; +import * as sinon from 'sinon'; +import { + CrashAction, + initializationStatusGraceMs, + isWorkspaceInitializationStatus, + maxConsecutiveInitializationCrashes, + stuckInitializingNoticeDelayMs, + WorkspaceInitializationMonitor +} from '../../src/LanguageServer/workspaceInitializationMonitor'; + +// Notifications recorded from the language server (1.36.0 binaries, macOS arm64, VS Code display language zh-CN). +// `at` is seconds since the server started. `status` is a 'cpptools/reportStatus' message, `tag` is the unformatted +// `localizeStringParams.text` of a 'cpptools/reportTagParseStatus' notification together with its `stringArgs`. +// Only the status messages that change `isParsingWorkspace` in DefaultClient.updateStatus are kept. +interface RecordedEvent { + at: number; + status?: string; + tag?: string; + args?: string[]; + isPaused?: boolean; +} + +const initializingNofM = 'Initializing ({0} of {1})'; +const initializingProjectsNofM = 'Initializing projects ({0} of {1})'; +const parsingFilesNofM = 'Parsing files ({0} of {1})'; +const parsingFilesNofMWithText = 'Parsing files ({0} of {1}): {2}'; +const workspaceParsingPaused = 'Workspace parsing paused'; + +// A folder with 21 files and no symbolic links. +const healthySingleRoot: RecordedEvent[] = [ + { at: 0.8, status: 'C_Cpp: Parser Initializing' }, + { at: 3.7, status: 'C_Cpp: Parsing' }, + { at: 4.0, tag: parsingFilesNofM, args: ['0', '21'] }, + { at: 7.0, status: 'C_Cpp: Parsing done' }, + { at: 7.0, status: 'C_Cpp: Idle' } +]; + +// A single file opened without a folder. +const singleFile: RecordedEvent[] = [ + { at: 0.5, status: 'C_Cpp: Idle' }, + { at: 0.6, status: 'C_Cpp: Parser Initializing' }, + { at: 0.7, status: 'C_Cpp: Parsing' }, + { at: 4.0, tag: initializingProjectsNofM, args: ['2', '1'] }, + { at: 5.0, status: 'C_Cpp: Parsing done' }, + { at: 5.0, status: 'C_Cpp: Idle' } +]; + +// A multi-root workspace with two small folders. +const healthyMultiRoot: RecordedEvent[] = [ + { at: 0.5, status: 'C_Cpp: Parser Initializing' }, + { at: 3.5, status: 'C_Cpp: Parsing' }, + { at: 3.9, tag: initializingNofM, args: ['1', '2'] }, + { at: 3.9, tag: initializingNofM, args: ['2', '2'] }, + { at: 4.0, tag: parsingFilesNofMWithText, args: ['1', '672', 'a.c'] }, + { at: 11.2, tag: initializingProjectsNofM, args: ['2', '2'] }, + { at: 12.1, status: 'C_Cpp: Parsing done' }, + { at: 12.1, status: 'C_Cpp: Idle' } +]; + +// Slow but finite: enumeration takes about ten seconds, then 219201 paths are parsed. +const slowButFinite: RecordedEvent[] = [ + { at: 0.6, status: 'C_Cpp: Parser Initializing' }, + { at: 3.5, status: 'C_Cpp: Parsing' }, + { at: 3.8, tag: initializingNofM, args: ['1', '1'] }, + { at: 6.4, tag: initializingNofM, args: ['2', '3'] }, + { at: 6.4, tag: initializingNofM, args: ['3', '3'] }, + { at: 14.2, tag: 'Scanning #includes for more files ({0} of {1})', args: ['1', '1'] }, + { at: 15.1, tag: initializingProjectsNofM, args: ['1', '1'] }, + { at: 16.1, tag: parsingFilesNofMWithText, args: ['1', '219201', 'a.c'] } +]; + +// Enumeration never finishes; nothing else arrives until the process is killed. +const runawaySingleRoot: RecordedEvent[] = [ + { at: 0.4, status: 'C_Cpp: Parser Initializing' }, + { at: 3.4, status: 'C_Cpp: Parsing' }, + { at: 3.7, tag: initializingNofM, args: ['1', '1'] }, + { at: 6.5, tag: initializingNofM, args: ['2', '3'] }, + { at: 6.5, tag: initializingNofM, args: ['3', '3'] } +]; + +// The same workspace while files in it are appended to, created, edited and saved. The language server reports +// 'Parsing files' for a moment and goes on initializing. +const runawayWithFileActivity: RecordedEvent[] = [ + { at: 0.0, status: 'C_Cpp: Parser Initializing' }, + { at: 1.3, tag: parsingFilesNofM, args: ['1', '1'] }, + { at: 2.9, status: 'C_Cpp: Parsing' }, + { at: 3.1, tag: initializingNofM, args: ['1', '1'] }, + { at: 18.6, tag: initializingNofM, args: ['1', '2'] }, + { at: 18.8, tag: initializingNofM, args: ['2', '2'] }, + { at: 30.5, tag: initializingNofM, args: ['2', '3'] }, + { at: 31.1, tag: initializingNofM, args: ['3', '3'] }, + { at: 33.5, tag: parsingFilesNofM, args: ['4', '4'] }, + { at: 33.5, tag: initializingNofM, args: ['4', '4'] }, + { at: 48.3, tag: initializingNofM, args: ['4', '5'] }, + { at: 49.3, tag: initializingNofM, args: ['5', '5'] }, + { at: 68.6, tag: initializingNofM, args: ['7', '7'] }, + { at: 71.4, tag: initializingNofM, args: ['7', '8'] }, + { at: 71.6, tag: initializingNofM, args: ['8', '8'] }, + { at: 74.4, tag: initializingNofM, args: ['8', '9'] }, + { at: 74.5, tag: initializingNofM, args: ['9', '9'] } +]; + +// Not recorded: the start of the session above with its second and third notification swapped. The language server +// sends the two within a few tenths of a second of each other, and nothing else for a long time afterwards. +const runawayStatusOrderReversed: RecordedEvent[] = [ + { at: 0.6, status: 'C_Cpp: Parser Initializing' }, + { at: 3.6, tag: initializingNofM, args: ['1', '1'] }, + { at: 3.7, status: 'C_Cpp: Parsing' } +]; + +// Multi-root workspace with one small folder and one folder whose enumeration never finishes. +const runawayMultiRoot: RecordedEvent[] = [ + { at: 0.6, status: 'C_Cpp: Parser Initializing' }, + { at: 3.7, status: 'C_Cpp: Parsing' }, + { at: 4.0, tag: initializingNofM, args: ['1', '2'] }, + { at: 4.0, tag: initializingNofM, args: ['2', '2'] } +]; + +/** + * Feeds a status message to the monitor the way DefaultClient.updateStatus does: the monitor is told about + * exactly the assignments that updateStatus makes to `model.isParsingWorkspace`. + */ +function reportStatus(monitor: WorkspaceInitializationMonitor, message: string): void { + if (message.endsWith('Parsing')) { + monitor.setParsingWorkspace(true); + } else if (message.endsWith('Initializing') || message.endsWith('Indexing') || message.endsWith('Failed')) { + monitor.setParsingWorkspace(false); + } else if (message.endsWith('Parsing done')) { + monitor.workspaceParsingDone(); + } +} + +describe('workspace initialization monitor', () => { + let clock: sinon.SinonFakeTimers; + let stuckCount: number; + let monitor: WorkspaceInitializationMonitor; + + beforeEach(() => { + clock = sinon.useFakeTimers(); + stuckCount = 0; + monitor = new WorkspaceInitializationMonitor(() => { stuckCount++; }); + monitor.serverStarted(); + }); + + afterEach(() => clock.restore()); + + /** Replays a recording against the fake clock and returns whether the monitor ever saw the initialization phase. */ + function replay(events: RecordedEvent[]): boolean { + let sawInitialization: boolean = false; + const start: number = clock.now; + for (const event of events) { + clock.tick(Math.max(0, Math.round(start + event.at * 1000) - clock.now)); + if (event.status !== undefined) { + reportStatus(monitor, event.status); + } + if (event.tag !== undefined) { + monitor.tagParseStatusChanged(event.tag, event.isPaused ?? false); + } + sawInitialization = sawInitialization || monitor.isInitializingWorkspace; + } + return sawInitialization; + } + + function enterInitialization(): void { + monitor.setParsingWorkspace(true); + monitor.tagParseStatusChanged(initializingNofM, false); + } + + describe('status matching', () => { + it('matches the workspace initialization templates', () => { + for (const text of ['Initializing', 'Initializing ({0} of {1})', 'Initializing ({0} of {1}): {2}', 'Initializing {0}']) { + strictEqual(isWorkspaceInitializationStatus(text), true, text); + } + }); + + it('does not match other tag parser statuses', () => { + for (const text of ['', 'Initializing projects', initializingProjectsNofM, 'Initializing projects ({0} of {1}): {2}', 'Initializing projects {0}', + parsingFilesNofM, 'Checking for out of date files', 'Scanning #includes for more files ({0} of {1})', 'Initializing something new', '正在初始化']) { + strictEqual(isWorkspaceInitializationStatus(text), false, text); + } + }); + }); + + describe('recorded sessions', () => { + it('never sees the initialization phase when a small folder goes straight to parsing files', () => { + strictEqual(replay(healthySingleRoot), false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('does not treat "Initializing projects" in single-file mode as workspace initialization', () => { + strictEqual(replay(singleFile), false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('leaves the phase again in a healthy multi-root workspace', () => { + strictEqual(replay(healthyMultiRoot), true); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('leaves the phase when a slow enumeration finishes, although "Parsing done" is still far away', () => { + strictEqual(replay(slowButFinite), true); + clock.tick(initializationStatusGraceMs); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('reports a single-root workspace that stays in the phase', () => { + strictEqual(replay(runawaySingleRoot), true); + strictEqual(monitor.isInitializingWorkspace, true); + clock.tick(stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 1); + }); + + it('measures from the first initialization status when another status interrupts for a moment', () => { + const start: number = clock.now; + replay(runawayWithFileActivity); + strictEqual(monitor.isInitializingWorkspace, true); + // The phase was entered 3.1 seconds after the server started. + clock.tick(start + 3100 + stuckInitializingNoticeDelayMs - 1 - clock.now); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('reports a multi-root workspace in which one folder stays in the phase', () => { + strictEqual(replay(runawayMultiRoot), true); + clock.tick(stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 1); + }); + }); + + describe('phase tracking', () => { + it('needs both workspace parsing and an initialization status, in either order', () => { + strictEqual(monitor.isInitializingWorkspace, false); + monitor.setParsingWorkspace(true); + strictEqual(monitor.isInitializingWorkspace, false, 'workspace parsing without a tag parse status'); + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, true); + + monitor.serverStarted(); + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, false, 'tag parse status without workspace parsing'); + monitor.setParsingWorkspace(true); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('enters the phase when the first tag parse status overtakes the "Parsing" status', () => { + replay(runawayStatusOrderReversed); + strictEqual(monitor.isInitializingWorkspace, true); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('cannot tell a late status of the previous cycle from an early status of the next one', () => { + enterInitialization(); + reportStatus(monitor, 'C_Cpp: Parsing done'); + // Belongs to the cycle that just ended, but nothing in the notification says so. + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, false); + reportStatus(monitor, 'C_Cpp: Parsing'); + strictEqual(monitor.isInitializingWorkspace, true, 'accepted: this is also what an early status of the new cycle looks like'); + + // The first tag parse status of the new cycle corrects it. + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(initializationStatusGraceMs); + strictEqual(monitor.isInitializingWorkspace, false); + }); + + it('forgets an initialization status when workspace parsing is reported as not in progress', () => { + for (const status of ['C_Cpp: Parser Initializing', 'C_Cpp: Indexing', 'C_Cpp: Failed', 'C_Cpp: Parsing done']) { + monitor.serverStarted(); + monitor.tagParseStatusChanged(initializingNofM, false); + reportStatus(monitor, status); + reportStatus(monitor, 'C_Cpp: Parsing'); + strictEqual(monitor.isInitializingWorkspace, false, status); + } + }); + + it('leaves the phase on every status that clears isParsingWorkspace', () => { + for (const status of ['C_Cpp: Parser Initializing', 'C_Cpp: Indexing', 'C_Cpp: Failed', 'C_Cpp: Parsing done']) { + enterInitialization(); + strictEqual(monitor.isInitializingWorkspace, true, status); + reportStatus(monitor, status); + strictEqual(monitor.isInitializingWorkspace, false, status); + } + }); + + it('leaves the phase when any other tag status lasts, including unknown and empty ones', () => { + for (const text of [parsingFilesNofM, initializingProjectsNofM, 'Something new', '']) { + enterInitialization(); + monitor.tagParseStatusChanged(text, false); + clock.tick(initializationStatusGraceMs - 1); + strictEqual(monitor.isInitializingWorkspace, true, text); + // Further statuses that are not initialization statuses do not extend the grace period. + monitor.tagParseStatusChanged(text, false); + clock.tick(1); + strictEqual(monitor.isInitializingWorkspace, false, text); + strictEqual(clock.countTimers(), 0); + monitor.setParsingWorkspace(false); + } + }); + + it('stays in the phase when another tag status is followed by an initialization status in time', () => { + enterInitialization(); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(initializationStatusGraceMs - 1); + monitor.tagParseStatusChanged(initializingNofM, false); + clock.tick(10 * initializationStatusGraceMs); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('does not wait for the grace period when the parsing cycle ends or the server goes away', () => { + enterInitialization(); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + reportStatus(monitor, 'C_Cpp: Parsing done'); + strictEqual(monitor.isInitializingWorkspace, false); + strictEqual(clock.countTimers(), 0); + + enterInitialization(); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + monitor.serverStopped(); + strictEqual(clock.countTimers(), 0); + + monitor.serverStarted(); + enterInitialization(); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + monitor.serverCrashed(clock.now); + strictEqual(clock.countTimers(), 0); + // The pending change of the previous server does not affect the next one. + monitor.serverStarted(); + enterInitialization(); + clock.tick(10 * initializationStatusGraceMs); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('does not carry an initialization status over to the next parsing cycle', () => { + enterInitialization(); + reportStatus(monitor, 'C_Cpp: Parsing done'); + reportStatus(monitor, 'C_Cpp: Parsing'); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('keeps the phase when the same parsing state is reported again', () => { + enterInitialization(); + monitor.setParsingWorkspace(true); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('forgets the phase when a new server starts or the server is stopped', () => { + enterInitialization(); + monitor.serverStarted(); + strictEqual(monitor.isInitializingWorkspace, false); + enterInitialization(); + monitor.serverStopped(); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + }); + + describe('stuck notification', () => { + it('fires after the delay and not a millisecond earlier', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('measures continuous time in the phase: progress updates do not restart the delay', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs / 2); + monitor.tagParseStatusChanged(initializingNofM, false); + monitor.tagParseStatusChanged('Initializing ({0} of {1}): {2}', false); + clock.tick(stuckInitializingNoticeDelayMs / 2); + strictEqual(stuckCount, 1); + }); + + it('fires once per server process', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + monitor.tagParseStatusChanged(initializingNofM, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 1); + + monitor.serverStarted(); + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 2); + }); + + it('starts over when the phase is left and entered again', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - initializationStatusGraceMs - 1); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(initializationStatusGraceMs); + strictEqual(monitor.isInitializingWorkspace, false); + monitor.tagParseStatusChanged(initializingNofM, false); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('does not start over when another status interrupts the phase for a moment', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - 1000); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(100); + monitor.tagParseStatusChanged(initializingNofM, false); + clock.tick(899); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('does not fire when another status has lasted just before the delay is over', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - initializationStatusGraceMs - 1); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + strictEqual(clock.countTimers(), 0); + }); + + it('fires when the delay is over before another status has lasted', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - initializationStatusGraceMs + 1); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(initializationStatusGraceMs - 1); + strictEqual(stuckCount, 1); + strictEqual(monitor.isInitializingWorkspace, true); + clock.tick(1); + strictEqual(monitor.isInitializingWorkspace, false); + strictEqual(clock.countTimers(), 0); + }); + + it('does not fire after the server crashed, whatever the crash handler decided', () => { + const actions: CrashAction[] = []; + for (let i: number = 0; i < maxConsecutiveInitializationCrashes; i++) { + monitor.serverStarted(); + enterInitialization(); + clock.tick(1000); + actions.push(monitor.serverCrashed(clock.now)); + clock.tick(10 * stuckInitializingNoticeDelayMs); + } + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.StopInitializationCrashLoop]); + strictEqual(stuckCount, 0); + + const other: WorkspaceInitializationMonitor = new WorkspaceInitializationMonitor(() => { stuckCount++; }); + for (let i: number = 0; i < 5; i++) { + other.serverStarted(); + other.setParsingWorkspace(true); + other.tagParseStatusChanged(i < 2 ? parsingFilesNofM : initializingNofM, false); + strictEqual(other.serverCrashed(clock.now), i < 4 ? CrashAction.Restart : CrashAction.StopCrashedTooOften); + clock.tick(1000); + } + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + }); + + describe('server lifetime', () => { + it('ignores notifications until a server is started', () => { + const idle: WorkspaceInitializationMonitor = new WorkspaceInitializationMonitor(() => { stuckCount++; }); + idle.setParsingWorkspace(true); + idle.tagParseStatusChanged(initializingNofM, false); + strictEqual(idle.isInitializingWorkspace, false); + strictEqual(clock.countTimers(), 0); + }); + + it('ignores notifications that are still delivered after the server was stopped', () => { + enterInitialization(); + strictEqual(clock.countTimers(), 1); + monitor.serverStopped(); + strictEqual(clock.countTimers(), 0); + + // The language client keeps its notification handlers while it waits for the shutdown response. + reportStatus(monitor, 'C_Cpp: Parsing'); + monitor.tagParseStatusChanged(initializingNofM, false); + monitor.resumeRequested(); + strictEqual(monitor.isInitializingWorkspace, false); + strictEqual(clock.countTimers(), 0); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('ignores notifications after a crash until the replacement server is started', () => { + enterInitialization(); + monitor.serverCrashed(clock.now); + strictEqual(clock.countTimers(), 0); + + enterInitialization(); + strictEqual(monitor.isInitializingWorkspace, false); + strictEqual(clock.countTimers(), 0); + + monitor.serverStarted(); + strictEqual(monitor.isInitializingWorkspace, false, 'what arrived while no server was running is discarded'); + strictEqual(clock.countTimers(), 0); + enterInitialization(); + strictEqual(monitor.isInitializingWorkspace, true); + strictEqual(clock.countTimers(), 1); + }); + + it('discards a pause request that was made while no server was running', () => { + enterInitialization(); + monitor.serverStopped(); + monitor.pauseRequested(); + monitor.serverStarted(); + enterInitialization(); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('starts no timer for tag parse statuses that arrive after the server was stopped or crashed', () => { + enterInitialization(); + monitor.serverStopped(); + monitor.tagParseStatusChanged(initializingNofM, false); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + strictEqual(clock.countTimers(), 0); + + monitor.serverStarted(); + enterInitialization(); + monitor.serverCrashed(clock.now); + monitor.tagParseStatusChanged(initializingNofM, false); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + strictEqual(clock.countTimers(), 0); + }); + + it('leaves no timer behind when the server is not restarted', () => { + for (let i: number = 0; i < maxConsecutiveInitializationCrashes; i++) { + monitor.serverStarted(); + enterInitialization(); + monitor.serverCrashed(clock.now); + strictEqual(clock.countTimers(), 0); + } + }); + + it('gives a replacement server the full delay', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - 1); + monitor.serverCrashed(clock.now); + monitor.serverStarted(); + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + }); + + describe('pausing', () => { + it('stops the delay when the server reports that parsing is paused and starts over when it resumes', () => { + enterInitialization(); + clock.tick(stuckInitializingNoticeDelayMs - 1); + monitor.tagParseStatusChanged(initializingNofM, true); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + + monitor.tagParseStatusChanged(initializingNofM, false); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('handles the paused status that the server reports, for a pause that is longer than the grace period', () => { + // Recorded: C_Cpp.PauseParsing 5 seconds into the phase, C_Cpp.ResumeParsing 130 seconds later. + enterInitialization(); + clock.tick(5000); + monitor.pauseRequested(); + monitor.tagParseStatusChanged(workspaceParsingPaused, true); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(130000); + strictEqual(stuckCount, 0); + strictEqual(clock.countTimers(), 0); + + monitor.resumeRequested(); + strictEqual(monitor.isInitializingWorkspace, false); + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, true); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('waits for the resume request when the server reports first that it is not paused', () => { + enterInitialization(); + monitor.pauseRequested(); + monitor.tagParseStatusChanged(workspaceParsingPaused, true); + clock.tick(10 * initializationStatusGraceMs); + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, false); + monitor.resumeRequested(); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('does not count a crash right after the server reported the paused status', () => { + const actions: CrashAction[] = []; + for (let i: number = 0; i < maxConsecutiveInitializationCrashes + 1; i++) { + monitor.serverStarted(); + enterInitialization(); + monitor.tagParseStatusChanged(workspaceParsingPaused, true); + actions.push(monitor.serverCrashed(clock.now)); + clock.tick(10 * 60 * 1000); + } + deepStrictEqual(actions, new Array(maxConsecutiveInitializationCrashes + 1).fill(CrashAction.Restart)); + }); + + it('honors a pause request before the server acknowledges it', () => { + enterInitialization(); + monitor.pauseRequested(); + strictEqual(monitor.isInitializingWorkspace, false); + // The server has not acted on the request yet and keeps reporting that it is not paused. + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, false); + clock.tick(10 * stuckInitializingNoticeDelayMs); + strictEqual(stuckCount, 0); + }); + + it('starts over when a resume is requested and the server does not report being paused', () => { + enterInitialization(); + monitor.pauseRequested(); + clock.tick(stuckInitializingNoticeDelayMs); + monitor.resumeRequested(); + strictEqual(monitor.isInitializingWorkspace, true); + clock.tick(stuckInitializingNoticeDelayMs - 1); + strictEqual(stuckCount, 0); + clock.tick(1); + strictEqual(stuckCount, 1); + }); + + it('waits for the server to report that it resumed after it reported being paused', () => { + enterInitialization(); + monitor.pauseRequested(); + monitor.tagParseStatusChanged(initializingNofM, true); + monitor.resumeRequested(); + strictEqual(monitor.isInitializingWorkspace, false); + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('forgets a pause request when a new server starts', () => { + monitor.pauseRequested(); + monitor.serverStarted(); + enterInitialization(); + strictEqual(monitor.isInitializingWorkspace, true); + }); + + it('does not count a crash while paused as an initialization crash', () => { + const actions: CrashAction[] = []; + for (let i: number = 0; i < maxConsecutiveInitializationCrashes + 1; i++) { + monitor.serverStarted(); + enterInitialization(); + monitor.pauseRequested(); + actions.push(monitor.serverCrashed(clock.now)); + clock.tick(10 * 60 * 1000); + } + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart]); + }); + }); + + describe('crash handling', () => { + const minute: number = 60 * 1000; + + /** Starts a server, optionally puts it into the initialization phase, and crashes it at the given time. */ + function crash(at: number, duringInitialization: boolean): CrashAction { + monitor.serverStarted(); + if (duringInitialization) { + enterInitialization(); + } else { + // Past the initialization phase and parsing files, but not done. + replay(slowButFinite); + clock.tick(initializationStatusGraceMs); + } + clock.tick(Math.max(0, at - clock.now)); + return monitor.serverCrashed(at); + } + + it('restarts after fewer than five crashes outside the initialization phase', () => { + deepStrictEqual([0, 1000, 2000, 3000].map(at => crash(at * 1000, false)), [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart]); + }); + + it('stops when the fifth crash is exactly three minutes after the first', () => { + const times: number[] = [0, 40000, 80000, 120000, 180000]; + deepStrictEqual(times.map(at => crash(at, false)), + [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.StopCrashedTooOften]); + }); + + it('keeps restarting when five crashes span more than three minutes, and slides the window', () => { + const times: number[] = [0, 40000, 80000, 120000, 180001, 200000, 220000]; + deepStrictEqual(times.map(at => crash(at, false)), + // 180001 - 0 > 3 min: restart and drop the first crash. 200000 - 40000 <= 3 min: stop. + [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.StopCrashedTooOften, CrashAction.StopCrashedTooOften]); + }); + + it('counts a burst of crashes that follows crashes far apart', () => { + const times: number[] = [0, 30 * minute, 60 * minute, 90 * minute, 120 * minute, 120 * minute + 1000, 120 * minute + 2000, 120 * minute + 3000, 120 * minute + 4000]; + const actions: CrashAction[] = times.map(at => crash(at, false)); + deepStrictEqual(actions.slice(0, 8), new Array(8).fill(CrashAction.Restart)); + strictEqual(actions[8], CrashAction.StopCrashedTooOften); + }); + + it('stops after three consecutive crashes in the initialization phase, however far apart they are', () => { + deepStrictEqual([0, 23 * minute, 46 * minute].map(at => crash(at, true)), + [CrashAction.Restart, CrashAction.Restart, CrashAction.StopInitializationCrashLoop]); + }); + + it('stops at the third crash when the server crashes quickly in the initialization phase', () => { + deepStrictEqual([0, 10000, 20000].map(at => crash(at, true)), + [CrashAction.Restart, CrashAction.Restart, CrashAction.StopInitializationCrashLoop]); + }); + + it('resets the count when a crash happens outside the initialization phase', () => { + const actions: CrashAction[] = [ + crash(0, true), crash(10 * minute, true), crash(20 * minute, false), + crash(30 * minute, true), crash(40 * minute, true), crash(50 * minute, true) + ]; + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, + CrashAction.Restart, CrashAction.Restart, CrashAction.StopInitializationCrashLoop]); + }); + + it('starts counting again after a server has parsed the workspace completely', () => { + // An initialization crash, a replacement that parses the workspace, and much later another initialization crash. + const actions: CrashAction[] = []; + for (let i: number = 0; i < 2 * maxConsecutiveInitializationCrashes; i++) { + actions.push(crash(i * 60 * minute, true)); + monitor.serverStarted(); + replay(healthySingleRoot); + } + deepStrictEqual(actions, new Array(2 * maxConsecutiveInitializationCrashes).fill(CrashAction.Restart)); + }); + + it('counts from one for a crash in a later initialization of a server that had parsed the workspace', () => { + crash(0, true); + crash(10 * minute, true); + monitor.serverStarted(); + replay(healthySingleRoot); + // Constructed, not recorded: the same server reports the initialization statuses again and crashes. + enterInitialization(); + const actions: CrashAction[] = [monitor.serverCrashed(20 * minute), crash(30 * minute, true), crash(40 * minute, true)]; + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.StopInitializationCrashLoop]); + }); + + it('keeps counting when a server only gets past the initialization phase without finishing', () => { + crash(0, true); + crash(10 * minute, true); + monitor.serverStarted(); + replay(slowButFinite); + clock.tick(initializationStatusGraceMs); + strictEqual(monitor.isInitializingWorkspace, false); + // Constructed, not recorded: without 'Parsing done', the server reports an initialization status again and crashes. + monitor.tagParseStatusChanged(initializingNofM, false); + strictEqual(monitor.serverCrashed(20 * minute), CrashAction.StopInitializationCrashLoop); + }); + + it('still stops after five crashes in three minutes when the workspace was parsed in between', () => { + const actions: CrashAction[] = []; + for (let i: number = 0; i < 5; i++) { + monitor.serverStarted(); + replay(healthySingleRoot); + actions.push(monitor.serverCrashed(i * 30000)); + } + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.StopCrashedTooOften]); + }); + + it('ignores "Parsing done" from a server that was stopped or has crashed', () => { + crash(0, true); + crash(10 * minute, true); + // Between the crash and the start of the replacement. + monitor.workspaceParsingDone(); + strictEqual(crash(20 * minute, true), CrashAction.StopInitializationCrashLoop); + + const other: WorkspaceInitializationMonitor = new WorkspaceInitializationMonitor(() => { stuckCount++; }); + for (const at of [0, 10 * minute]) { + other.serverStarted(); + other.setParsingWorkspace(true); + other.tagParseStatusChanged(initializingNofM, false); + strictEqual(other.serverCrashed(at), CrashAction.Restart); + } + other.serverStarted(); + other.serverStopped(); + other.workspaceParsingDone(); + other.serverStarted(); + other.setParsingWorkspace(true); + other.tagParseStatusChanged(initializingNofM, false); + strictEqual(other.serverCrashed(20 * minute), CrashAction.StopInitializationCrashLoop); + }); + + it('reports the existing reason when both rules apply to the same crash', () => { + const actions: CrashAction[] = [crash(0, false), crash(10000, false), crash(20000, true), crash(30000, true), crash(40000, true)]; + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.Restart, CrashAction.StopCrashedTooOften]); + }); + + it('counts a crash that happens while another status interrupts the phase for a moment', () => { + const actions: CrashAction[] = []; + for (let i: number = 0; i < maxConsecutiveInitializationCrashes; i++) { + monitor.serverStarted(); + enterInitialization(); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(initializationStatusGraceMs - 1); + actions.push(monitor.serverCrashed(clock.now)); + clock.tick(10 * minute); + } + deepStrictEqual(actions, [CrashAction.Restart, CrashAction.Restart, CrashAction.StopInitializationCrashLoop]); + }); + + it('does not count a crash after the other status has lasted', () => { + const actions: CrashAction[] = []; + for (let i: number = 0; i < maxConsecutiveInitializationCrashes + 1; i++) { + monitor.serverStarted(); + enterInitialization(); + monitor.tagParseStatusChanged(parsingFilesNofM, false); + clock.tick(initializationStatusGraceMs); + actions.push(monitor.serverCrashed(clock.now)); + clock.tick(10 * minute); + } + deepStrictEqual(actions, new Array(maxConsecutiveInitializationCrashes + 1).fill(CrashAction.Restart)); + }); + + it('keeps the crash history when a replacement server starts', () => { + crash(0, true); + crash(1000, true); + monitor.serverStarted(); + monitor.serverStarted(); + strictEqual(crash(2000, true), CrashAction.StopInitializationCrashLoop); + }); + + it('uses the state at the time of the crash, not a state that was left earlier', () => { + crash(0, true); + crash(10 * minute, true); + monitor.serverStarted(); + replay(slowButFinite); + // The server has been parsing files for a while when it crashes. + clock.tick(initializationStatusGraceMs); + strictEqual(monitor.serverCrashed(20 * minute), CrashAction.Restart); + }); + }); +});