feat(research): inspect scoped stored market data (RP01)
This commit is contained in:
parent
b4ac6460ef
commit
5bfaf37d08
12 changed files with 1592 additions and 3 deletions
240
test/integration/stored-source-inspection.test.ts
Normal file
240
test/integration/stored-source-inspection.test.ts
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
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 } from '@stock-bot/services';
|
||||
import {
|
||||
storedSourceCoverageSchema,
|
||||
storedSourceInspectionSchema,
|
||||
} from '@stock-bot/stock-config/stored-source';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import {
|
||||
inspectStoredSource,
|
||||
storedSourceCoverage,
|
||||
} from '../../apps/stock/web-api/src/services/stored-source-inspection';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('source-inspection-test');
|
||||
const start = Date.parse('2024-10-01T13:30:00Z');
|
||||
const selection = { instrumentId: 'AAPL.US', interval: '5m' } as const;
|
||||
const coveragePath = 'coverage?instrumentId=AAPL.US&interval=5m';
|
||||
const query = { ...selection, start, end: start + 900000 };
|
||||
const row = {
|
||||
eodSearchCode: 'AAPL.US',
|
||||
symbol: 'AAPL',
|
||||
exchange: 'US',
|
||||
timestamp: start / 1000,
|
||||
open: 10,
|
||||
high: 12,
|
||||
low: 9,
|
||||
close: 11,
|
||||
volume: 100,
|
||||
};
|
||||
function fixture(rows: Record<string, unknown>[] = [row]) {
|
||||
const find = mock(async () => structuredClone(rows));
|
||||
const aggregate = mock(async (collection: string, _pipeline: Record<string, unknown>[]) =>
|
||||
collection === 'eodIntraday5M'
|
||||
? [
|
||||
{
|
||||
_id: null,
|
||||
rowCount: 4,
|
||||
firstTimestamp: start / 1000,
|
||||
lastTimestamp: start / 1000 + 600,
|
||||
invalidTimestampRows: 1,
|
||||
},
|
||||
]
|
||||
: []
|
||||
);
|
||||
const database = mock(async () => {
|
||||
throw new Error('No PostgreSQL writes or reads allowed');
|
||||
});
|
||||
const store = { find, aggregate } as unknown as MongoDBClient;
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: 'source-admin-fixture-not-a-real-secret',
|
||||
serviceToken: 'source-service-fixture-not-a-real-secret',
|
||||
readToken: 'source-read-fixture-not-a-real-secret',
|
||||
environment: 'test',
|
||||
browserSessions: true,
|
||||
}).mount(app);
|
||||
app.route(
|
||||
'/',
|
||||
createDatasetRoutes({
|
||||
logger,
|
||||
mongodb: store,
|
||||
postgres: { query: database },
|
||||
} as unknown as IServiceContainer)
|
||||
);
|
||||
const request = (
|
||||
path: string,
|
||||
body?: unknown,
|
||||
token: string | null = 'source-admin-fixture-not-a-real-secret',
|
||||
signal?: AbortSignal
|
||||
) =>
|
||||
app.request(`/api/v2/datasets/stored-eod/${path}`, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
headers: {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
signal,
|
||||
});
|
||||
return { store, app, find, aggregate, database, request };
|
||||
}
|
||||
describe('stored EOD source discovery and diagnostics', () => {
|
||||
test('coverage reads only the explicitly selected instrument and collection with an indexable first match', async () => {
|
||||
const f = fixture();
|
||||
const response = await f.request(coveragePath);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
const value = storedSourceCoverageSchema.parse(await response.json());
|
||||
expect(value.series).toEqual([
|
||||
{
|
||||
instrumentId: 'AAPL.US',
|
||||
interval: '5m',
|
||||
rowCount: 4,
|
||||
firstTimestamp: start,
|
||||
lastTimestamp: start + 600000,
|
||||
invalidTimestampRows: 1,
|
||||
},
|
||||
]);
|
||||
expect(value.query).toEqual(selection);
|
||||
expect(f.aggregate).toHaveBeenCalledTimes(1);
|
||||
expect(f.aggregate.mock.calls[0]?.[0]).toBe('eodIntraday5M');
|
||||
expect(f.aggregate.mock.calls[0]?.[1]?.[0]).toEqual({ $match: { eodSearchCode: 'AAPL.US' } });
|
||||
expect(f.find).not.toHaveBeenCalled();
|
||||
expect(f.database).not.toHaveBeenCalled();
|
||||
});
|
||||
test('coverage requires an exact selection before any store access and preserves an empty selected series', async () => {
|
||||
const f = fixture();
|
||||
for (const path of [
|
||||
'coverage',
|
||||
'coverage?instrumentId=AAPL.US',
|
||||
'coverage?instrumentId=AAPL&interval=5m',
|
||||
'coverage?instrumentId=AAPL.US&interval=15m',
|
||||
'coverage?instrumentId=AAPL.US&interval=5m&all=true',
|
||||
]) {
|
||||
expect((await f.request(path)).status).toBe(400);
|
||||
}
|
||||
expect(f.aggregate).not.toHaveBeenCalled();
|
||||
f.aggregate.mockImplementation(async () => []);
|
||||
expect(await (await f.request(coveragePath)).json()).toMatchObject({
|
||||
query: selection,
|
||||
series: [],
|
||||
});
|
||||
expect(f.aggregate).toHaveBeenCalledTimes(1);
|
||||
expect(f.database).not.toHaveBeenCalled();
|
||||
});
|
||||
test('field problems, identity and duplicate rows remain visible without altering source prices', async () => {
|
||||
const rows = [
|
||||
row,
|
||||
{ ...row, volume: null },
|
||||
{ ...row, timestamp: start / 1000 + 300, close: 100 },
|
||||
{ ...row, timestamp: start / 1000 + 600, exchange: 'OTHER', volume: -1 },
|
||||
{ ...row, timestamp: 'not-an-instant' },
|
||||
{ ...row, timestamp: query.end / 1000 },
|
||||
];
|
||||
const before = structuredClone(rows);
|
||||
const f = fixture(rows);
|
||||
const response = await f.request('inspect', query);
|
||||
expect(response.status).toBe(200);
|
||||
const value = storedSourceInspectionSchema.parse(await response.json());
|
||||
expect(value).toMatchObject({
|
||||
query,
|
||||
rowCount: 6,
|
||||
invalidRows: 6,
|
||||
nullVolumeRows: 1,
|
||||
duplicateRows: 1,
|
||||
firstTimestamp: start,
|
||||
lastTimestamp: query.end,
|
||||
});
|
||||
expect(value.issues.map(issue => issue.code)).toEqual([
|
||||
'null-volume',
|
||||
'invalid-prices',
|
||||
'identity-mismatch',
|
||||
'invalid-volume',
|
||||
'invalid-timestamp',
|
||||
'outside-range',
|
||||
'duplicate-timestamp',
|
||||
]);
|
||||
expect(value.issues.find(issue => issue.code === 'duplicate-timestamp')).toMatchObject({
|
||||
rowCount: 2,
|
||||
timestamps: [start, start],
|
||||
});
|
||||
expect(value.days).toEqual([{ date: '2024-10-01', rowCount: 5, invalidRows: 5 }]);
|
||||
expect(rows).toEqual(before);
|
||||
expect(f.database).not.toHaveBeenCalled();
|
||||
expect(f.find.mock.calls[0]?.slice(0, 2)).toMatchObject([
|
||||
'eodIntraday5M',
|
||||
{ eodSearchCode: 'AAPL.US', timestamp: { $gte: start / 1000, $lt: query.end / 1000 } },
|
||||
]);
|
||||
});
|
||||
test('invalid queries reject before any store access; supported empty windows are explicit', async () => {
|
||||
const f = fixture([]);
|
||||
for (const invalid of [
|
||||
{ ...query, end: start },
|
||||
{ ...query, interval: '15m' },
|
||||
{ ...query, instrumentId: 'AAPL' },
|
||||
{ ...query, start: 1.5 },
|
||||
{ ...query, extra: true },
|
||||
]) {
|
||||
expect((await f.request('inspect', invalid)).status).toBe(400);
|
||||
}
|
||||
expect(f.find).not.toHaveBeenCalled();
|
||||
const empty = await f.request('inspect', query);
|
||||
expect(await empty.json()).toMatchObject({
|
||||
rowCount: 0,
|
||||
invalidRows: 0,
|
||||
firstTimestamp: null,
|
||||
lastTimestamp: null,
|
||||
days: [],
|
||||
issues: [],
|
||||
});
|
||||
});
|
||||
test('ordinary authentication roles remain enforced and source failures are sanitized', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request(coveragePath, undefined, null)).status).toBe(401);
|
||||
expect(
|
||||
(await f.request(coveragePath, undefined, 'source-read-fixture-not-a-real-secret')).status
|
||||
).toBe(200);
|
||||
expect(
|
||||
(await f.request('inspect', query, 'source-read-fixture-not-a-real-secret')).status
|
||||
).toBe(403);
|
||||
expect(f.find).not.toHaveBeenCalled();
|
||||
f.find.mockImplementation(async () => {
|
||||
throw new Error('private transport detail');
|
||||
});
|
||||
const failure = await f.request('inspect', query);
|
||||
expect(failure.status).toBe(500);
|
||||
expect(await failure.json()).toEqual({ error: 'Stored source inspection unavailable' });
|
||||
});
|
||||
test('absent storage is unavailable and cancellation fences queries and returned data', async () => {
|
||||
const abort = new AbortController();
|
||||
abort.abort(new Error('cancelled'));
|
||||
const f = fixture();
|
||||
await expect(inspectStoredSource(f.store, query, abort.signal)).rejects.toThrow('cancelled');
|
||||
await expect(storedSourceCoverage(f.store, selection, abort.signal)).rejects.toThrow(
|
||||
'cancelled'
|
||||
);
|
||||
expect(f.find).not.toHaveBeenCalled();
|
||||
expect(f.aggregate).not.toHaveBeenCalled();
|
||||
await expect(
|
||||
inspectStoredSource(null, query, new AbortController().signal)
|
||||
).rejects.toMatchObject({ status: 503 });
|
||||
const during = new AbortController();
|
||||
f.find.mockImplementation(async () => {
|
||||
during.abort(new Error('during query'));
|
||||
return [row];
|
||||
});
|
||||
await expect(inspectStoredSource(f.store, query, during.signal)).rejects.toThrow(
|
||||
'during query'
|
||||
);
|
||||
const httpAbort = new AbortController();
|
||||
f.find.mockImplementation(async () => {
|
||||
httpAbort.abort();
|
||||
return [row];
|
||||
});
|
||||
expect((await f.request('inspect', query, undefined, httpAbort.signal)).status).toBe(499);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue