refactor(data): normalize provider symbols and remove dead scaffolding (CL34)

This commit is contained in:
Boki 2026-10-28 13:56:31 -04:00
parent 5c9e32d0ef
commit e2292e4883
11 changed files with 287 additions and 581 deletions

View file

@ -1,6 +1,4 @@
export * from './config';
export * from './session-manager';
export * from './session-manager-redis';
export * from './session-manager-wrapper';
export * from './types';
export * from './operation-provider';
export * from './config';
export * from './session-manager';
export * from './types';
export * from './operation-provider';

View file

@ -1,381 +0,0 @@
/**
* QM Session Manager - Redis-based implementation for cluster support
* Uses Redis as the single source of truth for session management
*/
import type { CacheProvider } from '@stock-bot/cache';
import type { Logger } from '@stock-bot/services';
import { QM_SESSION_IDS, SESSION_CONFIG } from './config';
import type { QMSession } from './types';
export class QMSessionManagerRedis {
private static instance: QMSessionManagerRedis | null = null;
private cacheProvider: CacheProvider | null = null;
private logger: Logger | null = null;
private readonly SESSION_TTL = 86400; // 24 hours
private constructor() {}
static getInstance(): QMSessionManagerRedis {
if (!QMSessionManagerRedis.instance) {
QMSessionManagerRedis.instance = new QMSessionManagerRedis();
}
return QMSessionManagerRedis.instance;
}
/**
* Initialize with cache provider and logger
*/
initialize(cache?: CacheProvider, logger?: Logger): void {
if (cache) {
this.cacheProvider = cache;
}
if (logger) {
this.logger = logger;
this.logger.trace('Redis-based SessionManager initialized');
}
}
/**
* Get a random valid session for the given session ID
*/
async getSession(sessionId: string): Promise<QMSession | null> {
if (!this.cacheProvider) {
this.logger?.error('No cache provider available');
return null;
}
try {
// Get all session UUIDs for this sessionId
const sessionUuids = await this.getSessionUuids(sessionId);
if (sessionUuids.length === 0) {
this.logger?.debug(`No sessions found for ${sessionId}`);
return null;
}
// Shuffle and try to find a valid session
const shuffled = [...sessionUuids].sort(() => Math.random() - 0.5);
for (const uuid of shuffled) {
const session = await this.getSessionByUuid(sessionId, uuid);
if (session && (session.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS) {
this.logger?.trace(`Selected session`, {
uuid: session.uuid,
failedCalls: session.failedCalls,
successfulCalls: session.successfulCalls,
});
return session;
}
}
this.logger?.warn(`No valid sessions found for ${sessionId}`);
return null;
} catch (error) {
this.logger?.error('Failed to get session', { error, sessionId });
return null;
}
}
/**
* Get a specific session by UUID
*/
async getSessionByUuid(sessionId: string, uuid: string): Promise<QMSession | null> {
if (!this.cacheProvider) {
return null;
}
const sessionKey = this.getSessionKey(sessionId, uuid);
try {
const session = await this.cacheProvider.get<QMSession>(sessionKey);
if (session) {
// Ensure dates are Date objects
session.lastUsed = new Date(session.lastUsed);
session.createdAt = new Date(session.createdAt);
}
return session;
} catch (error) {
this.logger?.error('Failed to get session by UUID', { error, sessionId, uuid });
return null;
}
}
/**
* Add a session
*/
async addSession(sessionId: string, session: QMSession): Promise<void> {
if (!this.cacheProvider) {
throw new Error('No cache provider available');
}
const sessionKey = this.getSessionKey(sessionId, session.uuid);
const listKey = this.getSessionListKey(sessionId);
try {
// Store the session data
await this.cacheProvider.set(sessionKey, session, this.SESSION_TTL);
// Add UUID to the session list (using SET to simulate SADD)
const uuids = await this.getSessionUuids(sessionId);
if (!uuids.includes(session.uuid)) {
uuids.push(session.uuid);
await this.cacheProvider.set(listKey, uuids, this.SESSION_TTL);
}
this.logger?.debug(`Added session ${session.uuid} to ${sessionId}`);
} catch (error) {
this.logger?.error('Failed to add session', { error, sessionId, uuid: session.uuid });
throw error;
}
}
/**
* Remove a session
*/
async removeSession(sessionId: string, uuid: string): Promise<void> {
if (!this.cacheProvider) {
return;
}
const sessionKey = this.getSessionKey(sessionId, uuid);
const listKey = this.getSessionListKey(sessionId);
try {
// Remove session data
await this.cacheProvider.del(sessionKey);
// Remove UUID from list
const uuids = await this.getSessionUuids(sessionId);
const filtered = uuids.filter(u => u !== uuid);
if (filtered.length !== uuids.length) {
await this.cacheProvider.set(listKey, filtered, this.SESSION_TTL);
}
this.logger?.debug(`Removed session ${uuid} from ${sessionId}`);
} catch (error) {
this.logger?.error('Failed to remove session', { error, sessionId, uuid });
}
}
/**
* Get all sessions for a session ID
*/
async getSessions(sessionId: string): Promise<QMSession[]> {
if (!this.cacheProvider) {
return [];
}
const uuids = await this.getSessionUuids(sessionId);
const sessions: QMSession[] = [];
for (const uuid of uuids) {
const session = await this.getSessionByUuid(sessionId, uuid);
if (session) {
sessions.push(session);
}
}
return sessions;
}
/**
* Get session count
*/
async getSessionCount(sessionId?: string): Promise<number> {
if (!this.cacheProvider) {
return 0;
}
if (sessionId) {
const uuids = await this.getSessionUuids(sessionId);
return uuids.length;
}
// Count all sessions
let total = 0;
for (const sid of Object.values(QM_SESSION_IDS)) {
const uuids = await this.getSessionUuids(sid);
total += uuids.length;
}
return total;
}
/**
* Clean up failed sessions
*/
async cleanupFailedSessions(): Promise<number> {
if (!this.cacheProvider) {
return 0;
}
let removedCount = 0;
for (const sessionId of Object.values(QM_SESSION_IDS)) {
const sessions = await this.getSessions(sessionId);
for (const session of sessions) {
if (session.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS) {
await this.removeSession(sessionId, session.uuid);
removedCount++;
}
}
}
this.logger?.info(`Cleaned up ${removedCount} failed sessions`);
return removedCount;
}
/**
* Check if more sessions are needed
*/
async needsMoreSessions(sessionId: string): Promise<boolean> {
const sessions = await this.getSessions(sessionId);
const validSessions = sessions.filter(
s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS
);
return validSessions.length < SESSION_CONFIG.MAX_SESSIONS;
}
/**
* Get statistics
*/
async getStats(): Promise<Record<string, { total: number; valid: number; failed: number }>> {
const stats: Record<string, { total: number; valid: number; failed: number }> = {};
for (const [_sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) {
const sessions = await this.getSessions(sessionId);
const validSessions = sessions.filter(
s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS
);
const failedSessions = sessions.filter(s => s.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS);
stats[sessionId] = {
total: sessions.length,
valid: validSessions.length,
failed: failedSessions.length,
};
}
return stats;
}
/**
* Increment failed calls for a session
*/
async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise<void> {
const session = await this.getSessionByUuid(sessionId, sessionUuid);
if (session) {
session.failedCalls = (session.failedCalls || 0) + 1;
session.lastUsed = new Date();
const sessionKey = this.getSessionKey(sessionId, sessionUuid);
await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL);
this.logger?.debug(`Incremented failed calls for session`, {
sessionUuid,
failedCalls: session.failedCalls,
sessionId,
});
} else {
this.logger?.warn(`Session not found`, { sessionUuid, sessionId });
}
}
/**
* Increment successful calls for a session
*/
async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise<void> {
const session = await this.getSessionByUuid(sessionId, sessionUuid);
if (session) {
session.successfulCalls = (session.successfulCalls || 0) + 1;
session.lastUsed = new Date();
const sessionKey = this.getSessionKey(sessionId, sessionUuid);
await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL);
this.logger?.debug(`Incremented successful calls for session`, {
sessionUuid,
successfulCalls: session.successfulCalls,
sessionId,
});
} else {
this.logger?.warn(`Session not found`, { sessionUuid, sessionId });
}
}
/**
* Helper: Get session UUIDs from cache
*/
private async getSessionUuids(sessionId: string): Promise<string[]> {
if (!this.cacheProvider) {
return [];
}
const listKey = this.getSessionListKey(sessionId);
try {
const uuids = await this.cacheProvider.get<string[]>(listKey);
return uuids || [];
} catch (error) {
this.logger?.error('Failed to get session UUIDs', { error, sessionId });
return [];
}
}
/**
* Helper: Generate cache keys
*/
private getSessionKey(sessionId: string, uuid: string): string {
return `qm:sessions:${sessionId}:session:${uuid}`;
}
private getSessionListKey(sessionId: string): string {
return `qm:sessions:${sessionId}:list`;
}
/**
* Migrate from old session manager (for backward compatibility)
*/
async migrateFromOldFormat(): Promise<void> {
if (!this.cacheProvider) {
return;
}
this.logger?.info('Starting migration from old session format');
for (const [sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) {
const oldListKey = `qm:sessions:${sessionType.toLowerCase()}:list`;
const oldSessionIds = await this.cacheProvider.get<string[]>(oldListKey);
if (oldSessionIds && Array.isArray(oldSessionIds)) {
this.logger?.info(`Migrating ${oldSessionIds.length} sessions for ${sessionType}`);
for (const id of oldSessionIds) {
const oldSessionKey = `qm:sessions:${sessionType.toLowerCase()}:${id}`;
const oldSession =
await this.cacheProvider.get<import('./types').CachedSession>(oldSessionKey);
if (oldSession && oldSession.uuid) {
const session: QMSession = {
uuid: oldSession.uuid,
proxy: oldSession.proxy,
headers: oldSession.headers,
successfulCalls: oldSession.successfulCalls || 0,
failedCalls: oldSession.failedCalls || 0,
lastUsed: new Date(oldSession.lastUsed),
createdAt: new Date(oldSession.createdAt || new Date()),
};
await this.addSession(sessionId, session);
await this.cacheProvider.del(oldSessionKey);
}
}
await this.cacheProvider.del(oldListKey);
}
}
this.logger?.info('Migration completed');
}
}

View file

@ -1,128 +0,0 @@
/**
* Session Manager Wrapper - Provides a unified interface that can switch between implementations
*/
import type { CacheProvider } from '@stock-bot/cache';
import type { Logger } from '@stock-bot/services';
import { QMSessionManager } from './session-manager';
import { QMSessionManagerRedis } from './session-manager-redis';
import type { QMSession } from './types';
/**
* Wrapper that delegates to either in-memory or Redis-based implementation
* Set REDIS_SESSION_MANAGER=true to use Redis implementation
*/
export class SessionManagerWrapper {
private implementation: QMSessionManager | QMSessionManagerRedis;
private static instance: SessionManagerWrapper | null = null;
private constructor() {
// Use Redis implementation if env var is set or if in production
const useRedis =
process.env.REDIS_SESSION_MANAGER === 'true' || process.env.NODE_ENV === 'production';
if (useRedis) {
this.implementation = QMSessionManagerRedis.getInstance();
} else {
this.implementation = QMSessionManager.getInstance();
}
}
static getInstance(): SessionManagerWrapper {
if (!SessionManagerWrapper.instance) {
SessionManagerWrapper.instance = new SessionManagerWrapper();
}
return SessionManagerWrapper.instance;
}
/**
* Reset instance (for testing)
*/
static resetInstance(): void {
SessionManagerWrapper.instance = null;
}
/**
* Initialize with cache provider and logger
*/
initialize(cache?: CacheProvider, logger?: Logger): void {
this.implementation.initialize(cache, logger);
}
/**
* Get the implementation type
*/
getImplementationType(): string {
return this.implementation instanceof QMSessionManagerRedis ? 'redis' : 'memory';
}
// Delegate all methods to the implementation
async getSession(sessionId: string): Promise<QMSession | null> {
return this.implementation.getSession(sessionId);
}
async getSessionByUuid(sessionId: string, uuid: string): Promise<QMSession | null> {
if (this.implementation instanceof QMSessionManagerRedis) {
return this.implementation.getSessionByUuid(sessionId, uuid);
} else {
return this.implementation.getSessionByUuid(sessionId, uuid);
}
}
async addSession(sessionId: string, session: QMSession): Promise<void> {
return this.implementation.addSession(sessionId, session);
}
async getSessions(sessionId: string): Promise<QMSession[]> {
if (this.implementation instanceof QMSessionManagerRedis) {
return this.implementation.getSessions(sessionId);
} else {
return this.implementation.getSessions(sessionId);
}
}
async getSessionCount(sessionId?: string): Promise<number> {
if (this.implementation instanceof QMSessionManagerRedis) {
return this.implementation.getSessionCount(sessionId);
} else {
return this.implementation.getSessionCount(sessionId ?? '');
}
}
async cleanupFailedSessions(): Promise<number> {
return this.implementation.cleanupFailedSessions();
}
async needsMoreSessions(sessionId: string): Promise<boolean> {
return this.implementation.needsMoreSessions(sessionId);
}
async getStats(): Promise<Record<string, { total: number; valid: number; failed: number }>> {
return this.implementation.getStats();
}
async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise<void> {
return this.implementation.incrementFailedCalls(sessionId, sessionUuid);
}
async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise<void> {
return this.implementation.incrementSuccessfulCalls(sessionId, sessionUuid);
}
// Additional methods for memory implementation
async isAtCapacity(sessionId: string): Promise<boolean> {
if (this.implementation instanceof QMSessionManager) {
return this.implementation.isAtCapacity(sessionId);
}
// For Redis, we'd need to implement this async
throw new Error('isAtCapacity not available for Redis implementation');
}
// Migration helper
async migrateToRedis(): Promise<void> {
if (this.implementation instanceof QMSessionManagerRedis) {
return this.implementation.migrateFromOldFormat();
}
throw new Error('Migration only available for Redis implementation');
}
}

View file

@ -1,34 +0,0 @@
/**
* Service Container Setup for Data Pipeline
* Configures dependency injection for the data pipeline service
*/
import type { UnifiedAppConfig } from '@stock-bot/config';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('data-pipeline-container');
/**
* Configure the service container for data pipeline workloads
*/
export function setupServiceContainer(
config: UnifiedAppConfig,
container: IServiceContainer
): IServiceContainer {
logger.info('Configuring data pipeline service container...');
// Data pipeline specific configuration
// This service does more complex queries and transformations
const poolSizes = {
mongodb: config.environment === 'production' ? 40 : 20,
postgres: config.environment === 'production' ? 50 : 25,
cache: config.environment === 'production' ? 30 : 15,
};
logger.info('Data pipeline pool sizes configured', poolSizes);
// The container is already configured with connections
// Just return it with our logging
return container;
}

View file

@ -1,4 +1,8 @@
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
normalizeProviderSymbol,
type ProviderSymbolDocument,
} from '../../../normalization/provider-symbol';
import {
PipelineSyncRepository,
rejectDestructiveSync,
@ -21,7 +25,11 @@ export async function syncSymbolsFromProvider(
throw new Error('A supported provider (qm, eod, ib) is required');
}
const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres');
const rows = await mongodb.getDatabase().collection(collection).find({}).toArray();
const rows = await mongodb
.getDatabase()
.collection<ProviderSymbolDocument>(collection)
.find({})
.toArray();
return PipelineSyncRepository.transaction(postgres, async repository => {
const result: SyncResult = {
processed: rows.length,
@ -31,7 +39,8 @@ export async function syncSymbolsFromProvider(
errors: 0,
};
for (const row of rows) {
result[await repository.syncSymbol(provider, row)]++;
const symbol = normalizeProviderSymbol(row);
result[symbol ? await repository.syncSymbol(provider, symbol) : 'skipped']++;
}
await repository.updateStatus(provider, 'symbols', result.processed);
return result;

View file

@ -7,7 +7,6 @@ import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@st
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
import { setupServiceContainer } from './container-setup';
// Local imports
import { initializeAllHandlers } from './handlers';
@ -49,10 +48,6 @@ const app = new ServiceApplication(
{
// Custom lifecycle hooks
onAppReady: app => security.mount(app),
onContainerReady: container => {
// Setup service-specific configuration
setupServiceContainer(config, container);
},
onStarted: _port => {
const logger = getLogger('data-pipeline');
logger.info('Data pipeline service startup initiated with ServiceApplication framework');

View file

@ -0,0 +1,50 @@
/** Fields retained by the QM, EOD and IB symbol collections, including older spellings. */
export interface ProviderSymbolDocument {
symbol?: string | null;
code?: string | null;
Code?: string | null;
exchangeCode?: string | null;
exchange?: string | null;
exchange_id?: string | null;
Exchange?: string | null;
companyName?: string | null;
name?: string | null;
company_name?: string | null;
Name?: string | null;
countryCode?: string | null;
country_code?: string | null;
Country?: string | null;
currency?: string | null;
Currency?: string | null;
qmSearchCode?: string | null;
eodSearchCode?: string | null;
}
/** Provider codes stay exact: exchange resolution and curated mappings belong to SQL. */
export interface ProviderSymbol {
symbol: string;
exchangeCode: string;
providerSymbol: string;
companyName: string | null;
country: string | null;
currency: string | null;
}
/** Preserve the existing field precedence without guessing suffixes or exchange aliases. */
export function normalizeProviderSymbol(document: ProviderSymbolDocument): ProviderSymbol | null {
const symbol = document.symbol || document.code || document.Code;
const exchangeCode =
document.exchangeCode || document.exchange || document.exchange_id || document.Exchange;
if (!symbol || !exchangeCode) {
return null;
}
return {
symbol,
exchangeCode,
providerSymbol: document.qmSearchCode || document.eodSearchCode || symbol,
companyName:
document.companyName || document.name || document.company_name || document.Name || null,
country: document.countryCode || document.country_code || document.Country || null,
currency: document.currency || document.Currency || null,
};
}

View file

@ -1,7 +1,7 @@
import type { Document } from 'mongodb';
import type { TransactionCallback } from '@stock-bot/postgres';
import type { PostgresClient } from '@stock-bot/services';
import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types';
import type { ProviderSymbol } from '../normalization/provider-symbol';
type SqlClient = Pick<Parameters<TransactionCallback<unknown>>[0], 'query'>;
export type ResetScope = ReferenceDataResetScope;
@ -73,17 +73,14 @@ export class PipelineSyncRepository {
return inserted.rows.length ? 'created' : 'skipped';
}
async syncSymbol(provider: string, symbol: Document): Promise<'created' | 'updated' | 'skipped'> {
const code = symbol.symbol || symbol.code || symbol.Code;
const exchangeCode =
symbol.exchangeCode || symbol.exchange || symbol.exchange_id || symbol.Exchange;
if (!code || !exchangeCode) {
return 'skipped';
}
async syncSymbol(
provider: string,
symbol: ProviderSymbol
): Promise<'created' | 'updated' | 'skipped'> {
const mapping = await this.sql.query<{ master_exchange_id: string }>(
`SELECT master_exchange_id FROM provider_exchange_mappings
WHERE provider = $1 AND provider_exchange_code = $2 AND active = true`,
[provider, exchangeCode]
[provider, symbol.exchangeCode]
);
const exchangeId = mapping.rows[0]?.master_exchange_id;
if (!exchangeId) {
@ -91,7 +88,7 @@ export class PipelineSyncRepository {
}
const existing = await this.sql.query<{ id: string }>(
'SELECT id FROM symbols WHERE symbol = $1 AND exchange_id = $2',
[code, exchangeId]
[symbol.symbol, exchangeId]
);
const saved = await this.sql.query<{ id: string }>(
`INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
@ -99,13 +96,7 @@ export class PipelineSyncRepository {
company_name = COALESCE(EXCLUDED.company_name, symbols.company_name),
country = COALESCE(EXCLUDED.country, symbols.country),
currency = COALESCE(EXCLUDED.currency, symbols.currency), updated_at = NOW() RETURNING id`,
[
code,
exchangeId,
symbol.companyName || symbol.name || symbol.company_name || symbol.Name || null,
symbol.countryCode || symbol.country_code || symbol.Country || null,
symbol.currency || symbol.Currency || null,
]
[symbol.symbol, exchangeId, symbol.companyName, symbol.country, symbol.currency]
);
const symbolId = saved.rows[0]?.id;
if (!symbolId) {
@ -117,12 +108,7 @@ export class PipelineSyncRepository {
symbol_id = CASE WHEN provider_mappings.verified THEN provider_mappings.symbol_id ELSE EXCLUDED.symbol_id END,
provider_exchange = CASE WHEN provider_mappings.verified THEN provider_mappings.provider_exchange ELSE EXCLUDED.provider_exchange END,
last_seen = NOW()`,
[
symbolId,
provider,
symbol.qmSearchCode || symbol.eodSearchCode || symbol.symbol || symbol.code || symbol.Code,
exchangeCode,
]
[symbolId, provider, symbol.providerSymbol, symbol.exchangeCode]
);
return existing.rows.length ? 'updated' : 'created';
}