@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.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/package.json +65 -4
  4. package/src/bootstrap/client/index.ts +191 -0
  5. package/src/bootstrap/dispatcher/index.ts +204 -0
  6. package/src/bootstrap/index.ts +22 -0
  7. package/src/bootstrap/reconnect/index.ts +334 -0
  8. package/src/bootstrap/server/index.ts +284 -0
  9. package/src/buffer/bits/index.ts +2 -0
  10. package/src/buffer/bits/reader/index.ts +64 -0
  11. package/src/buffer/bits/writer/index.ts +79 -0
  12. package/src/buffer/index.ts +1375 -0
  13. package/src/buffer/pool/index.ts +46 -0
  14. package/src/buffer/quantizer/index.ts +101 -0
  15. package/src/channel/attribute/index.ts +89 -0
  16. package/src/channel/context/index.ts +621 -0
  17. package/src/channel/group/index.ts +256 -0
  18. package/src/channel/handler/duplex/index.ts +105 -0
  19. package/src/channel/handler/inbound/index.ts +78 -0
  20. package/src/channel/handler/index.ts +135 -0
  21. package/src/channel/handler/outbound/index.ts +33 -0
  22. package/src/channel/index.ts +619 -0
  23. package/src/channel/initializer/index.ts +77 -0
  24. package/src/channel/outbound/index.ts +611 -0
  25. package/src/channel/pipeline/head/index.ts +100 -0
  26. package/src/channel/pipeline/index.ts +414 -0
  27. package/src/channel/pipeline/tail/index.ts +45 -0
  28. package/src/channel/pipeline/tracker/index.ts +120 -0
  29. package/src/channel/queue/index.ts +203 -0
  30. package/src/channel/resolved/index.ts +34 -0
  31. package/src/channel/server/index.ts +164 -0
  32. package/src/channel/shutdown/index.ts +25 -0
  33. package/src/channel/simple/index.ts +38 -0
  34. package/src/channel/transport/index.ts +74 -0
  35. package/src/channel/transport/socket/index.ts +80 -0
  36. package/src/cluster/index.ts +360 -0
  37. package/src/codec/binary/index.ts +102 -0
  38. package/src/codec/decoder/index.ts +479 -0
  39. package/src/codec/delimiter/index.ts +189 -0
  40. package/src/codec/encoder/index.ts +48 -0
  41. package/src/codec/error/index.ts +33 -0
  42. package/src/codec/fixed/index.ts +45 -0
  43. package/src/codec/http/aggregator/index.ts +236 -0
  44. package/src/codec/http/client/index.ts +120 -0
  45. package/src/codec/http/decoder/index.ts +4 -0
  46. package/src/codec/http/decoder/object/index.ts +644 -0
  47. package/src/codec/http/decoder/request/index.ts +49 -0
  48. package/src/codec/http/decoder/response/index.ts +59 -0
  49. package/src/codec/http/encoder/index.ts +3 -0
  50. package/src/codec/http/encoder/object/index.ts +196 -0
  51. package/src/codec/http/encoder/request/index.ts +24 -0
  52. package/src/codec/http/encoder/response/index.ts +26 -0
  53. package/src/codec/http/headers/index.ts +287 -0
  54. package/src/codec/http/index.ts +33 -0
  55. package/src/codec/http/message/content/index.ts +36 -0
  56. package/src/codec/http/message/full/index.ts +10 -0
  57. package/src/codec/http/message/full/request/index.ts +45 -0
  58. package/src/codec/http/message/full/response/index.ts +43 -0
  59. package/src/codec/http/message/head/index.ts +79 -0
  60. package/src/codec/http/message/index.ts +16 -0
  61. package/src/codec/http/message/last/index.ts +27 -0
  62. package/src/codec/http/message/request/index.ts +39 -0
  63. package/src/codec/http/message/response/index.ts +31 -0
  64. package/src/codec/http/method/index.ts +101 -0
  65. package/src/codec/http/server/index.ts +81 -0
  66. package/src/codec/http/status/index.ts +170 -0
  67. package/src/codec/http/version/index.ts +70 -0
  68. package/src/codec/index.ts +83 -0
  69. package/src/codec/length/index.ts +330 -0
  70. package/src/codec/line/index.ts +45 -0
  71. package/src/codec/message/decoder/index.ts +84 -0
  72. package/src/codec/message/encoder/index.ts +56 -0
  73. package/src/codec/message/index.ts +2 -0
  74. package/src/codec/msgpack/index.ts +51 -0
  75. package/src/codec/prepender/index.ts +296 -0
  76. package/src/codec/protobuf/index.ts +57 -0
  77. package/src/codec/string/decoder/index.ts +47 -0
  78. package/src/codec/string/encoder/index.ts +26 -0
  79. package/src/codec/string/index.ts +2 -0
  80. package/src/codec/websocket/client/index.ts +235 -0
  81. package/src/codec/websocket/decoder/index.ts +371 -0
  82. package/src/codec/websocket/encoder/index.ts +170 -0
  83. package/src/codec/websocket/error/index.ts +42 -0
  84. package/src/codec/websocket/frame/base/index.ts +55 -0
  85. package/src/codec/websocket/frame/binary/index.ts +24 -0
  86. package/src/codec/websocket/frame/close/index.ts +82 -0
  87. package/src/codec/websocket/frame/continuation/index.ts +31 -0
  88. package/src/codec/websocket/frame/index.ts +10 -0
  89. package/src/codec/websocket/frame/opcode/index.ts +35 -0
  90. package/src/codec/websocket/frame/ping/index.ts +24 -0
  91. package/src/codec/websocket/frame/pong/index.ts +24 -0
  92. package/src/codec/websocket/frame/text/index.ts +31 -0
  93. package/src/codec/websocket/handshake/index.ts +38 -0
  94. package/src/codec/websocket/index.ts +25 -0
  95. package/src/codec/websocket/key/index.ts +41 -0
  96. package/src/codec/websocket/protocol/index.ts +147 -0
  97. package/src/codec/websocket/server/index.ts +233 -0
  98. package/src/codec/websocket/status/index.ts +97 -0
  99. package/src/codec/websocket/upgrade/index.ts +116 -0
  100. package/src/datagram/bootstrap/index.ts +269 -0
  101. package/src/datagram/channel/index.ts +103 -0
  102. package/src/datagram/index.ts +10 -0
  103. package/src/datagram/packet/index.ts +72 -0
  104. package/src/datagram/transport/index.ts +239 -0
  105. package/src/handler/flush/index.ts +187 -0
  106. package/src/handler/idle/index.ts +295 -0
  107. package/src/handler/index.ts +22 -0
  108. package/src/handler/logging/index.ts +195 -0
  109. package/src/handler/metrics/index.ts +300 -0
  110. package/src/handler/offload/index.ts +141 -0
  111. package/src/handler/timeout/error/index.ts +29 -0
  112. package/src/handler/timeout/index.ts +3 -0
  113. package/src/handler/timeout/read/index.ts +44 -0
  114. package/src/handler/timeout/write/index.ts +89 -0
  115. package/src/handler/traffic/index.ts +259 -0
  116. package/src/index.ts +258 -0
  117. package/src/logger/index.ts +47 -0
  118. package/src/reliable/bootstrap/index.ts +154 -0
  119. package/src/reliable/cipher/index.ts +227 -0
  120. package/src/reliable/cookie/index.ts +78 -0
  121. package/src/reliable/handler/index.ts +1202 -0
  122. package/src/reliable/handshake/index.ts +144 -0
  123. package/src/reliable/index.ts +38 -0
  124. package/src/reliable/lane/index.ts +420 -0
  125. package/src/reliable/message/index.ts +102 -0
  126. package/src/reliable/packet/index.ts +117 -0
  127. package/src/reliable/peer/index.ts +929 -0
  128. package/src/reliable/registry/index.ts +107 -0
  129. package/src/serve/bootstrap/index.ts +606 -0
  130. package/src/serve/channel/index.ts +246 -0
  131. package/src/serve/index.ts +17 -0
  132. package/src/serve/outbox/index.ts +292 -0
  133. package/src/serve/transport/index.ts +96 -0
  134. package/src/serve/writer/index.ts +119 -0
  135. package/src/shard/envelope/index.ts +44 -0
  136. package/src/shard/gateway/index.ts +119 -0
  137. package/src/shard/index.ts +11 -0
  138. package/src/shard/link/index.ts +743 -0
  139. package/src/shard/map/index.ts +91 -0
  140. package/src/worker/group/index.ts +175 -0
  141. package/src/worker/index.ts +10 -0
  142. package/src/worker/pool/index.ts +235 -0
  143. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,929 @@
