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