Class: CountingRateLimiter
Package:
@litert/concurrentImport path:@litert/concurrentSource: packages/partials/concurrent/src/Classes/CountingRateLimiter.tsImplements:ISyncRateLimiter
A synchronous rate limiter that delegates counting to any ICounter implementation (e.g. a SlideWindowCounter). The limiter blocks once the counter's total reaches limits. Calling reset() resets the underlying counter.
Constructor
new CountingRateLimiter(opts: ICountingRateLimiterOptions)See ICountingRateLimiterOptions.
Methods
challenge()
challenge(): voidThrows an error if the limit is reached; otherwise increments the counter by one.
Throws: E_RATE_LIMITED (or the custom error from errorCtorOnLimited).
isBlocking()
isBlocking(): booleanReturns true when the counter total is ≥ limits.
isIdle()
isIdle(): booleanReturns true when the counter total is 0.
call(fn)
call<TFn extends IFunction>(fn: TFn): ReturnType<TFn>Calls fn after a successful challenge().
Returns: The return value of fn. Throws: Rate-limit error if blocking, or any error thrown by fn.
reset()
reset(): voidResets the underlying counter to zero.
wrap(fn)
wrap<T extends IFunction>(fn: T): TReturns a wrapper function that calls challenge() before every invocation of fn.
Example
import { CountingRateLimiter, SlideWindowCounter } from '@litert/concurrent';
const counter = new SlideWindowCounter({ windowSizeMs: 1000, windowQty: 2 });
const limiter = new CountingRateLimiter({ limits: 10, counter });
try {
limiter.challenge(); // passes and increments
doWork();
} catch {
console.log('Rate limited');
}
// Or wrap a function
const limitedFn = limiter.wrap(doWork);