@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,107 @@
|
|
|
1
|
+
import type { PacketAddress } from '../../datagram/packet/index.ts'
|
|
2
|
+
import type { ReliablePeer } from '../peer/index.ts'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Peers by address, looked up without building a string per packet
|
|
6
|
+
* @class
|
|
7
|
+
*/
|
|
8
|
+
export class PeerRegistry {
|
|
9
|
+
/**
|
|
10
|
+
* Ports by host, then peers by port
|
|
11
|
+
*/
|
|
12
|
+
private readonly hosts: Map<string, Map<number, ReliablePeer>>
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Every peer, for walking them all
|
|
16
|
+
*/
|
|
17
|
+
private readonly all: Set<ReliablePeer>
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The last peer found, packets tend to come in runs
|
|
21
|
+
*/
|
|
22
|
+
private last: ReliablePeer | null
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Starts empty
|
|
26
|
+
*/
|
|
27
|
+
public constructor() {
|
|
28
|
+
this.hosts = new Map<string, Map<number, ReliablePeer>>()
|
|
29
|
+
this.all = new Set<ReliablePeer>()
|
|
30
|
+
this.last = null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* How many peers there are
|
|
35
|
+
*/
|
|
36
|
+
public get size(): number {
|
|
37
|
+
return this.all.size
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Every peer
|
|
42
|
+
*/
|
|
43
|
+
public get peers(): ReadonlySet<ReliablePeer> {
|
|
44
|
+
return this.all
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The peer at an address, or undefined
|
|
49
|
+
* @param address host and port
|
|
50
|
+
*/
|
|
51
|
+
public find(address: PacketAddress): ReliablePeer | undefined {
|
|
52
|
+
const last = this.last
|
|
53
|
+
if (
|
|
54
|
+
last !== null &&
|
|
55
|
+
last.address.port === address.port &&
|
|
56
|
+
last.address.hostname === address.hostname
|
|
57
|
+
) {
|
|
58
|
+
return last
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const peer = this.hosts.get(address.hostname)?.get(address.port)
|
|
62
|
+
if (peer !== undefined) this.last = peer
|
|
63
|
+
return peer
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Adds a peer, replacing any at the same address
|
|
68
|
+
* @param peer the peer
|
|
69
|
+
*/
|
|
70
|
+
public add(peer: ReliablePeer): void {
|
|
71
|
+
const { hostname, port } = peer.address
|
|
72
|
+
let ports = this.hosts.get(hostname)
|
|
73
|
+
if (ports === undefined) {
|
|
74
|
+
ports = new Map<number, ReliablePeer>()
|
|
75
|
+
this.hosts.set(hostname, ports)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const old = ports.get(port)
|
|
79
|
+
if (old !== undefined) this.all.delete(old)
|
|
80
|
+
ports.set(port, peer)
|
|
81
|
+
this.all.add(peer)
|
|
82
|
+
this.last = peer
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Removes a peer if it's still the one at its address
|
|
87
|
+
* @param peer the peer
|
|
88
|
+
*/
|
|
89
|
+
public remove(peer: ReliablePeer): void {
|
|
90
|
+
this.all.delete(peer)
|
|
91
|
+
if (this.last === peer) this.last = null
|
|
92
|
+
|
|
93
|
+
const ports = this.hosts.get(peer.address.hostname)
|
|
94
|
+
if (ports?.get(peer.address.port) !== peer) return
|
|
95
|
+
ports.delete(peer.address.port)
|
|
96
|
+
if (ports.size === 0) this.hosts.delete(peer.address.hostname)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Forgets everyone
|
|
101
|
+
*/
|
|
102
|
+
public clear(): void {
|
|
103
|
+
this.hosts.clear()
|
|
104
|
+
this.all.clear()
|
|
105
|
+
this.last = null
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
import type { HeadersInit, Server, ServerWebSocket, TLSOptions } from 'bun'
|
|
2
|
+
|
|
3
|
+
import { ByteBuf } from '../../buffer/index.ts'
|
|
4
|
+
import type { ChannelOptions } from '../../channel/index.ts'
|
|
5
|
+
import type { ChannelHandler } from '../../channel/handler/index.ts'
|
|
6
|
+
import { ShutdownEvent } from '../../channel/shutdown/index.ts'
|
|
7
|
+
import {
|
|
8
|
+
ChannelInitializer,
|
|
9
|
+
type ChannelSetup,
|
|
10
|
+
} from '../../channel/initializer/index.ts'
|
|
11
|
+
import { HttpHeaders } from '../../codec/http/headers/index.ts'
|
|
12
|
+
import { PingWebSocketFrame } from '../../codec/websocket/frame/ping/index.ts'
|
|
13
|
+
import { PongWebSocketFrame } from '../../codec/websocket/frame/pong/index.ts'
|
|
14
|
+
import { TextWebSocketFrame } from '../../codec/websocket/frame/text/index.ts'
|
|
15
|
+
import { WebSocketHandshakeComplete } from '../../codec/websocket/handshake/index.ts'
|
|
16
|
+
import { ConsoleLogger } from '../../logger/index.ts'
|
|
17
|
+
import { WebSocketChannel } from '../channel/index.ts'
|
|
18
|
+
import type { WebSocketState } from '../transport/index.ts'
|
|
19
|
+
import { WebSocketFrameWriter } from '../writer/index.ts'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Where to listen
|
|
23
|
+
*/
|
|
24
|
+
export type WebSocketBindOptions = {
|
|
25
|
+
/**
|
|
26
|
+
* Interface to bind, every interface if left out
|
|
27
|
+
*/
|
|
28
|
+
readonly hostname?: string
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Use 0 to let the OS pick a free port
|
|
32
|
+
*/
|
|
33
|
+
readonly port: number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* What the upgrade hook decided
|
|
38
|
+
*/
|
|
39
|
+
export type UpgradeVerdict =
|
|
40
|
+
| {
|
|
41
|
+
/**
|
|
42
|
+
* Let the client in
|
|
43
|
+
*/
|
|
44
|
+
readonly accept: true
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Anything to keep with the channel, like the logged in user
|
|
48
|
+
*/
|
|
49
|
+
readonly data?: unknown
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Extra headers on the 101 response, like a cookie or subprotocol
|
|
53
|
+
*/
|
|
54
|
+
readonly headers?: HeadersInit
|
|
55
|
+
}
|
|
56
|
+
| {
|
|
57
|
+
/**
|
|
58
|
+
* Turn the client away
|
|
59
|
+
*/
|
|
60
|
+
readonly accept: false
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* HTTP status to answer with, 403 by default
|
|
64
|
+
*/
|
|
65
|
+
readonly status?: number
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Runs before the upgrade, so a client can be refused before it gets a socket
|
|
70
|
+
*/
|
|
71
|
+
export type UpgradeHandler = (
|
|
72
|
+
request: Request,
|
|
73
|
+
) => UpgradeVerdict | Promise<UpgradeVerdict>
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* How the native server behaves, the limits keep a bad client from hurting it
|
|
77
|
+
*/
|
|
78
|
+
export type WebSocketBootstrapOptions = {
|
|
79
|
+
/**
|
|
80
|
+
* Only upgrade requests for this path, any path if left out
|
|
81
|
+
*/
|
|
82
|
+
readonly path?: string
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Certificates for wss, plain ws if left out
|
|
86
|
+
*/
|
|
87
|
+
readonly tls?: TLSOptions
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Lets several processes share the port
|
|
91
|
+
*/
|
|
92
|
+
readonly reusePort?: boolean
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Open connections allowed at once, extras get a 503
|
|
96
|
+
*/
|
|
97
|
+
readonly maxConnections?: number
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Biggest message a client may send, 1 MiB by default
|
|
101
|
+
*/
|
|
102
|
+
readonly maxPayloadLength?: number
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Seconds of silence before Bun closes the socket, 120 by default
|
|
106
|
+
*/
|
|
107
|
+
readonly idleTimeout?: number
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Bytes Bun queues per socket before netify holds sends back itself, 16 MiB by default
|
|
111
|
+
*/
|
|
112
|
+
readonly backpressureLimit?: number
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Close a socket that goes past backpressureLimit, off by default
|
|
116
|
+
*/
|
|
117
|
+
readonly closeOnBackpressureLimit?: boolean
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Compress messages with permessage-deflate, off by default
|
|
121
|
+
*/
|
|
122
|
+
readonly perMessageDeflate?: boolean
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Ping idle sockets so dead ones get noticed, on by default
|
|
126
|
+
*/
|
|
127
|
+
readonly sendPings?: boolean
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Checks each request before upgrading it, like authentication, everyone gets in if left out
|
|
131
|
+
*/
|
|
132
|
+
readonly upgrade?: UpgradeHandler
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Pass pings and pongs to the pipeline as frames, off by default
|
|
136
|
+
*/
|
|
137
|
+
readonly controlFrames?: boolean
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Reuses each channel's binary frame once channelRead settles, true by default
|
|
141
|
+
*/
|
|
142
|
+
readonly pooled?: boolean
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* A running native WebSocket server
|
|
147
|
+
* @class
|
|
148
|
+
*/
|
|
149
|
+
export class WebSocketServer {
|
|
150
|
+
/**
|
|
151
|
+
* The Bun server underneath
|
|
152
|
+
*/
|
|
153
|
+
public readonly server: Server<WebSocketState>
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Every open channel
|
|
157
|
+
*/
|
|
158
|
+
private readonly children: Set<WebSocketChannel>
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Wraps the Bun server
|
|
162
|
+
* @param server the Bun server
|
|
163
|
+
* @param children shared with the bootstrap
|
|
164
|
+
*/
|
|
165
|
+
public constructor(
|
|
166
|
+
server: Server<WebSocketState>,
|
|
167
|
+
children: Set<WebSocketChannel>,
|
|
168
|
+
) {
|
|
169
|
+
this.server = server
|
|
170
|
+
this.children = children
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The port it's listening on
|
|
175
|
+
*/
|
|
176
|
+
public get port(): number {
|
|
177
|
+
return this.server.port ?? 0
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The interface it's bound to
|
|
182
|
+
*/
|
|
183
|
+
public get hostname(): string {
|
|
184
|
+
return this.server.hostname ?? ''
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Every open channel
|
|
189
|
+
*/
|
|
190
|
+
public get channels(): ReadonlySet<WebSocketChannel> {
|
|
191
|
+
return this.children
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Sends to everyone on a topic, fanned out natively
|
|
196
|
+
* @param topic the topic
|
|
197
|
+
* @param content bytes go as binary, strings as text
|
|
198
|
+
*/
|
|
199
|
+
public publish(
|
|
200
|
+
topic: string,
|
|
201
|
+
content: ByteBuf | Uint8Array | string,
|
|
202
|
+
): number {
|
|
203
|
+
return this.server.publish(
|
|
204
|
+
topic,
|
|
205
|
+
content instanceof ByteBuf ? content.toUint8Array() : content,
|
|
206
|
+
)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* How many sockets are on a topic
|
|
211
|
+
* @param topic the topic
|
|
212
|
+
*/
|
|
213
|
+
public subscriberCount(topic: string): number {
|
|
214
|
+
return this.server.subscriberCount(topic)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Stops accepting, tells every channel, waits for them to close, then closes the rest
|
|
219
|
+
* @param timeout how long channels get in milliseconds
|
|
220
|
+
*/
|
|
221
|
+
public async shutdownGracefully(timeout = 10000): Promise<void> {
|
|
222
|
+
void this.server.stop(false)
|
|
223
|
+
const channels = [...this.children]
|
|
224
|
+
const event = new ShutdownEvent(Date.now() + timeout)
|
|
225
|
+
for (const channel of channels) {
|
|
226
|
+
void channel.pipeline.fireUserEventTriggered(event)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
await Promise.race([
|
|
230
|
+
Promise.allSettled(
|
|
231
|
+
channels.map(
|
|
232
|
+
(channel: WebSocketChannel): Promise<void> => channel.closed,
|
|
233
|
+
),
|
|
234
|
+
),
|
|
235
|
+
Bun.sleep(timeout),
|
|
236
|
+
])
|
|
237
|
+
await this.close()
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Stops listening and closes every channel
|
|
242
|
+
*/
|
|
243
|
+
public async close(): Promise<void> {
|
|
244
|
+
await Promise.all(
|
|
245
|
+
[...this.children].map((channel: WebSocketChannel): Promise<void> =>
|
|
246
|
+
channel.close(),
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
await this.server.stop(true)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Builder for WebSocket servers on Bun.serve, framing runs natively and each socket gets a channel
|
|
255
|
+
* @class
|
|
256
|
+
*/
|
|
257
|
+
export class WebSocketBootstrap {
|
|
258
|
+
/**
|
|
259
|
+
* Biggest message by default
|
|
260
|
+
*/
|
|
261
|
+
public static readonly defaultMaxPayloadLength = 1024 * 1024
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Null until childHandler is called, bind refuses to run without it
|
|
265
|
+
*/
|
|
266
|
+
private initializer: ChannelInitializer<WebSocketChannel> | null
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Settings for the server
|
|
270
|
+
*/
|
|
271
|
+
private serverSettings: WebSocketBootstrapOptions
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Settings every channel gets
|
|
275
|
+
*/
|
|
276
|
+
private childSettings: ChannelOptions
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Starts with no handler and default settings
|
|
280
|
+
*/
|
|
281
|
+
public constructor() {
|
|
282
|
+
this.initializer = null
|
|
283
|
+
this.serverSettings = {}
|
|
284
|
+
this.childSettings = {}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Adds this handler to every channel, usually a ChannelInitializer
|
|
289
|
+
* @param handler an initializer, or any handler that's safe to share
|
|
290
|
+
*/
|
|
291
|
+
public childHandler<T extends ChannelHandler>(handler: T): this
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Runs this against every channel to build its pipeline
|
|
295
|
+
* @param setup adds the handlers, may be async
|
|
296
|
+
*/
|
|
297
|
+
public childHandler(setup: ChannelSetup<WebSocketChannel>): this
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Remembers how to set up each channel
|
|
301
|
+
* @param handler an initializer, a handler or a setup function
|
|
302
|
+
*/
|
|
303
|
+
public childHandler(
|
|
304
|
+
handler: ChannelHandler | ChannelSetup<WebSocketChannel>,
|
|
305
|
+
): this {
|
|
306
|
+
this.initializer = ChannelInitializer.of<WebSocketChannel>(handler)
|
|
307
|
+
return this
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Settings for the server, like the path, TLS and limits
|
|
312
|
+
* @param options replaces anything set before
|
|
313
|
+
*/
|
|
314
|
+
public options(options: WebSocketBootstrapOptions): this {
|
|
315
|
+
this.serverSettings = options
|
|
316
|
+
return this
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Settings every channel gets, like the logger
|
|
321
|
+
* @param options replaces anything set before
|
|
322
|
+
*/
|
|
323
|
+
public childOptions(options: ChannelOptions): this {
|
|
324
|
+
this.childSettings = options
|
|
325
|
+
return this
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Starts listening
|
|
330
|
+
* @param address host and port
|
|
331
|
+
*/
|
|
332
|
+
public bind(address: WebSocketBindOptions): Promise<WebSocketServer> {
|
|
333
|
+
const initializer = this.initializer
|
|
334
|
+
if (initializer === null) {
|
|
335
|
+
return Promise.reject(new Error('Handler is not set'))
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const children = new Set<WebSocketChannel>()
|
|
339
|
+
let server: Server<WebSocketState>
|
|
340
|
+
try {
|
|
341
|
+
server = this.serve(address, initializer, children)
|
|
342
|
+
} catch (cause) {
|
|
343
|
+
return Promise.reject(new Error('Bind failed', { cause }))
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return Promise.resolve(new WebSocketServer(server, children))
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Calls Bun.serve with the upgrade and socket callbacks wired to channels
|
|
351
|
+
* @param address host and port
|
|
352
|
+
* @param initializer builds each pipeline
|
|
353
|
+
* @param children open channels
|
|
354
|
+
*/
|
|
355
|
+
private serve(
|
|
356
|
+
address: WebSocketBindOptions,
|
|
357
|
+
initializer: ChannelInitializer<WebSocketChannel>,
|
|
358
|
+
children: Set<WebSocketChannel>,
|
|
359
|
+
): Server<WebSocketState> {
|
|
360
|
+
const settings = this.serverSettings
|
|
361
|
+
const childSettings = this.childSettings
|
|
362
|
+
const logger = childSettings.logger ?? new ConsoleLogger()
|
|
363
|
+
const path = settings.path ?? null
|
|
364
|
+
const maxConnections = settings.maxConnections ?? Number.POSITIVE_INFINITY
|
|
365
|
+
const upgrade = settings.upgrade ?? null
|
|
366
|
+
const controlFrames = settings.controlFrames ?? false
|
|
367
|
+
const pooled = settings.pooled ?? true
|
|
368
|
+
|
|
369
|
+
return Bun.serve<WebSocketState>({
|
|
370
|
+
/**
|
|
371
|
+
* Interface to bind
|
|
372
|
+
*/
|
|
373
|
+
hostname: address.hostname ?? '0.0.0.0',
|
|
374
|
+
/**
|
|
375
|
+
* Port to bind, 0 for any
|
|
376
|
+
*/
|
|
377
|
+
port: address.port,
|
|
378
|
+
/**
|
|
379
|
+
* Off unless asked for
|
|
380
|
+
*/
|
|
381
|
+
reusePort: settings.reusePort ?? false,
|
|
382
|
+
...(settings.tls === undefined ? {} : { tls: settings.tls }),
|
|
383
|
+
/**
|
|
384
|
+
* Upgrades requests for our path and turns away the rest
|
|
385
|
+
* @param request the HTTP request
|
|
386
|
+
* @param server the Bun server
|
|
387
|
+
*/
|
|
388
|
+
fetch: (
|
|
389
|
+
request: Request,
|
|
390
|
+
server: Server<WebSocketState>,
|
|
391
|
+
): Response | undefined | Promise<Response | undefined> => {
|
|
392
|
+
const url = new URL(request.url)
|
|
393
|
+
if (path !== null && url.pathname !== path) {
|
|
394
|
+
return new Response(null, { status: 404 })
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (children.size >= maxConnections) {
|
|
398
|
+
return new Response(null, { status: 503 })
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if (upgrade === null) {
|
|
402
|
+
return WebSocketBootstrap.accept(request, server, url, null, null)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return WebSocketBootstrap.decide(request, server, url, upgrade)
|
|
406
|
+
},
|
|
407
|
+
websocket: {
|
|
408
|
+
/**
|
|
409
|
+
* Biggest message a client may send
|
|
410
|
+
*/
|
|
411
|
+
maxPayloadLength:
|
|
412
|
+
settings.maxPayloadLength ??
|
|
413
|
+
WebSocketBootstrap.defaultMaxPayloadLength,
|
|
414
|
+
/**
|
|
415
|
+
* Seconds before an idle socket closes
|
|
416
|
+
*/
|
|
417
|
+
idleTimeout: settings.idleTimeout ?? 120,
|
|
418
|
+
/**
|
|
419
|
+
* Bytes queued before backpressure
|
|
420
|
+
*/
|
|
421
|
+
backpressureLimit: settings.backpressureLimit ?? 16 * 1024 * 1024,
|
|
422
|
+
/**
|
|
423
|
+
* Whether to drop slow readers
|
|
424
|
+
*/
|
|
425
|
+
closeOnBackpressureLimit: settings.closeOnBackpressureLimit ?? false,
|
|
426
|
+
/**
|
|
427
|
+
* Compression
|
|
428
|
+
*/
|
|
429
|
+
perMessageDeflate: settings.perMessageDeflate ?? false,
|
|
430
|
+
/**
|
|
431
|
+
* Keep-alive pings
|
|
432
|
+
*/
|
|
433
|
+
sendPings: settings.sendPings ?? true,
|
|
434
|
+
/**
|
|
435
|
+
* Builds the channel and its pipeline
|
|
436
|
+
* @param socket the new socket
|
|
437
|
+
*/
|
|
438
|
+
open: (socket: ServerWebSocket<WebSocketState>): void => {
|
|
439
|
+
const channel = new WebSocketChannel(socket, childSettings, pooled)
|
|
440
|
+
socket.data.channel = channel
|
|
441
|
+
children.add(channel)
|
|
442
|
+
channel.pipeline.addFirst<WebSocketFrameWriter>(
|
|
443
|
+
'native',
|
|
444
|
+
new WebSocketFrameWriter(channel),
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
void channel
|
|
448
|
+
.activate((): void | Promise<void> =>
|
|
449
|
+
initializer.initialize(channel),
|
|
450
|
+
)
|
|
451
|
+
.then(
|
|
452
|
+
(): Promise<void> =>
|
|
453
|
+
channel.execute((): Promise<void> =>
|
|
454
|
+
channel.pipeline.fireUserEventTriggered(
|
|
455
|
+
WebSocketBootstrap.handshakeOf(socket.data),
|
|
456
|
+
),
|
|
457
|
+
),
|
|
458
|
+
(error: unknown): void => {
|
|
459
|
+
logger.warn(
|
|
460
|
+
{ err: error, channel: channel.id },
|
|
461
|
+
'Channel setup failed',
|
|
462
|
+
)
|
|
463
|
+
void channel.close()
|
|
464
|
+
},
|
|
465
|
+
)
|
|
466
|
+
},
|
|
467
|
+
/**
|
|
468
|
+
* Hands each message to the pipeline as a frame
|
|
469
|
+
* @param socket the socket
|
|
470
|
+
* @param message text or binary
|
|
471
|
+
*/
|
|
472
|
+
message: (
|
|
473
|
+
socket: ServerWebSocket<WebSocketState>,
|
|
474
|
+
message: string | Buffer<ArrayBuffer>,
|
|
475
|
+
): void => {
|
|
476
|
+
const channel = socket.data.channel
|
|
477
|
+
if (channel === null) return
|
|
478
|
+
if (typeof message === 'string') {
|
|
479
|
+
void channel.handleMessage(
|
|
480
|
+
new TextWebSocketFrame(message),
|
|
481
|
+
Buffer.byteLength(message),
|
|
482
|
+
)
|
|
483
|
+
} else {
|
|
484
|
+
channel.handleBinary(message)
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
/**
|
|
488
|
+
* Passes pings on as frames when asked to, Bun answers them either way
|
|
489
|
+
* @param socket the socket
|
|
490
|
+
* @param data the ping payload
|
|
491
|
+
*/
|
|
492
|
+
ping: (socket: ServerWebSocket<WebSocketState>, data: Buffer): void => {
|
|
493
|
+
if (!controlFrames) return
|
|
494
|
+
void socket.data.channel?.handleMessage(
|
|
495
|
+
new PingWebSocketFrame(ByteBuf.wrap(data)),
|
|
496
|
+
)
|
|
497
|
+
},
|
|
498
|
+
/**
|
|
499
|
+
* Passes pongs on as frames when asked to
|
|
500
|
+
* @param socket the socket
|
|
501
|
+
* @param data the pong payload
|
|
502
|
+
*/
|
|
503
|
+
pong: (socket: ServerWebSocket<WebSocketState>, data: Buffer): void => {
|
|
504
|
+
if (!controlFrames) return
|
|
505
|
+
void socket.data.channel?.handleMessage(
|
|
506
|
+
new PongWebSocketFrame(ByteBuf.wrap(data)),
|
|
507
|
+
)
|
|
508
|
+
},
|
|
509
|
+
/**
|
|
510
|
+
* Room to send again
|
|
511
|
+
* @param socket the socket
|
|
512
|
+
*/
|
|
513
|
+
drain: (socket: ServerWebSocket<WebSocketState>): void => {
|
|
514
|
+
socket.data.channel?.handleDrain()
|
|
515
|
+
},
|
|
516
|
+
/**
|
|
517
|
+
* Winds the channel down
|
|
518
|
+
* @param socket the socket
|
|
519
|
+
*/
|
|
520
|
+
close: (socket: ServerWebSocket<WebSocketState>): void => {
|
|
521
|
+
const channel = socket.data.channel
|
|
522
|
+
if (channel === null) return
|
|
523
|
+
children.delete(channel)
|
|
524
|
+
void channel.handleClose()
|
|
525
|
+
},
|
|
526
|
+
},
|
|
527
|
+
})
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Asks the upgrade hook, then upgrades or turns the request away
|
|
532
|
+
* @param request the HTTP request
|
|
533
|
+
* @param server the Bun server
|
|
534
|
+
* @param url the parsed request URL
|
|
535
|
+
* @param upgrade the hook
|
|
536
|
+
*/
|
|
537
|
+
private static async decide(
|
|
538
|
+
request: Request,
|
|
539
|
+
server: Server<WebSocketState>,
|
|
540
|
+
url: URL,
|
|
541
|
+
upgrade: UpgradeHandler,
|
|
542
|
+
): Promise<Response | undefined> {
|
|
543
|
+
let verdict: UpgradeVerdict
|
|
544
|
+
try {
|
|
545
|
+
verdict = await upgrade(request)
|
|
546
|
+
} catch {
|
|
547
|
+
return new Response(null, { status: 500 })
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (!verdict.accept) {
|
|
551
|
+
return new Response(null, { status: verdict.status ?? 403 })
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return WebSocketBootstrap.accept(
|
|
555
|
+
request,
|
|
556
|
+
server,
|
|
557
|
+
url,
|
|
558
|
+
verdict.data ?? null,
|
|
559
|
+
verdict.headers ?? null,
|
|
560
|
+
)
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Upgrades the request, carrying the hook's data onto the socket
|
|
565
|
+
* @param request the HTTP request
|
|
566
|
+
* @param server the Bun server
|
|
567
|
+
* @param url the parsed request URL
|
|
568
|
+
* @param data whatever the hook attached, or null
|
|
569
|
+
* @param headers extra response headers, or null
|
|
570
|
+
*/
|
|
571
|
+
private static accept(
|
|
572
|
+
request: Request,
|
|
573
|
+
server: Server<WebSocketState>,
|
|
574
|
+
url: URL,
|
|
575
|
+
data: unknown,
|
|
576
|
+
headers: HeadersInit | null,
|
|
577
|
+
): Response | undefined {
|
|
578
|
+
const upgraded = server.upgrade(request, {
|
|
579
|
+
/**
|
|
580
|
+
* Filled in as the socket opens
|
|
581
|
+
*/
|
|
582
|
+
data: {
|
|
583
|
+
channel: null,
|
|
584
|
+
uri: url.pathname + url.search,
|
|
585
|
+
headers: request.headers,
|
|
586
|
+
data,
|
|
587
|
+
},
|
|
588
|
+
...(headers === null ? {} : { headers }),
|
|
589
|
+
})
|
|
590
|
+
return upgraded ? undefined : new Response(null, { status: 400 })
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* The same event the JavaScript codec fires once a handshake is done
|
|
595
|
+
* @param state what the upgrade carried
|
|
596
|
+
*/
|
|
597
|
+
private static handshakeOf(
|
|
598
|
+
state: WebSocketState,
|
|
599
|
+
): WebSocketHandshakeComplete {
|
|
600
|
+
return new WebSocketHandshakeComplete(
|
|
601
|
+
state.uri,
|
|
602
|
+
new HttpHeaders(state.headers.entries()),
|
|
603
|
+
state.headers.get('sec-websocket-protocol'),
|
|
604
|
+
)
|
|
605
|
+
}
|
|
606
|
+
}
|