commit 2 refactor

This commit is contained in:
Boki 2026-10-20 14:35:45 -04:00
parent 588f666943
commit 32e43c9243
310 changed files with 33318 additions and 31189 deletions

View file

@ -1,4 +1,4 @@
import { QueueManager } from './queue-manager';
import type { QueueManager } from './queue-manager';
import type { BatchJobData, BatchResult, JobData, ProcessOptions } from './types';
/**
@ -9,7 +9,7 @@ export async function processItems<T>(
items: T[],
queueName: string,
options: ProcessOptions,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<BatchResult> {
const queue = queueManager.getQueue(queueName);
const logger = queue.createChildLogger('batch-processor', {
@ -61,7 +61,7 @@ async function processDirect<T>(
items: T[],
queueName: string,
options: ProcessOptions,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<Omit<BatchResult, 'duration'>> {
const queue = queueManager.getQueue(queueName);
const logger = queue.createChildLogger('batch-direct', {
@ -109,7 +109,7 @@ async function processBatched<T>(
items: T[],
queueName: string,
options: ProcessOptions,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<Omit<BatchResult, 'duration'>> {
const queue = queueManager.getQueue(queueName);
const logger = queue.createChildLogger('batch-batched', {
@ -174,7 +174,7 @@ async function processBatched<T>(
export async function processBatchJob(
jobData: BatchJobData,
queueName: string,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<unknown> {
const queue = queueManager.getQueue(queueName);
const logger = queue.createChildLogger('batch-job', {
@ -258,7 +258,7 @@ async function storeItems<T>(
items: T[],
queueName: string,
options: ProcessOptions,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<string> {
const cache = queueManager.getCache(queueName);
const payloadKey = `payload:${Date.now()}:${Math.random().toString(36).substr(2, 9)}`;
@ -284,7 +284,7 @@ async function storeItems<T>(
async function loadPayload<T>(
key: string,
queueName: string,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<{
items: T[];
options: {
@ -311,7 +311,7 @@ async function loadPayload<T>(
async function cleanupPayload(
key: string,
queueName: string,
queueManager: QueueManager
queueManager: Pick<QueueManager, keyof QueueManager>
): Promise<void> {
const cache = queueManager.getCache(queueName);
await cache.del(key);
@ -320,7 +320,7 @@ async function cleanupPayload(
async function addJobsInChunks(
queueName: string,
jobs: Array<{ name: string; data: JobData; opts?: Record<string, unknown> }>,
queueManager: QueueManager,
queueManager: Pick<QueueManager, keyof QueueManager>,
chunkSize = 100
): Promise<unknown[]> {
const queue = queueManager.getQueue(queueName);

View file

@ -1,10 +1,11 @@
import { Queue as BullQueue, type Job } from 'bullmq';
import Redis from 'ioredis';
import type { CacheProvider } from '@stock-bot/cache';
import { createCache } from '@stock-bot/cache';
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import { defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { LoggerLike as Logger } from '@stock-bot/logger';
import Redis from 'ioredis';
import { Queue, type QueueWorkerConfig } from './queue';
import { QueueRateLimiter } from './rate-limiter';
import { getFullQueueName, parseQueueName } from './service-utils';
@ -58,7 +59,7 @@ 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,
@ -311,8 +312,8 @@ export class QueueManager {
}
this.rateLimiter = new QueueRateLimiter(this.ioredisConnection, this.logger);
}
await Promise.all(rules.map(rule => this.rateLimiter!.addRule(rule)));
await Promise.all(rules.map(rule => defined(this.rateLimiter).addRule(rule)));
this.logger.info('Added rate limit rules to QueueManager', {
ruleCount: rules.length,
rules,
@ -339,10 +340,10 @@ export class QueueManager {
// 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!;
handler = defined(operationOrHandler);
operation = operationIfThreeParams;
} else {
// 2-parameter call: checkRateLimit(handler, operation)
@ -375,7 +376,7 @@ export class QueueManager {
const status = await this.rateLimiter.getStatus(handler, operation);
return {
queueName,
...status
...status,
};
}
@ -478,8 +479,8 @@ export class QueueManager {
try {
// Add timeout to queue.close() to prevent hanging
const closePromise = queue.close();
const timeoutPromise = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('Queue close timeout')), 5000) // 5 second timeout per queue
const timeoutPromise = new Promise<never>(
(_, reject) => setTimeout(() => reject(new Error('Queue close timeout')), 5000) // 5 second timeout per queue
);
await Promise.race([closePromise, timeoutPromise]);
@ -501,7 +502,7 @@ export class QueueManager {
});
await Promise.all(cacheShutdownPromises);
// Close ioredis connection
if (this.ioredisConnection) {
try {
@ -699,7 +700,7 @@ export class QueueManager {
});
this.producerQueues.set(queueName, queue);
}
return this.producerQueues.get(queueName)!;
return defined(this.producerQueues.get(queueName));
}
/**
@ -724,7 +725,7 @@ export class QueueManager {
service: ownerService,
handler: handlerName,
db: 0, // All queues in DB 0
operations: metadata.operations.map((op: any) => op.name),
operations: metadata.operations.map(op => op.name),
});
this.logger.trace('Discovered queue route', {

View file

@ -1,7 +1,8 @@
import { Queue as BullQueue, QueueEvents, Worker, type Job } from 'bullmq';
import type { LoggerLike as Logger } from '@stock-bot/logger';
// Handler registry will be injected
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import type { LoggerLike as Logger } from '@stock-bot/logger';
import type { QueueManager } from './queue-manager';
import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types';
import { getRedisConnection } from './utils';
@ -11,7 +12,7 @@ export interface QueueWorkerConfig {
startWorker?: boolean;
handlerRegistry?: HandlerRegistry;
serviceName?: string;
queueManager?: any; // Reference to queue manager for rate limiting
queueManager?: Pick<QueueManager, 'checkRateLimit'>; // Reference to queue manager for rate limiting
}
/**
@ -27,7 +28,7 @@ export class Queue {
private readonly logger: Logger;
private readonly handlerRegistry?: HandlerRegistry;
private serviceName?: string;
private queueManager?: any;
private queueManager?: Pick<QueueManager, 'checkRateLimit'>;
constructor(
queueName: string,
@ -274,26 +275,26 @@ export class Queue {
const workerClosePromises = this.workers.map(async (worker, idx) => {
try {
const closePromise = worker.close();
const timeoutPromise = new Promise<void>((resolve) => {
const timeoutPromise = new Promise<void>(resolve => {
setTimeout(() => {
this.logger.warn('Worker close timeout, forcing closure', {
queueName: this.queueName,
workerId: idx
this.logger.warn('Worker close timeout, forcing closure', {
queueName: this.queueName,
workerId: idx,
});
resolve();
}, 2000); // 2 second timeout per worker
});
await Promise.race([closePromise, timeoutPromise]);
} catch (error) {
this.logger.warn('Error closing worker', {
queueName: this.queueName,
workerId: idx,
error
this.logger.warn('Error closing worker', {
queueName: this.queueName,
workerId: idx,
error,
});
}
});
await Promise.all(workerClosePromises);
this.workers = [];
this.logger.debug('Workers closed', { queueName: this.queueName });
@ -337,19 +338,23 @@ export class Queue {
const connection = getRedisConnection(this.redisConfig);
for (let i = 0; i < workerCount; i++) {
const worker: Worker = new Worker(this.queueName, async (job: Job) => this.processJob(job, worker), {
connection,
concurrency,
maxStalledCount: 3,
stalledInterval: 30000,
// Add a name to identify the worker
name: `${this.serviceName || 'unknown'}_worker_${i}`,
// Enable manual rate limiting
limiter: {
max: 100,
duration: 1,
},
});
const worker: Worker = new Worker(
this.queueName,
async (job: Job) => this.processJob(job, worker),
{
connection,
concurrency,
maxStalledCount: 3,
stalledInterval: 30000,
// Add a name to identify the worker
name: `${this.serviceName || 'unknown'}_worker_${i}`,
// Enable manual rate limiting
limiter: {
max: 100,
duration: 1,
},
}
);
this.logger.info(`Starting worker ${i + 1}/${workerCount} for queue`, {
queueName: this.queueName,
@ -414,7 +419,7 @@ export class Queue {
jobName: job.name,
queueName: this.queueName,
hasQueueManager: !!this.queueManager,
jobData: job.data
jobData: job.data,
});
const { handler, operation, payload }: JobData = job.data;
@ -436,19 +441,16 @@ export class Queue {
this.logger.debug('Checking rate limits', {
handler,
operation,
queueManager: this.queueManager.constructor.name
queueManager: this.queueManager.constructor.name,
});
const rateLimitCheck = await this.queueManager.checkRateLimit(
handler,
operation
);
const rateLimitCheck = await this.queueManager.checkRateLimit(handler, operation);
this.logger.debug('Rate limit check result', {
allowed: rateLimitCheck.allowed,
retryDelayMs: rateLimitCheck.retryDelayMs,
handler,
operation
operation,
});
if (!rateLimitCheck.allowed) {
@ -456,7 +458,7 @@ export class Queue {
id: job.id,
handler,
operation,
retryDelayMs: rateLimitCheck.retryDelayMs
retryDelayMs: rateLimitCheck.retryDelayMs,
});
// Use BullMQ's manual rate limiting
@ -493,10 +495,13 @@ export class Queue {
return result;
} catch (error) {
// Re-throw RateLimitError without logging as error
if (error === Worker.RateLimitError() || (error as any).name === 'RateLimitError') {
if (
error === Worker.RateLimitError() ||
(error instanceof Error ? error.name : undefined) === 'RateLimitError'
) {
throw error;
}
this.logger.error('Job processing failed', {
id: job.id,
handler,
@ -544,7 +549,7 @@ export class Queue {
* Get active workers from BullMQ
* This uses BullMQ's built-in worker tracking
*/
async getActiveWorkers(): Promise<any[]> {
async getActiveWorkers(): ReturnType<BullQueue['getWorkers']> {
try {
const workers = await this.bullQueue.getWorkers();
return workers;

View file

@ -1,380 +1,403 @@
import type Redis from 'ioredis';
import { RateLimiterRedis, type IRateLimiterRedisOptions } from 'rate-limiter-flexible';
import type { RateLimitRule, RateLimitWindow } from './types';
// Logger interface for type safety
interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
}
interface RateLimiterEntry {
windows: Array<{
limiter: RateLimiterRedis;
window: RateLimitWindow;
}>;
cost: number;
}
export interface RateLimitResult {
allowed: boolean;
retryDelayMs?: number;
remainingPoints?: number;
cost?: number;
}
/**
* Enhanced rate limiter that supports:
* - Multiple time windows per rule
* - Variable costs per operation
* - Hierarchical rules (operation > handler > queue > global)
*/
export class QueueRateLimiter {
private limiters = new Map<string, RateLimiterEntry>();
private readonly logger: Logger;
constructor(
private redisClient: Redis,
logger?: Logger
) {
this.logger = logger || console;
this.logger.debug('QueueRateLimiter initialized', {
redisClientType: typeof this.redisClient,
redisClientKeys: this.redisClient ? Object.keys(this.redisClient).slice(0, 10) : [],
hasClient: !!this.redisClient,
isIoRedis: this.redisClient && this.redisClient.constructor.name === 'Redis'
});
}
/**
* Add a rate limit rule
*/
async addRule(rule: RateLimitRule): Promise<void> {
const key = this.getRuleKey(rule);
// Create array of limiters for each window
const windows: RateLimiterEntry['windows'] = [];
const limits = rule.config.limits || [];
this.logger.debug('Adding rate limit rule', {
key,
rule,
windowCount: limits.length,
cost: rule.config.cost
});
for (const window of limits) {
const limiterOptions: IRateLimiterRedisOptions = {
storeClient: this.redisClient as any,
keyPrefix: `rate_limit:${key}:${window.duration}s`,
points: window.points,
duration: window.duration,
blockDuration: window.blockDuration || 0,
};
this.logger.debug('Creating RateLimiterRedis', {
keyPrefix: limiterOptions.keyPrefix,
points: limiterOptions.points,
duration: limiterOptions.duration,
hasRedisClient: !!this.redisClient,
redisClientType: typeof this.redisClient
});
try {
const limiter = new RateLimiterRedis(limiterOptions);
windows.push({ limiter, window });
} catch (error) {
this.logger.error('Failed to create RateLimiterRedis', { error, limiterOptions });
throw error;
}
}
// Default cost: handler defines the pool (no default cost), operations default to 1
const defaultCost = rule.level === 'operation' ? 1 : 0;
this.limiters.set(key, {
windows,
cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost
});
this.logger.debug('Rate limit rule added', {
key,
level: rule.level,
handler: rule.handler,
operation: rule.operation,
windows: windows.length,
cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost
});
}
/**
* Check if an operation is allowed based on rate limits
*/
async checkLimit(handler: string, operation?: string): Promise<RateLimitResult> {
// Build keys to check from most specific to least specific
const keysToCheck: string[] = [];
if (operation) {
keysToCheck.push(this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule));
}
keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule));
this.logger.debug('Checking rate limits', {
handler,
operation,
keysToCheck,
availableKeys: Array.from(this.limiters.keys())
});
// First, find the cost from the most specific rule
let cost = 1; // Default cost
for (const key of keysToCheck) {
const entry = this.limiters.get(key);
if (entry && entry.cost !== undefined) {
cost = entry.cost;
this.logger.debug(`[RateLimiter] Using cost ${cost} from rule: ${key}`);
this.logger.debug('Using cost from rule', {
key,
cost,
handler,
operation
});
break;
}
}
// Then find the rate limit windows from the first matching rule that has windows
let windowEntry: RateLimiterEntry | undefined;
let appliedKey: string | undefined;
for (const key of keysToCheck) {
const entry = this.limiters.get(key);
if (entry && entry.windows.length > 0) {
windowEntry = entry;
appliedKey = key;
break;
}
}
if (!windowEntry) {
this.logger.debug('No rate limit rules found', {
handler,
operation
});
return { allowed: true };
}
this.logger.debug(`[RateLimiter] Applying rate limit rule: ${appliedKey}`, {
appliedKey,
windowCount: windowEntry.windows.length,
cost,
handler,
operation
});
// Check all windows with the determined cost
let maxRetryDelayMs = 0;
this.logger.debug('Checking rate limit windows', {
handler,
operation,
cost,
windowCount: windowEntry.windows.length
});
// Special handling for 0-cost operations - they should always pass
if (cost === 0) {
this.logger.debug(`[RateLimiter] Zero-cost operation ${handler}:${operation || 'N/A'} - allowing without consuming points`);
return {
allowed: true,
cost: 0
};
}
for (const { limiter, window } of windowEntry.windows) {
// For handler-level rate limits, all operations share the same pool
// Use the applied key to determine the consumer key
const consumerKey = appliedKey?.startsWith('handler:') ? handler :
(operation ? `${handler}:${operation}` : handler);
try {
// First check current state without consuming
const currentState = await limiter.get(consumerKey);
const now = Date.now();
this.logger.debug(`[RateLimiter] Current state before consume:`, {
handler,
operation,
consumerKey,
cost,
window: `${window.points}pts/${window.duration}s`,
consumedPoints: currentState?.consumedPoints || 0,
remainingPoints: currentState?.remainingPoints ?? window.points,
msBeforeNext: currentState?.msBeforeNext || 0,
currentTime: new Date(now).toISOString(),
resetTime: currentState?.msBeforeNext ? new Date(now + currentState.msBeforeNext).toISOString() : 'N/A',
hasState: !!currentState,
stateDetails: currentState ? JSON.stringify(currentState) : 'no state'
});
// Try to consume points
this.logger.debug(`[RateLimiter] Attempting to consume ${cost} points for ${consumerKey}`);
const result = await limiter.consume(consumerKey, cost);
this.logger.debug(`[RateLimiter] Successfully consumed ${cost} points, ${result.remainingPoints} remaining`);
this.logger.debug('Consumed points successfully', {
handler,
operation,
consumerKey,
window: `${window.points}pts/${window.duration}s`,
cost,
remainingPoints: result.remainingPoints,
msBeforeNext: result.msBeforeNext
});
this.logger.trace('Rate limit window passed', {
handler,
operation,
window: `${window.points}pts/${window.duration}s`,
cost
});
} catch (rejRes: any) {
// Rate limit exceeded for this window
const retryDelayMs = rejRes.msBeforeNext || window.blockDuration || 1000;
maxRetryDelayMs = Math.max(maxRetryDelayMs, retryDelayMs);
this.logger.debug(`[RateLimiter] RATE LIMIT HIT: ${consumerKey} - ${cost} points rejected, retry in ${retryDelayMs}ms`, {
consumedPoints: rejRes.consumedPoints || 0,
remainingPoints: rejRes.remainingPoints || 0,
totalPoints: rejRes.totalPoints || window.points,
isFirstInDuration: rejRes.isFirstInDuration || false,
msBeforeNext: rejRes.msBeforeNext || 0,
retryDelayMs
});
this.logger.trace('Rate limit exceeded', {
handler,
operation,
consumerKey,
window: `${window.points}pts/${window.duration}s`,
cost,
remainingPoints: rejRes.remainingPoints || 0,
retryDelayMs: maxRetryDelayMs
});
return {
allowed: false,
retryDelayMs: maxRetryDelayMs,
remainingPoints: rejRes.remainingPoints || 0,
cost
};
}
}
// All windows passed
return {
allowed: true,
cost
};
}
/**
* Get rule key for storing rate limiter
*/
private getRuleKey(rule: RateLimitRule): string {
switch (rule.level) {
case 'global':
return 'global';
case 'queue':
return `queue:${rule.queueName || 'default'}`;
case 'handler':
return `handler:${rule.handler}`;
case 'operation':
return `operation:${rule.handler}:${rule.operation}`;
default:
return rule.level;
}
}
/**
* Get current rate limit status
*/
async getStatus(handler: string, operation?: string): Promise<any> {
// Build keys to check from most specific to least specific
const keysToCheck: string[] = [];
if (operation) {
keysToCheck.push(this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule));
}
keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule));
// Find the first matching rule
let entry: RateLimiterEntry | undefined;
let appliedKey: string | undefined;
for (const key of keysToCheck) {
entry = this.limiters.get(key);
if (entry) {
appliedKey = key;
break;
}
}
if (!entry) {
return {
handler,
operation,
hasRule: false
};
}
// Get status for all windows
const consumerKey = operation ? `${handler}:${operation}` : handler;
const windows = await Promise.all(
entry.windows.map(async ({ limiter, window }) => {
const result = await limiter.get(consumerKey);
return {
points: window.points,
duration: window.duration,
remaining: result?.remainingPoints ?? window.points,
resetIn: result?.msBeforeNext ?? 0,
};
})
);
return {
handler,
operation,
hasRule: true,
appliedKey,
cost: entry.cost,
windows
};
}
/**
* Reset rate limits for a specific handler/operation
*/
async reset(handler: string, operation?: string): Promise<void> {
const keysToCheck: string[] = [];
if (operation) {
keysToCheck.push(this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule));
}
keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule));
for (const key of keysToCheck) {
const entry = this.limiters.get(key);
if (entry) {
await Promise.all(
entry.windows.map(({ limiter }) => limiter.delete(handler))
);
}
}
this.logger.debug('Rate limits reset', { handler, operation });
}
}
import type Redis from 'ioredis';
import {
RateLimiterRedis,
RateLimiterRes,
type IRateLimiterRedisOptions,
} from 'rate-limiter-flexible';
import type { RateLimitRule, RateLimitWindow } from './types';
// Logger interface for type safety
interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
}
interface RateLimiterEntry {
windows: Array<{
limiter: RateLimiterRedis;
window: RateLimitWindow;
}>;
cost: number;
}
export interface RateLimitResult {
allowed: boolean;
retryDelayMs?: number;
remainingPoints?: number;
cost?: number;
}
/**
* Enhanced rate limiter that supports:
* - Multiple time windows per rule
* - Variable costs per operation
* - Hierarchical rules (operation > handler > queue > global)
*/
export class QueueRateLimiter {
private limiters = new Map<string, RateLimiterEntry>();
private readonly logger: Logger;
constructor(
private redisClient: Redis,
logger?: Logger
) {
this.logger = logger || console;
this.logger.debug('QueueRateLimiter initialized', {
redisClientType: typeof this.redisClient,
redisClientKeys: this.redisClient ? Object.keys(this.redisClient).slice(0, 10) : [],
hasClient: !!this.redisClient,
isIoRedis: this.redisClient && this.redisClient.constructor.name === 'Redis',
});
}
/**
* Add a rate limit rule
*/
async addRule(rule: RateLimitRule): Promise<void> {
const key = this.getRuleKey(rule);
// Create array of limiters for each window
const windows: RateLimiterEntry['windows'] = [];
const limits = rule.config.limits || [];
this.logger.debug('Adding rate limit rule', {
key,
rule,
windowCount: limits.length,
cost: rule.config.cost,
});
for (const window of limits) {
const limiterOptions: IRateLimiterRedisOptions = {
storeClient: this.redisClient,
keyPrefix: `rate_limit:${key}:${window.duration}s`,
points: window.points,
duration: window.duration,
blockDuration: window.blockDuration || 0,
};
this.logger.debug('Creating RateLimiterRedis', {
keyPrefix: limiterOptions.keyPrefix,
points: limiterOptions.points,
duration: limiterOptions.duration,
hasRedisClient: !!this.redisClient,
redisClientType: typeof this.redisClient,
});
try {
const limiter = new RateLimiterRedis(limiterOptions);
windows.push({ limiter, window });
} catch (error) {
this.logger.error('Failed to create RateLimiterRedis', { error, limiterOptions });
throw error;
}
}
// Default cost: handler defines the pool (no default cost), operations default to 1
const defaultCost = rule.level === 'operation' ? 1 : 0;
this.limiters.set(key, {
windows,
cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost,
});
this.logger.debug('Rate limit rule added', {
key,
level: rule.level,
handler: rule.handler,
operation: rule.operation,
windows: windows.length,
cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost,
});
}
/**
* Check if an operation is allowed based on rate limits
*/
async checkLimit(handler: string, operation?: string): Promise<RateLimitResult> {
// Build keys to check from most specific to least specific
const keysToCheck: string[] = [];
if (operation) {
keysToCheck.push(
this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule)
);
}
keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule));
this.logger.debug('Checking rate limits', {
handler,
operation,
keysToCheck,
availableKeys: Array.from(this.limiters.keys()),
});
// First, find the cost from the most specific rule
let cost = 1; // Default cost
for (const key of keysToCheck) {
const entry = this.limiters.get(key);
if (entry && entry.cost !== undefined) {
cost = entry.cost;
this.logger.debug(`[RateLimiter] Using cost ${cost} from rule: ${key}`);
this.logger.debug('Using cost from rule', {
key,
cost,
handler,
operation,
});
break;
}
}
// Then find the rate limit windows from the first matching rule that has windows
let windowEntry: RateLimiterEntry | undefined;
let appliedKey: string | undefined;
for (const key of keysToCheck) {
const entry = this.limiters.get(key);
if (entry && entry.windows.length > 0) {
windowEntry = entry;
appliedKey = key;
break;
}
}
if (!windowEntry) {
this.logger.debug('No rate limit rules found', {
handler,
operation,
});
return { allowed: true };
}
this.logger.debug(`[RateLimiter] Applying rate limit rule: ${appliedKey}`, {
appliedKey,
windowCount: windowEntry.windows.length,
cost,
handler,
operation,
});
// Check all windows with the determined cost
let maxRetryDelayMs = 0;
this.logger.debug('Checking rate limit windows', {
handler,
operation,
cost,
windowCount: windowEntry.windows.length,
});
// Special handling for 0-cost operations - they should always pass
if (cost === 0) {
this.logger.debug(
`[RateLimiter] Zero-cost operation ${handler}:${operation || 'N/A'} - allowing without consuming points`
);
return {
allowed: true,
cost: 0,
};
}
for (const { limiter, window } of windowEntry.windows) {
// For handler-level rate limits, all operations share the same pool
// Use the applied key to determine the consumer key
const consumerKey = appliedKey?.startsWith('handler:')
? handler
: operation
? `${handler}:${operation}`
: handler;
try {
// First check current state without consuming
const currentState = await limiter.get(consumerKey);
const now = Date.now();
this.logger.debug(`[RateLimiter] Current state before consume:`, {
handler,
operation,
consumerKey,
cost,
window: `${window.points}pts/${window.duration}s`,
consumedPoints: currentState?.consumedPoints || 0,
remainingPoints: currentState?.remainingPoints ?? window.points,
msBeforeNext: currentState?.msBeforeNext || 0,
currentTime: new Date(now).toISOString(),
resetTime: currentState?.msBeforeNext
? new Date(now + currentState.msBeforeNext).toISOString()
: 'N/A',
hasState: !!currentState,
stateDetails: currentState ? JSON.stringify(currentState) : 'no state',
});
// Try to consume points
this.logger.debug(`[RateLimiter] Attempting to consume ${cost} points for ${consumerKey}`);
const result = await limiter.consume(consumerKey, cost);
this.logger.debug(
`[RateLimiter] Successfully consumed ${cost} points, ${result.remainingPoints} remaining`
);
this.logger.debug('Consumed points successfully', {
handler,
operation,
consumerKey,
window: `${window.points}pts/${window.duration}s`,
cost,
remainingPoints: result.remainingPoints,
msBeforeNext: result.msBeforeNext,
});
this.logger.trace('Rate limit window passed', {
handler,
operation,
window: `${window.points}pts/${window.duration}s`,
cost,
});
} catch (rejRes) {
if (!(rejRes instanceof RateLimiterRes)) {
throw rejRes;
}
// Rate limit exceeded for this window
const retryDelayMs = rejRes.msBeforeNext || window.blockDuration || 1000;
maxRetryDelayMs = Math.max(maxRetryDelayMs, retryDelayMs);
this.logger.debug(
`[RateLimiter] RATE LIMIT HIT: ${consumerKey} - ${cost} points rejected, retry in ${retryDelayMs}ms`,
{
consumedPoints: rejRes.consumedPoints || 0,
remainingPoints: rejRes.remainingPoints || 0,
totalPoints: window.points,
isFirstInDuration: rejRes.isFirstInDuration || false,
msBeforeNext: rejRes.msBeforeNext || 0,
retryDelayMs,
}
);
this.logger.trace('Rate limit exceeded', {
handler,
operation,
consumerKey,
window: `${window.points}pts/${window.duration}s`,
cost,
remainingPoints: rejRes.remainingPoints || 0,
retryDelayMs: maxRetryDelayMs,
});
return {
allowed: false,
retryDelayMs: maxRetryDelayMs,
remainingPoints: rejRes.remainingPoints || 0,
cost,
};
}
}
// All windows passed
return {
allowed: true,
cost,
};
}
/**
* Get rule key for storing rate limiter
*/
private getRuleKey(rule: RateLimitRule): string {
switch (rule.level) {
case 'global':
return 'global';
case 'queue':
return `queue:${rule.queueName || 'default'}`;
case 'handler':
return `handler:${rule.handler}`;
case 'operation':
return `operation:${rule.handler}:${rule.operation}`;
default:
return rule.level;
}
}
/**
* Get current rate limit status
*/
async getStatus(handler: string, operation?: string) {
// Build keys to check from most specific to least specific
const keysToCheck: string[] = [];
if (operation) {
keysToCheck.push(
this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule)
);
}
keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule));
keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule));
// Find the first matching rule
let entry: RateLimiterEntry | undefined;
let appliedKey: string | undefined;
for (const key of keysToCheck) {
entry = this.limiters.get(key);
if (entry) {
appliedKey = key;
break;
}
}
if (!entry) {
return {
handler,
operation,
hasRule: false,
};
}
// Get status for all windows
const consumerKey = operation ? `${handler}:${operation}` : handler;
const windows = await Promise.all(
entry.windows.map(async ({ limiter, window }) => {
const result = await limiter.get(consumerKey);
return {
points: window.points,
duration: window.duration,
remaining: result?.remainingPoints ?? window.points,
resetIn: result?.msBeforeNext ?? 0,
};
})
);
return {
handler,
operation,
hasRule: true,
appliedKey,
cost: entry.cost,
windows,
};
}
/**
* Reset rate limits for a specific handler/operation
*/
async reset(handler: string, operation?: string): Promise<void> {
const keysToCheck: string[] = [];
if (operation) {
keysToCheck.push(
this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule)
);
}
keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule));
for (const key of keysToCheck) {
const entry = this.limiters.get(key);
if (entry) {
await Promise.all(entry.windows.map(({ limiter }) => limiter.delete(handler)));
}
}
this.logger.debug('Rate limits reset', { handler, operation });
}
}

