@netifyjs/netify 0.0.0-stage → 1.0.0-alpha.1

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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/package.json +65 -4
  4. package/src/bootstrap/client/index.ts +191 -0
  5. package/src/bootstrap/dispatcher/index.ts +204 -0
  6. package/src/bootstrap/index.ts +22 -0
  7. package/src/bootstrap/reconnect/index.ts +334 -0
  8. package/src/bootstrap/server/index.ts +284 -0
  9. package/src/buffer/bits/index.ts +2 -0
  10. package/src/buffer/bits/reader/index.ts +64 -0
  11. package/src/buffer/bits/writer/index.ts +79 -0
  12. package/src/buffer/index.ts +1375 -0
  13. package/src/buffer/pool/index.ts +46 -0
  14. package/src/buffer/quantizer/index.ts +101 -0
  15. package/src/channel/attribute/index.ts +89 -0
  16. package/src/channel/context/index.ts +621 -0
  17. package/src/channel/group/index.ts +256 -0
  18. package/src/channel/handler/duplex/index.ts +105 -0
  19. package/src/channel/handler/inbound/index.ts +78 -0
  20. package/src/channel/handler/index.ts +135 -0
  21. package/src/channel/handler/outbound/index.ts +33 -0
  22. package/src/channel/index.ts +619 -0
  23. package/src/channel/initializer/index.ts +77 -0
  24. package/src/channel/outbound/index.ts +611 -0
  25. package/src/channel/pipeline/head/index.ts +100 -0
  26. package/src/channel/pipeline/index.ts +414 -0
  27. package/src/channel/pipeline/tail/index.ts +45 -0
  28. package/src/channel/pipeline/tracker/index.ts +120 -0
  29. package/src/channel/queue/index.ts +203 -0
  30. package/src/channel/resolved/index.ts +34 -0
  31. package/src/channel/server/index.ts +164 -0
  32. package/src/channel/shutdown/index.ts +25 -0
  33. package/src/channel/simple/index.ts +38 -0
  34. package/src/channel/transport/index.ts +74 -0
  35. package/src/channel/transport/socket/index.ts +80 -0
  36. package/src/cluster/index.ts +360 -0
  37. package/src/codec/binary/index.ts +102 -0
  38. package/src/codec/decoder/index.ts +479 -0
  39. package/src/codec/delimiter/index.ts +189 -0
  40. package/src/codec/encoder/index.ts +48 -0
  41. package/src/codec/error/index.ts +33 -0
  42. package/src/codec/fixed/index.ts +45 -0
  43. package/src/codec/http/aggregator/index.ts +236 -0
  44. package/src/codec/http/client/index.ts +120 -0
  45. package/src/codec/http/decoder/index.ts +4 -0
  46. package/src/codec/http/decoder/object/index.ts +644 -0
  47. package/src/codec/http/decoder/request/index.ts +49 -0
  48. package/src/codec/http/decoder/response/index.ts +59 -0
  49. package/src/codec/http/encoder/index.ts +3 -0
  50. package/src/codec/http/encoder/object/index.ts +196 -0
  51. package/src/codec/http/encoder/request/index.ts +24 -0
  52. package/src/codec/http/encoder/response/index.ts +26 -0
  53. package/src/codec/http/headers/index.ts +287 -0
  54. package/src/codec/http/index.ts +33 -0
  55. package/src/codec/http/message/content/index.ts +36 -0
  56. package/src/codec/http/message/full/index.ts +10 -0
  57. package/src/codec/http/message/full/request/index.ts +45 -0
  58. package/src/codec/http/message/full/response/index.ts +43 -0
  59. package/src/codec/http/message/head/index.ts +79 -0
  60. package/src/codec/http/message/index.ts +16 -0
  61. package/src/codec/http/message/last/index.ts +27 -0
  62. package/src/codec/http/message/request/index.ts +39 -0
  63. package/src/codec/http/message/response/index.ts +31 -0
  64. package/src/codec/http/method/index.ts +101 -0
  65. package/src/codec/http/server/index.ts +81 -0
  66. package/src/codec/http/status/index.ts +170 -0
  67. package/src/codec/http/version/index.ts +70 -0
  68. package/src/codec/index.ts +83 -0
  69. package/src/codec/length/index.ts +330 -0
  70. package/src/codec/line/index.ts +45 -0
  71. package/src/codec/message/decoder/index.ts +84 -0
  72. package/src/codec/message/encoder/index.ts +56 -0
  73. package/src/codec/message/index.ts +2 -0
  74. package/src/codec/msgpack/index.ts +51 -0
  75. package/src/codec/prepender/index.ts +296 -0
  76. package/src/codec/protobuf/index.ts +57 -0
  77. package/src/codec/string/decoder/index.ts +47 -0
  78. package/src/codec/string/encoder/index.ts +26 -0
  79. package/src/codec/string/index.ts +2 -0
  80. package/src/codec/websocket/client/index.ts +235 -0
  81. package/src/codec/websocket/decoder/index.ts +371 -0
  82. package/src/codec/websocket/encoder/index.ts +170 -0
  83. package/src/codec/websocket/error/index.ts +42 -0
  84. package/src/codec/websocket/frame/base/index.ts +55 -0
  85. package/src/codec/websocket/frame/binary/index.ts +24 -0
  86. package/src/codec/websocket/frame/close/index.ts +82 -0
  87. package/src/codec/websocket/frame/continuation/index.ts +31 -0
  88. package/src/codec/websocket/frame/index.ts +10 -0
  89. package/src/codec/websocket/frame/opcode/index.ts +35 -0
  90. package/src/codec/websocket/frame/ping/index.ts +24 -0
  91. package/src/codec/websocket/frame/pong/index.ts +24 -0
  92. package/src/codec/websocket/frame/text/index.ts +31 -0
  93. package/src/codec/websocket/handshake/index.ts +38 -0
  94. package/src/codec/websocket/index.ts +25 -0
  95. package/src/codec/websocket/key/index.ts +41 -0
  96. package/src/codec/websocket/protocol/index.ts +147 -0
  97. package/src/codec/websocket/server/index.ts +233 -0
  98. package/src/codec/websocket/status/index.ts +97 -0
  99. package/src/codec/websocket/upgrade/index.ts +116 -0
  100. package/src/datagram/bootstrap/index.ts +269 -0
  101. package/src/datagram/channel/index.ts +103 -0
  102. package/src/datagram/index.ts +10 -0
  103. package/src/datagram/packet/index.ts +72 -0
  104. package/src/datagram/transport/index.ts +239 -0
  105. package/src/handler/flush/index.ts +187 -0
  106. package/src/handler/idle/index.ts +295 -0
  107. package/src/handler/index.ts +22 -0
  108. package/src/handler/logging/index.ts +195 -0
  109. package/src/handler/metrics/index.ts +300 -0
  110. package/src/handler/offload/index.ts +141 -0
  111. package/src/handler/timeout/error/index.ts +29 -0
  112. package/src/handler/timeout/index.ts +3 -0
  113. package/src/handler/timeout/read/index.ts +44 -0
  114. package/src/handler/timeout/write/index.ts +89 -0
  115. package/src/handler/traffic/index.ts +259 -0
  116. package/src/index.ts +258 -0
  117. package/src/logger/index.ts +47 -0
  118. package/src/reliable/bootstrap/index.ts +154 -0
  119. package/src/reliable/cipher/index.ts +227 -0
  120. package/src/reliable/cookie/index.ts +78 -0
  121. package/src/reliable/handler/index.ts +1202 -0
  122. package/src/reliable/handshake/index.ts +144 -0
  123. package/src/reliable/index.ts +38 -0
  124. package/src/reliable/lane/index.ts +420 -0
  125. package/src/reliable/message/index.ts +102 -0
  126. package/src/reliable/packet/index.ts +117 -0
  127. package/src/reliable/peer/index.ts +929 -0
  128. package/src/reliable/registry/index.ts +107 -0
  129. package/src/serve/bootstrap/index.ts +606 -0
  130. package/src/serve/channel/index.ts +246 -0
  131. package/src/serve/index.ts +17 -0
  132. package/src/serve/outbox/index.ts +292 -0
  133. package/src/serve/transport/index.ts +96 -0
  134. package/src/serve/writer/index.ts +119 -0
  135. package/src/shard/envelope/index.ts +44 -0
  136. package/src/shard/gateway/index.ts +119 -0
  137. package/src/shard/index.ts +11 -0
  138. package/src/shard/link/index.ts +743 -0
  139. package/src/shard/map/index.ts +91 -0
  140. package/src/worker/group/index.ts +175 -0
  141. package/src/worker/index.ts +10 -0
  142. package/src/worker/pool/index.ts +235 -0
  143. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,269 @@
