@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.
- package/LICENSE +21 -0
- package/README.md +105 -2
- package/package.json +65 -4
- package/src/bootstrap/client/index.ts +191 -0
- package/src/bootstrap/dispatcher/index.ts +204 -0
- package/src/bootstrap/index.ts +22 -0
- package/src/bootstrap/reconnect/index.ts +334 -0
- package/src/bootstrap/server/index.ts +284 -0
- package/src/buffer/bits/index.ts +2 -0
- package/src/buffer/bits/reader/index.ts +64 -0
- package/src/buffer/bits/writer/index.ts +79 -0
- package/src/buffer/index.ts +1375 -0
- package/src/buffer/pool/index.ts +46 -0
- package/src/buffer/quantizer/index.ts +101 -0
- package/src/channel/attribute/index.ts +89 -0
- package/src/channel/context/index.ts +621 -0
- package/src/channel/group/index.ts +256 -0
- package/src/channel/handler/duplex/index.ts +105 -0
- package/src/channel/handler/inbound/index.ts +78 -0
- package/src/channel/handler/index.ts +135 -0
- package/src/channel/handler/outbound/index.ts +33 -0
- package/src/channel/index.ts +619 -0
- package/src/channel/initializer/index.ts +77 -0
- package/src/channel/outbound/index.ts +611 -0
- package/src/channel/pipeline/head/index.ts +100 -0
- package/src/channel/pipeline/index.ts +414 -0
- package/src/channel/pipeline/tail/index.ts +45 -0
- package/src/channel/pipeline/tracker/index.ts +120 -0
- package/src/channel/queue/index.ts +203 -0
- package/src/channel/resolved/index.ts +34 -0
- package/src/channel/server/index.ts +164 -0
- package/src/channel/shutdown/index.ts +25 -0
- package/src/channel/simple/index.ts +38 -0
- package/src/channel/transport/index.ts +74 -0
- package/src/channel/transport/socket/index.ts +80 -0
- package/src/cluster/index.ts +360 -0
- package/src/codec/binary/index.ts +102 -0
- package/src/codec/decoder/index.ts +479 -0
- package/src/codec/delimiter/index.ts +189 -0
- package/src/codec/encoder/index.ts +48 -0
- package/src/codec/error/index.ts +33 -0
- package/src/codec/fixed/index.ts +45 -0
- package/src/codec/http/aggregator/index.ts +236 -0
- package/src/codec/http/client/index.ts +120 -0
- package/src/codec/http/decoder/index.ts +4 -0
- package/src/codec/http/decoder/object/index.ts +644 -0
- package/src/codec/http/decoder/request/index.ts +49 -0
- package/src/codec/http/decoder/response/index.ts +59 -0
- package/src/codec/http/encoder/index.ts +3 -0
- package/src/codec/http/encoder/object/index.ts +196 -0
- package/src/codec/http/encoder/request/index.ts +24 -0
- package/src/codec/http/encoder/response/index.ts +26 -0
- package/src/codec/http/headers/index.ts +287 -0
- package/src/codec/http/index.ts +33 -0
- package/src/codec/http/message/content/index.ts +36 -0
- package/src/codec/http/message/full/index.ts +10 -0
- package/src/codec/http/message/full/request/index.ts +45 -0
- package/src/codec/http/message/full/response/index.ts +43 -0
- package/src/codec/http/message/head/index.ts +79 -0
- package/src/codec/http/message/index.ts +16 -0
- package/src/codec/http/message/last/index.ts +27 -0
- package/src/codec/http/message/request/index.ts +39 -0
- package/src/codec/http/message/response/index.ts +31 -0
- package/src/codec/http/method/index.ts +101 -0
- package/src/codec/http/server/index.ts +81 -0
- package/src/codec/http/status/index.ts +170 -0
- package/src/codec/http/version/index.ts +70 -0
- package/src/codec/index.ts +83 -0
- package/src/codec/length/index.ts +330 -0
- package/src/codec/line/index.ts +45 -0
- package/src/codec/message/decoder/index.ts +84 -0
- package/src/codec/message/encoder/index.ts +56 -0
- package/src/codec/message/index.ts +2 -0
- package/src/codec/msgpack/index.ts +51 -0
- package/src/codec/prepender/index.ts +296 -0
- package/src/codec/protobuf/index.ts +57 -0
- package/src/codec/string/decoder/index.ts +47 -0
- package/src/codec/string/encoder/index.ts +26 -0
- package/src/codec/string/index.ts +2 -0
- package/src/codec/websocket/client/index.ts +235 -0
- package/src/codec/websocket/decoder/index.ts +371 -0
- package/src/codec/websocket/encoder/index.ts +170 -0
- package/src/codec/websocket/error/index.ts +42 -0
- package/src/codec/websocket/frame/base/index.ts +55 -0
- package/src/codec/websocket/frame/binary/index.ts +24 -0
- package/src/codec/websocket/frame/close/index.ts +82 -0
- package/src/codec/websocket/frame/continuation/index.ts +31 -0
- package/src/codec/websocket/frame/index.ts +10 -0
- package/src/codec/websocket/frame/opcode/index.ts +35 -0
- package/src/codec/websocket/frame/ping/index.ts +24 -0
- package/src/codec/websocket/frame/pong/index.ts +24 -0
- package/src/codec/websocket/frame/text/index.ts +31 -0
- package/src/codec/websocket/handshake/index.ts +38 -0
- package/src/codec/websocket/index.ts +25 -0
- package/src/codec/websocket/key/index.ts +41 -0
- package/src/codec/websocket/protocol/index.ts +147 -0
- package/src/codec/websocket/server/index.ts +233 -0
- package/src/codec/websocket/status/index.ts +97 -0
- package/src/codec/websocket/upgrade/index.ts +116 -0
- package/src/datagram/bootstrap/index.ts +269 -0
- package/src/datagram/channel/index.ts +103 -0
- package/src/datagram/index.ts +10 -0
- package/src/datagram/packet/index.ts +72 -0
- package/src/datagram/transport/index.ts +239 -0
- package/src/handler/flush/index.ts +187 -0
- package/src/handler/idle/index.ts +295 -0
- package/src/handler/index.ts +22 -0
- package/src/handler/logging/index.ts +195 -0
- package/src/handler/metrics/index.ts +300 -0
- package/src/handler/offload/index.ts +141 -0
- package/src/handler/timeout/error/index.ts +29 -0
- package/src/handler/timeout/index.ts +3 -0
- package/src/handler/timeout/read/index.ts +44 -0
- package/src/handler/timeout/write/index.ts +89 -0
- package/src/handler/traffic/index.ts +259 -0
- package/src/index.ts +258 -0
- package/src/logger/index.ts +47 -0
- package/src/reliable/bootstrap/index.ts +154 -0
- package/src/reliable/cipher/index.ts +227 -0
- package/src/reliable/cookie/index.ts +78 -0
- package/src/reliable/handler/index.ts +1202 -0
- package/src/reliable/handshake/index.ts +144 -0
- package/src/reliable/index.ts +38 -0
- package/src/reliable/lane/index.ts +420 -0
- package/src/reliable/message/index.ts +102 -0
- package/src/reliable/packet/index.ts +117 -0
- package/src/reliable/peer/index.ts +929 -0
- package/src/reliable/registry/index.ts +107 -0
- package/src/serve/bootstrap/index.ts +606 -0
- package/src/serve/channel/index.ts +246 -0
- package/src/serve/index.ts +17 -0
- package/src/serve/outbox/index.ts +292 -0
- package/src/serve/transport/index.ts +96 -0
- package/src/serve/writer/index.ts +119 -0
- package/src/shard/envelope/index.ts +44 -0
- package/src/shard/gateway/index.ts +119 -0
- package/src/shard/index.ts +11 -0
- package/src/shard/link/index.ts +743 -0
- package/src/shard/map/index.ts +91 -0
- package/src/worker/group/index.ts +175 -0
- package/src/worker/index.ts +10 -0
- package/src/worker/pool/index.ts +235 -0
- package/src/worker/service/index.ts +55 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import type { Bootstrap, ConnectOptions } from '../client/index.ts'
|
|
2
|
+
import type { Channel } from '../../channel/index.ts'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Exponential backoff settings, all optional
|
|
6
|
+
*/
|
|
7
|
+
export type ReconnectOptions = {
|
|
8
|
+
/**
|
|
9
|
+
* Wait before the first retry in ms, 100 by default
|
|
10
|
+
*/
|
|
11
|
+
readonly initialDelay?: number
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Cap on the wait in ms, 30 seconds by default
|
|
15
|
+
*/
|
|
16
|
+
readonly maxDelay?: number
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Multiplier per attempt, 2 doubles the wait each time
|
|
20
|
+
*/
|
|
21
|
+
readonly factor?: number
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Random spread either side of the delay, 0 to 1, 0.2 by default
|
|
25
|
+
*/
|
|
26
|
+
readonly jitter?: number
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Give up after this many failures in a row, never by default
|
|
30
|
+
*/
|
|
31
|
+
readonly maxAttempts?: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Optional hooks for watching the connection come and go
|
|
36
|
+
*/
|
|
37
|
+
export type ReconnectEvents = {
|
|
38
|
+
/**
|
|
39
|
+
* Every successful connect, including after a reconnect
|
|
40
|
+
* @param channel the new live channel
|
|
41
|
+
*/
|
|
42
|
+
onConnect?(channel: Channel): void
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The channel closed, a retry is about to be scheduled
|
|
46
|
+
* @param channel the one that just went
|
|
47
|
+
*/
|
|
48
|
+
onDisconnect?(channel: Channel): void
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Good for logging, fires just before we start waiting
|
|
52
|
+
* @param attempt counts from 1 and resets after a good connect
|
|
53
|
+
* @param delay how long we'll wait, in ms
|
|
54
|
+
* @param error why the last try failed
|
|
55
|
+
*/
|
|
56
|
+
onRetry?(attempt: number, delay: number, error: unknown): void
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* ReconnectOptions after the defaults are applied
|
|
61
|
+
*/
|
|
62
|
+
type Backoff = {
|
|
63
|
+
/**
|
|
64
|
+
* First retry wait, in ms
|
|
65
|
+
*/
|
|
66
|
+
readonly initialDelay: number
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Longest wait, in ms
|
|
70
|
+
*/
|
|
71
|
+
readonly maxDelay: number
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Growth per attempt
|
|
75
|
+
*/
|
|
76
|
+
readonly factor: number
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Random spread, 0 to 1
|
|
80
|
+
*/
|
|
81
|
+
readonly jitter: number
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Infinity if we never give up
|
|
85
|
+
*/
|
|
86
|
+
readonly maxAttempts: number
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Keeps a client connection alive, reconnecting with backoff when it drops
|
|
91
|
+
* @class
|
|
92
|
+
*/
|
|
93
|
+
export class ReconnectingClient {
|
|
94
|
+
/**
|
|
95
|
+
* Already set up with handlers, we only call connect on it
|
|
96
|
+
*/
|
|
97
|
+
private readonly bootstrap: Bootstrap
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Target we keep reconnecting to
|
|
101
|
+
*/
|
|
102
|
+
private readonly address: ConnectOptions
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Retry timing with defaults filled in
|
|
106
|
+
*/
|
|
107
|
+
private readonly backoff: Backoff
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* User hooks, any of them may be missing
|
|
111
|
+
*/
|
|
112
|
+
private readonly events: ReconnectEvents
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Promises from waitForChannel that we still owe a channel
|
|
116
|
+
*/
|
|
117
|
+
private readonly waiters: PromiseWithResolvers<Channel>[]
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Live channel, null while we're between connections
|
|
121
|
+
*/
|
|
122
|
+
private current: Channel | null
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Pending retry so stop can cancel it
|
|
126
|
+
*/
|
|
127
|
+
private timer: Timer | null
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Failures since the last good connect
|
|
131
|
+
*/
|
|
132
|
+
private attempts: number
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* True from start until stop or giving up
|
|
136
|
+
*/
|
|
137
|
+
private running: boolean
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Throws a RangeError on bad backoff settings but doesn't connect until start
|
|
141
|
+
* @param bootstrap a configured client bootstrap
|
|
142
|
+
* @param address where to connect
|
|
143
|
+
* @param options backoff timing
|
|
144
|
+
* @param events optional connect, disconnect and retry hooks
|
|
145
|
+
*/
|
|
146
|
+
public constructor(
|
|
147
|
+
bootstrap: Bootstrap,
|
|
148
|
+
address: ConnectOptions,
|
|
149
|
+
options: ReconnectOptions = {},
|
|
150
|
+
events: ReconnectEvents = {},
|
|
151
|
+
) {
|
|
152
|
+
const reason = ReconnectingClient.refusal(options)
|
|
153
|
+
if (reason !== null) throw new RangeError(reason)
|
|
154
|
+
|
|
155
|
+
this.bootstrap = bootstrap
|
|
156
|
+
this.address = address
|
|
157
|
+
this.events = events
|
|
158
|
+
this.backoff = {
|
|
159
|
+
initialDelay: options.initialDelay ?? 100,
|
|
160
|
+
maxDelay: options.maxDelay ?? 30_000,
|
|
161
|
+
factor: options.factor ?? 2,
|
|
162
|
+
jitter: options.jitter ?? 0.2,
|
|
163
|
+
maxAttempts: options.maxAttempts ?? Number.POSITIVE_INFINITY,
|
|
164
|
+
}
|
|
165
|
+
this.waiters = []
|
|
166
|
+
this.current = null
|
|
167
|
+
this.timer = null
|
|
168
|
+
this.attempts = 0
|
|
169
|
+
this.running = false
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Error text for the first bad setting, or null
|
|
174
|
+
* @param options what the caller passed in
|
|
175
|
+
*/
|
|
176
|
+
private static refusal(options: ReconnectOptions): string | null {
|
|
177
|
+
if ((options.initialDelay ?? 1) <= 0) return 'Delay is invalid'
|
|
178
|
+
if ((options.maxDelay ?? 1) <= 0) return 'Delay is invalid'
|
|
179
|
+
if ((options.factor ?? 1) < 1) return 'Factor is invalid'
|
|
180
|
+
if ((options.jitter ?? 0) < 0 || (options.jitter ?? 0) > 1) {
|
|
181
|
+
return 'Jitter is invalid'
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if ((options.maxAttempts ?? 1) < 1) return 'Attempts are invalid'
|
|
185
|
+
|
|
186
|
+
return null
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Null while disconnected, so grab a fresh one rather than holding on to it
|
|
191
|
+
*/
|
|
192
|
+
public get channel(): Channel | null {
|
|
193
|
+
return this.current
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* False before start, after stop, or once we've given up
|
|
198
|
+
*/
|
|
199
|
+
public get isRunning(): boolean {
|
|
200
|
+
return this.running
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Resolves with the first channel, calling it again is harmless
|
|
205
|
+
*/
|
|
206
|
+
public start(): Promise<Channel> {
|
|
207
|
+
if (!this.running) {
|
|
208
|
+
this.running = true
|
|
209
|
+
void this.attempt()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return this.waitForChannel()
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Resolves straight away if connected, rejects if stopped
|
|
217
|
+
*/
|
|
218
|
+
public waitForChannel(): Promise<Channel> {
|
|
219
|
+
if (this.current !== null) return Promise.resolve(this.current)
|
|
220
|
+
if (!this.running) return Promise.reject(new Error('Client is stopped'))
|
|
221
|
+
|
|
222
|
+
const waiter = Promise.withResolvers<Channel>()
|
|
223
|
+
this.waiters.push(waiter)
|
|
224
|
+
return waiter.promise
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Cancels any retry, rejects waiters and waits for the channel to close
|
|
229
|
+
*/
|
|
230
|
+
public async stop(): Promise<void> {
|
|
231
|
+
this.running = false
|
|
232
|
+
if (this.timer !== null) clearTimeout(this.timer)
|
|
233
|
+
this.timer = null
|
|
234
|
+
this.reject(new Error('Client is stopped'))
|
|
235
|
+
|
|
236
|
+
const channel = this.current
|
|
237
|
+
this.current = null
|
|
238
|
+
if (channel !== null) {
|
|
239
|
+
await channel.close()
|
|
240
|
+
await channel.closed
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* One connect try, closing the result if stop was called while we waited
|
|
246
|
+
*/
|
|
247
|
+
private async attempt(): Promise<void> {
|
|
248
|
+
this.timer = null
|
|
249
|
+
if (!this.running) return
|
|
250
|
+
|
|
251
|
+
let channel: Channel
|
|
252
|
+
try {
|
|
253
|
+
channel = await this.bootstrap.connect(this.address)
|
|
254
|
+
} catch (error) {
|
|
255
|
+
this.retry(error)
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (this.isStopped()) {
|
|
260
|
+
await channel.close()
|
|
261
|
+
return
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
this.connected(channel)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Read fresh after an await, since stop may have run in between
|
|
269
|
+
*/
|
|
270
|
+
private isStopped(): boolean {
|
|
271
|
+
return !this.running
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Resets the failure count, wakes waiters and arranges a retry for when it drops
|
|
276
|
+
* @param channel freshly connected
|
|
277
|
+
*/
|
|
278
|
+
private connected(channel: Channel): void {
|
|
279
|
+
this.attempts = 0
|
|
280
|
+
this.current = channel
|
|
281
|
+
this.events.onConnect?.(channel)
|
|
282
|
+
for (const waiter of this.waiters.splice(0)) waiter.resolve(channel)
|
|
283
|
+
|
|
284
|
+
void channel.closed.then((): void => {
|
|
285
|
+
if (this.current !== channel) return
|
|
286
|
+
this.current = null
|
|
287
|
+
this.events.onDisconnect?.(channel)
|
|
288
|
+
this.retry(new Error('Connection was closed'))
|
|
289
|
+
})
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Sets a timer for the next try, or rejects waiters once maxAttempts is used up
|
|
294
|
+
* @param error why the last try failed
|
|
295
|
+
*/
|
|
296
|
+
private retry(error: unknown): void {
|
|
297
|
+
if (!this.running) return
|
|
298
|
+
|
|
299
|
+
this.attempts += 1
|
|
300
|
+
if (this.attempts > this.backoff.maxAttempts) {
|
|
301
|
+
this.running = false
|
|
302
|
+
this.reject(new Error('Reconnect gave up', { cause: error }))
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const delay = this.delayFor(this.attempts)
|
|
307
|
+
this.events.onRetry?.(this.attempts, delay, error)
|
|
308
|
+
this.timer = setTimeout((): void => {
|
|
309
|
+
void this.attempt()
|
|
310
|
+
}, delay)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Exponential delay capped at maxDelay, then jittered either way
|
|
315
|
+
* @param attempt counts from 1
|
|
316
|
+
*/
|
|
317
|
+
private delayFor(attempt: number): number {
|
|
318
|
+
const base = Math.min(
|
|
319
|
+
this.backoff.maxDelay,
|
|
320
|
+
this.backoff.initialDelay * this.backoff.factor ** (attempt - 1),
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
const spread = base * this.backoff.jitter
|
|
324
|
+
return Math.max(0, Math.round(base - spread + Math.random() * spread * 2))
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Empties the waiter list, failing each one
|
|
329
|
+
* @param error what they all get rejected with
|
|
330
|
+
*/
|
|
331
|
+
private reject(error: Error): void {
|
|
332
|
+
for (const waiter of this.waiters.splice(0)) waiter.reject(error)
|
|
333
|
+
}
|
|
334
|
+
}
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import type { SocketListener, TCPSocketListenOptions, TLSOptions } from 'bun'
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
Dispatcher,
|
|
5
|
+
type SocketData,
|
|
6
|
+
type SocketOptions,
|
|
7
|
+
} from '../dispatcher/index.ts'
|
|
8
|
+
import type { Channel } from '../../channel/index.ts'
|
|
9
|
+
import type { ChannelHandler } from '../../channel/handler/index.ts'
|
|
10
|
+
import {
|
|
11
|
+
ChannelInitializer,
|
|
12
|
+
type ChannelSetup,
|
|
13
|
+
} from '../../channel/initializer/index.ts'
|
|
14
|
+
import { ServerChannel } from '../../channel/server/index.ts'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Listen on a TCP port
|
|
18
|
+
*/
|
|
19
|
+
export type TcpBindOptions = {
|
|
20
|
+
/**
|
|
21
|
+
* Interface to bind, every interface if left out
|
|
22
|
+
*/
|
|
23
|
+
readonly hostname?: string
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Use 0 to let the OS pick a free port
|
|
27
|
+
*/
|
|
28
|
+
readonly port: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Listen on a Unix domain socket
|
|
33
|
+
*/
|
|
34
|
+
export type UnixBindOptions = {
|
|
35
|
+
/**
|
|
36
|
+
* Filesystem path to create the socket at
|
|
37
|
+
*/
|
|
38
|
+
readonly unix: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Either a TCP or a Unix target
|
|
43
|
+
*/
|
|
44
|
+
export type BindOptions = TcpBindOptions | UnixBindOptions
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* How the listening socket itself behaves
|
|
48
|
+
*/
|
|
49
|
+
export type ServerOptions = {
|
|
50
|
+
/**
|
|
51
|
+
* Certificates and so on, plain TCP if left out
|
|
52
|
+
*/
|
|
53
|
+
readonly tls?: TLSOptions
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Lets several processes share the port, which is what Cluster relies on
|
|
57
|
+
*/
|
|
58
|
+
readonly reusePort?: boolean
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Open connections allowed at once, extras get hung up on straight away
|
|
62
|
+
*/
|
|
63
|
+
readonly maxConnections?: number
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Open connections allowed from one IP, stops a single host hogging the server
|
|
67
|
+
*/
|
|
68
|
+
readonly maxConnectionsPerAddress?: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Bun accepts reusePort but its types don't list it yet
|
|
73
|
+
*/
|
|
74
|
+
type SharedListenOptions = TCPSocketListenOptions<SocketData> & {
|
|
75
|
+
/**
|
|
76
|
+
* Same as ServerOptions.reusePort
|
|
77
|
+
*/
|
|
78
|
+
readonly reusePort?: boolean
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Builder for servers, every accepted connection gets its own channel
|
|
83
|
+
* @class
|
|
84
|
+
*/
|
|
85
|
+
export class ServerBootstrap {
|
|
86
|
+
/**
|
|
87
|
+
* Every IPv4 interface
|
|
88
|
+
*/
|
|
89
|
+
public static readonly defaultHostname: string = '0.0.0.0'
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Null until childHandler is called, bind refuses to run without it
|
|
93
|
+
*/
|
|
94
|
+
private initializer: ChannelInitializer | null
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Settings for the listening socket
|
|
98
|
+
*/
|
|
99
|
+
private serverSettings: ServerOptions
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Settings every accepted channel gets
|
|
103
|
+
*/
|
|
104
|
+
private childSettings: SocketOptions
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Starts with no handler and default settings
|
|
108
|
+
*/
|
|
109
|
+
public constructor() {
|
|
110
|
+
this.initializer = null
|
|
111
|
+
this.serverSettings = {}
|
|
112
|
+
this.childSettings = {}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Adds this handler to every accepted channel, usually a ChannelInitializer
|
|
117
|
+
* @param handler an initializer, or any handler that's safe to share
|
|
118
|
+
*/
|
|
119
|
+
public childHandler<T extends ChannelHandler>(handler: T): this
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Runs this against every accepted channel to build its pipeline
|
|
123
|
+
* @param setup adds the handlers, may be async
|
|
124
|
+
*/
|
|
125
|
+
public childHandler(setup: ChannelSetup): this
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Remembers how to set up each accepted channel
|
|
129
|
+
* @param handler an initializer, a handler or a setup function
|
|
130
|
+
*/
|
|
131
|
+
public childHandler(handler: ChannelHandler | ChannelSetup): this {
|
|
132
|
+
this.initializer = ChannelInitializer.of<Channel>(handler)
|
|
133
|
+
return this
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Settings for the listening socket, like TLS and port sharing
|
|
138
|
+
* @param options replaces anything set before
|
|
139
|
+
*/
|
|
140
|
+
public options(options: ServerOptions): this {
|
|
141
|
+
this.serverSettings = options
|
|
142
|
+
return this
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Settings every accepted channel gets, like noDelay and water marks
|
|
147
|
+
* @param options replaces anything set before
|
|
148
|
+
*/
|
|
149
|
+
public childOptions(options: SocketOptions): this {
|
|
150
|
+
this.childSettings = options
|
|
151
|
+
return this
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Starts listening and resolves once the socket is bound
|
|
156
|
+
* @param address TCP host and port, or a Unix socket path
|
|
157
|
+
*/
|
|
158
|
+
public bind(address: BindOptions): Promise<ServerChannel> {
|
|
159
|
+
const initializer = this.initializer
|
|
160
|
+
if (initializer === null) {
|
|
161
|
+
return Promise.reject(new Error('Handler is not set'))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const children = new Set<Channel>()
|
|
165
|
+
const perAddress = new Map<string, number>()
|
|
166
|
+
const maxTotal =
|
|
167
|
+
this.serverSettings.maxConnections ?? Number.POSITIVE_INFINITY
|
|
168
|
+
const maxPerAddress =
|
|
169
|
+
this.serverSettings.maxConnectionsPerAddress ?? Number.POSITIVE_INFINITY
|
|
170
|
+
let open = 0
|
|
171
|
+
const dispatcher = new Dispatcher(
|
|
172
|
+
(channel: Channel): void | Promise<void> =>
|
|
173
|
+
initializer.initialize(channel),
|
|
174
|
+
this.childSettings,
|
|
175
|
+
{
|
|
176
|
+
/**
|
|
177
|
+
* Tracks the child so ServerChannel.close can reach it
|
|
178
|
+
* @param channel the new child
|
|
179
|
+
*/
|
|
180
|
+
opened: (channel: Channel): void => {
|
|
181
|
+
children.add(channel)
|
|
182
|
+
void channel.closed.then((): void => {
|
|
183
|
+
children.delete(channel)
|
|
184
|
+
})
|
|
185
|
+
},
|
|
186
|
+
/**
|
|
187
|
+
* A child that never got going has nothing to clean up
|
|
188
|
+
*/
|
|
189
|
+
failed: (): void => {
|
|
190
|
+
return
|
|
191
|
+
},
|
|
192
|
+
/**
|
|
193
|
+
* Turns away connections past the overall or per IP limit
|
|
194
|
+
* @param address the peer's IP
|
|
195
|
+
*/
|
|
196
|
+
admit: (address: string): boolean => {
|
|
197
|
+
const fromAddress = perAddress.get(address) ?? 0
|
|
198
|
+
if (open >= maxTotal || fromAddress >= maxPerAddress) return false
|
|
199
|
+
|
|
200
|
+
open += 1
|
|
201
|
+
perAddress.set(address, fromAddress + 1)
|
|
202
|
+
return true
|
|
203
|
+
},
|
|
204
|
+
/**
|
|
205
|
+
* Frees the slot an admitted connection held
|
|
206
|
+
* @param address the peer's IP
|
|
207
|
+
*/
|
|
208
|
+
release: (address: string): void => {
|
|
209
|
+
open -= 1
|
|
210
|
+
const left = (perAddress.get(address) ?? 1) - 1
|
|
211
|
+
if (left <= 0) perAddress.delete(address)
|
|
212
|
+
else perAddress.set(address, left)
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
let server: ServerChannel
|
|
218
|
+
try {
|
|
219
|
+
server = this.listen(address, dispatcher, children)
|
|
220
|
+
} catch (cause) {
|
|
221
|
+
return Promise.reject(new Error('Bind failed', { cause }))
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return Promise.resolve(server)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Calls Bun.listen for whichever kind of address we got
|
|
229
|
+
* @param address TCP host and port, or a Unix socket path
|
|
230
|
+
* @param dispatcher turns socket callbacks into channel events
|
|
231
|
+
* @param children shared with the ServerChannel we hand back
|
|
232
|
+
*/
|
|
233
|
+
private listen(
|
|
234
|
+
address: BindOptions,
|
|
235
|
+
dispatcher: Dispatcher,
|
|
236
|
+
children: Set<Channel>,
|
|
237
|
+
): ServerChannel {
|
|
238
|
+
const tls =
|
|
239
|
+
this.serverSettings.tls === undefined
|
|
240
|
+
? {}
|
|
241
|
+
: { tls: this.serverSettings.tls }
|
|
242
|
+
|
|
243
|
+
if ('unix' in address) {
|
|
244
|
+
const listener: SocketListener<SocketData> = Bun.listen<SocketData>({
|
|
245
|
+
/**
|
|
246
|
+
* Socket file to create
|
|
247
|
+
*/
|
|
248
|
+
unix: address.unix,
|
|
249
|
+
/**
|
|
250
|
+
* Callbacks shared by every accepted socket
|
|
251
|
+
*/
|
|
252
|
+
socket: dispatcher.handler(),
|
|
253
|
+
...tls,
|
|
254
|
+
})
|
|
255
|
+
return new ServerChannel(listener, { unix: address.unix }, children)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const settings: SharedListenOptions = {
|
|
259
|
+
/**
|
|
260
|
+
* Interface to bind
|
|
261
|
+
*/
|
|
262
|
+
hostname: address.hostname ?? ServerBootstrap.defaultHostname,
|
|
263
|
+
/**
|
|
264
|
+
* Port to bind, 0 for any
|
|
265
|
+
*/
|
|
266
|
+
port: address.port,
|
|
267
|
+
/**
|
|
268
|
+
* Off unless asked for
|
|
269
|
+
*/
|
|
270
|
+
reusePort: this.serverSettings.reusePort ?? false,
|
|
271
|
+
/**
|
|
272
|
+
* Callbacks shared by every accepted socket
|
|
273
|
+
*/
|
|
274
|
+
socket: dispatcher.handler(),
|
|
275
|
+
...tls,
|
|
276
|
+
}
|
|
277
|
+
const listener = Bun.listen<SocketData>(settings)
|
|
278
|
+
return new ServerChannel(
|
|
279
|
+
listener,
|
|
280
|
+
{ hostname: listener.hostname, port: listener.port },
|
|
281
|
+
children,
|
|
282
|
+
)
|
|
283
|
+
}
|
|
284
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ByteBuf } from '../../index.ts'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Reads fields packed by BitWriter, high bits first
|
|
5
|
+
* @class
|
|
6
|
+
*/
|
|
7
|
+
export class BitReader {
|
|
8
|
+
/**
|
|
9
|
+
* Where packed bytes come from
|
|
10
|
+
*/
|
|
11
|
+
private readonly buffer: ByteBuf
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Bits loaded but not read yet, right aligned
|
|
15
|
+
*/
|
|
16
|
+
private current: number
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* How many bits are loaded
|
|
20
|
+
*/
|
|
21
|
+
private left: number
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Reads from this buffer's reader index on
|
|
25
|
+
* @param buffer packed bytes
|
|
26
|
+
*/
|
|
27
|
+
public constructor(buffer: ByteBuf) {
|
|
28
|
+
this.buffer = buffer
|
|
29
|
+
this.current = 0
|
|
30
|
+
this.left = 0
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Reads a field as an unsigned integer
|
|
35
|
+
* @param bits how wide the field is, 1 to 32
|
|
36
|
+
*/
|
|
37
|
+
public read(bits: number): number {
|
|
38
|
+
if (!Number.isInteger(bits) || bits < 1 || bits > 32) {
|
|
39
|
+
throw new RangeError('Bit width is invalid')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (bits > 24) {
|
|
43
|
+
const high = this.read(bits - 16)
|
|
44
|
+
return high * 65536 + this.read(16)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
while (this.left < bits) {
|
|
48
|
+
this.current = ((this.current << 8) | this.buffer.readUint8()) >>> 0
|
|
49
|
+
this.left += 8
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
this.left -= bits
|
|
53
|
+
const value = (this.current >>> this.left) & ((1 << bits) - 1)
|
|
54
|
+
this.current &= (1 << this.left) - 1
|
|
55
|
+
return value
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Reads a single flag
|
|
60
|
+
*/
|
|
61
|
+
public readBoolean(): boolean {
|
|
62
|
+
return this.read(1) === 1
|
|
63
|
+
}
|
|
64
|
+
}
|