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

GitCafePullRequestProvider.ts

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