added proper error messaged

This commit is contained in:
Boki 2025-06-23 12:35:10 -04:00
parent 71f771862b
commit 8a1a28b26e
4 changed files with 90 additions and 72 deletions

2
.env
View file

@ -5,7 +5,7 @@
# Core Application Settings # Core Application Settings
NODE_ENV=development NODE_ENV=development
LOG_LEVEL=trace LOG_LEVEL=trace
LOG_HIDE_OBJECT=false LOG_HIDE_OBJECT=true
# Data Service Configuration # Data Service Configuration
DATA_SERVICE_PORT=2001 DATA_SERVICE_PORT=2001

View file

@ -4,11 +4,7 @@
*/ */
import { initializeStockConfig } from '@stock-bot/stock-config'; import { initializeStockConfig } from '@stock-bot/stock-config';
import { import { ServiceApplication } from '@stock-bot/di';
ServiceApplication,
createServiceContainerFromConfig,
initializeServices as initializeAwilixServices,
} from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
// Local imports // Local imports
@ -58,17 +54,24 @@ const app = new ServiceApplication(
// Container factory function // Container factory function
async function createContainer(config: any) { async function createContainer(config: any) {
const container = createServiceContainerFromConfig(config, { const { ServiceContainerBuilder } = await import('@stock-bot/di');
enableQuestDB: config.database.questdb?.enabled || false, const builder = new ServiceContainerBuilder();
// Data pipeline needs all databases
enableMongoDB: true, const container = await builder
enablePostgres: true, .withConfig(config)
enableCache: true, .withOptions({
enableQueue: true, enableQuestDB: false, // Disabled for now due to auth issues
enableBrowser: false, // Data pipeline doesn't need browser // Data pipeline needs all databases
enableProxy: false, // Data pipeline doesn't need proxy enableMongoDB: true,
}); enablePostgres: true,
await initializeAwilixServices(container); enableCache: true,
enableQueue: true,
enableBrowser: false, // Data pipeline doesn't need browser
enableProxy: false, // Data pipeline doesn't need proxy
skipInitialization: false, // Let builder handle initialization
})
.build();
return container; return container;
} }

View file

@ -177,15 +177,15 @@ export class Logger {
let data = { ...this.context, ...metadata }; let data = { ...this.context, ...metadata };
// Hide all metadata if hideObject is enabled // Hide all metadata if hideObject is enabled, EXCEPT for error and fatal levels
if (globalConfig.hideObject) { if (globalConfig.hideObject && level !== 'error' && level !== 'fatal') {
data = {}; // Clear all metadata data = {}; // Clear all metadata
} }
if (typeof message === 'string') { if (typeof message === 'string') {
(this.pino as any)[level](data, message); (this.pino as any)[level](data, message);
} else { } else {
if (globalConfig.hideObject) { if (globalConfig.hideObject && level !== 'error' && level !== 'fatal') {
(this.pino as any)[level]({}, `Object logged (hidden)`); (this.pino as any)[level]({}, `Object logged (hidden)`);
} else { } else {
(this.pino as any)[level]({ ...data, data: message }, 'Object logged'); (this.pino as any)[level]({ ...data, data: message }, 'Object logged');

View file

@ -45,69 +45,84 @@ export class MongoDBClient {
/** /**
* Connect to MongoDB with simple configuration * Connect to MongoDB with simple configuration
*/ */
async connect(): Promise<void> { async connect(retryAttempts: number = 3, retryDelay: number = 1000): Promise<void> {
if (this.isConnected && this.client) { if (this.isConnected && this.client) {
return; return;
} }
try { let lastError: Error | null = null;
const uri = this.buildConnectionUri();
this.logger.info('Connecting to MongoDB...');
this.client = new MongoClient(uri, { for (let attempt = 1; attempt <= retryAttempts; attempt++) {
maxPoolSize: this.config.poolSettings?.maxPoolSize || 10, try {
minPoolSize: this.config.poolSettings?.minPoolSize || 1, const uri = this.buildConnectionUri();
connectTimeoutMS: this.config.timeouts?.connectTimeout || 10000, this.logger.info(`Connecting to MongoDB (attempt ${attempt}/${retryAttempts})...`);
socketTimeoutMS: this.config.timeouts?.socketTimeout || 30000,
serverSelectionTimeoutMS: this.config.timeouts?.serverSelectionTimeout || 5000,
});
await this.client.connect(); this.client = new MongoClient(uri, {
await this.client.db(this.defaultDatabase).admin().ping(); maxPoolSize: this.config.poolSettings?.maxPoolSize || 10,
minPoolSize: this.config.poolSettings?.minPoolSize || 1,
connectTimeoutMS: this.config.timeouts?.connectTimeout || 10000,
socketTimeoutMS: this.config.timeouts?.socketTimeout || 30000,
serverSelectionTimeoutMS: this.config.timeouts?.serverSelectionTimeout || 5000,
});
// Set default database from config await this.client.connect();
this.db = this.client.db(this.defaultDatabase); await this.client.db(this.defaultDatabase).admin().ping();
this.isConnected = true;
// Update metrics // Set default database from config
this.metrics.totalConnections = this.config.poolSettings?.maxPoolSize || 10; this.db = this.client.db(this.defaultDatabase);
this.metrics.idleConnections = this.metrics.totalConnections; this.isConnected = true;
// Fire connection event // Update metrics
if (this.events?.onConnect) { this.metrics.totalConnections = this.config.poolSettings?.maxPoolSize || 10;
await Promise.resolve(this.events.onConnect()); this.metrics.idleConnections = this.metrics.totalConnections;
// Fire connection event
if (this.events?.onConnect) {
await Promise.resolve(this.events.onConnect());
}
// Fire pool created event
if (this.events?.onPoolCreated) {
await Promise.resolve(this.events.onPoolCreated());
}
this.logger.info('Successfully connected to MongoDB', {
database: this.defaultDatabase,
poolSize: this.metrics.totalConnections,
});
// Start pool monitoring if dynamic sizing is enabled
if (this.dynamicPoolConfig?.enabled) {
this.startPoolMonitoring();
}
return;
} catch (error) {
lastError = error as Error;
this.metrics.errors++;
this.metrics.lastError = lastError.message;
// Fire error event
if (this.events?.onError) {
await Promise.resolve(this.events.onError(lastError));
}
this.logger.error(`MongoDB connection attempt ${attempt} failed:`, error);
if (this.client) {
await this.client.close();
this.client = null;
}
if (attempt < retryAttempts) {
await new Promise(resolve => setTimeout(resolve, retryDelay * attempt));
}
} }
// Fire pool created event
if (this.events?.onPoolCreated) {
await Promise.resolve(this.events.onPoolCreated());
}
this.logger.info('Successfully connected to MongoDB', {
database: this.defaultDatabase,
poolSize: this.metrics.totalConnections,
});
// Start pool monitoring if dynamic sizing is enabled
if (this.dynamicPoolConfig?.enabled) {
this.startPoolMonitoring();
}
} catch (error) {
this.metrics.errors++;
this.metrics.lastError = error instanceof Error ? error.message : 'Unknown error';
// Fire error event
if (this.events?.onError) {
await Promise.resolve(this.events.onError(error as Error));
}
this.logger.error('MongoDB connection failed:', error);
if (this.client) {
await this.client.close();
this.client = null;
}
throw error;
} }
throw new Error(
`Failed to connect to MongoDB after ${retryAttempts} attempts: ${lastError?.message}`
);
} }
/** /**