fix: connections stats were not updated if no data is sent

Massimo Melina committed Mar 2, 2022 at 13:50 UTC 6c94cb14ed5433e51303491d9919f1c53153c208
2 files changed +9 -6
src/connections.ts
+1
@@ -36,6 +36,7 @@ export function socket2connection(socket: Socket) {
36 }
37
38 export function updateConnection(conn: Connection, change: Partial<Connection>) {
39 + if (Object.entries(change).every(([k,v]) => JSON.stringify(v) === JSON.stringify(conn[k as keyof Connection]) )) return // any change?
40 Object.assign(conn, change)
41 events.emit('connectionUpdated', conn, change)
42 }
src/throttler.ts
+8 -6
@@ -18,6 +18,7 @@ const ip2group: Record<string, {
18 }> = {}
19
20 const SymThrStr = Symbol('stream')
21 +const SymTimeout = Symbol('timeout')
22
23 export function throttler(): Koa.Middleware {
24 return async (ctx, next) => {
@@ -38,12 +39,13 @@ export function throttler(): Koa.Middleware {
39
40 const DELAY = 1000
41 const update = _.debounce(() => {
41 - updateConnection(conn, {
42 - sent: ts.getBytesSent(),
43 - outSpeed: _.round(ts.getSpeed(), 1)
44 - })
45 - },
46 - DELAY, { maxWait:DELAY })
42 + const ts = conn[SymThrStr]
43 + const outSpeed = _.round(ts.getSpeed(), 1)
44 + updateConnection(conn, { outSpeed, sent: ts.getBytesSent() })
45 + clearTimeout(conn[SymTimeout])
46 + if (outSpeed || !(ts.finished || ts.ended))
47 + conn[SymTimeout] = setTimeout(update, DELAY)
48 + }, DELAY, { maxWait:DELAY })
49 ts.on('sent', update)
50
51 ++ipGroup.count