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

pullRequests.ts

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