From 6eacfdcffa4ebcb8760f9b67d2477ea25fcb3ae6 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Sun, 15 Nov 2020 15:16:18 +0100 Subject: [PATCH] Throttler: log jail triggers --- src/HttpError.ts | 4 ++-- src/Throttler.ts | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/HttpError.ts b/src/HttpError.ts index 4de4d95..7071665 100644 --- a/src/HttpError.ts +++ b/src/HttpError.ts @@ -69,11 +69,11 @@ export class NotFoundHttpError extends BadRequestError { } export class TooManyRequestsHttpError extends BadRequestError { - public constructor(retryIn: number, cause?: Error) { + public constructor(retryIn: number, jailName: string, cause?: Error) { super( `You're making too many requests!`, `We need some rest. Please retry in ${Math.floor(retryIn / 1000)} seconds.`, - '', + jailName, cause, ); } diff --git a/src/Throttler.ts b/src/Throttler.ts index a1c592a..9c16638 100644 --- a/src/Throttler.ts +++ b/src/Throttler.ts @@ -1,4 +1,5 @@ import {TooManyRequestsHttpError} from "./HttpError"; +import {log} from "./Logger"; export default class Throttler { private static readonly throttles: Record = {}; @@ -25,7 +26,8 @@ export default class Throttler { jailPeriod: number = 30 * 1000, ): void { let throttle = this.throttles[action]; - if (!throttle) throttle = this.throttles[action] = new Throttle(max, resetPeriod, holdPeriod, jailPeriod); + if (!throttle) + throttle = this.throttles[action] = new Throttle(action, max, resetPeriod, holdPeriod, jailPeriod); throttle.trigger(id); } @@ -35,6 +37,7 @@ export default class Throttler { } class Throttle { + private readonly jailName: string; private readonly max: number; private readonly resetPeriod: number; private readonly holdPeriod: number; @@ -45,7 +48,8 @@ class Throttle { jailed?: number; } | undefined> = {}; - public constructor(max: number, resetPeriod: number, holdPeriod: number, jailPeriod: number) { + public constructor(jailName: string, max: number, resetPeriod: number, holdPeriod: number, jailPeriod: number) { + this.jailName = jailName; this.max = max; this.resetPeriod = resetPeriod; this.holdPeriod = holdPeriod; @@ -75,11 +79,15 @@ class Throttle { if (trigger.count > this.max) { trigger.jailed = currentDate; - return this.throw(trigger.jailed + this.jailPeriod - currentDate); + + const unjailedIn = trigger.jailed + this.jailPeriod - currentDate; + log.info(`Jail ${this.jailName} triggered by ${id} and will be unjailed in ${unjailedIn}ms.`); + + return this.throw(unjailedIn); } } protected throw(unjailedIn: number) { - throw new TooManyRequestsHttpError(unjailedIn); + throw new TooManyRequestsHttpError(unjailedIn, this.jailName); } }