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

GitCafePullRequestProvider.ts

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