@samitouri / QOSami-HFS / commits / 6b9a6d4b

fix: speed limit was not applied to plugins' output

Massimo Melina committed Jan 5, 2024 at 19:19 UTC 6b9a6d4bf0ac49d9214f80a3d8dd0f3c18963a5f
3 files changed +8 -5
src/index.ts
+1 -1
@@ -40,11 +40,11 @@ app.use(sessionMiddleware)
40 .use(geoFilter)
41 .use(gzipper)
42 .use(paramsDecoder) // must be done before plugins, so they can manipulate params
43 - .use(pluginsMiddleware)
43 .use(headRequests)
44 .use(logMw)
45 .use(throttler)
46 .use(rootsMiddleware)
47 + .use(pluginsMiddleware)
48 .use(mount(API_URI, apiMiddleware({ ...frontEndApis, ...adminApis })))
49 .use(serveGuiAndSharedFiles)
50 .on('error', errorHandler)
src/log.ts
+2 -1
@@ -70,11 +70,12 @@ const debounce = _.debounce(cb => cb(), 1000)
70
71 export const logMw: Koa.Middleware = async (ctx, next) => {
72 const now = new Date()
73 + // do it now so it's available for returning plugins
74 + ctx.state.completed = Promise.race([ once(ctx.res, 'finish'), once(ctx.res, 'close') ])
75 await next()
76 console.debug(ctx.status, ctx.method, ctx.originalUrl)
77 const conn = getConnection(ctx) // collect reference before close
78 // don't await, as we don't want to hold the middlewares chain
77 - ctx.state.completed = Promise.race([ once(ctx.res, 'finish'), once(ctx.res, 'close') ])
79 ctx.state.completed.then(() => {
80 if (ctx.state.dontLog || ctx.state.considerAsGui && !logGui.get()) return
81 if (dontLogNet.compiled()(ctx.ip)) return
src/throttler.ts
+5 -3
@@ -27,7 +27,9 @@ const maxKbpsPerIp = defineConfig('max_kbps_per_ip', Infinity)
27
28 export const throttler: Koa.Middleware = async (ctx, next) => {
29 await next()
30 - const { body } = ctx
30 + let { body } = ctx
31 + if (typeof body === 'string' || body && body instanceof Buffer)
32 + ctx.body = body = Readable.from(body)
33 if (!body || !(body instanceof Readable))
34 return
35 // we wrap the stream also for unlimited connections to get speed and other features
@@ -74,8 +76,8 @@ export const throttler: Koa.Middleware = async (ctx, next) => {
76 })
77
78 const downloadTotal: number = ctx.response.length
77 - ctx.state.originalStream = ctx.body
78 - ctx.body = ctx.body.pipe(ts)
79 + ctx.state.originalStream = body
80 + ctx.body = body.pipe(ts)
81
82 if (downloadTotal) // preserve this info
83 ctx.response.length = downloadTotal