commit 2 refactor

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

View file

@ -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;

View file

@ -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';

View file

@ -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,

View file

@ -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
);

View file

@ -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(),
});

View file

@ -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;

View file

@ -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', {

View file

@ -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>;
}