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