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

pullRequests.ts

471 lines19.0 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 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 runAction: createEnvironmentRpcCommand(runtime, {
274 label: "environment-data:pull-requests:run-action",
275 tag: WS_METHODS.pullRequestsRunAction,
276 execute: (input) => routedRequest(WS_METHODS.pullRequestsRunAction, input),
277 scheduler: commandScheduler,
278 concurrency: serialPerEnvironment,
279 }),
280 update: createEnvironmentRpcCommand(runtime, {
281 label: "environment-data:pull-requests:update",
282 tag: WS_METHODS.pullRequestsUpdate,
283 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
284 scheduler: commandScheduler,
285 concurrency: serialPerEnvironment,
286 }),
287 comment: createEnvironmentRpcCommand(runtime, {
288 label: "environment-data:pull-requests:comment",
289 tag: WS_METHODS.pullRequestsComment,
290 execute: (input) => routedRequest(WS_METHODS.pullRequestsComment, input),
291 scheduler: commandScheduler,
292 concurrency: serialPerEnvironment,
293 }),
294 updateComment: createEnvironmentRpcCommand(runtime, {
295 label: "environment-data:pull-requests:update-comment",
296 tag: WS_METHODS.pullRequestsUpdateComment,
297 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdateComment, input),
298 scheduler: commandScheduler,
299 concurrency: serialPerEnvironment,
300 onSuccess: ({ environmentId, input: { projectId, host, repository, number } }, registry) =>
301 Effect.sync(() =>
302 registry.refresh(
303 activity({
304 environmentId,
305 input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
306 }),
307 ),
308 ),
309 }),
310 submitReview: createEnvironmentRpcCommand(runtime, {
311 label: "environment-data:pull-requests:submit-review",
312 tag: WS_METHODS.pullRequestsSubmitReview,
313 execute: (input) => routedRequest(WS_METHODS.pullRequestsSubmitReview, input),
314 scheduler: commandScheduler,
315 concurrency: serialPerEnvironment,
316 }),
317 replyToThread: createEnvironmentRpcCommand(runtime, {
318 label: "environment-data:pull-requests:reply-to-thread",
319 tag: WS_METHODS.pullRequestsReplyToThread,
320 execute: (input) => routedRequest(WS_METHODS.pullRequestsReplyToThread, input),
321 scheduler: commandScheduler,
322 concurrency: serialPerEnvironment,
323 }),
324 /**
325 * Its own query rather than part of the detail: the people who may be asked are only wanted
326 * once somebody opens the reviewer menu, so this atom is read then and not before. Kept fresh
327 * for a minute, because who has access to a repository changes far more slowly than the
328 * change request it is being read for.
329 */
330 reviewerCandidates,
331 requestReviewers: createEnvironmentRpcCommand(runtime, {
332 label: "environment-data:pull-requests:request-reviewers",
333 tag: WS_METHODS.pullRequestsRequestReviewers,
334 execute: (input) => routedRequest(WS_METHODS.pullRequestsRequestReviewers, input),
335 scheduler: commandScheduler,
336 concurrency: serialPerEnvironment,
337 onSuccess: (target, registry) =>
338 Effect.sync(() => {
339 const { reviewers, requested } = target.input;
340 const candidatesAtom = reviewerCandidates(target);
341 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
342 const selected =
343 candidates?.candidates.filter((candidate) =>
344 reviewers.some(
345 (reviewer) => reviewer.id === candidate.id && reviewer.kind === candidate.kind,
346 ),
347 ) ?? [];
348 const missingIdentities = selected.length < reviewers.length;
349 updateCached(registry, candidatesAtom, (value) => ({
350 ...value,
351 candidates: value.candidates.map((candidate) =>
352 selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,
353 ),
354 }));
355 const selectedLogins = new Set(
356 selected.map((candidate) => candidate.login.toLowerCase()),
357 );
358 const updateReviewers = (
359 actors: ReadonlyArray<PullRequestActor>,
360 keep = (_actor: PullRequestActor) => false,
361 ) =>
362 requested
363 ? [
364 ...actors,
365 ...selected
366 .filter(
367 (candidate) =>
368 !actors.some(
369 (actor) => actor.login.toLowerCase() === candidate.login.toLowerCase(),
370 ),
371 )
372 .map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
373 ]
374 : actors.filter(
375 (actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
376 );
377 updateCached(
378 registry,
379 detail(target),
380 (value) => ({
381 ...value,
382 reviewers: updateReviewers(value.reviewers),
383 }),
384 missingIdentities,
385 );
386 updateCached(
387 registry,
388 activity(target),
389 (value) => ({
390 ...value,
391 reviewers:
392 value.reviewers === undefined
393 ? undefined
394 : updateReviewers(value.reviewers, (actor) =>
395 value.comments.some(
396 (comment) =>
397 (comment.kind === "review" || comment.kind === "review-comment") &&
398 comment.author?.login.toLowerCase() === actor.login.toLowerCase(),
399 ),
400 ),
401 }),
402 missingIdentities,
403 );
404 }),
405 }),
406 /** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */
407 labelCandidates,
408 setLabels: createEnvironmentRpcCommand(runtime, {
409 label: "environment-data:pull-requests:set-labels",
410 tag: WS_METHODS.pullRequestsSetLabels,
411 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
412 scheduler: commandScheduler,
413 concurrency: serialPerEnvironment,
414 onSuccess: (target, registry) =>
415 Effect.sync(() => {
416 const { labels, applied } = target.input;
417 const candidatesAtom = labelCandidates(target);
418 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
419 const names = new Set(labels);
420 updateCached(registry, candidatesAtom, (value) => ({
421 ...value,
422 candidates: value.candidates.map((candidate) =>
423 names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
424 ),
425 }));
426 updateCached(registry, detail(target), (value) => ({
427 ...value,
428 labels: applied
429 ? [
430 ...value.labels,
431 ...labels
432 .filter((name) => !value.labels.some((label) => label.name === name))
433 .map((name) => ({
434 name,
435 color:
436 candidates?.candidates.find((candidate) => candidate.name === name)
437 ?.color ?? null,
438 })),
439 ]
440 : value.labels.filter((label) => !names.has(label.name)),
441 }));
442 }),
443 }),
444 setThreadResolution: createEnvironmentRpcCommand(runtime, {
445 label: "environment-data:pull-requests:set-thread-resolution",
446 tag: WS_METHODS.pullRequestsSetThreadResolution,
447 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetThreadResolution, input),
448 scheduler: commandScheduler,
449 concurrency: serialPerEnvironment,
450 }),
451 setReaction: createEnvironmentRpcCommand(runtime, {
452 label: "environment-data:pull-requests:set-reaction",
453 tag: WS_METHODS.pullRequestsSetReaction,
454 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetReaction, input),
455 scheduler: commandScheduler,
456 concurrency: serialPerEnvironment,
457 }),
458 /**
459 * Explicit refresh: forget the server's cached answers, then re-run the reads. A separate
460 * request rather than a flag on a read, so only a person's refresh spends host requests
461 * while every silent re-read shares the cache.
462 */
463 invalidate: createEnvironmentRpcCommand(runtime, {
464 label: "environment-data:pull-requests:invalidate",
465 tag: WS_METHODS.pullRequestsInvalidate,
466 execute: (input) => routedRequest(WS_METHODS.pullRequestsInvalidate, input),
467 scheduler: commandScheduler,
468 concurrency: serialPerEnvironment,
469 }),
470 };