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