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

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 (142) 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/index.ts +10 -0
  137. package/src/shard/link/index.ts +743 -0
  138. package/src/shard/map/index.ts +91 -0
  139. package/src/worker/group/index.ts +175 -0
  140. package/src/worker/index.ts +10 -0
  141. package/src/worker/pool/index.ts +235 -0
  142. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,259 @@
1
+ import { ByteBuf } from '../../buffer/index.ts'
2
+ import type { Channel } from '../../channel/index.ts'
3
+ import type { HandlerContext } from '../../channel/context/index.ts'
4
+ import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
5
+ import { resolved } from '../../channel/resolved/index.ts'
6
+ import { DatagramPacket } from '../../datagram/packet/index.ts'
7
+ import { WebSocketFrame } from '../../codec/websocket/frame/base/index.ts'
8
+
9
+ /**
10
+ * Limits for a traffic shaping handler, 0 turns one off
11
+ */
12
+ export type TrafficShapingOptions = {
13
+ /**
14
+ * Bytes read per second
15
+ */
16
+ readonly readLimit?: number
17
+
18
+ /**
19
+ * Bytes written per second
20
+ */
21
+ readonly writeLimit?: number
22
+
23
+ /**
24
+ * Longest a single read or write waits in milliseconds, 15000 by default
25
+ */
26
+ readonly maxDelay?: number
27
+ }
28
+
29
+ /**
30
+ * Spends bytes against a rate and says how long to wait
31
+ * @class
32
+ */
33
+ export class TokenBucket {
34
+ /**
35
+ * Bytes per second, 0 for no limit
36
+ */
37
+ public readonly limit: number
38
+
39
+ /**
40
+ * Bytes that can go now, negative when in debt
41
+ */
42
+ private tokens: number
43
+
44
+ /**
45
+ * When tokens were last topped up
46
+ */
47
+ private at: number
48
+
49
+ /**
50
+ * Starts full
51
+ * @param limit bytes per second
52
+ */
53
+ public constructor(limit: number) {
54
+ if (!Number.isFinite(limit) || limit < 0) {
55
+ throw new RangeError('Limit is invalid')
56
+ }
57
+
58
+ this.limit = limit
59
+ this.tokens = limit
60
+ this.at = performance.now()
61
+ }
62
+
63
+ /**
64
+ * Spends bytes and returns how many milliseconds to wait first
65
+ * @param bytes the size
66
+ */
67
+ public take(bytes: number): number {
68
+ if (this.limit === 0 || bytes <= 0) return 0
69
+
70
+ const now = performance.now()
71
+ this.tokens = Math.min(
72
+ this.limit,
73
+ this.tokens + ((now - this.at) * this.limit) / 1000,
74
+ )
75
+ this.at = now
76
+ this.tokens -= bytes
77
+
78
+ return this.tokens >= 0 ? 0 : (-this.tokens * 1000) / this.limit
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Slows reads and writes down to a byte rate instead of dropping them
84
+ * @class
85
+ */
86
+ export class TrafficShapingHandler extends DuplexHandlerAdapter {
87
+ /**
88
+ * The read bucket
89
+ */
90
+ private readonly reads: TokenBucket
91
+
92
+ /**
93
+ * The write bucket
94
+ */
95
+ private readonly writes: TokenBucket
96
+
97
+ /**
98
+ * Longest wait in milliseconds
99
+ */
100
+ private readonly maxDelay: number
101
+
102
+ /**
103
+ * Bytes each channel had read when last seen
104
+ */
105
+ private readonly seen: WeakMap<Channel, number>
106
+
107
+ /**
108
+ * Delayed writes still waiting, by channel
109
+ */
110
+ private readonly waiting: WeakMap<Channel, number>
111
+
112
+ /**
113
+ * Channels that asked for a flush while writes were waiting
114
+ */
115
+ private readonly flushes: WeakSet<Channel>
116
+
117
+ /**
118
+ * Sets the limits
119
+ * @param options the limits
120
+ */
121
+ public constructor(options: TrafficShapingOptions) {
122
+ super()
123
+
124
+ const maxDelay = options.maxDelay ?? 15000
125
+ if (!Number.isFinite(maxDelay) || maxDelay < 0) {
126
+ throw new RangeError('Delay is invalid')
127
+ }
128
+
129
+ this.reads = new TokenBucket(options.readLimit ?? 0)
130
+ this.writes = new TokenBucket(options.writeLimit ?? 0)
131
+ this.maxDelay = maxDelay
132
+ this.seen = new WeakMap<Channel, number>()
133
+ this.waiting = new WeakMap<Channel, number>()
134
+ this.flushes = new WeakSet<Channel>()
135
+ }
136
+
137
+ /**
138
+ * Size of a message as it goes out
139
+ * @param message the message
140
+ */
141
+ public static sizeOf(message: unknown): number {
142
+ if (message instanceof ByteBuf) return message.readableBytes
143
+ if (message instanceof Uint8Array) return message.length
144
+ if (typeof message === 'string') return Buffer.byteLength(message)
145
+ if (message instanceof DatagramPacket) return message.content.readableBytes
146
+ if (message instanceof WebSocketFrame) return message.content.readableBytes
147
+
148
+ return 0
149
+ }
150
+
151
+ /**
152
+ * Holds the message until the read rate allows it
153
+ * @param context the channel's context
154
+ * @param message the message
155
+ */
156
+ public override channelRead(
157
+ context: HandlerContext,
158
+ message: unknown,
159
+ ): Promise<void> {
160
+ const channel = context.channel
161
+ const total = channel.bytesRead
162
+ const bytes = total - (this.seen.get(channel) ?? 0)
163
+ this.seen.set(channel, total)
164
+
165
+ const wait = this.delay(this.reads.take(bytes))
166
+ if (wait === 0) return context.fireChannelRead(message)
167
+
168
+ return Bun.sleep(wait).then((): Promise<void> =>
169
+ context.fireChannelRead(message),
170
+ )
171
+ }
172
+
173
+ /**
174
+ * Holds the write until the write rate allows it
175
+ * @param context the channel's context
176
+ * @param message the message
177
+ */
178
+ public override write(
179
+ context: HandlerContext,
180
+ message: unknown,
181
+ ): Promise<void> {
182
+ const channel = context.channel
183
+ const wait = this.delay(
184
+ this.writes.take(TrafficShapingHandler.sizeOf(message)),
185
+ )
186
+ if (wait === 0 && (this.waiting.get(channel) ?? 0) === 0) {
187
+ return context.write(message)
188
+ }
189
+
190
+ if (message instanceof ByteBuf) message.detach()
191
+
192
+ this.waiting.set(channel, (this.waiting.get(channel) ?? 0) + 1)
193
+ return Bun.sleep(wait).then((): Promise<void> =>
194
+ this.release(context, message),
195
+ )
196
+ }
197
+
198
+ /**
199
+ * Waits for held writes before flushing
200
+ * @param context the channel's context
201
+ */
202
+ public override flush(context: HandlerContext): Promise<void> {
203
+ if ((this.waiting.get(context.channel) ?? 0) === 0) return context.flush()
204
+
205
+ this.flushes.add(context.channel)
206
+ return resolved
207
+ }
208
+
209
+ /**
210
+ * Sends a held write and the flush that was asked for meanwhile
211
+ * @param context the channel's context
212
+ * @param message the message
213
+ */
214
+ private release(context: HandlerContext, message: unknown): Promise<void> {
215
+ const channel = context.channel
216
+ const left = (this.waiting.get(channel) ?? 1) - 1
217
+ this.waiting.set(channel, left)
218
+
219
+ const written = context.write(message)
220
+ if (left === 0 && this.flushes.delete(channel)) void context.flush()
221
+ return written
222
+ }
223
+
224
+ /**
225
+ * Caps a wait
226
+ * @param wait milliseconds asked for
227
+ */
228
+ private delay(wait: number): number {
229
+ return wait <= 0 ? 0 : Math.min(Math.ceil(wait), this.maxDelay)
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Shapes one channel, so each pipeline gets its own
235
+ * @class
236
+ */
237
+ export class ChannelTrafficShapingHandler extends TrafficShapingHandler {
238
+ /**
239
+ * Sets the limits for one channel
240
+ * @param options the limits
241
+ */
242
+ public constructor(options: TrafficShapingOptions) {
243
+ super(options)
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Shapes every channel it's added to against one shared limit
249
+ * @class
250
+ */
251
+ export class GlobalTrafficShapingHandler extends TrafficShapingHandler {
252
+ /**
253
+ * Sets the limits for the whole server
254
+ * @param options the limits
255
+ */
256
+ public constructor(options: TrafficShapingOptions) {
257
+ super(options)
258
+ }
259
+ }
package/src/index.ts ADDED
@@ -0,0 +1,258 @@
1
+ export {
2
+ Bootstrap,
3
+ Dispatcher,
4
+ ReconnectingClient,
5
+ ServerBootstrap,
6
+ } from './bootstrap/index.ts'
7
+ export type {
8
+ BindOptions,
9
+ ClientOptions,
10
+ ServerOptions,
11
+ ConnectOptions,
12
+ TcpBindOptions,
13
+ TcpConnectOptions,
14
+ UnixBindOptions,
15
+ UnixConnectOptions,
16
+ DispatcherEvents,
17
+ ReconnectEvents,
18
+ ReconnectOptions,
19
+ SocketData,
20
+ SocketOptions,
21
+ } from './bootstrap/index.ts'
22
+ export {
23
+ BitReader,
24
+ BitWriter,
25
+ ByteBuf,
26
+ ByteBufPool,
27
+ Quantizer,
28
+ } from './buffer/index.ts'
29
+ export type { Endian, QuantizerOptions } from './buffer/index.ts'
30
+ export {
31
+ AttributeKey,
32
+ AttributeMap,
33
+ Channel,
34
+ ChannelGroup,
35
+ ChannelInitializer,
36
+ DuplexHandlerAdapter,
37
+ EventQueue,
38
+ HandlerContext,
39
+ InboundHandlerAdapter,
40
+ OutboundHandlerAdapter,
41
+ HeadHandler,
42
+ OutboundBuffer,
43
+ Pipeline,
44
+ ServerChannel,
45
+ ShutdownEvent,
46
+ SimpleInboundHandler,
47
+ SocketTransport,
48
+ TailHandler,
49
+ WriteTracker,
50
+ } from './channel/index.ts'
51
+ export type {
52
+ ChannelHandler,
53
+ DuplexHandler,
54
+ InboundHandler,
55
+ ChannelMatcher,
56
+ ChannelOptions,
57
+ ChannelSetup,
58
+ GroupFailure,
59
+ GroupResult,
60
+ LifecycleCallbacks,
61
+ OutboundHandler,
62
+ OutboundOptions,
63
+ QueueEvents,
64
+ ServerAddress,
65
+ Sink,
66
+ Transport,
67
+ } from './channel/index.ts'
68
+ export { ConsoleLogger } from './logger/index.ts'
69
+ export type { LogFields, Logger } from './logger/index.ts'
70
+ export {
71
+ ByteToMessageDecoder,
72
+ DecoderError,
73
+ DelimiterBasedFrameDecoder,
74
+ EncoderError,
75
+ FixedLengthFrameDecoder,
76
+ LengthFieldBasedFrameDecoder,
77
+ LengthFieldPrepender,
78
+ LineBasedFrameDecoder,
79
+ MessageToByteEncoder,
80
+ MessageToMessageDecoder,
81
+ MessageToMessageEncoder,
82
+ StringDecoder,
83
+ StringEncoder,
84
+ } from './codec/index.ts'
85
+ export type {
86
+ DecoderOptions,
87
+ DelimiterOptions,
88
+ LengthFieldLength,
89
+ LengthFieldOptions,
90
+ LineOptions,
91
+ PrependerOptions,
92
+ } from './codec/index.ts'
93
+ export {
94
+ ChannelTrafficShapingHandler,
95
+ FlushConsolidationHandler,
96
+ GlobalTrafficShapingHandler,
97
+ IdleStateEvent,
98
+ IdleStateHandler,
99
+ LoggingHandler,
100
+ MetricsHandler,
101
+ OffloadHandler,
102
+ ReadTimeoutError,
103
+ ReadTimeoutHandler,
104
+ WriteTimeoutError,
105
+ TokenBucket,
106
+ TrafficShapingHandler,
107
+ WriteTimeoutHandler,
108
+ } from './handler/index.ts'
109
+ export type {
110
+ FlushConsolidationOptions,
111
+ IdleOptions,
112
+ IdleState,
113
+ MetricsOptions,
114
+ MetricsSnapshot,
115
+ OffloadOptions,
116
+ TrafficShapingOptions,
117
+ } from './handler/index.ts'
118
+ export {
119
+ DatagramBootstrap,
120
+ DatagramChannel,
121
+ DatagramPacket,
122
+ DatagramTransport,
123
+ } from './datagram/index.ts'
124
+ export type {
125
+ DatagramBindOptions,
126
+ DatagramConnectOptions,
127
+ PacketAddress,
128
+ UdpHandle,
129
+ } from './datagram/index.ts'
130
+ export {
131
+ CookieJar,
132
+ PacketKind,
133
+ connectPacket,
134
+ Lane,
135
+ PacketCipher,
136
+ PeerRegistry,
137
+ ReliableBootstrap,
138
+ PeerConnected,
139
+ PeerDisconnected,
140
+ ReliableHandler,
141
+ ReliableMessage,
142
+ ReliablePeer,
143
+ } from './reliable/index.ts'
144
+ export type {
145
+ EncryptionOptions,
146
+ KeyPair,
147
+ ReliableClient,
148
+ ReliableServer,
149
+ ReliableSettings,
150
+ Deliver,
151
+ Delivery,
152
+ DisconnectReason,
153
+ LaneOptions,
154
+ Outgoing,
155
+ PeerOptions,
156
+ PeerState,
157
+ PeerStats,
158
+ ReliableOptions,
159
+ ReliableRole,
160
+ SimulateOptions,
161
+ } from './reliable/index.ts'
162
+ export {
163
+ BinaryWebSocketFrame,
164
+ CloseWebSocketFrame,
165
+ ContinuationWebSocketFrame,
166
+ CorruptedFrameError,
167
+ FullHttpRequest,
168
+ FullHttpResponse,
169
+ HandshakeError,
170
+ HttpClientCodec,
171
+ HttpContent,
172
+ HttpHeaders,
173
+ HttpMessage,
174
+ HttpMethod,
175
+ HttpObjectAggregator,
176
+ HttpObjectDecoder,
177
+ HttpObjectEncoder,
178
+ HttpRequest,
179
+ HttpRequestDecoder,
180
+ HttpRequestEncoder,
181
+ HttpResponse,
182
+ HttpResponseDecoder,
183
+ HttpResponseEncoder,
184
+ HttpResponseStatus,
185
+ HttpServerCodec,
186
+ HttpVersion,
187
+ LastHttpContent,
188
+ PingWebSocketFrame,
189
+ PongWebSocketFrame,
190
+ TextWebSocketFrame,
191
+ WebSocketClientProtocolHandler,
192
+ WebSocketCloseStatus,
193
+ WebSocketFrame,
194
+ WebSocketFrameDecoder,
195
+ WebSocketFrameEncoder,
196
+ WebSocketHandshakeComplete,
197
+ WebSocketKey,
198
+ WebSocketOpcode,
199
+ WebSocketProtocolHandler,
200
+ WebSocketServerProtocolHandler,
201
+ WebSocketUpgrade,
202
+ } from './codec/index.ts'
203
+ export type {
204
+ ContentSource,
205
+ FrameSource,
206
+ FullHttpMessage,
207
+ HeaderEntry,
208
+ HeaderValue,
209
+ HttpDecoderOptions,
210
+ HttpObject,
211
+ WebSocketClientOptions,
212
+ WebSocketDecoderOptions,
213
+ WebSocketEncoderOptions,
214
+ WebSocketOpcodeValue,
215
+ WebSocketServerOptions,
216
+ } from './codec/index.ts'
217
+ export { Cluster } from './cluster/index.ts'
218
+ export type { ClusterOptions, ReloadOrder } from './cluster/index.ts'
219
+ export { ShardLink, ShardMap } from './shard/index.ts'
220
+ export type {
221
+ ShardLinkOptions,
222
+ ShardListener,
223
+ ShardMapOptions,
224
+ ShardPeer,
225
+ ShardResponder,
226
+ } from './shard/index.ts'
227
+ export { WorkerGroup, WorkerPool, WorkerService } from './worker/index.ts'
228
+ export type {
229
+ WorkerGroupOptions,
230
+ WorkerPoolOptions,
231
+ WorkerReply,
232
+ WorkerRequest,
233
+ WorkerTask,
234
+ } from './worker/index.ts'
235
+ export { BinaryCodec, MessagePackCodec, ProtobufCodec } from './codec/index.ts'
236
+ export type {
237
+ BinaryCodecOptions,
238
+ MessagePacker,
239
+ ProtobufType,
240
+ } from './codec/index.ts'
241
+ export {
242
+ WebSocketBootstrap,
243
+ WebSocketChannel,
244
+ WebSocketFrameWriter,
245
+ WebSocketOutbox,
246
+ WebSocketServer,
247
+ WebSocketTransport,
248
+ } from './serve/index.ts'
249
+ export type {
250
+ OutboxEvents,
251
+ OutgoingMessage,
252
+ SendResult,
253
+ UpgradeHandler,
254
+ UpgradeVerdict,
255
+ WebSocketBindOptions,
256
+ WebSocketBootstrapOptions,
257
+ WebSocketState,
258
+ } from './serve/index.ts'
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Extra context attached to a log line, like the channel id
3
+ */
4
+ export type LogFields = Record<string, unknown>
5
+
6
+ /**
7
+ * The bit of pino we use, so a pino instance drops straight in
8
+ */
9
+ export type Logger = {
10
+ /**
11
+ * For noisy stuff like discarded messages
12
+ * @param fields context for the line
13
+ * @param message short human-readable text
14
+ */
15
+ debug(fields: LogFields, message: string): void
16
+
17
+ /**
18
+ * For things someone should probably look at
19
+ * @param fields context for the line, often with an err
20
+ * @param message short human-readable text
21
+ */
22
+ warn(fields: LogFields, message: string): void
23
+ }
24
+
25
+ /**
26
+ * Fallback logger for when you haven't plugged in pino
27
+ * @class
28
+ */
29
+ export class ConsoleLogger implements Logger {
30
+ /**
31
+ * Goes to console.debug
32
+ * @param fields printed after the message
33
+ * @param message printed first
34
+ */
35
+ public debug(fields: LogFields, message: string): void {
36
+ console.debug(message, fields)
37
+ }
38
+
39
+ /**
40
+ * Goes to console.warn
41
+ * @param fields printed after the message
42
+ * @param message printed first
43
+ */
44
+ public warn(fields: LogFields, message: string): void {
45
+ console.warn(message, fields)
46
+ }
47
+ }
@@ -0,0 +1,154 @@
1
+ import type { ChannelOptions } from '../../channel/index.ts'
2
+ import type { ChannelSetup } from '../../channel/initializer/index.ts'
3
+ import {
4
+ DatagramBootstrap,
5
+ type DatagramBindOptions,
6
+ } from '../../datagram/bootstrap/index.ts'
7
+ import type { DatagramChannel } from '../../datagram/channel/index.ts'
8
+ import type { PacketAddress } from '../../datagram/packet/index.ts'
9
+ import { ReliableHandler, type ReliableOptions } from '../handler/index.ts'
10
+ import type { ReliablePeer } from '../peer/index.ts'
11
+
12
+ /**
13
+ * Everything in ReliableOptions except the role and server, which the bootstrap fills in
14
+ */
15
+ export type ReliableSettings = Omit<ReliableOptions, 'role' | 'server'>
16
+
17
+ /**
18
+ * A bound reliable server
19
+ */
20
+ export type ReliableServer = {
21
+ /**
22
+ * The UDP channel
23
+ */
24
+ readonly channel: DatagramChannel
25
+
26
+ /**
27
+ * The reliable handler on it
28
+ */
29
+ readonly handler: ReliableHandler
30
+ }
31
+
32
+ /**
33
+ * A connected reliable client
34
+ */
35
+ export type ReliableClient = {
36
+ /**
37
+ * The UDP channel
38
+ */
39
+ readonly channel: DatagramChannel
40
+
41
+ /**
42
+ * The reliable handler on it
43
+ */
44
+ readonly handler: ReliableHandler
45
+
46
+ /**
47
+ * The server
48
+ */
49
+ readonly peer: ReliablePeer
50
+ }
51
+
52
+ /**
53
+ * Builder for reliable UDP servers and clients
54
+ * @class
55
+ */
56
+ export class ReliableBootstrap {
57
+ /**
58
+ * Reliable settings for each channel
59
+ */
60
+ private settings: ReliableSettings
61
+
62
+ /**
63
+ * Channel settings for each channel
64
+ */
65
+ private channelSettings: ChannelOptions
66
+
67
+ /**
68
+ * Adds your handlers after the reliable one, or null
69
+ */
70
+ private setup: ChannelSetup<DatagramChannel> | null
71
+
72
+ /**
73
+ * Starts with defaults and no handlers
74
+ */
75
+ public constructor() {
76
+ this.settings = {}
77
+ this.channelSettings = {}
78
+ this.setup = null
79
+ }
80
+
81
+ /**
82
+ * Reliable settings, like lanes, limits and encryption
83
+ * @param options replaces anything set before
84
+ */
85
+ public options(options: ReliableSettings): this {
86
+ this.settings = options
87
+ return this
88
+ }
89
+
90
+ /**
91
+ * Channel settings, like the logger
92
+ * @param options replaces anything set before
93
+ */
94
+ public channelOptions(options: ChannelOptions): this {
95
+ this.channelSettings = options
96
+ return this
97
+ }
98
+
99
+ /**
100
+ * Adds your handlers after the reliable one
101
+ * @param setup gets each new channel
102
+ */
103
+ public handler(setup: ChannelSetup<DatagramChannel>): this {
104
+ this.setup = setup
105
+ return this
106
+ }
107
+
108
+ /**
109
+ * Starts a server
110
+ * @param address where to listen
111
+ */
112
+ public async bind(address: DatagramBindOptions): Promise<ReliableServer> {
113
+ const handler = new ReliableHandler({ ...this.settings, role: 'server' })
114
+ const channel = await this.datagram(handler).bind(address)
115
+
116
+ return { channel, handler }
117
+ }
118
+
119
+ /**
120
+ * Connects to a server and resolves once the handshake is done
121
+ * @param server where the server is
122
+ */
123
+ public async connect(server: PacketAddress): Promise<ReliableClient> {
124
+ const handler = new ReliableHandler({
125
+ ...this.settings,
126
+ role: 'client',
127
+ server,
128
+ })
129
+ const channel = await this.datagram(handler).bind({ port: 0 })
130
+
131
+ try {
132
+ const peer = await handler.connected
133
+ return { channel, handler, peer }
134
+ } catch (cause) {
135
+ await channel.close()
136
+ throw new Error('Connection failed', { cause })
137
+ }
138
+ }
139
+
140
+ /**
141
+ * A datagram bootstrap with our handler first in line
142
+ * @param handler the reliable handler
143
+ */
144
+ private datagram(handler: ReliableHandler): DatagramBootstrap {
145
+ const setup = this.setup
146
+
147
+ return new DatagramBootstrap()
148
+ .options(this.channelSettings)
149
+ .handler((channel: DatagramChannel): void | Promise<void> => {
150
+ channel.pipeline.addLast<ReliableHandler>('reliable', handler)
151
+ return setup?.(channel)
152
+ })
153
+ }
154
+ }