@omnitron-dev/titan-ratelimit 0.1.1
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/LICENSE +21 -0
- package/README.md +19 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/ratelimit.algorithms.d.ts +23 -0
- package/dist/ratelimit.algorithms.d.ts.map +1 -0
- package/dist/ratelimit.algorithms.js +104 -0
- package/dist/ratelimit.algorithms.js.map +1 -0
- package/dist/ratelimit.decorators.d.ts +8 -0
- package/dist/ratelimit.decorators.d.ts.map +1 -0
- package/dist/ratelimit.decorators.js +120 -0
- package/dist/ratelimit.decorators.js.map +1 -0
- package/dist/ratelimit.middleware.d.ts +21 -0
- package/dist/ratelimit.middleware.d.ts.map +1 -0
- package/dist/ratelimit.middleware.js +169 -0
- package/dist/ratelimit.middleware.js.map +1 -0
- package/dist/ratelimit.module.d.ts +8 -0
- package/dist/ratelimit.module.d.ts.map +1 -0
- package/dist/ratelimit.module.js +161 -0
- package/dist/ratelimit.module.js.map +1 -0
- package/dist/ratelimit.service.d.ts +24 -0
- package/dist/ratelimit.service.d.ts.map +1 -0
- package/dist/ratelimit.service.js +154 -0
- package/dist/ratelimit.service.js.map +1 -0
- package/dist/ratelimit.storage.d.ts +45 -0
- package/dist/ratelimit.storage.d.ts.map +1 -0
- package/dist/ratelimit.storage.js +268 -0
- package/dist/ratelimit.storage.js.map +1 -0
- package/dist/ratelimit.tokens.d.ts +7 -0
- package/dist/ratelimit.tokens.d.ts.map +1 -0
- package/dist/ratelimit.tokens.js +6 -0
- package/dist/ratelimit.tokens.js.map +1 -0
- package/dist/ratelimit.types.d.ts +107 -0
- package/dist/ratelimit.types.d.ts.map +1 -0
- package/dist/ratelimit.types.js +2 -0
- package/dist/ratelimit.types.js.map +1 -0
- package/package.json +37 -0
|
@@ -0,0 +1,161 @@
|
|
|
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 TitanRateLimitModule_1;
|
|
8
|
+
import { Module } from '@omnitron-dev/titan/decorators';
|
|
9
|
+
import { RateLimitService } from './ratelimit.service.js';
|
|
10
|
+
import { RATE_LIMIT_SERVICE_TOKEN, RATE_LIMIT_OPTIONS_TOKEN, RATE_LIMIT_STORAGE_TOKEN, DEFAULT_RATE_LIMIT_PREFIX, } from './ratelimit.tokens.js';
|
|
11
|
+
import { MemoryRateLimitStorage, RedisRateLimitStorage } from './ratelimit.storage.js';
|
|
12
|
+
import { getRedisClientToken } from '@omnitron-dev/titan-redis';
|
|
13
|
+
import { LOGGER_TOKEN } from '@omnitron-dev/titan/module/logger';
|
|
14
|
+
const DEFAULT_OPTIONS = {
|
|
15
|
+
enabled: true,
|
|
16
|
+
strategy: 'sliding-window',
|
|
17
|
+
keyPrefix: DEFAULT_RATE_LIMIT_PREFIX,
|
|
18
|
+
defaultLimit: 100,
|
|
19
|
+
defaultWindowMs: 60000,
|
|
20
|
+
burstLimit: 0,
|
|
21
|
+
tokenRefillRate: 100,
|
|
22
|
+
queueEnabled: false,
|
|
23
|
+
maxQueueSize: 1000,
|
|
24
|
+
queueTimeoutMs: 5000,
|
|
25
|
+
storageType: 'memory',
|
|
26
|
+
isGlobal: false,
|
|
27
|
+
};
|
|
28
|
+
let TitanRateLimitModule = TitanRateLimitModule_1 = class TitanRateLimitModule {
|
|
29
|
+
static forRoot(options = {}) {
|
|
30
|
+
const mergedOptions = { ...DEFAULT_OPTIONS, ...options };
|
|
31
|
+
const providers = [
|
|
32
|
+
[
|
|
33
|
+
RATE_LIMIT_OPTIONS_TOKEN,
|
|
34
|
+
{
|
|
35
|
+
useValue: mergedOptions,
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
[
|
|
39
|
+
RATE_LIMIT_STORAGE_TOKEN,
|
|
40
|
+
{
|
|
41
|
+
useFactory: (...args) => {
|
|
42
|
+
const storageType = mergedOptions.storageType;
|
|
43
|
+
const logger = args[args.length - 1];
|
|
44
|
+
if (storageType === 'redis') {
|
|
45
|
+
try {
|
|
46
|
+
const redisClient = args[0];
|
|
47
|
+
if (redisClient) {
|
|
48
|
+
return new RedisRateLimitStorage(redisClient, {
|
|
49
|
+
keyPrefix: mergedOptions.keyPrefix,
|
|
50
|
+
logger,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
logger?.warn('[RateLimitModule] Redis not available, falling back to memory storage');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return new MemoryRateLimitStorage({
|
|
59
|
+
cleanupIntervalMs: 60000,
|
|
60
|
+
maxKeys: 10000,
|
|
61
|
+
});
|
|
62
|
+
},
|
|
63
|
+
inject: mergedOptions.storageType === 'redis' ? [getRedisClientToken(), LOGGER_TOKEN] : [LOGGER_TOKEN],
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
[
|
|
67
|
+
RATE_LIMIT_SERVICE_TOKEN,
|
|
68
|
+
{
|
|
69
|
+
useClass: RateLimitService,
|
|
70
|
+
},
|
|
71
|
+
],
|
|
72
|
+
];
|
|
73
|
+
const exports = [
|
|
74
|
+
RATE_LIMIT_SERVICE_TOKEN,
|
|
75
|
+
RATE_LIMIT_OPTIONS_TOKEN,
|
|
76
|
+
RATE_LIMIT_STORAGE_TOKEN,
|
|
77
|
+
];
|
|
78
|
+
const result = {
|
|
79
|
+
module: TitanRateLimitModule_1,
|
|
80
|
+
providers,
|
|
81
|
+
exports,
|
|
82
|
+
};
|
|
83
|
+
if (mergedOptions.isGlobal) {
|
|
84
|
+
result.global = true;
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
static forRootAsync(options) {
|
|
89
|
+
const providers = [
|
|
90
|
+
[
|
|
91
|
+
RATE_LIMIT_OPTIONS_TOKEN,
|
|
92
|
+
{
|
|
93
|
+
useFactory: async (...args) => {
|
|
94
|
+
if (options.useFactory) {
|
|
95
|
+
const result = await options.useFactory(...args);
|
|
96
|
+
return { ...DEFAULT_OPTIONS, ...result };
|
|
97
|
+
}
|
|
98
|
+
return DEFAULT_OPTIONS;
|
|
99
|
+
},
|
|
100
|
+
inject: (options.inject ?? []),
|
|
101
|
+
},
|
|
102
|
+
],
|
|
103
|
+
[
|
|
104
|
+
RATE_LIMIT_STORAGE_TOKEN,
|
|
105
|
+
{
|
|
106
|
+
useFactory: async (...args) => {
|
|
107
|
+
const opts = args[0];
|
|
108
|
+
const logger = args[2];
|
|
109
|
+
const storageType = opts?.storageType ?? 'memory';
|
|
110
|
+
if (storageType === 'redis') {
|
|
111
|
+
try {
|
|
112
|
+
const redisClient = args[1];
|
|
113
|
+
if (redisClient) {
|
|
114
|
+
return new RedisRateLimitStorage(redisClient, {
|
|
115
|
+
keyPrefix: opts?.keyPrefix ?? DEFAULT_RATE_LIMIT_PREFIX,
|
|
116
|
+
logger,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
logger?.warn('[RateLimitModule] Redis not available, falling back to memory storage');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return new MemoryRateLimitStorage({
|
|
125
|
+
cleanupIntervalMs: 60000,
|
|
126
|
+
maxKeys: 10000,
|
|
127
|
+
});
|
|
128
|
+
},
|
|
129
|
+
inject: [RATE_LIMIT_OPTIONS_TOKEN, getRedisClientToken(), LOGGER_TOKEN],
|
|
130
|
+
},
|
|
131
|
+
],
|
|
132
|
+
[
|
|
133
|
+
RATE_LIMIT_SERVICE_TOKEN,
|
|
134
|
+
{
|
|
135
|
+
useClass: RateLimitService,
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
];
|
|
139
|
+
const exports = [
|
|
140
|
+
RATE_LIMIT_SERVICE_TOKEN,
|
|
141
|
+
RATE_LIMIT_OPTIONS_TOKEN,
|
|
142
|
+
RATE_LIMIT_STORAGE_TOKEN,
|
|
143
|
+
];
|
|
144
|
+
const result = {
|
|
145
|
+
module: TitanRateLimitModule_1,
|
|
146
|
+
imports: options.imports ?? [],
|
|
147
|
+
providers,
|
|
148
|
+
exports,
|
|
149
|
+
};
|
|
150
|
+
if (options.isGlobal) {
|
|
151
|
+
result.global = true;
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
TitanRateLimitModule = TitanRateLimitModule_1 = __decorate([
|
|
157
|
+
Module({})
|
|
158
|
+
], TitanRateLimitModule);
|
|
159
|
+
export { TitanRateLimitModule };
|
|
160
|
+
export const RateLimitModule = TitanRateLimitModule;
|
|
161
|
+
//# sourceMappingURL=ratelimit.module.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ratelimit.module.js","sourceRoot":"","sources":["../src/ratelimit.module.ts"],"names":[],"mappings":";;;;;;;AAQA,OAAO,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AAExD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACvF,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,m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M,eAAe,GAAG,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { IRateLimitService, IRateLimitStorage, IRateLimitResult, IRateLimitCheckOptions, IRateLimitStats, IRateLimitModuleOptions } from './ratelimit.types.js';
|
|
2
|
+
export declare class RateLimitExceededError extends Error {
|
|
3
|
+
readonly result: IRateLimitResult;
|
|
4
|
+
constructor(message: string, result: IRateLimitResult);
|
|
5
|
+
}
|
|
6
|
+
export declare class RateLimitService implements IRateLimitService {
|
|
7
|
+
private readonly storage;
|
|
8
|
+
private readonly options;
|
|
9
|
+
private readonly algorithm;
|
|
10
|
+
private readonly stats;
|
|
11
|
+
private readonly tierStats;
|
|
12
|
+
constructor(storage: IRateLimitStorage, options: IRateLimitModuleOptions);
|
|
13
|
+
private resolveTier;
|
|
14
|
+
private buildKey;
|
|
15
|
+
private updateStats;
|
|
16
|
+
check(options: IRateLimitCheckOptions): Promise<IRateLimitResult>;
|
|
17
|
+
consume(key: string, options?: Partial<IRateLimitCheckOptions>): Promise<IRateLimitResult>;
|
|
18
|
+
enforce(key: string, options?: Partial<IRateLimitCheckOptions>): Promise<void>;
|
|
19
|
+
getStatus(key: string, options?: Partial<IRateLimitCheckOptions>): Promise<IRateLimitResult>;
|
|
20
|
+
reset(key: string, tier?: string): Promise<void>;
|
|
21
|
+
getStats(): IRateLimitStats;
|
|
22
|
+
destroy(): void;
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=ratelimit.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ratelimit.service.d.ts","sourceRoot":"","sources":["../src/ratelimit.service.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EAExB,MAAM,sBAAsB,CAAC;AAuB9B,qBAAa,sBAAuB,SAAQ,KAAK;aAG7B,MAAM,EAAE,gBAAgB;gBADxC,OAAO,EAAE,MAAM,EACC,MAAM,EAAE,gBAAgB;CAK3C;AA0BD,qBACa,gBAAiB,YAAW,iBAAiB;IAQpB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAP5D,OAAO,CAAC,QAAQ,CAAC,OAAO,CACwE;IAChG,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAsB;IAChD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAkB;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmE;gBAGxC,OAAO,EAAE,iBAAiB,EAC3C,OAAO,EAAE,uBAAuB;IAsBpE,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,QAAQ;IAYhB,OAAO,CAAC,WAAW;IA2Bb,KAAK,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAyCjE,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAW1F,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAc9E,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAc5F,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUtD,QAAQ,IAAI,eAAe;IAc3B,OAAO,IAAI,IAAI;CAKhB"}
|
|
@@ -0,0 +1,154 @@
|
|
|
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 { Injectable, Inject } from '@omnitron-dev/titan/decorators';
|
|
14
|
+
import { RATE_LIMIT_OPTIONS_TOKEN, RATE_LIMIT_STORAGE_TOKEN, DEFAULT_RATE_LIMIT_PREFIX } from './ratelimit.tokens.js';
|
|
15
|
+
import { createAlgorithm } from './ratelimit.algorithms.js';
|
|
16
|
+
const DEFAULT_OPTIONS = {
|
|
17
|
+
enabled: true,
|
|
18
|
+
strategy: 'sliding-window',
|
|
19
|
+
keyPrefix: DEFAULT_RATE_LIMIT_PREFIX,
|
|
20
|
+
defaultLimit: 100,
|
|
21
|
+
defaultWindowMs: 60000,
|
|
22
|
+
burstLimit: 0,
|
|
23
|
+
tokenRefillRate: 100,
|
|
24
|
+
queueEnabled: false,
|
|
25
|
+
maxQueueSize: 1000,
|
|
26
|
+
queueTimeoutMs: 5000,
|
|
27
|
+
};
|
|
28
|
+
export class RateLimitExceededError extends Error {
|
|
29
|
+
constructor(message, result) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.result = result;
|
|
32
|
+
this.name = 'RateLimitExceededError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
let RateLimitService = class RateLimitService {
|
|
36
|
+
constructor(storage, options) {
|
|
37
|
+
this.storage = storage;
|
|
38
|
+
this.options = { ...DEFAULT_OPTIONS, ...options };
|
|
39
|
+
this.algorithm = createAlgorithm(this.options.strategy, {
|
|
40
|
+
refillRate: this.options.tokenRefillRate,
|
|
41
|
+
});
|
|
42
|
+
this.stats = {
|
|
43
|
+
totalChecks: 0,
|
|
44
|
+
totalAllowed: 0,
|
|
45
|
+
totalDenied: 0,
|
|
46
|
+
activeKeys: 0,
|
|
47
|
+
};
|
|
48
|
+
this.tierStats = new Map();
|
|
49
|
+
}
|
|
50
|
+
resolveTier(tierName) {
|
|
51
|
+
if (!tierName) {
|
|
52
|
+
return this.options.defaultTier;
|
|
53
|
+
}
|
|
54
|
+
return this.options.tiers?.[tierName] ?? this.options.defaultTier;
|
|
55
|
+
}
|
|
56
|
+
buildKey(key, tier) {
|
|
57
|
+
const parts = [this.options.keyPrefix];
|
|
58
|
+
if (tier) {
|
|
59
|
+
parts.push(tier);
|
|
60
|
+
}
|
|
61
|
+
parts.push(key);
|
|
62
|
+
return parts.join(':');
|
|
63
|
+
}
|
|
64
|
+
updateStats(allowed, tier) {
|
|
65
|
+
this.stats.totalChecks++;
|
|
66
|
+
if (allowed) {
|
|
67
|
+
this.stats.totalAllowed++;
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
this.stats.totalDenied++;
|
|
71
|
+
}
|
|
72
|
+
if (tier) {
|
|
73
|
+
let tierStat = this.tierStats.get(tier);
|
|
74
|
+
if (!tierStat) {
|
|
75
|
+
tierStat = { checks: 0, allowed: 0, denied: 0 };
|
|
76
|
+
this.tierStats.set(tier, tierStat);
|
|
77
|
+
}
|
|
78
|
+
tierStat.checks++;
|
|
79
|
+
if (allowed) {
|
|
80
|
+
tierStat.allowed++;
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
tierStat.denied++;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async check(options) {
|
|
88
|
+
if (!this.options.enabled) {
|
|
89
|
+
return {
|
|
90
|
+
allowed: true,
|
|
91
|
+
remaining: this.options.defaultLimit,
|
|
92
|
+
limit: this.options.defaultLimit,
|
|
93
|
+
resetAt: Date.now() + this.options.defaultWindowMs,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const tier = this.resolveTier(options.tier);
|
|
97
|
+
const limit = options.limit ?? tier?.limit ?? this.options.defaultLimit;
|
|
98
|
+
const windowMs = options.windowMs ?? tier?.windowMs ?? this.options.defaultWindowMs;
|
|
99
|
+
const burstLimit = tier?.burst ?? this.options.burstLimit;
|
|
100
|
+
const effectiveLimit = limit + burstLimit;
|
|
101
|
+
const storageKey = this.buildKey(options.key, options.tier);
|
|
102
|
+
const consume = options.consume ?? true;
|
|
103
|
+
const result = await this.algorithm.check(this.storage, storageKey, effectiveLimit, windowMs, consume);
|
|
104
|
+
if (options.tier) {
|
|
105
|
+
result.tier = options.tier;
|
|
106
|
+
}
|
|
107
|
+
this.updateStats(result.allowed, options.tier);
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
async consume(key, options) {
|
|
111
|
+
return this.check({
|
|
112
|
+
key,
|
|
113
|
+
consume: true,
|
|
114
|
+
...options,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async enforce(key, options) {
|
|
118
|
+
const result = await this.consume(key, options);
|
|
119
|
+
if (!result.allowed) {
|
|
120
|
+
throw new RateLimitExceededError(`Rate limit exceeded for key: ${key}. Retry after ${result.retryAfter}s`, result);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async getStatus(key, options) {
|
|
124
|
+
return this.check({
|
|
125
|
+
key,
|
|
126
|
+
consume: false,
|
|
127
|
+
...options,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
async reset(key, tier) {
|
|
131
|
+
const storageKey = this.buildKey(key, tier);
|
|
132
|
+
await this.algorithm.reset(this.storage, storageKey);
|
|
133
|
+
}
|
|
134
|
+
getStats() {
|
|
135
|
+
const stats = { ...this.stats };
|
|
136
|
+
if (this.tierStats.size > 0) {
|
|
137
|
+
stats.byTier = new Map(this.tierStats);
|
|
138
|
+
}
|
|
139
|
+
return stats;
|
|
140
|
+
}
|
|
141
|
+
destroy() {
|
|
142
|
+
if (this.storage.destroy) {
|
|
143
|
+
this.storage.destroy();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
RateLimitService = __decorate([
|
|
148
|
+
Injectable(),
|
|
149
|
+
__param(0, Inject(RATE_LIMIT_STORAGE_TOKEN)),
|
|
150
|
+
__param(1, Inject(RATE_LIMIT_OPTIONS_TOKEN)),
|
|
151
|
+
__metadata("design:paramtypes", [Object, Object])
|
|
152
|
+
], RateLimitService);
|
|
153
|
+
export { RateLimitService };
|
|
154
|
+
//# sourceMappingURL=ratelimit.service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ratelimit.service.js","sourceRoot":"","sources":["../src/ratelimit.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAQA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AAUpE,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAA4B,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAKtF,MAAM,eAAe,GAAkG;IACrH,OAAO,EAAE,IAAI;IACb,QAAQ,EAAE,gBAAgB;IAC1B,SAAS,EAAE,yBAAyB;IACpC,YAAY,EAAE,GAAG;IACjB,eAAe,EAAE,KAAK;IACtB,UAAU,EAAE,CAAC;IACb,eAAe,EAAE,GAAG;IACpB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,IAAI;IAClB,cAAc,EAAE,IAAI;CACrB,CAAC;AAKF,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YACE,OAAe,EACC,MAAwB;QAExC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,WAAM,GAAN,MAAM,CAAkB;QAGxC,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IAC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,CAAC,GAAW,EAAE,OAAyC;QACpE,OAAO,IAAI,CAAC,KAAK,CAAC;YAChB,GAAG;YACH,OAAO,EAAE,KAAK;YACd,GAAG,OAAO;SACX,CAAC,CAAC;IACL,CAAC;IAQD,KAAK,CAAC,KAAK,CAAC,GAAW,EAAE,IAAa;QACpC,MAAM,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC5C,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;IACvD,CAAC;IAOD,QAAQ;QACN,MAAM,KAAK,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;QAGhC,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YAC5B,KAAK,CAAC,MAAM,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACzC,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAKD,OAAO;QACL,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YACzB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACzB,CAAC;IACH,CAAC;CACF,CAAA;AA7LY,gBAAgB;IAD5B,UAAU,EAAE;IASR,WAAA,MAAM,CAAC,wBAAwB,CAAC,CAAA;IAChC,WAAA,MAAM,CAAC,wBAAwB,CAAC,CAAA;;GATxB,gBAAgB,CA6L5B"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { IRedisClient } from '@omnitron-dev/titan-redis';
|
|
2
|
+
import type { IRateLimitStorage } from './ratelimit.types.js';
|
|
3
|
+
import type { ILogger } from '@omnitron-dev/titan/types';
|
|
4
|
+
export declare class MemoryRateLimitStorage implements IRateLimitStorage {
|
|
5
|
+
private readonly store;
|
|
6
|
+
private readonly sortedSets;
|
|
7
|
+
private readonly cleanupInterval?;
|
|
8
|
+
private readonly maxKeys;
|
|
9
|
+
private static readonly MAX_KEYS;
|
|
10
|
+
constructor(options?: {
|
|
11
|
+
cleanupIntervalMs?: number;
|
|
12
|
+
maxKeys?: number;
|
|
13
|
+
});
|
|
14
|
+
increment(key: string, ttl?: number): Promise<number>;
|
|
15
|
+
get(key: string): Promise<number | null>;
|
|
16
|
+
set(key: string, value: number, ttl?: number): Promise<void>;
|
|
17
|
+
addToSortedSet(key: string, score: number, member: string, ttl?: number): Promise<void>;
|
|
18
|
+
removeFromSortedSetByScore(key: string, minScore: number, maxScore: number): Promise<void>;
|
|
19
|
+
countSortedSet(key: string): Promise<number>;
|
|
20
|
+
delete(key: string): Promise<void>;
|
|
21
|
+
ttl(key: string): Promise<number | null>;
|
|
22
|
+
private cleanup;
|
|
23
|
+
destroy(): void;
|
|
24
|
+
}
|
|
25
|
+
export declare class RedisRateLimitStorage implements IRateLimitStorage {
|
|
26
|
+
private readonly redis;
|
|
27
|
+
private readonly keyPrefix;
|
|
28
|
+
private readonly logger;
|
|
29
|
+
private redisAvailable;
|
|
30
|
+
constructor(redis: IRedisClient, options?: {
|
|
31
|
+
keyPrefix?: string;
|
|
32
|
+
logger?: ILogger;
|
|
33
|
+
});
|
|
34
|
+
private buildKey;
|
|
35
|
+
increment(key: string, ttl?: number): Promise<number>;
|
|
36
|
+
get(key: string): Promise<number | null>;
|
|
37
|
+
set(key: string, value: number, ttl?: number): Promise<void>;
|
|
38
|
+
addToSortedSet(key: string, score: number, member: string, ttl?: number): Promise<void>;
|
|
39
|
+
removeFromSortedSetByScore(key: string, minScore: number, maxScore: number): Promise<void>;
|
|
40
|
+
countSortedSet(key: string): Promise<number>;
|
|
41
|
+
delete(key: string): Promise<void>;
|
|
42
|
+
ttl(key: string): Promise<number | null>;
|
|
43
|
+
isAvailable(): boolean;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=ratelimit.storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ratelimit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GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA4BlC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IA0B9C,WAAW,IAAI,OAAO;CAGvB"}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { createNullLogger } from '@omnitron-dev/titan/types';
|
|
2
|
+
export class MemoryRateLimitStorage {
|
|
3
|
+
static { this.MAX_KEYS = 10000; }
|
|
4
|
+
constructor(options = {}) {
|
|
5
|
+
this.store = new Map();
|
|
6
|
+
this.sortedSets = new Map();
|
|
7
|
+
const cleanupIntervalMs = options.cleanupIntervalMs ?? 60000;
|
|
8
|
+
this.maxKeys = options.maxKeys ?? MemoryRateLimitStorage.MAX_KEYS;
|
|
9
|
+
this.cleanupInterval = setInterval(() => {
|
|
10
|
+
this.cleanup();
|
|
11
|
+
}, cleanupIntervalMs);
|
|
12
|
+
this.cleanupInterval.unref?.();
|
|
13
|
+
}
|
|
14
|
+
async increment(key, ttl) {
|
|
15
|
+
const entry = this.store.get(key);
|
|
16
|
+
const now = Date.now();
|
|
17
|
+
if (entry && entry.expiresAt && entry.expiresAt < now) {
|
|
18
|
+
this.store.delete(key);
|
|
19
|
+
}
|
|
20
|
+
const current = this.store.get(key);
|
|
21
|
+
const newValue = (current?.value ?? 0) + 1;
|
|
22
|
+
const expiresAt = ttl ? now + ttl : current?.expiresAt;
|
|
23
|
+
this.store.set(key, { value: newValue, expiresAt });
|
|
24
|
+
if (this.store.size > this.maxKeys) {
|
|
25
|
+
this.cleanup();
|
|
26
|
+
}
|
|
27
|
+
return newValue;
|
|
28
|
+
}
|
|
29
|
+
async get(key) {
|
|
30
|
+
const entry = this.store.get(key);
|
|
31
|
+
const now = Date.now();
|
|
32
|
+
if (!entry) {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
if (entry.expiresAt && entry.expiresAt < now) {
|
|
36
|
+
this.store.delete(key);
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
return entry.value;
|
|
40
|
+
}
|
|
41
|
+
async set(key, value, ttl) {
|
|
42
|
+
const expiresAt = ttl ? Date.now() + ttl : undefined;
|
|
43
|
+
this.store.set(key, { value, expiresAt });
|
|
44
|
+
if (this.store.size > this.maxKeys) {
|
|
45
|
+
this.cleanup();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async addToSortedSet(key, score, member, ttl) {
|
|
49
|
+
if (!this.sortedSets.has(key)) {
|
|
50
|
+
this.sortedSets.set(key, new Map());
|
|
51
|
+
}
|
|
52
|
+
const set = this.sortedSets.get(key);
|
|
53
|
+
set.set(member, score);
|
|
54
|
+
if (ttl) {
|
|
55
|
+
const expiresAt = Date.now() + ttl;
|
|
56
|
+
this.store.set(`${key}:ttl`, { value: expiresAt, expiresAt });
|
|
57
|
+
}
|
|
58
|
+
if (this.sortedSets.size > this.maxKeys) {
|
|
59
|
+
this.cleanup();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async removeFromSortedSetByScore(key, minScore, maxScore) {
|
|
63
|
+
const set = this.sortedSets.get(key);
|
|
64
|
+
if (!set) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
for (const [member, score] of set.entries()) {
|
|
68
|
+
if (score >= minScore && score <= maxScore) {
|
|
69
|
+
set.delete(member);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (set.size === 0) {
|
|
73
|
+
this.sortedSets.delete(key);
|
|
74
|
+
this.store.delete(`${key}:ttl`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async countSortedSet(key) {
|
|
78
|
+
const set = this.sortedSets.get(key);
|
|
79
|
+
return set ? set.size : 0;
|
|
80
|
+
}
|
|
81
|
+
async delete(key) {
|
|
82
|
+
this.store.delete(key);
|
|
83
|
+
this.sortedSets.delete(key);
|
|
84
|
+
this.store.delete(`${key}:ttl`);
|
|
85
|
+
}
|
|
86
|
+
async ttl(key) {
|
|
87
|
+
const entry = this.store.get(key);
|
|
88
|
+
if (!entry || !entry.expiresAt) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const ttlMs = entry.expiresAt - Date.now();
|
|
92
|
+
return Math.max(0, ttlMs);
|
|
93
|
+
}
|
|
94
|
+
cleanup() {
|
|
95
|
+
const now = Date.now();
|
|
96
|
+
for (const [key, entry] of this.store.entries()) {
|
|
97
|
+
if (entry.expiresAt && entry.expiresAt < now) {
|
|
98
|
+
this.store.delete(key);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
for (const key of this.sortedSets.keys()) {
|
|
102
|
+
const ttlEntry = this.store.get(`${key}:ttl`);
|
|
103
|
+
if (ttlEntry?.expiresAt && ttlEntry.expiresAt < now) {
|
|
104
|
+
this.sortedSets.delete(key);
|
|
105
|
+
this.store.delete(`${key}:ttl`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (this.store.size > this.maxKeys) {
|
|
109
|
+
const toRemove = this.store.size - Math.floor(this.maxKeys * 0.8);
|
|
110
|
+
const keys = Array.from(this.store.keys());
|
|
111
|
+
for (let i = 0; i < toRemove && i < keys.length; i++) {
|
|
112
|
+
const key = keys[i];
|
|
113
|
+
if (key) {
|
|
114
|
+
this.store.delete(key);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
destroy() {
|
|
120
|
+
if (this.cleanupInterval) {
|
|
121
|
+
clearInterval(this.cleanupInterval);
|
|
122
|
+
}
|
|
123
|
+
this.store.clear();
|
|
124
|
+
this.sortedSets.clear();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
export class RedisRateLimitStorage {
|
|
128
|
+
constructor(redis, options = {}) {
|
|
129
|
+
this.redis = redis;
|
|
130
|
+
this.redisAvailable = true;
|
|
131
|
+
this.keyPrefix = options.keyPrefix ?? 'ratelimit:';
|
|
132
|
+
this.logger = options.logger ?? createNullLogger();
|
|
133
|
+
this.redis.on('error', (error) => {
|
|
134
|
+
if (this.redisAvailable) {
|
|
135
|
+
this.logger.error({ error: error.message }, '[RedisRateLimitStorage] Redis connection error');
|
|
136
|
+
this.redisAvailable = false;
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
this.redis.on('ready', () => {
|
|
140
|
+
if (!this.redisAvailable) {
|
|
141
|
+
this.logger.info('[RedisRateLimitStorage] Redis connection restored');
|
|
142
|
+
this.redisAvailable = true;
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
buildKey(key) {
|
|
147
|
+
return `${this.keyPrefix}${key}`;
|
|
148
|
+
}
|
|
149
|
+
async increment(key, ttl) {
|
|
150
|
+
const fullKey = this.buildKey(key);
|
|
151
|
+
try {
|
|
152
|
+
if (ttl) {
|
|
153
|
+
const ttlSeconds = Math.ceil(ttl / 1000);
|
|
154
|
+
const pipeline = this.redis.pipeline();
|
|
155
|
+
pipeline.incr(fullKey);
|
|
156
|
+
pipeline.expire(fullKey, ttlSeconds);
|
|
157
|
+
const results = await pipeline.exec();
|
|
158
|
+
if (!results || !results[0] || results[0][0]) {
|
|
159
|
+
throw new Error(`Redis INCR failed: ${results?.[0]?.[0]}`);
|
|
160
|
+
}
|
|
161
|
+
return results[0][1];
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
return await this.redis.incr(fullKey);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
this.redisAvailable = false;
|
|
169
|
+
throw new Error(`Redis increment failed for key ${key}: ${error}`, { cause: error });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async get(key) {
|
|
173
|
+
const fullKey = this.buildKey(key);
|
|
174
|
+
try {
|
|
175
|
+
const value = await this.redis.get(fullKey);
|
|
176
|
+
return value ? parseInt(value, 10) : null;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
this.redisAvailable = false;
|
|
180
|
+
throw new Error(`Redis GET failed for key ${key}: ${error}`, { cause: error });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async set(key, value, ttl) {
|
|
184
|
+
const fullKey = this.buildKey(key);
|
|
185
|
+
try {
|
|
186
|
+
if (ttl) {
|
|
187
|
+
await this.redis.set(fullKey, value.toString(), 'PX', ttl);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
await this.redis.set(fullKey, value.toString());
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
this.redisAvailable = false;
|
|
195
|
+
throw new Error(`Redis SET failed for key ${key}: ${error}`, { cause: error });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
async addToSortedSet(key, score, member, ttl) {
|
|
199
|
+
const fullKey = this.buildKey(key);
|
|
200
|
+
try {
|
|
201
|
+
if (ttl) {
|
|
202
|
+
const ttlSeconds = Math.ceil(ttl / 1000);
|
|
203
|
+
const pipeline = this.redis.pipeline();
|
|
204
|
+
pipeline.zadd(fullKey, score, member);
|
|
205
|
+
pipeline.expire(fullKey, ttlSeconds);
|
|
206
|
+
const results = await pipeline.exec();
|
|
207
|
+
if (!results || results[0]?.[0]) {
|
|
208
|
+
throw new Error(`Redis ZADD failed: ${results?.[0]?.[0]}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
await this.redis.zadd(fullKey, score, member);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
this.redisAvailable = false;
|
|
217
|
+
throw new Error(`Redis ZADD failed for key ${key}: ${error}`, { cause: error });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async removeFromSortedSetByScore(key, minScore, maxScore) {
|
|
221
|
+
const fullKey = this.buildKey(key);
|
|
222
|
+
try {
|
|
223
|
+
await this.redis.zremrangebyscore(fullKey, minScore, maxScore);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
this.redisAvailable = false;
|
|
227
|
+
throw new Error(`Redis ZREMRANGEBYSCORE failed for key ${key}: ${error}`, { cause: error });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
async countSortedSet(key) {
|
|
231
|
+
const fullKey = this.buildKey(key);
|
|
232
|
+
try {
|
|
233
|
+
return await this.redis.zcard(fullKey);
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
this.redisAvailable = false;
|
|
237
|
+
throw new Error(`Redis ZCARD failed for key ${key}: ${error}`, { cause: error });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async delete(key) {
|
|
241
|
+
const fullKey = this.buildKey(key);
|
|
242
|
+
try {
|
|
243
|
+
await this.redis.del(fullKey);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
this.redisAvailable = false;
|
|
247
|
+
throw new Error(`Redis DEL failed for key ${key}: ${error}`, { cause: error });
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async ttl(key) {
|
|
251
|
+
const fullKey = this.buildKey(key);
|
|
252
|
+
try {
|
|
253
|
+
const ttl = await this.redis.pttl(fullKey);
|
|
254
|
+
if (ttl === -2 || ttl === -1) {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
return ttl;
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
this.redisAvailable = false;
|
|
261
|
+
throw new Error(`Redis PTTL failed for key ${key}: ${error}`, { cause: error });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
isAvailable() {
|
|
265
|
+
return this.redisAvailable && this.redis.status === 'ready';
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
//# sourceMappingURL=ratelimit.storage.js.map
|