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

NodeSocket.ts

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