@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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