/
richRemoteProvider.ts
546 lines (460 loc) · 15.7 KB
/
richRemoteProvider.ts
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import { authentication, EventEmitter, window } from 'vscode';
import type { AuthenticationSession, AuthenticationSessionsChangeEvent, Event, MessageItem } from 'vscode';
import { wrapForForcedInsecureSSL } from '@env/fetch';
import { isWeb } from '@env/platform';
import { configuration } from '../../configuration';
import type { Container } from '../../container';
import { AuthenticationError, ProviderRequestClientError } from '../../errors';
import { Logger } from '../../logger';
import { showIntegrationDisconnectedTooManyFailedRequestsWarningMessage } from '../../messages';
import type { IntegrationAuthenticationSessionDescriptor } from '../../plus/integrationAuthentication';
import { isSubscriptionPaidPlan, isSubscriptionPreviewTrialExpired } from '../../subscription';
import { gate } from '../../system/decorators/gate';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { isPromise } from '../../system/promise';
import type { Account } from '../models/author';
import type { DefaultBranch } from '../models/defaultBranch';
import type { IssueOrPullRequest } from '../models/issue';
import type { PullRequest, PullRequestState } from '../models/pullRequest';
import { RemoteProvider } from './remoteProvider';
import { RichRemoteProviders } from './remoteProviderConnections';
// TODO@eamodio revisit how once authenticated, all remotes are always connected, even after a restart
export abstract class RichRemoteProvider extends RemoteProvider {
override readonly type: 'simple' | 'rich' = 'rich';
private readonly _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> {
return this._onDidChange.event;
}
constructor(
protected readonly container: Container,
domain: string,
path: string,
protocol?: string,
name?: string,
custom?: boolean,
) {
super(domain, path, protocol, name, custom);
container.context.subscriptions.push(
configuration.onDidChange(e => {
if (configuration.changed(e, 'remotes')) {
this._ignoreSSLErrors.clear();
}
}),
// TODO@eamodio revisit how connections are linked or not
RichRemoteProviders.onDidChangeConnectionState(e => {
if (e.key !== this.key) return;
if (e.reason === 'disconnected') {
void this.disconnect({ silent: true });
} else if (e.reason === 'connected') {
void this.ensureSession(false);
}
}),
authentication.onDidChangeSessions(this.onAuthenticationSessionsChanged, this),
);
}
abstract get apiBaseUrl(): string;
protected abstract get authProvider(): { id: string; scopes: string[] };
protected get authProviderDescriptor(): IntegrationAuthenticationSessionDescriptor {
return { domain: this.domain, scopes: this.authProvider.scopes };
}
private get key() {
return this.custom ? `${this.name}:${this.domain}` : this.name;
}
private get connectedKey(): `connected:${string}` {
return `connected:${this.key}`;
}
get maybeConnected(): boolean | undefined {
return this._session === undefined ? undefined : this._session !== null;
}
protected _session: AuthenticationSession | null | undefined;
protected session() {
if (this._session === undefined) {
return this.ensureSession(false);
}
return this._session ?? undefined;
}
private onAuthenticationSessionsChanged(e: AuthenticationSessionsChangeEvent) {
if (e.provider.id === this.authProvider.id) {
void this.ensureSession(false);
}
}
@log()
async connect(): Promise<boolean> {
try {
const session = await this.ensureSession(true);
return Boolean(session);
} catch (ex) {
return false;
}
}
@gate()
@log()
async disconnect(options?: { silent?: boolean; currentSessionOnly?: boolean }): Promise<void> {
if (options?.currentSessionOnly && this._session === null) return;
const connected = this._session != null;
if (connected && !options?.silent) {
if (options?.currentSessionOnly) {
void showIntegrationDisconnectedTooManyFailedRequestsWarningMessage(this.name);
} else {
const disable = { title: 'Disable' };
const signout = { title: 'Disable & Sign Out' };
const cancel = { title: 'Cancel', isCloseAffordance: true };
let result: MessageItem | undefined;
if (this.container.integrationAuthentication.hasProvider(this.authProvider.id)) {
result = await window.showWarningMessage(
`Are you sure you want to disable the rich integration with ${this.name}?\n\nNote: signing out clears the saved authentication.`,
{ modal: true },
disable,
signout,
cancel,
);
} else {
result = await window.showWarningMessage(
`Are you sure you want to disable the rich integration with ${this.name}?`,
{ modal: true },
disable,
cancel,
);
}
if (result == null || result === cancel) return;
if (result === signout) {
void this.container.integrationAuthentication.deleteSession(this.id, this.authProviderDescriptor);
}
}
}
this.resetRequestExceptionCount();
this._prsByCommit.clear();
this._session = null;
if (connected) {
// Don't store the disconnected flag if this only for this current VS Code session (will be re-connected on next restart)
if (!options?.currentSessionOnly) {
void this.container.storage.storeWorkspace(this.connectedKey, false);
}
this._onDidChange.fire();
if (!options?.silent && !options?.currentSessionOnly) {
RichRemoteProviders.disconnected(this.key);
}
}
}
@log()
async reauthenticate(): Promise<void> {
if (this._session === undefined) return;
this._session = undefined;
void (await this.ensureSession(true, true));
}
private requestExceptionCount = 0;
resetRequestExceptionCount() {
this.requestExceptionCount = 0;
}
@debug()
trackRequestException() {
this.requestExceptionCount++;
if (this.requestExceptionCount >= 5 && this._session !== null) {
void this.disconnect({ currentSessionOnly: true });
}
}
@gate()
@debug<RichRemoteProvider['isConnected']>({
exit: connected => `returned ${connected}`,
})
async isConnected(): Promise<boolean> {
return (await this.session()) != null;
}
@gate()
@debug()
async getAccountForCommit(
ref: string,
options?: {
avatarSize?: number;
},
): Promise<Account | undefined> {
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined;
try {
const author = await this.getProviderAccountForCommit(this._session!, ref, options);
this.resetRequestExceptionCount();
return author;
} catch (ex) {
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException();
}
return undefined;
}
}
protected abstract getProviderAccountForCommit(
session: AuthenticationSession,
ref: string,
options?: {
avatarSize?: number;
},
): Promise<Account | undefined>;
@gate()
@debug()
async getAccountForEmail(
email: string,
options?: {
avatarSize?: number;
},
): Promise<Account | undefined> {
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined;
try {
const author = await this.getProviderAccountForEmail(this._session!, email, options);
this.resetRequestExceptionCount();
return author;
} catch (ex) {
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException();
}
return undefined;
}
}
protected abstract getProviderAccountForEmail(
session: AuthenticationSession,
email: string,
options?: {
avatarSize?: number;
},
): Promise<Account | undefined>;
@gate()
@debug()
async getDefaultBranch(): Promise<DefaultBranch | undefined> {
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined;
try {
const defaultBranch = await this.getProviderDefaultBranch(this._session!);
this.resetRequestExceptionCount();
return defaultBranch;
} catch (ex) {
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException();
}
return undefined;
}
}
protected abstract getProviderDefaultBranch({
accessToken,
}: AuthenticationSession): Promise<DefaultBranch | undefined>;
@gate()
@debug()
async getIssueOrPullRequest(id: string): Promise<IssueOrPullRequest | undefined> {
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined;
try {
const issueOrPullRequest = await this.getProviderIssueOrPullRequest(this._session!, id);
this.resetRequestExceptionCount();
return issueOrPullRequest;
} catch (ex) {
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException();
}
return undefined;
}
}
private _ignoreSSLErrors = new Map<string, boolean | 'force'>();
getIgnoreSSLErrors(): boolean | 'force' {
if (isWeb) return false;
let ignoreSSLErrors = this._ignoreSSLErrors.get(this.id);
if (ignoreSSLErrors === undefined) {
const cfg = configuration
.get('remotes')
?.find(remote => remote.type.toLowerCase() === this.id && remote.domain === this.domain);
ignoreSSLErrors = cfg?.ignoreSSLErrors ?? false;
this._ignoreSSLErrors.set(this.id, ignoreSSLErrors);
}
return ignoreSSLErrors;
}
protected abstract getProviderIssueOrPullRequest(
session: AuthenticationSession,
id: string,
): Promise<IssueOrPullRequest | undefined>;
@gate()
@debug()
async getPullRequestForBranch(
branch: string,
options?: {
avatarSize?: number;
include?: PullRequestState[];
},
): Promise<PullRequest | undefined> {
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined;
try {
const pr = await this.getProviderPullRequestForBranch(this._session!, branch, options);
this.resetRequestExceptionCount();
return pr;
} catch (ex) {
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException();
}
return undefined;
}
}
protected abstract getProviderPullRequestForBranch(
session: AuthenticationSession,
branch: string,
options?: {
avatarSize?: number;
include?: PullRequestState[];
},
): Promise<PullRequest | undefined>;
private _prsByCommit = new Map<string, Promise<PullRequest | null> | PullRequest | null>();
@debug()
getPullRequestForCommit(ref: string): Promise<PullRequest | undefined> | PullRequest | undefined {
let pr = this._prsByCommit.get(ref);
if (pr === undefined) {
pr = this.getPullRequestForCommitCore(ref);
this._prsByCommit.set(ref, pr);
}
if (pr == null || !isPromise(pr)) return pr ?? undefined;
return pr.then(pr => pr ?? undefined);
}
@debug()
private async getPullRequestForCommitCore(ref: string) {
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return null;
try {
const pr = (await this.getProviderPullRequestForCommit(this._session!, ref)) ?? null;
this._prsByCommit.set(ref, pr);
this.resetRequestExceptionCount();
return pr;
} catch (ex) {
Logger.error(ex, scope);
this._prsByCommit.delete(ref);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException();
}
return null;
}
}
protected abstract getProviderPullRequestForCommit(
session: AuthenticationSession,
ref: string,
): Promise<PullRequest | undefined>;
@gate()
private async ensureSession(
createIfNeeded: boolean,
forceNewSession: boolean = false,
): Promise<AuthenticationSession | undefined> {
if (this._session != null) return this._session;
if (!configuration.get('integrations.enabled')) return undefined;
if (createIfNeeded) {
await this.container.storage.deleteWorkspace(this.connectedKey);
} else if (this.container.storage.getWorkspace(this.connectedKey) === false) {
return undefined;
}
let session: AuthenticationSession | undefined | null;
try {
if (this.container.integrationAuthentication.hasProvider(this.authProvider.id)) {
session = await this.container.integrationAuthentication.getSession(
this.authProvider.id,
this.authProviderDescriptor,
{ createIfNeeded: createIfNeeded, forceNewSession: forceNewSession },
);
} else {
session = await wrapForForcedInsecureSSL(this.getIgnoreSSLErrors(), () =>
authentication.getSession(this.authProvider.id, this.authProvider.scopes, {
createIfNone: forceNewSession ? undefined : createIfNeeded,
silent: !createIfNeeded && !forceNewSession ? true : undefined,
forceNewSession: forceNewSession ? true : undefined,
}),
);
}
} catch (ex) {
await this.container.storage.deleteWorkspace(this.connectedKey);
if (ex instanceof Error && ex.message.includes('User did not consent')) {
return undefined;
}
session = null;
}
if (session === undefined && !createIfNeeded) {
await this.container.storage.deleteWorkspace(this.connectedKey);
}
this._session = session ?? null;
this.resetRequestExceptionCount();
if (session != null) {
await this.container.storage.storeWorkspace(this.connectedKey, true);
queueMicrotask(() => {
this._onDidChange.fire();
RichRemoteProviders.connected(this.key);
});
}
return session ?? undefined;
}
}
export async function ensurePaidPlan(providerName: string, container: Container): Promise<boolean> {
const title = `Connecting to a ${providerName} instance for rich integration features requires GitLens Pro.`;
while (true) {
const subscription = await container.subscription.getSubscription();
if (subscription.account?.verified === false) {
const resend = { title: 'Resend Verification' };
const cancel = { title: 'Cancel', isCloseAffordance: true };
const result = await window.showWarningMessage(
`${title}\n\nYou must verify your email address before you can continue.`,
{ modal: true },
resend,
cancel,
);
if (result === resend) {
if (await container.subscription.resendVerification()) {
continue;
}
}
return false;
}
const plan = subscription.plan.effective.id;
if (isSubscriptionPaidPlan(plan)) break;
if (subscription.account == null && !isSubscriptionPreviewTrialExpired(subscription)) {
const startTrial = { title: 'Start a GitLens Pro Trial' };
const cancel = { title: 'Cancel', isCloseAffordance: true };
const result = await window.showWarningMessage(
`${title}\n\nDo you want to also try GitLens+ features on private repos, free for 3 days?`,
{ modal: true },
startTrial,
cancel,
);
if (result !== startTrial) return false;
void container.subscription.startPreviewTrial();
break;
} else if (subscription.account == null) {
const signIn = { title: 'Extend Your GitLens Pro Trial' };
const cancel = { title: 'Cancel', isCloseAffordance: true };
const result = await window.showWarningMessage(
`${title}\n\nDo you want to continue to use GitLens+ features on private repos, free for an additional 7-days?`,
{ modal: true },
signIn,
cancel,
);
if (result === signIn) {
if (await container.subscription.loginOrSignUp()) {
continue;
}
}
} else {
const upgrade = { title: 'Upgrade to Pro' };
const cancel = { title: 'Cancel', isCloseAffordance: true };
const result = await window.showWarningMessage(
`${title}\n\nDo you want to continue to use GitLens+ features on private repos?`,
{ modal: true },
upgrade,
cancel,
);
if (result === upgrade) {
void container.subscription.purchase();
}
}
return false;
}
return true;
}