T-16: merge dev

This commit is contained in:
Studio 2026-11-27 12:04:11 -05:00
commit 6307d41c7e
9 changed files with 165 additions and 305 deletions

View file

@ -5,7 +5,6 @@ import { getExchangeStats } from './operations/exchange-stats.operations';
import { getProviderMappingStats } from './operations/provider-mapping-stats.operations';
import { syncQMExchanges } from './operations/qm-exchanges.operations';
import { syncAllExchanges } from './operations/sync-all-exchanges.operations';
import { syncIBExchanges } from './operations/sync-ib-exchanges.operations';
import { syncQMProviderMappings } from './operations/sync-qm-provider-mappings.operations';
@Handler('exchanges')
@ -41,19 +40,6 @@ class ExchangesHandler extends BaseHandler {
return syncQMExchanges({}, this);
}
/**
* Sync exchanges from Interactive Brokers
*/
@Operation('sync-ib-exchanges')
@ScheduledOperation('sync-ib-exchanges', '0 3 * * *', {
priority: 3,
description: 'Daily sync of IB exchanges at 3 AM',
})
async syncIBExchanges(): Promise<unknown> {
this.log('info', 'Starting IB exchanges sync...');
return syncIBExchanges({}, this);
}
/**
* Sync provider mappings from QuestionsAndMethods
*/

View file

@ -1,212 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import type { MasterExchange } from '@stock-bot/mongodb';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-ib-exchanges');
interface IBExchange {
id?: string;
_id?: unknown;
name?: string;
code?: string;
country_code?: string;
currency?: string;
}
export async function syncIBExchanges(
payload: JobPayload,
container: IServiceContainer
): Promise<{ syncedCount: number; totalExchanges: number }> {
logger.info('Syncing IB exchanges from database...');
try {
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const db = mongoClient.getDatabase();
// Filter by country code US and CA
const ibExchanges = await db
.collection<IBExchange>('ibExchanges')
.find({
country_code: { $in: ['US', 'CA'] },
})
.toArray();
logger.info('Found IB exchanges in database', { count: ibExchanges.length });
let syncedCount = 0;
for (const exchange of ibExchanges) {
try {
await createOrUpdateMasterExchange(exchange, container);
syncedCount++;
logger.debug('Synced IB exchange', {
ibId: exchange.id,
country: exchange.country_code,
});
} catch (error) {
logger.error('Failed to sync IB exchange', { exchange: exchange.id, error });
}
}
logger.info('IB exchange sync completed', {
syncedCount,
totalExchanges: ibExchanges.length,
});
return { syncedCount, totalExchanges: ibExchanges.length };
} catch (error) {
logger.error('Failed to fetch IB exchanges from database', { error });
return { syncedCount: 0, totalExchanges: 0 };
}
}
/**
* Create or update master exchange record 1:1 from IB exchange
*/
async function createOrUpdateMasterExchange(
ibExchange: IBExchange,
container: IServiceContainer
): Promise<void> {
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const db = mongoClient.getDatabase();
const collection = db.collection<MasterExchange>('masterExchanges');
const masterExchangeId = generateMasterExchangeId(ibExchange);
const now = new Date();
// Check if master exchange already exists
const existing = await collection.findOne({ masterExchangeId });
if (existing) {
// Update existing record
await collection.updateOne(
{ masterExchangeId },
{
$set: {
officialName: ibExchange.name || `Exchange ${ibExchange.id}`,
country: ibExchange.country_code || 'UNKNOWN',
currency: ibExchange.currency || 'USD',
timezone: inferTimezone(ibExchange),
updated_at: now,
},
}
);
logger.debug('Updated existing master exchange', { masterExchangeId });
} else {
// Create new master exchange
const masterExchange: MasterExchange = {
masterExchangeId,
shortName: masterExchangeId, // Set shortName to masterExchangeId on creation
officialName: ibExchange.name || `Exchange ${ibExchange.id}`,
country: ibExchange.country_code || 'UNKNOWN',
currency: ibExchange.currency || 'USD',
timezone: inferTimezone(ibExchange),
active: false, // Set active to false only on creation
sourceMappings: {
ib: {
id: ibExchange.id || ibExchange._id?.toString() || 'unknown',
name: ibExchange.name || `Exchange ${ibExchange.id}`,
code: ibExchange.code || ibExchange.id || '',
aliases: generateAliases(ibExchange),
lastUpdated: now,
},
},
confidence: 1.0, // High confidence for direct IB mapping
verified: true, // Mark as verified since it's direct from IB
// DocumentBase fields
source: 'ib-exchange-sync',
created_at: now,
updated_at: now,
};
await collection.insertOne(masterExchange);
logger.debug('Created new master exchange', { masterExchangeId });
}
}
/**
* Generate master exchange ID from IB exchange
*/
function generateMasterExchangeId(ibExchange: IBExchange): string {
// Use code if available, otherwise use ID, otherwise generate from name
if (ibExchange.code) {
return ibExchange.code.toUpperCase().replace(/[^A-Z0-9]/g, '');
}
if (ibExchange.id) {
return ibExchange.id.toUpperCase().replace(/[^A-Z0-9]/g, '');
}
if (ibExchange.name) {
return ibExchange.name
.toUpperCase()
.split(' ')
.slice(0, 2)
.join('_')
.replace(/[^A-Z0-9_]/g, '');
}
return 'UNKNOWN_EXCHANGE';
}
/**
* Generate aliases for the exchange
*/
function generateAliases(ibExchange: IBExchange): string[] {
const aliases: string[] = [];
if (ibExchange.name && ibExchange.name.includes(' ')) {
// Add abbreviated version
aliases.push(
ibExchange.name
.split(' ')
.map(w => w[0])
.join('')
.toUpperCase()
);
}
if (ibExchange.code) {
aliases.push(ibExchange.code.toUpperCase());
}
return aliases;
}
/**
* Infer timezone from exchange name/location
*/
function inferTimezone(ibExchange: IBExchange): string {
if (!ibExchange.name) {
return 'UTC';
}
const name = ibExchange.name.toUpperCase();
if (name.includes('NEW YORK') || name.includes('NYSE') || name.includes('NASDAQ')) {
return 'America/New_York';
}
if (name.includes('LONDON')) {
return 'Europe/London';
}
if (name.includes('TOKYO')) {
return 'Asia/Tokyo';
}
if (name.includes('SHANGHAI')) {
return 'Asia/Shanghai';
}
if (name.includes('TORONTO')) {
return 'America/Toronto';
}
if (name.includes('FRANKFURT')) {
return 'Europe/Berlin';
}
return 'UTC'; // Default
}

