Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitCafePullRequestProvider.ts

1,185 lines47.8 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
6import {
7 NonNegativeInt,
8 resolvePullRequestAuthorFilter,
9 TrimmedNonEmptyString,
10 type PullRequestCapabilities,
11 type PullRequestListFilters,
12 type PullRequestStackHead,
13} from "@t3tools/contracts";
14import {
15 PullRequestProviderError,
16 type ProviderRepositoryRef,
17 type PullRequestProviderApi,
18} from "@t3tools/source-control-core/server/PullRequestProvider";
19​
20import * as GitCafeApi from "./GitCafeApi.ts";
21import * as GitCafeHosts from "./gitCafeHosts.ts";
22import * as Json from "./gitCafePullRequestJson.ts";
23import { definition } from "../shared/definition.ts";
24​
25const CAPABILITIES: PullRequestCapabilities = {
26 diff: true,
27 comment: true,
28 actions: [...definition.changeRequestActions],
29 mergeMethods: ["merge", "squash", "rebase"],
30 // Only through a stack: GitCafe's one branch update restacks every layer above it.
31 updateMethods: ["rebase"],
32 search: true,
33 stacks: true,
34 stackActions: true,
35 reactions: true,
36 labels: true,
37 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
38 review: {
39 inlineComment: false,
40 reply: true,
41 resolve: true,
42 verdicts: ["approve", "request-changes", "comment"],
43 },
44 reviewers: { request: true, listCandidates: true },
45 edit: { changeRequest: true, comment: true },
46};
47​
48const PAGE_SIZE = 100;
49const MAX_PAGES = 10;
50/**
51 * Pages read looking for a GitHub-synced author before a listing filtered by them gives up. The
52 * login only appears on their pull requests, so one older than this many is out of reach.
53 */
54const AUTHOR_DISCOVERY_PAGES = 5;
55/** Bounds the logins remembered from listings; a repository's authors fit many times over. */
56const KNOWN_AUTHORS_LIMIT = 10_000;
57/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
58const DIFF_FILES_BATCH = 64;
59/**
60 * Line totals cost one hunk read per batch, so a pull request larger than this reports none
61 * rather than reading every file.
62 */
63const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
64const MAX_CHANGE_PAGES = 20;
65const LINE_STATS_CACHE_SIZE = 256;
66​
67const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
68 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
69 items.slice(index * size, (index + 1) * size),
70 );
71​
72const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
73 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
74​
75const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
76 status.merge.permitted !== false &&
77 status.merge.strategies.includes(strategy) &&
78 !(status.merge.blockers ?? []).some((blocker) =>
79 (blocker.blockedStrategies ?? []).includes(strategy),
80 );
81​
82const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
83const isId = Schema.is(Id);
84const isApiError = Schema.is(GitCafeApi.GitCafeApiError);
85const Principal = Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString });
86const User = Schema.Struct({ actorId: TrimmedNonEmptyString });
87const Written = Schema.Struct({ id: Id });
88const Versioned = Schema.Struct({ version: NonNegativeInt });
89const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
90const Status = Schema.Struct({
91 merge: Schema.Struct({
92 // The API reference lists "unknown" and "conflicting", but git.cafe also sends "none" and
93 // "pending", so any state is read and only the known ones are mapped.
94 conflicts: Schema.String,
95 fastForward: Schema.NullOr(Schema.Boolean),
96 strategies: Schema.Array(Schema.String),
97 permitted: Schema.optional(Schema.Boolean),
98 reasons: Schema.optional(Schema.Array(Schema.String)),
99 blockers: Schema.optional(
100 Schema.Array(
101 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
102 ),
103 ),
104 }),
105 checks: Schema.Struct({
106 pending: NonNegativeInt,
107 failing: NonNegativeInt,
108 total: NonNegativeInt,
109 }),
110});
111/** A merge GitCafe accepted runs on afterwards: on GitHub for a synced pull request, or natively. */
112const MERGE_IN_FLIGHT = new Set(["provider-merge-pending", "native-operation-pending"]);
113const Listed = Schema.Struct({
114 items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString })),
115 next: Schema.NullOr(Schema.String),
116});
117const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
118const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
119const Snapshot = {
120 version: NonNegativeInt,
121 headOid: TrimmedNonEmptyString,
122 comparisonBaseOid: TrimmedNonEmptyString,
123};
124const Changes = Schema.Struct({
125 ...Snapshot,
126 items: Json.GitCafeDiffFiles,
127 next: Schema.NullOr(TrimmedNonEmptyString),
128});
129const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
130const DiffCursor = Schema.Struct({
131 version: NonNegativeInt,
132 headOid: TrimmedNonEmptyString,
133 baseOid: TrimmedNonEmptyString,
134 after: TrimmedNonEmptyString,
135});
136const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
137const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
138const MergeOutcome = Schema.Struct({
139 id: Schema.String,
140 state: Schema.Literals(["accepted", "completed", "failed"]),
141 reason: Schema.optional(Schema.String),
142});
143const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
144const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
145​
146type PullRef = ProviderRepositoryRef & { readonly number: number };
147​
148/** GitHub's merge counts as soon as GitCafe records it, ahead of the sync that reports it. */
149const settledMerge = (pull: Json.GitCafePullDetail) =>
150 pull.state === "open" && pull.providerMerge != null
151 ? { state: "merged" as const, mergedAt: pull.providerMerge.mergedAt }
152 : {};
153type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
154​
155function stackHeadsCurrent(
156 stack: Json.GitCafeStack,
157 input: { readonly number: number; readonly merge: boolean },
158 expected: ReadonlyArray<PullRequestStackHead>,
159): boolean {
160 const members = stack.members.toSorted((a, b) => a.position - b.position);
161 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
162 if (index === -1) return false;
163 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
164 (member) => member.state !== "merged",
165 );
166 return (
167 moved.length === expected.length &&
168 moved.every(
169 (member) =>
170 member.headOid !== undefined &&
171 expected.some(
172 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
173 ),
174 )
175 );
177​
178const POSITION = /^(.+)~(\d+)$/u;
179const parsePosition = (raw: string | undefined) => {
180 const match = raw === undefined ? null : POSITION.exec(raw);
181 const created = match === null ? Number.NaN : Date.parse(match[1]!);
182 return match === null || Number.isNaN(created) ? null : { created, number: Number(match[2]) };
183};
184​
185const withDetails = (
186 files: ReadonlyArray<Json.GitCafeDiffFile>,
187 details: ReadonlyArray<Json.GitCafeDiffFile>,
188) => {
189 const byPath = new Map(details.map((file) => [file.path, file]));
190 return files.map((file) => byPath.get(file.path) ?? file);
191};
192​
193/** @public Service construction is part of the canonical Effect module API. */
194export const make = Effect.gen(function* () {
195 const api = yield* GitCafeApi.GitCafeApi;
196 // GitCafe filters by actor id and has no lookup from a GitHub login to the actor sync made for
197 // it, so the pairs are learned from the pull requests every listing reads.
198 const knownAuthors = new Map<string, string>();
199 const authorKey = (host: string, login: string) =>
200 `${host.toLowerCase()}\n${login.toLowerCase()}`;
201 const learnAuthors = (host: string, pulls: ReadonlyArray<Json.GitCafePull>) => {
202 for (const { author } of pulls) {
203 if (author.kind !== "github") continue;
204 if (knownAuthors.size >= KNOWN_AUTHORS_LIMIT) knownAuthors.clear();
205 knownAuthors.set(authorKey(host, author.login), author.actorId);
206 }
207 };
208​
209 const failure = (operation: string, detail: string, cause?: unknown) =>
210 new PullRequestProviderError({
211 provider: SourceControlProviderKind.make("gitcafe"),
212 operation,
213 reason: "failed",
214 detail,
215 ...(cause === undefined ? {} : { cause }),
216 });
217​
218 const repositoryPath = (
219 operation: string,
220 input: ProviderRepositoryRef,
221 ): Effect.Effect<string, PullRequestProviderError> =>
222 GitCafeHosts.isGitCafeHost(input.host) &&
223 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
224 ? Effect.succeed(`/repos/${input.repository}`)
225 : Effect.fail(
226 failure(
227 operation,
228 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
229 ),
230 );
231​
232 const send = (
233 operation: string,
234 input: Pick<ProviderRepositoryRef, "host">,
235 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
236 ) =>
237 api.request({ ...request, host: input.host, operation }).pipe(
238 Effect.mapError(
239 (error) =>
240 new PullRequestProviderError({
241 provider: SourceControlProviderKind.make("gitcafe"),
242 operation,
243 reason: error.reason,
244 detail: error.detail,
245 cause: error,
246 }),
247 ),
248 );
249​
250 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
251 operation: string,
252 input: Pick<ProviderRepositoryRef, "host">,
253 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
254 schema: S,
255 ) =>
256 send(operation, input, request).pipe(
257 Effect.flatMap((raw) =>
258 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
259 Effect.mapError((cause) =>
260 failure(operation, "GitCafe returned an unreadable response.", cause),
261 ),
262 ),
263 ),
264 );
265​
266 const pullPath = (operation: string, input: PullRef) =>
267 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
268​
269 const readPull = (operation: string, input: PullRef) =>
270 pullPath(operation, input).pipe(
271 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
272 );
273​
274 const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
275 S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
276 >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
277 const items: Array<S["Type"]["items"][number]> = [];
278 let next: string | null = null;
279 for (let page = 0; page < MAX_PAGES; page++) {
280 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
281 if (next !== null) query.set("after", next);
282 const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
283 items.push(...batch.items);
284 const previous: string | null = next;
285 next = batch.next;
286 if (next === null || next === previous || batch.items.length === 0) break;
287 }
288 return { items, next };
289 });
290​
291 /**
292 * GitCafe filters by ids, so label names and the author's handle are looked up first. A label it
293 * cannot resolve is left out, and the service narrows the rows by name instead. An author it
294 * cannot resolve comes back as `unresolvedAuthor` for the listing to find.
295 */
296 const listFilterParams = Effect.fn("GitCafePullRequestProvider.listFilterParams")(function* (
297 input: ProviderRepositoryRef & {
298 readonly filters?: PullRequestListFilters | undefined;
299 readonly authorNarrowed: boolean;
300 readonly viewer: string;
301 },
302 base: string,
303 ) {
304 const filters = input.filters;
305 const params: Array<readonly [string, string]> = [];
306 if (filters === undefined) return { params, unresolvedAuthor: null };
307 if (filters.draft !== undefined)
308 params.push([filters.draft === "only" ? "states" : "stateNots", encodeIds(["draft"])]);
309 const groups = filters.labels ?? [];
310 const excluded = filters.excludedLabels ?? [];
311 if (groups.length > 0 || excluded.length > 0) {
312 const labels = yield* readPages(
313 "listChangeRequests",
314 input,
315 `${base}/labels`,
316 Json.GitCafeLabels,
317 );
318 const ids = new Map(labels.items.map((label) => [label.name.toLowerCase(), label.id]));
319 const idsOf = (names: ReadonlyArray<string>) =>
320 names.flatMap((name) => {
321 const id = ids.get(name.trim().toLowerCase());
322 return id === undefined ? [] : [id];
323 });
324 // Several ids in `labels` match a pull request holding any one of them, which is exactly
325 // one group; the remaining groups are the service's to narrow.
326 const group = groups.find((names) => idsOf(names).length === names.length);
327 if (group !== undefined) params.push(["labels", encodeIds(idsOf(group))]);
328 const excludedIds = idsOf(excluded);
329 if (excludedIds.length > 0) params.push(["labelNots", encodeIds(excludedIds)]);
330 }
331 if (filters.author !== undefined && !input.authorNarrowed) {
332 const handle = resolvePullRequestAuthorFilter(filters.author, input.viewer);
333 // A profile matches what GitHub sync authored for it too. A GitHub-synced author with no
334 // profile is known only by the actor on their pull requests.
335 const user = yield* read(
336 "listChangeRequests",
337 input,
338 { path: `/users/${encodeURIComponent(handle)}` },
339 User,
340 ).pipe(
341 Effect.map(Option.some),
342 Effect.catchTags({
343 PullRequestProviderError: (error) =>
344 error.reason === "unauthenticated" || error.reason === "rate-limited"
345 ? Effect.fail(error)
346 : Effect.succeed(Option.none()),
347 }),
348 );
349 const actorId = Option.isSome(user)
350 ? user.value.actorId
351 : knownAuthors.get(authorKey(input.host, handle));
352 if (actorId === undefined) return { params, unresolvedAuthor: handle };
353 params.push(["authors", encodeIds([actorId])]);
354 }
355 return { params, unresolvedAuthor: null };
356 });
357​
358 const readComments = (operation: string, input: PullRef) =>
359 pullPath(operation, input).pipe(
360 Effect.flatMap((path) =>
361 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
362 ),
363 );
364​
365 const isForbidden = (error: PullRequestProviderError) =>
366 isApiError(error.cause) && error.cause.status === 403;
367​
368 /**
369 * GitCafe offers no way to read a token's scopes, so reviewer controls show
370 * for anyone who may edit the pull request; a token without the reviewer
371 * scopes learns which ones it lacks when it uses them.
372 */
373 const explainReviewerScopes =
374 (operation: string) =>
375 <A, R>(effect: Effect.Effect<A, PullRequestProviderError, R>) =>
376 effect.pipe(
377 Effect.catchIf(isForbidden, (error) =>
378 Effect.fail(
379 failure(
380 operation,
381 "This GitCafe token cannot request reviewers. It needs the pr:review:read and pr:reviewers:write scopes.",
382 error,
383 ),
384 ),
385 ),
386 );
387​
388 /**
389 * GitCafe replaces a pull request's whole reviewer or label list, so one toggle reads the
390 * list, changes it, and writes it back fenced on the pull request's version. The version is
391 * read first: a change landing between the two reads then fails the fence instead of being
392 * overwritten.
393 */
394 const toggleListed = Effect.fn("GitCafePullRequestProvider.toggleListed")(function* (
395 operation: string,
396 input: PullRef,
397 list: { readonly name: "reviewers" | "labels"; readonly key: "actorIds" | "labelIds" },
398 ids: ReadonlyArray<string>,
399 on: boolean,
400 ) {
401 const path = yield* pullPath(operation, input);
402 const pull = yield* readPull(operation, input);
403 const listed = yield* readPages(operation, input, `${path}/${list.name}`, Listed);
404 const current = listed.items.map((item) => item.id);
405 const next = on
406 ? [...new Set([...current, ...ids])]
407 : current.filter((id) => !ids.includes(id));
408 if (next.length === current.length) return;
409 yield* read(
410 operation,
411 input,
412 {
413 method: "PUT",
414 path: `${path}/${list.name}`,
415 body: { expectedVersion: pull.version, [list.key]: next },
416 },
417 Versioned,
418 );
419 });
420​
421 /**
422 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
423 * open layer's pull is read.
424 */
425 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
426 operation: string,
427 input: PullRef,
428 ) {
429 const path = yield* pullPath(operation, input);
430 const { stack } = yield* read(
431 operation,
432 input,
433 { path: `${path}/stack` },
434 Json.GitCafeStackEnvelope,
435 );
436 if (stack === null) return null;
437 const members = yield* Effect.forEach(
438 stack.members,
439 (member) =>
440 member.state === "merged"
441 ? Effect.succeed(member)
442 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
443 Effect.map((pull) =>
444 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
445 ),
446 ),
447 { concurrency: 4 },
448 );
449 return { ...stack, members };
450 });
451​
452 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
453 input: PullRef,
454 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
455 paths: ReadonlyArray<string>,
456 ) {
457 if (paths.length === 0) return [];
458 const path = yield* pullPath("getDiff", input);
459 const files = yield* read(
460 "getDiff",
461 input,
462 {
463 method: "POST",
464 path: `${path}/diff-files`,
465 body: { paths, expectedVersion: revision.version },
466 },
467 DiffFiles,
468 );
469 if (
470 files.version !== revision.version ||
471 files.headOid !== revision.headOid ||
472 files.comparisonBaseOid !== revision.baseOid
473 )
474 return yield* failure(
475 "getDiff",
476 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
477 );
478 return files.items;
479 });
480​
481 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
482 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
483 ) {
484 const land = input.action === "merge";
485 const operation = land ? "landStackThrough" : "restackStack";
486 if (!land && input.action !== "update-branch")
487 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
488 const stack = yield* readStack(operation, input);
489 if (
490 stack === null ||
491 stack.number !== input.stackNumber ||
492 input.expectedStackHeads === undefined ||
493 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
494 )
495 return yield* failure(
496 operation,
497 "The stack changed since it was read. Refresh it and try again.",
498 );
499 const base = yield* repositoryPath(operation, input);
500 const outcome = yield* read(
501 operation,
502 input,
503 {
504 method: "POST",
505 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
506 body: land
507 ? {
508 expectedRevision: stack.revision,
509 requestId: yield* randomUuidV4,
510 throughPullRequestNumber: input.number,
511 strategy: input.mergeMethod ?? "merge",
512 }
513 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
514 },
515 StackOutcome,
516 );
517 if (FAILED_STACK_STATES.has(outcome.state))
518 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
519 });
520​
521 // GitCafe's pulls carry no line totals, and linked pull requests are summarized every minute,
522 // so hunk totals are held per compared pair of commits. The file list that names the pair is
523 // cheap; a retarget or a landed parent layer moves the base without moving the head.
524 const lineTotals = new Map<string, { readonly additions: number; readonly deletions: number }>();
525​
526 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
527 input: PullRef,
528 version: number,
529 ) {
530 const path = yield* pullPath("getChangeRequest", input);
531 const files: Array<Json.GitCafeDiffFile> = [];
532 let revision: { version: number; headOid: string; baseOid: string } | undefined;
533 let after: string | null = null;
534 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
535 const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
536 if (after !== null) query.set("after", after);
537 const batch: typeof Changes.Type = yield* read(
538 "getChangeRequest",
539 input,
540 { path: `${path}/changes?${query}` },
541 Changes,
542 );
543 revision ??= {
544 version: batch.version,
545 headOid: batch.headOid,
546 baseOid: batch.comparisonBaseOid,
547 };
548 files.push(...batch.items);
549 const previous: string | null = after;
550 after = batch.next;
551 if (after === null || after === previous || batch.items.length === 0) break;
552 }
553 if (revision === undefined) return { changedFiles: 0, additions: 0, deletions: 0 };
554 const key = `${input.host} ${input.repository.toLowerCase()} ${input.number} ${revision.baseOid} ${revision.headOid}`;
555 const held = lineTotals.get(key);
556 if (held !== undefined) return { changedFiles: files.length, ...held };
557 const details = files.some((file) => file.additions !== undefined)
558 ? Option.some(files)
559 : files.length > LINE_STATS_MAX_FILES
560 ? Option.none()
561 : yield* Effect.forEach(
562 chunk(detailablePaths(files), DIFF_FILES_BATCH),
563 (paths) => readDiffFiles(input, revision, paths),
564 { concurrency: 4 },
565 ).pipe(
566 Effect.map((batches) => batches.flat()),
567 Effect.option,
568 );
569 // Unread hunks leave the lines unknown rather than zero; the file count still stands.
570 if (Option.isNone(details)) return { changedFiles: files.length };
571 const counted = details.value;
572 const totals = {
573 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
574 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
575 };
576 if (lineTotals.size >= LINE_STATS_CACHE_SIZE)
577 lineTotals.delete(lineTotals.keys().next().value!);
578 lineTotals.set(key, totals);
579 return { changedFiles: files.length, ...totals };
580 });
581​
582 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
583 input: Parameters<PullRequestProviderApi["runAction"]>[0],
584 ) {
585 const pull = yield* readPull("merge", input);
586 if (pull.state === "merged") return;
587 if (pull.mergeRoute === "unsupported")
588 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
589 const base = yield* repositoryPath("merge", input);
590 // GitCafe observes the base only for merges it routes to the provider; a native merge is
591 // fenced on the target branch's current commit.
592 const baseOid =
593 pull.mergeRoute === "provider"
594 ? pull.observedBaseOid
595 : (yield* read(
596 "merge",
597 input,
598 {
599 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
600 },
601 BranchCommit,
602 )).oid;
603 if (pull.headOid === null || baseOid == null)
604 return yield* failure(
605 "merge",
606 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
607 );
608 const path = yield* pullPath("merge", input);
609 const outcome = yield* read(
610 "merge",
611 input,
612 {
613 method: "POST",
614 path: `${path}/merge`,
615 body: {
616 requestId: yield* randomUuidV4,
617 expectedVersion: pull.version,
618 headOid: pull.headOid,
619 baseOid,
620 strategy: input.mergeMethod ?? "merge",
621 },
622 },
623 MergeOutcome,
624 );
625 if (outcome.state === "failed")
626 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
627 });
628​
629 const provider: PullRequestProviderApi = {
630 kind: SourceControlProviderKind.make("gitcafe"),
631 capabilities: CAPABILITIES,
632 getViewer: (input) =>
633 read(
634 "getViewer",
635 { host: input.host ?? "git.cafe" },
636 { path: "/auth/principal" },
637 Principal,
638 ).pipe(Effect.map((principal) => principal.handle)),
639 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
640 function* (input) {
641 const base = yield* repositoryPath("listChangeRequests", input);
642 const involved = input.involvement === "authored" || input.involvement === "reviewing";
643 let actorId: string | undefined;
644 if (involved) {
645 // The viewer is the token's principal, whose actor also matches the pull requests GitHub
646 // sync authored for its linked profile. When it can't be read, the listing comes back
647 // unnarrowed and the page's own involvement filter does the rest. A refused token or a
648 // rate limit still fails, since the service acts on those for the whole host.
649 const principal = yield* read(
650 "listChangeRequests",
651 input,
652 { path: "/auth/principal" },
653 Principal,
654 ).pipe(
655 Effect.map(Option.some),
656 Effect.catchTags({
657 PullRequestProviderError: (error) =>
658 error.reason === "unauthenticated" || error.reason === "rate-limited"
659 ? Effect.fail(error)
660 : Effect.succeed(Option.none()),
661 }),
662 );
663 if (Option.isSome(principal)) {
664 if (principal.value.handle.toLowerCase() !== input.viewer.toLowerCase())
665 return { items: [], truncated: false, continues: false };
666 actorId = principal.value.actorId;
667 }
668 }
669 const { params: filterParams, unresolvedAuthor } = yield* listFilterParams(
670 { ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },
671 base,
672 );
673 const readPage = (rows: number, after: string | null) => {
674 const query = new URLSearchParams({ limit: String(rows), sort: "newest" });
675 if (input.state !== "all") query.set("state", input.state);
676 if (input.query?.trim()) query.set("q", input.query.trim());
677 for (const [key, value] of filterParams) query.set(key, value);
678 if (actorId !== undefined)
679 query.set(
680 input.involvement === "reviewing" ? "reviewers" : "authors",
681 encodeIds([actorId]),
682 );
683 if (after !== null) query.set("after", after);
684 return read(
685 "listChangeRequests",
686 input,
687 { path: `${base}/pulls?${query}` },
688 Json.GitCafePulls,
689 ).pipe(Effect.tap((page) => Effect.sync(() => learnAuthors(input.host, page.items))));
690 };
691 if (unresolvedAuthor !== null) {
692 // Rows are only ever handed out narrowed by actor, so a continuation always carries on
693 // the same narrowed listing.
694 const key = authorKey(input.host, unresolvedAuthor);
695 let after: string | null = null;
696 let pages = 0;
697 do {
698 const page: typeof Json.GitCafePulls.Type = yield* readPage(PAGE_SIZE, after);
699 pages += 1;
700 after = page.items.length === 0 ? null : page.next;
701 } while (!knownAuthors.has(key) && after !== null && pages < AUTHOR_DISCOVERY_PAGES);
702 const found = knownAuthors.get(key);
703 if (found === undefined)
704 return { items: [], truncated: after !== null, continues: false };
705 filterParams.push(["authors", encodeIds([found])]);
706 }
707 const limit = Math.max(1, input.limit);
708 const items: Array<Json.GitCafePull> = [];
709 // GitCafe pages by an opaque token and orders by creation, so a continuation reads from the
710 // top and keeps only the rows created after the last one delivered. A count of rows would
711 // skip one for every row above it that closed in between.
712 const resume = parsePosition(input.cursor?.resumeAfter);
713 const isNew = (pull: Json.GitCafePull) => {
714 if (resume === null) return true;
715 const created = Date.parse(pull.createdAt);
716 return (
717 created < resume.created || (created === resume.created && pull.number < resume.number)
718 );
719 };
720 let next: string | null = null;
721 do {
722 const page: typeof Json.GitCafePulls.Type = yield* readPage(
723 resume === null ? Math.min(PAGE_SIZE, limit - items.length) : PAGE_SIZE,
724 next,
725 );
726 items.push(...page.items.filter(isNew));
727 next = page.items.length === 0 ? null : page.next;
728 } while (next !== null && items.length < limit);
729 const delivered = items.slice(0, limit);
730 const last = delivered.at(-1);
731 return {
732 ...(last === undefined ? {} : { resumeAfter: `${last.createdAt}~${last.number}` }),
733 items: delivered.map((pull) => {
734 const item = Json.toChangeRequest(pull, input);
735 return input.involvement === "reviewing" && actorId !== undefined
736 ? {
737 ...item,
738 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
739 }
740 : item;
741 }),
742 truncated: next !== null || items.length > limit,
743 continues: true,
744 };
745 },
746 ),
747 getChangeRequestSummary: Effect.fn("GitCafePullRequestProvider.getChangeRequestSummary")(
748 function* (input) {
749 const pull = yield* readPull("getChangeRequestSummary", input);
750 const changes =
751 pull.headOid === null
752 ? null
753 : yield* readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null));
754 // A count that could not be read is absent rather than zero.
755 const {
756 additions: _additions,
757 deletions: _deletions,
758 ...summary
759 } = Json.toChangeRequest(pull, input);
760 return {
761 ...summary,
762 ...(changes === null ? {} : changes),
763 closedAt: pull.closedAt,
764 mergedAt: pull.mergedAt,
765 ...settledMerge(pull),
766 };
767 },
768 ),
769 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
770 const pull = yield* readPull("getChangeRequest", input);
771 const path = yield* pullPath("getChangeRequest", input);
772 const base = yield* repositoryPath("getChangeRequest", input);
773 // A single pull request read carries neither its reviewers nor its labels.
774 const [status, checks, changes, reviewers, labels] = yield* Effect.all(
775 [
776 read("getChangeRequest", input, { path: `${path}/status` }, Status),
777 pull.headOid === null
778 ? Effect.succeed(null)
779 : readPages(
780 "getChangeRequest",
781 input,
782 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
783 Json.GitCafeChecks,
784 ),
785 pull.headOid === null
786 ? Effect.succeed(null)
787 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
788 // Reviewers need `pr:review:read`, which a contents-only token lacks.
789 readPages("getChangeRequest", input, `${path}/reviewers`, Json.GitCafeActorEntries).pipe(
790 Effect.catch((error) =>
791 isForbidden(error) ? Effect.succeed({ items: [], next: null }) : Effect.fail(error),
792 ),
793 ),
794 readPages("getChangeRequest", input, `${path}/labels`, Json.GitCafeLabels),
795 ],
796 { concurrency: 5 },
797 );
798 const listed = { ...pull, reviewers: reviewers.items, labels: labels.items };
799 const checkList = checks === null ? [] : Json.toChecks(checks);
800 // GitCafe's own counts include runs a re-run replaced, so the newest runs are the state. A
801 // truncated listing may be missing a failure; the counts never call failing checks passing.
802 const checksState =
803 checks !== null && checks.next === null
804 ? Json.checksStateOf(checkList)
805 : status.checks.total === 0
806 ? null
807 : status.checks.failing > 0
808 ? ("failing" as const)
809 : status.checks.pending > 0
810 ? ("pending" as const)
811 : ("passing" as const);
812 const permissions = Json.toViewerPermissions(pull);
813 const merging = status.merge.reasons?.some((reason) => MERGE_IN_FLIGHT.has(reason)) ?? false;
814 return {
815 ...Json.toChangeRequest(listed, input),
816 autoMergeEnabled: merging,
817 headSha: pull.headOid,
818 body: pull.description ?? "",
819 ...(pull.sourceRepo === null
820 ? {}
821 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
822 additions: changes?.additions ?? 0,
823 deletions: changes?.deletions ?? 0,
824 changedFiles: changes?.changedFiles ?? 0,
825 closedAt: pull.closedAt,
826 mergedAt: pull.mergedAt,
827 ...settledMerge(pull),
828 reviewers: Json.toReviewers(listed, input.host),
829 checks: checkList,
830 ...(checksState === null ? {} : { checksState }),
831 mergeability:
832 status.merge.conflicts === "conflicting"
833 ? ("conflicting" as const)
834 : status.merge.conflicts === "none"
835 ? ("mergeable" as const)
836 : ("unknown" as const),
837 baseComparison:
838 status.merge.fastForward === null
839 ? ("unknown" as const)
840 : status.merge.fastForward
841 ? ("up-to-date" as const)
842 : ("behind" as const),
843 mergeCapabilities: {
844 merge: mergeStrategyOpen(status, "merge"),
845 squash: mergeStrategyOpen(status, "squash"),
846 rebase: mergeStrategyOpen(status, "rebase"),
847 },
848 viewerPermissions:
849 status.merge.permitted === false || merging
850 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
851 : permissions,
852 };
853 }),
854 getChangeRequestStack: (input) =>
855 readStack("getChangeRequestStack", input).pipe(
856 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
857 ),
858 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
859 function* (input) {
860 const pull = yield* readPull("getChangeRequestActivity", input);
861 const path = yield* pullPath("getChangeRequestActivity", input);
862 const operation = "getChangeRequestActivity";
863 const [comments, reviews, commits, reactions] = yield* Effect.all(
864 [
865 readComments(operation, input),
866 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
867 pull.headOid === null
868 ? Effect.succeed({ items: [], next: null })
869 : // A closed pull request whose branch is gone keeps its head, but git.cafe answers
870 // 404 for commits it no longer has; the conversation still stands without them.
871 readPages(operation, input, `${path}/commits`, Json.GitCafeCommits).pipe(
872 Effect.catch((error) =>
873 error.reason === "not-found"
874 ? Effect.succeed({ items: [], next: null })
875 : Effect.fail(error),
876 ),
877 ),
878 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
879 Effect.orElseSucceed(() => undefined),
880 ),
881 ],
882 { concurrency: 4 },
883 );
884 return Json.toActivity({
885 comments,
886 reviews,
887 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
888 host: input.host,
889 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
890 ...(reactions === undefined ? {} : { reactions }),
891 });
892 },
893 ),
894 getViewerPermissions: (input) =>
895 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
896 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
897 if (input.commit !== undefined)
898 return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
899 const cursor =
900 input.cursor === undefined
901 ? null
902 : yield* decodeDiffCursor(input.cursor).pipe(
903 Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
904 );
905 const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
906 const path = yield* pullPath("getDiff", input);
907 const query = new URLSearchParams({
908 expectedVersion: String(version),
909 limit: String(DIFF_FILES_BATCH),
910 });
911 if (cursor !== null) query.set("after", cursor.after);
912 const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
913 if (
914 page.version !== version ||
915 (cursor !== null &&
916 (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
917 )
918 return yield* failure(
919 "getDiff",
920 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
921 );
922 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
923 const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
924 return {
925 ...Json.toDiff({ items: withDetails(page.items, details) }),
926 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
927 };
928 }),
929 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
930 if (input.stackNumber !== undefined)
931 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
932 switch (input.action) {
933 case "merge":
934 return yield* merge(input);
935 case "ready":
936 case "draft":
937 case "close":
938 case "reopen": {
939 const pull = yield* readPull(input.action, input);
940 const path = yield* pullPath(input.action, input);
941 yield* send(input.action, input, {
942 method: "POST",
943 path: `${path}/${input.action}`,
944 body: { expectedVersion: pull.version },
945 });
946 return;
947 }
948 default:
949 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
950 }
951 }),
952 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
953 function* (input) {
954 const pull = yield* readPull("updateChangeRequest", input);
955 const path = yield* pullPath("updateChangeRequest", input);
956 yield* read(
957 "updateChangeRequest",
958 input,
959 {
960 method: "PATCH",
961 path,
962 body: {
963 expectedVersion: pull.version,
964 ...(input.title === undefined ? {} : { title: input.title }),
965 ...(input.body === undefined ? {} : { description: input.body }),
966 },
967 },
968 Versioned,
969 );
970 },
971 ),
972 comment: (input) =>
973 pullPath("comment", input).pipe(
974 Effect.flatMap((path) =>
975 read(
976 "comment",
977 input,
978 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
979 Written,
980 ),
981 ),
982 Effect.asVoid,
983 ),
984 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
985 if (!isId(input.commentId))
986 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
987 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
988 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
989 yield* read(
990 "updateComment",
991 input,
992 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
993 Written,
994 );
995 }),
996 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
997 if (input.comments.length > 0)
998 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
999 const pull = yield* readPull("submitReview", input);
1000 if (pull.headOid === null)
1001 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
1002 const path = yield* pullPath("submitReview", input);
1003 yield* read(
1004 "submitReview",
1005 input,
1007 method: "POST",
1008 path: `${path}/reviews`,
1009 body: {
1010 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
1011 ...(input.body.length === 0 ? {} : { body: input.body }),
1012 commitOid: pull.headOid,
1013 expectedVersion: pull.version,
1014 requestId: yield* randomUuidV4,
1015 },
1016 },
1017 Written,
1018 );
1019 }),
1020 listReviewerCandidates: Effect.fn("GitCafePullRequestProvider.listReviewerCandidates")(
1021 function* (input) {
1022 const operation = "listReviewerCandidates";
1023 const path = yield* pullPath(operation, input);
1024 const [pull, candidates, reviewers] = yield* Effect.all(
1026 readPull(operation, input),
1027 readPages(
1028 operation,
1029 input,
1030 `${path}/reviewer-candidates`,
1031 Json.GitCafeActorEntries,
1032 ).pipe(explainReviewerScopes(operation)),
1033 readPages(operation, input, `${path}/reviewers`, Listed).pipe(
1034 explainReviewerScopes(operation),
1035 ),
1036 ],
1037 { concurrency: 3 },
1038 );
1039 return {
1040 candidates: Json.toReviewerCandidates(candidates, {
1041 requested: new Set(reviewers.items.map((reviewer) => reviewer.id)),
1042 authorActorId: pull.author.actorId,
1043 host: input.host,
1044 }),
1045 truncated: candidates.next !== null,
1046 };
1047 },
1048 ),
1049 setReviewerRequest: (input) =>
1050 toggleListed(
1051 "setReviewerRequest",
1052 input,
1053 { name: "reviewers", key: "actorIds" },
1054 input.reviewers.map((reviewer) => reviewer.id),
1055 input.requested,
1056 ).pipe(explainReviewerScopes("setReviewerRequest")),
1057 listLabelCandidates: Effect.fn("GitCafePullRequestProvider.listLabelCandidates")(
1058 function* (input) {
1059 const operation = "listLabelCandidates";
1060 const base = yield* repositoryPath(operation, input);
1061 const [labels, applied] = yield* Effect.all(
1063 readPages(operation, input, `${base}/labels`, Json.GitCafeLabels),
1064 readPages(operation, input, `${base}/pulls/${input.number}/labels`, Listed),
1065 ],
1066 { concurrency: 2 },
1067 );
1068 const appliedIds = new Set(applied.items.map((label) => label.id));
1069 return {
1070 candidates: labels.items.map((label) => ({
1071 name: label.name,
1072 color: label.color,
1073 description: label.description ?? null,
1074 isApplied: appliedIds.has(label.id),
1075 })),
1076 truncated: labels.next !== null,
1077 };
1078 },
1079 ),
1080 listRepositoryLabels: Effect.fn("GitCafePullRequestProvider.listRepositoryLabels")(
1081 function* (input) {
1082 const operation = "listRepositoryLabels";
1083 const base = yield* repositoryPath(operation, input);
1084 const labels = yield* readPages(operation, input, `${base}/labels`, Json.GitCafeLabels);
1085 return {
1086 items: labels.items.map((label) => ({ name: label.name, color: label.color })),
1087 truncated: labels.next !== null,
1088 };
1089 },
1090 ),
1091 searchRepositoryAuthors: Effect.fn("GitCafePullRequestProvider.searchRepositoryAuthors")(
1092 function* (input) {
1093 const operation = "searchRepositoryAuthors";
1094 const query = input.query?.trim() ?? "";
1095 // User search needs two characters; before that the repository's own people stand in.
1096 const path =
1097 query.length < 2
1098 ? `${yield* repositoryPath(operation, input)}/collaborators?${new URLSearchParams({ limit: "50" })}`
1099 : `/users?${new URLSearchParams({ q: query, limit: "50" })}`;
1100 const people = yield* read(operation, input, { path }, Json.GitCafePeople);
1101 return { items: Json.toPeople(people, input.host), truncated: people.next !== null };
1102 },
1103 ),
1104 setLabels: Effect.fn("GitCafePullRequestProvider.setLabels")(function* (input) {
1105 const base = yield* repositoryPath("setLabels", input);
1106 const labels = yield* readPages("setLabels", input, `${base}/labels`, Json.GitCafeLabels);
1107 const selected = labels.items.filter((label) => input.labels.includes(label.name));
1108 if (selected.length !== input.labels.length)
1109 return yield* failure("setLabels", "One or more requested labels could not be found.");
1110 yield* toggleListed(
1111 "setLabels",
1112 input,
1113 { name: "labels", key: "labelIds" },
1114 selected.map((label) => label.id),
1115 input.applied,
1116 );
1117 }),
1118 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
1119 if (!isId(input.threadId))
1120 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
1121 const path = yield* pullPath("replyToThread", input);
1122 yield* read(
1123 "replyToThread",
1124 input,
1126 method: "POST",
1127 path: `${path}/comments/${input.threadId}/replies`,
1128 body: { body: input.body },
1129 },
1130 Written,
1131 );
1132 }),
1133 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
1134 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
1135 const subject =
1136 input.subjectId === undefined
1137 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
1138 : { kind: "pull_request_comment" as const, id: input.subjectId };
1139 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
1140 const mine = reactions.items.find(
1141 (item) =>
1142 item.subject.kind === subject.kind &&
1143 item.subject.id === subject.id &&
1144 item.emoji.kind === "unicode" &&
1145 Json.reactionContent(item.emoji.value) === input.content,
1146 )?.viewerReactionId;
1147 if (input.reacted === (mine != null)) return;
1148 if (input.reacted) {
1149 yield* send("setReaction", input, {
1150 method: "POST",
1151 path,
1152 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
1153 });
1154 return;
1156 if (mine == null) return;
1157 if (!isId(mine))
1158 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
1159 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
1160 }),
1161 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
1162 function* (input) {
1163 const comments = yield* readComments("setThreadResolution", input);
1164 const root = comments.items.find(
1165 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
1166 );
1167 if (root === undefined || root.version === undefined || !isId(root.id))
1168 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
1169 if (input.resolved === (root.resolvedAt !== null)) return;
1170 const path = yield* pullPath("setThreadResolution", input);
1171 yield* read(
1172 "setThreadResolution",
1173 input,
1175 method: "POST",
1176 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
1177 body: { expectedVersion: root.version },
1178 },
1179 Written,
1180 );
1181 },
1182 ),
1183 };
1184 return provider;
1185});