Skip to content

Commit 551f76c

Browse files
Create a new octokit instance every time
I believe this doesn't change the user-visible behaviour at all. The user won't be prompted to log in any more or less often than they would have done before. One benefit of this is that we can remove the registerListeners method because we no longer need to know if the cached octokit is still valid. Instead we just call vscode.authentication.getSession every time and it will return the current session, which might be different from the last time we called it. This might prompt the user to log in, but that would have happened anyway because when the session changed we would have overwritten our cached octokit instance. Another benefit is that we no longer need the extension context and this removed a surprisingly large amount of code where we are passing this parameter around because we need it for the credentials. The only downside I can see is that we call getSession more often and create more javascript objects in general. I believe the performance impact of this will be negligible and not worth worrying about.
1 parent 8f34f6a commit 551f76c

12 files changed

Lines changed: 40 additions & 86 deletions

File tree

extensions/ql-vscode/src/authentication.ts

Lines changed: 17 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -13,42 +13,38 @@ const SCOPES = ["repo", "gist"];
1313
* Handles authentication to GitHub, using the VS Code [authentication API](https://code.visualstudio.com/api/references/vscode-api#authentication).
1414
*/
1515
export class Credentials {
16+
/**
17+
* A specific octokit to return, otherwise a new authenticated octokit will be created when needed.
18+
*/
1619
private octokit: Octokit.Octokit | undefined;
1720

1821
// Explicitly make the constructor private, so that we can't accidentally call the constructor from outside the class
1922
// without also initializing the class.
20-
// eslint-disable-next-line @typescript-eslint/no-empty-function
21-
private constructor() {}
23+
private constructor(octokit?: Octokit.Octokit) {
24+
this.octokit = octokit;
25+
}
2226

2327
/**
24-
* Initializes an instance of credentials with an octokit instance.
25-
*
26-
* Do not call this method until you know you actually need an instance of credentials.
27-
* since calling this method will require the user to log in.
28+
* Initializes a Credentials instance. This will generate octokit instances
29+
* authenticated as the user. If there is not already an authenticated GitHub
30+
* session availabeT then the user will be prompted to log in.
2831
*
29-
* @param context The extension context.
3032
* @returns An instance of credentials.
3133
*/
32-
static async initialize(
33-
context: vscode.ExtensionContext,
34-
): Promise<Credentials> {
35-
const c = new Credentials();
36-
c.registerListeners(context);
37-
return c;
34+
static async initialize(): Promise<Credentials> {
35+
return new Credentials();
3836
}
3937

4038
/**
4139
* Initializes an instance of credentials with an octokit instance using
42-
* a token from the user's GitHub account. This method is meant to be
43-
* used non-interactive environments such as tests.
40+
* a specific known token. This method is meant to be used non-interactive
41+
* environments such as tests.
4442
*
4543
* @param overrideToken The GitHub token to use for authentication.
4644
* @returns An instance of credentials.
4745
*/
4846
static async initializeWithToken(overrideToken: string) {
49-
const c = new Credentials();
50-
c.octokit = new Octokit.Octokit({ auth: overrideToken, retry });
51-
return c;
47+
return new Credentials(new Octokit.Octokit({ auth: overrideToken, retry }));
5248
}
5349

5450
private async createOctokit(): Promise<Octokit.Octokit> {
@@ -64,26 +60,15 @@ export class Credentials {
6460
});
6561
}
6662

67-
registerListeners(context: vscode.ExtensionContext): void {
68-
// Sessions are changed when a user logs in or logs out.
69-
context.subscriptions.push(
70-
vscode.authentication.onDidChangeSessions(async (e) => {
71-
if (e.provider.id === GITHUB_AUTH_PROVIDER_ID) {
72-
this.octokit = undefined;
73-
}
74-
}),
75-
);
76-
}
77-
7863
/**
7964
* Creates or returns an instance of Octokit.
8065
*
8166
* @returns An instance of Octokit.
8267
*/
8368
async getOctokit(): Promise<Octokit.Octokit> {
84-
if (!this.octokit) {
85-
this.octokit = await this.createOctokit();
69+
if (this.octokit) {
70+
return this.octokit;
8671
}
87-
return this.octokit;
72+
return await this.createOctokit();
8873
}
8974
}

extensions/ql-vscode/src/extension.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ async function activateWithInstalledDistribution(
591591
qs,
592592
getContextStoragePath(ctx),
593593
ctx.extensionPath,
594-
() => Credentials.initialize(ctx),
594+
() => Credentials.initialize(),
595595
);
596596
databaseUI.init();
597597
ctx.subscriptions.push(databaseUI);
@@ -1236,7 +1236,7 @@ async function activateWithInstalledDistribution(
12361236
commandRunner(
12371237
"codeQL.exportRemoteQueryResults",
12381238
async (queryId: string) => {
1239-
await exportRemoteQueryResults(qhm, rqm, ctx, queryId);
1239+
await exportRemoteQueryResults(qhm, rqm, queryId);
12401240
},
12411241
),
12421242
);
@@ -1251,7 +1251,6 @@ async function activateWithInstalledDistribution(
12511251
filterSort?: RepositoriesFilterSortStateWithIds,
12521252
) => {
12531253
await exportVariantAnalysisResults(
1254-
ctx,
12551254
variantAnalysisManager,
12561255
variantAnalysisId,
12571256
filterSort,
@@ -1356,7 +1355,7 @@ async function activateWithInstalledDistribution(
13561355
"codeQL.chooseDatabaseGithub",
13571356
async (progress: ProgressCallback, token: CancellationToken) => {
13581357
const credentials = isCanary()
1359-
? await Credentials.initialize(ctx)
1358+
? await Credentials.initialize()
13601359
: undefined;
13611360
await databaseUI.handleChooseDatabaseGithub(
13621361
credentials,
@@ -1411,7 +1410,7 @@ async function activateWithInstalledDistribution(
14111410
* Credentials for authenticating to GitHub.
14121411
* These are used when making API calls.
14131412
*/
1414-
const credentials = await Credentials.initialize(ctx);
1413+
const credentials = await Credentials.initialize();
14151414
const octokit = await credentials.getOctokit();
14161415
const userInfo = await octokit.users.getAuthenticated();
14171416
void showAndLogInformationMessage(

extensions/ql-vscode/src/query-history.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ export class QueryHistoryManager extends DisposableObject {
397397
private readonly variantAnalysisManager: VariantAnalysisManager,
398398
private readonly evalLogViewer: EvalLogViewer,
399399
private readonly queryStorageDir: string,
400-
private readonly ctx: ExtensionContext,
400+
ctx: ExtensionContext,
401401
private readonly queryHistoryConfigListener: QueryHistoryConfig,
402402
private readonly labelProvider: HistoryItemLabelProvider,
403403
private readonly doCompareCallback: (
@@ -633,7 +633,7 @@ export class QueryHistoryManager extends DisposableObject {
633633
}
634634

635635
private getCredentials() {
636-
return Credentials.initialize(this.ctx);
636+
return Credentials.initialize();
637637
}
638638

639639
/**

extensions/ql-vscode/src/remote-queries/analyses-results-manager.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { pathExists } from "fs-extra";
22
import { EOL } from "os";
33
import { extname } from "path";
4-
import { CancellationToken, ExtensionContext } from "vscode";
4+
import { CancellationToken } from "vscode";
55

66
import { Credentials } from "../authentication";
77
import { Logger } from "../common";
@@ -26,7 +26,6 @@ export class AnalysesResultsManager {
2626
private readonly analysesResults: Map<string, AnalysisResults[]>;
2727

2828
constructor(
29-
private readonly ctx: ExtensionContext,
3029
private readonly cliServer: CodeQLCliServer,
3130
readonly storagePath: string,
3231
private readonly logger: Logger,
@@ -43,7 +42,7 @@ export class AnalysesResultsManager {
4342
return;
4443
}
4544

46-
const credentials = await Credentials.initialize(this.ctx);
45+
const credentials = await Credentials.initialize();
4746

4847
void this.logger.log(
4948
`Downloading and processing results for ${analysisSummary.nwo}`,
@@ -77,7 +76,7 @@ export class AnalysesResultsManager {
7776
(x) => !this.isAnalysisInMemory(x),
7877
);
7978

80-
const credentials = await Credentials.initialize(this.ctx);
79+
const credentials = await Credentials.initialize();
8180

8281
void this.logger.log("Downloading and processing analyses results");
8382

extensions/ql-vscode/src/remote-queries/export-results.ts

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { ensureDir, writeFile } from "fs-extra";
44
import {
55
commands,
66
CancellationToken,
7-
ExtensionContext,
87
Uri,
98
ViewColumn,
109
window,
@@ -74,7 +73,6 @@ export async function exportSelectedRemoteQueryResults(
7473
export async function exportRemoteQueryResults(
7574
queryHistoryManager: QueryHistoryManager,
7675
remoteQueriesManager: RemoteQueriesManager,
77-
ctx: ExtensionContext,
7876
queryId: string,
7977
): Promise<void> {
8078
const queryHistoryItem = queryHistoryManager.getRemoteQueryById(queryId);
@@ -107,7 +105,6 @@ export async function exportRemoteQueryResults(
107105
const exportedResultsDirectory = join(exportDirectory, "exported-results");
108106

109107
await exportRemoteQueryAnalysisResults(
110-
ctx,
111108
exportedResultsDirectory,
112109
query,
113110
analysesResults,
@@ -116,7 +113,6 @@ export async function exportRemoteQueryResults(
116113
}
117114

118115
export async function exportRemoteQueryAnalysisResults(
119-
ctx: ExtensionContext,
120116
exportedResultsPath: string,
121117
query: RemoteQuery,
122118
analysesResults: AnalysisResults[],
@@ -126,7 +122,6 @@ export async function exportRemoteQueryAnalysisResults(
126122
const markdownFiles = generateMarkdown(query, analysesResults, exportFormat);
127123

128124
await exportResults(
129-
ctx,
130125
exportedResultsPath,
131126
description,
132127
markdownFiles,
@@ -141,7 +136,6 @@ const MAX_VARIANT_ANALYSIS_EXPORT_PROGRESS_STEPS = 2;
141136
* The user is prompted to select the export format.
142137
*/
143138
export async function exportVariantAnalysisResults(
144-
ctx: ExtensionContext,
145139
variantAnalysisManager: VariantAnalysisManager,
146140
variantAnalysisId: number,
147141
filterSort: RepositoriesFilterSortStateWithIds | undefined,
@@ -255,7 +249,6 @@ export async function exportVariantAnalysisResults(
255249
);
256250

257251
await exportVariantAnalysisAnalysisResults(
258-
ctx,
259252
exportedResultsDirectory,
260253
variantAnalysis,
261254
getAnalysesResults(),
@@ -266,7 +259,6 @@ export async function exportVariantAnalysisResults(
266259
}
267260

268261
export async function exportVariantAnalysisAnalysisResults(
269-
ctx: ExtensionContext,
270262
exportedResultsPath: string,
271263
variantAnalysis: VariantAnalysis,
272264
analysesResults: AsyncIterable<
@@ -297,7 +289,6 @@ export async function exportVariantAnalysisAnalysisResults(
297289
);
298290

299291
await exportResults(
300-
ctx,
301292
exportedResultsPath,
302293
description,
303294
markdownFiles,
@@ -341,7 +332,6 @@ async function determineExportFormat(): Promise<"gist" | "local" | undefined> {
341332
}
342333

343334
export async function exportResults(
344-
ctx: ExtensionContext,
345335
exportedResultsPath: string,
346336
description: string,
347337
markdownFiles: MarkdownFile[],
@@ -354,7 +344,7 @@ export async function exportResults(
354344
}
355345

356346
if (exportFormat === "gist") {
357-
await exportToGist(ctx, description, markdownFiles, progress, token);
347+
await exportToGist(description, markdownFiles, progress, token);
358348
} else if (exportFormat === "local") {
359349
await exportToLocalMarkdown(
360350
exportedResultsPath,
@@ -366,7 +356,6 @@ export async function exportResults(
366356
}
367357

368358
export async function exportToGist(
369-
ctx: ExtensionContext,
370359
description: string,
371360
markdownFiles: MarkdownFile[],
372361
progress?: ProgressCallback,
@@ -378,7 +367,7 @@ export async function exportToGist(
378367
message: "Creating Gist",
379368
});
380369

381-
const credentials = await Credentials.initialize(ctx);
370+
const credentials = await Credentials.initialize();
382371

383372
if (token?.isCancellationRequested) {
384373
throw new UserCancellationException("Cancelled");

extensions/ql-vscode/src/remote-queries/remote-queries-manager.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,20 +81,19 @@ export class RemoteQueriesManager extends DisposableObject {
8181
private readonly view: RemoteQueriesView;
8282

8383
constructor(
84-
private readonly ctx: ExtensionContext,
84+
ctx: ExtensionContext,
8585
private readonly cliServer: CodeQLCliServer,
8686
private readonly storagePath: string,
8787
logger: Logger,
8888
) {
8989
super();
9090
this.analysesResultsManager = new AnalysesResultsManager(
91-
ctx,
9291
cliServer,
9392
storagePath,
9493
logger,
9594
);
9695
this.view = new RemoteQueriesView(ctx, logger, this.analysesResultsManager);
97-
this.remoteQueriesMonitor = new RemoteQueriesMonitor(ctx, logger);
96+
this.remoteQueriesMonitor = new RemoteQueriesMonitor(logger);
9897

9998
this.remoteQueryAddedEventEmitter = this.push(
10099
new EventEmitter<NewQueryEvent>(),
@@ -160,7 +159,7 @@ export class RemoteQueriesManager extends DisposableObject {
160159
progress: ProgressCallback,
161160
token: CancellationToken,
162161
): Promise<void> {
163-
const credentials = await Credentials.initialize(this.ctx);
162+
const credentials = await Credentials.initialize();
164163

165164
const {
166165
actionBranch,
@@ -218,7 +217,7 @@ export class RemoteQueriesManager extends DisposableObject {
218217
remoteQuery: RemoteQuery,
219218
cancellationToken: CancellationToken,
220219
): Promise<void> {
221-
const credentials = await Credentials.initialize(this.ctx);
220+
const credentials = await Credentials.initialize();
222221

223222
const queryWorkflowResult = await this.remoteQueriesMonitor.monitorQuery(
224223
remoteQuery,

extensions/ql-vscode/src/remote-queries/remote-queries-monitor.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,13 @@ export class RemoteQueriesMonitor {
1616
private static readonly maxAttemptCount = 17280;
1717
private static readonly sleepTime = 5000;
1818

19-
constructor(
20-
private readonly extensionContext: vscode.ExtensionContext,
21-
private readonly logger: Logger,
22-
) {}
19+
constructor(private readonly logger: Logger) {}
2320

2421
public async monitorQuery(
2522
remoteQuery: RemoteQuery,
2623
cancellationToken: vscode.CancellationToken,
2724
): Promise<RemoteQueryWorkflowResult> {
28-
const credentials = await Credentials.initialize(this.extensionContext);
25+
const credentials = await Credentials.initialize();
2926

3027
let attemptCount = 0;
3128

extensions/ql-vscode/src/remote-queries/variant-analysis-manager.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ export class VariantAnalysisManager
106106
super();
107107
this.variantAnalysisMonitor = this.push(
108108
new VariantAnalysisMonitor(
109-
ctx,
110109
this.shouldCancelMonitorVariantAnalysis.bind(this),
111110
),
112111
);
@@ -125,7 +124,7 @@ export class VariantAnalysisManager
125124
progress: ProgressCallback,
126125
token: CancellationToken,
127126
): Promise<void> {
128-
const credentials = await Credentials.initialize(this.ctx);
127+
const credentials = await Credentials.initialize();
129128

130129
const {
131130
actionBranch,
@@ -479,7 +478,7 @@ export class VariantAnalysisManager
479478

480479
await this.onRepoStateUpdated(variantAnalysis.id, repoState);
481480

482-
const credentials = await Credentials.initialize(this.ctx);
481+
const credentials = await Credentials.initialize();
483482

484483
if (cancellationToken && cancellationToken.isCancellationRequested) {
485484
repoState.downloadStatus =
@@ -577,7 +576,7 @@ export class VariantAnalysisManager
577576
);
578577
}
579578

580-
const credentials = await Credentials.initialize(this.ctx);
579+
const credentials = await Credentials.initialize();
581580

582581
void showAndLogInformationMessage(
583582
"Cancelling variant analysis. This may take a while.",

0 commit comments

Comments
 (0)