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

NodeSocket.ts

286 lines8.8 KB

1/**
2 * Node socket adapters for Effect sockets.
3 *
4 * This module opens `node:net` connections or wraps existing Node `Duplex`
5 * streams and presents them as `Socket.Socket` values, socket channels, or
6 * layers. It is the low-level bridge for TCP clients, Unix domain socket
7 * clients, and protocols that already expose a Node duplex stream.
8 *
9 * **Mental model**
10 *
11 * A socket acquired here is scoped. `makeNet` dials with
12 * `net.createConnection`, `fromDuplex` adapts any duplex returned by an Effect,
13 * `makeNetChannel` exposes the socket as a `Channel`, and `layerNet` provides
14 * it through the Effect environment. While a socket handler is running,
15 * `NetSocket` gives access to the underlying Node `net.Socket` for cases that
16 * need Node-specific operations.
17 *
18 * **Gotchas**
19 *
20 * `openTimeout` only limits opening the connection. Writes complete when Node
21 * accepts or flushes a chunk, close events are translated to `SocketError`
22 * values, and finalizers close or destroy the stream when the surrounding scope
23 * ends. Unix socket paths are supplied through `NetConnectOpts.path`, so use
24 * the same platform path rules as Node.
25 *
26 * @since 4.0.0
27 */
28import type { Array } from "effect"
29import * as Channel from "effect/Channel"
30import * as Context from "effect/Context"
31import * as Deferred from "effect/Deferred"
32import type * as Duration from "effect/Duration"
33import * as Effect from "effect/Effect"
34import * as FiberSet from "effect/FiberSet"
35import * as Function from "effect/Function"
36import { identity } from "effect/Function"
37import * as Latch from "effect/Latch"
38import * as Layer from "effect/Layer"
39import * as Scope from "effect/Scope"
40import * as Socket from "effect/unstable/socket/Socket"
41import * as Net from "node:net"
42import type { Duplex } from "node:stream"
43​
44/**
45 * @category re-exports
46 * @since 4.0.0
47 */
48export * as NodeWS from "ws"
49​
50/**
51 * Service tag for the underlying Node `net.Socket` associated with the current
52 * socket connection.
53 *
54 * @category tags
55 * @since 4.0.0
56 */
57export class NetSocket extends Context.Service<NetSocket, Net.Socket>()(
58 "@effect/platform-node/NodeSocket/NetSocket"
59) {}
60​
61/**
62 * Opens a Node TCP connection as an Effect socket.
63 *
64 * **When to use**
65 *
66 * Use to create a scoped `Socket.Socket` from Node `net.createConnection`.
67 *
68 * **Details**
69 *
70 * Supports `openTimeout` and closes or destroys the underlying socket when the
71 * enclosing scope is finalized.
72 *
73 * @category constructors
74 * @since 4.0.0
75 */
76export const makeNet = (
77 options: Net.NetConnectOpts & {
78 readonly openTimeout?: Duration.Input | undefined
79 }
80): Effect.Effect<Socket.Socket> =>
81 fromDuplex(
82 Effect.contextWith((context: Context.Context<Scope.Scope>) => {
83 let conn: Net.Socket | undefined
84 return Effect.flatMap(
85 Scope.addFinalizer(
86 Context.get(context, Scope.Scope),
87 Effect.sync(() => {
88 if (!conn) return
89 if (conn.closed === false) {
90 if ("destroySoon" in conn) {
91 conn.destroySoon()
92 } else {
93 ;(conn as Net.Socket).destroy()
94 }
95 }
96 })
97 ),
98 () =>
99 Effect.callback<Net.Socket, Socket.SocketError, never>((resume) => {
100 conn = Net.createConnection(options)
101 conn.once("connect", () => {
102 resume(Effect.succeed(conn!))
103 })
104 conn.on("error", (cause: Error) => {
105 resume(Effect.fail(
106 new Socket.SocketError({
107 reason: new Socket.SocketOpenError({ kind: "Unknown", cause })
108 })
109 ))
110 })
111 })
112 )
113 }),
114 options
115 )
116​
117/**
118 * Adapts a Node `Duplex` into a `Socket.Socket`, wiring data events to socket
119 * handlers, providing a scoped writer, and mapping open, read, write, and close
120 * failures to `SocketError`.
121 *
122 * @category constructors
123 * @since 4.0.0
124 */
125export const fromDuplex = <RO>(
126 open: Effect.Effect<Duplex, Socket.SocketError, RO>,
127 options?: {
128 readonly openTimeout?: Duration.Input | undefined
129 }
130): Effect.Effect<Socket.Socket, never, Exclude<RO, Scope.Scope>> =>
131 Effect.withFiber<Socket.Socket, never, Exclude<RO, Scope.Scope>>((fiber) => {
132 let currentSocket: Duplex | undefined
133 const latch = Latch.makeUnsafe(false)
134 const openServices = fiber.context as Context.Context<RO>
135​
136 const run = <R, E, _>(handler: (_: Uint8Array) => Effect.Effect<_, E, R> | void, opts?: {
137 readonly onOpen?: Effect.Effect<void> | undefined
138 }) =>
139 Effect.scopedWith(Effect.fnUntraced(function*(scope) {
140 const fiberSet = yield* FiberSet.make<any, E | Socket.SocketError>().pipe(
141 Scope.provide(scope)
142 )
143 let conn: Duplex | undefined = undefined
144 yield* Scope.addFinalizer(
145 scope,
146 Effect.sync(() => {
147 if (!conn) return
148 conn.off("data", onData)
149 conn.off("end", onEnd)
150 conn.off("error", onError)
151 conn.off("close", onClose)
152 })
153 )
154 conn = yield* Scope.provide(open, scope).pipe(
155 options?.openTimeout ?
156 Effect.timeoutOrElse({
157 duration: options.openTimeout,
158 orElse: () =>
159 Effect.fail(
160 new Socket.SocketError({
161 reason: new Socket.SocketOpenError({ kind: "Timeout", cause: new Error("Connection timed out") })
162 })
163 )
164 }) :
165 identity
166 )
167 conn.on("end", onEnd)
168 conn.on("error", onError)
169 conn.on("close", onClose)
170 const run = yield* Effect.provideService(FiberSet.runtime(fiberSet)<R>(), NetSocket, conn as Net.Socket)
171 conn.on("data", onData)
172​
173 currentSocket = conn
174 latch.openUnsafe()
175 if (opts?.onOpen) {
176 yield* opts.onOpen
177 }
178​
179 return yield* FiberSet.join(fiberSet)
180​
181 function onData(chunk: Uint8Array) {
182 const result = handler(chunk)
183 if (Effect.isEffect(result)) {
184 run(result)
185 }
186 }
187 function onEnd() {
188 Deferred.doneUnsafe(fiberSet.deferred, Effect.void)
189 }
190 function onError(cause: Error) {
191 Deferred.doneUnsafe(
192 fiberSet.deferred,
193 Effect.fail(
194 new Socket.SocketError({
195 reason: new Socket.SocketReadError({ cause })
196 })
197 )
198 )
199 }
200 function onClose(hadError: boolean) {
201 Deferred.doneUnsafe(
202 fiberSet.deferred,
203 Effect.fail(
204 new Socket.SocketError({
205 reason: new Socket.SocketCloseError({ code: hadError ? 1006 : 1000 })
206 })
207 )
208 )
209 }
210 })).pipe(
211 Effect.updateContext((input: Context.Context<R>) => Context.merge(openServices, input)),
212 Effect.onExit(() =>
213 Effect.sync(() => {
214 latch.closeUnsafe()
215 currentSocket = undefined
216 })
217 )
218 )
219​
220 const write = (chunk: Uint8Array | string | Socket.CloseEvent) =>
221 latch.whenOpen(Effect.callback<void, Socket.SocketError>((resume) => {
222 const conn = currentSocket!
223 if (Socket.isCloseEvent(chunk)) {
224 conn.destroy(chunk.code > 1000 ? new Error(`closed with code ${chunk.code}`) : undefined)
225 return resume(Effect.void)
226 }
227 currentSocket!.write(chunk, (cause) => {
228 resume(
229 cause
230 ? Effect.fail(
231 new Socket.SocketError({
232 reason: new Socket.SocketWriteError({ cause: cause! })
233 })
234 )
235 : Effect.void
236 )
237 })
238 }))
239​
240 const writer = Effect.acquireRelease(
241 Effect.succeed(write),
242 () =>
243 Effect.sync(() => {
244 if (!currentSocket || currentSocket.writableEnded) return
245 currentSocket.end()
246 })
247 )
248​
249 return Effect.succeed(Socket.make({
250 run,
251 runRaw: run,
252 writer
253 }))
254 })
255​
256/**
257 * Creates a `Channel` over a TCP socket, reading arrays of `Uint8Array`
258 * chunks and writing arrays of bytes, strings, or socket close events.
259 *
260 * @category constructors
261 * @since 4.0.0
262 */
263export const makeNetChannel = <IE = never>(
264 options: Net.NetConnectOpts
265): Channel.Channel<
266 Array.NonEmptyReadonlyArray<Uint8Array>,
267 Socket.SocketError | IE,
268 void,
269 Array.NonEmptyReadonlyArray<Uint8Array | string | Socket.CloseEvent>,
270 IE
271> =>
272 Channel.unwrap(
273 Effect.map(makeNet(options), Socket.toChannelWith<IE>())
274 )
275​
276/**
277 * Provides a `Socket.Socket` by opening a TCP connection with the supplied
278 * Node `net` connection options.
279 *
280 * @category layers
281 * @since 4.0.0
282 */
283export const layerNet: (options: Net.NetConnectOpts) => Layer.Layer<
284 Socket.Socket,
285 Socket.SocketError
286> = Function.flow(makeNet, Layer.effect(Socket.Socket))