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

pullRequests.ts

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