Skip to content
Merged
5 changes: 5 additions & 0 deletions .changeset/electron-video-close.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@e2e-dev/electron': patch
---

A video recording ends in its close time when ffmpeg stops reading frames, a window never answers the start of its screencast, or the app's main process is too busy to answer the end of it; each used to hold the end of the test for good. A recording whose ffmpeg fails before it writes any video fails with `ENGINE_FAILURE` and leaves no empty file, and a capture of a window that loaded a page outside the app's directory while it was taken is dropped.
92 changes: 72 additions & 20 deletions packages/electron/src/video.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { spawn, type ChildProcess } from 'node:child_process';
import { existsSync, mkdirSync, rmSync } from 'node:fs';
import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs';
import path from 'node:path';
import { EngineError, type VideoFile } from '@e2e-dev/core/engine';
import { answerWithin } from './budget.ts';
Expand All @@ -23,6 +23,10 @@ const CLOSE_TIMEOUT_MS = 10_000;
const STDERR_TAIL = 2_000;
/** How long a window gets to hand over its last screen when the recording stops. */
const LAST_SCREEN_MS = 2_000;
/** How long the end of a recording waits for a window switch, which a window that does not answer can hold up. */
const SWITCH_WAIT_MS = 2_000;
/** How long a window gets to answer the end of its screencast: a busy main process answers no DevTools call. */
const STOP_SCREENCAST_MS = 2_000;

