fixed up ratelimiting

This commit is contained in:
Boki 2025-07-06 18:53:02 -04:00
parent a616c92656
commit a7146a3f57
15 changed files with 912 additions and 186 deletions

View file

@ -3,8 +3,9 @@ import type { CacheProvider } from '@stock-bot/cache';
import { createCache } from '@stock-bot/cache';
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import { getLogger } from '@stock-bot/logger';
import Redis from 'ioredis';
import { Queue, type QueueWorkerConfig } from './queue';
import { QueueRateLimiter } from './rate-limiter';
import { QueueRateLimiter } from './rate-limiter-new';
import { getFullQueueName, parseQueueName } from './service-utils';
import type {
GlobalStats,
@ -37,6 +38,7 @@ export class QueueManager {
private caches = new Map<string, CacheProvider>();
private rateLimiter?: QueueRateLimiter;
private redisConnection: ReturnType<typeof getRedisConnection>;
private ioredisConnection?: Redis;
private isShuttingDown = false;
private shutdownPromise: Promise<void> | null = null;
private config: QueueManagerConfig;
@ -65,16 +67,19 @@ export class QueueManager {
this.handlerRegistry = handlerRegistry;
this.logger = logger || getLogger('QueueManager');
this.redisConnection = getRedisConnection(config.redis);
// Create ioredis connection for rate limiter
this.ioredisConnection = new Redis({
host: config.redis.host,
port: config.redis.port,
password: config.redis.password,
db: config.redis.db || 0,
maxRetriesPerRequest: 3,
enableReadyCheck: true,
});
// Initialize rate limiter if rules are provided
if (config.rateLimitRules && config.rateLimitRules.length > 0) {
this.rateLimiter = new QueueRateLimiter(this.redisConnection, this.logger);
config.rateLimitRules.forEach(rule => {
if (this.rateLimiter) {
this.rateLimiter.addRule(rule);
}
});
}
// Rate limiter will be initialized when rules are added dynamically
// No longer initialized from config
// Auto-discover routes if enabled and registry provided
if (config.serviceName && config.autoDiscoverHandlers !== false && handlerRegistry) {
@ -153,6 +158,7 @@ export class QueueManager {
startWorker: workers > 0,
handlerRegistry: options.handlerRegistry || this.handlerRegistry,
serviceName: this.config.serviceName,
queueManager: this,
};
const queue = new Queue(
@ -169,16 +175,7 @@ export class QueueManager {
// Automatically initialize batch cache for the queue
this.initializeBatchCacheSync(queueName);
// Add queue-specific rate limit rules
if (this.rateLimiter && mergedOptions.rateLimitRules) {
mergedOptions.rateLimitRules.forEach(rule => {
// Ensure queue name is set for queue-specific rules
const ruleWithQueue = { ...rule, queueName };
if (this.rateLimiter) {
this.rateLimiter.addRule(ruleWithQueue);
}
});
}
// Rate limit rules are now added via addRateLimitRules after handlers are initialized
this.logger.info('Queue created with batch cache', {
queueName,
@ -303,23 +300,44 @@ export class QueueManager {
/**
* Add a rate limit rule
*/
addRateLimitRule(rule: RateLimitRule): void {
async addRateLimitRule(rule: RateLimitRule): Promise<void> {
if (!this.rateLimiter) {
this.rateLimiter = new QueueRateLimiter(this.redisConnection, this.logger);
if (!this.ioredisConnection) {
throw new Error('IoRedis connection not initialized');
}
this.rateLimiter = new QueueRateLimiter(this.ioredisConnection, this.logger);
}
this.rateLimiter.addRule(rule);
await this.rateLimiter.addRule(rule);
}
/**
* Check rate limits for a job
* Add multiple rate limit rules at once
*/
async addRateLimitRules(rules: RateLimitRule[]): Promise<void> {
if (!this.rateLimiter) {
if (!this.ioredisConnection) {
throw new Error('IoRedis connection not initialized');
}
this.rateLimiter = new QueueRateLimiter(this.ioredisConnection, this.logger);
}
await Promise.all(rules.map(rule => this.rateLimiter!.addRule(rule)));
this.logger.info('Added rate limit rules to QueueManager', {
ruleCount: rules.length,
rules,
});
}
/**
* Check rate limits for a job - overloaded to support both interfaces
*/
async checkRateLimit(
queueName: string,
handler: string,
operation: string
handlerOrQueueName: string,
operationOrHandler?: string,
operationIfThreeParams?: string
): Promise<{
allowed: boolean;
retryAfter?: number;
retryDelayMs?: number;
remainingPoints?: number;
appliedRule?: RateLimitRule;
}> {
@ -327,7 +345,27 @@ export class QueueManager {
return { allowed: true };
}
return await this.rateLimiter.checkLimit(queueName, handler, operation);
// Support both 2-parameter and 3-parameter calls
let handler: string;
let operation: string | undefined;
if (operationIfThreeParams !== undefined) {
// 3-parameter call: checkRateLimit(queueName, handler, operation)
handler = operationOrHandler!;
operation = operationIfThreeParams;
} else {
// 2-parameter call: checkRateLimit(handler, operation)
handler = handlerOrQueueName;
operation = operationOrHandler;
}
// The new rate limiter only needs handler and operation
const result = await this.rateLimiter.checkLimit(handler, operation);
return {
allowed: result.allowed,
retryDelayMs: result.retryDelayMs,
remainingPoints: result.remainingPoints,
};
}
/**
@ -342,7 +380,12 @@ export class QueueManager {
};
}
return await this.rateLimiter.getStatus(queueName, handler, operation);
// The new rate limiter only needs handler and operation
const status = await this.rateLimiter.getStatus(handler, operation);
return {
queueName,
...status
};
}
/**
@ -467,6 +510,16 @@ export class QueueManager {
});
await Promise.all(cacheShutdownPromises);
// Close ioredis connection
if (this.ioredisConnection) {
try {
await this.ioredisConnection.quit();
this.logger.debug('IoRedis connection closed');
} catch (error) {
this.logger.warn('Error closing ioredis connection', { error: (error as Error).message });
}
}
// Clear collections
this.queues.clear();