296 lines
10 KiB
TypeScript
296 lines
10 KiB
TypeScript
import { Hono, type MiddlewareHandler } from 'hono';
|
|
import { z } from 'zod';
|
|
import { getResearchHttpPrincipal } from '@stock-bot/di';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import type { IServiceContainer } from '@stock-bot/services';
|
|
import { isResearchAgent } from '@stock-bot/types';
|
|
import {
|
|
parseCostSensitivityInput,
|
|
parseCostSensitivitySubmission,
|
|
} from '../services/cost-sensitivity-input';
|
|
import {
|
|
ExperimentError,
|
|
experimentId,
|
|
experimentReceipt,
|
|
parseExperimentInput,
|
|
parseExperimentSubmission,
|
|
} from '../services/experiment-input';
|
|
import { parseExperimentRetry } from '../services/experiment-retry';
|
|
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
|
|
import { createResearchServices, type ResearchServices } from '../services/research-services';
|
|
import {
|
|
parseValidationFinalization,
|
|
parseValidationSelection,
|
|
parseValidationSubmission,
|
|
} from '../services/validation-evidence';
|
|
import { parseChronologicalValidation } from '../services/validation-preview';
|
|
import {
|
|
parseWalkForwardFinalization,
|
|
parseWalkForwardInput,
|
|
parseWalkForwardSubmission,
|
|
} from '../services/walk-forward-input';
|
|
|
|
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
|
|
export function createExperimentRoutes(
|
|
container: IServiceContainer,
|
|
services: Pick<
|
|
ResearchServices,
|
|
'experiments' | 'validations' | 'walkForwards'
|
|
> = createResearchServices(container)
|
|
) {
|
|
const app = new Hono();
|
|
const { experiments: service, validations, walkForwards } = services;
|
|
const logger = getLogger('experiments-api');
|
|
const credentials: MiddlewareHandler = async (c, next) => {
|
|
c.header('Cache-Control', 'no-store');
|
|
if (!['GET', 'HEAD'].includes(c.req.method) && !getResearchHttpPrincipal(c.req.raw)) {
|
|
return c.json({ error: 'Verified credential principal required' }, 401);
|
|
}
|
|
await next();
|
|
return undefined;
|
|
};
|
|
app.use('/api/v2/experiments', credentials);
|
|
app.use('/api/v2/experiments/*', credentials);
|
|
app.onError((error, c) => {
|
|
const agentError =
|
|
error instanceof ResearchAgentError ? error : researchAgentDatabaseError(error);
|
|
if (agentError) {
|
|
return c.json(
|
|
{
|
|
error: agentError.message,
|
|
code: agentError.status === 429 ? 'research_budget_exceeded' : 'research_access_denied',
|
|
},
|
|
agentError.status
|
|
);
|
|
}
|
|
if (error instanceof ExperimentError) {
|
|
return c.json({ error: error.message }, error.status);
|
|
}
|
|
logger.error('Experiment operation failed', error);
|
|
return c.json({ error: 'Experiment operation unavailable' }, 500);
|
|
});
|
|
const agentScope = (request: Request) => {
|
|
const principal = getResearchHttpPrincipal(request);
|
|
return principal && isResearchAgent(principal) ? principal : undefined;
|
|
};
|
|
const body = async (request: Request): Promise<unknown> => {
|
|
try {
|
|
return await request.json();
|
|
} catch {
|
|
throw new ExperimentError(400, 'Invalid JSON request');
|
|
}
|
|
};
|
|
app.post('/api/v2/experiments/cost-sensitivity/preview', async c =>
|
|
c.json({
|
|
preview: await service.previewCosts(
|
|
parseCostSensitivityInput(await body(c.req.raw)),
|
|
getResearchHttpPrincipal(c.req.raw) ?? ''
|
|
),
|
|
})
|
|
);
|
|
app.post('/api/v2/experiments/cost-sensitivity', async c => {
|
|
const input = parseCostSensitivitySubmission(await body(c.req.raw));
|
|
const experiment = await service.submitCosts(
|
|
input,
|
|
experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
})
|
|
);
|
|
c.header('Location', `/api/v2/experiments/${experiment.id}`);
|
|
return c.json({ experiment }, 202);
|
|
});
|
|
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
|
c.json({
|
|
preview: await walkForwards.preview(
|
|
parseWalkForwardInput(await body(c.req.raw)),
|
|
getResearchHttpPrincipal(c.req.raw) ?? ''
|
|
),
|
|
})
|
|
);
|
|
app.post('/api/v2/experiments/walk-forward', async c => {
|
|
const input = parseWalkForwardSubmission(await body(c.req.raw));
|
|
const walkForward = await walkForwards.submit(
|
|
input,
|
|
experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
})
|
|
);
|
|
c.header('Location', `/api/v2/experiments/walk-forward/${walkForward.id}`);
|
|
return c.json({ walkForward }, 202);
|
|
});
|
|
app.get('/api/v2/experiments/walk-forward', async c =>
|
|
c.json({
|
|
walkForwards: await walkForwards.list(c.req.query('backtestId'), agentScope(c.req.raw)),
|
|
})
|
|
);
|
|
app.get('/api/v2/experiments/walk-forward/:id', async c =>
|
|
c.json({ walkForward: await walkForwards.get(experimentId(c.req.param('id'))) })
|
|
);
|
|
app.post('/api/v2/experiments/walk-forward/:id/finalize', async c => {
|
|
const id = experimentId(c.req.param('id')),
|
|
input = parseWalkForwardFinalization(await body(c.req.raw));
|
|
return c.json(
|
|
await walkForwards.finalize(
|
|
id,
|
|
input,
|
|
experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
})
|
|
),
|
|
202
|
|
);
|
|
});
|
|
app.post('/api/v2/experiments/walk-forward/:id/cancel', async c => {
|
|
const id = experimentId(c.req.param('id'));
|
|
if (
|
|
!z
|
|
.object({})
|
|
.strict()
|
|
.safeParse(await body(c.req.raw)).success
|
|
) {
|
|
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
|
}
|
|
return c.json({ walkForward: await walkForwards.cancel(id) });
|
|
});
|
|
app.post('/api/v2/experiments/validation/preview', async c => {
|
|
const input = parseChronologicalValidation(await body(c.req.raw));
|
|
return c.json({
|
|
preview: await service.previewValidation(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
|
|
});
|
|
});
|
|
app.post('/api/v2/experiments/validation', async c => {
|
|
const input = parseValidationSubmission(await body(c.req.raw));
|
|
const validation = await validations.submit(
|
|
input,
|
|
experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
})
|
|
);
|
|
c.header('Location', `/api/v2/experiments/validation/${validation.id}`);
|
|
return c.json({ validation }, 202);
|
|
});
|
|
app.get('/api/v2/experiments/validation', async c =>
|
|
c.json({
|
|
validations: await validations.list(c.req.query('backtestId'), agentScope(c.req.raw)),
|
|
})
|
|
);
|
|
app.get('/api/v2/experiments/validation/:id', async c =>
|
|
c.json({ validation: await validations.get(experimentId(c.req.param('id'))) })
|
|
);
|
|
app.post('/api/v2/experiments/validation/:id/select', async c => {
|
|
const id = experimentId(c.req.param('id')),
|
|
input = parseValidationSelection(await body(c.req.raw));
|
|
return c.json(
|
|
await validations.select(
|
|
id,
|
|
input,
|
|
experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
})
|
|
),
|
|
202
|
|
);
|
|
});
|
|
app.post('/api/v2/experiments/validation/:id/finalize', async c => {
|
|
const id = experimentId(c.req.param('id')),
|
|
input = parseValidationFinalization(await body(c.req.raw));
|
|
return c.json(
|
|
await validations.finalize(
|
|
id,
|
|
input,
|
|
experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
})
|
|
),
|
|
202
|
|
);
|
|
});
|
|
app.post('/api/v2/experiments/validation/:id/cancel', async c => {
|
|
const id = experimentId(c.req.param('id'));
|
|
if (
|
|
!z
|
|
.object({})
|
|
.strict()
|
|
.safeParse(await body(c.req.raw)).success
|
|
) {
|
|
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
|
}
|
|
return c.json({ validation: await validations.cancel(id) });
|
|
});
|
|
app.post('/api/v2/experiments/preview', async c => {
|
|
const input = parseExperimentInput(await body(c.req.raw));
|
|
return c.json({
|
|
preview: await service.preview(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
|
|
});
|
|
});
|
|
app.post('/api/v2/experiments', async c => {
|
|
const input = parseExperimentSubmission(await body(c.req.raw));
|
|
const receipt = experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
});
|
|
const experiment = await service.submit(input, receipt);
|
|
c.header('Location', `/api/v2/experiments/${experiment.id}`);
|
|
return c.json({ experiment }, 202);
|
|
});
|
|
app.get('/api/v2/experiments', async c => {
|
|
const filter = c.req.query('backtestId');
|
|
if (filter !== undefined) {
|
|
experimentId(filter);
|
|
}
|
|
return c.json({ experiments: await service.list(filter, agentScope(c.req.raw)) });
|
|
});
|
|
app.get('/api/v2/experiments/compare', async c => {
|
|
const params = new URL(c.req.url).searchParams;
|
|
const seen = new Set<string>();
|
|
for (const key of params.keys()) {
|
|
if (seen.has(key) || !['leftId', 'rightId', 'referenceTrialKey'].includes(key)) {
|
|
throw new ExperimentError(400, 'Unknown or duplicate comparison query parameter');
|
|
}
|
|
seen.add(key);
|
|
}
|
|
return c.json({ comparison: await service.compare(Object.fromEntries(params)) });
|
|
});
|
|
app.get('/api/v2/experiments/:id', async c =>
|
|
c.json({ experiment: await service.get(experimentId(c.req.param('id'))) })
|
|
);
|
|
app.post('/api/v2/experiments/:id/cancel', async c => {
|
|
const id = experimentId(c.req.param('id'));
|
|
if (
|
|
!z
|
|
.object({})
|
|
.strict()
|
|
.safeParse(await body(c.req.raw)).success
|
|
) {
|
|
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
|
}
|
|
return c.json({ experiment: await service.cancel(id) });
|
|
});
|
|
app.get('/api/v2/experiments/:id/trials/:runId/retries', async c =>
|
|
c.json({
|
|
retries: await service.listTrialRetries(
|
|
experimentId(c.req.param('id')),
|
|
experimentId(c.req.param('runId'))
|
|
),
|
|
})
|
|
);
|
|
app.post('/api/v2/experiments/:id/trials/:runId/retry', async c => {
|
|
const id = experimentId(c.req.param('id')),
|
|
runId = experimentId(c.req.param('runId'));
|
|
const input = parseExperimentRetry(await body(c.req.raw));
|
|
const receipt = experimentReceipt({
|
|
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
|
|
key: c.req.header('Idempotency-Key') ?? '',
|
|
});
|
|
const result = await service.retryTrial(id, runId, input, receipt);
|
|
c.header('Location', `/api/v2/experiments/${id}`);
|
|
return c.json(result, 202);
|
|
});
|
|
return app;
|
|
}
|