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

Manager.ts

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