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

Manager.ts

464 lines15.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 readonly requestReveal: (
50 input: PreviewCloseInput & { readonly tabId: string; readonly force: boolean },
51 ) => Effect.Effect<void, PreviewError>;
52 readonly resize: (
53 input: PreviewResizeInput,
54 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
55 readonly adjust: (
56 input: PreviewAdjustInput,
57 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
58 readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
59 readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
60 readonly events: Stream.Stream<PreviewEvent>;
61 readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
62 }
63>()("t3/preview/Manager/PreviewManager") {}
64​
65interface PreviewSessionState {
66 readonly threadId: string;
67 readonly tabId: string;
68 readonly snapshot: PreviewSessionSnapshot;
70​
71interface ManagerState {
72 readonly sessions: ReadonlyMap<string, PreviewSessionState>;
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​
120/** @public */
121export const make = Effect.gen(function* PreviewManagerMake() {
122 const random = yield* SecureRandom.SecureRandom;
123 const serverEpoch = yield* random.uuidV4();
124 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
125 const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
126 const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
127​
128 /** Publish inside the lock to preserve state-transition order. */
129 const mutateExistingSession = <R, E>(
130 threadId: string,
131 tabId: string,
132 mutator: (
133 session: PreviewSessionState,
134 ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEventDraft | null; result: R }, E>,
135 ): Effect.Effect<R, E | PreviewSessionLookupError> => {
136 type ModifyResult =
137 | { kind: "fail"; error: PreviewSessionLookupError }
138 | { kind: "ok"; result: R };
139​
140 return SynchronizedRef.modifyEffect(stateRef, (state) => {
141 const session = state.sessions.get(compositeKey(threadId, tabId));
142 if (!session) {
143 return Effect.succeed([
144 { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
145 state,
146 ] as readonly [ModifyResult, ManagerState]);
147 }
148 return mutator(session).pipe(
149 Effect.flatMap(
150 Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
151 const revision = emit ? state.revision + 1 : state.revision;
152 if (emit) {
153 yield* PubSub.publish(eventsPubSub, {
154 ...emit,
155 revision,
156 serverEpoch,
157 } as PreviewEvent);
158 }
159 const sessions = new Map(state.sessions);
160 sessions.set(compositeKey(threadId, tabId), next);
161 return [{ kind: "ok", result } as ModifyResult, { sessions, revision }] as readonly [
162 ModifyResult,
163 ManagerState,
164 ];
165 }),
166 ),
167 );
168 }).pipe(
169 Effect.flatMap((modify) =>
170 modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
171 ),
172 );
173 };
174​
175 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
176 function* (input) {
177 const runtime = input.runtime;
178 // Persisted client surfaces must not bind to a different tab after a server restart.
179 const tabId = `${newPreviewTabId()}${runtime === "server" ? `_${serverEpoch}` : ""}`;
180 const updatedAt = yield* currentIsoTimestamp;
181 const snapshot: PreviewSessionSnapshot = {
182 threadId: input.threadId,
183 tabId,
184 navStatus: input.url
185 ? { _tag: "Loading", url: yield* normalizeUrl(input.url), title: "" }
186 : { _tag: "Idle" },
187 canGoBack: false,
188 canGoForward: false,
189 viewport: input.viewport ?? FILL_PREVIEW_VIEWPORT,
190 ...(input.profileId === undefined ? {} : { profileId: input.profileId }),
191 ...(runtime === undefined ? {} : { runtime }),
192 ...(runtime === "server" && input.automationOwner !== undefined
193 ? { automationOwner: input.automationOwner }
194 : {}),
195 ...(input.reveal === undefined ? {} : { reveal: input.reveal }),
196 updatedAt,
197 };
198 yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
199 Effect.gen(function* () {
200 const revision = state.revision + 1;
201 const sessions = new Map(state.sessions);
202 sessions.set(compositeKey(input.threadId, tabId), {
203 threadId: input.threadId,
204 tabId,
205 snapshot,
206 });
207 input.beforePublish?.(snapshot);
208 yield* PubSub.publish(eventsPubSub, {
209 type: "opened",
210 threadId: input.threadId,
211 tabId,
212 createdAt: snapshot.updatedAt,
213 serverEpoch,
214 revision,
215 snapshot,
216 });
217 return [snapshot, { sessions, revision }] as const;
218 }),
219 );
220 return snapshot;
221 },
222 );
223​
224 const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
225 "PreviewManager.reportStatus",
226 )(function* (input) {
227 yield* mutateExistingSession(
228 input.threadId,
229 input.tabId,
230 Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
231 if (session.snapshot.runtime === "server" && !input.serverControlled)
232 return yield* new PreviewControlRequiredError({ tabId: input.tabId });
233 const updatedAt = yield* currentIsoTimestamp;
234 const snapshot: PreviewSessionSnapshot = {
235 ...session.snapshot,
236 navStatus: input.navStatus,
237 canGoBack: input.canGoBack,
238 canGoForward: input.canGoForward,
239 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
240 updatedAt,
241 };
242 const emit: PreviewEventDraft =
243 input.navStatus._tag === "LoadFailed"
244 ? {
245 type: "failed",
246 threadId: session.threadId,
247 tabId: session.tabId,
248 createdAt: snapshot.updatedAt,
249 url: input.navStatus.url,
250 title: input.navStatus.title,
251 code: input.navStatus.code,
252 description: input.navStatus.description,
253 ...(input.navStatus.download === undefined
254 ? {}
255 : { download: input.navStatus.download }),
256 }
257 : {
258 type: "navigated",
259 threadId: session.threadId,
260 tabId: session.tabId,
261 createdAt: snapshot.updatedAt,
262 snapshot,
263 };
264 return {
265 next: { ...session, snapshot },
266 emit,
267 result: undefined as void,
268 };
269 }),
270 );
271 });
272​
273 const markHeadless: PreviewManager["Service"]["markHeadless"] = Effect.fn(
274 "PreviewManager.markHeadless",
275 )(function* (input) {
276 return yield* mutateExistingSession(
277 input.threadId,
278 input.tabId,
279 Effect.fn("PreviewManager.markSessionHeadless")(function* (session) {
280 if (session.snapshot.headless) return { next: session, emit: null, result: undefined };
281 const snapshot: PreviewSessionSnapshot = {
282 ...session.snapshot,
283 headless: true,
284 updatedAt: yield* currentIsoTimestamp,
285 };
286 return {
287 next: { ...session, snapshot },
288 emit: {
289 type: "resized",
290 threadId: session.threadId,
291 tabId: session.tabId,
292 createdAt: snapshot.updatedAt,
293 snapshot,
294 },
295 result: undefined,
296 };
297 }),
298 );
299 });
300​
301 const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
302 function* (input) {
303 return yield* mutateExistingSession(
304 input.threadId,
305 input.tabId,
306 Effect.fn("PreviewManager.resizeSession")(function* (session) {
307 const updatedAt = yield* currentIsoTimestamp;
308 const snapshot: PreviewSessionSnapshot = {
309 ...session.snapshot,
310 viewport: input.viewport,
311 updatedAt,
312 };
313 return {
314 next: { ...session, snapshot },
315 emit: {
316 type: "resized",
317 threadId: session.threadId,
318 tabId: session.tabId,
319 createdAt: snapshot.updatedAt,
320 snapshot,
321 },
322 result: snapshot,
323 };
324 }),
325 );
326 },
327 );
328​
329 const adjust: PreviewManager["Service"]["adjust"] = Effect.fn("PreviewManager.adjust")(
330 function* (input) {
331 return yield* mutateExistingSession(
332 input.threadId,
333 input.tabId,
334 Effect.fn("PreviewManager.adjustSession")(function* (session) {
335 const updatedAt = yield* currentIsoTimestamp;
336 const snapshot: PreviewSessionSnapshot = {
337 ...session.snapshot,
338 ...(input.colorScheme === undefined ? {} : { colorScheme: input.colorScheme }),
339 ...(input.zoomFactor === undefined ? {} : { zoomFactor: input.zoomFactor }),
340 updatedAt,
341 };
342 const request =
343 input.hardReload || input.clear
344 ? {
345 request: {
346 ...(input.hardReload ? { hardReload: true } : {}),
347 ...(input.clear ? { clear: input.clear } : {}),
348 },
349 }
350 : {};
351 return {
352 next: { ...session, snapshot },
353 emit: {
354 ...request,
355 type: "resized",
356 threadId: session.threadId,
357 tabId: session.tabId,
358 createdAt: snapshot.updatedAt,
359 snapshot,
360 },
361 result: snapshot,
362 };
363 }),
364 );
365 },
366 );
367​
368 const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")(
369 function* (input) {
370 const createdAt = yield* currentIsoTimestamp;
371 yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
372 const eventsToEmit: PreviewEvent[] = [];
373 const sessions = new Map(state.sessions);
374 const targets = input.tabId
375 ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
376 (entry): entry is PreviewSessionState => entry !== undefined,
377 )
378 : sessionsForThread(state, input.threadId);
379 let revision = state.revision;
380 for (const target of targets) {
381 revision += 1;
382 sessions.delete(compositeKey(target.threadId, target.tabId));
383 eventsToEmit.push({
384 type: "closed",
385 threadId: target.threadId,
386 tabId: target.tabId,
387 createdAt,
388 serverEpoch,
389 revision,
390 });
391 }
392 if (eventsToEmit.length === 0) {
393 return Effect.succeed([undefined, state] as const);
394 }
395 return Effect.as(
396 Effect.forEach(eventsToEmit, (event) => PubSub.publish(eventsPubSub, event), {
397 discard: true,
398 }),
399 [undefined, { sessions, revision }] as const,
400 );
401 });
402 },
403 );
404​
405 const list: PreviewManager["Service"]["list"] = Effect.fn("PreviewManager.list")(
406 function* (input) {
407 return yield* SynchronizedRef.get(stateRef).pipe(
408 Effect.map((state): PreviewListResult => ({
409 sessions: sessionsForThread(state, input.threadId)
410 .map((s) => s.snapshot)
411 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
412 serverEpoch,
413 revision: state.revision,
414 })),
415 );
416 },
417 );
418​
419 const requestReveal: PreviewManager["Service"]["requestReveal"] = Effect.fn(
420 "PreviewManager.requestReveal",
421 )(function* (input) {
422 yield* mutateExistingSession(
423 input.threadId,
424 input.tabId,
425 Effect.fn("PreviewManager.revealSession")(function* (session) {
426 const snapshot = {
427 ...session.snapshot,
428 reveal: true,
429 revealRequest: {
430 id: yield* random.uuidV4(),
431 force: input.force,
432 },
433 updatedAt: yield* currentIsoTimestamp,
434 };
435 return {
436 next: { ...session, snapshot },
437 emit: {
438 type: "navigated" as const,
439 threadId: session.threadId,
440 tabId: session.tabId,
441 createdAt: snapshot.updatedAt,
442 snapshot,
443 },
444 result: undefined,
445 };
446 }),
447 );
448 });
449​
450 return PreviewManager.of({
451 open,
452 requestReveal,
453 reportStatus,
454 markHeadless,
455 resize,
456 adjust,
457 close,
458 list,
459 events,
460 subscribeEvents: PubSub.subscribe(eventsPubSub),
461 });
462}).pipe(Effect.withSpan("PreviewManager.make"));
463​
464export const layer = Layer.effect(PreviewManager, make);