fix: removed limit of 10 ip addresses downloading

Massimo Melina committed Jan 27, 2022 at 23:25 UTC 74643dc5ebb8ed449e2a255dc22e52adb555bb82
2 files changed +16 -9
src/config.ts
+6 -1
@@ -9,6 +9,7 @@ const PATH = 'config.yaml'
9 let started = false
10 let state:Record<string,any> = {}
11 const emitter = new EventEmitter()
12 +emitter.setMaxListeners(10_000)
13 const path = argv.config || process.env.HFS_CONFIG || PATH
14 watchLoad(path, data => {
15 started = true
@@ -35,13 +36,17 @@ export function subscribeConfig({ k, ...definition }:{ k:string } & ConfigProps,
36 const a = argv[k]
37 if (a !== undefined)
38 return cb(caster ? caster(a) : a)
38 - emitter.on('new.'+k, cb)
39 + const eventName = 'new.'+k
40 + emitter.on(eventName, cb)
41 if (!started) return
42 let v = state[k]
43 if (v === undefined)
44 v = defaultValue
45 if (v !== undefined)
46 cb(v)
47 + return () => {
48 + emitter.off(eventName, cb)
49 + }
50 }
51
52 export function getConfig(k:string) {
src/throttler.ts
+10 -8
@@ -6,10 +6,10 @@ import { getOrSet } from './misc'
6
7 const mainThrottleGroup = new ThrottleGroup(Infinity)
8
9 -subscribeConfig({ k:'max_kbps', defaultValue:Infinity }, v =>
10 - mainThrottleGroup.updateLimit(v))
9 +subscribeConfig({ k:'max_kbps', defaultValue:null }, v =>
10 + mainThrottleGroup.updateLimit(v ?? Infinity))
11
12 -interface GroupThrottler { count:number, throttler:ThrottledStream }
12 +interface GroupThrottler { count:number, throttler:ThrottledStream, destroy:()=>void }
13 const ip2group: Record<string,GroupThrottler> = {}
14
15 export function throttler(): Koa.Middleware {
@@ -20,14 +20,16 @@ export function throttler(): Koa.Middleware {
20 return
21 const ipGroup = getOrSet(ip2group, ctx.ip, ()=> {
22 const tg = new ThrottleGroup(Infinity, mainThrottleGroup)
23 - subscribeConfig({ k:'max_kbps_per_ip', defaultValue:Infinity }, v =>
24 - tg.updateLimit(v))
25 - return { tg, count:0 }
23 + const unsub = subscribeConfig({ k:'max_kbps_per_ip', defaultValue:null }, v =>
24 + tg.updateLimit(v ?? Infinity))
25 + return { tg, count:0, destroy: unsub }
26 })
27 const ts = new ThrottledStream(ipGroup.tg)
28 + ++ipGroup.count
29 ts.on('close', ()=> {
29 - if (!--ipGroup.count) // any left?
30 - delete ip2group[ctx.ip]
30 + if (--ipGroup.count) return // any left?
31 + ipGroup.destroy?.()
32 + delete ip2group[ctx.ip]
33 })
34 const bak = ctx.response.length // preserve
35 ctx.body = ctx.body.pipe(ts)