te.js 1.3.0 → 2.0.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.
Files changed (80) hide show
  1. package/.cursor/plans/ai_native_framework_features_5bb1a20a.plan.md +234 -0
  2. package/.cursor/plans/auto_error_fix_agent_e68979c5.plan.md +356 -0
  3. package/.cursor/plans/tejas_framework_test_suite_5e3c6fad.plan.md +168 -0
  4. package/.prettierignore +31 -0
  5. package/README.md +156 -14
  6. package/auto-docs/analysis/handler-analyzer.js +58 -0
  7. package/auto-docs/analysis/source-resolver.js +101 -0
  8. package/auto-docs/constants.js +37 -0
  9. package/auto-docs/index.js +146 -0
  10. package/auto-docs/llm/index.js +6 -0
  11. package/auto-docs/llm/parse.js +88 -0
  12. package/auto-docs/llm/prompts.js +222 -0
  13. package/auto-docs/llm/provider.js +187 -0
  14. package/auto-docs/openapi/endpoint-processor.js +277 -0
  15. package/auto-docs/openapi/generator.js +107 -0
  16. package/auto-docs/openapi/level3.js +131 -0
  17. package/auto-docs/openapi/spec-builders.js +244 -0
  18. package/auto-docs/ui/docs-ui.js +186 -0
  19. package/auto-docs/utils/logger.js +17 -0
  20. package/auto-docs/utils/strip-usage.js +10 -0
  21. package/cli/docs-command.js +315 -0
  22. package/cli/fly-command.js +71 -0
  23. package/cli/index.js +57 -0
  24. package/database/index.js +163 -5
  25. package/database/mongodb.js +146 -0
  26. package/database/redis.js +201 -0
  27. package/docs/README.md +36 -0
  28. package/docs/ammo.md +362 -0
  29. package/docs/api-reference.md +489 -0
  30. package/docs/auto-docs.md +215 -0
  31. package/docs/cli.md +152 -0
  32. package/docs/configuration.md +233 -0
  33. package/docs/database.md +391 -0
  34. package/docs/error-handling.md +417 -0
  35. package/docs/file-uploads.md +334 -0
  36. package/docs/getting-started.md +181 -0
  37. package/docs/middleware.md +356 -0
  38. package/docs/rate-limiting.md +394 -0
  39. package/docs/routing.md +302 -0
  40. package/example/API_OVERVIEW.md +77 -0
  41. package/example/README.md +155 -0
  42. package/example/index.js +27 -2
  43. package/example/openapi.json +390 -0
  44. package/example/package.json +5 -2
  45. package/example/services/cache.service.js +25 -0
  46. package/example/services/user.service.js +42 -0
  47. package/example/start-redis.js +2 -0
  48. package/example/targets/cache.target.js +35 -0
  49. package/example/targets/index.target.js +11 -2
  50. package/example/targets/users.target.js +60 -0
  51. package/example/tejas.config.json +13 -1
  52. package/package.json +20 -5
  53. package/rate-limit/algorithms/fixed-window.js +141 -0
  54. package/rate-limit/algorithms/sliding-window.js +147 -0
  55. package/rate-limit/algorithms/token-bucket.js +115 -0
  56. package/rate-limit/base.js +165 -0
  57. package/rate-limit/index.js +147 -0
  58. package/rate-limit/storage/base.js +104 -0
  59. package/rate-limit/storage/memory.js +102 -0
  60. package/rate-limit/storage/redis.js +88 -0
  61. package/server/ammo/body-parser.js +152 -25
  62. package/server/ammo/enhancer.js +6 -2
  63. package/server/ammo.js +356 -327
  64. package/server/endpoint.js +21 -0
  65. package/server/handler.js +113 -87
  66. package/server/target.js +50 -9
  67. package/server/targets/registry.js +111 -6
  68. package/te.js +363 -137
  69. package/tests/auto-docs/handler-analyzer.test.js +44 -0
  70. package/tests/auto-docs/openapi-generator.test.js +103 -0
  71. package/tests/auto-docs/parse.test.js +63 -0
  72. package/tests/auto-docs/source-resolver.test.js +58 -0
  73. package/tests/helpers/index.js +37 -0
  74. package/tests/helpers/mock-http.js +342 -0
  75. package/tests/helpers/test-utils.js +446 -0
  76. package/tests/setup.test.js +148 -0
  77. package/utils/configuration.js +13 -10
  78. package/vitest.config.js +54 -0
  79. package/database/mongo.js +0 -67
  80. package/example/targets/user/user.target.js +0 -17
