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

GitCafePullRequestProvider.ts

867 lines33.3 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
5import {
6 NonNegativeInt,
7 TrimmedNonEmptyString,
8 type PullRequestCapabilities,
9 type PullRequestStackHead,
10} from "@t3tools/contracts";
11import {
12 PullRequestProviderError,
13 type ProviderRepositoryRef,
14 type PullRequestProviderApi,
15} from "@t3tools/source-control-core/server/PullRequestProvider";
16​
17import * as GitCafeApi from "./GitCafeApi.ts";
18import * as GitCafeHosts from "./gitCafeHosts.ts";
19import * as Json from "./gitCafePullRequestJson.ts";
20​
21const CAPABILITIES: PullRequestCapabilities = {
22 diff: true,
23 comment: true,
24 actions: ["ready", "draft", "close", "reopen", "merge", "update-branch"],
25 mergeMethods: ["merge", "squash", "rebase"],
26 // Only through a stack: GitCafe's one branch update restacks every layer above it.
27 updateMethods: ["rebase"],
28 search: true,
29 stacks: true,
30 stackActions: true,
31 reactions: true,
32 labels: false,
33 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
34 review: {
35 inlineComment: false,
36 reply: true,
37 resolve: true,
38 verdicts: ["approve", "request-changes", "comment"],
39 },
40 reviewers: { request: false, listCandidates: false },
41 edit: { changeRequest: true, comment: true },
42};
43​
44const PAGE_SIZE = 100;
45/** Conversation pages read before the list is reported as truncated. */
46const MAX_PAGES = 10;
47/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
48const DIFF_FILES_BATCH = 64;
49/**
50 * Line totals cost one hunk read per batch, so a pull request larger than this reports none
51 * rather than reading every file.
52 */
53const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
54/** Structural `/changes` pages, 500 files each, read to count a pull request's files. */
55const MAX_CHANGE_PAGES = 20;
56​
57const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
58 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
59 items.slice(index * size, (index + 1) * size),
60 );
61​
62/** Files whose hunks GitCafe can return; binary and oversized ones are listed as they are. */
63const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
64 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
65​
66/**
67 * A strategy GitCafe lists, the viewer may use, and no blocker names. A blocker without
68 * strategies (changes requested, a lock) still leaves Merge offered, so pressing it shows
69 * GitCafe's own reason.
70 */
71const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
72 status.merge.permitted !== false &&
73 status.merge.strategies.includes(strategy) &&
74 !(status.merge.blockers ?? []).some((blocker) =>
75 (blocker.blockedStrategies ?? []).includes(strategy),
76 );
77​
78const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
79const isId = Schema.is(Id);
80const Principal = Schema.Struct({ handle: TrimmedNonEmptyString });
81const Written = Schema.Struct({ id: Id });
82const Versioned = Schema.Struct({ version: NonNegativeInt });
83const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
84const Status = Schema.Struct({
85 merge: Schema.Struct({
86 conflicts: Schema.Literals(["unknown", "conflicting"]),
87 fastForward: Schema.NullOr(Schema.Boolean),
88 strategies: Schema.Array(Schema.String),
89 permitted: Schema.optional(Schema.Boolean),
90 blockers: Schema.optional(
91 Schema.Array(
92 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
93 ),
94 ),
95 }),
96 checks: Schema.Struct({
97 pending: NonNegativeInt,
98 failing: NonNegativeInt,
99 total: NonNegativeInt,
100 }),
101});
102const FilterOptions = Schema.Struct({
103 actors: Schema.Array(
104 Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString }),
105 ),
106});
107const encodeActorIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
108const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
109const Snapshot = {
110 version: NonNegativeInt,
111 headOid: TrimmedNonEmptyString,
112 comparisonBaseOid: TrimmedNonEmptyString,
113};
114const Changes = Schema.Struct({
115 ...Snapshot,
116 items: Json.GitCafeDiffFiles,
117 next: Schema.NullOr(TrimmedNonEmptyString),
118});
119const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
120const DiffCursor = Schema.Struct({
121 version: NonNegativeInt,
122 headOid: TrimmedNonEmptyString,
123 baseOid: TrimmedNonEmptyString,
124 after: TrimmedNonEmptyString,
125});
126const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
127const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
128const MergeOutcome = Schema.Struct({
129 id: Schema.String,
130 state: Schema.Literals(["accepted", "completed", "failed"]),
131 reason: Schema.optional(Schema.String),
132});
133const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
134/** Where a stack operation stopped short; anything else is underway or done. */
135const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
136​
137type PullRef = ProviderRepositoryRef & { readonly number: number };
138type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
139​
140/** The heads a reader saw are still every unmerged layer the action moves. */
141function stackHeadsCurrent(
142 stack: Json.GitCafeStack,
143 input: { readonly number: number; readonly merge: boolean },
144 expected: ReadonlyArray<PullRequestStackHead>,
145): boolean {
146 const members = stack.members.toSorted((a, b) => a.position - b.position);
147 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
148 if (index === -1) return false;
149 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
150 (member) => member.state !== "merged",
151 );
152 return (
153 moved.length === expected.length &&
154 moved.every(
155 (member) =>
156 member.headOid !== undefined &&
157 expected.some(
158 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
159 ),
160 )
161 );
163​
164/** Lays the detailed files over the structural page, keeping its order and anything omitted. */
165const withDetails = (
166 files: ReadonlyArray<Json.GitCafeDiffFile>,
167 details: ReadonlyArray<Json.GitCafeDiffFile>,
168) => {
169 const byPath = new Map(details.map((file) => [file.path, file]));
170 return files.map((file) => byPath.get(file.path) ?? file);
171};
172​
173/** @public Service construction is part of the canonical Effect module API. */
174export const make = Effect.gen(function* () {
175 const api = yield* GitCafeApi.GitCafeApi;
176​
177 const failure = (operation: string, detail: string, cause?: unknown) =>
178 new PullRequestProviderError({
179 provider: "gitcafe",
180 operation,
181 reason: "failed",
182 detail,
183 ...(cause === undefined ? {} : { cause }),
184 });
185​
186 /** The repository's API root, refused before anything is sent for a host GitCafe is not on. */
187 const repositoryPath = (
188 operation: string,
189 input: ProviderRepositoryRef,
190 ): Effect.Effect<string, PullRequestProviderError> =>
191 GitCafeHosts.isGitCafeHost(input.host) &&
192 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
193 ? Effect.succeed(`/repos/${input.repository}`)
194 : Effect.fail(
195 failure(
196 operation,
197 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
198 ),
199 );
200​
201 const send = (
202 operation: string,
203 input: Pick<ProviderRepositoryRef, "host">,
204 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
205 ) =>
206 api.request({ ...request, host: input.host, operation }).pipe(
207 Effect.mapError(
208 (error) =>
209 new PullRequestProviderError({
210 provider: "gitcafe",
211 operation,
212 reason: error.reason,
213 detail: error.detail,
214 cause: error,
215 }),
216 ),
217 );
218​
219 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
220 operation: string,
221 input: Pick<ProviderRepositoryRef, "host">,
222 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
223 schema: S,
224 ) =>
225 send(operation, input, request).pipe(
226 Effect.flatMap((raw) =>
227 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
228 Effect.mapError((cause) =>
229 failure(operation, "GitCafe returned an unreadable response.", cause),
230 ),
231 ),
232 ),
233 );
234​
235 const pullPath = (operation: string, input: PullRef) =>
236 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
237​
238 const readPull = (operation: string, input: PullRef) =>
239 pullPath(operation, input).pipe(
240 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
241 );
242​
243 /** Every page of a cursor list, up to `MAX_PAGES`; `next` stays set when more remained. */
244 const readPages = <S extends Schema.Codec<Paged<unknown>, unknown, never, never>>(
245 operation: string,
246 input: Pick<ProviderRepositoryRef, "host">,
247 path: string,
248 schema: S,
249 ) =>
250 Effect.gen(function* () {
251 const items: Array<S["Type"]["items"][number]> = [];
252 let next: string | null = null;
253 for (let page = 0; page < MAX_PAGES; page++) {
254 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
255 if (next !== null) query.set("after", next);
256 const batch: S["Type"] = yield* read(
257 operation,
258 input,
259 { path: `${path}?${query}` },
260 schema,
261 );
262 items.push(...batch.items);
263 const previous: string | null = next;
264 next = batch.next;
265 if (next === null || next === previous || batch.items.length === 0) break;
266 }
267 return { items, next };
268 });
269​
270 const readComments = (operation: string, input: PullRef) =>
271 pullPath(operation, input).pipe(
272 Effect.flatMap((path) =>
273 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
274 ),
275 );
276​
277 /**
278 * The stack a pull request belongs to, with each unmerged layer's head. GitCafe's stack lists no
279 * heads, and they are what a land or restack is fenced on, so each open layer's pull is read.
280 */
281 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
282 operation: string,
283 input: PullRef,
284 ) {
285 const path = yield* pullPath(operation, input);
286 const { stack } = yield* read(
287 operation,
288 input,
289 { path: `${path}/stack` },
290 Json.GitCafeStackEnvelope,
291 );
292 if (stack === null) return null;
293 const members = yield* Effect.forEach(
294 stack.members,
295 (member) =>
296 member.state === "merged"
297 ? Effect.succeed(member)
298 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
299 Effect.map((pull) =>
300 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
301 ),
302 ),
303 { concurrency: 4 },
304 );
305 return { ...stack, members };
306 });
307​
308 /** One `/diff-files` read, refused if GitCafe answers from another revision than the page. */
309 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
310 input: PullRef,
311 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
312 paths: ReadonlyArray<string>,
313 ) {
314 if (paths.length === 0) return [];
315 const path = yield* pullPath("getDiff", input);
316 const files = yield* read(
317 "getDiff",
318 input,
319 {
320 method: "POST",
321 path: `${path}/diff-files`,
322 body: { paths, expectedVersion: revision.version },
323 },
324 DiffFiles,
325 );
326 if (
327 files.version !== revision.version ||
328 files.headOid !== revision.headOid ||
329 files.comparisonBaseOid !== revision.baseOid
330 )
331 return yield* failure(
332 "getDiff",
333 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
334 );
335 return files.items;
336 });
337​
338 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
339 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
340 ) {
341 const land = input.action === "merge";
342 const operation = land ? "landStackThrough" : "restackStack";
343 if (!land && input.action !== "update-branch")
344 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
345 const stack = yield* readStack(operation, input);
346 if (
347 stack === null ||
348 stack.number !== input.stackNumber ||
349 input.expectedStackHeads === undefined ||
350 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
351 )
352 return yield* failure(
353 operation,
354 "The stack changed since it was read. Refresh it and try again.",
355 );
356 const base = yield* repositoryPath(operation, input);
357 const outcome = yield* read(
358 operation,
359 input,
360 {
361 method: "POST",
362 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
363 body: land
364 ? {
365 expectedRevision: stack.revision,
366 requestId: yield* randomUuidV4,
367 throughPullRequestNumber: input.number,
368 strategy: input.mergeMethod ?? "merge",
369 }
370 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
371 },
372 StackOutcome,
373 );
374 if (FAILED_STACK_STATES.has(outcome.state))
375 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
376 });
377​
378 /**
379 * Added and deleted line totals and the file count. `/changes` lists files without counting
380 * lines, so the counts come from batched hunk reads, and a pull request past the cap reports
381 * none rather than paying for every file.
382 */
383 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
384 input: PullRef,
385 version: number,
386 ) {
387 const path = yield* pullPath("getChangeRequest", input);
388 const files: Array<Json.GitCafeDiffFile> = [];
389 let revision: { version: number; headOid: string; baseOid: string } | undefined;
390 let after: string | null = null;
391 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
392 const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
393 if (after !== null) query.set("after", after);
394 const batch: typeof Changes.Type = yield* read(
395 "getChangeRequest",
396 input,
397 { path: `${path}/changes?${query}` },
398 Changes,
399 );
400 revision ??= {
401 version: batch.version,
402 headOid: batch.headOid,
403 baseOid: batch.comparisonBaseOid,
404 };
405 files.push(...batch.items);
406 const previous: string | null = after;
407 after = batch.next;
408 if (after === null || after === previous || batch.items.length === 0) break;
409 }
410 // A hunk read that loses a race with a push leaves the counts at zero rather than dropping
411 // the file count with them.
412 const counted =
413 files.some((file) => file.additions !== undefined) ||
414 files.length > LINE_STATS_MAX_FILES ||
415 revision === undefined
416 ? files
417 : (yield* Effect.forEach(
418 chunk(detailablePaths(files), DIFF_FILES_BATCH),
419 (paths) => readDiffFiles(input, revision, paths),
420 { concurrency: 4 },
421 ).pipe(Effect.orElseSucceed(() => [[]]))).flat();
422 return {
423 changedFiles: files.length,
424 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
425 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
426 };
427 });
428​
429 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
430 input: Parameters<PullRequestProviderApi["runAction"]>[0],
431 ) {
432 const pull = yield* readPull("merge", input);
433 if (pull.state === "merged") return;
434 if (pull.mergeRoute === "unsupported")
435 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
436 const base = yield* repositoryPath("merge", input);
437 // GitCafe observes the base only for merges it routes to the provider; a native merge is
438 // fenced on the target branch's current commit.
439 const baseOid =
440 pull.mergeRoute === "provider"
441 ? pull.observedBaseOid
442 : (yield* read(
443 "merge",
444 input,
445 {
446 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
447 },
448 BranchCommit,
449 )).oid;
450 if (pull.headOid === null || baseOid == null)
451 return yield* failure(
452 "merge",
453 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
454 );
455 const path = yield* pullPath("merge", input);
456 const outcome = yield* read(
457 "merge",
458 input,
459 {
460 method: "POST",
461 path: `${path}/merge`,
462 body: {
463 requestId: yield* randomUuidV4,
464 expectedVersion: pull.version,
465 headOid: pull.headOid,
466 baseOid,
467 strategy: input.mergeMethod ?? "merge",
468 },
469 },
470 MergeOutcome,
471 );
472 // An accepted merge is GitCafe's to finish; the pull request's state reports when it has.
473 if (outcome.state === "failed")
474 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
475 });
476​
477 const provider: PullRequestProviderApi = {
478 kind: "gitcafe",
479 capabilities: CAPABILITIES,
480 getViewer: (input) =>
481 read(
482 "getViewer",
483 { host: input.host ?? "git.cafe" },
484 { path: "/auth/principal" },
485 Principal,
486 ).pipe(Effect.map((principal) => principal.handle)),
487 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
488 function* (input) {
489 const base = yield* repositoryPath("listChangeRequests", input);
490 const involved = input.involvement === "authored" || input.involvement === "reviewing";
491 let actorId: string | undefined;
492 if (involved) {
493 // A host narrows as far as it can: when the actor list can't be read, the listing comes
494 // back unnarrowed and the page's own involvement filter does the rest. A refused token
495 // or a rate limit still fails, since the service acts on those for the whole host.
496 const options = yield* read(
497 "listChangeRequests",
498 input,
499 { path: `${base}/filter-options` },
500 FilterOptions,
501 ).pipe(
502 Effect.map(Option.some),
503 Effect.catchTags({
504 PullRequestProviderError: (error) =>
505 error.reason === "unauthenticated" || error.reason === "rate-limited"
506 ? Effect.fail(error)
507 : Effect.succeed(Option.none()),
508 }),
509 );
510 if (Option.isSome(options)) {
511 actorId = options.value.actors.find(
512 (actor) => actor.handle.toLowerCase() === input.viewer.toLowerCase(),
513 )?.actorId;
514 // A viewer GitCafe knows no actor for has authored and been asked to review nothing.
515 if (actorId === undefined) return { items: [], truncated: false, continues: false };
516 }
517 }
518 const limit = Math.max(1, input.limit);
519 const items: Array<Json.GitCafePull> = [];
520 let next: string | null = null;
521 do {
522 const query = new URLSearchParams({
523 limit: String(Math.min(PAGE_SIZE, limit - items.length)),
524 sort: "newest",
525 });
526 if (input.state !== "all") query.set("state", input.state);
527 if (input.query?.trim()) query.set("q", input.query.trim());
528 if (actorId !== undefined)
529 query.set(
530 input.involvement === "reviewing" ? "reviewers" : "authors",
531 encodeActorIds([actorId]),
532 );
533 if (next !== null) query.set("after", next);
534 const page: typeof Json.GitCafePulls.Type = yield* read(
535 "listChangeRequests",
536 input,
537 { path: `${base}/pulls?${query}` },
538 Json.GitCafePulls,
539 );
540 items.push(...page.items);
541 next = page.items.length === 0 ? null : page.next;
542 } while (next !== null && items.length < limit);
543 return {
544 items: items.slice(0, limit).map((pull) => {
545 const item = Json.toChangeRequest(pull, input);
546 // GitCafe filtered by reviewer, so the viewer is one even where the pull omits it. An
547 // unnarrowed listing (no actor to filter by) says nothing about who was asked.
548 return input.involvement === "reviewing" && actorId !== undefined
549 ? {
550 ...item,
551 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
552 }
553 : item;
554 }),
555 truncated: next !== null,
556 continues: false,
557 };
558 },
559 ),
560 getChangeRequestSummary: (input) =>
561 readPull("getChangeRequestSummary", input).pipe(
562 Effect.map((pull) => ({
563 ...Json.toChangeRequest(pull, input),
564 closedAt: pull.closedAt,
565 mergedAt: pull.mergedAt,
566 })),
567 ),
568 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
569 const pull = yield* readPull("getChangeRequest", input);
570 const path = yield* pullPath("getChangeRequest", input);
571 const base = yield* repositoryPath("getChangeRequest", input);
572 const [status, checks, changes] = yield* Effect.all(
573 [
574 read("getChangeRequest", input, { path: `${path}/status` }, Status),
575 pull.headOid === null
576 ? Effect.succeed(null)
577 : readPages(
578 "getChangeRequest",
579 input,
580 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
581 Json.GitCafeChecks,
582 ),
583 pull.headOid === null
584 ? Effect.succeed(null)
585 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
586 ],
587 { concurrency: 3 },
588 );
589 const permissions = Json.toViewerPermissions(pull);
590 return {
591 ...Json.toChangeRequest(pull, input),
592 headSha: pull.headOid,
593 body: pull.description ?? "",
594 ...(pull.sourceRepo === null
595 ? {}
596 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
597 additions: changes?.additions ?? 0,
598 deletions: changes?.deletions ?? 0,
599 changedFiles: changes?.changedFiles ?? 0,
600 closedAt: pull.closedAt,
601 mergedAt: pull.mergedAt,
602 reviewers: Json.toReviewers(pull, input.host),
603 checks: checks === null ? [] : Json.toChecks(checks),
604 ...(status.checks.total === 0
605 ? {}
606 : {
607 checksState:
608 status.checks.failing > 0
609 ? ("failing" as const)
610 : status.checks.pending > 0
611 ? ("pending" as const)
612 : ("passing" as const),
613 }),
614 mergeability:
615 status.merge.conflicts === "conflicting"
616 ? ("conflicting" as const)
617 : ("unknown" as const),
618 baseComparison:
619 status.merge.fastForward === null
620 ? ("unknown" as const)
621 : status.merge.fastForward
622 ? ("up-to-date" as const)
623 : ("behind" as const),
624 mergeCapabilities: {
625 merge: mergeStrategyOpen(status, "merge"),
626 squash: mergeStrategyOpen(status, "squash"),
627 rebase: mergeStrategyOpen(status, "rebase"),
628 },
629 viewerPermissions:
630 status.merge.permitted === false
631 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
632 : permissions,
633 };
634 }),
635 getChangeRequestStack: (input) =>
636 readStack("getChangeRequestStack", input).pipe(
637 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
638 ),
639 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
640 function* (input) {
641 const pull = yield* readPull("getChangeRequestActivity", input);
642 const path = yield* pullPath("getChangeRequestActivity", input);
643 const operation = "getChangeRequestActivity";
644 const [comments, reviews, commits, reactions] = yield* Effect.all(
645 [
646 readComments(operation, input),
647 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
648 pull.headOid === null
649 ? Effect.succeed({ items: [], next: null })
650 : readPages(operation, input, `${path}/commits`, Json.GitCafeCommits),
651 // Reactions decorate the conversation; a failed read leaves them out, not it.
652 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
653 Effect.orElseSucceed(() => undefined),
654 ),
655 ],
656 { concurrency: 4 },
657 );
658 return Json.toActivity({
659 comments,
660 reviews,
661 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
662 host: input.host,
663 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
664 ...(reactions === undefined ? {} : { reactions }),
665 });
666 },
667 ),
668 getViewerPermissions: (input) =>
669 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
670 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
671 if (input.commit !== undefined)
672 return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
673 const cursor =
674 input.cursor === undefined
675 ? null
676 : yield* decodeDiffCursor(input.cursor).pipe(
677 Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
678 );
679 const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
680 const path = yield* pullPath("getDiff", input);
681 const query = new URLSearchParams({
682 expectedVersion: String(version),
683 limit: String(DIFF_FILES_BATCH),
684 });
685 if (cursor !== null) query.set("after", cursor.after);
686 const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
687 if (
688 page.version !== version ||
689 (cursor !== null &&
690 (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
691 )
692 return yield* failure(
693 "getDiff",
694 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
695 );
696 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
697 const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
698 return {
699 ...Json.toDiff({ items: withDetails(page.items, details) }),
700 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
701 };
702 }),
703 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
704 if (input.stackNumber !== undefined)
705 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
706 switch (input.action) {
707 case "merge":
708 return yield* merge(input);
709 case "ready":
710 case "draft":
711 case "close":
712 case "reopen": {
713 const pull = yield* readPull(input.action, input);
714 const path = yield* pullPath(input.action, input);
715 yield* send(input.action, input, {
716 method: "POST",
717 path: `${path}/${input.action}`,
718 body: { expectedVersion: pull.version },
719 });
720 return;
721 }
722 default:
723 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
724 }
725 }),
726 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
727 function* (input) {
728 const pull = yield* readPull("updateChangeRequest", input);
729 const path = yield* pullPath("updateChangeRequest", input);
730 yield* read(
731 "updateChangeRequest",
732 input,
733 {
734 method: "PATCH",
735 path,
736 body: {
737 expectedVersion: pull.version,
738 ...(input.title === undefined ? {} : { title: input.title }),
739 ...(input.body === undefined ? {} : { description: input.body }),
740 },
741 },
742 Versioned,
743 );
744 },
745 ),
746 comment: (input) =>
747 pullPath("comment", input).pipe(
748 Effect.flatMap((path) =>
749 read(
750 "comment",
751 input,
752 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
753 Written,
754 ),
755 ),
756 Effect.asVoid,
757 ),
758 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
759 if (!isId(input.commentId))
760 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
761 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
762 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
763 yield* read(
764 "updateComment",
765 input,
766 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
767 Written,
768 );
769 }),
770 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
771 if (input.comments.length > 0)
772 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
773 const pull = yield* readPull("submitReview", input);
774 if (pull.headOid === null)
775 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
776 const path = yield* pullPath("submitReview", input);
777 yield* read(
778 "submitReview",
779 input,
780 {
781 method: "POST",
782 path: `${path}/reviews`,
783 body: {
784 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
785 ...(input.body.length === 0 ? {} : { body: input.body }),
786 commitOid: pull.headOid,
787 expectedVersion: pull.version,
788 requestId: yield* randomUuidV4,
789 },
790 },
791 Written,
792 );
793 }),
794 listReviewerCandidates: () =>
795 Effect.fail(
796 failure("listReviewerCandidates", "GitCafe reviewer requests are not supported."),
797 ),
798 setReviewerRequest: () =>
799 Effect.fail(failure("setReviewerRequest", "GitCafe reviewer requests are not supported.")),
800 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
801 if (!isId(input.threadId))
802 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
803 const path = yield* pullPath("replyToThread", input);
804 yield* read(
805 "replyToThread",
806 input,
807 {
808 method: "POST",
809 path: `${path}/comments/${input.threadId}/replies`,
810 body: { body: input.body },
811 },
812 Written,
813 );
814 }),
815 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
816 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
817 const subject =
818 input.subjectId === undefined
819 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
820 : { kind: "pull_request_comment" as const, id: input.subjectId };
821 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
822 const mine = reactions.items.find(
823 (item) =>
824 item.subject.kind === subject.kind &&
825 item.subject.id === subject.id &&
826 item.emoji.kind === "unicode" &&
827 Json.reactionContent(item.emoji.value) === input.content,
828 )?.viewerReactionId;
829 if (input.reacted === (mine != null)) return;
830 if (input.reacted) {
831 yield* send("setReaction", input, {
832 method: "POST",
833 path,
834 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
835 });
836 return;
837 }
838 if (mine == null) return;
839 if (!isId(mine))
840 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
841 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
842 }),
843 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
844 function* (input) {
845 const comments = yield* readComments("setThreadResolution", input);
846 const root = comments.items.find(
847 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
848 );
849 if (root === undefined || root.version === undefined || !isId(root.id))
850 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
851 if (input.resolved === (root.resolvedAt !== null)) return;
852 const path = yield* pullPath("setThreadResolution", input);
853 yield* read(
854 "setThreadResolution",
855 input,
856 {
857 method: "POST",
858 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
859 body: { expectedVersion: root.version },
860 },
861 Written,
862 );
863 },
864 ),
865 };
866 return provider;
867});