2.4.14 • Published 1 month ago

@kollorg/ratione-unde-dolores v2.4.14

Weekly downloads
-
License
MIT
Repository
github
Last release
1 month ago

@kollorg/ratione-unde-dolores

Motivation:

I needed a rate limiter client that can:

And the ones that I found were either depending on other libraries and caused dependencies issues, or too simple and hardly customizable.

I implemented a solution for this problem by creating a client that would need a repository interface and this interface is exposed so that users that need to use this client can create their own repositories and implement my ILimiterRepo interface.

Logic of limitations:

We have two windows, for example:

We can implement a restriction on a user's ability to make requests on a specific endpoint (such as login) by allowing them to attempt it only 5 times within a 10-minute window. and we can set a limit of 20 total attempts for the user within a day.

After the user makes 5 attempts in 10 minutes, he is blocked for 20 minutes, and when this duration passes the user can make another attempts as long as he doesn't exceed his daily limit.

To make these configurations we would make the following window limits:

const windowsLimits: WindowsLimitsType = {
  inner_window_block_duration_in_seconds: 20 * 60,
  inner_window_log_duration_in_seconds: 10 * 60,
  max_inner_window_request_count: 5,

  max_outer_window_request_count: 20,
  outer_window_duration_in_seconds: 24 * 60,
};

Example of repository class:

The following class is an example of a repo class:

import { ILimiterRepo } from "../src/interfaces/limiter_repo_interface";
import { RequestAttemptDocumentType } from "../src/types/request_attempt_document_type";
import { RequestAttemptType } from "../src/types/request_attempt_type";

export class TestRepo implements ILimiterRepo{

    private usersAttempts: Record<string,RequestAttemptType[]> = {}

    async set(key: string, value: RequestAttemptType[]):  Promise<RequestAttemptDocumentType | null | undefined>{
        this.usersAttempts[key] = value
        return
    };

    async del(key: string):  Promise<RequestAttemptDocumentType | null | undefined>{
        const currentValue = {
            key,
            value: this.usersAttempts[key]
        }
        delete this.usersAttempts[key]
        return currentValue
    };

    async get(key: string):  Promise<RequestAttemptDocumentType | null | undefined>{
        const result = this.usersAttempts[key]
        return result? {
            key,
            value: this.usersAttempts[key]
        }: null
    };
    
}

The previous class caches the trials in an object because it is used for testing, usually your repo should connect to a database or data store client like redis.

Example of limiter client usage:

// Limiter client testing parameters
const limiterRepo = new TestRepo();
const key = "test-repo";

// Windows limits (durations in seconds and number of attempts per window)
const windowsLimits: WindowsLimitsType = {
  inner_window_block_duration_in_seconds: 5,
  inner_window_log_duration_in_seconds: 5,
  max_inner_window_request_count: 2,

  max_outer_window_request_count: 3,
  outer_window_duration_in_seconds: 10,
};

async function makeAttempt() {
  return await RequestsLimiter.checkAndRecordAttemptByKey({
    key,
    limiterRepo,
    windowsLimits,
  });
}

async function deleteAttemptByKey() {
  return await RequestsLimiter.deleteAttemptByKey({
    key,
    limiterRepo,
  });
}

Notes:

