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

220 lines
7.5 KiB
TypeScript

import { z } from 'zod';
import {
costSensitivityInputSchema,
type CostSensitivityInput,
type CostSensitivitySubmission,
} from '@stock-bot/stock-config/cost-sensitivity';
import {
experimentRetrySchema,
type ExperimentInput,
type ExperimentRetryInput,
type ExperimentSubmission,
type ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import {
ExperimentApiError,
invalidExperimentResponse as invalid,
parseCostSensitivityPreview,
parseExperimentDetail,
parseExperimentPreview,
parseExperimentSummary as parseSummary,
parseWorkbenchExperimentDetail,
experimentRetryReceiptSchema as retryReceipt,
sameExperimentInput as same,
type ExperimentRetryTarget,
} from '@stock-bot/stock-config/research-responses';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export {
ExperimentApiError,
experimentMetricsSchema,
parseCostSensitivityPreview,
parseExperimentDetail,
parseExperimentPreview,
parseWorkbenchExperimentDetail,
type CostSensitivityDetailView,
type CostSensitivityPreviewView,
type ExperimentDetailView,
type ExperimentPreviewView,
type ExperimentRetryTarget,
type WorkbenchExperimentDetailView,
type WorkbenchExperimentPreviewView,
} from '@stock-bot/stock-config/research-responses';
function request<T>(
path: string,
init: RequestInit,
status: number,
parse: (body: unknown) => T
): Promise<T> {
return requestJson(`${API_BASE_URL}/api/v2/experiments${path}`, init, status, parse, {
create: (message, code) => new ExperimentApiError(message, code),
invalid,
lostMessage:
'The experiment response was lost. Retry the same submission to check whether it was accepted.',
failureLabel: 'Experiment request failed',
});
}
const envelope = (body: unknown, field: string): unknown =>
z.record(z.unknown()).parse(body)[field];
const json = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
export const experimentApi = {
costPreview: (input: CostSensitivityInput, signal?: AbortSignal) =>
request(
'/cost-sensitivity/preview',
{ ...json(costSensitivityInputSchema.parse(input)), signal },
200,
body => {
const value = parseCostSensitivityPreview(envelope(body, 'preview'));
if (!same(value.input, costSensitivityInputSchema.parse(input))) {
throw invalid();
}
return value;
}
),
costSubmit: (input: CostSensitivitySubmission, key: string) =>
request(
'/cost-sensitivity',
{ ...json(input), headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key } },
202,
body => {
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
const { previewHash, ...original } = input;
if (
value.preview.version !== 'cost-sensitivity-preview/v1' ||
value.previewHash !== previewHash ||
!same(value.preview.input, costSensitivityInputSchema.parse(original))
) {
throw invalid();
}
return value;
}
),
retryTrial: (target: ExperimentRetryTarget, input: ExperimentRetryInput, key: string) =>
request(
`/${encodeURIComponent(target.experimentId)}/trials/${encodeURIComponent(target.runId)}/retry`,
{
...json(experimentRetrySchema.parse(input)),
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
},
202,
body => {
const receipt = retryReceipt.parse(envelope(body, 'retry'));
const experiment = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
const current = experiment.trials.find(
item => item.trialKey === target.trialKey && item.runId === target.runId
);
if (
receipt.experimentId !== target.experimentId ||
receipt.runId !== target.runId ||
receipt.trialKey !== target.trialKey ||
receipt.retryNumber !== input.expectedRetryCount + 1 ||
receipt.previousAttemptNumber !== input.expectedAttemptNumber ||
experiment.id !== target.experimentId ||
experiment.backtestId !== target.backtestId ||
experiment.previewHash !== target.previewHash ||
(receipt.reviewId === null &&
experiment.preview.request.strategy.origin !== 'candidate') ||
!current ||
current.retryCount < receipt.retryNumber ||
current.attemptNumber < receipt.previousAttemptNumber
) {
throw invalid();
}
// Receipt replay may return a newer failed/completed/cancelled state. The original receipt remains success.
return { retry: receipt as ExperimentTrialRetry, experiment };
}
),
retryHistory: (
experimentId: string,
runId: string,
trialKey: string,
signal?: AbortSignal,
origin: 'builtin' | 'candidate' = 'builtin'
) =>
request(
`/${encodeURIComponent(experimentId)}/trials/${encodeURIComponent(runId)}/retries`,
{ signal },
200,
body => {
const rows = z.array(retryReceipt).parse(envelope(body, 'retries'));
if (
new Set(rows.map(item => item.id)).size !== rows.length ||
rows.some(
(item, index) =>
item.experimentId !== experimentId ||
item.runId !== runId ||
item.trialKey !== trialKey ||
(item.reviewId === null && origin !== 'candidate') ||
item.retryNumber !== index + 1
)
) {
throw invalid();
}
return rows as ExperimentTrialRetry[];
}
),
list: (backtestId?: string, signal?: AbortSignal) =>
request(
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
{ signal },
200,
body => {
const rows = z.array(z.unknown()).parse(envelope(body, 'experiments')).map(parseSummary);
if (
new Set(rows.map(row => row.id)).size !== rows.length ||
(backtestId && rows.some(row => row.backtestId !== backtestId))
) {
throw invalid();
}
return rows;
}
),
preview: (input: ExperimentInput, signal?: AbortSignal) =>
request('/preview', { ...json(input), signal }, 200, body => {
const value = parseExperimentPreview(envelope(body, 'preview'));
if (!same(value.input, input)) {
throw invalid();
}
return value;
}),
create: (input: ExperimentSubmission, key: string) =>
request(
'',
{
...json(input),
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
},
202,
body => {
const value = parseExperimentDetail(envelope(body, 'experiment'));
const { previewHash, ...original } = input;
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
throw invalid();
}
return value;
}
),
get: (id: string, signal?: AbortSignal) =>
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
if (value.id !== id) {
throw invalid();
}
return value;
}),
cancel: (id: string) =>
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
if (value.id !== id || !value.cancelRequested) {
throw invalid();
}
return value;
}),
};