@effect/platform-deno 4.0.2 → 4.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/AGENTS.md +24 -0
  2. package/CLAUDE.md +24 -0
  3. package/ai-docs/package.json +2 -2
  4. package/ai-docs/src/52_graphql/10_basics.ts +111 -0
  5. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  6. package/ai-docs/src/52_graphql/30_batching.ts +116 -0
  7. package/ai-docs/src/52_graphql/40_aliased-batching.ts +122 -0
  8. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  9. package/ai-docs/src/52_graphql/index.md +6 -0
  10. package/dist/DenoAddressResolver.d.ts +13 -0
  11. package/dist/DenoAddressResolver.d.ts.map +1 -0
  12. package/dist/DenoAddressResolver.js +32 -0
  13. package/dist/DenoAddressResolver.js.map +1 -0
  14. package/dist/DenoDatagramSocket.d.ts +208 -0
  15. package/dist/DenoDatagramSocket.d.ts.map +1 -0
  16. package/dist/DenoDatagramSocket.js +423 -0
  17. package/dist/DenoDatagramSocket.js.map +1 -0
  18. package/dist/DenoDns.d.ts +62 -0
  19. package/dist/DenoDns.d.ts.map +1 -0
  20. package/dist/DenoDns.js +144 -0
  21. package/dist/DenoDns.js.map +1 -0
  22. package/dist/DenoFileSystem.d.ts.map +1 -1
  23. package/dist/DenoFileSystem.js +48 -19
  24. package/dist/DenoFileSystem.js.map +1 -1
  25. package/dist/DenoSocket.d.ts +2 -0
  26. package/dist/DenoSocket.d.ts.map +1 -1
  27. package/dist/DenoSocket.js +3 -1
  28. package/dist/DenoSocket.js.map +1 -1
  29. package/dist/DenoStdio.d.ts.map +1 -1
  30. package/dist/DenoStdio.js +1 -0
  31. package/dist/DenoStdio.js.map +1 -1
  32. package/dist/DenoTerminal.d.ts +4 -3
  33. package/dist/DenoTerminal.d.ts.map +1 -1
  34. package/dist/DenoTerminal.js +4 -3
  35. package/dist/DenoTerminal.js.map +1 -1
  36. package/dist/index.d.ts +15 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +15 -0
  39. package/dist/index.js.map +1 -1
  40. package/package.json +7 -5
  41. package/src/DenoAddressResolver.ts +36 -0
  42. package/src/DenoDatagramSocket.ts +571 -0
  43. package/src/DenoDns.ts +196 -0
  44. package/src/DenoFileSystem.ts +60 -27
  45. package/src/DenoSocket.ts +3 -1
  46. package/src/DenoStdio.ts +1 -0
  47. package/src/DenoTerminal.ts +4 -3
  48. package/src/index.ts +18 -0
