Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/gitProviders/GitHubContactServiceProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export class GitHubContactServiceProvider implements ContactServiceProvider {
}
const origin = await this.pullRequestManager.folderManagers[0]?.getOrigin();
if (origin) {
const currentUser = origin.hub.currentUser ? await origin.hub.currentUser : undefined;
const currentUser = await origin.getAuthenticatedUser();
if (currentUser) {
return currentUser.login;
}
Expand Down
37 changes: 31 additions & 6 deletions src/github/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,19 +551,25 @@ export class CredentialStore extends Disposable {
}

public async isCurrentUser(authProviderId: AuthProvider, username: string): Promise<boolean> {
const api = authProviderId === AuthProvider.github ? this._githubAPI : this._githubEnterpriseAPI;
return (await api?.currentUser)?.login === username;
return (await this.getCurrentUser(authProviderId))?.login === username;
}

public async getIsEmu(authProviderId: AuthProvider): Promise<boolean> {
const github = this.getHub(authProviderId);
this.ensureCurrentUser(github);
return !!(await github?.isEmu);
}

public getCurrentUser(authProviderId: AuthProvider): Promise<IAccount> {
const github = this.getHub(authProviderId);
const octokit = github?.octokit;
return (octokit && github?.currentUser)!;
this.ensureCurrentUser(github);
return github?.currentUser!;
}

private ensureCurrentUser(github: GitHub | undefined): void {
if (github && (!github.currentUser || !github.isEmu)) {
this.setCurrentUser(github);
}
}

private setCurrentUser(github: GitHub): void {
Expand All @@ -577,8 +583,27 @@ export class CredentialStore extends Disposable {
reject(e);
});
});
github.currentUser = getUser.then(result => convertRESTUserToAccount(result.data));
github.isEmu = getUser.then(result => result.data.plan?.name === 'emu_user');
let currentUser: Promise<IAccount>;
let isEmu: Promise<boolean>;
const clearFailedRequest = () => {
if (github.currentUser === currentUser && github.isEmu === isEmu) {
github.currentUser = undefined;
github.isEmu = undefined;
}
};
currentUser = getUser.then(result => convertRESTUserToAccount(result.data), e => {
clearFailedRequest();
throw e;
});
isEmu = getUser.then(result => result.data.plan?.name === 'emu_user', e => {
clearFailedRequest();
throw e;
});
github.currentUser = currentUser;
github.isEmu = isEmu;

void currentUser.catch(() => undefined);
void isEmu.catch(() => undefined);
}

private async getSession(authProviderId: AuthProvider, getAuthSessionOptions: vscode.AuthenticationGetSessionOptions, scopes: string[], requireScopes: boolean): Promise<{ session: vscode.AuthenticationSession | undefined, isNew: boolean, scopes: string[] }> {
Expand Down
19 changes: 13 additions & 6 deletions src/github/githubRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ export class GitHubRepository extends Disposable {
repo
});
Logger.debug(`Fetch metadata for repo ${owner}/${repo} - done`, this.id);
const metadata = { ...result.data, currentUser: await this._hub?.currentUser };
const metadata = { ...result.data, currentUser: await this.getAuthenticatedUser() };
return metadata;
}

