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

pullRequests.ts

525 lines21.4 KB

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