View file

@ -73,16 +73,6 @@ export function createPipelineRoutes(container: IServiceContainer) {
}
});
pipeline.post('/provider-mappings/ib', async c => {
try {
const result = await pipelineService.syncIBExchanges();
return c.json(result, result.success ? 200 : 503);
} catch (error) {
logger.error('Error in POST /provider-mappings/ib', { error });
return c.json({ success: false, error: 'Internal server error' }, 500);
}
});
// Status endpoint
pipeline.get('/status', async c => {
try {

View file

@ -182,38 +182,6 @@ export class PipelineService {
}
}
/**
* Queue a job to sync IB exchanges
*/
async syncIBExchanges(): Promise<PipelineJobResult> {
try {
const queueManager = this.container.queueManager;
if (!queueManager) {
return { success: false, error: 'Queue manager not available' };
}
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
const job = await exchangesQueue.add('sync-ib-exchanges', {
handler: 'exchanges',
operation: 'sync-ib-exchanges',
payload: {},
});
logger.info('IB exchanges sync job queued', { jobId: job.id });
return {
success: true,
jobId: job.id,
message: 'IB exchanges sync job queued',
};
} catch (error) {
logger.error('Failed to queue IB exchanges sync job', { error });
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to queue sync job',
};
}
}
/**
* Get sync status
*/

View file

@ -59,14 +59,6 @@ const operations: PipelineOperation[] = [
method: 'POST',
category: 'sync',
},
{
id: 'sync-ib-exchanges',
name: 'Sync IB Exchanges',
description: 'Sync exchanges from Interactive Brokers',
endpoint: '/provider-mappings/ib',
method: 'POST',
category: 'sync',
},
// Maintenance operations
{
id: 'clear-postgresql',
@ -89,7 +81,6 @@ export function PipelinePage() {
syncQMExchanges,
syncAllExchanges,
syncQMProviderMappings,
syncIBExchanges,
clearPostgreSQLData,
getExchangeStats,
getProviderMappingStats,
@ -136,9 +127,6 @@ export function PipelinePage() {
case 'sync-qm-provider-mappings':
await syncQMProviderMappings();
break;
case 'sync-ib-exchanges':
await syncIBExchanges();
break;
case 'clear-postgresql':
{
const expected = `DELETE STOCK REFERENCE DATA:${clearDataType}`;

View file

@ -65,11 +65,6 @@ export function usePipeline() {
[executeOperation]
);
const syncIBExchanges = useCallback(
() => executeOperation(() => pipelineApi.syncIBExchanges()),
[executeOperation]
);
// Maintenance operations
const clearPostgreSQLData = useCallback(
(dataType: DataClearType, confirmation: string) =>
@ -148,7 +143,6 @@ export function usePipeline() {
// Provider mapping operations
syncQMProviderMappings,
syncIBExchanges,
// Maintenance operations
clearPostgreSQLData,

View file

@ -46,10 +46,6 @@ class PipelineApiService {
return this.request<PipelineJobResult>('/provider-mappings/qm', { method: 'POST' });
}
async syncIBExchanges(): Promise<PipelineJobResult> {
return this.request<PipelineJobResult>('/provider-mappings/ib', { method: 'POST' });
}
// Status and maintenance operations
async getSyncStatus(): Promise<PipelineJobResult> {
return this.request<PipelineJobResult>('/status');

View file

@ -96,20 +96,20 @@ describe('createJobHandler', () => {
});
it('should support async operations', async () => {
let resolveStep!: () => void;
let asyncStepCompleted = false;
const stepGate = new Promise<void>(resolve => {
resolveStep = resolve;
// Gate created before the wrapper runs, so the test does not assume synchronous invocation.
let releaseAsyncWork!: () => void;
const asyncWorkGate = new Promise<void>(resolve => {
releaseAsyncWork = resolve;
});
let callbackFinished = false;
const handler = createJobHandler<TestPayload, TestResult>(async job => {
await stepGate;
asyncStepCompleted = true;
await asyncWorkGate;
callbackFinished = true;
return {
success: true,
processedBy: job.data.userId,
timestamp: new Date(),
timestamp: new Date(0),
};
});
@ -126,14 +126,22 @@ describe('createJobHandler', () => {
updateProgress: async () => {},
};
const pending = handler(mockJob as any);
expect(asyncStepCompleted).toBe(false);
resolveStep();
const result = await pending;
let wrapperSettled = false;
const resultPromise = handler(mockJob as any).finally(() => {
wrapperSettled = true;
});
expect(asyncStepCompleted).toBe(true);
expect(result.success).toBe(true);
expect(result.processedBy).toBe('user-789');
// Drain microtasks: the wrapper must still be waiting on the callback.
await Promise.resolve();
await Promise.resolve();
expect(wrapperSettled).toBe(false);
expect(callbackFinished).toBe(false);
releaseAsyncWork();
const result = await resultPromise;
expect(callbackFinished).toBe(true);
expect(result).toEqual({ success: true, processedBy: 'user-789', timestamp: new Date(0) });
});
it('should maintain type safety for complex payloads', () => {

View file

@ -0,0 +1,142 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { ExchangesHandler } from '../../apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler';
import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes';
import { PipelineService } from '../../apps/stock/web-api/src/services/pipeline.service';
const repository = fileURLToPath(new URL('../../', import.meta.url));
function scanSourceFiles(relativeDir: string): string[] {
const dir = join(repository, relativeDir);
return [...new Bun.Glob('**/*.{ts,tsx}').scanSync({ cwd: dir })].map(file => join(dir, file));
}
describe('legacy sync-ib-exchanges removal', () => {
it('legacy MongoDB-writing sync-ib-exchanges operations file does not exist', () => {
const legacyFile = join(
repository,
'apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts'
);
expect(existsSync(legacyFile)).toBe(false);
});
it('no source file in data-pipeline, web-api, or web-app references sync-ib-exchanges or syncIBExchanges', () => {
const trees = [
'apps/stock/data-pipeline/src',
'apps/stock/web-api/src',
'apps/stock/web-app/src',
];
const forbiddenSymbols = ['sync-ib-exchanges', 'syncIBExchanges'];
const hits: string[] = [];
for (const tree of trees) {
for (const file of scanSourceFiles(tree)) {
const content = readFileSync(file, 'utf8');
for (const token of forbiddenSymbols) {
if (content.includes(token)) {
hits.push(`${file}: ${token}`);
}
}
if (tree !== 'apps/stock/data-pipeline/src' && content.includes('/provider-mappings/ib')) {
hits.push(`${file}: /provider-mappings/ib`);
}
}
}
expect(hits).toEqual([]);
});
it('POST /api/pipeline/provider-mappings/ib returns 404 without enqueueing jobs while QM mapping route stays active', async () => {
const jobs: unknown[] = [];
const services = {
queueManager: {
getQueue() {
return {
async add(_name: string, data: unknown) {
jobs.push(data);
return { id: 'fixture' };
},
};
},
},
} as unknown as IServiceContainer;
const app = new Hono();
app.route('/api/pipeline', createPipelineRoutes(services));
const removed = await app.request('/api/pipeline/provider-mappings/ib', { method: 'POST' });
expect(removed.status).toBe(404);
expect(jobs).toHaveLength(0);
const active = await app.request('/api/pipeline/provider-mappings/qm', { method: 'POST' });
expect(active.status).toBe(200);
expect(jobs).toEqual([
{ handler: 'exchanges', operation: 'sync-qm-provider-mappings', payload: {} },
]);
});
});
describe('exchanges handler after sync-ib-exchanges removal', () => {
it('registers exactly the remaining exchange operations and no IB operation', () => {
const metadata = ExchangesHandler.extractMetadata();
expect(metadata?.name).toBe('exchanges');
// @Operation + @ScheduledOperation on one method registers the name twice, so compare the set.
expect([...new Set(metadata?.operations ?? [])].sort()).toEqual([
'clear-postgresql-data',
'get-exchange-stats',
'get-provider-mapping-stats',
'sync-all-exchanges',
'sync-qm-exchanges',
'sync-qm-provider-mappings',
]);
});
it('keeps the other nightly schedules but drops the 03:00 IB exchange schedule', () => {
const metadata = ExchangesHandler.extractMetadata();
const schedules = (metadata?.scheduledJobs ?? [])
.map(job => ({ operation: job.operation, cronPattern: job.cronPattern }))
.sort((a, b) => a.operation.localeCompare(b.operation));
expect(schedules).toEqual([
{ operation: 'sync-all-exchanges', cronPattern: '0 0 * * 0' },
{ operation: 'sync-qm-exchanges', cronPattern: '0 1 * * *' },
{ operation: 'sync-qm-provider-mappings', cronPattern: '0 3 * * *' },
]);
});
it('rejects a leftover queued sync-ib-exchanges job without touching MongoDB', async () => {
const mongoCalls: string[] = [];
const mongodb = new Proxy(
{},
{
get(_target, property) {
mongoCalls.push(String(property));
return () => {
throw new Error('MongoDB must not be used');
};
},
}
);
const handler = new ExchangesHandler({ mongodb } as unknown as IServiceContainer);
await expect(
handler.execute('sync-ib-exchanges', {}, { type: 'queue', metadata: {} } as never)
).rejects.toThrow('Unknown operation: sync-ib-exchanges');
expect(mongoCalls).toEqual([]);
});
});
describe('web-api pipeline service after sync-ib-exchanges removal', () => {
it('no longer exposes a method that enqueues sync-ib-exchanges', () => {
const service = new PipelineService({} as IServiceContainer);
expect('syncIBExchanges' in service).toBe(false);
expect(typeof service.syncQMProviderMappings).toBe('function');
});
});