@@ -0,0 +1,571 @@
1
+ /**
2
+ * Deno UDP adapter for `effect/socket/DatagramSocket`, built on the native
3
+ * `Deno.listenDatagram`.
4
+ *
5
+ * `make` opens a new `Deno.DatagramConn` for each reader acquisition,
6
+ * `fromDatagramConn` adopts a connection the caller opens, and `layer`
7
+ * provides the `DatagramSocket` service.
8
+ *
9
+ * `Deno.listenDatagram` is unstable. Run with `--unstable-net`, or add `"net"`
10
+ * to the `"unstable"` list in `deno.json`. Without it, acquiring a reader fails
11
+ * with a `DatagramSocketUnsupportedError`, and without `--allow-net` it fails
12
+ * with a `DatagramSocketOpenError` of kind `"PermissionDenied"`.
13
+ *
14
+ * Compared with the Node and Bun adapters, Deno has no `connect`, no
15
+ * source-specific multicast, and broadcast is always on. Received packets are
16
+ * read into one reused 64 KiB buffer and copied out, so payloads are safe to
17
+ * retain. On Linux a datagram larger than that buffer is silently truncated.
18
+ *
19
+ * The reader owns the native socket, so a send-only client must still acquire
20
+ * a reader, or its writes wait forever. Every write waits for Deno's `send`
21
+ * promise, so send errors fail the write that caused them.
22
+ *
23
+ * `writeAll` sends sequentially and stops at the first failure. Earlier sends
24
+ * are not resent; the error carries the failed datagram's `address`. Send order
25
+ * does not guarantee arrival order.
26
+ *
27
+ * On Windows, ICMP connection resets or refusals reported by `receive` are
28
+ * passed to `onError` and reading continues.
29
+ *
30
+ * **Example** (Echo server)
31
+ *
32
+ * ```ts
33
+ * import { DenoDatagramSocket } from "@effect/platform-deno"
34
+ * import { Effect } from "effect"
35
+ *
36
+ * const echo = Effect.gen(function*() {
37
+ * const socket = yield* DenoDatagramSocket.make({ bind: { port: 9000 } })
38
+ * const reader = yield* socket.reader
39
+ * const writer = yield* socket.writer
40
+ * while (true) {
41
+ * for (const received of yield* reader.pull) {
42
+ * yield* writer.write({ payload: received.payload, address: received })
43
+ * }
44
+ * }
45
+ * }).pipe(Effect.scoped)
46
+ * ```
47
+ *
48
+ * **Example** (Send-only client)
49
+ *
50
+ * ```ts
51
+ * import { DenoDatagramSocket } from "@effect/platform-deno"
52
+ * import { Effect } from "effect"
53
+ *
54
+ * const send = (payload: string) =>
55
+ * Effect.gen(function*() {
56
+ * const socket = yield* DenoDatagramSocket.make({
57
+ * peer: { address: "localhost", port: 9000 }
58
+ * })
59
+ * // Required even for send-only clients.
60
+ * yield* socket.reader
61
+ * const writer = yield* socket.writer
62
+ * yield* writer.write({ payload })
63
+ * }).pipe(Effect.scoped)
64
+ * ```
65
+ *
66
+ * **Example** (Multicast receiver and sender)
67
+ *
68
+ * ```ts
69
+ * import { DenoDatagramSocket } from "@effect/platform-deno"
70
+ * import { Effect } from "effect"
71
+ * import { NetAddress } from "effect/net"
72
+ *
73
+ * const group = NetAddress.ipFromStringUnsafe("239.255.0.1")
74
+ *
75
+ * const receive = Effect.gen(function*() {
76
+ * if (!NetAddress.isMulticast(group) || !NetAddress.isIpv4Address(group)) return
77
+ * const socket = yield* DenoDatagramSocket.make({
78
+ * bind: { address: "0.0.0.0", port: 5000 },
79
+ * reuseAddress: true
80
+ * })
81
+ * const reader = yield* socket.reader
82
+ * yield* reader.joinMulticast({ group, interface: NetAddress.ipv4Loopback })
83
+ * return yield* reader.pull
84
+ * }).pipe(Effect.scoped)
85
+ *
86
+ * const announce = Effect.gen(function*() {
87
+ * const socket = yield* DenoDatagramSocket.make({
88
+ * // Deno has no egress `multicast.interface` option, so the bind address
89
+ * // picks the interface the group's datagrams leave through
90
+ * bind: { address: "127.0.0.1" },
91
+ * peer: { address: group, port: 5000 },
92
+ * multicast: { loopback: true }
93
+ * })
94
+ * yield* socket.reader
95
+ * const writer = yield* socket.writer
96
+ * yield* writer.write({ payload: "hello" })
97
+ * }).pipe(Effect.scoped)
98
+ * ```
99
+ *
100
+ * @stability experimental
101
+ * @since 4.0.0
102
+ */
103
+ import * as Effect from "effect/Effect"
104
+ import { constVoid } from "effect/Function"
105
+ import * as Layer from "effect/Layer"
106
+ import * as NetAddress from "effect/net/NetAddress"
107
+ import type * as Scope from "effect/Scope"
108
+ import * as DatagramSocket from "effect/socket/DatagramSocket"
109
+ import * as Dns from "node:dns"
110
+ import * as Net from "node:net"
111
+
112
+ /**
113
+ * An open-time endpoint. Hostnames resolve once per reader acquisition via
114
+ * `node:dns.lookup`.
115
+ * An `InetAddress` can be passed directly.
116
+ *
117
+ * @stability experimental
118
+ * @category models
119
+ * @since 4.0.0
120
+ */
121
+ export interface Endpoint {
122
+ readonly address: string | NetAddress.IpAddress
123
+ readonly port: number
124
+ }
125
+
126
+ /**
127
+ * Options for `make` and `layer`.
128
+ *
129
+ * **Details**
130
+ *
131
+ * `bind` defaults to `0.0.0.0` (or `::` for `family: "ipv6"`) and an
132
+ * ephemeral port. `peer` is a default destination and doesn't filter senders;
133
+ * Deno has no `connect`.
134
+ *
135
+ * Family selection, in order: explicit `family`, a `bind` IP literal, the
136
+ * `peer` address, a `bind` hostname, then `"ipv4"`. Hostname
137
+ * lookups use the family selected so far, or prefer IPv4 if none is set.
138
+ *
139
+ * `reuseAddress` means `SO_REUSEADDR` on Linux and `SO_REUSEPORT` on BSD and
140
+ * macOS. `multicast.loopback` loops sent multicast datagrams back to the local
141
+ * host. Deno has no egress multicast interface setting; the `interface` of
142
+ * `Reader.joinMulticast` is the ingress interface, a different socket option.
143
+ *
144
+ * @stability experimental
145
+ * @category options
146
+ * @since 4.0.0
147
+ */
148
+ export interface Options {
149
+ readonly bind?: { readonly address?: string | NetAddress.IpAddress; readonly port?: number } | undefined
150
+ readonly family?: "ipv4" | "ipv6" | undefined
151
+ readonly peer?: Endpoint | undefined
152
+ readonly reuseAddress?: boolean | undefined
153
+ readonly multicast?: { readonly loopback?: boolean | undefined } | undefined
154
+ readonly receiveBuffer?: DatagramSocket.ReceiveBufferOptions | undefined
155
+ readonly onError?: ((error: DatagramSocket.DatagramSocketError) => void) | undefined
156
+ }
157
+
158
+ /**
159
+ * Options for `fromDatagramConn`. The caller configures the adopted
160
+ * connection, so only the options that live in JavaScript apply.
161
+ *
162
+ * @stability experimental
163
+ * @category options
164
+ * @since 4.0.0
165
+ */
166
+ export type AdoptOptions = Pick<Options, "peer" | "receiveBuffer" | "onError">
167
+
168
+ /**
169
+ * Creates a `DatagramSocket` that opens and binds a new `Deno.DatagramConn`
170
+ * for each reader acquisition.
171
+ *
172
+ * **Details**
173
+ *
174
+ * Creating the socket never fails. Checking for `Deno.listenDatagram`,
175
+ * binding and resolving names happen when a reader is acquired, and fail that
176
+ * acquisition with a `DatagramSocketError`. Hostnames in `bind` and `peer` are
177
+ * resolved once per acquisition, so no send waits for DNS.
178
+ *
179
+ * Invalid `receiveBuffer.capacity` values cause a defect; use a positive
180
+ * safe integer.
181
+ *
182
+ * @stability experimental
183
+ * @category constructors
184
+ * @since 4.0.0
185
+ */
186
+ export const make = (options: Options = {}): Effect.Effect<DatagramSocket.DatagramSocket> =>
187
+ DatagramSocket.makeFromBackingSocket((events) => open(options, events), options)
188
+
189
+ /**
190
+ * Adopts a `Deno.DatagramConn`.
191
+ *
192
+ * **Details**
193
+ *
194
+ * `acquire` runs once per reader acquisition, inside the reader's scope, and
195
+ * the adapter closes the connection when that scope ends. The adapter starts
196
+ * reading as soon as `acquire` completes, so nothing else should read from the
197
+ * connection.
198
+ *
199
+ * @stability experimental
200
+ * @category constructors
201
+ * @since 4.0.0
202
+ */
203
+ export const fromDatagramConn = <R>(
204
+ acquire: Effect.Effect<Deno.DatagramConn, DatagramSocket.DatagramSocketError, R>,
205
+ options: AdoptOptions = {}
206
+ ): Effect.Effect<DatagramSocket.DatagramSocket, never, Exclude<R, Scope.Scope>> =>
207
+ DatagramSocket.makeFromBackingSocket(
208
+ (events) => Effect.flatMap(acquire, (conn) => adopt(conn, options, events)),
209
+ options
210
+ )
211
+
212
+ /**
213
+ * Provides a `DatagramSocket` built with `make`.
214
+ *
215
+ * @stability experimental
216
+ * @category layers
217
+ * @since 4.0.0
218
+ */
219
+ export const layer = (options: Options = {}): Layer.Layer<DatagramSocket.DatagramSocket> =>
220
+ Layer.effect(DatagramSocket.DatagramSocket, make(options))
221
+
222
+ interface DenoError {
223
+ readonly name?: unknown
224
+ readonly code?: unknown
225
+ }
226
+
227
+ const errorCode = (error: unknown): unknown => (error as DenoError)?.code
228
+
229
+ const openError = (
230
+ error: unknown,
231
+ kind?: DatagramSocket.DatagramSocketOpenError["kind"]
232
+ ): DatagramSocket.DatagramSocketError => {
233
+ if ((error as DenoError)?.name === "NotCapable") {
234
+ kind = "PermissionDenied"
235
+ } else if (kind === undefined) {
236
+ const code = errorCode(error)
237
+ kind = code === "EADDRINUSE"
238
+ ? "AddressInUse"
239
+ : code === "EADDRNOTAVAIL"
240
+ ? "AddressNotAvailable"
241
+ : code === "EACCES" || code === "EPERM"
242
+ ? "PermissionDenied"
243
+ : "Unknown"
244
+ }
245
+ return new DatagramSocket.DatagramSocketError({
246
+ reason: new DatagramSocket.DatagramSocketOpenError({ kind, cause: error })
247
+ })
248
+ }
249
+
250
+ // DNS lookup reports a missing Deno net permission as EPERM, not NotCapable.
251
+ const lookupOpenError = (error: unknown) => {
252
+ const code = (error as DenoError)?.code
253
+ return openError(error, code === "EPERM" || code === "EACCES" ? "PermissionDenied" : "AddressNotAvailable")
254
+ }
255
+
256
+ const unsupportedError = (capability: string) =>
257
+ new DatagramSocket.DatagramSocketError({
258
+ reason: new DatagramSocket.DatagramSocketUnsupportedError({ capability, runtime: "Deno" })
259
+ })
260
+
261
+ const ioKind = (error: unknown): DatagramSocket.IoErrorKind => {
262
+ switch (errorCode(error)) {
263
+ case "EMSGSIZE":
264
+ return "MessageTooLarge"
265
+ case "EHOSTUNREACH":
266
+ case "ENETUNREACH":
267
+ case "EHOSTDOWN":
268
+ case "ENETDOWN":
269
+ return "Unreachable"
270
+ case "ECONNREFUSED":
271
+ case "ECONNRESET":
272
+ return "ConnectionRefused"
273
+ case "EACCES":
274
+ case "EPERM":
275
+ return "PermissionDenied"
276
+ }
277
+ switch ((error as DenoError)?.name) {
278
+ case "NotCapable":
279
+ case "PermissionDenied":
280
+ return "PermissionDenied"
281
+ case "ConnectionRefused":
282
+ case "ConnectionReset":
283
+ return "ConnectionRefused"
284
+ default:
285
+ return "Unknown"
286
+ }
287
+ }
288
+
289
+ const closedError = (): DatagramSocket.DatagramSocketError =>
290
+ new DatagramSocket.DatagramSocketError({ reason: new DatagramSocket.DatagramSocketClosedError() })
291
+
292
+ const writeError = (error: unknown): DatagramSocket.DatagramSocketError =>
293
+ (error as DenoError)?.name === "BadResource" ? closedError() : new DatagramSocket.DatagramSocketError({
294
+ reason: new DatagramSocket.DatagramSocketWriteError({ kind: ioKind(error), cause: error })
295
+ })
296
+
297
+ const readError = (error: unknown): DatagramSocket.DatagramSocketError =>
298
+ new DatagramSocket.DatagramSocketError({
299
+ reason: new DatagramSocket.DatagramSocketReadError({ kind: ioKind(error), cause: error })
300
+ })
301
+
302
+ type Family = "ipv4" | "ipv6"
303
+
304
+ // Deno has no interface names to map, so IPv6 zones stay numeric
305
+ const noScopeIds: ReadonlyMap<string, number> = new Map()
306
+
307
+ const familyOfLiteral = (address: string | NetAddress.IpAddress): Family | undefined => {
308
+ if (typeof address !== "string") return NetAddress.isIpv4Address(address) ? "ipv4" : "ipv6"
309
+ const version = Net.isIP(address)
310
+ return version === 4 ? "ipv4" : version === 6 ? "ipv6" : undefined
311
+ }
312
+
313
+ // `endpoint` may be a whole `InetAddress`, whose IPv6 scope must survive
314
+ const formatEndpoint = (
315
+ endpoint: { readonly address?: string | NetAddress.IpAddress | undefined },
316
+ scopeIds: ReadonlyMap<string, number>
317
+ ): string | undefined =>
318
+ NetAddress.isInetAddress(endpoint)
319
+ ? NetAddress.formatNativeHost(endpoint, scopeIds)
320
+ : endpoint.address === undefined || typeof endpoint.address === "string"
321
+ ? endpoint.address
322
+ : NetAddress.formatIp(endpoint.address)
323
+
324
+ interface Resolved {
325
+ readonly host: string
326
+ readonly family: Family
327
+ }
328
+
329
+ // Prefer IPv4 unless the family is fixed; IP literals resolve synchronously.
330
+ const resolve = (
331
+ address: string | NetAddress.IpAddress | undefined,
332
+ family: Family | undefined,
333
+ onError: (error: unknown) => void,
334
+ next: (resolved: Resolved | undefined) => void
335
+ ): void => {
336
+ if (typeof address !== "string") return next(undefined)
337
+ const literal = familyOfLiteral(address)
338
+ if (literal !== undefined) return next({ host: address, family: literal })
339
+ try {
340
+ Dns.lookup(address, { all: true, family: family === "ipv4" ? 4 : family === "ipv6" ? 6 : 0 }, (error, results) => {
341
+ if (error) return onError(error)
342
+ const result = results.find((result) => result.family === 4) ?? results[0]
343
+ if (result === undefined) return onError(new Error(`${address} has no addresses`))
344
+ next({ host: result.address, family: result.family === 6 ? "ipv6" : "ipv4" })
345
+ })
346
+ } catch (error) {
347
+ onError(error)
348
+ }
349
+ }
350
+
351
+ interface OpenPlan {
352
+ readonly bindHost: string
353
+ readonly remote: DatagramSocket.BackingAddress | undefined
354
+ }
355
+
356
+ const planOpen = (
357
+ options: {
358
+ readonly family?: Family | undefined
359
+ readonly bind?: { readonly address?: string | NetAddress.IpAddress | undefined } | undefined
360
+ readonly remote?: { readonly address: string | NetAddress.IpAddress; readonly port: number } | undefined
361
+ },
362
+ onLookupError: (error: unknown) => void,
363
+ next: (plan: OpenPlan) => void
364
+ ): void => {
365
+ const { bind, remote } = options
366
+ const fixed = options.family ?? (bind?.address === undefined ? undefined : familyOfLiteral(bind.address))
367
+ resolve(remote?.address, fixed, onLookupError, (resolvedRemote) => {
368
+ const remoteFamily = resolvedRemote?.family ?? (remote === undefined ? undefined : familyOfLiteral(remote.address))
369
+ resolve(bind?.address, fixed ?? remoteFamily, onLookupError, (resolvedBind) => {
370
+ const family = fixed ?? remoteFamily ?? resolvedBind?.family ?? "ipv4"
371
+ next({
372
+ bindHost: resolvedBind?.host ??
373
+ (bind === undefined ? undefined : formatEndpoint(bind, noScopeIds)) ??
374
+ (family === "ipv6" ? "::" : "0.0.0.0"),
375
+ remote: remote === undefined ? undefined : {
376
+ host: resolvedRemote?.host ?? formatEndpoint(remote, noScopeIds)!,
377
+ port: remote.port
378
+ }
379
+ })
380
+ })
381
+ })
382
+ }
383
+
384
+ const resolvePeer = (
385
+ peer: { readonly address: string | NetAddress.IpAddress; readonly port: number } | undefined,
386
+ family: Family,
387
+ onLookupError: (error: unknown) => void,
388
+ next: (peer: DatagramSocket.BackingAddress | undefined) => void
389
+ ): void => {
390
+ if (peer === undefined) return next(undefined)
391
+ if (typeof peer.address !== "string") return next({ host: formatEndpoint(peer, noScopeIds)!, port: peer.port })
392
+ resolve(peer.address, family, onLookupError, (resolved) => next({ host: resolved!.host, port: peer.port }))
393
+ }
394
+
395
+ const open = (
396
+ options: Options,
397
+ events: DatagramSocket.BackingEvents
398
+ ): Effect.Effect<DatagramSocket.BackingSocket, DatagramSocket.DatagramSocketError> =>
399
+ // checked per reader, not at module load, so the module imports without the flag
400
+ typeof Deno.listenDatagram !== "function"
401
+ ? Effect.fail(unsupportedError(
402
+ `UDP sockets without --unstable-net (pass --unstable-net or add "net" to "unstable" in deno.json)`
403
+ ))
404
+ : Effect.callback((resume) => {
405
+ planOpen(
406
+ { family: options.family, bind: options.bind, remote: options.peer },
407
+ (error) => resume(Effect.fail(lookupOpenError(error))),
408
+ (plan) => {
409
+ let conn: Deno.DatagramConn
410
+ try {
411
+ conn = Deno.listenDatagram({
412
+ transport: "udp",
413
+ hostname: plan.bindHost,
414
+ port: options.bind?.port ?? 0,
415
+ reuseAddress: options.reuseAddress ?? false,
416
+ loopback: options.multicast?.loopback ?? false
417
+ })
418
+ } catch (error) {
419
+ return resume(Effect.fail(openError(error)))
420
+ }
421
+ resume(Effect.succeed(new NativeConn(conn, events).open(plan.remote)))
422
+ }
423
+ )
424
+ })
425
+
426
+ const adopt = (
427
+ conn: Deno.DatagramConn,
428
+ options: AdoptOptions,
429
+ events: DatagramSocket.BackingEvents
430
+ ): Effect.Effect<DatagramSocket.BackingSocket, DatagramSocket.DatagramSocketError> =>
431
+ Effect.callback((resume) => {
432
+ const family: Family = (conn.addr as Deno.NetAddr).hostname.includes(":") ? "ipv6" : "ipv4"
433
+ resolvePeer(
434
+ options.peer,
435
+ family,
436
+ (error) => {
437
+ try {
438
+ conn.close()
439
+ } catch {
440
+ }
441
+ resume(Effect.fail(lookupOpenError(error)))
442
+ },
443
+ (peer) => resume(Effect.succeed(new NativeConn(conn, events).open(peer)))
444
+ )
445
+ })
446
+
447
+ // One `receive` in flight at a time, since concurrent receives reorder packets
448
+ const receiveBufferSize = 65536
449
+
450
+ class NativeConn {
451
+ readonly conn: Deno.DatagramConn
452
+ readonly events: DatagramSocket.BackingEvents
453
+ readonly buffer = new Uint8Array(receiveBufferSize)
454
+ closing = false
455
+ // the last destination, reused while consecutive sends share it
456
+ lastAddr: Deno.NetAddr | undefined = undefined
457
+
458
+ constructor(conn: Deno.DatagramConn, events: DatagramSocket.BackingEvents) {
459
+ this.conn = conn
460
+ this.events = events
461
+ }
462
+
463
+ receive() {
464
+ try {
465
+ this.conn.receive(this.buffer).then(this.onReceive, this.onReceiveError)
466
+ } catch (error) {
467
+ this.onReceiveError(error)
468
+ }
469
+ }
470
+
471
+ readonly onReceive = (received: [Uint8Array, Deno.Addr]) => {
472
+ if (this.closing) return
473
+ const addr = received[1] as Deno.NetAddr
474
+ this.events.onPacket(received[0].slice(), addr.hostname, addr.port)
475
+ // a woken pull may have closed the reader
476
+ if (!this.closing) this.receive()
477
+ }
478
+
479
+ readonly onReceiveError = (error: unknown) => {
480
+ if (this.closing) return
481
+ switch ((error as DenoError)?.name) {
482
+ // a pending receive is interrupted by a close, and the next one then
483
+ // reports the closed socket
484
+ case "Interrupted":
485
+ return this.receive()
486
+ case "BadResource":
487
+ return this.events.onClose()
488
+ // ICMP reports, as Windows raises them on unconnected sockets
489
+ case "ConnectionReset":
490
+ case "ConnectionRefused":
491
+ this.events.onError(readError(error))
492
+ return this.receive()
493
+ default:
494
+ return this.events.onReadError(readError(error))
495
+ }
496
+ }
497
+
498
+ addrOf(destination: DatagramSocket.BackingAddress): Deno.NetAddr {
499
+ const last = this.lastAddr
500
+ if (last !== undefined && last.hostname === destination.host && last.port === destination.port) return last
501
+ return this.lastAddr = { transport: "udp", hostname: destination.host, port: destination.port }
502
+ }
503
+
504
+ send(payload: Uint8Array, destination: DatagramSocket.BackingAddress | undefined): Promise<number> {
505
+ if (destination === undefined) return Promise.reject(new Error("DatagramSocket write has no destination"))
506
+ try {
507
+ return this.conn.send(payload, this.addrOf(destination))
508
+ } catch (error) {
509
+ return Promise.reject(error)
510
+ }
511
+ }
512
+
513
+ // Await each send before submitting the next, including on a warm socket.
514
+ async sendAll(
515
+ payloads: ReadonlyArray<Uint8Array>,
516
+ destinations: ReadonlyArray<DatagramSocket.BackingAddress | undefined>,
517
+ done: (error?: DatagramSocket.DatagramSocketError, index?: number) => void
518
+ ) {
519
+ for (let i = 0; i < payloads.length; i++) {
520
+ try {
521
+ await this.send(payloads[i], destinations[i])
522
+ } catch (error) {
523
+ done(writeError(error), i)
524
+ return
525
+ }
526
+ }
527
+ done()
528
+ }
529
+
530
+ open(peer: DatagramSocket.BackingAddress | undefined): DatagramSocket.BackingSocket {
531
+ const conn = this.conn
532
+ const bound = conn.addr as Deno.NetAddr
533
+ this.receive()
534
+ return {
535
+ address: { host: bound.hostname, port: bound.port },
536
+ peer,
537
+ connected: false,
538
+ send: (payload, destination, done) => {
539
+ this.send(payload, destination).then(() => done(), (error) => done(writeError(error)))
540
+ },
541
+ sendMany: (payloads, destinations, done) => {
542
+ void this.sendAll(payloads, destinations, done)
543
+ },
544
+ joinMulticast: ({ group, interface: ingress, source }) => {
545
+ if (source !== undefined) return Effect.fail(unsupportedError("source-specific multicast"))
546
+ return Effect.tryPromise({
547
+ try: () =>
548
+ NetAddress.isIpv4Address(group)
549
+ ? conn.joinMulticastV4(
550
+ NetAddress.formatIp(group),
551
+ ingress === undefined ? "0.0.0.0" : NetAddress.formatIp(ingress as NetAddress.Ipv4Address)
552
+ )
553
+ : conn.joinMulticastV6(NetAddress.formatIp(group), (ingress as number | undefined) ?? 0),
554
+ catch: (error) => openError(error)
555
+ }).pipe(
556
+ Effect.map((membership) => () => Effect.promise(() => membership.leave().then(constVoid, constVoid)))
557
+ )
558
+ },
559
+ close: () => this.close()
560
+ }
561
+ }
562
+
563
+ close() {
564
+ if (this.closing) return
565
+ this.closing = true
566
+ try {
567
+ this.conn.close()
568
+ } catch {
569
+ }
570
+ }
571
+ }