- 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
244 lines
7 KiB
TypeScript
244 lines
7 KiB
TypeScript
import type { PoolConfig, QueryResultRow } from 'pg';
|
|
import { Pool } from 'pg';
|
|
import type { LoggerLike } from '@stock-bot/logger';
|
|
import { PostgreSQLTransactionManager } from './transactions';
|
|
import type {
|
|
ConnectionEvents,
|
|
PoolMetrics,
|
|
PostgreSQLClientConfig,
|
|
PostgreSQLConnectionOptions,
|
|
QueryResult,
|
|
TransactionCallback,
|
|
} from './types';
|
|
|
|
export class PostgreSQLClient {
|
|
private pool: Pool | null = null;
|
|
private readonly config: PostgreSQLClientConfig;
|
|
private readonly options: PostgreSQLConnectionOptions;
|
|
private readonly logger: LoggerLike;
|
|
private readonly transactionManager: PostgreSQLTransactionManager;
|
|
private isConnected = false;
|
|
private readonly metrics: PoolMetrics;
|
|
private readonly events?: ConnectionEvents;
|
|
|
|
constructor(
|
|
config: PostgreSQLClientConfig,
|
|
logger?: LoggerLike,
|
|
options?: PostgreSQLConnectionOptions,
|
|
events?: ConnectionEvents
|
|
) {
|
|
this.config = config;
|
|
this.options = {
|
|
retryAttempts: 3,
|
|
retryDelay: 1000,
|
|
...options,
|
|
};
|
|
this.events = events;
|
|
this.logger = logger || console;
|
|
this.transactionManager = new PostgreSQLTransactionManager(this);
|
|
this.metrics = {
|
|
totalConnections: 0,
|
|
activeConnections: 0,
|
|
idleConnections: 0,
|
|
waitingRequests: 0,
|
|
errors: 0,
|
|
created: new Date(),
|
|
};
|
|
}
|
|
|
|
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 <= attempts; attempt++) {
|
|
try {
|
|
this.logger.info(`Connecting to PostgreSQL (attempt ${attempt}/${attempts})...`);
|
|
|
|
this.pool = new Pool(this.buildPoolConfig());
|
|
|
|
const client = await this.pool.connect();
|
|
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;
|
|
|
|
if (this.events?.onConnect) {
|
|
await Promise.resolve(this.events.onConnect());
|
|
}
|
|
if (this.events?.onPoolCreated) {
|
|
await Promise.resolve(this.events.onPoolCreated());
|
|
}
|
|
|
|
this.setupErrorHandlers();
|
|
this.logger.info('Successfully connected to PostgreSQL', {
|
|
poolSize: this.metrics.totalConnections,
|
|
});
|
|
return;
|
|
} catch (error) {
|
|
lastError = error as Error;
|
|
this.metrics.errors++;
|
|
this.metrics.lastError = lastError.message;
|
|
|
|
if (this.events?.onError) {
|
|
await Promise.resolve(this.events.onError(lastError));
|
|
}
|
|
|
|
this.logger.error(`PostgreSQL connection attempt ${attempt} failed:`, error);
|
|
|
|
if (this.pool) {
|
|
await this.pool.end().catch(() => {});
|
|
this.pool = null;
|
|
}
|
|
|
|
if (attempt < attempts) {
|
|
await new Promise(resolve => setTimeout(resolve, (this.options.retryDelay ?? 1000) * attempt));
|
|
}
|
|
}
|
|
}
|
|
|
|
throw new Error(
|
|
`Failed to connect to PostgreSQL after ${attempts} attempts: ${lastError?.message}`
|
|
);
|
|
}
|
|
|
|
async disconnect(): Promise<void> {
|
|
if (!this.pool) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await this.pool.end();
|
|
this.isConnected = false;
|
|
this.pool = null;
|
|
|
|
if (this.events?.onDisconnect) {
|
|
await Promise.resolve(this.events.onDisconnect());
|
|
}
|
|
|
|
this.logger.info('Disconnected from PostgreSQL');
|
|
} catch (error) {
|
|
this.logger.error('Error disconnecting from PostgreSQL:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async query<T extends QueryResultRow = QueryResultRow>(
|
|
text: string,
|
|
params?: unknown[]
|
|
): Promise<QueryResult<T>> {
|
|
if (!this.pool) {
|
|
throw new Error('PostgreSQL client not connected');
|
|
}
|
|
|
|
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,
|
|
} as QueryResult<T>;
|
|
} catch (error) {
|
|
const executionTime = Date.now() - startTime;
|
|
this.logger.error(`Query failed after ${executionTime}ms:`, {
|
|
error,
|
|
query: text,
|
|
params,
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async transaction<T>(callback: TransactionCallback<T>): Promise<T> {
|
|
return await this.transactionManager.execute(callback);
|
|
}
|
|
|
|
async getStats(): Promise<QueryResultRow> {
|
|
const result = await this.query(`
|
|
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,
|
|
pg_size_pretty(pg_database_size(current_database())) as database_size
|
|
`);
|
|
return result.rows[0] ?? {};
|
|
}
|
|
|
|
get connected(): boolean {
|
|
return this.isConnected && !!this.pool;
|
|
}
|
|
|
|
get connectionPool(): Pool | null {
|
|
return this.pool;
|
|
}
|
|
|
|
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,
|
|
hasPassword: Boolean(this.config.password),
|
|
});
|
|
|
|
return {
|
|
host: this.config.host,
|
|
port: this.config.port,
|
|
database: this.config.database,
|
|
user: this.config.username,
|
|
password:
|
|
typeof this.config.password === 'string'
|
|
? this.config.password
|
|
: String(this.config.password || ''),
|
|
min: this.config.poolSettings?.min,
|
|
max: this.config.poolSettings?.max,
|
|
idleTimeoutMillis: this.config.poolSettings?.idleTimeoutMillis,
|
|
connectionTimeoutMillis: this.config.timeouts?.connection,
|
|
query_timeout: this.config.timeouts?.query,
|
|
statement_timeout: this.config.timeouts?.statement,
|
|
lock_timeout: this.config.timeouts?.lock,
|
|
idle_in_transaction_session_timeout: this.config.timeouts?.idleInTransaction,
|
|
ssl: this.config.ssl?.enabled
|
|
? {
|
|
rejectUnauthorized: this.config.ssl.rejectUnauthorized,
|
|
}
|
|
: false,
|
|
};
|
|
}
|
|
|
|
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);
|
|
});
|
|
}
|
|
}
|