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