chore(repo): restructure as monorepo with server and client workspaces

- move NestJS app into server/ subdirectory
- add client/ React+TypeScript (Vite) app with Hello World
- update docker-compose to build and run both services
- add root package.json declaring npm workspaces
- update .gitignore to cover node_modules and dist at all depths
This commit is contained in:
ars9 committed 2026-04-08 21:28:01 +03:00
1 parent afc4627353
commit 5cc16725fb
88 files changed
+12637 -405

No files matched your search

@@ -0,0 +1,45 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsIn,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
Min,
} from "class-validator";
import { StepType } from "../scenario-step.entity";
export class CreateScenarioStepDto {
@ApiProperty({ example: 0, description: "Execution order (ascending)" })
@IsInt()
@Min(0)
order: number;
@ApiProperty({ enum: ["login", "exec", "sign"], example: "exec" })
@IsIn(["login", "exec", "sign"])
type: StepType;
@ApiProperty({
description:
"Session name used by this step. login steps create it; exec steps consume it.",
example: "my-session",
})
@IsString()
@IsNotEmpty()
sessionName: string;
@ApiPropertyOptional({ example: "return await page.title();" })
@IsOptional()
@IsString()
@IsNotEmpty()
execCode?: string;
@ApiPropertyOptional({
example:
'return { success: result !== null, description: "title present" };',
})
@IsOptional()
@IsString()
@IsNotEmpty()
validateCode?: string;
}
@@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString } from "class-validator";
export class CreateScenarioDto {
@ApiProperty({ example: "Login and verify cabinet" })
@IsString()
@IsNotEmpty()
name: string;
}
@@ -0,0 +1 @@
export { PaginationQueryDto } from "../../common/dto/pagination.dto";
+28
View File
@@ -0,0 +1,28 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsIn, IsInt, IsOptional, Min } from "class-validator";
import { RunStatus } from "../scenario-run.entity";
export class RunsQueryDto {
@ApiPropertyOptional({ example: 1, default: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number = 1;
@ApiPropertyOptional({ example: 20, default: 20 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
limit?: number = 20;
@ApiPropertyOptional({
enum: ["pending", "in_progress", "pass", "fail"],
description: "Filter by run status",
})
@IsOptional()
@IsIn(["pending", "in_progress", "pass", "fail"])
status?: RunStatus;
}
@@ -0,0 +1,54 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsArray,
IsIn,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
Min,
ValidateNested,
} from "class-validator";
import { StepType } from "../scenario-step.entity";
export class ScenarioStepExportDto {
@ApiProperty()
@IsInt()
@Min(0)
order: number;
@ApiProperty({ enum: ["login", "exec", "sign"] })
@IsIn(["login", "exec", "sign"])
type: StepType;
@ApiProperty()
@IsString()
@IsNotEmpty()
sessionName: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
execCode: string | null;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
validateCode: string | null;
}
export class ScenarioExportDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
name: string;
@ApiProperty({ type: [ScenarioStepExportDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => ScenarioStepExportDto)
steps: ScenarioStepExportDto[];
}
@@ -0,0 +1,41 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import {
IsIn,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
Min,
} from "class-validator";
import { StepType } from "../scenario-step.entity";
export class UpdateScenarioStepDto {
@ApiPropertyOptional({ example: 0 })
@IsOptional()
@IsInt()
@Min(0)
order?: number;
@ApiPropertyOptional({ enum: ["login", "exec", "sign"] })
@IsOptional()
@IsIn(["login", "exec", "sign"])
type?: StepType;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
sessionName?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
execCode?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
validateCode?: string;
}
@@ -0,0 +1,10 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsNotEmpty } from "class-validator";
export class UpdateScenarioDto {
@ApiPropertyOptional({ example: "Updated scenario name" })
@IsOptional()
@IsString()
@IsNotEmpty()
name?: string;
}
@@ -0,0 +1,44 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
} from "typeorm";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
export type LogLevel = "log" | "warn" | "error";
@Entity("scenario_run_logs")
export class ScenarioRunLogEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
runId: number;
@ManyToOne(() => ScenarioRunEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "runId" })
run: ScenarioRunEntity;
@Column({ nullable: true })
stepRunId: number | null;
@ManyToOne(() => ScenarioRunStepEntity, {
onDelete: "SET NULL",
nullable: true,
})
@JoinColumn({ name: "stepRunId" })
stepRun: ScenarioRunStepEntity | null;
@Column({ type: "text", default: "log" })
level: LogLevel;
@Column({ type: "text" })
message: string;
@CreateDateColumn()
createdAt: Date;
}
@@ -0,0 +1,59 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from "typeorm";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
export type RunStepStatus =
| "waiting"
| "pending"
| "in_progress"
| "pass"
| "fail"
| "cancelled";
@Entity("scenario_run_steps")
export class ScenarioRunStepEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
runId: number;
@ManyToOne(() => ScenarioRunEntity, (run) => run.stepRuns, {
onDelete: "CASCADE",
})
@JoinColumn({ name: "runId" })
run: ScenarioRunEntity;
@Column()
scenarioStepId: number;
@ManyToOne(() => ScenarioStepEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioStepId" })
scenarioStep: ScenarioStepEntity;
@Column({ type: "text", default: "waiting" })
status: RunStepStatus;
@Column({ default: 0 })
order: number;
@Column({ type: "text", nullable: true })
description: string | null;
@Column({ type: "text", nullable: true })
output: string | null;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
@@ -0,0 +1,42 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
OneToMany,
JoinColumn,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
export type RunStatus = "pending" | "in_progress" | "pass" | "fail";
@Entity("scenario_runs")
export class ScenarioRunEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
scenarioId: number;
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioId" })
scenario: ScenarioEntity;
@Column({ type: "text", default: "pending" })
status: RunStatus;
@OneToMany(() => ScenarioRunStepEntity, (rs) => rs.run, {
cascade: true,
eager: false,
})
stepRuns: ScenarioRunStepEntity[];
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
@@ -0,0 +1,411 @@
import { Injectable } from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { traceStorage } from "../common/trace-context";
import { Interval } from "@nestjs/schedule";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import * as crypto from "crypto";
import { chromium } from "playwright";
import type { Browser, BrowserContext, Page } from "playwright";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import type { ScriptLogger } from "../code-executor/code-executor.service";
import { AuthService } from "../auth/auth.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { SessionService } from "../session/session.service";
interface ValidateResult {
success: boolean;
description?: string;
}
interface BrowserHandle {
browser: Browser;
context: BrowserContext;
page: Page;
}
@Injectable()
export class ScenarioSchedulerService {
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
private readonly activeRuns = new Set<number>();
private readonly runBrowsers = new Map<number, BrowserHandle>();
constructor(
@InjectRepository(ScenarioRunEntity)
private readonly runRepo: Repository<ScenarioRunEntity>,
@InjectRepository(ScenarioRunStepEntity)
private readonly runStepRepo: Repository<ScenarioRunStepEntity>,
@InjectRepository(ScenarioRunLogEntity)
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
private readonly authService: AuthService,
private readonly codeExecutor: CodeExecutorService,
private readonly sessionService: SessionService,
) {}
private persistLog(
runId: number,
stepRunId: number | null,
level: "log" | "warn" | "error",
message: string,
): void {
void this.runLogRepo.save(
this.runLogRepo.create({ runId, stepRunId, level, message }),
);
}
private stepLogger(stepRunId: number, runId: number): ScriptLogger {
return (level, msg) => {
this.logger[level](`StepRun #${stepRunId} script: ${msg}`);
this.persistLog(runId, stepRunId, level, msg);
};
}
private makeGetStepOutput(
stepRun: ScenarioRunStepEntity,
): (order: number) => Promise<unknown> {
return async (order: number) => {
const targetOrder = order < 0 ? stepRun.order + order : order;
if (targetOrder < 0) return null;
const sr = await this.runStepRepo.findOne({
where: { runId: stepRun.runId, order: targetOrder },
});
if (!sr?.output) return null;
try {
return JSON.parse(sr.output) as unknown;
} catch {
return sr.output;
}
};
}
// ── Job: pick up pending runs and process each to completion ─────────────
@Interval(1000)
async pickUpPendingRuns(): Promise<void> {
const pending = await this.runRepo.find({ where: { status: "pending" } });
for (const run of pending) {
if (this.activeRuns.has(run.id)) continue;
this.activeRuns.add(run.id);
run.status = "in_progress";
await this.runRepo.save(run);
this.logger.log(`Run #${run.id} → in_progress`);
const traceId = crypto.randomUUID();
void traceStorage.run({ traceId }, () =>
this.processRunToCompletion(run.id),
);
}
}
private async processRunToCompletion(runId: number): Promise<void> {
try {
let stepRun = await this.runStepRepo.findOne({
where: { runId, status: "pending" },
relations: ["scenarioStep"],
order: { order: "ASC" },
});
while (stepRun) {
await this.executeStepRun(stepRun);
stepRun = await this.runStepRepo.findOne({
where: { runId, status: "pending" },
relations: ["scenarioStep"],
order: { order: "ASC" },
});
}
} catch (err) {
this.logger.error(
`Run #${runId}: unexpected error: ${(err as Error).message}`,
);
await this.runRepo.update(runId, { status: "fail" });
} finally {
this.activeRuns.delete(runId);
}
}
private async executeStepRun(stepRun: ScenarioRunStepEntity): Promise<void> {
const step = stepRun.scenarioStep as ScenarioStepEntity;
stepRun.status = "in_progress";
await this.runStepRepo.save(stepRun);
this.logger.log(
`StepRun #${stepRun.id} (run #${stepRun.runId}, step #${step.id} order=${step.order}) → in_progress`,
);
try {
if (step.type === "login") {
await this.executeLoginStep(stepRun, step);
} else if (step.type === "sign") {
await this.executeSignStep(stepRun, step);
} else {
await this.executeExecStep(stepRun, step);
}
} catch (err) {
const msg = (err as Error).message ?? String(err);
this.logger.error(`StepRun #${stepRun.id} threw: ${msg}`);
await this.failStepRun(stepRun, msg);
}
}
// ── Shared browser per run ─────────────────────────────────────────────────
private async getOrCreateBrowserHandle(
runId: number,
sessionName: string,
): Promise<BrowserHandle> {
const existing = this.runBrowsers.get(runId);
if (existing) return existing;
const session = await this.sessionService.findBySessionName(sessionName);
if (!session) throw new Error(`Session not found: ${sessionName}`);
const cookies = JSON.parse(session.cookies) as Parameters<
BrowserContext["addCookies"]
>[0];
const localStorageData: Record<string, string> = JSON.parse(
session.localStorage,
);
const browser = await chromium.launch({
headless: true,
// TODO: env var move to config
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext();
await context.addCookies(cookies);
await context.addInitScript((entries: Record<string, string>) => {
for (const [k, v] of Object.entries(entries))
window.localStorage.setItem(k, v);
}, localStorageData);
const page = await context.newPage();
const handle: BrowserHandle = { browser, context, page };
this.runBrowsers.set(runId, handle);
this.logger.log(`Run #${runId}: browser created (session: ${sessionName})`);
return handle;
}
private async closeBrowserHandle(runId: number): Promise<void> {
const handle = this.runBrowsers.get(runId);
if (!handle) return;
this.runBrowsers.delete(runId);
try {
await handle.browser.close();
this.logger.log(`Run #${runId}: browser closed`);
} catch (err) {
this.logger.warn(
`Run #${runId}: error closing browser: ${(err as Error).message}`,
);
}
}
// ── Login step ─────────────────────────────────────────────────────────────
private async executeLoginStep(
stepRun: ScenarioRunStepEntity,
step: ScenarioStepEntity,
): Promise<void> {
// execCode must be a JSON object: { "keyId": "...", "environmentName": "..." }
let params: { keyId: string; environmentName: string };
try {
params = JSON.parse(step.execCode ?? "{}");
} catch {
throw new Error(
"login step execCode must be valid JSON with keyId and environmentName",
);
}
if (!params.keyId || !params.environmentName) {
throw new Error(
"login step execCode must include keyId and environmentName",
);
}
const loginResult = await this.authService.login(
params.keyId,
params.environmentName,
step.sessionName,
);
this.logger.log(
`StepRun #${stepRun.id}: login OK, session=${loginResult.sessionName}`,
);
if (step.validateCode) {
const { page, context } = await this.getOrCreateBrowserHandle(
stepRun.runId,
step.sessionName,
);
this.codeExecutor.validate(step.validateCode);
const { result } = await this.codeExecutor.execute(
page,
context,
step.validateCode,
this.stepLogger(stepRun.id, stepRun.runId),
this.makeGetStepOutput(stepRun),
);
const vr = this.parseValidateResult(result);
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
}
await this.passStepRun(stepRun, null);
}
// ── Exec step ──────────────────────────────────────────────────────────────
private async executeExecStep(
stepRun: ScenarioRunStepEntity,
step: ScenarioStepEntity,
): Promise<void> {
if (!step.execCode) throw new Error("exec step has no execCode");
this.codeExecutor.validate(step.execCode);
const { page, context } = await this.getOrCreateBrowserHandle(
stepRun.runId,
step.sessionName,
);
const getStepOutput = this.makeGetStepOutput(stepRun);
const { result: execOutput } = await this.codeExecutor.execute(
page,
context,
step.execCode,
this.stepLogger(stepRun.id, stepRun.runId),
getStepOutput,
);
this.logger.log(`StepRun #${stepRun.id}: exec OK`);
if (step.validateCode) {
this.codeExecutor.validate(step.validateCode);
const { result } = await this.codeExecutor.execute(
page,
context,
step.validateCode,
this.stepLogger(stepRun.id, stepRun.runId),
getStepOutput,
);
const vr = this.parseValidateResult(result);
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
}
await this.passStepRun(stepRun, null, execOutput);
}
// ── Sign step ──────────────────────────────────────────────────────────────
private async executeSignStep(
stepRun: ScenarioRunStepEntity,
step: ScenarioStepEntity,
): Promise<void> {
// execCode must be a JSON object: { "keyId": "..." }
let params: { keyId: string };
try {
params = JSON.parse(step.execCode ?? "{}");
} catch {
throw new Error("sign step execCode must be valid JSON with keyId");
}
if (!params.keyId) throw new Error("sign step execCode must include keyId");
const { page, context } = await this.getOrCreateBrowserHandle(
stepRun.runId,
step.sessionName,
);
await this.authService.signWithKey(params.keyId, page);
this.logger.log(`StepRun #${stepRun.id}: sign OK`);
if (step.validateCode) {
this.codeExecutor.validate(step.validateCode);
const { result } = await this.codeExecutor.execute(
page,
context,
step.validateCode,
this.stepLogger(stepRun.id, stepRun.runId),
this.makeGetStepOutput(stepRun),
);
const vr = this.parseValidateResult(result);
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
}
await this.passStepRun(stepRun, null);
}
// ── Validation helper ──────────────────────────────────────────────────────
private parseValidateResult(raw: unknown): ValidateResult {
if (typeof raw === "boolean") return { success: raw };
if (raw && typeof raw === "object") {
const r = raw as Record<string, unknown>;
return {
success: Boolean(r["success"]),
description:
r["description"] != null ? String(r["description"]) : undefined,
};
}
return { success: Boolean(raw) };
}
// ── Pass / fail helpers ────────────────────────────────────────────────────
private async passStepRun(
stepRun: ScenarioRunStepEntity,
description: string | null,
output: unknown = null,
): Promise<void> {
stepRun.status = "pass";
stepRun.description = description;
stepRun.output =
output !== null && output !== undefined ? JSON.stringify(output) : null;
await this.runStepRepo.save(stepRun);
this.logger.log(`StepRun #${stepRun.id} → pass`);
// Find the next waiting step in this run (next by order)
const nextStep = await this.runStepRepo.findOne({
where: { runId: stepRun.runId, status: "waiting" },
order: { order: "ASC" },
});
if (nextStep) {
nextStep.status = "pending";
await this.runStepRepo.save(nextStep);
} else {
// No more waiting steps — check if any are still in_progress/pending (shouldn't be, but guard anyway)
const remaining = await this.runStepRepo.count({
where: [
{ runId: stepRun.runId, status: "pending" },
{ runId: stepRun.runId, status: "in_progress" },
{ runId: stepRun.runId, status: "waiting" },
],
});
if (remaining === 0) {
await this.closeBrowserHandle(stepRun.runId);
await this.runRepo.update(stepRun.runId, { status: "pass" });
this.logger.log(`Run #${stepRun.runId} → pass (all steps passed)`);
}
}
}
private async failStepRun(
stepRun: ScenarioRunStepEntity,
description: string,
): Promise<void> {
stepRun.status = "fail";
stepRun.description = description;
await this.runStepRepo.save(stepRun);
this.logger.log(`StepRun #${stepRun.id} → fail: ${description}`);
// Cancel all remaining waiting/pending step runs in this run
await this.runStepRepo
.createQueryBuilder()
.update()
.set({ status: "cancelled" })
.where("runId = :runId AND status IN (:...statuses)", {
runId: stepRun.runId,
statuses: ["waiting", "pending"],
})
.execute();
this.logger.log(`Run #${stepRun.runId}: remaining steps cancelled`);
await this.closeBrowserHandle(stepRun.runId);
await this.runRepo.update(stepRun.runId, { status: "fail" });
this.logger.log(`Run #${stepRun.runId} → fail`);
}
}
@@ -0,0 +1,48 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
export type StepType = "login" | "exec" | "sign";
@Entity("scenario_steps")
export class ScenarioStepEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
scenarioId: number;
@ManyToOne(() => ScenarioEntity, (scenario) => scenario.steps, {
onDelete: "CASCADE",
})
@JoinColumn({ name: "scenarioId" })
scenario: ScenarioEntity;
@Column({ default: 0 })
order: number;
@Column({ type: "text" })
type: StepType;
@Column({ type: "text" })
sessionName: string;
@Column({ type: "text", nullable: true })
execCode: string | null;
@Column({ type: "text", nullable: true })
validateCode: string | null;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
+184
View File
@@ -0,0 +1,184 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
ParseIntPipe,
Patch,
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { ScenarioService } from "./scenario.service";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { PaginationQueryDto } from "./dto/pagination-query.dto";
import { ScenarioOrderBy } from "./scenario.service";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ScenarioExportDto } from "./dto/scenario-export.dto";
@ApiTags("scenarios")
@Controller("scenarios")
export class ScenarioController {
constructor(private readonly scenarioService: ScenarioService) {}
// ── 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" })
@ApiResponse({ status: 201, description: "Scenario imported" })
importScenario(@Body() dto: ScenarioExportDto) {
return this.scenarioService.importScenario(dto);
}
@Get()
@ApiOperation({ summary: "List all scenarios (paginated)" })
@ApiResponse({ status: 200 })
findAll(@Query() query: PaginationQueryDto<ScenarioOrderBy>) {
return this.scenarioService.findAll(query);
}
@Get(":id")
@ApiOperation({ summary: "Get a scenario with its steps" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findOne(@Param("id", ParseIntPipe) id: number) {
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", ParseIntPipe) id: number,
@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", ParseIntPipe) id: number) {
return this.scenarioService.remove(id);
}
@Get(":id/export")
@ApiOperation({ summary: "Export a scenario as a portable JSON payload" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
exportScenario(@Param("id", ParseIntPipe) id: number) {
return this.scenarioService.exportScenario(id);
}
// ── 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", ParseIntPipe) id: number,
@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", ParseIntPipe) id: number,
@Param("stepId", ParseIntPipe) stepId: number,
) {
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", ParseIntPipe) id: number,
@Param("stepId", ParseIntPipe) stepId: number,
@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", ParseIntPipe) id: number,
@Param("stepId", ParseIntPipe) stepId: number,
) {
return this.scenarioService.removeStep(id, stepId);
}
// ── 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", ParseIntPipe) id: number,
@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", ParseIntPipe) id: number) {
return this.scenarioService.createRun(id);
}
@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", ParseIntPipe) id: number,
@Param("runId", ParseIntPipe) runId: number,
) {
return this.scenarioService.findRun(id, runId);
}
@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", ParseIntPipe) id: number,
@Param("runId", ParseIntPipe) runId: number,
) {
return this.scenarioService.waitForRun(id, runId);
}
}
+30
View File
@@ -0,0 +1,30 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
OneToMany,
} from "typeorm";
import { ScenarioStepEntity } from "./scenario-step.entity";
@Entity("scenarios")
export class ScenarioEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => ScenarioStepEntity, (step) => step.scenario, {
cascade: true,
eager: false,
})
steps: ScenarioStepEntity[];
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
+32
View File
@@ -0,0 +1,32 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioService } from "./scenario.service";
import { ScenarioController } from "./scenario.controller";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { AuthModule } from "../auth/auth.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { SessionModule } from "../session/session.module";
@Module({
imports: [
TypeOrmModule.forFeature([
ScenarioEntity,
ScenarioStepEntity,
ScenarioRunEntity,
ScenarioRunStepEntity,
ScenarioRunLogEntity,
]),
AuthModule,
CodeExecutorModule,
SessionModule,
],
controllers: [ScenarioController],
providers: [ScenarioService, ScenarioSchedulerService],
exports: [ScenarioService],
})
export class ScenarioModule {}
+245
View File
@@ -0,0 +1,245 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ScenarioExportDto } from "./dto/scenario-export.dto";
export { PaginatedResult } from "../common/dto/pagination.dto";
export type ScenarioOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@Injectable()
export class ScenarioService {
constructor(
@InjectRepository(ScenarioEntity)
private readonly scenarioRepo: Repository<ScenarioEntity>,
@InjectRepository(ScenarioStepEntity)
private readonly stepRepo: Repository<ScenarioStepEntity>,
@InjectRepository(ScenarioRunEntity)
private readonly runRepo: Repository<ScenarioRunEntity>,
@InjectRepository(ScenarioRunStepEntity)
private readonly runStepRepo: Repository<ScenarioRunStepEntity>,
@InjectRepository(ScenarioRunLogEntity)
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
) {}
// ── Scenarios ─────────────────────────────────────────────────────────────
create(dto: CreateScenarioDto): Promise<ScenarioEntity> {
return this.scenarioRepo.save(this.scenarioRepo.create(dto));
}
async findAll(
query: PaginationQueryDto<ScenarioOrderBy>,
): Promise<PaginatedResult<ScenarioEntity>> {
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const orderBy = query.orderBy ?? "id";
const orderDir = query.orderDir ?? "ASC";
const [data, total] = await this.scenarioRepo.findAndCount({
order: { [orderBy]: orderDir },
skip: (page - 1) * limit,
take: limit,
});
return { data, total, page, limit };
}
async findOne(id: number): Promise<ScenarioEntity> {
const scenario = await this.scenarioRepo.findOne({
where: { id },
relations: ["steps"],
order: { steps: { order: "ASC" } },
});
if (!scenario) throw new NotFoundException(`Scenario ${id} not found`);
return scenario;
}
async update(id: number, dto: UpdateScenarioDto): Promise<ScenarioEntity> {
const scenario = await this.findOne(id);
Object.assign(scenario, dto);
return this.scenarioRepo.save(scenario);
}
async remove(id: number): Promise<void> {
await this.findOne(id);
await this.scenarioRepo.delete(id);
}
// ── Steps ─────────────────────────────────────────────────────────────────
async createStep(
scenarioId: number,
dto: CreateScenarioStepDto,
): Promise<ScenarioStepEntity> {
await this.findOne(scenarioId);
return this.stepRepo.save(
this.stepRepo.create({
...dto,
scenarioId,
execCode: dto.execCode ?? null,
validateCode: dto.validateCode ?? null,
}),
);
}
async findStep(
scenarioId: number,
stepId: number,
): Promise<ScenarioStepEntity> {
const step = await this.stepRepo.findOneBy({ id: stepId, scenarioId });
if (!step)
throw new NotFoundException(
`Step ${stepId} not found in scenario ${scenarioId}`,
);
return step;
}
async updateStep(
scenarioId: number,
stepId: number,
dto: UpdateScenarioStepDto,
): Promise<ScenarioStepEntity> {
const step = await this.findStep(scenarioId, stepId);
Object.assign(step, dto);
return this.stepRepo.save(step);
}
async removeStep(scenarioId: number, stepId: number): Promise<void> {
await this.findStep(scenarioId, stepId);
await this.stepRepo.delete(stepId);
}
async findRuns(
scenarioId: number,
query: RunsQueryDto,
): Promise<PaginatedResult<ScenarioRunEntity>> {
await this.findOne(scenarioId); // 404 guard
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const where: Record<string, unknown> = { scenarioId };
if (query.status) where["status"] = query.status;
const [data, total] = await this.runRepo.findAndCount({
where,
relations: ["stepRuns"],
order: { id: "DESC", stepRuns: { order: "ASC" } },
skip: (page - 1) * limit,
take: limit,
});
return { data, total, page, limit };
}
async findRun(
scenarioId: number,
runId: number,
): Promise<ScenarioRunEntity & { logs: ScenarioRunLogEntity[] }> {
await this.findOne(scenarioId); // 404 guard
const run = await this.runRepo.findOne({
where: { id: runId, scenarioId },
relations: ["stepRuns", "stepRuns.scenarioStep"],
order: { stepRuns: { order: "ASC" } },
});
if (!run)
throw new NotFoundException(
`Run ${runId} not found in scenario ${scenarioId}`,
);
const logs = await this.runLogRepo.find({
where: { runId },
order: { createdAt: "ASC" },
});
return Object.assign(run, { logs });
}
async waitForRun(
scenarioId: number,
runId: number,
timeoutMs = 300_000,
): Promise<ScenarioRunEntity & { logs: ScenarioRunLogEntity[] }> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const run = await this.runRepo.findOneBy({ id: runId, scenarioId });
if (!run)
throw new NotFoundException(
`Run ${runId} not found in scenario ${scenarioId}`,
);
if (run.status === "pass" || run.status === "fail") {
return this.findRun(scenarioId, runId);
}
await new Promise<void>((resolve) => setTimeout(resolve, 500));
}
return this.findRun(scenarioId, runId);
}
async createRun(scenarioId: number): Promise<ScenarioRunEntity> {
const scenario = await this.findOne(scenarioId);
const run = await this.runRepo.save(
this.runRepo.create({ scenarioId, status: "pending" }),
);
const stepRuns = scenario.steps.map((step, index) =>
this.runStepRepo.create({
runId: run.id,
scenarioStepId: step.id,
order: step.order,
status: index === 0 ? "pending" : "waiting",
description: null,
}),
);
await this.runStepRepo.save(stepRuns);
return this.runRepo.findOne({
where: { id: run.id },
relations: ["stepRuns"],
order: { stepRuns: { order: "ASC" } },
}) as Promise<ScenarioRunEntity>;
}
// ── Export / Import ───────────────────────────────────────────────────────
async exportScenario(id: number): Promise<ScenarioExportDto> {
const scenario = await this.findOne(id);
return {
name: scenario.name,
steps: scenario.steps.map((s) => ({
order: s.order,
type: s.type,
sessionName: s.sessionName,
execCode: s.execCode,
validateCode: s.validateCode,
})),
};
}
async importScenario(dto: ScenarioExportDto): Promise<ScenarioEntity> {
const scenario = await this.scenarioRepo.save(
this.scenarioRepo.create({ name: dto.name }),
);
if (dto.steps.length > 0) {
const steps = dto.steps.map((s) =>
this.stepRepo.create({
scenarioId: scenario.id,
order: s.order,
type: s.type,
sessionName: s.sessionName,
execCode: s.execCode ?? null,
validateCode: s.validateCode ?? null,
}),
);
await this.stepRepo.save(steps);
}
return this.findOne(scenario.id);
}
}