@application-kit/rate-limit 0.2.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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # @application-kit/rate-limit
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d8557a5: `RateLimitModule.forRootAsync` без опции `counter` выбирает хранилище счётчика сам по окружению `VALKEY_*`
8
+ (`VALKEY_HOST`, `VALKEY_PORT`, `VALKEY_CLUSTER`, `VALKEY_USERNAME`, `VALKEY_PASSWORD`): адрес задан — `ValkeyAttemptCounter`
9
+ над ленивым клиентом кластера или одиночного сервера, пуст — `InMemoryAttemptCounter` и одно предупреждение в лог.
10
+ Окружение валидируется в `forRootAsync`, не на импорте пакета. Переданный `counter` работает как раньше, и тогда
11
+ `VALKEY_*` не читается. Новые экспорты: `ValkeyEnvironment`, `ValkeyConfig`, `createValkeyClient`, `createAttemptCounter`;
12
+ `iovalkey` — зависимость пакета, `@libs-for-dev/nestjs-config-module`, `class-transformer`, `class-validator` — новые
13
+ peer: потребителю — поставить их, а свою сборку клиента и фабрику счётчика заменить умолчанием модуля.
14
+
3
15
  ## 0.2.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -9,31 +9,39 @@
9
9
  yarn add @application-kit/rate-limit
10
10
  ```
11
11
 
12
- Peer-зависимости: `@nestjs/common`, `@nestjs/core`, `nestjs-pino`, `oxide.ts`, `rxjs`. Клиент Valkey пакет не импортирует — его собирает
13
- приложение из своего конфига и отдаёт готовым экземпляром.
12
+ Peer-зависимости: `@libs-for-dev/nestjs-config-module`, `@nestjs/common`, `@nestjs/core`, `class-transformer`,
13
+ `class-validator`, `nestjs-pino`, `oxide.ts`, `rxjs`. Клиент Valkey (`iovalkey`) — зависимость пакета.
14
14
 
15
15
  ## Подключение
16
16
 
17
17
  ```ts
18
- import { InMemoryAttemptCounter, RateLimitModule, ValkeyAttemptCounter } from '@application-kit/rate-limit'
18
+ import { RateLimitModule } from '@application-kit/rate-limit'
19
19
 
20
20
  RateLimitModule.forRootAsync({
21
- // Память или Valkey выбирает приложение: адрес хранилища знает его конфиг.
22
- counter: {
23
- inject: [ValkeyConfig],
24
- useFactory: (config: ValkeyConfig) => (config.isEnabled
25
- ? new ValkeyAttemptCounter(createValkeyClient(config))
26
- : new InMemoryAttemptCounter()),
27
- },
28
21
  // Исполнитель команд оси — решения и исхода: обычно — шина команд приложения.
29
22
  execute: {
30
23
  inject: [CommandBus],
31
24
  useFactory: (commandBus: CommandBus) => async (command: object) => commandBus.execute(command),
32
25
  },
33
- imports: [ValkeyConfigModule],
26
+ imports: [CqrsModule],
34
27
  })
