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

DesktopBrowserChannel.ts

213 lines8.3 KB

1// @effect-diagnostics nodeBuiltinImport:off - Bridges Playwright's WebSocket transport to the desktop's fds.
2/** Playwright needs a CDP WebSocket; the secret loopback endpoint relays desktop debugger frames over bootstrap fds. */
3import * as NodeStream from "@effect/platform-node/NodeStream";
4import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer";
5import {
6 DesktopBrowserCommand,
7 DesktopBrowserEvent,
8 type DesktopBrowserCommand as DesktopBrowserCommandType,
9} from "@t3tools/contracts";
10import * as Context from "effect/Context";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as PubSub from "effect/PubSub";
16import * as Queue from "effect/Queue";
17import * as Schema from "effect/Schema";
18import * as Scope from "effect/Scope";
19import * as Semaphore from "effect/Semaphore";
20import * as Stream from "effect/Stream";
21import * as Ndjson from "effect/encoding/Ndjson";
22import * as NodeCrypto from "node:crypto";
23import * as NodeNet from "node:net";
24​
25import * as ServerConfig from "../config.ts";
26import { writeAllToFileDescriptor } from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
27​
28const decodeEvent = Schema.decodeUnknownEffect(DesktopBrowserEvent);
29const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(DesktopBrowserCommand));
30​
31export interface DesktopTabKey {
32 readonly threadId: string;
33 readonly tabId: string;
35​
36const keyOf = ({ threadId, tabId }: DesktopTabKey) => `${threadId}\u0000${tabId}`;
37​
38export class DesktopBrowserChannel extends Context.Service<
39 DesktopBrowserChannel,
40 {
41 readonly available: boolean;
42 /** Subscribe before checking so concurrent attaches cannot be missed. */
43 readonly awaitAttached: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect<boolean>;
44 readonly detached: Stream.Stream<DesktopTabKey>;
45 readonly attached: Stream.Stream<DesktopTabKey>;
46 readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
47 readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
48 readonly pointer: (
49 key: DesktopTabKey,
50 pointer: { readonly phase: "move" | "click"; readonly x: number; readonly y: number },
51 ) => Effect.Effect<void>;
52 }
53>()("t3/preview/DesktopBrowserChannel") {}
54​
55const make = Effect.gen(function* () {
56 const config = yield* ServerConfig.ServerConfig;
57 const inputFd = config.desktopBrowserFd;
58 const controlFd = config.desktopBrowserControlFd;
59 const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
60 const attachedTabs = new Set<string>();
61 const inbound = new Map<string, Queue.Queue<string>>();
62 const writeLock = yield* Semaphore.make(1);
63​
64 if (inputFd === undefined || controlFd === undefined) {
65 return DesktopBrowserChannel.of({
66 available: false,
67 awaitAttached: () => Effect.succeed(false),
68 detached: Stream.empty,
69 attached: Stream.empty,
70 isAttached: () => Effect.succeed(false),
71 endpoint: () => Effect.die("No desktop app is attached to this server."),
72 pointer: () => Effect.void,
73 });
74 }
75​
76 const command = (message: DesktopBrowserCommandType) =>
77 writeLock.withPermits(1)(
78 encodeCommand(message).pipe(
79 Effect.flatMap((line) => writeAllToFileDescriptor(controlFd, Buffer.from(`${line}\n`))),
80 Effect.catchCause((cause) =>
81 Effect.logWarning("desktop browser command failed", { cause }),
82 ),
83 ),
84 );
85​
86 // Use cancellable socket reads; filesystem pipe reads keep Node alive after scope shutdown.
87 const readable = yield* Effect.acquireRelease(
88 Effect.sync(() => new NodeNet.Socket({ fd: inputFd, readable: true, writable: false })),
89 (stream) => Effect.sync(() => stream.destroy()),
90 );
91 yield* NodeStream.fromReadable<Uint8Array, Error>({
92 evaluate: () => readable,
93 closeOnDone: true,
94 onError: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
95 }).pipe(
96 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
97 Stream.mapEffect((value) => decodeEvent(value).pipe(Effect.option)),
98 Stream.runForEach((decoded) => {
99 if (Option.isNone(decoded)) return Effect.void;
100 const event = decoded.value;
101 const key = { threadId: event.threadId, tabId: event.tabId };
102 const id = keyOf(key);
103 switch (event.type) {
104 case "cdp": {
105 const queue = inbound.get(id);
106 return queue ? Queue.offer(queue, event.message).pipe(Effect.asVoid) : Effect.void;
107 }
108 case "attached":
109 attachedTabs.add(id);
110 return PubSub.publish(changes, { key, attached: true });
111 case "detached": {
112 attachedTabs.delete(id);
113 const queue = inbound.get(id);
114 return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
115 Effect.andThen(PubSub.publish(changes, { key, attached: false })),
116 );
117 }
118 }
119 }),
120 Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
121 Effect.forkScoped,
122 );
123​
124 const endpoint = Effect.fn("DesktopBrowserChannel.endpoint")(function* (key: DesktopTabKey) {
125 const id = keyOf(key);
126 const secret = NodeCrypto.randomBytes(24).toString("base64url");
127 const server = yield* NodeSocketServer.makeWebSocket({
128 host: "127.0.0.1",
129 port: 0,
130 path: `/${secret}`,
131 }).pipe(Effect.orDie);
132 const queue = yield* Queue.unbounded<string>();
133 inbound.set(id, queue);
134 // A detach before this registration shut down no queue, so check again.
135 if (!attachedTabs.has(id)) {
136 inbound.delete(id);
137 return yield* Effect.die("The desktop tab detached before the server connected.");
138 }
139 yield* Effect.addFinalizer(() =>
140 Effect.gen(function* () {
141 if (inbound.get(id) === queue) inbound.delete(id);
142 yield* Queue.shutdown(queue);
143 yield* command({ type: "release", ...key });
144 }),
145 );
146 // The relay serves one Playwright connection; a second would see the first's sessions.
147 let connected = false;
148 yield* server
149 .run((socket) =>
150 Effect.gen(function* () {
151 if (connected) return;
152 connected = true;
153 const writer = yield* socket.writer;
154 const reader = yield* socket.reader;
155 yield* Stream.fromQueue(queue).pipe(
156 Stream.runForEach((message) => writer.write(message)),
157 Effect.forkScoped,
158 );
159 const decoder = new TextDecoder();
160 return yield* reader.pull.pipe(
161 Effect.flatMap((frames) =>
162 Effect.forEach(
163 frames,
164 (frame) =>
165 command({
166 type: "cdp",
167 ...key,
168 message: typeof frame === "string" ? frame : decoder.decode(frame),
169 }),
170 { discard: true },
171 ),
172 ),
173 Effect.forever,
174 );
175 }).pipe(Effect.scoped, Effect.ignore),
176 )
177 .pipe(Effect.forkScoped);
178 const address = server.address;
179 if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
180 return `ws://127.0.0.1:${address.port}/${secret}`;
181 });
182​
183 return DesktopBrowserChannel.of({
184 available: true,
185 awaitAttached: (key, timeout) =>
186 Effect.scoped(
187 Effect.gen(function* () {
188 const subscription = yield* PubSub.subscribe(changes);
189 if (attachedTabs.has(keyOf(key))) return true;
190 return yield* Stream.fromSubscription(subscription).pipe(
191 Stream.filter((change) => change.attached && keyOf(change.key) === keyOf(key)),
192 Stream.runHead,
193 Effect.map(Option.isSome),
194 Effect.timeoutOption(timeout),
195 Effect.map((result) => Option.getOrElse(result, () => false)),
196 );
197 }),
198 ),
199 detached: Stream.fromPubSub(changes).pipe(
200 Stream.filter((change) => !change.attached),
201 Stream.map((change) => change.key),
202 ),
203 attached: Stream.fromPubSub(changes).pipe(
204 Stream.filter((change) => change.attached),
205 Stream.map((change) => change.key),
206 ),
207 isAttached: (key) => Effect.sync(() => attachedTabs.has(keyOf(key))),
208 endpoint,
209 pointer: (key, pointer) => command({ type: "pointer", ...key, ...pointer }),
210 });
211});
212​
213export const layer = Layer.effect(DesktopBrowserChannel, make);