mtcute/packages/client/src/utils/rps-meter.ts
Alina Tumanova f5976a2d74
ESM + end-to-end tests (#11)
* feat: moved tl-runtime to esm and native ArrayBuffers

* feat: migration to esm

* fix(core): web-related fixes

* test: finally, some good fucking e2e

* chore: fixed linters etc

* ci: added e2e to ci

* build(tl): fixed gen-code on node 20

* fix: codegen Uint8Array, not Buffer

never `git reset --hard` kids

* build: only do type-aware linting for `packages/*`

* build: ignore no-unresolved in ci for e2e

* fix: node 16 doesn't have subtle crypto apparently?

* fix(tests): use Uint8Array

for gods sake please can i just merge this already

* ci: don't parallel tasks in ci

because machines are utter garbage and it may just randomly break

* ci: pass secrets to e2e tests

* ci: separate cli command for ci

apparently im retarded

* fix: run codegen in e2e

im actually retarded

* ci: more fixes for e2e

* ci: debugging stuff

* ci: still debugging

* ci: hopefully fix ci???
2023-10-16 19:23:53 +03:00

46 lines
1.3 KiB
TypeScript

import { Deque } from '@mtcute/core/utils.js'
export class RpsMeter {
_hits: Deque<bigint>
time: bigint
constructor(
readonly size = 500,
time = 5000,
) {
if (typeof process === 'undefined' || !process.hrtime.bigint) {
throw new Error('RPS meter is not supported on this platform')
}
this._hits = new Deque<bigint>(size)
this.time = BigInt(time) * BigInt(1e6)
}
hit(): void {
this._hits.pushBack(process.hrtime.bigint())
}
getRps(): number {
// calculate average load based on last `size` hits in the last `time` ms
if (!this._hits.length) return 0 // no hits at all
const now = process.hrtime.bigint()
const window = now - this.time
// find the first hit within the last `time` ms
const iter = this._hits.iter()
let first = iter.next()
let idx = 0
while (!first.done && first.value < window) {
first = iter.next()
idx += 1
}
if (!first.value) return 0 // no recent hits
// number of hits within the window
const hits = this._hits.length - idx
// average load per second
return (hits * 1e9) / Number(now - first.value)
}
}