35
28
  ```
36
29
 
30
+ Счётчик без опции `counter` выбирает окружение:
31
+
32
+ | Переменная | Умолчание | Смысл |
33
+ |---|---|---|
34
+ | `VALKEY_HOST` | `''` | адрес хранилища; пусто — счётчик в памяти процесса и одно предупреждение в лог |
35
+ | `VALKEY_PORT` | `6379` | порт |
36
+ | `VALKEY_CLUSTER` | `true` | кластерный протокол (адрес — стартовый узел); `false` — одиночный сервер |
37
+ | `VALKEY_USERNAME` | `default` | пользователь ACL |
38
+ | `VALKEY_PASSWORD` | `''` | пароль |
39
+
40
+ Клиент ленивый (`lazyConnect`): соединение открывает первая попытка, а не сборка графа. Окружение читается и
41
+ валидируется в `forRootAsync`, а не на импорте пакета; неверное значение роняет старт с именем переменной.
42
+ Свой счётчик — фабрикой в опции `counter` (`{ useFactory: () => new FakeAttemptCounter() }` из
43
+ `@application-kit/rate-limit/testing` в спеках): тогда `VALKEY_*` не читается.
44
+
37
45
  Модуль экспортирует токены счётчика и исполнителя (`RATE_LIMIT_COUNTER`, `RATE_LIMIT_EXECUTE`), `ThrottleBudget` и
38
46
  `ThrottleGate`: модуль ручки обязан их видеть — guard и интерцептор оси создаются там. Логгер отказов
39
47
  (`RATE_LIMIT_LOGGER`, `RateLimitLogger`) модуль связывает сам — нужен глобальный `LoggerModule` из `nestjs-pino`.
@@ -0,0 +1 @@
1
+ export * from './valkey.environment.js';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./valkey.environment.js"), exports);
@@ -0,0 +1,7 @@
1
+ export declare class ValkeyEnvironment {
2
+ VALKEY_CLUSTER: boolean;
3
+ VALKEY_HOST: string;
4
+ VALKEY_PASSWORD: string;
5
+ VALKEY_PORT: number;
6
+ VALKEY_USERNAME: string;
7
+ }
@@ -0,0 +1,50 @@
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.ValkeyEnvironment = void 0;
13
+ const nestjs_config_module_1 = require("@libs-for-dev/nestjs-config-module");
14
+ const class_transformer_1 = require("class-transformer");
15
+ const class_validator_1 = require("class-validator");
16
+ class ValkeyEnvironment {
17
+ VALKEY_CLUSTER = true;
18
+ VALKEY_HOST = '';
19
+ VALKEY_PASSWORD = '';
20
+ VALKEY_PORT = 6379;
21
+ VALKEY_USERNAME = 'default';
22
+ }
23
+ exports.ValkeyEnvironment = ValkeyEnvironment;
24
+ __decorate([
25
+ (0, class_transformer_1.Expose)(),
26
+ (0, class_validator_1.IsBoolean)(),
27
+ (0, nestjs_config_module_1.ParseBoolean)(),
28
+ __metadata("design:type", Object)
29
+ ], ValkeyEnvironment.prototype, "VALKEY_CLUSTER", void 0);
30
+ __decorate([
31
+ (0, class_transformer_1.Expose)(),
32
+ (0, class_validator_1.IsString)(),
33
+ __metadata("design:type", Object)
34
+ ], ValkeyEnvironment.prototype, "VALKEY_HOST", void 0);
35
+ __decorate([
36
+ (0, class_transformer_1.Expose)(),
37
+ (0, class_validator_1.IsString)(),
38
+ __metadata("design:type", Object)
39
+ ], ValkeyEnvironment.prototype, "VALKEY_PASSWORD", void 0);
40
+ __decorate([
41
+ (0, class_transformer_1.Expose)(),
42
+ (0, class_validator_1.IsNumber)(),
43
+ (0, class_transformer_1.Type)(() => Number),
44
+ __metadata("design:type", Object)
45
+ ], ValkeyEnvironment.prototype, "VALKEY_PORT", void 0);
46
+ __decorate([
47
+ (0, class_transformer_1.Expose)(),
48
+ (0, class_validator_1.IsString)(),
49
+ __metadata("design:type", Object)
50
+ ], ValkeyEnvironment.prototype, "VALKEY_USERNAME", void 0);
@@ -0,0 +1,2 @@
1
+ export * from './envs/index.js';
2
+ export * from './valkey.config.js';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./envs/index.js"), exports);
18
+ __exportStar(require("./valkey.config.js"), exports);
@@ -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,43 @@
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.ValkeyConfig = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const valkey_environment_js_1 = require("./envs/valkey.environment.js");
15
+ let ValkeyConfig = class ValkeyConfig {
16
+ environment;
17
+ get host() {
18
+ return this.environment.VALKEY_HOST;
19
+ }
20
+ get isCluster() {
21
+ return this.environment.VALKEY_CLUSTER;
22
+ }
23
+ get isEnabled() {
24
+ return this.environment.VALKEY_HOST !== '';
25
+ }
26
+ get password() {
27
+ return this.environment.VALKEY_PASSWORD;
28
+ }
29
+ get port() {
30
+ return this.environment.VALKEY_PORT;
31
+ }
32
+ get username() {
33
+ return this.environment.VALKEY_USERNAME;
34
+ }
35
+ constructor(environment) {
36
+ this.environment = environment;
37
+ }
38
+ };
39
+ exports.ValkeyConfig = ValkeyConfig;
40
+ exports.ValkeyConfig = ValkeyConfig = __decorate([
41
+ (0, common_1.Injectable)(),
42
+ __metadata("design:paramtypes", [valkey_environment_js_1.ValkeyEnvironment])
43
+ ], ValkeyConfig);
@@ -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,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAttemptCounter = exports.createValkeyClient = void 0;
4
+ const iovalkey_1 = require("iovalkey");
5
+ const in_memory_attempt_counter_js_1 = require("./in-memory-attempt-counter.js");
6
+ const valkey_attempt_counter_js_1 = require("./valkey-attempt-counter.js");
7
+ const IN_MEMORY_FALLBACK_WARNING = 'VALKEY_HOST is empty: attempt counters are kept in process memory,'
8
+ + ' so the lockout threshold applies per replica and resets on restart';
9
+ const createValkeyClient = (config) => {
10
+ const options = { lazyConnect: true, password: config.password, username: config.username };
11
+ return config.isCluster
12
+ ? new iovalkey_1.Cluster([{ host: config.host, port: config.port }], { lazyConnect: true, redisOptions: options })
13
+ : new iovalkey_1.Redis({ ...options, host: config.host, port: config.port });
14
+ };
15
+ exports.createValkeyClient = createValkeyClient;
16
+ const createAttemptCounter = (config, logger) => {
17
+ if (config.isEnabled) {
18
+ return new valkey_attempt_counter_js_1.ValkeyAttemptCounter((0, exports.createValkeyClient)(config));
19
+ }
20
+ logger.warn({}, IN_MEMORY_FALLBACK_WARNING);
21
+ return new in_memory_attempt_counter_js_1.InMemoryAttemptCounter();
22
+ };
23
+ exports.createAttemptCounter = createAttemptCounter;
@@ -1,5 +1,7 @@
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';
package/dist/cjs/index.js CHANGED
@@ -14,8 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./configs/index.js"), exports);
17
18
  __exportStar(require("./attempt-counter.interface.js"), exports);
18
19
  __exportStar(require("./constants.js"), exports);
20
+ __exportStar(require("./create-attempt-counter.js"), exports);
19
21
  __exportStar(require("./in-memory-attempt-counter.js"), exports);
20
22
  __exportStar(require("./rate-limit-logger.js"), exports);
21
23
  __exportStar(require("./rate-limit-logger.interface.js"), exports);
@@ -2,7 +2,7 @@ import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/com
2
2
  import type { AttemptCounterInterface } from './attempt-counter.interface.js';
3
3
  import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
4
4
  export interface RateLimitModuleOptionsInterface {
5
- readonly counter: FactoryOptions<AttemptCounterInterface>;
5
+ readonly counter?: FactoryOptions<AttemptCounterInterface>;
6
6
  readonly execute: FactoryOptions<ThrottleExecuteFunction>;
7
7
  readonly imports?: ModuleMetadata['imports'];
8
8
  }
@@ -7,19 +7,33 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  };
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.RateLimitModule = void 0;
10
+ const nestjs_config_module_1 = require("@libs-for-dev/nestjs-config-module");
10
11
  const common_1 = require("@nestjs/common");
12
+ const valkey_environment_js_1 = require("./configs/envs/valkey.environment.js");
13
+ const valkey_config_js_1 = require("./configs/valkey.config.js");
11
14
  const constants_js_1 = require("./constants.js");
15
+ const create_attempt_counter_js_1 = require("./create-attempt-counter.js");
12
16
  const rate_limit_logger_js_1 = require("./rate-limit-logger.js");
13
17
  const throttle_budget_js_1 = require("./throttle-budget.js");
14
18
  const throttle_gate_js_1 = require("./throttle-gate.js");
19
+ const bindCounter = (counter) => {
20
+ if (counter !== undefined) {
21
+ return { imports: [], provider: counter };
22
+ }
23
+ return {
24
+ imports: [nestjs_config_module_1.ConfigsModule.forFeature([valkey_config_js_1.ValkeyConfig], [valkey_environment_js_1.ValkeyEnvironment])],
25
+ provider: { inject: [valkey_config_js_1.ValkeyConfig, constants_js_1.RATE_LIMIT_LOGGER], useFactory: create_attempt_counter_js_1.createAttemptCounter },
26
+ };
27
+ };
15
28
  let RateLimitModule = class RateLimitModule {
16
29
  static forRootAsync(options) {
30
+ const counter = bindCounter(options.counter);
17
31
  return {
18
32
  exports: [constants_js_1.RATE_LIMIT_COUNTER, constants_js_1.RATE_LIMIT_EXECUTE, throttle_budget_js_1.ThrottleBudget, throttle_gate_js_1.ThrottleGate],
19
- imports: options.imports ?? [],
33
+ imports: [...(options.imports ?? []), ...counter.imports],
20
34
  module: this,
21
35
  providers: [
22
- { ...options.counter, provide: constants_js_1.RATE_LIMIT_COUNTER },
36
+ { ...counter.provider, provide: constants_js_1.RATE_LIMIT_COUNTER },
23
37
  { ...options.execute, provide: constants_js_1.RATE_LIMIT_EXECUTE },
24
38
  { provide: constants_js_1.RATE_LIMIT_LOGGER, useClass: rate_limit_logger_js_1.RateLimitLogger },
25
39
  throttle_budget_js_1.ThrottleBudget,
@@ -0,0 +1 @@
1
+ export * from './valkey.environment.js';
@@ -0,0 +1 @@
1
+ export * from './valkey.environment.js';
@@ -0,0 +1,7 @@
1
+ export declare class ValkeyEnvironment {
2
+ VALKEY_CLUSTER: boolean;
3
+ VALKEY_HOST: string;
4
+ VALKEY_PASSWORD: string;
5
+ VALKEY_PORT: number;
6
+ VALKEY_USERNAME: string;
7
+ }
@@ -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,2 @@
1
+ export * from './envs/index.js';
2
+ export * from './valkey.config.js';
@@ -0,0 +1,2 @@
1
+ export * from './envs/index.js';
2
+ export * from './valkey.config.js';
@@ -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 };
@@ -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
+ };
@@ -1,5 +1,7 @@
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';
package/dist/esm/index.js CHANGED
@@ -1,5 +1,7 @@
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';
@@ -2,7 +2,7 @@ import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/com
2
2
  import type { AttemptCounterInterface } from './attempt-counter.interface.js';
3
3
  import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
4
4
  export interface RateLimitModuleOptionsInterface {
5
- readonly counter: FactoryOptions<AttemptCounterInterface>;
5
+ readonly counter?: FactoryOptions<AttemptCounterInterface>;
6
6
  readonly execute: FactoryOptions<ThrottleExecuteFunction>;
7
7
  readonly imports?: ModuleMetadata['imports'];
8
8
  }
@@ -4,19 +4,33 @@ 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';
9
+ import { ValkeyEnvironment } from './configs/envs/valkey.environment.js';
10
+ import { ValkeyConfig } from './configs/valkey.config.js';
8
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
29
  exports: [RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, ThrottleBudget, ThrottleGate],
16
- imports: options.imports ?? [],
30
+ imports: [...(options.imports ?? []), ...counter.imports],
17
31
  module: this,
18
32
  providers: [
19
- { ...options.counter, provide: RATE_LIMIT_COUNTER },
33
+ { ...counter.provider, provide: RATE_LIMIT_COUNTER },
20
34
  { ...options.execute, provide: RATE_LIMIT_EXECUTE },
21
35
  { provide: RATE_LIMIT_LOGGER, useClass: RateLimitLogger },
22
36
  ThrottleBudget,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@application-kit/rate-limit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Частотная защита для NestJS: счётчик попыток с окном (память и Valkey с атомарным Lua), бюджет попыток и gate с Retry-After",
5
5
  "keywords": [
6
6
  "nestjs",
@@ -56,14 +56,19 @@
56
56
  "test:mutation": "stryker run",
57
57
  "test:unit": "vitest run"
58
58
  },
59
+ "dependencies": {
60
+ "iovalkey": "^0.4.0"
61
+ },
59
62
  "devDependencies": {
63
+ "@libs-for-dev/nestjs-config-module": "3.0.0",
60
64
  "@nestjs/common": "^11.2.7",
61
65
  "@nestjs/core": "^11.2.7",
62
66
  "@nestjs/testing": "^11.2.7",
63
67
  "@stryker-mutator/core": "^10.0.0",
64
68
  "@stryker-mutator/vitest-runner": "^10.0.0",
65
69
  "@types/node": "^26.2.0",
66
- "iovalkey": "^0.4.0",
70
+ "class-transformer": "^0.5.1",
71
+ "class-validator": "^0.15.1",
67
72
  "nestjs-pino": "^4.6.1",
68
73
  "oxide.ts": "^1.1.0",
69
74
  "pino": "^10.3.1",
@@ -75,8 +80,11 @@
75
80
  "vitest": "^4.1.11"
76
81
  },
77
82
  "peerDependencies": {
83
+ "@libs-for-dev/nestjs-config-module": "^3.0.0",
78
84
  "@nestjs/common": "^11.0.0",
79
85
  "@nestjs/core": "^11.0.0",
86
+ "class-transformer": "^0.5.1",
87
+ "class-validator": "^0.15.1",
80
88
  "nestjs-pino": "^4.6.1",
81
89
  "oxide.ts": "^1.1.0",
82
90
  "rxjs": "^7.8.0"