import { z } from 'zod'; import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research'; import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@stock-bot/types'; import { parseHistoricalDatasetMetadataV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; import { HistoricalStorageError, type StorageService, } from '../../../orchestrator/src/services/StorageService'; import { DatasetPreparationError, previewDatasetPreparation } from './dataset-preparation.service'; export class StoredDatasetPreparationError extends Error { constructor( readonly status: 400 | 404 | 422 | 503, message: string ) { super(message); } } const bodySchema = z.object({ metadata: z.unknown() }).strict(); function freeze(value: T): T { if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { Object.values(value).forEach(freeze); Object.freeze(value); } return value; } function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 { try { const parsed = bodySchema.parse(body); return freeze(parseHistoricalDatasetMetadataV2(parsed.metadata)); } catch (error) { const path = error instanceof z.ZodError ? error.issues[0]?.path.join('.') : undefined; throw new StoredDatasetPreparationError( 400, path ? `Invalid complete source metadata at ${path}` : 'Stored source requires valid complete v2 metadata' ); } } /** Materialize one explicit stored EOD query. Captured bytes, not this mutable query, are retained. */ export async function prepareStoredDataset( body: unknown, storage: Pick, signal: AbortSignal ): Promise { signal.throwIfAborted(); const metadata = metadataFromBody(body); const series = metadata.series[0]; if ( !series || metadata.series.length !== 1 || metadata.executionSeries.length !== 1 || metadata.universe.instrumentIds.length !== 1 || series.source.provider !== 'eod' || !['1m', '5m', '1h'].includes(series.interval) || series.adjustment !== 'raw' || series.timestamp !== 'interval-start' || series.availability !== 'interval-end-assumption' ) { throw new StoredDatasetPreparationError( 400, 'Stored source supports one EOD raw 1m/5m/1h series with interval-start timestamps and declared interval-end-assumption availability' ); } let rows; try { rows = await storage.getHistoricalBars( series.instrumentId, new Date(metadata.bounds.warmupStart), new Date(metadata.bounds.tradeEnd), series.interval, { adjustment: 'raw', timestamp: 'utc-instant' }, signal, 'eod' ); } catch (error) { signal.throwIfAborted(); if (error instanceof HistoricalStorageError && error.code === 'missing-range') { throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range'); } if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') { throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable'); } throw error; } signal.throwIfAborted(); if (!rows.length) { throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range'); } for (const row of rows) { if ( row.symbol !== series.instrumentId || row.source !== 'eod' || row.interpolated === true || !(row.timestamp instanceof Date) || !Number.isSafeInteger(row.timestamp.getTime()) || row.timestamp.getTime() < metadata.bounds.warmupStart || row.timestamp.getTime() >= metadata.bounds.tradeEnd ) { throw new Error('Stored source returned inconsistent bar identity or range'); } } const input: HistoricalDatasetInputV2 = freeze({ metadata, // Ordinal is deterministic adapter ordering, not a vendor publication sequence. bars: [...rows] .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()) .map((row, sourceSequence) => ({ seriesId: series.id, timestamp: row.timestamp.getTime(), sourceSequence, open: row.open, high: row.high, low: row.low, close: row.close, volume: row.volume, ...(row.vwap === undefined ? {} : { vwap: row.vwap }), })), }); let preparation; try { preparation = previewDatasetPreparation({ input }); } catch (error) { if (error instanceof DatasetPreparationError) { throw new StoredDatasetPreparationError( 422, 'Stored bars do not match the declared complete dataset metadata and interval policy' ); } throw error; } signal.throwIfAborted(); return freeze({ input, preparation }); }