-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathvariant-analysis-monitor.ts
More file actions
206 lines (176 loc) · 6.58 KB
/
variant-analysis-monitor.ts
File metadata and controls
206 lines (176 loc) · 6.58 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
import { env, EventEmitter } from "vscode";
import { getVariantAnalysis } from "./gh-api/gh-api-client";
import { RequestError } from "@octokit/request-error";
import type {
VariantAnalysis,
VariantAnalysisScannedRepository,
VariantAnalysisStatus,
} from "./shared/variant-analysis";
import {
isFinalVariantAnalysisStatus,
repoHasDownloadableArtifact,
} from "./shared/variant-analysis";
import type { VariantAnalysis as ApiVariantAnalysis } from "./gh-api/variant-analysis";
import { mapUpdatedVariantAnalysis } from "./variant-analysis-mapper";
import { DisposableObject } from "../common/disposable-object";
import { sleep } from "../common/time";
import { getErrorMessage } from "../common/helpers-pure";
import type { App } from "../common/app";
import { showAndLogWarningMessage } from "../common/logging";
export class VariantAnalysisMonitor extends DisposableObject {
// With a sleep of 5 seconds, the maximum number of attempts takes
// us to just over 2 days worth of monitoring.
public static maxAttemptCount = 17280;
public static sleepTime = 5000;
private readonly _onVariantAnalysisChange = this.push(
new EventEmitter<VariantAnalysis | undefined>(),
);
readonly onVariantAnalysisChange = this._onVariantAnalysisChange.event;
private readonly monitoringVariantAnalyses = new Set<number>();
constructor(
private readonly app: App,
private readonly shouldCancelMonitor: (
variantAnalysisId: number,
) => Promise<boolean>,
private readonly getVariantAnalysisStatus: (
variantAnalysisId: number,
) => VariantAnalysisStatus,
) {
super();
}
public isMonitoringVariantAnalysis(variantAnalysisId: number): boolean {
return this.monitoringVariantAnalyses.has(variantAnalysisId);
}
public async monitorVariantAnalysis(
variantAnalysis: VariantAnalysis,
): Promise<void> {
if (this.monitoringVariantAnalyses.has(variantAnalysis.id)) {
void this.app.logger.log(
`Already monitoring variant analysis ${variantAnalysis.id}`,
);
return;
}
this.monitoringVariantAnalyses.add(variantAnalysis.id);
try {
await this._monitorVariantAnalysis(variantAnalysis);
} finally {
this.monitoringVariantAnalyses.delete(variantAnalysis.id);
}
}
private async _monitorVariantAnalysis(
variantAnalysis: VariantAnalysis,
): Promise<void> {
const variantAnalysisLabel = `${variantAnalysis.query.name} (${
variantAnalysis.language
}) [${new Date(variantAnalysis.executionStartTime).toLocaleString(
env.language,
)}]`;
let attemptCount = 0;
const scannedReposDownloaded: number[] = [];
let lastErrorShown: string | undefined = undefined;
while (attemptCount <= VariantAnalysisMonitor.maxAttemptCount) {
await sleep(VariantAnalysisMonitor.sleepTime);
if (await this.shouldCancelMonitor(variantAnalysis.id)) {
return;
}
let variantAnalysisSummary: ApiVariantAnalysis;
try {
variantAnalysisSummary = await getVariantAnalysis(
this.app.credentials,
variantAnalysis.controllerRepo.id,
variantAnalysis.id,
);
} catch (e) {
const errorMessage = getErrorMessage(e);
const message = `Error while monitoring variant analysis ${variantAnalysisLabel}: ${errorMessage}`;
// If we have already shown this error to the user, don't show it again.
if (lastErrorShown === errorMessage) {
void this.app.logger.log(message);
} else {
void showAndLogWarningMessage(this.app.logger, message);
lastErrorShown = errorMessage;
}
if (e instanceof RequestError && e.status === 404) {
// We want to show the error message to the user, but we don't want to
// keep polling for the variant analysis if it no longer exists.
// Therefore, this block is down here rather than at the top of the
// catch block.
void this.app.logger.log(
`Variant analysis ${variantAnalysisLabel} no longer exists or is no longer accessible, stopping monitoring.`,
);
// Cancel monitoring on 404, as this probably means the user does not have access to it anymore
// e.g. lost access to repo, or repo was deleted
return;
}
continue;
}
// Get the current status of the variant analysis as known by the rest
// of the app, because it may have changed by the user, but the API
// may not be aware of it yet.
const currentStatus = this.getVariantAnalysisStatus(variantAnalysis.id);
variantAnalysis = mapUpdatedVariantAnalysis(
variantAnalysis,
currentStatus,
variantAnalysisSummary,
);
this._onVariantAnalysisChange.fire(variantAnalysis);
const downloadedRepos = this.downloadVariantAnalysisResults(
variantAnalysis,
scannedReposDownloaded,
);
scannedReposDownloaded.push(...downloadedRepos);
if (isFinalVariantAnalysisStatus(variantAnalysis.status)) {
break;
}
attemptCount++;
// Reset the last error shown if we have successfully retrieved the variant analysis.
lastErrorShown = undefined;
}
}
private scheduleForDownload(
scannedRepo: VariantAnalysisScannedRepository,
variantAnalysisSummary: VariantAnalysis,
) {
void this.app.commands.execute(
"codeQL.autoDownloadVariantAnalysisResult",
scannedRepo,
variantAnalysisSummary,
);
}
private shouldDownload(
scannedRepo: VariantAnalysisScannedRepository,
alreadyDownloaded: number[],
): boolean {
return (
!alreadyDownloaded.includes(scannedRepo.repository.id) &&
repoHasDownloadableArtifact(scannedRepo)
);
}
private getReposToDownload(
variantAnalysisSummary: VariantAnalysis,
alreadyDownloaded: number[],
): VariantAnalysisScannedRepository[] {
if (variantAnalysisSummary.scannedRepos) {
return variantAnalysisSummary.scannedRepos.filter((scannedRepo) =>
this.shouldDownload(scannedRepo, alreadyDownloaded),
);
} else {
return [];
}
}
private downloadVariantAnalysisResults(
variantAnalysisSummary: VariantAnalysis,
scannedReposDownloaded: number[],
): number[] {
const repoResultsToDownload = this.getReposToDownload(
variantAnalysisSummary,
scannedReposDownloaded,
);
const downloadedRepos: number[] = [];
repoResultsToDownload.forEach((scannedRepo) => {
downloadedRepos.push(scannedRepo.repository.id);
this.scheduleForDownload(scannedRepo, variantAnalysisSummary);
});
return downloadedRepos;
}
}