@netifyjs/netify 1.0.0-alpha.4 → 1.0.0-alpha.5
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/README.md +6 -6
- package/package.json +1 -1
- package/src/bootstrap/client/index.ts +1 -1
- package/src/bootstrap/dispatcher/index.ts +7 -0
- package/src/bootstrap/reconnect/index.ts +14 -4
- package/src/bootstrap/server/index.ts +10 -4
- package/src/buffer/index.ts +229 -88
- package/src/buffer/quantizer/index.ts +16 -3
- package/src/channel/context/index.ts +18 -11
- package/src/channel/handler/index.ts +1 -1
- package/src/channel/index.ts +30 -7
- package/src/channel/outbound/index.ts +28 -12
- package/src/channel/pipeline/index.ts +45 -5
- package/src/channel/queue/index.ts +3 -2
- package/src/channel/resolved/index.ts +13 -3
- package/src/channel/server/index.ts +19 -10
- package/src/cluster/index.ts +73 -32
- package/src/codec/binary/index.ts +19 -0
- package/src/codec/decoder/index.ts +223 -83
- package/src/codec/delimiter/index.ts +95 -37
- package/src/codec/encoder/index.ts +30 -5
- package/src/codec/fixed/index.ts +5 -1
- package/src/codec/http/aggregator/index.ts +45 -16
- package/src/codec/http/decoder/object/index.ts +156 -40
- package/src/codec/http/decoder/request/index.ts +6 -2
- package/src/codec/http/encoder/object/index.ts +2 -7
- package/src/codec/http/encoder/request/index.ts +5 -0
- package/src/codec/http/headers/index.ts +45 -2
- package/src/codec/http/message/full/request/index.ts +1 -1
- package/src/codec/http/message/full/response/index.ts +1 -1
- package/src/codec/http/message/request/index.ts +14 -1
- package/src/codec/http/message/response/index.ts +1 -1
- package/src/codec/http/version/index.ts +3 -0
- package/src/codec/length/index.ts +66 -44
- package/src/codec/message/decoder/index.ts +18 -1
- package/src/codec/message/encoder/index.ts +85 -8
- package/src/codec/prepender/index.ts +4 -1
- package/src/codec/string/decoder/index.ts +6 -1
- package/src/codec/websocket/decoder/index.ts +78 -3
- package/src/codec/websocket/encoder/index.ts +90 -6
- package/src/codec/websocket/frame/base/index.ts +19 -10
- package/src/codec/websocket/frame/text/index.ts +2 -2
- package/src/codec/websocket/protocol/index.ts +12 -0
- package/src/datagram/bootstrap/index.ts +1 -1
- package/src/datagram/transport/index.ts +30 -1
- package/src/handler/flush/index.ts +25 -5
- package/src/handler/idle/index.ts +120 -26
- package/src/handler/logging/index.ts +13 -1
- package/src/handler/metrics/index.ts +49 -16
- package/src/handler/offload/index.ts +7 -0
- package/src/handler/timeout/read/index.ts +1 -1
- package/src/handler/timeout/write/index.ts +104 -23
- package/src/handler/traffic/index.ts +251 -38
- package/src/index.ts +1 -0
- package/src/reliable/cipher/index.ts +49 -5
- package/src/reliable/cookie/index.ts +64 -2
- package/src/reliable/handler/index.ts +11 -15
- package/src/reliable/index.ts +7 -1
- package/src/reliable/lane/index.ts +277 -58
- package/src/reliable/peer/index.ts +125 -38
- package/src/serve/bootstrap/index.ts +82 -135
- package/src/serve/channel/index.ts +84 -2
- package/src/serve/gate/index.ts +215 -0
- package/src/serve/index.ts +6 -2
- package/src/serve/outbox/index.ts +63 -2
- package/src/serve/transport/index.ts +33 -3
- package/src/serve/writer/index.ts +4 -3
- package/src/shard/gateway/index.ts +102 -29
- package/src/shard/link/index.ts +15 -0
- package/src/worker/group/index.ts +231 -13
- package/src/worker/pool/index.ts +100 -19
- package/src/worker/service/index.ts +9 -1
|
@@ -4,6 +4,7 @@ import type { PacketAddress } from '../../datagram/packet/index.ts'
|
|
|
4
4
|
import {
|
|
5
5
|
Lane,
|
|
6
6
|
type Deliver,
|
|
7
|
+
type LaneLimits,
|
|
7
8
|
type LaneOptions,
|
|
8
9
|
type Outgoing,
|
|
9
10
|
} from '../lane/index.ts'
|
|
@@ -117,6 +118,11 @@ const ringSize = 1024
|
|
|
117
118
|
*/
|
|
118
119
|
const ringMask = ringSize - 1
|
|
119
120
|
|
|
121
|
+
/**
|
|
122
|
+
* Longest resend wait in ms
|
|
123
|
+
*/
|
|
124
|
+
const maxTimeout = 1000
|
|
125
|
+
|
|
120
126
|
/**
|
|
121
127
|
* Turns strings into bytes
|
|
122
128
|
*/
|
|
@@ -297,6 +303,16 @@ export class ReliablePeer {
|
|
|
297
303
|
*/
|
|
298
304
|
private timeout: number
|
|
299
305
|
|
|
306
|
+
/**
|
|
307
|
+
* Times the wait has doubled since the last ack
|
|
308
|
+
*/
|
|
309
|
+
private backoff: number
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* When the wait last doubled
|
|
313
|
+
*/
|
|
314
|
+
private backedOffAt: number
|
|
315
|
+
|
|
300
316
|
/**
|
|
301
317
|
* Earliest moment anything in flight could be due
|
|
302
318
|
*/
|
|
@@ -349,13 +365,11 @@ export class ReliablePeer {
|
|
|
349
365
|
this.closing = false
|
|
350
366
|
this.data = null
|
|
351
367
|
this.cipher = null
|
|
352
|
-
this.lanes = options.lanes.map(
|
|
353
|
-
(lane: LaneOptions): Lane => new Lane(lane, options.window),
|
|
354
|
-
)
|
|
355
368
|
this.options = options
|
|
356
369
|
this.wake = wake
|
|
357
370
|
this.payloadSize = options.mtu - dataHeaderSize - messageHeaderSize
|
|
358
371
|
this.maxFragments = Math.ceil(options.maxMessageSize / this.payloadSize)
|
|
372
|
+
this.lanes = ReliablePeer.lanesOf(options, this.maxFragments)
|
|
359
373
|
this.nextSequence = 0
|
|
360
374
|
this.sentSequences = new Int32Array(ringSize).fill(-1)
|
|
361
375
|
this.sentTimes = new Float64Array(ringSize)
|
|
@@ -376,6 +390,8 @@ export class ReliablePeer {
|
|
|
376
390
|
this.variation = 0
|
|
377
391
|
this.sampled = false
|
|
378
392
|
this.timeout = 100
|
|
393
|
+
this.backoff = 0
|
|
394
|
+
this.backedOffAt = Number.NEGATIVE_INFINITY
|
|
379
395
|
this.nextResendAt = Number.POSITIVE_INFINITY
|
|
380
396
|
this.scratch = new Uint8Array(options.mtu)
|
|
381
397
|
this.cursor = 0
|
|
@@ -389,6 +405,23 @@ export class ReliablePeer {
|
|
|
389
405
|
}
|
|
390
406
|
}
|
|
391
407
|
|
|
408
|
+
/**
|
|
409
|
+
* Builds a lane per setting
|
|
410
|
+
* @param options settings from the handler
|
|
411
|
+
* @param maxFragments most pieces per message
|
|
412
|
+
*/
|
|
413
|
+
private static lanesOf(options: PeerOptions, maxFragments: number): Lane[] {
|
|
414
|
+
const limits: LaneLimits = {
|
|
415
|
+
window: options.window,
|
|
416
|
+
maxMessageSize: options.maxMessageSize,
|
|
417
|
+
maxHeldBytes: (options.window + maxFragments) * options.mtu,
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return options.lanes.map(
|
|
421
|
+
(lane: LaneOptions): Lane => new Lane(lane, limits),
|
|
422
|
+
)
|
|
423
|
+
}
|
|
424
|
+
|
|
392
425
|
/**
|
|
393
426
|
* Smoothed round trip in ms, 0 before the first ack
|
|
394
427
|
*/
|
|
@@ -477,11 +510,14 @@ export class ReliablePeer {
|
|
|
477
510
|
* @param out gets every message that's ready
|
|
478
511
|
*/
|
|
479
512
|
public receive(bytes: Uint8Array, now: number, out: ReliableMessage[]): void {
|
|
513
|
+
const cipher = this.cipher
|
|
514
|
+
const body = cipher === null ? bytes : cipher.open(bytes)
|
|
515
|
+
if (body === null) return
|
|
516
|
+
|
|
480
517
|
const sequence = ((bytes[5] ?? 0) << 8) | (bytes[6] ?? 0)
|
|
481
|
-
if (
|
|
518
|
+
if (this.stale(sequence)) return
|
|
482
519
|
|
|
483
520
|
this.lastReceivedAt = now
|
|
484
|
-
this.stats.packetsReceived += 1
|
|
485
521
|
if (((bytes[0] ?? 0) & ackFlag) !== 0) {
|
|
486
522
|
const ack = ((bytes[7] ?? 0) << 8) | (bytes[8] ?? 0)
|
|
487
523
|
const bits =
|
|
@@ -492,13 +528,16 @@ export class ReliablePeer {
|
|
|
492
528
|
this.acknowledgePackets(ack, bits, now)
|
|
493
529
|
}
|
|
494
530
|
|
|
495
|
-
|
|
531
|
+
const start = cipher === null ? dataHeaderSize : 0
|
|
532
|
+
this.reading = out
|
|
533
|
+
if (!this.read(body, start)) return
|
|
534
|
+
|
|
535
|
+
this.track(sequence)
|
|
536
|
+
this.stats.packetsReceived += 1
|
|
537
|
+
if (body.length > start) {
|
|
496
538
|
this.ackPending = true
|
|
497
539
|
this.unacked += 1
|
|
498
540
|
}
|
|
499
|
-
|
|
500
|
-
this.reading = out
|
|
501
|
-
this.read(bytes)
|
|
502
541
|
}
|
|
503
542
|
|
|
504
543
|
/**
|
|
@@ -539,26 +578,30 @@ export class ReliablePeer {
|
|
|
539
578
|
}
|
|
540
579
|
|
|
541
580
|
/**
|
|
542
|
-
*
|
|
581
|
+
* Whether a packet is stale or a repeat
|
|
543
582
|
* @param sequence its sequence
|
|
544
583
|
*/
|
|
545
|
-
private
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
584
|
+
private stale(sequence: number): boolean {
|
|
585
|
+
if (this.receivedSequences[sequence & ringMask] === sequence) return true
|
|
586
|
+
|
|
587
|
+
return (
|
|
549
588
|
this.hasRemote &&
|
|
550
589
|
!isNewer(sequence, this.remoteSequence) &&
|
|
551
590
|
((this.remoteSequence - sequence) & 0xffff) >= ringSize
|
|
552
|
-
)
|
|
553
|
-
|
|
554
|
-
}
|
|
591
|
+
)
|
|
592
|
+
}
|
|
555
593
|
|
|
556
|
-
|
|
594
|
+
/**
|
|
595
|
+
* Remembers a sequence to ack
|
|
596
|
+
* @param sequence packet number
|
|
597
|
+
*/
|
|
598
|
+
private track(sequence: number): void {
|
|
599
|
+
this.receivedSequences[sequence & ringMask] = sequence
|
|
557
600
|
if (!this.hasRemote) {
|
|
558
601
|
this.hasRemote = true
|
|
559
602
|
this.remoteSequence = sequence
|
|
560
603
|
this.receivedBits = 0
|
|
561
|
-
return
|
|
604
|
+
return
|
|
562
605
|
}
|
|
563
606
|
|
|
564
607
|
if (isNewer(sequence, this.remoteSequence)) {
|
|
@@ -570,15 +613,13 @@ export class ReliablePeer {
|
|
|
570
613
|
? 0x80000000
|
|
571
614
|
: ((this.receivedBits << shift) | (1 << (shift - 1))) >>> 0
|
|
572
615
|
this.remoteSequence = sequence
|
|
573
|
-
return
|
|
616
|
+
return
|
|
574
617
|
}
|
|
575
618
|
|
|
576
619
|
const distance = (this.remoteSequence - sequence) & 0xffff
|
|
577
620
|
if (distance <= 32) {
|
|
578
621
|
this.receivedBits = (this.receivedBits | (1 << (distance - 1))) >>> 0
|
|
579
622
|
}
|
|
580
|
-
|
|
581
|
-
return true
|
|
582
623
|
}
|
|
583
624
|
|
|
584
625
|
/**
|
|
@@ -641,6 +682,7 @@ export class ReliablePeer {
|
|
|
641
682
|
const messages = this.sentMessages[slot]
|
|
642
683
|
if (messages === null || messages === undefined) return
|
|
643
684
|
this.sentMessages[slot] = null
|
|
685
|
+
this.backoff = 0
|
|
644
686
|
|
|
645
687
|
for (const message of messages) {
|
|
646
688
|
this.lanes[message.lane]?.acknowledge(message)
|
|
@@ -682,24 +724,26 @@ export class ReliablePeer {
|
|
|
682
724
|
}
|
|
683
725
|
|
|
684
726
|
this.timeout = Math.min(
|
|
685
|
-
|
|
727
|
+
maxTimeout,
|
|
686
728
|
Math.max(30, this.smoothed + 4 * this.variation),
|
|
687
729
|
)
|
|
688
730
|
}
|
|
689
731
|
|
|
690
732
|
/**
|
|
691
|
-
*
|
|
692
|
-
* @param bytes the
|
|
733
|
+
* Hands messages to their lanes, false if any was refused
|
|
734
|
+
* @param bytes the packet or its opened body
|
|
735
|
+
* @param start where the first message begins
|
|
693
736
|
*/
|
|
694
|
-
private read(bytes: Uint8Array):
|
|
737
|
+
private read(bytes: Uint8Array, start: number): boolean {
|
|
695
738
|
const end = bytes.length
|
|
696
|
-
let offset =
|
|
739
|
+
let offset = start
|
|
740
|
+
let kept = true
|
|
697
741
|
|
|
698
742
|
while (offset < end) {
|
|
699
743
|
const head = bytes[offset] ?? 0
|
|
700
744
|
const laneIndex = head & 0x7f
|
|
701
745
|
const lane = this.lanes[laneIndex]
|
|
702
|
-
if (lane === undefined || offset + 4 > end) return
|
|
746
|
+
if (lane === undefined || offset + 4 > end) return false
|
|
703
747
|
|
|
704
748
|
const id = ((bytes[offset + 1] ?? 0) << 8) | (bytes[offset + 2] ?? 0)
|
|
705
749
|
offset += 3
|
|
@@ -709,33 +753,36 @@ export class ReliablePeer {
|
|
|
709
753
|
index = bytes[offset] ?? 0
|
|
710
754
|
count = bytes[offset + 1] ?? 0
|
|
711
755
|
offset += 2
|
|
712
|
-
if (!lane.reliable || count < 2 || index >= count) return
|
|
713
|
-
if (count > this.maxFragments) return
|
|
756
|
+
if (!lane.reliable || count < 2 || index >= count) return false
|
|
757
|
+
if (count > this.maxFragments) return false
|
|
714
758
|
}
|
|
715
759
|
|
|
716
760
|
let length = 0
|
|
717
761
|
let shift = 0
|
|
718
762
|
let byte = 0x80
|
|
719
763
|
while ((byte & 0x80) !== 0) {
|
|
720
|
-
if (offset >= end || shift > 14) return
|
|
764
|
+
if (offset >= end || shift > 14) return false
|
|
721
765
|
byte = bytes[offset] ?? 0
|
|
722
766
|
offset += 1
|
|
723
767
|
length |= (byte & 0x7f) << shift
|
|
724
768
|
shift += 7
|
|
725
769
|
}
|
|
726
770
|
|
|
727
|
-
if (offset + length > end) return
|
|
771
|
+
if (offset + length > end) return false
|
|
728
772
|
|
|
729
773
|
this.readingLane = laneIndex
|
|
730
|
-
lane.receive(
|
|
774
|
+
const taken = lane.receive(
|
|
731
775
|
id,
|
|
732
776
|
index,
|
|
733
777
|
count,
|
|
734
778
|
bytes.subarray(offset, offset + length),
|
|
735
779
|
this.deliver,
|
|
736
780
|
)
|
|
781
|
+
if (!taken) kept = false
|
|
737
782
|
offset += length
|
|
738
783
|
}
|
|
784
|
+
|
|
785
|
+
return kept
|
|
739
786
|
}
|
|
740
787
|
|
|
741
788
|
/**
|
|
@@ -781,26 +828,61 @@ export class ReliablePeer {
|
|
|
781
828
|
* @param out gets each finished packet
|
|
782
829
|
*/
|
|
783
830
|
private resend(now: number, out: Uint8Array[]): void {
|
|
831
|
+
const limited = this.options.maxSendRate !== 0
|
|
832
|
+
const wait = this.wait()
|
|
784
833
|
let next = Number.POSITIVE_INFINITY
|
|
834
|
+
let sent = false
|
|
835
|
+
let expired = false
|
|
785
836
|
|
|
786
837
|
for (const lane of this.lanes) {
|
|
787
|
-
|
|
788
|
-
|
|
838
|
+
const end = lane.flightEnd
|
|
839
|
+
for (let id = lane.flightStart; id !== end; id = (id + 1) & 0xffff) {
|
|
840
|
+
const message = lane.flying(id)
|
|
841
|
+
if (message === undefined) continue
|
|
842
|
+
|
|
843
|
+
const due = message.lastSent + wait
|
|
789
844
|
if (due > now) {
|
|
790
845
|
if (due < next) next = due
|
|
791
846
|
continue
|
|
792
847
|
}
|
|
793
848
|
|
|
794
|
-
if (
|
|
849
|
+
if (limited && this.tokens <= 0) {
|
|
850
|
+
next = now
|
|
851
|
+
continue
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
if (Number.isFinite(message.lastSent)) expired = true
|
|
795
855
|
this.append(message, true, now, out)
|
|
796
856
|
this.stats.resends += 1
|
|
797
|
-
|
|
857
|
+
sent = true
|
|
798
858
|
}
|
|
799
859
|
}
|
|
800
860
|
|
|
861
|
+
if (expired) this.slow(now, wait)
|
|
862
|
+
if (sent) next = Math.min(next, now + this.wait())
|
|
801
863
|
this.nextResendAt = next
|
|
802
864
|
}
|
|
803
865
|
|
|
866
|
+
/**
|
|
867
|
+
* Current resend wait
|
|
868
|
+
*/
|
|
869
|
+
private wait(): number {
|
|
870
|
+
return Math.min(maxTimeout, this.timeout * 2 ** this.backoff)
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Doubles the wait after a timeout
|
|
875
|
+
* @param now current time in ms
|
|
876
|
+
* @param wait the wait that ran out
|
|
877
|
+
*/
|
|
878
|
+
private slow(now: number, wait: number): void {
|
|
879
|
+
this.cut(now)
|
|
880
|
+
if (now - this.backedOffAt < wait || this.backoff >= 6) return
|
|
881
|
+
|
|
882
|
+
this.backoff += 1
|
|
883
|
+
this.backedOffAt = now
|
|
884
|
+
}
|
|
885
|
+
|
|
804
886
|
/**
|
|
805
887
|
* Moves queued messages into packets, as far as the window allows
|
|
806
888
|
* @param lane the lane to drain
|
|
@@ -907,7 +989,12 @@ export class ReliablePeer {
|
|
|
907
989
|
scratch[10] = (this.receivedBits >>> 16) & 0xff
|
|
908
990
|
scratch[11] = (this.receivedBits >>> 8) & 0xff
|
|
909
991
|
scratch[12] = this.receivedBits & 0xff
|
|
910
|
-
|
|
992
|
+
const cipher = this.cipher
|
|
993
|
+
out.push(
|
|
994
|
+
cipher === null
|
|
995
|
+
? scratch.slice(0, this.cursor)
|
|
996
|
+
: cipher.seal(scratch.subarray(0, this.cursor)),
|
|
997
|
+
)
|
|
911
998
|
|
|
912
999
|
const slot = sequence & ringMask
|
|
913
1000
|
this.sentSequences[slot] = sequence
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Server, ServerWebSocket, TLSOptions } from 'bun'
|
|
2
2
|
|
|
3
3
|
import { ByteBuf } from '../../buffer/index.ts'
|
|
4
4
|
import type { ChannelOptions } from '../../channel/index.ts'
|
|
@@ -15,6 +15,7 @@ import { TextWebSocketFrame } from '../../codec/websocket/frame/text/index.ts'
|
|
|
15
15
|
import { WebSocketHandshakeComplete } from '../../codec/websocket/handshake/index.ts'
|
|
16
16
|
import { ConsoleLogger } from '../../logger/index.ts'
|
|
17
17
|
import { WebSocketChannel } from '../channel/index.ts'
|
|
18
|
+
import { UpgradeGate, type UpgradeHandler } from '../gate/index.ts'
|
|
18
19
|
import type { WebSocketState } from '../transport/index.ts'
|
|
19
20
|
import { WebSocketFrameWriter } from '../writer/index.ts'
|
|
20
21
|
|
|
@@ -23,7 +24,7 @@ import { WebSocketFrameWriter } from '../writer/index.ts'
|
|
|
23
24
|
*/
|
|
24
25
|
export type WebSocketBindOptions = {
|
|
25
26
|
/**
|
|
26
|
-
* Interface to bind,
|
|
27
|
+
* Interface to bind, or all of them
|
|
27
28
|
*/
|
|
28
29
|
readonly hostname?: string
|
|
29
30
|
|
|
@@ -33,56 +34,17 @@ export type WebSocketBindOptions = {
|
|
|
33
34
|
readonly port: number
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
/**
|
|
37
|
-
* What the upgrade hook decided
|
|
38
|
-
*/
|
|
39
|
-
export type UpgradeVerdict =
|
|
40
|
-
| {
|
|
41
|
-
/**
|
|
42
|
-
* Let the client in
|
|
43
|
-
*/
|
|
44
|
-
readonly accept: true
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Anything to keep with the channel, like the logged in user
|
|
48
|
-
*/
|
|
49
|
-
readonly data?: unknown
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Extra headers on the 101 response, like a cookie or subprotocol
|
|
53
|
-
*/
|
|
54
|
-
readonly headers?: HeadersInit
|
|
55
|
-
}
|
|
56
|
-
| {
|
|
57
|
-
/**
|
|
58
|
-
* Turn the client away
|
|
59
|
-
*/
|
|
60
|
-
readonly accept: false
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* HTTP status to answer with, 403 by default
|
|
64
|
-
*/
|
|
65
|
-
readonly status?: number
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Runs before the upgrade, so a client can be refused before it gets a socket
|
|
70
|
-
*/
|
|
71
|
-
export type UpgradeHandler = (
|
|
72
|
-
request: Request,
|
|
73
|
-
) => UpgradeVerdict | Promise<UpgradeVerdict>
|
|
74
|
-
|
|
75
37
|
/**
|
|
76
38
|
* How the native server behaves, the limits keep a bad client from hurting it
|
|
77
39
|
*/
|
|
78
40
|
export type WebSocketBootstrapOptions = {
|
|
79
41
|
/**
|
|
80
|
-
*
|
|
42
|
+
* Path that upgrades, or any
|
|
81
43
|
*/
|
|
82
44
|
readonly path?: string
|
|
83
45
|
|
|
84
46
|
/**
|
|
85
|
-
* Certificates for wss
|
|
47
|
+
* Certificates for wss
|
|
86
48
|
*/
|
|
87
49
|
readonly tls?: TLSOptions
|
|
88
50
|
|
|
@@ -116,6 +78,11 @@ export type WebSocketBootstrapOptions = {
|
|
|
116
78
|
*/
|
|
117
79
|
readonly closeOnBackpressureLimit?: boolean
|
|
118
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Drain time for a closing socket in ms
|
|
83
|
+
*/
|
|
84
|
+
readonly closeTimeout?: number
|
|
85
|
+
|
|
119
86
|
/**
|
|
120
87
|
* Compress messages with permessage-deflate, off by default
|
|
121
88
|
*/
|
|
@@ -127,7 +94,7 @@ export type WebSocketBootstrapOptions = {
|
|
|
127
94
|
readonly sendPings?: boolean
|
|
128
95
|
|
|
129
96
|
/**
|
|
130
|
-
* Checks each request before
|
|
97
|
+
* Checks each request before the upgrade
|
|
131
98
|
*/
|
|
132
99
|
readonly upgrade?: UpgradeHandler
|
|
133
100
|
|
|
@@ -221,33 +188,66 @@ export class WebSocketServer {
|
|
|
221
188
|
public async shutdownGracefully(timeout = 10000): Promise<void> {
|
|
222
189
|
void this.server.stop(false)
|
|
223
190
|
const channels = [...this.children]
|
|
224
|
-
const
|
|
191
|
+
const deadline = Date.now() + timeout
|
|
192
|
+
const event = new ShutdownEvent(deadline)
|
|
225
193
|
for (const channel of channels) {
|
|
226
194
|
void channel.pipeline.fireUserEventTriggered(event)
|
|
227
195
|
}
|
|
228
196
|
|
|
229
|
-
await
|
|
197
|
+
await WebSocketServer.within(
|
|
230
198
|
Promise.allSettled(
|
|
231
199
|
channels.map(
|
|
232
200
|
(channel: WebSocketChannel): Promise<void> => channel.closed,
|
|
233
201
|
),
|
|
234
202
|
),
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
await this.close()
|
|
203
|
+
timeout,
|
|
204
|
+
)
|
|
205
|
+
await this.close(Math.max(0, deadline - Date.now()))
|
|
238
206
|
}
|
|
239
207
|
|
|
240
208
|
/**
|
|
241
209
|
* Stops listening and closes every channel
|
|
210
|
+
* @param timeout drain time in ms
|
|
242
211
|
*/
|
|
243
|
-
public async close(): Promise<void> {
|
|
212
|
+
public async close(timeout = 10000): Promise<void> {
|
|
213
|
+
const channels = [...this.children]
|
|
214
|
+
|
|
244
215
|
await Promise.all(
|
|
245
|
-
|
|
216
|
+
channels.map((channel: WebSocketChannel): Promise<void> =>
|
|
246
217
|
channel.close(),
|
|
247
218
|
),
|
|
248
219
|
)
|
|
220
|
+
await WebSocketServer.within(
|
|
221
|
+
Promise.all(
|
|
222
|
+
channels.map(
|
|
223
|
+
(channel: WebSocketChannel): Promise<undefined> => channel.drained,
|
|
224
|
+
),
|
|
225
|
+
),
|
|
226
|
+
timeout,
|
|
227
|
+
)
|
|
249
228
|
await this.server.stop(true)
|
|
250
229
|
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Waits for the work or the timeout
|
|
233
|
+
* @param work what to wait for
|
|
234
|
+
* @param timeout longest wait in milliseconds
|
|
235
|
+
*/
|
|
236
|
+
private static async within(
|
|
237
|
+
work: Promise<unknown>,
|
|
238
|
+
timeout: number,
|
|
239
|
+
): Promise<void> {
|
|
240
|
+
const expiry = Promise.withResolvers<undefined>()
|
|
241
|
+
const timer = setTimeout((): void => {
|
|
242
|
+
expiry.resolve(undefined)
|
|
243
|
+
}, timeout)
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
await Promise.race<unknown>([work, expiry.promise])
|
|
247
|
+
} finally {
|
|
248
|
+
clearTimeout(timer)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
251
|
}
|
|
252
252
|
|
|
253
253
|
/**
|
|
@@ -360,9 +360,28 @@ export class WebSocketBootstrap {
|
|
|
360
360
|
const settings = this.serverSettings
|
|
361
361
|
const childSettings = this.childSettings
|
|
362
362
|
const logger = childSettings.logger ?? new ConsoleLogger()
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
363
|
+
const gate = new UpgradeGate({
|
|
364
|
+
/**
|
|
365
|
+
* Upgrade path, or null
|
|
366
|
+
*/
|
|
367
|
+
path: settings.path ?? null,
|
|
368
|
+
/**
|
|
369
|
+
* Connection cap
|
|
370
|
+
*/
|
|
371
|
+
maxConnections: settings.maxConnections ?? Number.POSITIVE_INFINITY,
|
|
372
|
+
/**
|
|
373
|
+
* Upgrade hook, or null
|
|
374
|
+
*/
|
|
375
|
+
upgrade: settings.upgrade ?? null,
|
|
376
|
+
/**
|
|
377
|
+
* Same logger the channels get
|
|
378
|
+
*/
|
|
379
|
+
logger,
|
|
380
|
+
/**
|
|
381
|
+
* Live channels
|
|
382
|
+
*/
|
|
383
|
+
children,
|
|
384
|
+
})
|
|
366
385
|
const controlFrames = settings.controlFrames ?? false
|
|
367
386
|
const pooled = settings.pooled ?? true
|
|
368
387
|
|
|
@@ -388,22 +407,8 @@ export class WebSocketBootstrap {
|
|
|
388
407
|
fetch: (
|
|
389
408
|
request: Request,
|
|
390
409
|
server: Server<WebSocketState>,
|
|
391
|
-
): Response | undefined | Promise<Response | undefined> =>
|
|
392
|
-
|
|
393
|
-
if (path !== null && url.pathname !== path) {
|
|
394
|
-
return new Response(null, { status: 404 })
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
if (children.size >= maxConnections) {
|
|
398
|
-
return new Response(null, { status: 503 })
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
if (upgrade === null) {
|
|
402
|
-
return WebSocketBootstrap.accept(request, server, url, null, null)
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
return WebSocketBootstrap.decide(request, server, url, upgrade)
|
|
406
|
-
},
|
|
410
|
+
): Response | undefined | Promise<Response | undefined> =>
|
|
411
|
+
gate.handle(request, server),
|
|
407
412
|
websocket: {
|
|
408
413
|
/**
|
|
409
414
|
* Biggest message a client may send
|
|
@@ -436,7 +441,12 @@ export class WebSocketBootstrap {
|
|
|
436
441
|
* @param socket the new socket
|
|
437
442
|
*/
|
|
438
443
|
open: (socket: ServerWebSocket<WebSocketState>): void => {
|
|
439
|
-
const channel = new WebSocketChannel(
|
|
444
|
+
const channel = new WebSocketChannel(
|
|
445
|
+
socket,
|
|
446
|
+
childSettings,
|
|
447
|
+
pooled,
|
|
448
|
+
settings.closeTimeout,
|
|
449
|
+
)
|
|
440
450
|
socket.data.channel = channel
|
|
441
451
|
children.add(channel)
|
|
442
452
|
channel.pipeline.addFirst<WebSocketFrameWriter>(
|
|
@@ -527,69 +537,6 @@ export class WebSocketBootstrap {
|
|
|
527
537
|
})
|
|
528
538
|
}
|
|
529
539
|
|
|
530
|
-
/**
|
|
531
|
-
* Asks the upgrade hook, then upgrades or turns the request away
|
|
532
|
-
* @param request the HTTP request
|
|
533
|
-
* @param server the Bun server
|
|
534
|
-
* @param url the parsed request URL
|
|
535
|
-
* @param upgrade the hook
|
|
536
|
-
*/
|
|
537
|
-
private static async decide(
|
|
538
|
-
request: Request,
|
|
539
|
-
server: Server<WebSocketState>,
|
|
540
|
-
url: URL,
|
|
541
|
-
upgrade: UpgradeHandler,
|
|
542
|
-
): Promise<Response | undefined> {
|
|
543
|
-
let verdict: UpgradeVerdict
|
|
544
|
-
try {
|
|
545
|
-
verdict = await upgrade(request)
|
|
546
|
-
} catch {
|
|
547
|
-
return new Response(null, { status: 500 })
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
if (!verdict.accept) {
|
|
551
|
-
return new Response(null, { status: verdict.status ?? 403 })
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
return WebSocketBootstrap.accept(
|
|
555
|
-
request,
|
|
556
|
-
server,
|
|
557
|
-
url,
|
|
558
|
-
verdict.data ?? null,
|
|
559
|
-
verdict.headers ?? null,
|
|
560
|
-
)
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
/**
|
|
564
|
-
* Upgrades the request, carrying the hook's data onto the socket
|
|
565
|
-
* @param request the HTTP request
|
|
566
|
-
* @param server the Bun server
|
|
567
|
-
* @param url the parsed request URL
|
|
568
|
-
* @param data whatever the hook attached, or null
|
|
569
|
-
* @param headers extra response headers, or null
|
|
570
|
-
*/
|
|
571
|
-
private static accept(
|
|
572
|
-
request: Request,
|
|
573
|
-
server: Server<WebSocketState>,
|
|
574
|
-
url: URL,
|
|
575
|
-
data: unknown,
|
|
576
|
-
headers: HeadersInit | null,
|
|
577
|
-
): Response | undefined {
|
|
578
|
-
const upgraded = server.upgrade(request, {
|
|
579
|
-
/**
|
|
580
|
-
* Filled in as the socket opens
|
|
581
|
-
*/
|
|
582
|
-
data: {
|
|
583
|
-
channel: null,
|
|
584
|
-
uri: url.pathname + url.search,
|
|
585
|
-
headers: request.headers,
|
|
586
|
-
data,
|
|
587
|
-
},
|
|
588
|
-
...(headers === null ? {} : { headers }),
|
|
589
|
-
})
|
|
590
|
-
return upgraded ? undefined : new Response(null, { status: 400 })
|
|
591
|
-
}
|
|
592
|
-
|
|
593
540
|
/**
|
|
594
541
|
* The same event the JavaScript codec fires once a handshake is done
|
|
595
542
|
* @param state what the upgrade carried
|
|
@@ -600,7 +547,7 @@ export class WebSocketBootstrap {
|
|
|
600
547
|
return new WebSocketHandshakeComplete(
|
|
601
548
|
state.uri,
|
|
602
549
|
new HttpHeaders(state.headers.entries()),
|
|
603
|
-
state.
|
|
550
|
+
state.subprotocol,
|
|
604
551
|
)
|
|
605
552
|
}
|
|
606
553
|
}
|