feat(files): add file storage subsystem with scenario and run artifact support

- add FileEntity, ScenarioFileEntity, ScenarioRunFileEntity with UUID-sharded disk tree
- FileStorageService: write/sha256/expiry, paginated listing, dynamic cleanup cron via SchedulerRegistry
- expose getScenarioFiles() and downloadFile() on ScriptContext for use in exec code
- wire scenarioId, runId, fileService into ExecContextBuilder and scenario scheduler
- add file upload and listing endpoints to ScenarioController
- add FILES_DIR, FILE_RUN_EXPIRATION_DAYS, FILE_CLEANUP_CRON to AppConfig
This commit is contained in:
ars9 committed 2026-04-21 13:01:09 +03:00
1 parent aa3bae9020
commit 6a91ce30e3
15 files changed
+864

No files matched your search

@@ -6,6 +6,7 @@ import { Effect } from "effect";
import type { Browser, BrowserContext, Page } from "playwright";
import { chromium } from "playwright";
import { Repository } from "typeorm";
import { FileStorageService } from "../file/file-storage.service";
import type { ScriptLogger } from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
@@ -43,6 +44,8 @@ export class ScenarioSchedulerService implements OnModuleInit {
private readonly runEnvironments = new Map<string, EnvironmentData>();
// Cache scenario-level timeout (seconds) per run
private readonly runScenarioTimeouts = new Map<string, number | null>();
// Cache scenarioId per run
private readonly runScenarioIds = new Map<string, string>();
private static readonly DEFAULT_SCENARIO_TIMEOUT_SEC = 600;
private static readonly DEFAULT_STEP_TIMEOUT_SEC = 60;
@@ -62,6 +65,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
private readonly snippetService: SnippetService,
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly fileStorageService: FileStorageService,
) {}
async onModuleInit(): Promise<void> {
@@ -198,6 +202,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
.findOne(run.scenarioId)
.catch(() => null);
this.runScenarioTimeouts.set(run.id, scenario?.timeoutSeconds ?? null);
this.runScenarioIds.set(run.id, run.scenarioId);
const traceId = crypto.randomUUID();
void traceStorage.run({ traceId }, () =>
this.processRunToCompletion(run.id),
@@ -210,6 +215,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
this.runSnippets.delete(run.id);
this.runEnvironments.delete(run.id);
this.runScenarioTimeouts.delete(run.id);
this.runScenarioIds.delete(run.id);
this.logger.error(
`Run #${run.id}: setup failed — ${String(err)}`,
);
@@ -272,6 +278,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
this.runSnippets.delete(runId);
this.runEnvironments.delete(runId);
this.runScenarioTimeouts.delete(runId);
this.runScenarioIds.delete(runId);
await this.maybePreserveSession(runId);
}
}
@@ -349,6 +356,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
const creds = this.runCredentials.get(stepRun.runId);
const snips = this.runSnippets.get(stepRun.runId);
const env = this.runEnvironments.get(stepRun.runId);
const scenarioId = this.runScenarioIds.get(stepRun.runId);
const execCtx = new ExecContextBuilder()
.page(page)
.browser(context)
@@ -358,6 +366,9 @@ export class ScenarioSchedulerService implements OnModuleInit {
.credentials(creds)
.environment(env)
.snippets(snips)
.scenarioId(scenarioId)
.runId(stepRun.runId)
.fileService(this.fileStorageService)
.build();
const scenarioTimeoutSec = this.runScenarioTimeouts.get(stepRun.runId) ?? null;
@@ -10,9 +10,13 @@ import {
Post,
Query,
Res,
UseInterceptors,
UploadedFile,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Response } from "express";
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";
@@ -270,4 +274,78 @@ export class ScenarioController {
) {
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);
}
}
+6
View File
@@ -4,6 +4,9 @@ import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialEntity } from "../credential/credential.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { EnvironmentModule } from "../environment/environment.module";
import { FileModule } from "../file/file.module";
import { ScenarioFileEntity } from "../file/scenario-file.entity";
import { ScenarioRunFileEntity } from "../file/scenario-run-file.entity";
import { SessionModule } from "../session/session.module";
import { SnippetModule } from "../snippet/snippet.module";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
@@ -27,11 +30,14 @@ import { ScenarioService } from "./scenario.service";
ScenarioCredentialEntity,
CredentialEntity,
EnvironmentEntity,
ScenarioFileEntity,
ScenarioRunFileEntity,
]),
CodeExecutorModule,
SessionModule,
EnvironmentModule,
SnippetModule,
FileModule,
],
controllers: [ScenarioController],
providers: [ScenarioService, ScenarioSchedulerService],
+175
View File
@@ -12,6 +12,9 @@ import {
} from "../common/dto/pagination.dto";
import { CredentialEntity } from "../credential/credential.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { FileStorageService } from "../file/file-storage.service";
import { ScenarioFileEntity } from "../file/scenario-file.entity";
import { ScenarioRunFileEntity } from "../file/scenario-run-file.entity";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
@@ -30,6 +33,8 @@ import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioEntity } from "./scenario.entity";
import { Response } from "express";
import type { File as MulterFile } from "multer";
export { PaginatedResult } from "../common/dto/pagination.dto";
export type ScenarioOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@@ -53,6 +58,11 @@ export class ScenarioService {
private readonly credentialRepo: Repository<CredentialEntity>,
@InjectRepository(EnvironmentEntity)
private readonly environmentRepo: Repository<EnvironmentEntity>,
@InjectRepository(ScenarioFileEntity)
private readonly scenarioFileRepo: Repository<ScenarioFileEntity>,
@InjectRepository(ScenarioRunFileEntity)
private readonly scenarioRunFileRepo: Repository<ScenarioRunFileEntity>,
private readonly fileStorageService: FileStorageService,
) {}
// ── Scenarios ─────────────────────────────────────────────────────────────
@@ -651,4 +661,169 @@ export class ScenarioService {
}
return this.findOne(scenario.id);
}
// ── Files ─────────────────────────────────────────────────────────────────
async uploadFile(
scenarioId: string,
file: MulterFile,
expiresAtStr?: string,
): Promise<any> {
// Verify scenario exists
await this.findOne(scenarioId);
if (!file) {
throw new BadRequestException("No file provided");
}
// Parse optional expiresAt
let expiresAt: Date | undefined = undefined;
if (expiresAtStr) {
expiresAt = new Date(expiresAtStr);
if (isNaN(expiresAt.getTime())) {
throw new BadRequestException("Invalid expiresAt date");
}
}
// Save file to disk and database
const savedFile = await this.fileStorageService.saveFile(
file.buffer,
file.originalname,
file.mimetype,
expiresAt,
);
// Create scenario file mapping
const scenarioFile = this.scenarioFileRepo.create({
scenarioId,
fileId: savedFile.id,
});
await this.scenarioFileRepo.save(scenarioFile);
// Return file metadata
return {
id: savedFile.id,
name: savedFile.originalName,
mimeType: savedFile.mimeType,
size: savedFile.size,
expiresAt: savedFile.expiresAt,
createdAt: savedFile.createdAt,
};
}
async listScenarioFiles(
scenarioId: string,
limit?: number,
offset?: number,
): Promise<any> {
// Verify scenario exists
await this.findOne(scenarioId);
const result = await this.fileStorageService.listScenarioFiles(
scenarioId,
limit,
offset,
);
return {
items: result.items.map((item) => ({
id: item.id,
name: item.name,
mimeType: item.mimeType,
size: item.size,
})),
total: result.total,
};
}
async getScenarioFileContent(
scenarioId: string,
fileId: string,
res: Response,
): Promise<void> {
// Verify scenario exists
await this.findOne(scenarioId);
// Check if file is linked to this scenario
const link = await this.scenarioFileRepo.findOne({
where: { scenarioId, fileId },
relations: ["file"],
});
if (!link) {
throw new NotFoundException(`File ${fileId} not found in scenario ${scenarioId}`);
}
const file = link.file;
const fullPath = this.fileStorageService.getAbsolutePath(file.filePath);
res.setHeader("Content-Type", file.mimeType);
res.setHeader("Content-Disposition", `inline; filename="${file.originalName}"`);
res.setHeader("Content-Length", file.size);
res.sendFile(fullPath);
}
async listRunFiles(
scenarioId: string,
runId: string,
limit?: number,
offset?: number,
): Promise<any> {
// Verify scenario and run exist
await this.findOne(scenarioId);
const run = await this.runRepo.findOneBy({ id: runId, scenarioId });
if (!run) {
throw new NotFoundException(`Run ${runId} not found in scenario ${scenarioId}`);
}
const result = await this.fileStorageService.listRunFiles(
runId,
limit,
offset,
);
return {
items: result.items.map((item) => ({
id: item.id,
name: item.name,
mimeType: item.mimeType,
size: item.size,
})),
total: result.total,
};
}
async getRunFileContent(
scenarioId: string,
runId: string,
fileId: string,
res: Response,
): Promise<void> {
// Verify scenario and run exist
await this.findOne(scenarioId);
const run = await this.runRepo.findOneBy({ id: runId, scenarioId });
if (!run) {
throw new NotFoundException(`Run ${runId} not found in scenario ${scenarioId}`);
}
// Check if file is linked to this run
const link = await this.scenarioRunFileRepo.findOne({
where: { runId, fileId },
relations: ["file"],
});
if (!link) {
throw new NotFoundException(`File ${fileId} not found in run ${runId}`);
}
const file = link.file;
const fullPath = this.fileStorageService.getAbsolutePath(file.filePath);
res.setHeader("Content-Type", file.mimeType);
res.setHeader("Content-Disposition", `inline; filename="${file.originalName}"`);
res.setHeader("Content-Length", file.size);
res.sendFile(fullPath);
}
}