Open History to see the last commit
1/**
2 * The marks a reader has ticked off, for a host that keeps none of its own, and the held record of
3 * what the head has of those files. The revisions cache is filed here because this is its only
4 * consumer: when a second one appears, export `makeFileRevisions` and split it into its own file.
5 */
6import * as Clock from "effect/Clock";
7import * as DateTime from "effect/DateTime";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Semaphore from "effect/Semaphore";
11import {
12 PullRequestOperationError,
13 type PullRequestFilesViewedResult,
14 type PullRequestRef,
15 type PullRequestSetFilesViewedInput,
16} from "@t3tools/contracts";
17
18import type * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";
19import type { ProviderFileRevisions, PullRequestProviderError } from "./PullRequestProvider.ts";
20import type { PullRequestError, SupportedProject } from "./PullRequestService.ts";
21
22/**
23 * How long the head's version of a file is believed, and how long a held answer stands while the
24 * next one is fetched. This is the host call behind the **Changed** badge alone, so a held answer
25 * costs a badge that is a minute behind rather than a stale tick.
26 */
27const FILE_REVISIONS_CACHE_TTL = Duration.seconds(60);
28const FILE_REVISIONS_STALE_WINDOW = Duration.minutes(10);
29export const FILE_REVISIONS_CACHE_CAPACITY = 64;
30
31/**
32 * How many paths one scope's entry carries. Bounds a single scope, not how many scopes are held:
33 * a reader ticking one file after another renews the same scope and grows it without limit
34 * otherwise.
35 */
36export const MAX_FILE_REVISION_PATHS = 1_000;
37
38interface FileRevisionsDependencies {
39 readonly runFork: (effect: Effect.Effect<void>) => unknown;
40 readonly refEpoch: (ref: PullRequestRef) => number;
41 readonly fileRevisionsEpoch: () => number;
42 readonly toPullRequestError: (
43 operation: string,
44 ) => (error: PullRequestProviderError) => PullRequestError;
45}
46
47const makeFileRevisions = (dependencies: FileRevisionsDependencies) => {
48 const { runFork, refEpoch, fileRevisionsEpoch, toPullRequestError } = dependencies;
49 /**
50 * What the head has of the files a reader has marked, held between reads. The entry tracks what
51 * has been asked as well as what was heard, since a path missing from an answer keeps whatever
52 * version was last given for it rather than being cleared.
53 */
54 interface HeldFileRevisions {
55 readonly at: number;
56 readonly asked: ReadonlySet<string>;
57 readonly revisions: ReadonlyMap<string, string>;
58 }
59 const heldFileRevisions = new Map<string, HeldFileRevisions>();
60 const refreshingFileRevisions = new Set<string>();
61
62 /**
63 * Carries the reference's epoch, so whatever moved the head strands what was held (or in
64 * flight) against the old one. Spelled from the project rather than the reference, since a
65 * reference arrives however the client spelled it while the epoch is bumped against the
66 * remote's own spelling.
67 */
68 const fileRevisionsKey = (project: SupportedProject, ref: PullRequestRef) =>
69 [
70 refEpoch({ ...ref, host: project.host, repository: project.repository }),
71 fileRevisionsEpoch(),
72 ref.projectId,
73 project.repository.trim().toLowerCase(),
74 ref.number,
75 ].join(" ");
76
77 /**
78 * `paths` are what was asked about, and are held as answered for whether the host had a version
79 * for them or not: that is what stops the same question being asked again. A `complete` answer
80 * adds every other path it carries, since a host that read the whole change to answer for one
81 * file has already paid for all of them, and the tick after this one names a file nothing has
82 * asked about yet.
83 */
84 const recordFileRevisions = (
85 key: string,
86 paths: ReadonlyArray<string>,
87 answer: ProviderFileRevisions,
88 ) =>
89 Effect.map(Clock.currentTimeMillis, (at) => {
90 const held = heldFileRevisions.get(key);
91 // Past the stale window the old entry is not worth merging into: it would carry paths
92 // nobody has asked about since, at revisions the head has long moved off.
93 const carried =
94 held !== undefined && at - held.at <= Duration.toMillis(FILE_REVISIONS_STALE_WINDOW)
95 ? held
96 : null;
97 const revisions = new Map(carried?.revisions ?? []);
98 const asked = new Set(carried?.asked ?? []);
99 // The paths asked for go last, so a whole-change answer wider than the cap is trimmed down
100 // to the reader's own files rather than over them.
101 const learned = answer.complete === true ? [...answer.revisions.keys(), ...paths] : paths;
102 for (const path of learned) {
103 // Reinserted rather than added, so what a full entry drops below is the path nobody has
104 // asked about in the longest rather than one just asked for.
105 asked.delete(path);
106 asked.add(path);
107 const revision = answer.revisions.get(path);
108 // A path left out of the answer keeps its last known version rather than being cleared.
109 if (revision !== undefined) {
110 revisions.delete(path);
111 revisions.set(path, revision);
112 }
113 }
114 for (const path of asked) {
115 if (asked.size <= MAX_FILE_REVISION_PATHS) break;
116 asked.delete(path);
117 revisions.delete(path);
118 }
119 heldFileRevisions.delete(key);
120 if (heldFileRevisions.size >= FILE_REVISIONS_CACHE_CAPACITY) {
121 const oldest = heldFileRevisions.keys().next().value;
122 if (oldest !== undefined) heldFileRevisions.delete(oldest);
123 }
124 // The entry is only as fresh as its oldest revision: stamping it with `now` on a partial
125 // answer would let an old revision ride past the point it should have been re-read.
126 const stamped = [...revisions.keys()].every((path) => answer.revisions.has(path))
127 ? at
128 : (carried?.at ?? at);
129 heldFileRevisions.set(key, { at: stamped, asked, revisions });
130 return revisions;
131 });
132
133 /** A held entry that covers every path asked for and is still worth answering from. */
134 const heldFileRevisionsFor = (key: string, paths: ReadonlyArray<string>, now: number) => {
135 const held = heldFileRevisions.get(key);
136 if (held === undefined) return null;
137 // Put back at the end on every read, so the scope a reader is working through is not the one
138 // evicted by a listing walking scopes nobody has open.
139 heldFileRevisions.delete(key);
140 heldFileRevisions.set(key, held);
141 if (now - held.at > Duration.toMillis(FILE_REVISIONS_STALE_WINDOW)) return null;
142 return paths.every((path) => held.asked.has(path)) ? held : null;
143 };
144
145 /**
146 * What the head has of these files, or null where the host cannot say (not an error: the marks
147 * just stop reporting staleness). `held` answers from a stale value and refetches off the
148 * critical path, since a badge a moment behind beats a page that won't paint until the host
149 * answers; `fresh` is for the press itself, which must not store a revision the head already
150 * moved off.
151 */
152 const fileRevisionsOf = (
153 project: SupportedProject,
154 ref: PullRequestRef,
155 paths: ReadonlyArray<string>,
156 operation: string,
157 freshness: "held" | "fresh" = "held",
158 ): Effect.Effect<ReadonlyMap<string, string> | null, PullRequestError> => {
159 const read = project.api.getFileRevisions;
160 if (read === undefined) return Effect.succeed(null);
161 // Suspended, so a held answer costs the host nothing: a provider is free to do its work as
162 // the request is built rather than as the effect is run.
163 const fetch = Effect.suspend(() => {
164 const key = fileRevisionsKey(project, ref);
165 return read({
166 cwd: project.project.workspaceRoot,
167 repository: project.repository,
168 host: project.host,
169 number: ref.number,
170 paths,
171 }).pipe(
172 Effect.mapError(toPullRequestError(operation)),
173 Effect.flatMap((answer) => recordFileRevisions(key, paths, answer)),
174 );
175 });
176 return Effect.flatMap(Clock.currentTimeMillis, (now) => {
177 const key = fileRevisionsKey(project, ref);
178 const held = heldFileRevisionsFor(key, paths, now);
179 if (held === null) return fetch;
180 if (now - held.at <= Duration.toMillis(FILE_REVISIONS_CACHE_TTL))
181 return Effect.succeed(held.revisions);
182 if (freshness === "fresh") return fetch;
183 if (refreshingFileRevisions.has(key)) return Effect.succeed(held.revisions);
184 // Its own fiber rather than a child: the caller has been answered and is gone before this
185 // lands. One at a time per change request, so a page of files costs one host read.
186 return Effect.sync(() => {
187 refreshingFileRevisions.add(key);
188 runFork(
189 Effect.ignore(fetch).pipe(
190 Effect.ensuring(Effect.sync(() => refreshingFileRevisions.delete(key))),
191 ),
192 );
193 }).pipe(Effect.as(held.revisions));
194 });
195 };
196
197 return { fileRevisionsOf } as const;
198};
199
200export interface Dependencies extends FileRevisionsDependencies {
201 readonly filesViewedStore: PullRequestFilesViewed.PullRequestFilesViewedRepository["Service"];
202 readonly requireProject: (
203 ref: PullRequestRef,
204 ) => Effect.Effect<SupportedProject, PullRequestError>;
205 readonly requiredViewerOf: (
206 project: SupportedProject,
207 operation: string,
208 ) => Effect.Effect<string | null, PullRequestError>;
209}
210
211// A plain factory rather than a `Context.Service` (against the preference in
212// `.repos/effect-smol/LLMS.md`): the held revisions, refresh set, and write gates are only correct
213// at one instance per service, and a layer provided at two points would give two of each behind
214// one epoch counter.
215export const make = (dependencies: Dependencies) => {
216 const { filesViewedStore, requireProject, requiredViewerOf, toPullRequestError } = dependencies;
217 const { fileRevisionsOf } = makeFileRevisions(dependencies);
218 /**
219 * Which change request's marks, and whose. Provider and host lead the key because the same
220 * repository can exist on more than one install; the reader is part of it because a host's own
221 * record is per-account. A host that names no reader is one reader, not none.
222 */
223 const filesViewedScope = (project: SupportedProject, number: number, viewer: string | null) => ({
224 provider: project.api.kind,
225 host: project.host,
226 repository: project.remote,
227 number,
228 viewer: viewer ?? "",
229 });
230
231 const toFilesViewedStoreError = (operation: string) => (cause: unknown) =>
232 new PullRequestOperationError({
233 operation,
234 detail: "This environment could not reach its record of which files you have seen.",
235 cause,
236 });
237
238 /**
239 * The marks this environment keeps for a host that keeps none of its own. A file the head
240 * still has at the revision it was cleared at is cleared; one the head has moved on from is
241 * reported as changed. Revisions are asked for the marked paths alone, so a reader who has
242 * marked nothing costs no host call.
243 */
244 const environmentFilesViewed = (
245 project: SupportedProject,
246 ref: PullRequestRef,
247 ): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> =>
248 Effect.gen(function* () {
249 const viewer = yield* requiredViewerOf(project, "filesViewed");
250 const held = yield* filesViewedStore
251 .list(filesViewedScope(project, ref.number, viewer))
252 .pipe(Effect.mapError(toFilesViewedStoreError("filesViewed")));
253 const marks = held.files;
254 if (marks.length === 0) return { files: [], truncated: held.truncated };
255 // A host that won't say what its head has costs the marks their staleness (`fileRevisionsOf`
256 // returns null), rather than costing the reader every tick they've made.
257 const revisions = yield* fileRevisionsOf(
258 project,
259 ref,
260 marks.map((mark) => mark.path),
261 "filesViewed",
262 ).pipe(
263 Effect.catch((error) =>
264 Effect.logWarning("reporting viewed files without what the head has of them", {
265 operation: "filesViewed",
266 reason: error._tag,
267 }).pipe(Effect.as(null)),
268 ),
269 );
270 return {
271 files: marks.map((mark) => {
272 // A mark stamped with no baseline holds until the reader presses it again.
273 if (mark.revision === null) return { path: mark.path, state: "viewed" as const };
274 const revision = revisions?.get(mark.path);
275 // A deleted file is answered as the empty revision, matching its stamp, so it stays
276 // cleared; a path the host had no answer for (`undefined`) also holds as cleared.
277 return {
278 path: mark.path,
279 state:
280 revision === undefined || revision === mark.revision
281 ? ("viewed" as const)
282 : ("dismissed" as const),
283 };
284 }),
285 // The store caps marks per scope; a reader over that cap is told so, like a paginated read.
286 truncated: held.truncated,
287 };
288 });
289
290 /**
291 * One environment-backed write at a time per change request. A tick's host round trip is
292 * slower than an untick's, so unordered presses could finish out of order and leave a stale
293 * tick standing over a later untick.
294 */
295 const filesViewedGates = new Map<
296 string,
297 { readonly gate: Semaphore.Semaphore; pending: number }
298 >();
299
300 const inFilesViewedOrder = (
301 project: SupportedProject,
302 number: number,
303 write: Effect.Effect<void, PullRequestError>,
304 ) =>
305 // Suspended rather than generated, so finding the gate, putting it in and taking a place in
306 // its queue are one step: yielding for `Semaphore.make` between the lookup and the insert
307 // lets two presses each make a gate of their own and neither wait on the other.
308 Effect.suspend(() => {
309 const key = `${project.project.id} ${project.remote} ${number}`;
310 const held = filesViewedGates.get(key);
311 const entry = held ?? { gate: Semaphore.makeUnsafe(1), pending: 0 };
312 if (held === undefined) filesViewedGates.set(key, entry);
313 entry.pending += 1;
314 // Dropped once nobody is queued behind it, so a long-lived server does not keep a gate per
315 // change request anyone has ever ticked a file in.
316 return entry.gate
317 .withPermits(1)(write)
318 .pipe(
319 Effect.ensuring(
320 Effect.sync(() => {
321 entry.pending -= 1;
322 if (entry.pending === 0) filesViewedGates.delete(key);
323 }),
324 ),
325 );
326 });
327
328 const environmentSetFilesViewed = (
329 project: SupportedProject,
330 input: PullRequestSetFilesViewedInput,
331 ): Effect.Effect<void, PullRequestError> =>
332 Effect.gen(function* () {
333 const viewer = yield* requiredViewerOf(project, "setFilesViewed");
334 // Only the files being cleared need a revision. An unticked one is about to lose its row,
335 // and what the head has of it changes nothing about deleting it.
336 const cleared = input.files.filter((file) => file.viewed).map((file) => file.path);
337 const revisions =
338 cleared.length === 0
339 ? null
340 : yield* fileRevisionsOf(project, input, cleared, "setFilesViewed", "fresh").pipe(
341 // A host that won't say what its head has costs the press its baseline, not the
342 // press itself: the mark is stored with none and holds until pressed again.
343 Effect.catch((error) =>
344 Effect.logWarning("recording viewed files without what the head has of them", {
345 operation: "setFilesViewed",
346 reason: error._tag,
347 }).pipe(Effect.as(null)),
348 ),
349 );
350 const viewedAt = DateTime.formatIso(yield* DateTime.now);
351 yield* filesViewedStore
352 .set({
353 ...filesViewedScope(project, input.number, viewer),
354 // A path left out of the answer stores with no baseline, not the empty revision, since
355 // the empty revision is itself an answer and would misreport the file once it turns
356 // out to have a version after all.
357 files: input.files.map((file) => ({
358 path: file.path,
359 revision: revisions?.get(file.path) ?? null,
360 viewed: file.viewed,
361 })),
362 viewedAt,
363 })
364 .pipe(Effect.mapError(toFilesViewedStoreError("setFilesViewed")));
365 });
366
367 const filesViewed = (input: PullRequestRef) =>
368 requireProject(input).pipe(
369 Effect.flatMap((project): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> => {
370 const read = project.api.getFilesViewed;
371 if (project.api.capabilities.viewedFiles === "host" && read) {
372 return read({
373 cwd: project.project.workspaceRoot,
374 repository: project.repository,
375 host: project.host,
376 number: input.number,
377 }).pipe(Effect.mapError(toPullRequestError("filesViewed")));
378 }
379 if (project.api.capabilities.viewedFiles === "environment") {
380 return environmentFilesViewed(project, input);
381 }
382 return Effect.fail(
383 new PullRequestOperationError({
384 operation: "filesViewed",
385 detail: "This host does not track which files a reader has seen.",
386 }),
387 );
388 }),
389 );
390
391 const setFilesViewed = (
392 input: PullRequestSetFilesViewedInput,
393 ): Effect.Effect<void, PullRequestError> =>
394 requireProject(input).pipe(
395 Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
396 const write = project.api.setFilesViewed;
397 if (project.api.capabilities.viewedFiles === "host" && write) {
398 return write({
399 cwd: project.project.workspaceRoot,
400 repository: project.repository,
401 host: project.host,
402 number: input.number,
403 files: input.files,
404 }).pipe(Effect.mapError(toPullRequestError("setFilesViewed")));
405 }
406 if (project.api.capabilities.viewedFiles === "environment") {
407 return inFilesViewedOrder(
408 project,
409 input.number,
410 environmentSetFilesViewed(project, input),
411 );
412 }
413 return Effect.fail(
414 new PullRequestOperationError({
415 operation: "setFilesViewed",
416 detail: "This host does not track which files a reader has seen.",
417 }),
418 );
419 }),
420 );
421
422 return { filesViewed, setFilesViewed };
423};