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

ServerBrowserStream.ts

277 lines11.3 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";
29/** Matches `PREVIEW_STREAM_TAB_GONE_CODE` in the client. */
30const TAB_GONE_CODE = 4404;
31​
32const DEFAULT_QUALITY = 70;
33const MAX_SOCKET_BUFFER_BYTES = 8 * 1024 * 1024;
34const MAX_UNACKNOWLEDGED_FRAMES = 64;
35const textDecoder = new TextDecoder();
36​
37const intParam = (params: URLSearchParams, name: string, fallback: number, max: number) => {
38 const value = Number(params.get(name));
39 return Number.isFinite(value) && value > 0 ? Math.min(Math.round(value), max) : fallback;
40};
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​
53const makeHandler = (browser: ServerBrowser.ServerBrowser["Service"]) =>
54 Effect.gen(function* () {
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.
128 const unacknowledged: Array<Effect.Effect<void>> = [];
129 const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(
130 Effect.andThen(Effect.interrupt),
131 );
132 const write = (data: Uint8Array | string) =>
133 Effect.suspend(() => {
134 const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
135 if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) {
136 return disconnectSlowViewer;
137 }
138 return writer.write(data);
139 });
140 const sendOutput = Queue.take(viewer.output).pipe(
141 Effect.flatMap((output) => {
142 switch (output._tag) {
143 case "frame":
144 if (unacknowledged.length >= MAX_UNACKNOWLEDGED_FRAMES) {
145 return disconnectSlowViewer;
146 }
147 return write(output.data).pipe(
148 Effect.andThen(Effect.sync(() => unacknowledged.push(output.ack))),
149 );
150 case "viewport":
151 case "control":
152 case "clipboard":
153 case "download":
154 case "fileChooser":
155 case "fileChooserClosed":
156 case "popup":
157 case "pointer":
158 case "probe": {
159 const { _tag: type, ...data } = output;
160 return write(JSON.stringify({ type, ...data }));
161 }
162 case "gone":
163 return gone.pipe(Effect.andThen(Effect.interrupt));
164 case "reconnect":
165 return writer
166 .write(new Socket.CloseEvent(1012, "reconnect"))
167 .pipe(Effect.andThen(Effect.interrupt));
168 }
169 }),
170 );
171 const receive = (chunk: Uint8Array | string) => {
172 const message = parseMessage(chunk);
173 // Ownership serializes actions in the service. Keep reading so dialog
174 // replies and takeover can unblock an action already waiting on the page.
175 if (!isAck(message))
176 return canOperate
177 ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
178 : Effect.void;
179 const ack = unacknowledged.shift();
180 // Forked: Chromium acks are paced and must not hold up input.
181 return ack ? Effect.forkScoped(ack).pipe(Effect.asVoid) : Effect.void;
182 };
183 const receiveInput = reader.pull.pipe(
184 Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
185 );
186 return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput));
187 }),
188 ).pipe(
189 Effect.catchTags({
190 ServerBrowserLaunchError: (error) =>
191 Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(
192 Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),
193 ),
194 }),
195 Effect.catch(() => Effect.succeed(HttpServerResponse.empty())),
196 );
197 });
198​
199const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined =>
200 isSandboxError(cause)
201 ? { need: "sandbox", command: cause.setupCommand }
202 : isLibrariesError(cause)
203 ? { need: "libraries", command: cause.setupCommand }
204 : undefined;
205const isSandboxError = Schema.is(PreviewBrowserHost.PreviewBrowserSandboxError);
206const isLibrariesError = Schema.is(PreviewBrowserHost.PreviewBrowserLibrariesError);
207const encodeHostSetup = Schema.encodeSync(Schema.fromJsonString(PreviewStreamHostSetup));
208​
209const serveDownload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>
210 Effect.gen(function* () {
211 yield* authenticateMediaRequest(AuthOrchestrationReadScope);
212 const download = yield* browser.openDownload({
213 threadId: params.get("threadId") ?? "",
214 tabId: params.get("tabId") ?? "",
215 downloadId: params.get("id") ?? "",
216 });
217 if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });
218 return yield* HttpServerResponse.file(download.value.path, {
219 headers: assetResponseHeaders(download.value.path, {
220 download: true,
221 fileName: download.value.fileName,
222 }),
223 });
224 });
225​
226const UPLOAD_MAX_FILE_BYTES = 100 * 1024 * 1024;
227const UPLOAD_MAX_FILES = 20;
228​
229const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>
230 Effect.gen(function* () {
231 yield* authenticateMediaRequest(AuthPreviewOperateScope);
232 const request = yield* HttpServerRequest.HttpServerRequest;
233 const fs = yield* FileSystem.FileSystem;
234 const parts = yield* request.multipart.pipe(
235 Effect.provideContext(
236 Multipart.limitsServices({
237 maxParts: UPLOAD_MAX_FILES,
238 maxFileSize: UPLOAD_MAX_FILE_BYTES,
239 maxTotalSize: UPLOAD_MAX_FILE_BYTES,
240 }),
241 ),
242 );
243 const files = yield* Effect.forEach(
244 Object.values(parts).flatMap((value) =>
245 Array.isArray(value) ? value.filter(Multipart.isPersistedFile) : [],
246 ),
247 (file) =>
248 fs.readFile(file.path).pipe(
249 Effect.map((bytes) => ({
250 name: file.name,
251 mimeType: file.contentType,
252 buffer: Buffer.from(bytes),
253 })),
254 ),
255 );
256 const answered = yield* browser.answerFileChooser({
257 threadId: params.get("threadId") ?? "",
258 tabId: params.get("tabId") ?? "",
259 chooserId: params.get("chooser") ?? "",
260 files,
261 });
262 return answered
263 ? HttpServerResponse.empty({ status: 204 })
264 : HttpServerResponse.text("The page's file picker is no longer open.", { status: 409 });
265 }).pipe(Effect.scoped);
266​
267export const routeLayer = HttpRouter.use((router) =>
268 Effect.gen(function* () {
269 const browser = yield* ServerBrowser.ServerBrowser;
270 const platform = yield* Effect.context<
271 HttpPlatform.HttpPlatform | FileSystem.FileSystem | Path.Path
272 >();
273 const handler = makeHandler(browser).pipe(Effect.provideContext(platform));
274 yield* router.add("GET", `${PREVIEW_STREAM_ROUTE_PREFIX}/*`, handler);
275 yield* router.add("POST", `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`, handler);
276 }),
277);