Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as DateTime from "effect/DateTime";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Semaphore from "effect/Semaphore";
6import {
7 PullRequestOperationError,
8 type PullRequestFilesViewedResult,
9 type PullRequestRef,
10 type PullRequestSetFilesViewedInput,
11} from "@t3tools/contracts";
12
13import type * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";
14import type {
15 ProviderFileRevisions,
16 PullRequestProviderError,
17} from "@t3tools/source-control-core/server/PullRequestProvider";
18import type { PullRequestError, SupportedProject } from "./PullRequestService.ts";
19
20const FILE_REVISIONS_CACHE_TTL = Duration.seconds(60);
21const FILE_REVISIONS_STALE_WINDOW = Duration.minutes(10);
22const FILE_REVISIONS_CACHE_CAPACITY = 64;
23
24/**
25 * Bounds a single scope, not how many scopes are held: a reader ticking one file after
26 * another renews the same scope and grows it without limit otherwise.
27 */
28const MAX_FILE_REVISION_PATHS = 1_000;
29
30interface FileRevisionsDependencies {
31 readonly runFork: (effect: Effect.Effect<void>) => unknown;
32 readonly refEpoch: (ref: PullRequestRef) => number;
33 readonly fileRevisionsEpoch: () => number;
34 readonly toPullRequestError: (
35 operation: string,
36 ) => (error: PullRequestProviderError) => PullRequestError;
37}
38
39const makeFileRevisions = (dependencies: FileRevisionsDependencies) => {
40 const { runFork, refEpoch, fileRevisionsEpoch, toPullRequestError } = dependencies;
41 interface HeldFileRevisions {
42 readonly at: number;
43 readonly asked: ReadonlySet<string>;
44 readonly revisions: ReadonlyMap<string, string>;
45 }
46 const heldFileRevisions = new Map<string, HeldFileRevisions>();
47 const refreshingFileRevisions = new Set<string>();
48
49 /**
50 * Spelled from the project rather than the reference, since a reference arrives however
51 * the client spelled it while the epoch is bumped against the remote's own spelling.
52 */
53 const fileRevisionsKey = (project: SupportedProject, ref: PullRequestRef) =>
54 [
55 refEpoch({ ...ref, host: project.host, repository: project.repository }),
56 fileRevisionsEpoch(),
57 ref.projectId,
58 project.repository.trim().toLowerCase(),
59 ref.number,
60 ].join(" ");
61
62 const recordFileRevisions = (
63 key: string,
64 paths: ReadonlyArray<string>,
65 answer: ProviderFileRevisions,
66 ) =>
67 Effect.map(Clock.currentTimeMillis, (at) => {
68 const held = heldFileRevisions.get(key);
69 const carried =
70 held !== undefined && at - held.at <= Duration.toMillis(FILE_REVISIONS_STALE_WINDOW)
71 ? held
72 : null;
73 const revisions = new Map(carried?.revisions ?? []);
74 const asked = new Set(carried?.asked ?? []);
75 const learned = answer.complete === true ? [...answer.revisions.keys(), ...paths] : paths;
76 for (const path of learned) {
77 asked.delete(path);
78 asked.add(path);
79 const revision = answer.revisions.get(path);
80 if (revision !== undefined) {
81 revisions.delete(path);
82 revisions.set(path, revision);
83 }
84 }
85 for (const path of asked) {
86 if (asked.size <= MAX_FILE_REVISION_PATHS) break;
87 asked.delete(path);
88 revisions.delete(path);
89 }
90 heldFileRevisions.delete(key);
91 if (heldFileRevisions.size >= FILE_REVISIONS_CACHE_CAPACITY) {
92 const oldest = heldFileRevisions.keys().next().value;
93 if (oldest !== undefined) heldFileRevisions.delete(oldest);
94 }
95 // The entry is only as fresh as its oldest revision: stamping it with `now` on a partial
96 // answer would let an old revision ride past the point it should have been re-read.
97 const stamped = [...revisions.keys()].every((path) => answer.revisions.has(path))
98 ? at
99 : (carried?.at ?? at);
100 heldFileRevisions.set(key, { at: stamped, asked, revisions });
101 return revisions;
102 });
103
104 const heldFileRevisionsFor = (key: string, paths: ReadonlyArray<string>, now: number) => {
105 const held = heldFileRevisions.get(key);
106 if (held === undefined) return null;
107 heldFileRevisions.delete(key);
108 heldFileRevisions.set(key, held);
109 if (now - held.at > Duration.toMillis(FILE_REVISIONS_STALE_WINDOW)) return null;
110 return paths.every((path) => held.asked.has(path)) ? held : null;
111 };
112
113 /**
114 * `held` answers from a stale value and refetches off the critical path, since a badge a
115 * moment behind beats a page that won't paint until the host answers; `fresh` is for the
116 * press itself, which must not store a revision the head already moved off.
117 */
118 const fileRevisionsOf = (
119 project: SupportedProject,
120 ref: PullRequestRef,
121 paths: ReadonlyArray<string>,
122 operation: string,
123 freshness: "held" | "fresh" = "held",
124 ): Effect.Effect<ReadonlyMap<string, string> | null, PullRequestError> => {
125 const read = project.api.getFileRevisions;
126 if (read === undefined) return Effect.succeed(null);
127 // Suspended, so a held answer costs the host nothing: a provider is free to do its work as
128 // the request is built rather than as the effect is run.
129 const fetch = Effect.suspend(() => {
130 const key = fileRevisionsKey(project, ref);
131 return read({
132 cwd: project.project.workspaceRoot,
133 repository: project.repository,
134 host: project.host,
135 number: ref.number,
136 paths,
137 }).pipe(
138 Effect.mapError(toPullRequestError(operation)),
139 Effect.flatMap((answer) => recordFileRevisions(key, paths, answer)),
140 );
141 });
142 return Effect.flatMap(Clock.currentTimeMillis, (now) => {
143 const key = fileRevisionsKey(project, ref);
144 const held = heldFileRevisionsFor(key, paths, now);
145 if (held === null) return fetch;
146 if (now - held.at <= Duration.toMillis(FILE_REVISIONS_CACHE_TTL))
147 return Effect.succeed(held.revisions);
148 if (freshness === "fresh") return fetch;
149 if (refreshingFileRevisions.has(key)) return Effect.succeed(held.revisions);
150 // Its own fiber rather than a child: the caller has been answered and is gone before this
151 // lands.
152 return Effect.sync(() => {
153 refreshingFileRevisions.add(key);
154 runFork(
155 Effect.ignore(fetch).pipe(
156 Effect.ensuring(Effect.sync(() => refreshingFileRevisions.delete(key))),
157 ),
158 );
159 }).pipe(Effect.as(held.revisions));
160 });
161 };
162
163 return { fileRevisionsOf } as const;
164};
165
166export interface Dependencies extends FileRevisionsDependencies {
167 readonly filesViewedStore: PullRequestFilesViewed.PullRequestFilesViewedRepository["Service"];
168 readonly requireProject: (
169 ref: PullRequestRef,
170 ) => Effect.Effect<SupportedProject, PullRequestError>;
171 readonly requiredViewerOf: (
172 project: SupportedProject,
173 operation: string,
174 ) => Effect.Effect<string | null, PullRequestError>;
175}
176
177// A plain factory rather than a `Context.Service` (against the preference in
178// `.repos/effect-smol/LLMS.md`): the held revisions, refresh set, and write gates are only correct
179// at one instance per service, and a layer provided at two points would give two of each behind
180// one epoch counter.
181export const make = (dependencies: Dependencies) => {
182 const { filesViewedStore, requireProject, requiredViewerOf, toPullRequestError } = dependencies;
183 const { fileRevisionsOf } = makeFileRevisions(dependencies);
184 const filesViewedScope = (project: SupportedProject, number: number, viewer: string | null) => ({
185 provider: project.api.kind,
186 host: project.host,
187 repository: project.remote,
188 number,
189 viewer: viewer ?? "",
190 });
191
192 const toFilesViewedStoreError = (operation: string) => (cause: unknown) =>
193 new PullRequestOperationError({
194 operation,
195 detail: "This environment could not reach its record of which files you have seen.",
196 cause,
197 });
198
199 const environmentFilesViewed = Effect.fn("pullRequestViewedFiles.environmentFilesViewed")(
200 function* (
201 project: SupportedProject,
202 ref: PullRequestRef,
203 ): Effect.fn.Return<PullRequestFilesViewedResult, PullRequestError> {
204 const viewer = yield* requiredViewerOf(project, "filesViewed");
205 const held = yield* filesViewedStore
206 .list(filesViewedScope(project, ref.number, viewer))
207 .pipe(Effect.mapError(toFilesViewedStoreError("filesViewed")));
208 const marks = held.files;
209 if (marks.length === 0) return { files: [], truncated: held.truncated };
210 const revisions = yield* fileRevisionsOf(
211 project,
212 ref,
213 marks.map((mark) => mark.path),
214 "filesViewed",
215 ).pipe(
216 Effect.catch((error) =>
217 Effect.logWarning("reporting viewed files without what the head has of them", {
218 operation: "filesViewed",
219 reason: error._tag,
220 }).pipe(Effect.as(null)),
221 ),
222 );
223 return {
224 files: marks.map((mark) => {
225 if (mark.revision === null) return { path: mark.path, state: "viewed" as const };
226 const revision = revisions?.get(mark.path);
227 return {
228 path: mark.path,
229 state:
230 revision === undefined || revision === mark.revision
231 ? ("viewed" as const)
232 : ("dismissed" as const),
233 };
234 }),
235 truncated: held.truncated,
236 };
237 },
238 );
239
240 /**
241 * A tick's host round trip is slower than an untick's, so unordered presses could finish
242 * out of order and leave a stale tick standing over a later untick.
243 */
244 const filesViewedGates = new Map<
245 string,
246 { readonly gate: Semaphore.Semaphore; pending: number }
247 >();
248
249 const inFilesViewedOrder = (
250 project: SupportedProject,
251 number: number,
252 write: Effect.Effect<void, PullRequestError>,
253 ) =>
254 // Suspended rather than generated, so finding the gate, putting it in and taking a place in
255 // its queue are one step: yielding for `Semaphore.make` between the lookup and the insert
256 // lets two presses each make a gate of their own and neither wait on the other.
257 Effect.suspend(() => {
258 const key = `${project.project.id} ${project.remote} ${number}`;
259 const held = filesViewedGates.get(key);
260 const entry = held ?? { gate: Semaphore.makeUnsafe(1), pending: 0 };
261 if (held === undefined) filesViewedGates.set(key, entry);
262 entry.pending += 1;
263 return entry.gate
264 .withPermits(1)(write)
265 .pipe(
266 Effect.ensuring(
267 Effect.sync(() => {
268 entry.pending -= 1;
269 if (entry.pending === 0) filesViewedGates.delete(key);
270 }),
271 ),
272 );
273 });
274
275 const environmentSetFilesViewed = Effect.fn("pullRequestViewedFiles.environmentSetFilesViewed")(
276 function* (
277 project: SupportedProject,
278 input: PullRequestSetFilesViewedInput,
279 ): Effect.fn.Return<void, PullRequestError> {
280 const viewer = yield* requiredViewerOf(project, "setFilesViewed");
281 const cleared = input.files.filter((file) => file.viewed).map((file) => file.path);
282 const revisions =
283 cleared.length === 0
284 ? null
285 : yield* fileRevisionsOf(project, input, cleared, "setFilesViewed", "fresh").pipe(
286 Effect.catch((error) =>
287 Effect.logWarning("recording viewed files without what the head has of them", {
288 operation: "setFilesViewed",
289 reason: error._tag,
290 }).pipe(Effect.as(null)),
291 ),
292 );
293 const viewedAt = DateTime.formatIso(yield* DateTime.now);
294 yield* filesViewedStore
295 .set({
296 ...filesViewedScope(project, input.number, viewer),
297 // A path left out of the answer stores with no baseline, not the empty revision, since
298 // the empty revision is itself an answer and would misreport the file once it turns
299 // out to have a version after all.
300 files: input.files.map((file) => ({
301 path: file.path,
302 revision: revisions?.get(file.path) ?? null,
303 viewed: file.viewed,
304 })),
305 viewedAt,
306 })
307 .pipe(Effect.mapError(toFilesViewedStoreError("setFilesViewed")));
308 },
309 );
310
311 const filesViewed = (input: PullRequestRef) =>
312 requireProject(input).pipe(
313 Effect.flatMap((project): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> => {
314 const read = project.api.getFilesViewed;
315 if (project.api.capabilities.viewedFiles === "host" && read) {
316 return read({
317 cwd: project.project.workspaceRoot,
318 repository: project.repository,
319 host: project.host,
320 number: input.number,
321 }).pipe(Effect.mapError(toPullRequestError("filesViewed")));
322 }
323 if (project.api.capabilities.viewedFiles === "environment") {
324 return environmentFilesViewed(project, input);
325 }
326 return Effect.fail(
327 new PullRequestOperationError({
328 operation: "filesViewed",
329 detail: "This host does not track which files a reader has seen.",
330 }),
331 );
332 }),
333 );
334
335 const setFilesViewed = (
336 input: PullRequestSetFilesViewedInput,
337 ): Effect.Effect<void, PullRequestError> =>
338 requireProject(input).pipe(
339 Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
340 const write = project.api.setFilesViewed;
341 if (project.api.capabilities.viewedFiles === "host" && write) {
342 return write({
343 cwd: project.project.workspaceRoot,
344 repository: project.repository,
345 host: project.host,
346 number: input.number,
347 files: input.files,
348 }).pipe(Effect.mapError(toPullRequestError("setFilesViewed")));
349 }
350 if (project.api.capabilities.viewedFiles === "environment") {
351 return inFilesViewedOrder(
352 project,
353 input.number,
354 environmentSetFilesViewed(project, input),
355 );
356 }
357 return Effect.fail(
358 new PullRequestOperationError({
359 operation: "setFilesViewed",
360 detail: "This host does not track which files a reader has seen.",
361 }),
362 );
363 }),
364 );
365
366 return { filesViewed, setFilesViewed };
367};