fix: changing max-kbps at runtime was not applied

Massimo Melina committed Jan 10, 2022 at 10:43 UTC 8c4a5c9b0653d7b4d03eac9a2dddd0b8025ce048
2 files changed +17 -16
src/ThrottledStream.ts
+15 -16
@@ -15,8 +15,9 @@ export class ThrottledStream extends Transform {
15 async _transform(chunk: any, encoding: BufferEncoding, done: TransformCallback) {
16 let pos = 0
17 while (1) {
18 - const slice = chunk.slice(pos, pos + this.group.getMin() / 10)
19 - const n = slice.length
18 + let n = this.group.suggestChunkSize()
19 + const slice = chunk.slice(pos, pos + n)
20 + n = slice.length
21 if (!n) // we're done here
22 return done()
23 try {
@@ -46,40 +47,38 @@ export class ThrottledStream extends Transform {
47
48 export class ThrottleGroup {
49
49 - private bucket?: TokenBucket
50 + private bucket: TokenBucket
51
51 - constructor(public kBs: number, parent?: ThrottleGroup) {
52 - this.updateLimit(kBs)
53 - if (parent)
54 - this.bucket!.parentBucket = parent.bucket
52 + constructor(kBs: number, private parent?: ThrottleGroup) {
53 + this.bucket = this.updateLimit(kBs) // assignment is redundant and yet the best way I've found to shut up typescript
54 }
55
56 // @return kBs
57 getLimit() {
59 - return this.bucket!.bucketSize / 1000
58 + return this.bucket.bucketSize / 1000
59 }
60
61 updateLimit(kBs: number) {
62 if (kBs < 0)
63 throw new Error('invalid bytesPerSecond')
64 kBs *= 1000
66 - this.bucket = new TokenBucket({
65 + return this.bucket = new TokenBucket({
66 bucketSize: kBs,
67 tokensPerInterval: kBs,
68 interval: 'second',
70 - parentBucket: this.bucket?.parentBucket,
69 })
70 }
71
74 - getMin() {
72 + suggestChunkSize() {
73 let b: TokenBucket | undefined = this.bucket
76 - let ret = b!.bucketSize
77 - while (b = b!.parentBucket)
78 - ret = Math.min(ret, b.bucketSize)
79 - return ret
74 + b.parentBucket = this.parent?.bucket
75 + let min = b.bucketSize
76 + while (b = b.parentBucket)
77 + min = Math.min(min, b.bucketSize)
78 + return min / 10
79 }
80
81 consume(n: number) {
83 - return this.bucket!.removeTokens(n)
82 + return this.bucket.removeTokens(n)
83 }
84 }
todo.md
+2
@@ -1,8 +1,10 @@
1 # To do
2 +- inverted order
3 - download counter
4 - update tests to SRP login
5 - anti-csrf
6 - upload
7 +- updater (stop,unzip,start)
8 - search and login dialogs should push to history so that mobile can use back button to close them
9 - node.comment
10 - config: max connections (total/per-ip)