commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
12
libs/core/cache/src/redis-cache.ts
vendored
12
libs/core/cache/src/redis-cache.ts
vendored
|
|
@ -8,18 +8,10 @@ import type { CacheOptions, CacheProvider, CacheStats } from './types';
|
|||
*/
|
||||
export class RedisCache implements CacheProvider {
|
||||
private redis: Redis;
|
||||
private logger: { info?: (...args: unknown[]) => void; error?: (...args: unknown[]) => void } =
|
||||
console;
|
||||
private logger: NonNullable<CacheOptions['logger']>;
|
||||
private defaultTTL: number;
|
||||
private keyPrefix: string;
|
||||
private stats: CacheStats = {
|
||||
hits: 0,
|
||||
misses: 0,
|
||||
errors: 0,
|
||||
hitRate: 0,
|
||||
total: 0,
|
||||
uptime: 0,
|
||||
};
|
||||
private stats: CacheStats = { hits: 0, misses: 0, errors: 0, hitRate: 0, total: 0, uptime: 0 };
|
||||
private startTime = Date.now();
|
||||
|
||||
constructor(options: CacheOptions) {
|
||||
|
|
|
|||
9
libs/core/cache/src/types.ts
vendored
9
libs/core/cache/src/types.ts
vendored
|
|
@ -1,3 +1,5 @@
|
|||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
|
||||
export interface RedisConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
|
|
@ -113,12 +115,7 @@ export interface CacheOptions {
|
|||
name?: string; // Name for connection identification
|
||||
shared?: boolean; // Whether to use shared connection
|
||||
redisConfig: RedisConfig;
|
||||
logger?: {
|
||||
info?: (...args: unknown[]) => void;
|
||||
error?: (...args: unknown[]) => void;
|
||||
warn?: (...args: unknown[]) => void;
|
||||
debug?: (...args: unknown[]) => void;
|
||||
};
|
||||
logger?: Partial<LoggerLike>;
|
||||
}
|
||||
|
||||
export interface CacheStats {
|
||||
|
|
|
|||
|
|
@ -24,7 +24,8 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"@stock-bot/logger": "workspace:*",
|
||||
"zod": "^3.22.4"
|
||||
"zod": "^3.22.4",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.0.0",
|
||||
|
|
|
|||
|
|
@ -52,10 +52,10 @@ export const unifiedAppSchema = baseAppSchema
|
|||
}
|
||||
if (data.database.questdb && !data.questdb) {
|
||||
// Handle the ilpPort -> influxPort mapping for DI system
|
||||
const questdbConfig = { ...data.database.questdb };
|
||||
if ('ilpPort' in questdbConfig && !('influxPort' in questdbConfig)) {
|
||||
(questdbConfig as any).influxPort = questdbConfig.ilpPort;
|
||||
}
|
||||
const questdbConfig = {
|
||||
...data.database.questdb,
|
||||
influxPort: data.database.questdb.ilpPort,
|
||||
};
|
||||
data.questdb = questdbConfig;
|
||||
}
|
||||
}
|
||||
|
|
@ -68,7 +68,7 @@ export type UnifiedAppConfig = z.infer<typeof unifiedAppSchema>;
|
|||
/**
|
||||
* Helper to convert StockBotAppConfig to UnifiedAppConfig
|
||||
*/
|
||||
export function toUnifiedConfig(config: any): UnifiedAppConfig {
|
||||
export function toUnifiedConfig(config: unknown): UnifiedAppConfig {
|
||||
return unifiedAppSchema.parse(config);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -83,21 +83,21 @@ export function isSecret(value: unknown): value is SecretValue {
|
|||
/**
|
||||
* Redact secrets from an object
|
||||
*/
|
||||
export function redactSecrets<T extends Record<string, any>>(
|
||||
export function redactSecrets<T extends Record<string, unknown>>(
|
||||
obj: T,
|
||||
secretPaths: string[] = []
|
||||
): T {
|
||||
const result = { ...obj };
|
||||
const result = redactSecretValues(obj) as T;
|
||||
|
||||
// Redact known secret paths
|
||||
for (const path of secretPaths) {
|
||||
const keys = path.split('.');
|
||||
let current: any = result;
|
||||
let current: Record<string, unknown> = result;
|
||||
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const key = keys[i];
|
||||
if (key && current[key] && typeof current[key] === 'object') {
|
||||
current = current[key];
|
||||
current = current[key] as Record<string, unknown>;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
|
@ -110,7 +110,7 @@ export function redactSecrets<T extends Record<string, any>>(
|
|||
}
|
||||
|
||||
// Recursively redact SecretValue instances
|
||||
function redactSecretValues(obj: any): any {
|
||||
function redactSecretValues(obj: unknown): unknown {
|
||||
if (obj === null || obj === undefined) {
|
||||
return obj;
|
||||
}
|
||||
|
|
@ -124,7 +124,7 @@ export function redactSecrets<T extends Record<string, any>>(
|
|||
}
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
const result: any = {};
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = redactSecretValues(value);
|
||||
}
|
||||
|
|
@ -134,7 +134,7 @@ export function redactSecrets<T extends Record<string, any>>(
|
|||
return obj;
|
||||
}
|
||||
|
||||
return redactSecretValues(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
|
||||
export interface ValidationResult {
|
||||
valid: boolean;
|
||||
|
|
@ -62,19 +63,19 @@ export function checkRequiredEnvVars(required: string[]): ValidationResult {
|
|||
* Validate configuration completeness
|
||||
*/
|
||||
export function validateCompleteness(
|
||||
config: Record<string, any>,
|
||||
config: Record<string, unknown>,
|
||||
required: string[]
|
||||
): ValidationResult {
|
||||
const errors: ValidationResult['errors'] = [];
|
||||
|
||||
for (const path of required) {
|
||||
const keys = path.split('.');
|
||||
let current: any = config;
|
||||
let current: unknown = config;
|
||||
let found = true;
|
||||
|
||||
for (const key of keys) {
|
||||
if (current && typeof current === 'object' && key in current) {
|
||||
current = current[key];
|
||||
current = (current as Record<string, unknown>)[key];
|
||||
} else {
|
||||
found = false;
|
||||
break;
|
||||
|
|
@ -144,11 +145,11 @@ export function mergeSchemas<T extends z.ZodSchema[]>(
|
|||
throw new Error('At least two schemas required for merge');
|
||||
}
|
||||
|
||||
let result = schemas[0]!.and(schemas[1]!);
|
||||
let result: z.ZodTypeAny = defined(schemas[0]).and(defined(schemas[1]));
|
||||
|
||||
for (let i = 2; i < schemas.length; i++) {
|
||||
result = result.and(schemas[i]!) as any;
|
||||
result = result.and(defined(schemas[i]));
|
||||
}
|
||||
|
||||
return result as any;
|
||||
return result as z.ZodIntersection<T[0], T[1]>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -579,7 +579,7 @@ KEY_WITHOUT_VALUE=
|
|||
|
||||
it('should handle all .env file paths exhausted', () => {
|
||||
const readFileSpy = readFileSync as any;
|
||||
readFileSpy.mockImplementation((path: string) => {
|
||||
readFileSpy.mockImplementation((_path: string) => {
|
||||
const error: any = new Error('Not found');
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { existsSync, readFileSync } from 'fs';
|
||||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { ConfigLoaderError } from '../src/errors';
|
||||
import { FileLoader } from '../src/loaders/file.loader';
|
||||
|
||||
|
|
|
|||
|
|
@ -690,7 +690,9 @@ describe('Config Schemas', () => {
|
|||
retries: 5,
|
||||
};
|
||||
const config = baseProviderConfigSchema.parse(input);
|
||||
expect(config).toEqual(input);
|
||||
// Rate limiting is owned by handlers/queues, not the base provider schema.
|
||||
const { rateLimit: _rateLimit, ...supported } = input;
|
||||
expect(config).toEqual(supported);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -202,9 +202,10 @@ describe('Config Utils', () => {
|
|||
});
|
||||
|
||||
it('should not modify original object', () => {
|
||||
const obj = { password: 'secret' };
|
||||
const original = { ...obj };
|
||||
redactSecrets(obj, ['password']);
|
||||
const obj = { password: 'secret', nested: { token: 'nested-secret' } };
|
||||
const original = { password: 'secret', nested: { token: 'nested-secret' } };
|
||||
const redacted = redactSecrets(obj, ['password', 'nested.token']);
|
||||
expect(redacted.nested.token).toBe('***REDACTED***');
|
||||
expect(obj).toEqual(original);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,5 +6,9 @@
|
|||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": []
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@
|
|||
"glob": "^10.0.0",
|
||||
"zod": "^3.23.8",
|
||||
"hono": "^4.0.0",
|
||||
"awilix": "^12.0.5"
|
||||
"awilix": "^12.0.5",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/pg": "^8.10.7"
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@ import { HandlerScanner } from '../scanner';
|
|||
import { ServiceLifecycleManager } from '../utils/lifecycle';
|
||||
import type { ContainerBuildOptions, ServiceDefinitions } from './types';
|
||||
|
||||
function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): number {
|
||||
return config.influxPort ?? config.ilpPort ?? 9009;
|
||||
}
|
||||
|
||||
export class ServiceContainerBuilder {
|
||||
private config: Partial<AppConfig> = {};
|
||||
private unifiedConfig: UnifiedAppConfig | null = null;
|
||||
|
|
@ -86,7 +90,7 @@ export class ServiceContainerBuilder {
|
|||
const questdbConfig = config.questdb
|
||||
? {
|
||||
...config.questdb,
|
||||
influxPort: (config.questdb as any).influxPort || (config.questdb as any).ilpPort || 9009,
|
||||
influxPort: getInfluxPort(config.questdb),
|
||||
}
|
||||
: {
|
||||
enabled: true,
|
||||
|
|
@ -200,7 +204,7 @@ export class ServiceContainerBuilder {
|
|||
host: config.questdb.host || 'localhost',
|
||||
httpPort: config.questdb.httpPort || 9000,
|
||||
pgPort: config.questdb.pgPort || 8812,
|
||||
influxPort: (config.questdb as any).influxPort || (config.questdb as any).ilpPort || 9009,
|
||||
influxPort: getInfluxPort(config.questdb),
|
||||
database: config.questdb.database || 'questdb',
|
||||
}
|
||||
: undefined;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,9 @@ export {
|
|||
questdbConfigSchema,
|
||||
proxyConfigSchema,
|
||||
browserConfigSchema,
|
||||
queueConfigSchema
|
||||
queueConfigSchema,
|
||||
} from './config/schemas';
|
||||
|
||||
export type { ServiceDefinitions, ServiceCradle } from './container/types';
|
||||
|
||||
export type { HandlerInitializationContext } from './service-application';
|
||||
|
|
|
|||
|
|
@ -14,14 +14,14 @@ export interface OperationContextOptions {
|
|||
operationName: string;
|
||||
parentLogger?: Logger;
|
||||
container?: ServiceResolver;
|
||||
metadata?: Record<string, any>;
|
||||
metadata?: Record<string, unknown>;
|
||||
traceId?: string;
|
||||
}
|
||||
|
||||
export class OperationContext {
|
||||
public readonly logger: Logger;
|
||||
public readonly traceId: string;
|
||||
public readonly metadata: Record<string, any>;
|
||||
public readonly metadata: Record<string, unknown>;
|
||||
private readonly container?: ServiceResolver;
|
||||
private readonly startTime: Date;
|
||||
|
||||
|
|
@ -48,7 +48,7 @@ export class OperationContext {
|
|||
options: {
|
||||
container?: ServiceResolver;
|
||||
parentLogger?: Logger;
|
||||
metadata?: Record<string, any>;
|
||||
metadata?: Record<string, unknown>;
|
||||
traceId?: string;
|
||||
} = {}
|
||||
): OperationContext {
|
||||
|
|
@ -82,7 +82,7 @@ export class OperationContext {
|
|||
/**
|
||||
* Add metadata to the context
|
||||
*/
|
||||
addMetadata(key: string, value: any): void {
|
||||
addMetadata(key: string, value: unknown): void {
|
||||
this.metadata[key] = value;
|
||||
}
|
||||
|
||||
|
|
@ -124,7 +124,7 @@ export class OperationContext {
|
|||
/**
|
||||
* Create child context
|
||||
*/
|
||||
createChild(operationName: string, metadata?: Record<string, any>): OperationContext {
|
||||
createChild(operationName: string, metadata?: Record<string, unknown>): OperationContext {
|
||||
return new OperationContext({
|
||||
handlerName: 'child',
|
||||
operationName,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { asFunction, asValue, type AwilixContainer } from 'awilix';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { QuestDBClient } from '@stock-bot/questdb';
|
||||
|
|
@ -66,11 +67,11 @@ export function registerDatabaseServices(
|
|||
questdbClient: asFunction(({ logger }) => {
|
||||
return new QuestDBClient(
|
||||
{
|
||||
host: config.questdb!.host,
|
||||
httpPort: config.questdb!.httpPort,
|
||||
pgPort: config.questdb!.pgPort,
|
||||
influxPort: config.questdb!.influxPort,
|
||||
database: config.questdb!.database,
|
||||
host: defined(config.questdb).host,
|
||||
httpPort: defined(config.questdb).httpPort,
|
||||
pgPort: defined(config.questdb).pgPort,
|
||||
influxPort: defined(config.questdb).influxPort,
|
||||
database: defined(config.questdb).database,
|
||||
},
|
||||
logger
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { asClass, asFunction, asValue, type AwilixContainer } from 'awilix';
|
||||
import { Browser } from '@stock-bot/browser';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { ProxyManager } from '@stock-bot/proxy';
|
||||
import type { AppConfig } from '../config/schemas';
|
||||
import type { ServiceDefinitions } from '../container/types';
|
||||
|
|
@ -15,14 +16,14 @@ export function registerApplicationServices(
|
|||
.singleton()
|
||||
.inject(() => ({
|
||||
options: {
|
||||
headless: config.browser!.headless,
|
||||
timeout: config.browser!.timeout,
|
||||
headless: defined(config.browser).headless,
|
||||
timeout: defined(config.browser).timeout,
|
||||
},
|
||||
})),
|
||||
});
|
||||
} else {
|
||||
container.register({
|
||||
browser: asValue(null as any), // Required field
|
||||
browser: asValue(null), // Required field
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -62,7 +63,7 @@ export function registerApplicationServices(
|
|||
container.register({
|
||||
queueManager: asFunction(({ logger, handlerRegistry }) => {
|
||||
const { QueueManager } = require('@stock-bot/queue');
|
||||
|
||||
|
||||
const queueConfig = {
|
||||
serviceName: config.service?.serviceName || config.service?.name || 'unknown',
|
||||
redis: {
|
||||
|
|
@ -72,14 +73,14 @@ export function registerApplicationServices(
|
|||
db: config.redis.db,
|
||||
},
|
||||
defaultQueueOptions: {
|
||||
workers: config.queue!.workers || 1,
|
||||
concurrency: config.queue!.concurrency || 1,
|
||||
defaultJobOptions: config.queue!.defaultJobOptions,
|
||||
workers: defined(config.queue).workers || 1,
|
||||
concurrency: defined(config.queue).concurrency || 1,
|
||||
defaultJobOptions: defined(config.queue).defaultJobOptions,
|
||||
},
|
||||
enableScheduledJobs: config.queue!.enableScheduledJobs ?? true,
|
||||
enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? true,
|
||||
autoDiscoverHandlers: true,
|
||||
};
|
||||
|
||||
|
||||
return new QueueManager(queueConfig, handlerRegistry, logger);
|
||||
}).singleton(),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -11,7 +11,12 @@ import type {
|
|||
HandlerRegistry,
|
||||
} from '@stock-bot/handler-registry';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { ExecutionContext, IHandler } from '@stock-bot/types';
|
||||
import type {
|
||||
DecoratedHandlerClass,
|
||||
ExecutionContext,
|
||||
IHandler,
|
||||
JobHandler,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
export interface HandlerScannerOptions {
|
||||
serviceName?: string;
|
||||
|
|
@ -21,7 +26,7 @@ export interface HandlerScannerOptions {
|
|||
|
||||
export class HandlerScanner {
|
||||
private logger = getLogger('handler-scanner');
|
||||
private discoveredHandlers = new Map<string, any>();
|
||||
private discoveredHandlers = new Map<string, DecoratedHandlerClass>();
|
||||
|
||||
constructor(
|
||||
private registry: HandlerRegistry,
|
||||
|
|
@ -69,7 +74,7 @@ export class HandlerScanner {
|
|||
/**
|
||||
* Register handlers found in a module
|
||||
*/
|
||||
private registerHandlersFromModule(module: any, filePath: string): void {
|
||||
private registerHandlersFromModule(module: Record<string, unknown>, filePath: string): void {
|
||||
for (const [exportName, exported] of Object.entries(module)) {
|
||||
if (this.isHandler(exported)) {
|
||||
this.registerHandler(exported, exportName, filePath);
|
||||
|
|
@ -80,14 +85,14 @@ export class HandlerScanner {
|
|||
/**
|
||||
* Check if an exported value is a handler
|
||||
*/
|
||||
private isHandler(exported: any): boolean {
|
||||
private isHandler(exported: unknown): exported is DecoratedHandlerClass {
|
||||
if (typeof exported !== 'function') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for handler metadata added by decorators
|
||||
const hasHandlerName = !!(exported as any).__handlerName;
|
||||
const hasOperations = Array.isArray((exported as any).__operations);
|
||||
const hasHandlerName = !!(exported as DecoratedHandlerClass).__handlerName;
|
||||
const hasOperations = Array.isArray((exported as DecoratedHandlerClass).__operations);
|
||||
|
||||
return hasHandlerName && hasOperations;
|
||||
}
|
||||
|
|
@ -95,8 +100,15 @@ export class HandlerScanner {
|
|||
/**
|
||||
* Register a handler with the registry and DI container
|
||||
*/
|
||||
private registerHandler(HandlerClass: any, exportName: string, filePath: string): void {
|
||||
private registerHandler(
|
||||
HandlerClass: DecoratedHandlerClass,
|
||||
exportName: string,
|
||||
filePath: string
|
||||
): void {
|
||||
const handlerName = HandlerClass.__handlerName;
|
||||
if (!handlerName) {
|
||||
throw new Error('Handler name is missing');
|
||||
}
|
||||
const operations = HandlerClass.__operations || [];
|
||||
const schedules = HandlerClass.__schedules || [];
|
||||
const isDisabled = HandlerClass.__disabled || false;
|
||||
|
|
@ -110,24 +122,24 @@ export class HandlerScanner {
|
|||
}
|
||||
|
||||
// Filter out disabled operations
|
||||
const enabledOperations = operations.filter((op: any) => {
|
||||
const enabledOperations = operations.filter(op => {
|
||||
const isDisabled = disabledOperations.includes(op.method);
|
||||
if (isDisabled) {
|
||||
this.logger.debug('Skipping disabled operation', {
|
||||
handlerName,
|
||||
this.logger.debug('Skipping disabled operation', {
|
||||
handlerName,
|
||||
operation: op.name,
|
||||
method: op.method
|
||||
method: op.method,
|
||||
});
|
||||
}
|
||||
return !isDisabled;
|
||||
});
|
||||
|
||||
const enabledSchedules = schedules.filter((schedule: any) => {
|
||||
const enabledSchedules = schedules.filter(schedule => {
|
||||
const isDisabled = disabledOperations.includes(schedule.operation);
|
||||
if (isDisabled) {
|
||||
this.logger.debug('Skipping disabled scheduled operation', {
|
||||
handlerName,
|
||||
operation: schedule.operation
|
||||
this.logger.debug('Skipping disabled scheduled operation', {
|
||||
handlerName,
|
||||
operation: schedule.operation,
|
||||
});
|
||||
}
|
||||
return !isDisabled;
|
||||
|
|
@ -137,12 +149,12 @@ export class HandlerScanner {
|
|||
const metadata: HandlerMetadata = {
|
||||
name: handlerName,
|
||||
service: this.options.serviceName,
|
||||
operations: enabledOperations.map((op: any) => ({
|
||||
operations: enabledOperations.map(op => ({
|
||||
name: op.name,
|
||||
method: op.method,
|
||||
rateLimit: operationRateLimits[op.method] || null,
|
||||
})),
|
||||
schedules: enabledSchedules.map((schedule: any) => ({
|
||||
schedules: enabledSchedules.map(schedule => ({
|
||||
operation: schedule.operation,
|
||||
cronPattern: schedule.cronPattern,
|
||||
priority: schedule.priority,
|
||||
|
|
@ -155,9 +167,9 @@ export class HandlerScanner {
|
|||
};
|
||||
|
||||
// Build configuration with operation handlers
|
||||
const operationHandlers: Record<string, any> = {};
|
||||
const operationHandlers: Record<string, JobHandler> = {};
|
||||
for (const op of enabledOperations) {
|
||||
operationHandlers[op.name] = async (payload: any) => {
|
||||
operationHandlers[op.name] = async (payload: unknown) => {
|
||||
const handler = this.container.resolve<IHandler>(handlerName);
|
||||
const context: ExecutionContext = {
|
||||
type: 'queue',
|
||||
|
|
@ -170,8 +182,8 @@ export class HandlerScanner {
|
|||
const configuration: HandlerConfiguration = {
|
||||
name: handlerName,
|
||||
operations: operationHandlers,
|
||||
scheduledJobs: enabledSchedules.map((schedule: any) => {
|
||||
const operation = enabledOperations.find((op: any) => op.method === schedule.operation);
|
||||
scheduledJobs: enabledSchedules.map(schedule => {
|
||||
const operation = enabledOperations.find(op => op.method === schedule.operation);
|
||||
return {
|
||||
type: `${handlerName}-${schedule.operation}`,
|
||||
operation: operation?.name || schedule.operation,
|
||||
|
|
@ -192,7 +204,7 @@ export class HandlerScanner {
|
|||
if (this.options.autoRegister !== false) {
|
||||
this.container.register({
|
||||
[handlerName]: asFunction(({ serviceContainer }) => {
|
||||
return new HandlerClass(serviceContainer);
|
||||
return Reflect.construct(HandlerClass, [serviceContainer]) as IHandler;
|
||||
}).singleton(),
|
||||
});
|
||||
}
|
||||
|
|
@ -214,14 +226,17 @@ export class HandlerScanner {
|
|||
/**
|
||||
* Get all discovered handlers
|
||||
*/
|
||||
getDiscoveredHandlers(): Map<string, any> {
|
||||
getDiscoveredHandlers(): Map<string, DecoratedHandlerClass> {
|
||||
return new Map(this.discoveredHandlers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually register a handler class
|
||||
*/
|
||||
registerHandlerClass(HandlerClass: any, options: { serviceName?: string } = {}): void {
|
||||
registerHandlerClass(
|
||||
HandlerClass: DecoratedHandlerClass,
|
||||
options: { serviceName?: string } = {}
|
||||
): void {
|
||||
const serviceName = options.serviceName || this.options.serviceName;
|
||||
const originalServiceName = this.options.serviceName;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import type { AwilixContainer } from 'awilix';
|
||||
import { Hono } from 'hono';
|
||||
import { cors } from 'hono/cors';
|
||||
/**
|
||||
* ServiceApplication - Common service initialization and lifecycle management
|
||||
* Encapsulates common patterns for Hono-based microservices
|
||||
|
|
@ -6,13 +9,12 @@
|
|||
import type { BaseAppConfig, UnifiedAppConfig } from '@stock-bot/config';
|
||||
import { toUnifiedConfig } from '@stock-bot/config';
|
||||
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger, setLoggerConfig, shutdownLoggers, type Logger } from '@stock-bot/logger';
|
||||
import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { AwilixContainer } from 'awilix';
|
||||
import { Hono } from 'hono';
|
||||
import { cors } from 'hono/cors';
|
||||
import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown';
|
||||
import type { ServiceDefinitions } from './container/types';
|
||||
import type { HandlerScanner } from './scanner';
|
||||
|
||||
/**
|
||||
* Configuration for ServiceApplication
|
||||
|
|
@ -47,6 +49,11 @@ export interface ServiceApplicationConfig {
|
|||
/**
|
||||
* Lifecycle hooks for service customization
|
||||
*/
|
||||
export interface HandlerInitializationContext {
|
||||
handlerScanner: HandlerScanner;
|
||||
handlerRegistry: HandlerRegistry;
|
||||
}
|
||||
|
||||
export interface ServiceLifecycleHooks {
|
||||
/** Called after container is created but before routes */
|
||||
onContainerReady?: (container: IServiceContainer) => Promise<void> | void;
|
||||
|
|
@ -167,7 +174,7 @@ export class ServiceApplication {
|
|||
this.logger.info('Registering shutdown handlers', {
|
||||
service: this.serviceConfig.serviceName,
|
||||
scheduledJobs: this.serviceConfig.enableScheduledJobs,
|
||||
timeout: this.serviceConfig.shutdownTimeout
|
||||
timeout: this.serviceConfig.shutdownTimeout,
|
||||
});
|
||||
|
||||
// Priority 1: Queue system (highest priority)
|
||||
|
|
@ -222,7 +229,7 @@ export class ServiceApplication {
|
|||
this.shutdown.onShutdown(
|
||||
async () => {
|
||||
try {
|
||||
await this.hooks.onBeforeShutdown!();
|
||||
await defined(this.hooks.onBeforeShutdown)();
|
||||
} catch (error) {
|
||||
this.logger.error('Error in custom shutdown hook', { error });
|
||||
}
|
||||
|
|
@ -239,7 +246,7 @@ export class ServiceApplication {
|
|||
const startTime = Date.now();
|
||||
const disposed: string[] = [];
|
||||
const failed: string[] = [];
|
||||
|
||||
|
||||
try {
|
||||
if (this.container) {
|
||||
// Disconnect database clients
|
||||
|
|
@ -280,11 +287,11 @@ export class ServiceApplication {
|
|||
}
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
this.logger.info('Service disposal completed', {
|
||||
duration,
|
||||
disposed,
|
||||
this.logger.info('Service disposal completed', {
|
||||
duration,
|
||||
disposed,
|
||||
failed,
|
||||
success: failed.length === 0
|
||||
success: failed.length === 0,
|
||||
});
|
||||
} else {
|
||||
this.logger.warn('No container available for service disposal');
|
||||
|
|
@ -309,16 +316,19 @@ export class ServiceApplication {
|
|||
// console.log(`[${new Date().toISOString()}] Loggers shut down successfully (${Date.now() - startTime}ms)`);
|
||||
} catch (error) {
|
||||
// Use console.error since logger might be partially shut down
|
||||
console.error(`[${new Date().toISOString()}] Error shutting down loggers:`, error);
|
||||
process.stderr.write(`Error shutting down loggers: ${String(error)}\n`);
|
||||
}
|
||||
},
|
||||
SHUTDOWN_DEFAULTS.LOW_PRIORITY,
|
||||
'Loggers'
|
||||
);
|
||||
|
||||
|
||||
this.logger.info('All shutdown handlers registered', {
|
||||
service: this.serviceConfig.serviceName,
|
||||
handlerCount: 3 + (this.serviceConfig.enableScheduledJobs ? 1 : 0) + (this.hooks.onBeforeShutdown ? 1 : 0)
|
||||
handlerCount:
|
||||
3 +
|
||||
(this.serviceConfig.enableScheduledJobs ? 1 : 0) +
|
||||
(this.hooks.onBeforeShutdown ? 1 : 0),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -328,7 +338,10 @@ export class ServiceApplication {
|
|||
async start(
|
||||
containerFactory: (config: UnifiedAppConfig) => Promise<AwilixContainer<ServiceDefinitions>>,
|
||||
routeFactory: (container: IServiceContainer) => Hono,
|
||||
handlerInitializer?: (container: IServiceContainer) => Promise<void>
|
||||
handlerInitializer?: (
|
||||
container: IServiceContainer,
|
||||
context: HandlerInitializationContext
|
||||
) => Promise<void>
|
||||
): Promise<void> {
|
||||
this.logger.info(`Initializing ${this.serviceConfig.serviceName} service...`);
|
||||
|
||||
|
|
@ -337,7 +350,7 @@ export class ServiceApplication {
|
|||
this.logger.debug('Creating DI container...');
|
||||
// Config already has service name from constructor
|
||||
this.container = await containerFactory(this.config);
|
||||
this.serviceContainer = this.container!.resolve('serviceContainer');
|
||||
this.serviceContainer = defined(this.container).resolve('serviceContainer');
|
||||
this.logger.info('DI container created and initialized');
|
||||
|
||||
// Call container ready hook
|
||||
|
|
@ -356,31 +369,30 @@ export class ServiceApplication {
|
|||
// Initialize handlers if enabled
|
||||
if (this.serviceConfig.enableHandlers && handlerInitializer) {
|
||||
this.logger.debug('Initializing handlers...');
|
||||
// Pass the service container with the DI container attached
|
||||
const containerWithDI = Object.assign({}, this.serviceContainer, {
|
||||
_diContainer: this.container,
|
||||
await handlerInitializer(this.serviceContainer, {
|
||||
handlerScanner: this.container.resolve('handlerScanner'),
|
||||
handlerRegistry: this.container.resolve('handlerRegistry'),
|
||||
});
|
||||
await handlerInitializer(containerWithDI);
|
||||
this.logger.info('Handlers initialized');
|
||||
|
||||
|
||||
// After handlers are initialized, add rate limit rules to queue manager
|
||||
const queueManager = this.container.resolve('queueManager');
|
||||
const handlerRegistry = this.container.resolve<HandlerRegistry>('handlerRegistry');
|
||||
|
||||
|
||||
if (queueManager && handlerRegistry) {
|
||||
const rateLimitRules = [];
|
||||
const allMetadata = handlerRegistry.getAllMetadata();
|
||||
|
||||
|
||||
for (const [handlerName, metadata] of allMetadata) {
|
||||
// Handler-level rate limit
|
||||
if (metadata.rateLimit) {
|
||||
rateLimitRules.push({
|
||||
level: 'handler' as const,
|
||||
handler: handlerName,
|
||||
config: metadata.rateLimit as any, // Type mismatch between packages
|
||||
config: metadata.rateLimit, // Type mismatch between packages
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Operation-level rate limits
|
||||
for (const operation of metadata.operations) {
|
||||
if (operation.rateLimit) {
|
||||
|
|
@ -388,12 +400,12 @@ export class ServiceApplication {
|
|||
level: 'operation' as const,
|
||||
handler: handlerName,
|
||||
operation: operation.name,
|
||||
config: operation.rateLimit as any, // Type mismatch between packages
|
||||
config: operation.rateLimit, // Type mismatch between packages
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (rateLimitRules.length > 0) {
|
||||
await queueManager.addRateLimitRules(rateLimitRules);
|
||||
this.logger.info('Rate limit rules added to QueueManager', {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// Generic types to avoid circular dependencies
|
||||
export interface GenericClientConfig {
|
||||
[key: string]: any;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ConnectionPoolConfig {
|
||||
|
|
@ -58,14 +58,14 @@ export interface PoolMetrics {
|
|||
}
|
||||
|
||||
export interface ConnectionFactory {
|
||||
createMongoDB(config: MongoDBPoolConfig): Promise<ConnectionPool<any>>;
|
||||
createPostgreSQL(config: PostgreSQLPoolConfig): Promise<ConnectionPool<any>>;
|
||||
createCache(config: CachePoolConfig): Promise<ConnectionPool<any>>;
|
||||
createQueue(config: QueuePoolConfig): Promise<ConnectionPool<any>>;
|
||||
createMongoDB(config: MongoDBPoolConfig): Promise<ConnectionPool<unknown>>;
|
||||
createPostgreSQL(config: PostgreSQLPoolConfig): Promise<ConnectionPool<unknown>>;
|
||||
createCache(config: CachePoolConfig): Promise<ConnectionPool<unknown>>;
|
||||
createQueue(config: QueuePoolConfig): Promise<ConnectionPool<unknown>>;
|
||||
getPool(
|
||||
type: 'mongodb' | 'postgres' | 'cache' | 'queue',
|
||||
name: string
|
||||
): ConnectionPool<any> | undefined;
|
||||
): ConnectionPool<unknown> | undefined;
|
||||
listPools(): Array<{ type: string; name: string; metrics: PoolMetrics }>;
|
||||
disposeAll(): Promise<void>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ class MockHandler implements IHandler {
|
|||
|
||||
constructor(private serviceContainer: any) {}
|
||||
|
||||
async execute(operation: string, payload: any, context: ExecutionContext): Promise<any> {
|
||||
async execute(operation: string, payload: any, _context: ExecutionContext): Promise<any> {
|
||||
switch (operation) {
|
||||
case 'processData':
|
||||
return { processed: true, data: payload };
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { asClass, asFunction, asValue, createContainer } from 'awilix';
|
||||
import { asFunction, asValue, createContainer } from 'awilix';
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import {
|
||||
registerApplicationServices,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { afterEach, describe, expect, it, mock } from 'bun:test';
|
||||
import type { BaseAppConfig } from '@stock-bot/config';
|
||||
import { ServiceApplication } from '../src/service-application';
|
||||
import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application';
|
||||
|
|
@ -31,7 +31,7 @@ const mockShutdownInstance = {
|
|||
};
|
||||
|
||||
const mockShutdown = {
|
||||
getInstance: mock(() => mockShutdownInstance)
|
||||
getInstance: mock(() => mockShutdownInstance),
|
||||
};
|
||||
|
||||
mock.module('@stock-bot/shutdown', () => ({
|
||||
|
|
@ -45,7 +45,7 @@ const mockServer = {
|
|||
hostname: '0.0.0.0',
|
||||
};
|
||||
|
||||
const originalBunServe = Bun.serve;
|
||||
const _originalBunServe = Bun.serve;
|
||||
Bun.serve = mock(() => mockServer);
|
||||
|
||||
const mockConfig: BaseAppConfig = {
|
||||
|
|
|
|||
|
|
@ -253,7 +253,7 @@ describe('DI Types', () => {
|
|||
health: async () => true,
|
||||
dispose: async () => {},
|
||||
}),
|
||||
getPool: (type, name) => undefined,
|
||||
getPool: (_type, _name) => undefined,
|
||||
listPools: () => [],
|
||||
disposeAll: async () => {},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -11,9 +11,20 @@
|
|||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist", "test"],
|
||||
"references": [
|
||||
{ "path": "../services" },
|
||||
{ "path": "../config" },
|
||||
{ "path": "../logger" },
|
||||
{ "path": "../queue" }
|
||||
{
|
||||
"path": "../services"
|
||||
},
|
||||
{
|
||||
"path": "../config"
|
||||
},
|
||||
{
|
||||
"path": "../logger"
|
||||
},
|
||||
{
|
||||
"path": "../queue"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@
|
|||
"dependencies": {
|
||||
"@stock-bot/logger": "*",
|
||||
"ioredis": "^5.3.2",
|
||||
"eventemitter3": "^5.0.1"
|
||||
"eventemitter3": "^5.0.1",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
|
|
|
|||
|
|
@ -98,7 +98,11 @@ export class EventBus extends EventEmitter {
|
|||
/**
|
||||
* Publish an event
|
||||
*/
|
||||
async publish<T = any>(type: string, data: T, metadata?: Record<string, any>): Promise<void> {
|
||||
async publish<T = unknown>(
|
||||
type: string,
|
||||
data: T,
|
||||
metadata?: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
const message: EventBusMessage<T> = {
|
||||
id: this.generateId(),
|
||||
type,
|
||||
|
|
@ -129,9 +133,12 @@ export class EventBus extends EventEmitter {
|
|||
/**
|
||||
* Subscribe to an event
|
||||
*/
|
||||
async subscribe<T = any>(eventType: string, handler: EventHandler<T>): Promise<void> {
|
||||
async subscribe<T = unknown>(eventType: string, handler: EventHandler<T>): Promise<void> {
|
||||
// Register handler
|
||||
this.subscriptions.set(eventType, { channel: `events:${eventType}`, handler });
|
||||
this.subscriptions.set(eventType, {
|
||||
channel: `events:${eventType}`,
|
||||
handler: message => handler(message as EventBusMessage<T>),
|
||||
});
|
||||
|
||||
// Add local listener
|
||||
this.on(eventType, handler);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import type { EventBusMessage, EventHandler, EventSubscription } from './types';
|
||||
|
||||
/**
|
||||
|
|
@ -18,7 +19,7 @@ export class SimpleEventBus {
|
|||
if (!this.subscriptions.has(channel)) {
|
||||
this.subscriptions.set(channel, new Set());
|
||||
}
|
||||
this.subscriptions.get(channel)!.add(subscription);
|
||||
defined(this.subscriptions.get(channel)).add(subscription);
|
||||
this.subscriptionById.set(id, { id, channel, handler });
|
||||
|
||||
return { channel, handler };
|
||||
|
|
@ -66,7 +67,7 @@ export class SimpleEventBus {
|
|||
}
|
||||
}
|
||||
|
||||
async publish(event: string, data: any): Promise<void> {
|
||||
async publish(event: string, data: unknown): Promise<void> {
|
||||
const message: EventBusMessage = {
|
||||
id: `msg-${this.nextId++}`,
|
||||
type: event,
|
||||
|
|
@ -93,14 +94,14 @@ export class SimpleEventBus {
|
|||
// Execute all handlers
|
||||
await Promise.all(
|
||||
handlers.map(handler =>
|
||||
Promise.resolve(handler(message)).catch(err => {
|
||||
Promise.resolve(handler(message)).catch(_err => {
|
||||
// Silently catch errors
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
publishSync(event: string, data: any): void {
|
||||
publishSync(event: string, data: unknown): void {
|
||||
const message: EventBusMessage = {
|
||||
id: `msg-${this.nextId++}`,
|
||||
type: event,
|
||||
|
|
@ -188,7 +189,7 @@ export class SimpleEventBus {
|
|||
}
|
||||
|
||||
hasSubscribers(event: string): boolean {
|
||||
return this.subscriptions.has(event) && this.subscriptions.get(event)!.size > 0;
|
||||
return this.subscriptions.has(event) && defined(this.subscriptions.get(event)).size > 0;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
export interface EventBusMessage<T = any> {
|
||||
export interface EventBusMessage<T = unknown> {
|
||||
id: string;
|
||||
type: string;
|
||||
source: string;
|
||||
|
|
@ -7,7 +7,7 @@ export interface EventBusMessage<T = any> {
|
|||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface EventHandler<T = any> {
|
||||
export interface EventHandler<T = unknown> {
|
||||
(message: EventBusMessage<T>): Promise<void> | void;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,5 +6,12 @@
|
|||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [{ "path": "../../core/logger" }]
|
||||
"references": [
|
||||
{
|
||||
"path": "../../core/logger"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,16 +3,18 @@
|
|||
* Pure types for handler metadata and registration
|
||||
*/
|
||||
|
||||
import type { JobHandler, ScheduledJob } from '@stock-bot/types';
|
||||
import type {
|
||||
DecoratedHandlerClass,
|
||||
HandlerRateLimitConfig,
|
||||
JobHandler,
|
||||
RateLimitWindow,
|
||||
ScheduledJob,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
/**
|
||||
* Rate limit configuration
|
||||
*/
|
||||
export interface RateLimitConfig {
|
||||
points: number;
|
||||
duration: number;
|
||||
blockDuration?: number;
|
||||
}
|
||||
export type RateLimitConfig = HandlerRateLimitConfig & Partial<RateLimitWindow>;
|
||||
|
||||
/**
|
||||
* Metadata for a single operation within a handler
|
||||
|
|
@ -72,6 +74,6 @@ export interface RegistryStats {
|
|||
*/
|
||||
export interface HandlerDiscoveryResult {
|
||||
handler: HandlerMetadata;
|
||||
constructor: any;
|
||||
constructor: DecoratedHandlerClass;
|
||||
filePath?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,7 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import type { JobHandler, ScheduledJob } from '@stock-bot/types';
|
||||
import { HandlerRegistry } from '../src/registry';
|
||||
import type {
|
||||
HandlerConfiguration,
|
||||
HandlerMetadata,
|
||||
OperationMetadata,
|
||||
ScheduleMetadata,
|
||||
} from '../src/types';
|
||||
import type { HandlerConfiguration, HandlerMetadata } from '../src/types';
|
||||
|
||||
describe('HandlerRegistry Edge Cases', () => {
|
||||
let registry: HandlerRegistry;
|
||||
|
|
|
|||
|
|
@ -1,15 +1,17 @@
|
|||
import type { Collection, Document } from 'mongodb';
|
||||
import { createNamespacedCache } from '@stock-bot/cache';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
|
||||
import type {
|
||||
DecoratedHandlerClass,
|
||||
ExecutionContext,
|
||||
HandlerConfigWithSchedule,
|
||||
HandlerMetadata,
|
||||
IHandler,
|
||||
JobHandler,
|
||||
} from '@stock-bot/types';
|
||||
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
|
||||
import type { FetchOptions } from '@stock-bot/utils';
|
||||
import { fetch } from '@stock-bot/utils';
|
||||
import type { Collection, Document } from 'mongodb';
|
||||
// Handler registry is now injected, not imported
|
||||
import { createJobHandler } from '../utils/create-job-handler';
|
||||
|
||||
|
|
@ -40,7 +42,9 @@ export interface JobScheduleOptions {
|
|||
* Abstract base class for all handlers with improved DI
|
||||
* Provides common functionality and structure for queue/event operations
|
||||
*/
|
||||
export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes> implements IHandler {
|
||||
export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
||||
implements IHandler
|
||||
{
|
||||
// Direct service properties - flattened for cleaner access with proper types
|
||||
readonly logger: TServices['logger'];
|
||||
readonly cache: TServices['cache'];
|
||||
|
|
@ -57,7 +61,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
|
||||
constructor(services: TServices, handlerName?: string) {
|
||||
// Read handler name from decorator first, then fallback to parameter or class name
|
||||
const constructor = this.constructor as any;
|
||||
const constructor = this.constructor as DecoratedHandlerClass;
|
||||
this.handlerName =
|
||||
constructor.__handlerName || handlerName || this.constructor.name.toLowerCase();
|
||||
|
||||
|
|
@ -83,28 +87,28 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
* Works with queue (events commented for future)
|
||||
*/
|
||||
async execute(operation: string, input: unknown, context: ExecutionContext): Promise<unknown> {
|
||||
const constructor = this.constructor as any;
|
||||
const constructor = this.constructor as DecoratedHandlerClass;
|
||||
const operations = constructor.__operations || [];
|
||||
|
||||
// Debug logging
|
||||
this.logger.debug('Handler execute called', {
|
||||
handler: this.handlerName,
|
||||
operation,
|
||||
availableOperations: operations.map((op: any) => ({ name: op.name, method: op.method })),
|
||||
availableOperations: operations.map(op => ({ name: op.name, method: op.method })),
|
||||
});
|
||||
|
||||
// Find the operation metadata
|
||||
const operationMeta = operations.find((op: any) => op.name === operation);
|
||||
const operationMeta = operations.find(op => op.name === operation);
|
||||
if (!operationMeta) {
|
||||
this.logger.error('Operation not found', {
|
||||
requestedOperation: operation,
|
||||
availableOperations: operations.map((op: any) => op.name),
|
||||
availableOperations: operations.map(op => op.name),
|
||||
});
|
||||
throw new Error(`Unknown operation: ${operation}`);
|
||||
}
|
||||
|
||||
// Get the method from the instance and call it
|
||||
const method = (this as any)[operationMeta.method];
|
||||
const method: unknown = Reflect.get(this, operationMeta.method);
|
||||
if (typeof method !== 'function') {
|
||||
throw new Error(`Operation method '${operationMeta.method}' not found on handler`);
|
||||
}
|
||||
|
|
@ -125,7 +129,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
if (!this.queue) {
|
||||
throw new Error('Queue service is not available for this handler');
|
||||
}
|
||||
|
||||
|
||||
const jobData = {
|
||||
handler: this.handlerName,
|
||||
operation,
|
||||
|
|
@ -140,7 +144,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
*/
|
||||
protected createExecutionContext(
|
||||
type: 'http' | 'queue' | 'scheduled',
|
||||
metadata: Record<string, any> = {}
|
||||
metadata: Record<string, unknown> = {}
|
||||
): ExecutionContext {
|
||||
return {
|
||||
type,
|
||||
|
|
@ -177,18 +181,18 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
/**
|
||||
* Set cache with handler-prefixed key
|
||||
*/
|
||||
protected async cacheSet(key: string, value: any, ttl?: number): Promise<void> {
|
||||
protected async cacheSet(key: string, value: unknown, ttl?: number): Promise<void> {
|
||||
if (!this.cache) {
|
||||
return;
|
||||
}
|
||||
// Don't add 'cache:' prefix since the cache already has its own prefix
|
||||
return this.cache.set(`${this.handlerName}:${key}`, value, ttl);
|
||||
await this.cache.set(`${this.handlerName}:${key}`, value, ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache with handler-prefixed key
|
||||
*/
|
||||
protected async cacheGet<T = any>(key: string): Promise<T | null> {
|
||||
protected async cacheGet<T = unknown>(key: string): Promise<T | null> {
|
||||
if (!this.cache) {
|
||||
return null;
|
||||
}
|
||||
|
|
@ -210,17 +214,17 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
/**
|
||||
* Set global cache with key
|
||||
*/
|
||||
protected async globalCacheSet(key: string, value: any, ttl?: number): Promise<void> {
|
||||
protected async globalCacheSet(key: string, value: unknown, ttl?: number): Promise<void> {
|
||||
if (!this.globalCache) {
|
||||
return;
|
||||
}
|
||||
return this.globalCache.set(key, value, ttl);
|
||||
await this.globalCache.set(key, value, ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get global cache with key
|
||||
*/
|
||||
protected async globalCacheGet<T = any>(key: string): Promise<T | null> {
|
||||
protected async globalCacheGet<T = unknown>(key: string): Promise<T | null> {
|
||||
if (!this.globalCache) {
|
||||
return null;
|
||||
}
|
||||
|
|
@ -254,7 +258,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
/**
|
||||
* Log with handler context
|
||||
*/
|
||||
protected log(level: 'info' | 'warn' | 'error' | 'debug', message: string, meta?: any): void {
|
||||
protected log(level: 'info' | 'warn' | 'error' | 'debug', message: string, meta?: object): void {
|
||||
this.logger[level](message, { handler: this.handlerName, ...meta });
|
||||
}
|
||||
|
||||
|
|
@ -263,9 +267,9 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
*/
|
||||
protected get http() {
|
||||
return {
|
||||
get: (url: string, options?: any) =>
|
||||
get: (url: string, options?: FetchOptions) =>
|
||||
fetch(url, { ...options, method: 'GET', logger: this.logger }),
|
||||
post: (url: string, data?: any, options?: any) =>
|
||||
post: (url: string, data?: unknown, options?: FetchOptions) =>
|
||||
fetch(url, {
|
||||
...options,
|
||||
method: 'POST',
|
||||
|
|
@ -273,7 +277,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
logger: this.logger,
|
||||
}),
|
||||
put: (url: string, data?: any, options?: any) =>
|
||||
put: (url: string, data?: unknown, options?: FetchOptions) =>
|
||||
fetch(url, {
|
||||
...options,
|
||||
method: 'PUT',
|
||||
|
|
@ -281,7 +285,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
logger: this.logger,
|
||||
}),
|
||||
delete: (url: string, options?: any) =>
|
||||
delete: (url: string, options?: FetchOptions) =>
|
||||
fetch(url, { ...options, method: 'DELETE', logger: this.logger }),
|
||||
};
|
||||
}
|
||||
|
|
@ -314,7 +318,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
|
||||
const operationHandlers: Record<string, JobHandler> = {};
|
||||
for (const opName of metadata.operations) {
|
||||
operationHandlers[opName] = createJobHandler(async (payload: any) => {
|
||||
operationHandlers[opName] = createJobHandler(async (payload: unknown) => {
|
||||
const context: ExecutionContext = {
|
||||
type: 'queue',
|
||||
metadata: { source: 'queue', timestamp: Date.now() },
|
||||
|
|
@ -335,7 +339,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
* This returns metadata only - actual handler instances are created by the scanner
|
||||
*/
|
||||
static extractMetadata(): HandlerMetadata | null {
|
||||
const constructor = this as any;
|
||||
const constructor = this as DecoratedHandlerClass;
|
||||
const handlerName = constructor.__handlerName;
|
||||
if (!handlerName) {
|
||||
return null;
|
||||
|
|
@ -345,9 +349,9 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
const schedules = constructor.__schedules || [];
|
||||
|
||||
// Create scheduled jobs from decorator metadata
|
||||
const scheduledJobs = schedules.map((schedule: any) => {
|
||||
const scheduledJobs = schedules.map(schedule => {
|
||||
// Find the operation name from the method name
|
||||
const operation = operations.find((op: any) => op.method === schedule.operation);
|
||||
const operation = operations.find(op => op.method === schedule.operation);
|
||||
return {
|
||||
type: `${handlerName}-${schedule.operation}`,
|
||||
operation: operation?.name || schedule.operation,
|
||||
|
|
@ -362,7 +366,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
|
||||
return {
|
||||
name: handlerName,
|
||||
operations: operations.map((op: any) => op.name),
|
||||
operations: operations.map(op => op.name),
|
||||
scheduledJobs,
|
||||
description: constructor.__description,
|
||||
};
|
||||
|
|
@ -373,7 +377,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
|
|||
* @param operation The operation name that needs a payload
|
||||
* @returns The payload for the scheduled job, or undefined
|
||||
*/
|
||||
protected getScheduledJobPayload?(operation: string): any;
|
||||
protected getScheduledJobPayload?(operation: string): unknown;
|
||||
|
||||
/**
|
||||
* Lifecycle hooks - can be overridden by subclasses
|
||||
|
|
|
|||
|
|
@ -1,14 +1,20 @@
|
|||
// Bun-compatible decorators (hybrid approach)
|
||||
import type {
|
||||
ClassMemberMetadataDecorator,
|
||||
DecoratedHandlerClass,
|
||||
MemberMetadataDecorator,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
// Bun-compatible legacy decorators.
|
||||
|
||||
/**
|
||||
* Handler decorator - marks a class as a handler
|
||||
* @param name Handler name for registration
|
||||
*/
|
||||
export function Handler(name: string) {
|
||||
return function <T extends { new (...args: any[]): {} }>(target: T, _context?: any) {
|
||||
return function <T extends Function>(target: T, _context?: unknown) {
|
||||
// Store handler name on the constructor
|
||||
(target as any).__handlerName = name;
|
||||
(target as any).__needsAutoRegistration = true;
|
||||
(target as DecoratedHandlerClass).__handlerName = name;
|
||||
(target as DecoratedHandlerClass).__needsAutoRegistration = true;
|
||||
|
||||
return target;
|
||||
};
|
||||
|
|
@ -30,17 +36,17 @@ export function Operation(
|
|||
direct?: boolean;
|
||||
};
|
||||
}
|
||||
): any {
|
||||
return function (target: any, methodName: string, descriptor?: PropertyDescriptor): any {
|
||||
): MemberMetadataDecorator {
|
||||
return function (target: object, methodName: string | symbol, descriptor?: PropertyDescriptor) {
|
||||
// Store metadata directly on the class constructor
|
||||
const constructor = target.constructor;
|
||||
const constructor = target.constructor as DecoratedHandlerClass;
|
||||
|
||||
if (!constructor.__operations) {
|
||||
constructor.__operations = [];
|
||||
}
|
||||
constructor.__operations.push({
|
||||
name,
|
||||
method: methodName,
|
||||
method: String(methodName),
|
||||
batch: options?.batch,
|
||||
});
|
||||
|
||||
|
|
@ -59,7 +65,7 @@ export function QueueSchedule(
|
|||
priority?: number;
|
||||
immediately?: boolean;
|
||||
description?: string;
|
||||
payload?: any;
|
||||
payload?: unknown;
|
||||
batch?: {
|
||||
enabled?: boolean;
|
||||
size?: number;
|
||||
|
|
@ -68,16 +74,16 @@ export function QueueSchedule(
|
|||
direct?: boolean;
|
||||
};
|
||||
}
|
||||
): any {
|
||||
return function (target: any, methodName: string, descriptor?: PropertyDescriptor): any {
|
||||
): MemberMetadataDecorator {
|
||||
return function (target: object, methodName: string | symbol, descriptor?: PropertyDescriptor) {
|
||||
// Store metadata directly on the class constructor
|
||||
const constructor = target.constructor;
|
||||
const constructor = target.constructor as DecoratedHandlerClass;
|
||||
|
||||
if (!constructor.__schedules) {
|
||||
constructor.__schedules = [];
|
||||
}
|
||||
constructor.__schedules.push({
|
||||
operation: methodName,
|
||||
operation: String(methodName),
|
||||
cronPattern,
|
||||
...options,
|
||||
});
|
||||
|
|
@ -92,22 +98,27 @@ export function QueueSchedule(
|
|||
* - Classes: Entire handler will be skipped during auto-registration
|
||||
* - Methods: Individual operations will be skipped during registration
|
||||
*/
|
||||
export function Disabled() {
|
||||
return function (target: any, propertyKey?: string, descriptor?: PropertyDescriptor): any {
|
||||
if (propertyKey) {
|
||||
export function Disabled(): ClassMemberMetadataDecorator {
|
||||
const decorator = function (
|
||||
target: object,
|
||||
propertyKey?: unknown,
|
||||
descriptor?: PropertyDescriptor
|
||||
) {
|
||||
if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') {
|
||||
// Method decorator - mark specific operation as disabled
|
||||
const constructor = target.constructor;
|
||||
const constructor = target.constructor as DecoratedHandlerClass;
|
||||
if (!constructor.__disabledOperations) {
|
||||
constructor.__disabledOperations = [];
|
||||
}
|
||||
constructor.__disabledOperations.push(propertyKey);
|
||||
constructor.__disabledOperations.push(String(propertyKey));
|
||||
return descriptor;
|
||||
} else {
|
||||
// Class decorator - mark entire handler as disabled
|
||||
(target as any).__disabled = true;
|
||||
(target as DecoratedHandlerClass).__disabled = true;
|
||||
return target;
|
||||
}
|
||||
};
|
||||
return decorator as ClassMemberMetadataDecorator;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -124,7 +135,7 @@ export function ScheduledOperation(
|
|||
priority?: number;
|
||||
immediately?: boolean;
|
||||
description?: string;
|
||||
payload?: any;
|
||||
payload?: unknown;
|
||||
batch?: {
|
||||
enabled?: boolean;
|
||||
size?: number;
|
||||
|
|
@ -133,8 +144,8 @@ export function ScheduledOperation(
|
|||
direct?: boolean;
|
||||
};
|
||||
}
|
||||
): any {
|
||||
return function (target: any, methodName: string, descriptor?: PropertyDescriptor): any {
|
||||
): MemberMetadataDecorator {
|
||||
return function (target: object, methodName: string | symbol, descriptor?: PropertyDescriptor) {
|
||||
// Apply both decorators with batch configuration
|
||||
Operation(name, { batch: options?.batch })(target, methodName, descriptor);
|
||||
QueueSchedule(cronPattern, options)(target, methodName, descriptor);
|
||||
|
|
@ -144,7 +155,7 @@ export function ScheduledOperation(
|
|||
|
||||
// Future event decorators - commented for now
|
||||
// export function EventListener(eventName: string) {
|
||||
// return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
|
||||
// return function (target: object, propertyName: string, descriptor: PropertyDescriptor) {
|
||||
// if (!target.constructor.__eventListeners) {
|
||||
// target.constructor.__eventListeners = [];
|
||||
// }
|
||||
|
|
@ -157,7 +168,7 @@ export function ScheduledOperation(
|
|||
// }
|
||||
|
||||
// export function EventPublisher(eventName: string) {
|
||||
// return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
|
||||
// return function (target: object, propertyName: string, descriptor: PropertyDescriptor) {
|
||||
// if (!target.constructor.__eventPublishers) {
|
||||
// target.constructor.__eventPublishers = [];
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -1,110 +1,110 @@
|
|||
/**
|
||||
* Individual rate limit window configuration
|
||||
*/
|
||||
export interface RateLimitWindow {
|
||||
points: number; // Number of allowed points in the time window
|
||||
duration: number; // Time window in seconds
|
||||
blockDuration?: number; // How long to block after limit is hit (seconds)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rate limit configuration for handlers and operations
|
||||
*/
|
||||
export interface RateLimitConfig {
|
||||
limits?: RateLimitWindow[]; // Array of rate limit windows
|
||||
cost?: number; // How many points this operation costs (default: 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Flexible rate limit configuration
|
||||
* Can be:
|
||||
* - A full config object with limits and cost
|
||||
* - Just a cost number (for operations inheriting handler limits)
|
||||
* - An array of limit windows (legacy support)
|
||||
* - A single limit window (legacy support)
|
||||
*/
|
||||
export type RateLimitOptions = RateLimitConfig | number | RateLimitWindow[] | RateLimitWindow;
|
||||
|
||||
/**
|
||||
* RateLimit decorator - configures rate limiting for handlers or operations
|
||||
*
|
||||
* Can be applied to:
|
||||
* - Classes: Sets default rate limit for all operations in the handler
|
||||
* - Methods: Sets specific rate limit for individual operations (overrides handler-level)
|
||||
*
|
||||
* @param options Rate limit configuration - flexible format
|
||||
*
|
||||
* @example
|
||||
* // Handler-level rate limit with multiple windows
|
||||
* @Handler('myHandler')
|
||||
* @RateLimit({
|
||||
* limits: [
|
||||
* { points: 100, duration: 1 }, // 100 points/second
|
||||
* { points: 10000, duration: 3600 } // 10k points/hour
|
||||
* ],
|
||||
* cost: 1 // Default cost for all operations
|
||||
* })
|
||||
* class MyHandler extends BaseHandler {
|
||||
* // All operations inherit these limits
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // Operation-specific cost only (inherits handler limits)
|
||||
* @Operation('fetch-simple')
|
||||
* @RateLimit(1) // Costs 1 point
|
||||
* async fetchSimple() {}
|
||||
*
|
||||
* @Operation('fetch-complex')
|
||||
* @RateLimit({ cost: 10 }) // Costs 10 points
|
||||
* async fetchComplex() {}
|
||||
*
|
||||
* @example
|
||||
* // Operation with custom limits and cost
|
||||
* @Operation('special-operation')
|
||||
* @RateLimit({
|
||||
* limits: [
|
||||
* { points: 10, duration: 60 } // More restrictive: 10/minute
|
||||
* ],
|
||||
* cost: 5
|
||||
* })
|
||||
* async specialOperation() {}
|
||||
*/
|
||||
export function RateLimit(options: RateLimitOptions) {
|
||||
return function (target: any, propertyKey?: string, descriptor?: PropertyDescriptor): any {
|
||||
// Normalize options to RateLimitConfig format
|
||||
let config: RateLimitConfig;
|
||||
|
||||
if (typeof options === 'number') {
|
||||
// Just a cost number
|
||||
config = { cost: options };
|
||||
} else if (Array.isArray(options)) {
|
||||
// Array of limit windows (legacy support)
|
||||
config = { limits: options };
|
||||
} else if ('points' in options && 'duration' in options) {
|
||||
// Single limit window (legacy support)
|
||||
config = { limits: [options as RateLimitWindow] };
|
||||
} else {
|
||||
// Already a RateLimitConfig
|
||||
config = options as RateLimitConfig;
|
||||
}
|
||||
|
||||
if (propertyKey) {
|
||||
// Method decorator - operation-specific rate limit
|
||||
const constructor = target.constructor;
|
||||
|
||||
// Initialize rate limits array if not exists
|
||||
if (!constructor.__rateLimits) {
|
||||
constructor.__rateLimits = {};
|
||||
}
|
||||
|
||||
// Store rate limit config for this operation
|
||||
constructor.__rateLimits[propertyKey] = config;
|
||||
|
||||
return descriptor;
|
||||
} else {
|
||||
// Class decorator - handler-level rate limit
|
||||
(target as any).__handlerRateLimit = config;
|
||||
return target;
|
||||
}
|
||||
};
|
||||
}
|
||||
import type { ClassMemberMetadataDecorator, DecoratedHandlerClass } from '@stock-bot/types';
|
||||
|
||||
/**
|
||||
* Individual rate limit window configuration
|
||||
*/
|
||||
export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow;
|
||||
|
||||
/**
|
||||
* Rate limit configuration for handlers and operations
|
||||
*/
|
||||
export type RateLimitConfig = import('@stock-bot/types').HandlerRateLimitConfig;
|
||||
|
||||
/**
|
||||
* Flexible rate limit configuration
|
||||
* Can be:
|
||||
* - A full config object with limits and cost
|
||||
* - Just a cost number (for operations inheriting handler limits)
|
||||
* - An array of limit windows (legacy support)
|
||||
* - A single limit window (legacy support)
|
||||
*/
|
||||
export type RateLimitOptions = RateLimitConfig | number | RateLimitWindow[] | RateLimitWindow;
|
||||
|
||||
/**
|
||||
* RateLimit decorator - configures rate limiting for handlers or operations
|
||||
*
|
||||
* Can be applied to:
|
||||
* - Classes: Sets default rate limit for all operations in the handler
|
||||
* - Methods: Sets specific rate limit for individual operations (overrides handler-level)
|
||||
*
|
||||
* @param options Rate limit configuration - flexible format
|
||||
*
|
||||
* @example
|
||||
* // Handler-level rate limit with multiple windows
|
||||
* @Handler('myHandler')
|
||||
* @RateLimit({
|
||||
* limits: [
|
||||
* { points: 100, duration: 1 }, // 100 points/second
|
||||
* { points: 10000, duration: 3600 } // 10k points/hour
|
||||
* ],
|
||||
* cost: 1 // Default cost for all operations
|
||||
* })
|
||||
* class MyHandler extends BaseHandler {
|
||||
* // All operations inherit these limits
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // Operation-specific cost only (inherits handler limits)
|
||||
* @Operation('fetch-simple')
|
||||
* @RateLimit(1) // Costs 1 point
|
||||
* async fetchSimple() {}
|
||||
*
|
||||
* @Operation('fetch-complex')
|
||||
* @RateLimit({ cost: 10 }) // Costs 10 points
|
||||
* async fetchComplex() {}
|
||||
*
|
||||
* @example
|
||||
* // Operation with custom limits and cost
|
||||
* @Operation('special-operation')
|
||||
* @RateLimit({
|
||||
* limits: [
|
||||
* { points: 10, duration: 60 } // More restrictive: 10/minute
|
||||
* ],
|
||||
* cost: 5
|
||||
* })
|
||||
* async specialOperation() {}
|
||||
*/
|
||||
export function RateLimit(options: RateLimitOptions): ClassMemberMetadataDecorator {
|
||||
const decorator = function (
|
||||
target: object,
|
||||
propertyKey?: unknown,
|
||||
descriptor?: PropertyDescriptor
|
||||
) {
|
||||
// Normalize options to RateLimitConfig format
|
||||
let config: RateLimitConfig;
|
||||
|
||||
if (typeof options === 'number') {
|
||||
// Just a cost number
|
||||
config = { cost: options };
|
||||
} else if (Array.isArray(options)) {
|
||||
// Array of limit windows (legacy support)
|
||||
config = { limits: options };
|
||||
} else if ('points' in options && 'duration' in options) {
|
||||
// Single limit window (legacy support)
|
||||
config = { limits: [options as RateLimitWindow] };
|
||||
} else {
|
||||
// Already a RateLimitConfig
|
||||
config = options as RateLimitConfig;
|
||||
}
|
||||
|
||||
if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') {
|
||||
// Method decorator - operation-specific rate limit
|
||||
const constructor = target.constructor as DecoratedHandlerClass;
|
||||
|
||||
// Initialize rate limits array if not exists
|
||||
if (!constructor.__rateLimits) {
|
||||
constructor.__rateLimits = {};
|
||||
}
|
||||
|
||||
// Store rate limit config for this operation
|
||||
constructor.__rateLimits[String(propertyKey)] = config;
|
||||
|
||||
return descriptor;
|
||||
} else {
|
||||
// Class decorator - handler-level rate limit
|
||||
(target as DecoratedHandlerClass).__handlerRateLimit = config;
|
||||
return target;
|
||||
}
|
||||
};
|
||||
return decorator as ClassMemberMetadataDecorator;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import { BaseHandler } from '../src/base/BaseHandler';
|
||||
|
||||
// Test handler with metadata
|
||||
|
|
@ -23,11 +23,11 @@ class ConfigTestHandler extends BaseHandler {
|
|||
];
|
||||
static __description = 'Test handler for configuration';
|
||||
|
||||
async processData(input: any, context: ExecutionContext) {
|
||||
async processData(input: any, _context: ExecutionContext) {
|
||||
return { processed: true, input };
|
||||
}
|
||||
|
||||
async validateData(input: any, context: ExecutionContext) {
|
||||
async validateData(input: any, _context: ExecutionContext) {
|
||||
return { valid: true, input };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import * as utils from '@stock-bot/utils';
|
||||
import { BaseHandler } from '../src/base/BaseHandler';
|
||||
|
|
|
|||
|
|
@ -1,13 +1,8 @@
|
|||
import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
|
||||
import type { Collection, Db, MongoClient } from 'mongodb';
|
||||
import type { Pool, QueryResult } from 'pg';
|
||||
import type { SimpleBrowser } from '@stock-bot/browser';
|
||||
import type { CacheProvider } from '@stock-bot/cache';
|
||||
import type { QueryResult } from 'pg';
|
||||
import type { Logger } from '@stock-bot/logger';
|
||||
import type { SimpleProxyManager } from '@stock-bot/proxy';
|
||||
import type { Queue, QueueManager } from '@stock-bot/queue';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler';
|
||||
import { Handler, Operation } from '../src/decorators/decorators';
|
||||
|
||||
|
|
@ -68,7 +63,7 @@ type MockMongoDB = {
|
|||
|
||||
describe('BaseHandler', () => {
|
||||
let mockServices: IServiceContainer;
|
||||
let mockContext: ExecutionContext;
|
||||
let _mockContext: ExecutionContext;
|
||||
let mockQueue: MockQueue;
|
||||
let mockQueueManager: MockQueueManager;
|
||||
let mockCache: MockCache;
|
||||
|
|
@ -139,7 +134,7 @@ describe('BaseHandler', () => {
|
|||
queue: mockQueue as unknown as ServiceTypes['queue'],
|
||||
};
|
||||
|
||||
mockContext = {
|
||||
_mockContext = {
|
||||
logger: mockLogger as unknown as Logger,
|
||||
traceId: 'trace-123',
|
||||
handlerName: 'TestHandler',
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ describe('createJobHandler', () => {
|
|||
it('should create a type-safe job handler function', () => {
|
||||
const handler = createJobHandler<TestPayload, TestResult>(async job => {
|
||||
// Job should have correct payload type
|
||||
const { userId, action, data } = job.data;
|
||||
const { userId, action: _action, data: _data } = job.data;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
|
@ -166,8 +166,8 @@ describe('createJobHandler', () => {
|
|||
|
||||
// Type-safe access to nested properties
|
||||
const userId = job.data.user.id;
|
||||
const requestType = job.data.request.type;
|
||||
const version = job.data.metadata.version;
|
||||
const _requestType = job.data.request.type;
|
||||
const _version = job.data.metadata.version;
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
|
|
|
|||
|
|
@ -376,7 +376,7 @@ describe('Decorators Edge Cases', () => {
|
|||
|
||||
@Operation('hasOwnProperty-op')
|
||||
hasOwnProperty(v: string | symbol): boolean {
|
||||
return super.hasOwnProperty(v);
|
||||
return Object.prototype.hasOwnProperty.call(this, v);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
|
||||
import type { CacheProvider } from '@stock-bot/cache';
|
||||
import type { Logger } from '@stock-bot/logger';
|
||||
import type { Queue, QueueManager } from '@stock-bot/queue';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
|
||||
import type { ExecutionContext } from '@stock-bot/types';
|
||||
import { BaseHandler } from '../src/base/BaseHandler';
|
||||
import {
|
||||
Handler,
|
||||
|
|
|
|||
|
|
@ -28,20 +28,13 @@ describe('Handlers Package Exports', () => {
|
|||
expect(typeof handlersExports.Disabled).toBe('function');
|
||||
});
|
||||
|
||||
|
||||
it('should export types', () => {
|
||||
// Type tests - compile-time checks
|
||||
type TestJobScheduleOptions = handlersExports.JobScheduleOptions;
|
||||
type TestExecutionContext = handlersExports.ExecutionContext;
|
||||
type TestIHandler = handlersExports.IHandler;
|
||||
type TestJobHandler = handlersExports.JobHandler;
|
||||
type TestScheduledJob = handlersExports.ScheduledJob;
|
||||
type TestHandlerConfig = handlersExports.HandlerConfig;
|
||||
type TestHandlerConfigWithSchedule = handlersExports.HandlerConfigWithSchedule;
|
||||
type TestTypedJobHandler = handlersExports.TypedJobHandler;
|
||||
|
||||
type TestHandlerMetadata = handlersExports.HandlerMetadata;
|
||||
type TestOperationMetadata = handlersExports.OperationMetadata;
|
||||
type TestIServiceContainer = handlersExports.IServiceContainer;
|
||||
|
||||
// Runtime type usage tests
|
||||
const scheduleOptions: TestJobScheduleOptions = {
|
||||
|
|
@ -74,5 +67,4 @@ describe('Handlers Package Exports', () => {
|
|||
expect(handlerMetadata).toBeDefined();
|
||||
expect(operationMetadata).toBeDefined();
|
||||
});
|
||||
|
||||
});
|
||||
|
|
|
|||
18
libs/core/invariants/package.json
Normal file
18
libs/core/invariants/package.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "@stock-bot/invariants",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf dist"
|
||||
}
|
||||
}
|
||||
15
libs/core/invariants/src/index.ts
Normal file
15
libs/core/invariants/src/index.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
/** Assert required input without turning missing data into NaN or a later TypeError. */
|
||||
export function defined<T>(value: T | null | undefined, message = 'Required value is missing'): T {
|
||||
if (value === undefined || value === null) {
|
||||
throw new Error(message);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function at<T>(values: ArrayLike<T>, index: number): T {
|
||||
const value = values[index];
|
||||
if (value === undefined) {
|
||||
throw new RangeError(`Missing array element at index ${index} (length ${values.length})`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
5
libs/core/invariants/tsconfig.json
Normal file
5
libs/core/invariants/tsconfig.json
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"extends": "../../../tsconfig.lib.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist", "composite": true },
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
|
|
@ -183,12 +183,12 @@ export class Logger {
|
|||
}
|
||||
|
||||
if (typeof message === 'string') {
|
||||
(this.pino as any)[level](data, message);
|
||||
this.pino[level](data, message);
|
||||
} else {
|
||||
if (globalConfig.hideObject && level !== 'error' && level !== 'fatal') {
|
||||
(this.pino as any)[level]({}, `Object logged (hidden)`);
|
||||
this.pino[level]({}, `Object logged (hidden)`);
|
||||
} else {
|
||||
(this.pino as any)[level]({ ...data, data: message }, 'Object logged');
|
||||
this.pino[level]({ ...data, data: message }, 'Object logged');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -210,8 +210,8 @@ export class Logger {
|
|||
this.log('warn', message, metadata);
|
||||
}
|
||||
|
||||
error(message: string | object, metadata?: (LogMetadata & { error?: any }) | unknown): void {
|
||||
let data: any = {};
|
||||
error(message: string | object, metadata?: unknown): void {
|
||||
let data: Record<string, unknown> = {};
|
||||
|
||||
// Handle metadata parameter normalization
|
||||
if (metadata instanceof Error) {
|
||||
|
|
@ -242,8 +242,8 @@ export class Logger {
|
|||
this.log('error', message, data);
|
||||
}
|
||||
|
||||
fatal(message: string | object, metadata?: (LogMetadata & { error?: any }) | unknown): void {
|
||||
let data: any = {};
|
||||
fatal(message: string | object, metadata?: unknown): void {
|
||||
let data: Record<string, unknown> = {};
|
||||
|
||||
// Handle metadata parameter normalization (same as error)
|
||||
if (metadata instanceof Error) {
|
||||
|
|
@ -273,7 +273,7 @@ export class Logger {
|
|||
/**
|
||||
* Normalize any error type to a structured format
|
||||
*/
|
||||
private normalizeError(error: any): any {
|
||||
private normalizeError(error: unknown): LogMetadata {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
name: error.name,
|
||||
|
|
@ -283,13 +283,14 @@ export class Logger {
|
|||
}
|
||||
|
||||
if (error && typeof error === 'object') {
|
||||
const errorObject = error as Record<string, unknown>;
|
||||
// Handle error-like objects
|
||||
return {
|
||||
name: error.name || 'UnknownError',
|
||||
message: error.message || error.toString(),
|
||||
...(error.stack && { stack: error.stack }),
|
||||
...(error.code && { code: error.code }),
|
||||
...(error.status && { status: error.status }),
|
||||
name: errorObject.name || 'UnknownError',
|
||||
message: errorObject.message || String(error),
|
||||
...(errorObject.stack ? { stack: errorObject.stack } : {}),
|
||||
...(errorObject.code ? { code: errorObject.code } : {}),
|
||||
...(errorObject.status ? { status: errorObject.status } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,13 +12,11 @@ export type LoggerLike = Pick<Logger, Exclude<LogLevel, 'fatal'>> &
|
|||
|
||||
// Context that persists across log calls
|
||||
export interface LogContext {
|
||||
[key: string]: any;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// Metadata for individual log entries
|
||||
export interface LogMetadata {
|
||||
[key: string]: any;
|
||||
}
|
||||
export type LogMetadata = object;
|
||||
|
||||
// Logger configuration
|
||||
export interface LoggerConfig {
|
||||
|
|
|
|||
|
|
@ -17,7 +17,8 @@
|
|||
"@stock-bot/cache": "*",
|
||||
"@stock-bot/handler-registry": "*",
|
||||
"@stock-bot/logger": "*",
|
||||
"@stock-bot/types": "*"
|
||||
"@stock-bot/types": "*",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.3.0",
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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', {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
|
||||
import type { Logger } from '@stock-bot/logger';
|
||||
import { processBatchJob, processItems } from '../src/batch-processor';
|
||||
import type { BatchJobData, ProcessOptions, Queue, QueueManager } from '../src/types';
|
||||
import type { BatchJobData, ProcessOptions, QueueManager } from '../src/types';
|
||||
|
||||
describe('Batch Processor', () => {
|
||||
type MockLogger = {
|
||||
|
|
@ -122,7 +121,7 @@ describe('Batch Processor', () => {
|
|||
});
|
||||
|
||||
// processBatchJob should still complete even if addBulk fails
|
||||
const result = await processBatchJob(
|
||||
const _result = await processBatchJob(
|
||||
batchData,
|
||||
'test-queue',
|
||||
mockQueueManager as unknown as QueueManager
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { Queue } from '../src/queue';
|
||||
import type { JobData, QueueWorkerConfig, RedisConfig } from '../src/types';
|
||||
import type { QueueWorkerConfig, RedisConfig } from '../src/types';
|
||||
|
||||
describe('Queue Class', () => {
|
||||
const mockRedisConfig: RedisConfig = {
|
||||
|
|
|
|||
|
|
@ -210,7 +210,7 @@ describe.skip('QueueManager', () => {
|
|||
mockLogger
|
||||
);
|
||||
|
||||
const queue = manager.createQueue('test-queue');
|
||||
const _queue = manager.createQueue('test-queue');
|
||||
const stats = await manager.getQueueStats('test-queue');
|
||||
|
||||
expect(stats).toBeDefined();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { createServiceCache, ServiceCache } from '../src/service-cache';
|
||||
import {
|
||||
generateCachePrefix,
|
||||
|
|
|
|||
|
|
@ -7,9 +7,20 @@
|
|||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [
|
||||
{ "path": "../cache" },
|
||||
{ "path": "../handler-registry" },
|
||||
{ "path": "../logger" },
|
||||
{ "path": "../types" }
|
||||
{
|
||||
"path": "../cache"
|
||||
},
|
||||
{
|
||||
"path": "../handler-registry"
|
||||
},
|
||||
{
|
||||
"path": "../logger"
|
||||
},
|
||||
{
|
||||
"path": "../types"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,5 +40,18 @@ export interface ServiceTypes {
|
|||
}
|
||||
|
||||
export interface IServiceContainer extends ServiceTypes {
|
||||
readonly custom?: Record<string, any>;
|
||||
readonly custom?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Validate required capabilities at the boundary before starting any work. */
|
||||
export function requireServices<T extends ServiceTypes, K extends keyof ServiceTypes>(
|
||||
services: T,
|
||||
...keys: K[]
|
||||
): T & { [P in K]-?: NonNullable<ServiceTypes[P]> } {
|
||||
for (const key of keys) {
|
||||
if (services[key] === null || services[key] === undefined) {
|
||||
throw new Error(`Required service '${key}' is unavailable`);
|
||||
}
|
||||
}
|
||||
return services as T & { [P in K]-?: NonNullable<ServiceTypes[P]> };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ export class Shutdown {
|
|||
return {
|
||||
isShuttingDown: this.isShuttingDown,
|
||||
signal: this.triggerSignal,
|
||||
callbackCount: this.callbacks.length
|
||||
callbackCount: this.callbacks.length,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -64,9 +64,9 @@ export class Shutdown {
|
|||
async shutdown(signal?: string): Promise<void> {
|
||||
// If already shutting down, return the existing promise
|
||||
if (this.shutdownPromise) {
|
||||
this.logger.warn('Shutdown already in progress, ignoring additional request', {
|
||||
this.logger.warn('Shutdown already in progress, ignoring additional request', {
|
||||
originalSignal: this.triggerSignal,
|
||||
newSignal: signal
|
||||
newSignal: signal,
|
||||
});
|
||||
return this.shutdownPromise;
|
||||
}
|
||||
|
|
@ -77,16 +77,16 @@ export class Shutdown {
|
|||
|
||||
this.isShuttingDown = true;
|
||||
this.triggerSignal = signal || 'manual';
|
||||
|
||||
this.logger.info('Starting graceful shutdown', {
|
||||
|
||||
this.logger.info('Starting graceful shutdown', {
|
||||
signal: this.triggerSignal,
|
||||
timeout: this.shutdownTimeout,
|
||||
callbackCount: this.callbacks.length
|
||||
callbackCount: this.callbacks.length,
|
||||
});
|
||||
|
||||
// Create and store the shutdown promise
|
||||
this.shutdownPromise = this.performShutdown();
|
||||
|
||||
|
||||
try {
|
||||
await this.shutdownPromise;
|
||||
this.logger.info('Graceful shutdown completed successfully');
|
||||
|
|
@ -97,23 +97,23 @@ export class Shutdown {
|
|||
}
|
||||
|
||||
private async performShutdown(): Promise<void> {
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Shutdown timeout')), this.shutdownTimeout)
|
||||
);
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('Shutdown timeout')), this.shutdownTimeout);
|
||||
});
|
||||
try {
|
||||
await Promise.race([this.executeCallbacks(), timeout]);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
private async executeCallbacks(): Promise<void> {
|
||||
const sorted = [...this.callbacks].sort((a, b) => a.priority - b.priority);
|
||||
|
||||
this.logger.debug('Executing shutdown callbacks', {
|
||||
|
||||
this.logger.debug('Executing shutdown callbacks', {
|
||||
count: sorted.length,
|
||||
callbacks: sorted.map(c => ({ name: c.name || 'unnamed', priority: c.priority }))
|
||||
callbacks: sorted.map(c => ({ name: c.name || 'unnamed', priority: c.priority })),
|
||||
});
|
||||
|
||||
let completed = 0;
|
||||
|
|
@ -124,9 +124,9 @@ export class Shutdown {
|
|||
try {
|
||||
this.logger.debug(`Starting shutdown callback: ${callbackName}`, { priority });
|
||||
const startTime = Date.now();
|
||||
|
||||
|
||||
await callback();
|
||||
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
completed++;
|
||||
this.logger.debug(`Completed shutdown callback: ${callbackName}`, { duration, priority });
|
||||
|
|
@ -136,10 +136,10 @@ export class Shutdown {
|
|||
}
|
||||
}
|
||||
|
||||
this.logger.info('Shutdown callbacks execution completed', {
|
||||
this.logger.info('Shutdown callbacks execution completed', {
|
||||
total: sorted.length,
|
||||
completed,
|
||||
failed
|
||||
failed,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -155,7 +155,7 @@ export class Shutdown {
|
|||
// Use process.on instead of process.once to handle multiple signals
|
||||
process.on(signal, async () => {
|
||||
this.logger.info(`Received ${signal} signal`);
|
||||
|
||||
|
||||
// If already shutting down, ignore the signal
|
||||
if (this.isShuttingDown || this.shutdownPromise) {
|
||||
this.logger.info(`Already shutting down, ignoring ${signal}`);
|
||||
|
|
@ -164,22 +164,22 @@ export class Shutdown {
|
|||
|
||||
try {
|
||||
await this.shutdown(signal);
|
||||
|
||||
|
||||
// Add small delay to ensure logs are flushed
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
|
||||
this.logger.info('Exiting process with code 0');
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
this.logger.error('Shutdown error, exiting with code 1', { error });
|
||||
|
||||
|
||||
// Add small delay to ensure error logs are flushed
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
this.logger.debug(`Registered handler for ${signal}`);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,5 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import {
|
||||
onShutdown,
|
||||
Shutdown,
|
||||
SHUTDOWN_DEFAULTS,
|
||||
} from '../src';
|
||||
import type { ShutdownOptions } from '../src/types';
|
||||
import { onShutdown, Shutdown } from '../src';
|
||||
|
||||
describe('Shutdown Comprehensive Tests', () => {
|
||||
let shutdownInstance: Shutdown;
|
||||
|
|
@ -15,7 +10,7 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
// Create a fresh instance for each test
|
||||
shutdownInstance = new Shutdown({ autoRegister: false });
|
||||
});
|
||||
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up singleton
|
||||
(Shutdown as any).instance = null;
|
||||
|
|
@ -24,9 +19,9 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
describe('Basic Functionality', () => {
|
||||
it('should register callbacks', () => {
|
||||
const callback = mock(async () => {});
|
||||
|
||||
|
||||
shutdownInstance.onShutdown(callback, 50, 'test-callback');
|
||||
|
||||
|
||||
// We can't directly check callback count, but we can verify it executes
|
||||
expect(callback).toBeDefined();
|
||||
});
|
||||
|
|
@ -34,19 +29,19 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
it('should execute callbacks on shutdown', async () => {
|
||||
const callback1 = mock(async () => {});
|
||||
const callback2 = mock(async () => {});
|
||||
|
||||
|
||||
shutdownInstance.onShutdown(callback1, 10, 'callback-1');
|
||||
shutdownInstance.onShutdown(callback2, 20, 'callback-2');
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
|
||||
|
||||
expect(callback1).toHaveBeenCalledTimes(1);
|
||||
expect(callback2).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should execute callbacks in priority order', async () => {
|
||||
const order: string[] = [];
|
||||
|
||||
|
||||
const highPriority = mock(async () => {
|
||||
order.push('high');
|
||||
});
|
||||
|
|
@ -56,14 +51,14 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
const lowPriority = mock(async () => {
|
||||
order.push('low');
|
||||
});
|
||||
|
||||
|
||||
// Lower number = higher priority
|
||||
shutdownInstance.onShutdown(lowPriority, 30, 'low');
|
||||
shutdownInstance.onShutdown(highPriority, 10, 'high');
|
||||
shutdownInstance.onShutdown(mediumPriority, 20, 'medium');
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
|
||||
|
||||
expect(order).toEqual(['high', 'medium', 'low']);
|
||||
});
|
||||
|
||||
|
|
@ -72,13 +67,13 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
const errorCallback = mock(async () => {
|
||||
throw new Error('Callback error');
|
||||
});
|
||||
|
||||
|
||||
shutdownInstance.onShutdown(successCallback, 10, 'success');
|
||||
shutdownInstance.onShutdown(errorCallback, 20, 'error');
|
||||
|
||||
|
||||
// Should not throw even if callbacks fail
|
||||
await expect(shutdownInstance.shutdown()).resolves.toBeUndefined();
|
||||
|
||||
|
||||
expect(successCallback).toHaveBeenCalledTimes(1);
|
||||
expect(errorCallback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
|
@ -86,11 +81,11 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
it('should only shutdown once', async () => {
|
||||
const callback = mock(async () => {});
|
||||
shutdownInstance.onShutdown(callback);
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
await shutdownInstance.shutdown();
|
||||
await shutdownInstance.shutdown();
|
||||
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
|
@ -101,47 +96,47 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
throw new Error('Should not execute');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
shutdownInstance.onShutdown(firstCallback);
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
|
||||
|
||||
expect(firstCallback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Timeout Handling', () => {
|
||||
it('should timeout if callbacks take too long', async () => {
|
||||
const slowShutdown = new Shutdown({
|
||||
const slowShutdown = new Shutdown({
|
||||
timeout: 100,
|
||||
autoRegister: false
|
||||
autoRegister: false,
|
||||
});
|
||||
|
||||
|
||||
const slowCallback = mock(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
});
|
||||
|
||||
|
||||
slowShutdown.onShutdown(slowCallback, 10, 'slow');
|
||||
|
||||
|
||||
const startTime = Date.now();
|
||||
await expect(slowShutdown.shutdown()).rejects.toThrow('Shutdown timeout');
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
|
||||
expect(duration).toBeLessThan(150);
|
||||
});
|
||||
|
||||
it('should complete if callbacks finish before timeout', async () => {
|
||||
const quickShutdown = new Shutdown({
|
||||
const quickShutdown = new Shutdown({
|
||||
timeout: 1000,
|
||||
autoRegister: false
|
||||
autoRegister: false,
|
||||
});
|
||||
|
||||
|
||||
const quickCallback = mock(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
});
|
||||
|
||||
|
||||
quickShutdown.onShutdown(quickCallback);
|
||||
|
||||
|
||||
await expect(quickShutdown.shutdown()).resolves.toBeUndefined();
|
||||
expect(quickCallback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
|
@ -151,19 +146,19 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
it('should return same instance via getInstance', () => {
|
||||
const instance1 = Shutdown.getInstance();
|
||||
const instance2 = Shutdown.getInstance();
|
||||
|
||||
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
|
||||
it('should maintain state across getInstance calls', async () => {
|
||||
const instance = Shutdown.getInstance();
|
||||
const callback = mock(async () => {});
|
||||
|
||||
|
||||
instance.onShutdown(callback);
|
||||
|
||||
|
||||
const sameInstance = Shutdown.getInstance();
|
||||
await sameInstance.shutdown();
|
||||
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -171,29 +166,29 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
describe('Global onShutdown Function', () => {
|
||||
it('should use singleton instance', async () => {
|
||||
const callback = mock(async () => {});
|
||||
|
||||
|
||||
// Use global function
|
||||
onShutdown(callback, 50, 'global-callback');
|
||||
|
||||
|
||||
// Get instance and shutdown
|
||||
const instance = Shutdown.getInstance();
|
||||
await instance.shutdown();
|
||||
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle different parameter orders', () => {
|
||||
const callback = mock(async () => {});
|
||||
|
||||
|
||||
// Test with all parameters
|
||||
onShutdown(callback, 10, 'with-all-params');
|
||||
|
||||
|
||||
// Test with default priority
|
||||
onShutdown(callback);
|
||||
|
||||
|
||||
// Test with priority but no name
|
||||
onShutdown(callback, 20);
|
||||
|
||||
|
||||
expect(callback).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -203,11 +198,11 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
const syncCallback = mock(() => {
|
||||
// Synchronous callback
|
||||
});
|
||||
|
||||
|
||||
shutdownInstance.onShutdown(syncCallback as any, 10, 'sync');
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
|
||||
|
||||
expect(syncCallback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
|
@ -215,9 +210,9 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
const throwingCallback = mock(async () => {
|
||||
throw 'string error';
|
||||
});
|
||||
|
||||
|
||||
shutdownInstance.onShutdown(throwingCallback);
|
||||
|
||||
|
||||
// Should not throw
|
||||
await expect(shutdownInstance.shutdown()).resolves.toBeUndefined();
|
||||
expect(throwingCallback).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -229,16 +224,14 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
});
|
||||
|
||||
it('should handle many callbacks', async () => {
|
||||
const callbacks = Array.from({ length: 50 }, (_, i) =>
|
||||
mock(async () => {})
|
||||
);
|
||||
|
||||
const callbacks = Array.from({ length: 50 }, (_, _i) => mock(async () => {}));
|
||||
|
||||
callbacks.forEach((cb, i) => {
|
||||
shutdownInstance.onShutdown(cb, i, `callback-${i}`);
|
||||
});
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
|
||||
|
||||
callbacks.forEach(cb => {
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
|
@ -248,19 +241,19 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
describe('Default Values', () => {
|
||||
it('should use default priority', async () => {
|
||||
const callback = mock(async () => {});
|
||||
|
||||
|
||||
// No priority specified
|
||||
shutdownInstance.onShutdown(callback);
|
||||
|
||||
|
||||
await shutdownInstance.shutdown();
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should use default timeout', () => {
|
||||
const defaultShutdown = new Shutdown();
|
||||
|
||||
const _defaultShutdown = new Shutdown();
|
||||
|
||||
// Can't directly test timeout value, but we can verify it doesn't throw
|
||||
expect(() => new Shutdown()).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ describe('Shutdown Signal Handlers', () => {
|
|||
process.once = processOnceSpy as any;
|
||||
|
||||
// Mock process.exit
|
||||
processExitSpy = mock((code?: number) => {
|
||||
processExitSpy = mock((_code?: number) => {
|
||||
// Just record the call, don't actually exit
|
||||
return undefined as never;
|
||||
});
|
||||
|
|
@ -79,7 +79,7 @@ describe('Shutdown Signal Handlers', () => {
|
|||
|
||||
const listeners = (global as any).__testListeners;
|
||||
const sigtermHandler = listeners['SIGTERM']?.[0];
|
||||
|
||||
|
||||
expect(sigtermHandler).toBeDefined();
|
||||
|
||||
// Mock the shutdown method to track it was called
|
||||
|
|
@ -101,7 +101,7 @@ describe('Shutdown Signal Handlers', () => {
|
|||
|
||||
const listeners = (global as any).__testListeners;
|
||||
const sigintHandler = listeners['SIGINT']?.[0];
|
||||
|
||||
|
||||
expect(sigintHandler).toBeDefined();
|
||||
|
||||
// Mock the shutdown method
|
||||
|
|
@ -162,17 +162,17 @@ describe('Shutdown Signal Handlers', () => {
|
|||
const instance2 = Shutdown.getInstance();
|
||||
|
||||
expect(instance1).toBe(instance2);
|
||||
|
||||
|
||||
// Only one set of signal handlers should be registered
|
||||
expect(processOnceSpy).toHaveBeenCalledTimes(2); // SIGTERM and SIGINT
|
||||
});
|
||||
|
||||
it('should handle callbacks registered before signal', async () => {
|
||||
shutdown = new Shutdown({ autoRegister: true });
|
||||
|
||||
|
||||
const callback1 = mock(async () => {});
|
||||
const callback2 = mock(async () => {});
|
||||
|
||||
|
||||
shutdown.onShutdown(callback1, 10);
|
||||
shutdown.onShutdown(callback2, 20);
|
||||
|
||||
|
|
@ -200,7 +200,7 @@ describe('Shutdown Signal Handlers', () => {
|
|||
shutdown = new Shutdown({ autoRegister: true });
|
||||
|
||||
const listeners = (global as any).__testListeners;
|
||||
|
||||
|
||||
// Verify handlers exist
|
||||
expect(listeners['SIGTERM']).toBeDefined();
|
||||
expect(listeners['SIGINT']).toBeDefined();
|
||||
|
|
@ -216,4 +216,4 @@ describe('Shutdown Signal Handlers', () => {
|
|||
expect(processOnceSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -29,13 +29,61 @@ export interface DecoratorMetadata {
|
|||
/**
|
||||
* Type for decorator factories
|
||||
*/
|
||||
export type DecoratorFactory<T = any> = (target: T, context?: any) => T | void;
|
||||
export type DecoratorFactory<T = object> = (target: T, context?: unknown) => T | void;
|
||||
|
||||
/**
|
||||
* Type for method decorators
|
||||
*/
|
||||
export type MethodDecoratorFactory = (
|
||||
target: any,
|
||||
target: object,
|
||||
propertyKey: string,
|
||||
descriptor?: PropertyDescriptor
|
||||
) => any;
|
||||
) => void | PropertyDescriptor;
|
||||
|
||||
/** Metadata shared by decorators, discovery, and handler dispatch. */
|
||||
export interface RateLimitWindow {
|
||||
points: number;
|
||||
duration: number;
|
||||
blockDuration?: number;
|
||||
}
|
||||
export interface HandlerRateLimitConfig {
|
||||
limits?: RateLimitWindow[];
|
||||
cost?: number;
|
||||
}
|
||||
export interface HandlerOperationDefinition {
|
||||
name: string;
|
||||
method: string;
|
||||
batch?: import('./handlers').ScheduledJob['batch'];
|
||||
}
|
||||
export interface HandlerScheduleDefinition {
|
||||
operation: string;
|
||||
cronPattern: string;
|
||||
priority?: number;
|
||||
immediately?: boolean;
|
||||
description?: string;
|
||||
payload?: unknown;
|
||||
batch?: import('./handlers').ScheduledJob['batch'];
|
||||
}
|
||||
export interface DecoratedHandlerMetadata {
|
||||
__handlerName?: string;
|
||||
__description?: string;
|
||||
__needsAutoRegistration?: boolean;
|
||||
__operations?: HandlerOperationDefinition[];
|
||||
__schedules?: HandlerScheduleDefinition[];
|
||||
__disabled?: boolean;
|
||||
__disabledOperations?: string[];
|
||||
__handlerRateLimit?: HandlerRateLimitConfig;
|
||||
__rateLimits?: Record<string, HandlerRateLimitConfig>;
|
||||
}
|
||||
export type DecoratedHandlerClass = Function & DecoratedHandlerMetadata;
|
||||
export interface MemberMetadataDecorator {
|
||||
(target: object, propertyKey: string | symbol): void;
|
||||
(
|
||||
target: object,
|
||||
propertyKey: string | symbol,
|
||||
descriptor: PropertyDescriptor | undefined
|
||||
): PropertyDescriptor | void;
|
||||
}
|
||||
export interface ClassMemberMetadataDecorator extends MemberMetadataDecorator {
|
||||
<T extends Function>(target: T): T;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,3 +71,14 @@ export type {
|
|||
|
||||
// Export queue types
|
||||
export type { JobData, JobOptions, QueueStats, BatchJobData, QueueWorkerConfig } from './queue';
|
||||
|
||||
export type {
|
||||
DecoratedHandlerClass,
|
||||
DecoratedHandlerMetadata,
|
||||
HandlerOperationDefinition,
|
||||
HandlerScheduleDefinition,
|
||||
HandlerRateLimitConfig,
|
||||
RateLimitWindow,
|
||||
MemberMetadataDecorator,
|
||||
ClassMemberMetadataDecorator,
|
||||
} from './decorators';
|
||||
|
|
|
|||
|
|
@ -1,6 +1,20 @@
|
|||
import type { Logger } from '@stock-bot/logger';
|
||||
import type { Document, OptionalUnlessRequiredId } from 'mongodb';
|
||||
import type {
|
||||
AggregateOptions,
|
||||
BulkWriteOptions,
|
||||
CountDocumentsOptions,
|
||||
CreateCollectionOptions,
|
||||
CreateIndexesOptions,
|
||||
DeleteOptions,
|
||||
Document,
|
||||
DropIndexesOptions,
|
||||
Filter,
|
||||
FindOptions,
|
||||
IndexSpecification,
|
||||
OptionalUnlessRequiredId,
|
||||
UpdateOptions,
|
||||
} from 'mongodb';
|
||||
import { Collection, Db, MongoClient } from 'mongodb';
|
||||
import type { Logger } from '@stock-bot/logger';
|
||||
import type {
|
||||
ConnectionEvents,
|
||||
DocumentBase,
|
||||
|
|
@ -312,15 +326,18 @@ export class MongoDBClient {
|
|||
}
|
||||
}
|
||||
|
||||
this.logger.debug(`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`, {
|
||||
database: dbName,
|
||||
collection: collectionName,
|
||||
totalRecords: documents.length,
|
||||
inserted: totalInserted,
|
||||
updated: totalUpdated,
|
||||
errors: errors.length,
|
||||
uniqueKeys: keyFields,
|
||||
});
|
||||
this.logger.debug(
|
||||
`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`,
|
||||
{
|
||||
database: dbName,
|
||||
collection: collectionName,
|
||||
totalRecords: documents.length,
|
||||
inserted: totalInserted,
|
||||
updated: totalUpdated,
|
||||
errors: errors.length,
|
||||
uniqueKeys: keyFields,
|
||||
}
|
||||
);
|
||||
|
||||
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors };
|
||||
}
|
||||
|
|
@ -366,22 +383,25 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Insert multiple documents
|
||||
*/
|
||||
async insertMany<T = any>(
|
||||
async insertMany<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
documents: T[],
|
||||
options?: any,
|
||||
options?: BulkWriteOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const now = new Date();
|
||||
|
||||
const docsWithTimestamps = documents.map(doc => ({
|
||||
...doc,
|
||||
created_at: (doc as any).created_at || now,
|
||||
created_at: doc.created_at || now,
|
||||
updated_at: now,
|
||||
}));
|
||||
|
||||
const result = await collection.insertMany(docsWithTimestamps as any, options);
|
||||
const result = await collection.insertMany(
|
||||
docsWithTimestamps as OptionalUnlessRequiredId<Document>[],
|
||||
options
|
||||
);
|
||||
return {
|
||||
insertedCount: result.insertedCount,
|
||||
insertedIds: result.insertedIds,
|
||||
|
|
@ -391,13 +411,13 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Find multiple documents
|
||||
*/
|
||||
async find<T = any>(
|
||||
async find<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
filter: any = {},
|
||||
options?: any,
|
||||
filter: Filter<Document> = {},
|
||||
options?: FindOptions,
|
||||
dbName?: string
|
||||
): Promise<T[]> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const collection = this.getCollection<T>(collectionName, dbName);
|
||||
const cursor = collection.find(filter, options);
|
||||
return (await cursor.toArray()) as T[];
|
||||
}
|
||||
|
|
@ -405,13 +425,13 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Find a single document
|
||||
*/
|
||||
async findOne<T = any>(
|
||||
async findOne<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
options?: FindOptions,
|
||||
dbName?: string
|
||||
): Promise<T | null> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const collection = this.getCollection<T>(collectionName, dbName);
|
||||
const result = await collection.findOne(filter, options);
|
||||
return result as T | null;
|
||||
}
|
||||
|
|
@ -421,11 +441,11 @@ export class MongoDBClient {
|
|||
*/
|
||||
async updateOne(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
update: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
update: Document,
|
||||
options?: UpdateOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
||||
// Add updated_at timestamp
|
||||
|
|
@ -449,11 +469,11 @@ export class MongoDBClient {
|
|||
*/
|
||||
async updateMany(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
update: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
update: Document,
|
||||
options?: UpdateOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
||||
// Add updated_at timestamp
|
||||
|
|
@ -477,10 +497,10 @@ export class MongoDBClient {
|
|||
*/
|
||||
async deleteOne(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
options?: DeleteOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const result = await collection.deleteOne(filter, options);
|
||||
return {
|
||||
|
|
@ -493,10 +513,10 @@ export class MongoDBClient {
|
|||
*/
|
||||
async deleteMany(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
options?: DeleteOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const result = await collection.deleteMany(filter, options);
|
||||
return {
|
||||
|
|
@ -509,8 +529,8 @@ export class MongoDBClient {
|
|||
*/
|
||||
async countDocuments(
|
||||
collectionName: string,
|
||||
filter: any = {},
|
||||
options?: any,
|
||||
filter: Filter<Document> = {},
|
||||
options?: CountDocumentsOptions,
|
||||
dbName?: string
|
||||
): Promise<number> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -520,10 +540,10 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Perform aggregation operations
|
||||
*/
|
||||
async aggregate<T = any>(
|
||||
async aggregate<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
pipeline: any[],
|
||||
options?: any,
|
||||
pipeline: Document[],
|
||||
options?: AggregateOptions,
|
||||
dbName?: string
|
||||
): Promise<T[]> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -536,8 +556,8 @@ export class MongoDBClient {
|
|||
*/
|
||||
async createIndex(
|
||||
collectionName: string,
|
||||
indexSpec: any,
|
||||
options?: any,
|
||||
indexSpec: IndexSpecification,
|
||||
options?: CreateIndexesOptions,
|
||||
dbName?: string
|
||||
): Promise<string> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -550,7 +570,7 @@ export class MongoDBClient {
|
|||
async dropIndex(
|
||||
collectionName: string,
|
||||
indexName: string,
|
||||
options?: any,
|
||||
options?: DropIndexesOptions,
|
||||
dbName?: string
|
||||
): Promise<void> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -560,7 +580,7 @@ export class MongoDBClient {
|
|||
/**
|
||||
* List all indexes on a collection
|
||||
*/
|
||||
async listIndexes(collectionName: string, dbName?: string): Promise<any[]> {
|
||||
async listIndexes(collectionName: string, dbName?: string): Promise<Document[]> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const cursor = collection.listIndexes();
|
||||
return await cursor.toArray();
|
||||
|
|
@ -576,7 +596,11 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Create a new collection
|
||||
*/
|
||||
async createCollection(collectionName: string, options?: any, dbName?: string): Promise<void> {
|
||||
async createCollection(
|
||||
collectionName: string,
|
||||
options?: CreateCollectionOptions,
|
||||
dbName?: string
|
||||
): Promise<void> {
|
||||
const db = this.getDatabase(dbName);
|
||||
await db.createCollection(collectionName, options);
|
||||
}
|
||||
|
|
@ -592,7 +616,7 @@ export class MongoDBClient {
|
|||
/**
|
||||
* List all collections in a database
|
||||
*/
|
||||
async listCollections(filter: any = {}, dbName?: string): Promise<any[]> {
|
||||
async listCollections(filter: Filter<Document> = {}, dbName?: string): Promise<Document[]> {
|
||||
const db = this.getDatabase(dbName);
|
||||
const collections = await db.listCollections(filter).toArray();
|
||||
return collections;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { beforeEach, describe, expect, it } from 'bun:test';
|
||||
import { SimpleMongoDBClient } from '../src/simple-mongodb';
|
||||
import { SimpleMongoDBClient } from './support/simple-mongodb';
|
||||
|
||||
describe('MongoDBClient', () => {
|
||||
let client: SimpleMongoDBClient;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Simple MongoDB client implementation for testing
|
||||
* Test-only in-memory MongoDB double. Never used by production adapters.
|
||||
*/
|
||||
export class SimpleMongoDBClient {
|
||||
private collections = new Map<string, any[]>();
|
||||
|
|
@ -144,7 +144,7 @@ export class SimpleMongoDBClient {
|
|||
return docs.length;
|
||||
}
|
||||
|
||||
async createIndex(collection: string, index: any, options?: any): Promise<void> {
|
||||
async createIndex(_collection: string, _index: any, _options?: any): Promise<void> {
|
||||
// No-op for simple implementation
|
||||
}
|
||||
|
||||
|
|
@ -15,7 +15,8 @@
|
|||
"dependencies": {
|
||||
"@stock-bot/logger": "*",
|
||||
"@stock-bot/types": "*",
|
||||
"pg": "^8.11.3"
|
||||
"pg": "^8.11.3",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import type { PoolConfig, QueryResultRow } from 'pg';
|
||||
import { Pool } from 'pg';
|
||||
import type { QueryResultRow } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
import { PostgreSQLHealthMonitor } from './health';
|
||||
import { PostgreSQLQueryBuilder } from './query-builder';
|
||||
import { PostgreSQLTransactionManager } from './transactions';
|
||||
|
|
@ -23,7 +25,7 @@ export class PostgreSQLClient {
|
|||
private pool: Pool | null = null;
|
||||
private readonly config: PostgreSQLClientConfig;
|
||||
private readonly options: PostgreSQLConnectionOptions;
|
||||
private readonly logger: any;
|
||||
private readonly logger: LoggerLike;
|
||||
private readonly healthMonitor: PostgreSQLHealthMonitor;
|
||||
private readonly transactionManager: PostgreSQLTransactionManager;
|
||||
private isConnected = false;
|
||||
|
|
@ -34,7 +36,7 @@ export class PostgreSQLClient {
|
|||
|
||||
constructor(
|
||||
config: PostgreSQLClientConfig,
|
||||
logger?: any,
|
||||
logger?: LoggerLike,
|
||||
options?: PostgreSQLConnectionOptions,
|
||||
events?: ConnectionEvents
|
||||
) {
|
||||
|
|
@ -183,9 +185,9 @@ export class PostgreSQLClient {
|
|||
/**
|
||||
* Execute a query
|
||||
*/
|
||||
async query<T extends QueryResultRow = any>(
|
||||
async query<T extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
if (!this.pool) {
|
||||
throw new Error('PostgreSQL client not connected');
|
||||
|
|
@ -262,9 +264,9 @@ export class PostgreSQLClient {
|
|||
/**
|
||||
* Execute a stored procedure or function
|
||||
*/
|
||||
async callFunction<T extends QueryResultRow = any>(
|
||||
async callFunction<T extends QueryResultRow = QueryResultRow>(
|
||||
functionName: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
const placeholders = params ? params.map((_, i) => `$${i + 1}`).join(', ') : '';
|
||||
const query = `SELECT * FROM ${functionName}(${placeholders})`;
|
||||
|
|
@ -375,13 +377,16 @@ export class PostgreSQLClient {
|
|||
)`,
|
||||
[schemaName, tableName]
|
||||
);
|
||||
return result.rows[0].exists;
|
||||
return at(result.rows, 0).exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get table schema information
|
||||
*/
|
||||
async getTableSchema(tableName: string, schemaName: string = 'public'): Promise<any[]> {
|
||||
async getTableSchema(
|
||||
tableName: string,
|
||||
schemaName: string = 'public'
|
||||
): Promise<QueryResultRow[]> {
|
||||
const result = await this.query(
|
||||
`SELECT
|
||||
column_name,
|
||||
|
|
@ -400,16 +405,16 @@ export class PostgreSQLClient {
|
|||
/**
|
||||
* Execute EXPLAIN for query analysis
|
||||
*/
|
||||
async explain(query: string, params?: any[]): Promise<any[]> {
|
||||
async explain(query: string, params?: unknown[]): Promise<QueryResultRow[]> {
|
||||
const explainQuery = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`;
|
||||
const result = await this.query(explainQuery, params);
|
||||
return result.rows[0]['QUERY PLAN'];
|
||||
return at(result.rows, 0)['QUERY PLAN'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database statistics
|
||||
*/
|
||||
async getStats(): Promise<any> {
|
||||
async getStats(): Promise<QueryResultRow> {
|
||||
const result = await this.query(`
|
||||
SELECT
|
||||
(SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections,
|
||||
|
|
@ -417,7 +422,7 @@ export class PostgreSQLClient {
|
|||
(SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections,
|
||||
pg_size_pretty(pg_database_size(current_database())) as database_size
|
||||
`);
|
||||
return result.rows[0];
|
||||
return result.rows[0] ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -434,7 +439,7 @@ export class PostgreSQLClient {
|
|||
return this.pool;
|
||||
}
|
||||
|
||||
private buildPoolConfig(): any {
|
||||
private buildPoolConfig(): PoolConfig {
|
||||
this.logger.debug('Building PostgreSQL pool config:', {
|
||||
host: this.config.host,
|
||||
port: this.config.port,
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ export class PostgreSQLQueryBuilder {
|
|||
private orderByConditions: OrderByCondition[] = [];
|
||||
private limitCount: number | null = null;
|
||||
private offsetCount: number | null = null;
|
||||
private insertValues: Record<string, any> = {};
|
||||
private updateValues: Record<string, any> = {};
|
||||
private insertValues: Record<string, unknown> = {};
|
||||
private updateValues: Record<string, unknown> = {};
|
||||
|
||||
private readonly client: PostgreSQLClient;
|
||||
|
||||
|
|
@ -55,8 +55,8 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* WHERE clause
|
||||
*/
|
||||
where(column: string, operator: string, value?: any): this {
|
||||
this.whereConditions.push({ column, operator: operator as any, value });
|
||||
where(column: string, operator: WhereCondition['operator'], value?: unknown): this {
|
||||
this.whereConditions.push({ column, operator, value });
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
@ -104,7 +104,7 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* VALUES for INSERT
|
||||
*/
|
||||
values(data: Record<string, any>): this {
|
||||
values(data: Record<string, unknown>): this {
|
||||
this.insertValues = data;
|
||||
return this;
|
||||
}
|
||||
|
|
@ -121,7 +121,7 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* SET for UPDATE
|
||||
*/
|
||||
set(data: Record<string, any>): this {
|
||||
set(data: Record<string, unknown>): this {
|
||||
this.updateValues = data;
|
||||
return this;
|
||||
}
|
||||
|
|
@ -138,7 +138,7 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* Build and execute the query
|
||||
*/
|
||||
async execute<T extends QueryResultRow = any>(): Promise<QueryResult<T>> {
|
||||
async execute<T extends QueryResultRow = QueryResultRow>(): Promise<QueryResult<T>> {
|
||||
const { sql, params } = this.build();
|
||||
return await this.client.query<T>(sql, params);
|
||||
}
|
||||
|
|
@ -146,8 +146,8 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* Build the SQL query
|
||||
*/
|
||||
build(): { sql: string; params: any[] } {
|
||||
const params: any[] = [];
|
||||
build(): { sql: string; params: unknown[] } {
|
||||
const params: unknown[] = [];
|
||||
let sql = '';
|
||||
|
||||
switch (this.queryType) {
|
||||
|
|
@ -170,7 +170,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return { sql, params };
|
||||
}
|
||||
|
||||
private buildSelectQuery(params: any[]): string {
|
||||
private buildSelectQuery(params: unknown[]): string {
|
||||
let sql = `SELECT ${this.selectColumns.join(', ')}`;
|
||||
|
||||
if (this.fromTable) {
|
||||
|
|
@ -220,7 +220,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return sql;
|
||||
}
|
||||
|
||||
private buildInsertQuery(params: any[]): string {
|
||||
private buildInsertQuery(params: unknown[]): string {
|
||||
const columns = Object.keys(this.insertValues);
|
||||
const placeholders = columns.map((_, i) => `$${params.length + i + 1}`);
|
||||
|
||||
|
|
@ -229,7 +229,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return `INSERT INTO ${this.fromTable} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`;
|
||||
}
|
||||
|
||||
private buildUpdateQuery(params: any[]): string {
|
||||
private buildUpdateQuery(params: unknown[]): string {
|
||||
const sets = Object.keys(this.updateValues).map((key, i) => {
|
||||
return `${key} = $${params.length + i + 1}`;
|
||||
});
|
||||
|
|
@ -245,7 +245,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return sql;
|
||||
}
|
||||
|
||||
private buildDeleteQuery(params: any[]): string {
|
||||
private buildDeleteQuery(params: unknown[]): string {
|
||||
let sql = `DELETE FROM ${this.fromTable}`;
|
||||
|
||||
if (this.whereConditions.length > 0) {
|
||||
|
|
@ -255,7 +255,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return sql;
|
||||
}
|
||||
|
||||
private buildWhereClause(conditions: WhereCondition[], params: any[]): string {
|
||||
private buildWhereClause(conditions: WhereCondition[], params: unknown[]): string {
|
||||
return conditions
|
||||
.map(condition => {
|
||||
if (condition.operator === 'IS NULL' || condition.operator === 'IS NOT NULL') {
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ export interface PostgreSQLMetrics {
|
|||
/**
|
||||
* Query Result Types
|
||||
*/
|
||||
export interface QueryResult<T extends QueryResultRow = any> extends PgQueryResult<T> {
|
||||
export interface QueryResult<T extends QueryResultRow = QueryResultRow> extends PgQueryResult<T> {
|
||||
executionTime?: number;
|
||||
}
|
||||
|
||||
|
|
@ -182,7 +182,7 @@ export interface Strategy {
|
|||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
parameters: Record<string, any>;
|
||||
parameters: Record<string, unknown>;
|
||||
status: 'active' | 'inactive' | 'paused';
|
||||
performance_metrics: Record<string, number>;
|
||||
portfolio_id: string;
|
||||
|
|
@ -207,8 +207,8 @@ export interface AuditLog {
|
|||
action: string;
|
||||
entity_type: string;
|
||||
entity_id: string;
|
||||
old_values?: Record<string, any>;
|
||||
new_values?: Record<string, any>;
|
||||
old_values?: Record<string, unknown>;
|
||||
new_values?: Record<string, unknown>;
|
||||
user_id?: string;
|
||||
ip_address?: string;
|
||||
user_agent?: string;
|
||||
|
|
@ -233,7 +233,7 @@ export interface WhereCondition {
|
|||
| 'ILIKE'
|
||||
| 'IS NULL'
|
||||
| 'IS NOT NULL';
|
||||
value?: any;
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export interface JoinCondition {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import {
|
|||
SimplePostgresClient,
|
||||
SimpleQueryBuilder,
|
||||
SimpleTransactionManager,
|
||||
} from '../src/simple-postgres';
|
||||
} from './support/simple-postgres';
|
||||
|
||||
describe('PostgresClient', () => {
|
||||
let client: SimplePostgresClient;
|
||||
|
|
@ -195,7 +195,7 @@ describe('TransactionManager', () => {
|
|||
|
||||
it('should rollback on error', async () => {
|
||||
await expect(
|
||||
manager.transaction(async client => {
|
||||
manager.transaction(async _client => {
|
||||
throw new Error('Transaction failed');
|
||||
})
|
||||
).rejects.toThrow('Transaction failed');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Simple PostgreSQL client for testing
|
||||
* Test-only in-memory PostgreSQL double. Never used by production adapters.
|
||||
*/
|
||||
export class SimplePostgresClient {
|
||||
private tables = new Map<string, any[]>();
|
||||
|
|
@ -7,7 +7,7 @@ export class SimplePostgresClient {
|
|||
|
||||
constructor(private config: any) {}
|
||||
|
||||
async query(sql: string, params?: any[]): Promise<{ rows: any[]; rowCount: number }> {
|
||||
async query(_sql: string, _params?: any[]): Promise<{ rows: any[]; rowCount: number }> {
|
||||
// Simple mock implementation
|
||||
return { rows: [], rowCount: 0 };
|
||||
}
|
||||
|
|
@ -119,7 +119,7 @@ export class SimpleQueryBuilder {
|
|||
|
||||
where(conditions: any): SimpleQueryBuilder {
|
||||
const whereClause = Object.entries(conditions)
|
||||
.map(([key], i) => {
|
||||
.map(([key], _i) => {
|
||||
this.params.push(conditions[key]);
|
||||
return `${key} = $${this.params.length}`;
|
||||
})
|
||||
|
|
@ -196,7 +196,7 @@ export class SimpleTransactionManager {
|
|||
|
||||
async transaction<T>(fn: (client: any) => Promise<T>): Promise<T> {
|
||||
const mockClient = {
|
||||
query: async (sql?: string) => ({ rows: [], rowCount: 0 }),
|
||||
query: async (_sql?: string) => ({ rows: [], rowCount: 0 }),
|
||||
release: () => {},
|
||||
};
|
||||
|
||||
|
|
@ -6,5 +6,15 @@
|
|||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [{ "path": "../../core/logger" }, { "path": "../../core/types" }]
|
||||
"references": [
|
||||
{
|
||||
"path": "../../core/logger"
|
||||
},
|
||||
{
|
||||
"path": "../../core/types"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@
|
|||
"dependencies": {
|
||||
"@stock-bot/logger": "*",
|
||||
"@stock-bot/types": "*",
|
||||
"pg": "^8.11.3"
|
||||
"pg": "^8.11.3",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import type { PoolConfig, QueryResultRow } from 'pg';
|
||||
import { Pool } from 'pg';
|
||||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
import { QuestDBHealthMonitor } from './health';
|
||||
import { QuestDBInfluxWriter } from './influx-writer';
|
||||
import { QuestDBQueryBuilder } from './query-builder';
|
||||
|
|
@ -20,13 +22,17 @@ export class QuestDBClient {
|
|||
private pgPool: Pool | null = null;
|
||||
private readonly config: QuestDBClientConfig;
|
||||
private readonly options: QuestDBConnectionOptions;
|
||||
private readonly logger: any;
|
||||
private readonly logger: LoggerLike;
|
||||
private readonly healthMonitor: QuestDBHealthMonitor;
|
||||
private readonly influxWriter: QuestDBInfluxWriter;
|
||||
private readonly schemaManager: QuestDBSchemaManager;
|
||||
private isConnected = false;
|
||||
|
||||
constructor(config: QuestDBClientConfig, logger?: any, options?: QuestDBConnectionOptions) {
|
||||
constructor(
|
||||
config: QuestDBClientConfig,
|
||||
logger?: LoggerLike,
|
||||
options?: QuestDBConnectionOptions
|
||||
) {
|
||||
this.config = config;
|
||||
this.logger = logger || console;
|
||||
this.options = {
|
||||
|
|
@ -128,7 +134,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Execute a SQL query
|
||||
*/
|
||||
async query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>> {
|
||||
async query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>> {
|
||||
if (!this.pgPool) {
|
||||
throw new Error('QuestDB client not connected');
|
||||
}
|
||||
|
|
@ -150,7 +156,7 @@ export class QuestDBClient {
|
|||
executionTime,
|
||||
metadata: {
|
||||
columns:
|
||||
result.fields?.map((field: any) => ({
|
||||
result.fields?.map(field => ({
|
||||
name: field.name,
|
||||
type: this.mapDataType(field.dataTypeID),
|
||||
})) || [],
|
||||
|
|
@ -227,13 +233,13 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Execute a time-series specific query with SAMPLE BY
|
||||
*/
|
||||
async sampleBy<T = any>(
|
||||
async sampleBy<T = QueryResultRow>(
|
||||
table: TableNames,
|
||||
columns: string[],
|
||||
interval: string,
|
||||
_timeColumn: string = 'timestamp',
|
||||
where?: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
const columnsStr = columns.join(', ');
|
||||
const whereClause = where ? `WHERE ${where}` : '';
|
||||
|
|
@ -252,7 +258,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Get latest values by symbol using LATEST BY
|
||||
*/
|
||||
async latestBy<T = any>(
|
||||
async latestBy<T = QueryResultRow>(
|
||||
table: TableNames,
|
||||
columns: string | string[] = '*',
|
||||
keyColumns: string | string[] = 'symbol'
|
||||
|
|
@ -272,13 +278,13 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Execute ASOF JOIN for time-series correlation
|
||||
*/
|
||||
async asofJoin<T = any>(
|
||||
async asofJoin<T = QueryResultRow>(
|
||||
leftTable: TableNames,
|
||||
rightTable: TableNames,
|
||||
joinCondition: string,
|
||||
columns?: string[],
|
||||
where?: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
const columnsStr = columns ? columns.join(', ') : '*';
|
||||
const whereClause = where ? `WHERE ${where}` : '';
|
||||
|
|
@ -296,7 +302,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Get database statistics
|
||||
*/
|
||||
async getStats(): Promise<any> {
|
||||
async getStats(): Promise<QueryResultRow[]> {
|
||||
const result = await this.query(`
|
||||
SELECT
|
||||
table_name,
|
||||
|
|
@ -313,7 +319,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Get table information
|
||||
*/
|
||||
async getTableInfo(tableName: string): Promise<any> {
|
||||
async getTableInfo(tableName: string): Promise<QueryResultRow[]> {
|
||||
const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [
|
||||
tableName,
|
||||
]);
|
||||
|
|
@ -412,8 +418,8 @@ export class QuestDBClient {
|
|||
return { ...this.config };
|
||||
}
|
||||
|
||||
private buildPgPoolConfig(): any {
|
||||
const config: any = {
|
||||
private buildPgPoolConfig(): PoolConfig {
|
||||
const config: PoolConfig = {
|
||||
host: this.config.host,
|
||||
port: this.config.pgPort,
|
||||
database: this.config.database,
|
||||
|
|
@ -430,7 +436,7 @@ export class QuestDBClient {
|
|||
|
||||
// Only add user/password if they are provided
|
||||
if (this.config.user) {
|
||||
this.logger.debug('Adding user to QuestDB pool config:', this.config.user);
|
||||
this.logger.debug('Adding user to QuestDB pool config', { user: this.config.user });
|
||||
config.user = this.config.user;
|
||||
} else {
|
||||
this.logger.debug('No user provided for QuestDB connection');
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { HealthStatus, PerformanceMetrics, QueryResult } from './types';
|
||||
|
||||
// Interface to avoid circular dependency
|
||||
interface QuestDBClientInterface {
|
||||
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
||||
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
||||
isPgPoolHealthy(): boolean;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { QueryResult, TableNames, TimeRange } from './types';
|
||||
|
||||
// Interface to avoid circular dependency
|
||||
interface QuestDBClientInterface {
|
||||
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
||||
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -190,7 +191,7 @@ export class QuestDBQueryBuilder {
|
|||
/**
|
||||
* Build and execute the query
|
||||
*/
|
||||
public async execute<T = any>(): Promise<QueryResult<T>> {
|
||||
public async execute<T = QueryResultRow>(): Promise<QueryResult<T>> {
|
||||
const sql = this.build();
|
||||
this.logger.debug('Executing query', { sql });
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { QueryResult, TableSchema } from './types';
|
||||
|
||||
// Interface to avoid circular dependency
|
||||
interface QuestDBClientInterface {
|
||||
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
||||
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -215,7 +217,7 @@ export class QuestDBSchemaManager {
|
|||
WHERE table_name = '${tableName}'
|
||||
`);
|
||||
|
||||
return result.rows.length > 0 && result.rows[0].count > 0;
|
||||
return result.rows.length > 0 && at(result.rows, 0).count > 0;
|
||||
} catch (error) {
|
||||
this.logger.error(`Error checking if table exists: ${tableName}`, error);
|
||||
return false;
|
||||
|
|
@ -266,7 +268,7 @@ export class QuestDBSchemaManager {
|
|||
/**
|
||||
* Get table statistics
|
||||
*/
|
||||
public async getTableStats(tableName: string): Promise<any> {
|
||||
public async getTableStats(tableName: string): Promise<QueryResultRow | undefined> {
|
||||
try {
|
||||
const result = await this.client.query(`
|
||||
SELECT
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
|
||||
/**
|
||||
* QuestDB Client Configuration and Types
|
||||
*/
|
||||
|
|
@ -101,7 +103,7 @@ export interface QuoteData extends BaseTimeSeriesData {
|
|||
export interface IndicatorData extends BaseTimeSeriesData {
|
||||
indicator_name: string;
|
||||
value: number;
|
||||
parameters?: Record<string, any>;
|
||||
parameters?: Record<string, unknown>;
|
||||
timeframe: string;
|
||||
}
|
||||
|
||||
|
|
@ -127,7 +129,7 @@ export interface RiskMetrics extends BaseTimeSeriesData {
|
|||
/**
|
||||
* Query Result Types
|
||||
*/
|
||||
export interface QueryResult<T = any> {
|
||||
export interface QueryResult<T = QueryResultRow> {
|
||||
rows: T[];
|
||||
rowCount: number;
|
||||
executionTime: number;
|
||||
|
|
|
|||
|
|
@ -6,5 +6,15 @@
|
|||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [{ "path": "../../core/logger" }, { "path": "../../core/types" }]
|
||||
"references": [
|
||||
{
|
||||
"path": "../../core/logger"
|
||||
},
|
||||
{
|
||||
"path": "../../core/types"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,16 @@
|
|||
import { chromium } from 'playwright';
|
||||
import type { BrowserContext, Page, Browser as PlaywrightBrowser } from 'playwright';
|
||||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
import type { BrowserOptions, NetworkEvent, NetworkEventHandler } from './types';
|
||||
|
||||
export class Browser {
|
||||
private browser?: PlaywrightBrowser;
|
||||
private contexts: Map<string, BrowserContext> = new Map();
|
||||
private logger: any;
|
||||
private logger: LoggerLike;
|
||||
private options: BrowserOptions;
|
||||
private initialized = false;
|
||||
|
||||
constructor(logger?: any, defaultOptions?: BrowserOptions) {
|
||||
constructor(logger?: LoggerLike, defaultOptions?: BrowserOptions) {
|
||||
this.logger = logger || console;
|
||||
this.options = {
|
||||
headless: true,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { SimpleBrowser } from '../src/simple-browser';
|
||||
import { SimpleBrowser } from './support/simple-browser';
|
||||
|
||||
describe('Browser', () => {
|
||||
let browser: SimpleBrowser;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { Page } from 'playwright';
|
||||
import type { BrowserOptions, ScrapingResult } from './types';
|
||||
import type { BrowserOptions, ScrapingResult } from '../../src/types';
|
||||
|
||||
/**
|
||||
* Simple browser implementation for testing
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
* Centralized Proxy Manager - Handles proxy storage, retrieval, and caching
|
||||
*/
|
||||
import type { CacheProvider } from '@stock-bot/cache';
|
||||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
import type { ProxyInfo, ProxyManagerConfig, ProxyStats } from './types';
|
||||
|
||||
export class ProxyManager {
|
||||
|
|
@ -11,10 +12,10 @@ export class ProxyManager {
|
|||
private lastUpdate: Date | null = null;
|
||||
private lastFetchTime: Date | null = null;
|
||||
private isInitialized = false;
|
||||
private logger: any;
|
||||
private logger: LoggerLike;
|
||||
private config: ProxyManagerConfig;
|
||||
|
||||
constructor(cache: CacheProvider, config: ProxyManagerConfig = {}, logger?: any) {
|
||||
constructor(cache: CacheProvider, config: ProxyManagerConfig = {}, logger?: LoggerLike) {
|
||||
this.cache = cache;
|
||||
this.config = config;
|
||||
this.logger = logger || console;
|
||||
|
|
@ -85,7 +86,7 @@ export class ProxyManager {
|
|||
// Note: We don't increment the index here since getProxy() already does that
|
||||
const currentIndex = this.proxyIndex > 0 ? this.proxyIndex - 1 : this.proxies.length - 1;
|
||||
const proxyInfo = this.proxies[currentIndex];
|
||||
|
||||
|
||||
return proxyInfo || null;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,11 +13,16 @@
|
|||
"@stock-bot/config": "workspace:*",
|
||||
"@stock-bot/logger": "workspace:*",
|
||||
"@stock-bot/cache": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*"
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
"typescript": "^5.3.0",
|
||||
"bun-types": "^1.2.15"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./assertions": "./src/assertions.ts"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
1
libs/utils/src/assertions.ts
Normal file
1
libs/utils/src/assertions.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export { at, defined } from '@stock-bot/invariants';
|
||||
|
|
@ -92,8 +92,8 @@ export function analyzePortfolio(
|
|||
_benchmarkReturns?: number[],
|
||||
_riskFreeRate: number = 0.02
|
||||
): {
|
||||
performance: any;
|
||||
risk: any;
|
||||
performance: Record<string, unknown>;
|
||||
risk: Record<string, unknown>;
|
||||
} {
|
||||
// Note: Implementation depends on performance-metrics and risk-metrics
|
||||
// This is a placeholder for the full implementation
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
/**
|
||||
* Technical Indicators
|
||||
* Comprehensive set of technical analysis indicators
|
||||
|
|
@ -807,7 +808,7 @@ export function ichimoku(
|
|||
}
|
||||
|
||||
// Chikou Span (Lagging Span)
|
||||
chikouSpan.push(ohlcv[i]!.close);
|
||||
chikouSpan.push(defined(ohlcv[i]).close);
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -837,13 +838,13 @@ export function ultimateOscillator(
|
|||
|
||||
// Calculate BP and TR
|
||||
for (let i = 0; i < ohlcv.length; i++) {
|
||||
const current = ohlcv[i]!;
|
||||
const current = defined(ohlcv[i]);
|
||||
|
||||
if (i === 0) {
|
||||
bp.push(current.close - current.low);
|
||||
tr.push(current.high - current.low);
|
||||
} else {
|
||||
const previous = ohlcv[i - 1]!;
|
||||
const previous = defined(ohlcv[i - 1]);
|
||||
bp.push(current.close - Math.min(current.low, previous.close));
|
||||
tr.push(
|
||||
Math.max(
|
||||
|
|
@ -886,8 +887,8 @@ export function easeOfMovement(ohlcv: OHLCV[], period: number = 14): number[] {
|
|||
const emv: number[] = [];
|
||||
|
||||
for (let i = 1; i < ohlcv.length; i++) {
|
||||
const current = ohlcv[i]!;
|
||||
const previous = ohlcv[i - 1]!;
|
||||
const current = defined(ohlcv[i]);
|
||||
const previous = defined(ohlcv[i - 1]);
|
||||
|
||||
const distance = (current.high + current.low) / 2 - (previous.high + previous.low) / 2;
|
||||
const boxHeight = current.high - current.low;
|
||||
|
|
@ -1030,8 +1031,8 @@ export function klingerVolumeOscillator(
|
|||
const volumeForce: number[] = [];
|
||||
|
||||
for (let i = 1; i < ohlcv.length; i++) {
|
||||
const current = ohlcv[i]!;
|
||||
const previous = ohlcv[i - 1]!;
|
||||
const current = defined(ohlcv[i]);
|
||||
const previous = defined(ohlcv[i - 1]);
|
||||
|
||||
const typicalPrice = (current.high + current.low + current.close) / 3;
|
||||
const prevTypicalPrice = (previous.high + previous.low + previous.close) / 3;
|
||||
|
|
@ -1164,7 +1165,7 @@ export function stochasticRSI(
|
|||
const slice = rsiValues.slice(i - stochPeriod + 1, i + 1);
|
||||
const highest = Math.max(...slice);
|
||||
const lowest = Math.min(...slice);
|
||||
const currentRSI = rsiValues[i]!;
|
||||
const currentRSI = defined(rsiValues[i]);
|
||||
|
||||
if (highest === lowest) {
|
||||
stochRSI.push(0);
|
||||
|
|
@ -1196,8 +1197,8 @@ export function vortexIndicator(
|
|||
const tr: number[] = [];
|
||||
|
||||
for (let i = 1; i < ohlcv.length; i++) {
|
||||
const current = ohlcv[i]!;
|
||||
const previous = ohlcv[i - 1]!;
|
||||
const current = defined(ohlcv[i]);
|
||||
const previous = defined(ohlcv[i - 1]);
|
||||
|
||||
// Vortex Movement
|
||||
vm_plus.push(Math.abs(current.high - previous.low));
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
|
||||
/**
|
||||
* Enhanced fetch wrapper with proxy support and automatic debug logging
|
||||
* Drop-in replacement for native fetch with additional features
|
||||
|
|
@ -8,7 +10,7 @@ export interface BunRequestInit extends RequestInit {
|
|||
}
|
||||
|
||||
export interface FetchOptions extends RequestInit {
|
||||
logger?: any;
|
||||
logger?: LoggerLike;
|
||||
proxy?: string | null;
|
||||
timeout?: number;
|
||||
}
|
||||
|
|
@ -61,7 +63,7 @@ export async function fetch(input: RequestInfo | URL, options?: FetchOptions): P
|
|||
async function performFetch(
|
||||
input: RequestInfo | URL,
|
||||
requestOptions: RequestInit,
|
||||
logger: any,
|
||||
logger: LoggerLike,
|
||||
url: string
|
||||
): Promise<Response> {
|
||||
logger.debug('HTTP request', {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
/**
|
||||
* Generic utility functions that work with standardized types
|
||||
* These functions demonstrate how to use generic types with OHLCV data
|
||||
|
|
@ -69,10 +70,10 @@ export function calculateTrueRange<T extends HasOHLC>(data: T[]): number[] {
|
|||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
if (i === 0) {
|
||||
result.push(data[i]!.high - data[i]!.low);
|
||||
result.push(defined(data[i]).high - defined(data[i]).low);
|
||||
} else {
|
||||
const current = data[i]!;
|
||||
const previous = data[i - 1]!;
|
||||
const current = defined(data[i]);
|
||||
const previous = defined(data[i - 1]);
|
||||
const tr = Math.max(
|
||||
current.high - current.low,
|
||||
Math.abs(current.high - previous.close),
|
||||
|
|
@ -93,8 +94,8 @@ export function calculateReturns<T extends HasClose>(data: T[]): number[] {
|
|||
const returns: number[] = [];
|
||||
|
||||
for (let i = 1; i < closes.length; i++) {
|
||||
const current = closes[i]!;
|
||||
const previous = closes[i - 1]!;
|
||||
const current = defined(closes[i]);
|
||||
const previous = defined(closes[i - 1]);
|
||||
if (previous > 0) {
|
||||
returns.push((current - previous) / previous);
|
||||
} else {
|
||||
|
|
@ -113,8 +114,8 @@ export function calculateLogReturns<T extends HasClose>(data: T[]): number[] {
|
|||
const logReturns: number[] = [];
|
||||
|
||||
for (let i = 1; i < closes.length; i++) {
|
||||
const current = closes[i]!;
|
||||
const previous = closes[i - 1]!;
|
||||
const current = defined(closes[i]);
|
||||
const previous = defined(closes[i - 1]);
|
||||
if (previous > 0 && current > 0) {
|
||||
logReturns.push(Math.log(current / previous));
|
||||
} else {
|
||||
|
|
@ -172,7 +173,7 @@ export function groupBySymbol(data: OHLCV[]): Record<string, OHLCV[]> {
|
|||
if (!grouped[item.symbol]) {
|
||||
grouped[item.symbol] = [];
|
||||
}
|
||||
grouped[item.symbol]!.push(item);
|
||||
defined(grouped[item.symbol]).push(item);
|
||||
}
|
||||
|
||||
return grouped;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
export * from './calculations/index';
|
||||
export * from './assertions';
|
||||
export * from './common';
|
||||
export * from './dateUtils';
|
||||
export * from './generic-functions';
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
|
||||
/**
|
||||
* User Agent utility for generating random user agents
|
||||
*/
|
||||
|
|
@ -26,5 +28,5 @@ const USER_AGENTS = [
|
|||
|
||||
export function getRandomUserAgent(): string {
|
||||
const index = Math.floor(Math.random() * USER_AGENTS.length);
|
||||
return USER_AGENTS[index]!;
|
||||
return defined(USER_AGENTS[index]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,9 +10,20 @@
|
|||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"references": [
|
||||
{ "path": "../core/types" },
|
||||
{ "path": "../core/cache" },
|
||||
{ "path": "../core/config" },
|
||||
{ "path": "../core/logger" }
|
||||
{
|
||||
"path": "../core/types"
|
||||
},
|
||||
{
|
||||
"path": "../core/cache"
|
||||
},
|
||||
{
|
||||
"path": "../core/config"
|
||||
},
|
||||
{
|
||||
"path": "../core/logger"
|
||||
},
|
||||
{
|
||||
"path": "../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue