import { Hono } from 'hono'; import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; import { HistoricalDataRequestError } from '@stock-bot/types'; import { StorageService } from '../../../orchestrator/src/services/StorageService'; import { canonicalDatasetEntry } from '../services/canonical-research.service'; import { DatasetCatalogService } from '../services/dataset-catalog.service'; import { DatasetPreparationError, previewDatasetPreparation, retainDatasetPreparation, } from '../services/dataset-preparation.service'; import { prepareStoredDataset, StoredDatasetPreparationError, } from '../services/stored-dataset-preparation'; import { inspectStoredSource, storedSourceCoverage, StoredSourceInspectionError, } from '../services/stored-source-inspection'; const logger = getLogger('dataset-catalog-routes'); export function createDatasetRoutes(container: IServiceContainer) { const app = new Hono(); const catalog = new DatasetCatalogService(requireServices(container, 'postgres').postgres); const database = requireServices(container, 'postgres').postgres; const readBody = async (request: Request): Promise => { try { return await request.json(); } catch { throw new DatasetPreparationError(400, 'Invalid JSON request'); } }; app.get('/api/v2/datasets/stored-eod/coverage', async c => { c.header('Cache-Control', 'no-store'); try { return c.json(await storedSourceCoverage(container.mongodb, c.req.query(), c.req.raw.signal)); } catch (error) { if (c.req.raw.signal.aborted) { return Response.json( { error: 'Stored source inspection cancelled' }, { status: 499, headers: { 'Cache-Control': 'no-store' } } ); } if (error instanceof StoredSourceInspectionError) { return c.json({ error: error.message }, error.status); } logger.error('Failed to inspect stored source coverage', error); return c.json({ error: 'Stored source coverage unavailable' }, 500); } }); app.post('/api/v2/datasets/stored-eod/inspect', async c => { c.header('Cache-Control', 'no-store'); try { return c.json( await inspectStoredSource(container.mongodb, await readBody(c.req.raw), c.req.raw.signal) ); } catch (error) { if (c.req.raw.signal.aborted) { return Response.json( { error: 'Stored source inspection cancelled' }, { status: 499, headers: { 'Cache-Control': 'no-store' } } ); } if ( error instanceof StoredSourceInspectionError || error instanceof DatasetPreparationError ) { return c.json({ error: error.message }, error.status); } logger.error('Failed to inspect stored source quality', error); return c.json({ error: 'Stored source inspection unavailable' }, 500); } }); app.post('/api/v2/datasets/canonical/stored-source', async c => { c.header('Cache-Control', 'no-store'); try { const body = await readBody(c.req.raw); // Request-local read adapter: no initialization, mode changes or shared trading runtime. const storage = new StorageService(container.logger, container.mongodb, null); const prepared = await prepareStoredDataset(body, storage, c.req.raw.signal); c.req.raw.signal.throwIfAborted(); return c.json(prepared); } catch (error) { if (c.req.raw.signal.aborted) { return Response.json( { error: 'Stored source preparation cancelled' }, { status: 499, headers: { 'Cache-Control': 'no-store' } } ); } if ( error instanceof StoredDatasetPreparationError || error instanceof DatasetPreparationError ) { return c.json({ error: error.message }, error.status); } logger.error('Failed to prepare stored source dataset', error); return c.json({ error: 'Stored source preparation unavailable' }, 500); } }); app.post('/api/v2/datasets/canonical/preview', async c => { c.header('Cache-Control', 'no-store'); try { return c.json({ preparation: previewDatasetPreparation(await readBody(c.req.raw)) }); } catch (error) { if (error instanceof DatasetPreparationError) { return c.json({ error: error.message }, error.status); } logger.error('Failed to preview source dataset', error); return c.json({ error: 'Source dataset preparation unavailable' }, 500); } }); app.post('/api/v2/datasets/canonical/retain', async c => { c.header('Cache-Control', 'no-store'); try { return c.json({ preparation: await retainDatasetPreparation(database, await readBody(c.req.raw)), }); } catch (error) { if (error instanceof DatasetPreparationError) { return c.json({ error: error.message }, error.status); } logger.error('Failed to retain source dataset', error); return c.json({ error: 'Source dataset retention unavailable' }, 500); } }); app.get('/api/v2/datasets/canonical', async c => { try { const limit = c.req.query('limit') ?? '50'; const offset = c.req.query('offset') ?? '0'; if ( !/^\d+$/.test(limit) || !/^\d+$/.test(offset) || !Number.isSafeInteger(Number(limit)) || Number(limit) < 1 || !Number.isSafeInteger(Number(offset)) ) { return c.json( { error: 'Dataset pagination requires a positive limit and nonnegative offset' }, 400 ); } const rows = await database.query<{ hash: string; created_at: Date }>( "SELECT hash,created_at FROM backtest_datasets WHERE payload#>>'{manifest,version}'='2' ORDER BY created_at DESC,hash LIMIT $1 OFFSET $2", [Number(limit), Number(offset)] ); const datasets = []; for (const row of rows.rows) { datasets.push(await canonicalDatasetEntry(database, row)); } return c.json({ datasets }); } catch (error) { logger.error('Failed to list canonical datasets', error); return c.json({ error: 'Failed to list canonical datasets' }, 500); } }); app.get('/api/v2/datasets/canonical/:hash', async c => { try { const hash = c.req.param('hash'); if (!/^[a-f0-9]{64}$/.test(hash)) { return c.json({ error: 'Invalid dataset hash' }, 400); } const row = ( await database.query<{ hash: string; created_at: Date }>( 'SELECT hash,created_at FROM backtest_datasets WHERE hash=$1', [hash] ) ).rows[0]; return row ? c.json({ dataset: await canonicalDatasetEntry(database, row) }) : c.json({ error: 'Dataset not found' }, 404); } catch (error) { logger.error('Failed to get canonical dataset', error); return c.json({ error: 'Failed to get canonical dataset' }, 500); } }); app.get('/api/v2/datasets', async c => { try { const limit = c.req.query('limit') ?? '50'; const offset = c.req.query('offset') ?? '0'; if (!/^\d+$/.test(limit) || !/^\d+$/.test(offset)) { throw new HistoricalDataRequestError('Dataset limit and offset must be integers'); } return c.json({ datasets: await catalog.list({ limit: Number(limit), offset: Number(offset) }), }); } catch (error) { if (error instanceof HistoricalDataRequestError) { return c.json({ error: error.message }, 400); } logger.error('Failed to list datasets', error); return c.json({ error: 'Failed to list datasets' }, 500); } }); app.get('/api/v2/datasets/:hash', async c => { try { const dataset = await catalog.get(c.req.param('hash')); return dataset ? c.json({ dataset }) : c.json({ error: 'Dataset not found' }, 404); } catch (error) { if (error instanceof HistoricalDataRequestError) { return c.json({ error: error.message }, 400); } logger.error('Failed to get dataset', error); return c.json({ error: 'Failed to get dataset' }, 500); } }); return app; }