56 lines
2.3 KiB
TypeScript
56 lines
2.3 KiB
TypeScript
/** Explicit offline custody of an existing v2 dataset. No provider/calendar inference. */
|
|
import { readFile } from 'node:fs/promises';
|
|
import { Pool } from 'pg';
|
|
import { validateDatasetV2 } from '../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
|
|
|
export async function retainResearchDataset(database: Pick<Pool, 'query'>, input: unknown) {
|
|
const dataset = validateDatasetV2(input);
|
|
await database.query(
|
|
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
|
|
[dataset.manifest.hash, JSON.stringify(dataset)]
|
|
);
|
|
const stored = (
|
|
await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
|
dataset.manifest.hash,
|
|
])
|
|
).rows[0];
|
|
if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) {
|
|
throw new Error('Retained dataset content does not match the imported identity');
|
|
}
|
|
return dataset.manifest;
|
|
}
|
|
|
|
if (import.meta.main) {
|
|
let database: Pool | undefined;
|
|
try {
|
|
const args = process.argv.slice(2);
|
|
if (args.length !== 2 || args[0] !== '--file' || !args[1]) {
|
|
throw new Error(
|
|
'Usage: RESEARCH_DATASET_DATABASE_URL=<database> bun run scripts/import-research-dataset.ts --file <v2-dataset.json>'
|
|
);
|
|
}
|
|
const connectionString = process.env.RESEARCH_DATASET_DATABASE_URL;
|
|
if (
|
|
!connectionString ||
|
|
!['postgres:', 'postgresql:'].includes(new URL(connectionString).protocol)
|
|
) {
|
|
throw new Error(
|
|
'Set RESEARCH_DATASET_DATABASE_URL explicitly; this command retains research data'
|
|
);
|
|
}
|
|
const input: unknown = JSON.parse(await readFile(args[1], 'utf8'));
|
|
// Validate before opening a database connection. Existing startup migrations
|
|
// own the schema; import never updates/deletes retained data or migrates tables.
|
|
validateDatasetV2(input);
|
|
database = new Pool({ connectionString, connectionTimeoutMillis: 5000 });
|
|
const manifest = await retainResearchDataset(database, input);
|
|
process.stdout.write(
|
|
`${JSON.stringify({ hash: manifest.hash, barCount: manifest.barCount, eligibility: manifest.eligibility, limitations: manifest.limitations }, null, 2)}\n`
|
|
);
|
|
} catch (error) {
|
|
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
process.exitCode = 1;
|
|
} finally {
|
|
await database?.end();
|
|
}
|
|
}
|