Files
liqa/server/src/scenario/scenario.controller.ts
T
ars9 81164f8494
CI / changes (pull_request) Successful in 14s
CI / server (pull_request) Successful in 2m25s
CI / client (pull_request) Successful in 1m35s
CI / image (pull_request) Skipped
feat: export e2e tests for a chosen scenario version
- GET /scenarios/:id/export-e2e and the export_e2e_test MCP tool take
  an optional version, defaulting to the latest
- build the test project from that version's steps, name and timeout
- put the version in the zip name (<scenario>-vN-e2e-test.zip), the
  generated package name and the README heading
- the Export e2e test button exports the version being viewed
- document the e2e export in scenario.md and mcp.md
2026-10-08 18:37:33 +03:00

490 lines
17 KiB
TypeScript

import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
ParseIntPipe,
ParseUUIDPipe,
Patch,
Post,
Query,
Res,
Sse,
UseInterceptors,
UploadedFile,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Response } from "express";
import { interval, map, merge, type Observable } from "rxjs";
import type { File as MulterFile } from "multer";
import { stringify as yamlStringify } from "yaml";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
import { CreateScenarioRunDto } from "./dto/create-scenario-run.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { ScenarioQueryDto } from "./dto/pagination-query.dto";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ExportEntity, ScenarioExportDto } from "./dto/scenario-export.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { RunEventsService } from "./run-events.service";
import { ScenarioService } from "./scenario.service";
import { E2eExportService } from "./e2e-export.service";
interface SseMessage {
type: string;
data: object;
}
@ApiTags("scenarios")
@Controller("scenarios")
export class ScenarioController {
private static readonly HEARTBEAT_MS = 25_000;
constructor(
private readonly scenarioService: ScenarioService,
private readonly e2eExportService: E2eExportService,
private readonly runEvents: RunEventsService,
) {}
// ── Scenarios ─────────────────────────────────────────────────────────────
@Post()
@ApiOperation({ summary: "Create a scenario" })
@ApiResponse({ status: 201, description: "Scenario created" })
create(@Body() dto: CreateScenarioDto) {
return this.scenarioService.create(dto);
}
@Post("import")
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" })
@ApiResponse({ status: 201, description: "Scenario imported" })
importScenario(@Body() payload: unknown) {
return this.scenarioService.importScenario(
payload as ScenarioExportDto | ExportEntity[],
);
}
@Get()
@ApiOperation({ summary: "List all scenarios (paginated)" })
@ApiResponse({ status: 200 })
findAll(@Query() query: ScenarioQueryDto) {
return this.scenarioService.findAll(query);
}
@Get("runs")
@ApiOperation({
summary: "List runs across all scenarios (paginated, filterable by status)",
})
@ApiResponse({ status: 200 })
findAllRuns(@Query() query: RunsQueryDto) {
return this.scenarioService.findAllRuns(query);
}
@Sse("runs/events")
@ApiOperation({
summary:
"Server-sent events stream of run lifecycle events (run.started, run.finished) for all scenarios",
})
@ApiResponse({ status: 200, description: "text/event-stream" })
streamRunEvents(): Observable<SseMessage> {
const events = this.runEvents
.stream()
.pipe(map((event): SseMessage => ({ type: event.type, data: event })));
// Periodic named event so proxies don't drop an idle connection
const heartbeat = interval(ScenarioController.HEARTBEAT_MS).pipe(
map((): SseMessage => ({ type: "ping", data: {} })),
);
return merge(events, heartbeat);
}
@Get("run-defaults")
@ApiOperation({ summary: "Get server-configured defaults for new runs" })
@ApiResponse({ status: 200 })
getRunDefaults() {
return this.scenarioService.getRunDefaults();
}
@Get(":id")
@ApiOperation({ summary: "Get a scenario with its steps" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.findOne(id);
}
@Patch(":id")
@ApiOperation({ summary: "Update a scenario" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
update(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: UpdateScenarioDto,
) {
return this.scenarioService.update(id, dto);
}
@Delete(":id")
@HttpCode(204)
@ApiOperation({ summary: "Delete a scenario and all its steps" })
@ApiResponse({ status: 204 })
@ApiResponse({ status: 404, description: "Scenario not found" })
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.remove(id);
}
@Get(":id/versions")
@ApiOperation({ summary: "List a scenario's versions, newest first" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
listVersions(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.listVersions(id);
}
@Get(":id/versions/:version")
@ApiOperation({ summary: "Get one version of a scenario, with its steps" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or version not found" })
findVersion(
@Param("id", ParseUUIDPipe) id: string,
@Param("version", ParseIntPipe) version: number,
) {
return this.scenarioService.findVersion(id, version);
}
@Get(":id/export")
@ApiOperation({ summary: "Export a scenario as portable YAML" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
async exportScenario(
@Param("id", ParseUUIDPipe) id: string,
@Query("includeEnvironment") includeEnvironment: string,
@Query("credentialIds") credentialIds: string | string[] | undefined,
@Query("snippetIds") snippetIds: string | string[] | undefined,
@Query("version", new ParseIntPipe({ optional: true }))
version: number | undefined,
@Res({ passthrough: true }) res: Response,
) {
const toIds = (ids: string | string[] | undefined): string[] =>
ids ? (Array.isArray(ids) ? ids : ids.split(",").filter(Boolean)) : [];
const entities = await this.scenarioService.exportScenario(id, {
includeEnvironment: includeEnvironment === "true",
credentialIds: toIds(credentialIds),
snippetIds: toIds(snippetIds),
version,
});
res.setHeader("Content-Type", "application/yaml; charset=utf-8");
// Serialize as a YAML stream: one `---` document per entity, each with a
// comment naming it. POST /import reads this format back.
const kindLabels: Record<string, string> = {
environment: "Environment",
credential: "Credential",
snippet: "Snippet",
scenario: "Scenario",
};
return (entities as ExportEntity[])
.map((entity) => {
const label = kindLabels[entity.kind ?? ""] ?? entity.kind ?? "Entity";
const title =
entity.kind === "snippet"
? `${entity.alias ?? entity.name} v${entity.version}`
: entity.name;
const comment = `# ${label}: ${title ?? entity.id ?? ""}`;
return `---\n${comment}\n${yamlStringify(entity)}`;
})
.join("");
}
@Get(":id/export-e2e")
@ApiOperation({
summary: "Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
})
@ApiResponse({ status: 200, description: "Zip archive" })
@ApiResponse({ status: 404, description: "Scenario or version not found" })
async exportE2eTest(
@Param("id", ParseUUIDPipe) id: string,
@Query("version", new ParseIntPipe({ optional: true }))
version: number | undefined,
@Res() res: Response,
) {
const { filename, buffer } = await this.e2eExportService.buildE2eTestPackage(
id,
version,
);
res.setHeader("Content-Type", "application/zip");
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
res.setHeader("Content-Length", buffer.length);
res.send(buffer);
}
// ── Steps ─────────────────────────────────────────────────────────────────
@Post(":id/steps")
@ApiOperation({ summary: "Add a step to a scenario" })
@ApiResponse({ status: 201, description: "Step created" })
@ApiResponse({ status: 404, description: "Scenario not found" })
createStep(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: CreateScenarioStepDto,
) {
return this.scenarioService.createStep(id, dto);
}
@Get(":id/steps/:stepId")
@ApiOperation({ summary: "Get a single step" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or step not found" })
findStep(
@Param("id", ParseUUIDPipe) id: string,
@Param("stepId", ParseUUIDPipe) stepId: string,
) {
return this.scenarioService.findStep(id, stepId);
}
@Patch(":id/steps/:stepId")
@ApiOperation({ summary: "Update a step" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or step not found" })
updateStep(
@Param("id", ParseUUIDPipe) id: string,
@Param("stepId", ParseUUIDPipe) stepId: string,
@Body() dto: UpdateScenarioStepDto,
) {
return this.scenarioService.updateStep(id, stepId, dto);
}
@Delete(":id/steps/:stepId")
@HttpCode(204)
@ApiOperation({ summary: "Delete a step" })
@ApiResponse({ status: 204 })
@ApiResponse({ status: 404, description: "Scenario or step not found" })
removeStep(
@Param("id", ParseUUIDPipe) id: string,
@Param("stepId", ParseUUIDPipe) stepId: string,
) {
return this.scenarioService.removeStep(id, stepId);
}
@Get(":id/used-snippets")
@ApiOperation({
summary: "List snippets referenced (directly or transitively) by this scenario's steps",
})
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
getUsedSnippets(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.getUsedSnippets(id);
}
// ── Credentials ───────────────────────────────────────────────────────────
@Get(":id/credentials")
@ApiOperation({ summary: "List credentials assigned to a scenario" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findScenarioCredentials(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.findScenarioCredentials(id);
}
@Post(":id/credentials")
@ApiOperation({ summary: "Add a credential to a scenario with an alias" })
@ApiResponse({ status: 201, description: "Credential added" })
@ApiResponse({ status: 404, description: "Scenario or credential not found" })
@ApiResponse({
status: 409,
description: "Alias already used in this scenario",
})
addScenarioCredential(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: AddScenarioCredentialDto,
) {
return this.scenarioService.addScenarioCredential(id, dto);
}
@Delete(":id/credentials/:scCredId")
@HttpCode(204)
@ApiOperation({ summary: "Remove a credential from a scenario" })
@ApiResponse({ status: 204 })
@ApiResponse({
status: 404,
description: "Scenario or credential assignment not found",
})
removeScenarioCredential(
@Param("id", ParseUUIDPipe) id: string,
@Param("scCredId", ParseUUIDPipe) scCredId: string,
) {
return this.scenarioService.removeScenarioCredential(id, scCredId);
}
// ── Runs ──────────────────────────────────────────────────────────────────
@Get(":id/runs")
@ApiOperation({
summary: "List runs for a scenario (paginated, filterable by status)",
})
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findRuns(
@Param("id", ParseUUIDPipe) id: string,
@Query() query: RunsQueryDto,
) {
return this.scenarioService.findRuns(id, query);
}
@Post(":id/run")
@ApiOperation({ summary: "Create a new run for a scenario" })
@ApiResponse({ status: 201, description: "Run created with step runs" })
@ApiResponse({ status: 404, description: "Scenario not found" })
createRun(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: CreateScenarioRunDto,
) {
return this.scenarioService.createRun(
id,
dto.environmentId,
dto.saveSession,
dto.traceMode,
dto.version,
);
}
@Get(":id/run/:runId")
@ApiOperation({ summary: "Get a specific run with step runs and logs" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or run not found" })
findRun(
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
@Query("q") q?: string,
) {
return this.scenarioService.findRun(id, runId, q);
}
@Get(":id/run/:runId/logs/export")
@ApiOperation({ summary: "Export run logs as CSV or Markdown" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or run not found" })
async exportRunLogs(
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
@Query("format") format: string | undefined,
@Res({ passthrough: true }) res: Response,
) {
const fmt = format === "csv" ? "csv" : "md";
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
const contentType =
fmt === "csv" ? "text/csv; charset=utf-8" : "text/markdown; charset=utf-8";
const ext = fmt === "csv" ? "csv" : "md";
res.setHeader("Content-Type", contentType);
res.setHeader(
"Content-Disposition",
`attachment; filename="run-${runId}-logs.${ext}"`,
);
return content;
}
@Post(":id/run/:runId/wait")
@HttpCode(200)
@ApiOperation({
summary:
"Block until the run reaches pass or fail (max 5 min), then return run with logs",
})
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or run not found" })
waitForRun(
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
) {
return this.scenarioService.waitForRun(id, runId);
}
// ── Files ─────────────────────────────────────────────────────────────────
@Post(":id/files")
@UseInterceptors(FileInterceptor("file"))
@ApiOperation({ summary: "Upload a file to a scenario" })
@ApiResponse({ status: 201, description: "File uploaded" })
@ApiResponse({ status: 404, description: "Scenario not found" })
uploadFile(
@Param("id", ParseUUIDPipe) id: string,
@UploadedFile() file: MulterFile,
@Body() body: { expiresAt?: string },
) {
return this.scenarioService.uploadFile(id, file, body.expiresAt);
}
@Get(":id/files")
@ApiOperation({ summary: "List files attached to a scenario" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
listScenarioFiles(
@Param("id", ParseUUIDPipe) id: string,
@Query("limit") limit?: string,
@Query("offset") offset?: string,
) {
return this.scenarioService.listScenarioFiles(
id,
limit ? parseInt(limit, 10) : undefined,
offset ? parseInt(offset, 10) : undefined,
);
}
@Get(":id/files/:fileId/content")
@ApiOperation({ summary: "Download file content" })
@ApiResponse({ status: 200, description: "File content" })
@ApiResponse({ status: 404, description: "Scenario or file not found" })
async getScenarioFileContent(
@Param("id", ParseUUIDPipe) id: string,
@Param("fileId", ParseUUIDPipe) fileId: string,
@Res() res: Response,
) {
return this.scenarioService.getScenarioFileContent(id, fileId, res);
}
@Get(":id/runs/:runId/files")
@ApiOperation({ summary: "List files created during a run" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or run not found" })
listRunFiles(
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
@Query("limit") limit?: string,
@Query("offset") offset?: string,
) {
return this.scenarioService.listRunFiles(
id,
runId,
limit ? parseInt(limit, 10) : undefined,
offset ? parseInt(offset, 10) : undefined,
);
}
@Get(":id/runs/:runId/files/:fileId/content")
@ApiOperation({ summary: "Download run artifact file content" })
@ApiResponse({ status: 200, description: "File content" })
@ApiResponse({ status: 404, description: "Scenario, run, or file not found" })
async getRunFileContent(
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
@Param("fileId", ParseUUIDPipe) fileId: string,
@Res() res: Response,
) {
return this.scenarioService.getRunFileContent(id, runId, fileId, res);
}
@Delete(":id/runs/:runId/files/:fileId")
@HttpCode(204)
@ApiOperation({ summary: "Delete a file from a run" })
@ApiResponse({ status: 204, description: "File deleted" })
@ApiResponse({ status: 404, description: "Scenario, run, or file not found" })
deleteRunFile(
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
@Param("fileId", ParseUUIDPipe) fileId: string,
) {
return this.scenarioService.deleteRunFile(id, runId, fileId);
}
}