feat(automation): implement DAG WorkflowEngine, cron/event triggers, dry-run, and BroadcastService

This commit is contained in:
tyuXX 2026-11-27 06:12:51 +00:00
parent 55948591db
commit f21699963f
4 changed files with 2028 additions and 0 deletions

View file

@ -0,0 +1,354 @@
import crypto from 'node:crypto';
import type { ServerWsFrame } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.js';
import type { AuditService } from '../security/audit.js';
import type { VaultService } from '../security/vault.js';
import type { SSHPool } from '../ssh/ssh-pool.js';
import { BufferedStreamEmitter } from './stream-buffer.js';
import {
buildWorkflowEnv,
interpolateShellCommandSafe,
resolveTargetServers,
validateAndResolveInputs,
} from './template.js';
export interface BroadcastTargetResult {
serverId: string;
serverName: string;
status: 'pending' | 'running' | 'ok' | 'error' | 'cancelled';
exitCode: number | null;
stdout: string;
stderr: string;
durationMs: number;
}
export interface BroadcastJobSummary {
jobId: string;
snippetId?: string;
command: string;
sudo: boolean;
createdAt: number;
finishedAt: number | null;
cancelled: boolean;
done: boolean;
targets: BroadcastTargetResult[];
}
interface ActiveBroadcastJob extends BroadcastJobSummary {
emitter: BufferedStreamEmitter;
abortController: AbortController;
}
const MAX_RETAINED_BROADCASTS = 25;
const MAX_OUTPUT_PER_SERVER = 256 * 1024;
async function runPool<T>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<void>,
): Promise<void> {
const limit = Math.max(1, Math.min(concurrency, items.length || 1));
let idx = 0;
const runners = Array.from({ length: limit }, async () => {
while (idx < items.length) {
const current = items[idx++]!;
await worker(current);
}
});
await Promise.all(runners);
}
export class BroadcastService {
private readonly jobs = new Map<string, ActiveBroadcastJob>();
constructor(
private readonly configManager: ConfigManager,
private readonly vaultService: VaultService,
private readonly sshPool: SSHPool,
private readonly wsHub: WsHub,
private readonly auditService: AuditService,
) {}
getStreamReplayFrames(jobId: string): ServerWsFrame[] {
return this.jobs.get(jobId)?.emitter.getReplayFrames() ?? [];
}
getBroadcastResult(jobId: string): BroadcastJobSummary | undefined {
const job = this.jobs.get(jobId);
if (!job) return undefined;
return {
jobId: job.jobId,
snippetId: job.snippetId,
command: job.command,
sudo: job.sudo,
createdAt: job.createdAt,
finishedAt: job.finishedAt,
cancelled: job.cancelled,
done: job.done,
targets: job.targets.map((t) => ({ ...t })),
};
}
cancelBroadcast(jobId: string): boolean {
const job = this.jobs.get(jobId);
if (!job || job.done) return false;
job.cancelled = true;
job.abortController.abort();
return true;
}
cancelAll(): void {
for (const job of this.jobs.values()) {
if (!job.done) {
job.cancelled = true;
job.abortController.abort();
}
}
}
startBroadcast(opts: {
snippetId?: string;
command?: string;
inputs?: Record<string, unknown>;
sudo?: boolean;
concurrency?: number;
timeoutSec?: number;
target: { serverId?: string; serverIds?: string[]; tags?: string[]; all?: boolean };
actorIp: string;
sessionIdHash: string | null;
}): BroadcastJobSummary {
if (!this.vaultService.isRuntimeReady) {
throw new Error('Vault is sealed; unseal Vault before running Fleet Broadcast');
}
let rawCommand = opts.command?.trim() ?? '';
let sudo = Boolean(opts.sudo);
let resolvedInputs: Record<string, string> = {};
if (opts.snippetId) {
const snip = this.configManager
.getSnippets()
.snippets.find((s) => s.id === opts.snippetId);
if (!snip) {
throw new Error(`Unknown command snippet "${opts.snippetId}"`);
}
resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {});
rawCommand = snip.command;
sudo = opts.sudo ?? snip.sudo;
} else {
if (!rawCommand) {
throw new Error('Command or snippetId is required for Fleet Broadcast');
}
if (opts.inputs) {
for (const [k, v] of Object.entries(opts.inputs)) {
if (v !== undefined && v !== null) resolvedInputs[k] = String(v);
}
}
}
const baseCtx = { inputs: resolvedInputs };
const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx);
const allServers = this.configManager.listServers();
let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx);
if (opts.target.serverIds && opts.target.serverIds.length > 0) {
const byId = new Set(matchedServers.map((s) => s.id));
const wanted = new Set(opts.target.serverIds);
for (const s of allServers) {
if (s.enabled && wanted.has(s.id) && !byId.has(s.id)) {
byId.add(s.id);
matchedServers.push(s);
}
}
}
if (matchedServers.length === 0) {
throw new Error('No enabled target servers matched broadcast filter');
}
const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`;
const emitter = new BufferedStreamEmitter(this.wsHub, jobId);
const abortController = new AbortController();
const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({
serverId: s.id,
serverName: s.name,
status: 'pending',
exitCode: null,
stdout: '',
stderr: '',
durationMs: 0,
}));
const job: ActiveBroadcastJob = {
jobId,
snippetId: opts.snippetId,
command: renderedCommand,
sudo,
createdAt: Date.now(),
finishedAt: null,
cancelled: false,
done: false,
targets,
emitter,
abortController,
};
this.jobs.set(jobId, job);
this.auditService.log({
action: 'broadcast.start',
actorIp: opts.actorIp,
sessionIdHash: opts.sessionIdHash,
target: opts.snippetId ?? 'adhoc',
status: 'ok',
details: {
jobId,
serverIds: matchedServers.map((s) => s.id),
},
});
emitter.pushMeta({
event: 'start',
jobId,
command: renderedCommand,
targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })),
});
const timeoutMs = (opts.timeoutSec ?? 120) * 1000;
const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32));
void runPool(matchedServers, concurrency, async (srv) => {
const targetEntry = job.targets.find((t) => t.serverId === srv.id)!;
if (abortController.signal.aborted) {
targetEntry.status = 'cancelled';
emitter.pushMeta({
event: 'server-exit',
serverId: srv.id,
exitCode: null,
durationMs: 0,
status: 'cancelled',
});
return;
}
const started = Date.now();
targetEntry.status = 'running';
emitter.pushMeta({ event: 'server-start', serverId: srv.id });
const env = buildWorkflowEnv({
inputs: resolvedInputs,
serverId: srv.id,
});
try {
const handle = await this.sshPool.execStream(srv.id, renderedCommand, {
env,
sudo,
});
const outChunks: Buffer[] = [];
const errChunks: Buffer[] = [];
let outBytes = 0;
let errBytes = 0;
handle.channel.on('data', (chunk: Buffer) => {
const text = chunk.toString('utf8');
if (outBytes < MAX_OUTPUT_PER_SERVER) {
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes);
outChunks.push(slice);
outBytes += slice.length;
}
emitter.push('stdout', `[${srv.id}] ${text}`);
emitter.pushMeta({
event: 'server-output',
serverId: srv.id,
channel: 'stdout',
data: text,
});
});
handle.channel.stderr?.on('data', (chunk: Buffer) => {
const text = chunk.toString('utf8');
if (errBytes < MAX_OUTPUT_PER_SERVER) {
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes);
errChunks.push(slice);
errBytes += slice.length;
}
emitter.push('stderr', `[${srv.id}] ${text}`);
emitter.pushMeta({
event: 'server-output',
serverId: srv.id,
channel: 'stderr',
data: text,
});
});
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
handle.abort();
}, timeoutMs);
timer.unref();
const onAbort = () => handle.abort();
abortController.signal.addEventListener('abort', onAbort, { once: true });
try {
const { exitCode } = await handle.done;
targetEntry.stdout = Buffer.concat(outChunks).toString('utf8');
targetEntry.stderr = Buffer.concat(errChunks).toString('utf8');
targetEntry.durationMs = Date.now() - started;
targetEntry.exitCode = exitCode;
if (job.cancelled || abortController.signal.aborted) {
targetEntry.status = 'cancelled';
} else if (timedOut) {
targetEntry.status = 'error';
targetEntry.stderr += `\nTimed out after ${timeoutMs}ms`;
} else {
targetEntry.status = exitCode === 0 ? 'ok' : 'error';
}
} finally {
clearTimeout(timer);
abortController.signal.removeEventListener('abort', onAbort);
}
} catch (err) {
targetEntry.durationMs = Date.now() - started;
targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error';
const msg = err instanceof Error ? err.message : String(err);
targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg;
emitter.push('stderr', `[${srv.id}] ${msg}\n`);
}
emitter.pushMeta({
event: 'server-exit',
serverId: srv.id,
exitCode: targetEntry.exitCode,
durationMs: targetEntry.durationMs,
status: targetEntry.status,
});
}).finally(() => {
job.done = true;
job.finishedAt = Date.now();
const okCount = job.targets.filter((t) => t.status === 'ok').length;
emitter.pushMeta({
event: 'done',
cancelled: job.cancelled,
okCount,
total: job.targets.length,
});
this.pruneJobs();
});
return this.getBroadcastResult(jobId)!;
}
private pruneJobs(): void {
const done = [...this.jobs.values()].filter((j) => j.done);
while (done.length > MAX_RETAINED_BROADCASTS) {
const oldest = done.shift()!;
this.jobs.delete(oldest.jobId);
}
}
}

View file

@ -0,0 +1,44 @@
import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js';
const DEFAULT_MAX_REPLAY_BYTES = 128 * 1024;
export class BufferedStreamEmitter {
private readonly frames: ServerWsFrame[] = [];
private bufferBytes = 0;
constructor(
private readonly wsHub: WsHub,
public readonly jobId: string,
private readonly maxReplayBytes = DEFAULT_MAX_REPLAY_BYTES,
) {}
push(stream: 'stdout' | 'stderr' | 'meta', data: string): void {
const frame: ServerWsFrame = {
type: 'stream:chunk',
jobId: this.jobId,
stream,
data,
};
const bytes = Buffer.byteLength(data, 'utf8');
this.frames.push(frame);
this.bufferBytes += bytes;
while (this.bufferBytes > this.maxReplayBytes && this.frames.length > 0) {
const dropped = this.frames.shift()!;
if (dropped.type === 'stream:chunk') {
this.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8');
}
}
this.wsHub.broadcastChannel(WS_CHANNELS.stream(this.jobId), frame);
}
pushMeta(payload: Record<string, unknown>): void {
this.push('meta', JSON.stringify(payload));
}
getReplayFrames(): ServerWsFrame[] {
return [...this.frames];
}
}

View file

@ -0,0 +1,192 @@
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;
}

File diff suppressed because it is too large Load diff