Open History to see the last commit
1import {
2 type AtomCommandResult,
3 isAtomCommandInterrupted,
4 runAtomCommand,
5} from "@t3tools/client-runtime/state/runtime";
6import type {
7 EnvironmentId,
8 PullRequestFilesViewedResult,
9 PullRequestRef,
10} from "@t3tools/contracts";
11import { AsyncResult } from "effect/reactivity";
12
13import { appAtomRegistry } from "~/rpc/atomRegistry";
14import { pullRequestEnvironment } from "~/state/pullRequests";
15
16import { toastManager } from "../ui/toast";
17import {
18 revertFileViewedOverlay,
19 settleFileViewedOverlay,
20 toFileViewedBatch,
21 toFileViewedStates,
22 type FileViewedOverlay,
23 type FileViewedPress,
24} from "./pullRequestFilesViewed.logic";
25
26export interface FilesViewedTarget {
27 readonly environmentId: EnvironmentId;
28 readonly reference: PullRequestRef;
29}
30
31type FilesViewedBatch = ReadonlyArray<{
32 readonly path: string;
33 readonly viewed: boolean;
34 readonly revision?: string;
35}>;
36
37export interface FilesViewedStoreDeps {
38 readonly flushDelayMs: number;
39 /** Calls `onAnswer` with the host's current answer at once, then with every later one. */
40 readonly subscribeAnswers: (
41 target: FilesViewedTarget,
42 onAnswer: (answer: PullRequestFilesViewedResult | null) => void,
43 ) => () => void;
44 readonly send: (
45 target: FilesViewedTarget,
46 batch: FilesViewedBatch,
47 ) => Promise<AtomCommandResult<unknown, unknown>>;
48 readonly refresh: (target: FilesViewedTarget) => void;
49 readonly reportFailure: () => void;
50}
51
52export interface FilesViewedScopeHandle {
53 /** Holds the scope open while subscribed; the last reader to leave sends its last presses. */
54 readonly subscribe: (listener: () => void) => () => void;
55 readonly getSnapshot: () => FileViewedOverlay;
56 /** `revision` is the file's version in the diff the press was made on, when it names one. */
57 readonly setViewed: (path: string, viewed: boolean, revision?: string) => void;
58}
59
60const NO_OVERLAY: FileViewedOverlay = new Map();
61
62interface FilesViewedScope {
63 readonly target: FilesViewedTarget;
64 readonly listeners: Set<() => void>;
65 readonly unsubscribeAnswers: () => void;
66 overlay: FileViewedOverlay;
67 queued: Map<string, FileViewedPress>;
68 readonly sentBy: Map<string, number>;
69 requests: number;
70 timer: ReturnType<typeof setTimeout> | null;
71 answer: PullRequestFilesViewedResult | null;
72 /**
73 * The host's answer as it stood when a completed write was acknowledged, per path. The first
74 * answer that differs from it is the first read that could have seen the write, which is what
75 * retires the press rather than the host happening to agree with it.
76 */
77 readonly answeredFrom: Map<string, PullRequestFilesViewedResult | null>;
78}
79
80/**
81 * Presses on one change request on one environment. The environment is part of the scope: two of
82 * them can hand out the same project id, and a press made against one must never be answered for
83 * by the other.
84 */
85export function createFilesViewedStore(deps: FilesViewedStoreDeps) {
86 const scopes = new Map<string, FilesViewedScope>();
87 const handles = new Map<string, FilesViewedScopeHandle>();
88
89 const publish = (scope: FilesViewedScope, overlay: FileViewedOverlay) => {
90 if (overlay === scope.overlay) return;
91 scope.overlay = overlay;
92 for (const listener of scope.listeners) listener();
93 };
94
95 const isLive = (key: string, scope: FilesViewedScope) => scopes.get(key) === scope;
96
97 const settle = (scope: FilesViewedScope, answer: PullRequestFilesViewedResult | null) => {
98 if (answer === scope.answer) return;
99 scope.answer = answer;
100 const pending = new Set([...scope.queued.keys(), ...scope.sentBy.keys()]);
101 const answered = new Set<string>();
102 for (const [path, from] of scope.answeredFrom) {
103 if (pending.has(path) || from === answer) continue;
104 answered.add(path);
105 scope.answeredFrom.delete(path);
106 }
107 publish(
108 scope,
109 settleFileViewedOverlay(scope.overlay, toFileViewedStates(answer), pending, answered),
110 );
111 };
112
113 const flush = (key: string, scope: FilesViewedScope) => {
114 scope.timer = null;
115 const batch = toFileViewedBatch(scope.queued);
116 if (batch.length === 0) return;
117 scope.queued = new Map();
118 const request = ++scope.requests;
119 for (const file of batch) scope.sentBy.set(file.path, request);
120 void deps.send(scope.target, batch).then((result) => {
121 const mine = batch
122 .map((file) => file.path)
123 .filter((path) => scope.sentBy.get(path) === request);
124 for (const path of mine) scope.sentBy.delete(path);
125 if (!isLive(key, scope)) {
126 // The overlay this press stood in is gone, but the cached answer still predates the
127 // write, and a reader coming back to this change request would be shown that.
128 if (result._tag === "Success" || !isAtomCommandInterrupted(result)) {
129 deps.refresh(scope.target);
130 }
131 return;
132 }
133 if (result._tag === "Failure") {
134 const owned = new Set(mine.filter((path) => !scope.queued.has(path)));
135 publish(scope, revertFileViewedOverlay(scope.overlay, batch, owned));
136 if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
137 deps.reportFailure();
138 deps.refresh(scope.target);
139 }
140 return;
141 }
142 // Answered for from the next read on, whatever it says. A push landing between the write
143 // and that read comes back as `dismissed`, and the press must not stand over it.
144 for (const path of mine) scope.answeredFrom.set(path, scope.answer);
145 deps.refresh(scope.target);
146 });
147 };
148
149 const acquire = (
150 key: string,
151 target: FilesViewedTarget,
152 handle: FilesViewedScopeHandle,
153 listener: () => void,
154 ) => {
155 // Registered from `subscribe`, which runs at commit, so a render that never commits leaves
156 // nothing behind. Re-registering here also carries a handle across StrictMode's
157 // subscribe-release-subscribe, so later renders keep returning it.
158 if (!handles.has(key)) handles.set(key, handle);
159 let scope = scopes.get(key);
160 if (scope === undefined) {
161 const listeners = new Set<() => void>();
162 let created: FilesViewedScope | undefined;
163 let initial: PullRequestFilesViewedResult | null = null;
164 const unsubscribeAnswers = deps.subscribeAnswers(target, (answer) => {
165 if (created === undefined) initial = answer;
166 else settle(created, answer);
167 });
168 created = {
169 target,
170 listeners,
171 unsubscribeAnswers,
172 overlay: NO_OVERLAY,
173 queued: new Map(),
174 sentBy: new Map(),
175 requests: 0,
176 timer: null,
177 answer: initial,
178 answeredFrom: new Map(),
179 };
180 scope = created;
181 scopes.set(key, scope);
182 }
183 const owned = scope;
184 owned.listeners.add(listener);
185 return () => {
186 if (!owned.listeners.delete(listener) || owned.listeners.size > 0) return;
187 // Leaving a change request, the environment it lives on, or the page itself records what
188 // was pressed and then drops the rest, sending those last presses to the scope being left.
189 if (owned.timer !== null) {
190 clearTimeout(owned.timer);
191 flush(key, owned);
192 }
193 scopes.delete(key);
194 handles.delete(key);
195 owned.unsubscribeAnswers();
196 };
197 };
198
199 return {
200 /**
201 * One stable handle per open scope, so readers keep their subscription across renders. Pure
202 * during render: an uncommitted handle is not cached, and any handle for a key behaves the same.
203 */
204 scope(target: FilesViewedTarget): FilesViewedScopeHandle {
205 const key = filesViewedScopeKey(target);
206 const cached = handles.get(key);
207 if (cached !== undefined) return cached;
208 const owned = { environmentId: target.environmentId, reference: { ...target.reference } };
209 const handle: FilesViewedScopeHandle = {
210 subscribe: (listener) => acquire(key, owned, handle, listener),
211 getSnapshot: () => scopes.get(key)?.overlay ?? NO_OVERLAY,
212 setViewed: (path, viewed, revision) => {
213 const scope = scopes.get(key);
214 if (scope === undefined) return;
215 scope.queued.set(path, { viewed, revision });
216 publish(scope, new Map(scope.overlay).set(path, viewed));
217 if (scope.timer !== null) clearTimeout(scope.timer);
218 scope.timer = setTimeout(() => flush(key, scope), deps.flushDelayMs);
219 },
220 };
221 return handle;
222 },
223 };
224}
225
226function filesViewedScopeKey({ environmentId, reference }: FilesViewedTarget): string {
227 return JSON.stringify([
228 environmentId,
229 reference.projectId,
230 reference.host ?? null,
231 reference.expectedAccountId ?? null,
232 reference.allowStale ?? null,
233 reference.repository,
234 reference.number,
235 ]);
236}
237
238const filesViewedAtom = ({ environmentId, reference }: FilesViewedTarget) =>
239 pullRequestEnvironment.filesViewed({ environmentId, input: reference });
240
241const filesViewedStore = createFilesViewedStore({
242 flushDelayMs: 400,
243 subscribeAnswers: (target, onAnswer) =>
244 appAtomRegistry.subscribe(
245 filesViewedAtom(target),
246 (result) => onAnswer(AsyncResult.getOrElse(result, () => null)),
247 { immediate: true },
248 ),
249 send: ({ environmentId, reference }, files) =>
250 runAtomCommand(
251 appAtomRegistry,
252 pullRequestEnvironment.setFilesViewed,
253 { environmentId, input: { ...reference, files } },
254 { reportFailure: false },
255 ),
256 refresh: (target) => appAtomRegistry.refresh(filesViewedAtom(target)),
257 reportFailure: () => toastManager.add({ type: "error", title: "Could not update viewed files" }),
258});
259
260export function filesViewedScope(target: FilesViewedTarget): FilesViewedScopeHandle {
261 return filesViewedStore.scope(target);
262}