Skip to content
Merged
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
50 changes: 40 additions & 10 deletions src/notifications/notificationsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@

import * as vscode from 'vscode';
import { isNotificationTreeItem, NotificationTreeDataItem, NotificationTreeItem } from './notificationItem';
import { NotificationsProvider } from './notificationsProvider';
import { isSameNotificationSource, NotificationsProvider } from './notificationsProvider';
import { commands, contexts } from '../common/executeCommands';
import { Disposable } from '../common/lifecycle';
import Logger from '../common/logger';
import { ISSUES_SETTINGS_NAMESPACE, NOTIFICATION_SETTING, NotificationVariants, PR_SETTINGS_NAMESPACE, SHOW_ISSUE_NUMBER_IN_TREE, SHOW_PULL_REQUEST_NUMBER_IN_TREE } from '../common/settingKeys';
import { EventType, TimelineEvent } from '../common/timelineEvent';
import { toNotificationUri } from '../common/uri';
import { CredentialStore } from '../github/credentials';
import { CredentialStore, GitHub } from '../github/credentials';
import { AccountType, NotificationSubjectType } from '../github/interface';
import { IssueModel } from '../github/issueModel';
import { issueMarkdown } from '../github/markdownUtils';
Expand Down Expand Up @@ -49,6 +49,8 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP
private _dateTime: Date = new Date();
private _fetchNotifications: boolean = false;
private _notifications = new Map<string, NotificationTreeItem>();
// The account that the cached notifications, and their pagination, belong to.
private _source: GitHub | undefined;

private _pollingDuration: number = 60; // Default polling duration
private _pollingHandler: NodeJS.Timeout | null;
Expand Down Expand Up @@ -81,6 +83,13 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP
this._register(PullRequestOverviewPanel.onVisible(e => {
this.markPrNotificationsAsRead(e);
}));
const refreshIfSourceChanged = () => {
if (this._source && !isSameNotificationSource(this._source, this._notificationProvider.getSource())) {
this.refresh();
}
};
this._register(this._repositoriesManager.onDidChangeAnyGitHubRepository(refreshIfSourceChanged));
this._register(this._repositoriesManager.onDidChangeFolderRepositories(refreshIfSourceChanged));
Comment thread
alexr00 marked this conversation as resolved.
Resolved
}

//#region TreeDataProvider
Expand Down Expand Up @@ -227,12 +236,27 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP
}