View file

@ -1,4 +1,5 @@
import { createCache, type CacheProvider, type CacheStats } from '@stock-bot/cache';
import type { LoggerLike } from '@stock-bot/logger';
import { generateCachePrefix } from './service-utils';
import type { RedisConfig } from './types';
@ -14,7 +15,7 @@ export class ServiceCache implements CacheProvider {
serviceName: string,
redisConfig: RedisConfig,
isGlobalCache: boolean = false,
logger?: any
logger?: LoggerLike
) {
// Determine Redis DB and prefix
let db: number;
@ -45,11 +46,11 @@ export class ServiceCache implements CacheProvider {
}
// Implement CacheProvider interface
async get<T = any>(key: string): Promise<T | null> {
async get<T = unknown>(key: string): Promise<T | null> {
return this.cache.get<T>(key);
}
async set<T = any>(
async set<T = unknown>(
key: string,
value: T,
options?:
@ -98,7 +99,7 @@ export class ServiceCache implements CacheProvider {
}
// Enhanced cache methods (delegate to underlying cache if available)
async update<T = any>(key: string, value: T): Promise<T | null> {
async update<T = unknown>(key: string, value: T): Promise<T | null> {
if (this.cache.update) {
return this.cache.update(key, value);
}
@ -106,7 +107,7 @@ export class ServiceCache implements CacheProvider {
return this.cache.set(key, value, { preserveTTL: true });
}
async setIfExists<T = any>(key: string, value: T, ttl?: number): Promise<boolean> {
async setIfExists<T = unknown>(key: string, value: T, ttl?: number): Promise<boolean> {
if (this.cache.setIfExists) {
return this.cache.setIfExists(key, value, ttl);
}
@ -115,7 +116,7 @@ export class ServiceCache implements CacheProvider {
return result !== null;
}
async setIfNotExists<T = any>(key: string, value: T, ttl?: number): Promise<boolean> {
async setIfNotExists<T = unknown>(key: string, value: T, ttl?: number): Promise<boolean> {
if (this.cache.setIfNotExists) {
return this.cache.setIfNotExists(key, value, ttl);
}
@ -124,7 +125,7 @@ export class ServiceCache implements CacheProvider {
return result !== null;
}
async replace<T = any>(key: string, value: T, ttl?: number): Promise<T | null> {
async replace<T = unknown>(key: string, value: T, ttl?: number): Promise<T | null> {
if (this.cache.replace) {
return this.cache.replace(key, value, ttl);
}
@ -132,7 +133,7 @@ export class ServiceCache implements CacheProvider {
return this.cache.set(key, value, ttl);
}
async updateField<T = any>(
async updateField<T = unknown>(
key: string,
updater: (current: T | null) => T,
ttl?: number
@ -172,7 +173,7 @@ export class ServiceCache implements CacheProvider {
export function createServiceCache(
serviceName: string,
redisConfig: RedisConfig,
options: { global?: boolean; logger?: any } = {}
options: { global?: boolean; logger?: LoggerLike } = {}
): ServiceCache {
return new ServiceCache(serviceName, redisConfig, options.global, options.logger);
}

View file

@ -1,3 +1,4 @@
import type { HandlerRegistry } from '@stock-bot/handler-registry';
// Import types we need to extend
import type { JobOptions, QueueStats } from '@stock-bot/types';
@ -61,7 +62,7 @@ export interface QueueOptions {
concurrency?: number;
enableMetrics?: boolean;
enableDLQ?: boolean;
handlerRegistry?: any; // HandlerRegistry from @stock-bot/handler-registry
handlerRegistry?: HandlerRegistry; // HandlerRegistry from @stock-bot/handler-registry
}
export interface QueueManagerConfig {
@ -104,16 +105,9 @@ export interface HandlerInitializer {
}
// Rate limiting types
export interface RateLimitWindow {
points: number;
duration: number;
blockDuration?: number;
}
export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow;
export interface RateLimitConfig {
limits?: RateLimitWindow[];
cost?: number;
}
export type RateLimitConfig = import('@stock-bot/types').HandlerRateLimitConfig;
export interface RateLimitRule {
level: 'global' | 'queue' | 'handler' | 'operation';
@ -154,7 +148,7 @@ export interface SmartQueueConfig extends QueueManagerConfig {
/** Whether to auto-discover handlers from registry */
autoDiscoverHandlers?: boolean;
/** Custom service registry (defaults to built-in) */
serviceRegistry?: Record<string, any>;
serviceRegistry?: Record<string, unknown>;
}
export interface QueueRoute {