1
+ import { ByteBuf } from '../../buffer/index.ts'
2
+ import type { PacketCipher } from '../cipher/index.ts'
3
+ import type { PacketAddress } from '../../datagram/packet/index.ts'
4
+ import {
5
+ Lane,
6
+ type Deliver,
7
+ type LaneOptions,
8
+ type Outgoing,
9
+ } from '../lane/index.ts'
10
+ import { ReliableMessage } from '../message/index.ts'
11
+ import {
12
+ PacketKind,
13
+ ackFlag,
14
+ dataHeaderSize,
15
+ fragmentFlag,
16
+ isNewer,
17
+ messageHeaderSize,
18
+ } from '../packet/index.ts'
19
+
20
+ /**
21
+ * Where a peer is in its life
22
+ */
23
+ export type PeerState = 'connecting' | 'connected' | 'closed'
24
+
25
+ /**
26
+ * Everything a peer needs to know, filled in by ReliableHandler
27
+ */
28
+ export type PeerOptions = {
29
+ /**
30
+ * Where its packets go
31
+ */
32
+ readonly address: PacketAddress
33
+
34
+ /**
35
+ * Session id, 0 until the handshake finishes on the client
36
+ */
37
+ readonly session: number
38
+
39
+ /**
40
+ * Random number the client picked for the handshake
41
+ */
42
+ readonly salt: number
43
+
44
+ /**
45
+ * Lane settings, the same on both ends
46
+ */
47
+ readonly lanes: readonly LaneOptions[]
48
+
49
+ /**
50
+ * Biggest packet we'll send
51
+ */
52
+ readonly mtu: number
53
+
54
+ /**
55
+ * Reliable messages in flight per lane
56
+ */
57
+ readonly window: number
58
+
59
+ /**
60
+ * Send an empty packet after this long without sending anything
61
+ */
62
+ readonly keepalive: number
63
+
64
+ /**
65
+ * Biggest message after joining fragments
66
+ */
67
+ readonly maxMessageSize: number
68
+
69
+ /**
70
+ * Bytes waiting to go out before send starts throwing
71
+ */
72
+ readonly maxQueuedBytes: number
73
+
74
+ /**
75
+ * Sends of one message before we give up on the peer
76
+ */
77
+ readonly maxResends: number
78
+
79
+ /**
80
+ * Shrink the window on loss and grow it back on acks
81
+ */
82
+ readonly congestion: boolean
83
+
84
+ /**
85
+ * Bytes per second we'll send it, 0 for no limit
86
+ */
87
+ readonly maxSendRate: number
88
+ }
89
+
90
+ /**
91
+ * Running counters for one peer
92
+ */
93
+ export type PeerStats = {
94
+ /**
95
+ * Packets we sent
96
+ */
97
+ packetsSent: number
98
+
99
+ /**
100
+ * Packets we took in
101
+ */
102
+ packetsReceived: number
103
+
104
+ /**
105
+ * Reliable messages sent again
106
+ */
107
+ resends: number
108
+ }
109
+
110
+ /**
111
+ * Sent packets remembered for acks, a power of two
112
+ */
113
+ const ringSize = 1024
114
+
115
+ /**
116
+ * Masks a sequence down to a ring slot
117
+ */
118
+ const ringMask = ringSize - 1
119
+
120
+ /**
121
+ * Turns strings into bytes
122
+ */
123
+ const encoder = new TextEncoder()
124
+
125
+ /**
126
+ * One connection over reliable UDP, owned by a ReliableHandler
127
+ * @class
128
+ */
129
+ export class ReliablePeer {
130
+ /**
131
+ * Where its packets go
132
+ */
133
+ public readonly address: PacketAddress
134
+
135
+ /**
136
+ * Random number the client picked for the handshake
137
+ */
138
+ public readonly salt: number
139
+
140
+ /**
141
+ * Session id, every data packet has to carry it
142
+ */
143
+ public session: number
144
+
145
+ /**
146
+ * Where it is in its life
147
+ */
148
+ public state: PeerState
149
+
150
+ /**
151
+ * Running counters
152
+ */
153
+ public readonly stats: PeerStats
154
+
155
+ /**
156
+ * When we last heard from it
157
+ */
158
+ public lastReceivedAt: number
159
+
160
+ /**
161
+ * When we last sent it anything
162
+ */
163
+ public lastSentAt: number
164
+
165
+ /**
166
+ * Set once a message ran out of resends
167
+ */
168
+ public failed: boolean
169
+
170
+ /**
171
+ * Set by close, the handler hangs up on the next pass
172
+ */
173
+ public closing: boolean
174
+
175
+ /**
176
+ * Your own data, the handler never touches it
177
+ */
178
+ public data: unknown
179
+
180
+ /**
181
+ * Seals and opens data packets once the handshake agreed on keys, or null
182
+ */
183
+ public cipher: PacketCipher | null
184
+
185
+ /**
186
+ * Send and receive state per lane
187
+ */
188
+ private readonly lanes: Lane[]
189
+
190
+ /**
191
+ * Settings from the handler
192
+ */
193
+ private readonly options: PeerOptions
194
+
195
+ /**
196
+ * Tells the handler there's something to send
197
+ */
198
+ private readonly wake: (peer: ReliablePeer) => void
199
+
200
+ /**
201
+ * Biggest payload one message can carry
202
+ */
203
+ private readonly payloadSize: number
204
+
205
+ /**
206
+ * Most fragments one message can be cut into
207
+ */
208
+ private readonly maxFragments: number
209
+
210
+ /**
211
+ * Sequence for our next packet
212
+ */
213
+ private nextSequence: number
214
+
215
+ /**
216
+ * Sequence held in each sent slot, -1 when free
217
+ */
218
+ private readonly sentSequences: Int32Array
219
+
220
+ /**
221
+ * When each sent slot went out
222
+ */
223
+ private readonly sentTimes: Float64Array
224
+
225
+ /**
226
+ * Reliable messages each sent slot carried
227
+ */
228
+ private readonly sentMessages: (Outgoing[] | null)[]
229
+
230
+ /**
231
+ * Sequence held in each received slot, -1 when free
232
+ */
233
+ private readonly receivedSequences: Int32Array
234
+
235
+ /**
236
+ * Newest sequence we've had from it
237
+ */
238
+ private remoteSequence: number
239
+
240
+ /**
241
+ * Which of the 32 before remoteSequence we've had
242
+ */
243
+ private receivedBits: number
244
+
245
+ /**
246
+ * Whether we've had any data packet yet
247
+ */
248
+ private hasRemote: boolean
249
+
250
+ /**
251
+ * Whether it's waiting on an ack from us
252
+ */
253
+ private ackPending: boolean
254
+
255
+ /**
256
+ * Data packets in since our last ack
257
+ */
258
+ private unacked: number
259
+
260
+ /**
261
+ * Reliable messages allowed in flight right now
262
+ */
263
+ private congestionWindow: number
264
+
265
+ /**
266
+ * When we last shrank the window
267
+ */
268
+ private lastCutAt: number
269
+
270
+ /**
271
+ * Bytes we may still send before the rate limit kicks in
272
+ */
273
+ private tokens: number
274
+
275
+ /**
276
+ * When tokens was last topped up
277
+ */
278
+ private refilledAt: number
279
+
280
+ /**
281
+ * Smoothed round trip in ms
282
+ */
283
+ private smoothed: number
284
+
285
+ /**
286
+ * Round trip variation in ms
287
+ */
288
+ private variation: number
289
+
290
+ /**
291
+ * Whether we have a round trip sample yet
292
+ */
293
+ private sampled: boolean
294
+
295
+ /**
296
+ * How long before an unacked message goes again
297
+ */
298
+ private timeout: number
299
+
300
+ /**
301
+ * Earliest moment anything in flight could be due
302
+ */
303
+ private nextResendAt: number
304
+
305
+ /**
306
+ * Packet being built
307
+ */
308
+ private readonly scratch: Uint8Array
309
+
310
+ /**
311
+ * Bytes used in scratch, 0 when no packet is open
312
+ */
313
+ private cursor: number
314
+
315
+ /**
316
+ * Reliable messages in the open packet
317
+ */
318
+ private carried: Outgoing[]
319
+
320
+ /**
321
+ * Messages from the packet being read
322
+ */
323
+ private reading: ReliableMessage[]
324
+
325
+ /**
326
+ * Lane of the message being read
327
+ */
328
+ private readingLane: number
329
+
330
+ /**
331
+ * Hands lane output to the reading list
332
+ */
333
+ private readonly deliver: Deliver
334
+
335
+ /**
336
+ * Usually built by ReliableHandler
337
+ * @param options settings from the handler
338
+ * @param wake called whenever there's something new to send
339
+ */
340
+ public constructor(options: PeerOptions, wake: (peer: ReliablePeer) => void) {
341
+ this.address = options.address
342
+ this.salt = options.salt
343
+ this.session = options.session
344
+ this.state = 'connecting'
345
+ this.stats = { packetsSent: 0, packetsReceived: 0, resends: 0 }
346
+ this.lastReceivedAt = performance.now()
347
+ this.lastSentAt = Number.NEGATIVE_INFINITY
348
+ this.failed = false
349
+ this.closing = false
350
+ this.data = null
351
+ this.cipher = null
352
+ this.lanes = options.lanes.map(
353
+ (lane: LaneOptions): Lane => new Lane(lane, options.window),
354
+ )
355
+ this.options = options
356
+ this.wake = wake
357
+ this.payloadSize = options.mtu - dataHeaderSize - messageHeaderSize
358
+ this.maxFragments = Math.ceil(options.maxMessageSize / this.payloadSize)
359
+ this.nextSequence = 0
360
+ this.sentSequences = new Int32Array(ringSize).fill(-1)
361
+ this.sentTimes = new Float64Array(ringSize)
362
+ this.sentMessages = new Array<Outgoing[] | null>(ringSize).fill(null)
363
+ this.receivedSequences = new Int32Array(ringSize).fill(-1)
364
+ this.remoteSequence = 0
365
+ this.receivedBits = 0
366
+ this.hasRemote = false
367
+ this.ackPending = false
368
+ this.unacked = 0
369
+ this.congestionWindow = options.congestion
370
+ ? Math.min(options.window, 64)
371
+ : options.window
372
+ this.lastCutAt = Number.NEGATIVE_INFINITY
373
+ this.tokens = options.maxSendRate
374
+ this.refilledAt = performance.now()
375
+ this.smoothed = 0
376
+ this.variation = 0
377
+ this.sampled = false
378
+ this.timeout = 100
379
+ this.nextResendAt = Number.POSITIVE_INFINITY
380
+ this.scratch = new Uint8Array(options.mtu)
381
+ this.cursor = 0
382
+ this.carried = []
383
+ this.reading = []
384
+ this.readingLane = 0
385
+ this.deliver = (content: Uint8Array): void => {
386
+ this.reading.push(
387
+ new ReliableMessage(this, this.readingLane, ByteBuf.wrap(content)),
388
+ )
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Smoothed round trip in ms, 0 before the first ack
394
+ */
395
+ public get rtt(): number {
396
+ return this.smoothed
397
+ }
398
+
399
+ /**
400
+ * Queues a message, it goes out on the next flush or tick
401
+ * @param lane lane number
402
+ * @param content the bytes, don't change them afterwards
403
+ */
404
+ public send(lane: number, content: ByteBuf | Uint8Array | string): void {
405
+ const bytes = ReliablePeer.bytesOf(content)
406
+ const target = this.lanes[lane]
407
+ if (target === undefined) throw new RangeError('Lane is unknown')
408
+ const reason = this.refusal(target, bytes)
409
+ if (reason !== null) throw new RangeError(reason)
410
+
411
+ target.enqueue(lane, target.reliable ? this.split(bytes) : [bytes])
412
+ this.wake(this)
413
+ }
414
+
415
+ /**
416
+ * Hangs up on the next pass
417
+ */
418
+ public close(): void {
419
+ if (this.state === 'closed') return
420
+
421
+ this.closing = true
422
+ this.wake(this)
423
+ }
424
+
425
+ /**
426
+ * Why a send can't go ahead, or null
427
+ * @param lane the target lane
428
+ * @param bytes the message
429
+ */
430
+ private refusal(lane: Lane, bytes: Uint8Array): string | null {
431
+ if (this.state === 'closed' || this.closing) return 'Peer is closed'
432
+ if (bytes.length > this.options.maxMessageSize) {
433
+ return 'Message is too large'
434
+ }
435
+
436
+ if (!lane.reliable && bytes.length > this.payloadSize) {
437
+ return 'Message is too large'
438
+ }
439
+
440
+ if (lane.queuedBytes + bytes.length > this.options.maxQueuedBytes) {
441
+ return 'Send queue is full'
442
+ }
443
+
444
+ return null
445
+ }
446
+
447
+ /**
448
+ * Cuts a message into pieces that fit a packet
449
+ * @param bytes the message
450
+ */
451
+ private split(bytes: Uint8Array): Uint8Array[] {
452
+ if (bytes.length <= this.payloadSize) return [bytes]
453
+
454
+ const pieces: Uint8Array[] = []
455
+ for (let start = 0; start < bytes.length; start += this.payloadSize) {
456
+ pieces.push(bytes.subarray(start, start + this.payloadSize))
457
+ }
458
+
459
+ return pieces
460
+ }
461
+
462
+ /**
463
+ * Turns whatever we got into bytes
464
+ * @param content a ByteBuf, bytes or a string
465
+ */
466
+ private static bytesOf(content: ByteBuf | Uint8Array | string): Uint8Array {
467
+ if (content instanceof ByteBuf) return content.toUint8Array()
468
+ if (typeof content === 'string') return encoder.encode(content)
469
+
470
+ return content
471
+ }
472
+
473
+ /**
474
+ * Reads a data packet whose kind and session already checked out
475
+ * @param bytes the whole packet
476
+ * @param now current time in ms
477
+ * @param out gets every message that's ready
478
+ */
479
+ public receive(bytes: Uint8Array, now: number, out: ReliableMessage[]): void {
480
+ const sequence = ((bytes[5] ?? 0) << 8) | (bytes[6] ?? 0)
481
+ if (!this.track(sequence)) return
482
+
483
+ this.lastReceivedAt = now
484
+ this.stats.packetsReceived += 1
485
+ if (((bytes[0] ?? 0) & ackFlag) !== 0) {
486
+ const ack = ((bytes[7] ?? 0) << 8) | (bytes[8] ?? 0)
487
+ const bits =
488
+ ((bytes[9] ?? 0) << 24) |
489
+ ((bytes[10] ?? 0) << 16) |
490
+ ((bytes[11] ?? 0) << 8) |
491
+ (bytes[12] ?? 0)
492
+ this.acknowledgePackets(ack, bits, now)
493
+ }
494
+
495
+ if (bytes.length > dataHeaderSize) {
496
+ this.ackPending = true
497
+ this.unacked += 1
498
+ }
499
+
500
+ this.reading = out
501
+ this.read(bytes)
502
+ }
503
+
504
+ /**
505
+ * Whether it owes two acks, has a resend due or has messages it could send now
506
+ */
507
+ public get hasWork(): boolean {
508
+ if (this.unacked >= 2 || this.nextResendAt <= this.lastReceivedAt) {
509
+ return true
510
+ }
511
+
512
+ const limit = this.congestionWindow
513
+ for (const lane of this.lanes) {
514
+ if (lane.queue.length > 0 && (!lane.reliable || lane.hasRoom(limit))) {
515
+ return true
516
+ }
517
+ }
518
+
519
+ return false
520
+ }
521
+
522
+ /**
523
+ * Whether a tick has anything to do for it, checked before packing
524
+ * @param now current time in ms
525
+ */
526
+ public isDue(now: number): boolean {
527
+ if (this.ackPending || now >= this.nextResendAt) return true
528
+ if (now - this.lastSentAt >= this.options.keepalive) return true
529
+
530
+ for (const lane of this.lanes) if (lane.queue.length > 0) return true
531
+ return false
532
+ }
533
+
534
+ /**
535
+ * Whether it's waiting on an ack from us
536
+ */
537
+ public get owesAck(): boolean {
538
+ return this.ackPending
539
+ }
540
+
541
+ /**
542
+ * Notes a packet's sequence for our acks, false for duplicates and stale ones
543
+ * @param sequence its sequence
544
+ */
545
+ private track(sequence: number): boolean {
546
+ const slot = sequence & ringMask
547
+ if (this.receivedSequences[slot] === sequence) return false
548
+ if (
549
+ this.hasRemote &&
550
+ !isNewer(sequence, this.remoteSequence) &&
551
+ ((this.remoteSequence - sequence) & 0xffff) >= ringSize
552
+ ) {
553
+ return false
554
+ }
555
+
556
+ this.receivedSequences[slot] = sequence
557
+ if (!this.hasRemote) {
558
+ this.hasRemote = true
559
+ this.remoteSequence = sequence
560
+ this.receivedBits = 0
561
+ return true
562
+ }
563
+
564
+ if (isNewer(sequence, this.remoteSequence)) {
565
+ const shift = (sequence - this.remoteSequence) & 0xffff
566
+ this.receivedBits =
567
+ shift > 32
568
+ ? 0
569
+ : shift === 32
570
+ ? 0x80000000
571
+ : ((this.receivedBits << shift) | (1 << (shift - 1))) >>> 0
572
+ this.remoteSequence = sequence
573
+ return true
574
+ }
575
+
576
+ const distance = (this.remoteSequence - sequence) & 0xffff
577
+ if (distance <= 32) {
578
+ this.receivedBits = (this.receivedBits | (1 << (distance - 1))) >>> 0
579
+ }
580
+
581
+ return true
582
+ }
583
+
584
+ /**
585
+ * Works through the ack and the 32 bits behind it
586
+ * @param ack newest packet it has from us
587
+ * @param bits which of the 32 before that it has
588
+ * @param now current time in ms
589
+ */
590
+ private acknowledgePackets(ack: number, bits: number, now: number): void {
591
+ this.acknowledgePacket(ack, now)
592
+
593
+ let remaining = bits
594
+ while (remaining !== 0) {
595
+ const lowest = remaining & -remaining
596
+ this.acknowledgePacket((ack - 32 + Math.clz32(lowest)) & 0xffff, now)
597
+ remaining ^= lowest
598
+ }
599
+
600
+ let missing = ~bits & ~3
601
+ while (missing !== 0) {
602
+ const lowest = missing & -missing
603
+ this.lose((ack - 32 + Math.clz32(lowest)) & 0xffff, now)
604
+ missing ^= lowest
605
+ }
606
+ }
607
+
608
+ /**
609
+ * Treats a packet as lost once three newer ones got through, so its messages go again now
610
+ * @param sequence the packet's sequence
611
+ * @param now current time in ms
612
+ */
613
+ private lose(sequence: number, now: number): void {
614
+ const slot = sequence & ringMask
615
+ if (this.sentSequences[slot] !== sequence) return
616
+ this.sentSequences[slot] = -1
617
+
618
+ const messages = this.sentMessages[slot]
619
+ this.sentMessages[slot] = null
620
+ if (messages === null || messages === undefined) return
621
+
622
+ for (const message of messages) {
623
+ if (!message.acked) message.lastSent = Number.NEGATIVE_INFINITY
624
+ }
625
+
626
+ this.nextResendAt = 0
627
+ this.cut(now)
628
+ }
629
+
630
+ /**
631
+ * Marks everything in one of our packets as delivered
632
+ * @param sequence the packet's sequence
633
+ * @param now current time in ms
634
+ */
635
+ private acknowledgePacket(sequence: number, now: number): void {
636
+ const slot = sequence & ringMask
637
+ if (this.sentSequences[slot] !== sequence) return
638
+ this.sentSequences[slot] = -1
639
+
640
+ this.sample(now - (this.sentTimes[slot] ?? now))
641
+ const messages = this.sentMessages[slot]
642
+ if (messages === null || messages === undefined) return
643
+ this.sentMessages[slot] = null
644
+
645
+ for (const message of messages) {
646
+ this.lanes[message.lane]?.acknowledge(message)
647
+ }
648
+
649
+ if (this.options.congestion) {
650
+ this.congestionWindow = Math.min(
651
+ this.options.window,
652
+ this.congestionWindow + messages.length,
653
+ )
654
+ }
655
+ }
656
+
657
+ /**
658
+ * Halves the congestion window, at most once per round trip
659
+ * @param now current time in ms
660
+ */
661
+ private cut(now: number): void {
662
+ if (!this.options.congestion) return
663
+ if (now - this.lastCutAt < Math.max(this.smoothed, 1)) return
664
+
665
+ this.lastCutAt = now
666
+ this.congestionWindow = Math.max(16, Math.floor(this.congestionWindow / 2))
667
+ }
668
+
669
+ /**
670
+ * Folds a round trip sample into the estimate, RFC 6298 style
671
+ * @param rtt the sample in ms
672
+ */
673
+ private sample(rtt: number): void {
674
+ if (this.sampled) {
675
+ this.variation =
676
+ 0.75 * this.variation + 0.25 * Math.abs(this.smoothed - rtt)
677
+ this.smoothed = 0.875 * this.smoothed + 0.125 * rtt
678
+ } else {
679
+ this.sampled = true
680
+ this.smoothed = rtt
681
+ this.variation = rtt / 2
682
+ }
683
+
684
+ this.timeout = Math.min(
685
+ 1000,
686
+ Math.max(30, this.smoothed + 4 * this.variation),
687
+ )
688
+ }
689
+
690
+ /**
691
+ * Walks the messages in a packet and hands them to their lanes
692
+ * @param bytes the whole packet
693
+ */
694
+ private read(bytes: Uint8Array): void {
695
+ const end = bytes.length
696
+ let offset = dataHeaderSize
697
+
698
+ while (offset < end) {
699
+ const head = bytes[offset] ?? 0
700
+ const laneIndex = head & 0x7f
701
+ const lane = this.lanes[laneIndex]
702
+ if (lane === undefined || offset + 4 > end) return
703
+
704
+ const id = ((bytes[offset + 1] ?? 0) << 8) | (bytes[offset + 2] ?? 0)
705
+ offset += 3
706
+ let index = 0
707
+ let count = 1
708
+ if ((head & fragmentFlag) !== 0) {
709
+ index = bytes[offset] ?? 0
710
+ count = bytes[offset + 1] ?? 0
711
+ offset += 2
712
+ if (!lane.reliable || count < 2 || index >= count) return
713
+ if (count > this.maxFragments) return
714
+ }
715
+
716
+ let length = 0
717
+ let shift = 0
718
+ let byte = 0x80
719
+ while ((byte & 0x80) !== 0) {
720
+ if (offset >= end || shift > 14) return
721
+ byte = bytes[offset] ?? 0
722
+ offset += 1
723
+ length |= (byte & 0x7f) << shift
724
+ shift += 7
725
+ }
726
+
727
+ if (offset + length > end) return
728
+
729
+ this.readingLane = laneIndex
730
+ lane.receive(
731
+ id,
732
+ index,
733
+ count,
734
+ bytes.subarray(offset, offset + length),
735
+ this.deliver,
736
+ )
737
+ offset += length
738
+ }
739
+ }
740
+
741
+ /**
742
+ * Builds every packet that's due, resends first, then new messages, then acks and keep-alives
743
+ * @param now current time in ms
744
+ * @param out gets each finished packet
745
+ * @param force send a lone ack even if only one packet is owed one
746
+ */
747
+ public pack(now: number, out: Uint8Array[], force: boolean): void {
748
+ if (this.state !== 'connected') return
749
+
750
+ this.refill(now)
751
+ if (now >= this.nextResendAt) this.resend(now, out)
752
+ for (const lane of this.lanes) this.fresh(lane, now, out)
753
+ this.seal(now, out)
754
+
755
+ const owed = this.ackPending && (force || this.unacked >= 2)
756
+ if (owed || now - this.lastSentAt >= this.options.keepalive) {
757
+ this.cursor = dataHeaderSize
758
+ this.seal(now, out)
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Tops up the send budget
764
+ * @param now current time in ms
765
+ */
766
+ private refill(now: number): void {
767
+ const rate = this.options.maxSendRate
768
+ if (rate === 0) return
769
+
770
+ const burst = Math.max(this.options.mtu * 4, rate / 20)
771
+ this.tokens = Math.min(
772
+ burst,
773
+ this.tokens + (rate * (now - this.refilledAt)) / 1000,
774
+ )
775
+ this.refilledAt = now
776
+ }
777
+
778
+ /**
779
+ * Sends again anything that's gone unacked too long
780
+ * @param now current time in ms
781
+ * @param out gets each finished packet
782
+ */
783
+ private resend(now: number, out: Uint8Array[]): void {
784
+ let next = Number.POSITIVE_INFINITY
785
+
786
+ for (const lane of this.lanes) {
787
+ for (const message of lane.inFlight.values()) {
788
+ const due = message.lastSent + this.timeout
789
+ if (due > now) {
790
+ if (due < next) next = due
791
+ continue
792
+ }
793
+
794
+ if (Number.isFinite(message.lastSent)) this.cut(now)
795
+ this.append(message, true, now, out)
796
+ this.stats.resends += 1
797
+ next = Math.min(next, now + this.timeout)
798
+ }
799
+ }
800
+
801
+ this.nextResendAt = next
802
+ }
803
+
804
+ /**
805
+ * Moves queued messages into packets, as far as the window allows
806
+ * @param lane the lane to drain
807
+ * @param now current time in ms
808
+ * @param out gets each finished packet
809
+ */
810
+ private fresh(lane: Lane, now: number, out: Uint8Array[]): void {
811
+ const queue = lane.queue
812
+ if (queue.length === 0) return
813
+
814
+ const limited = this.options.maxSendRate !== 0
815
+ const limit = this.congestionWindow
816
+ let taken = 0
817
+ for (const message of queue) {
818
+ if (limited && this.tokens <= 0) break
819
+ if (lane.reliable) {
820
+ if (!lane.hasRoom(limit)) break
821
+ lane.launch(message)
822
+ } else {
823
+ lane.queuedBytes -= message.payload.length
824
+ }
825
+
826
+ this.append(message, lane.reliable, now, out)
827
+ taken += 1
828
+ }
829
+
830
+ if (lane.reliable && taken > 0) {
831
+ this.nextResendAt = Math.min(this.nextResendAt, now + this.timeout)
832
+ }
833
+
834
+ if (taken === queue.length) queue.length = 0
835
+ else queue.splice(0, taken)
836
+ }
837
+
838
+ /**
839
+ * Writes one message into the open packet, sealing it first if it won't fit
840
+ * @param message what to write
841
+ * @param reliable whether to track it for acks
842
+ * @param now current time in ms
843
+ * @param out gets the packet if it gets sealed
844
+ */
845
+ private append(
846
+ message: Outgoing,
847
+ reliable: boolean,
848
+ now: number,
849
+ out: Uint8Array[],
850
+ ): void {
851
+ const length = message.payload.length
852
+ const fragmented = message.count > 1
853
+ const size =
854
+ (fragmented ? 6 : 4) + (length < 0x80 ? 0 : length < 0x4000 ? 1 : 2)
855
+ if (this.cursor + size + length > this.options.mtu) this.seal(now, out)
856
+ if (this.cursor === 0) this.cursor = dataHeaderSize
857
+
858
+ const scratch = this.scratch
859
+ let offset = this.cursor
860
+ scratch[offset++] = fragmented ? message.lane | fragmentFlag : message.lane
861
+ scratch[offset++] = message.id >>> 8
862
+ scratch[offset++] = message.id & 0xff
863
+ if (fragmented) {
864
+ scratch[offset++] = message.index
865
+ scratch[offset++] = message.count
866
+ }
867
+
868
+ let value = length
869
+ while (value >= 0x80) {
870
+ scratch[offset++] = (value & 0x7f) | 0x80
871
+ value >>>= 7
872
+ }
873
+
874
+ scratch[offset++] = value
875
+ scratch.set(message.payload, offset)
876
+ this.cursor = offset + length
877
+ this.tokens -= size + length
878
+ if (!reliable) return
879
+
880
+ message.lastSent = now
881
+ message.sends += 1
882
+ if (message.sends > this.options.maxResends) this.failed = true
883
+ this.carried.push(message)
884
+ }
885
+
886
+ /**
887
+ * Finishes the open packet, if there is one
888
+ * @param now current time in ms
889
+ * @param out gets the packet
890
+ */
891
+ private seal(now: number, out: Uint8Array[]): void {
892
+ if (this.cursor === 0) return
893
+
894
+ const scratch = this.scratch
895
+ const sequence = this.nextSequence
896
+ const session = this.session
897
+ scratch[0] = PacketKind.data | (this.hasRemote ? ackFlag : 0)
898
+ scratch[1] = session >>> 24
899
+ scratch[2] = (session >>> 16) & 0xff
900
+ scratch[3] = (session >>> 8) & 0xff
901
+ scratch[4] = session & 0xff
902
+ scratch[5] = sequence >>> 8
903
+ scratch[6] = sequence & 0xff
904
+ scratch[7] = this.remoteSequence >>> 8
905
+ scratch[8] = this.remoteSequence & 0xff
906
+ scratch[9] = this.receivedBits >>> 24
907
+ scratch[10] = (this.receivedBits >>> 16) & 0xff
908
+ scratch[11] = (this.receivedBits >>> 8) & 0xff
909
+ scratch[12] = this.receivedBits & 0xff
910
+ out.push(scratch.slice(0, this.cursor))
911
+
912
+ const slot = sequence & ringMask
913
+ this.sentSequences[slot] = sequence
914
+ this.sentTimes[slot] = now
915
+ if (this.carried.length === 0) {
916
+ this.sentMessages[slot] = null
917
+ } else {
918
+ this.sentMessages[slot] = this.carried
919
+ this.carried = []
920
+ }
921
+
922
+ this.nextSequence = (sequence + 1) & 0xffff
923
+ this.cursor = 0
924
+ this.ackPending = false
925
+ this.unacked = 0
926
+ this.lastSentAt = now
927
+ this.stats.packetsSent += 1
928
+ }
929
+ }