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 },
69 }: Parameters<typeof family>[0]) =>
70 writable(
71 family({
72 environmentId,
73 input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
74 }),
75 );
76}
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));
87}
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 });
96}
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 });
113}
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 });
129}
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 };
144}
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 labelCandidates = writableQueryFamily(
180 createEnvironmentRpcQueryAtomFamily(runtime, {
181 label: "environment-data:pull-requests:label-candidates",
182 tag: WS_METHODS.pullRequestsLabelCandidates,
183 execute: (input) => routedRequest(WS_METHODS.pullRequestsLabelCandidates, input),
184 staleTimeMs: 60_000,
185 }),
186 );
187 const reviewerCandidates = writableQueryFamily(
188 createEnvironmentRpcQueryAtomFamily(runtime, {
189 label: "environment-data:pull-requests:reviewer-candidates",
190 tag: WS_METHODS.pullRequestsReviewerCandidates,
191 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewerCandidates, input),
192 staleTimeMs: 60_000,
193 }),
194 );
195 return {
196 refreshes,
197 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
198 label: "environment-data:pull-requests:linked-threads",
199 tag: WS_METHODS.pullRequestsLinkedThreads,
200 staleTimeMs: 0,
201 refreshIntervalMs: 10_000,
202 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
203 }),
204 list: createEnvironmentRpcQueryAtomFamily(runtime, {
205 label: "environment-data:pull-requests:list",
206 tag: WS_METHODS.pullRequestsList,
207 staleTimeMs: 30_000,
208 refreshTrigger: ({ environmentId, input }) =>
209 input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
210 }),
211 /**
212 * The line counts for rows the listing has already handed over. Its own query because the
213 * listing is quicker without them — measured over twelve repositories, ~4.0s against ~7.1s —
214 * so the rows arrive first and their stats a moment later. Kept longer than the listing:
215 * a change request's size only moves when somebody pushes to it.
216 */
217 listStats: createEnvironmentRpcQueryAtomFamily(runtime, {
218 label: "environment-data:pull-requests:list-stats",
219 tag: WS_METHODS.pullRequestsListStats,
220 staleTimeMs: 60_000,
221 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
222 }),
223 detail,
224 activity,
225 threadComments: createEnvironmentRpcCommand(runtime, {
226 label: "environment-data:pull-requests:thread-comments",
227 tag: WS_METHODS.pullRequestsThreadComments,
228 execute: (input) => routedRequest(WS_METHODS.pullRequestsThreadComments, input),
229 scheduler: commandScheduler,
230 concurrency: {
231 mode: "singleFlight",
232 key: ({ environmentId, input }) =>
233 JSON.stringify([environmentId, input.threadId, input.cursor]),
234 },
235 }),
236 diff: createEnvironmentQueryAtomFamily(runtime, {
237 label: "environment-data:pull-requests:diff",
238 staleTimeMs: 60_000,
239 execute: (input: PullRequestDiffInput) =>
240 Effect.gen(function* () {
241 const supervisor = yield* EnvironmentSupervisor;
242 const loader = yield* PullRequestDiffLoader;
243 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
244 if (Option.isNone(prepared)) {
245 return yield* new EnvironmentHttpConnectionNotReadyError({
246 message: "The environment HTTP connection is not ready.",
247 });
248 }
249 return yield* loader.load(prepared.value, input);
250 }),
251 }),
252 diffFileContents: createEnvironmentRpcCommand(runtime, {
253 label: "environment-data:pull-requests:diff-file-contents",
254 tag: WS_METHODS.pullRequestsDiffFileContents,
255 execute: (input) => routedRequest(WS_METHODS.pullRequestsDiffFileContents, input),
256 scheduler: commandScheduler,
257 concurrency: {
258 mode: "singleFlight",
259 key: ({ environmentId, input }) =>
260 JSON.stringify([
261 environmentId,
262 input.projectId,
263 input.host?.toLowerCase() ?? null,
264 input.repository,
265 input.number,
266 input.commit ?? null,
267 input.changeType,
268 input.oldPath,
269 input.newPath,
270 ]),
271 },
272 }),
273 filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, {
274 label: "environment-data:pull-requests:files-viewed",
275 tag: WS_METHODS.pullRequestsFilesViewed,
276 execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),
277 staleTimeMs: 15_000,
278 }),
279 /**
280 * One write in flight per change request: the host applies these in order, and a reader
281 * ticking down a file list faster than the round trip would otherwise race their own presses.
282 */
283 setFilesViewed: createEnvironmentRpcCommand(runtime, {
284 label: "environment-data:pull-requests:set-files-viewed",
285 tag: WS_METHODS.pullRequestsSetFilesViewed,
286 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetFilesViewed, input),
287 scheduler: commandScheduler,
288 concurrency: {
289 mode: "serial",
290 key: ({ environmentId, input }) =>
291 JSON.stringify([environmentId, input.projectId, input.repository, input.number]),
292 },
293 }),
294 runAction: createEnvironmentRpcCommand(runtime, {
295 label: "environment-data:pull-requests:run-action",
296 tag: WS_METHODS.pullRequestsRunAction,
297 execute: (input) => routedRequest(WS_METHODS.pullRequestsRunAction, input),
298 scheduler: commandScheduler,
299 concurrency: serialPerEnvironment,
300 }),
301 update: createEnvironmentRpcCommand(runtime, {
302 label: "environment-data:pull-requests:update",
303 tag: WS_METHODS.pullRequestsUpdate,
304 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
305 scheduler: commandScheduler,
306 concurrency: serialPerEnvironment,
307 }),
308 comment: createEnvironmentRpcCommand(runtime, {
309 label: "environment-data:pull-requests:comment",
310 tag: WS_METHODS.pullRequestsComment,
311 execute: (input) => routedRequest(WS_METHODS.pullRequestsComment, input),
312 scheduler: commandScheduler,
313 concurrency: serialPerEnvironment,
314 }),
315 updateComment: createEnvironmentRpcCommand(runtime, {
316 label: "environment-data:pull-requests:update-comment",
317 tag: WS_METHODS.pullRequestsUpdateComment,
318 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdateComment, input),
319 scheduler: commandScheduler,
320 concurrency: serialPerEnvironment,
321 onSuccess: ({ environmentId, input: { projectId, host, repository, number } }, registry) =>
322 Effect.sync(() =>
323 registry.refresh(
324 activity({
325 environmentId,
326 input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
327 }),
328 ),
329 ),
330 }),
331 submitReview: createEnvironmentRpcCommand(runtime, {
332 label: "environment-data:pull-requests:submit-review",
333 tag: WS_METHODS.pullRequestsSubmitReview,
334 execute: (input) => routedRequest(WS_METHODS.pullRequestsSubmitReview, input),
335 scheduler: commandScheduler,
336 concurrency: serialPerEnvironment,
337 }),
338 replyToThread: createEnvironmentRpcCommand(runtime, {
339 label: "environment-data:pull-requests:reply-to-thread",
340 tag: WS_METHODS.pullRequestsReplyToThread,
341 execute: (input) => routedRequest(WS_METHODS.pullRequestsReplyToThread, input),
342 scheduler: commandScheduler,
343 concurrency: serialPerEnvironment,
344 }),
345 /**
346 * Its own query rather than part of the detail: the people who may be asked are only wanted
347 * once somebody opens the reviewer menu, so this atom is read then and not before. Kept fresh
348 * for a minute, because who has access to a repository changes far more slowly than the
349 * change request it is being read for.
350 */
351 reviewerCandidates,
352 requestReviewers: createEnvironmentRpcCommand(runtime, {
353 label: "environment-data:pull-requests:request-reviewers",
354 tag: WS_METHODS.pullRequestsRequestReviewers,
355 execute: (input) => routedRequest(WS_METHODS.pullRequestsRequestReviewers, input),
356 scheduler: commandScheduler,
357 concurrency: serialPerEnvironment,
358 onSuccess: (target, registry) =>
359 Effect.sync(() => {
360 const { reviewers, requested } = target.input;
361 const candidatesAtom = reviewerCandidates(target);
362 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
363 const selected =
364 candidates?.candidates.filter((candidate) =>
365 reviewers.some(
366 (reviewer) => reviewer.id === candidate.id && reviewer.kind === candidate.kind,
367 ),
368 ) ?? [];
369 const missingIdentities = selected.length < reviewers.length;
370 updateCached(registry, candidatesAtom, (value) => ({
371 ...value,
372 candidates: value.candidates.map((candidate) =>
373 selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,
374 ),
375 }));
376 const selectedLogins = new Set(
377 selected.map((candidate) => candidate.login.toLowerCase()),
378 );
379 const updateReviewers = (
380 actors: ReadonlyArray<PullRequestActor>,
381 keep = (_actor: PullRequestActor) => false,
382 ) =>
383 requested
384 ? [
385 ...actors,
386 ...selected
387 .filter(
388 (candidate) =>
389 !actors.some(
390 (actor) => actor.login.toLowerCase() === candidate.login.toLowerCase(),
391 ),
392 )
393 .map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
394 ]
395 : actors.filter(
396 (actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
397 );
398 updateCached(
399 registry,
400 detail(target),
401 (value) => ({
402 ...value,
403 reviewers: updateReviewers(value.reviewers),
404 }),
405 missingIdentities,
406 );
407 updateCached(
408 registry,
409 activity(target),
410 (value) => ({
411 ...value,
412 reviewers:
413 value.reviewers === undefined
414 ? undefined
415 : updateReviewers(value.reviewers, (actor) =>
416 value.comments.some(
417 (comment) =>
418 (comment.kind === "review" || comment.kind === "review-comment") &&
419 comment.author?.login.toLowerCase() === actor.login.toLowerCase(),
420 ),
421 ),
422 }),
423 missingIdentities,
424 );
425 }),
426 }),
427 /** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */
428 labelCandidates,
429 setLabels: createEnvironmentRpcCommand(runtime, {
430 label: "environment-data:pull-requests:set-labels",
431 tag: WS_METHODS.pullRequestsSetLabels,
432 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
433 scheduler: commandScheduler,
434 concurrency: serialPerEnvironment,
435 onSuccess: (target, registry) =>
436 Effect.sync(() => {
437 const { labels, applied } = target.input;
438 const candidatesAtom = labelCandidates(target);
439 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
440 const names = new Set(labels);
441 updateCached(registry, candidatesAtom, (value) => ({
442 ...value,
443 candidates: value.candidates.map((candidate) =>
444 names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
445 ),
446 }));
447 updateCached(registry, detail(target), (value) => ({
448 ...value,
449 labels: applied
450 ? [
451 ...value.labels,
452 ...labels
453 .filter((name) => !value.labels.some((label) => label.name === name))
454 .map((name) => ({
455 name,
456 color:
457 candidates?.candidates.find((candidate) => candidate.name === name)
458 ?.color ?? null,
459 })),
460 ]
461 : value.labels.filter((label) => !names.has(label.name)),
462 }));
463 }),
464 }),
465 setThreadResolution: createEnvironmentRpcCommand(runtime, {
466 label: "environment-data:pull-requests:set-thread-resolution",
467 tag: WS_METHODS.pullRequestsSetThreadResolution,
468 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetThreadResolution, input),
469 scheduler: commandScheduler,
470 concurrency: serialPerEnvironment,
471 }),
472 setReaction: createEnvironmentRpcCommand(runtime, {
473 label: "environment-data:pull-requests:set-reaction",
474 tag: WS_METHODS.pullRequestsSetReaction,
475 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetReaction, input),
476 scheduler: commandScheduler,
477 concurrency: serialPerEnvironment,
478 }),
479 /**
480 * Explicit refresh: forget the server's cached answers, then re-run the reads. A separate
481 * request rather than a flag on a read, so only a person's refresh spends host requests
482 * while every silent re-read shares the cache.
483 */
484 invalidate: createEnvironmentRpcCommand(runtime, {
485 label: "environment-data:pull-requests:invalidate",
486 tag: WS_METHODS.pullRequestsInvalidate,
487 execute: (input) => routedRequest(WS_METHODS.pullRequestsInvalidate, input),
488 scheduler: commandScheduler,
489 concurrency: serialPerEnvironment,
490 }),
491 };
492}