Expand All @@ -437,15 +437,22 @@ export class GitHubRepository extends Disposable {

Logger.debug(`Fetch metadata - enter`, this.id);
const { remote } = await this.ensure();
this._metadata = this.getMetadataForRepo(remote.owner, remote.repositoryName).catch(e => {
if ((getErrorCode(e) === '404') && !isSamlError(e) && !this._isInaccessible) {
this._isInaccessible = true;
Logger.warn(`Repository ${remote.owner}/${remote.repositoryName} from remote ${remote.remoteName} in workspace folder ${this.rootUri.fsPath} returned HTTP 404 and will be skipped for this session.`, this.id);
const metadata = this.getMetadataForRepo(remote.owner, remote.repositoryName).catch(e => {
if (this._metadata === metadata) {
if ((getErrorCode(e) === '404') && !isSamlError(e)) {
if (!this._isInaccessible) {
this._isInaccessible = true;
Logger.warn(`Repository ${remote.owner}/${remote.repositoryName} from remote ${remote.remoteName} in workspace folder ${this.rootUri.fsPath} returned HTTP 404 and will be skipped for this session.`, this.id);
}
} else {
this._metadata = undefined;
}
}
throw e;
});
this._metadata = metadata;
Logger.debug(`Fetch metadata ${remote.owner}/${remote.repositoryName} - done`, this.id);
return this._metadata;
return metadata;
}

/**
Expand Down
44 changes: 25 additions & 19 deletions src/github/pullRequestOverview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ import { asPromise, formatError } from '../common/utils';
import { IRequestMessage, PULL_REQUEST_OVERVIEW_VIEW_TYPE } from '../common/webview';
import { toCheckRunLogUri } from '../view/checkRunLogContentProvider';

function withErrorContext<T>(operation: string, promise: Promise<T>): Promise<T> {
return promise.catch(e => {
throw new Error(`${operation} failed: ${formatError(e)}`);
});
}

export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestModel> {
public static override ID: string = 'PullRequestOverviewPanel';
public static override readonly viewType = PULL_REQUEST_OVERVIEW_VIEW_TYPE;
Expand Down Expand Up @@ -344,27 +350,27 @@ export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestMode

try {
const updatingPromise = Promise.all([
this._folderRepositoryManager.resolvePullRequest(
withErrorContext('Resolving pull request', this._folderRepositoryManager.resolvePullRequest(
pullRequestModel.remote.owner,
pullRequestModel.remote.repositoryName,
pullRequestModel.number,
),
pullRequestModel.getTimelineEvents(),
this._folderRepositoryManager.getPullRequestRepositoryDefaultBranch(pullRequestModel),
pullRequestModel.getStatusChecks(),
pullRequestModel.getReviewRequests(),
this._folderRepositoryManager.getPullRequestRepositoryAccessAndMergeMethods(pullRequestModel),
this._folderRepositoryManager.getBranchNameForPullRequest(pullRequestModel),
this._folderRepositoryManager.getCurrentUser(pullRequestModel.githubRepository),
pullRequestModel.canEdit(),
this._folderRepositoryManager.getOrgTeamsCount(pullRequestModel.githubRepository),
this._folderRepositoryManager.mergeQueueMethodForBranch(pullRequestModel.base.ref, pullRequestModel.remote.owner, pullRequestModel.remote.repositoryName),
this._folderRepositoryManager.isHeadUpToDateWithBase(pullRequestModel),
pullRequestModel.getMergeability(),
this._folderRepositoryManager.getPreferredEmail(pullRequestModel),
pullRequestModel.getCoAuthors(),
pullRequestModel.validateDraftMode(),
this._folderRepositoryManager.getAssignableUsers()
)),
withErrorContext('Fetching timeline events', pullRequestModel.getTimelineEvents()),
withErrorContext('Fetching the repository default branch', this._folderRepositoryManager.getPullRequestRepositoryDefaultBranch(pullRequestModel)),
withErrorContext('Fetching status checks', pullRequestModel.getStatusChecks()),
withErrorContext('Fetching review requests', pullRequestModel.getReviewRequests()),
withErrorContext('Fetching repository access and merge methods', this._folderRepositoryManager.getPullRequestRepositoryAccessAndMergeMethods(pullRequestModel)),
withErrorContext('Fetching the pull request branch', this._folderRepositoryManager.getBranchNameForPullRequest(pullRequestModel)),
withErrorContext('Fetching current user', this._folderRepositoryManager.getCurrentUser(pullRequestModel.githubRepository)),
withErrorContext('Checking edit permission', pullRequestModel.canEdit()),
withErrorContext('Fetching organization teams', this._folderRepositoryManager.getOrgTeamsCount(pullRequestModel.githubRepository)),
withErrorContext('Fetching the merge queue method', this._folderRepositoryManager.mergeQueueMethodForBranch(pullRequestModel.base.ref, pullRequestModel.remote.owner, pullRequestModel.remote.repositoryName)),
withErrorContext('Checking whether the branch is up to date', this._folderRepositoryManager.isHeadUpToDateWithBase(pullRequestModel)),
withErrorContext('Fetching mergeability', pullRequestModel.getMergeability()),
withErrorContext('Fetching the preferred email', this._folderRepositoryManager.getPreferredEmail(pullRequestModel)),
withErrorContext('Fetching co-authors', pullRequestModel.getCoAuthors()),
withErrorContext('Validating draft mode', pullRequestModel.validateDraftMode()),
withErrorContext('Fetching assignable users', this._folderRepositoryManager.getAssignableUsers())
]);
const clearingPromise = updatingPromise.finally(() => {
if (this._updatingPromise === clearingPromise) {
Expand Down Expand Up @@ -482,7 +488,7 @@ export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestMode
this._folderRepositoryManager.checkBranchUpToDate(pullRequest, true);
}
} catch (e) {
vscode.window.showErrorMessage(`Error updating pull request description: ${formatError(e)}`);
vscode.window.showErrorMessage(`Error updating pull request: ${formatError(e)}`);
}
}

Expand Down
65 changes: 63 additions & 2 deletions src/test/github/credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { strictEqual, deepStrictEqual } from 'assert';
import { deepStrictEqual, rejects, strictEqual } from 'assert';
import { Octokit } from '@octokit/rest';
import { SinonSandbox, createSandbox } from 'sinon';
import * as vscode from 'vscode';
import { AuthProvider } from '../../common/authentication';
import { findExistingSession } from '../../github/credentials';
import { CredentialStore, findExistingSession, GitHub } from '../../github/credentials';
import { LoggingApolloClient, LoggingOctokit, RateLogger } from '../../github/loggingOctokit';
import { MockExtensionContext } from '../mocks/mockExtensionContext';
import { MockTelemetry } from '../mocks/mockTelemetry';

const oldestScopes = ['read:user', 'user:email', 'repo'];
const defaultScopes = [...oldestScopes, 'workflow'];
Expand All @@ -29,6 +34,16 @@ function createSession(id: string, accountId: string, scopes: string[]): vscode.
}

describe('CredentialStore', function () {
let sinon: SinonSandbox;

beforeEach(function () {
sinon = createSandbox();
});

afterEach(function () {
sinon.restore();
});

describe('findExistingSession', function () {
it('keeps broader scope lookup on the preferred account', async function () {
const firstAccountAdditional = createSession('first-additional', 'first', additionalScopes);
Expand Down Expand Up @@ -99,4 +114,50 @@ describe('CredentialStore', function () {
deepStrictEqual(additionalResult?.scopes, additionalScopes);
});
});

it('retries a shared current user request after a failure', async function () {
const telemetry = new MockTelemetry();
const credentialStore = new CredentialStore(telemetry, new MockExtensionContext());
const github: GitHub = {
octokit: new LoggingOctokit(new Octokit(), new RateLogger(telemetry, false)),
graphql: {} as LoggingApolloClient,
};
sinon.stub(credentialStore, 'getHub').returns(github);
const getAuthenticatedUser = sinon.stub(github.octokit, 'call');
const error = new Error('Connect Timeout Error');
getAuthenticatedUser.onFirstCall().rejects(error);
getAuthenticatedUser.onSecondCall().resolves({
data: {
login: 'octocat',
node_id: 'MDQ6VXNlcjE=',
html_url: 'https://github.com/octocat',
avatar_url: 'https://github.com/images/error/octocat_happy.gif',
type: 'User',
plan: { name: 'emu_user' },
}
});

await rejects(Promise.all([
credentialStore.getCurrentUser(AuthProvider.github),
credentialStore.getIsEmu(AuthProvider.github),
]), candidate => candidate === error);
strictEqual(getAuthenticatedUser.callCount, 1);

const [currentUser, isEmu] = await Promise.all([
credentialStore.getCurrentUser(AuthProvider.github),
credentialStore.getIsEmu(AuthProvider.github),
]);

deepStrictEqual({
requests: getAuthenticatedUser.callCount,
login: currentUser.login,
isEmu,
}, {
requests: 2,
login: 'octocat',
isEmu: true,
});
strictEqual(await credentialStore.isCurrentUser(AuthProvider.github, 'octocat'), true);
strictEqual(getAuthenticatedUser.callCount, 2);
});
});
19 changes: 19 additions & 0 deletions src/test/github/githubRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,25 @@ describe('GitHubRepository', function () {
});
});

describe('getMetadata', function () {
it('retries after a transient failure and caches the successful result', async function () {
const url = 'https://github.com/some/repo';
const remote = new GitHubRemote('origin', url, new Protocol(url), GitHubServerType.GitHubDotCom);
const repo = new GitHubRepository(1, remote, Uri.file('/workspaces/repo'), credentialStore, telemetry);
sinon.stub(repo, 'ensure').resolves(repo);
const fetchMetadata = sinon.stub(repo as any, 'getMetadataForRepo');
const error = new Error('Connect Timeout Error');
const metadata = { name: 'repo', owner: { login: 'some' } };
fetchMetadata.onFirstCall().rejects(error);
fetchMetadata.onSecondCall().resolves(metadata);

await assert.rejects(repo.getMetadata(), candidate => candidate === error);
assert.strictEqual(await repo.getMetadata(), metadata);
assert.strictEqual(await repo.getMetadata(), metadata);
assert.strictEqual(fetchMetadata.callCount, 2);
});
});

describe('resolveRemote', function () {
beforeEach(function () {
sinon.stub(credentialStore, 'isAuthenticated').returns(true);
Expand Down
21 changes: 21 additions & 0 deletions src/test/github/pullRequestOverview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,27 @@ describe('PullRequestOverview', function () {
assert.notStrictEqual(PullRequestOverviewPanel.findPanel('aaa', 'bbb', 1000), undefined);
});

it('identifies the operation that failed while updating', async function () {
repo.addGraphQLPullRequest(builder => {
builder.pullRequest(response => {
response.repository(r => {
r.pullRequest(pr => pr.number(1000));
});
});
});

const prItem = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).build(), repo);
const prModel = new PullRequestModel(credentialStore, telemetry, repo, remote, prItem);
const identity = { owner: prModel.remote.owner, repo: prModel.remote.repositoryName, number: prModel.number };
sinon.stub(pullRequestManager, 'getCurrentUser').rejects(new Error('Connect Timeout Error'));
const showErrorMessage = sinon.stub(vscode.window, 'showErrorMessage');

await PullRequestOverviewPanel.createOrShow(telemetry, EXTENSION_URI, pullRequestManager, identity, prModel);

assert.strictEqual(showErrorMessage.callCount, 1);
assert.strictEqual(showErrorMessage.firstCall.args[0], 'Error updating pull request: Fetching current user failed: Connect Timeout Error');
});

it('reveals an existing panel for the same PR', async function () {
const createWebviewPanel = sinon.spy(vscode.window, 'createWebviewPanel');

Expand Down