Repository navigation
Expand file tree
/
Copy pathPullRequestService.ts
More file actions
3867 lines (3747 loc) · 149 KB
/
Copy pathPullRequestService.ts
File metadata and controls
3867 lines (3747 loc) · 149 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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import {
PullRequestOperationError,
PullRequestUnavailableError,
resolvePullRequestAuthorFilter,
type OrchestrationProjectShell,
type ProjectId,
type PullRequestAction,
type PullRequestActionInput,
type PullRequestActivity,
type PullRequestCommentInput,
type PullRequestCommentUpdateInput,
type PullRequestDetail,
type PullRequestPreview,
type PullRequestChecks,
type PullRequestDiffFileContentsInput,
type PullRequestDiffFileContentsResult,
type PullRequestDiffStat,
type PullRequestDiffInput,
type PullRequestChangeBreakdown,
type PullRequestFilesViewedResult,
type PullRequestDiffResult,
type PullRequestInvalidateInput,
type PullRequestReportStateInput,
type PullRequestListEntry,
type PullRequestListFilters,
type PullRequestListInput,
type PullRequestListProjectError,
type PullRequestListResult,
type PullRequestListStatsInput,
type PullRequestFilterOptions,
type PullRequestFilterOptionsInput,
type PullRequestActor,
type PullRequestReferenceCandidate,
type PullRequestLabel,
type PullRequestListStatsResult,
type PullRequestProviderSummary,
type PullRequestReactionInput,
type PullRequestRef,
type PullRequestRoutingResult,
type PullRequestRoutingIdentityInput,
type PullRequestRoutingIdentityResult,
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
type PullRequestReviewerCandidatesInput,
type PullRequestReviewerRequestInput,
type PullRequestLabelCandidateList,
type PullRequestLabelChangeInput,
type PullRequestSetFilesViewedInput,
type PullRequestState,
type PullRequestSubmitReviewInput,
PullRequestStack,
PullRequestSummary,
type PullRequestThreadReplyInput,
type PullRequestThreadResolutionInput,
type PullRequestThreadCommentsInput,
type PullRequestThreadCommentsResult,
type PullRequestUpdateInput,
type SourceControlProviderInfo,
SourceControlProviderKind,
type ThreadPullRequestKey,
} from "@t3tools/contracts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import {
type ProviderChangeRequest,
type ProviderChangeRequestDetail,
type ProviderDiffFilePaths,
type ProviderFilterOptionPage,
type ProviderListCursor,
type ProviderChangeRequestSummary,
type ProviderChangeRequestWatchFingerprint,
type PullRequestProviderApi,
PullRequestProviderError,
} from "@t3tools/source-control-core/server/PullRequestProvider";
import * as PullRequestReadCache from "./PullRequestReadCache.ts";
import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts";
import * as ViewedFiles from "./pullRequestViewedFiles.ts";
import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts";
export interface PullRequestMergeEvent extends PullRequestRef {
readonly mergedAt: string;
}
type PullRequestReading = Pick<
PullRequestSummary,
"state" | "isDraft" | "updatedAt" | "observedAt"
>;
function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) {
if (current === undefined) return true;
if (current.state === "merged" && next.state !== "merged") return false;
if (next.updatedAt !== current.updatedAt) return next.updatedAt > current.updatedAt;
return (next.observedAt ?? -Infinity) >= (current.observedAt ?? -Infinity);
}
// Providers request one extra row; 99 stays within GitHub/GitLab's 100-row API limit.
const DEFAULT_REPOSITORY_LIST_LIMIT = 99;
const REPOSITORY_CONCURRENCY = 12;
const REPOSITORY_SEARCH_CHUNK = 100;
const FILTERED_LIST_READS = 5;
// Host reads spawn CLIs and hit low quotas; briefly share results and identical in-flight reads.
const LIST_CACHE_TTL = Duration.seconds(30);
const DETAIL_CACHE_TTL = Duration.seconds(60);
const MERGED_DETAIL_CACHE_TTL = Duration.minutes(10);
const detailTimeToLive = (state: PullRequestState | undefined) =>
state === "merged" ? MERGED_DETAIL_CACHE_TTL : DETAIL_CACHE_TTL;
const CHECKS_CACHE_TTL = Duration.seconds(15);
const REPORTED_STATE_DEDUPE_MS = 5 * 60 * 1_000;
const DIFF_CACHE_TTL = Duration.seconds(60);
const COMMIT_DIFF_CACHE_TTL = Duration.minutes(10);
const LIST_STATS_CACHE_TTL = Duration.seconds(60);
const FILES_VIEWED_CACHE_TTL = Duration.seconds(15);
const DIFF_STALE_WINDOW = Duration.minutes(10);
const DIFF_SWEEP_INTERVAL = Duration.minutes(1);
const VIEWER_CACHE_TTL = Duration.minutes(10);
const STALE_DETAIL_WINDOW = Duration.minutes(10);
const isPullRequestProviderError = Schema.is(PullRequestProviderError);
const LIST_CACHE_CAPACITY = 64;
const LIST_STATS_CACHE_CAPACITY = 32;
const DETAIL_CACHE_CAPACITY = 128;
const DIFF_CACHE_CAPACITY = 128;
// Each holder stays within this UTF-16 patch budget as well as its entry-count bound.
const DIFF_CACHE_PATCH_BUDGET_BYTES = 32 * 1024 * 1024;
const canCacheDiff = (value: PullRequestDiffResult) =>
value.patch.length * 2 <= DIFF_CACHE_PATCH_BUDGET_BYTES;
const diffCacheEvictions = (entries: Iterable<readonly [string, PullRequestDiffResult]>) => {
let bytes = 0;
const evictions: string[] = [];
for (const [key, value] of Array.from(entries).toReversed()) {
const size = value.patch.length * 2;
if (bytes + size > DIFF_CACHE_PATCH_BUDGET_BYTES) {
evictions.push(key);
} else {
bytes += size;
}
}
return evictions;
};
const FILES_VIEWED_CACHE_CAPACITY = 128;
const VIEWER_CACHE_CAPACITY = 32;
export type PullRequestError = PullRequestUnavailableError | PullRequestOperationError;
const routingCredential = Context.Reference<{
readonly credentialFingerprint: string;
readonly viewer: string;
} | null>("t3/PullRequestService/routingCredential", { defaultValue: () => null });
const credentialNamespace = Symbol("pullRequestCredentialNamespace");
type CredentialRef = PullRequestRef & { readonly [credentialNamespace]?: string };
export class PullRequestService extends Context.Service<
PullRequestService,
{
readonly list: (
input: PullRequestListInput,
) => Effect.Effect<PullRequestListResult, PullRequestError>;
readonly listStats: (
input: PullRequestListStatsInput,
) => Effect.Effect<PullRequestListStatsResult, PullRequestError>;
readonly filterOptions: (
input: PullRequestFilterOptionsInput,
) => Effect.Effect<PullRequestFilterOptions, PullRequestError>;
readonly routing: (
input: PullRequestRef,
) => Effect.Effect<PullRequestRoutingResult, PullRequestError>;
readonly routingIdentity: (
input: PullRequestRoutingIdentityInput,
) => Effect.Effect<PullRequestRoutingIdentityResult, PullRequestError>;
readonly withRoutingCredential: <A, E, R>(
input: PullRequestRef,
operation: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | PullRequestError, R>;
readonly summary: (
input: PullRequestRef,
options?: { readonly recoverTransientFailure?: boolean },
) => Effect.Effect<PullRequestSummary, PullRequestError>;
readonly stack: (
input: PullRequestRef,
options?: { readonly includeDetails?: boolean },
) => Effect.Effect<PullRequestStack | null, PullRequestError>;
readonly subscribeMerges: Effect.Effect<
Stream.Stream<PullRequestMergeEvent>,
never,
Scope.Scope
>;
readonly subscribeStateChanges: Effect.Effect<
Stream.Stream<ThreadPullRequestKey>,
never,
Scope.Scope
>;
readonly reportState: (
input: PullRequestReportStateInput,
) => Effect.Effect<void, PullRequestError>;
readonly subscribeRefreshes: Stream.Stream<number>;
readonly refreshAfterTurn: (projectId: ProjectId) => Effect.Effect<void>;
/** Project and remote lookups inside `effect` read once per filter, e.g. across one sync sweep. */
readonly withSharedProjectReads: <A, E, R>(
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;
readonly detail: (input: PullRequestRef) => Effect.Effect<PullRequestDetail, PullRequestError>;
readonly preview: (
input: PullRequestRef,
) => Effect.Effect<PullRequestPreview, PullRequestError>;
readonly checks: (
input: PullRequestRef,
) => Effect.Effect<PullRequestChecks | null, PullRequestError>;
readonly watchFingerprint: (
input: PullRequestRef,
) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, PullRequestError>;
readonly activity: (
input: PullRequestRef,
) => Effect.Effect<PullRequestActivity, PullRequestError>;
/** Emits when the host reports a change; empty where the host has no event feed. */
readonly changes: (input: PullRequestRef) => Stream.Stream<void>;
readonly threadComments: (
input: PullRequestThreadCommentsInput,
) => Effect.Effect<PullRequestThreadCommentsResult, PullRequestError>;
readonly diff: (
input: PullRequestDiffInput,
) => Effect.Effect<PullRequestDiffResult, PullRequestError>;
readonly diffFileContents: (
input: PullRequestDiffFileContentsInput,
) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>;
readonly filesViewed: (
input: PullRequestRef,
) => Effect.Effect<PullRequestFilesViewedResult, PullRequestError>;
readonly setFilesViewed: (
input: PullRequestSetFilesViewedInput,
) => Effect.Effect<void, PullRequestError>;
readonly changeBreakdown: (
input: PullRequestRef,
) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>;
readonly runAction: (
input: PullRequestActionInput,
) => Effect.Effect<PullRequestSummary | undefined, PullRequestError>;
readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
readonly updateComment: (
input: PullRequestCommentUpdateInput,
) => Effect.Effect<void, PullRequestError>;
readonly submitReview: (
input: PullRequestSubmitReviewInput,
) => Effect.Effect<void, PullRequestError>;
readonly replyToThread: (
input: PullRequestThreadReplyInput,
) => Effect.Effect<void, PullRequestError>;
readonly setThreadResolution: (
input: PullRequestThreadResolutionInput,
) => Effect.Effect<void, PullRequestError>;
readonly setReaction: (
input: PullRequestReactionInput,
) => Effect.Effect<void, PullRequestError>;
readonly reviewerCandidates: (
input: PullRequestReviewerCandidatesInput,
) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>;
readonly requestReviewers: (
input: PullRequestReviewerRequestInput,
) => Effect.Effect<void, PullRequestError>;
readonly labelCandidates: (
input: PullRequestRef,
) => Effect.Effect<PullRequestLabelCandidateList, PullRequestError>;
readonly setLabels: (
input: PullRequestLabelChangeInput,
) => Effect.Effect<void, PullRequestError>;
readonly invalidate: (
input: PullRequestInvalidateInput,
options?: { readonly notifyReaders?: boolean },
) => Effect.Effect<void>;
}
>()("t3/pullRequest/PullRequestService") {}
const VERDICT_LABELS: Record<PullRequestReviewVerdict, string> = {
comment: "review",
approve: "approve",
"request-changes": "request changes on",
};
const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
merge: "You need write access on this repository to merge.",
ready:
"You need write access on this repository, or to have opened this change request, to mark it ready for review.",
draft:
"You need write access on this repository, or to have opened this change request, to return it to a draft.",
close:
"You need write access on this repository, or to have opened this change request, to close it.",
"update-branch":
"You need write access on this repository, or to have opened this change request, to update its branch.",
reopen:
"You need write access on this repository, or to have opened this change request, to reopen it.",
"enable-auto-merge":
"Auto-merge needs write access on this repository, and the repository has to allow it.",
"disable-auto-merge":
"You need write access on this repository to stop it being merged for you once it is ready.",
revert: "You need write access on this repository to open a revert pull request.",
"delete-branch": "You need write access on the source repository to delete its branch.",
"approve-workflows":
"You need write access on this repository to approve workflows from a fork pull request.",
};
const REVIEWER_REQUEST_REFUSAL = "You need write access on this repository to ask for a review.";
const LABEL_CHANGE_REFUSAL = "You need triage access on this repository to change its labels.";
export interface SupportedProject {
readonly cursorKey: string;
readonly project: OrchestrationProjectShell;
readonly api: PullRequestProviderApi;
readonly repository: string;
readonly host: string;
/** Unlike Azure repository names, remotes are unique across an organization. */
readonly remote: string;
readonly repositoryKey: string | null;
}
interface WorkspaceProjects {
readonly supported: ReadonlyArray<SupportedProject>;
readonly unimplemented: ReadonlyMap<
string,
{ readonly kind: SourceControlProviderKind; readonly projectCount: number }
>;
readonly viewerRoots: ReadonlyMap<string, ReadonlyArray<string>>;
}
// Inherited by fibers forked inside the scope, so it is closed, not just dropped, when the scope ends.
const sharedProjectReads = Context.Reference<{
open: boolean;
readonly reads: Map<string, Effect.Effect<WorkspaceProjects, PullRequestError>>;
} | null>("t3/PullRequestService/sharedProjectReads", { defaultValue: () => null });
interface RepositoryBatch {
readonly key: string;
readonly entries: ReadonlyArray<PullRequestListEntry>;
readonly errors: ReadonlyArray<PullRequestListProjectError>;
readonly truncated: boolean;
readonly nextCursor: string | null;
}
interface ListCursor extends ProviderListCursor {
readonly seenAt: ReadonlyArray<number>;
}
const LIST_CURSOR_PATTERN =
/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?(?:\|([\w.:~+-]{1,128}))?$/;
function parseListCursor(raw: string): ListCursor | null {
const match = LIST_CURSOR_PATTERN.exec(raw);
if (match === null) return null;
const seenAt = match[3];
return {
updatedBefore: match[1]!,
delivered: Number(match[2]),
seenAt: seenAt === undefined ? [] : seenAt.split(",").map(Number),
...(match[4] === undefined ? {} : { resumeAfter: match[4] }),
};
}
function listCursorKey(host: string, repository: string): string {
return `${host} ${repository.toLowerCase()}`;
}
// Preserve exclusions across slices sharing a timestamp to avoid redelivery.
function nextListCursor(
previous: ListCursor | undefined,
fetched: ReadonlyArray<ProviderChangeRequest>,
delivered: ReadonlyArray<ProviderChangeRequest>,
/** A provider may consume malformed offset-paged rows that never appear in `delivered`. */
cursorAdvance = delivered.length,
resumeAfter?: string,
): string | null {
if (fetched.length === 0) return null;
// Use all fetched rows: a slice containing only duplicates must still advance to older rows.
const oldest = fetched.reduce((left, right) => (right.updatedAt < left.updatedAt ? right : left));
return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance, resumeAfter);
}
function listCursorAt(
previous: ListCursor | undefined,
boundary: string,
fetched: ReadonlyArray<ProviderChangeRequest>,
deliveredCount: number,
resumeAfter?: string,
): string {
const seenAt = new Set([
...(previous?.updatedBefore === boundary ? previous.seenAt : []),
...fetched.filter((item) => item.updatedAt === boundary).map((item) => item.number),
]);
const cursor = `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${[...seenAt].join(",")}`;
return resumeAfter === undefined ? cursor : `${cursor}|${resumeAfter}`;
}
function isProviderUnusable(error: PullRequestProviderError): boolean {
return error.reason === "missing-tool" || error.reason === "unauthenticated";
}
type UnavailableRequirementOf = (
kind: SourceControlProviderKind,
) => PullRequestProviderApi["unavailableRequirement"];
function unavailableRequirement(
requirementOf: UnavailableRequirementOf,
error: PullRequestProviderError,
): string | undefined {
const requirement = requirementOf(error.provider);
if (requirement === undefined) return undefined;
return error.reason === "missing-tool" ? requirement.missing : requirement.unauthenticated;
}
function providerDetail(
requirementOf: UnavailableRequirementOf,
error: PullRequestProviderError,
): string {
if (!isProviderUnusable(error)) return error.detail;
return unavailableRequirement(requirementOf, error) ?? error.detail;
}
function toPullRequestErrorWith(
requirementOf: UnavailableRequirementOf,
): (operation: string) => (error: PullRequestProviderError) => PullRequestError {
return (operation) => (error) => {
if (isProviderUnusable(error)) {
const requirement = unavailableRequirement(requirementOf, error);
return new PullRequestUnavailableError({
reason: error.reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated",
provider: error.provider,
...(requirement === undefined ? {} : { requirement }),
cause: error,
});
}
return new PullRequestOperationError({
operation,
detail: error.detail,
...(error.reason === "not-found" ? { reason: "not-found" as const } : {}),
cause: error,
});
};
}
function withRateLimitBackoff(
api: PullRequestProviderApi,
host: string,
limits: SourceControlRateLimit.SourceControlRateLimit["Service"],
options?: { readonly viewerAllowsPause: boolean },
): PullRequestProviderApi {
const key = { provider: api.kind, host };
const protect = <A>(
operation: string,
effect: Effect.Effect<A, PullRequestProviderError>,
allowPaused: boolean,
) =>
limits.check(key, allowPaused ? { allowPaused: true } : undefined).pipe(
Effect.mapError(
(error) =>
new PullRequestProviderError({
provider: api.kind,
operation,
reason: "rate-limited",
detail: error.detail,
retryAt: error.retryAt,
cause: error,
}),
),
Effect.flatMap((lease) =>
effect.pipe(
Effect.provideService(SourceControlRateLimit.Interactive, allowPaused),
Effect.tap(() => limits.recordSuccess({ ...key, lease })),
Effect.tapError((error) =>
error.reason === "rate-limited"
? limits.recordRateLimit({
...key,
lease,
...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
})
: Effect.void,
),
),
),
);
const wrap =
<Args extends ReadonlyArray<unknown>, A>(
operation: string,
call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,
allowPaused = false,
) =>
(...args: Args) =>
protect(operation, call(...args), allowPaused);
const interactive = <Args extends ReadonlyArray<unknown>, A>(
operation: string,
call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,
) => wrap(operation, call, true);
const wrapped = {
kind: api.kind,
capabilities: api.capabilities,
...(api.mergeMessageRewrite === undefined
? {}
: { mergeMessageRewrite: api.mergeMessageRewrite }),
...(api.unavailableRequirement === undefined
? {}
: { unavailableRequirement: api.unavailableRequirement }),
...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),
...(api.servesHost === undefined ? {} : { servesHost: api.servesHost }),
...(api.readsPublicHostWithoutCheckout === undefined
? {}
: { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }),
getViewer:
options?.viewerAllowsPause === true
? interactive("getViewer", api.getViewer)
: wrap("getViewer", api.getViewer),
...(api.getRoutingIdentity === undefined ? {} : { getRoutingIdentity: api.getRoutingIdentity }),
...(api.withVerifiedCredential === undefined
? {}
: { withVerifiedCredential: api.withVerifiedCredential }),
listChangeRequests: wrap("listChangeRequests", api.listChangeRequests),
...(api.listChangeRequestsAcross === undefined
? {}
: {
listChangeRequestsAcross: wrap("listChangeRequestsAcross", api.listChangeRequestsAcross),
}),
...(api.listChangeRequestStats === undefined
? {}
: {
listChangeRequestStats: wrap("listChangeRequestStats", api.listChangeRequestStats),
}),
getChangeRequest: wrap("getChangeRequest", api.getChangeRequest),
...(api.forgetChangeRequestReads === undefined
? {}
: { forgetChangeRequestReads: api.forgetChangeRequestReads }),
...(api.getChangeRequestPreview === undefined
? {}
: { getChangeRequestPreview: wrap("getChangeRequestPreview", api.getChangeRequestPreview) }),
...(api.getChangeRequestChecks === undefined
? {}
: { getChangeRequestChecks: wrap("getChangeRequestChecks", api.getChangeRequestChecks) }),
...(api.getChangeRequestSummary === undefined
? {}
: {
getChangeRequestSummary: wrap("getChangeRequestSummary", api.getChangeRequestSummary),
}),
...(api.getChangeRequestStack === undefined
? {}
: { getChangeRequestStack: wrap("getChangeRequestStack", api.getChangeRequestStack) }),
...(api.getChangeRequestWatchFingerprint === undefined
? {}
: {
getChangeRequestWatchFingerprint: wrap(
"getChangeRequestWatchFingerprint",
api.getChangeRequestWatchFingerprint,
),
}),
// A long-lived feed, not a read: the quota guard would hold its lease for hours.
...(api.changeRequestEvents === undefined
? {}
: { changeRequestEvents: api.changeRequestEvents }),
getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity),
...(api.getReviewThreadComments === undefined
? {}
: {
getReviewThreadComments: wrap("getReviewThreadComments", api.getReviewThreadComments),
}),
getViewerPermissions: interactive("getViewerPermissions", api.getViewerPermissions),
getDiff: wrap("getDiff", api.getDiff),
...(api.getDiffFilePaths === undefined
? {}
: { getDiffFilePaths: wrap("getDiffFilePaths", api.getDiffFilePaths) }),
...(api.getDiffFileContents === undefined
? {}
: { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }),
...(api.getFilesViewed === undefined
? {}
: { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }),
...(api.getFileStats === undefined
? {}
: { getFileStats: wrap("getFileStats", api.getFileStats) }),
...(api.setFilesViewed === undefined
? {}
: { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }),
...(api.getFileRevisions === undefined
? {}
: { getFileRevisions: wrap("getFileRevisions", api.getFileRevisions) }),
runAction: interactive("runAction", api.runAction),
...(api.updateChangeRequest === undefined
? {}
: {
updateChangeRequest: interactive("updateChangeRequest", api.updateChangeRequest),
}),
comment: interactive("comment", api.comment),
...(api.updateComment === undefined
? {}
: { updateComment: interactive("updateComment", api.updateComment) }),
submitReview: interactive("submitReview", api.submitReview),
listReviewerCandidates: interactive("listReviewerCandidates", api.listReviewerCandidates),
setReviewerRequest: interactive("setReviewerRequest", api.setReviewerRequest),
...(api.listLabelCandidates === undefined
? {}
: { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }),
...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }),
...(api.listRepositoryLabels === undefined
? {}
: { listRepositoryLabels: interactive("listRepositoryLabels", api.listRepositoryLabels) }),
...(api.searchRepositoryAuthors === undefined
? {}
: {
searchRepositoryAuthors: interactive(
"searchRepositoryAuthors",
api.searchRepositoryAuthors,
),
}),
...(api.searchRepositoryReferences === undefined
? {}
: {
searchRepositoryReferences: interactive(
"searchRepositoryReferences",
api.searchRepositoryReferences,
),
}),
replyToThread: interactive("replyToThread", api.replyToThread),
setReaction: interactive("setReaction", api.setReaction),
setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
};
// Optional provider methods must be forwarded too; returning the interface alone permits omissions.
return wrapped satisfies PullRequestProviderApi &
Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;
}
const FILTER_OPTIONS_LIMIT = 100;
/**
* Exact matches first, then names that begin with the query, then the rest, so a short query
* still puts the obvious answer at the top of a long list.
*/
function rankFilterOptions<A>(
pages: ReadonlyArray<ProviderFilterOptionPage<A>>,
input: {
readonly query: string | undefined;
readonly keyOf: (item: A) => string;
readonly textsOf: (item: A) => ReadonlyArray<string | null>;
/** Ties keep the hosts' order instead of sorting by key. */
readonly hostOrder?: boolean;
},
): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } {
const query = input.query?.trim().toLowerCase() ?? "";
const unique = new Map<string, A>();
for (const page of pages) {
for (const item of page.items) {
const key = input.keyOf(item).toLowerCase();
if (!unique.has(key)) unique.set(key, item);
}
}
const rank = (item: A) => {
const texts = input.textsOf(item).flatMap((text) => (text ? [text.toLowerCase()] : []));
if (query.length === 0) return 0;
if (texts.includes(query)) return 0;
if (texts.some((text) => text.startsWith(query))) return 1;
if (texts.some((text) => text.includes(query))) return 2;
return null;
};
const ranked = [...unique.values()]
.flatMap((item) => {
const score = rank(item);
return score === null ? [] : [{ item, score, key: input.keyOf(item) }];
})
.toSorted(
(left, right) =>
left.score - right.score ||
(input.hostOrder === true
? 0
: left.key.localeCompare(right.key, undefined, { sensitivity: "base" })),
);
return {
items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item),
truncated: ranked.length > FILTER_OPTIONS_LIMIT || pages.some((page) => page.truncated),
};
}
const remoteHostKey = (recognized: SourceControlProviderInfo, remoteUrl: string) =>
`${recognized.baseUrl}\n${isSshRemoteUrl(remoteUrl) ? "ssh" : "web"}`;
/** An HTTP remote names its server's web host, port included. */
function httpRemoteHost(remoteUrl: string): string | null {
try {
const remote = new URL(remoteUrl);
return remote.protocol === "http:" || remote.protocol === "https:"
? remote.host.toLowerCase()
: null;
} catch {
return null;
}
}
// Capture before the provider read so a slow response keeps its original freshness through caches.
const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {
const observedAt = yield* Clock.currentTimeMillis;
return { value: yield* read, observedAt };
});
export const make = Effect.gen(function* () {
const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64);
const stateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64);
const pullRequestRefreshes = yield* SubscriptionRef.make(0);
const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry;
const requirementOf: UnavailableRequirementOf = (kind) =>
registry.get(kind)?.unavailableRequirement;
const toPullRequestError = toPullRequestErrorWith(requirementOf);
const serverSettings = yield* ServerSettings.ServerSettingsService;
const projects = yield* ProjectService.ProjectService;
const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit;
const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository;
const readCache = yield* PullRequestReadCache.PullRequestReadCache;
const clock = yield* Clock.Clock;
/**
* Where each project's remote is served from, by the remote's recognised base URL: a remote no
* definition placed is identified by the hosting CLIs, and a host whose remotes may not name
* its web server says which one does. One project per base URL and transport answers for all
* of them.
*/
const resolveRemoteHosts = Effect.fn("PullRequestService.resolveRemoteHosts")(function* (
projects: ReadonlyArray<OrchestrationProjectShell>,
filter: Pick<PullRequestListInput, "projectId" | "host">,
) {
type Candidate = {
readonly project: OrchestrationProjectShell;
readonly context: SourceControlProviderContext;
};
const candidatesByKey = new Map<string, Candidate[]>();
for (const project of projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
const identity = project.repositoryIdentity;
if (
!identity ||
identity.provider === undefined ||
sourceControlDefinitions.repositorySelector(identity) === null
)
continue;
if (identity.provider !== "unknown") {
const provider = yield* sourceControlProviders
.get(identity.provider)
.pipe(Effect.orElseSucceed(() => null));
if (provider?.resolveRemoteWebHost === undefined) continue;
}
const host = sourceControlDefinitions.changeRequestHost(identity, "unknown");
if (
filter.host !== undefined &&
host !== "unknown" &&
host !== filter.host.toLowerCase() &&
httpRemoteHost(identity.locator.remoteUrl) !== filter.host.toLowerCase() &&
!isSshRemoteUrl(identity.locator.remoteUrl)
) {
continue;
}
const { remoteName, remoteUrl } = identity.locator;
const recognized = sourceControlDefinitions.recognizeRemote(remoteUrl);
if (recognized === null) continue;
const candidate = {
project,
context: {
provider:
identity.provider === "unknown"
? recognized
: { ...recognized, kind: identity.provider },
remoteName,
remoteUrl,
...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)
? { requestedHost: filter.host }
: {}),
},
};
const key = remoteHostKey(recognized, remoteUrl);
const candidates = candidatesByKey.get(key);
if (candidates === undefined) candidatesByKey.set(key, [candidate]);
else candidates.push(candidate);
}
const resolveContext = (input: {
readonly cwd: string;
readonly context: SourceControlProviderContext;
}) => sourceControlProviders.resolveHandle(input).pipe(Effect.map((handle) => handle.context));
type RemoteHost = { readonly kind: SourceControlProviderKind; readonly host: string | null };
const resolveCandidate = ({ project, context }: Candidate) =>
(context.provider.kind === "unknown"
? resolveContext({ cwd: project.workspaceRoot, context }).pipe(
Effect.map((resolved) =>
resolved === null || resolved.provider.kind === "unknown"
? null
: { context: resolved, discovered: true },
),
)
: Effect.succeed({ context, discovered: false })
).pipe(
Effect.flatMap((found) =>
found === null
? Effect.succeed(null)
: sourceControlProviders.get(found.context.provider.kind).pipe(
Effect.flatMap(
(provider) =>
provider.resolveRemoteWebHost?.({
cwd: project.workspaceRoot,
context: found.context,
// A remote discovery just placed is not looked up a second time.
resolveContext: found.discovered
? () => Effect.succeed(found.context)
: resolveContext,
}) ?? Effect.succeed(null),
),
Effect.orElseSucceed(() => null),
Effect.map((host): RemoteHost => ({ kind: found.context.provider.kind, host })),
),
),
Effect.orElseSucceed(() => null),
);
// An SSH remote whose web host one checkout could not name may be named by the next; a
// kind found without a host still stands if none can.
const resolveKey = Effect.fn("PullRequestService.resolveRemoteHost")(function* (
candidates: ReadonlyArray<Candidate>,
) {
let fallback: RemoteHost | null = null;
for (const candidate of candidates) {
const resolved = yield* resolveCandidate(candidate);
if (resolved === null) continue;
if (resolved.host !== null || !isSshRemoteUrl(candidate.context.remoteUrl)) {
return resolved;
}
fallback ??= resolved;
}
return fallback;
});
return yield* Effect.forEach(
candidatesByKey,
([key, candidates]) =>
resolveKey(candidates).pipe(Effect.map((resolved) => [key, resolved] as const)),
{ concurrency: REPOSITORY_CONCURRENCY },
).pipe(Effect.map((resolved) => new Map(resolved)));
});
const listWorkspaceProjects = (
filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
): Effect.Effect<WorkspaceProjects, PullRequestError> =>
Effect.flatMap(sharedProjectReads, (shared) => {
if (shared === null || !shared.open) return readWorkspaceProjects(filter);
const key = JSON.stringify([filter.projectId, filter.projectIds, filter.host]);
const existing = shared.reads.get(key);
if (existing !== undefined) return existing;
return Effect.cached(readWorkspaceProjects(filter)).pipe(
Effect.tap((read) => Effect.sync(() => shared.reads.set(key, read))),
Effect.flatten,
);
});
const withSharedProjectReads = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.suspend(() => {
const shared = { open: true, reads: new Map() };
return effect.pipe(
Effect.provideService(sharedProjectReads, shared),
Effect.ensuring(
Effect.sync(() => {
shared.open = false;
shared.reads.clear();
}),
),
);
});
const readWorkspaceProjects = (
filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
): Effect.Effect<WorkspaceProjects, PullRequestError> =>
(filter.projectId === undefined
? projects.listShells(
filter.projectIds === undefined ? undefined : { projectIds: filter.projectIds },
)
: projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
).pipe(
Effect.mapError(
(error) =>
new PullRequestOperationError({
operation: "listProjects",
detail: "The project list could not be read.",
cause: error,
}),
),
Effect.flatMap((projects) =>
Effect.forEach(
projects,
(project) =>
project.repositoryIdentity != null
? Effect.succeed(project)
: repositoryIdentities
.resolve(project.workspaceRoot)
.pipe(Effect.map((repositoryIdentity) => ({ ...project, repositoryIdentity }))),
{ concurrency: REPOSITORY_CONCURRENCY },
),
),
Effect.flatMap((projects) =>
resolveRemoteHosts(projects, filter).pipe(
Effect.map((remoteHosts) => ({ remoteHosts, projects })),
),
),
Effect.map(({ remoteHosts, projects }) => {
const supported: SupportedProject[] = [];
const unimplemented = new Map<
string,
{ kind: SourceControlProviderKind; projectCount: number }
>();
const viewerRoots = new Map<string, string[]>();
const seen = new Set<string>();
for (const project of projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
const identity = project.repositoryIdentity;
let kind = identity?.provider;
const repository = sourceControlDefinitions.repositorySelector(
project.repositoryIdentity,
);
if (!identity || kind === undefined || repository === null) continue;
const recognized = sourceControlDefinitions.recognizeRemote(identity.locator.remoteUrl);
const remote =
recognized === null
? undefined
: remoteHosts.get(remoteHostKey(recognized, identity.locator.remoteUrl));
kind = remote?.kind ?? kind;
const host = remote?.host ?? sourceControlDefinitions.changeRequestHost(identity, kind);
if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
continue;
}
const registered = registry.get(kind);
const api = registered?.servesHost?.(host) === false ? null : registered;
if (api !== null) {
const roots = viewerRoots.get(host);
if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);
else if (!roots.includes(project.workspaceRoot)) roots.push(project.workspaceRoot);
}
const repositoryKey =
api?.repositoryKey?.({ canonicalKey: identity.canonicalKey }) ?? null;
const key = listCursorKey(host, repositoryKey ?? repository);
if (seen.has(key)) continue;
seen.add(key);
if (api === null) {
const counted = unimplemented.get(host);
if (counted === undefined) unimplemented.set(host, { kind, projectCount: 1 });
else counted.projectCount += 1;
continue;
}
supported.push({
cursorKey: key,
project,
api: withRateLimitBackoff(api, host, rateLimits),
repository,
host,
remote:
repositoryKey ??
sourceControlDefinitions.repositoryKeyFromRemote(`https://${host}/${repository}`),
repositoryKey:
repositoryKey === null
? null
: sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()),
});
}
return { supported, unimplemented, viewerRoots };
}),
);
// Azure derives organization from the checkout; require the matching repository.
const requireProject = (ref: PullRequestRef): Effect.Effect<SupportedProject, PullRequestError> =>
listWorkspaceProjects({ projectId: ref.projectId }).pipe(
Effect.flatMap(({ supported }): Effect.Effect<SupportedProject, PullRequestError> => {
const own = supported[0];
const repository = ref.repository.trim();
const host = ref.host?.trim().toLowerCase();
if (own !== undefined && own.repository.toLowerCase() === repository.toLowerCase()) {
if (host === undefined || host === own.host) return Effect.succeed(own);
}
if (host === undefined) {