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

Manager.ts

371 lines12.5 KB

1/**
2 * In-memory PreviewManager implementation.
3 *
4 * Sessions are keyed by `(threadId, tabId)`; a single thread can host
5 * multiple tabs (browser-style). `open` always creates a new tab — tab
6 * lifecycle is owned by the renderer.
7 *
8 * Events are published via Effect's `PubSub`, so subscriber failures are
9 * isolated from the publishing call (a closed WS subscriber queue cannot
10 * fail an in-progress `navigate()`).
11 */
12import {
13 type PreviewCloseInput,
14 type PreviewEvent,
15 type PreviewError,
16 PreviewInvalidUrlError,
17 type PreviewListInput,
18 type PreviewListResult,
19 type PreviewNavigateInput,
20 type PreviewOpenInput,
21 type PreviewRefreshInput,
22 type PreviewReportStatusInput,
23 PreviewSessionLookupError,
24 type PreviewSessionSnapshot,
25} from "@t3tools/contracts";
26import {
27 isPreviewUrlNormalizationError,
28 newPreviewTabId,
29 normalizePreviewUrl,
30} from "@t3tools/shared/preview";
31import * as Context from "effect/Context";
32import * as DateTime from "effect/DateTime";
33import * as Effect from "effect/Effect";
34import * as Layer from "effect/Layer";
35import * as PubSub from "effect/PubSub";
36import * as Scope from "effect/Scope";
37import * as Stream from "effect/Stream";
38import * as SynchronizedRef from "effect/SynchronizedRef";
39​
40export class PreviewManager extends Context.Service<
41 PreviewManager,
42 {
43 readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
44 readonly navigate: (
45 input: PreviewNavigateInput,
46 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
47 readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
48 readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
49 readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
50 readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
51 readonly events: Stream.Stream<PreviewEvent>;
52 readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
53 }
54>()("t3/preview/Manager/PreviewManager") {}
55​
56interface PreviewSessionState {
57 readonly threadId: string;
58 readonly tabId: string;
59 readonly snapshot: PreviewSessionSnapshot;
61​
62interface ManagerState {
63 /** All sessions across every thread, keyed by `${threadId}\u0000${tabId}`. */
64 readonly sessions: ReadonlyMap<string, PreviewSessionState>;
66​
67const initialState: ManagerState = { sessions: new Map() };
68​
69const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
70​
71const sessionsForThread = (
72 state: ManagerState,
73 threadId: string,
74): ReadonlyArray<PreviewSessionState> => {
75 const out: PreviewSessionState[] = [];
76 for (const session of state.sessions.values()) {
77 if (session.threadId === threadId) out.push(session);
78 }
79 return out;
80};
81​
82const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
83 Effect.try({
84 try: () => normalizePreviewUrl(rawUrl),
85 catch: (cause) => {
86 if (isPreviewUrlNormalizationError(cause)) {
87 return new PreviewInvalidUrlError({
88 inputLength: cause.inputLength,
89 reason: cause.reason,
90 protocol: cause.protocol,
91 cause,
92 });
93 }
94​
95 return new PreviewInvalidUrlError({
96 inputLength: rawUrl.length,
97 reason: "unexpected",
98 cause,
99 });
100 },
101 });
102​
103const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
104​
105const buildLoadingSnapshot = (input: {
106 readonly threadId: string;
107 readonly tabId: string;
108 readonly url: string;
109 readonly title: string;
110 readonly updatedAt: string;
111}): PreviewSessionSnapshot => ({
112 threadId: input.threadId,
113 tabId: input.tabId,
114 navStatus: { _tag: "Loading", url: input.url, title: input.title },
115 canGoBack: false,
116 canGoForward: false,
117 updatedAt: input.updatedAt,
118});
119​
120const buildIdleSnapshot = (input: {
121 readonly threadId: string;
122 readonly tabId: string;
123 readonly updatedAt: string;
124}): PreviewSessionSnapshot => ({
125 threadId: input.threadId,
126 tabId: input.tabId,
127 navStatus: { _tag: "Idle" },
128 canGoBack: false,
129 canGoForward: false,
130 updatedAt: input.updatedAt,
131});
132​
133export const make = Effect.gen(function* PreviewManagerMake() {
134 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
135 // Unbounded PubSub is fine here — events are tiny and we don't want to
136 // block publishers if a subscriber is slow. WS clients backpressure on
137 // their own queues downstream.
138 const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
139 const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
140​
141 /**
142 * Atomic read-modify-write over the session for `(threadId, tabId)`. The
143 * mutator runs under the SynchronizedRef so concurrent writers cannot
144 * interleave. Lookup failures travel through the modify result so both
145 * branches yield the same `[A, S]` shape `modifyEffect` requires.
146 *
147 * The event is published INSIDE the lock so observers see events in the
148 * same order as the underlying state transitions. Publishing an unbounded
149 * PubSub is non-blocking, so this is cheap.
150 */
151 const mutateExistingSession = <R, E>(
152 threadId: string,
153 tabId: string,
154 mutator: (
155 session: PreviewSessionState,
156 ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEvent | null; result: R }, E>,
157 ): Effect.Effect<R, E | PreviewSessionLookupError> => {
158 type ModifyResult =
159 | { kind: "fail"; error: PreviewSessionLookupError }
160 | { kind: "ok"; result: R };
161​
162 return SynchronizedRef.modifyEffect(stateRef, (state) => {
163 const session = state.sessions.get(compositeKey(threadId, tabId));
164 if (!session) {
165 return Effect.succeed([
166 { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
167 state,
168 ] as readonly [ModifyResult, ManagerState]);
169 }
170 return mutator(session).pipe(
171 Effect.flatMap(
172 Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
173 if (emit) yield* PubSub.publish(eventsPubSub, emit);
174 const sessions = new Map(state.sessions);
175 sessions.set(compositeKey(threadId, tabId), next);
176 return [{ kind: "ok", result } as ModifyResult, { sessions }] as readonly [
177 ModifyResult,
178 ManagerState,
179 ];
180 }),
181 ),
182 );
183 }).pipe(
184 Effect.flatMap((modify) =>
185 modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
186 ),
187 );
188 };
189​
190 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
191 function* (input) {
192 const tabId = newPreviewTabId();
193 const updatedAt = yield* currentIsoTimestamp;
194 const snapshot = input.url
195 ? buildLoadingSnapshot({
196 threadId: input.threadId,
197 tabId,
198 url: yield* normalizeUrl(input.url),
199 title: "",
200 updatedAt,
201 })
202 : buildIdleSnapshot({ threadId: input.threadId, tabId, updatedAt });
203 yield* SynchronizedRef.update(stateRef, (state) => {
204 const sessions = new Map(state.sessions);
205 sessions.set(compositeKey(input.threadId, tabId), {
206 threadId: input.threadId,
207 tabId,
208 snapshot,
209 });
210 return { sessions };
211 });
212 yield* PubSub.publish(eventsPubSub, {
213 type: "opened",
214 threadId: input.threadId,
215 tabId,
216 createdAt: snapshot.updatedAt,
217 snapshot,
218 });
219 return snapshot;
220 },
221 );
222​
223 const navigate: PreviewManager["Service"]["navigate"] = Effect.fn("PreviewManager.navigate")(
224 function* (input) {
225 const url = yield* normalizeUrl(input.url);
226 return yield* mutateExistingSession(
227 input.threadId,
228 input.tabId,
229 Effect.fn("PreviewManager.navigateSession")(function* (session) {
230 const updatedAt = yield* currentIsoTimestamp;
231 const previousTitle =
232 session.snapshot.navStatus._tag === "Idle" ? "" : session.snapshot.navStatus.title;
233 const resolvedTitle = input.resolvedTitle ?? previousTitle;
234 const snapshot: PreviewSessionSnapshot = {
235 threadId: session.threadId,
236 tabId: session.tabId,
237 navStatus: { _tag: "Success", url, title: resolvedTitle },
238 canGoBack: session.snapshot.canGoBack,
239 canGoForward: session.snapshot.canGoForward,
240 updatedAt,
241 };
242 return {
243 next: { ...session, snapshot },
244 emit: {
245 type: "navigated",
246 threadId: session.threadId,
247 tabId: session.tabId,
248 createdAt: snapshot.updatedAt,
249 snapshot,
250 },
251 result: snapshot,
252 };
253 }),
254 );
255 },
256 );
257​
258 const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
259 "PreviewManager.reportStatus",
260 )(function* (input) {
261 yield* mutateExistingSession(
262 input.threadId,
263 input.tabId,
264 Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
265 const updatedAt = yield* currentIsoTimestamp;
266 const snapshot: PreviewSessionSnapshot = {
267 threadId: session.threadId,
268 tabId: session.tabId,
269 navStatus: input.navStatus,
270 canGoBack: input.canGoBack,
271 canGoForward: input.canGoForward,
272 updatedAt,
273 };
274 const emit: PreviewEvent =
275 input.navStatus._tag === "LoadFailed"
276 ? {
277 type: "failed",
278 threadId: session.threadId,
279 tabId: session.tabId,
280 createdAt: snapshot.updatedAt,
281 url: input.navStatus.url,
282 title: input.navStatus.title,
283 code: input.navStatus.code,
284 description: input.navStatus.description,
285 }
286 : {
287 type: "navigated",
288 threadId: session.threadId,
289 tabId: session.tabId,
290 createdAt: snapshot.updatedAt,
291 snapshot,
292 };
293 return {
294 next: { ...session, snapshot },
295 emit,
296 result: undefined as void,
297 };
298 }),
299 );
300 });
301​
302 const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
303 function* (input) {
304 // Verify the session exists; the desktop bridge handles the actual reload
305 // and will report progress back via `reportStatus`. No event emitted.
306 yield* mutateExistingSession(input.threadId, input.tabId, (session) =>
307 Effect.succeed({ next: session, emit: null, result: undefined as void }),
308 );
309 },
310 );
311​
312 const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")(
313 function* (input) {
314 const createdAt = yield* currentIsoTimestamp;
315 const events = yield* SynchronizedRef.modify(stateRef, (state) => {
316 const eventsToEmit: PreviewEvent[] = [];
317 const sessions = new Map(state.sessions);
318 const targets = input.tabId
319 ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
320 (entry): entry is PreviewSessionState => entry !== undefined,
321 )
322 : sessionsForThread(state, input.threadId);
323 for (const target of targets) {
324 sessions.delete(compositeKey(target.threadId, target.tabId));
325 eventsToEmit.push({
326 type: "closed",
327 threadId: target.threadId,
328 tabId: target.tabId,
329 createdAt,
330 });
331 }
332 if (eventsToEmit.length === 0) {
333 return [eventsToEmit, state] as const;
334 }
335 return [eventsToEmit, { sessions }] as const;
336 });
337 if (events.length > 0) {
338 yield* Effect.forEach(events, (event) => PubSub.publish(eventsPubSub, event), {
339 discard: true,
340 });
341 }
342 },
343 );
344​
345 const list: PreviewManager["Service"]["list"] = Effect.fn("PreviewManager.list")(
346 function* (input) {
347 return yield* SynchronizedRef.get(stateRef).pipe(
348 Effect.map(
349 (state): PreviewListResult => ({
350 sessions: sessionsForThread(state, input.threadId)
351 .map((s) => s.snapshot)
352 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
353 }),
354 ),
355 );
356 },
357 );
358​
359 return PreviewManager.of({
360 open,
361 navigate,
362 reportStatus,
363 refresh,
364 close,
365 list,
366 events,
367 subscribeEvents: PubSub.subscribe(eventsPubSub),
368 });
369}).pipe(Effect.withSpan("PreviewManager.make"));
370​
371export const layer = Layer.effect(PreviewManager, make);