File size: 6,250 Bytes
1244914 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | import { exec } from "child_process";
import { promisify } from "util";
import Handlebars from "handlebars";
import type { Task, Validation } from "./model.js";
import { escapeRegex } from "./utils.js";
const execAsync = promisify(exec);
// Register Handlebars helper for escaping regex
Handlebars.registerHelper("escapeRegex", escapeRegex);
export type ValidationResult = {
name: string;
passed: boolean;
message: string;
};
/**
* Validates output against a regex pattern
*/
function validateRegex(
output: string,
regex: string,
name: string,
): ValidationResult {
const pattern = new RegExp(regex);
const passed = pattern.test(output);
return {
name,
passed,
message: passed ? `Matched: ${regex}` : `Did not match: ${regex}`,
};
}
/**
* Validates output using a shell command
*/
async function validateShellCommand(
output: string,
command: string,
expectedExitCode: number,
name: string,
): Promise<ValidationResult> {
try {
const { spawn } = await import("child_process");
// Use spawn to pipe stdin properly
const result = await new Promise<{ code: number }>((resolve, reject) => {
const child = spawn(command, {
shell: true,
stdio: ["pipe", "pipe", "pipe"],
});
let processExited = false;
// Handle stdin errors (EPIPE when process exits early)
child.stdin.on("error", (err: NodeJS.ErrnoException) => {
// Ignore EPIPE errors - they happen when the child process
// exits before we finish writing, which is expected behavior
if (err.code !== "EPIPE") {
reject(err);
}
});
child.on("close", (code) => {
processExited = true;
resolve({ code: code ?? 0 });
});
child.on("error", (err) => {
reject(err);
});
// Write output to stdin
// Use setImmediate to ensure event handlers are attached first
setImmediate(() => {
if (!processExited && child.stdin.writable) {
child.stdin.write(output, (err?: Error | null) => {
if (err && (err as NodeJS.ErrnoException).code !== "EPIPE") {
// Only reject on non-EPIPE errors
reject(err);
} else {
child.stdin.end();
}
});
} else {
// Process already exited or stdin not writable
child.stdin.end();
}
});
});
// Command succeeded (exit code 0)
const passed = result.code === expectedExitCode;
return {
name,
passed,
message: passed
? `Command succeeded with exit code ${result.code}`
: `Expected exit code ${expectedExitCode}, got ${result.code}`,
};
} catch (error: any) {
// Command failed with error
return {
name,
passed: false,
message: `Command failed: ${error.message}`,
};
}
}
/**
* Runs all validations on output and returns results
*/
export async function runValidations(
output: string,
validations: Array<Validation>,
context?: Record<string, string>,
): Promise<ValidationResult[]> {
const results: ValidationResult[] = [];
for (const validation of validations) {
if (validation.type === "regex") {
// Interpolate regex with context if provided
let regex = validation.regex;
if (context) {
const template = Handlebars.compile(regex, { strict: true });
regex = template(context);
}
results.push(validateRegex(output, regex, validation.name));
} else if (validation.type === "shell") {
// Interpolate command with context if provided
let command = validation.command;
if (context) {
const template = Handlebars.compile(command, { strict: true });
command = template(context);
}
const expectedExitCode = validation.exit_code ?? 0;
results.push(
await validateShellCommand(
output,
command,
expectedExitCode,
validation.name,
),
);
}
}
return results;
}
/**
* Checks if all validation results passed
*/
export function allValidationsPassed(results: ValidationResult[]): boolean {
return results.every((result) => result.passed);
}
/**
* Counts how many validations passed
*/
export function countPassed(results: ValidationResult[]): number {
return results.filter((result) => result.passed).length;
}
export type ProcessValidationsResult = {
validationResults: ValidationResult[];
status: "passed" | "validation_failed";
};
/**
* Processes validations and returns results with status
*/
export async function processValidations(
output: string | undefined,
task: Task,
logger: {
info: (data: any, message: string) => void;
warn: (data: any, message: string) => void;
error: (data: any, message: string) => void;
},
task_id: number,
duration: number,
logFile: string,
context?: Record<string, string>,
): Promise<ProcessValidationsResult> {
// Run validations if configured and output is available
const validationResults =
task.validations && task.validations.length > 0 && output
? await runValidations(output, task.validations, context)
: [];
const allPassed = allValidationsPassed(validationResults);
const status = allPassed ? "passed" : "validation_failed";
// Log all validation results
if (validationResults.length > 0) {
const passedCount = countPassed(validationResults);
const totalCount = validationResults.length;
if (allPassed) {
logger.info(
{
task_id,
duration,
log: logFile,
parameters: context,
passed: validationResults.map((r) => r.name),
},
"Validation passed",
);
} else {
logger.error(
{
task_id,
duration,
log_file: logFile,
parameters: context,
failed: validationResults
.filter((r) => !r.passed)
.map((r) => ({
name: r.name,
message: r.message,
})),
summary: `${passedCount}/${totalCount} passed`,
},
"Validation Failed",
);
}
}
return { validationResults, status };
}
|