@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 649 lines 21 KB
Raw
1 /**
2 * Node socket adapters for Effect sockets.
3 *
4 * This module opens `node:net` or `node:tls` connections, or wraps existing
5 * Node `Duplex` streams, and presents them as `Socket.Socket` values, socket
6 * channels, or layers. It also exposes the `NetSocket` service tag for the
7 * underlying Node socket.
8 *
9 * @stability unstable
10 * @since 4.0.0
11 */
12 import * as Arr from "effect/Array"
13 import * as Channel from "effect/Channel"
14 import * as Context from "effect/Context"
15 import type * as Duration from "effect/Duration"
16 import * as Effect from "effect/Effect"
17 import * as Function from "effect/Function"
18 import { identity } from "effect/Function"
19 import * as Latch from "effect/Latch"
20 import * as Layer from "effect/Layer"
21 import * as Redacted from "effect/Redacted"
22 import * as Scope from "effect/Scope"
23 import * as Socket from "effect/socket/Socket"
24 import { Buffer } from "node:buffer"
25 import * as Net from "node:net"
26 import type { Duplex } from "node:stream"
27 import * as Tls from "node:tls"
28
29 const isDeno = "Deno" in globalThis
30
31 /**
32 * Service tag for the underlying Node `net.Socket` associated with the current
33 * socket connection.
34 *
35 * @stability unstable
36 * @category services
37 * @since 4.0.0
38 */
39 export class NetSocket extends Context.Service<NetSocket, Net.Socket>()(
40 "@effect/platform-node/NodeSocket/NetSocket"
41 ) {}
42
43 const readAvailable = (
44 conn: Duplex,
45 chunkSize: number
46 ): Arr.NonEmptyReadonlyArray<Uint8Array | string> | undefined => {
47 const first = conn.read() as Uint8Array | string | null
48 if (first === null) return undefined
49 const out: [Uint8Array | string, ...Array<Uint8Array | string>] = [first]
50 let chunk: Uint8Array | string | null
51 // read() may synchronously refill the buffer; leave further reads to the next pull.
52 while (out.length < chunkSize && (chunk = conn.read() as Uint8Array | string | null) !== null) {
53 out.push(chunk)
54 }
55 return out
56 }
57
58 const toBuffers = (input: string | Uint8Array | ReadonlyArray<string | Uint8Array>): Array<Buffer> =>
59 Arr.map(Arr.ensure(input), (value) => Buffer.from(value))
60
61 const closeSocket = (conn: Net.Socket, isOpen: boolean) => {
62 if (conn.closed !== false) return
63 if (!isOpen || !("destroySoon" in conn)) {
64 conn.destroy()
65 } else {
66 conn.destroySoon()
67 }
68 }
69
70 /**
71 * Opens a Node TCP connection as an Effect socket.
72 *
73 * **When to use**
74 *
75 * Use to create a `Socket.Socket` whose reader acquisition dials
76 * `net.createConnection`.
77 *
78 * **Details**
79 *
80 * Supports `openTimeout` and closes or destroys the underlying socket when the
81 * reader scope is finalized.
82 *
83 * @stability unstable
84 * @category constructors
85 * @since 4.0.0
86 */
87 export const makeNet = (
88 options: Net.NetConnectOpts & {
89 readonly openTimeout?: Duration.Input | undefined
90 /**
91 * Maximum chunks per pull. Defaults to 4096 unless a positive safe integer or Infinity is supplied.
92 * Use Infinity for unbounded batching.
93 */
94 readonly chunkSize?: number | undefined
95 }
96 ): Effect.Effect<Socket.Socket> =>
97 fromDuplex(
98 Effect.contextWith((context: Context.Context<Scope.Scope>) => {
99 let conn: Net.Socket | undefined
100 let isOpen = false
101 return Effect.flatMap(
102 Scope.addFinalizer(
103 Context.get(context, Scope.Scope),
104 Effect.sync(() => {
105 if (!conn) return
106 closeSocket(conn, isOpen)
107 })
108 ),
109 () =>
110 Effect.callback<Net.Socket, Socket.SocketError, never>((resume) => {
111 conn = Net.createConnection(options)
112 conn.once("connect", () => {
113 isOpen = true
114 resume(Effect.succeed(conn!))
115 })
116 conn.on("error", (cause: Error) => {
117 resume(Effect.fail(
118 new Socket.SocketError({
119 reason: new Socket.SocketOpenError({ kind: "Unknown", cause })
120 })
121 ))
122 })
123 })
124 )
125 }),
126 options
127 )
128
129 /**
130 * Adapts a Node `Duplex` into a `Socket.Socket`.
131 *
132 * **Details**
133 *
134 * Reader acquisition opens the duplex and keeps it paused: each pull reads at
135 * most `chunkSize` chunks (default 4096) with `stream.read()`. On Node 26+ that
136 * yields each buffered chunk as a separate batch element with no copy. Earlier Node
137 * concatenates the buffer into one chunk. The stream is never resumed, so once
138 * Node's buffer reaches its `highWaterMark` the kernel receive window closes
139 * and the peer blocks: backpressure is end-to-end with no buffering above
140 * Node's own.
141 *
142 * Writes use `write()` return-value backpressure, awaiting one `drain` when
143 * the internal buffer is full. `writeAll` corks the stream around the batch.
144 * Releasing the writer scope half-closes the stream (`end()`).
145 *
146 * @stability unstable
147 * @category constructors
148 * @since 4.0.0
149 */
150 export const fromDuplex = <RO>(
151 open: Effect.Effect<Duplex, Socket.SocketError, RO>,
152 options?: {
153 readonly openTimeout?: Duration.Input | undefined
154 /**
155 * Maximum chunks per pull. Defaults to 4096 unless a positive safe integer or Infinity is supplied.
156 * Use Infinity for unbounded batching.
157 */
158 readonly chunkSize?: number | undefined
159 readonly tlsServer?: boolean | undefined
160 }
161 ): Effect.Effect<Socket.Socket, never, Exclude<RO, Scope.Scope>> =>
162 Effect.withFiber<Socket.Socket, never, Exclude<RO, Scope.Scope>>((fiber) => {
163 let currentSocket: Duplex | undefined
164 const latch = Latch.makeUnsafe(false)
165 const openServices = fiber.context as Context.Context<RO>
166 const isServer = options?.tlsServer === true
167 const requestedChunkSize = options?.chunkSize ?? 4096
168 const chunkSize = requestedChunkSize === Infinity ||
169 (Number.isSafeInteger(requestedChunkSize) && requestedChunkSize > 0)
170 ? requestedChunkSize
171 : 4096
172 const secureEvent = isServer ? "secure" : "secureConnect"
173
174 const reader: Socket.Socket["reader"] = Effect.gen(function*() {
175 const scope = yield* Effect.scope
176 let conn = yield* Scope.provide(open, scope).pipe(
177 options?.openTimeout !== undefined ?
178 Effect.timeoutOrElse({
179 duration: options.openTimeout,
180 orElse: () =>
181 Effect.fail(
182 new Socket.SocketError({
183 reason: new Socket.SocketOpenError({ kind: "Timeout", cause: new Error("Connection timed out") })
184 })
185 )
186 }) :
187 identity
188 )
189
190 type ReadResume = (
191 effect: Effect.Effect<Arr.NonEmptyReadonlyArray<Uint8Array | string>, Socket.SocketError>
192 ) => void
193
194 let error: Socket.SocketError | undefined
195 let waiter: ReadResume | undefined
196 // Bytes consumed by read() while the parked pull was interrupted.
197 let pending: Arr.NonEmptyReadonlyArray<Uint8Array | string> | undefined
198 let reading = false
199 let closed = false
200 let upgradeAvailable = true
201
202 // The only place a waiter is resumed, so delivery order has one owner:
203 // retained bytes first, then freshly read bytes, then the error.
204 function drain() {
205 if (waiter === undefined || reading) return
206 let chunk = pending
207 pending = undefined
208 if (chunk === undefined && !closed) {
209 // A data listener can interrupt and replace the pull synchronously.
210 // The replacement must wait for this read to preserve byte order.
211 reading = true
212 try {
213 chunk = readAvailable(conn, chunkSize)
214 } finally {
215 reading = false
216 }
217 }
218 // A close during read() discards the bytes it consumed.
219 if (closed) chunk = undefined
220 if (waiter === undefined) {
221 pending = chunk
222 return
223 }
224 const result = chunk !== undefined
225 ? Effect.succeed(chunk)
226 : error !== undefined
227 ? Effect.fail(error)
228 : undefined
229 if (result === undefined) return
230 const resume = waiter
231 waiter = undefined
232 resume(result)
233 }
234 // Normal EOF: already consumed bytes are still delivered before the error.
235 function end(err: Socket.SocketError) {
236 error ??= err
237 drain()
238 }
239 // Teardown or failure: consumed bytes are discarded.
240 function close(err: Socket.SocketError) {
241 error ??= err
242 closed = true
243 pending = undefined
244 drain()
245 }
246 function onEnd() {
247 end(new Socket.SocketError({ reason: new Socket.SocketCloseError({ code: 1000 }) }))
248 }
249 function onError(cause: Error) {
250 close(
251 new Socket.SocketError({
252 reason: new Socket.SocketReadError({ cause })
253 })
254 )
255 }
256 function onClose(hadError: boolean) {
257 const err = new Socket.SocketError({
258 reason: new Socket.SocketCloseError({ code: hadError ? 1006 : 1000 })
259 })
260 if (hadError) close(err)
261 else end(err)
262 }
263
264 function attachReadListeners(conn: Duplex) {
265 conn.on("readable", drain)
266 conn.on("end", onEnd)
267 conn.on("error", onError)
268 conn.on("close", onClose)
269 }
270
271 function detachReadListeners(conn: Duplex) {
272 conn.off("readable", drain)
273 conn.off("end", onEnd)
274 conn.off("error", onError)
275 conn.off("close", onClose)
276 }
277
278 // Deno's node:net compatibility layer stops emitting `readable` after
279 // an explicit pause. The stream is already non-flowing without one.
280 if (!isDeno) conn.pause()
281 attachReadListeners(conn)
282 yield* Scope.addFinalizer(
283 scope,
284 Effect.sync(() => {
285 // resume a pull blocked in another fiber before detaching
286 close(
287 new Socket.SocketError({
288 reason: new Socket.SocketCloseError({ code: 1006 })
289 })
290 )
291 detachReadListeners(conn)
292 latch.closeUnsafe()
293 currentSocket = undefined
294 upgradeAvailable = false
295 })
296 )
297
298 currentSocket = conn
299 latch.openUnsafe()
300
301 const pull = Effect.callback<Arr.NonEmptyReadonlyArray<Uint8Array | string>, Socket.SocketError>((resume) => {
302 waiter = resume
303 drain()
304 // Resumed synchronously: nothing to cancel.
305 if (waiter !== resume) return
306 return Effect.sync(() => {
307 if (waiter === resume) waiter = undefined
308 })
309 })
310
311 const upgrade: Socket.Reader["upgrade"] = (upgradeOptions = {}) =>
312 Effect.suspend(() => {
313 if (!upgradeAvailable) {
314 return Effect.fail(
315 new Socket.SocketError({
316 reason: new Socket.SocketUpgradeError({
317 cause: new Error("socket is already upgraded or closed")
318 })
319 })
320 )
321 }
322 const hasKey = upgradeOptions.key !== undefined
323 const hasCert = upgradeOptions.cert !== undefined
324 if ((isServer && (!hasKey || !hasCert)) || hasKey !== hasCert) {
325 return Effect.fail(
326 new Socket.SocketError({
327 reason: new Socket.SocketUpgradeError({
328 cause: new Error(
329 isServer
330 ? "server TLS upgrade requires both key and cert"
331 : "TLS upgrade credentials must include both key and cert"
332 )
333 })
334 })
335 )
336 }
337 return Effect.callback<void, Socket.SocketError>((resume) => {
338 const raw = conn
339 detachReadListeners(raw)
340
341 let tls: Tls.TLSSocket
342 try {
343 const secureContext = Tls.createSecureContext({
344 key: upgradeOptions.key === undefined
345 ? undefined
346 : Arr.map(
347 Arr.ensure(upgradeOptions.key),
348 (value) => Buffer.from(Redacted.value(value))
349 ),
350 cert: upgradeOptions.cert === undefined ? undefined : toBuffers(upgradeOptions.cert),
351 ca: upgradeOptions.ca === undefined ? undefined : toBuffers(upgradeOptions.ca),
352 passphrase: upgradeOptions.passphrase === undefined
353 ? undefined
354 : Redacted.value(upgradeOptions.passphrase)
355 })
356 const tlsOptions = {
357 secureContext,
358 ALPNProtocols: upgradeOptions.alpnProtocols === undefined
359 ? undefined
360 : [...upgradeOptions.alpnProtocols],
361 requestCert: upgradeOptions.requestCert,
362 rejectUnauthorized: upgradeOptions.rejectUnauthorized
363 }
364 tls = isServer
365 ? new Tls.TLSSocket(raw as Net.Socket, { ...tlsOptions, isServer: true })
366 : Tls.connect({ ...tlsOptions, servername: upgradeOptions.servername, socket: raw as Net.Socket })
367 } catch (cause) {
368 attachReadListeners(raw)
369 resume(Effect.fail(
370 new Socket.SocketError({
371 reason: new Socket.SocketUpgradeError({ cause })
372 })
373 ))
374 return
375 }
376
377 conn = tls
378 currentSocket = tls
379 tls.pause()
380
381 function cleanup() {
382 tls.off(secureEvent, succeed)
383 tls.off("error", failUpgrade)
384 tls.off("close", onUpgradeClose)
385 }
386 function succeed() {
387 cleanup()
388 upgradeAvailable = false
389 attachReadListeners(tls)
390 resume(Effect.void)
391 }
392 function failUpgrade(cause: unknown) {
393 cleanup()
394 const upgradeError = new Socket.SocketError({
395 reason: new Socket.SocketUpgradeError({ cause })
396 })
397 close(upgradeError)
398 resume(Effect.fail(upgradeError))
399 }
400 function onUpgradeClose() {
401 failUpgrade(new Error("socket closed during TLS upgrade"))
402 }
403
404 tls.once(secureEvent, succeed)
405 tls.once("error", failUpgrade)
406 tls.once("close", onUpgradeClose)
407
408 return Effect.sync(() => {
409 cleanup()
410 close(
411 new Socket.SocketError({
412 reason: new Socket.SocketCloseError({ code: 1006 })
413 })
414 )
415 tls.destroy()
416 })
417 })
418 })
419
420 return { pull, upgrade }
421 }).pipe(
422 Effect.updateContext((input: Context.Context<Scope.Scope>) => Context.merge(openServices, input))
423 ) as Socket.Socket["reader"]
424
425 const awaitDrain = (conn: Duplex) =>
426 Effect.callback<void, Socket.SocketError>((resume) => {
427 function cleanup() {
428 conn.off("drain", onDrain)
429 conn.off("error", onError)
430 conn.off("close", onClose)
431 }
432 function onDrain() {
433 cleanup()
434 resume(Effect.void)
435 }
436 function onError(cause: Error) {
437 cleanup()
438 resume(Effect.fail(
439 new Socket.SocketError({
440 reason: new Socket.SocketWriteError({ cause })
441 })
442 ))
443 }
444 function onClose() {
445 cleanup()
446 resume(Effect.fail(
447 new Socket.SocketError({
448 reason: new Socket.SocketWriteError({ cause: new Error("socket closed") })
449 })
450 ))
451 }
452 conn.on("drain", onDrain)
453 conn.on("error", onError)
454 conn.on("close", onClose)
455 return Effect.sync(cleanup)
456 })
457
458 const write = (
459 chunk: Uint8Array | string | Socket.CloseEvent
460 ): Effect.Effect<void, Socket.SocketError> =>
461 Effect.suspend(() => {
462 const conn = currentSocket
463 if (conn === undefined) return latch.whenOpen(write(chunk))
464 if (Socket.isCloseEvent(chunk)) {
465 conn.destroy(chunk.code > 1000 ? new Error(`closed with code ${chunk.code}`) : undefined)
466 return Effect.void
467 }
468 try {
469 return conn.write(chunk) ? Effect.void : awaitDrain(conn)
470 } catch (cause) {
471 return Effect.fail(
472 new Socket.SocketError({
473 reason: new Socket.SocketWriteError({ cause })
474 })
475 )
476 }
477 })
478
479 const writeAll = (
480 chunks: Arr.NonEmptyReadonlyArray<Uint8Array | string>
481 ): Effect.Effect<void, Socket.SocketError> =>
482 Effect.suspend(() => {
483 const conn = currentSocket
484 if (conn === undefined) return latch.whenOpen(writeAll(chunks))
485 let needsDrain = false
486 try {
487 if (chunks.length === 1) {
488 needsDrain = !conn.write(chunks[0])
489 } else {
490 conn.cork()
491 try {
492 for (let i = 0; i < chunks.length; i++) {
493 needsDrain = !conn.write(chunks[i]) || needsDrain
494 }
495 } finally {
496 conn.uncork()
497 }
498 }
499 } catch (cause) {
500 return Effect.fail(
501 new Socket.SocketError({
502 reason: new Socket.SocketWriteError({ cause })
503 })
504 )
505 }
506 return needsDrain ? awaitDrain(conn) : Effect.void
507 })
508
509 const writer: Socket.Socket["writer"] = Effect.acquireRelease(
510 Effect.succeed({ write, writeAll }),
511 () =>
512 Effect.sync(() => {
513 if (!currentSocket || currentSocket.writableEnded) return
514 currentSocket.end()
515 })
516 )
517
518 return Effect.succeed(Socket.make({ reader, writer }))
519 })
520
521 /**
522 * Creates a `Channel` over a TCP socket, reading arrays of `Uint8Array`
523 * chunks and writing arrays of bytes, strings, or socket close events.
524 *
525 * @stability unstable
526 * @category constructors
527 * @since 4.0.0
528 */
529 export const makeNetChannel = <IE = never>(
530 options: Parameters<typeof makeNet>[0]
531 ): Channel.Channel<
532 Arr.NonEmptyReadonlyArray<Uint8Array>,
533 Socket.SocketError | IE,
534 void,
535 Arr.NonEmptyReadonlyArray<Uint8Array | string | Socket.CloseEvent>,
536 IE
537 > =>
538 Channel.unwrap(
539 Effect.map(makeNet(options), Socket.toChannelWith<IE>())
540 )
541
542 /**
543 * Provides a `Socket.Socket` by opening a TCP connection with the supplied
544 * Node `net` connection options.
545 *
546 * @stability unstable
547 * @category layers
548 * @since 4.0.0
549 */
550 export const layerNet: (options: Parameters<typeof makeNet>[0]) => Layer.Layer<
551 Socket.Socket,
552 Socket.SocketError
553 > = Function.flow(makeNet, Layer.effect(Socket.Socket))
554
555 /**
556 * Opens a Node TLS connection as an Effect socket.
557 *
558 * **When to use**
559 *
560 * Use to create a `Socket.Socket` whose reader acquisition dials
561 * `tls.connect` and completes once the TLS handshake has finished.
562 *
563 * **Details**
564 *
565 * Accepts the same options as `tls.connect`, so trust anchors (`ca`), client
566 * certificates (`cert` / `key`), ALPN protocols, and `servername` are set
567 * there. A failed handshake, including an untrusted or expired peer
568 * certificate, fails with a `SocketOpenError`. Supports `openTimeout` and
569 * destroys the underlying socket when the reader scope is finalized.
570 *
571 * @stability unstable
572 * @category constructors
573 * @since 4.0.0
574 */
575 export const makeTls = (
576 options: Tls.ConnectionOptions & {
577 readonly openTimeout?: Duration.Input | undefined
578 /**
579 * Maximum chunks per pull. Defaults to 4096 unless a positive safe integer or Infinity is supplied.
580 * Use Infinity for unbounded batching.
581 */
582 readonly chunkSize?: number | undefined
583 }
584 ): Effect.Effect<Socket.Socket> =>
585 fromDuplex(
586 Effect.contextWith((context: Context.Context<Scope.Scope>) => {
587 let conn: Tls.TLSSocket | undefined
588 let isOpen = false
589 return Effect.flatMap(
590 Scope.addFinalizer(
591 Context.get(context, Scope.Scope),
592 Effect.sync(() => {
593 if (!conn) return
594 closeSocket(conn, isOpen)
595 })
596 ),
597 () =>
598 Effect.callback<Tls.TLSSocket, Socket.SocketError, never>((resume) => {
599 conn = Tls.connect(options)
600 conn.once("secureConnect", () => {
601 isOpen = true
602 resume(Effect.succeed(conn!))
603 })
604 conn.on("error", (cause: Error) => {
605 resume(Effect.fail(
606 new Socket.SocketError({
607 reason: new Socket.SocketOpenError({ kind: "Unknown", cause })
608 })
609 ))
610 })
611 })
612 )
613 }),
614 options
615 )
616
617 /**
618 * Creates a `Channel` over a TLS socket, reading arrays of `Uint8Array`
619 * chunks and writing arrays of bytes, strings, or socket close events.
620 *
621 * @stability unstable
622 * @category constructors
623 * @since 4.0.0
624 */
625 export const makeTlsChannel = <IE = never>(
626 options: Parameters<typeof makeTls>[0]
627 ): Channel.Channel<
628 Arr.NonEmptyReadonlyArray<Uint8Array>,
629 Socket.SocketError | IE,
630 void,
631 Arr.NonEmptyReadonlyArray<Uint8Array | string | Socket.CloseEvent>,
632 IE
633 > =>
634 Channel.unwrap(
635 Effect.map(makeTls(options), Socket.toChannelWith<IE>())
636 )
637
638 /**
639 * Provides a `Socket.Socket` by opening a TLS connection with the supplied
640 * Node `tls` connection options.
641 *
642 * @stability unstable
643 * @category layers
644 * @since 4.0.0
645 */
646 export const layerTls: (options: Parameters<typeof makeTls>[0]) => Layer.Layer<
647 Socket.Socket,
648 Socket.SocketError
649 > = Function.flow(makeTls, Layer.effect(Socket.Socket))