129 lines
4.7 KiB
TypeScript
129 lines
4.7 KiB
TypeScript
import type { QueryResultRow } from 'pg';
|
|
import {
|
|
assertDatasetMatchesRequest,
|
|
datasetHashSchema,
|
|
validateDatasetManifestMetadata,
|
|
} from '@stock-bot/stock-config/backtest';
|
|
import { HistoricalDataRequestError, type HistoricalDatasetCatalogEntry } from '@stock-bot/types';
|
|
|
|
/** Accept either the pool or the already locked run transaction. */
|
|
export interface DatasetCatalogQuery {
|
|
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
|
}
|
|
|
|
// Never transfer the bar payload to the API process. CASE guards PostgreSQL's
|
|
// array/object functions so malformed retained JSON becomes a diagnostic row.
|
|
const metadataProjection = `SELECT hash, created_at, payload->'manifest' AS manifest,
|
|
jsonb_typeof(payload) AS payload_type,
|
|
jsonb_typeof(payload->'manifest') AS manifest_type,
|
|
jsonb_typeof(payload->'bars') AS bars_type,
|
|
CASE WHEN jsonb_typeof(payload->'bars') = 'array'
|
|
THEN jsonb_array_length(payload->'bars') ELSE NULL END AS bar_count,
|
|
CASE WHEN jsonb_typeof(payload) = 'object'
|
|
THEN ARRAY(SELECT key FROM jsonb_object_keys(payload) AS key ORDER BY key)
|
|
ELSE NULL END AS root_keys
|
|
FROM backtest_datasets`;
|
|
|
|
function entry(row: QueryResultRow): HistoricalDatasetCatalogEntry {
|
|
const raw = row.manifest;
|
|
const version =
|
|
raw && typeof raw === 'object' && !Array.isArray(raw) && Number.isSafeInteger(raw.version)
|
|
? (raw.version as number)
|
|
: null;
|
|
const result: HistoricalDatasetCatalogEntry = {
|
|
hash: row.hash,
|
|
version,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
manifest: null,
|
|
status: 'invalid',
|
|
reason: null,
|
|
coverage: 'unknown',
|
|
integrity: 'not-verified',
|
|
};
|
|
if (version !== null && version !== 1) {
|
|
return {
|
|
...result,
|
|
status: 'unsupported',
|
|
reason:
|
|
version === 2
|
|
? 'Dataset v2 requires canonical workbench support (R05); choose a v1 dataset or prepare source data.'
|
|
: `Dataset version ${version} is unsupported; choose a supported dataset or prepare source data.`,
|
|
};
|
|
}
|
|
if (
|
|
row.payload_type !== 'object' ||
|
|
row.manifest_type !== 'object' ||
|
|
row.bars_type !== 'array' ||
|
|
JSON.stringify(row.root_keys) !== JSON.stringify(['bars', 'manifest'])
|
|
) {
|
|
return { ...result, reason: 'Retained dataset structure is invalid; prepare a new dataset.' };
|
|
}
|
|
try {
|
|
const manifest = validateDatasetManifestMetadata(raw);
|
|
if (manifest.hash !== row.hash) {
|
|
return { ...result, reason: 'Dataset key and manifest hash differ; prepare a new dataset.' };
|
|
}
|
|
if (manifest.barCount !== row.bar_count) {
|
|
return {
|
|
...result,
|
|
reason: 'Dataset manifest bar count differs from retained data; prepare a new dataset.',
|
|
};
|
|
}
|
|
return { ...result, manifest, status: 'available' };
|
|
} catch {
|
|
return {
|
|
...result,
|
|
reason: 'Retained dataset manifest metadata is invalid; prepare a new dataset.',
|
|
};
|
|
}
|
|
}
|
|
|
|
export class DatasetCatalogService {
|
|
constructor(private readonly database: DatasetCatalogQuery) {}
|
|
|
|
async list(params: { limit: number; offset: number }): Promise<HistoricalDatasetCatalogEntry[]> {
|
|
if (
|
|
!Number.isSafeInteger(params.limit) ||
|
|
params.limit <= 0 ||
|
|
!Number.isSafeInteger(params.offset) ||
|
|
params.offset < 0
|
|
) {
|
|
throw new HistoricalDataRequestError(
|
|
'Dataset pagination requires a positive limit and nonnegative offset'
|
|
);
|
|
}
|
|
const result = await this.database.query(
|
|
`${metadataProjection} ORDER BY created_at DESC, hash ASC LIMIT $1 OFFSET $2`,
|
|
[params.limit, params.offset]
|
|
);
|
|
return result.rows.map(entry);
|
|
}
|
|
|
|
async get(hash: string): Promise<HistoricalDatasetCatalogEntry | null> {
|
|
if (!datasetHashSchema.safeParse(hash).success) {
|
|
throw new HistoricalDataRequestError('Invalid dataset hash');
|
|
}
|
|
const result = await this.database.query(`${metadataProjection} WHERE hash = $1`, [hash]);
|
|
return result.rows[0] ? entry(result.rows[0]) : null;
|
|
}
|
|
}
|
|
|
|
/** Acceptance uses metadata only. The existing runner still verifies full content. */
|
|
export async function assertSelectedDatasetMatchesRequest(
|
|
database: DatasetCatalogQuery,
|
|
config: Parameters<typeof assertDatasetMatchesRequest>[1]
|
|
): Promise<void> {
|
|
if (config.datasetHash === undefined) {
|
|
return;
|
|
}
|
|
const selected = await new DatasetCatalogService(database).get(config.datasetHash);
|
|
if (!selected) {
|
|
throw new HistoricalDataRequestError('Selected frozen dataset was not found');
|
|
}
|
|
if (selected.status !== 'available' || !selected.manifest) {
|
|
throw new HistoricalDataRequestError(
|
|
selected.reason ?? 'Selected frozen dataset is unavailable'
|
|
);
|
|
}
|
|
assertDatasetMatchesRequest(selected.manifest, config);
|
|
}
|