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