public async getNotifications(): Promise<INotificationTreeItems | undefined> {
const notificationsCache = this._notifications;
let notificationsCache = this._notifications;
let pollInterval = this._pollingDuration;
let lastModified = this._pollingLastModified;
if (this._fetchNotifications) {
const source = this._notificationProvider.getSource();
if (!source) {
return undefined;
}
if (!isSameNotificationSource(this._source, source)) {
// Cached notifications and pages belong to the previous account. Replacing the cache also
// invalidates fetches that are still in flight for the previous account.
const updates = this.clearNotifications();
if (updates.length > 0) {
this._onDidChangeNotifications.fire(updates);
}
notificationsCache = this._notifications;
}
this._source = source;

// Get raw notifications
const notificationsData = await this._notificationProvider.getNotifications(this._dateTime.toISOString(), this._pageCount);
const notificationsData = await this._notificationProvider.getNotifications(source, this._dateTime.toISOString(), this._pageCount);
if (!notificationsData) {
return undefined;
}
Expand Down Expand Up @@ -316,6 +340,7 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP
private clearNotifications(): NotificationTreeItem[] {
const updates = Array.from(this._notifications.values());
this._pageCount = 1;
this._hasNextPage = false;
this._dateTime = new Date();
this._notifications = new Map();
this._updateContext();
Expand All @@ -324,6 +349,7 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP

public clear(): void {
const updates = this.clearNotifications();
this._source = undefined;
this._fetchNotifications = false;
this._onDidChangeNotifications.fire(updates);
this._onDidChangeTreeData.fire();
Expand All @@ -347,8 +373,8 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP

public async markAsRead(notificationIdentifier: { threadId: string, notificationKey: string }): Promise<void> {
const notification = this._notifications.get(notificationIdentifier.notificationKey);
if (notification) {
await this._notificationProvider.markAsRead(notificationIdentifier);
if (notification && this._source) {
await this._notificationProvider.markAsRead(this._source, notificationIdentifier.threadId);
Comment thread
alexr00 marked this conversation as resolved.
Resolved

this._onDidChangeNotifications.fire([notification]);
this._notifications.delete(notificationIdentifier.notificationKey);
Expand All @@ -360,8 +386,8 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP

public async markAsDone(notificationIdentifier: { threadId: string, notificationKey: string }): Promise<void> {
const notification = this._notifications.get(notificationIdentifier.notificationKey);
if (notification) {
await this._notificationProvider.markAsDone(notificationIdentifier);
if (notification && this._source) {
await this._notificationProvider.markAsDone(this._source, notificationIdentifier.threadId);

this._onDidChangeNotifications.fire([notification]);
this._notifications.delete(notificationIdentifier.notificationKey);
Expand Down Expand Up @@ -415,6 +441,10 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP
}

public async markPullRequests(markAsDone: boolean = false): Promise<void> {
const source = this._source;
if (!source) {
return;
}
const filteredNotifications = Array.from(this._notifications.values()).filter(notification => notification.notification.subject.type === NotificationSubjectType.PullRequest);
const timelines = await Promise.all(filteredNotifications.map(notification => (notification.model as PullRequestModel).getActivityTimelineEvents()));

Expand Down Expand Up @@ -442,9 +472,9 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP

if (!nonUserLastEvent || (userLastEvent && (userLastEvent.getTime() > nonUserLastEvent.getTime()))) {
if (markAsDone) {
markPromises.push(this._notificationProvider.markAsDone({ threadId: notification.notification.id, notificationKey: notification.notification.key }));
markPromises.push(this._notificationProvider.markAsDone(source, notification.notification.id));
} else {
markPromises.push(this._notificationProvider.markAsRead({ threadId: notification.notification.id, notificationKey: notification.notification.key }));
markPromises.push(this._notificationProvider.markAsRead(source, notification.notification.id));
}
this._notifications.delete(notification.notification.key);
}
Expand Down
65 changes: 26 additions & 39 deletions src/notifications/notificationsProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,63 +31,50 @@ export interface INotificationPriority {
readonly priorityReasoning: string | undefined;
}

export function isSameNotificationSource(first: GitHub | undefined, second: GitHub | undefined): boolean {
return first === second || (!!first && !!second
&& first.serverUri.toString() === second.serverUri.toString()
&& first.session?.account.id === second.session?.account.id);
}

export class NotificationsProvider extends Disposable {
private static readonly ID = 'NotificationsProvider';
private _authProvider: AuthProvider | undefined;

constructor(
private readonly _credentialStore: CredentialStore,
private readonly _repositoriesManager: RepositoriesManager
) {
super();
const setAuthProvider = () => {
if (_credentialStore.isAuthenticated(AuthProvider.githubEnterprise)) {
this._authProvider = AuthProvider.githubEnterprise;
} else if (_credentialStore.isAuthenticated(AuthProvider.github)) {
this._authProvider = AuthProvider.github;
} else {
this._authProvider = undefined;
}
};
setAuthProvider();
this._register(
_credentialStore.onDidChangeSessions(_ => {
setAuthProvider();
})
);
}

private _getGitHub(): GitHub | undefined {
return (this._authProvider !== undefined) ?
this._credentialStore.getHub(this._authProvider) :
undefined;
/**
* The account whose notifications are shown. Notifications are fetched from a single account at a time.
*/
public getSource(): GitHub | undefined {
const enterprise = this._credentialStore.getHub(AuthProvider.githubEnterprise);
const github = this._credentialStore.getHub(AuthProvider.github);
// An enterprise session can exist without any enterprise repositories in the workspace,
// so only prefer it when a workspace repository is hosted on that enterprise server.
if (enterprise && this._repositoriesManager.folderManagers.some(folderManager =>
folderManager.gitHubRepositories.some(repo => repo.remote.isEnterprise && repo.remote.matchesServerUri(enterprise.serverUri)))) {
return enterprise;
Comment thread
alexr00 marked this conversation as resolved.
Resolved
}
return github ?? enterprise;
}

public async markAsRead(notificationIdentifier: { threadId: string, notificationKey: string }): Promise<void> {
const gitHub = this._getGitHub();
if (gitHub === undefined) {
return undefined;
}
await gitHub.octokit.call(gitHub.octokit.api.activity.markThreadAsRead, {
thread_id: Number(notificationIdentifier.threadId)
public async markAsRead(source: GitHub, threadId: string): Promise<void> {
await source.octokit.call(source.octokit.api.activity.markThreadAsRead, {
thread_id: Number(threadId)
});
}

public async markAsDone(notificationIdentifier: { threadId: string, notificationKey: string }): Promise<void> {
const gitHub = this._getGitHub();
if (gitHub === undefined) {
return undefined;
}
await gitHub.octokit.call(gitHub.octokit.api.activity.markThreadAsDone, {
thread_id: Number(notificationIdentifier.threadId)
public async markAsDone(source: GitHub, threadId: string): Promise<void> {
await source.octokit.call(source.octokit.api.activity.markThreadAsDone, {
thread_id: Number(threadId)
});
}

public async getNotifications(before: string, page: number): Promise<INotifications | undefined> {
const gitHub = this._getGitHub();
if (gitHub === undefined) {
return undefined;
}
public async getNotifications(gitHub: GitHub, before: string, page: number): Promise<INotifications | undefined> {
if (this._repositoriesManager.folderManagers.length === 0) {
return undefined;
}
Expand Down
112 changes: 92 additions & 20 deletions src/test/notifications/notificationsManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,79 @@
*--------------------------------------------------------------------------------------------*/

import { default as assert } from 'assert';
import { createSandbox, SinonSandbox } from 'sinon';
import { CredentialStore } from '../../github/credentials';
import { createSandbox, SinonSandbox, SinonStub } from 'sinon';
import * as vscode from 'vscode';
import { CredentialStore, GitHub } from '../../github/credentials';
import { FolderRepositoryManager } from '../../github/folderRepositoryManager';
import { Notification, NotificationSubjectType } from '../../github/interface';
import { IssueModel } from '../../github/issueModel';
import { RepositoriesManager } from '../../github/repositoriesManager';
import { NotificationTreeItem } from '../../notifications/notificationItem';
import { NotificationsManager } from '../../notifications/notificationsManager';
import { NotificationsProvider } from '../../notifications/notificationsProvider';
import { INotifications, NotificationsProvider } from '../../notifications/notificationsProvider';
import { MockCommandRegistry } from '../mocks/mockCommandRegistry';
import { MockExtensionContext } from '../mocks/mockExtensionContext';

describe('NotificationsManager', function () {
const github = { serverUri: vscode.Uri.parse('https://github.com') } as GitHub;
const enterprise = { serverUri: vscode.Uri.parse('https://octo.ghe.com') } as GitHub;

let sinon: SinonSandbox;
let manager: NotificationsManager;
let source: GitHub | undefined;
let getNotifications: SinonStub;
let markAsRead: SinonStub;
let onDidChangeAnyGitHubRepository: vscode.EventEmitter<FolderRepositoryManager>;

beforeEach(function () {
sinon = createSandbox();
MockCommandRegistry.install(sinon);
source = github;
getNotifications = sinon.stub();
markAsRead = sinon.stub().resolves();
const provider: Pick<NotificationsProvider, 'getSource' | 'getNotifications' | 'getNotificationModel' | 'markAsRead'> = {
getSource: () => source,
getNotifications,
getNotificationModel: async () => ({} as IssueModel),
markAsRead,
};
onDidChangeAnyGitHubRepository = new vscode.EventEmitter<FolderRepositoryManager>();
const repositoriesManager: Pick<RepositoriesManager, 'onDidChangeAnyGitHubRepository' | 'onDidChangeFolderRepositories'> = {
onDidChangeAnyGitHubRepository: onDidChangeAnyGitHubRepository.event,
onDidChangeFolderRepositories: new vscode.EventEmitter<{ added?: FolderRepositoryManager }>().event,
};
manager = new NotificationsManager(
{} as NotificationsProvider,
provider as NotificationsProvider,
{} as CredentialStore,
{} as RepositoriesManager,
repositoriesManager as RepositoriesManager,
new MockExtensionContext(),
);
});

afterEach(function () {
manager.dispose();
onDidChangeAnyGitHubRepository.dispose();
sinon.restore();
});

function notificationsResult(...keys: string[]): INotifications {
return {
notifications: keys.map(key => ({
key,
id: key,
updatedAt: new Date(),
subject: { title: key, type: NotificationSubjectType.PullRequest, url: 'https://api.github.com/repos/o/r/pulls/1' },
} as Notification)),
hasNextPage: true,
pollInterval: 60,
lastModified: '',
};
}

function cachedKeys(): string[] {
return manager.getAllNotifications().map(item => item.notification.key);
}

it('clears cached notifications without fetching', function () {
const notification = {} as NotificationTreeItem;
const internal = manager as unknown as {
Expand All @@ -55,24 +99,11 @@ describe('NotificationsManager', function () {
});

it('does not publish notifications into a replacement cache', async function () {
let resolveNotifications: (notifications: {
notifications: [];
hasNextPage: boolean;
pollInterval: number;
lastModified: string;
}) => void;
const notifications = new Promise<{
notifications: [];
hasNextPage: boolean;
pollInterval: number;
lastModified: string;
}>(resolve => resolveNotifications = resolve);
const getNotifications = sinon.stub().returns(notifications);
let resolveNotifications: (notifications: INotifications) => void;
getNotifications.returns(new Promise<INotifications>(resolve => resolveNotifications = resolve));
const internal = manager as unknown as {
_notificationProvider: { getNotifications: typeof getNotifications };
_fetchNotifications: boolean;
};
internal._notificationProvider = { getNotifications };
internal._fetchNotifications = true;

const pendingNotifications = manager.getNotifications();
Expand All @@ -88,4 +119,45 @@ describe('NotificationsManager', function () {
assert.deepStrictEqual(manager.getAllNotifications(), []);
assert.strictEqual(internal._fetchNotifications, false);
});

it('restarts pagination and drops in-flight results when the account changes', async function () {
let resolveGitHubNotifications: (notifications: INotifications) => void;
getNotifications.withArgs(github).returns(new Promise<INotifications>(resolve => resolveGitHubNotifications = resolve));
getNotifications.withArgs(enterprise).resolves(notificationsResult('enterprise'));
manager.refresh();
const pendingGitHubNotifications = manager.getNotifications();

source = enterprise;
manager.loadMore();
await manager.getNotifications();
resolveGitHubNotifications!(notificationsResult('github'));

assert.strictEqual(await pendingGitHubNotifications, undefined);
assert.strictEqual(getNotifications.withArgs(enterprise).firstCall.args[2], 1);
assert.deepStrictEqual(cachedKeys(), ['enterprise']);
});

it('marks notifications on the account they were fetched from', async function () {
getNotifications.resolves(notificationsResult('github'));
manager.refresh();
await manager.getNotifications();

source = enterprise;
await manager.markAsRead({ threadId: 'github', notificationKey: 'github' });

assert.strictEqual(markAsRead.calledOnceWith(github, 'github'), true);
});

it('refreshes when a repository change selects a different account', async function () {
getNotifications.resolves(notificationsResult('github'));
manager.refresh();
await manager.getNotifications();

onDidChangeAnyGitHubRepository.fire({} as FolderRepositoryManager);
assert.deepStrictEqual(cachedKeys(), ['github']);

source = enterprise;
onDidChangeAnyGitHubRepository.fire({} as FolderRepositoryManager);
assert.deepStrictEqual(cachedKeys(), []);
});
});
Loading
Loading