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

ServerBrowserStream.ts

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