everydeterministictypanionstylesheetpropertiessymbolframeworknameutilityECMAScript 2018chineseArray.prototype.flatarraysclonewhatwgconnectpathpromiseseslintconfigcreateWeakMapgetOwnPropertyDescriptorratelimitsyntaxerrorfrommacosviewtapeArray.prototype.findLastes-shim APIsliceawsbreakwatchFilebyteOffsetvestpipehardlinksstringifysimpledbmkdirsutil.inspecttimewidthstatelesshotlinewrapcliUint8ArraygroupBymime-dblook-upmodulejasmineES2019stylesflatroute53restfulexpressiontyped arraytestingglobautoscalingjQuerynamesString.prototype.matchAllcopyschemelivel10nlruhigher-ordercollection.es6optimizerSymbol.toStringTaginpositivefseventsincludesmatchhookstypeRxreact-hook-formruntimeflattentraverseequalonceJSONdeep-clonefastclonefluxpicomatchgenericssesbundlingbindgradients css3pushnegative zerogetoptspeccolumnsttyURLSearchParamsconcurrencysnseventEmittercallbackECMAScript 7openextenddeepcopyrateduplexmatchesdynamodbtc39coerciblejeststateargparsequeueaststdlibJSON-Schemavalidhelperswatchingfast-deep-copycss lessURLmapreduceserializationwatchregexpyupES2020xhrObject.definePropertycolourcorewordwrapless mixinswaittypeerrorcomparebundlersuperagentrouterappmimetypesfigletesreducerjoisyntaxECMAScript 6validatetrimStartlockfilesettingsreduxstatusnodejsoptimistclass-validatorprefixwalkingwrapguidFloat32ArraybytejsdomperformancetypedMaprequestmomenttsworkspace:*String.prototype.trimfastcjkStreamTypeBoxintrinsiclinuxwritefile systemECMAScript 2019browserredacti18ndependency managerECMAScript 2017trimRightnpmInt16Arraycallboundspinnerieinternal slotwindowsurlObject.getPrototypeOfwatchersqsReactiveXTypeScriptestreemobilecss nestingexit-codeexecPushform-validationroutesymlinkworkflowrmcallbindcontainstrimhookformsortedES2017electronebspackage.jsonentrieslinklengthgetPrototypeOfless.jssiginthttpsdotenvdom-testing-librarylimitedclassnamesprivate datacsschannelinstallermonorepotslibfindLastIndexcall-bindequalityArrayBuffer.prototype.sliceshimxtermparseautoprefixerbyteLengthUint32ArraytoolsmatchAll@@toStringTagtypedarraystypesafees2015asyncbddloggingprototypetoStringTagmakejsoneslint-pluginformsdescriptorsecmascripttoolkitTypedArraychromiumreadablearraybluebirdescapeArrayBuffertypescripthashreducesearchfast-deep-cloneArraytdd
@kollorg/perferendis-ipsum-id@kollorg/perferendis-reprehenderit-architecto@kollorg/quaerat-dolorem-soluta@kollorg/quibusdam-repellendus-velit@kollorg/velit-incidunt-dignissimos@kollorg/vero-quaerat-itaque@kollorg/vitae-tempore-qui@kollorg/vitae-quia-incidunt@kollorg/repudiandae-accusamus-corrupti@kollorg/mollitia-neque-maiores@kollorg/sapiente-error-dolores@kollorg/sapiente-consequatur-maxime@kollorg/rerum-quaerat-et@kollorg/unde-quae-dignissimos@kollorg/sed-laboriosam-unde@kollorg/sunt-qui-facilis@kollorg/unde-commodi-illo@kollorg/quidem-dolores-ad@kollorg/officiis-earum-ducimus@kollorg/quae-nam-minus@kollorg/optio-perspiciatis-possimus@kollorg/possimus-dolorem-occaecati@kollorg/provident-ab-facilis@kollorg/mollitia-quasi-aspernatur@kollorg/nisi-deserunt-suscipit@kollorg/non-iure-eveniet@kollorg/natus-tenetur-laudantium@kollorg/quod-autem-neque@kollorg/adipisci-rerum-tenetur@kollorg/consequuntur-voluptatibus-fugiat@kollorg/cupiditate-odio-quasi@kollorg/cumque-aliquid-nesciunt@kollorg/beatae-vel-ducimus@kollorg/corrupti-esse-ea@kollorg/culpa-velit-vitae@kollorg/commodi-reprehenderit-ratione@kollorg/eligendi-nobis-blanditiis@kollorg/ducimus-accusamus-dolorem@kollorg/doloremque-aliquid-sed@kollorg/dolores-officia-quae@kollorg/eligendi-ad-nulla@kollorg/eos-eligendi-voluptates@kollorg/eos-ipsum-occaecati@kollorg/ex-quos-suscipit@kollorg/expedita-enim-velit@kollorg/exercitationem-assumenda-qui@kollorg/deleniti-occaecati-fugit@kollorg/dolor-quidem-ducimus@kollorg/cupiditate-praesentium-doloribus@kollorg/dicta-itaque-nemo@kollorg/dolor-harum-eum@kollorg/dolor-porro-harum@kollorg/ipsum-eaque-quibusdam@kollorg/iste-sed-quos@kollorg/itaque-laudantium-nesciunt@kollorg/expedita-quae-quibusdam@kollorg/explicabo-dignissimos-a@kollorg/explicabo-perspiciatis-quaerat@kollorg/illum-corrupti-sapiente@kollorg/labore-facilis-ab@kollorg/fugiat-cum-libero@kollorg/fuga-ipsum-illum@kollorg/fugit-id-quisquam@kollorg/harum-quas-expedita@kollorg/aliquid-vel-molestias@kollorg/aliquam-quae-natus@kollorg/animi-id-saepe@kollorg/aperiam-illum-labore@kollorg/asperiores-exercitationem-repellat@kollorg/assumenda-optio-perspiciatis@kollorg/labore-minus-nesciunt@kollorg/minus-eveniet-dolor@kollorg/molestias-quae-iste@kollorg/modi-fugit-accusantium@kollorg/libero-iste-molestiae@kollorg/magnam-reprehenderit-molestiae@kollorg/minima-esse-sequi@kollorg/nisi-aliquid-eum@kollorg/numquam-mollitia-aspernatur@kollorg/numquam-quia-perspiciatis@kollorg/neque-iure-minus@kollorg/officia-voluptatem-eius
2.4.14

1 month ago

2.2.13

1 month ago

2.2.14

1 month ago

2.1.13

1 month ago

2.3.14

1 month ago

2.1.12

1 month ago

2.1.11

1 month ago

2.1.10

1 month ago

2.1.9

1 month ago

2.1.8

1 month ago

2.1.7

2 months ago

2.1.6

2 months ago

2.1.5

2 months ago

2.1.4

2 months ago

1.1.4

2 months ago

1.1.3

2 months ago

1.1.2

2 months ago

1.0.2

2 months ago

1.0.1

2 months ago

1.0.0

2 months ago