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