stock-bot/libs/data/questdb/src/client.ts

716 lines
21 KiB
TypeScript

import type { PoolConfig, QueryResultRow } from 'pg';
import { Pool } from 'pg';
import type { LoggerLike } from '@stock-bot/logger';
import { QuestDBHealthMonitor } from './health';
import { QuestDBInfluxWriter } from './influx-writer';
import {
assertIdentifier,
assertSampleInterval,
assertSelectColumn,
QuestDBQueryBuilder,
rebaseWhereCondition,
} from './query-builder';
import { QuestDBSchemaManager } from './schema';
import type {
Bar1mRow,
LatestByOptions,
QueryResult,
QuestDBClientConfig,
QuestDBConnectionOptions,
QuestDBQueryable,
TableNames,
} from './types';
const INT32_MIN = -2147483648;
const INT32_MAX = 2147483647;
const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/;
const ISO_UTC_OR_OFFSET_RE =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))$/;
const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']);
function formatInt32ListingId(listingId: number): string {
if (!Number.isInteger(listingId) || listingId < INT32_MIN || listingId > INT32_MAX) {
throw new RangeError(
`Invalid listingId: expected signed INT32 integer, received ${String(listingId)}`
);
}
return String(listingId === 0 ? 0 : listingId);
}
function parseInt32ListingSymbol(raw: unknown): number {
if (typeof raw !== 'string' || !CANONICAL_INT_RE.test(raw)) {
throw new Error(`Malformed bars_1m listing_id SYMBOL value: "${String(raw)}"`);
}
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < INT32_MIN || parsed > INT32_MAX) {
throw new RangeError(`Out-of-range bars_1m listing_id SYMBOL value: "${raw}"`);
}
return parsed;
}
function toUtcIsoString(value: Date | string, label: string): string {
if (value instanceof Date) {
if (Number.isNaN(value.getTime())) {
throw new Error(`Invalid ${label} timestamp: Date is NaN`);
}
return value.toISOString();
}
if (typeof value === 'string') {
const trimmed = value.trim();
const match = ISO_UTC_OR_OFFSET_RE.exec(trimmed);
if (!match) {
throw new Error(
`Invalid ${label} timestamp: expected ISO-8601 string with explicit UTC or offset timezone, received "${value}"`
);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hour = Number(match[4]);
const minute = Number(match[5]);
const second = Number(match[6]);
const frac = match[7];
const tz = match[8];
const baseUtcMs = Date.UTC(year, month - 1, day, hour, minute, second);
const check = new Date(baseUtcMs);
if (
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day ||
check.getUTCHours() !== hour ||
check.getUTCMinutes() !== minute ||
check.getUTCSeconds() !== second
) {
throw new Error(`Invalid ${label} timestamp calendar date/time: "${value}"`);
}
if (tz === 'Z') {
return trimmed;
}
const sign = match[9] === '+' ? 1 : -1;
const offsetHours = Number(match[10]);
const offsetMinutes = Number(match[11]);
if (offsetHours > 23 || offsetMinutes > 59) {
throw new Error(`Invalid ${label} timestamp timezone offset: "${value}"`);
}
const adjustedUtcMs = baseUtcMs - sign * (offsetHours * 60 + offsetMinutes) * 60_000;
const utcDate = new Date(adjustedUtcMs);
const isoSeconds = utcDate.toISOString().slice(0, 19);
return frac ? `${isoSeconds}.${frac}Z` : `${isoSeconds}Z`;
}
throw new Error(`Invalid ${label} timestamp: "${String(value)}"`);
}
function parseUtcEpochMicros(raw: unknown, field: string): bigint {
if (typeof raw === 'bigint') {
return raw;
}
if (typeof raw === 'string' && CANONICAL_INT_RE.test(raw)) {
return BigInt(raw);
}
if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
return BigInt(raw);
}
throw new Error(`Invalid bars_1m ${field} UTC epoch microseconds: "${String(raw)}"`);
}
function parseRequiredFiniteNumber(raw: unknown, field: string): number {
const value =
typeof raw === 'number'
? raw
: typeof raw === 'string' && raw.trim().length > 0
? Number(raw)
: Number.NaN;
if (!Number.isFinite(value)) {
throw new Error(`Invalid bars_1m ${field} value: "${String(raw)}"`);
}
return value;
}
function parseNullableFiniteNumber(raw: unknown, field: string): number | null {
if (raw === null || raw === undefined) {
return null;
}
return parseRequiredFiniteNumber(raw, field);
}
function parseNullableString(raw: unknown, field: string): string | null {
if (raw === null || raw === undefined) {
return null;
}
if (typeof raw === 'string') {
return raw;
}
throw new Error(`Invalid bars_1m ${field} value: expected string or null`);
}
/**
* Read 1-minute bars for a single listing over `[from, to)` ordered by `ts ASC` from `bars_1m`.
*
* Binds `listingId` as its canonical decimal string (`SYMBOL`) and converts returned `listing_id`
* values back to signed `INT32` numbers at the boundary (`design/DATA-CONTRACTS.md` §3.B).
*
* Storage-layer read: preserves `known_at` on each row without applying replay cutoffs.
* Research callers (`MarketDataStore`) remain responsible for as-of availability and Vault fencing.
*/
export async function readBars1m(
client: QuestDBQueryable,
listingId: number,
from: Date | string,
to: Date | string
): Promise<Bar1mRow[]> {
const listingIdParam = formatInt32ListingId(listingId);
const fromIso = toUtcIsoString(from, 'from');
const toIso = toUtcIsoString(to, 'to');
const sql =
'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' +
'FROM bars_1m ' +
'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' +
'ORDER BY ts ASC';
const result = await client.query<Record<string, unknown>>(sql, [listingIdParam, fromIso, toIso]);
return result.rows.map(row => ({
listing_id: parseInt32ListingSymbol(row.listing_id),
open: parseRequiredFiniteNumber(row.open, 'open'),
high: parseRequiredFiniteNumber(row.high, 'high'),
low: parseRequiredFiniteNumber(row.low, 'low'),
close: parseRequiredFiniteNumber(row.close, 'close'),
volume: parseRequiredFiniteNumber(row.volume, 'volume'),
vwap: parseNullableFiniteNumber(row.vwap, 'vwap'),
session: parseNullableString(row.session, 'session'),
source: parseNullableString(row.source, 'source'),
known_at: parseUtcEpochMicros(row.known_at_us, 'known_at'),
ts: parseUtcEpochMicros(row.ts_us, 'ts'),
}));
}
/**
* QuestDB Client for Stock Bot
*
* Provides high-performance time-series data access with support for
* multiple protocols (HTTP, PostgreSQL, InfluxDB Line Protocol).
*/
export class QuestDBClient {
private pgPool: Pool | null = null;
private readonly config: QuestDBClientConfig;
private readonly options: QuestDBConnectionOptions;
private readonly logger: LoggerLike;
private readonly healthMonitor: QuestDBHealthMonitor;
private readonly influxWriter: QuestDBInfluxWriter;
private readonly schemaManager: QuestDBSchemaManager;
private isConnected = false;
constructor(
config: QuestDBClientConfig,
logger?: LoggerLike,
options?: QuestDBConnectionOptions
) {
this.config = config;
this.logger = logger || console;
this.options = {
protocol: 'pg',
retryAttempts: 3,
retryDelay: 1000,
healthCheckInterval: 30000,
...options,
};
// Debug: log the received config
this.logger.debug('QuestDB client created with config:', {
...config,
user: config.user || '[NOT PROVIDED]',
password: config.password ? '[PROVIDED]' : '[NOT PROVIDED]',
});
this.healthMonitor = new QuestDBHealthMonitor(this);
this.influxWriter = new QuestDBInfluxWriter(this);
this.schemaManager = new QuestDBSchemaManager(this);
}
/**
* Connect to QuestDB
*/
async connect(): Promise<void> {
if (this.isConnected) {
return;
}
let lastError: Error | null = null;
for (let attempt = 1; attempt <= (this.options.retryAttempts ?? 3); attempt++) {
try {
this.logger.info(
`Connecting to QuestDB (attempt ${attempt}/${this.options.retryAttempts})...`
);
// Connect via PostgreSQL wire protocol
this.pgPool = new Pool(this.buildPgPoolConfig());
// Test the connection
const client = await this.pgPool.connect();
await client.query('SELECT 1');
client.release();
this.isConnected = true;
this.logger.info('Successfully connected to QuestDB');
// Initialize schema
await this.schemaManager.initializeDatabase();
// Start health monitoring
this.healthMonitor.startMonitoring();
return;
} catch (error) {
lastError = error as Error;
this.logger.warn(`QuestDB connection attempt ${attempt} failed:`, error as Error);
if (this.pgPool) {
await this.pgPool.end();
this.pgPool = null;
}
if (attempt < (this.options.retryAttempts ?? 3)) {
await this.delay((this.options.retryDelay ?? 1000) * attempt);
}
}
}
throw new Error(
`Failed to connect to QuestDB after ${this.options.retryAttempts} attempts: ${lastError?.message}`
);
}
/**
* Disconnect from QuestDB
*/
async disconnect(): Promise<void> {
if (!this.isConnected) {
return;
}
try {
this.healthMonitor.stopMonitoring();
if (this.pgPool) {
await this.pgPool.end();
this.pgPool = null;
}
this.isConnected = false;
this.logger.info('Disconnected from QuestDB');
} catch (error) {
this.logger.error('Error disconnecting from QuestDB:', error);
throw error;
}
}
/**
* Execute a SQL query
*/
async query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>> {
if (!this.pgPool) {
throw new Error('QuestDB client not connected');
}
const startTime = Date.now();
try {
const result = await this.pgPool.query(sql, params);
const executionTime = Date.now() - startTime;
this.logger.debug(`Query executed in ${executionTime}ms`, {
query: sql.substring(0, 100),
rowCount: result.rowCount,
});
return {
rows: result.rows,
rowCount: result.rowCount || 0,
executionTime,
metadata: {
columns:
result.fields?.map(field => ({
name: field.name,
type: this.mapDataType(field.dataTypeID),
})) || [],
},
};
} catch (error) {
const executionTime = Date.now() - startTime;
this.logger.error(`Query failed after ${executionTime}ms:`, {
error: (error as Error).message,
query: sql,
params,
});
throw error;
}
}
/**
* Write OHLCV data using InfluxDB Line Protocol
*/
async writeOHLCV(
symbol: string,
exchange: string,
data: Array<{
timestamp: Date;
open: number;
high: number;
low: number;
close: number;
volume: number;
}>
): Promise<void> {
return await this.influxWriter.writeOHLCV(symbol, exchange, data);
}
/**
* Write market analytics data
*/
async writeMarketAnalytics(
symbol: string,
exchange: string,
analytics: {
timestamp: Date;
rsi?: number;
macd?: number;
signal?: number;
histogram?: number;
bollinger_upper?: number;
bollinger_lower?: number;
volume_sma?: number;
}
): Promise<void> {
return await this.influxWriter.writeMarketAnalytics(symbol, exchange, analytics);
}
/**
* Get a query builder instance
*/
queryBuilder(): QuestDBQueryBuilder {
return new QuestDBQueryBuilder(this);
}
/**
* Create a SELECT query builder
*/
select(...columns: string[]): QuestDBQueryBuilder {
return this.queryBuilder().select(...columns);
}
/**
* Create an aggregation query builder
*/
aggregate(table: TableNames): QuestDBQueryBuilder {
return this.queryBuilder().from(table);
}
/**
* Execute a time-series specific query with SAMPLE BY.
* `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`.
*/
async sampleBy<T = QueryResultRow>(
table: TableNames | string,
columns: string[],
interval: string,
timeColumn: string = 'timestamp',
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const validTable = assertIdentifier(table, 'table name');
if (columns.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
const validColumns = columns.map(col => assertSelectColumn(col));
const validInterval = assertSampleInterval(interval);
assertIdentifier(timeColumn, 'timestamp column');
let whereClause = '';
const boundParams = params ? [...params] : [];
if (where !== undefined) {
const validatedWhere = rebaseWhereCondition(where, boundParams, 0);
whereClause = `WHERE ${validatedWhere}`;
} else if (boundParams.length > 0) {
throw new Error('params provided to sampleBy without a where clause');
}
const sql = [
`SELECT ${validColumns.join(', ')}`,
`FROM ${validTable}`,
whereClause,
`SAMPLE BY ${validInterval}`,
'ALIGN TO CALENDAR',
]
.filter(Boolean)
.join(' ');
return await this.query<T>(sql, boundParams.length > 0 ? boundParams : undefined);
}
/**
* Get latest rows per partition key using QuestDB 10.2.0 `LATEST ON`.
* Defaults to `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` otherwise.
* `options.where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `options.params`.
*/
async latestBy<T = QueryResultRow>(
table: TableNames | string,
columns: string | string[] = '*',
keyColumns: string | string[] = 'symbol',
options?: LatestByOptions
): Promise<QueryResult<T>> {
const cols = Array.isArray(columns) ? columns : [columns];
if (cols.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
const keys = Array.isArray(keyColumns) ? keyColumns : [keyColumns];
const builder = this.queryBuilder().select(...cols).from(table);
if (options?.where !== undefined) {
builder.where(options.where, options.params);
} else if (options?.params && options.params.length > 0) {
throw new Error('params provided to latestBy without a where clause');
}
if (options?.timestampColumn !== undefined) {
builder.latestOn(options.timestampColumn, ...keys);
} else {
builder.latestBy(...keys);
}
return await builder.execute<T>();
}
/**
* Execute ASOF JOIN for time-series correlation.
* `joinCondition` and `where` are treated as trusted SQL fragments.
*/
async asofJoin<T = QueryResultRow>(
leftTable: TableNames | string,
rightTable: TableNames | string,
joinCondition: string,
columns?: string[],
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const validLeft = assertIdentifier(leftTable, 'left table name');
const validRight = assertIdentifier(rightTable, 'right table name');
if (typeof joinCondition !== 'string' || joinCondition.trim().length === 0) {
throw new Error('ASOF JOIN condition must be a non-empty SQL fragment');
}
let columnsStr = '*';
if (columns !== undefined) {
if (columns.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
columnsStr = columns.map(col => assertSelectColumn(col)).join(', ');
}
let whereClause = '';
const boundParams = params ? [...params] : [];
if (where !== undefined) {
const validatedWhere = rebaseWhereCondition(where, boundParams, 0);
whereClause = `WHERE ${validatedWhere}`;
} else if (boundParams.length > 0) {
throw new Error('params provided to asofJoin without a where clause');
}
const sql = [
`SELECT ${columnsStr}`,
`FROM ${validLeft}`,
`ASOF JOIN ${validRight} ON ${joinCondition}`,
whereClause,
]
.filter(Boolean)
.join(' ');
return await this.query<T>(sql, boundParams.length > 0 ? boundParams : undefined);
}
/**
* Get database statistics
*/
async getStats(): Promise<QueryResultRow[]> {
const result = await this.query(`
SELECT
table_name,
row_count,
partition_count,
size_bytes
FROM tables()
WHERE table_name NOT LIKE 'sys.%'
ORDER BY row_count DESC
`);
return result.rows;
}
/**
* Get table information
*/
async getTableInfo(tableName: string): Promise<QueryResultRow[]> {
const result = await this.query('SELECT * FROM table_columns($1)', [tableName]);
return result.rows;
}
/**
* Check if PostgreSQL pool is healthy
*/
isPgPoolHealthy(): boolean {
return this.pgPool !== null && !this.pgPool.ended;
}
/**
* Get HTTP endpoint URL
*/
getHttpUrl(): string {
const protocol = this.config.tls?.enabled ? 'https' : 'http';
return `${protocol}://${this.config.host}:${this.config.httpPort}`;
}
/**
* Get InfluxDB endpoint URL
*/
getInfluxUrl(): string {
const protocol = this.config.tls?.enabled ? 'https' : 'http';
return `${protocol}://${this.config.host}:${this.config.influxPort}`;
}
/**
* Get health monitor instance
*/
getHealthMonitor(): QuestDBHealthMonitor {
return this.healthMonitor;
}
/**
* Get schema manager instance
*/
getSchemaManager(): QuestDBSchemaManager {
return this.schemaManager;
}
/**
* Get InfluxDB writer instance
*/
getInfluxWriter(): QuestDBInfluxWriter {
return this.influxWriter;
}
/**
* Optimize table by rebuilding partitions
*/
async optimizeTable(tableName: string): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
await this.query(`VACUUM TABLE ${validTable}`);
this.logger.debug(`Optimized table: ${validTable}`);
}
/**
* Create a table with time-series optimizations
*/
async createTable(
tableName: string,
columns: string,
partitionBy: string = 'DAY',
timestampColumn: string = 'timestamp'
): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
const validTimestamp = assertIdentifier(timestampColumn, 'timestamp column');
if (!ALLOWED_PARTITIONS.has(partitionBy)) {
throw new Error(`Invalid PARTITION BY value: "${String(partitionBy)}"`);
}
const sql = `
CREATE TABLE IF NOT EXISTS ${validTable} (
${columns}
) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy}
`;
await this.query(sql);
this.logger.info(`Created table: ${validTable}`);
}
/**
* Check if client is connected
*/
get connected(): boolean {
return this.isConnected && !!this.pgPool;
}
/**
* Get the PostgreSQL connection pool
*/
get connectionPool(): Pool | null {
return this.pgPool;
}
/**
* Get configuration
*/
get configuration(): QuestDBClientConfig {
return { ...this.config };
}
private buildPgPoolConfig(): PoolConfig {
const config: PoolConfig = {
host: this.config.host,
port: this.config.pgPort,
database: this.config.database,
connectionTimeoutMillis: this.config.timeouts?.connection,
query_timeout: this.config.timeouts?.request,
ssl: this.config.tls?.enabled
? {
rejectUnauthorized: this.config.tls.verifyServerCert,
}
: false,
min: 2,
max: 10,
};
// Only add user/password if they are provided
if (this.config.user) {
this.logger.debug('Adding user to QuestDB pool config', { user: this.config.user });
config.user = this.config.user;
} else {
this.logger.debug('No user provided for QuestDB connection');
}
if (this.config.password) {
this.logger.debug('Adding password to QuestDB pool config');
config.password = this.config.password;
} else {
this.logger.debug('No password provided for QuestDB connection');
}
this.logger.debug('Final QuestDB pool config:', {
...config,
password: config.password ? '[REDACTED]' : undefined,
});
return config;
}
private mapDataType(typeId: number): string {
// Map PostgreSQL type IDs to QuestDB types
const typeMap: Record<number, string> = {
16: 'BOOLEAN',
20: 'LONG',
21: 'INT',
23: 'INT',
25: 'STRING',
700: 'FLOAT',
701: 'DOUBLE',
1043: 'STRING',
1082: 'DATE',
1114: 'TIMESTAMP',
1184: 'TIMESTAMP',
};
return typeMap[typeId] || 'STRING';
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}