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

ServerBrowserStream.ts

347 lines14.5 KB

1import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest";
2import {
3 AuthOrchestrationReadScope,
4 AuthPreviewOperateScope,
5 PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
6 PreviewStreamHostSetup,
7} from "@t3tools/contracts";
8import * as Clock from "effect/Clock";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Schema from "effect/Schema";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import {
16 HttpPlatform,
17 HttpRouter,
18 HttpServerRequest,
19 HttpServerResponse,
20 Multipart,
21} from "effect/http";
22import * as Socket from "effect/socket/Socket";
23​
24import { authenticateMediaRequest, failEnvironmentInternal } from "../auth/http.ts";
25import * as SessionStore from "../auth/SessionStore.ts";
26import { assetResponseHeaders } from "../http.ts";
27import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";
28import { makePreviewFrameWindow } from "./PreviewFrameWindow.ts";
29import * as ServerBrowser from "./ServerBrowser.ts";
30import { requestUrl } from "../requestUrl.ts";
31​
32const PREVIEW_STREAM_ROUTE_PREFIX = "/api/preview-stream";
33const TAB_GONE_CODE = 4404;
34​
35const DEFAULT_QUALITY = 70;
36const MAX_SOCKET_BUFFER_BYTES = 8 * 1024 * 1024;
37const LATENCY_PROBE = new Uint8Array(0);
38const textDecoder = new TextDecoder();
39​
40const intParam = (params: URLSearchParams, name: string, fallback: number, max: number) => {
41 const value = Number(params.get(name));
42 return Number.isFinite(value) && value > 0 ? Math.min(Math.round(value), max) : fallback;
43};
44​
45type Frame = Extract<ServerBrowser.ServerBrowserViewerOutput, { readonly _tag: "frame" }>;
46​
47const isAck = (message: unknown) =>
48 typeof message === "object" && message !== null && "type" in message && message.type === "ack";
49​
50const parseMessage = (chunk: Uint8Array | string): unknown => {
51 try {
52 return JSON.parse(typeof chunk === "string" ? chunk : textDecoder.decode(chunk));
53 } catch {
54 return null;
55 }
56};
57​
58// Request middleware owns tracing, including long-lived WebSocket sessions.
59const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBrowser["Service"]) {
60 const request = yield* HttpServerRequest.HttpServerRequest;
61 const url = requestUrl(request);
62 if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 });
63 if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) {
64 return yield* serveDownload(browser, url.value.searchParams);
65 }
66 if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) {
67 return request.method === "POST"
68 ? yield* receiveUpload(browser, url.value.searchParams)
69 : HttpServerResponse.text("Method Not Allowed", { status: 405 });
70 }
71 if (
72 url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` ||
73 request.headers.upgrade?.toLowerCase() !== "websocket"
74 ) {
75 return HttpServerResponse.text("Not Found", { status: 404 });
76 }
77 const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);
78 const params = url.value.searchParams;
79 const canOperate =
80 session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";
81 const threadId = params.get("threadId") ?? "";
82 const tabId = params.get("tabId") ?? "";
83 if (threadId.length === 0 || tabId.length === 0) {
84 return HttpServerResponse.text("Not Found", { status: 404 });
85 }
86 const sessions = yield* SessionStore.SessionStore;
87 const stream = Effect.scoped(
88 Effect.gen(function* () {
89 const attached = yield* browser
90 .attachViewer({
91 threadId,
92 tabId,
93 canOperate,
94 maxWidth: intParam(params, "maxWidth", 1280, 7680),
95 maxHeight: intParam(params, "maxHeight", 800, 4320),
96 quality: intParam(params, "quality", DEFAULT_QUALITY, 100),
97 })
98 .pipe(
99 Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),
100 Effect.catchTags({
101 ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }),
102 ServerBrowserLaunchError: (error) => {
103 const setup = hostSetup(error.cause);
104 return setup === undefined
105 ? Effect.fail(error)
106 : Effect.succeed({ _tag: "hostSetup" as const, setup });
107 },
108 }),
109 );
110 const incoming = NodeHttpServerRequest.toIncomingMessage(request);
111 // JPEGs are already compressed. Disabling deflate also keeps all
112 // pending writes in the socket buffer we bound below, not a zlib queue.
113 delete incoming.headers["sec-websocket-extensions"];
114 const transport = incoming.socket;
115 const socket = yield* request.upgrade;
116 const reader = yield* socket.reader;
117 const writer = yield* socket.writer;
118 // A refused upgrade reads as an auth failure to ticket clients, so a
119 // missing tab is a close code they stop on.
120 const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed"));
121 if (attached._tag === "gone") {
122 yield* gone;
123 return HttpServerResponse.empty();
124 }
125 if (attached._tag === "hostSetup") {
126 yield* writer.write(encodeJson({ type: "hostSetup", ...attached.setup }));
127 yield* writer.write(
128 new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, closeReason(attached.setup)),
129 );
130 return HttpServerResponse.empty();
131 }
132 const viewer = attached.viewer;
133 // `write` returns once the frame is queued, so the viewer's `ack` messages say when
134 // the link is done with it. One frame is on the wire and only the newest waits behind
135 // it, so replies never queue behind stale images on a slow link. Only a link measured
136 // as fast carries several unacked frames.
137 const window = makePreviewFrameWindow();
138 let pending: Frame | null = null;
139 // Chromium's ack for each unacked frame, or null once it has been released.
140 const held: Array<Effect.Effect<void> | null> = [];
141 const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(
142 Effect.andThen(Effect.interrupt),
143 );
144 const writeAll = (messages: Parameters<typeof writer.writeAll>[0]) =>
145 Effect.suspend(() => {
146 let bytes = 0;
147 for (const data of messages) {
148 bytes += (typeof data === "string" ? Buffer.byteLength(data) : data.byteLength) + 14;
149 }
150 if (transport.writableLength + bytes > MAX_SOCKET_BUFFER_BYTES) {
151 return disconnectSlowViewer;
152 }
153 return writer.writeAll(messages);
154 });
155 const write = (data: Uint8Array | string) => writeAll([data]);
156 // Frames are frequent and share the session span.
157 const sendFrame = Effect.fnUntraced(function* (frame: Frame, now: number) {
158 // Viewers ack every binary message and cannot decode an empty one, so it paints
159 // nothing and its ack times the link without an image on it.
160 const probing = window.idle();
161 if (probing) window.sent(now, true);
162 window.sent(now, false);
163 // On a fast link Chromium is released at once: waiting for the viewer would cap
164 // capture at the frames Chromium leaves unacked per round trip.
165 const release = window.fast();
166 held.push(release ? null : frame.ack);
167 // One write, so no other frame can come between the empty message and its image.
168 yield* writeAll(probing ? [LATENCY_PROBE, frame.data] : [frame.data]);
169 if (release) yield* Effect.forkScoped(frame.ack);
170 });
171 const sendOutput = Effect.zip(Queue.take(viewer.output), Clock.currentTimeMillis).pipe(
172 Effect.flatMap(([output, now]) => {
173 switch (output._tag) {
174 case "frame": {
175 // A waiting frame is older, so a newer one replaces it and never follows it.
176 const superseded = pending;
177 const sending = window.canSend(now);
178 pending = sending ? null : output;
179 // Never sent, but Chromium still waits for its ack.
180 return Effect.andThen(
181 superseded ? Effect.forkScoped(superseded.ack) : Effect.void,
182 sending ? sendFrame(output, now) : Effect.void,
183 );
184 }
185 case "viewport":
186 case "control":
187 case "clipboard":
188 case "download":
189 case "fileChooser":
190 case "fileChooserClosed":
191 case "selectMenu":
192 case "selectMenuClosed":
193 case "popup":
194 case "pointer":
195 case "probe": {
196 const { _tag: type, ...data } = output;
197 return write(JSON.stringify({ type, ...data }));
198 }
199 case "gone":
200 return gone.pipe(Effect.andThen(Effect.interrupt));
201 case "reconnect":
202 return writer
203 .write(new Socket.CloseEvent(1012, "reconnect"))
204 .pipe(Effect.andThen(Effect.interrupt));
205 }
206 }),
207 );
208 // Incoming messages share the session span; frame acknowledgements are frequent.
209 const receive = Effect.fnUntraced(function* (chunk: Uint8Array | string) {
210 const message = parseMessage(chunk);
211 // Ownership serializes actions in the service. Keep reading so dialog
212 // replies and takeover can unblock an action already waiting on the page.
213 if (!isAck(message))
214 return yield* canOperate
215 ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
216 : Effect.void;
217 const now = yield* Clock.currentTimeMillis;
218 const ack = window.acked(now) === "frame" ? held.shift() : null;
219 const next = window.canSend(now) ? pending : null;
220 if (next !== null) pending = null;
221 // Forked: Chromium acks are paced and must not hold up input.
222 return yield* Effect.andThen(
223 ack ? Effect.forkScoped(ack) : Effect.void,
224 next ? sendFrame(next, now) : Effect.void,
225 );
226 });
227 const receiveInput = reader.pull.pipe(
228 Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
229 );
230 return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput)).pipe(
231 Effect.onInterrupt(() => Effect.sync(() => transport.destroy())),
232 );
233 }),
234 ).pipe(
235 Effect.catchTags({
236 ServerBrowserLaunchError: (error) =>
237 Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(
238 Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),
239 ),
240 }),
241 Effect.orElseSucceed(() => HttpServerResponse.empty()),
242 );
243 return yield* Effect.raceFirst(
244 stream,
245 sessions.awaitInvalidation(session.sessionId).pipe(
246 Effect.as(HttpServerResponse.empty()),
247 Effect.catchTags({
248 SessionCredentialVerificationError: (error) =>
249 failEnvironmentInternal("internal_error", error),
250 }),
251 ),
252 );
253});
254​
255const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined =>
256 isSandboxError(cause)
257 ? { need: "sandbox", command: cause.setupCommand }
258 : isLibrariesError(cause)
259 ? { need: "libraries", command: cause.setupCommand }
260 : undefined;
261const isSandboxError = Schema.is(PreviewBrowserHost.PreviewBrowserSandboxError);
262const isLibrariesError = Schema.is(PreviewBrowserHost.PreviewBrowserLibrariesError);
263const encodeHostSetup = Schema.encodeSync(Schema.fromJsonString(PreviewStreamHostSetup));
264const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
265// ws throws on a close reason over 123 bytes; the full command goes ahead as a message.
266const closeReason = (setup: PreviewStreamHostSetup) => {
267 const reason = encodeHostSetup(setup);
268 return Buffer.byteLength(reason) <= 123
269 ? reason
270 : encodeHostSetup({ need: setup.need, command: "sudo npx t3 browser setup" });
271};
272​
273// The request span already covers this download route.
274const serveDownload = Effect.fnUntraced(function* (
275 browser: ServerBrowser.ServerBrowser["Service"],
276 params: URLSearchParams,
277) {
278 yield* authenticateMediaRequest(AuthOrchestrationReadScope);
279 const download = yield* browser.openDownload({
280 threadId: params.get("threadId") ?? "",
281 tabId: params.get("tabId") ?? "",
282 downloadId: params.get("id") ?? "",
283 });
284 if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });
285 return yield* HttpServerResponse.file(download.value.path, {
286 headers: assetResponseHeaders(download.value.path, {
287 download: true,
288 fileName: download.value.fileName,
289 }),
290 });
291});
292​
293const UPLOAD_MAX_FILE_BYTES = 100 * 1024 * 1024;
294const UPLOAD_MAX_FILES = 20;
295​
296// The request span already covers this upload route.
297const receiveUpload = Effect.fnUntraced(
298 function* (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) {
299 yield* authenticateMediaRequest(AuthPreviewOperateScope);
300 const request = yield* HttpServerRequest.HttpServerRequest;
301 const fs = yield* FileSystem.FileSystem;
302 const parts = yield* request.multipart.pipe(
303 Effect.provideContext(
304 Multipart.limitsServices({
305 maxParts: UPLOAD_MAX_FILES,
306 maxFileSize: UPLOAD_MAX_FILE_BYTES,
307 maxTotalSize: UPLOAD_MAX_FILE_BYTES,
308 }),
309 ),
310 );
311 const files = yield* Effect.forEach(
312 Object.values(parts).flatMap((value) =>
313 Array.isArray(value) ? value.filter(Multipart.isPersistedFile) : [],
314 ),
315 (file) =>
316 fs.readFile(file.path).pipe(
317 Effect.map((bytes) => ({
318 name: file.name,
319 mimeType: file.contentType,
320 buffer: Buffer.from(bytes),
321 })),
322 ),
323 );
324 const answered = yield* browser.answerFileChooser({
325 threadId: params.get("threadId") ?? "",
326 tabId: params.get("tabId") ?? "",
327 chooserId: params.get("chooser") ?? "",
328 files,
329 });
330 return answered
331 ? HttpServerResponse.empty({ status: 204 })
332 : HttpServerResponse.text("The page's file picker is no longer open.", { status: 409 });
333 },
334 (effect, _browser, _params) => effect.pipe(Effect.scoped),
335);
336​
337export const routeLayer = HttpRouter.use((router) =>
338 Effect.gen(function* () {
339 const browser = yield* ServerBrowser.ServerBrowser;
340 const platform = yield* Effect.context<
341 HttpPlatform.HttpPlatform | FileSystem.FileSystem | Path.Path
342 >();
343 const handler = makeHandler(browser).pipe(Effect.provideContext(platform));
344 yield* router.add("GET", `${PREVIEW_STREAM_ROUTE_PREFIX}/*`, handler);
345 yield* router.add("POST", `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`, handler);
346 }),
347);