Files
liqa/server/src/code-executor/code-executor.service.ts
T
ars9 959b3b70c9
CI / changes (pull_request) Successful in 9s
CI / version (pull_request) Skipped
CI / server (pull_request) Successful in 1m44s
CI / client (pull_request) Successful in 1m36s
CI / image (pull_request) Skipped
feat(scenario): attach step output and assertion details to run log
- "Step N passed" log entry carries the step's return value as data
- context.assert accepts an optional details argument; on failure the
  assertion:fail entry stores { details, error } as data
- assertion failures throw AssertionFailedError so "Step N failed" and
  "Snippet X failed" entries name only the assertion, without repeating
  the details; the step run description keeps the full message
- exported e2e runtime accepts and prints assert details
- log output shows elapsed time in whole seconds, matching the stored
  timestamp resolution
- run artifact and scenario file names link to the inline file content
  in a new tab
2026-10-02 11:05:29 +03:00

410 lines
14 KiB
TypeScript

import {
BadRequestException,
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { expect as playwrightExpect } from "@playwright/test";
import { parse } from "acorn";
import type { BrowserContext, Page } from "playwright";
import { URL } from "node:url";
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import type { FileStorageService } from "../file/file-storage.service";
import type { DomNode } from "./dom-helpers";
import { dumpDom } from "./dom-helpers";
export interface ExecResult {
result: unknown;
}
/**
* Thrown by `context.assert`. Its `message` includes the failure reason;
* `summary` doesn't, so failure reports that follow the `assertion:fail` log
* entry (which already holds the details) can stay short.
*/
export class AssertionFailedError extends Error {
constructor(
message: string,
readonly summary: string,
) {
super(message);
this.name = "AssertionFailedError";
}
}
/** The `AssertionFailedError` behind `err` (directly or via `cause`), if any. */
export function findAssertionFailure(
err: unknown,
): AssertionFailedError | null {
for (let e = err; e instanceof Error; e = (e as { cause?: unknown }).cause) {
if (e instanceof AssertionFailedError) return e;
}
return null;
}
export type ScriptLogger = (
level: "debug" | "log" | "warn" | "error",
message: string,
/** Where the message was generated, e.g. "step:2", "snippet:login", "assertion:pass". */
context?: string | null,
/** Structured payload attached to the message (e.g. a created file's metadata). */
data?: unknown,
) => void;
/** The `context` object available inside user scripts as the sole argument. */
export interface ScriptContext {
/** Playwright Page for the current session. */
page: Page;
/** Playwright BrowserContext for the current session. */
browser: BrowserContext;
/** All environment values for the current run (empty object if none set). */
env: Record<string, string | undefined>;
/** Returns the environment value for `key`, or throws if not defined. */
getEnv: (key: string) => string;
/** Returns the credential value for `alias`, or throws if not found. */
getCredential: (alias: string) => unknown;
/** Returns the serialised output of a previous step by order index (negative = relative). */
getStepOutput: (order: number) => Promise<unknown>;
/** Dumps the DOM of the current page, optionally scoped to a CSS selector. */
dumpDom: (selector?: string) => Promise<DomNode>;
log: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
debug: (...args: unknown[]) => void;
/**
* Runs `fn` and requires it to return `true`. Logs the outcome under
* `description`, then throws if `fn` returned anything other than `true`
* or threw an exception. On failure, `details` (and the exception message,
* if any) are stored as the log entry's data.
*/
assert: (
fn: () => boolean | Promise<boolean>,
description: string,
details?: unknown,
) => Promise<void>;
/** Runs a named snippet with the same context, plus any extra positional args. */
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
/** Returns metadata + absolute disk path for files attached to the current scenario. */
getScenarioFiles: (opts?: { limit?: number; offset?: number }) => Promise<{
items: Array<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
total: number;
}>;
/** Downloads a file and creates a run artifact. */
downloadFile: (
url: string,
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
) => Promise<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
}
export interface ExecContext {
page: Page;
browser: BrowserContext;
code: string;
log?: ScriptLogger;
/** Base log context for this execution, e.g. "step:2". */
logContext?: string | null;
getStepOutput?: (order: number) => Promise<unknown>;
credentials?: Record<string, unknown>;
environment?: EnvironmentData | null;
snippets?: Record<string, string> | null;
scenarioId?: string;
runId?: string;
fileService?: FileStorageService;
}
@Injectable()
export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name);
/**
* Validates `code` by wrapping it in an async function body and attempting
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(context) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
throw new BadRequestException(
`Code parse error: ${(err as Error).message}`,
{ cause: err },
);
}
}
/**
* Executes `code` as an async function body with a single `context` argument
* that exposes page, browser, env helpers, credentials, snippets, and logging.
* Always call `validate()` before this method.
*/
async execute(ctx: ExecContext): Promise<ExecResult> {
const {
page,
browser,
code,
log,
logContext,
getStepOutput,
credentials,
environment,
snippets,
scenarioId,
runId,
fileService,
} = ctx;
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
// Splits console/log args into a plain-text message (strings, numbers, ...)
// and a structured data payload (objects/arrays), logged separately so the
// message stays a stable string regardless of the object's shape.
const splitLogArgs = (
args: unknown[],
): { message: string; data: unknown } => {
const strings: string[] = [];
const objects: unknown[] = [];
for (const a of args) {
if (a !== null && typeof a === "object") {
objects.push(a);
} else {
strings.push(String(a));
}
}
return {
message: strings.join(" "),
data: objects.length === 0 ? null : objects.length === 1 ? objects[0] : objects,
};
};
// Innermost running snippet (if any) tags log entries; falls back to
// logContext (e.g. the current step) outside of any runSnippet call.
const contextStack: string[] = logContext ? [logContext] : [];
const currentContext = (): string | null =>
contextStack.length > 0 ? contextStack[contextStack.length - 1] : null;
const emit = (
level: "debug" | "log" | "warn" | "error",
message: string,
contextOverride?: string,
data?: unknown,
): void =>
scriptLog(level, message, contextOverride ?? currentContext(), data);
const emitArgs = (level: "debug" | "log" | "warn" | "error", args: unknown[]): void => {
const { message, data } = splitLogArgs(args);
emit(level, message, undefined, data);
};
const credMap: Record<string, unknown> = credentials ?? {};
const envData: EnvironmentData = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// scriptContext is referenced by runSnippet, so we declare it first.
let scriptContext: ScriptContext;
const fakeConsole = {
log: (...args: unknown[]) => emitArgs("log", args),
warn: (...args: unknown[]) => emitArgs("warn", args),
error: (...args: unknown[]) => emitArgs("error", args),
info: (...args: unknown[]) => emitArgs("log", args),
debug: (...args: unknown[]) => emitArgs("debug", args),
};
try {
scriptContext = {
page,
browser,
dumpDom: (selector?: string) => dumpDom(page, selector),
log: (...args: unknown[]) => emitArgs("log", args),
warn: (...args: unknown[]) => emitArgs("warn", args),
error: (...args: unknown[]) => emitArgs("error", args),
debug: (...args: unknown[]) => emitArgs("debug", args),
assert: async (
fn: () => boolean | Promise<boolean>,
description: string,
details?: unknown,
): Promise<void> => {
let passed: boolean;
let failureReason: string | undefined;
try {
passed = (await fn()) === true;
} catch (err) {
passed = false;
failureReason = (err as Error).message;
}
if (passed) {
emit("log", description, "assertion:pass");
return;
}
const message = failureReason
? `Assertion failed: ${description} (${failureReason})`
: `Assertion failed: ${description}`;
const failureData =
failureReason !== undefined || details !== undefined
? {
...(failureReason !== undefined && { error: failureReason }),
...(details !== undefined && { details }),
}
: undefined;
emit("error", message, "assertion:fail", failureData);
throw new AssertionFailedError(
message,
`Assertion failed: ${description}`,
);
},
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
getCredential: (alias: string): unknown => {
if (!(alias in credMap)) {
throw new Error(
`Credential alias "${alias}" not found in this scenario`,
);
}
return credMap[alias];
},
env: { ...envData },
getEnv: (key: string): string => {
const value = envData[key];
if (value == null) {
throw new Error(
`Environment value "${key}" is not defined for this environment`,
);
}
return value;
},
runSnippet: async (
alias: string,
...args: unknown[]
): Promise<unknown> => {
const snippetCode = snippetMap[alias];
if (snippetCode == null) {
throw new Error(`Snippet alias "${alias}" not found`);
}
const snippetContext = `snippet:${alias}`;
contextStack.push(snippetContext);
emit("log", `Snippet "${alias}" started`, snippetContext);
const snippetFn = new Function(
"context",
"console",
"snippetArgs",
"expect",
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
);
try {
const snippetResult = await snippetFn(
scriptContext,
fakeConsole,
args,
playwrightExpect,
);
emit("log", `Snippet "${alias}" finished`, snippetContext);
return snippetResult;
} catch (err) {
emit(
"error",
`Snippet "${alias}" failed: ${findAssertionFailure(err)?.summary ?? (err as Error).message}`,
snippetContext,
);
throw err;
} finally {
contextStack.pop();
}
},
getScenarioFiles: async (opts?: { limit?: number; offset?: number }) => {
if (!fileService || !scenarioId) {
throw new Error("File service not available in this context");
}
const result = await fileService.listScenarioFiles(
scenarioId,
opts?.limit,
opts?.offset,
);
return {
items: result.items.map((item) => ({
id: item.id,
name: item.name,
mimeType: item.mimeType,
size: item.size,
sha256: item.sha256,
path: item.path,
})),
total: result.total,
};
},
downloadFile: async (
url: string,
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
) => {
if (!fileService || !scenarioId || !runId) {
throw new Error("File service or run context not available");
}
// Download file
const buffer = await downloadFileImpl(url, opts);
// Determine filename and mime type
const filename = opts?.filename ?? new URL(url).pathname.split("/").pop() ?? "download";
const mimeType = this.getMimeType(filename);
// Create run artifact with mapping
const savedFile = await fileService.createAndSaveRunArtifact(
runId,
buffer,
filename,
mimeType,
);
return {
id: savedFile.id,
name: savedFile.originalName,
mimeType: savedFile.mimeType,
size: savedFile.size,
sha256: savedFile.sha256,
path: fileService.getAbsolutePath(savedFile.filePath),
};
},
};
// `console` and `expect` are injected as named parameters so scripts
// can reference them directly.
const fn = new Function(
"context",
"console",
"expect",
`return (async (context) => { ${code} })(context)`,
);
this.logger.debug("Executing user code");
const execResult = await fn(
scriptContext,
fakeConsole,
playwrightExpect,
);
return { result: execResult };
} catch (err) {
throw new InternalServerErrorException(
`Code execution failed: ${(err as Error).message}`,
{ cause: err },
);
}
}
/**
* Infers MIME type from filename.
*/
private getMimeType(filename: string): string {
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
const mimeTypes: Record<string, string> = {
pdf: "application/pdf",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
csv: "text/csv",
txt: "text/plain",
zip: "application/zip",
};
return mimeTypes[ext] ?? "application/octet-stream";
}
}