Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

filesViewedStore.ts

251 lines9.0 KB

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