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

@ -14,8 +14,6 @@
},
"dependencies": {
"@stock-bot/logger": "*",
"@stock-bot/types": "*",
"@types/mongodb": "^4.0.7",
"mongodb": "^6.17.0"
},
"devDependencies": {

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

View file

@ -1,29 +1,10 @@
/**
* MongoDB Client Library for Stock Bot Data Service
*
* Provides a MongoDB client focused on batch upsert operations
* for high-performance data ingestion.
*/
export { MongoDBClient } from './client';
// Types
export type {
AnalystReport,
ConnectionEvents,
DocumentBase,
DynamicPoolConfig,
EarningsTranscript,
ExchangeSourceMapping,
MasterExchange,
MongoDBClientConfig,
MongoDBConnectionOptions,
NewsArticle,
PoolMetrics,
RawDocument,
SecFiling,
SentimentData,
} from './types';
// Note: Factory functions removed - use Awilix DI container instead
// See: libs/core/di/src/awilix-container.ts

View file

@ -1,8 +1,5 @@
import type { ObjectId } from 'mongodb';
/**
* MongoDB Client Configuration
*/
export interface MongoDBClientConfig {
host: string;
port: number;
@ -35,9 +32,6 @@ export interface MongoDBClientConfig {
};
}
/**
* MongoDB Connection Options
*/
export interface MongoDBConnectionOptions {
retryAttempts?: number;
retryDelay?: number;
@ -63,20 +57,6 @@ export interface ConnectionEvents {
onPoolCreated?: () => void | Promise<void>;
}
export interface DynamicPoolConfig {
enabled: boolean;
minSize: number;
maxSize: number;
scaleUpThreshold: number; // % of pool in use (0-100)
scaleDownThreshold: number; // % of pool idle (0-100)
scaleUpIncrement: number; // connections to add
scaleDownIncrement: number; // connections to remove
evaluationInterval: number; // ms between checks
}
/**
* Base Document Interface
*/
export interface DocumentBase {
_id?: ObjectId;
created_at: Date;
@ -85,129 +65,6 @@ export interface DocumentBase {
metadata?: Record<string, unknown>;
}
/**
* Sentiment Data Document
*/
export interface SentimentData extends DocumentBase {
symbol: string;
sentiment_score: number;
sentiment_label: 'positive' | 'negative' | 'neutral';
confidence: number;
text: string;
source_type: 'reddit' | 'twitter' | 'news' | 'forums';
source_id: string;
timestamp: Date;
processed_at: Date;
language: string;
keywords: string[];
entities: Array<{
name: string;
type: string;
confidence: number;
}>;
}
/**
* Raw Document
*/
export interface RawDocument extends DocumentBase {
document_type: 'html' | 'pdf' | 'text' | 'json' | 'xml';
content: string;
content_hash: string;
url?: string;
title?: string;
author?: string;
published_date?: Date;
extracted_text?: string;
processing_status: 'pending' | 'processed' | 'failed';
size_bytes: number;
language?: string;
}
/**
* News Article
*/
export interface NewsArticle extends DocumentBase {
headline: string;
content: string;
summary?: string;
author: string;
publication: string;
published_date: Date;
url: string;
symbols: string[];
categories: string[];
sentiment_score?: number;
relevance_score?: number;
image_url?: string;
tags: string[];
}
/**
* SEC Filing
*/
export interface SecFiling extends DocumentBase {
cik: string;
accession_number: string;
filing_type: string;
company_name: string;
symbols: string[];
filing_date: Date;
period_end_date: Date;
url: string;
content: string;
extracted_data?: Record<string, unknown>;
financial_statements?: Array<{
statement_type: string;
data: Record<string, number>;
}>;
processing_status: 'pending' | 'processed' | 'failed';
}
/**
* Earnings Transcript
*/
export interface EarningsTranscript extends DocumentBase {
symbol: string;
company_name: string;
quarter: string;
year: number;
call_date: Date;
transcript: string;
participants: Array<{
name: string;
title: string;
type: 'executive' | 'analyst';
}>;
key_topics: string[];
sentiment_analysis?: {
overall_sentiment: number;
topic_sentiments: Record<string, number>;
};
financial_highlights?: Record<string, number>;
}
/**
* Analyst Report
*/
export interface AnalystReport extends DocumentBase {
symbol: string;
analyst_firm: string;
analyst_name: string;
report_title: string;
report_date: Date;
rating: 'buy' | 'hold' | 'sell' | 'strong_buy' | 'strong_sell';
price_target?: number;
previous_rating?: string;
content: string;
summary: string;
key_points: string[];
financial_projections?: Record<string, number>;
}
/**
* Exchange-related types
*/
export interface ExchangeSourceMapping {
id: string;
name: string;
@ -224,13 +81,11 @@ export interface MasterExchange extends DocumentBase {
currency: string;
timezone: string;
active?: boolean;
tradingHours?: {
open: string;
close: string;
timezone: string;
};
sourceMappings: Record<string, ExchangeSourceMapping>;
confidence: number;
verified: boolean;

View file

@ -1,197 +0,0 @@
import { beforeEach, describe, expect, it } from 'bun:test';
import { SimpleMongoDBClient } from './support/simple-mongodb';
describe('MongoDBClient', () => {
let client: SimpleMongoDBClient;
const config = {
uri: 'mongodb://localhost:27017',
database: 'test-db',
};
beforeEach(() => {
client = new SimpleMongoDBClient(config);
});
describe('connection', () => {
it('should connect on first operation', async () => {
const results = await client.find('test-collection', {});
expect(results).toBeDefined();
expect(results).toEqual([]);
});
it('should handle health check', async () => {
// Connect first by doing an operation
await client.find('test', {});
const health = await client.healthCheck();
expect(health.status).toBe('healthy');
expect(health.isConnected).toBe(true);
});
it('should disconnect properly', async () => {
await client.find('test', {});
await client.disconnect();
const health = await client.healthCheck();
expect(health.isConnected).toBe(false);
});
});
describe('CRUD operations', () => {
it('should find documents', async () => {
await client.insert('users', { id: 1, active: true });
await client.insert('users', { id: 2, active: true });
await client.insert('users', { id: 3, active: false });
const results = await client.find('users', { active: true });
expect(results).toHaveLength(2);
expect(results[0].active).toBe(true);
expect(results[1].active).toBe(true);
});
it('should find one document', async () => {
await client.insert('users', { id: 1, name: 'Test' });
await client.insert('users', { id: 2, name: 'Other' });
const result = await client.findOne('users', { id: 1 });
expect(result).toBeDefined();
expect(result.id).toBe(1);
expect(result.name).toBe('Test');
});
it('should insert documents', async () => {
const doc = { name: 'Test User', email: 'test@example.com' };
await client.insert('users', doc);
const result = await client.findOne('users', { email: 'test@example.com' });
expect(result).toBeDefined();
expect(result.name).toBe('Test User');
});
it('should insert many documents', async () => {
const docs = [{ name: 'User 1' }, { name: 'User 2' }];
await client.insertMany('users', docs);
const all = await client.find('users', {});
expect(all).toHaveLength(2);
});
it('should update documents', async () => {
await client.insert('users', { id: 1, active: true });
const updated = await client.update('users', { id: 1 }, { $set: { active: false } });
expect(updated).toBe(1);
const result = await client.findOne('users', { id: 1 });
expect(result.active).toBe(false);
});
it('should update many documents', async () => {
await client.insert('users', { id: 1, active: true });
await client.insert('users', { id: 2, active: true });
await client.insert('users', { id: 3, active: false });
const updated = await client.updateMany(
'users',
{ active: true },
{ $set: { status: 'active' } }
);
expect(updated).toBe(2);
const activeUsers = await client.find('users', { status: 'active' });
expect(activeUsers).toHaveLength(2);
});
it('should delete documents', async () => {
await client.insert('users', { id: 1 });
await client.insert('users', { id: 2 });
const deleted = await client.delete('users', { id: 1 });
expect(deleted).toBe(1);
const remaining = await client.find('users', {});
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe(2);
});
it('should delete many documents', async () => {
await client.insert('users', { id: 1, active: true });
await client.insert('users', { id: 2, active: false });
await client.insert('users', { id: 3, active: false });
const deleted = await client.deleteMany('users', { active: false });
expect(deleted).toBe(2);
const remaining = await client.find('users', {});
expect(remaining).toHaveLength(1);
expect(remaining[0].active).toBe(true);
});
});
describe('batch operations', () => {
it('should perform batch upsert', async () => {
const docs = [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
];
await client.batchUpsert('users', docs, ['id']);
const all = await client.find('users', {});
expect(all).toHaveLength(2);
// Update existing
await client.batchUpsert('users', [{ id: 1, name: 'Updated User 1' }], ['id']);
const updated = await client.findOne('users', { id: 1 });
expect(updated.name).toBe('Updated User 1');
});
it('should handle empty batch', async () => {
await client.batchUpsert('users', [], ['id']);
const all = await client.find('users', {});
expect(all).toHaveLength(0);
});
});
describe('utility methods', () => {
it('should count documents', async () => {
await client.insert('users', { active: true });
await client.insert('users', { active: true });
await client.insert('users', { active: false });
const count = await client.count('users', { active: true });
expect(count).toBe(2);
});
it('should create indexes', async () => {
await client.createIndex('users', { email: 1 }, { unique: true });
// Simple implementation doesn't throw, just no-op
expect(true).toBe(true);
});
});
describe('error handling', () => {
it('should handle disconnected state', async () => {
await client.disconnect();
// Simple implementation auto-reconnects
const results = await client.find('users', {});
expect(results).toBeDefined();
});
it('should return empty array for non-existent collection', async () => {
const results = await client.find('non-existent', {});
expect(results).toEqual([]);
});
});
});

View file

@ -1,165 +0,0 @@
/**
* Test-only in-memory MongoDB double. Never used by production adapters.
*/
export class SimpleMongoDBClient {
private collections = new Map<string, any[]>();
private connected = false;
constructor(private config: any) {}
async connect(): Promise<void> {
this.connected = true;
}
async disconnect(): Promise<void> {
this.connected = false;
}
async find(collection: string, filter: any = {}): Promise<any[]> {
if (!this.connected) {
await this.connect();
}
const docs = this.collections.get(collection) || [];
// Simple filter matching
if (Object.keys(filter).length === 0) {
return docs;
}
return docs.filter(doc => {
for (const [key, value] of Object.entries(filter)) {
if (doc[key] !== value) {
return false;
}
}
return true;
});
}
async findOne(collection: string, filter: any = {}): Promise<any | null> {
const results = await this.find(collection, filter);
return results[0] || null;
}
async insert(collection: string, doc: any): Promise<void> {
if (!this.connected) {
await this.connect();
}
const docs = this.collections.get(collection) || [];
docs.push({ ...doc, _id: Math.random().toString(36) });
this.collections.set(collection, docs);
}
async insertMany(collection: string, documents: any[]): Promise<void> {
for (const doc of documents) {
await this.insert(collection, doc);
}
}
async update(collection: string, filter: any, update: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const docs = await this.find(collection, filter);
if (docs.length === 0) {
return 0;
}
const doc = docs[0];
if (update.$set) {
Object.assign(doc, update.$set);
}
return 1;
}
async updateMany(collection: string, filter: any, update: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const docs = await this.find(collection, filter);
for (const doc of docs) {
if (update.$set) {
Object.assign(doc, update.$set);
}
}
return docs.length;
}
async delete(collection: string, filter: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const allDocs = this.collections.get(collection) || [];
const toDelete = await this.find(collection, filter);
if (toDelete.length === 0) {
return 0;
}
const remaining = allDocs.filter(doc => !toDelete.includes(doc));
this.collections.set(collection, remaining);
return 1;
}
async deleteMany(collection: string, filter: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const allDocs = this.collections.get(collection) || [];
const toDelete = await this.find(collection, filter);
const remaining = allDocs.filter(doc => !toDelete.includes(doc));
this.collections.set(collection, remaining);
return toDelete.length;
}
async batchUpsert(collection: string, documents: any[], uniqueKeys: string[]): Promise<void> {
if (!this.connected) {
await this.connect();
}
for (const doc of documents) {
const filter: any = {};
for (const key of uniqueKeys) {
filter[key] = doc[key];
}
const existing = await this.findOne(collection, filter);
if (existing) {
await this.update(collection, filter, { $set: doc });
} else {
await this.insert(collection, doc);
}
}
}
async count(collection: string, filter: any = {}): Promise<number> {
const docs = await this.find(collection, filter);
return docs.length;
}
async createIndex(_collection: string, _index: any, _options?: any): Promise<void> {
// No-op for simple implementation
}
async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> {
try {
return {
status: this.connected ? 'healthy' : 'unhealthy',
isConnected: this.connected,
};
} catch (error: any) {
return {
status: 'unhealthy',
isConnected: false,
error: error.message,
};
}
}
}

View file

@ -14,7 +14,6 @@
},
"dependencies": {
"@stock-bot/logger": "*",
"@stock-bot/types": "*",
"pg": "^8.11.3",
"@stock-bot/invariants": "workspace:*"
},

View file

@ -1,13 +1,9 @@
import type { PoolConfig, QueryResultRow } from 'pg';
import { Pool } 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';
import type {
ConnectionEvents,
DynamicPoolConfig,
PoolMetrics,
PostgreSQLClientConfig,
PostgreSQLConnectionOptions,
@ -15,24 +11,15 @@ import type {
TransactionCallback,
} from './types';
/**
* PostgreSQL Client for Stock Bot
*
* Provides type-safe access to PostgreSQL with connection pooling,
* health monitoring, and transaction support.
*/
export class PostgreSQLClient {
private pool: Pool | null = null;
private readonly config: PostgreSQLClientConfig;
private readonly options: PostgreSQLConnectionOptions;
private readonly logger: LoggerLike;
private readonly healthMonitor: PostgreSQLHealthMonitor;
private readonly transactionManager: PostgreSQLTransactionManager;
private isConnected = false;
private readonly metrics: PoolMetrics;
private readonly events?: ConnectionEvents;
private dynamicPoolConfig?: DynamicPoolConfig;
private poolMonitorInterval?: NodeJS.Timeout;
constructor(
config: PostgreSQLClientConfig,
@ -44,15 +31,11 @@ export class PostgreSQLClient {
this.options = {
retryAttempts: 3,
retryDelay: 1000,
healthCheckInterval: 30000,
...options,
};
this.events = events;
this.logger = logger || console;
this.healthMonitor = new PostgreSQLHealthMonitor(this);
this.transactionManager = new PostgreSQLTransactionManager(this);
this.metrics = {
totalConnections: 0,
activeConnections: 0,
@ -63,71 +46,48 @@ export class PostgreSQLClient {
};
}
/**
* Connect to PostgreSQL
*/
async connect(): Promise<void> {
if (this.isConnected && this.pool) {
return;
}
let lastError: Error | null = null;
const attempts = this.options.retryAttempts ?? 3;
for (let attempt = 1; attempt <= (this.options.retryAttempts ?? 3); attempt++) {
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
this.logger.info(
`Connecting to PostgreSQL (attempt ${attempt}/${this.options.retryAttempts})...`
);
this.logger.info(`Connecting to PostgreSQL (attempt ${attempt}/${attempts})...`);
this.pool = new Pool(this.buildPoolConfig());
// Test the connection
const client = await this.pool.connect();
await client.query('SELECT 1');
client.release();
try {
await client.query('SELECT 1');
} finally {
client.release();
}
this.isConnected = true;
this.metrics.totalConnections = this.config.poolSettings?.max || 10;
this.metrics.idleConnections = this.pool.idleCount;
// Update metrics
const poolConfig = this.config.poolSettings;
this.metrics.totalConnections = poolConfig?.max || 10;
this.metrics.idleConnections = poolConfig?.min || 2;
// 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.setupErrorHandlers();
this.logger.info('Successfully connected to PostgreSQL', {
poolSize: this.metrics.totalConnections,
});
// Start health monitoring
this.healthMonitor.start();
// Setup error handlers
this.setupErrorHandlers();
// Setup pool event listeners for metrics
this.setupPoolMetrics();
// Start dynamic pool monitoring if 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));
}
@ -135,42 +95,31 @@ export class PostgreSQLClient {
this.logger.error(`PostgreSQL connection attempt ${attempt} failed:`, error);
if (this.pool) {
await this.pool.end();
await this.pool.end().catch(() => {});
this.pool = null;
}
if (attempt < (this.options.retryAttempts ?? 3)) {
await this.delay((this.options.retryDelay ?? 1000) * attempt);
if (attempt < attempts) {
await new Promise(resolve => setTimeout(resolve, (this.options.retryDelay ?? 1000) * attempt));
}
}
}
throw new Error(
`Failed to connect to PostgreSQL after ${this.options.retryAttempts} attempts: ${lastError?.message}`
`Failed to connect to PostgreSQL after ${attempts} attempts: ${lastError?.message}`
);
}
/**
* Disconnect from PostgreSQL
*/
async disconnect(): Promise<void> {
if (!this.pool) {
return;
}
try {
// Stop pool monitoring
if (this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
this.healthMonitor.stop();
await this.pool.end();
this.isConnected = false;
this.pool = null;
// Fire disconnect event
if (this.events?.onDisconnect) {
await Promise.resolve(this.events.onDisconnect());
}
@ -182,9 +131,6 @@ export class PostgreSQLClient {
}
}
/**
* Execute a query
*/
async query<T extends QueryResultRow = QueryResultRow>(
text: string,
params?: unknown[]
@ -194,16 +140,13 @@ export class PostgreSQLClient {
}
const startTime = Date.now();
try {
const result = await this.pool.query<T>(text, params);
const executionTime = Date.now() - startTime;
this.logger.debug(`Query executed in ${executionTime}ms`, {
query: text.substring(0, 100),
params: params?.length,
});
return {
...result,
executionTime,
@ -219,204 +162,13 @@ export class PostgreSQLClient {
}
}
/**
* Execute multiple queries in a transaction
*/
async transaction<T>(callback: TransactionCallback<T>): Promise<T> {
return await this.transactionManager.execute(callback);
}
/**
* Get a query builder instance
*/
queryBuilder(): PostgreSQLQueryBuilder {
return new PostgreSQLQueryBuilder(this);
}
/**
* Create a new query builder with SELECT
*/
select(columns: string | string[] = '*'): PostgreSQLQueryBuilder {
return this.queryBuilder().select(columns);
}
/**
* Create a new query builder with INSERT
*/
insert(table: string): PostgreSQLQueryBuilder {
return this.queryBuilder().insert(table);
}
/**
* Create a new query builder with UPDATE
*/
update(table: string): PostgreSQLQueryBuilder {
return this.queryBuilder().update(table);
}
/**
* Create a new query builder with DELETE
*/
delete(table: string): PostgreSQLQueryBuilder {
return this.queryBuilder().delete(table);
}
/**
* Execute a stored procedure or function
*/
async callFunction<T extends QueryResultRow = QueryResultRow>(
functionName: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const placeholders = params ? params.map((_, i) => `$${i + 1}`).join(', ') : '';
const query = `SELECT * FROM ${functionName}(${placeholders})`;
return await this.query<T>(query, params);
}
/**
* Batch upsert operation for high-performance inserts/updates
*/
async batchUpsert(
tableName: string,
data: Record<string, unknown>[],
conflictColumn: string,
options: {
chunkSize?: number;
excludeColumns?: string[];
} = {}
): Promise<{ insertedCount: number; updatedCount: number }> {
if (!this.pool) {
throw new Error('PostgreSQL client not connected');
}
if (data.length === 0) {
return { insertedCount: 0, updatedCount: 0 };
}
const { chunkSize = 1000, excludeColumns = [] } = options;
const columns = Object.keys(data[0] ?? {}).filter(col => !excludeColumns.includes(col));
const updateColumns = columns.filter(col => col !== conflictColumn);
let totalInserted = 0;
let totalUpdated = 0;
// Process in chunks to avoid memory issues and parameter limits
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.slice(i, i + chunkSize);
// Build placeholders for this chunk
const placeholders = chunk.map((_, rowIndex) => {
const rowPlaceholders = columns.map((_, colIndex) => {
return `$${rowIndex * columns.length + colIndex + 1}`;
});
return `(${rowPlaceholders.join(', ')})`;
});
// Flatten the chunk data
const values = chunk.flatMap(row => columns.map(col => row[col as keyof typeof row]));
// Build the upsert query
const updateClauses = updateColumns.map(col => `${col} = EXCLUDED.${col}`);
const query = `
INSERT INTO ${tableName} (${columns.join(', ')})
VALUES ${placeholders.join(', ')}
ON CONFLICT (${conflictColumn})
DO UPDATE SET
${updateClauses.join(', ')},
updated_at = NOW()
RETURNING (xmax = 0) AS is_insert
`;
try {
const startTime = Date.now();
const result = await this.pool.query(query, values);
const executionTime = Date.now() - startTime;
// Count inserts vs updates
const inserted = result.rows.filter((row: { is_insert: boolean }) => row.is_insert).length;
const updated = result.rows.length - inserted;
totalInserted += inserted;
totalUpdated += updated;
this.logger.debug(`Batch upsert chunk processed in ${executionTime}ms`, {
chunkSize: chunk.length,
inserted,
updated,
table: tableName,
});
} catch (error) {
this.logger.error(`Batch upsert failed on chunk ${Math.floor(i / chunkSize) + 1}:`, {
error,
table: tableName,
chunkStart: i,
chunkSize: chunk.length,
});
throw error;
}
}
this.logger.info('Batch upsert completed', {
table: tableName,
totalRecords: data.length,
inserted: totalInserted,
updated: totalUpdated,
});
return { insertedCount: totalInserted, updatedCount: totalUpdated };
}
/**
* Check if a table exists
*/
async tableExists(tableName: string, schemaName: string = 'public'): Promise<boolean> {
const result = await this.query(
`SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = $1 AND table_name = $2
)`,
[schemaName, tableName]
);
return at(result.rows, 0).exists;
}
/**
* Get table schema information
*/
async getTableSchema(
tableName: string,
schemaName: string = 'public'
): Promise<QueryResultRow[]> {
const result = await this.query(
`SELECT
column_name,
data_type,
is_nullable,
column_default,
character_maximum_length
FROM information_schema.columns
WHERE table_schema = $1 AND table_name = $2
ORDER BY ordinal_position`,
[schemaName, tableName]
);
return result.rows;
}
/**
* Execute EXPLAIN for query analysis
*/
async explain(query: string, params?: unknown[]): Promise<QueryResultRow[]> {
const explainQuery = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`;
const result = await this.query(explainQuery, params);
return at(result.rows, 0)['QUERY PLAN'];
}
/**
* Get database statistics
*/
async getStats(): Promise<QueryResultRow> {
const result = await this.query(`
SELECT
SELECT
(SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections,
(SELECT count(*) FROM pg_stat_activity WHERE state = 'idle') as idle_connections,
(SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections,
@ -425,34 +177,24 @@ export class PostgreSQLClient {
return result.rows[0] ?? {};
}
/**
* Check if client is connected
*/
get connected(): boolean {
return this.isConnected && !!this.pool;
}
/**
* Get the underlying connection pool
*/
get connectionPool(): Pool | null {
return this.pool;
}
private buildPoolConfig(): PoolConfig {
buildPoolConfig(): PoolConfig {
this.logger.debug('Building PostgreSQL pool config:', {
host: this.config.host,
port: this.config.port,
database: this.config.database,
user: this.config.username,
passwordLength: this.config.password?.length,
passwordType: typeof this.config.password,
passwordValue: this.config.password
? `${this.config.password.substring(0, 3)}***`
: 'NO_PASSWORD',
hasPassword: Boolean(this.config.password),
});
const poolConfig = {
return {
host: this.config.host,
port: this.config.port,
database: this.config.database,
@ -475,166 +217,28 @@ export class PostgreSQLClient {
}
: false,
};
}
return poolConfig;
getPoolMetrics(): PoolMetrics {
this.metrics.lastUsed = new Date();
if (this.pool) {
this.metrics.totalConnections = this.pool.totalCount;
this.metrics.idleConnections = this.pool.idleCount;
this.metrics.waitingRequests = this.pool.waitingCount;
this.metrics.activeConnections = Math.max(
0,
this.metrics.totalConnections - this.metrics.idleConnections
);
}
return { ...this.metrics };
}
private setupErrorHandlers(): void {
if (!this.pool) {
return;
}
this.pool.on('error', error => {
this.logger.error('PostgreSQL pool error:', error);
});
this.pool.on('connect', () => {
this.logger.debug('New PostgreSQL client connected');
});
this.pool.on('remove', () => {
this.logger.debug('PostgreSQL client removed from pool');
});
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Get current pool metrics
*/
getPoolMetrics(): PoolMetrics {
// Update last used timestamp
this.metrics.lastUsed = new Date();
// Update metrics from pool if available
if (this.pool) {
this.metrics.totalConnections = this.pool.totalCount;
this.metrics.idleConnections = this.pool.idleCount;
this.metrics.waitingRequests = this.pool.waitingCount;
this.metrics.activeConnections = this.metrics.totalConnections - this.metrics.idleConnections;
}
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);
}
/**
* Setup pool event listeners for metrics
*/
private setupPoolMetrics(): void {
if (!this.pool) {
return;
}
// Track when connections are acquired
this.pool.on('acquire', () => {
this.metrics.activeConnections++;
this.metrics.idleConnections--;
});
// Track when connections are released
this.pool.on('release', () => {
this.metrics.activeConnections--;
this.metrics.idleConnections++;
});
}
/**
* Evaluate and adjust pool size based on usage
*/
private async evaluatePoolSize(): Promise<void> {
if (!this.dynamicPoolConfig || !this.pool) {
return;
}
const metrics = this.getPoolMetrics();
const { minSize, maxSize, scaleUpThreshold, scaleDownThreshold } = this.dynamicPoolConfig;
const currentSize = metrics.totalConnections;
const utilization = currentSize > 0 ? (metrics.activeConnections / currentSize) * 100 : 0;
this.logger.debug('Pool utilization', {
utilization: `${utilization.toFixed(1)}%`,
active: metrics.activeConnections,
total: currentSize,
waiting: metrics.waitingRequests,
});
// Scale up if utilization is high or there are waiting requests
if ((utilization > scaleUpThreshold || metrics.waitingRequests > 0) && currentSize < maxSize) {
const newSize = Math.min(currentSize + this.dynamicPoolConfig.scaleUpIncrement, maxSize);
this.logger.info('Would scale up connection pool', {
from: currentSize,
to: newSize,
utilization,
});
// Note: pg module doesn't support dynamic resizing, would need reconnection
}
// Scale down if utilization is low
else if (utilization < scaleDownThreshold && currentSize > minSize) {
const newSize = Math.max(currentSize - this.dynamicPoolConfig.scaleDownIncrement, minSize);
this.logger.info('Would scale down connection pool', {
from: currentSize,
to: newSize,
utilization,
});
// Note: pg module doesn't support dynamic resizing, would need reconnection
}
}
/**
* Enable pool warmup on connect
*/
async warmupPool(): Promise<void> {
if (!this.pool || !this.isConnected) {
throw new Error('Client not connected');
}
const minSize = this.config.poolSettings?.min || 2;
const promises: Promise<void>[] = [];
// Create minimum connections by running parallel queries
for (let i = 0; i < minSize; i++) {
promises.push(
this.pool
.query('SELECT 1')
.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 });
}
}

View file

@ -1,145 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import type { PostgreSQLClient } from './client';
import type { PostgreSQLHealthCheck, PostgreSQLHealthStatus, PostgreSQLMetrics } from './types';
/**
* PostgreSQL Health Monitor
*
* Monitors PostgreSQL connection health and provides metrics
*/
export class PostgreSQLHealthMonitor {
private readonly client: PostgreSQLClient;
private readonly logger: ReturnType<typeof getLogger>;
private healthCheckInterval: NodeJS.Timeout | null = null;
private metrics: PostgreSQLMetrics;
private lastHealthCheck: PostgreSQLHealthCheck | null = null;
constructor(client: PostgreSQLClient) {
this.client = client;
this.logger = getLogger('postgres-health-monitor');
this.metrics = {
queriesPerSecond: 0,
averageQueryTime: 0,
errorRate: 0,
connectionPoolUtilization: 0,
slowQueries: 0,
};
}
/**
* Start health monitoring
*/
start(intervalMs: number = 30000): void {
if (this.healthCheckInterval) {
this.stop();
}
this.logger.info(`Starting PostgreSQL health monitoring (interval: ${intervalMs}ms)`);
this.healthCheckInterval = setInterval(async () => {
try {
await this.performHealthCheck();
} catch (error) {
this.logger.error('Health check failed:', error);
}
}, intervalMs);
// Perform initial health check
this.performHealthCheck().catch(error => {
this.logger.error('Initial health check failed:', error);
});
}
/**
* Stop health monitoring
*/
stop(): void {
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
this.healthCheckInterval = null;
this.logger.info('Stopped PostgreSQL health monitoring');
}
}
/**
* Get current health status
*/
async getHealth(): Promise<PostgreSQLHealthCheck> {
if (!this.lastHealthCheck) {
await this.performHealthCheck();
}
if (!this.lastHealthCheck) {
throw new Error('Health check failed to produce results');
}
return this.lastHealthCheck;
}
/**
* Get current metrics
*/
getMetrics(): PostgreSQLMetrics {
return { ...this.metrics };
}
/**
* Perform a health check
*/
private async performHealthCheck(): Promise<void> {
const startTime = Date.now();
const errors: string[] = [];
let status: PostgreSQLHealthStatus = 'healthy';
try {
if (!this.client.connected) {
errors.push('PostgreSQL client not connected');
status = 'unhealthy';
} else {
// Test basic connectivity
await this.client.query('SELECT 1');
// Get connection stats
const stats = await this.client.getStats();
// Check connection pool utilization
const utilization = parseInt(stats.active_connections) / parseInt(stats.max_connections);
if (utilization > 0.8) {
errors.push('High connection pool utilization');
status = status === 'healthy' ? 'degraded' : status;
}
// Check for high latency
const latency = Date.now() - startTime;
if (latency > 1000) {
errors.push(`High latency: ${latency}ms`);
status = status === 'healthy' ? 'degraded' : status;
}
this.metrics.connectionPoolUtilization = utilization;
}
} catch (error) {
errors.push(`Health check failed: ${(error as Error).message}`);
status = 'unhealthy';
}
const latency = Date.now() - startTime;
this.lastHealthCheck = {
status,
timestamp: new Date(),
latency,
connections: {
active: 1,
idle: 9,
total: 10,
},
errors: errors.length > 0 ? errors : undefined,
};
// Log health status changes
if (status !== 'healthy') {
this.logger.warn(`PostgreSQL health status: ${status}`, { errors, latency });
} else {
this.logger.debug(`PostgreSQL health check passed (${latency}ms)`);
}
}
}

View file

@ -1,37 +1,11 @@
/**
* PostgreSQL Client Library for Stock Bot
*
* Provides type-safe PostgreSQL access for operational data,
* transactions, and relational queries.
*/
export { PostgreSQLClient } from './client';
export { PostgreSQLHealthMonitor } from './health';
export { PostgreSQLTransactionManager } from './transactions';
export { PostgreSQLQueryBuilder } from './query-builder';
// export { PostgreSQLMigrationManager } from './migrations'; // TODO: Implement migrations
// Types
export { runPostgresMigrations, type MigrationTrack } from './migrations';
export type {
ConnectionEvents,
PoolMetrics,
PostgreSQLClientConfig,
PostgreSQLConnectionOptions,
PostgreSQLHealthStatus,
PostgreSQLMetrics,
QueryResult,
TransactionCallback,
SchemaNames,
TableNames,
Trade,
Order,
Position,
Portfolio,
Strategy,
RiskLimit,
AuditLog,
PoolMetrics,
ConnectionEvents,
DynamicPoolConfig,
} from './types';
// Note: Factory functions removed - instantiate directly with new PostgreSQLClient()
// or use the Awilix DI container (recommended)

View file

@ -0,0 +1,113 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { getLogger } from '@stock-bot/logger';
import type { PostgreSQLClient } from './client';
const logger = getLogger('postgres-migrations');
export type MigrationTrack = 'master' | 'research' | 'all';
const MASTER_FILES = new Set([
'01-init-database.sql',
'02-master-schema.sql',
'03-initial-data.sql',
'04-provider-exchange-mapping-schema.sql',
'05-add-visible-column.sql',
]);
const RESEARCH_FILES = new Set([
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'11-simulation-execution-ledger.sql',
'12-historical-datasets.sql',
'13-strategy-recovery.sql',
'14-backtest-submission.sql',
'15-canonical-paper-intents.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
'29-isolated-candidates.sql',
'30-paper-deployments.sql',
'31-research-agent-project-links.sql',
'32-candidate-parameter-defaults.sql',
'33-candidate-decimal-normalization.sql',
]);
function locateMigrationsDir(): string {
let directory = dirname(fileURLToPath(import.meta.url));
while (!existsSync(join(directory, 'database', 'postgres', 'init'))) {
const parent = dirname(directory);
if (parent === directory) {
throw new Error('Cannot locate PostgreSQL migrations directory (database/postgres/init)');
}
directory = parent;
}
return join(directory, 'database', 'postgres', 'init');
}
function matchesTrack(file: string, track: MigrationTrack): boolean {
if (!file.endsWith('.sql')) {
return false;
}
const inMaster = MASTER_FILES.has(file);
const inResearch = file.startsWith('001_') || RESEARCH_FILES.has(file);
if (track === 'master') {
return inMaster;
}
if (track === 'research') {
return inResearch;
}
return inMaster || inResearch;
}
export async function runPostgresMigrations(
postgres: Pick<PostgreSQLClient, 'transaction'>,
options: { track?: MigrationTrack; migrationsDir?: string } = {}
): Promise<string[]> {
const track = options.track ?? 'research';
const applied: string[] = [];
await postgres.transaction(async client => {
await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]);
await client.query(`
CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) NOT NULL UNIQUE,
executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
`);
const migrationsDir = options.migrationsDir ?? locateMigrationsDir();
const files = readdirSync(migrationsDir)
.filter(f => matchesTrack(f, track))
.sort();
for (const file of files) {
const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]);
if (result.rows.length === 0) {
logger.info(`Running migration: ${file}`);
const sql = readFileSync(join(migrationsDir, file), 'utf8');
await client.query(sql);
await client.query(
'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING',
[file]
);
applied.push(file);
}
}
});
return applied;
}

View file

@ -1,270 +0,0 @@
import type { QueryResultRow } from 'pg';
import type { PostgreSQLClient } from './client';
import type { JoinCondition, OrderByCondition, QueryResult, WhereCondition } from './types';
/**
* PostgreSQL Query Builder
*
* Provides a fluent interface for building SQL queries
*/
export class PostgreSQLQueryBuilder {
private queryType: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | null = null;
private selectColumns: string[] = [];
private fromTable: string = '';
private joins: JoinCondition[] = [];
private whereConditions: WhereCondition[] = [];
private groupByColumns: string[] = [];
private havingConditions: WhereCondition[] = [];
private orderByConditions: OrderByCondition[] = [];
private limitCount: number | null = null;
private offsetCount: number | null = null;
private insertValues: Record<string, unknown> = {};
private updateValues: Record<string, unknown> = {};
private readonly client: PostgreSQLClient;
constructor(client: PostgreSQLClient) {
this.client = client;
}
/**
* SELECT statement
*/
select(columns: string | string[] = '*'): this {
this.queryType = 'SELECT';
this.selectColumns = Array.isArray(columns) ? columns : [columns];
return this;
}
/**
* FROM clause
*/
from(table: string): this {
this.fromTable = table;
return this;
}
/**
* JOIN clause
*/
join(table: string, on: string, type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL' = 'INNER'): this {
this.joins.push({ type, table, on });
return this;
}
/**
* WHERE clause
*/
where(column: string, operator: WhereCondition['operator'], value?: unknown): this {
this.whereConditions.push({ column, operator, value });
return this;
}
/**
* GROUP BY clause
*/
groupBy(columns: string | string[]): this {
this.groupByColumns = Array.isArray(columns) ? columns : [columns];
return this;
}
/**
* ORDER BY clause
*/
orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): this {
this.orderByConditions.push({ column, direction });
return this;
}
/**
* LIMIT clause
*/
limit(count: number): this {
this.limitCount = count;
return this;
}
/**
* OFFSET clause
*/
offset(count: number): this {
this.offsetCount = count;
return this;
}
/**
* INSERT statement
*/
insert(table: string): this {
this.queryType = 'INSERT';
this.fromTable = table;
return this;
}
/**
* VALUES for INSERT
*/
values(data: Record<string, unknown>): this {
this.insertValues = data;
return this;
}
/**
* UPDATE statement
*/
update(table: string): this {
this.queryType = 'UPDATE';
this.fromTable = table;
return this;
}
/**
* SET for UPDATE
*/
set(data: Record<string, unknown>): this {
this.updateValues = data;
return this;
}
/**
* DELETE statement
*/
delete(table: string): this {
this.queryType = 'DELETE';
this.fromTable = table;
return this;
}
/**
* Build and execute the query
*/
async execute<T extends QueryResultRow = QueryResultRow>(): Promise<QueryResult<T>> {
const { sql, params } = this.build();
return await this.client.query<T>(sql, params);
}
/**
* Build the SQL query
*/
build(): { sql: string; params: unknown[] } {
const params: unknown[] = [];
let sql = '';
switch (this.queryType) {
case 'SELECT':
sql = this.buildSelectQuery(params);
break;
case 'INSERT':
sql = this.buildInsertQuery(params);
break;
case 'UPDATE':
sql = this.buildUpdateQuery(params);
break;
case 'DELETE':
sql = this.buildDeleteQuery(params);
break;
default:
throw new Error('Query type not specified');
}
return { sql, params };
}
private buildSelectQuery(params: unknown[]): string {
let sql = `SELECT ${this.selectColumns.join(', ')}`;
if (this.fromTable) {
sql += ` FROM ${this.fromTable}`;
}
// Add JOINs
for (const join of this.joins) {
sql += ` ${join.type} JOIN ${join.table} ON ${join.on}`;
}
// Add WHERE
if (this.whereConditions.length > 0) {
sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params);
}
// Add GROUP BY
if (this.groupByColumns.length > 0) {
sql += ` GROUP BY ${this.groupByColumns.join(', ')}`;
}
// Add HAVING
if (this.havingConditions.length > 0) {
sql += ' HAVING ' + this.buildWhereClause(this.havingConditions, params);
}
// Add ORDER BY
if (this.orderByConditions.length > 0) {
const orderBy = this.orderByConditions
.map(order => `${order.column} ${order.direction}`)
.join(', ');
sql += ` ORDER BY ${orderBy}`;
}
// Add LIMIT
if (this.limitCount !== null) {
sql += ` LIMIT $${params.length + 1}`;
params.push(this.limitCount);
}
// Add OFFSET
if (this.offsetCount !== null) {
sql += ` OFFSET $${params.length + 1}`;
params.push(this.offsetCount);
}
return sql;
}
private buildInsertQuery(params: unknown[]): string {
const columns = Object.keys(this.insertValues);
const placeholders = columns.map((_, i) => `$${params.length + i + 1}`);
params.push(...Object.values(this.insertValues));
return `INSERT INTO ${this.fromTable} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`;
}
private buildUpdateQuery(params: unknown[]): string {
const sets = Object.keys(this.updateValues).map((key, i) => {
return `${key} = $${params.length + i + 1}`;
});
params.push(...Object.values(this.updateValues));
let sql = `UPDATE ${this.fromTable} SET ${sets.join(', ')}`;
if (this.whereConditions.length > 0) {
sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params);
}
return sql;
}
private buildDeleteQuery(params: unknown[]): string {
let sql = `DELETE FROM ${this.fromTable}`;
if (this.whereConditions.length > 0) {
sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params);
}
return sql;
}
private buildWhereClause(conditions: WhereCondition[], params: unknown[]): string {
return conditions
.map(condition => {
if (condition.operator === 'IS NULL' || condition.operator === 'IS NOT NULL') {
return `${condition.column} ${condition.operator}`;
} else {
params.push(condition.value);
return `${condition.column} ${condition.operator} $${params.length}`;
}
})
.join(' AND ');
}
}

View file

@ -1,8 +1,5 @@
import type { QueryResult as PgQueryResult, PoolClient, QueryResultRow } from 'pg';
/**
* PostgreSQL Client Configuration
*/
export interface PostgreSQLClientConfig {
host: string;
port: number;
@ -27,13 +24,9 @@ export interface PostgreSQLClientConfig {
};
}
/**
* PostgreSQL Connection Options
*/
export interface PostgreSQLConnectionOptions {
retryAttempts?: number;
retryDelay?: number;
healthCheckInterval?: number;
}
export interface PoolMetrics {
@ -43,7 +36,6 @@ export interface PoolMetrics {
waitingRequests: number;
errors: number;
lastError?: string;
avgResponseTime?: number;
created: Date;
lastUsed?: Date;
}
@ -55,194 +47,8 @@ export interface ConnectionEvents {
onPoolCreated?: () => void | Promise<void>;
}
export interface DynamicPoolConfig {
enabled: boolean;
minSize: number;
maxSize: number;
scaleUpThreshold: number; // % of pool in use (0-100)
scaleDownThreshold: number; // % of pool idle (0-100)
scaleUpIncrement: number; // connections to add
scaleDownIncrement: number; // connections to remove
evaluationInterval: number; // ms between checks
}
/**
* Health Status Types
*/
export type PostgreSQLHealthStatus = 'healthy' | 'degraded' | 'unhealthy';
export interface PostgreSQLHealthCheck {
status: PostgreSQLHealthStatus;
timestamp: Date;
latency: number;
connections: {
active: number;
idle: number;
total: number;
};
errors?: string[];
}
export interface PostgreSQLMetrics {
queriesPerSecond: number;
averageQueryTime: number;
errorRate: number;
connectionPoolUtilization: number;
slowQueries: number;
}
/**
* Query Result Types
*/
export interface QueryResult<T extends QueryResultRow = QueryResultRow> extends PgQueryResult<T> {
executionTime?: number;
}
export type TransactionCallback<T> = (client: PoolClient) => Promise<T>;
/**
* Schema and Table Names
*/
export type SchemaNames = 'trading' | 'strategy' | 'risk' | 'audit';
export type TableNames =
| 'trades'
| 'orders'
| 'positions'
| 'portfolios'
| 'strategies'
| 'risk_limits'
| 'audit_logs'
| 'users'
| 'accounts'
| 'symbols'
| 'exchanges';
/**
* Trading Domain Types
*/
export interface Trade {
id: string;
order_id: string;
symbol: string;
side: 'buy' | 'sell';
quantity: number;
price: number;
executed_at: Date;
commission: number;
fees: number;
portfolio_id: string;
strategy_id?: string;
created_at: Date;
updated_at: Date;
}
export interface Order {
id: string;
symbol: string;
side: 'buy' | 'sell';
type: 'market' | 'limit' | 'stop' | 'stop_limit';
quantity: number;
price?: number;
stop_price?: number;
status: 'pending' | 'filled' | 'cancelled' | 'rejected';
portfolio_id: string;
strategy_id?: string;
created_at: Date;
updated_at: Date;
expires_at?: Date;
}
export interface Position {
id: string;
symbol: string;
quantity: number;
average_cost: number;
market_value: number;
unrealized_pnl: number;
realized_pnl: number;
portfolio_id: string;
created_at: Date;
updated_at: Date;
}
export interface Portfolio {
id: string;
name: string;
cash_balance: number;
total_value: number;
unrealized_pnl: number;
realized_pnl: number;
user_id: string;
created_at: Date;
updated_at: Date;
}
export interface Strategy {
id: string;
name: string;
description: string;
parameters: Record<string, unknown>;
status: 'active' | 'inactive' | 'paused';
performance_metrics: Record<string, number>;
portfolio_id: string;
created_at: Date;
updated_at: Date;
}
export interface RiskLimit {
id: string;
type: 'position_size' | 'daily_loss' | 'max_drawdown' | 'concentration';
value: number;
threshold: number;
status: 'active' | 'breached' | 'disabled';
portfolio_id?: string;
strategy_id?: string;
created_at: Date;
updated_at: Date;
}
export interface AuditLog {
id: string;
action: string;
entity_type: string;
entity_id: string;
old_values?: Record<string, unknown>;
new_values?: Record<string, unknown>;
user_id?: string;
ip_address?: string;
user_agent?: string;
timestamp: Date;
}
/**
* Query Builder Types
*/
export interface WhereCondition {
column: string;
operator:
| '='
| '!='
| '>'
| '<'
| '>='
| '<='
| 'IN'
| 'NOT IN'
| 'LIKE'
| 'ILIKE'
| 'IS NULL'
| 'IS NOT NULL';
value?: unknown;
}
export interface JoinCondition {
type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL';
table: string;
on: string;
}
export interface OrderByCondition {
column: string;
direction: 'ASC' | 'DESC';
}

View file

@ -1,213 +0,0 @@
import { beforeEach, describe, expect, it } from 'bun:test';
import {
SimplePostgresClient,
SimpleQueryBuilder,
SimpleTransactionManager,
} from './support/simple-postgres';
describe('PostgresClient', () => {
let client: SimplePostgresClient;
const config = {
host: 'localhost',
port: 5432,
database: 'test',
user: 'test',
password: 'test',
max: 10,
};
beforeEach(() => {
client = new SimplePostgresClient(config);
});
describe('query execution', () => {
it('should execute simple query', async () => {
const result = await client.query('SELECT * FROM users WHERE id = $1', [1]);
expect(result).toBeDefined();
expect(result.rows).toBeDefined();
expect(result.rowCount).toBe(0);
});
it('should handle empty results', async () => {
const result = await client.query('SELECT * FROM invalid');
expect(result.rows).toEqual([]);
expect(result.rowCount).toBe(0);
});
});
describe('convenience methods', () => {
it('should find one record', async () => {
await client.insert('users', { name: 'Test' });
const result = await client.findOne('users', { id: 1 });
expect(result).toBeDefined();
expect(result.id).toBe(1);
expect(result.name).toBe('Test');
});
it('should find multiple records', async () => {
await client.insert('users', { name: 'User 1', active: true });
await client.insert('users', { name: 'User 2', active: true });
await client.insert('users', { name: 'User 3', active: false });
const results = await client.find('users', { active: true });
expect(results).toHaveLength(2);
});
it('should insert record', async () => {
const result = await client.insert('users', { name: 'New User' });
expect(result).toBeDefined();
expect(result.id).toBe(1);
expect(result.name).toBe('New User');
});
it('should update records', async () => {
await client.insert('users', { name: 'User 1', active: false });
await client.insert('users', { name: 'User 2', active: false });
const result = await client.update('users', { active: false }, { status: 'inactive' });
expect(result).toBe(2);
});
it('should delete records', async () => {
await client.insert('users', { name: 'User 1', active: false });
await client.insert('users', { name: 'User 2', active: false });
await client.insert('users', { name: 'User 3', active: true });
const result = await client.delete('users', { active: false });
expect(result).toBe(2);
});
});
describe('health check', () => {
it('should perform health check', async () => {
const health = await client.healthCheck();
expect(health.status).toBe('healthy');
expect(health.isConnected).toBe(true);
});
it('should handle disconnection', async () => {
await client.disconnect();
// Simple implementation doesn't track connection state in health check
const health = await client.healthCheck();
expect(health.status).toBe('healthy');
});
});
describe('connection management', () => {
it('should disconnect properly', async () => {
await client.disconnect();
// Simple test - just ensure no errors
expect(true).toBe(true);
});
});
});
describe('QueryBuilder', () => {
it('should build SELECT query', () => {
const query = new SimpleQueryBuilder()
.select(['id', 'name'])
.from('users')
.where({ active: true })
.orderBy('created_at', 'DESC')
.limit(10)
.build();
expect(query.text).toContain('SELECT id, name FROM users');
expect(query.text).toContain('WHERE active = $1');
expect(query.text).toContain('ORDER BY created_at DESC');
expect(query.text).toContain('LIMIT 10');
expect(query.values).toEqual([true]);
});
it('should build INSERT query', () => {
const query = new SimpleQueryBuilder()
.insert('users', { name: 'Test', email: 'test@example.com' })
.returning('*')
.build();
expect(query.text).toContain('INSERT INTO users');
expect(query.text).toContain('(name, email)');
expect(query.text).toContain('VALUES ($1, $2)');
expect(query.text).toContain('RETURNING *');
expect(query.values).toEqual(['Test', 'test@example.com']);
});
it('should build UPDATE query', () => {
const date = new Date();
const query = new SimpleQueryBuilder()
.update('users')
.set({ name: 'Updated', modified: date })
.where({ id: 1 })
.build();
expect(query.text).toContain('UPDATE users SET');
expect(query.text).toContain('name = $1');
expect(query.text).toContain('WHERE id = $3');
expect(query.values).toHaveLength(3);
});
it('should build DELETE query', () => {
const query = new SimpleQueryBuilder().delete('users').where({ id: 1 }).build();
expect(query.text).toContain('DELETE FROM users');
expect(query.text).toContain('WHERE id = $1');
expect(query.values).toEqual([1]);
});
it('should handle joins', () => {
const query = new SimpleQueryBuilder()
.select(['u.name', 'p.title'])
.from('users u')
.join('posts p', 'u.id = p.user_id')
.where({ 'u.active': true })
.build();
expect(query.text).toContain('JOIN posts p ON u.id = p.user_id');
});
});
describe('TransactionManager', () => {
let manager: SimpleTransactionManager;
beforeEach(() => {
manager = new SimpleTransactionManager({} as any);
});
it('should execute transaction successfully', async () => {
const result = await manager.transaction(async client => {
await client.query('INSERT INTO users (name) VALUES ($1)', ['Test']);
return { success: true };
});
expect(result).toEqual({ success: true });
});
it('should rollback on error', async () => {
await expect(
manager.transaction(async _client => {
throw new Error('Transaction failed');
})
).rejects.toThrow('Transaction failed');
});
it('should handle multiple operations', async () => {
const result = await manager.transaction(async client => {
await client.query('INSERT INTO users VALUES ($1)', ['User 1']);
await client.query('INSERT INTO users VALUES ($1)', ['User 2']);
return { count: 2 };
});
expect(result).toEqual({ count: 2 });
});
});

View file

@ -1,215 +0,0 @@
/**
* Test-only in-memory PostgreSQL double. Never used by production adapters.
*/
export class SimplePostgresClient {
private tables = new Map<string, any[]>();
private connected = false;
constructor(private config: any) {}
async query(_sql: string, _params?: any[]): Promise<{ rows: any[]; rowCount: number }> {
// Simple mock implementation
return { rows: [], rowCount: 0 };
}
async findOne(table: string, where: any): Promise<any | null> {
const rows = this.tables.get(table) || [];
for (const row of rows) {
let match = true;
for (const [key, value] of Object.entries(where)) {
if (row[key] !== value) {
match = false;
break;
}
}
if (match) {
return row;
}
}
return null;
}
async find(table: string, where: any): Promise<any[]> {
const rows = this.tables.get(table) || [];
if (Object.keys(where).length === 0) {
return rows;
}
return rows.filter(row => {
for (const [key, value] of Object.entries(where)) {
if (row[key] !== value) {
return false;
}
}
return true;
});
}
async insert(table: string, data: any): Promise<any> {
const rows = this.tables.get(table) || [];
const newRow = { ...data, id: rows.length + 1 };
rows.push(newRow);
this.tables.set(table, rows);
return newRow;
}
async update(table: string, where: any, data: any): Promise<number> {
const rows = this.tables.get(table) || [];
let updated = 0;
for (const row of rows) {
let match = true;
for (const [key, value] of Object.entries(where)) {
if (row[key] !== value) {
match = false;
break;
}
}
if (match) {
Object.assign(row, data);
updated++;
}
}
return updated;
}
async delete(table: string, where: any): Promise<number> {
const rows = this.tables.get(table) || [];
const remaining = rows.filter(row => {
for (const [key, value] of Object.entries(where)) {
if (row[key] !== value) {
return true;
}
}
return false;
});
const deleted = rows.length - remaining.length;
this.tables.set(table, remaining);
return deleted;
}
async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> {
return {
status: 'healthy',
isConnected: true,
};
}
async disconnect(): Promise<void> {
this.connected = false;
}
}
export class SimpleQueryBuilder {
private parts: string[] = [];
private params: any[] = [];
select(columns: string[] | string = '*'): SimpleQueryBuilder {
const cols = Array.isArray(columns) ? columns.join(', ') : columns;
this.parts.push(`SELECT ${cols}`);
return this;
}
from(table: string): SimpleQueryBuilder {
this.parts.push(`FROM ${table}`);
return this;
}
where(conditions: any): SimpleQueryBuilder {
const whereClause = Object.entries(conditions)
.map(([key], _i) => {
this.params.push(conditions[key]);
return `${key} = $${this.params.length}`;
})
.join(' AND ');
this.parts.push(`WHERE ${whereClause}`);
return this;
}
orderBy(column: string, direction = 'ASC'): SimpleQueryBuilder {
this.parts.push(`ORDER BY ${column} ${direction}`);
return this;
}
limit(count: number): SimpleQueryBuilder {
this.parts.push(`LIMIT ${count}`);
return this;
}
insert(table: string, data: any): SimpleQueryBuilder {
const columns = Object.keys(data);
const values = Object.values(data);
this.params.push(...values);
const placeholders = columns.map((_, i) => `$${i + 1}`);
this.parts.push(
`INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`
);
return this;
}
update(table: string): SimpleQueryBuilder {
this.parts.push(`UPDATE ${table}`);
return this;
}
set(data: any): SimpleQueryBuilder {
const setClause = Object.entries(data)
.map(([key, value]) => {
this.params.push(value);
return `${key} = $${this.params.length}`;
})
.join(', ');
this.parts.push(`SET ${setClause}`);
return this;
}
delete(table: string): SimpleQueryBuilder {
this.parts.push(`DELETE FROM ${table}`);
return this;
}
returning(columns: string): SimpleQueryBuilder {
this.parts.push(`RETURNING ${columns}`);
return this;
}
join(table: string, condition: string): SimpleQueryBuilder {
this.parts.push(`JOIN ${table} ON ${condition}`);
return this;
}
build(): { text: string; values: any[] } {
return {
text: this.parts.join(' '),
values: this.params,
};
}
}
export class SimpleTransactionManager {
constructor(private pool: any) {}
async transaction<T>(fn: (client: any) => Promise<T>): Promise<T> {
const mockClient = {
query: async (_sql?: string) => ({ rows: [], rowCount: 0 }),
release: () => {},
};
await mockClient.query('BEGIN');
try {
const result = await fn(mockClient);
await mockClient.query('COMMIT');
return result;
} catch (error) {
await mockClient.query('ROLLBACK');
throw error;
} finally {
mockClient.release();
}
}
}

View file

@ -14,7 +14,6 @@
},
"dependencies": {
"@stock-bot/logger": "*",
"@stock-bot/types": "*",
"pg": "^8.11.3",
"@stock-bot/invariants": "workspace:*"
},