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

Manager.ts

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