refactor(api): validate shared product response contracts (CL25)
This commit is contained in:
parent
e2292e4883
commit
366a6054bf
22 changed files with 989 additions and 451 deletions
|
|
@ -18,50 +18,25 @@ import type {
|
|||
CanonicalStoredSourcePreparation,
|
||||
ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
backtestResponseSchema,
|
||||
runResponseSchema,
|
||||
type BacktestResponse as Backtest,
|
||||
type RunResponse as Run,
|
||||
} from '@stock-bot/stock-config/product-responses';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
HistoricalDatasetCatalogEntry,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
name: string;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
config: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
archivedAt: string | null;
|
||||
}
|
||||
|
||||
export interface Run {
|
||||
id: string;
|
||||
originalRunId?: string | null;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
speedMultiplier: number | null;
|
||||
error?: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
pausedAt?: string;
|
||||
progress: number;
|
||||
cancelRequested?: boolean;
|
||||
attemptNumber?: number;
|
||||
currentSimulationDate?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
dataset?: BacktestRunDatasetSelection;
|
||||
}
|
||||
export type {
|
||||
BacktestResponse as Backtest,
|
||||
RunResponse as Run,
|
||||
} from '@stock-bot/stock-config/product-responses';
|
||||
|
||||
export interface CreateBacktestRequest {
|
||||
name: string;
|
||||
|
|
@ -112,6 +87,28 @@ export class ReproductionSubmissionError extends Error {
|
|||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
function productRequest<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, parse, {
|
||||
create: message => new Error(message),
|
||||
invalid: () =>
|
||||
new Error(
|
||||
'The backtest response could not be verified. Check saved runs before submitting again.'
|
||||
),
|
||||
lostMessage: 'The backtest response was lost. Check saved runs before submitting again.',
|
||||
failureLabel: 'Backtest request failed',
|
||||
});
|
||||
}
|
||||
const jsonRequest = (method: string, body: unknown): RequestInit => ({
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const acknowledgement = z.object({ message: z.string() });
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
const nullableText = (value: unknown) => value === null || typeof value === 'string';
|
||||
|
|
@ -456,45 +453,33 @@ export const backtestApiV2 = {
|
|||
};
|
||||
},
|
||||
async reproduceRun(originalRunId: string, submissionKey: string): Promise<Run> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
|
||||
body: '{}',
|
||||
return requestJson(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
|
||||
body: '{}',
|
||||
},
|
||||
202,
|
||||
body => {
|
||||
const run = runResponseSchema.parse(body);
|
||||
if (run.id === originalRunId || run.originalRunId !== originalRunId) {
|
||||
throw new Error('Wrong original run identity');
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
|
||||
null
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = await requestError(response, 'Could not reproduce original run');
|
||||
throw new ReproductionSubmissionError(error.message, response.status);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (
|
||||
response.status !== 202 ||
|
||||
!isRecord(body) ||
|
||||
typeof body.id !== 'string' ||
|
||||
!body.id ||
|
||||
body.id === originalRunId ||
|
||||
typeof body.backtestId !== 'string' ||
|
||||
body.originalRunId !== originalRunId ||
|
||||
!['pending', 'running', 'completed', 'failed', 'cancelled', 'paused'].includes(
|
||||
String(body.status)
|
||||
)
|
||||
) {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The accepted reproduction response could not be verified. Retry with this same submission key.',
|
||||
null
|
||||
);
|
||||
}
|
||||
return body as unknown as Run;
|
||||
return run;
|
||||
},
|
||||
{
|
||||
create: (message, status) => new ReproductionSubmissionError(message, status),
|
||||
invalid: () =>
|
||||
new ReproductionSubmissionError(
|
||||
'The accepted reproduction response could not be verified. Retry with this same submission key.',
|
||||
null
|
||||
),
|
||||
lostMessage:
|
||||
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
|
||||
failureLabel: 'Could not reproduce original run',
|
||||
}
|
||||
);
|
||||
},
|
||||
async reproductionComparison(
|
||||
id: string,
|
||||
|
|
@ -636,130 +621,95 @@ export const backtestApiV2 = {
|
|||
}
|
||||
return (await response.json()).dataset;
|
||||
},
|
||||
// Backtest operations
|
||||
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
// Web saves are deliberately separate from durable run submission.
|
||||
body: JSON.stringify({ ...request, autoStart: false }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to create backtest');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
// Templates are saved separately from durable run submission.
|
||||
createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
|
||||
return productRequest(
|
||||
'backtests',
|
||||
jsonRequest('POST', { ...request, autoStart: false }),
|
||||
201,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
|
||||
async getBacktest(id: string): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get backtest: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
getBacktest(id: string): Promise<Backtest> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}`,
|
||||
{},
|
||||
200,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
|
||||
async listBacktests(
|
||||
listBacktests(
|
||||
limit = 50,
|
||||
offset = 0,
|
||||
includeArchived = false,
|
||||
signal?: AbortSignal
|
||||
): Promise<Backtest[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
|
||||
{ signal }
|
||||
return productRequest(
|
||||
`backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
|
||||
{ signal },
|
||||
200,
|
||||
backtestResponseSchema.array().parse
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to list backtests');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}`,
|
||||
jsonRequest('PUT', updates),
|
||||
200,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
deleteBacktest(id: string): Promise<void> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}`,
|
||||
{ method: 'DELETE' },
|
||||
204,
|
||||
z.undefined().parse
|
||||
);
|
||||
},
|
||||
setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}/archive`,
|
||||
jsonRequest('POST', { archived }),
|
||||
200,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
createRun(backtestId: string, request?: CreateRunRequest, submissionKey?: string): Promise<Run> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(backtestId)}/runs`,
|
||||
{
|
||||
...jsonRequest('POST', request || {}),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
|
||||
},
|
||||
},
|
||||
body: JSON.stringify(updates),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to update backtest');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
202,
|
||||
body => {
|
||||
const run = runResponseSchema.parse(body);
|
||||
if (run.backtestId !== backtestId) {
|
||||
throw new Error('Wrong backtest identity');
|
||||
}
|
||||
return run;
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async deleteBacktest(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to delete backtest');
|
||||
}
|
||||
listRuns(backtestId: string): Promise<Run[]> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(backtestId)}/runs`,
|
||||
{},
|
||||
200,
|
||||
runResponseSchema.array().parse
|
||||
);
|
||||
},
|
||||
|
||||
async setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}/archive`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ archived }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to change archive status');
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
|
||||
// Run operations
|
||||
async createRun(
|
||||
backtestId: string,
|
||||
request?: CreateRunRequest,
|
||||
submissionKey?: string
|
||||
): Promise<Run> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
|
||||
},
|
||||
body: JSON.stringify(request || {}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to create run');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
async listRuns(backtestId: string): Promise<Run[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to list runs: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
async getRun(id: string, signal?: AbortSignal): Promise<Run> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`, { signal });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get run: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
getRun(id: string, signal?: AbortSignal): Promise<Run> {
|
||||
return productRequest(
|
||||
`runs/${encodeURIComponent(id)}`,
|
||||
{ signal },
|
||||
200,
|
||||
runResponseSchema.parse
|
||||
);
|
||||
},
|
||||
|
||||
async getRunResults(runId: string, signal?: AbortSignal): Promise<ResearchRunResult> {
|
||||
|
|
@ -777,48 +727,36 @@ export const backtestApiV2 = {
|
|||
},
|
||||
|
||||
async pauseRun(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to pause run: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/pause`,
|
||||
{ method: 'POST' },
|
||||
200,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
async resumeRun(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to resume run: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/resume`,
|
||||
{ method: 'POST' },
|
||||
200,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
async cancelRun(id: string, signal?: AbortSignal): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
|
||||
method: 'POST',
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to cancel run: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/cancel`,
|
||||
{ method: 'POST', signal },
|
||||
202,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ speedMultiplier }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to update run speed: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/speed`,
|
||||
jsonRequest('PUT', { speedMultiplier }),
|
||||
200,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
// Note: WebSocket connections are handled by the useWebSocket hook
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue