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

pullRequests.ts

576 lines23.5 KB

1import {
2 WS_METHODS,
3 type EnvironmentId,
4 type PullRequestActor,
5 type PullRequestActionInput,
6 type PullRequestDetail,
7 type PullRequestDiffInput,
8 type PullRequestRef,
9 type PullRequestMergeMethod,
10 PullRequestOperationError,
11 type PullRequestSummary,
12 type VcsStatusResult,
13} from "@t3tools/contracts";
14import * as Data from "effect/Data";
15import * as Effect from "effect/Effect";
16import * as Option from "effect/Option";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
19​
20import {
21 createAtomCommandScheduler,
22 createEnvironmentCommand,
23 createEnvironmentRpcCommand,
24 createEnvironmentRpcQueryAtomFamily,
25 createEnvironmentRpcSubscriptionAtomFamily,
26 createEnvironmentQueryAtomFamily,
27} from "./runtime.ts";
28import { createPullRequestRouter } from "./pullRequestRouting.ts";
29import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
30import type { EnvironmentRegistry } from "../connection/registry.ts";
31import * as EnvironmentSupervisor from "../connection/supervisor.ts";
32​
33export {
34 type PullRequestDiffLoadError,
35 PullRequestDiffCredentialRejectedError,
36} from "./pullRequestDiffHttp.ts";
37export * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
38​
39/** @public Required to name the error in consumers' inferred pull request results. */
40export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(
41 "EnvironmentHttpConnectionNotReadyError",
42)<{ readonly message: string }> {}
43​
44const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000;
45​
46/** Keep confirmed edits on the same cached reference regardless of input property order. */
47function writableQueryFamily<A, E>(
48 family: (target: {
49 readonly environmentId: EnvironmentId;
50 readonly input: PullRequestRef;
51 }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
52) {
53 const writable = Atom.family((source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
54 Atom.writable(
55 (get) => {
56 const result = get(source);
57 if (result._tag === "Success" && !result.waiting) return result;
58 const previous = get.self<AsyncResult.AsyncResult<A, E>>();
59 const value = Option.flatMap(previous, AsyncResult.value);
60 if (Option.isNone(value)) return result;
61 return result._tag === "Failure"
62 ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
63 : AsyncResult.success<A, E>(value.value, result);
64 },
65 (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
66 (refresh) => refresh(source),
67 ).pipe(Atom.setIdleTTL(5 * 60_000)),
68 );
69 return ({
70 environmentId,
71 input: { projectId, host, repository, number, allowStale },
72 }: Parameters<typeof family>[0]) =>
73 writable(
74 family({
75 environmentId,
76 input: {
77 projectId,
78 ...(host === undefined ? {} : { host }),
79 repository,
80 number,
81 ...(allowStale === undefined ? {} : { allowStale }),
82 },
83 }),
84 );
86​
87/** Restart pre-mutation reads before patching so they cannot restore stale values. */
88function updateCached<A, E>(
89 registry: AtomRegistry.AtomRegistry,
90 atom: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
91 update: (value: A) => A,
92 refresh = false,
93) {
94 if (refresh || registry.get(atom).waiting) registry.refresh(atom);
95 registry.update(atom, AsyncResult.map(update));
97​
98function createPullRequestRefreshAtomFamily<R, E>(
99 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
100) {
101 return createEnvironmentRpcSubscriptionAtomFamily(runtime, {
102 label: "environment-data:pull-requests:turn-refreshes",
103 tag: WS_METHODS.pullRequestsSubscribeRefreshes,
104 });
106​
107/** Refresh only the live fields a linked thread renders. */
108export function createLinkedPullRequestSummaryAtomFamily<R, E>(
109 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
110 refreshes = createPullRequestRefreshAtomFamily(runtime),
111) {
112 const routedRequest = createPullRequestRouter();
113 return createEnvironmentRpcQueryAtomFamily(runtime, {
114 label: "environment-data:pull-requests:linked-summary",
115 tag: WS_METHODS.pullRequestsSummary,
116 execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
117 staleTimeMs: 60_000,
118 refreshIntervalMs: 60_000,
119 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
120 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
121 });
123​
124/** The host-native stack a pull request belongs to; null where it is not stacked. */
125export function createPullRequestStackAtomFamily<R, E>(
126 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
127 refreshes = createPullRequestRefreshAtomFamily(runtime),
128) {
129 const routedRequest = createPullRequestRouter();
130 return createEnvironmentRpcQueryAtomFamily(runtime, {
131 label: "environment-data:pull-requests:stack",
132 tag: WS_METHODS.pullRequestsStack,
133 execute: (input) => routedRequest(WS_METHODS.pullRequestsStack, input),
134 staleTimeMs: 60_000,
135 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
136 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
137 });
139​
140export function pullRequestDetailToVcsStatus(
141 detail: PullRequestDetail | PullRequestSummary,
142): NonNullable<VcsStatusResult["pr"]> {
143 return {
144 number: detail.number,
145 title: detail.title,
146 url: detail.url,
147 baseRef: detail.baseBranch,
148 headRef: detail.headBranch,
149 state: detail.state,
150 ...(detail.isDraft === true ? { isDraft: true } : {}),
151 updatedAt: detail.updatedAt,
152 };
154​
155/**
156 * Reopening a PR within a minute reuses detail and activity. Explicit refreshes and
157 * turn notifications still revalidate. Mutations run serially per environment: actions on the same
158 * pull request are order-sensitive. Confirmed label and reviewer edits update cached state.
159 */
160export function createPullRequestEnvironmentAtoms<R, E>(
161 runtime: Atom.AtomRuntime<
162 EnvironmentRegistry | PullRequestDiffLoader.PullRequestDiffLoader | R,
163 E
164 >,
165) {
166 const refreshes = createPullRequestRefreshAtomFamily(runtime);
167 const commandScheduler = createAtomCommandScheduler();
168 const routedRequest = createPullRequestRouter();
169 const serialPerEnvironment = {
170 mode: "serial",
171 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
172 } as const;
173 const activity = writableQueryFamily(
174 createEnvironmentRpcQueryAtomFamily(runtime, {
175 label: "environment-data:pull-requests:activity",
176 tag: WS_METHODS.pullRequestsActivity,
177 execute: (input) => routedRequest(WS_METHODS.pullRequestsActivity, input),
178 staleTimeMs: 60_000,
179 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
180 }),
181 );
182 const detail = writableQueryFamily(
183 createEnvironmentRpcQueryAtomFamily(runtime, {
184 label: "environment-data:pull-requests:detail",
185 tag: WS_METHODS.pullRequestsDetail,
186 execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
187 staleTimeMs: 60_000,
188 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
189 }),
190 );
191 const preview = writableQueryFamily(
192 createEnvironmentRpcQueryAtomFamily(runtime, {
193 label: "environment-data:pull-requests:preview",
194 tag: WS_METHODS.pullRequestsPreview,
195 execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
196 staleTimeMs: 60_000,
197 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
198 }),
199 );
200 const labelCandidates = writableQueryFamily(
201 createEnvironmentRpcQueryAtomFamily(runtime, {
202 label: "environment-data:pull-requests:label-candidates",
203 tag: WS_METHODS.pullRequestsLabelCandidates,
204 execute: (input) => routedRequest(WS_METHODS.pullRequestsLabelCandidates, input),
205 staleTimeMs: 60_000,
206 }),
207 );
208 const reviewerCandidates = writableQueryFamily(
209 createEnvironmentRpcQueryAtomFamily(runtime, {
210 label: "environment-data:pull-requests:reviewer-candidates",
211 tag: WS_METHODS.pullRequestsReviewerCandidates,
212 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewerCandidates, input),
213 staleTimeMs: 60_000,
214 }),
215 );
216 return {
217 refreshes,
218 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
219 label: "environment-data:pull-requests:linked-threads",
220 tag: WS_METHODS.pullRequestsLinkedThreads,
221 staleTimeMs: 0,
222 refreshIntervalMs: 10_000,
223 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
224 }),
225 list: createEnvironmentRpcQueryAtomFamily(runtime, {
226 label: "environment-data:pull-requests:list",
227 tag: WS_METHODS.pullRequestsList,
228 staleTimeMs: 30_000,
229 refreshTrigger: ({ environmentId, input }) =>
230 input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
231 }),
232 /**
233 * The line counts for rows the listing has already handed over. Its own query because the
234 * listing is quicker without them — measured over twelve repositories, ~4.0s against ~7.1s —
235 * so the rows arrive first and their stats a moment later. Kept longer than the listing:
236 * a change request's size only moves when somebody pushes to it.
237 */
238 listStats: createEnvironmentRpcQueryAtomFamily(runtime, {
239 label: "environment-data:pull-requests:list-stats",
240 tag: WS_METHODS.pullRequestsListStats,
241 staleTimeMs: 60_000,
242 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
243 }),
244 detail,
245 preview,
246 checks: createEnvironmentRpcQueryAtomFamily(runtime, {
247 label: "environment-data:pull-requests:checks",
248 tag: WS_METHODS.pullRequestsChecks,
249 execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),
250 staleTimeMs: 45_000,
251 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
252 }),
253 activity,
254 threadComments: createEnvironmentRpcCommand(runtime, {
255 label: "environment-data:pull-requests:thread-comments",
256 tag: WS_METHODS.pullRequestsThreadComments,
257 execute: (input) => routedRequest(WS_METHODS.pullRequestsThreadComments, input),
258 scheduler: commandScheduler,
259 concurrency: {
260 mode: "singleFlight",
261 key: ({ environmentId, input }) =>
262 JSON.stringify([environmentId, input.threadId, input.cursor]),
263 },
264 }),
265 diff: createEnvironmentQueryAtomFamily(runtime, {
266 label: "environment-data:pull-requests:diff",
267 staleTimeMs: 60_000,
268 execute: (input: PullRequestDiffInput) =>
269 Effect.gen(function* () {
270 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
271 const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;
272 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
273 if (Option.isNone(prepared)) {
274 return yield* new EnvironmentHttpConnectionNotReadyError({
275 message: "The environment HTTP connection is not ready.",
276 });
277 }
278 return yield* loader.load(prepared.value, input);
279 }),
280 }),
281 diffFileContents: createEnvironmentRpcCommand(runtime, {
282 label: "environment-data:pull-requests:diff-file-contents",
283 tag: WS_METHODS.pullRequestsDiffFileContents,
284 execute: (input) => routedRequest(WS_METHODS.pullRequestsDiffFileContents, input),
285 scheduler: commandScheduler,
286 concurrency: {
287 mode: "singleFlight",
288 key: ({ environmentId, input }) =>
289 JSON.stringify([
290 environmentId,
291 input.projectId,
292 input.host?.toLowerCase() ?? null,
293 input.repository,
294 input.number,
295 input.commit ?? null,
296 input.changeType,
297 input.oldPath,
298 input.newPath,
299 ]),
300 },
301 }),
302 filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, {
303 label: "environment-data:pull-requests:files-viewed",
304 tag: WS_METHODS.pullRequestsFilesViewed,
305 execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),
306 staleTimeMs: 15_000,
307 }),
308 /**
309 * One write in flight per change request: the host applies these in order, and a reader
310 * ticking down a file list faster than the round trip would otherwise race their own presses.
311 */
312 setFilesViewed: createEnvironmentRpcCommand(runtime, {
313 label: "environment-data:pull-requests:set-files-viewed",
314 tag: WS_METHODS.pullRequestsSetFilesViewed,
315 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetFilesViewed, input),
316 scheduler: commandScheduler,
317 concurrency: {
318 mode: "serial",
319 key: ({ environmentId, input }) =>
320 JSON.stringify([environmentId, input.projectId, input.repository, input.number]),
321 },
322 }),
323 runAction: createEnvironmentCommand(runtime, {
324 label: "environment-data:pull-requests:run-action",
325 // Preparation belongs to the write's lane. Refreshable queries would restart it after
326 // every preceding action, and preparing outside the lane could reorder the clicks.
327 execute: (
328 input: PullRequestActionInput & {
329 readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
330 },
331 registry,
332 environmentId,
333 ) =>
334 Effect.gen(function* () {
335 const { resolveMergeMethod, ...actionInput } = input;
336 let preparedInput = actionInput;
337 if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {
338 const { projectId, host, repository, number } = actionInput;
339 const reference = { projectId, host, repository, number, allowStale: false };
340 const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);
341 if (
342 detail.state !== "open" ||
343 detail.isDraft ||
344 !detail.capabilities.actions.includes("merge") ||
345 !detail.viewerPermissions.actions.includes("merge")
346 ) {
347 return yield* new PullRequestOperationError({
348 operation: "runAction",
349 detail: "This pull request cannot be merged.",
350 });
351 }
352 if (detail.capabilities.stackActions) {
353 const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);
354 if (stack !== null) {
355 return yield* new PullRequestOperationError({
356 operation: "runAction",
357 detail: "Open this pull request to merge its stack.",
358 });
359 }
360 }
361 const mergeMethod = yield* Effect.try({
362 try: () => resolveMergeMethod(detail),
363 catch: (cause) =>
364 new PullRequestOperationError({
365 operation: "runAction",
366 detail:
367 cause instanceof Error ? cause.message : "Could not choose a merge method.",
368 }),
369 });
370 preparedInput = { ...actionInput, mergeMethod };
371 }
372 yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
373 registry.refresh(preview({ environmentId, input: actionInput }));
374 }),
375 scheduler: commandScheduler,
376 concurrency: serialPerEnvironment,
377 }),
378 update: createEnvironmentRpcCommand(runtime, {
379 label: "environment-data:pull-requests:update",
380 tag: WS_METHODS.pullRequestsUpdate,
381 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
382 onSuccess: (target, registry) => Effect.sync(() => registry.refresh(preview(target))),
383 scheduler: commandScheduler,
384 concurrency: serialPerEnvironment,
385 }),
386 comment: createEnvironmentRpcCommand(runtime, {
387 label: "environment-data:pull-requests:comment",
388 tag: WS_METHODS.pullRequestsComment,
389 execute: (input) => routedRequest(WS_METHODS.pullRequestsComment, input),
390 scheduler: commandScheduler,
391 concurrency: serialPerEnvironment,
392 }),
393 updateComment: createEnvironmentRpcCommand(runtime, {
394 label: "environment-data:pull-requests:update-comment",
395 tag: WS_METHODS.pullRequestsUpdateComment,
396 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdateComment, input),
397 scheduler: commandScheduler,
398 concurrency: serialPerEnvironment,
399 onSuccess: ({ environmentId, input: { projectId, host, repository, number } }, registry) =>
400 Effect.sync(() =>
401 registry.refresh(
402 activity({
403 environmentId,
404 input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
405 }),
406 ),
407 ),
408 }),
409 submitReview: createEnvironmentRpcCommand(runtime, {
410 label: "environment-data:pull-requests:submit-review",
411 tag: WS_METHODS.pullRequestsSubmitReview,
412 execute: (input) => routedRequest(WS_METHODS.pullRequestsSubmitReview, input),
413 scheduler: commandScheduler,
414 concurrency: serialPerEnvironment,
415 }),
416 replyToThread: createEnvironmentRpcCommand(runtime, {
417 label: "environment-data:pull-requests:reply-to-thread",
418 tag: WS_METHODS.pullRequestsReplyToThread,
419 execute: (input) => routedRequest(WS_METHODS.pullRequestsReplyToThread, input),
420 scheduler: commandScheduler,
421 concurrency: serialPerEnvironment,
422 }),
423 /**
424 * Its own query rather than part of the detail: the people who may be asked are only wanted
425 * once somebody opens the reviewer menu, so this atom is read then and not before. Kept fresh
426 * for a minute, because who has access to a repository changes far more slowly than the
427 * change request it is being read for.
428 */
429 reviewerCandidates,
430 requestReviewers: createEnvironmentRpcCommand(runtime, {
431 label: "environment-data:pull-requests:request-reviewers",
432 tag: WS_METHODS.pullRequestsRequestReviewers,
433 execute: (input) => routedRequest(WS_METHODS.pullRequestsRequestReviewers, input),
434 scheduler: commandScheduler,
435 concurrency: serialPerEnvironment,
436 onSuccess: (target, registry) =>
437 Effect.sync(() => {
438 const { reviewers, requested } = target.input;
439 const candidatesAtom = reviewerCandidates(target);
440 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
441 const selected =
442 candidates?.candidates.filter((candidate) =>
443 reviewers.some(
444 (reviewer) => reviewer.id === candidate.id && reviewer.kind === candidate.kind,
445 ),
446 ) ?? [];
447 const missingIdentities = selected.length < reviewers.length;
448 updateCached(registry, candidatesAtom, (value) => ({
449 ...value,
450 candidates: value.candidates.map((candidate) =>
451 selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,
452 ),
453 }));
454 const selectedLogins = new Set(
455 selected.map((candidate) => candidate.login.toLowerCase()),
456 );
457 const updateReviewers = (
458 actors: ReadonlyArray<PullRequestActor>,
459 keep = (_actor: PullRequestActor) => false,
460 ) =>
461 requested
462 ? [
463 ...actors,
464 ...selected
465 .filter(
466 (candidate) =>
467 !actors.some(
468 (actor) => actor.login.toLowerCase() === candidate.login.toLowerCase(),
469 ),
470 )
471 .map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
472 ]
473 : actors.filter(
474 (actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
475 );
476 updateCached(
477 registry,
478 detail(target),
479 (value) => ({
480 ...value,
481 reviewers: updateReviewers(value.reviewers),
482 }),
483 missingIdentities,
484 );
485 updateCached(
486 registry,
487 activity(target),
488 (value) => ({
489 ...value,
490 reviewers:
491 value.reviewers === undefined
492 ? undefined
493 : updateReviewers(value.reviewers, (actor) =>
494 value.comments.some(
495 (comment) =>
496 (comment.kind === "review" || comment.kind === "review-comment") &&
497 comment.author?.login.toLowerCase() === actor.login.toLowerCase(),
498 ),
499 ),
500 }),
501 missingIdentities,
502 );
503 }),
504 }),
505 /** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */
506 labelCandidates,
507 setLabels: createEnvironmentRpcCommand(runtime, {
508 label: "environment-data:pull-requests:set-labels",
509 tag: WS_METHODS.pullRequestsSetLabels,
510 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
511 scheduler: commandScheduler,
512 concurrency: serialPerEnvironment,
513 onSuccess: (target, registry) =>
514 Effect.sync(() => {
515 const { labels, applied } = target.input;
516 const candidatesAtom = labelCandidates(target);
517 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
518 const names = new Set(labels);
519 updateCached(registry, candidatesAtom, (value) => ({
520 ...value,
521 candidates: value.candidates.map((candidate) =>
522 names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
523 ),
524 }));
525 updateCached(registry, detail(target), (value) => ({
526 ...value,
527 labels: applied
528 ? [
529 ...value.labels,
530 ...labels
531 .filter((name) => !value.labels.some((label) => label.name === name))
532 .map((name) => ({
533 name,
534 color:
535 candidates?.candidates.find((candidate) => candidate.name === name)
536 ?.color ?? null,
537 })),
538 ]
539 : value.labels.filter((label) => !names.has(label.name)),
540 }));
541 }),
542 }),
543 setThreadResolution: createEnvironmentRpcCommand(runtime, {
544 label: "environment-data:pull-requests:set-thread-resolution",
545 tag: WS_METHODS.pullRequestsSetThreadResolution,
546 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetThreadResolution, input),
547 scheduler: commandScheduler,
548 concurrency: serialPerEnvironment,
549 }),
550 setReaction: createEnvironmentRpcCommand(runtime, {
551 label: "environment-data:pull-requests:set-reaction",
552 tag: WS_METHODS.pullRequestsSetReaction,
553 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetReaction, input),
554 scheduler: commandScheduler,
555 concurrency: serialPerEnvironment,
556 }),
557 /**
558 * Explicit refresh: forget the server's cached answers, then re-run the reads. A separate
559 * request rather than a flag on a read, so only a person's refresh spends host requests
560 * while every silent re-read shares the cache.
561 */
562 invalidate: createEnvironmentRpcCommand(runtime, {
563 label: "environment-data:pull-requests:invalidate",
564 tag: WS_METHODS.pullRequestsInvalidate,
565 execute: (input) => routedRequest(WS_METHODS.pullRequestsInvalidate, input),
566 onSuccess: ({ environmentId, input }, registry) =>
567 Effect.sync(() => {
568 if (input.reference !== undefined) {
569 registry.refresh(preview({ environmentId, input: input.reference }));
570 }
571 }),
572 scheduler: commandScheduler,
573 concurrency: serialPerEnvironment,
574 }),
575 };