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

Manager.ts

493 lines16.6 KB

1import {
2 type PreviewCloseInput,
3 type PreviewEvent,
4 type PreviewError,
5 PreviewInvalidUrlError,
6 type PreviewListInput,
7 type PreviewListResult,
8 type PreviewOpenInput,
9 type PreviewReportStatusInput,
10 type PreviewResizeInput,
11 type PreviewAdjustInput,
12 FILL_PREVIEW_VIEWPORT,
13 PreviewSessionLookupError,
14 type PreviewSessionSnapshot,
15} from "@t3tools/contracts";
16import {
17 isPreviewUrlNormalizationError,
18 newPreviewTabId,
19 normalizePreviewUrl,
20} from "@t3tools/shared/preview";
21import * as Context from "effect/Context";
22import * as SecureRandom from "effect/crypto/SecureRandom";
23import * as DateTime from "effect/DateTime";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as PubSub from "effect/PubSub";
27import * as Scope from "effect/Scope";
28import * as Stream from "effect/Stream";
29import * as SynchronizedRef from "effect/SynchronizedRef";
30import { PreviewControlRequiredError } from "@t3tools/contracts";
31​
32export class PreviewManager extends Context.Service<
33 PreviewManager,
34 {
35 readonly open: (
36 input: PreviewOpenInput & {
37 readonly automationOwner?: string;
38 /** Runs before the `opened` event publishes, so subscribers find state keyed by the tab. */
39 readonly beforePublish?: (snapshot: PreviewSessionSnapshot) => void;
40 },
41 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
42 readonly reportStatus: (
43 input: PreviewReportStatusInput & { readonly serverControlled?: boolean },
44 ) => Effect.Effect<void, PreviewError>;
45 /** Records that a server tab runs headless. It stays headless until it closes. */
46 readonly markHeadless: (
47 input: PreviewCloseInput & { readonly tabId: string },
48 ) => Effect.Effect<void, PreviewError>;
49 /** Publishes the tab's unchanged snapshot again, for clients that dropped the tab. */
50 readonly announce: (
51 input: PreviewCloseInput & { readonly tabId: string },
52 ) => Effect.Effect<void, PreviewError>;
53 readonly requestReveal: (
54 input: PreviewCloseInput & { readonly tabId: string; readonly force: boolean },
55 ) => Effect.Effect<void, PreviewError>;
56 readonly resize: (
57 input: PreviewResizeInput,
58 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
59 readonly adjust: (
60 input: PreviewAdjustInput,
61 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
62 readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
63 readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
64 readonly events: Stream.Stream<PreviewEvent>;
65 readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
66 }
67>()("t3/preview/Manager/PreviewManager") {}
68​
69interface PreviewSessionState {
70 readonly threadId: string;
71 readonly tabId: string;
72 readonly snapshot: PreviewSessionSnapshot;
74​
75interface ManagerState {
76 readonly sessions: ReadonlyMap<string, PreviewSessionState>;
77 readonly revision: number;
79​
80const initialState: ManagerState = { sessions: new Map(), revision: 0 };
81​
82type PreviewEventDraft = PreviewEvent extends infer Event
83 ? Event extends { readonly revision: number }
84 ? Omit<Event, "revision" | "serverEpoch">
85 : never
86 : never;
87​
88const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
89​
90const sessionsForThread = (
91 state: ManagerState,
92 threadId: string,
93): ReadonlyArray<PreviewSessionState> => {
94 const out: PreviewSessionState[] = [];
95 for (const session of state.sessions.values()) {
96 if (session.threadId === threadId) out.push(session);
97 }
98 return out;
99};
100​
101const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
102 Effect.try({
103 try: () => normalizePreviewUrl(rawUrl),
104 catch: (cause) => {
105 if (isPreviewUrlNormalizationError(cause)) {
106 return new PreviewInvalidUrlError({
107 inputLength: cause.inputLength,
108 reason: cause.reason,
109 protocol: cause.protocol,
110 cause,
111 });
112 }
113​
114 return new PreviewInvalidUrlError({
115 inputLength: rawUrl.length,
116 reason: "unexpected",
117 cause,
118 });
119 },
120 });
121​
122const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
123​
124/** @public */
125export const make = Effect.gen(function* PreviewManagerMake() {
126 const random = yield* SecureRandom.SecureRandom;
127 const serverEpoch = yield* random.uuidV4();
128 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
129 const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
130 const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
131​
132 /** Publish inside the lock to preserve state-transition order. */
133 const mutateExistingSession = <R, E>(
134 threadId: string,
135 tabId: string,
136 mutator: (
137 session: PreviewSessionState,
138 ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEventDraft | null; result: R }, E>,
139 ): Effect.Effect<R, E | PreviewSessionLookupError> => {
140 type ModifyResult =
141 | { kind: "fail"; error: PreviewSessionLookupError }
142 | { kind: "ok"; result: R };
143​
144 return SynchronizedRef.modifyEffect(stateRef, (state) => {
145 const session = state.sessions.get(compositeKey(threadId, tabId));
146 if (!session) {
147 return Effect.succeed([
148 { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
149 state,
150 ] as readonly [ModifyResult, ManagerState]);
151 }
152 return mutator(session).pipe(
153 Effect.flatMap(
154 Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
155 const revision = emit ? state.revision + 1 : state.revision;
156 if (emit) {
157 yield* PubSub.publish(eventsPubSub, {
158 ...emit,
159 revision,
160 serverEpoch,
161 } as PreviewEvent);
162 }
163 const sessions = new Map(state.sessions);
164 sessions.set(compositeKey(threadId, tabId), next);
165 return [{ kind: "ok", result } as ModifyResult, { sessions, revision }] as readonly [
166 ModifyResult,
167 ManagerState,
168 ];
169 }),
170 ),
171 );
172 }).pipe(
173 Effect.flatMap((modify) =>
174 modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
175 ),
176 );
177 };
178​
179 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
180 function* (input) {
181 const runtime = input.runtime;
182 // Persisted client surfaces must not bind to a different tab after a server restart.
183 const tabId = `${newPreviewTabId()}${runtime === "server" ? `_${serverEpoch}` : ""}`;
184 const updatedAt = yield* currentIsoTimestamp;
185 const snapshot: PreviewSessionSnapshot = {
186 threadId: input.threadId,
187 tabId,
188 navStatus: input.url
189 ? { _tag: "Loading", url: yield* normalizeUrl(input.url), title: "" }
190 : { _tag: "Idle" },
191 canGoBack: false,
192 canGoForward: false,
193 viewport: input.viewport ?? FILL_PREVIEW_VIEWPORT,
194 ...(input.profileId === undefined ? {} : { profileId: input.profileId }),
195 ...(runtime === undefined ? {} : { runtime }),
196 ...(input.colorScheme === undefined ? {} : { colorScheme: input.colorScheme }),
197 ...(input.zoomFactor === undefined ? {} : { zoomFactor: input.zoomFactor }),
198 ...(runtime === "server" && input.automationOwner !== undefined
199 ? { automationOwner: input.automationOwner }
200 : {}),
201 ...(input.reveal === undefined ? {} : { reveal: input.reveal }),
202 updatedAt,
203 };
204 yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
205 Effect.gen(function* () {
206 const revision = state.revision + 1;
207 const sessions = new Map(state.sessions);
208 sessions.set(compositeKey(input.threadId, tabId), {
209 threadId: input.threadId,
210 tabId,
211 snapshot,
212 });
213 input.beforePublish?.(snapshot);
214 yield* PubSub.publish(eventsPubSub, {
215 type: "opened",
216 threadId: input.threadId,
217 tabId,
218 createdAt: snapshot.updatedAt,
219 serverEpoch,
220 revision,
221 snapshot,
222 });
223 return [snapshot, { sessions, revision }] as const;
224 }),
225 );
226 return snapshot;
227 },
228 );
229​
230 const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
231 "PreviewManager.reportStatus",
232 )(function* (input) {
233 yield* mutateExistingSession(
234 input.threadId,
235 input.tabId,
236 Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
237 if (session.snapshot.runtime === "server" && !input.serverControlled)
238 return yield* new PreviewControlRequiredError({ tabId: input.tabId });
239 const updatedAt = yield* currentIsoTimestamp;
240 const snapshot: PreviewSessionSnapshot = {
241 ...session.snapshot,
242 navStatus: input.navStatus,
243 canGoBack: input.canGoBack,
244 canGoForward: input.canGoForward,
245 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
246 updatedAt,
247 };
248 const emit: PreviewEventDraft =
249 input.navStatus._tag === "LoadFailed"
250 ? {
251 type: "failed",
252 threadId: session.threadId,
253 tabId: session.tabId,
254 createdAt: snapshot.updatedAt,
255 url: input.navStatus.url,
256 title: input.navStatus.title,
257 code: input.navStatus.code,
258 description: input.navStatus.description,
259 ...(input.navStatus.download === undefined
260 ? {}
261 : { download: input.navStatus.download }),
262 }
263 : {
264 type: "navigated",
265 threadId: session.threadId,
266 tabId: session.tabId,
267 createdAt: snapshot.updatedAt,
268 snapshot,
269 };
270 return {
271 next: { ...session, snapshot },
272 emit,
273 result: undefined as void,
274 };
275 }),
276 );
277 });
278​
279 const markHeadless: PreviewManager["Service"]["markHeadless"] = Effect.fn(
280 "PreviewManager.markHeadless",
281 )(function* (input) {
282 return yield* mutateExistingSession(
283 input.threadId,
284 input.tabId,
285 Effect.fn("PreviewManager.markSessionHeadless")(function* (session) {
286 if (session.snapshot.headless) return { next: session, emit: null, result: undefined };
287 const snapshot: PreviewSessionSnapshot = {
288 ...session.snapshot,
289 headless: true,
290 updatedAt: yield* currentIsoTimestamp,
291 };
292 return {
293 next: { ...session, snapshot },
294 emit: {
295 type: "resized",
296 threadId: session.threadId,
297 tabId: session.tabId,
298 createdAt: snapshot.updatedAt,
299 snapshot,
300 },
301 result: undefined,
302 };
303 }),
304 );
305 });
306​
307 const announce: PreviewManager["Service"]["announce"] = Effect.fn("PreviewManager.announce")(
308 function* (input) {
309 return yield* mutateExistingSession(
310 input.threadId,
311 input.tabId,
312 Effect.fn("PreviewManager.announceSession")(function* (session) {
313 return {
314 next: session,
315 emit: {
316 type: "resized",
317 threadId: session.threadId,
318 tabId: session.tabId,
319 createdAt: yield* currentIsoTimestamp,
320 snapshot: session.snapshot,
321 },
322 result: undefined,
323 };
324 }),
325 );
326 },
327 );
328​
329 const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
330 function* (input) {
331 return yield* mutateExistingSession(
332 input.threadId,
333 input.tabId,
334 Effect.fn("PreviewManager.resizeSession")(function* (session) {
335 const updatedAt = yield* currentIsoTimestamp;
336 const snapshot: PreviewSessionSnapshot = {
337 ...session.snapshot,
338 viewport: input.viewport,
339 updatedAt,
340 };
341 return {
342 next: { ...session, snapshot },
343 emit: {
344 type: "resized",
345 threadId: session.threadId,
346 tabId: session.tabId,
347 createdAt: snapshot.updatedAt,
348 snapshot,
349 },
350 result: snapshot,
351 };
352 }),
353 );
354 },
355 );
356​
357 const adjust: PreviewManager["Service"]["adjust"] = Effect.fn("PreviewManager.adjust")(
358 function* (input) {
359 return yield* mutateExistingSession(
360 input.threadId,
361 input.tabId,
362 Effect.fn("PreviewManager.adjustSession")(function* (session) {
363 const updatedAt = yield* currentIsoTimestamp;
364 const snapshot: PreviewSessionSnapshot = {
365 ...session.snapshot,
366 ...(input.colorScheme === undefined ? {} : { colorScheme: input.colorScheme }),
367 ...(input.zoomFactor === undefined ? {} : { zoomFactor: input.zoomFactor }),
368 updatedAt,
369 };
370 const request =
371 input.hardReload || input.clear
372 ? {
373 request: {
374 ...(input.hardReload ? { hardReload: true } : {}),
375 ...(input.clear ? { clear: input.clear } : {}),
376 },
377 }
378 : {};
379 return {
380 next: { ...session, snapshot },
381 emit: {
382 ...request,
383 type: "resized",
384 threadId: session.threadId,
385 tabId: session.tabId,
386 createdAt: snapshot.updatedAt,
387 snapshot,
388 },
389 result: snapshot,
390 };
391 }),
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 const requestReveal: PreviewManager["Service"]["requestReveal"] = Effect.fn(
448 "PreviewManager.requestReveal",
449 )(function* (input) {
450 yield* mutateExistingSession(
451 input.threadId,
452 input.tabId,
453 Effect.fn("PreviewManager.revealSession")(function* (session) {
454 const snapshot = {
455 ...session.snapshot,
456 reveal: true,
457 revealRequest: {
458 id: yield* random.uuidV4(),
459 force: input.force,
460 },
461 updatedAt: yield* currentIsoTimestamp,
462 };
463 return {
464 next: { ...session, snapshot },
465 emit: {
466 type: "navigated" as const,
467 threadId: session.threadId,
468 tabId: session.tabId,
469 createdAt: snapshot.updatedAt,
470 snapshot,
471 },
472 result: undefined,
473 };
474 }),
475 );
476 });
477​
478 return PreviewManager.of({
479 open,
480 requestReveal,
481 reportStatus,
482 markHeadless,
483 announce,
484 resize,
485 adjust,
486 close,
487 list,
488 events,
489 subscribeEvents: PubSub.subscribe(eventsPubSub),
490 });
491}).pipe(Effect.withSpan("PreviewManager.make"));
492​
493export const layer = Layer.effect(PreviewManager, make);