1
+ import { ByteBuf } from '../../buffer/index.ts'
2
+ import type { ChannelOptions } from '../../channel/index.ts'
3
+ import type { ChannelHandler } from '../../channel/handler/index.ts'
4
+ import {
5
+ ChannelInitializer,
6
+ type ChannelSetup,
7
+ } from '../../channel/initializer/index.ts'
8
+ import { DatagramChannel } from '../channel/index.ts'
9
+ import { DatagramPacket } from '../packet/index.ts'
10
+ import { DatagramTransport, type UdpHandle } from '../transport/index.ts'
11
+ import type { udp } from 'bun'
12
+
13
+ /**
14
+ * Local side of a UDP socket, both parts optional
15
+ */
16
+ export type DatagramBindOptions = {
17
+ /**
18
+ * Interface to bind, every interface if left out
19
+ */
20
+ readonly hostname?: string
21
+
22
+ /**
23
+ * Leave out or use 0 to let the OS pick
24
+ */
25
+ readonly port?: number
26
+ }
27
+
28
+ /**
29
+ * Bind options plus the single peer to lock the socket to
30
+ */
31
+ export type DatagramConnectOptions = {
32
+ /**
33
+ * Peer host name or IP
34
+ */
35
+ readonly remoteHostname: string
36
+
37
+ /**
38
+ * Peer port
39
+ */
40
+ readonly remotePort: number
41
+ } & DatagramBindOptions
42
+
43
+ /**
44
+ * Lets Bun's callbacks find the channel, which we only build after the socket opens
45
+ */
46
+ type Binding = {
47
+ /**
48
+ * Null for the brief gap before open fills it in
49
+ */
50
+ channel: DatagramChannel | null
51
+ }
52
+
53
+ /**
54
+ * Builder for UDP channels, either free to send anywhere or tied to one peer
55
+ * @class
56
+ */
57
+ export class DatagramBootstrap {
58
+ /**
59
+ * Every IPv4 interface
60
+ */
61
+ public static readonly defaultHostname: string = '0.0.0.0'
62
+
63
+ /**
64
+ * Null until handler is called, bind and connect refuse to run without it
65
+ */
66
+ private initializer: ChannelInitializer<DatagramChannel> | null
67
+
68
+ /**
69
+ * Applied to every channel this bootstrap opens
70
+ */
71
+ private settings: ChannelOptions
72
+
73
+ /**
74
+ * Starts with no handler and default options
75
+ */
76
+ public constructor() {
77
+ this.initializer = null
78
+ this.settings = {}
79
+ }
80
+
81
+ /**
82
+ * Adds this handler to each new channel, usually a ChannelInitializer
83
+ * @param handler an initializer, or any handler that's safe to share
84
+ */
85
+ public handler<T extends ChannelHandler>(handler: T): this
86
+
87
+ /**
88
+ * Runs this against each new channel to build its pipeline
89
+ * @param setup adds the handlers, may be async
90
+ */
91
+ public handler(setup: ChannelSetup<DatagramChannel>): this
92
+
93
+ /**
94
+ * Remembers how to set up each channel
95
+ * @param handler an initializer, a handler or a setup function
96
+ */
97
+ public handler(
98
+ handler: ChannelHandler | ChannelSetup<DatagramChannel>,
99
+ ): this {
100
+ this.initializer = ChannelInitializer.of<DatagramChannel>(handler)
101
+ return this
102
+ }
103
+
104
+ /**
105
+ * Replaces any options set earlier rather than merging
106
+ * @param options channel settings like the logger and water marks
107
+ */
108
+ public options(options: ChannelOptions): this {
109
+ this.settings = options
110
+ return this
111
+ }
112
+
113
+ /**
114
+ * Unconnected socket, every outgoing packet needs a recipient
115
+ * @param options local address, defaults to any interface and port
116
+ */
117
+ public async bind(
118
+ options: DatagramBindOptions = {},
119
+ ): Promise<DatagramChannel> {
120
+ const initializer = this.require()
121
+ const binding: Binding = { channel: null }
122
+
123
+ let socket: udp.Socket<'uint8array'>
124
+ try {
125
+ socket = await Bun.udpSocket<'uint8array'>({
126
+ /**
127
+ * Falls back to every interface
128
+ */
129
+ hostname: options.hostname ?? DatagramBootstrap.defaultHostname,
130
+ /**
131
+ * Zero means any free port
132
+ */
133
+ port: options.port ?? 0,
134
+ /**
135
+ * Ask Bun for Uint8Arrays so ByteBuf can wrap them
136
+ */
137
+ binaryType: 'uint8array',
138
+ /**
139
+ * Bun callbacks that forward to the channel
140
+ */
141
+ socket: DatagramBootstrap.handler(binding),
142
+ })
143
+ } catch (cause) {
144
+ throw new Error('Bind failed', { cause })
145
+ }
146
+
147
+ return this.open({ kind: 'bound', socket }, binding, initializer)
148
+ }
149
+
150
+ /**
151
+ * Socket locked to one peer, so packets don't need a recipient
152
+ * @param options local address plus the peer to talk to
153
+ */
154
+ public async connect(
155
+ options: DatagramConnectOptions,
156
+ ): Promise<DatagramChannel> {
157
+ const initializer = this.require()
158
+ const binding: Binding = { channel: null }
159
+
160
+ let socket: udp.ConnectedSocket<'uint8array'>
161
+ try {
162
+ socket = await Bun.udpSocket<'uint8array'>({
163
+ /**
164
+ * Falls back to every interface
165
+ */
166
+ hostname: options.hostname ?? DatagramBootstrap.defaultHostname,
167
+ /**
168
+ * Zero means any free port
169
+ */
170
+ port: options.port ?? 0,
171
+ /**
172
+ * Ask Bun for Uint8Arrays so ByteBuf can wrap them
173
+ */
174
+ binaryType: 'uint8array',
175
+ /**
176
+ * Bun callbacks that forward to the channel
177
+ */
178
+ socket: DatagramBootstrap.handler(binding),
179
+ /**
180
+ * Peer the socket gets locked to
181
+ */
182
+ connect: { hostname: options.remoteHostname, port: options.remotePort },
183
+ })
184
+ } catch (cause) {
185
+ throw new Error('Connection failed', { cause })
186
+ }
187
+
188
+ return this.open({ kind: 'connected', socket }, binding, initializer)
189
+ }
190
+
191
+ /**
192
+ * Bun wants callbacks before the channel exists, so they go through binding
193
+ * @param binding filled in with the channel once it's built
194
+ */
195
+ private static handler(binding: Binding): udp.SocketHandler<'uint8array'> {
196
+ return {
197
+ /**
198
+ * Wraps the bytes in a packet stamped with the sender
199
+ */
200
+ data: (
201
+ socket: udp.Socket<'uint8array'>,
202
+ bytes: Uint8Array,
203
+ port: number,
204
+ address: string,
205
+ ): void => {
206
+ const packet = new DatagramPacket(ByteBuf.wrap(bytes), null, {
207
+ hostname: address,
208
+ port,
209
+ })
210
+ void binding.channel?.handleBurst(packet, bytes.length)
211
+ },
212
+ /**
213
+ * Socket has room again, so held-back writes can go
214
+ */
215
+ drain: (): void => {
216
+ binding.channel?.handleDrain()
217
+ },
218
+ /**
219
+ * Socket errors go to exceptionCaught, apart from refused ports
220
+ */
221
+ error: (...args: readonly unknown[]): void => {
222
+ const error = args.find(
223
+ (value: unknown): value is Error => value instanceof Error,
224
+ )
225
+ const channel = binding.channel
226
+ if (channel === null || DatagramTransport.isRefused(error)) return
227
+ void channel.handleError(error ?? new Error('Socket failed'))
228
+ },
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Throws Handler is not set if handler was never called
234
+ */
235
+ private require(): ChannelInitializer<DatagramChannel> {
236
+ if (this.initializer === null) throw new Error('Handler is not set')
237
+
238
+ return this.initializer
239
+ }
240
+
241
+ /**
242
+ * Builds the channel and runs setup, closing it again if setup throws
243
+ * @param socket tagged socket Bun just opened
244
+ * @param binding gets pointed at the new channel
245
+ * @param initializer adds the handlers
246
+ */
247
+ private async open(
248
+ socket: UdpHandle,
249
+ binding: Binding,
250
+ initializer: ChannelInitializer<DatagramChannel>,
251
+ ): Promise<DatagramChannel> {
252
+ const channel = new DatagramChannel(
253
+ new DatagramTransport(socket),
254
+ this.settings,
255
+ )
256
+ binding.channel = channel
257
+
258
+ try {
259
+ await channel.activate((): void | Promise<void> =>
260
+ initializer.initialize(channel),
261
+ )
262
+ } catch (cause) {
263
+ await channel.close()
264
+ throw new Error('Channel setup failed', { cause })
265
+ }
266
+
267
+ return channel
268
+ }
269
+ }
@@ -0,0 +1,103 @@
1
+ import { ByteBuf } from '../../buffer/index.ts'
2
+ import { Channel, type ChannelOptions } from '../../channel/index.ts'
3
+ import type { PacketAddress } from '../packet/index.ts'
4
+ import type { DatagramTransport } from '../transport/index.ts'
5
+
6
+ /**
7
+ * UDP flavour of a channel, its pipeline deals in DatagramPackets
8
+ * @class
9
+ */
10
+ export class DatagramChannel extends Channel {
11
+ /**
12
+ * Kept with its concrete type so we can reach the UDP socket
13
+ */
14
+ private readonly udpTransport: DatagramTransport
15
+
16
+ /**
17
+ * Normally built by DatagramBootstrap rather than by hand
18
+ * @param transport wraps the bound UDP socket
19
+ * @param options same knobs as any other channel
20
+ */
21
+ public constructor(transport: DatagramTransport, options: ChannelOptions) {
22
+ super(transport, options)
23
+
24
+ this.udpTransport = transport
25
+ }
26
+
27
+ /**
28
+ * Where we're bound, read fresh from the socket
29
+ */
30
+ public get localAddress(): PacketAddress {
31
+ return {
32
+ hostname: this.udpTransport.socket.hostname,
33
+ port: this.udpTransport.socket.port,
34
+ }
35
+ }
36
+
37
+ /**
38
+ * True once connected to a single peer, false for a free-for-all socket
39
+ */
40
+ public get isConnected(): boolean {
41
+ return this.udpTransport.isConnected
42
+ }
43
+
44
+ /**
45
+ * Fans one payload out in a single syscall, bypassing the pipeline
46
+ * @param content already encoded, nothing will touch it
47
+ * @param recipients everyone who should get a copy
48
+ */
49
+ public sendMany(
50
+ content: ByteBuf | Uint8Array,
51
+ recipients: readonly PacketAddress[],
52
+ ): number {
53
+ const bytes = content instanceof ByteBuf ? content.toUint8Array() : content
54
+
55
+ return this.udpTransport.sendMany(bytes, recipients)
56
+ }
57
+
58
+ /**
59
+ * Needed before sending to something like 255.255.255.255
60
+ * @param enabled turn SO_BROADCAST on or off
61
+ */
62
+ public setBroadcast(enabled: boolean): this {
63
+ this.udpTransport.socket.setBroadcast(enabled)
64
+ return this
65
+ }
66
+
67
+ /**
68
+ * Caps how many routers our packets can pass through
69
+ * @param ttl hop limit for outgoing packets
70
+ */
71
+ public setTtl(ttl: number): this {
72
+ this.udpTransport.socket.setTTL(ttl)
73
+ return this
74
+ }
75
+
76
+ /**
77
+ * Starts receiving multicast traffic for a group
78
+ * @param group multicast address to join
79
+ * @param interfaceAddress local interface to join on, or null to let the OS pick
80
+ */
81
+ public joinGroup(
82
+ group: string,
83
+ interfaceAddress: string | null = null,
84
+ ): boolean {
85
+ return interfaceAddress === null
86
+ ? this.udpTransport.socket.addMembership(group)
87
+ : this.udpTransport.socket.addMembership(group, interfaceAddress)
88
+ }
89
+
90
+ /**
91
+ * Undoes joinGroup
92
+ * @param group multicast address to leave
93
+ * @param interfaceAddress same interface it was joined on, or null
94
+ */
95
+ public leaveGroup(
96
+ group: string,
97
+ interfaceAddress: string | null = null,
98
+ ): boolean {
99
+ return interfaceAddress === null
100
+ ? this.udpTransport.socket.dropMembership(group)
101
+ : this.udpTransport.socket.dropMembership(group, interfaceAddress)
102
+ }
103
+ }
@@ -0,0 +1,10 @@
1
+ export { DatagramBootstrap } from './bootstrap/index.ts'
2
+ export type {
3
+ DatagramBindOptions,
4
+ DatagramConnectOptions,
5
+ } from './bootstrap/index.ts'
6
+ export { DatagramChannel } from './channel/index.ts'
7
+ export { DatagramPacket } from './packet/index.ts'
8
+ export type { PacketAddress } from './packet/index.ts'
9
+ export { DatagramTransport } from './transport/index.ts'
10
+ export type { UdpHandle } from './transport/index.ts'
@@ -0,0 +1,72 @@
1
+ import { ByteBuf } from '../../buffer/index.ts'
2
+
3
+ /**
4
+ * Either end of a UDP packet
5
+ */
6
+ export type PacketAddress = {
7
+ /**
8
+ * Host name or IP
9
+ */
10
+ readonly hostname: string
11
+
12
+ /**
13
+ * UDP port number
14
+ */
15
+ readonly port: number
16
+ }
17
+
18
+ /**
19
+ * One UDP packet plus who sent it and where it's headed
20
+ * @class
21
+ */
22
+ export class DatagramPacket {
23
+ /**
24
+ * Payload bytes
25
+ */
26
+ public readonly content: ByteBuf
27
+
28
+ /**
29
+ * Destination, null means send to whoever we're connected to
30
+ */
31
+ public readonly recipient: PacketAddress | null
32
+
33
+ /**
34
+ * Filled in for packets we received, null on ones we build
35
+ */
36
+ public readonly sender: PacketAddress | null
37
+
38
+ /**
39
+ * Strings and raw bytes get wrapped in a ByteBuf for you
40
+ * @param content payload in whatever form is handy
41
+ * @param recipient destination, or null for the connected peer
42
+ * @param sender origin, usually only set on incoming packets
43
+ */
44
+ public constructor(
45
+ content: ByteBuf | Uint8Array | string,
46
+ recipient: PacketAddress | null = null,
47
+ sender: PacketAddress | null = null,
48
+ ) {
49
+ this.content = DatagramPacket.bufferOf(content)
50
+ this.recipient = recipient
51
+ this.sender = sender
52
+ }
53
+
54
+ /**
55
+ * Passes ByteBufs through, encodes strings and wraps bytes without copying
56
+ * @param content payload in any accepted form
57
+ */
58
+ private static bufferOf(content: ByteBuf | Uint8Array | string): ByteBuf {
59
+ if (content instanceof ByteBuf) return content
60
+ if (typeof content === 'string') return ByteBuf.fromString(content)
61
+
62
+ return ByteBuf.wrap(content)
63
+ }
64
+
65
+ /**
66
+ * Handy for echo-style servers, sends back to whoever sent this
67
+ * @param content what to send back
68
+ */
69
+ public reply(content: ByteBuf | Uint8Array | string): DatagramPacket {
70
+ return new DatagramPacket(content, this.sender)
71
+ }
72
+ }
@@ -0,0 +1,239 @@
1
+ import type {
2
+ OutgoingDatagram,
3
+ Transport,
4
+ } from '../../channel/transport/index.ts'
5
+ import type { PacketAddress } from '../packet/index.ts'
6
+ import type { udp } from 'bun'
7
+
8
+ /**
9
+ * Bun's UDP socket tagged with whether it's tied to one peer
10
+ */
11
+ export type UdpHandle =
12
+ | {
13
+ /**
14
+ * Free to send anywhere, each write needs a recipient
15
+ */
16
+ readonly kind: 'bound'
17
+ /**
18
+ * Bun socket from udpSocket without a connect target
19
+ */
20
+ readonly socket: udp.Socket<'uint8array'>
21
+ }
22
+ | {
23
+ /**
24
+ * Locked to one peer, recipients are ignored
25
+ */
26
+ readonly kind: 'connected'
27
+ /**
28
+ * Bun socket from udpSocket with a connect target
29
+ */
30
+ readonly socket: udp.ConnectedSocket<'uint8array'>
31
+ }
32
+
33
+ /**
34
+ * Lets a Bun UDP socket sit behind a channel
35
+ * @class
36
+ */
37
+ export class DatagramTransport implements Transport {
38
+ /**
39
+ * Always true here
40
+ */
41
+ public readonly datagram: boolean
42
+
43
+ /**
44
+ * Socket plus the bound or connected tag
45
+ */
46
+ private readonly handle: UdpHandle
47
+
48
+ /**
49
+ * Reused argument list for sendMany
50
+ */
51
+ private readonly batch: (Uint8Array | number | string)[]
52
+
53
+ /**
54
+ * Reused list for sendMany on a connected socket
55
+ */
56
+ private readonly frames: Uint8Array[]
57
+
58
+ /**
59
+ * Wraps a socket DatagramBootstrap already opened
60
+ * @param handle tagged socket, see UdpHandle
61
+ */
62
+ public constructor(handle: UdpHandle) {
63
+ this.handle = handle
64
+ this.datagram = true
65
+ this.batch = []
66
+ this.frames = []
67
+ }
68
+
69
+ /**
70
+ * Raw Bun socket, for things like multicast and TTL
71
+ */
72
+ public get socket(): udp.BaseUDPSocket {
73
+ return this.handle.socket
74
+ }
75
+
76
+ /**
77
+ * True if this was opened with a connect target
78
+ */
79
+ public get isConnected(): boolean {
80
+ return this.handle.kind === 'connected'
81
+ }
82
+
83
+ /**
84
+ * Empty string unless connected
85
+ */
86
+ public get remoteAddress(): string {
87
+ return this.handle.kind === 'connected'
88
+ ? this.handle.socket.remoteAddress.address
89
+ : ''
90
+ }
91
+
92
+ /**
93
+ * Zero unless connected
94
+ */
95
+ public get remotePort(): number {
96
+ return this.handle.kind === 'connected'
97
+ ? this.handle.socket.remoteAddress.port
98
+ : 0
99
+ }
100
+
101
+ /**
102
+ * Full length on success, 0 if Bun refused, -1 once closed
103
+ * @param bytes one whole datagram
104
+ * @param recipient required on a bound socket, ignored on a connected one
105
+ */
106
+ public write(bytes: Uint8Array, recipient: PacketAddress | null): number {
107
+ if (this.handle.socket.closed) return -1
108
+
109
+ const sent = this.send(bytes, recipient)
110
+ return sent ? bytes.length : 0
111
+ }
112
+
113
+ /**
114
+ * Sends many packets with one system call
115
+ * @param packets what to send, in order
116
+ */
117
+ public writeBatch(packets: readonly OutgoingDatagram[]): number {
118
+ const handle = this.handle
119
+ if (handle.socket.closed) return -1
120
+
121
+ try {
122
+ if (handle.kind === 'connected') {
123
+ const frames = this.frames
124
+ frames.length = 0
125
+ for (const packet of packets) frames.push(packet.bytes)
126
+ return this.finish(handle.socket.sendMany(frames), packets)
127
+ }
128
+
129
+ const batch = this.batch
130
+ batch.length = 0
131
+ for (const packet of packets) {
132
+ const recipient = packet.recipient
133
+ if (recipient === null) throw new Error('Recipient is missing')
134
+ batch.push(packet.bytes, recipient.port, recipient.hostname)
135
+ }
136
+
137
+ return this.finish(handle.socket.sendMany(batch), packets)
138
+ } catch (cause) {
139
+ if (!DatagramTransport.isRefused(cause)) throw cause
140
+ return this.writeEach(packets)
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Retries what a short batch left behind, a refused port cuts a batch short too
146
+ * @param sent how many the batch got out
147
+ * @param packets the whole batch
148
+ */
149
+ private finish(sent: number, packets: readonly OutgoingDatagram[]): number {
150
+ if (sent >= packets.length) return sent
151
+
152
+ return sent + this.writeEach(packets.slice(sent))
153
+ }
154
+
155
+ /**
156
+ * Sends packets one by one, used when a batch hits a refused port
157
+ * @param packets what to send, in order
158
+ */
159
+ private writeEach(packets: readonly OutgoingDatagram[]): number {
160
+ let sent = 0
161
+ for (const packet of packets) {
162
+ if (!this.send(packet.bytes, packet.recipient)) return sent
163
+ sent += 1
164
+ }
165
+
166
+ return sent
167
+ }
168
+
169
+ /**
170
+ * Whether an error is the port unreachable a closed peer causes
171
+ * @param error what was thrown
172
+ */
173
+ public static isRefused(error: unknown): boolean {
174
+ return (
175
+ error instanceof Error && 'code' in error && error.code === 'ECONNREFUSED'
176
+ )
177
+ }
178
+
179
+ /**
180
+ * Broadcast-style send in a single syscall, bound sockets only
181
+ * @param bytes the same payload goes to everyone
182
+ * @param recipients who gets a copy
183
+ */
184
+ public sendMany(
185
+ bytes: Uint8Array,
186
+ recipients: readonly PacketAddress[],
187
+ ): number {
188
+ if (this.handle.kind === 'connected') {
189
+ throw new Error('Socket is connected')
190
+ }
191
+
192
+ if (this.handle.socket.closed) return 0
193
+
194
+ const packets: (Uint8Array | number | string)[] = []
195
+ for (const recipient of recipients) {
196
+ packets.push(bytes, recipient.port, recipient.hostname)
197
+ }
198
+
199
+ return this.handle.socket.sendMany(packets)
200
+ }
201
+
202
+ /**
203
+ * Closes the UDP socket outright, there's nothing to flush
204
+ */
205
+ public end(): void {
206
+ this.handle.socket.close()
207
+ }
208
+
209
+ /**
210
+ * No-op, Bun can't pause a UDP socket
211
+ */
212
+ public pause(): void {
213
+ return
214
+ }
215
+
216
+ /**
217
+ * No-op to match pause
218
+ */
219
+ public resume(): void {
220
+ return
221
+ }
222
+
223
+ /**
224
+ * Picks the right Bun send overload and throws if a bound socket has no target
225
+ * @param bytes one whole datagram
226
+ * @param recipient target for bound sockets
227
+ */
228
+ private send(bytes: Uint8Array, recipient: PacketAddress | null): boolean {
229
+ if (this.handle.kind === 'connected') return this.handle.socket.send(bytes)
230
+ if (recipient === null) throw new Error('Recipient is missing')
231
+
232
+ try {
233
+ return this.handle.socket.send(bytes, recipient.port, recipient.hostname)
234
+ } catch (cause) {
235
+ if (DatagramTransport.isRefused(cause)) return true
236
+ throw cause
237
+ }
238
+ }
239
+ }