feat(snippets): add snippets entity, crud, and auto-browser-per-run
- add Snippet entity with name, description, code; full CRUD backend - add snippets pages (list, create, edit, detail) and nav entry - add runSnippet helper in code-executor using new Function with args array - add result param to execute() so validateCode can access exec output - remove sessionName from steps; each run now spawns its own fresh browser - fix waitForURL race by polling localStorage for token instead
This commit is contained in:
@@ -14,10 +14,10 @@ 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";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
import { EnvironmentService } from "../environment/environment.service";
|
||||
import type { EnvironmentUrls } from "../environment/environment.entity";
|
||||
import { SnippetService } from "../snippet/snippet.service";
|
||||
|
||||
interface ValidateResult {
|
||||
success: boolean;
|
||||
@@ -39,6 +39,8 @@ export class ScenarioSchedulerService {
|
||||
private readonly runCredentials = new Map<number, Record<string, unknown>>();
|
||||
// Cache environment URLs per run (resolved from the first login step)
|
||||
private readonly runEnvironments = new Map<number, EnvironmentUrls>();
|
||||
// Cache snippet code map per run (built once when a run starts)
|
||||
private readonly runSnippets = new Map<number, Record<string, string>>();
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
@@ -49,9 +51,9 @@ export class ScenarioSchedulerService {
|
||||
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
|
||||
private readonly authService: AuthService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly scenarioService: ScenarioService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly snippetService: SnippetService,
|
||||
) {}
|
||||
|
||||
private persistLog(
|
||||
@@ -133,6 +135,11 @@ export class ScenarioSchedulerService {
|
||||
// Resolve environment from the first login step (best-effort)
|
||||
const envUrls = await this.resolveRunEnvironment(run.scenarioId);
|
||||
if (envUrls) this.runEnvironments.set(run.id, envUrls);
|
||||
// Pre-load snippet map
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({} as Record<string, string>));
|
||||
this.runSnippets.set(run.id, snippetMap);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
@@ -170,6 +177,7 @@ export class ScenarioSchedulerService {
|
||||
this.activeRuns.delete(runId);
|
||||
this.runCredentials.delete(runId);
|
||||
this.runEnvironments.delete(runId);
|
||||
this.runSnippets.delete(runId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,39 +207,20 @@ export class ScenarioSchedulerService {
|
||||
|
||||
// ── Shared browser per run ─────────────────────────────────────────────────
|
||||
|
||||
private async getOrCreateBrowserHandle(
|
||||
runId: number,
|
||||
sessionName: string,
|
||||
): Promise<BrowserHandle> {
|
||||
private async getOrCreateBrowserHandle(runId: number): 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})`);
|
||||
this.logger.log(`Run #${runId}: browser created`);
|
||||
return handle;
|
||||
}
|
||||
|
||||
@@ -273,7 +262,7 @@ export class ScenarioSchedulerService {
|
||||
const loginResult = await this.authService.login(
|
||||
params.keyId,
|
||||
params.environmentName,
|
||||
step.sessionName,
|
||||
step.sessionName ?? undefined,
|
||||
);
|
||||
this.logger.log(
|
||||
`StepRun #${stepRun.id}: login OK, session=${loginResult.sessionName}`,
|
||||
@@ -282,7 +271,6 @@ export class ScenarioSchedulerService {
|
||||
if (step.validateCode) {
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(
|
||||
stepRun.runId,
|
||||
step.sessionName,
|
||||
);
|
||||
this.codeExecutor.validate(step.validateCode);
|
||||
const { result } = await this.codeExecutor.execute(
|
||||
@@ -293,6 +281,8 @@ export class ScenarioSchedulerService {
|
||||
this.makeGetStepOutput(stepRun),
|
||||
this.runCredentials.get(stepRun.runId),
|
||||
this.runEnvironments.get(stepRun.runId),
|
||||
this.runSnippets.get(stepRun.runId),
|
||||
null,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
@@ -312,11 +302,11 @@ export class ScenarioSchedulerService {
|
||||
this.codeExecutor.validate(step.execCode);
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(
|
||||
stepRun.runId,
|
||||
step.sessionName,
|
||||
);
|
||||
const getStepOutput = this.makeGetStepOutput(stepRun);
|
||||
const creds = this.runCredentials.get(stepRun.runId);
|
||||
const env = this.runEnvironments.get(stepRun.runId);
|
||||
const snips = this.runSnippets.get(stepRun.runId);
|
||||
const { result: execOutput } = await this.codeExecutor.execute(
|
||||
page,
|
||||
context,
|
||||
@@ -325,6 +315,7 @@ export class ScenarioSchedulerService {
|
||||
getStepOutput,
|
||||
creds,
|
||||
env,
|
||||
snips,
|
||||
);
|
||||
this.logger.log(`StepRun #${stepRun.id}: exec OK`);
|
||||
|
||||
@@ -338,6 +329,8 @@ export class ScenarioSchedulerService {
|
||||
getStepOutput,
|
||||
creds,
|
||||
env,
|
||||
snips,
|
||||
execOutput,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
@@ -363,7 +356,6 @@ export class ScenarioSchedulerService {
|
||||
|
||||
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`);
|
||||
@@ -378,6 +370,8 @@ export class ScenarioSchedulerService {
|
||||
this.makeGetStepOutput(stepRun),
|
||||
this.runCredentials.get(stepRun.runId),
|
||||
this.runEnvironments.get(stepRun.runId),
|
||||
this.runSnippets.get(stepRun.runId),
|
||||
null,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
|
||||
Reference in New Issue
Block a user