feat(versioning): version scenarios and snippets, bump to 1.16.0
- snapshot scenario and snippet content into version tables on every
content change; live tables keep holding the latest version
- record the scenario version on each run and copy its steps into the
run steps, so runs execute and show the version they were created with
- keep run step history when a step is deleted (FK set null)
- pin a snippet version with runSnippet('alias@N')
- add version picker to the run modal and version info across the UI
- add version list/get endpoints and MCP tools
- include version in exports and require it on import, restoring the
exact version by id + version
This commit is contained in:
1 parent
9fb6e8538b
commit
eed385debf
40 files changed
+1457
-137
No files matched your search
@@ -3,6 +3,7 @@ import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
@@ -13,7 +14,10 @@ import {
|
||||
PaginatedResult,
|
||||
PaginationQueryDto,
|
||||
} from "../common/dto/pagination.dto";
|
||||
import { resolveUsedSnippetAliases } from "../common/snippet-usage";
|
||||
import {
|
||||
parseSnippetRef,
|
||||
resolveUsedSnippetAliases,
|
||||
} from "../common/snippet-usage";
|
||||
import type { AppConfig, TraceMode } from "../config/app.config";
|
||||
import { CredentialEntity } from "../credential/credential.entity";
|
||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||
@@ -39,6 +43,10 @@ import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
import {
|
||||
ScenarioStepSnapshot,
|
||||
ScenarioVersionEntity,
|
||||
} from "./scenario-version.entity";
|
||||
import { ScenarioEntity } from "./scenario.entity";
|
||||
import { Response } from "express";
|
||||
import type { File as MulterFile } from "multer";
|
||||
@@ -46,13 +54,49 @@ import type { File as MulterFile } from "multer";
|
||||
export { PaginatedResult } from "../common/dto/pagination.dto";
|
||||
export type ScenarioOrderBy = "id" | "name" | "createdAt" | "updatedAt";
|
||||
|
||||
/** The versioned content of a scenario. */
|
||||
type ScenarioContent = Pick<
|
||||
ScenarioVersionEntity,
|
||||
"name" | "description" | "environmentId" | "timeoutSeconds" | "steps"
|
||||
>;
|
||||
|
||||
function contentKey(c: ScenarioContent): string {
|
||||
return JSON.stringify([
|
||||
c.name,
|
||||
c.description ?? null,
|
||||
c.environmentId ?? null,
|
||||
c.timeoutSeconds ?? null,
|
||||
// Step ids are not content: re-created steps with equal content are equal
|
||||
c.steps.map((s) => [s.order, s.title, s.execCode, s.timeoutSeconds]),
|
||||
]);
|
||||
}
|
||||
|
||||
function stepsSnapshot(steps: ScenarioStepEntity[]): ScenarioStepSnapshot[] {
|
||||
return [...steps]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((s) => ({
|
||||
id: s.id,
|
||||
order: s.order,
|
||||
title: s.title,
|
||||
execCode: s.execCode,
|
||||
timeoutSeconds: s.timeoutSeconds,
|
||||
}));
|
||||
}
|
||||
|
||||
export type UsedSnippet = SnippetEntity & {
|
||||
/** Version pinned via `runSnippet("alias@N")`, or null for the latest. */
|
||||
pinnedVersion: number | null;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class ScenarioService {
|
||||
export class ScenarioService implements OnModuleInit {
|
||||
constructor(
|
||||
@InjectRepository(ScenarioEntity)
|
||||
private readonly scenarioRepo: Repository<ScenarioEntity>,
|
||||
@InjectRepository(ScenarioStepEntity)
|
||||
private readonly stepRepo: Repository<ScenarioStepEntity>,
|
||||
@InjectRepository(ScenarioVersionEntity)
|
||||
private readonly versionRepo: Repository<ScenarioVersionEntity>,
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
private readonly runRepo: Repository<ScenarioRunEntity>,
|
||||
@InjectRepository(ScenarioRunStepEntity)
|
||||
@@ -74,10 +118,93 @@ export class ScenarioService {
|
||||
private readonly configService: ConfigService<AppConfig, true>,
|
||||
) {}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.backfillVersions();
|
||||
await this.backfillRunStepSnapshots();
|
||||
}
|
||||
|
||||
/** Records the current content of scenarios that have no row for their current version yet. */
|
||||
private async backfillVersions(): Promise<void> {
|
||||
const scenarios = await this.scenarioRepo.find({ select: { id: true } });
|
||||
for (const { id } of scenarios) await this.commitVersion(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run steps created before versioning point at the live step instead of
|
||||
* holding a copy of it; copy the live step content into them.
|
||||
*/
|
||||
private async backfillRunStepSnapshots(): Promise<void> {
|
||||
await this.runStepRepo.query(`
|
||||
UPDATE scenario_run_steps SET
|
||||
title = (SELECT title FROM scenario_steps WHERE id = scenarioStepId),
|
||||
execCode = (SELECT execCode FROM scenario_steps WHERE id = scenarioStepId),
|
||||
timeoutSeconds = (SELECT timeoutSeconds FROM scenario_steps WHERE id = scenarioStepId)
|
||||
WHERE title IS NULL AND execCode IS NULL AND timeoutSeconds IS NULL
|
||||
AND scenarioStepId IS NOT NULL
|
||||
AND runId IN (SELECT id FROM scenario_runs WHERE scenarioVersion IS NULL)
|
||||
`);
|
||||
}
|
||||
|
||||
// ── Versions ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Snapshots the scenario's current content. The first snapshot is stored as
|
||||
* the scenario's current version; later ones bump the version, unless the
|
||||
* content is unchanged since the latest snapshot.
|
||||
*/
|
||||
private async commitVersion(scenarioId: string): Promise<void> {
|
||||
const scenario = await this.findOne(scenarioId);
|
||||
const content: ScenarioContent = {
|
||||
name: scenario.name,
|
||||
description: scenario.description,
|
||||
environmentId: scenario.environmentId,
|
||||
timeoutSeconds: scenario.timeoutSeconds,
|
||||
steps: stepsSnapshot(scenario.steps),
|
||||
};
|
||||
const latest = await this.versionRepo.findOneBy({
|
||||
scenarioId,
|
||||
version: scenario.version,
|
||||
});
|
||||
if (latest && contentKey(latest) === contentKey(content)) return;
|
||||
const version = latest ? scenario.version + 1 : scenario.version;
|
||||
if (version !== scenario.version) {
|
||||
await this.scenarioRepo.update(scenarioId, { version });
|
||||
}
|
||||
await this.versionRepo.save(
|
||||
this.versionRepo.create({ scenarioId, version, ...content }),
|
||||
);
|
||||
}
|
||||
|
||||
async listVersions(scenarioId: string): Promise<ScenarioVersionEntity[]> {
|
||||
await this.findOne(scenarioId); // 404 guard
|
||||
return this.versionRepo.find({
|
||||
where: { scenarioId },
|
||||
order: { version: "DESC" },
|
||||
});
|
||||
}
|
||||
|
||||
async findVersion(
|
||||
scenarioId: string,
|
||||
version: number,
|
||||
): Promise<ScenarioVersionEntity> {
|
||||
await this.findOne(scenarioId); // 404 guard
|
||||
const row = await this.versionRepo.findOneBy({ scenarioId, version });
|
||||
if (!row) {
|
||||
throw new NotFoundException(
|
||||
`Scenario ${scenarioId} has no version ${version}`,
|
||||
);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────
|
||||
|
||||
create(dto: CreateScenarioDto): Promise<ScenarioEntity> {
|
||||
return this.scenarioRepo.save(this.scenarioRepo.create(dto));
|
||||
async create(dto: CreateScenarioDto): Promise<ScenarioEntity> {
|
||||
const scenario = await this.scenarioRepo.save(
|
||||
this.scenarioRepo.create({ ...dto, version: 1 }),
|
||||
);
|
||||
await this.commitVersion(scenario.id);
|
||||
return this.findOne(scenario.id);
|
||||
}
|
||||
|
||||
async findAll(
|
||||
@@ -145,7 +272,9 @@ export class ScenarioService {
|
||||
async update(id: string, dto: UpdateScenarioDto): Promise<ScenarioEntity> {
|
||||
const scenario = await this.findOne(id);
|
||||
Object.assign(scenario, dto);
|
||||
return this.scenarioRepo.save(scenario);
|
||||
await this.scenarioRepo.save(scenario);
|
||||
await this.commitVersion(id);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
@@ -185,6 +314,7 @@ export class ScenarioService {
|
||||
}),
|
||||
);
|
||||
await this.normalizeStepOrder(scenarioId);
|
||||
await this.commitVersion(scenarioId);
|
||||
return this.findStep(scenarioId, created.id);
|
||||
}
|
||||
|
||||
@@ -243,6 +373,7 @@ export class ScenarioService {
|
||||
await this.normalizeStepOrder(scenarioId);
|
||||
}
|
||||
|
||||
await this.commitVersion(scenarioId);
|
||||
return this.findStep(scenarioId, stepId);
|
||||
}
|
||||
|
||||
@@ -250,6 +381,7 @@ export class ScenarioService {
|
||||
await this.findStep(scenarioId, stepId);
|
||||
await this.stepRepo.delete(stepId);
|
||||
await this.normalizeStepOrder(scenarioId);
|
||||
await this.commitVersion(scenarioId);
|
||||
}
|
||||
|
||||
// ── Scenario Credentials ──────────────────────────────────────────────────
|
||||
@@ -343,19 +475,22 @@ export class ScenarioService {
|
||||
* Returns the snippets referenced (directly, or transitively via other snippets)
|
||||
* by this scenario's step code, in discovery order - for linking to them from the UI.
|
||||
*/
|
||||
async getUsedSnippets(scenarioId: string): Promise<SnippetEntity[]> {
|
||||
async getUsedSnippets(scenarioId: string): Promise<UsedSnippet[]> {
|
||||
const scenario = await this.findOne(scenarioId);
|
||||
const snippetMap = await this.snippetService.buildSnippetMap();
|
||||
const usedAliases = resolveUsedSnippetAliases(
|
||||
const usedRefs = resolveUsedSnippetAliases(
|
||||
scenario.steps.map((s) => s.execCode ?? ""),
|
||||
snippetMap,
|
||||
);
|
||||
if (usedAliases.length === 0) return [];
|
||||
const snippets = await this.snippetService.findByAliases(usedAliases);
|
||||
).map(parseSnippetRef);
|
||||
if (usedRefs.length === 0) return [];
|
||||
const snippets = await this.snippetService.findByAliases([
|
||||
...new Set(usedRefs.map((r) => r.alias)),
|
||||
]);
|
||||
const byAlias = new Map(snippets.map((s) => [s.alias, s]));
|
||||
return usedAliases
|
||||
.map((alias) => byAlias.get(alias))
|
||||
.filter((s): s is SnippetEntity => s != null);
|
||||
return usedRefs.flatMap(({ alias, version }) => {
|
||||
const snippet = byAlias.get(alias);
|
||||
return snippet ? [{ ...snippet, pinnedVersion: version }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
// ── Runs ──────────────────────────────────────────────────────────────────
|
||||
@@ -500,8 +635,13 @@ export class ScenarioService {
|
||||
environmentId: string,
|
||||
saveSession = false,
|
||||
traceMode?: TraceMode,
|
||||
version?: number,
|
||||
): Promise<ScenarioRunEntity> {
|
||||
const scenario = await this.findOne(scenarioId);
|
||||
const scenarioVersion = await this.findVersion(
|
||||
scenarioId,
|
||||
version ?? scenario.version,
|
||||
);
|
||||
const environment = await this.environmentRepo.findOneBy({
|
||||
id: environmentId,
|
||||
});
|
||||
@@ -516,14 +656,19 @@ export class ScenarioService {
|
||||
status: "pending",
|
||||
saveSession,
|
||||
traceMode: traceMode ?? this.getRunDefaults().traceMode,
|
||||
scenarioVersion: scenarioVersion.version,
|
||||
}),
|
||||
);
|
||||
|
||||
const stepRuns = scenario.steps.map((step, index) =>
|
||||
const liveStepIds = new Set(scenario.steps.map((s) => s.id));
|
||||
const stepRuns = scenarioVersion.steps.map((step, index) =>
|
||||
this.runStepRepo.create({
|
||||
runId: run.id,
|
||||
scenarioStepId: step.id,
|
||||
scenarioStepId: step.id && liveStepIds.has(step.id) ? step.id : null,
|
||||
order: step.order,
|
||||
title: step.title,
|
||||
execCode: step.execCode,
|
||||
timeoutSeconds: step.timeoutSeconds,
|
||||
status: index === 0 ? "pending" : "waiting",
|
||||
description: null,
|
||||
}),
|
||||
@@ -542,9 +687,18 @@ export class ScenarioService {
|
||||
|
||||
async exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[] },
|
||||
options: {
|
||||
includeEnvironment: boolean;
|
||||
credentialIds: string[];
|
||||
/** Version to export; defaults to the latest. */
|
||||
version?: number;
|
||||
},
|
||||
): Promise<ExportEntity[]> {
|
||||
const scenario = await this.findOne(id);
|
||||
const content = await this.findVersion(
|
||||
id,
|
||||
options.version ?? scenario.version,
|
||||
);
|
||||
const entities: ExportEntity[] = [];
|
||||
|
||||
// Include environment entity if requested and linked
|
||||
@@ -591,13 +745,16 @@ export class ScenarioService {
|
||||
const scenarioDto: ScenarioExportDto = {
|
||||
kind: "scenario",
|
||||
id: scenario.id,
|
||||
name: scenario.name,
|
||||
description: scenario.description ?? undefined,
|
||||
environmentId: scenario.environmentId ?? undefined,
|
||||
version: content.version,
|
||||
name: content.name,
|
||||
description: content.description ?? undefined,
|
||||
environmentId: content.environmentId ?? undefined,
|
||||
timeoutSeconds: content.timeoutSeconds ?? undefined,
|
||||
credentials: credentialMappings.length > 0 ? credentialMappings : undefined,
|
||||
steps: scenario.steps.map((s) => ({
|
||||
steps: content.steps.map((s) => ({
|
||||
title: s.title,
|
||||
execCode: s.execCode,
|
||||
...(s.timeoutSeconds != null ? { timeoutSeconds: s.timeoutSeconds } : {}),
|
||||
})),
|
||||
};
|
||||
entities.push(scenarioDto);
|
||||
@@ -678,46 +835,72 @@ export class ScenarioService {
|
||||
throw new BadRequestException("steps must be an array");
|
||||
}
|
||||
|
||||
if (!Number.isInteger(scenarioDto.version) || scenarioDto.version < 1) {
|
||||
throw new BadRequestException("version must be a positive integer");
|
||||
}
|
||||
|
||||
// Restore the exported version: upsert by id + version. An existing
|
||||
// version is left untouched; a new one is stored under its number and
|
||||
// becomes the latest when it is higher than the current latest.
|
||||
const dto = scenarioDto;
|
||||
const content: ScenarioContent = {
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
environmentId: dto.environmentId ?? null,
|
||||
timeoutSeconds: dto.timeoutSeconds ?? null,
|
||||
steps: dto.steps.map((s, index) => ({
|
||||
id: null,
|
||||
order: index + 1,
|
||||
title: s.title ?? null,
|
||||
execCode: s.execCode ?? null,
|
||||
timeoutSeconds: s.timeoutSeconds ?? null,
|
||||
})),
|
||||
};
|
||||
const existing = dto.id
|
||||
? await this.scenarioRepo.findOneBy({ id: dto.id })
|
||||
: null;
|
||||
let scenario: ScenarioEntity;
|
||||
if (dto.id) {
|
||||
const existing = await this.scenarioRepo.findOneBy({ id: dto.id });
|
||||
if (existing) {
|
||||
existing.name = dto.name;
|
||||
existing.description = dto.description ?? null;
|
||||
existing.environmentId = dto.environmentId ?? existing.environmentId;
|
||||
scenario = await this.scenarioRepo.save(existing);
|
||||
await this.stepRepo.delete({ scenarioId: scenario.id });
|
||||
} else {
|
||||
scenario = await this.scenarioRepo.save(
|
||||
this.scenarioRepo.create({
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
environmentId: dto.environmentId ?? null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (!existing) {
|
||||
scenario = await this.scenarioRepo.save(
|
||||
this.scenarioRepo.create({
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
environmentId: dto.environmentId ?? null,
|
||||
...(dto.id ? { id: dto.id } : {}),
|
||||
name: content.name,
|
||||
description: content.description,
|
||||
environmentId: content.environmentId,
|
||||
timeoutSeconds: content.timeoutSeconds,
|
||||
version: dto.version,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (dto.steps.length > 0) {
|
||||
const steps = dto.steps.map((s, index) =>
|
||||
this.stepRepo.create({
|
||||
scenarioId: scenario.id,
|
||||
order: index,
|
||||
title: s.title ?? null,
|
||||
execCode: s.execCode ?? null,
|
||||
}),
|
||||
);
|
||||
await this.stepRepo.save(steps);
|
||||
await this.normalizeStepOrder(scenario.id);
|
||||
await this.replaceSteps(scenario.id, content.steps);
|
||||
await this.commitVersion(scenario.id);
|
||||
} else {
|
||||
scenario = existing;
|
||||
const hasVersion = await this.versionRepo.existsBy({
|
||||
scenarioId: existing.id,
|
||||
version: dto.version,
|
||||
});
|
||||
if (!hasVersion) {
|
||||
if (dto.version > existing.version) {
|
||||
Object.assign(existing, {
|
||||
name: content.name,
|
||||
description: content.description,
|
||||
environmentId: content.environmentId ?? existing.environmentId,
|
||||
timeoutSeconds: content.timeoutSeconds,
|
||||
version: dto.version,
|
||||
});
|
||||
scenario = await this.scenarioRepo.save(existing);
|
||||
await this.replaceSteps(scenario.id, content.steps);
|
||||
await this.commitVersion(scenario.id);
|
||||
} else {
|
||||
await this.versionRepo.save(
|
||||
this.versionRepo.create({
|
||||
scenarioId: existing.id,
|
||||
version: dto.version,
|
||||
...content,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Restore credential alias mappings
|
||||
if (dto.credentials && dto.credentials.length > 0) {
|
||||
@@ -734,6 +917,26 @@ export class ScenarioService {
|
||||
return this.findOne(scenario.id);
|
||||
}
|
||||
|
||||
private async replaceSteps(
|
||||
scenarioId: string,
|
||||
steps: ScenarioStepSnapshot[],
|
||||
): Promise<void> {
|
||||
await this.stepRepo.delete({ scenarioId });
|
||||
if (steps.length === 0) return;
|
||||
await this.stepRepo.save(
|
||||
steps.map((s) =>
|
||||
this.stepRepo.create({
|
||||
scenarioId,
|
||||
order: s.order,
|
||||
title: s.title,
|
||||
execCode: s.execCode,
|
||||
timeoutSeconds: s.timeoutSeconds,
|
||||
}),
|
||||
),
|
||||
);
|
||||
await this.normalizeStepOrder(scenarioId);
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────────
|
||||
|
||||
async uploadFile(
|
||||
|
||||
Reference in new issue
Block a user