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

Manager.ts

460 lines15.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 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​
156export const make = Effect.gen(function* PreviewManagerMake() {
157 const serverEpoch = NodeCrypto.randomUUID();
158 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
159 // Unbounded PubSub is fine here — events are tiny and we don't want to
160 // block publishers if a subscriber is slow. WS clients backpressure on
161 // their own queues downstream.
162 const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
163 const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
164​
165 /**
166 * Atomic read-modify-write over the session for `(threadId, tabId)`. The
167 * mutator runs under the SynchronizedRef so concurrent writers cannot
168 * interleave. Lookup failures travel through the modify result so both
169 * branches yield the same `[A, S]` shape `modifyEffect` requires.
170 *
171 * The event is published INSIDE the lock so observers see events in the
172 * same order as the underlying state transitions. Publishing an unbounded
173 * PubSub is non-blocking, so this is cheap.
174 */
175 const mutateExistingSession = <R, E>(
176 threadId: string,
177 tabId: string,
178 mutator: (
179 session: PreviewSessionState,
180 ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEventDraft | null; result: R }, E>,
181 ): Effect.Effect<R, E | PreviewSessionLookupError> => {
182 type ModifyResult =
183 | { kind: "fail"; error: PreviewSessionLookupError }
184 | { kind: "ok"; result: R };
185​
186 return SynchronizedRef.modifyEffect(stateRef, (state) => {
187 const session = state.sessions.get(compositeKey(threadId, tabId));
188 if (!session) {
189 return Effect.succeed([
190 { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
191 state,
192 ] as readonly [ModifyResult, ManagerState]);
193 }
194 return mutator(session).pipe(
195 Effect.flatMap(
196 Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
197 const revision = emit ? state.revision + 1 : state.revision;
198 if (emit) {
199 yield* PubSub.publish(eventsPubSub, {
200 ...emit,
201 revision,
202 serverEpoch,
203 } as PreviewEvent);
204 }
205 const sessions = new Map(state.sessions);
206 sessions.set(compositeKey(threadId, tabId), next);
207 return [{ kind: "ok", result } as ModifyResult, { sessions, revision }] as readonly [
208 ModifyResult,
209 ManagerState,
210 ];
211 }),
212 ),
213 );
214 }).pipe(
215 Effect.flatMap((modify) =>
216 modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
217 ),
218 );
219 };
220​
221 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
222 function* (input) {
223 const tabId = newPreviewTabId();
224 const updatedAt = yield* currentIsoTimestamp;
225 // Clients with a configured default send the viewport up front so the
226 // session is born at the right size; older clients omit it and keep the
227 // historical fill-panel behaviour.
228 const viewport = input.viewport ?? FILL_PREVIEW_VIEWPORT;
229 const snapshot = input.url
230 ? buildLoadingSnapshot({
231 threadId: input.threadId,
232 tabId,
233 url: yield* normalizeUrl(input.url),
234 title: "",
235 viewport,
236 profileId: input.profileId,
237 updatedAt,
238 })
239 : buildIdleSnapshot({
240 threadId: input.threadId,
241 tabId,
242 viewport,
243 profileId: input.profileId,
244 updatedAt,
245 });
246 yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
247 Effect.gen(function* () {
248 const revision = state.revision + 1;
249 const sessions = new Map(state.sessions);
250 sessions.set(compositeKey(input.threadId, tabId), {
251 threadId: input.threadId,
252 tabId,
253 snapshot,
254 });
255 yield* PubSub.publish(eventsPubSub, {
256 type: "opened",
257 threadId: input.threadId,
258 tabId,
259 createdAt: snapshot.updatedAt,
260 serverEpoch,
261 revision,
262 snapshot,
263 });
264 return [snapshot, { sessions, revision }] as const;
265 }),
266 );
267 return snapshot;
268 },
269 );
270​
271 const navigate: PreviewManager["Service"]["navigate"] = Effect.fn("PreviewManager.navigate")(
272 function* (input) {
273 const url = yield* normalizeUrl(input.url);
274 return yield* mutateExistingSession(
275 input.threadId,
276 input.tabId,
277 Effect.fn("PreviewManager.navigateSession")(function* (session) {
278 const updatedAt = yield* currentIsoTimestamp;
279 const previousTitle =
280 session.snapshot.navStatus._tag === "Idle" ? "" : session.snapshot.navStatus.title;
281 const resolvedTitle = input.resolvedTitle ?? previousTitle;
282 const snapshot: PreviewSessionSnapshot = {
283 threadId: session.threadId,
284 tabId: session.tabId,
285 navStatus: { _tag: "Success", url, title: resolvedTitle },
286 canGoBack: session.snapshot.canGoBack,
287 canGoForward: session.snapshot.canGoForward,
288 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
289 ...(session.snapshot.profileId === undefined
290 ? {}
291 : { profileId: session.snapshot.profileId }),
292 updatedAt,
293 };
294 return {
295 next: { ...session, snapshot },
296 emit: {
297 type: "navigated",
298 threadId: session.threadId,
299 tabId: session.tabId,
300 createdAt: snapshot.updatedAt,
301 snapshot,
302 },
303 result: snapshot,
304 };
305 }),
306 );
307 },
308 );
309​
310 const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
311 "PreviewManager.reportStatus",
312 )(function* (input) {
313 yield* mutateExistingSession(
314 input.threadId,
315 input.tabId,
316 Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
317 const updatedAt = yield* currentIsoTimestamp;
318 const snapshot: PreviewSessionSnapshot = {
319 threadId: session.threadId,
320 tabId: session.tabId,
321 navStatus: input.navStatus,
322 canGoBack: input.canGoBack,
323 canGoForward: input.canGoForward,
324 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
325 ...(session.snapshot.profileId === undefined
326 ? {}
327 : { profileId: session.snapshot.profileId }),
328 updatedAt,
329 };
330 const emit: PreviewEventDraft =
331 input.navStatus._tag === "LoadFailed"
332 ? {
333 type: "failed",
334 threadId: session.threadId,
335 tabId: session.tabId,
336 createdAt: snapshot.updatedAt,
337 url: input.navStatus.url,
338 title: input.navStatus.title,
339 code: input.navStatus.code,
340 description: input.navStatus.description,
341 }
342 : {
343 type: "navigated",
344 threadId: session.threadId,
345 tabId: session.tabId,
346 createdAt: snapshot.updatedAt,
347 snapshot,
348 };
349 return {
350 next: { ...session, snapshot },
351 emit,
352 result: undefined as void,
353 };
354 }),
355 );
356 });
357​
358 const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
359 function* (input) {
360 return yield* mutateExistingSession(
361 input.threadId,
362 input.tabId,
363 Effect.fn("PreviewManager.resizeSession")(function* (session) {
364 const updatedAt = yield* currentIsoTimestamp;
365 const snapshot: PreviewSessionSnapshot = {
366 ...session.snapshot,
367 viewport: input.viewport,
368 updatedAt,
369 };
370 return {
371 next: { ...session, snapshot },
372 emit: {
373 type: "resized",
374 threadId: session.threadId,
375 tabId: session.tabId,
376 createdAt: snapshot.updatedAt,
377 snapshot,
378 },
379 result: snapshot,
380 };
381 }),
382 );
383 },
384 );
385​
386 const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
387 function* (input) {
388 // Verify the session exists; the desktop bridge handles the actual reload
389 // and will report progress back via `reportStatus`. No event emitted.
390 yield* mutateExistingSession(input.threadId, input.tabId, (session) =>
391 Effect.succeed({ next: session, emit: null, result: undefined as void }),
392 );
393 },
394 );
395​
396 const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")(
397 function* (input) {
398 const createdAt = yield* currentIsoTimestamp;
399 yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
400 const eventsToEmit: PreviewEvent[] = [];
401 const sessions = new Map(state.sessions);
402 const targets = input.tabId
403 ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
404 (entry): entry is PreviewSessionState => entry !== undefined,
405 )
406 : sessionsForThread(state, input.threadId);
407 let revision = state.revision;
408 for (const target of targets) {
409 revision += 1;
410 sessions.delete(compositeKey(target.threadId, target.tabId));
411 eventsToEmit.push({
412 type: "closed",
413 threadId: target.threadId,
414 tabId: target.tabId,
415 createdAt,
416 serverEpoch,
417 revision,
418 });
419 }
420 if (eventsToEmit.length === 0) {
421 return Effect.succeed([undefined, state] as const);
422 }
423 return Effect.as(
424 Effect.forEach(eventsToEmit, (event) => PubSub.publish(eventsPubSub, event), {
425 discard: true,
426 }),
427 [undefined, { sessions, revision }] as const,
428 );
429 });
430 },
431 );
432​
433 const list: PreviewManager["Service"]["list"] = Effect.fn("PreviewManager.list")(
434 function* (input) {
435 return yield* SynchronizedRef.get(stateRef).pipe(
436 Effect.map((state): PreviewListResult => ({
437 sessions: sessionsForThread(state, input.threadId)
438 .map((s) => s.snapshot)
439 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
440 serverEpoch,
441 revision: state.revision,
442 })),
443 );
444 },
445 );
446​
447 return PreviewManager.of({
448 open,
449 navigate,
450 reportStatus,
451 resize,
452 refresh,
453 close,
454 list,
455 events,
456 subscribeEvents: PubSub.subscribe(eventsPubSub),
457 });
458}).pipe(Effect.withSpan("PreviewManager.make"));
459​
460export const layer = Layer.effect(PreviewManager, make);