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

DenoSocket.ts

410 lines13.3 KB

1/**
2 * Native Deno socket adapters for Effect sockets.
3 *
4 * This module uses Deno-specific names: `makeTcp`, `makeTcpChannel`,
5 * `layerTcp`, and `fromConn` correspond to the Node platform's net and duplex
6 * APIs. Deno does not support `keepAliveInitialDelay`, and the `noDelay` and
7 * `keepAlive` options have no effect on Unix connections. A `CloseEvent` always
8 * closes gracefully because Deno has no equivalent of Node's reset-on-close.
9 *
10 * @stability unstable
11 * @since 4.0.0
12 */
13import * as Arr from "effect/Array"
14import * as Channel from "effect/Channel"
15import * as Context from "effect/Context"
16import type * as Duration from "effect/Duration"
17import * as Effect from "effect/Effect"
18import * as Function from "effect/Function"
19import { constVoid } 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/socket/Socket"
24​
25/**
26 * Options for opening a TCP or Unix connection.
27 *
28 * @stability unstable
29 * @category options
30 * @since 4.0.0
31 */
32export type ConnectOptions = (Deno.ConnectOptions | Deno.UnixConnectOptions) & {
33 readonly noDelay?: boolean | undefined
34 readonly keepAlive?: boolean | undefined
36​
37/**
38 * Options for opening a TCP or Unix connection.
39 *
40 * @stability unstable
41 * @category options
42 * @since 4.0.0
43 */
44export type TcpOptions = ConnectOptions & {
45 readonly openTimeout?: Duration.Input | undefined
47​
48/**
49 * Service tag for the underlying Deno connection.
50 *
51 * @stability unstable
52 * @category services
53 * @since 4.0.0
54 */
55export class Conn extends Context.Service<Conn, Deno.Conn>()(
56 "@effect/platform-deno/DenoSocket/Conn"
57) {}
58​
59/**
60 * Adapts a Deno connection into an Effect socket.
61 *
62 * **Details**
63 *
64 * Readers over TCP connections can upgrade in place with `Deno.startTls`.
65 * Deno exposes only the client side of this transition; Unix connections fail
66 * the upgrade with a `SocketUpgradeError`.
67 * `servername` supplies the TLS hostname; when omitted, the remote address
68 * hostname is used.
69 *
70 * `Deno.startTls` does not support client certificates, so `key`, `cert`,
71 * `passphrase`, and `requestCert` do not affect Deno upgrades. Setting
72 * `rejectUnauthorized` to `false` disables hostname verification only;
73 * certificate-chain validation still applies.
74 *
75 * @stability unstable
76 * @category constructors
77 * @since 4.0.0
78 */
79export const fromConn = <RO>(
80 open: Effect.Effect<Deno.Conn, Socket.SocketError, RO>
81): Effect.Effect<Socket.Socket, never, Exclude<RO, Scope.Scope>> =>
82 Effect.withFiber<Socket.Socket, never, Exclude<RO, Scope.Scope>>((fiber) => {
83 let current: {
84 readonly conn: Deno.Conn
85 readonly writer: WritableStreamDefaultWriter<Uint8Array>
86 readonly fail: (error: Socket.SocketError) => void
87 } | undefined
88 let tearingDown = false
89 let writeClosed = false
90 const latch = Latch.makeUnsafe(false)
91 const openServices = fiber.context as Context.Context<RO>
92​
93 const reader: Socket.Socket["reader"] = Effect.gen(function*() {
94 const scope = yield* Effect.scope
95 let conn: Deno.Conn | undefined
96 let upgradeAvailable = true
97 yield* Scope.addFinalizer(
98 scope,
99 Effect.suspend(() => {
100 tearingDown = true
101 latch.closeUnsafe()
102 current = undefined
103 upgradeAvailable = false
104 return conn === undefined ? Effect.void : close(conn)
105 })
106 )
107 conn = yield* Scope.provide(open, scope)
108 let readerHandle = conn.readable.getReader()
109 let writerHandle = conn.writable.getWriter()
110​
111 let error: Socket.SocketError | undefined
112 const fail = (err: Socket.SocketError) => {
113 if (error === undefined) error = err
114 tearingDown = true
115 readerHandle.cancel().catch(constVoid)
116 }
117 current = {
118 conn,
119 writer: writerHandle,
120 fail
121 }
122 tearingDown = false
123 if (writeClosed) {
124 writeClosed = false
125 writerHandle.releaseLock()
126 yield* closeWrite(conn)
127 }
128 latch.openUnsafe()
129​
130 const read = Effect.tryPromise({
131 try: () => readerHandle.read(),
132 catch: (cause) =>
133 tearingDown && isTeardownError(cause)
134 ? error ?? new Socket.SocketError({
135 reason: new Socket.SocketCloseError({ code: 1000 })
136 })
137 : new Socket.SocketError({
138 reason: new Socket.SocketReadError({ cause })
139 })
140 })
141 const upgrade: Socket.Reader["upgrade"] = (options = {}) =>
142 Effect.suspend(() => {
143 if (!upgradeAvailable) {
144 return Effect.fail(
145 new Socket.SocketError({
146 reason: new Socket.SocketUpgradeError({
147 cause: new Error("socket is already upgraded or closed")
148 })
149 })
150 )
151 }
152 if (conn!.remoteAddr.transport !== "tcp") {
153 return Effect.fail(
154 new Socket.SocketError({
155 reason: new Socket.SocketUpgradeError({
156 cause: new Error("TLS upgrade requires a TCP connection")
157 })
158 })
159 )
160 }
161 upgradeAvailable = false
162 const raw = conn as Deno.TcpConn
163 readerHandle.releaseLock()
164 writerHandle.releaseLock()
165 return Effect.tryPromise({
166 try: async () => {
167 const tls = await Deno.startTls(raw, {
168 hostname: options.servername ?? raw.remoteAddr.hostname,
169 caCerts: options.ca === undefined ? [] : toStrings(options.ca),
170 unsafelyDisableHostnameVerification: options.rejectUnauthorized === false,
171 ...(options.alpnProtocols === undefined ? {} : { alpnProtocols: [...options.alpnProtocols] })
172 })
173 await tls.handshake()
174 return tls
175 },
176 catch: (cause) =>
177 new Socket.SocketError({
178 reason: new Socket.SocketUpgradeError({ cause })
179 })
180 }).pipe(
181 Effect.tap((tls) =>
182 Effect.sync(() => {
183 conn = tls
184 readerHandle = tls.readable.getReader()
185 writerHandle = tls.writable.getWriter()
186 current = { conn: tls, writer: writerHandle, fail }
187 })
188 ),
189 Effect.tapError((upgradeError) => Effect.sync(() => fail(upgradeError))),
190 Effect.asVoid
191 )
192 })
193 return {
194 pull: Effect.suspend(() => {
195 if (error !== undefined) return Effect.fail(error)
196 return Effect.flatMap(read, ({ done, value }) =>
197 done
198 ? Effect.fail(
199 error ?? new Socket.SocketError({
200 reason: new Socket.SocketCloseError({ code: 1000 })
201 })
202 )
203 : Effect.succeed([value] as const))
204 }),
205 upgrade
206 }
207 }).pipe(
208 Effect.updateContext((input: Context.Context<Scope.Scope>) => Context.merge(openServices, input))
209 ) as Socket.Socket["reader"]
210​
211 const write = (chunk: Uint8Array | string | Socket.CloseEvent) =>
212 latch.whenOpen(Effect.suspend(() => {
213 const { conn, fail, writer } = current!
214 if (Socket.isCloseEvent(chunk)) {
215 fail(
216 new Socket.SocketError({
217 reason: new Socket.SocketCloseError({ code: chunk.code, closeReason: chunk.reason })
218 })
219 )
220 return close(conn)
221 }
222 const bytes = typeof chunk === "string" ? encoder.encode(chunk) : chunk
223 return Effect.tryPromise({
224 try: () => writer.ready.then(() => writer.write(bytes)),
225 catch: (cause) =>
226 new Socket.SocketError({
227 reason: new Socket.SocketWriteError({ cause })
228 })
229 })
230 }))
231​
232 const writeAll = (chunks: Arr.NonEmptyReadonlyArray<Uint8Array | string>) =>
233 latch.whenOpen(Effect.tryPromise({
234 try: async () => {
235 const { writer } = current!
236 for (let i = 0; i < chunks.length; i++) {
237 const chunk = chunks[i]
238 const bytes = typeof chunk === "string" ? encoder.encode(chunk) : chunk
239 await writer.ready
240 await writer.write(bytes)
241 }
242 },
243 catch: (cause) =>
244 new Socket.SocketError({
245 reason: new Socket.SocketWriteError({ cause })
246 })
247 }))
248​
249 const writer: Socket.Socket["writer"] = Effect.acquireRelease(
250 Effect.sync(() => {
251 writeClosed = false
252 return { write, writeAll }
253 }),
254 () =>
255 Effect.suspend(() => {
256 if (current === undefined) {
257 writeClosed = true
258 return Effect.void
259 }
260 const { conn, writer } = current
261 writer.releaseLock()
262 return closeWrite(conn)
263 })
264 )
265​
266 return Effect.succeed(Socket.make({ reader, writer }))
267 })
268​
269/**
270 * Opens a native Deno TCP or Unix connection as an Effect socket.
271 *
272 * **Details**
273 *
274 * An `openTimeout` interrupts acquisition but cannot cancel the in-flight
275 * `Deno.connect` promise. The scope finalizer closes a connection that arrives
276 * after the timeout.
277 *
278 * @stability unstable
279 * @category constructors
280 * @since 4.0.0
281 */
282export const makeTcp = (options: TcpOptions): Effect.Effect<Socket.Socket> => {
283 const { keepAlive, noDelay, openTimeout, ...connectOptions } = options
284 const acquire = Effect.contextWith((context: Context.Context<Scope.Scope>) => {
285 let conn: Deno.Conn | undefined
286 let finalized = false
287 return Scope.addFinalizer(
288 Context.get(context, Scope.Scope),
289 Effect.suspend(() => {
290 finalized = true
291 return conn === undefined ? Effect.void : close(conn)
292 })
293 ).pipe(
294 Effect.andThen(Effect.tryPromise({
295 try: () => {
296 const connecting = connectOptions.transport === "unix"
297 ? Deno.connect(connectOptions)
298 : Deno.connect(connectOptions)
299 return connecting.then((connection) => {
300 conn = connection
301 if (finalized) connection.close()
302 return connection
303 })
304 },
305 catch: (cause) =>
306 new Socket.SocketError({
307 reason: new Socket.SocketOpenError({ kind: "Unknown", cause })
308 })
309 })),
310 Effect.tap((connection) =>
311 Effect.sync(() => {
312 if ("setNoDelay" in connection && noDelay !== undefined) {
313 connection.setNoDelay(noDelay)
314 }
315 if ("setKeepAlive" in connection && keepAlive !== undefined) {
316 connection.setKeepAlive(keepAlive)
317 }
318 })
319 )
320 )
321 }).pipe(
322 openTimeout === undefined
323 ? Function.identity
324 : Effect.timeoutOrElse({
325 duration: openTimeout,
326 orElse: () =>
327 Effect.fail(
328 new Socket.SocketError({
329 reason: new Socket.SocketOpenError({ kind: "Timeout", cause: new Error("Connection timed out") })
330 })
331 )
332 })
333 )
334 return fromConn(acquire)
336​
337/**
338 * Creates a channel over a native Deno TCP or Unix connection.
339 *
340 * @stability unstable
341 * @category constructors
342 * @since 4.0.0
343 */
344export const makeTcpChannel = <IE = never>(
345 options: ConnectOptions
346): Channel.Channel<
347 Arr.NonEmptyReadonlyArray<Uint8Array>,
348 Socket.SocketError | IE,
349 void,
350 Arr.NonEmptyReadonlyArray<Uint8Array | string | Socket.CloseEvent>,
351 IE
352> => Channel.unwrap(Effect.map(makeTcp(options), Socket.toChannelWith<IE>()))
353​
354/**
355 * Provides a socket by opening a native Deno TCP or Unix connection.
356 *
357 * @stability unstable
358 * @category layers
359 * @since 4.0.0
360 */
361export const layerTcp: (options: ConnectOptions) => Layer.Layer<
362 Socket.Socket,
363 Socket.SocketError
364> = Function.flow(makeTcp, Layer.effect(Socket.Socket))
365​
366/**
367 * Creates a socket layer connected to a URL with Deno's global WebSocket.
368 *
369 * @stability unstable
370 * @category layers
371 * @since 4.0.0
372 */
373export const layerWebSocket = (url: string, options?: {
374 readonly openTimeout?: Duration.Input | undefined
375 readonly protocols?: string | globalThis.Array<string> | undefined
376 readonly highWaterMark?: number | undefined
377}): Layer.Layer<Socket.Socket> =>
378 Layer.effect(Socket.Socket, Socket.makeWebSocket(url, options)).pipe(
379 Layer.provide(layerWebSocketConstructor)
380 )
381​
382/**
383 * Provides the WebSocket constructor backed by `globalThis.WebSocket`.
384 *
385 * @stability unstable
386 * @category layers
387 * @since 4.0.0
388 */
389export const layerWebSocketConstructor: Layer.Layer<Socket.WebSocketConstructor> =
390 Socket.layerWebSocketConstructorGlobal
391​
392const encoder = new TextEncoder()
393const decoder = new TextDecoder()
394​
395const toStrings = (values: string | Uint8Array | ReadonlyArray<string | Uint8Array>): Array<string> =>
396 Arr.map(Arr.ensure(values), (value) => typeof value === "string" ? value : decoder.decode(value))
397​
398const isBadResource = (cause: unknown): cause is Deno.errors.BadResource => cause instanceof Deno.errors.BadResource
399​
400const isTeardownError = (cause: unknown): boolean => cause instanceof Deno.errors.Interrupted || isBadResource(cause)
401​
402const close = (conn: Deno.Conn): Effect.Effect<void> =>
403 Effect.try(() => conn.close()).pipe(
404 Effect.catch(({ cause }) => isBadResource(cause) ? Effect.void : Effect.die(cause))
405 )
406​
407const closeWrite = (conn: Deno.Conn): Effect.Effect<void> =>
408 Effect.tryPromise(() => conn.closeWrite()).pipe(
409 Effect.catch(({ cause }) => isBadResource(cause) ? Effect.void : Effect.die(cause))
410 )