@application-kit/rate-limit 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +57 -18
- package/dist/cjs/configs/envs/index.d.ts +1 -0
- package/dist/cjs/configs/envs/index.js +17 -0
- package/dist/cjs/configs/envs/valkey.environment.d.ts +7 -0
- package/dist/cjs/configs/envs/valkey.environment.js +50 -0
- package/dist/cjs/configs/index.d.ts +2 -0
- package/dist/cjs/configs/index.js +18 -0
- package/dist/cjs/configs/valkey.config.d.ts +11 -0
- package/dist/cjs/configs/valkey.config.js +43 -0
- package/dist/cjs/constants.d.ts +1 -1
- package/dist/cjs/constants.js +2 -2
- package/dist/cjs/create-attempt-counter.d.ts +6 -0
- package/dist/cjs/create-attempt-counter.js +23 -0
- package/dist/cjs/index.d.ts +7 -0
- package/dist/cjs/index.js +7 -0
- package/dist/cjs/rate-limit.module.d.ts +3 -3
- package/dist/cjs/rate-limit.module.js +18 -4
- package/dist/cjs/throttle-axis.d.ts +7 -0
- package/dist/cjs/throttle-axis.interface.d.ts +32 -0
- package/dist/cjs/throttle-axis.interface.js +2 -0
- package/dist/cjs/throttle-axis.js +8 -0
- package/dist/cjs/throttle-gate.d.ts +8 -18
- package/dist/cjs/throttle-gate.js +23 -7
- package/dist/cjs/throttle-outcome.interceptor.d.ts +12 -0
- package/dist/cjs/throttle-outcome.interceptor.js +51 -0
- package/dist/cjs/throttle.decorator.d.ts +2 -0
- package/dist/cjs/throttle.decorator.js +15 -0
- package/dist/cjs/throttle.guard.d.ts +9 -0
- package/dist/cjs/throttle.guard.js +33 -0
- package/dist/esm/configs/envs/index.d.ts +1 -0
- package/dist/esm/configs/envs/index.js +1 -0
- package/dist/esm/configs/envs/valkey.environment.d.ts +7 -0
- package/dist/esm/configs/envs/valkey.environment.js +46 -0
- package/dist/esm/configs/index.d.ts +2 -0
- package/dist/esm/configs/index.js +2 -0
- package/dist/esm/configs/valkey.config.d.ts +11 -0
- package/dist/esm/configs/valkey.config.js +40 -0
- package/dist/esm/constants.d.ts +1 -1
- package/dist/esm/constants.js +1 -1
- package/dist/esm/create-attempt-counter.d.ts +6 -0
- package/dist/esm/create-attempt-counter.js +18 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/rate-limit.module.d.ts +3 -3
- package/dist/esm/rate-limit.module.js +19 -5
- package/dist/esm/throttle-axis.d.ts +7 -0
- package/dist/esm/throttle-axis.interface.d.ts +32 -0
- package/dist/esm/throttle-axis.interface.js +1 -0
- package/dist/esm/throttle-axis.js +4 -0
- package/dist/esm/throttle-gate.d.ts +8 -18
- package/dist/esm/throttle-gate.js +24 -8
- package/dist/esm/throttle-outcome.interceptor.d.ts +12 -0
- package/dist/esm/throttle-outcome.interceptor.js +48 -0
- package/dist/esm/throttle.decorator.d.ts +2 -0
- package/dist/esm/throttle.decorator.js +11 -0
- package/dist/esm/throttle.guard.d.ts +9 -0
- package/dist/esm/throttle.guard.js +30 -0
- package/package.json +13 -3
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ThrottleOutcomeInterceptor = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
18
|
+
const rxjs_1 = require("rxjs");
|
|
19
|
+
const constants_js_1 = require("./constants.js");
|
|
20
|
+
const throttle_axis_js_1 = require("./throttle-axis.js");
|
|
21
|
+
let ThrottleOutcomeInterceptor = class ThrottleOutcomeInterceptor {
|
|
22
|
+
reflector;
|
|
23
|
+
execute;
|
|
24
|
+
constructor(reflector, execute) {
|
|
25
|
+
this.reflector = reflector;
|
|
26
|
+
this.execute = execute;
|
|
27
|
+
}
|
|
28
|
+
intercept(executionContext, next) {
|
|
29
|
+
const axis = this.reflector.get(throttle_axis_js_1.ThrottleOutcomeMetadata, executionContext.getHandler());
|
|
30
|
+
const context = axis.readContext(executionContext);
|
|
31
|
+
return next.handle().pipe((0, rxjs_1.concatMap)(async (answer) => {
|
|
32
|
+
await this.register(axis, context, true);
|
|
33
|
+
return answer;
|
|
34
|
+
}), (0, rxjs_1.catchError)((error) => (0, rxjs_1.from)(this.registerRejection(axis, context, error))));
|
|
35
|
+
}
|
|
36
|
+
async register(axis, context, didSucceed) {
|
|
37
|
+
await this.execute(axis.outcome.createCommand(context, didSucceed));
|
|
38
|
+
}
|
|
39
|
+
async registerRejection(axis, context, error) {
|
|
40
|
+
if (axis.outcome.isAttemptSpent(error)) {
|
|
41
|
+
await this.register(axis, context, false);
|
|
42
|
+
}
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
exports.ThrottleOutcomeInterceptor = ThrottleOutcomeInterceptor;
|
|
47
|
+
exports.ThrottleOutcomeInterceptor = ThrottleOutcomeInterceptor = __decorate([
|
|
48
|
+
(0, common_1.Injectable)(),
|
|
49
|
+
__param(1, (0, common_1.Inject)(constants_js_1.RATE_LIMIT_EXECUTE)),
|
|
50
|
+
__metadata("design:paramtypes", [core_1.Reflector, Function])
|
|
51
|
+
], ThrottleOutcomeInterceptor);
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { ThrottleAxisInterface, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
2
|
+
export declare const Throttle: <TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(axis: ThrottleAxisInterface<TContext, TDecision>) => MethodDecorator;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Throttle = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const throttle_axis_js_1 = require("./throttle-axis.js");
|
|
6
|
+
const throttle_outcome_interceptor_js_1 = require("./throttle-outcome.interceptor.js");
|
|
7
|
+
const throttle_guard_js_1 = require("./throttle.guard.js");
|
|
8
|
+
const Throttle = (axis) => {
|
|
9
|
+
const decorators = [(0, throttle_axis_js_1.ThrottleAxisMetadata)(axis), (0, common_1.UseGuards)(throttle_guard_js_1.ThrottleGuard)];
|
|
10
|
+
if ('outcome' in axis) {
|
|
11
|
+
decorators.push((0, throttle_axis_js_1.ThrottleOutcomeMetadata)({ outcome: axis.outcome, readContext: (context) => axis.readContext(context) }), (0, common_1.UseInterceptors)(throttle_outcome_interceptor_js_1.ThrottleOutcomeInterceptor));
|
|
12
|
+
}
|
|
13
|
+
return (0, common_1.applyDecorators)(...decorators);
|
|
14
|
+
};
|
|
15
|
+
exports.Throttle = Throttle;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import { ThrottleGate } from './throttle-gate.js';
|
|
4
|
+
export declare class ThrottleGuard implements CanActivate {
|
|
5
|
+
private readonly reflector;
|
|
6
|
+
private readonly gate;
|
|
7
|
+
constructor(reflector: Reflector, gate: ThrottleGate);
|
|
8
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.ThrottleGuard = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const core_1 = require("@nestjs/core");
|
|
15
|
+
const throttle_axis_js_1 = require("./throttle-axis.js");
|
|
16
|
+
const throttle_gate_js_1 = require("./throttle-gate.js");
|
|
17
|
+
let ThrottleGuard = class ThrottleGuard {
|
|
18
|
+
reflector;
|
|
19
|
+
gate;
|
|
20
|
+
constructor(reflector, gate) {
|
|
21
|
+
this.reflector = reflector;
|
|
22
|
+
this.gate = gate;
|
|
23
|
+
}
|
|
24
|
+
async canActivate(context) {
|
|
25
|
+
return this.gate.pass(context, this.reflector.get(throttle_axis_js_1.ThrottleAxisMetadata, context.getHandler()));
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
exports.ThrottleGuard = ThrottleGuard;
|
|
29
|
+
exports.ThrottleGuard = ThrottleGuard = __decorate([
|
|
30
|
+
(0, common_1.Injectable)(),
|
|
31
|
+
__metadata("design:paramtypes", [core_1.Reflector,
|
|
32
|
+
throttle_gate_js_1.ThrottleGate])
|
|
33
|
+
], ThrottleGuard);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './valkey.environment.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './valkey.environment.js';
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { ParseBoolean } from '@libs-for-dev/nestjs-config-module';
|
|
11
|
+
import { Expose, Type } from 'class-transformer';
|
|
12
|
+
import { IsBoolean, IsNumber, IsString } from 'class-validator';
|
|
13
|
+
export class ValkeyEnvironment {
|
|
14
|
+
VALKEY_CLUSTER = true;
|
|
15
|
+
VALKEY_HOST = '';
|
|
16
|
+
VALKEY_PASSWORD = '';
|
|
17
|
+
VALKEY_PORT = 6379;
|
|
18
|
+
VALKEY_USERNAME = 'default';
|
|
19
|
+
}
|
|
20
|
+
__decorate([
|
|
21
|
+
Expose(),
|
|
22
|
+
IsBoolean(),
|
|
23
|
+
ParseBoolean(),
|
|
24
|
+
__metadata("design:type", Object)
|
|
25
|
+
], ValkeyEnvironment.prototype, "VALKEY_CLUSTER", void 0);
|
|
26
|
+
__decorate([
|
|
27
|
+
Expose(),
|
|
28
|
+
IsString(),
|
|
29
|
+
__metadata("design:type", Object)
|
|
30
|
+
], ValkeyEnvironment.prototype, "VALKEY_HOST", void 0);
|
|
31
|
+
__decorate([
|
|
32
|
+
Expose(),
|
|
33
|
+
IsString(),
|
|
34
|
+
__metadata("design:type", Object)
|
|
35
|
+
], ValkeyEnvironment.prototype, "VALKEY_PASSWORD", void 0);
|
|
36
|
+
__decorate([
|
|
37
|
+
Expose(),
|
|
38
|
+
IsNumber(),
|
|
39
|
+
Type(() => Number),
|
|
40
|
+
__metadata("design:type", Object)
|
|
41
|
+
], ValkeyEnvironment.prototype, "VALKEY_PORT", void 0);
|
|
42
|
+
__decorate([
|
|
43
|
+
Expose(),
|
|
44
|
+
IsString(),
|
|
45
|
+
__metadata("design:type", Object)
|
|
46
|
+
], ValkeyEnvironment.prototype, "VALKEY_USERNAME", void 0);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ValkeyEnvironment } from './envs/valkey.environment.js';
|
|
2
|
+
export declare class ValkeyConfig {
|
|
3
|
+
private readonly environment;
|
|
4
|
+
get host(): string;
|
|
5
|
+
get isCluster(): boolean;
|
|
6
|
+
get isEnabled(): boolean;
|
|
7
|
+
get password(): string;
|
|
8
|
+
get port(): number;
|
|
9
|
+
get username(): string;
|
|
10
|
+
constructor(environment: ValkeyEnvironment);
|
|
11
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { Injectable } from '@nestjs/common';
|
|
11
|
+
import { ValkeyEnvironment } from './envs/valkey.environment.js';
|
|
12
|
+
let ValkeyConfig = class ValkeyConfig {
|
|
13
|
+
environment;
|
|
14
|
+
get host() {
|
|
15
|
+
return this.environment.VALKEY_HOST;
|
|
16
|
+
}
|
|
17
|
+
get isCluster() {
|
|
18
|
+
return this.environment.VALKEY_CLUSTER;
|
|
19
|
+
}
|
|
20
|
+
get isEnabled() {
|
|
21
|
+
return this.environment.VALKEY_HOST !== '';
|
|
22
|
+
}
|
|
23
|
+
get password() {
|
|
24
|
+
return this.environment.VALKEY_PASSWORD;
|
|
25
|
+
}
|
|
26
|
+
get port() {
|
|
27
|
+
return this.environment.VALKEY_PORT;
|
|
28
|
+
}
|
|
29
|
+
get username() {
|
|
30
|
+
return this.environment.VALKEY_USERNAME;
|
|
31
|
+
}
|
|
32
|
+
constructor(environment) {
|
|
33
|
+
this.environment = environment;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
ValkeyConfig = __decorate([
|
|
37
|
+
Injectable(),
|
|
38
|
+
__metadata("design:paramtypes", [ValkeyEnvironment])
|
|
39
|
+
], ValkeyConfig);
|
|
40
|
+
export { ValkeyConfig };
|
package/dist/esm/constants.d.ts
CHANGED
package/dist/esm/constants.js
CHANGED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Cluster, Redis } from 'iovalkey';
|
|
2
|
+
import type { AttemptCounterInterface } from './attempt-counter.interface.js';
|
|
3
|
+
import type { ValkeyConfig } from './configs/valkey.config.js';
|
|
4
|
+
import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
|
|
5
|
+
export declare const createValkeyClient: (config: ValkeyConfig) => Cluster | Redis;
|
|
6
|
+
export declare const createAttemptCounter: (config: ValkeyConfig, logger: RateLimitLoggerInterface) => AttemptCounterInterface;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Cluster, Redis } from 'iovalkey';
|
|
2
|
+
import { InMemoryAttemptCounter } from './in-memory-attempt-counter.js';
|
|
3
|
+
import { ValkeyAttemptCounter } from './valkey-attempt-counter.js';
|
|
4
|
+
const IN_MEMORY_FALLBACK_WARNING = 'VALKEY_HOST is empty: attempt counters are kept in process memory,'
|
|
5
|
+
+ ' so the lockout threshold applies per replica and resets on restart';
|
|
6
|
+
export const createValkeyClient = (config) => {
|
|
7
|
+
const options = { lazyConnect: true, password: config.password, username: config.username };
|
|
8
|
+
return config.isCluster
|
|
9
|
+
? new Cluster([{ host: config.host, port: config.port }], { lazyConnect: true, redisOptions: options })
|
|
10
|
+
: new Redis({ ...options, host: config.host, port: config.port });
|
|
11
|
+
};
|
|
12
|
+
export const createAttemptCounter = (config, logger) => {
|
|
13
|
+
if (config.isEnabled) {
|
|
14
|
+
return new ValkeyAttemptCounter(createValkeyClient(config));
|
|
15
|
+
}
|
|
16
|
+
logger.warn({}, IN_MEMORY_FALLBACK_WARNING);
|
|
17
|
+
return new InMemoryAttemptCounter();
|
|
18
|
+
};
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
+
export * from './configs/index.js';
|
|
1
2
|
export * from './attempt-counter.interface.js';
|
|
2
3
|
export * from './constants.js';
|
|
4
|
+
export * from './create-attempt-counter.js';
|
|
3
5
|
export * from './in-memory-attempt-counter.js';
|
|
4
6
|
export * from './rate-limit-logger.js';
|
|
5
7
|
export * from './rate-limit-logger.interface.js';
|
|
6
8
|
export * from './rate-limit.module.js';
|
|
9
|
+
export * from './throttle-axis.js';
|
|
10
|
+
export * from './throttle-axis.interface.js';
|
|
7
11
|
export * from './throttle-budget.js';
|
|
8
12
|
export * from './throttle-gate.js';
|
|
13
|
+
export * from './throttle-outcome.interceptor.js';
|
|
14
|
+
export * from './throttle.decorator.js';
|
|
15
|
+
export * from './throttle.guard.js';
|
|
9
16
|
export * from './valkey-attempt-counter.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
+
export * from './configs/index.js';
|
|
1
2
|
export * from './attempt-counter.interface.js';
|
|
2
3
|
export * from './constants.js';
|
|
4
|
+
export * from './create-attempt-counter.js';
|
|
3
5
|
export * from './in-memory-attempt-counter.js';
|
|
4
6
|
export * from './rate-limit-logger.js';
|
|
5
7
|
export * from './rate-limit-logger.interface.js';
|
|
6
8
|
export * from './rate-limit.module.js';
|
|
9
|
+
export * from './throttle-axis.js';
|
|
10
|
+
export * from './throttle-axis.interface.js';
|
|
7
11
|
export * from './throttle-budget.js';
|
|
8
12
|
export * from './throttle-gate.js';
|
|
13
|
+
export * from './throttle-outcome.interceptor.js';
|
|
14
|
+
export * from './throttle.decorator.js';
|
|
15
|
+
export * from './throttle.guard.js';
|
|
9
16
|
export * from './valkey-attempt-counter.js';
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/common';
|
|
2
2
|
import type { AttemptCounterInterface } from './attempt-counter.interface.js';
|
|
3
|
-
import type {
|
|
3
|
+
import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
|
|
4
4
|
export interface RateLimitModuleOptionsInterface {
|
|
5
|
-
readonly counter
|
|
6
|
-
readonly
|
|
5
|
+
readonly counter?: FactoryOptions<AttemptCounterInterface>;
|
|
6
|
+
readonly execute: FactoryOptions<ThrottleExecuteFunction>;
|
|
7
7
|
readonly imports?: ModuleMetadata['imports'];
|
|
8
8
|
}
|
|
9
9
|
type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
|
|
@@ -4,20 +4,34 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
4
4
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
|
+
import { ConfigsModule } from '@libs-for-dev/nestjs-config-module';
|
|
7
8
|
import { Module } from '@nestjs/common';
|
|
8
|
-
import {
|
|
9
|
+
import { ValkeyEnvironment } from './configs/envs/valkey.environment.js';
|
|
10
|
+
import { ValkeyConfig } from './configs/valkey.config.js';
|
|
11
|
+
import { RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, RATE_LIMIT_LOGGER } from './constants.js';
|
|
12
|
+
import { createAttemptCounter } from './create-attempt-counter.js';
|
|
9
13
|
import { RateLimitLogger } from './rate-limit-logger.js';
|
|
10
14
|
import { ThrottleBudget } from './throttle-budget.js';
|
|
11
15
|
import { ThrottleGate } from './throttle-gate.js';
|
|
16
|
+
const bindCounter = (counter) => {
|
|
17
|
+
if (counter !== undefined) {
|
|
18
|
+
return { imports: [], provider: counter };
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
imports: [ConfigsModule.forFeature([ValkeyConfig], [ValkeyEnvironment])],
|
|
22
|
+
provider: { inject: [ValkeyConfig, RATE_LIMIT_LOGGER], useFactory: createAttemptCounter },
|
|
23
|
+
};
|
|
24
|
+
};
|
|
12
25
|
let RateLimitModule = class RateLimitModule {
|
|
13
26
|
static forRootAsync(options) {
|
|
27
|
+
const counter = bindCounter(options.counter);
|
|
14
28
|
return {
|
|
15
|
-
exports: [RATE_LIMIT_COUNTER, ThrottleBudget, ThrottleGate],
|
|
16
|
-
imports: options.imports ?? [],
|
|
29
|
+
exports: [RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, ThrottleBudget, ThrottleGate],
|
|
30
|
+
imports: [...(options.imports ?? []), ...counter.imports],
|
|
17
31
|
module: this,
|
|
18
32
|
providers: [
|
|
19
|
-
{ ...
|
|
20
|
-
{ ...options.
|
|
33
|
+
{ ...counter.provider, provide: RATE_LIMIT_COUNTER },
|
|
34
|
+
{ ...options.execute, provide: RATE_LIMIT_EXECUTE },
|
|
21
35
|
{ provide: RATE_LIMIT_LOGGER, useClass: RateLimitLogger },
|
|
22
36
|
ThrottleBudget,
|
|
23
37
|
ThrottleGate,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ThrottleAxisInterface, ThrottleAxisOutcomeInterface, ThrottleDecidedAxisInterface, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
2
|
+
export interface ThrottleOutcomeAxisInterface<TContext extends ThrottleGuardContextInterface> extends Pick<ThrottleDecidedAxisInterface<TContext, ThrottleGateDecisionInterface>, 'readContext'> {
|
|
3
|
+
readonly outcome: ThrottleAxisOutcomeInterface<TContext>;
|
|
4
|
+
}
|
|
5
|
+
export declare const defineThrottleAxis: <TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface = ThrottleGateDecisionInterface>(axis: ThrottleAxisInterface<TContext, TDecision>) => ThrottleAxisInterface<TContext, TDecision>;
|
|
6
|
+
export declare const ThrottleAxisMetadata: import("@nestjs/core").ReflectableDecorator<ThrottleAxisInterface<ThrottleGuardContextInterface>, ThrottleAxisInterface<ThrottleGuardContextInterface>>;
|
|
7
|
+
export declare const ThrottleOutcomeMetadata: import("@nestjs/core").ReflectableDecorator<ThrottleOutcomeAxisInterface<ThrottleGuardContextInterface>, ThrottleOutcomeAxisInterface<ThrottleGuardContextInterface>>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ExecutionContext, InjectionToken } from '@nestjs/common';
|
|
2
|
+
import type { ThrottleRateLimitInterface, ThrottleRefusalInterface } from './throttle-budget.js';
|
|
3
|
+
export type ThrottleAxisInterface<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface = ThrottleGateDecisionInterface> = ThrottleDecidedAxisInterface<TContext, TDecision> | ThrottleSpentAxisInterface<TContext>;
|
|
4
|
+
export interface ThrottleAxisOutcomeInterface<TContext extends ThrottleGuardContextInterface> {
|
|
5
|
+
createCommand(context: TContext, didSucceed: boolean): object;
|
|
6
|
+
isAttemptSpent(error: unknown): boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface ThrottleDecidedAxisInterface<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface> extends ThrottleAxisBaseInterface<TContext> {
|
|
9
|
+
createCommand(context: TContext): object;
|
|
10
|
+
isAllowed(decision: TDecision): boolean;
|
|
11
|
+
readonly outcome?: ThrottleAxisOutcomeInterface<TContext>;
|
|
12
|
+
}
|
|
13
|
+
export type ThrottleExecuteFunction = <TResult>(command: object) => Promise<TResult>;
|
|
14
|
+
export interface ThrottleGateDecisionInterface {
|
|
15
|
+
retryAfterSeconds: number;
|
|
16
|
+
}
|
|
17
|
+
export interface ThrottleGuardContextInterface {
|
|
18
|
+
reply: ThrottleReplyInterface;
|
|
19
|
+
}
|
|
20
|
+
export interface ThrottleReplyInterface {
|
|
21
|
+
header(name: string, value: string): unknown;
|
|
22
|
+
}
|
|
23
|
+
export interface ThrottleSpentAxisInterface<TContext extends ThrottleGuardContextInterface> extends ThrottleAxisBaseInterface<TContext> {
|
|
24
|
+
key(context: TContext): string;
|
|
25
|
+
readonly limit: InjectionToken<ThrottleRateLimitInterface>;
|
|
26
|
+
readonly refusal: ThrottleRefusalInterface;
|
|
27
|
+
}
|
|
28
|
+
interface ThrottleAxisBaseInterface<TContext extends ThrottleGuardContextInterface> {
|
|
29
|
+
createError(): Error;
|
|
30
|
+
readContext(context: ExecutionContext): TContext;
|
|
31
|
+
}
|
|
32
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,22 +1,12 @@
|
|
|
1
1
|
import type { ExecutionContext } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
isAllowed(decision: TDecision): boolean;
|
|
6
|
-
readContext(context: ExecutionContext): TContext;
|
|
7
|
-
}
|
|
8
|
-
export type ThrottleDecideFunction = <TDecision>(command: object) => Promise<TDecision>;
|
|
9
|
-
export interface ThrottleGateDecisionInterface {
|
|
10
|
-
retryAfterSeconds: number;
|
|
11
|
-
}
|
|
12
|
-
export interface ThrottleGuardContextInterface {
|
|
13
|
-
reply: ThrottleReplyInterface;
|
|
14
|
-
}
|
|
15
|
-
export interface ThrottleReplyInterface {
|
|
16
|
-
header(name: string, value: string): unknown;
|
|
17
|
-
}
|
|
2
|
+
import { ModuleRef } from '@nestjs/core';
|
|
3
|
+
import type { ThrottleAxisInterface, ThrottleExecuteFunction, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
4
|
+
import { ThrottleBudget } from './throttle-budget.js';
|
|
18
5
|
export declare class ThrottleGate {
|
|
19
|
-
private readonly
|
|
20
|
-
|
|
6
|
+
private readonly execute;
|
|
7
|
+
private readonly budget;
|
|
8
|
+
private readonly moduleReference;
|
|
9
|
+
constructor(execute: ThrottleExecuteFunction, budget: ThrottleBudget, moduleReference: ModuleRef);
|
|
21
10
|
pass<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(executionContext: ExecutionContext, axis: ThrottleAxisInterface<TContext, TDecision>): Promise<boolean>;
|
|
11
|
+
private decide;
|
|
22
12
|
}
|
|
@@ -11,26 +11,42 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
-
import {
|
|
14
|
+
import { ModuleRef } from '@nestjs/core';
|
|
15
|
+
import { RATE_LIMIT_EXECUTE } from './constants.js';
|
|
16
|
+
import { ThrottleBudget } from './throttle-budget.js';
|
|
15
17
|
const RETRY_AFTER_HEADER = 'retry-after';
|
|
18
|
+
const isSpentAxis = (axis) => 'limit' in axis;
|
|
16
19
|
let ThrottleGate = class ThrottleGate {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
+
execute;
|
|
21
|
+
budget;
|
|
22
|
+
moduleReference;
|
|
23
|
+
constructor(execute, budget, moduleReference) {
|
|
24
|
+
this.execute = execute;
|
|
25
|
+
this.budget = budget;
|
|
26
|
+
this.moduleReference = moduleReference;
|
|
20
27
|
}
|
|
21
28
|
async pass(executionContext, axis) {
|
|
22
29
|
const context = axis.readContext(executionContext);
|
|
23
|
-
const decision = await this.decide(axis
|
|
24
|
-
if (
|
|
30
|
+
const decision = await this.decide(axis, context);
|
|
31
|
+
if (decision.allowed) {
|
|
25
32
|
return true;
|
|
26
33
|
}
|
|
27
34
|
void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
|
|
28
35
|
throw axis.createError();
|
|
29
36
|
}
|
|
37
|
+
async decide(axis, context) {
|
|
38
|
+
if (isSpentAxis(axis)) {
|
|
39
|
+
const limit = this.moduleReference.get(axis.limit, { strict: false });
|
|
40
|
+
return this.budget.spend({ key: axis.key(context), limit, refusal: axis.refusal });
|
|
41
|
+
}
|
|
42
|
+
const decision = await this.execute(axis.createCommand(context));
|
|
43
|
+
return { allowed: axis.isAllowed(decision), retryAfterSeconds: decision.retryAfterSeconds };
|
|
44
|
+
}
|
|
30
45
|
};
|
|
31
46
|
ThrottleGate = __decorate([
|
|
32
47
|
Injectable(),
|
|
33
|
-
__param(0, Inject(
|
|
34
|
-
__metadata("design:paramtypes", [Function
|
|
48
|
+
__param(0, Inject(RATE_LIMIT_EXECUTE)),
|
|
49
|
+
__metadata("design:paramtypes", [Function, ThrottleBudget,
|
|
50
|
+
ModuleRef])
|
|
35
51
|
], ThrottleGate);
|
|
36
52
|
export { ThrottleGate };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
|
|
2
|
+
import type { Observable } from 'rxjs';
|
|
3
|
+
import { Reflector } from '@nestjs/core';
|
|
4
|
+
import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
|
|
5
|
+
export declare class ThrottleOutcomeInterceptor implements NestInterceptor {
|
|
6
|
+
private readonly reflector;
|
|
7
|
+
private readonly execute;
|
|
8
|
+
constructor(reflector: Reflector, execute: ThrottleExecuteFunction);
|
|
9
|
+
intercept(executionContext: ExecutionContext, next: CallHandler): Observable<unknown>;
|
|
10
|
+
private register;
|
|
11
|
+
private registerRejection;
|
|
12
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
+
import { Reflector } from '@nestjs/core';
|
|
15
|
+
import { catchError, concatMap, from } from 'rxjs';
|
|
16
|
+
import { RATE_LIMIT_EXECUTE } from './constants.js';
|
|
17
|
+
import { ThrottleOutcomeMetadata } from './throttle-axis.js';
|
|
18
|
+
let ThrottleOutcomeInterceptor = class ThrottleOutcomeInterceptor {
|
|
19
|
+
reflector;
|
|
20
|
+
execute;
|
|
21
|
+
constructor(reflector, execute) {
|
|
22
|
+
this.reflector = reflector;
|
|
23
|
+
this.execute = execute;
|
|
24
|
+
}
|
|
25
|
+
intercept(executionContext, next) {
|
|
26
|
+
const axis = this.reflector.get(ThrottleOutcomeMetadata, executionContext.getHandler());
|
|
27
|
+
const context = axis.readContext(executionContext);
|
|
28
|
+
return next.handle().pipe(concatMap(async (answer) => {
|
|
29
|
+
await this.register(axis, context, true);
|
|
30
|
+
return answer;
|
|
31
|
+
}), catchError((error) => from(this.registerRejection(axis, context, error))));
|
|
32
|
+
}
|
|
33
|
+
async register(axis, context, didSucceed) {
|
|
34
|
+
await this.execute(axis.outcome.createCommand(context, didSucceed));
|
|
35
|
+
}
|
|
36
|
+
async registerRejection(axis, context, error) {
|
|
37
|
+
if (axis.outcome.isAttemptSpent(error)) {
|
|
38
|
+
await this.register(axis, context, false);
|
|
39
|
+
}
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
ThrottleOutcomeInterceptor = __decorate([
|
|
44
|
+
Injectable(),
|
|
45
|
+
__param(1, Inject(RATE_LIMIT_EXECUTE)),
|
|
46
|
+
__metadata("design:paramtypes", [Reflector, Function])
|
|
47
|
+
], ThrottleOutcomeInterceptor);
|
|
48
|
+
export { ThrottleOutcomeInterceptor };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { ThrottleAxisInterface, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
2
|
+
export declare const Throttle: <TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(axis: ThrottleAxisInterface<TContext, TDecision>) => MethodDecorator;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { applyDecorators, UseGuards, UseInterceptors } from '@nestjs/common';
|
|
2
|
+
import { ThrottleAxisMetadata, ThrottleOutcomeMetadata } from './throttle-axis.js';
|
|
3
|
+
import { ThrottleOutcomeInterceptor } from './throttle-outcome.interceptor.js';
|
|
4
|
+
import { ThrottleGuard } from './throttle.guard.js';
|
|
5
|
+
export const Throttle = (axis) => {
|
|
6
|
+
const decorators = [ThrottleAxisMetadata(axis), UseGuards(ThrottleGuard)];
|
|
7
|
+
if ('outcome' in axis) {
|
|
8
|
+
decorators.push(ThrottleOutcomeMetadata({ outcome: axis.outcome, readContext: (context) => axis.readContext(context) }), UseInterceptors(ThrottleOutcomeInterceptor));
|
|
9
|
+
}
|
|
10
|
+
return applyDecorators(...decorators);
|
|
11
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import { ThrottleGate } from './throttle-gate.js';
|
|
4
|
+
export declare class ThrottleGuard implements CanActivate {
|
|
5
|
+
private readonly reflector;
|
|
6
|
+
private readonly gate;
|
|
7
|
+
constructor(reflector: Reflector, gate: ThrottleGate);
|
|
8
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { Injectable } from '@nestjs/common';
|
|
11
|
+
import { Reflector } from '@nestjs/core';
|
|
12
|
+
import { ThrottleAxisMetadata } from './throttle-axis.js';
|
|
13
|
+
import { ThrottleGate } from './throttle-gate.js';
|
|
14
|
+
let ThrottleGuard = class ThrottleGuard {
|
|
15
|
+
reflector;
|
|
16
|
+
gate;
|
|
17
|
+
constructor(reflector, gate) {
|
|
18
|
+
this.reflector = reflector;
|
|
19
|
+
this.gate = gate;
|
|
20
|
+
}
|
|
21
|
+
async canActivate(context) {
|
|
22
|
+
return this.gate.pass(context, this.reflector.get(ThrottleAxisMetadata, context.getHandler()));
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
ThrottleGuard = __decorate([
|
|
26
|
+
Injectable(),
|
|
27
|
+
__metadata("design:paramtypes", [Reflector,
|
|
28
|
+
ThrottleGate])
|
|
29
|
+
], ThrottleGuard);
|
|
30
|
+
export { ThrottleGuard };
|