Skip to content

🎥 Make videos programmatically with React

`@remotion/renderer`: Fix parallel browser downloads (#9882)

Jonny Burger880d3be11b9f
diff --git a/packages/renderer/src/browser/BrowserFetcher.ts b/packages/renderer/src/browser/BrowserFetcher.ts
index da4d606531..35760665e0 100644
--- a/packages/renderer/src/browser/BrowserFetcher.ts
+++ b/packages/renderer/src/browser/BrowserFetcher.ts
@@ -23,6 +23,7 @@ import {makeFileExecutableIfItIsNot} from '../compositor/make-file-executable';
import type {LogLevel} from '../log-level';
import {ChromeMode} from '../options/chrome-mode';
import type {DownloadBrowserProgressFn} from '../options/on-browser-download';
+import {acquireBrowserDownloadLock} from './browser-download-lock';
import {extractZipArchive} from './extract-zip-archive';
import {
getChromeDownloadUrl,
@@ -135,9 +136,6 @@ export const downloadBrowser = async ({
if (installedVersion === expectedVersion) {
return getRevisionInfo(chromeMode);
}
-
- // VERSION file missing or mismatched - delete and re-download
- fs.rmSync(outputPath, {recursive: true, force: true});
}
if (!(await existsAsync(downloadsFolder))) {
@@ -158,75 +156,93 @@ export const downloadBrowser = async ({
);
}
- logDownloadUrl({url: downloadURL, logLevel, indent});
+ const releaseLock = await acquireBrowserDownloadLock(
+ path.join(downloadsFolder, 'download.lock'),
+ );
try {
- await downloadFile({
- url: downloadURL,
- to: () => archivePath,
- onProgress: (progress) => {
- if (progress.totalSize === null || progress.percent === null) {
- throw new Error('Expected totalSize and percent to be defined');
- }
-
- onProgress({
- downloadedBytes: progress.downloaded,
- totalSizeInBytes: progress.totalSize,
- percent: progress.percent,
- alreadyAvailable: false,
- });
- },
- indent,
- logLevel,
- abortSignal: new AbortController().signal,
- });
- await extractZipArchive(archivePath, outputPath);
-
- const possibleSubdirs = [
- 'chrome-linux',
- 'chrome-headless-shell-linux64',
- 'chromium-headless-shell-amazon-linux2023-arm64',
- 'chromium-headless-shell-amazon-linux2023-x64',
- ];
-
- for (const subdir of possibleSubdirs) {
- const chromeLinuxFolder = path.join(outputPath, subdir);
- const chromePath = path.join(chromeLinuxFolder, 'chrome');
-
- if (fs.existsSync(chromePath)) {
- const chromeHeadlessShellPath = path.join(
- chromeLinuxFolder,
- 'chrome-headless-shell',
- );
-
- fs.renameSync(chromePath, chromeHeadlessShellPath);
+ if (await existsAsync(outputPath)) {
+ const installedVersion = readVersionFile(chromeMode);
+ if (installedVersion === expectedVersion) {
+ return getRevisionInfo(chromeMode);
}
- if (fs.existsSync(chromeLinuxFolder)) {
- const targetFolder = path.join(
- outputPath,
- 'chrome-headless-shell-' + platform,
- );
+ // VERSION file missing or mismatched - delete and re-download
+ fs.rmSync(outputPath, {recursive: true, force: true});
+ }
+
+ logDownloadUrl({url: downloadURL, logLevel, indent});
+
+ try {
+ await downloadFile({
+ url: downloadURL,
+ to: () => archivePath,
+ onProgress: (progress) => {
+ if (progress.totalSize === null || progress.percent === null) {
+ throw new Error('Expected totalSize and percent to be defined');
+ }
+
+ onProgress({
+ downloadedBytes: progress.downloaded,
+ totalSizeInBytes: progress.totalSize,
+ percent: progress.percent,
+ alreadyAvailable: false,
+ });
+ },
+ indent,
+ logLevel,
+ abortSignal: new AbortController().signal,
+ });
+ await extractZipArchive(archivePath, outputPath);
+
+ const possibleSubdirs = [
+ 'chrome-linux',
+ 'chrome-headless-shell-linux64',
+ 'chromium-headless-shell-amazon-linux2023-arm64',
+ 'chromium-headless-shell-amazon-linux2023-x64',
+ ];
+
+ for (const subdir of possibleSubdirs) {
+ const chromeLinuxFolder = path.join(outputPath, subdir);
+ const chromePath = path.join(chromeLinuxFolder, 'chrome');
+
+ if (fs.existsSync(chromePath)) {
+ const chromeHeadlessShellPath = path.join(
+ chromeLinuxFolder,
+ 'chrome-headless-shell',
+ );
+
+ fs.renameSync(chromePath, chromeHeadlessShellPath);
+ }
+
+ if (fs.existsSync(chromeLinuxFolder)) {
+ const targetFolder = path.join(
+ outputPath,
+ 'chrome-headless-shell-' + platform,
+ );
- if (chromeLinuxFolder !== targetFolder) {
- fs.renameSync(chromeLinuxFolder, targetFolder);
+ if (chromeLinuxFolder !== targetFolder) {
+ fs.renameSync(chromeLinuxFolder, targetFolder);
+ }
}
}
+ } catch (err) {
+ return Promise.reject(err);
+ } finally {
+ if (await existsAsync(archivePath)) {
+ await unlinkAsync(archivePath);
+ }
}
- } catch (err) {
- return Promise.reject(err);
- } finally {
- if (await existsAsync(archivePath)) {
- await unlinkAsync(archivePath);
- }
- }
- writeVersionFile(chromeMode, expectedVersion);
+ writeVersionFile(chromeMode, expectedVersion);
- const revisionInfo = getRevisionInfo(chromeMode);
- makeFileExecutableIfItIsNot(revisionInfo.executablePath);
+ const revisionInfo = getRevisionInfo(chromeMode);
+ makeFileExecutableIfItIsNot(revisionInfo.executablePath);
- return revisionInfo;
+ return revisionInfo;
+ } finally {
+ await releaseLock();
+ }
};
const getFolderPath = (downloadsFolder: string, platform: Platform): string => {
diff --git a/packages/renderer/src/browser/browser-download-lock.ts b/packages/renderer/src/browser/browser-download-lock.ts
new file mode 100644
index 0000000000..bf24f516cd
--- /dev/null
+++ b/packages/renderer/src/browser/browser-download-lock.ts
@@ -0,0 +1,148 @@
+import {randomUUID} from 'node:crypto';
+import * as fs from 'node:fs';
+import os from 'node:os';
+
+const RETRY_INTERVAL_IN_MS = 100;
+const STALE_LOCK_IN_MS = 30_000;
+const HEARTBEAT_INTERVAL_IN_MS = 5_000;
+
+type LockContents = {
+ hostname: string;
+ pid: number;
+ token: string;
+};
+
+const wait = (timeoutInMilliseconds: number): Promise<void> => {
+ return new Promise((resolve) => {
+ setTimeout(resolve, timeoutInMilliseconds);
+ });
+};
+
+const isErrorWithCode = (error: unknown, code: string): boolean => {
+ return (
+ error instanceof Error &&
+ 'code' in error &&
+ (error as NodeJS.ErrnoException).code === code
+ );
+};
+
+const readLock = async (lockPath: string): Promise<LockContents | null> => {
+ try {
+ const parsed = JSON.parse(
+ await fs.promises.readFile(lockPath, 'utf8'),
+ ) as Partial<LockContents>;
+
+ if (
+ typeof parsed.hostname !== 'string' ||
+ typeof parsed.pid !== 'number' ||
+ typeof parsed.token !== 'string'
+ ) {
+ return null;
+ }
+
+ return parsed as LockContents;
+ } catch {
+ return null;
+ }
+};
+
+const isProcessRunning = (pid: number): boolean => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return !isErrorWithCode(error, 'ESRCH');
+ }
+};
+
+const removeStaleLock = async (lockPath: string): Promise<void> => {
+ let stats: fs.Stats;
+ try {
+ stats = await fs.promises.stat(lockPath);
+ } catch (error) {
+ if (isErrorWithCode(error, 'ENOENT')) {
+ return;
+ }
+
+ throw error;
+ }
+
+ const lock = await readLock(lockPath);
+ if (lock?.hostname === os.hostname()) {
+ if (isProcessRunning(lock.pid)) {
+ return;
+ }
+ } else if (Date.now() - stats.mtimeMs < STALE_LOCK_IN_MS) {
+ return;
+ }
+
+ try {
+ await fs.promises.unlink(lockPath);
+ } catch (error) {
+ if (!isErrorWithCode(error, 'ENOENT')) {
+ throw error;
+ }
+ }
+};
+
+export const acquireBrowserDownloadLock = async (
+ lockPath: string,
+): Promise<() => Promise<void>> => {
+ // Browser archives and extraction directories are shared by every Remotion
+ // process in a project, so the whole installation must be cross-process safe.
+ for (;;) {
+ const token = randomUUID();
+ let lockFile: fs.promises.FileHandle;
+
+ try {
+ lockFile = await fs.promises.open(lockPath, 'wx');
+ } catch (error) {
+ if (!isErrorWithCode(error, 'EEXIST')) {
+ throw error;
+ }
+
+ await removeStaleLock(lockPath);
+ await wait(RETRY_INTERVAL_IN_MS);
+ continue;
+ }
+
+ try {
+ await lockFile.writeFile(
+ JSON.stringify({
+ hostname: os.hostname(),
+ pid: process.pid,
+ token,
+ } satisfies LockContents),
+ );
+ } catch (error) {
+ await lockFile.close();
+ await fs.promises.rm(lockPath, {force: true});
+ throw error;
+ }
+
+ const heartbeat = setInterval(async () => {
+ const currentLock = await readLock(lockPath);
+ if (currentLock?.token !== token) {
+ return;
+ }
+
+ const now = new Date();
+ try {
+ await fs.promises.utimes(lockPath, now, now);
+ } catch {
+ // The lock may have been cleaned up while the heartbeat was pending.
+ }
+ }, HEARTBEAT_INTERVAL_IN_MS);
+ heartbeat.unref();
+
+ return async () => {
+ clearInterval(heartbeat);
+ const currentLock = await readLock(lockPath);
+ await lockFile.close();
+
+ if (currentLock?.token === token) {
+ await fs.promises.rm(lockPath, {force: true});
+ }
+ };
+ }
+};
diff --git a/packages/renderer/src/test/browser-download-lock.test.ts b/packages/renderer/src/test/browser-download-lock.test.ts
new file mode 100644
index 0000000000..7cbc083e51
--- /dev/null
+++ b/packages/renderer/src/test/browser-download-lock.test.ts
@@ -0,0 +1,111 @@
+import {expect, test} from 'bun:test';
+import {spawn} from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+const workerPath = path.join(
+ __dirname,
+ 'fixtures/browser-download-lock-worker.ts',
+);
+
+const runWorker = ({
+ lockPath,
+ eventsPath,
+ name,
+ releaseSignal,
+}: {
+ lockPath: string;
+ eventsPath: string;
+ name: string;
+ releaseSignal: string | null;
+}): Promise<void> => {
+ return new Promise((resolve, reject) => {
+ const child = spawn(
+ process.execPath,
+ [
+ workerPath,
+ lockPath,
+ eventsPath,
+ name,
+ ...(releaseSignal === null ? [] : [releaseSignal]),
+ ],
+ {stdio: 'inherit'},
+ );
+
+ child.on('error', reject);
+ child.on('exit', (code) => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(new Error(`Browser download lock worker exited with ${code}`));
+ }
+ });
+ });
+};
+
+const waitForEvent = async ({
+ eventsPath,
+ event,
+}: {
+ eventsPath: string;
+ event: string;
+}): Promise<void> => {
+ for (let attempts = 0; attempts < 500; attempts++) {
+ const events = fs.existsSync(eventsPath)
+ ? fs.readFileSync(eventsPath, 'utf8')
+ : '';
+ if (events.includes(event)) {
+ return;
+ }
+
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 10);
+ });
+ }
+
+ throw new Error(`Timed out waiting for event: ${event}`);
+};
+
+test(
+ 'serializes browser downloads across processes',
+ async () => {
+ const temporaryDirectory = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'remotion-browser-lock-'),
+ );
+ const lockPath = path.join(temporaryDirectory, 'download.lock');
+ const eventsPath = path.join(temporaryDirectory, 'events');
+ const releaseSignal = path.join(temporaryDirectory, 'release');
+
+ try {
+ const firstWorker = runWorker({
+ lockPath,
+ eventsPath,
+ name: 'first',
+ releaseSignal,
+ });
+ await waitForEvent({eventsPath, event: 'first:acquired'});
+
+ const secondWorker = runWorker({
+ lockPath,
+ eventsPath,
+ name: 'second',
+ releaseSignal: null,
+ });
+ await waitForEvent({eventsPath, event: 'second:attempting'});
+
+ expect(fs.readFileSync(eventsPath, 'utf8')).not.toContain(
+ 'second:acquired',
+ );
+
+ fs.writeFileSync(releaseSignal, '');
+ await Promise.all([firstWorker, secondWorker]);
+
+ expect(fs.readFileSync(eventsPath, 'utf8')).toContain('second:released');
+ expect(fs.existsSync(lockPath)).toBe(false);
+ } finally {
+ fs.rmSync(temporaryDirectory, {recursive: true, force: true});
+ }
+ },
+ {timeout: 10_000},
+);
diff --git a/packages/renderer/src/test/fixtures/browser-download-lock-worker.ts b/packages/renderer/src/test/fixtures/browser-download-lock-worker.ts
new file mode 100644
index 0000000000..eea7a1fdb4
--- /dev/null
+++ b/packages/renderer/src/test/fixtures/browser-download-lock-worker.ts
@@ -0,0 +1,37 @@
+import fs from 'node:fs';
+import {acquireBrowserDownloadLock} from '../../browser/browser-download-lock';
+
+const [lockPath, eventsPath, name, releaseSignal] = process.argv.slice(2);
+
+const appendEvent = (event: string) => {
+ fs.appendFileSync(eventsPath, `${name}:${event}\n`);
+};
+
+const wait = (timeoutInMilliseconds: number): Promise<void> => {
+ return new Promise((resolve) => {
+ setTimeout(resolve, timeoutInMilliseconds);
+ });
+};
+
+const main = async () => {
+ if (!lockPath || !eventsPath || !name) {
+ throw new Error('Expected lock path, events path and worker name');
+ }
+
+ appendEvent('attempting');
+ const releaseLock = await acquireBrowserDownloadLock(lockPath);
+ appendEvent('acquired');
+
+ if (releaseSignal) {
+ while (!fs.existsSync(releaseSignal)) {
+ await wait(10);
+ }
+ }
+
+ await releaseLock();
+ appendEvent('released');
+};
+
+main().catch((error) => {
+ throw error;
+});