stock-bot/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts

122 lines
4.4 KiB
TypeScript

import { z } from 'zod';
import {
type ChronologicalValidationActionReceipt,
type ChronologicalValidationFinalizationInput,
type ChronologicalValidationSelectionInput,
type ChronologicalValidationSubmission,
type ChronologicalValidationSummary,
type ValidationResultEvidence,
} from '@stock-bot/stock-config/chronological-validation';
import {
invalidValidationResponse as invalid,
parseValidationDetail,
validationReceiptSchema as receipt,
sameValidationInput as same,
validationSummarySchema as summary,
ValidationApiError,
} from '@stock-bot/stock-config/research-responses';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export {
parseValidationDetail,
ValidationApiError,
validationEvidenceSchema,
type ValidationDetailView,
} from '@stock-bot/stock-config/research-responses';
export type { ValidationResultEvidence };
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
function request<T>(
path: string,
init: RequestInit,
status: number,
parse: (body: unknown) => T
): Promise<T> {
return requestJson(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init, status, parse, {
create: (message, code) => new ValidationApiError(message, code),
invalid,
lostMessage: 'The validation response was lost. Retry the same request to recover its receipt.',
failureLabel: 'Validation request failed',
});
}
const post = (body: unknown, key?: string): RequestInit => ({
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
});
export const chronologicalValidationDurableApi = {
list: (backtestId?: string, signal?: AbortSignal) =>
request(
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
{ signal },
200,
body => {
const rows = z.array(summary).parse(envelope(body, 'validations'));
if (
new Set(rows.map(row => row.id)).size !== rows.length ||
(backtestId && rows.some(row => row.backtestId !== backtestId))
) {
throw invalid();
}
return rows as ChronologicalValidationSummary[];
}
),
get: (id: string, signal?: AbortSignal) =>
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
const value = parseValidationDetail(envelope(body, 'validation'));
if (value.id !== id) {
throw invalid();
}
return value;
}),
submit: (input: ChronologicalValidationSubmission, key: string) =>
request('', post(input, key), 202, body => {
const value = parseValidationDetail(envelope(body, 'validation'));
const { previewHash, ...original } = input;
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
throw invalid();
}
return value;
}),
advance: (
id: string,
operation: 'select' | 'finalize',
input: ChronologicalValidationSelectionInput | ChronologicalValidationFinalizationInput,
key: string
) =>
request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => {
const accepted = receipt.parse(envelope(body, 'receipt'));
const value = parseValidationDetail(envelope(body, 'validation'));
const record = operation === 'select' ? value.selection : value.report;
if (
accepted.validationId !== id ||
value.id !== id ||
accepted.previewHash !== input.previewHash ||
value.previewHash !== input.previewHash ||
accepted.operation !==
(operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report') ||
accepted.selectionHash !== value.selection?.selectionHash ||
!record ||
accepted.id !== record.id ||
accepted.createdAt !== record.createdAt ||
accepted.principal !== record.principal ||
(operation === 'finalize' &&
(!('selectionHash' in input) ||
accepted.selectionHash !== input.selectionHash ||
!value.report))
) {
throw invalid();
}
return { receipt: accepted as ChronologicalValidationActionReceipt, validation: value };
}),
cancel: (id: string) =>
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
const value = parseValidationDetail(envelope(body, 'validation'));
if (value.id !== id || !value.cancelRequested) {
throw invalid();
}
return value;
}),
};