forked from github/vscode-codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariant-analysis-results-manager.ts
More file actions
362 lines (308 loc) · 9.96 KB
/
variant-analysis-results-manager.ts
File metadata and controls
362 lines (308 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import { appendFile, pathExists, rm } from "fs-extra";
import { EOL } from "os";
import { join } from "path";
import type { Logger } from "../common/logging";
import type {
AnalysisAlert,
AnalysisRawResults,
} from "./shared/analysis-result";
import { sarifParser } from "../common/sarif-parser";
import { extractAnalysisAlerts } from "./sarif-processing";
import type { CodeQLCliServer } from "../codeql-cli/cli";
import { extractRawResults } from "./bqrs-processing";
import { VariantAnalysisRepoStatus } from "./shared/variant-analysis";
import type {
VariantAnalysis,
VariantAnalysisRepositoryTask,
VariantAnalysisScannedRepositoryResult,
} from "./shared/variant-analysis";
import type { DisposeHandler } from "../common/disposable-object";
import { DisposableObject } from "../common/disposable-object";
import { EventEmitter } from "vscode";
import { unzipToDirectoryConcurrently } from "../common/unzip-concurrently";
import { readRepoTask, writeRepoTask } from "./repo-tasks-store";
import type { VariantAnalysisConfig } from "../config";
type CacheKey = `${number}/${string}`;
const createCacheKey = (
variantAnalysisId: number,
repositoryFullName: string,
): CacheKey => `${variantAnalysisId}/${repositoryFullName}`;
type ResultDownloadedEvent = {
variantAnalysisId: number;
repoTask: VariantAnalysisRepositoryTask;
};
export type LoadResultsOptions = {
// If true, when results are loaded from storage, they will not be stored in the cache. This reduces memory usage if
// results are only needed temporarily (e.g. for exporting results to a different format).
skipCacheStore?: boolean;
};
export class VariantAnalysisResultsManager extends DisposableObject {
private static readonly RESULTS_DIRECTORY = "results";
private static readonly RESULTS_SARIF_FILENAME = "results.sarif";
private readonly cachedResults: Map<
CacheKey,
VariantAnalysisScannedRepositoryResult
>;
private readonly _onResultDownloaded = this.push(
new EventEmitter<ResultDownloadedEvent>(),
);
readonly onResultDownloaded = this._onResultDownloaded.event;
private readonly _onResultLoaded = this.push(
new EventEmitter<VariantAnalysisScannedRepositoryResult>(),
);
readonly onResultLoaded = this._onResultLoaded.event;
constructor(
private readonly cliServer: CodeQLCliServer,
private readonly config: VariantAnalysisConfig,
private readonly logger: Logger,
) {
super();
this.cachedResults = new Map();
}
public async download(
variantAnalysisId: number,
repoTask: VariantAnalysisRepositoryTask,
variantAnalysisStoragePath: string,
onDownloadPercentageChanged: (downloadPercentage: number) => Promise<void>,
): Promise<void> {
if (!repoTask.artifactUrl) {
throw new Error("Missing artifact URL");
}
const resultDirectory = this.getRepoStorageDirectory(
variantAnalysisStoragePath,
repoTask.repository.fullName,
);
await writeRepoTask(resultDirectory, repoTask);
const zipFilePath = join(resultDirectory, "results.zip");
// in case of restarted download delete possible artifact from previous download
await rm(zipFilePath, { force: true });
const response = await fetch(repoTask.artifactUrl);
const responseSize = parseInt(
response.headers.get("content-length") || "1",
);
if (!response.body) {
throw new Error("No response body found");
}
const reader = response.body.getReader();
let amountDownloaded = 0;
for (;;) {
const { value: chunk, done } = await reader.read();
if (done) {
break;
}
await appendFile(zipFilePath, Buffer.from(chunk));
amountDownloaded += chunk.length;
await onDownloadPercentageChanged(
Math.floor((amountDownloaded / responseSize) * 100),
);
}
const unzippedFilesDirectory = join(
resultDirectory,
VariantAnalysisResultsManager.RESULTS_DIRECTORY,
);
await unzipToDirectoryConcurrently(zipFilePath, unzippedFilesDirectory);
this._onResultDownloaded.fire({
variantAnalysisId,
repoTask,
});
}
public async loadResults(
variantAnalysisId: number,
variantAnalysisStoragePath: string,
repositoryFullName: string,
options?: LoadResultsOptions,
): Promise<VariantAnalysisScannedRepositoryResult> {
const result = this.cachedResults.get(
createCacheKey(variantAnalysisId, repositoryFullName),
);
if (result) {
this._onResultLoaded.fire(result);
return result;
}
if (options?.skipCacheStore) {
return this.loadResultsFromStorage(
variantAnalysisId,
variantAnalysisStoragePath,
repositoryFullName,
);
}
return this.loadResultsIntoMemory(
variantAnalysisId,
variantAnalysisStoragePath,
repositoryFullName,
);
}
private async loadResultsIntoMemory(
variantAnalysisId: number,
variantAnalysisStoragePath: string,
repositoryFullName: string,
): Promise<VariantAnalysisScannedRepositoryResult> {
const result = await this.loadResultsFromStorage(
variantAnalysisId,
variantAnalysisStoragePath,
repositoryFullName,
);
this.cachedResults.set(
createCacheKey(variantAnalysisId, repositoryFullName),
result,
);
this._onResultLoaded.fire(result);
return result;
}
private async loadResultsFromStorage(
variantAnalysisId: number,
variantAnalysisStoragePath: string,
repositoryFullName: string,
): Promise<VariantAnalysisScannedRepositoryResult> {
if (
!(await this.isVariantAnalysisRepoDownloaded(
variantAnalysisStoragePath,
repositoryFullName,
))
) {
throw new Error("Variant analysis results not downloaded");
}
const storageDirectory = this.getRepoStorageDirectory(
variantAnalysisStoragePath,
repositoryFullName,
);
const repoTask: VariantAnalysisRepositoryTask =
await readRepoTask(storageDirectory);
if (!repoTask.databaseCommitSha || !repoTask.sourceLocationPrefix) {
throw new Error("Missing database commit SHA");
}
const fileLinkPrefix = this.createGitHubFileLinkPrefix(
repoTask.repository.fullName,
repoTask.databaseCommitSha,
);
const resultsDirectory = join(
storageDirectory,
VariantAnalysisResultsManager.RESULTS_DIRECTORY,
);
const sarifPath = join(
resultsDirectory,
VariantAnalysisResultsManager.RESULTS_SARIF_FILENAME,
);
const bqrsPath = join(resultsDirectory, "results.bqrs");
let interpretedResults: AnalysisAlert[] | undefined;
let rawResults: AnalysisRawResults | undefined;
if (await pathExists(sarifPath)) {
interpretedResults = await this.readSarifResults(
sarifPath,
fileLinkPrefix,
);
}
if (await pathExists(bqrsPath)) {
rawResults = await this.readBqrsResults(
bqrsPath,
fileLinkPrefix,
repoTask.sourceLocationPrefix,
);
}
if (!interpretedResults && !rawResults) {
throw new Error("Missing results file");
}
return {
variantAnalysisId,
repositoryId: repoTask.repository.id,
interpretedResults,
rawResults,
};
}
public async isVariantAnalysisRepoDownloaded(
variantAnalysisStoragePath: string,
repositoryFullName: string,
): Promise<boolean> {
return await pathExists(
this.getRepoStorageDirectory(
variantAnalysisStoragePath,
repositoryFullName,
),
);
}
private async readBqrsResults(
filePath: string,
fileLinkPrefix: string,
sourceLocationPrefix: string,
): Promise<AnalysisRawResults> {
return await extractRawResults(
this.cliServer,
this.logger,
filePath,
fileLinkPrefix,
sourceLocationPrefix,
);
}
private async readSarifResults(
filePath: string,
fileLinkPrefix: string,
): Promise<AnalysisAlert[]> {
const sarifLog = await sarifParser(filePath);
const processedSarif = extractAnalysisAlerts(sarifLog, fileLinkPrefix);
if (processedSarif.errors.length) {
void this.logger.log(
`Error processing SARIF file: ${EOL}${processedSarif.errors.join(EOL)}`,
);
}
return processedSarif.alerts;
}
public getRepoStorageDirectory(
variantAnalysisStoragePath: string,
fullName: string,
): string {
return join(variantAnalysisStoragePath, fullName);
}
public getRepoResultsSarifStoragePath(
variantAnalysisStoragePath: string,
fullName: string,
): string {
return join(
this.getRepoStorageDirectory(variantAnalysisStoragePath, fullName),
VariantAnalysisResultsManager.RESULTS_DIRECTORY,
VariantAnalysisResultsManager.RESULTS_SARIF_FILENAME,
);
}
private createGitHubFileLinkPrefix(fullName: string, sha: string): string {
return new URL(
`/${fullName}/blob/${sha}`,
this.config.githubUrl,
).toString();
}
public removeAnalysisResults(variantAnalysis: VariantAnalysis) {
const scannedRepos = variantAnalysis.scannedRepos;
if (scannedRepos) {
scannedRepos.forEach((scannedRepo) => {
const cacheKey = createCacheKey(
variantAnalysis.id,
scannedRepo.repository.fullName,
);
if (this.cachedResults.get(cacheKey)) {
this.cachedResults.delete(cacheKey);
}
});
}
}
public getLoadedResultsForVariantAnalysis(
variantAnalysis: VariantAnalysis,
): VariantAnalysisScannedRepositoryResult[] {
const scannedRepos = variantAnalysis.scannedRepos?.filter(
(r) => r.analysisStatus === VariantAnalysisRepoStatus.Succeeded,
);
if (!scannedRepos) {
return [];
}
return scannedRepos
.map((scannedRepo) =>
this.cachedResults.get(
createCacheKey(variantAnalysis.id, scannedRepo.repository.fullName),
),
)
.filter(
(r): r is VariantAnalysisScannedRepositoryResult => r !== undefined,
);
}
public dispose(disposeHandler?: DisposeHandler) {
super.dispose(disposeHandler);
this.cachedResults.clear();
}
}