@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
|
@@ -0,0 +1,1202 @@
|
|
|
1
|
+
import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
|
|
2
|
+
import type { HandlerContext } from '../../channel/context/index.ts'
|
|
3
|
+
import { pending, resolved } from '../../channel/resolved/index.ts'
|
|
4
|
+
import {
|
|
5
|
+
DatagramPacket,
|
|
6
|
+
type PacketAddress,
|
|
7
|
+
} from '../../datagram/packet/index.ts'
|
|
8
|
+
import { type KeyPair, PacketCipher } from '../cipher/index.ts'
|
|
9
|
+
import { CookieJar } from '../cookie/index.ts'
|
|
10
|
+
import {
|
|
11
|
+
acceptPacket,
|
|
12
|
+
challengePacket,
|
|
13
|
+
connectPacket,
|
|
14
|
+
disconnectPacket,
|
|
15
|
+
isOurs,
|
|
16
|
+
keySalt,
|
|
17
|
+
readUint32,
|
|
18
|
+
} from '../handshake/index.ts'
|
|
19
|
+
import type { LaneOptions } from '../lane/index.ts'
|
|
20
|
+
import {
|
|
21
|
+
type DisconnectReason,
|
|
22
|
+
PeerConnected,
|
|
23
|
+
PeerDisconnected,
|
|
24
|
+
ReliableMessage,
|
|
25
|
+
} from '../message/index.ts'
|
|
26
|
+
import {
|
|
27
|
+
ConnectField,
|
|
28
|
+
PacketKind,
|
|
29
|
+
acceptSize,
|
|
30
|
+
challengeSize,
|
|
31
|
+
connectSize,
|
|
32
|
+
cookieSize,
|
|
33
|
+
dataHeaderSize,
|
|
34
|
+
encryptFlag,
|
|
35
|
+
keySize,
|
|
36
|
+
messageHeaderSize,
|
|
37
|
+
} from '../packet/index.ts'
|
|
38
|
+
import { ReliablePeer } from '../peer/index.ts'
|
|
39
|
+
import { PeerRegistry } from '../registry/index.ts'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Which end of the handshake we are
|
|
43
|
+
*/
|
|
44
|
+
export type ReliableRole = 'server' | 'client'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Fake network trouble for testing, applied to everything we send
|
|
48
|
+
*/
|
|
49
|
+
export type SimulateOptions = {
|
|
50
|
+
/**
|
|
51
|
+
* Share of packets dropped, 0 to 1
|
|
52
|
+
*/
|
|
53
|
+
readonly loss?: number
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Delay added to every packet in ms
|
|
57
|
+
*/
|
|
58
|
+
readonly latency?: number
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Extra random delay up to this many ms, which also reorders packets
|
|
62
|
+
*/
|
|
63
|
+
readonly jitter?: number
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Share of packets sent twice, 0 to 1
|
|
67
|
+
*/
|
|
68
|
+
readonly duplicate?: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Keys for an encrypted session
|
|
73
|
+
*/
|
|
74
|
+
export type EncryptionOptions = {
|
|
75
|
+
/**
|
|
76
|
+
* The server's fixed keys, a fresh pair is made if left out
|
|
77
|
+
*/
|
|
78
|
+
readonly keyPair?: KeyPair
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The key a client expects the server to have, stops anyone sitting in the middle
|
|
82
|
+
*/
|
|
83
|
+
readonly serverPublicKey?: Uint8Array
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Settings for ReliableHandler
|
|
88
|
+
*/
|
|
89
|
+
export type ReliableOptions = {
|
|
90
|
+
/**
|
|
91
|
+
* Server waits for peers, client connects to one
|
|
92
|
+
*/
|
|
93
|
+
readonly role: ReliableRole
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Where the client connects to, clients only
|
|
97
|
+
*/
|
|
98
|
+
readonly server?: PacketAddress
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Lane settings, the same on both ends, reliable ordered then unreliable by default
|
|
102
|
+
*/
|
|
103
|
+
readonly lanes?: readonly LaneOptions[]
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Biggest packet we send, 1200 by default
|
|
107
|
+
*/
|
|
108
|
+
readonly mtu?: number
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Drop a peer after this many ms of silence, 10 seconds by default
|
|
112
|
+
*/
|
|
113
|
+
readonly timeout?: number
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Send an empty packet after this many ms without sending, 1 second by default
|
|
117
|
+
*/
|
|
118
|
+
readonly keepalive?: number
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* How often resends, acks and timeouts are checked, 10 ms by default
|
|
122
|
+
*/
|
|
123
|
+
readonly tick?: number
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Longest a lone ack waits for company in ms, 1 by default
|
|
127
|
+
*/
|
|
128
|
+
readonly ackDelay?: number
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Peers allowed at once, 4096 by default
|
|
132
|
+
*/
|
|
133
|
+
readonly maxPeers?: number
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Biggest message after joining fragments, 256 KiB by default
|
|
137
|
+
*/
|
|
138
|
+
readonly maxMessageSize?: number
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Bytes queued per lane before send throws, 4 MiB by default
|
|
142
|
+
*/
|
|
143
|
+
readonly maxQueuedBytes?: number
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Sends of one message before giving up on the peer, 64 by default
|
|
147
|
+
*/
|
|
148
|
+
readonly maxResends?: number
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Reliable messages in flight per lane, 1024 by default
|
|
152
|
+
*/
|
|
153
|
+
readonly window?: number
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Halve the window on loss and grow it back on acks, off by default
|
|
157
|
+
*/
|
|
158
|
+
readonly congestion?: boolean
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Bytes per second sent to each peer, no limit by default
|
|
162
|
+
*/
|
|
163
|
+
readonly maxSendRate?: number
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Encrypt data packets, both ends have to agree, off by default
|
|
167
|
+
*/
|
|
168
|
+
readonly encryption?: boolean | EncryptionOptions
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Fake loss and lag, off by default
|
|
172
|
+
*/
|
|
173
|
+
readonly simulate?: SimulateOptions
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Encryption settings with keys filled in
|
|
178
|
+
*/
|
|
179
|
+
type Encryption = {
|
|
180
|
+
/**
|
|
181
|
+
* Our keys
|
|
182
|
+
*/
|
|
183
|
+
readonly keyPair: KeyPair
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The key we expect the server to have, or null
|
|
187
|
+
*/
|
|
188
|
+
readonly serverPublicKey: Uint8Array | null
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Settings with every default filled in
|
|
193
|
+
*/
|
|
194
|
+
type Settings = {
|
|
195
|
+
/**
|
|
196
|
+
* Same as ReliableOptions.role
|
|
197
|
+
*/
|
|
198
|
+
readonly role: ReliableRole
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Same as ReliableOptions.server, or null
|
|
202
|
+
*/
|
|
203
|
+
readonly server: PacketAddress | null
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Same as ReliableOptions.lanes
|
|
207
|
+
*/
|
|
208
|
+
readonly lanes: readonly LaneOptions[]
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Same as ReliableOptions.mtu
|
|
212
|
+
*/
|
|
213
|
+
readonly mtu: number
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Same as ReliableOptions.timeout
|
|
217
|
+
*/
|
|
218
|
+
readonly timeout: number
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Same as ReliableOptions.keepalive
|
|
222
|
+
*/
|
|
223
|
+
readonly keepalive: number
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Same as ReliableOptions.tick
|
|
227
|
+
*/
|
|
228
|
+
readonly tick: number
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Same as ReliableOptions.ackDelay
|
|
232
|
+
*/
|
|
233
|
+
readonly ackDelay: number
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Same as ReliableOptions.maxPeers
|
|
237
|
+
*/
|
|
238
|
+
readonly maxPeers: number
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Same as ReliableOptions.maxMessageSize
|
|
242
|
+
*/
|
|
243
|
+
readonly maxMessageSize: number
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Same as ReliableOptions.maxQueuedBytes
|
|
247
|
+
*/
|
|
248
|
+
readonly maxQueuedBytes: number
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Same as ReliableOptions.maxResends
|
|
252
|
+
*/
|
|
253
|
+
readonly maxResends: number
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Same as ReliableOptions.window
|
|
257
|
+
*/
|
|
258
|
+
readonly window: number
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Same as ReliableOptions.congestion
|
|
262
|
+
*/
|
|
263
|
+
readonly congestion: boolean
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Same as ReliableOptions.maxSendRate, 0 for none
|
|
267
|
+
*/
|
|
268
|
+
readonly maxSendRate: number
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Same as ReliableOptions.encryption, or null
|
|
272
|
+
*/
|
|
273
|
+
readonly encryption: Encryption | null
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Same as ReliableOptions.simulate, or null
|
|
277
|
+
*/
|
|
278
|
+
readonly simulate: Required<SimulateOptions> | null
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Reliable UDP on a DatagramChannel, turns packets into ReliableMessages and back
|
|
283
|
+
* @class
|
|
284
|
+
*/
|
|
285
|
+
export class ReliableHandler extends DuplexHandlerAdapter {
|
|
286
|
+
/**
|
|
287
|
+
* Reliable ordered on lane 0, unreliable on lane 1
|
|
288
|
+
*/
|
|
289
|
+
public static readonly defaultLanes: readonly LaneOptions[] = [
|
|
290
|
+
{ delivery: 'reliable-ordered' },
|
|
291
|
+
{ delivery: 'unreliable' },
|
|
292
|
+
]
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* How often a client repeats its connect packet
|
|
296
|
+
*/
|
|
297
|
+
public static readonly connectInterval = 100
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Settings with defaults filled in
|
|
301
|
+
*/
|
|
302
|
+
private readonly settings: Settings
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Peers by address
|
|
306
|
+
*/
|
|
307
|
+
private readonly registry: PeerRegistry
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Peers with something new to send
|
|
311
|
+
*/
|
|
312
|
+
private readonly dirty: Set<ReliablePeer>
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Peers owed a lone ack
|
|
316
|
+
*/
|
|
317
|
+
private readonly acking: Set<ReliablePeer>
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Finished packets waiting to be written
|
|
321
|
+
*/
|
|
322
|
+
private readonly outbox: Uint8Array[]
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Hands out and checks connect cookies
|
|
326
|
+
*/
|
|
327
|
+
private readonly cookies: CookieJar
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Our place in the pipeline, null until added
|
|
331
|
+
*/
|
|
332
|
+
private context: HandlerContext | null
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* The tick timer, null when stopped
|
|
336
|
+
*/
|
|
337
|
+
private timer: Timer | null
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The delayed ack timer, null when none is due
|
|
341
|
+
*/
|
|
342
|
+
private ackTimer: Timer | null
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Whether a flush is already on its way
|
|
346
|
+
*/
|
|
347
|
+
private scheduled: boolean
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The client's peer for the server, or null
|
|
351
|
+
*/
|
|
352
|
+
private server: ReliablePeer | null
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Cookie the server gave our client, or null
|
|
356
|
+
*/
|
|
357
|
+
private cookie: Uint8Array | null
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* When that cookie was issued
|
|
361
|
+
*/
|
|
362
|
+
private cookieTime: number
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* When the client started connecting
|
|
366
|
+
*/
|
|
367
|
+
private connectStartedAt: number
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* When the client last sent a connect packet
|
|
371
|
+
*/
|
|
372
|
+
private lastConnectAt: number
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Settled once the client is connected or gives up
|
|
376
|
+
*/
|
|
377
|
+
private readonly connecting: PromiseWithResolvers<ReliablePeer>
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Bound once so peers can call it
|
|
381
|
+
*/
|
|
382
|
+
private readonly wake: (peer: ReliablePeer) => void
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Checks the settings and fills in defaults
|
|
386
|
+
* @param options role, lanes and limits
|
|
387
|
+
*/
|
|
388
|
+
public constructor(options: ReliableOptions) {
|
|
389
|
+
super()
|
|
390
|
+
|
|
391
|
+
const settings = ReliableHandler.resolve(options)
|
|
392
|
+
const reason = ReliableHandler.refusal(settings)
|
|
393
|
+
if (reason !== null) throw new RangeError(reason)
|
|
394
|
+
|
|
395
|
+
this.settings = settings
|
|
396
|
+
this.registry = new PeerRegistry()
|
|
397
|
+
this.dirty = new Set<ReliablePeer>()
|
|
398
|
+
this.acking = new Set<ReliablePeer>()
|
|
399
|
+
this.outbox = []
|
|
400
|
+
this.cookies = new CookieJar()
|
|
401
|
+
this.context = null
|
|
402
|
+
this.timer = null
|
|
403
|
+
this.ackTimer = null
|
|
404
|
+
this.scheduled = false
|
|
405
|
+
this.server = null
|
|
406
|
+
this.cookie = null
|
|
407
|
+
this.cookieTime = 0
|
|
408
|
+
this.connectStartedAt = 0
|
|
409
|
+
this.lastConnectAt = 0
|
|
410
|
+
this.connecting = Promise.withResolvers<ReliablePeer>()
|
|
411
|
+
void this.connecting.promise.catch((): undefined => undefined)
|
|
412
|
+
this.wake = (peer: ReliablePeer): void => {
|
|
413
|
+
this.schedule(peer)
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Makes keys for a server with a fixed identity
|
|
419
|
+
*/
|
|
420
|
+
public static generateKeyPair(): KeyPair {
|
|
421
|
+
return PacketCipher.generateKeyPair()
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Resolves with the server's peer once a client is connected
|
|
426
|
+
*/
|
|
427
|
+
public get connected(): Promise<ReliablePeer> {
|
|
428
|
+
return this.connecting.promise
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Every peer we know about
|
|
433
|
+
*/
|
|
434
|
+
public get peers(): ReadonlySet<ReliablePeer> {
|
|
435
|
+
return this.registry.peers
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Our public key when encrypting, or null
|
|
440
|
+
*/
|
|
441
|
+
public get publicKey(): Uint8Array | null {
|
|
442
|
+
return this.settings.encryption?.keyPair.publicKey ?? null
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Fills in a default for everything left out
|
|
447
|
+
* @param options what the caller gave us
|
|
448
|
+
*/
|
|
449
|
+
private static resolve(options: ReliableOptions): Settings {
|
|
450
|
+
const simulate = options.simulate
|
|
451
|
+
|
|
452
|
+
return {
|
|
453
|
+
role: options.role,
|
|
454
|
+
server: options.server ?? null,
|
|
455
|
+
lanes: options.lanes ?? ReliableHandler.defaultLanes,
|
|
456
|
+
mtu: options.mtu ?? 1200,
|
|
457
|
+
timeout: options.timeout ?? 10_000,
|
|
458
|
+
keepalive: options.keepalive ?? 1000,
|
|
459
|
+
tick: options.tick ?? 10,
|
|
460
|
+
ackDelay: options.ackDelay ?? 1,
|
|
461
|
+
maxPeers: options.maxPeers ?? 4096,
|
|
462
|
+
maxMessageSize: options.maxMessageSize ?? 256 * 1024,
|
|
463
|
+
maxQueuedBytes: options.maxQueuedBytes ?? 4 * 1024 * 1024,
|
|
464
|
+
maxResends: options.maxResends ?? 64,
|
|
465
|
+
window: options.window ?? 1024,
|
|
466
|
+
congestion: options.congestion ?? false,
|
|
467
|
+
maxSendRate: options.maxSendRate ?? 0,
|
|
468
|
+
encryption: ReliableHandler.resolveEncryption(options.encryption),
|
|
469
|
+
simulate:
|
|
470
|
+
simulate === undefined
|
|
471
|
+
? null
|
|
472
|
+
: {
|
|
473
|
+
loss: simulate.loss ?? 0,
|
|
474
|
+
latency: simulate.latency ?? 0,
|
|
475
|
+
jitter: simulate.jitter ?? 0,
|
|
476
|
+
duplicate: simulate.duplicate ?? 0,
|
|
477
|
+
},
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Fills in keys for encryption, or null when it's off
|
|
483
|
+
* @param encryption what the caller gave us
|
|
484
|
+
*/
|
|
485
|
+
private static resolveEncryption(
|
|
486
|
+
encryption: boolean | EncryptionOptions | undefined,
|
|
487
|
+
): Encryption | null {
|
|
488
|
+
if (encryption === undefined || encryption === false) return null
|
|
489
|
+
if (encryption === true) {
|
|
490
|
+
return { keyPair: PacketCipher.generateKeyPair(), serverPublicKey: null }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return {
|
|
494
|
+
keyPair: encryption.keyPair ?? PacketCipher.generateKeyPair(),
|
|
495
|
+
serverPublicKey: encryption.serverPublicKey ?? null,
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Why the settings won't work, or null
|
|
501
|
+
* @param settings settings with defaults filled in
|
|
502
|
+
*/
|
|
503
|
+
private static refusal(settings: Settings): string | null {
|
|
504
|
+
if (settings.role === 'client' && settings.server === null) {
|
|
505
|
+
return 'Server is not set'
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
if (settings.mtu < 256 || settings.mtu > 65_507)
|
|
509
|
+
return 'MTU is out of range'
|
|
510
|
+
if (settings.lanes.length < 1 || settings.lanes.length > 127) {
|
|
511
|
+
return 'Lane count is out of range'
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
if (settings.window < 1 || settings.window > 16_384) {
|
|
515
|
+
return 'Window is out of range'
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const payload =
|
|
519
|
+
ReliableHandler.peerMtu(settings) - dataHeaderSize - messageHeaderSize
|
|
520
|
+
const fragments = Math.ceil(settings.maxMessageSize / payload)
|
|
521
|
+
if (fragments > 255 || fragments > settings.window) {
|
|
522
|
+
return 'Message size needs too many fragments'
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (settings.tick <= 0 || settings.timeout <= 0 || settings.ackDelay < 0) {
|
|
526
|
+
return 'Timer is out of range'
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (settings.maxSendRate < 0) return 'Send rate is negative'
|
|
530
|
+
return null
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Packet size peers build to, leaving room for the cipher
|
|
535
|
+
* @param settings settings with defaults filled in
|
|
536
|
+
*/
|
|
537
|
+
private static peerMtu(settings: Settings): number {
|
|
538
|
+
return settings.encryption === null
|
|
539
|
+
? settings.mtu
|
|
540
|
+
: settings.mtu - PacketCipher.overhead
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Starts ticking if the channel is already up
|
|
545
|
+
* @param context our place in the pipeline
|
|
546
|
+
*/
|
|
547
|
+
public handlerAdded(context: HandlerContext): void {
|
|
548
|
+
this.context = context
|
|
549
|
+
if (context.channel.isActive) this.start(context)
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Stops ticking
|
|
554
|
+
*/
|
|
555
|
+
public handlerRemoved(): void {
|
|
556
|
+
this.stop()
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Starts ticking and, on a client, connecting
|
|
561
|
+
* @param context our place in the pipeline
|
|
562
|
+
*/
|
|
563
|
+
public override channelActive(context: HandlerContext): Promise<void> {
|
|
564
|
+
this.context = context
|
|
565
|
+
this.start(context)
|
|
566
|
+
return context.fireChannelActive()
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Stops ticking and forgets every peer
|
|
571
|
+
* @param context our place in the pipeline
|
|
572
|
+
*/
|
|
573
|
+
public override channelInactive(context: HandlerContext): Promise<void> {
|
|
574
|
+
this.stop()
|
|
575
|
+
return context.fireChannelInactive()
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Sorts incoming packets by kind
|
|
580
|
+
* @param context our place in the pipeline
|
|
581
|
+
* @param message usually a DatagramPacket
|
|
582
|
+
*/
|
|
583
|
+
public override channelRead(
|
|
584
|
+
context: HandlerContext,
|
|
585
|
+
message: unknown,
|
|
586
|
+
): void | Promise<void> {
|
|
587
|
+
if (!(message instanceof DatagramPacket) || message.sender === null) {
|
|
588
|
+
return context.fireChannelRead(message)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const bytes = message.content.toUint8Array()
|
|
592
|
+
const now = performance.now()
|
|
593
|
+
switch ((bytes[0] ?? 0) & 0x7f) {
|
|
594
|
+
case PacketKind.data:
|
|
595
|
+
return this.data(context, bytes, message.sender, now)
|
|
596
|
+
case PacketKind.connect:
|
|
597
|
+
return this.connect(context, bytes, message.sender, now)
|
|
598
|
+
case PacketKind.challenge:
|
|
599
|
+
this.challenge(context, bytes, now)
|
|
600
|
+
return
|
|
601
|
+
case PacketKind.accept:
|
|
602
|
+
return this.accept(context, bytes, now)
|
|
603
|
+
case PacketKind.disconnect:
|
|
604
|
+
return this.hangup(context, bytes, message.sender)
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
return resolved
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Sends ReliableMessages through their peer and passes anything else on
|
|
612
|
+
* @param context our place in the pipeline
|
|
613
|
+
* @param message usually a ReliableMessage
|
|
614
|
+
*/
|
|
615
|
+
public override write(
|
|
616
|
+
context: HandlerContext,
|
|
617
|
+
message: unknown,
|
|
618
|
+
): Promise<void> {
|
|
619
|
+
if (!(message instanceof ReliableMessage)) return context.write(message)
|
|
620
|
+
|
|
621
|
+
try {
|
|
622
|
+
message.peer.send(message.lane, message.content)
|
|
623
|
+
} catch (cause) {
|
|
624
|
+
return Promise.reject(new Error('Send failed', { cause }))
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
return resolved
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Says goodbye to every peer before the channel closes
|
|
632
|
+
* @param context our place in the pipeline
|
|
633
|
+
*/
|
|
634
|
+
public override async close(context: HandlerContext): Promise<void> {
|
|
635
|
+
for (const peer of this.registry.peers) {
|
|
636
|
+
if (peer.state === 'connected') this.sendDisconnect(context, peer)
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
await context.flush()
|
|
640
|
+
|
|
641
|
+
this.stop()
|
|
642
|
+
await context.close()
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Starts the tick timer, and the handshake on a client
|
|
647
|
+
* @param context our place in the pipeline
|
|
648
|
+
*/
|
|
649
|
+
private start(context: HandlerContext): void {
|
|
650
|
+
if (this.timer !== null) return
|
|
651
|
+
|
|
652
|
+
this.timer = setInterval((): void => {
|
|
653
|
+
void context.channel.execute((): Promise<void> => this.update(context))
|
|
654
|
+
}, this.settings.tick)
|
|
655
|
+
this.timer.unref()
|
|
656
|
+
|
|
657
|
+
const server = this.settings.server
|
|
658
|
+
if (this.settings.role !== 'client' || server === null) return
|
|
659
|
+
const peer = this.createPeer(server, 0, ReliableHandler.random())
|
|
660
|
+
this.server = peer
|
|
661
|
+
this.registry.add(peer)
|
|
662
|
+
this.connectStartedAt = performance.now()
|
|
663
|
+
this.sendConnect(context, peer, this.connectStartedAt)
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Stops ticking and forgets every peer
|
|
668
|
+
*/
|
|
669
|
+
private stop(): void {
|
|
670
|
+
if (this.timer !== null) clearInterval(this.timer)
|
|
671
|
+
if (this.ackTimer !== null) clearTimeout(this.ackTimer)
|
|
672
|
+
this.timer = null
|
|
673
|
+
this.ackTimer = null
|
|
674
|
+
|
|
675
|
+
for (const peer of this.registry.peers) peer.state = 'closed'
|
|
676
|
+
this.registry.clear()
|
|
677
|
+
this.dirty.clear()
|
|
678
|
+
this.acking.clear()
|
|
679
|
+
this.connecting.reject(new Error('Channel is closed'))
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Builds a peer wired up to this handler
|
|
684
|
+
* @param address where it lives
|
|
685
|
+
* @param session session id, 0 on a client until accepted
|
|
686
|
+
* @param salt the client's handshake number
|
|
687
|
+
*/
|
|
688
|
+
private createPeer(
|
|
689
|
+
address: PacketAddress,
|
|
690
|
+
session: number,
|
|
691
|
+
salt: number,
|
|
692
|
+
): ReliablePeer {
|
|
693
|
+
const settings = this.settings
|
|
694
|
+
|
|
695
|
+
return new ReliablePeer(
|
|
696
|
+
{
|
|
697
|
+
address,
|
|
698
|
+
session,
|
|
699
|
+
salt,
|
|
700
|
+
lanes: settings.lanes,
|
|
701
|
+
mtu: ReliableHandler.peerMtu(settings),
|
|
702
|
+
window: settings.window,
|
|
703
|
+
keepalive: settings.keepalive,
|
|
704
|
+
maxMessageSize: settings.maxMessageSize,
|
|
705
|
+
maxQueuedBytes: settings.maxQueuedBytes,
|
|
706
|
+
maxResends: settings.maxResends,
|
|
707
|
+
congestion: settings.congestion,
|
|
708
|
+
maxSendRate: settings.maxSendRate,
|
|
709
|
+
},
|
|
710
|
+
this.wake,
|
|
711
|
+
)
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Hands a data packet to its peer and passes on what comes out
|
|
716
|
+
* @param context our place in the pipeline
|
|
717
|
+
* @param bytes the packet
|
|
718
|
+
* @param sender who sent it
|
|
719
|
+
* @param now current time in ms
|
|
720
|
+
*/
|
|
721
|
+
private data(
|
|
722
|
+
context: HandlerContext,
|
|
723
|
+
bytes: Uint8Array,
|
|
724
|
+
sender: PacketAddress,
|
|
725
|
+
now: number,
|
|
726
|
+
): void | Promise<void> {
|
|
727
|
+
if (bytes.length < dataHeaderSize) return
|
|
728
|
+
const peer = this.server ?? this.registry.find(sender)
|
|
729
|
+
if (peer?.state !== 'connected') return
|
|
730
|
+
if (peer.session !== readUint32(bytes, 1)) return
|
|
731
|
+
|
|
732
|
+
const plain = peer.cipher === null ? bytes : peer.cipher.open(bytes)
|
|
733
|
+
if (plain === null) return
|
|
734
|
+
const messages: ReliableMessage[] = []
|
|
735
|
+
peer.receive(plain, now, messages)
|
|
736
|
+
if (peer.hasWork) this.schedule(peer)
|
|
737
|
+
else if (peer.owesAck) this.delayAck(context, peer)
|
|
738
|
+
|
|
739
|
+
return ReliableHandler.deliver(context, messages, 0)
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* Passes messages on one at a time, staying sync until a handler goes async
|
|
744
|
+
* @param context our place in the pipeline
|
|
745
|
+
* @param messages what came out of the packet
|
|
746
|
+
* @param from where to carry on from
|
|
747
|
+
*/
|
|
748
|
+
private static deliver(
|
|
749
|
+
context: HandlerContext,
|
|
750
|
+
messages: readonly ReliableMessage[],
|
|
751
|
+
from: number,
|
|
752
|
+
): void | Promise<void> {
|
|
753
|
+
for (let index = from; index < messages.length; index++) {
|
|
754
|
+
const waiting = pending(context.fireChannelRead(messages[index]))
|
|
755
|
+
if (waiting !== null) {
|
|
756
|
+
return waiting.then((): void | Promise<void> =>
|
|
757
|
+
ReliableHandler.deliver(context, messages, index + 1),
|
|
758
|
+
)
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* A client asking in, answered with a challenge until it proves its address
|
|
765
|
+
* @param context our place in the pipeline
|
|
766
|
+
* @param bytes the packet
|
|
767
|
+
* @param sender who sent it
|
|
768
|
+
* @param now current time in ms
|
|
769
|
+
*/
|
|
770
|
+
private connect(
|
|
771
|
+
context: HandlerContext,
|
|
772
|
+
bytes: Uint8Array,
|
|
773
|
+
sender: PacketAddress,
|
|
774
|
+
now: number,
|
|
775
|
+
): void | Promise<void> {
|
|
776
|
+
if (this.settings.role !== 'server' || bytes.length < connectSize) return
|
|
777
|
+
if (!isOurs(bytes)) return
|
|
778
|
+
|
|
779
|
+
const salt = readUint32(bytes, ConnectField.salt)
|
|
780
|
+
const existing = this.registry.find(sender)
|
|
781
|
+
if (existing?.salt === salt) {
|
|
782
|
+
this.sendAccept(context, existing)
|
|
783
|
+
return
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const encryption = this.settings.encryption
|
|
787
|
+
const encrypted = ((bytes[ConnectField.flags] ?? 0) & encryptFlag) !== 0
|
|
788
|
+
if (encrypted !== (encryption !== null)) return
|
|
789
|
+
|
|
790
|
+
const time = readUint32(bytes, ConnectField.time)
|
|
791
|
+
const cookie = bytes.subarray(
|
|
792
|
+
ConnectField.cookie,
|
|
793
|
+
ConnectField.cookie + cookieSize,
|
|
794
|
+
)
|
|
795
|
+
if (!this.cookies.verify(sender, salt, time, cookie)) {
|
|
796
|
+
const issued = CookieJar.now()
|
|
797
|
+
this.emit(
|
|
798
|
+
context,
|
|
799
|
+
challengePacket(salt, issued, this.cookies.issue(sender, salt, issued)),
|
|
800
|
+
sender,
|
|
801
|
+
)
|
|
802
|
+
void context.flush()
|
|
803
|
+
return
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
if (
|
|
807
|
+
existing === undefined &&
|
|
808
|
+
this.registry.size >= this.settings.maxPeers
|
|
809
|
+
) {
|
|
810
|
+
return
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const peer = this.createPeer(sender, ReliableHandler.random(), salt)
|
|
814
|
+
if (encryption !== null) {
|
|
815
|
+
const theirs = bytes.subarray(
|
|
816
|
+
ConnectField.key,
|
|
817
|
+
ConnectField.key + keySize,
|
|
818
|
+
)
|
|
819
|
+
try {
|
|
820
|
+
peer.cipher = PacketCipher.derive(
|
|
821
|
+
encryption.keyPair,
|
|
822
|
+
theirs,
|
|
823
|
+
keySalt(salt, peer.session),
|
|
824
|
+
false,
|
|
825
|
+
)
|
|
826
|
+
} catch {
|
|
827
|
+
return
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
return this.admit(context, peer, existing, now)
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Lets a checked client in, replacing an old session from the same address
|
|
836
|
+
* @param context our place in the pipeline
|
|
837
|
+
* @param peer the new peer
|
|
838
|
+
* @param existing the old peer at that address, or undefined
|
|
839
|
+
* @param now current time in ms
|
|
840
|
+
*/
|
|
841
|
+
private admit(
|
|
842
|
+
context: HandlerContext,
|
|
843
|
+
peer: ReliablePeer,
|
|
844
|
+
existing: ReliablePeer | undefined,
|
|
845
|
+
now: number,
|
|
846
|
+
): Promise<void> {
|
|
847
|
+
peer.state = 'connected'
|
|
848
|
+
peer.lastReceivedAt = now
|
|
849
|
+
const replaced =
|
|
850
|
+
existing === undefined ? resolved : this.drop(context, existing, 'closed')
|
|
851
|
+
this.registry.add(peer)
|
|
852
|
+
this.sendAccept(context, peer)
|
|
853
|
+
|
|
854
|
+
return replaced.then((): Promise<void> =>
|
|
855
|
+
context.fireUserEventTriggered(new PeerConnected(peer)),
|
|
856
|
+
)
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* The server asking our client to send its cookie back
|
|
861
|
+
* @param context our place in the pipeline
|
|
862
|
+
* @param bytes the packet
|
|
863
|
+
* @param now current time in ms
|
|
864
|
+
*/
|
|
865
|
+
private challenge(
|
|
866
|
+
context: HandlerContext,
|
|
867
|
+
bytes: Uint8Array,
|
|
868
|
+
now: number,
|
|
869
|
+
): void {
|
|
870
|
+
const peer = this.server
|
|
871
|
+
if (peer?.state !== 'connecting' || bytes.length < challengeSize) return
|
|
872
|
+
if (!isOurs(bytes) || readUint32(bytes, 5) !== peer.salt) {
|
|
873
|
+
return
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
this.cookieTime = readUint32(bytes, 9)
|
|
877
|
+
this.cookie = bytes.slice(13, 13 + cookieSize)
|
|
878
|
+
this.sendConnect(context, peer, now)
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* The server letting our client in
|
|
883
|
+
* @param context our place in the pipeline
|
|
884
|
+
* @param bytes the packet
|
|
885
|
+
* @param now current time in ms
|
|
886
|
+
*/
|
|
887
|
+
private accept(
|
|
888
|
+
context: HandlerContext,
|
|
889
|
+
bytes: Uint8Array,
|
|
890
|
+
now: number,
|
|
891
|
+
): void | Promise<void> {
|
|
892
|
+
const peer = this.server
|
|
893
|
+
const encryption = this.settings.encryption
|
|
894
|
+
const size = acceptSize + (encryption === null ? 0 : keySize)
|
|
895
|
+
if (peer?.state !== 'connecting' || bytes.length < size) return
|
|
896
|
+
if (!isOurs(bytes) || readUint32(bytes, 5) !== peer.salt) {
|
|
897
|
+
return
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const session = readUint32(bytes, 9)
|
|
901
|
+
if (encryption !== null) {
|
|
902
|
+
const theirs = bytes.subarray(acceptSize, acceptSize + keySize)
|
|
903
|
+
const pinned = encryption.serverPublicKey
|
|
904
|
+
if (pinned !== null && !Buffer.from(pinned).equals(theirs)) return
|
|
905
|
+
try {
|
|
906
|
+
peer.cipher = PacketCipher.derive(
|
|
907
|
+
encryption.keyPair,
|
|
908
|
+
theirs,
|
|
909
|
+
keySalt(peer.salt, session),
|
|
910
|
+
true,
|
|
911
|
+
)
|
|
912
|
+
} catch {
|
|
913
|
+
return
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
peer.session = session
|
|
918
|
+
peer.state = 'connected'
|
|
919
|
+
peer.lastReceivedAt = now
|
|
920
|
+
this.connecting.resolve(peer)
|
|
921
|
+
this.schedule(peer)
|
|
922
|
+
return context.fireUserEventTriggered(new PeerConnected(peer))
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* A peer hanging up on us
|
|
927
|
+
* @param context our place in the pipeline
|
|
928
|
+
* @param bytes the packet
|
|
929
|
+
* @param sender who sent it
|
|
930
|
+
*/
|
|
931
|
+
private hangup(
|
|
932
|
+
context: HandlerContext,
|
|
933
|
+
bytes: Uint8Array,
|
|
934
|
+
sender: PacketAddress,
|
|
935
|
+
): void | Promise<void> {
|
|
936
|
+
const peer = this.server ?? this.registry.find(sender)
|
|
937
|
+
if (peer?.state !== 'connected' || bytes.length < dataHeaderSize) return
|
|
938
|
+
if (peer.session !== readUint32(bytes, 1)) return
|
|
939
|
+
if (peer.cipher !== null && peer.cipher.open(bytes) === null) return
|
|
940
|
+
|
|
941
|
+
return this.drop(context, peer, 'closed')
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Forgets a peer and tells the pipeline
|
|
946
|
+
* @param context our place in the pipeline
|
|
947
|
+
* @param peer the peer to drop
|
|
948
|
+
* @param reason why
|
|
949
|
+
*/
|
|
950
|
+
private drop(
|
|
951
|
+
context: HandlerContext,
|
|
952
|
+
peer: ReliablePeer,
|
|
953
|
+
reason: DisconnectReason,
|
|
954
|
+
): Promise<void> {
|
|
955
|
+
const wasConnecting = peer.state === 'connecting'
|
|
956
|
+
peer.state = 'closed'
|
|
957
|
+
this.registry.remove(peer)
|
|
958
|
+
this.dirty.delete(peer)
|
|
959
|
+
this.acking.delete(peer)
|
|
960
|
+
if (wasConnecting) {
|
|
961
|
+
this.connecting.reject(new Error('Connection timed out'))
|
|
962
|
+
return resolved
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
return context.fireUserEventTriggered(new PeerDisconnected(peer, reason))
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Notes a peer as having something to send and flushes on the next microtask
|
|
970
|
+
* @param peer the peer
|
|
971
|
+
*/
|
|
972
|
+
private schedule(peer: ReliablePeer): void {
|
|
973
|
+
this.dirty.add(peer)
|
|
974
|
+
if (this.scheduled) return
|
|
975
|
+
this.scheduled = true
|
|
976
|
+
|
|
977
|
+
queueMicrotask((): void => {
|
|
978
|
+
const context = this.context
|
|
979
|
+
if (context === null) return
|
|
980
|
+
void context.channel.execute((): void => {
|
|
981
|
+
this.flushDirty(context)
|
|
982
|
+
})
|
|
983
|
+
})
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* Holds a lone ack back briefly in case something can ride along with it
|
|
988
|
+
* @param context our place in the pipeline
|
|
989
|
+
* @param peer the peer owed an ack
|
|
990
|
+
*/
|
|
991
|
+
private delayAck(context: HandlerContext, peer: ReliablePeer): void {
|
|
992
|
+
this.acking.add(peer)
|
|
993
|
+
if (this.ackTimer !== null) return
|
|
994
|
+
|
|
995
|
+
this.ackTimer = setTimeout((): void => {
|
|
996
|
+
this.ackTimer = null
|
|
997
|
+
void context.channel.execute((): void => {
|
|
998
|
+
this.flushAcks(context)
|
|
999
|
+
})
|
|
1000
|
+
}, this.settings.ackDelay)
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* Sends the acks that waited
|
|
1005
|
+
* @param context our place in the pipeline
|
|
1006
|
+
*/
|
|
1007
|
+
private flushAcks(context: HandlerContext): void {
|
|
1008
|
+
const now = performance.now()
|
|
1009
|
+
|
|
1010
|
+
for (const peer of this.acking) {
|
|
1011
|
+
if (peer.state === 'connected' && peer.owesAck) {
|
|
1012
|
+
this.send(context, peer, now, true)
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
this.acking.clear()
|
|
1017
|
+
void context.flush()
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* Sends whatever the dirty peers have queued
|
|
1022
|
+
* @param context our place in the pipeline
|
|
1023
|
+
*/
|
|
1024
|
+
private flushDirty(context: HandlerContext): void {
|
|
1025
|
+
this.scheduled = false
|
|
1026
|
+
const now = performance.now()
|
|
1027
|
+
|
|
1028
|
+
for (const peer of this.dirty) {
|
|
1029
|
+
if (peer.closing) continue
|
|
1030
|
+
this.send(context, peer, now, false)
|
|
1031
|
+
if (peer.owesAck) this.delayAck(context, peer)
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
this.dirty.clear()
|
|
1035
|
+
void context.flush()
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/**
|
|
1039
|
+
* One tick, handles timeouts, resends, acks and keep-alives for every peer
|
|
1040
|
+
* @param context our place in the pipeline
|
|
1041
|
+
*/
|
|
1042
|
+
private async update(context: HandlerContext): Promise<void> {
|
|
1043
|
+
const now = performance.now()
|
|
1044
|
+
const settings = this.settings
|
|
1045
|
+
const server = this.server
|
|
1046
|
+
if (server?.state === 'connecting') {
|
|
1047
|
+
if (now - this.connectStartedAt > settings.timeout) {
|
|
1048
|
+
await this.drop(context, server, 'timeout')
|
|
1049
|
+
return
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (now - this.lastConnectAt >= ReliableHandler.connectInterval) {
|
|
1053
|
+
this.sendConnect(context, server, now)
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
const gone: [ReliablePeer, DisconnectReason][] = []
|
|
1058
|
+
for (const peer of this.registry.peers) {
|
|
1059
|
+
if (peer.state !== 'connected') continue
|
|
1060
|
+
if (now - peer.lastReceivedAt > settings.timeout) {
|
|
1061
|
+
gone.push([peer, 'timeout'])
|
|
1062
|
+
} else if (peer.failed || peer.closing) {
|
|
1063
|
+
this.sendDisconnect(context, peer)
|
|
1064
|
+
gone.push([peer, peer.failed ? 'resends' : 'local'])
|
|
1065
|
+
} else if (peer.isDue(now)) {
|
|
1066
|
+
this.send(context, peer, now, true)
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
void context.flush()
|
|
1071
|
+
|
|
1072
|
+
for (const [peer, reason] of gone) await this.drop(context, peer, reason)
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* Packs a peer's packets, seals them if encrypted and writes them
|
|
1077
|
+
* @param context our place in the pipeline
|
|
1078
|
+
* @param peer the peer
|
|
1079
|
+
* @param now current time in ms
|
|
1080
|
+
* @param force send a lone ack if one is owed
|
|
1081
|
+
*/
|
|
1082
|
+
private send(
|
|
1083
|
+
context: HandlerContext,
|
|
1084
|
+
peer: ReliablePeer,
|
|
1085
|
+
now: number,
|
|
1086
|
+
force: boolean,
|
|
1087
|
+
): void {
|
|
1088
|
+
const outbox = this.outbox
|
|
1089
|
+
peer.pack(now, outbox, force)
|
|
1090
|
+
|
|
1091
|
+
const cipher = peer.cipher
|
|
1092
|
+
for (const bytes of outbox) {
|
|
1093
|
+
this.emit(
|
|
1094
|
+
context,
|
|
1095
|
+
cipher === null ? bytes : cipher.seal(bytes),
|
|
1096
|
+
peer.address,
|
|
1097
|
+
)
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
outbox.length = 0
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* Writes one packet, through the simulator if it's on
|
|
1105
|
+
* @param context our place in the pipeline
|
|
1106
|
+
* @param bytes the packet
|
|
1107
|
+
* @param address where it goes
|
|
1108
|
+
*/
|
|
1109
|
+
private emit(
|
|
1110
|
+
context: HandlerContext,
|
|
1111
|
+
bytes: Uint8Array,
|
|
1112
|
+
address: PacketAddress,
|
|
1113
|
+
): void {
|
|
1114
|
+
const simulate = this.settings.simulate
|
|
1115
|
+
if (simulate === null) {
|
|
1116
|
+
context.writeSync(new DatagramPacket(bytes, address))
|
|
1117
|
+
return
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
if (Math.random() < simulate.loss) return
|
|
1121
|
+
|
|
1122
|
+
const copies = Math.random() < simulate.duplicate ? 2 : 1
|
|
1123
|
+
for (let copy = 0; copy < copies; copy++) {
|
|
1124
|
+
const delay = simulate.latency + Math.random() * simulate.jitter
|
|
1125
|
+
if (delay <= 0) {
|
|
1126
|
+
context.writeSync(new DatagramPacket(bytes, address))
|
|
1127
|
+
continue
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
setTimeout((): void => {
|
|
1131
|
+
void context.channel.execute((): void => {
|
|
1132
|
+
if (context.channel.isActive) {
|
|
1133
|
+
context.writeAndFlushSync(new DatagramPacket(bytes, address))
|
|
1134
|
+
}
|
|
1135
|
+
})
|
|
1136
|
+
}, delay)
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/**
|
|
1141
|
+
* Sends the client's padded connect packet, with the cookie once we have one
|
|
1142
|
+
* @param context our place in the pipeline
|
|
1143
|
+
* @param peer the client's peer for the server
|
|
1144
|
+
* @param now current time in ms
|
|
1145
|
+
*/
|
|
1146
|
+
private sendConnect(
|
|
1147
|
+
context: HandlerContext,
|
|
1148
|
+
peer: ReliablePeer,
|
|
1149
|
+
now: number,
|
|
1150
|
+
): void {
|
|
1151
|
+
const publicKey = this.settings.encryption?.keyPair.publicKey ?? null
|
|
1152
|
+
|
|
1153
|
+
this.lastConnectAt = now
|
|
1154
|
+
this.emit(
|
|
1155
|
+
context,
|
|
1156
|
+
connectPacket(peer.salt, this.cookieTime, this.cookie, publicKey),
|
|
1157
|
+
peer.address,
|
|
1158
|
+
)
|
|
1159
|
+
void context.flush()
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/**
|
|
1163
|
+
* Sends the server's accept packet
|
|
1164
|
+
* @param context our place in the pipeline
|
|
1165
|
+
* @param peer the new peer
|
|
1166
|
+
*/
|
|
1167
|
+
private sendAccept(context: HandlerContext, peer: ReliablePeer): void {
|
|
1168
|
+
const publicKey = this.settings.encryption?.keyPair.publicKey ?? null
|
|
1169
|
+
|
|
1170
|
+
this.emit(
|
|
1171
|
+
context,
|
|
1172
|
+
acceptPacket(peer.salt, peer.session, publicKey),
|
|
1173
|
+
peer.address,
|
|
1174
|
+
)
|
|
1175
|
+
void context.flush()
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/**
|
|
1179
|
+
* Sends a hang up, sealed when encrypted so nobody else can forge one
|
|
1180
|
+
* @param context our place in the pipeline
|
|
1181
|
+
* @param peer the peer
|
|
1182
|
+
*/
|
|
1183
|
+
private sendDisconnect(context: HandlerContext, peer: ReliablePeer): void {
|
|
1184
|
+
const bytes = disconnectPacket(peer.session)
|
|
1185
|
+
|
|
1186
|
+
context.writeSync(
|
|
1187
|
+
new DatagramPacket(
|
|
1188
|
+
peer.cipher === null ? bytes : peer.cipher.seal(bytes),
|
|
1189
|
+
peer.address,
|
|
1190
|
+
),
|
|
1191
|
+
)
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* A random non-zero 32 bit number
|
|
1196
|
+
*/
|
|
1197
|
+
private static random(): number {
|
|
1198
|
+
const value = crypto.getRandomValues(new Uint32Array(1))[0] ?? 0
|
|
1199
|
+
|
|
1200
|
+
return value === 0 ? 1 : value
|
|
1201
|
+
}
|
|
1202
|
+
}
|