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

Manager.ts

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