730 lines
27 KiB
TypeScript
730 lines
27 KiB
TypeScript
import { describe, expect, mock, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { createHttpSecurity } from '@stock-bot/di';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import type { IServiceContainer, MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
|
import { parseFinancialDecimal, type HistoricalDatasetMetadataV2 } from '@stock-bot/types';
|
|
import {
|
|
NativeReplaySession,
|
|
prepareReplayLoad,
|
|
runReplayConformance,
|
|
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
|
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
|
import {
|
|
StorageService,
|
|
type HistoricalBar,
|
|
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
|
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
|
import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service';
|
|
import { prepareStoredDataset } from '../../apps/stock/web-api/src/services/stored-dataset-preparation';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|
const logger = getLogger('stored-source-test');
|
|
const token = 'stored-source-admin-fixture-not-a-real-secret';
|
|
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
|
type Row = {
|
|
symbol: string;
|
|
exchange: string;
|
|
eodSearchCode: string;
|
|
timestamp: number;
|
|
open: number;
|
|
high: number;
|
|
low: number;
|
|
close: number;
|
|
volume: number;
|
|
};
|
|
function at<T>(values: readonly T[], index = 0): T {
|
|
const value = values[index];
|
|
if (value === undefined) {
|
|
throw new Error('Missing fixture row');
|
|
}
|
|
return value;
|
|
}
|
|
function source(interval: '1m' | '5m' | '1h' = '1m') {
|
|
const f = nativeReplayFixture(3),
|
|
duration = { '1m': 60000, '5m': 300000, '1h': 3600000 }[interval];
|
|
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
|
f.dataset.manifest;
|
|
const metadata = structuredClone({
|
|
calendars,
|
|
series,
|
|
executionSeries,
|
|
bounds,
|
|
universe,
|
|
corporateActions,
|
|
}) as Mutable<HistoricalDatasetMetadataV2>;
|
|
const declared = at(metadata.series);
|
|
declared.interval = interval;
|
|
declared.source = { provider: 'eod', revision: 'operator-declared-source-v1' };
|
|
declared.availability = 'interval-end-assumption';
|
|
metadata.bounds.tradeStart = f.start + duration;
|
|
metadata.bounds.tradeEnd = f.start + 3 * duration;
|
|
at(metadata.corporateActions).end = metadata.bounds.tradeEnd;
|
|
const rows: Row[] = f.dataset.bars.map((bar, index) => ({
|
|
symbol: 'X0',
|
|
exchange: 'US',
|
|
eodSearchCode: 'X0.US',
|
|
timestamp: (f.start + index * duration) / 1000,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
}));
|
|
return { metadata, rows, f, duration };
|
|
}
|
|
function fixture(
|
|
find: (
|
|
collection: string,
|
|
filter: Record<string, unknown>,
|
|
options: Record<string, unknown>
|
|
) => Promise<Row[]> = async () => source().rows,
|
|
mongoAvailable = true
|
|
) {
|
|
const query = mock(async () => {
|
|
throw new Error('Preparation must not reach PostgreSQL');
|
|
});
|
|
const read = mock(find);
|
|
const mongodb = mongoAvailable ? ({ find: read } as unknown as MongoDBClient) : undefined;
|
|
const questdb = {
|
|
query: mock(async () => {
|
|
throw new Error('Unexpected provider fallback');
|
|
}),
|
|
} as unknown as QuestDBClient;
|
|
const container = {
|
|
logger,
|
|
mongodb,
|
|
questdb,
|
|
postgres: { query },
|
|
} as unknown as IServiceContainer;
|
|
const app = new Hono();
|
|
createHttpSecurity({
|
|
adminToken: token,
|
|
serviceToken: 'stored-source-service-fixture-not-a-real-secret',
|
|
readToken: 'stored-source-read-fixture-not-a-real-secret',
|
|
environment: 'test',
|
|
browserSessions: true,
|
|
}).mount(app);
|
|
app.route('/', createDatasetRoutes(container));
|
|
const request = (body: unknown, signal?: AbortSignal) =>
|
|
app.request('/api/v2/datasets/canonical/stored-source', {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
signal,
|
|
});
|
|
return {
|
|
request,
|
|
app,
|
|
read,
|
|
query,
|
|
questdb,
|
|
storage: new StorageService(container.logger, mongodb, questdb),
|
|
container,
|
|
};
|
|
}
|
|
|
|
describe('stored EOD preparation', () => {
|
|
test('all supported intraday intervals use the actual strict EOD adapter once, exact UTC query bounds and unchanged raw observations', async () => {
|
|
for (const interval of ['1m', '5m', '1h'] as const) {
|
|
const input = source(interval);
|
|
const f = fixture(async () => [...input.rows].reverse());
|
|
const reply = await f.request({ metadata: input.metadata });
|
|
expect(reply.status).toBe(200);
|
|
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
|
const body = await reply.json();
|
|
expect(f.read).toHaveBeenCalledTimes(1);
|
|
expect(f.read.mock.calls[0]).toEqual([
|
|
{ '1m': 'eodIntraday1M', '5m': 'eodIntraday5M', '1h': 'eodIntraday1H' }[interval],
|
|
{
|
|
eodSearchCode: 'X0.US',
|
|
timestamp: {
|
|
$gte: input.metadata.bounds.warmupStart / 1000,
|
|
$lt: input.metadata.bounds.tradeEnd / 1000,
|
|
},
|
|
},
|
|
{
|
|
sort: { timestamp: 1 },
|
|
projection: {
|
|
symbol: 1,
|
|
exchange: 1,
|
|
eodSearchCode: 1,
|
|
timestamp: 1,
|
|
open: 1,
|
|
high: 1,
|
|
low: 1,
|
|
close: 1,
|
|
volume: 1,
|
|
},
|
|
},
|
|
]);
|
|
expect(body.input.metadata).toEqual(input.metadata);
|
|
expect(body.input.bars.map((bar: { sourceSequence: number }) => bar.sourceSequence)).toEqual([
|
|
0, 1, 2,
|
|
]);
|
|
expect(body.input.bars.map((bar: { timestamp: number }) => bar.timestamp)).toEqual(
|
|
input.rows.map(row => row.timestamp * 1000)
|
|
);
|
|
expect(
|
|
body.input.bars.every(
|
|
(bar: Record<string, unknown>) =>
|
|
!Object.hasOwn(bar, 'vwap') && !Object.hasOwn(bar, 'availableAt')
|
|
)
|
|
).toBe(true);
|
|
expect(body.preparation).toEqual(previewDatasetPreparation({ input: body.input }));
|
|
const normalized = createDatasetV2(body.input);
|
|
expect(
|
|
normalized.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)
|
|
).toBe(true);
|
|
expect(normalized.manifest.parentDatasetHash).toBeNull();
|
|
expect(f.query).not.toHaveBeenCalled();
|
|
expect(f.questdb.query).not.toHaveBeenCalled();
|
|
}
|
|
});
|
|
|
|
test('complete metadata and supported scope reject before every provider read', async () => {
|
|
const f = fixture();
|
|
const bodies: unknown[] = [
|
|
null,
|
|
{},
|
|
{ metadata: {} },
|
|
{ metadata: source().metadata, extra: true },
|
|
];
|
|
const changes: Array<(metadata: Mutable<HistoricalDatasetMetadataV2>) => void> = [
|
|
metadata => {
|
|
at(metadata.series).source.provider = 'auto';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).source.provider = 'questdb';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).source.revision = '';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).interval = '15m';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).interval = '1d';
|
|
at(metadata.series).timestamp = 'session-date';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).adjustment = 'provider-adjusted';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).timestamp = 'interval-end';
|
|
},
|
|
metadata => {
|
|
at(metadata.series).availability = 'explicit';
|
|
},
|
|
metadata => {
|
|
metadata.corporateActions = [];
|
|
},
|
|
metadata => {
|
|
at(metadata.calendars).timeZone = 'private-invalid-timezone';
|
|
},
|
|
metadata => {
|
|
metadata.bounds.tradeStart = metadata.bounds.tradeEnd;
|
|
},
|
|
metadata => {
|
|
metadata.series.push({ ...at(metadata.series), id: 'X1.US:1m', instrumentId: 'X1.US' });
|
|
metadata.executionSeries.push({ instrumentId: 'X1.US', seriesId: 'X1.US:1m' });
|
|
metadata.universe.instrumentIds.push('X1.US');
|
|
metadata.corporateActions.push({ ...at(metadata.corporateActions), instrumentId: 'X1.US' });
|
|
},
|
|
];
|
|
for (const change of changes) {
|
|
const { metadata } = source();
|
|
change(metadata);
|
|
bodies.push({ metadata });
|
|
}
|
|
for (const body of bodies) {
|
|
const reply = await f.request(body);
|
|
expect(reply.status).toBe(400);
|
|
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await reply.text()).not.toContain('private-invalid-timezone');
|
|
}
|
|
expect(f.read).not.toHaveBeenCalled();
|
|
expect(f.query).not.toHaveBeenCalled();
|
|
expect(f.questdb.query).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('empty, unavailable, corrupt and transport failure cases stay distinct without fallback or private errors', async () => {
|
|
const body = { metadata: source().metadata };
|
|
const cases: Array<[ReturnType<typeof fixture>, number]> = [
|
|
[fixture(async () => []), 404],
|
|
[fixture(undefined, false), 503],
|
|
[
|
|
fixture(async () => {
|
|
throw new Error('private database connection details');
|
|
}),
|
|
500,
|
|
],
|
|
[
|
|
fixture(async () =>
|
|
source().rows.map((row, index) => (index === 0 ? { ...row, high: 0 } : row))
|
|
),
|
|
500,
|
|
],
|
|
[fixture(async () => source().rows.map(row => ({ ...row, exchange: 'WRONG' }))), 500],
|
|
[fixture(async () => [...source().rows, at(source().rows)]), 500],
|
|
];
|
|
for (const [f, status] of cases) {
|
|
const reply = await f.request(body);
|
|
expect(reply.status).toBe(status);
|
|
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await reply.text()).not.toContain('private database connection details');
|
|
expect(f.query).not.toHaveBeenCalled();
|
|
expect(f.questdb.query).not.toHaveBeenCalled();
|
|
}
|
|
});
|
|
|
|
test('valid unavailable declarations remain inspectable; partial intervals and declared session mismatches fail422', async () => {
|
|
const input = source();
|
|
input.metadata.universe.selection = 'unknown';
|
|
input.metadata.universe.asOf = null;
|
|
const reply = await fixture().request({ metadata: input.metadata });
|
|
expect(reply.status).toBe(200);
|
|
expect((await reply.json()).preparation).toMatchObject({
|
|
available: false,
|
|
manifest: { eligibility: 'exploratory' },
|
|
});
|
|
const partial = source();
|
|
partial.metadata.bounds.tradeEnd -= 30000;
|
|
const partialReply = await fixture().request({ metadata: partial.metadata });
|
|
expect(partialReply.status).toBe(422);
|
|
const wrongSession = source();
|
|
at(at(wrongSession.metadata.calendars).sessions).open += 30000;
|
|
const sessionReply = await fixture().request({ metadata: wrongSession.metadata });
|
|
expect(sessionReply.status).toBe(422);
|
|
expect(await sessionReply.text()).toContain('declared complete dataset metadata');
|
|
});
|
|
|
|
test('metadata is detached and deeply frozen before await; later caller/store mutations cannot alter returned captured bytes', async () => {
|
|
const initial = source(),
|
|
expectedMetadata = structuredClone(initial.metadata);
|
|
let release: (() => void) | undefined;
|
|
const gate = new Promise<void>(resolve => {
|
|
release = resolve;
|
|
});
|
|
const f = fixture(async () => {
|
|
await gate;
|
|
return initial.rows;
|
|
});
|
|
const promise = prepareStoredDataset(
|
|
{ metadata: initial.metadata },
|
|
f.storage,
|
|
new AbortController().signal
|
|
);
|
|
expect(f.read).toHaveBeenCalledTimes(1);
|
|
at(initial.metadata.series).source.revision = 'later source revision';
|
|
initial.metadata.bounds.tradeEnd += initial.duration;
|
|
if (!release) {
|
|
throw new Error('Missing fixture barrier');
|
|
}
|
|
release();
|
|
const prepared = await promise;
|
|
expect(prepared.input.metadata).toEqual(expectedMetadata);
|
|
expect(Object.isFrozen(prepared)).toBe(true);
|
|
expect(Object.isFrozen(prepared.input.metadata.calendars[0]?.sessions)).toBe(true);
|
|
expect(Object.isFrozen(prepared.input.bars[0])).toBe(true);
|
|
at(initial.rows).close = 10.5;
|
|
expect(prepared.input.bars[0]?.close).toBe(11);
|
|
expect(prepared.preparation).toEqual(previewDatasetPreparation({ input: prepared.input }));
|
|
});
|
|
|
|
test('initial and late cancellation return499 even when underlying Mongo finishes; cancelled calls write nothing', async () => {
|
|
const initial = new AbortController();
|
|
initial.abort(new Error('private abort reason'));
|
|
const f = fixture();
|
|
const early = await f.request({ metadata: source().metadata }, initial.signal);
|
|
expect(early.status).toBe(499);
|
|
expect(early.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(f.read).not.toHaveBeenCalled();
|
|
const controller = new AbortController();
|
|
let release: (() => void) | undefined;
|
|
const gate = new Promise<void>(resolve => {
|
|
release = resolve;
|
|
});
|
|
let entered: (() => void) | undefined;
|
|
const started = new Promise<void>(resolve => {
|
|
entered = resolve;
|
|
});
|
|
const slow = fixture(async () => {
|
|
entered?.();
|
|
await gate;
|
|
return source().rows;
|
|
});
|
|
const pending = slow.request({ metadata: source().metadata }, controller.signal);
|
|
await started;
|
|
controller.abort(new Error('private abort reason'));
|
|
if (!release) {
|
|
throw new Error('Missing fixture barrier');
|
|
}
|
|
release();
|
|
const late = await pending;
|
|
expect(late.status).toBe(499);
|
|
expect(late.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await late.text()).not.toContain('private abort reason');
|
|
expect(slow.read).toHaveBeenCalledTimes(1);
|
|
expect(slow.query).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('the focused adapter independently refuses wrong source, symbol, interpolation and out-of-range rows', async () => {
|
|
const input = source();
|
|
const f = fixture();
|
|
const baseline = await f.storage.getHistoricalBars(
|
|
'X0.US',
|
|
new Date(input.metadata.bounds.warmupStart),
|
|
new Date(input.metadata.bounds.tradeEnd),
|
|
'1m',
|
|
{ adjustment: 'raw', timestamp: 'utc-instant' },
|
|
undefined,
|
|
'eod'
|
|
);
|
|
const changes: Array<(row: HistoricalBar) => HistoricalBar> = [
|
|
row => ({ ...row, source: 'questdb' }),
|
|
row => ({ ...row, symbol: 'WRONG.US' }),
|
|
row => ({ ...row, interpolated: true }),
|
|
row => ({ ...row, timestamp: new Date(input.metadata.bounds.tradeEnd) }),
|
|
];
|
|
for (const change of changes) {
|
|
await expect(
|
|
prepareStoredDataset(
|
|
{ metadata: input.metadata },
|
|
{ getHistoricalBars: async () => [change(at(baseline))] },
|
|
new AbortController().signal
|
|
)
|
|
).rejects.toThrow('inconsistent bar identity or range');
|
|
}
|
|
});
|
|
|
|
test('actual stored adapter output preserves native next-open costs/equity and never reveals observations before interval end', async () => {
|
|
const input = source(),
|
|
f = fixture(async () => input.rows);
|
|
const captured = await prepareStoredDataset(
|
|
{ metadata: input.metadata },
|
|
f.storage,
|
|
new AbortController().signal
|
|
);
|
|
const dataset = createDatasetV2(captured.input);
|
|
let decisions = 0;
|
|
const { result } = runReplayConformance(
|
|
new NativeReplaySession(prepareReplayLoad(dataset, input.f.config)),
|
|
(_owner, context, observations) => {
|
|
decisions++;
|
|
expect(
|
|
observations.every(
|
|
bar => bar.available_at === bar.interval_end && bar.available_at <= context.barrier.at
|
|
)
|
|
).toBe(true);
|
|
return context.barrier.at === input.f.start + input.f.minute
|
|
? {
|
|
mode: 'target',
|
|
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
|
|
}
|
|
: { mode: 'target', targets: [] };
|
|
}
|
|
);
|
|
expect(decisions).toBe(2);
|
|
expect(String(result.view.portfolio.cash)).toBe('9975.76000000');
|
|
expect(String(result.view.equity)).toBe('10005.76000000');
|
|
expect<unknown>(result.view.portfolio.fees).toEqual([{ ownerId: 'A', amount: '0.24000000' }]);
|
|
});
|
|
|
|
test('mounted security denies read-token writes and untrusted browser origins', async () => {
|
|
const f = fixture();
|
|
const payload = JSON.stringify({ metadata: source().metadata });
|
|
const denied = await f.app.request('/api/v2/datasets/canonical/stored-source', {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: 'Bearer stored-source-read-fixture-not-a-real-secret',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: payload,
|
|
});
|
|
expect(denied.status).toBe(403);
|
|
const login = await f.app.request('/api/auth/session', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', Origin: 'http://localhost' },
|
|
body: JSON.stringify({ token }),
|
|
});
|
|
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
|
|
if (!cookie) {
|
|
throw new Error('Missing authenticated session');
|
|
}
|
|
const browser = (origin?: string) =>
|
|
f.app.request('/api/v2/datasets/canonical/stored-source', {
|
|
method: 'POST',
|
|
headers: {
|
|
Cookie: cookie,
|
|
'Content-Type': 'application/json',
|
|
...(origin ? { Origin: origin } : {}),
|
|
},
|
|
body: payload,
|
|
});
|
|
expect((await browser()).status).toBe(403);
|
|
expect((await browser('https://foreign.invalid')).status).toBe(403);
|
|
expect(f.read).not.toHaveBeenCalled();
|
|
expect((await browser('http://localhost')).status).toBe(200);
|
|
expect(f.read).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
function sessionSource() {
|
|
const input = source('5m');
|
|
const calendar = at(input.metadata.calendars);
|
|
const first = at(calendar.sessions);
|
|
first.close = input.metadata.bounds.tradeEnd;
|
|
const offset = 86400000;
|
|
const second = {
|
|
date: new Date(first.open + offset).toISOString().slice(0, 10),
|
|
open: first.open + offset,
|
|
close: first.close + offset,
|
|
};
|
|
calendar.sessions.push(second);
|
|
calendar.endDate = new Date(second.close + offset).toISOString().slice(0, 10);
|
|
input.metadata.bounds.tradeEnd = second.close;
|
|
at(input.metadata.corporateActions).end = second.close;
|
|
return {
|
|
...input,
|
|
rows: [
|
|
...input.rows,
|
|
...input.rows.map(row => ({ ...row, timestamp: row.timestamp + offset / 1000 })),
|
|
],
|
|
sessions: [first, second],
|
|
};
|
|
}
|
|
function filterRows(rows: Row[]) {
|
|
return async (_collection: string, filter: Record<string, unknown>) => {
|
|
const range = filter.timestamp as { $gte: number; $lt: number };
|
|
return rows.filter(row => row.timestamp >= range.$gte && row.timestamp < range.$lt);
|
|
};
|
|
}
|
|
|
|
describe('explicit declared-session stored preparation', () => {
|
|
const selection = 'declared-sessions' as const;
|
|
test('only explicit mode selects sessions, excluding an invalid close marker without post-filtering source rows', async () => {
|
|
const input = sessionSource();
|
|
const marker = {
|
|
...at(input.rows),
|
|
timestamp: at(input.sessions).close / 1000,
|
|
volume: null as unknown as number,
|
|
};
|
|
const rows = [...input.rows, marker];
|
|
const regular = fixture(filterRows(rows));
|
|
expect((await regular.request({ metadata: input.metadata })).status).toBe(500);
|
|
expect(regular.read).toHaveBeenCalledTimes(1);
|
|
const selected = fixture(filterRows(rows));
|
|
const response = await selected.request({ metadata: input.metadata, selection });
|
|
expect(response.status).toBe(200);
|
|
const captured = await response.json();
|
|
expect(captured.selection).toBe(selection);
|
|
expect(captured.input.bars.map((bar: { timestamp: number }) => bar.timestamp)).toEqual(
|
|
input.rows.map(row => row.timestamp * 1000)
|
|
);
|
|
expect(
|
|
captured.input.bars.map((bar: { sourceSequence: number }) => bar.sourceSequence)
|
|
).toEqual([0, 1, 2, 3, 4, 5]);
|
|
expect(selected.read.mock.calls.map(call => call[1].timestamp)).toEqual(
|
|
input.sessions.map(session => ({ $gte: session.open / 1000, $lt: session.close / 1000 }))
|
|
);
|
|
expect(selected.query).not.toHaveBeenCalled();
|
|
expect(selected.questdb.query).not.toHaveBeenCalled();
|
|
const repeated = await (await selected.request({ metadata: input.metadata, selection })).json();
|
|
expect(repeated.preparation.hash).toBe(captured.preparation.hash);
|
|
expect(captured.preparation).toEqual(previewDatasetPreparation({ input: captured.input }));
|
|
expect(rows).toContain(marker);
|
|
expect(marker.volume).toBeNull();
|
|
});
|
|
|
|
test('missing and invalid selected sessions fail the entire capture, including later failures', async () => {
|
|
for (const defect of ['missing', 'null-volume', 'ohlc', 'identity', 'duplicate'] as const) {
|
|
const input = sessionSource();
|
|
const last = at(input.rows, 3);
|
|
if (defect === 'missing') {
|
|
input.rows.splice(3);
|
|
}
|
|
if (defect === 'null-volume') {
|
|
last.volume = null as unknown as number;
|
|
}
|
|
if (defect === 'ohlc') {
|
|
last.high = last.low - 1;
|
|
}
|
|
if (defect === 'identity') {
|
|
last.symbol = 'WRONG';
|
|
}
|
|
if (defect === 'duplicate') {
|
|
input.rows.push({ ...last });
|
|
}
|
|
const f = fixture(filterRows(input.rows));
|
|
const response = await f.request({ metadata: input.metadata, selection });
|
|
expect(response.status).toBe(defect === 'missing' ? 404 : 500);
|
|
expect(await response.json()).not.toHaveProperty('input');
|
|
expect(f.read).toHaveBeenCalledTimes(2);
|
|
expect(f.query).not.toHaveBeenCalled();
|
|
}
|
|
});
|
|
|
|
test('empty intersections and unsupported selection reject before any source read', async () => {
|
|
const input = sessionSource();
|
|
const f = fixture();
|
|
input.metadata.bounds.warmupStart = at(input.sessions).close;
|
|
input.metadata.bounds.tradeStart = at(input.sessions).close;
|
|
input.metadata.bounds.tradeEnd = at(input.sessions, 1).open;
|
|
expect((await f.request({ metadata: input.metadata, selection })).status).toBe(422);
|
|
expect((await f.request({ metadata: input.metadata, selection: 'regular-hours' })).status).toBe(
|
|
400
|
|
);
|
|
expect((await f.request({ metadata: input.metadata, selection: null })).status).toBe(400);
|
|
expect(f.read).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('declared DST instants, early close and clipped bounds are exact; sparse nonempty sessions remain allowed', async () => {
|
|
const input = sessionSource();
|
|
const calendar = at(input.metadata.calendars);
|
|
calendar.timeZone = 'America/New_York';
|
|
calendar.startDate = '2024-03-08';
|
|
calendar.endDate = '2024-03-12';
|
|
calendar.sessions = [
|
|
{
|
|
date: '2024-03-08',
|
|
open: Date.parse('2024-03-08T14:30:00Z'),
|
|
close: Date.parse('2024-03-08T18:00:00Z'),
|
|
},
|
|
{
|
|
date: '2024-03-11',
|
|
open: Date.parse('2024-03-11T13:30:00Z'),
|
|
close: Date.parse('2024-03-11T20:00:00Z'),
|
|
},
|
|
];
|
|
input.metadata.bounds = {
|
|
warmupStart: Date.parse('2024-03-08T14:35:00Z'),
|
|
tradeStart: Date.parse('2024-03-08T14:40:00Z'),
|
|
tradeEnd: Date.parse('2024-03-11T13:40:00Z'),
|
|
};
|
|
at(input.metadata.corporateActions).start = input.metadata.bounds.warmupStart;
|
|
at(input.metadata.corporateActions).end = input.metadata.bounds.tradeEnd;
|
|
input.metadata.universe.asOf = input.metadata.bounds.warmupStart;
|
|
const rows = [
|
|
{ ...at(input.rows), timestamp: input.metadata.bounds.warmupStart / 1000 },
|
|
{ ...at(input.rows), timestamp: Date.parse('2024-03-11T13:30:00Z') / 1000 },
|
|
];
|
|
const f = fixture(filterRows(rows));
|
|
const response = await f.request({ metadata: input.metadata, selection });
|
|
expect(response.status).toBe(200);
|
|
expect(f.read.mock.calls.map(call => call[1].timestamp)).toEqual([
|
|
{
|
|
$gte: Date.parse('2024-03-08T14:35:00Z') / 1000,
|
|
$lt: Date.parse('2024-03-08T18:00:00Z') / 1000,
|
|
},
|
|
{
|
|
$gte: Date.parse('2024-03-11T13:30:00Z') / 1000,
|
|
$lt: Date.parse('2024-03-11T13:40:00Z') / 1000,
|
|
},
|
|
]);
|
|
expect((await response.json()).input.bars).toHaveLength(2);
|
|
});
|
|
|
|
test('a selected bar crossing session close or clipped trading end is rejected rather than shortened or dropped', async () => {
|
|
for (const boundary of ['close', 'tradeEnd'] as const) {
|
|
const input = sessionSource();
|
|
if (boundary === 'close') {
|
|
at(at(input.metadata.calendars).sessions).close -= 30000;
|
|
} else {
|
|
input.metadata.bounds.tradeEnd -= 30000;
|
|
}
|
|
const f = fixture(filterRows(input.rows));
|
|
const response = await f.request({ metadata: input.metadata, selection });
|
|
expect(response.status).toBe(422);
|
|
expect(await response.json()).not.toHaveProperty('input');
|
|
expect(f.read.mock.calls[0]?.[1].timestamp).toEqual({
|
|
$gte: at(input.sessions).open / 1000,
|
|
$lt: at(input.sessions).close / 1000,
|
|
});
|
|
}
|
|
});
|
|
|
|
test('each adapter response must belong to its own session and empty responses cannot be skipped', async () => {
|
|
const input = sessionSource();
|
|
const base = fixture(filterRows(input.rows));
|
|
const bars = await base.storage.getHistoricalBars(
|
|
'X0.US',
|
|
new Date(input.metadata.bounds.warmupStart),
|
|
new Date(input.metadata.bounds.tradeEnd),
|
|
'5m',
|
|
{ adjustment: 'raw', timestamp: 'utc-instant' },
|
|
undefined,
|
|
'eod'
|
|
);
|
|
const wrong = mock(async () => [at(bars, 3)]);
|
|
await expect(
|
|
prepareStoredDataset(
|
|
{ metadata: input.metadata, selection },
|
|
{ getHistoricalBars: wrong },
|
|
new AbortController().signal
|
|
)
|
|
).rejects.toThrow('inconsistent bar identity or range');
|
|
expect(wrong).toHaveBeenCalledTimes(1);
|
|
await expect(
|
|
prepareStoredDataset(
|
|
{ metadata: input.metadata, selection },
|
|
{ getHistoricalBars: async () => [] },
|
|
new AbortController().signal
|
|
)
|
|
).rejects.toMatchObject({ status: 404 });
|
|
});
|
|
|
|
test('metadata and earlier rows are captured before subsequent reads can mutate them', async () => {
|
|
const input = sessionSource();
|
|
const base = fixture(filterRows(input.rows));
|
|
const bars = await base.storage.getHistoricalBars(
|
|
'X0.US',
|
|
new Date(input.metadata.bounds.warmupStart),
|
|
new Date(input.metadata.bounds.tradeEnd),
|
|
'5m',
|
|
{ adjustment: 'raw', timestamp: 'utc-instant' },
|
|
undefined,
|
|
'eod'
|
|
);
|
|
const expected = structuredClone(input.metadata);
|
|
const firstTimestamp = at(bars).timestamp.getTime();
|
|
let calls = 0;
|
|
const read = mock(async () => {
|
|
calls++;
|
|
if (calls === 1) {
|
|
return bars.slice(0, 3);
|
|
}
|
|
at(bars).timestamp.setTime(0);
|
|
at(bars).close = 999;
|
|
at(input.metadata.calendars).sessions = [];
|
|
await Promise.resolve();
|
|
return bars.slice(3);
|
|
});
|
|
const result = await prepareStoredDataset(
|
|
{ metadata: input.metadata, selection },
|
|
{ getHistoricalBars: read },
|
|
new AbortController().signal
|
|
);
|
|
expect(result.input.metadata).toEqual(expected);
|
|
expect(at(result.input.bars).timestamp).toBe(firstTimestamp);
|
|
expect(at(result.input.bars).close).toBe(11);
|
|
expect(result.preparation).toEqual(previewDatasetPreparation({ input: result.input }));
|
|
expect(Object.isFrozen(at(result.input.bars))).toBe(true);
|
|
});
|
|
|
|
test('cancellation after one read prevents every later session read', async () => {
|
|
const input = sessionSource();
|
|
const controller = new AbortController();
|
|
const f = fixture(async (_collection, filter) => {
|
|
const rows = await filterRows(input.rows)('', filter);
|
|
controller.abort();
|
|
return rows;
|
|
});
|
|
expect(
|
|
(await f.request({ metadata: input.metadata, selection }, controller.signal)).status
|
|
).toBe(499);
|
|
expect(f.read).toHaveBeenCalledTimes(1);
|
|
expect(f.query).not.toHaveBeenCalled();
|
|
});
|
|
});
|