@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.
- 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/index.ts +10 -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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019-present Sxip
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
|
1
|
-
|
|
1
|
+
<img alt="Netify. Netty's design at Bun's speed." src=".github/assets/banner.png" />
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://netifyjs.dev">Website</a> ·
|
|
5
|
+
<a href="https://netifyjs.dev/guide/introduction">Docs</a> ·
|
|
6
|
+
<a href="https://netifyjs.dev/scaling/performance">Benchmarks</a> ·
|
|
7
|
+
<a href="LICENSE">MIT licence</a>
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
<p align="center">
|
|
11
|
+
<a href="https://www.npmjs.com/package/@netifyjs/netify"><img alt="npm" src="https://img.shields.io/npm/v/@netifyjs/netify?color=000&labelColor=000" /></a>
|
|
12
|
+
<img alt="Bun 1.2 or newer" src="https://img.shields.io/badge/bun-%E2%89%A51.2-000?labelColor=000" />
|
|
13
|
+
<a href="LICENSE"><img alt="MIT licence" src="https://img.shields.io/badge/licence-MIT-000?labelColor=000" /></a>
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
Netify is a networking framework for Bun, modelled on Netty. You build servers and clients out of channels, pipelines, handlers and codecs, and the same handler runs over TCP, UDP, reliable UDP or WebSocket. It's built for game servers and anything else that keeps a lot of connections open.
|
|
17
|
+
|
|
18
|
+
> Netify is in alpha. The API can still change before 1.0.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
bun add @netifyjs/netify
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Needs Bun 1.2 or newer. No runtime dependencies.
|
|
27
|
+
|
|
28
|
+
## Example
|
|
29
|
+
|
|
30
|
+
A line-based echo server and a client that talks to it.
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import {
|
|
34
|
+
Bootstrap,
|
|
35
|
+
InboundHandlerAdapter,
|
|
36
|
+
LineBasedFrameDecoder,
|
|
37
|
+
ServerBootstrap,
|
|
38
|
+
StringDecoder,
|
|
39
|
+
StringEncoder,
|
|
40
|
+
type Channel,
|
|
41
|
+
type HandlerContext,
|
|
42
|
+
} from '@netifyjs/netify'
|
|
43
|
+
|
|
44
|
+
class Echo extends InboundHandlerAdapter<string> {
|
|
45
|
+
public override channelRead(context: HandlerContext, line: string): void {
|
|
46
|
+
context.writeAndFlushSync(`${line}\n`)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class Print extends InboundHandlerAdapter<string> {
|
|
51
|
+
public override channelRead(context: HandlerContext, line: string): void {
|
|
52
|
+
console.log(line)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const lines = (channel: Channel): void => {
|
|
57
|
+
channel.pipeline
|
|
58
|
+
.addLast<LineBasedFrameDecoder>(
|
|
59
|
+
'lines',
|
|
60
|
+
new LineBasedFrameDecoder({ maxLength: 512 }),
|
|
61
|
+
)
|
|
62
|
+
.addLast<StringDecoder>('decoder', new StringDecoder())
|
|
63
|
+
.addLast<StringEncoder>('encoder', new StringEncoder())
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
await new ServerBootstrap()
|
|
67
|
+
.childHandler((channel: Channel): void => {
|
|
68
|
+
lines(channel)
|
|
69
|
+
channel.pipeline.addLast<Echo>('echo', new Echo())
|
|
70
|
+
})
|
|
71
|
+
.bind({ port: 7000 })
|
|
72
|
+
|
|
73
|
+
const client = await new Bootstrap()
|
|
74
|
+
.handler((channel: Channel): void => {
|
|
75
|
+
lines(channel)
|
|
76
|
+
channel.pipeline.addLast<Print>('print', new Print())
|
|
77
|
+
})
|
|
78
|
+
.connect({ hostname: '127.0.0.1', port: 7000 })
|
|
79
|
+
|
|
80
|
+
await client.writeAndFlush('hello\n')
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Benchmarks
|
|
84
|
+
|
|
85
|
+
One core, 64-byte messages, Ryzen 7 7800X3D. Method and full results are on the [benchmarks page](https://netifyjs.dev/scaling/performance).
|
|
86
|
+
|
|
87
|
+
| Test | Netify | Compared with |
|
|
88
|
+
| ------------------------------------- | ------------ | ----------------------------------------------------- |
|
|
89
|
+
| TCP echo, length-framed | 2.52M msg/s | `node:net` 2.42M, `Bun.listen` 2.84M |
|
|
90
|
+
| UDP echo | 149k msg/s | `node:dgram` 68k, `Bun.udpSocket` 146k |
|
|
91
|
+
| WebSocket echo | 1.19M msg/s | `ws` 1.20M, uWebSockets.js 1.17M |
|
|
92
|
+
| WebSocket broadcast to 1000 clients | 2.16M msg/s | uWebSockets.js 1.69M, `ws` 200k |
|
|
93
|
+
| HTTP plaintext, pipelined | 208k req/s | `Bun.serve` 148k, `node:http` 127k |
|
|
94
|
+
| TCP echo on 4 cores | 7.14M msg/s | `node:net` 6.35M, `Bun.listen` 8.23M |
|
|
95
|
+
|
|
96
|
+
## Docs
|
|
97
|
+
|
|
98
|
+
- [Introduction](https://netifyjs.dev/guide/introduction)
|
|
99
|
+
- [Your first server](https://netifyjs.dev/guide/first-server)
|
|
100
|
+
- [Transports](https://netifyjs.dev/transports/tcp)
|
|
101
|
+
- [Scaling](https://netifyjs.dev/scaling/clustering)
|
|
102
|
+
- [API reference](https://netifyjs.dev/reference/api)
|
|
103
|
+
|
|
104
|
+
## Licence
|
|
105
|
+
|
|
106
|
+
[MIT](LICENSE) © 2019-present Sxip
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netifyjs/netify",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "A Netty-inspired networking framework for Bun, for TCP, UDP, reliable UDP and WebSocket game servers",
|
|
4
|
+
"version": "1.0.0-alpha.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"src"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "bun test",
|
|
14
|
+
"typecheck": "bun --bun tsc --noEmit",
|
|
15
|
+
"lint": "bun --bun eslint .",
|
|
16
|
+
"format": "bun --bun prettier --write .",
|
|
17
|
+
"check": "bun run typecheck && bun run lint && bun --bun prettier --check . && bun test"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"bun": ">=1.2.0"
|
|
21
|
+
},
|
|
22
|
+
"author": "Sxip",
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://netifyjs.dev",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/netifyjs/netify.git"
|
|
31
|
+
},
|
|
32
|
+
"bugs": {
|
|
33
|
+
"url": "https://github.com/netifyjs/netify/issues"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"bun",
|
|
37
|
+
"netty",
|
|
38
|
+
"networking",
|
|
39
|
+
"tcp",
|
|
40
|
+
"udp",
|
|
41
|
+
"reliable-udp",
|
|
42
|
+
"websocket",
|
|
43
|
+
"http",
|
|
44
|
+
"socket",
|
|
45
|
+
"server",
|
|
46
|
+
"game-server",
|
|
47
|
+
"multiplayer",
|
|
48
|
+
"mmo",
|
|
49
|
+
"pipeline",
|
|
50
|
+
"codec",
|
|
51
|
+
"cluster",
|
|
52
|
+
"sharding"
|
|
53
|
+
],
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@eslint/js": "^10.0.1",
|
|
56
|
+
"@types/bun": "^1.4.5",
|
|
57
|
+
"eslint": "^10.15.0",
|
|
58
|
+
"eslint-config-prettier": "^10.1.8",
|
|
59
|
+
"eslint-plugin-import-x": "^4.18.1",
|
|
60
|
+
"jiti": "^2.7.0",
|
|
61
|
+
"msgpackr": "^2.1.4",
|
|
62
|
+
"prettier": "^3.10.1",
|
|
63
|
+
"protobufjs": "^8.8.1",
|
|
64
|
+
"typescript": "^6",
|
|
65
|
+
"typescript-eslint": "^8.74.0"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import type { Socket, 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
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Connect over TCP
|
|
17
|
+
*/
|
|
18
|
+
export type TcpConnectOptions = {
|
|
19
|
+
/**
|
|
20
|
+
* Host name or IP of the server
|
|
21
|
+
*/
|
|
22
|
+
readonly hostname: string
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Server port
|
|
26
|
+
*/
|
|
27
|
+
readonly port: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Connect to a Unix domain socket
|
|
32
|
+
*/
|
|
33
|
+
export type UnixConnectOptions = {
|
|
34
|
+
/**
|
|
35
|
+
* Filesystem path of the server socket
|
|
36
|
+
*/
|
|
37
|
+
readonly unix: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Either a TCP or a Unix target
|
|
42
|
+
*/
|
|
43
|
+
export type ConnectOptions = TcpConnectOptions | UnixConnectOptions
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Socket settings for a client, TLS included
|
|
47
|
+
*/
|
|
48
|
+
export type ClientOptions = {
|
|
49
|
+
/**
|
|
50
|
+
* True for Bun's defaults, or your own settings, plain TCP if left out
|
|
51
|
+
*/
|
|
52
|
+
readonly tls?: TLSOptions | boolean
|
|
53
|
+
} & SocketOptions
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Builder for outgoing connections
|
|
57
|
+
* @class
|
|
58
|
+
*/
|
|
59
|
+
export class Bootstrap {
|
|
60
|
+
/**
|
|
61
|
+
* Null until handler is called, connect refuses to run without it
|
|
62
|
+
*/
|
|
63
|
+
private initializer: ChannelInitializer | null
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Settings each connection gets
|
|
67
|
+
*/
|
|
68
|
+
private settings: ClientOptions
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Starts with no handler and default settings
|
|
72
|
+
*/
|
|
73
|
+
public constructor() {
|
|
74
|
+
this.initializer = null
|
|
75
|
+
this.settings = {}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Adds this handler to each connection, usually a ChannelInitializer
|
|
80
|
+
* @param handler an initializer, or any handler that's safe to share
|
|
81
|
+
*/
|
|
82
|
+
public handler<T extends ChannelHandler>(handler: T): this
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Runs this against each connection to build its pipeline
|
|
86
|
+
* @param setup adds the handlers, may be async
|
|
87
|
+
*/
|
|
88
|
+
public handler(setup: ChannelSetup): this
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Remembers how to set up each connection
|
|
92
|
+
* @param handler an initializer, a handler or a setup function
|
|
93
|
+
*/
|
|
94
|
+
public handler(handler: ChannelHandler | ChannelSetup): this {
|
|
95
|
+
this.initializer = ChannelInitializer.of<Channel>(handler)
|
|
96
|
+
return this
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Settings for each connection, like TLS, noDelay and water marks
|
|
101
|
+
* @param options replaces anything set before
|
|
102
|
+
*/
|
|
103
|
+
public options(options: ClientOptions): this {
|
|
104
|
+
this.settings = options
|
|
105
|
+
return this
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Opens a connection, resolving once the channel is active
|
|
110
|
+
* @param address TCP host and port, or a Unix socket path
|
|
111
|
+
*/
|
|
112
|
+
public async connect(address: ConnectOptions): Promise<Channel> {
|
|
113
|
+
const initializer = this.initializer
|
|
114
|
+
if (initializer === null) throw new Error('Handler is not set')
|
|
115
|
+
|
|
116
|
+
const opening = Promise.withResolvers<Channel>()
|
|
117
|
+
void opening.promise.catch((): undefined => undefined)
|
|
118
|
+
const dispatcher = new Dispatcher(
|
|
119
|
+
(channel: Channel): void | Promise<void> =>
|
|
120
|
+
initializer.initialize(channel),
|
|
121
|
+
this.settings,
|
|
122
|
+
{
|
|
123
|
+
/**
|
|
124
|
+
* Hands the live channel back to connect
|
|
125
|
+
* @param channel the new connection
|
|
126
|
+
*/
|
|
127
|
+
opened: (channel: Channel): void => {
|
|
128
|
+
opening.resolve(channel)
|
|
129
|
+
},
|
|
130
|
+
/**
|
|
131
|
+
* Turns a socket or setup failure into a rejected connect
|
|
132
|
+
* @param cause what went wrong
|
|
133
|
+
*/
|
|
134
|
+
failed: (cause: Error): void => {
|
|
135
|
+
opening.reject(new Error('Connection failed', { cause }))
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
await this.open(address, dispatcher)
|
|
142
|
+
} catch (cause) {
|
|
143
|
+
throw new Error('Connection failed', { cause })
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return opening.promise
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Calls Bun.connect for whichever kind of address we got
|
|
151
|
+
* @param address TCP host and port, or a Unix socket path
|
|
152
|
+
* @param dispatcher turns socket callbacks into channel events
|
|
153
|
+
*/
|
|
154
|
+
private open(
|
|
155
|
+
address: ConnectOptions,
|
|
156
|
+
dispatcher: Dispatcher,
|
|
157
|
+
): Promise<Socket<SocketData>> {
|
|
158
|
+
const tls =
|
|
159
|
+
this.settings.tls === undefined ? {} : { tls: this.settings.tls }
|
|
160
|
+
|
|
161
|
+
if ('unix' in address) {
|
|
162
|
+
return Bun.connect<SocketData>({
|
|
163
|
+
/**
|
|
164
|
+
* Socket file to connect to
|
|
165
|
+
*/
|
|
166
|
+
unix: address.unix,
|
|
167
|
+
/**
|
|
168
|
+
* Callbacks for this socket
|
|
169
|
+
*/
|
|
170
|
+
socket: dispatcher.handler(),
|
|
171
|
+
...tls,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return Bun.connect<SocketData>({
|
|
176
|
+
/**
|
|
177
|
+
* Server host
|
|
178
|
+
*/
|
|
179
|
+
hostname: address.hostname,
|
|
180
|
+
/**
|
|
181
|
+
* Server port
|
|
182
|
+
*/
|
|
183
|
+
port: address.port,
|
|
184
|
+
/**
|
|
185
|
+
* Callbacks for this socket
|
|
186
|
+
*/
|
|
187
|
+
socket: dispatcher.handler(),
|
|
188
|
+
...tls,
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { Channel, type ChannelOptions } from '../../channel/index.ts'
|
|
2
|
+
import { SocketTransport } from '../../channel/transport/index.ts'
|
|
3
|
+
import { ConsoleLogger, type Logger } from '../../logger/index.ts'
|
|
4
|
+
import type { Socket, SocketHandler } from 'bun'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Your hook for adding handlers to each new channel, may be async
|
|
8
|
+
*/
|
|
9
|
+
export type Initializer = (channel: Channel) => void | Promise<void>
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What we stash on socket.data, undefined until open fires
|
|
13
|
+
*/
|
|
14
|
+
export type SocketData = Channel | undefined
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Channel options plus the TCP knobs a bootstrap applies
|
|
18
|
+
*/
|
|
19
|
+
export type SocketOptions = {
|
|
20
|
+
/**
|
|
21
|
+
* Turns Nagle off, defaults to true
|
|
22
|
+
*/
|
|
23
|
+
readonly noDelay?: boolean
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Turns on TCP keep-alive, off unless you ask
|
|
27
|
+
*/
|
|
28
|
+
readonly keepAlive?: boolean
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Milliseconds of silence before the connection is closed, off by default
|
|
32
|
+
*/
|
|
33
|
+
readonly idleTimeout?: number
|
|
34
|
+
} & ChannelOptions
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* How a dispatcher tells its bootstrap a connection worked or didn't
|
|
38
|
+
*/
|
|
39
|
+
export type DispatcherEvents = {
|
|
40
|
+
/**
|
|
41
|
+
* Fires after the initializer has run and the channel is live
|
|
42
|
+
* @param channel ready to use
|
|
43
|
+
*/
|
|
44
|
+
opened(channel: Channel): void
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Fires if we never got as far as an active channel
|
|
48
|
+
* @param error connect error, close reason or setup failure
|
|
49
|
+
*/
|
|
50
|
+
failed(error: Error): void
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Gets a say before a channel is built, false turns the socket away
|
|
54
|
+
* @param address the peer's IP
|
|
55
|
+
*/
|
|
56
|
+
admit?(address: string): boolean
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Fires once an admitted connection has gone
|
|
60
|
+
* @param address the peer's IP, same as admit saw
|
|
61
|
+
*/
|
|
62
|
+
release?(address: string): void
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Glue between Bun's socket callbacks and our channels
|
|
67
|
+
* @class
|
|
68
|
+
*/
|
|
69
|
+
export class Dispatcher {
|
|
70
|
+
/**
|
|
71
|
+
* Run against every channel before it goes active
|
|
72
|
+
*/
|
|
73
|
+
private readonly initializer: Initializer
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Passed to each channel and used for noDelay and keepAlive
|
|
77
|
+
*/
|
|
78
|
+
private readonly options: SocketOptions
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Bootstrap's success and failure hooks
|
|
82
|
+
*/
|
|
83
|
+
private readonly events: DispatcherEvents
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Used when an initializer throws, defaults to the console
|
|
87
|
+
*/
|
|
88
|
+
private readonly logger: Logger
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* One per bootstrap call, shared by every socket it opens
|
|
92
|
+
* @param initializer adds handlers to each new channel
|
|
93
|
+
* @param options socket and channel settings
|
|
94
|
+
* @param events told when a channel opens or fails to
|
|
95
|
+
*/
|
|
96
|
+
public constructor(
|
|
97
|
+
initializer: Initializer,
|
|
98
|
+
options: SocketOptions,
|
|
99
|
+
events: DispatcherEvents,
|
|
100
|
+
) {
|
|
101
|
+
this.initializer = initializer
|
|
102
|
+
this.options = options
|
|
103
|
+
this.events = events
|
|
104
|
+
this.logger = options.logger ?? new ConsoleLogger()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The callbacks object Bun.listen and Bun.connect want
|
|
109
|
+
*/
|
|
110
|
+
public handler(): SocketHandler<SocketData> {
|
|
111
|
+
return {
|
|
112
|
+
/**
|
|
113
|
+
* Plain Uint8Arrays, so every buffer in the pipeline has the same shape
|
|
114
|
+
*/
|
|
115
|
+
binaryType: 'uint8array',
|
|
116
|
+
/**
|
|
117
|
+
* New socket, so build it a channel
|
|
118
|
+
*/
|
|
119
|
+
open: (socket: Socket<SocketData>): void => {
|
|
120
|
+
this.open(socket)
|
|
121
|
+
},
|
|
122
|
+
/**
|
|
123
|
+
* Incoming bytes go to the channel's pipeline
|
|
124
|
+
*/
|
|
125
|
+
data: (socket: Socket<SocketData>, bytes: Uint8Array): void => {
|
|
126
|
+
void socket.data?.handleData(bytes)
|
|
127
|
+
},
|
|
128
|
+
/**
|
|
129
|
+
* Socket has room again, so the channel can write what it held back
|
|
130
|
+
*/
|
|
131
|
+
drain: (socket: Socket<SocketData>): void => {
|
|
132
|
+
socket.data?.handleDrain()
|
|
133
|
+
},
|
|
134
|
+
/**
|
|
135
|
+
* Socket errors end up in exceptionCaught
|
|
136
|
+
*/
|
|
137
|
+
error: (socket: Socket<SocketData>, error: Error): void => {
|
|
138
|
+
void socket.data?.handleError(error)
|
|
139
|
+
},
|
|
140
|
+
/**
|
|
141
|
+
* Never connected at all
|
|
142
|
+
*/
|
|
143
|
+
connectError: (socket: Socket<SocketData>, error: Error): void => {
|
|
144
|
+
this.events.failed(error)
|
|
145
|
+
},
|
|
146
|
+
/**
|
|
147
|
+
* Nothing happened for idleTimeout, so hang up
|
|
148
|
+
*/
|
|
149
|
+
timeout: (socket: Socket<SocketData>): void => {
|
|
150
|
+
void socket.data?.close()
|
|
151
|
+
},
|
|
152
|
+
/**
|
|
153
|
+
* Counts as a failure if the channel never got built
|
|
154
|
+
*/
|
|
155
|
+
close: (socket: Socket<SocketData>, error?: Error): void => {
|
|
156
|
+
const channel = socket.data
|
|
157
|
+
if (channel === undefined) {
|
|
158
|
+
this.events.failed(error ?? new Error('Connection was closed'))
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (error !== undefined) void channel.handleError(error)
|
|
163
|
+
void channel.handleClose()
|
|
164
|
+
},
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Builds the channel, runs the initializer and closes it again if that throws
|
|
170
|
+
* @param socket freshly opened by Bun
|
|
171
|
+
*/
|
|
172
|
+
private open(socket: Socket<SocketData>): void {
|
|
173
|
+
const address = socket.remoteAddress
|
|
174
|
+
if (this.events.admit?.(address) === false) {
|
|
175
|
+
socket.terminate()
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const channel = new Channel(new SocketTransport(socket), this.options)
|
|
180
|
+
socket.data = channel
|
|
181
|
+
socket.setNoDelay(this.options.noDelay ?? true)
|
|
182
|
+
if (this.options.keepAlive === true) socket.setKeepAlive(true)
|
|
183
|
+
const idle = this.options.idleTimeout ?? 0
|
|
184
|
+
if (idle > 0) socket.timeout(Math.max(1, Math.ceil(idle / 1000)))
|
|
185
|
+
void channel.closed.then((): void => {
|
|
186
|
+
this.events.release?.(address)
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
void channel.activate(this.initializer).then(
|
|
190
|
+
(): void => {
|
|
191
|
+
if (channel.isActive) this.events.opened(channel)
|
|
192
|
+
else this.events.failed(new Error('Connection was closed'))
|
|
193
|
+
},
|
|
194
|
+
(error: unknown): void => {
|
|
195
|
+
this.logger.warn(
|
|
196
|
+
{ err: error, channel: channel.id },
|
|
197
|
+
'Channel setup failed',
|
|
198
|
+
)
|
|
199
|
+
void channel.close()
|
|
200
|
+
this.events.failed(new Error('Channel setup failed', { cause: error }))
|
|
201
|
+
},
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export { Bootstrap } from './client/index.ts'
|
|
2
|
+
export type {
|
|
3
|
+
ClientOptions,
|
|
4
|
+
ConnectOptions,
|
|
5
|
+
TcpConnectOptions,
|
|
6
|
+
UnixConnectOptions,
|
|
7
|
+
} from './client/index.ts'
|
|
8
|
+
export { Dispatcher } from './dispatcher/index.ts'
|
|
9
|
+
export type {
|
|
10
|
+
DispatcherEvents,
|
|
11
|
+
SocketData,
|
|
12
|
+
SocketOptions,
|
|
13
|
+
} from './dispatcher/index.ts'
|
|
14
|
+
export { ReconnectingClient } from './reconnect/index.ts'
|
|
15
|
+
export type { ReconnectEvents, ReconnectOptions } from './reconnect/index.ts'
|
|
16
|
+
export { ServerBootstrap } from './server/index.ts'
|
|
17
|
+
export type {
|
|
18
|
+
BindOptions,
|
|
19
|
+
ServerOptions,
|
|
20
|
+
TcpBindOptions,
|
|
21
|
+
UnixBindOptions,
|
|
22
|
+
} from './server/index.ts'
|