The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Node socket server adapters for Effect's unstable socket server API. |
| 3 | * |
| 4 | * This module turns `node:net` TCP or Unix-domain servers, `node:tls` servers, |
| 5 | * and `ws` WebSocket servers into scoped `SocketServer.SocketServer` services. |
| 6 | * Use the TCP and TLS constructors when handlers should receive a |
| 7 | * `Socket.Socket` backed by a Node `net.Socket`; use the WebSocket |
| 8 | * constructors when handlers should receive a `Socket.Socket` backed by `ws` |
| 9 | * and have access to the per-connection WebSocket and `IncomingMessage` |
| 10 | * services. |
| 11 | * |
| 12 | * @stability unstable |
| 13 | * @since 4.0.0 |
| 14 | */ |
| 15 | import * as Context from "effect/Context" |
| 16 | import * as Deferred from "effect/Deferred" |
| 17 | import * as Effect from "effect/Effect" |
| 18 | import * as Exit from "effect/Exit" |
| 19 | import * as Fiber from "effect/Fiber" |
| 20 | import { pipe } from "effect/Function" |
| 21 | import * as Function from "effect/Function" |
| 22 | import * as Layer from "effect/Layer" |
| 23 | import * as NetAddress from "effect/net/NetAddress" |
| 24 | import * as Scope from "effect/Scope" |
| 25 | import * as Socket from "effect/socket/Socket" |
| 26 | import * as SocketServer from "effect/socket/SocketServer" |
| 27 | import type * as Http from "node:http" |
| 28 | import * as Net from "node:net" |
| 29 | import * as Tls from "node:tls" |
| 30 | import * as NodeSocket from "./NodeSocket.ts" |
| 31 | import * as NodeWS from "./NodeWS.ts" |
| 32 | |
| 33 | const isDeno = "Deno" in globalThis |
| 34 | |
| 35 | const socketAddressFromNode = ( |
| 36 | address: string | Net.AddressInfo |
| 37 | ): Effect.Effect<NetAddress.SocketAddress, SocketServer.SocketServerError> => |
| 38 | typeof address === "string" |
| 39 | ? Effect.succeed(NetAddress.unixPathAddress(address)) |
| 40 | : Effect.fromResult(NetAddress.inetAddressFromIpString(address.address, address.port)).pipe( |
| 41 | Effect.mapError((cause) => |
| 42 | new SocketServer.SocketServerError({ |
| 43 | reason: new SocketServer.SocketServerOpenError({ cause }) |
| 44 | }) |
| 45 | ) |
| 46 | ) |
| 47 | |
| 48 | /** |
| 49 | * Service tag for the Node `IncomingMessage` associated with the current |
| 50 | * WebSocket server connection. |
| 51 | * |
| 52 | * @stability unstable |
| 53 | * @category services |
| 54 | * @since 4.0.0 |
| 55 | */ |
| 56 | export class IncomingMessage extends Context.Service< |
| 57 | IncomingMessage, |
| 58 | Http.IncomingMessage |
| 59 | >()("@effect/platform-node-shared/NodeSocketServer/IncomingMessage") {} |
| 60 | |
| 61 | /** |
| 62 | * Creates a scoped TCP `SocketServer` from a Node `net.Server`, starts |
| 63 | * listening with the supplied options, queues pending connections until `run` |
| 64 | * is called, and closes the server when the scope ends. |
| 65 | * |
| 66 | * @stability unstable |
| 67 | * @category constructors |
| 68 | * @since 4.0.0 |
| 69 | */ |
| 70 | export const make = ( |
| 71 | options: Net.ServerOpts & Net.ListenOptions |
| 72 | ): Effect.Effect< |
| 73 | SocketServer.SocketServer["Service"], |
| 74 | SocketServer.SocketServerError, |
| 75 | Scope.Scope |
| 76 | > => |
| 77 | makeNetServer({ |
| 78 | listenOptions: options, |
| 79 | connectionEvent: "connection", |
| 80 | createServer: () => Net.createServer(options) |
| 81 | }) |
| 82 | |
| 83 | /** |
| 84 | * Provides a TCP `SocketServer` by creating and managing a scoped Node |
| 85 | * `net.Server` with the supplied server and listen options. |
| 86 | * |
| 87 | * @stability unstable |
| 88 | * @category layers |
| 89 | * @since 4.0.0 |
| 90 | */ |
| 91 | export const layer: ( |
| 92 | options: Net.ServerOpts & Net.ListenOptions |
| 93 | ) => Layer.Layer< |
| 94 | SocketServer.SocketServer, |
| 95 | SocketServer.SocketServerError |
| 96 | > = Function.flow(make, Layer.effect(SocketServer.SocketServer)) |
| 97 | |
| 98 | /** |
| 99 | * Creates a scoped TLS `SocketServer` from a Node `tls.Server`, starts |
| 100 | * listening with the supplied options, queues pending connections until `run` |
| 101 | * is called, and closes the server when the scope ends. |
| 102 | * |
| 103 | * **Details** |
| 104 | * |
| 105 | * Connections reach `run` only once their handshake has completed, and the |
| 106 | * handler receives a `Socket.Socket` backed by the `tls.TLSSocket`, which is |
| 107 | * also provided as `NodeSocket.NetSocket`. Connections that fail the handshake |
| 108 | * are destroyed and the server keeps listening. |
| 109 | * |
| 110 | * @stability unstable |
| 111 | * @category constructors |
| 112 | * @since 4.0.0 |
| 113 | */ |
| 114 | export const makeTls = ( |
| 115 | options: Tls.TlsOptions & Net.ListenOptions |
| 116 | ): Effect.Effect< |
| 117 | SocketServer.SocketServer["Service"], |
| 118 | SocketServer.SocketServerError, |
| 119 | Scope.Scope |
| 120 | > => |
| 121 | makeNetServer({ |
| 122 | listenOptions: options, |
| 123 | connectionEvent: "secureConnection", |
| 124 | createServer: () => { |
| 125 | const server = Tls.createServer(options) |
| 126 | server.on("tlsClientError", (_error, socket) => { |
| 127 | socket.destroy() |
| 128 | }) |
| 129 | return server |
| 130 | } |
| 131 | }) |
| 132 | |
| 133 | /** |
| 134 | * Provides a TLS `SocketServer` by creating and managing a scoped Node |
| 135 | * `tls.Server` with the supplied TLS and listen options. |
| 136 | * |
| 137 | * @stability unstable |
| 138 | * @category layers |
| 139 | * @since 4.0.0 |
| 140 | */ |
| 141 | export const layerTls: ( |
| 142 | options: Tls.TlsOptions & Net.ListenOptions |
| 143 | ) => Layer.Layer< |
| 144 | SocketServer.SocketServer, |
| 145 | SocketServer.SocketServerError |
| 146 | > = Function.flow(makeTls, Layer.effect(SocketServer.SocketServer)) |
| 147 | |
| 148 | /** |
| 149 | * Creates a scoped WebSocket `SocketServer` backed by the `ws` package, |
| 150 | * providing the WebSocket and its Node `IncomingMessage` to connection |
| 151 | * handlers and closing the server when the scope ends. |
| 152 | * |
| 153 | * @stability unstable |
| 154 | * @category constructors |
| 155 | * @since 4.0.0 |
| 156 | */ |
| 157 | export const makeWebSocket: ( |
| 158 | options: NodeWS.ServerOptions<typeof NodeWS.WebSocket, typeof Http.IncomingMessage> |
| 159 | ) => Effect.Effect< |
| 160 | SocketServer.SocketServer["Service"], |
| 161 | SocketServer.SocketServerError, |
| 162 | Scope.Scope |
| 163 | > = Effect.fnUntraced(function*( |
| 164 | options: NodeWS.ServerOptions |
| 165 | ) { |
| 166 | const pendingConnections = new Map< |
| 167 | NodeWS.WebSocket, |
| 168 | readonly [request: Http.IncomingMessage, remove: () => void] |
| 169 | >() |
| 170 | const server = yield* Effect.acquireRelease( |
| 171 | Effect.sync(() => new NodeWS.WebSocketServer(options)), |
| 172 | (server) => |
| 173 | Effect.callback<void>((resume) => { |
| 174 | pendingConnections.forEach(([, remove], conn) => { |
| 175 | remove() |
| 176 | conn.terminate() |
| 177 | }) |
| 178 | server.close(() => resume(Effect.void)) |
| 179 | }) |
| 180 | ) |
| 181 | function defaultHandler(conn: NodeWS.WebSocket, req: Http.IncomingMessage) { |
| 182 | const remove = () => { |
| 183 | pendingConnections.delete(conn) |
| 184 | conn.removeEventListener("close", remove) |
| 185 | } |
| 186 | pendingConnections.set(conn, [req, remove]) |
| 187 | conn.addEventListener("close", remove) |
| 188 | } |
| 189 | let onConnection = defaultHandler |
| 190 | server.on("connection", (conn, req) => { |
| 191 | // pause immediately so nothing is dropped before a handler acquires the |
| 192 | // socket's reader |
| 193 | conn.pause() |
| 194 | onConnection(conn, req as Http.IncomingMessage) |
| 195 | }) |
| 196 | |
| 197 | yield* Effect.callback<void, SocketServer.SocketServerError>((resume) => { |
| 198 | server.once("error", (error) => { |
| 199 | resume(Effect.fail( |
| 200 | new SocketServer.SocketServerError({ |
| 201 | reason: new SocketServer.SocketServerOpenError({ |
| 202 | cause: error |
| 203 | }) |
| 204 | }) |
| 205 | )) |
| 206 | }) |
| 207 | server.once("listening", () => { |
| 208 | resume(Effect.void) |
| 209 | }) |
| 210 | }) |
| 211 | |
| 212 | const run = Effect.fnUntraced(function*<R, E, _>(handler: (socket: Socket.Socket) => Effect.Effect<_, E, R>) { |
| 213 | const scope = yield* Scope.make() |
| 214 | const services = Context.omit(Scope.Scope)(yield* Effect.context<R>()) as Context.Context<R> |
| 215 | const trackFiber = Fiber.runIn(scope) |
| 216 | const prevOnConnection = onConnection |
| 217 | onConnection = function(conn: NodeWS.WebSocket, req: Http.IncomingMessage) { |
| 218 | let context = services |
| 219 | context = Context.add(context, IncomingMessage, req) |
| 220 | context = Context.add(context, Socket.WebSocket, conn) |
| 221 | pipe( |
| 222 | Socket.fromWebSocket( |
| 223 | Effect.acquireRelease( |
| 224 | Effect.succeed(conn), |
| 225 | (conn) => |
| 226 | Effect.sync(() => { |
| 227 | conn.close() |
| 228 | }) |
| 229 | ) |
| 230 | ), |
| 231 | Effect.flatMap(handler), |
| 232 | Effect.ignoreCause({ log: "Unhandled", message: "Unhandled error in SocketServer" }), |
| 233 | Effect.runForkWith(context), |
| 234 | trackFiber |
| 235 | ) |
| 236 | } |
| 237 | pendingConnections.forEach(([req, remove], conn) => { |
| 238 | remove() |
| 239 | onConnection(conn, req) |
| 240 | }) |
| 241 | return yield* Effect.callback<never>((_resume) => { |
| 242 | return Effect.sync(() => { |
| 243 | onConnection = prevOnConnection |
| 244 | }) |
| 245 | }).pipe( |
| 246 | Effect.ensuring(Scope.close(scope, Exit.void)) |
| 247 | ) |
| 248 | }) |
| 249 | |
| 250 | const boundAddress = yield* socketAddressFromNode(server.address()!) |
| 251 | return SocketServer.SocketServer.of({ |
| 252 | address: boundAddress, |
| 253 | run |
| 254 | }) |
| 255 | }) |
| 256 | |
| 257 | /** |
| 258 | * Provides a WebSocket `SocketServer` backed by the `ws` package and managed |
| 259 | * with the supplied server options. |
| 260 | * |
| 261 | * @stability unstable |
| 262 | * @category layers |
| 263 | * @since 4.0.0 |
| 264 | */ |
| 265 | export const layerWebSocket: ( |
| 266 | options: NodeWS.ServerOptions<typeof NodeWS.WebSocket, typeof Http.IncomingMessage> |
| 267 | ) => Layer.Layer< |
| 268 | SocketServer.SocketServer, |
| 269 | SocketServer.SocketServerError |
| 270 | > = Function.flow(makeWebSocket, Layer.effect(SocketServer.SocketServer)) |
| 271 | |
| 272 | const makeNetServer = Effect.fnUntraced(function*(options: { |
| 273 | readonly createServer: () => Net.Server |
| 274 | readonly connectionEvent: "connection" | "secureConnection" |
| 275 | readonly listenOptions: Net.ListenOptions |
| 276 | }) { |
| 277 | const errorDeferred = Deferred.makeUnsafe<never, Error>() |
| 278 | const pending = new Map<Net.Socket, () => void>() |
| 279 | function defaultOnConnection(conn: Net.Socket) { |
| 280 | const remove = () => { |
| 281 | pending.delete(conn) |
| 282 | conn.off("close", remove) |
| 283 | conn.off("error", remove) |
| 284 | } |
| 285 | pending.set(conn, remove) |
| 286 | conn.on("close", remove) |
| 287 | conn.on("error", remove) |
| 288 | } |
| 289 | let onConnection = defaultOnConnection |
| 290 | // oxlint-disable-next-line prefer-const |
| 291 | let server: Net.Server | undefined |
| 292 | yield* Effect.addFinalizer(() => |
| 293 | Effect.callback<void>((resume) => { |
| 294 | pending.forEach((remove, conn) => { |
| 295 | remove() |
| 296 | conn.destroy() |
| 297 | }) |
| 298 | server?.close(() => resume(Effect.void)) |
| 299 | }) |
| 300 | ) |
| 301 | server = options.createServer() |
| 302 | server.on(options.connectionEvent, (conn: Net.Socket) => { |
| 303 | // pause immediately so nothing is dropped before a handler acquires the |
| 304 | // socket's reader. Deno's node:net compatibility layer leaves the socket |
| 305 | // non-flowing but breaks `readable` events after an explicit pause. |
| 306 | if (!isDeno) conn.pause() |
| 307 | onConnection(conn) |
| 308 | }) |
| 309 | server.on("error", (err) => Deferred.doneUnsafe(errorDeferred, Exit.fail(err))) |
| 310 | |
| 311 | yield* Effect.callback<void, SocketServer.SocketServerError>((resume) => { |
| 312 | server.listen(options.listenOptions, () => resume(Effect.void)) |
| 313 | }).pipe( |
| 314 | Effect.raceFirst(Effect.mapError(Deferred.await(errorDeferred), (err) => |
| 315 | new SocketServer.SocketServerError({ |
| 316 | reason: new SocketServer.SocketServerOpenError({ |
| 317 | cause: err |
| 318 | }) |
| 319 | }))) |
| 320 | ) |
| 321 | |
| 322 | const run = Effect.fnUntraced(function*<R, E, _>(handler: (socket: Socket.Socket) => Effect.Effect<_, E, R>) { |
| 323 | const scope = yield* Scope.make() |
| 324 | const services = Context.omit(Scope.Scope)(yield* Effect.context<R>()) as Context.Context<R> |
| 325 | const trackFiber = Fiber.runIn(scope) |
| 326 | const prevOnConnection = onConnection |
| 327 | onConnection = function(conn: Net.Socket) { |
| 328 | let error: Error | undefined |
| 329 | conn.on("error", (err) => { |
| 330 | error = err |
| 331 | }) |
| 332 | pipe( |
| 333 | NodeSocket.fromDuplex( |
| 334 | Effect.acquireRelease( |
| 335 | Effect.suspend((): Effect.Effect<Net.Socket, Socket.SocketError> => { |
| 336 | if (error) { |
| 337 | return Effect.fail( |
| 338 | new Socket.SocketError({ |
| 339 | reason: new Socket.SocketOpenError({ |
| 340 | kind: "Unknown", |
| 341 | cause: error |
| 342 | }) |
| 343 | }) |
| 344 | ) |
| 345 | } else if (conn.closed) { |
| 346 | return Effect.fail( |
| 347 | new Socket.SocketError({ |
| 348 | reason: new Socket.SocketCloseError({ code: 1000 }) |
| 349 | }) |
| 350 | ) |
| 351 | } |
| 352 | return Effect.succeed(conn) |
| 353 | }), |
| 354 | (conn) => |
| 355 | Effect.sync(() => { |
| 356 | if (conn.closed === false) { |
| 357 | conn.destroySoon() |
| 358 | } |
| 359 | }) |
| 360 | ), |
| 361 | { tlsServer: true } |
| 362 | ), |
| 363 | Effect.flatMap(handler), |
| 364 | Effect.ignoreCause({ log: "Unhandled", message: "Unhandled error in SocketServer" }), |
| 365 | Effect.runForkWith(Context.add(services, NodeSocket.NetSocket, conn)), |
| 366 | trackFiber |
| 367 | ) |
| 368 | } |
| 369 | pending.forEach((remove, conn) => { |
| 370 | remove() |
| 371 | onConnection(conn) |
| 372 | }) |
| 373 | return yield* Effect.callback<never>((_resume) => { |
| 374 | return Effect.suspend(() => { |
| 375 | onConnection = prevOnConnection |
| 376 | return Scope.close(scope, Exit.void) |
| 377 | }) |
| 378 | }) |
| 379 | }) |
| 380 | |
| 381 | const boundAddress = yield* socketAddressFromNode(server.address()!) |
| 382 | return SocketServer.SocketServer.of({ |
| 383 | address: boundAddress, |
| 384 | run |
| 385 | }) |
| 386 | }) |