refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -18,17 +18,37 @@ import type { Logger } from '@stock-bot/logger';
import type {
ConnectionEvents,
DocumentBase,
DynamicPoolConfig,
MongoDBClientConfig,
PoolMetrics,
} from './types';
/**
* MongoDB Client for Stock Bot Data Service
*
* MongoDB client focused on batch upsert operations
* with minimal configuration and no health monitoring complexity.
*/
const READ_ONLY_COLLECTION_METHODS = new Set<string | symbol>([
'find',
'findOne',
'countDocuments',
'estimatedDocumentCount',
'distinct',
'listIndexes',
'indexExists',
'indexes',
'options',
]);
const READ_ONLY_COLLECTION_PROPS = new Set<string | symbol>([
'collectionName',
'dbName',
'namespace',
'then',
]);
const READ_ONLY_DB_METHODS = new Set<string | symbol>(['listCollections', 'stats']);
const READ_ONLY_DB_PROPS = new Set<string | symbol>([
'databaseName',
'namespace',
'options',
'then',
]);
export class MongoDBClient {
private client: MongoClient | null = null;
private db: Db | null = null;
@ -38,8 +58,6 @@ export class MongoDBClient {
private isConnected = false;
private readonly metrics: PoolMetrics;
private readonly events?: ConnectionEvents;
private dynamicPoolConfig?: DynamicPoolConfig;
private poolMonitorInterval?: Timer;
constructor(mongoConfig: MongoDBClientConfig, logger: Logger, events?: ConnectionEvents) {
this.config = mongoConfig;
@ -56,9 +74,6 @@ export class MongoDBClient {
};
}
/**
* Connect to MongoDB with simple configuration
*/
async connect(retryAttempts: number = 3, retryDelay: number = 1000): Promise<void> {
if (this.isConnected && this.client) {
return;
@ -74,6 +89,7 @@ export class MongoDBClient {
this.client = new MongoClient(uri, {
maxPoolSize: this.config.poolSettings?.maxPoolSize || 10,
minPoolSize: this.config.poolSettings?.minPoolSize || 1,
maxIdleTimeMS: this.config.poolSettings?.maxIdleTime,
connectTimeoutMS: this.config.timeouts?.connectTimeout || 10000,
socketTimeoutMS: this.config.timeouts?.socketTimeout || 30000,
serverSelectionTimeoutMS: this.config.timeouts?.serverSelectionTimeout || 5000,
@ -82,20 +98,15 @@ export class MongoDBClient {
await this.client.connect();
await this.client.db(this.defaultDatabase).command({ ping: 1 });
// Set default database from config
this.db = this.client.db(this.defaultDatabase);
this.isConnected = true;
// Update metrics
this.metrics.totalConnections = this.config.poolSettings?.maxPoolSize || 10;
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());
}
@ -103,20 +114,14 @@ export class MongoDBClient {
this.logger.info('Successfully connected to MongoDB', {
database: this.defaultDatabase,
poolSize: this.metrics.totalConnections,
readOnly: Boolean(this.config.readOnly),
});
// 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));
}
@ -124,7 +129,7 @@ export class MongoDBClient {
this.logger.error(`MongoDB connection attempt ${attempt} failed:`, error);
if (this.client) {
await this.client.close();
await this.client.close().catch(() => {});
this.client = null;
}
@ -139,27 +144,17 @@ export class MongoDBClient {
);
}
/**
* Disconnect from MongoDB
*/
async disconnect(): Promise<void> {
if (!this.client) {
return;
}
try {
// Stop pool monitoring
if (this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
await this.client.close();
this.isConnected = false;
this.client = null;
this.db = null;
// Fire disconnect event
if (this.events?.onDisconnect) {
await Promise.resolve(this.events.onDisconnect());
}
@ -171,9 +166,6 @@ export class MongoDBClient {
}
}
/**
* Set the default database for operations
*/
setDefaultDatabase(databaseName: string): void {
this.defaultDatabase = databaseName;
if (this.client) {
@ -182,28 +174,90 @@ export class MongoDBClient {
}
}
/**
* Get the current default database name
*/
getDefaultDatabase(): string {
return this.defaultDatabase;
}
/**
* Get a database instance by name
*/
getDatabase(databaseName?: string): Db {
private getRawDatabase(databaseName?: string): Db {
if (!this.client) {
throw new Error('MongoDB client not connected');
}
const dbName = databaseName || this.defaultDatabase;
return this.client.db(dbName);
return this.client.db(databaseName || this.defaultDatabase);
}
private wrapReadOnlyCollection<T extends Document>(collection: Collection<T>): Collection<T> {
return new Proxy(collection, {
get: (target, prop, receiver) => {
if (typeof prop === 'symbol' || READ_ONLY_COLLECTION_PROPS.has(prop)) {
return Reflect.get(target, prop, receiver);
}
if (prop === 'aggregate') {
return (pipeline: Document[] = [], options?: AggregateOptions) => {
this.assertReadOnlyPipeline(pipeline);
return target.aggregate(pipeline, options);
};
}
if (READ_ONLY_COLLECTION_METHODS.has(prop)) {
const fn = Reflect.get(target, prop, target);
return typeof fn === 'function' ? fn.bind(target) : fn;
}
return () => {
throw new Error(
`MongoDB client is configured in read-only mode; collection operation "${String(prop)}" is forbidden`
);
};
},
});
}
private wrapReadOnlyDatabase(db: Db): Db {
return new Proxy(db, {
get: (target, prop, receiver) => {
if (typeof prop === 'symbol' || READ_ONLY_DB_PROPS.has(prop)) {
return Reflect.get(target, prop, receiver);
}
if (prop === 'collection') {
return <T extends Document = Document>(name: string) =>
this.wrapReadOnlyCollection(target.collection<T>(name));
}
if (READ_ONLY_DB_METHODS.has(prop)) {
const fn = Reflect.get(target, prop, target);
return typeof fn === 'function' ? fn.bind(target) : fn;
}
return () => {
throw new Error(
`MongoDB client is configured in read-only mode; database operation "${String(prop)}" is forbidden`
);
};
},
});
}
getDatabase(databaseName?: string): Db {
const raw = this.getRawDatabase(databaseName);
return this.config.readOnly ? this.wrapReadOnlyDatabase(raw) : raw;
}
getDb(dbName?: string): Db {
return this.getDatabase(dbName);
}
get database(): Db | null {
if (!this.db) {
return null;
}
return this.config.readOnly ? this.wrapReadOnlyDatabase(this.db) : this.db;
}
getCollection<T extends Document = Document>(name: string, database?: string): Collection<T> {
const raw = this.getRawDatabase(database).collection<T>(name);
return this.config.readOnly ? this.wrapReadOnlyCollection(raw) : raw;
}
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
return this.getCollection<T>(name, database);
}
/**
* Check whether this client is locked to read-only mode
*/
isReadOnly(): boolean {
return this.config.readOnly === true;
}
@ -221,7 +275,9 @@ export class MongoDBClient {
return;
}
const checkStage = (value: unknown): void => {
if (!value || typeof value !== 'object') return;
if (!value || typeof value !== 'object') {
return;
}
for (const [key, child] of Object.entries(value)) {
if (key === '$out' || key === '$merge') {
throw new Error(
@ -236,10 +292,6 @@ export class MongoDBClient {
}
}
/**
* Batch upsert documents for high-performance operations
* Supports single or multiple unique keys for matching
*/
async batchUpsert<T extends DocumentBase>(
collectionName: string,
documents: Array<
@ -248,7 +300,7 @@ export class MongoDBClient {
uniqueKeys: string | string[],
options: {
chunkSize?: number;
database?: string; // Optional database override
database?: string;
} = {}
): Promise<{ insertedCount: number; updatedCount: number; errors: unknown[] }> {
this.assertWritable(`batchUpsert(${collectionName})`);
@ -260,42 +312,24 @@ export class MongoDBClient {
return { insertedCount: 0, updatedCount: 0, errors: [] };
}
// Normalize uniqueKeys to array
const keyFields = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys];
if (keyFields.length === 0) {
throw new Error('At least one unique key must be provided');
}
const { chunkSize = 10000, database } = options;
const db = this.getDatabase(database);
const collection = db.collection<T>(collectionName);
const collection = this.getRawDatabase(database).collection<T>(collectionName);
const operationId = Math.random().toString(36).substring(7);
const dbName = database || this.defaultDatabase;
let totalInserted = 0;
let totalUpdated = 0;
const errors: unknown[] = [];
this.logger.debug(
`Starting batch upsert operation [${collectionName}-${documents.length}][${operationId}]`,
{
database: dbName,
collection: collectionName,
totalDocuments: documents.length,
uniqueKeys: keyFields,
chunkSize,
}
);
// Process documents in chunks to avoid memory issues
for (let i = 0; i < documents.length; i += chunkSize) {
const chunk = documents.slice(i, i + chunkSize);
try {
const startTime = Date.now();
// Prepare bulk operations
const bulkOps = chunk.map(doc => {
const now = new Date();
const docWithTimestamps = {
@ -304,17 +338,15 @@ export class MongoDBClient {
updated_at: now,
};
// Create filter using multiple unique keys
const filter: Record<string, unknown> = {};
keyFields.forEach(key => {
for (const key of keyFields) {
const value = (doc as Record<string, unknown>)[key];
if (value === undefined || value === null) {
throw new Error(`Document missing required unique key: ${key}`);
}
filter[key] = value;
});
}
// Remove created_at from $set to avoid conflict with $setOnInsert
const { created_at, ...updateFields } = docWithTimestamps;
return {
@ -329,22 +361,16 @@ export class MongoDBClient {
};
});
// Execute bulk operation with type assertion to handle complex MongoDB types
const result = await collection.bulkWrite(bulkOps as never, { ordered: false });
const executionTime = Date.now() - startTime;
const inserted = result.upsertedCount;
const updated = result.modifiedCount;
totalInserted += inserted;
totalUpdated += updated;
totalInserted += result.upsertedCount;
totalUpdated += result.modifiedCount;
this.logger.debug(`Batch upsert chunk processed [${operationId}]`, {
chunkNumber: Math.floor(i / chunkSize) + 1,
chunkSize: chunk.length,
inserted,
updated,
executionTime,
inserted: result.upsertedCount,
updated: result.modifiedCount,
executionTime: Date.now() - startTime,
database: dbName,
collection: collectionName,
});
@ -358,45 +384,13 @@ export class MongoDBClient {
chunkSize: chunk.length,
uniqueKeys: keyFields,
});
errors.push(error);
throw error;
}
}
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 };
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors: [] };
}
/**
* Get a typed collection
*/
getCollection<T extends Document = Document>(name: string, database?: string): Collection<T> {
const db = this.getDatabase(database);
return db.collection<T>(name);
}
/**
* Get a collection (interface compatibility method)
* This method provides compatibility with the IMongoDBClient interface
*/
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
return this.getCollection<T>(name, database);
}
/**
* Simple insert operation
*/
async insertOne<T extends DocumentBase>(
collectionName: string,
document: Omit<T, '_id' | 'created_at' | 'updated_at'> &
@ -404,7 +398,7 @@ export class MongoDBClient {
database?: string
): Promise<T> {
this.assertWritable(`insertOne(${collectionName})`);
const collection = this.getCollection<T>(collectionName, database);
const collection = this.getRawDatabase(database).collection<T>(collectionName);
const now = new Date();
const docWithTimestamps = {
@ -417,9 +411,6 @@ export class MongoDBClient {
return { ...docWithTimestamps, _id: result.insertedId } as T;
}
/**
* Insert multiple documents
*/
async insertMany<T extends Document = Document>(
collectionName: string,
documents: T[],
@ -427,7 +418,7 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`insertMany(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const now = new Date();
const docsWithTimestamps = documents.map(doc => ({
@ -446,9 +437,6 @@ export class MongoDBClient {
};
}
/**
* Find multiple documents
*/
async find<T extends Document = Document>(
collectionName: string,
filter: Filter<Document> = {},
@ -460,9 +448,6 @@ export class MongoDBClient {
return (await cursor.toArray()) as T[];
}
/**
* Find a single document
*/
async findOne<T extends Document = Document>(
collectionName: string,
filter: Filter<Document>,
@ -474,9 +459,21 @@ export class MongoDBClient {
return result as T | null;
}
/**
* Update a single document
*/
private withUpdatedTimestamp(update: Document): Document {
const now = new Date();
const hasOperator = Object.keys(update).some(key => key.startsWith('$'));
if (!hasOperator) {
return { $set: { ...update, updated_at: now } };
}
return {
...update,
$set: {
...(update.$set && typeof update.$set === 'object' ? update.$set : {}),
updated_at: now,
},
};
}
async updateOne(
collectionName: string,
filter: Filter<Document>,
@ -485,16 +482,8 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`updateOne(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
// Add updated_at timestamp
if (update.$set) {
update.$set.updated_at = new Date();
} else if (!update.$setOnInsert && !update.$unset && !update.$inc) {
update = { $set: { ...update, updated_at: new Date() } };
}
const result = await collection.updateOne(filter, update, options);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.updateOne(filter, this.withUpdatedTimestamp(update), options);
return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
@ -503,9 +492,6 @@ export class MongoDBClient {
};
}
/**
* Update multiple documents
*/
async updateMany(
collectionName: string,
filter: Filter<Document>,
@ -514,16 +500,8 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`updateMany(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
// Add updated_at timestamp
if (update.$set) {
update.$set.updated_at = new Date();
} else if (!update.$setOnInsert && !update.$unset && !update.$inc) {
update = { $set: { ...update, updated_at: new Date() } };
}
const result = await collection.updateMany(filter, update, options);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.updateMany(filter, this.withUpdatedTimestamp(update), options);
return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
@ -532,9 +510,6 @@ export class MongoDBClient {
};
}
/**
* Delete a single document
*/
async deleteOne(
collectionName: string,
filter: Filter<Document>,
@ -542,16 +517,11 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`deleteOne(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.deleteOne(filter, options);
return {
deletedCount: result.deletedCount,
};
return { deletedCount: result.deletedCount };
}
/**
* Delete multiple documents
*/
async deleteMany(
collectionName: string,
filter: Filter<Document>,
@ -559,16 +529,11 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`deleteMany(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.deleteMany(filter, options);
return {
deletedCount: result.deletedCount,
};
return { deletedCount: result.deletedCount };
}
/**
* Count documents matching a filter
*/
async countDocuments(
collectionName: string,
filter: Filter<Document> = {},
@ -579,9 +544,6 @@ export class MongoDBClient {
return await collection.countDocuments(filter, options);
}
/**
* Perform aggregation operations
*/
async aggregate<T extends Document = Document>(
collectionName: string,
pipeline: Document[],
@ -589,14 +551,11 @@ export class MongoDBClient {
dbName?: string
): Promise<T[]> {
this.assertReadOnlyPipeline(pipeline);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const cursor = collection.aggregate(pipeline, options);
return (await cursor.toArray()) as T[];
}
/**
* Create an index
*/
async createIndex(
collectionName: string,
indexSpec: IndexSpecification,
@ -604,13 +563,10 @@ export class MongoDBClient {
dbName?: string
): Promise<string> {
this.assertWritable(`createIndex(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
return await collection.createIndex(indexSpec, options);
}
/**
* Drop an index
*/
async dropIndex(
collectionName: string,
indexName: string,
@ -618,118 +574,44 @@ export class MongoDBClient {
dbName?: string
): Promise<void> {
this.assertWritable(`dropIndex(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
await collection.dropIndex(indexName, options);
}
/**
* List all indexes on a collection
*/
async listIndexes(collectionName: string, dbName?: string): Promise<Document[]> {
const collection = this.getCollection(collectionName, dbName);
const cursor = collection.listIndexes();
return await cursor.toArray();
}
/**
* Get a database instance (interface compatibility)
*/
getDb(dbName?: string): Db {
return this.getDatabase(dbName);
}
/**
* Create a new collection
*/
async createCollection(
collectionName: string,
options?: CreateCollectionOptions,
dbName?: string
): Promise<void> {
this.assertWritable(`createCollection(${collectionName})`);
const db = this.getDatabase(dbName);
const db = this.getRawDatabase(dbName);
await db.createCollection(collectionName, options);
}
/**
* Drop a collection
*/
async dropCollection(collectionName: string, dbName?: string): Promise<void> {
this.assertWritable(`dropCollection(${collectionName})`);
const db = this.getDatabase(dbName);
const db = this.getRawDatabase(dbName);
await db.dropCollection(collectionName);
}
/**
* List all collections in a database
*/
async listCollections(filter: Filter<Document> = {}, dbName?: string): Promise<Document[]> {
const db = this.getDatabase(dbName);
const collections = await db.listCollections(filter).toArray();
return collections;
return await db.listCollections(filter).toArray();
}
/**
* Check if client is connected
*/
get connected(): boolean {
return this.isConnected && !!this.client;
}
/**
* Get the default database instance
*/
get database(): Db | null {
return this.db;
}
/**
* Convenience methods for common databases
*/
// Stock database operations
async batchUpsertStock<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: { chunkSize?: number } = {}
) {
return this.batchUpsert(collectionName, documents, uniqueKeys, {
...options,
database: 'stock',
});
}
// Trading documents database operations
async batchUpsertTrading<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: { chunkSize?: number } = {}
) {
return this.batchUpsert(collectionName, documents, uniqueKeys, {
...options,
database: 'trading_documents',
});
}
// Analytics database operations
async batchUpsertAnalytics<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: { chunkSize?: number } = {}
) {
return this.batchUpsert(collectionName, documents, uniqueKeys, {
...options,
database: 'analytics',
});
getPoolMetrics(): PoolMetrics {
this.metrics.lastUsed = new Date();
return { ...this.metrics };
}
private buildConnectionUri(): string {
@ -738,136 +620,12 @@ export class MongoDBClient {
}
const { host, port, username, password, database, authSource } = this.config;
// Build URI components
const auth = username && password ? `${username}:${password}@` : '';
const authParam = authSource && username ? `?authSource=${authSource}` : '';
const auth =
username && password !== undefined
? `${encodeURIComponent(username)}:${encodeURIComponent(password)}@`
: '';
const authParam = authSource && username ? `?authSource=${encodeURIComponent(authSource)}` : '';
return `mongodb://${auth}${host}:${port}/${database}${authParam}`;
}
/**
* Get current pool metrics
*/
getPoolMetrics(): PoolMetrics {
// Update last used timestamp
this.metrics.lastUsed = new Date();
// Note: MongoDB driver doesn't expose detailed pool metrics
// These are estimates based on configuration
return { ...this.metrics };
}
/**
* Set dynamic pool configuration
*/
setDynamicPoolConfig(config: DynamicPoolConfig): void {
this.dynamicPoolConfig = config;
if (config.enabled && this.isConnected && !this.poolMonitorInterval) {
this.startPoolMonitoring();
} else if (!config.enabled && this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
}
/**
* Start monitoring pool and adjust size dynamically
*/
private startPoolMonitoring(): void {
if (!this.dynamicPoolConfig || this.poolMonitorInterval) {
return;
}
this.poolMonitorInterval = setInterval(() => {
this.evaluatePoolSize();
}, this.dynamicPoolConfig.evaluationInterval);
}
/**
* Evaluate and adjust pool size based on usage
*/
private async evaluatePoolSize(): Promise<void> {
if (!this.dynamicPoolConfig || !this.client) {
return;
}
const { minSize, maxSize, scaleUpThreshold, scaleDownThreshold } = this.dynamicPoolConfig;
const currentSize = this.metrics.totalConnections;
const utilization = (this.metrics.activeConnections / currentSize) * 100;
this.logger.debug('Pool utilization', {
utilization: `${utilization.toFixed(1)}%`,
active: this.metrics.activeConnections,
total: currentSize,
});
// Scale up if utilization is high
if (utilization > scaleUpThreshold && currentSize < maxSize) {
const newSize = Math.min(currentSize + this.dynamicPoolConfig.scaleUpIncrement, maxSize);
await this.resizePool(newSize);
this.logger.info('Scaling up connection pool', {
from: currentSize,
to: newSize,
utilization,
});
}
// Scale down if utilization is low
else if (utilization < scaleDownThreshold && currentSize > minSize) {
const newSize = Math.max(currentSize - this.dynamicPoolConfig.scaleDownIncrement, minSize);
await this.resizePool(newSize);
this.logger.info('Scaling down connection pool', {
from: currentSize,
to: newSize,
utilization,
});
}
}
/**
* Resize the connection pool
* Note: MongoDB driver doesn't support dynamic resizing, this would require reconnection
*/
private async resizePool(newSize: number): Promise<void> {
// MongoDB doesn't support dynamic pool resizing
// This is a placeholder for future implementation
this.logger.warn('Dynamic pool resizing not yet implemented for MongoDB', {
requestedSize: newSize,
});
// Update metrics to reflect desired state
this.metrics.totalConnections = newSize;
}
/**
* Enable pool warmup on connect
*/
async warmupPool(): Promise<void> {
if (!this.client || !this.isConnected) {
throw new Error('Client not connected');
}
const minSize = this.config.poolSettings?.minPoolSize || 1;
const promises: Promise<void>[] = [];
// Create minimum connections by running parallel pings
for (let i = 0; i < minSize; i++) {
promises.push(
this.client
.db(this.defaultDatabase)
.admin()
.ping()
.then(() => {
this.logger.debug(`Warmed up connection ${i + 1}/${minSize}`);
})
.catch(error => {
this.logger.warn(`Failed to warm up connection ${i + 1}`, { error });
})
);
}
await Promise.allSettled(promises);
this.logger.info('Connection pool warmup complete', { connections: minSize });
}
}