@@ -0,0 +1,165 @@
1
+ import TejError from '../server/error.js';
2
+ import MemoryStorage from './storage/memory.js';
3
+ import RedisStorage from './storage/redis.js';
4
+ import dbManager from '../database/index.js';
5
+
6
+ /**
7
+ * Base rate limiter class implementing common functionality for rate limiting algorithms
8
+ *
9
+ * @abstract
10
+ * @class
11
+ * @description
12
+ * This is the base class for all rate limiting algorithms. It provides common configuration
13
+ * options and storage handling, while allowing specific algorithms to implement their own logic.
14
+ * Only one algorithm can be active per instance - the algorithm is determined by which options
15
+ * object is provided (tokenBucketConfig, slidingWindowConfig, or fixedWindowConfig).
16
+ *
17
+ * @example
18
+ * // Using with Redis storage and token bucket algorithm
19
+ * const limiter = new TokenBucketRateLimiter({
20
+ * maxRequests: 10,
21
+ * timeWindowSeconds: 60,
22
+ * store: 'redis',
23
+ * tokenBucketConfig: {
24
+ * refillRate: 0.5,
25
+ * burstSize: 15
26
+ * }
27
+ * });
28
+ */
29
+ class RateLimiter {
30
+ /**
31
+ * Creates a new rate limiter instance
32
+ *
33
+ * @param {Object} options - Configuration options for the rate limiter
34
+ * @param {number} [options.maxRequests=60] - Maximum number of requests allowed within the time window.
35
+ * This is the default rate limit cap that applies across all algorithms.
36
+ * For token bucket, this affects the default refill rate.
37
+ * @param {number} [options.timeWindowSeconds=60] - Time window in seconds for rate limiting.
38
+ * For fixed window, this is the window duration.
39
+ * For sliding window, this is the total time span considered.
40
+ * For token bucket, this affects the default refill rate calculation.
41
+ * @param {string} [options.keyPrefix='rl:'] - Prefix for storage keys. Useful when implementing different rate limit
42
+ * rules with different prefixes (e.g., 'rl:api:', 'rl:web:').
43
+ * @param {string} [options.store='memory'] - Storage backend to use ('memory' or 'redis')
44
+ * @param {Object} [options.tokenBucketConfig] - Token bucket algorithm specific options
45
+ * @param {Object} [options.slidingWindowConfig] - Sliding window algorithm specific options
46
+ * @param {Object} [options.fixedWindowConfig] - Fixed window algorithm specific options
47
+ */
48
+ constructor(options) {
49
+ // Common options for all algorithms
50
+ this.options = {
51
+ maxRequests: 60, // Maximum number of requests
52
+ timeWindowSeconds: 60, // Time window in seconds
53
+ keyPrefix: 'rl:', // Key prefix for storage
54
+ store: 'memory', // Default to memory storage
55
+ ...options,
56
+ };
57
+
58
+ // Only one algorithm can be active per instance
59
+ if (options?.tokenBucketConfig && options?.slidingWindowConfig) {
60
+ throw new TejError(
61
+ 400,
62
+ 'Cannot use multiple rate limiting algorithms. Choose either tokenBucketConfig or slidingWindowConfig or fixedWindowConfig.',
63
+ );
64
+ }
65
+
66
+ if (options?.tokenBucketConfig && options?.fixedWindowConfig) {
67
+ throw new TejError(
68
+ 500,
69
+ 'Cannot use multiple rate limiting algorithms. Choose either tokenBucketConfig or slidingWindowConfig or fixedWindowConfig.',
70
+ );
71
+ }
72
+
73
+ if (options?.slidingWindowConfig && options?.fixedWindowConfig) {
74
+ throw new TejError(
75
+ 500,
76
+ 'Cannot use multiple rate limiting algorithms. Choose either tokenBucketConfig or slidingWindowConfig or fixedWindowConfig.',
77
+ );
78
+ }
79
+
80
+ // Set default values for algorithm options if any are provided
81
+ this.tokenBucketOptions = options?.tokenBucketConfig
82
+ ? {
83
+ refillRate: this.options.maxRequests / this.options.timeWindowSeconds, // Tokens per second
84
+ burstSize: this.options.maxRequests, // Maximum token capacity
85
+ ...options.tokenBucketConfig,
86
+ }
87
+ : null;
88
+
89
+ this.slidingWindowOptions = options?.slidingWindowConfig
90
+ ? {
91
+ granularity: 1, // Time precision in seconds
92
+ weights: { current: 1, previous: 0 }, // Weights for current and previous windows
93
+ ...options.slidingWindowConfig,
94
+ }
95
+ : null;
96
+
97
+ this.fixedWindowOptions = options?.fixedWindowConfig
98
+ ? {
99
+ strictWindow: false, // If true, windows align with clock
100
+ ...options.fixedWindowConfig,
101
+ }
102
+ : null;
103
+
104
+ // Initialize storage based on store type
105
+ if (this.options.store === 'redis') {
106
+ if (!dbManager.hasConnection('redis')) {
107
+ throw new TejError(
108
+ 500,
109
+ 'Redis store selected but no Redis connection available. Call withRedis() first.',
110
+ );
111
+ }
112
+ const redisClient = dbManager.getConnection('redis');
113
+ this.storage = new RedisStorage(redisClient);
114
+ } else {
115
+ this.storage = new MemoryStorage();
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Generate storage key for the rate limit identifier
121
+ *
122
+ * @param {string} identifier - Unique identifier for the rate limit (e.g. IP address, user ID)
123
+ * @returns {string} The storage key with prefix
124
+ */
125
+ getKey(identifier) {
126
+ return `${this.options.keyPrefix}${identifier}`;
127
+ }
128
+
129
+ /**
130
+ * Abstract method for checking if request is allowed
131
+ * Must be implemented by concrete rate limiter classes
132
+ *
133
+ * @abstract
134
+ * @param {string} identifier - Unique identifier for the rate limit (e.g. IP address, user ID)
135
+ * @returns {Promise<Object>} Rate limit check result
136
+ * @returns {boolean} result.success - Whether the request is allowed
137
+ * @returns {number} result.remainingRequests - Number of requests remaining in the window
138
+ * @returns {number} result.resetTime - Unix timestamp when the rate limit resets
139
+ * @throws {Error} If not implemented by child class
140
+ */
141
+ async consume(identifier) {
142
+ throw new TejError(500, 'Not implemented');
143
+ }
144
+
145
+ /**
146
+ * Get algorithm-specific options for the specified algorithm type
147
+ *
148
+ * @param {string} type - Algorithm type ('tokenBucketConfig', 'slidingWindowConfig', or 'fixedWindowConfig')
149
+ * @returns {Object|null} The algorithm-specific options, or null if type not found
150
+ */
151
+ getAlgorithmOptions(type) {
152
+ switch (type) {
153
+ case 'token-bucket':
154
+ return this.tokenBucketOptions;
155
+ case 'sliding-window':
156
+ return this.slidingWindowOptions;
157
+ case 'fixed-window':
158
+ return this.fixedWindowOptions;
159
+ default:
160
+ return null;
161
+ }
162
+ }
163
+ }
164
+
165
+ export default RateLimiter;
@@ -0,0 +1,147 @@
1
+ import TejError from '../server/error.js';
2
+ import FixedWindowRateLimiter from './algorithms/fixed-window.js';
3
+ import SlidingWindowRateLimiter from './algorithms/sliding-window.js';
4
+ import TokenBucketRateLimiter from './algorithms/token-bucket.js';
5
+ import dbManager from '../database/index.js';
6
+
7
+ /**
8
+ * Creates a rate limiting middleware function with the specified algorithm and storage
9
+ *
10
+ * @param {Object} options - Configuration options for the rate limiter
11
+ * @param {number} options.maxRequests - Maximum number of requests allowed within the time window
12
+ * @param {number} options.timeWindowSeconds - Time window in seconds
13
+ * @param {string} [options.algorithm='sliding-window'] - Rate limiting algorithm to use:
14
+ * - 'token-bucket': Best for handling traffic bursts
15
+ * - 'sliding-window': Best for smooth rate limiting
16
+ * - 'fixed-window': Simplest approach
17
+ * @param {string} [options.store='memory'] - Storage backend to use:
18
+ * - 'memory': In-memory storage (default)
19
+ * - 'redis': Redis-based storage (requires global Redis config)
20
+ * @param {Object} [options.algorithmOptions] - Algorithm-specific options
21
+ * @param {Function} [options.keyGenerator] - Optional function to generate unique identifiers
22
+ * @param {Object} [options.headerFormat] - Rate limit header format configuration
23
+ * @param {string} [options.headerFormat.type='standard'] - Type of headers to use:
24
+ * - 'legacy': Use X-RateLimit-* headers
25
+ * - 'standard': Use RateLimit-* headers (draft 6+)
26
+ * - 'both': Use both legacy and standard headers
27
+ * @param {boolean} [options.headerFormat.draft7=false] - Whether to include draft 7 policy header
28
+ * @param {boolean} [options.headerFormat.draft8=false] - Whether to include draft 8 reset format
29
+ * @param {Function} [options.onRateLimited] - Optional callback when rate limit is exceeded
30
+ * @returns {Function} Middleware function for use with te.js
31
+ */
32
+ function rateLimiter(options) {
33
+ const {
34
+ algorithm = 'sliding-window',
35
+ store = 'memory',
36
+ keyGenerator = (ammo) => ammo.ip,
37
+ headerFormat = { type: 'standard' },
38
+ onRateLimited,
39
+ ...limiterOptions
40
+ } = options;
41
+
42
+ // Check Redis connectivity if Redis store is selected
43
+ if (store === 'redis' && !dbManager.hasConnection('redis', {})) {
44
+ throw new TejError(
45
+ 400,
46
+ 'Redis store selected but no Redis connection found. Please use withRedis() before using withRateLimit()',
47
+ );
48
+ }
49
+
50
+ // Map algorithm names to their config property names
51
+ const configMap = {
52
+ 'token-bucket': 'tokenBucketConfig',
53
+ 'sliding-window': 'slidingWindowConfig',
54
+ 'fixed-window': 'fixedWindowConfig',
55
+ };
56
+
57
+ const configKey = configMap[algorithm];
58
+ if (!configKey) {
59
+ throw new TejError(
60
+ 400,
61
+ `Invalid algorithm: ${algorithm}. Must be one of: ${Object.keys(configMap).join(', ')}`,
62
+ );
63
+ }
64
+
65
+ // Create algorithm-specific config
66
+ const limiterConfig = {
67
+ maxRequests: limiterOptions.maxRequests,
68
+ timeWindowSeconds: limiterOptions.timeWindowSeconds,
69
+ [configKey]: limiterOptions.algorithmOptions || {},
70
+ store, // Pass the store type to the limiter
71
+ };
72
+
73
+ // Create the appropriate limiter instance
74
+ let limiter;
75
+ switch (algorithm) {
76
+ case 'token-bucket':
77
+ limiter = new TokenBucketRateLimiter(limiterConfig);
78
+ break;
79
+ case 'sliding-window':
80
+ limiter = new SlidingWindowRateLimiter(limiterConfig);
81
+ break;
82
+ case 'fixed-window':
83
+ limiter = new FixedWindowRateLimiter(limiterConfig);
84
+ break;
85
+ default:
86
+ throw new TejError(400, 'Invalid algorithm specified');
87
+ }
88
+
89
+ // Helper to set headers based on format
90
+ const setRateLimitHeaders = (ammo, result) => {
91
+ const { type = 'standard', draft7 = false, draft8 = false } = headerFormat;
92
+ const useStandard = type === 'standard' || type === 'both';
93
+ const useLegacy = type === 'legacy' || type === 'both';
94
+
95
+ if (useStandard) {
96
+ // Standard headers (draft 6+)
97
+ ammo.res.setHeader('RateLimit-Limit', limiter.options.maxRequests);
98
+ ammo.res.setHeader('RateLimit-Remaining', result.remainingRequests);
99
+
100
+ // Draft 8 uses delta-seconds format
101
+ if (draft8) {
102
+ const resetDelta = result.resetTime - Math.floor(Date.now() / 1000);
103
+ ammo.res.setHeader('RateLimit-Reset', resetDelta);
104
+ } else {
105
+ ammo.res.setHeader('RateLimit-Reset', result.resetTime);
106
+ }
107
+
108
+ // Draft 7 added optional policy information
109
+ if (draft7) {
110
+ const policy = `${limiter.options.maxRequests};w=${limiter.options.timeWindowSeconds}`;
111
+ ammo.res.setHeader('RateLimit-Policy', policy);
112
+ }
113
+ }
114
+
115
+ if (useLegacy) {
116
+ // Legacy X- headers
117
+ ammo.res.setHeader('X-RateLimit-Limit', limiter.options.maxRequests);
118
+ ammo.res.setHeader('X-RateLimit-Remaining', result.remainingRequests);
119
+ ammo.res.setHeader('X-RateLimit-Reset', result.resetTime);
120
+ }
121
+
122
+ // Always set Retry-After on 429 responses
123
+ if (!result.success) {
124
+ const retryAfter = result.resetTime - Math.floor(Date.now() / 1000);
125
+ ammo.res.setHeader('Retry-After', retryAfter);
126
+ }
127
+ };
128
+
129
+ // Return middleware function
130
+ return async (ammo, next) => {
131
+ const key = keyGenerator(ammo);
132
+ const result = await limiter.consume(key);
133
+
134
+ setRateLimitHeaders(ammo, result);
135
+
136
+ if (!result.success) {
137
+ if (onRateLimited) {
138
+ return onRateLimited(ammo);
139
+ }
140
+ return ammo.throw(429, 'Too Many Requests');
141
+ }
142
+
143
+ await next();
144
+ };
145
+ }
146
+
147
+ export default rateLimiter;
@@ -0,0 +1,104 @@
1
+ import TejError from '../../server/error.js';
2
+
3
+ /**
4
+ * Abstract base class for rate limiter storage backends
5
+ *
6
+ * @abstract
7
+ * @description
8
+ * Defines the interface that all storage implementations must follow.
9
+ * Storage backends are responsible for persisting rate limit data and handling
10
+ * data expiration. Two implementations are provided out of the box:
11
+ * - MemoryStorage: For single-instance applications and testing
12
+ * - RedisStorage: For distributed applications
13
+ *
14
+ * Custom storage implementations can be created by extending this class
15
+ * and implementing all required methods.
16
+ *
17
+ * @example
18
+ * // Custom storage implementation
19
+ * class MyCustomStorage extends RateLimitStorage {
20
+ * async get(key) {
21
+ * // Implementation
22
+ * }
23
+ * async set(key, value, ttl) {
24
+ * // Implementation
25
+ * }
26
+ * async increment(key) {
27
+ * // Implementation
28
+ * }
29
+ * async delete(key) {
30
+ * // Implementation
31
+ * }
32
+ * }
33
+ */
34
+ class RateLimitStorage {
35
+ /**
36
+ * Retrieve rate limit data for a given key
37
+ *
38
+ * @abstract
39
+ * @param {string} key - The storage key to retrieve data for
40
+ * @returns {Promise<Object|null>} The stored data, or null if not found
41
+ * @throws {Error} If not implemented by child class
42
+ *
43
+ * @example
44
+ * const data = await storage.get('rl:127.0.0.1');
45
+ * if (data) {
46
+ * console.log('Found rate limit data:', data);
47
+ * }
48
+ */
49
+ async get(key) {
50
+ throw new TejError(500, 'Not implemented');
51
+ }
52
+
53
+ /**
54
+ * Store rate limit data with optional expiration
55
+ *
56
+ * @abstract
57
+ * @param {string} key - The storage key to store data under
58
+ * @param {Object} value - The data to store
59
+ * @param {number} ttl - Time-to-live in seconds
60
+ * @returns {Promise<void>}
61
+ * @throws {Error} If not implemented by child class
62
+ *
63
+ * @example
64
+ * await storage.set('rl:127.0.0.1', { counter: 5 }, 60);
65
+ */
66
+ async set(key, value, ttl) {
67
+ throw new TejError(500, 'Not implemented');
68
+ }
69
+
70
+ /**
71
+ * Increment a numeric value in storage
72
+ *
73
+ * @abstract
74
+ * @param {string} key - The storage key to increment
75
+ * @returns {Promise<number|null>} The new value after increment, or null if key not found
76
+ * @throws {Error} If not implemented by child class
77
+ *
78
+ * @example
79
+ * const newValue = await storage.increment('rl:127.0.0.1');
80
+ * if (newValue !== null) {
81
+ * console.log('New counter value:', newValue);
82
+ * }
83
+ */
84
+ async increment(key) {
85
+ throw new TejError(500, 'Not implemented');
86
+ }
87
+
88
+ /**
89
+ * Delete data for a given key
90
+ *
91
+ * @abstract
92
+ * @param {string} key - The storage key to delete
93
+ * @returns {Promise<void>}
94
+ * @throws {Error} If not implemented by child class
95
+ *
96
+ * @example
97
+ * await storage.delete('rl:127.0.0.1');
98
+ */
99
+ async delete(key) {
100
+ throw new TejError(500, 'Not implemented');
101
+ }
102
+ }
103
+
104
+ export default RateLimitStorage;
@@ -0,0 +1,102 @@
1
+ import RateLimitStorage from './base.js';
2
+
3
+ /**
4
+ * In-memory storage implementation for rate limiting
5
+ *
6
+ * @extends RateLimitStorage
7
+ * @description
8
+ * This storage backend uses a JavaScript Map to store rate limit data in memory.
9
+ * It's suitable for single-instance applications or testing environments, but not
10
+ * recommended for production use in distributed systems as data is not shared
11
+ * between instances.
12
+ *
13
+ * Key features:
14
+ * - Fast access (all data in memory)
15
+ * - Automatic cleanup of expired entries
16
+ * - No external dependencies
17
+ * - Data is lost on process restart
18
+ * - Not suitable for distributed systems
19
+ *
20
+ * @example
21
+ * import { TokenBucketRateLimiter, MemoryStorage } from 'te.js/rate-limit';
22
+ *
23
+ * // Memory storage is used by default if no redis config is provided
24
+ * const limiter = new TokenBucketRateLimiter({
25
+ * maxRequests: 60,
26
+ * timeWindowSeconds: 60,
27
+ * tokenBucketConfig: {
28
+ * refillRate: 1,
29
+ * burstSize: 60
30
+ * }
31
+ * });
32
+ *
33
+ * // Or create storage instance explicitly
34
+ * const storage = new MemoryStorage();
35
+ * await storage.set('key', { counter: 5 }, 60); // Store for 60 seconds
36
+ */
37
+ class MemoryStorage extends RateLimitStorage {
38
+ /**
39
+ * Initialize a new memory storage instance
40
+ */
41
+ constructor() {
42
+ super();
43
+ this.store = new Map();
44
+ }
45
+
46
+ /**
47
+ * Get stored data for a key, handling expiration
48
+ *
49
+ * @param {string} key - The storage key to retrieve data for
50
+ * @returns {Promise<Object|null>} The stored data, or null if not found or expired
51
+ */
52
+ async get(key) {
53
+ const item = this.store.get(key);
54
+ if (!item) return null;
55
+ if (item.expireAt < Date.now()) {
56
+ this.store.delete(key);
57
+ return null;
58
+ }
59
+ return item.value;
60
+ }
61
+
62
+ /**
63
+ * Store data with expiration time
64
+ *
65
+ * @param {string} key - The storage key
66
+ * @param {Object} value - The data to store
67
+ * @param {number} ttl - Time-to-live in seconds
68
+ * @returns {Promise<void>}
69
+ */
70
+ async set(key, value, ttl) {
71
+ this.store.set(key, {
72
+ value,
73
+ expireAt: Date.now() + ttl * 1000
74
+ });
75
+ }
76
+
77
+ /**
78
+ * Increment a numeric value in storage
79
+ *
80
+ * @param {string} key - The storage key to increment
81
+ * @returns {Promise<number|null>} New value after increment, or null if key not found/expired
82
+ */
83
+ async increment(key) {
84
+ const item = await this.get(key);
85
+ if (!item) return null;
86
+ item.counter = (item.counter || 0) + 1;
87
+ await this.set(key, item, (item.expireAt - Date.now()) / 1000);
88
+ return item.counter;
89
+ }
90
+
91
+ /**
92
+ * Delete data for a key
93
+ *
94
+ * @param {string} key - The storage key to delete
95
+ * @returns {Promise<void>}
96
+ */
97
+ async delete(key) {
98
+ this.store.delete(key);
99
+ }
100
+ }
101
+
102
+ export default MemoryStorage;
@@ -0,0 +1,88 @@
1
+ import RateLimitStorage from './base.js';
2
+
3
+ /**
4
+ * Redis storage implementation for rate limiting
5
+ *
6
+ * @extends RateLimitStorage
7
+ * @description
8
+ * This storage backend uses Redis for distributed rate limiting across multiple application instances.
9
+ * It's the recommended storage backend for production use in distributed systems as it provides
10
+ * reliable rate limiting across all application instances.
11
+ *
12
+ * Key features:
13
+ * - Distributed rate limiting (works across multiple app instances)
14
+ * - Atomic operations for race condition prevention
15
+ * - Automatic key expiration using Redis TTL
16
+ * - Persistence options available through Redis configuration
17
+ * - Clustering support for high availability
18
+ *
19
+ * @example
20
+ * import { TokenBucketRateLimiter } from 'te.js/rate-limit';
21
+ *
22
+ * // Use Redis storage for distributed rate limiting
23
+ * const limiter = new TokenBucketRateLimiter({
24
+ * maxRequests: 100,
25
+ * timeWindowSeconds: 60,
26
+ * store: 'redis', // Use Redis storage
27
+ * tokenBucketConfig: {
28
+ * refillRate: 2,
29
+ * burstSize: 100
30
+ * }
31
+ * });
32
+ */
33
+ class RedisStorage extends RateLimitStorage {
34
+ /**
35
+ * Initialize Redis storage with client
36
+ *
37
+ * @param {RedisClient} client - Connected Redis client instance
38
+ */
39
+ constructor(client) {
40
+ super();
41
+ this.client = client;
42
+ }
43
+
44
+ /**
45
+ * Get stored data for a key
46
+ *
47
+ * @param {string} key - The storage key to retrieve
48
+ * @returns {Promise<Object|null>} Stored value if found, null otherwise
49
+ */
50
+ async get(key) {
51
+ const value = await this.client.get(key);
52
+ return value ? JSON.parse(value) : null;
53
+ }
54
+
55
+ /**
56
+ * Store data with expiration time
57
+ *
58
+ * @param {string} key - The storage key
59
+ * @param {Object} value - The data to store
60
+ * @param {number} ttl - Time-to-live in seconds
61
+ * @returns {Promise<void>}
62
+ */
63
+ async set(key, value, ttl) {
64
+ await this.client.set(key, JSON.stringify(value), { EX: ttl });
65
+ }
66
+
67
+ /**
68
+ * Increment a counter value atomically
69
+ *
70
+ * @param {string} key - The storage key to increment
71
+ * @returns {Promise<number>} New value after increment
72
+ */
73
+ async increment(key) {
74
+ return await this.client.incr(key);
75
+ }
76
+
77
+ /**
78
+ * Delete data for a key
79
+ *
80
+ * @param {string} key - The storage key to delete
81
+ * @returns {Promise<void>}
82
+ */
83
+ async delete(key) {
84
+ await this.client.del(key);
85
+ }
86
+ }
87
+
88
+ export default RedisStorage;