interface Size {
readonly width: number;
Expand Down Expand Up @@ -66,11 +70,15 @@ export class Recorder {
private async switchTo(page: PageTarget | undefined): Promise<void> {
if (this.stopped || this.source?.page === page) return;
await this.source?.stop();
// The recording ended while the window before was stopped: the window shown next gets no screencast.
if (this.stopped) return;
this.source = undefined;
if (page === undefined || page.isClosed()) return;
const { session } = page;
if (this.encoder === undefined) {
const { cssVisualViewport } = await session.send('Page.getLayoutMetrics');
// The recording ended while the window was asked: it gets no encoder.
if (this.stopped) return;
// Even sides: the encoder's pixel format halves them.
const size = { width: Math.max(2, Math.floor(cssVisualViewport.clientWidth / 2) * 2), height: Math.max(2, Math.floor(cssVisualViewport.clientHeight / 2) * 2) };
mkdirSync(path.dirname(this.absolute), { recursive: true });
Expand All @@ -89,9 +97,10 @@ export class Recorder {
stop: async () => {
off();
page.recording = false;
await session.send('Page.stopScreencast').catch(() => undefined);
await answerWithin(session.send('Page.stopScreencast'), STOP_SCREENCAST_MS);
},
};
const source = this.source;
try {
await session.send('Page.startScreencast', { format: 'jpeg', quality: JPEG_QUALITY, maxWidth: encoder.size.width, maxHeight: encoder.size.height });
} catch {
Expand All @@ -101,6 +110,11 @@ export class Recorder {
this.source = undefined;
return;
}
// The recording ended while the screencast started: it sends no frame to an encoder that closed.
if (this.stopped && this.source !== source) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
await source.stop();
return;
}
// A window shown again repaints nothing: the video would hold the window before it.
await this.snap();
}
Expand All @@ -110,22 +124,49 @@ export class Recorder {
* ever shown.
*/
async stop(): Promise<readonly VideoFile[]> {
await this.switching;
return await this.withinCloseTime(async () => {
Comment thread
kdy1 marked this conversation as resolved.
Resolved
await this.settleSwitching();
const { source, encoder, startedAt } = this;
if (encoder === undefined || startedAt === undefined) return [];
try {
await this.snap();
await source?.stop();
} finally {
this.source = undefined;
await encoder.close().catch((cause: unknown) => {
// What ffmpeg wrote before it failed still plays; an empty file is no video.
if ((statSync(this.absolute, { throwIfNoEntry: false })?.size ?? 0) > 0) return;
rmSync(this.absolute, { force: true });
throw new EngineError('ENGINE_FAILURE', `the video ${this.relative} could not be finalized: ${cause instanceof Error ? cause.message : String(cause)}`, { retryable: false, cause });
});
}
return existsSync(this.absolute) ? [{ path: this.relative, startedAt }] : [];
});
}

/**
* Waits for the window switch in progress, for at most `SWITCH_WAIT_MS`: a
* window that does not answer the switch's DevTools calls holds it up for
* good. A switch that answers later backs out (`stopped`).
*/
private async settleSwitching(): Promise<void> {
await answerWithin(this.switching, SWITCH_WAIT_MS);
this.stopped = true;
const { source, encoder, startedAt } = this;
if (encoder === undefined || startedAt === undefined) return [];
}

/**
* Runs the end of a recording with the encoder killed once it has had
* `CLOSE_TIMEOUT_MS`: an ffmpeg that stops reading holds a frame's write,
* and the window switch and the last snapshot that wait on it, before its
* own close would start a timer.
*/
private async withinCloseTime<T>(end: () => Promise<T>): Promise<T> {
const stuck = setTimeout(() => this.encoder?.kill(), CLOSE_TIMEOUT_MS);
Comment thread
kdy1 marked this conversation as resolved.
Resolved
Comment thread
kdy1 marked this conversation as resolved.
Resolved
try {
await this.snap();
await source?.stop();
return await end();
} finally {
this.source = undefined;
await encoder.close().catch((cause: unknown) => {
if (!existsSync(this.absolute)) {
throw new EngineError('ENGINE_FAILURE', `the video ${this.relative} could not be finalized: ${cause instanceof Error ? cause.message : String(cause)}`, { retryable: false, cause });
}
});
clearTimeout(stuck);
}
return existsSync(this.absolute) ? [{ path: this.relative, startedAt }] : [];
}

/**
Expand All @@ -136,17 +177,21 @@ export class Recorder {
async snap(): Promise<void> {
const { source, encoder } = this;
if (source === undefined || encoder === undefined || source.page.isClosed() || !this.allowed(source.page)) return;
const { generation } = source.page;
const screen = await answerWithin(source.page.session.send('Page.captureScreenshot', { format: 'jpeg', quality: JPEG_QUALITY }), LAST_SCREEN_MS);
if (screen !== undefined) await encoder.frame(Buffer.from(screen.data, 'base64'));
// A window that loaded another document while it was captured may show what no frame may: the capture is dropped.
if (screen === undefined || source.page.generation !== generation || !this.allowed(source.page)) return;
await encoder.frame(Buffer.from(screen.data, 'base64'));
}

/** Ends a recording nobody collects: the file it wrote is removed. */
async abandon(): Promise<void> {
await this.switching;
this.stopped = true;
await this.source?.stop();
this.source = undefined;
await this.encoder?.abort();
await this.withinCloseTime(async () => {
await this.settleSwitching();
await this.source?.stop();
this.source = undefined;
await this.encoder?.abort();
});
}
}

Expand Down Expand Up @@ -227,6 +272,13 @@ class FrameEncoder {
if (code !== 0) throw new Error(`ffmpeg ${signal === null ? `exited with ${String(code)}` : `was killed (${signal})`}${this.stderr === '' ? '' : `: ${this.stderr.trim()}`}`);
}

/** Kills the encoder: the frames it holds are dropped, and a write waiting on it returns. */
kill(): void {
this.process.kill('SIGKILL');
// Its input closes on this side too, so a write waiting for room in it returns whatever still holds the pipe.
this.process.stdin?.destroy();
}

/** Kills the encoder and removes what it wrote. */
async abort(): Promise<void> {
this.process.kill('SIGKILL');
Expand Down
64 changes: 61 additions & 3 deletions packages/electron/tests/integration/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,11 +566,11 @@ describe('video', () => {
return frames;
}

async function twoWindows(): Promise<{ readonly windows: Windows; readonly directory: string; readonly ffmpeg: string }> {
const { windows, launch, directory } = appWith(TWO_WINDOWS);
async function twoWindows(): Promise<{ readonly app: AppProcess; readonly windows: Windows; readonly directory: string; readonly ffmpeg: string }> {
const { app, windows, launch, directory } = appWith(TWO_WINDOWS);
await launch();
await expect.poll(() => windows.open().length).toBe(2);
return { windows, directory, ffmpeg: await ensureFfmpeg(process.env, new AbortController().signal) };
return { app, windows, directory, ffmpeg: await ensureFfmpeg(process.env, new AbortController().signal) };
}

it('records the shown window, and the next one shown, into one file', async () => {
Expand Down Expand Up @@ -610,6 +610,64 @@ describe('video', () => {
expect(frames.some(([red, , blue]) => red < 80 && blue > 180)).toBe(true);
});

it.skipIf(process.platform === 'win32')('fails, and keeps no file, when the encoder fails before it writes any video', async () => {
const { windows, directory } = await twoWindows();
// An encoder that opens its output, as ffmpeg does before it reads a frame, and then fails.
const failing = path.join(directory, 'failing-ffmpeg.sh');
writeFileSync(failing, '#!/bin/sh\nfor output; do :; done\n: > "$output"\ncat > /dev/null\nexit 23\n', { mode: 0o755 });
const recorder = new Recorder(failing, directory, 'video/failed.webm', () => true);
recorder.follow(windows.open()[0]!.page);
await new Promise((resolve) => setTimeout(resolve, 300));
expect(await recorder.stop().then(() => undefined, (error: unknown) => error)).toMatchObject({ code: 'ENGINE_FAILURE', message: expect.stringContaining('exited with 23') as string });
expect(existsSync(path.join(directory, 'video', 'failed.webm'))).toBe(false);
});

it.skipIf(process.platform === 'win32')('ends, in its close time, a recording whose encoder stopped reading', async () => {
// Noise, redrawn every frame: each JPEG is large, so the encoder's input pipe fills in a moment.
const { windows, launch, directory } = appWith(`const noise = '<body style="margin:0"><canvas width="600" height="400"></canvas><script>const c = document.querySelector("canvas").getContext("2d"); const image = c.createImageData(600, 400); setInterval(() => { for (let i = 0; i < image.data.length; i += 1) image.data[i] = Math.random() * 256; c.putImageData(image, 0, 0); }, 30)</script>';
app.whenReady().then(() => new BrowserWindow({ show: ${SHOWN}, width: 600, height: 400 }).loadURL('data:text/html,' + encodeURIComponent(noise)));`);
await launch();
// An encoder that never reads a frame: its input pipe fills, and a write waits on it for good.
const stuck = path.join(directory, 'stuck-ffmpeg.sh');
writeFileSync(stuck, '#!/bin/sh\nexec sleep 60\n', { mode: 0o755 });
const recorder = new Recorder(stuck, directory, 'video/stuck.webm', () => true);
recorder.follow(windows.require().page);
await new Promise((resolve) => setTimeout(resolve, 2000));
const started = Date.now();
await expect(recorder.stop()).rejects.toMatchObject({ code: 'ENGINE_FAILURE' });
expect(Date.now() - started).toBeLessThan(14_000);
});

it('ends a recording whose window never answers the start of its screencast', async () => {
const { windows, directory, ffmpeg } = await twoWindows();
const busy = windows.open()[0]!.page;
// A page that never yields: the window answers no DevTools call its renderer handles.
void busy.session.send('Runtime.evaluate', { expression: 'while (true) {}' }).catch(() => undefined);
const recorder = new Recorder(ffmpeg, directory, 'video/busy.webm', () => true);
recorder.follow(busy);
await new Promise((resolve) => setTimeout(resolve, 300));
const started = Date.now();
expect(await recorder.stop()).toEqual([]);
expect(Date.now() - started).toBeLessThan(5000);
expect(existsSync(path.join(directory, 'video', 'busy.webm'))).toBe(false);
});

it('ends a recording, in its close time, while the app\'s main process answers nothing', async () => {
const { app, windows, directory, ffmpeg } = await twoWindows();
const recorder = new Recorder(ffmpeg, directory, 'video/blocked.webm', () => true);
recorder.follow(windows.open()[0]!.page);
await new Promise((resolve) => setTimeout(resolve, 500));
// The main process runs the browser's DevTools handlers: while it is busy, no window answers the end of its screencast.
void app.evaluate(() => {
const end = Date.now() + 15_000;
while (Date.now() < end);
}, undefined).catch(() => undefined);
await new Promise((resolve) => setTimeout(resolve, 200));
const started = Date.now();
expect(await recorder.stop()).toEqual([{ path: 'video/blocked.webm', startedAt: expect.any(String) as string }]);
expect(Date.now() - started).toBeLessThan(8000);
});

it('keeps no frame of a window it may not show, and writes no file for a recording with none', async () => {
const { windows, directory, ffmpeg } = await twoWindows();
const [one, two] = windows.open();
Expand Down
94 changes: 94 additions & 0 deletions packages/electron/tests/unit/video.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import type { PageTarget } from '../../src/page.ts';
import { Recorder } from '../../src/video.ts';

/** A call the test answers when it chooses. */
interface Held {
readonly answer: () => void;
}

/**
* The part of a page target a recording drives: its DevTools session, which
* answers every call at once unless the test holds that method, and whether
* a screencast runs on it.
*/
class FakePage {
recording = false;
readonly generation = 0;
readonly sent: string[] = [];
listeners = 0;
private readonly holds = new Map<string, Held[]>();

readonly session = {
send: (method: string): Promise<unknown> => {
this.sent.push(method);
const answer = method === 'Page.getLayoutMetrics' ? { cssVisualViewport: { clientWidth: 100, clientHeight: 100 } } : method === 'Page.captureScreenshot' ? { data: 'AAAA' } : {};
const held = this.holds.get(method)?.shift();
if (held === undefined) return Promise.resolve(answer);
return new Promise((resolve) => {
(held as { answer: () => void }).answer = () => resolve(answer);
});
},
on: (): (() => void) => {
this.listeners += 1;
let on = true;
return () => {
if (on) this.listeners -= 1;
on = false;
};
},
};

/** Holds the next call of `method` until the returned `answer` is called. */
hold(method: string): Held {
const held: { answer: () => void } = { answer: () => undefined };
this.holds.set(method, [...(this.holds.get(method) ?? []), held]);
return { answer: () => held.answer() };
}

isClosed(): boolean {
return false;
}

asTarget(): PageTarget {
return this as unknown as PageTarget;
}
}

const directories: string[] = [];

afterEach(() => {
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
});

const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));

describe.skipIf(process.platform === 'win32')('Recorder', () => {
it('starts no screencast for a window switch that the end of the recording left waiting', async () => {
const directory = mkdtempSync(path.join(tmpdir(), 'e2e-electron-video-'));
directories.push(directory);
// An encoder that takes every frame and writes nothing.
const encoder = path.join(directory, 'ffmpeg.sh');
writeFileSync(encoder, '#!/bin/sh\ncat > /dev/null\n', { mode: 0o755 });
const one = new FakePage();
const two = new FakePage();
const startOne = one.hold('Page.startScreencast');
const recorder = new Recorder(encoder, directory, 'video.webm', () => true);
recorder.follow(one.asTarget());
recorder.follow(two.asTarget());
const stopping = recorder.stop();
// The switch to the first window ends a second into the two the recording's end waits; the switch to the second then waits on the first's stop past them.
const stopOne = one.hold('Page.stopScreencast');
await wait(1000);
startOne.answer();
await stopping;
stopOne.answer();
await wait(100);
expect(two.sent).not.toContain('Page.startScreencast');
expect(two.recording).toBe(false);
expect(two.listeners).toBe(0);
});
});
Loading