Open History to see the last commit
1import {
2 WS_METHODS,
3 type PullRequestDetail,
4 type PullRequestDiffInput,
5 type PullRequestSummary,
6 type VcsStatusResult,
7} from "@t3tools/contracts";
8import * as Data from "effect/Data";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as SubscriptionRef from "effect/SubscriptionRef";
12import { Atom } from "effect/unstable/reactivity";
13
14import {
15 createAtomCommandScheduler,
16 createEnvironmentRpcCommand,
17 createEnvironmentRpcQueryAtomFamily,
18 createEnvironmentRpcSubscriptionAtomFamily,
19 createEnvironmentQueryAtomFamily,
20} from "./runtime.ts";
21import { PullRequestDiffLoader } from "./pullRequestDiffHttp.ts";
22import type { EnvironmentRegistry } from "../connection/registry.ts";
23import { EnvironmentSupervisor } from "../connection/supervisor.ts";
24
25export {
26 type PullRequestDiffLoadError,
27 PullRequestDiffCredentialRejectedError,
28 PullRequestDiffLoader,
29 pullRequestDiffLoaderLayer,
30} from "./pullRequestDiffHttp.ts";
31
32/** @public Required to name the error in consumers' inferred pull request results. */
33export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(
34 "EnvironmentHttpConnectionNotReadyError",
35)<{ readonly message: string }> {}
36
37const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000;
38
39function createPullRequestRefreshAtomFamily<R, E>(
40 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
41) {
42 return createEnvironmentRpcSubscriptionAtomFamily(runtime, {
43 label: "environment-data:pull-requests:turn-refreshes",
44 tag: WS_METHODS.pullRequestsSubscribeRefreshes,
45 });
46}
47
48/** Refresh only the live fields a linked thread renders. */
49export function createLinkedPullRequestSummaryAtomFamily<R, E>(
50 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
51 refreshes = createPullRequestRefreshAtomFamily(runtime),
52) {
53 return createEnvironmentRpcQueryAtomFamily(runtime, {
54 label: "environment-data:pull-requests:linked-summary",
55 tag: WS_METHODS.pullRequestsSummary,
56 staleTimeMs: 60_000,
57 refreshIntervalMs: 60_000,
58 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
59 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
60 });
61}
62
63export function pullRequestDetailToVcsStatus(
64 detail: PullRequestDetail | PullRequestSummary,
65): NonNullable<VcsStatusResult["pr"]> {
66 return {
67 number: detail.number,
68 title: detail.title,
69 url: detail.url,
70 baseRef: detail.baseBranch,
71 headRef: detail.headBranch,
72 state: detail.state,
73 ...(detail.isDraft === true ? { isDraft: true } : {}),
74 updatedAt: detail.updatedAt,
75 };
76}
77
78/**
79 * Reopening a PR within a minute reuses detail and activity. Explicit refreshes and
80 * turn notifications still revalidate. Mutations run serially per environment: actions on the same
81 * pull request are order-sensitive, and the detail view refetches after each one.
82 */
83export function createPullRequestEnvironmentAtoms<R, E>(
84 runtime: Atom.AtomRuntime<EnvironmentRegistry | PullRequestDiffLoader | R, E>,
85) {
86 const refreshes = createPullRequestRefreshAtomFamily(runtime);
87 const commandScheduler = createAtomCommandScheduler();
88 const serialPerEnvironment = {
89 mode: "serial",
90 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
91 } as const;
92 const activity = createEnvironmentRpcQueryAtomFamily(runtime, {
93 label: "environment-data:pull-requests:activity",
94 tag: WS_METHODS.pullRequestsActivity,
95 staleTimeMs: 60_000,
96 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
97 });
98 return {
99 refreshes,
100 list: createEnvironmentRpcQueryAtomFamily(runtime, {
101 label: "environment-data:pull-requests:list",
102 tag: WS_METHODS.pullRequestsList,
103 staleTimeMs: 30_000,
104 refreshTrigger: ({ environmentId, input }) =>
105 input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
106 }),
107 /**
108 * The line counts for rows the listing has already handed over. Its own query because the
109 * listing is quicker without them — measured over twelve repositories, ~4.0s against ~7.1s —
110 * so the rows arrive first and their stats a moment later. Kept longer than the listing:
111 * a change request's size only moves when somebody pushes to it.
112 */
113 listStats: createEnvironmentRpcQueryAtomFamily(runtime, {
114 label: "environment-data:pull-requests:list-stats",
115 tag: WS_METHODS.pullRequestsListStats,
116 staleTimeMs: 60_000,
117 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
118 }),
119 detail: createEnvironmentRpcQueryAtomFamily(runtime, {
120 label: "environment-data:pull-requests:detail",
121 tag: WS_METHODS.pullRequestsDetail,
122 staleTimeMs: 60_000,
123 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
124 }),
125 activity,
126 threadComments: createEnvironmentRpcCommand(runtime, {
127 label: "environment-data:pull-requests:thread-comments",
128 tag: WS_METHODS.pullRequestsThreadComments,
129 scheduler: commandScheduler,
130 concurrency: {
131 mode: "singleFlight",
132 key: ({ environmentId, input }) =>
133 JSON.stringify([environmentId, input.threadId, input.cursor]),
134 },
135 }),
136 diff: createEnvironmentQueryAtomFamily(runtime, {
137 label: "environment-data:pull-requests:diff",
138 staleTimeMs: 60_000,
139 execute: (input: PullRequestDiffInput) =>
140 Effect.gen(function* () {
141 const supervisor = yield* EnvironmentSupervisor;
142 const loader = yield* PullRequestDiffLoader;
143 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
144 if (Option.isNone(prepared)) {
145 return yield* new EnvironmentHttpConnectionNotReadyError({
146 message: "The environment HTTP connection is not ready.",
147 });
148 }
149 return yield* loader.load(prepared.value, input);
150 }),
151 }),
152 diffFileContents: createEnvironmentRpcCommand(runtime, {
153 label: "environment-data:pull-requests:diff-file-contents",
154 tag: WS_METHODS.pullRequestsDiffFileContents,
155 scheduler: commandScheduler,
156 concurrency: {
157 mode: "singleFlight",
158 key: ({ environmentId, input }) =>
159 JSON.stringify([
160 environmentId,
161 input.projectId,
162 input.repository,
163 input.number,
164 input.commit ?? null,
165 input.changeType,
166 input.oldPath,
167 input.newPath,
168 ]),
169 },
170 }),
171 runAction: createEnvironmentRpcCommand(runtime, {
172 label: "environment-data:pull-requests:run-action",
173 tag: WS_METHODS.pullRequestsRunAction,
174 scheduler: commandScheduler,
175 concurrency: serialPerEnvironment,
176 }),
177 update: createEnvironmentRpcCommand(runtime, {
178 label: "environment-data:pull-requests:update",
179 tag: WS_METHODS.pullRequestsUpdate,
180 scheduler: commandScheduler,
181 concurrency: serialPerEnvironment,
182 }),
183 comment: createEnvironmentRpcCommand(runtime, {
184 label: "environment-data:pull-requests:comment",
185 tag: WS_METHODS.pullRequestsComment,
186 scheduler: commandScheduler,
187 concurrency: serialPerEnvironment,
188 }),
189 updateComment: createEnvironmentRpcCommand(runtime, {
190 label: "environment-data:pull-requests:update-comment",
191 tag: WS_METHODS.pullRequestsUpdateComment,
192 scheduler: commandScheduler,
193 concurrency: serialPerEnvironment,
194 onSuccess: ({ environmentId, input: { projectId, repository, number } }, registry) =>
195 Effect.sync(() =>
196 registry.refresh(activity({ environmentId, input: { projectId, repository, number } })),
197 ),
198 }),
199 submitReview: createEnvironmentRpcCommand(runtime, {
200 label: "environment-data:pull-requests:submit-review",
201 tag: WS_METHODS.pullRequestsSubmitReview,
202 scheduler: commandScheduler,
203 concurrency: serialPerEnvironment,
204 }),
205 replyToThread: createEnvironmentRpcCommand(runtime, {
206 label: "environment-data:pull-requests:reply-to-thread",
207 tag: WS_METHODS.pullRequestsReplyToThread,
208 scheduler: commandScheduler,
209 concurrency: serialPerEnvironment,
210 }),
211 /**
212 * Its own query rather than part of the detail: the people who may be asked are only wanted
213 * once somebody opens the reviewer menu, so this atom is read then and not before. Kept fresh
214 * for a minute, because who has access to a repository changes far more slowly than the
215 * change request it is being read for.
216 */
217 reviewerCandidates: createEnvironmentRpcQueryAtomFamily(runtime, {
218 label: "environment-data:pull-requests:reviewer-candidates",
219 tag: WS_METHODS.pullRequestsReviewerCandidates,
220 staleTimeMs: 60_000,
221 }),
222 requestReviewers: createEnvironmentRpcCommand(runtime, {
223 label: "environment-data:pull-requests:request-reviewers",
224 tag: WS_METHODS.pullRequestsRequestReviewers,
225 scheduler: commandScheduler,
226 concurrency: serialPerEnvironment,
227 }),
228 /** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */
229 labelCandidates: createEnvironmentRpcQueryAtomFamily(runtime, {
230 label: "environment-data:pull-requests:label-candidates",
231 tag: WS_METHODS.pullRequestsLabelCandidates,
232 staleTimeMs: 60_000,
233 }),
234 setLabels: createEnvironmentRpcCommand(runtime, {
235 label: "environment-data:pull-requests:set-labels",
236 tag: WS_METHODS.pullRequestsSetLabels,
237 scheduler: commandScheduler,
238 concurrency: serialPerEnvironment,
239 }),
240 setThreadResolution: createEnvironmentRpcCommand(runtime, {
241 label: "environment-data:pull-requests:set-thread-resolution",
242 tag: WS_METHODS.pullRequestsSetThreadResolution,
243 scheduler: commandScheduler,
244 concurrency: serialPerEnvironment,
245 }),
246 setReaction: createEnvironmentRpcCommand(runtime, {
247 label: "environment-data:pull-requests:set-reaction",
248 tag: WS_METHODS.pullRequestsSetReaction,
249 scheduler: commandScheduler,
250 concurrency: serialPerEnvironment,
251 }),
252 /**
253 * Explicit refresh: forget the server's cached answers, then re-run the reads. A separate
254 * request rather than a flag on a read, so only a person's refresh spends host requests
255 * while every silent re-read shares the cache.
256 */
257 invalidate: createEnvironmentRpcCommand(runtime, {
258 label: "environment-data:pull-requests:invalidate",
259 tag: WS_METHODS.pullRequestsInvalidate,
260 scheduler: commandScheduler,
261 concurrency: serialPerEnvironment,
262 }),
263 };
264}