refactor(api): compose research services with narrow collaborators (CL28)
This commit is contained in:
parent
3a63b2039e
commit
24487d35da
28 changed files with 281 additions and 94 deletions
|
|
@ -8,6 +8,7 @@ import { cors } from 'hono/cors';
|
|||
import type { HttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { createWebApiSecurity } from '../http-security';
|
||||
import { createResearchServices } from '../services/research-services';
|
||||
import { createBacktestRoutes } from './backtest.routes';
|
||||
import { createBacktestV2Routes } from './backtests-v2.routes';
|
||||
import { createDatasetRoutes } from './datasets.routes';
|
||||
|
|
@ -44,6 +45,7 @@ export function createRoutes(
|
|||
})
|
||||
);
|
||||
security.mount(app);
|
||||
const researchServices = createResearchServices(container);
|
||||
|
||||
// Create routes with container
|
||||
const healthRoutes = createHealthRoutes(container);
|
||||
|
|
@ -63,13 +65,14 @@ export function createRoutes(
|
|||
app.route('/', backtestRoutes); // Mounted at root since routes already have /api prefix
|
||||
app.route('/', backtestV2Routes); // V2 routes also mounted at root
|
||||
app.route('/', createDatasetRoutes(container));
|
||||
app.route('/', createStrategyRoutes(container));
|
||||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createStrategyRoutes(container, researchServices.catalog));
|
||||
app.route('/', createResearchRoutes(container, researchServices.research));
|
||||
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
app.route('/', createExperimentRoutes(container, researchServices));
|
||||
app.route(
|
||||
'/',
|
||||
createPaperDeploymentRoutes(container, {
|
||||
service: researchServices.paperDeployments,
|
||||
origin: integrations ? integrations.paperOrchestratorOrigin : process.env.ORCHESTRATOR_URL,
|
||||
origins: security.allowedOrigins,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import { z } from 'zod';
|
|||
import { getResearchHttpPrincipal } from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { ChronologicalValidationService } from '../services/chronological-validation.service';
|
||||
import {
|
||||
parseCostSensitivityInput,
|
||||
parseCostSensitivitySubmission,
|
||||
|
|
@ -16,8 +15,8 @@ import {
|
|||
parseExperimentSubmission,
|
||||
} from '../services/experiment-input';
|
||||
import { parseExperimentRetry } from '../services/experiment-retry';
|
||||
import { ExperimentsService } from '../services/experiments.service';
|
||||
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
|
||||
import { createResearchServices, type ResearchServices } from '../services/research-services';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
|
|
@ -29,14 +28,17 @@ import {
|
|||
parseWalkForwardInput,
|
||||
parseWalkForwardSubmission,
|
||||
} from '../services/walk-forward-input';
|
||||
import { WalkForwardService } from '../services/walk-forward.service';
|
||||
|
||||
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
|
||||
export function createExperimentRoutes(container: IServiceContainer) {
|
||||
export function createExperimentRoutes(
|
||||
container: IServiceContainer,
|
||||
services: Pick<
|
||||
ResearchServices,
|
||||
'experiments' | 'validations' | 'walkForwards'
|
||||
> = createResearchServices(container)
|
||||
) {
|
||||
const app = new Hono();
|
||||
const service = new ExperimentsService(container);
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const walkForwards = new WalkForwardService(container);
|
||||
const { experiments: service, validations, walkForwards } = services;
|
||||
const logger = getLogger('experiments-api');
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
|
|||
|
|
@ -12,8 +12,9 @@ import {
|
|||
paperAllowedOrigins,
|
||||
requirePaperOperator,
|
||||
} from '@stock-bot/trading-runtime/paper-operator';
|
||||
import { PaperDeploymentsService } from '../services/paper-deployments.service';
|
||||
import type { PaperDeploymentsService } from '../services/paper-deployments.service';
|
||||
import { ResearchError } from '../services/research-errors';
|
||||
import { createResearchServices } from '../services/research-services';
|
||||
|
||||
/** Forwards the original human credential; never substitutes a service token. */
|
||||
export async function forwardPaperCommand(
|
||||
|
|
@ -95,7 +96,7 @@ export function createPaperDeploymentRoutes(
|
|||
} = {}
|
||||
) {
|
||||
const app = new Hono(),
|
||||
service = options.service ?? new PaperDeploymentsService(container),
|
||||
service = options.service ?? createResearchServices(container).paperDeployments,
|
||||
origins = options.origins ?? paperAllowedOrigins();
|
||||
app.use('*', async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import type { IServiceContainer } from '@stock-bot/services';
|
|||
import { archiveResearchSchema, parseResearchInput } from '@stock-bot/stock-config/research';
|
||||
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
|
||||
import { ResearchError } from '../services/research-errors';
|
||||
import { ResearchService } from '../services/research.service';
|
||||
import { createResearchServices } from '../services/research-services';
|
||||
|
||||
const emptyBody = z.object({}).strict();
|
||||
function includeArchived(value: string | undefined): boolean {
|
||||
|
|
@ -25,9 +25,11 @@ async function noMutationBody(request: Request): Promise<void> {
|
|||
}
|
||||
|
||||
/** Research metadata only; the mounted security layer owns authenticated read access. */
|
||||
export function createResearchRoutes(container: IServiceContainer) {
|
||||
export function createResearchRoutes(
|
||||
container: IServiceContainer,
|
||||
service = createResearchServices(container).research
|
||||
) {
|
||||
const app = new Hono();
|
||||
const service = new ResearchService(container);
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (!['GET', 'HEAD'].includes(c.req.method) && !getResearchHttpPrincipal(c.req.raw)) {
|
||||
|
|
|
|||
|
|
@ -11,9 +11,11 @@ const publication = z
|
|||
const parameters = z.object({ parameters: z.unknown() }).strict();
|
||||
const submissionKey = z.string().regex(/^[\x21-\x7e]{1,200}$/);
|
||||
|
||||
export function createStrategyRoutes(container: IServiceContainer) {
|
||||
export function createStrategyRoutes(
|
||||
container: IServiceContainer,
|
||||
service = new StrategyCatalogService(container)
|
||||
) {
|
||||
const app = new Hono();
|
||||
const service = new StrategyCatalogService(container);
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (!['GET', 'HEAD'].includes(c.req.method) && !getResearchHttpPrincipal(c.req.raw)) {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import type {
|
|||
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import type { ResearchActor } from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { BacktestServiceV2 } from './backtest-v2.service';
|
||||
import type { BacktestResults } from './backtests/results';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
|
|
@ -28,7 +28,7 @@ import {
|
|||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
} from './experiment-input';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import type { ExperimentsService } from './experiments.service';
|
||||
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import {
|
||||
|
|
@ -76,10 +76,16 @@ export class ChronologicalValidationService {
|
|||
private readonly database;
|
||||
private readonly experiments;
|
||||
private readonly results;
|
||||
constructor(private readonly container: IServiceContainer) {
|
||||
constructor(
|
||||
private readonly container: IServiceContainer,
|
||||
collaborators: {
|
||||
experiments: Pick<ExperimentsService, 'lockedPreview' | 'readParameterDetail'>;
|
||||
results: Pick<BacktestResults, 'getRunResults'>;
|
||||
}
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.experiments = new ExperimentsService(container);
|
||||
this.results = new BacktestServiceV2(container);
|
||||
this.experiments = collaborators.experiments;
|
||||
this.results = collaborators.results;
|
||||
}
|
||||
async submit(raw: unknown, actor: Actor): Promise<ChronologicalValidationDetail> {
|
||||
const submission = parseValidationSubmission(raw),
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import {
|
|||
type PaperPromotionPreview,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type { ResearchEvidenceReference } from '@stock-bot/types';
|
||||
import { validatePaperConfiguration } from '@stock-bot/trading-runtime/paper-configuration';
|
||||
import {
|
||||
authorizedPaperPackage,
|
||||
|
|
@ -24,7 +23,9 @@ import {
|
|||
retainedPaperDeployment,
|
||||
} from '@stock-bot/trading-runtime/paper-deployment-custody';
|
||||
import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity';
|
||||
import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service';
|
||||
import type { ResearchEvidenceReference } from '@stock-bot/types';
|
||||
import type { BacktestResultQuery } from './backtests/contracts';
|
||||
import type { BacktestResults } from './backtests/results';
|
||||
import { retainedCostSensitivityPreview } from './cost-sensitivity-input';
|
||||
import { canonicalReproductionHash } from './reproduction-comparison';
|
||||
import { verifyResearchSource } from './research-source-evidence';
|
||||
|
|
@ -70,13 +71,12 @@ function evidence(result: CanonicalRunResult) {
|
|||
|
||||
export class PaperDeploymentsService {
|
||||
private readonly database;
|
||||
private readonly results;
|
||||
constructor(
|
||||
private readonly container: IServiceContainer,
|
||||
private readonly results: Pick<BacktestResults, 'getRunResults'>,
|
||||
private readonly identity = readPaperHostIdentity
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.results = new BacktestServiceV2(container);
|
||||
}
|
||||
private async prepare(
|
||||
input: PaperPromotionInput,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@ import type {
|
|||
ResearchEvidenceReference,
|
||||
ResearchFindingSource,
|
||||
} from '@stock-bot/types';
|
||||
import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service';
|
||||
import type { BacktestResultQuery } from './backtests/contracts';
|
||||
import type { BacktestResults } from './backtests/results';
|
||||
import { ResearchError } from './research-errors';
|
||||
import { verifyResearchSource } from './research-source-evidence';
|
||||
|
||||
|
|
@ -124,10 +125,11 @@ export function projectResearchEvidence(
|
|||
|
||||
export class ResearchEvidenceResolver {
|
||||
private readonly database;
|
||||
private readonly results;
|
||||
constructor(container: IServiceContainer) {
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
private readonly results: Pick<BacktestResults, 'getRunResults'>
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.results = new BacktestServiceV2(container);
|
||||
}
|
||||
|
||||
async resolveAll(
|
||||
|
|
|
|||
36
apps/stock/web-api/src/services/research-services.ts
Normal file
36
apps/stock/web-api/src/services/research-services.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { BacktestResults } from './backtests/results';
|
||||
import { ChronologicalValidationService } from './chronological-validation.service';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import { PaperDeploymentsService } from './paper-deployments.service';
|
||||
import { ResearchEvidenceResolver } from './research-evidence';
|
||||
import { ResearchService } from './research.service';
|
||||
import { StrategyCatalogService } from './strategy-catalog.service';
|
||||
import { WalkForwardService } from './walk-forward.service';
|
||||
|
||||
/** Per-application composition only: constructors do no I/O and do not start workers or paper hosts. */
|
||||
export function createResearchServices(
|
||||
container: IServiceContainer,
|
||||
options: { paperIdentity?: ConstructorParameters<typeof PaperDeploymentsService>[2] } = {}
|
||||
) {
|
||||
const results = new BacktestResults(requireServices(container, 'postgres'));
|
||||
const experiments = new ExperimentsService(container);
|
||||
const validations = new ChronologicalValidationService(container, { experiments, results });
|
||||
const walkForwards = new WalkForwardService(container, { experiments, validations });
|
||||
const catalog = new StrategyCatalogService(container);
|
||||
const evidence = new ResearchEvidenceResolver(container, results);
|
||||
const research = new ResearchService(container, { evidence, catalog });
|
||||
const paperDeployments = new PaperDeploymentsService(container, results, options.paperIdentity);
|
||||
return {
|
||||
results,
|
||||
experiments,
|
||||
validations,
|
||||
walkForwards,
|
||||
catalog,
|
||||
evidence,
|
||||
research,
|
||||
paperDeployments,
|
||||
};
|
||||
}
|
||||
|
||||
export type ResearchServices = ReturnType<typeof createResearchServices>;
|
||||
|
|
@ -30,8 +30,8 @@ import type {
|
|||
} from '@stock-bot/types';
|
||||
import { lockResearchAgent } from './research-agent-budget';
|
||||
import { ResearchError } from './research-errors';
|
||||
import { ResearchEvidenceResolver } from './research-evidence';
|
||||
import { StrategyCatalogService } from './strategy-catalog.service';
|
||||
import type { ResearchEvidenceResolver } from './research-evidence';
|
||||
import type { StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
type Database = {
|
||||
query<T extends QueryResultRow = QueryResultRow>(
|
||||
|
|
@ -134,10 +134,16 @@ export class ResearchService {
|
|||
private readonly database;
|
||||
private readonly evidence;
|
||||
private readonly catalog;
|
||||
constructor(container: IServiceContainer) {
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
collaborators: {
|
||||
evidence: Pick<ResearchEvidenceResolver, 'resolveAll'>;
|
||||
catalog: Pick<StrategyCatalogService, 'getStrategy'>;
|
||||
}
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.evidence = new ResearchEvidenceResolver(container);
|
||||
this.catalog = new StrategyCatalogService(container);
|
||||
this.evidence = collaborators.evidence;
|
||||
this.catalog = collaborators.catalog;
|
||||
}
|
||||
|
||||
async listProjects(includeArchived = false): Promise<ResearchProject[]> {
|
||||
|
|
|
|||
|
|
@ -11,14 +11,14 @@ import type {
|
|||
WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import { ChronologicalValidationService } from './chronological-validation.service';
|
||||
import type { ChronologicalValidationService } from './chronological-validation.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
} from './experiment-input';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import type { ExperimentsService } from './experiments.service';
|
||||
import { lockResearchAgent } from './research-agent-budget';
|
||||
import { validationEqual } from './validation-evidence';
|
||||
import {
|
||||
|
|
@ -73,10 +73,19 @@ export class WalkForwardService {
|
|||
private readonly database;
|
||||
private readonly experiments;
|
||||
private readonly validations;
|
||||
constructor(container: IServiceContainer) {
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
collaborators: {
|
||||
experiments: Pick<ExperimentsService, 'lockedPreview'>;
|
||||
validations: Pick<
|
||||
ChronologicalValidationService,
|
||||
'admitPrepared' | 'verifiedSealedReport' | 'readDetail'
|
||||
>;
|
||||
}
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.experiments = new ExperimentsService(container);
|
||||
this.validations = new ChronologicalValidationService(container);
|
||||
this.experiments = collaborators.experiments;
|
||||
this.validations = collaborators.validations;
|
||||
}
|
||||
async preview(raw: unknown, principal = 'operator') {
|
||||
const input = parseWalkForwardInput(raw);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue