GCoordinator/src/server/automation/template.ts

192 lines
5.6 KiB
TypeScript

import type { InputDef } from '../../shared/schemas/common.js';
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
import { posixSingleQuote } from '../ssh/sudo.js';
export interface StepOutputSummary {
stdout: string;
exitCode: number | null;
}
export interface TemplateContext {
workflowId?: string;
runId?: string;
serverId?: string;
inputs: Record<string, string>;
stepOutputs?: Map<string, StepOutputSummary>;
captures?: Map<string, string>;
eventMeta?: Record<string, string>;
}
export function toEnvIdent(raw: string): string {
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
}
export function validateAndResolveInputs(
defs: InputDef[],
supplied: Record<string, unknown> = {},
): Record<string, string> {
const out: Record<string, string> = {};
for (const def of defs) {
const raw = supplied[def.name];
const hasSupplied = raw !== undefined && raw !== null && raw !== '';
const candidate = hasSupplied ? raw : def.default;
if (candidate === undefined || candidate === null || candidate === '') {
if (def.required) {
throw new Error(`Missing required input "${def.label ?? def.name}"`);
}
continue;
}
if (def.type === 'number') {
const n = Number(candidate);
if (!Number.isFinite(n)) {
throw new Error(`Input "${def.name}" must be a valid number`);
}
out[def.name] = String(n);
continue;
}
if (def.type === 'boolean') {
if (typeof candidate === 'boolean') {
out[def.name] = candidate ? 'true' : 'false';
} else {
const lower = String(candidate).trim().toLowerCase();
if (lower === 'true' || lower === '1' || lower === 'yes') out[def.name] = 'true';
else if (lower === 'false' || lower === '0' || lower === 'no') out[def.name] = 'false';
else throw new Error(`Input "${def.name}" must be true or false`);
}
continue;
}
const strVal = String(candidate);
if (def.type === 'select' && def.options && def.options.length > 0) {
if (!def.options.includes(strVal)) {
throw new Error(
`Input "${def.name}" must be one of: ${def.options.join(', ')}`,
);
}
}
out[def.name] = strVal;
}
for (const [k, v] of Object.entries(supplied)) {
if (!(k in out) && v !== undefined && v !== null) {
out[k] = String(v);
}
}
return out;
}
export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
const env: Record<string, string> = {};
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
if (ctx.runId) env.GCOORD_RUN_ID = ctx.runId;
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
for (const [k, v] of Object.entries(ctx.inputs)) {
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
}
if (ctx.stepOutputs) {
for (const [stepId, res] of ctx.stepOutputs.entries()) {
const keyBase = `GCOORD_STEP_${toEnvIdent(stepId)}`;
env[`${keyBase}_STDOUT`] = res.stdout.slice(0, 32 * 1024);
env[`${keyBase}_EXIT`] = res.exitCode === null ? '' : String(res.exitCode);
}
}
if (ctx.captures) {
for (const [alias, val] of ctx.captures.entries()) {
env[`GCOORD_CAPTURE_${toEnvIdent(alias)}`] = val.slice(0, 32 * 1024);
}
}
if (ctx.eventMeta) {
for (const [k, v] of Object.entries(ctx.eventMeta)) {
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
}
}
return env;
}
function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string {
const expr = rawExpr.trim();
if (expr.startsWith('inputs.')) {
const key = expr.slice('inputs.'.length);
return ctx.inputs[key] ?? '';
}
if (expr.startsWith('steps.')) {
const rest = expr.slice('steps.'.length);
const dot = rest.lastIndexOf('.');
if (dot > 0) {
const stepId = rest.slice(0, dot);
const field = rest.slice(dot + 1);
const out = ctx.stepOutputs?.get(stepId);
if (!out) return '';
if (field === 'stdout') return out.stdout.trim();
if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode);
}
}
if (expr.startsWith('captures.')) {
const key = expr.slice('captures.'.length);
return (ctx.captures?.get(key) ?? '').trim();
}
if (expr.startsWith('event.')) {
const key = expr.slice('event.'.length);
return ctx.eventMeta?.[key] ?? '';
}
return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim();
}
export function interpolateValuePlain(template: string, ctx: TemplateContext): string {
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
resolveTemplateToken(expr, ctx),
);
}
export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string {
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
posixSingleQuote(resolveTemplateToken(expr, ctx)),
);
}
export function resolveTargetServers(
target: { serverId?: string; tags?: string[]; all?: boolean },
servers: ServerConfig[],
ctx: TemplateContext,
): ServerConfig[] {
const enabled = servers.filter((s) => s.enabled);
if (target.all) {
return enabled;
}
const out: ServerConfig[] = [];
const seen = new Set<string>();
if (target.serverId) {
const resolvedId = interpolateValuePlain(target.serverId, ctx).trim();
const match = enabled.find((s) => s.id === resolvedId);
if (match) {
seen.add(match.id);
out.push(match);
}
}
if (target.tags && target.tags.length > 0) {
const wanted = new Set(target.tags);
for (const s of enabled) {
if (seen.has(s.id)) continue;
if (s.tags.some((t) => wanted.has(t))) {
seen.add(s.id);
out.push(s);
}
}
}
return out;
}