stock-bot/apps/stock/web-api/src/routes/paper-deployments.routes.ts

178 lines
6 KiB
TypeScript

import { Hono } from 'hono';
import { z } from 'zod';
import type { IServiceContainer } from '@stock-bot/services';
import { paperDeploymentStatusSchema } from '@stock-bot/stock-config/paper-deployments';
import {
paperActivationSchema,
paperHaltSchema,
PaperRuntimeError,
} from '../../../orchestrator/src/contracts/paper-runtime';
import { PaperDeploymentError } from '../../../orchestrator/src/paper/paper-deployment-custody';
import {
paperAllowedOrigins,
requirePaperOperator,
} from '../../../orchestrator/src/paper/paper-operator';
import { PaperDeploymentsService } from '../services/paper-deployments.service';
import { ResearchError } from '../services/research-errors';
/** Forwards the original human credential; never substitutes a service token. */
export async function forwardPaperCommand(
request: Request,
id: string,
operation: 'bind' | 'activate' | 'halt' | 'readiness',
body: unknown,
options: {
origin?: string;
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
}
) {
if (!options.origin) {
throw new PaperDeploymentError(503, 'Paper orchestrator origin is not configured');
}
let base: URL;
try {
base = new URL(options.origin);
} catch {
throw new PaperDeploymentError(503, 'Paper orchestrator origin is invalid');
}
if (
!['http:', 'https:'].includes(base.protocol) ||
base.username ||
base.password ||
base.pathname !== '/' ||
base.search ||
base.hash
) {
throw new PaperDeploymentError(503, 'Paper orchestrator requires a fixed HTTP origin');
}
const headers = new Headers({ 'Content-Type': 'application/json' });
for (const name of ['authorization', 'cookie', 'origin']) {
const value = request.headers.get(name);
if (value) {
headers.set(name, value);
}
}
let response: Response;
try {
response = await (options.request ?? fetch)(
new URL(`/api/paper/deployments/${id}/${operation}`, base),
{
method: operation === 'readiness' ? 'GET' : 'POST',
headers,
...(operation === 'readiness' ? {} : { body: JSON.stringify(body) }),
redirect: 'error',
signal: AbortSignal.timeout(15000),
}
);
} catch {
throw new PaperDeploymentError(
503,
'Paper orchestrator could not confirm the command; check readiness before retrying'
);
}
const value: unknown = await response.json().catch(() => null);
if (!response.ok) {
const status = [400, 403, 404, 409, 422, 503].includes(response.status) ? response.status : 503;
const message =
value && typeof value === 'object' && 'error' in value && typeof value.error === 'string'
? value.error
: 'Paper orchestrator rejected the request';
throw new PaperDeploymentError(status as 400 | 403 | 404 | 409 | 422 | 503, message);
}
const status = paperDeploymentStatusSchema.parse(value);
if (status.deploymentId !== id) {
throw new Error('Paper orchestrator returned another deployment');
}
return status;
}
export function createPaperDeploymentRoutes(
container: IServiceContainer,
options: {
origin?: string;
origins?: readonly string[];
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
service?: PaperDeploymentsService;
} = {}
) {
const app = new Hono(),
service = options.service ?? new PaperDeploymentsService(container),
origins = options.origins ?? paperAllowedOrigins();
app.use('*', async (c, next) => {
c.header('Cache-Control', 'no-store');
if (c.req.method !== 'GET' || c.req.path.endsWith('/readiness')) {
requirePaperOperator(c.req.raw, origins);
}
await next();
});
app.onError((error, c) => {
if (error instanceof PaperDeploymentError || error instanceof ResearchError) {
return c.json({ error: error.message }, error.status);
}
if (
error instanceof z.ZodError ||
error instanceof SyntaxError ||
error instanceof PaperRuntimeError
) {
return c.json(
{
error:
error instanceof PaperRuntimeError ? error.message : 'Invalid paper promotion request',
},
400
);
}
container.logger.error('Paper deployment operation failed', { error });
return c.json({ error: 'Paper deployment evidence or storage unavailable' }, 500);
});
app.get('/api/v2/paper-deployments', async c => c.json({ deployments: await service.list() }));
app.post('/api/v2/paper-deployments/preview', async c =>
c.json(await service.preview(await c.req.json()))
);
app.post('/api/v2/paper-deployments', async c =>
c.json(await service.create(await c.req.json(), c.req.header('Idempotency-Key') ?? ''), 201)
);
app.get('/api/v2/paper-deployments/:id', async c =>
c.json(
await service.get(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id'))
)
)
);
for (const operation of ['bind', 'activate', 'halt', 'readiness'] as const) {
const path = `/api/v2/paper-deployments/:id/${operation}`;
app.on(operation === 'readiness' ? 'GET' : 'POST', path, async c => {
const id = z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id'));
const body =
operation === 'readiness'
? undefined
: operation === 'activate'
? paperActivationSchema.parse(await c.req.json())
: operation === 'halt'
? paperHaltSchema.parse(await c.req.json())
: z
.object({})
.strict()
.parse(await c.req.json());
if (operation === 'bind' || operation === 'activate') {
await service.authorizeCommand(id);
} else {
await service.get(id);
}
return c.json(
await forwardPaperCommand(c.req.raw, id, operation, body, {
origin: options.origin ?? process.env.ORCHESTRATOR_URL,
request: options.request,
})
);
});
}
return app;
}