🎥 Make videos programmatically with React
error display nice for missing composition
Matt McGillivray98e14bd3b4aa
diff --git a/packages/cloudrun/container/readme.md b/packages/cloudrun/container/readme.mdindex 0b6492e38e..6246c73bc5 100644--- a/packages/cloudrun/container/readme.md+++ b/packages/cloudrun/container/readme.md@@ -12,11 +12,11 @@ The Dockerfile also bundles chromium and ffmpeg, and installs the [functions-fraThe Artifact Registry in GCP is a place to store container images. The Remotion-dev project has been created in GCP as a central place to host a public registry which can be read from by anyone. In particular, it is read from in the [Remotion GCP API when deploying a new Cloud Run instance](../src/api/deploy-new-cloud-run.ts).-There are two folders in the registry, production and development. When uploading a new image using `node submit.mjs`, you need to pass `ARTIFACT_REGISTRY_ENV=development || production` as detailed in the upload steps below.+There are two folders in the registry, production and development. When uploading a new image using `node submit.mjs`, you need to pass `ARTIFACT_REGISTRY_ENV=development` or `ARTIFACT_REGISTRY_ENV=production` as detailed in the upload steps below.The image that is retrieved is located at `us-docker.pkg.dev/remotion-dev/<production | development>/render:${remotionVersion}` where remotionVersion is a prop that gets passed in. Therefore, whenever a new version of Remotion is released, a new image needs to be added to the Artifact Registry that makes use of the latest Remotion Package. The images are tagged with the Remotion version, so that people can get the required version for their environment.-If developing a new image, you will need to choose it manually from within the GCP console. Alternatively, `src/shared/validate-image-remotion-version.ts` and `src/api/helpers/construct-service-deploy-request.ts` will need to be edited to use the development folder. Perhaps in the future this can check a .env variable.+If deploying a development image to cloud run, you will need to choose it manually from within the GCP console. The Container image url will be `us-docker.pkg.dev/remotion-dev/development/render:${remotionVersion}`. Alternatively, `src/shared/validate-image-remotion-version.ts` and `src/api/helpers/construct-service-deploy-request.ts` will need to be edited to use the development folder. Perhaps in the future this can check a .env variable.## Upload to Artifact Registrydiff --git a/packages/cloudrun/src/api/render-media-on-cloudrun.ts b/packages/cloudrun/src/api/render-media-on-cloudrun.tsindex fe7751ec26..32a71bf36e 100644--- a/packages/cloudrun/src/api/render-media-on-cloudrun.ts+++ b/packages/cloudrun/src/api/render-media-on-cloudrun.ts@@ -217,6 +217,10 @@ export const renderMediaOnCloudrun = async ({} else if (chunkResponse.onProgress) {updateRenderProgress?.(chunkResponse.onProgress);}++ if (chunkResponse.type === 'error') {+ reject(chunkResponse);+ }});stream.on('end', () => {@@ -227,7 +231,7 @@ export const renderMediaOnCloudrun = async ({updateRenderProgress?.(0, true);resolve({- status: 'crash',+ type: 'crash',cloudRunEndpoint,message:'Service crashed without sending a response. Check the logs in GCP console.',@@ -235,8 +239,8 @@ export const renderMediaOnCloudrun = async ({requestCrashTime: formattedCrashTime,requestElapsedTimeInSeconds: (crashTime - startTime) / 1000,});- } else if (response.status !== 'success' && response.status !== 'crash') {- throw new Error(response.stack);+ } else if (response.type !== 'success' && response.type !== 'crash') {+ throw response;}resolve(response);diff --git a/packages/cloudrun/src/cli/commands/render/index.ts b/packages/cloudrun/src/cli/commands/render/index.tsindex bcaa43ad2a..06c1be30b7 100644--- a/packages/cloudrun/src/cli/commands/render/index.ts+++ b/packages/cloudrun/src/cli/commands/render/index.ts@@ -208,7 +208,7 @@ ${downloadName ? ` Downloaded File = ${downloadName}` : ''}preferLossless: false,});- if (res.status === 'crash') {+ if (res.type === 'crash') {let timeoutPreMsg = '';const timeout = extractTimeoutFromURL(res.cloudRunEndpoint);@@ -277,7 +277,7 @@ Full logs are available at https://console.cloud.google.com/run?project=${procesLog.info(logResponse.textPayload);Log.info();}- } else if (res.status === 'success') {+ } else if (res.type === 'success') {renderProgress.doneIn = Date.now() - renderStart;updateProgress();Log.info(`diff --git a/packages/cloudrun/src/cli/index.ts b/packages/cloudrun/src/cli/index.tsindex d29ace2f72..a044304be7 100644--- a/packages/cloudrun/src/cli/index.ts+++ b/packages/cloudrun/src/cli/index.ts@@ -1,3 +1,6 @@+import {CliInternals} from '@remotion/cli';+import {ConfigInternals} from '@remotion/cli/config';+import {RenderInternals} from '@remotion/renderer';import {parsedCloudrunCli} from './args';import {permissionsCommand, PERMISSIONS_COMMAND} from './commands/permissions';import {regionsCommand, REGIONS_COMMAND} from './commands/regions';@@ -54,9 +57,27 @@ export const executeCommand = async (args: string[], remotionRoot: string) => {await matchCommand(args, remotionRoot);} catch (err) {const error = err as Error;- // todo: catch errors and print a message. Check lambda cli for example+ if (error instanceof RenderInternals.SymbolicateableError) {+ await CliInternals.handleCommonError(+ error,+ ConfigInternals.Logging.getLogLevel()+ );+ } else {+ const frames = RenderInternals.parseStack(error.stack?.split('\n') ?? []);++ const errorWithStackFrame = new RenderInternals.SymbolicateableError({+ message: error.message,+ frame: null,+ name: error.name,+ stack: error.stack,+ stackFrame: frames,+ });+ await CliInternals.handleCommonError(+ errorWithStackFrame,+ ConfigInternals.Logging.getLogLevel()+ );+ }- Log.error(error.stack);quit(1);}};diff --git a/packages/cloudrun/src/functions/helpers/payloads.ts b/packages/cloudrun/src/functions/helpers/payloads.tsindex 61ee90fdfb..48697a333a 100644--- a/packages/cloudrun/src/functions/helpers/payloads.ts+++ b/packages/cloudrun/src/functions/helpers/payloads.ts@@ -72,13 +72,13 @@ export const CloudRunPayload = z.discriminatedUnion('type', []);const renderFailResponsePayload = z.object({- status: z.literal('error'),- error: z.string(),+ type: z.literal('error'),+ message: z.string(),stack: z.string(),});const renderStillOnCloudrunResponsePayload = z.object({- status: z.literal('success'),+ type: z.literal('success'),publicUrl: z.string().optional().nullable(),cloudStorageUri: z.string(),size: z.number(),@@ -88,7 +88,7 @@ const renderStillOnCloudrunResponsePayload = z.object({});const renderMediaOnCloudrunResponsePayload = z.object({- status: z.literal('success'),+ type: z.literal('success'),publicUrl: z.string().optional().nullable(),cloudStorageUri: z.string(),size: z.number(),@@ -98,7 +98,7 @@ const renderMediaOnCloudrunResponsePayload = z.object({});const cloudRunCrashResponse = z.object({- status: z.literal('crash'),+ type: z.literal('crash'),cloudRunEndpoint: z.string(),message: z.literal('Service crashed without sending a response. Check the logs in GCP console.'diff --git a/packages/cloudrun/src/functions/index.ts b/packages/cloudrun/src/functions/index.tsindex bd346936f0..c506c84e38 100644--- a/packages/cloudrun/src/functions/index.ts+++ b/packages/cloudrun/src/functions/index.ts@@ -1,6 +1,5 @@import type * as ff from '@google-cloud/functions-framework';import {RenderInternals} from '@remotion/renderer';-import {Log} from '../cli/log';import type {ErrorResponsePayload} from './helpers/payloads';import {CloudRunPayload} from './helpers/payloads';import {renderMediaSingleThread} from './render-media-single-thread';@@ -8,7 +7,6 @@ import {renderStillSingleThread} from './render-still-single-thread';const renderOnCloudRun = async (req: ff.Request, res: ff.Response) => {try {- Log.info('renderOnCloudRun', req.body);const body = CloudRunPayload.parse(req.body);const renderType = body.type;@@ -26,14 +24,13 @@ const renderOnCloudRun = async (req: ff.Request, res: ff.Response) => {.send('Invalid render type, must be either "media" or "still"');}} catch (err) {- Log.error('Error while rendering', err);const response: ErrorResponsePayload = {- error: (err as Error).message,- status: 'error',- stack: (err as Error).stack ?? '',+ type: 'error',+ message: (err as Error).message,+ stack: (err as Error).stack as string,};-- res.status(500).send(JSON.stringify(response));+ res.write(JSON.stringify(response));+ res.end();}};diff --git a/packages/cloudrun/src/functions/render-media-single-thread.ts b/packages/cloudrun/src/functions/render-media-single-thread.tsindex 541f0e3673..e92593d181 100644--- a/packages/cloudrun/src/functions/render-media-single-thread.ts+++ b/packages/cloudrun/src/functions/render-media-single-thread.ts@@ -9,6 +9,7 @@ import type {CloudRunPayloadType,RenderMediaOnCloudrunOutput,} from './helpers/payloads';+import {writeCloudrunError} from './write-cloudrun-error';export const renderMediaSingleThread = async (body: CloudRunPayloadType,@@ -18,105 +19,122 @@ export const renderMediaSingleThread = async (throw new Error('expected type media');}- const composition = await getCompositionFromBody(body);-- const defaultOutName = `out.${RenderInternals.getFileExtensionFromCodec(- body.codec,- body.audioCodec- )}`;- const tempFilePath = `/tmp/${defaultOutName}`;const renderId = randomHash({randomInTests: true});- let previousProgress = 2;- const onProgress: RenderMediaOnProgress = ({progress}) => {- if (previousProgress !== progress) {- res.write(JSON.stringify({onProgress: progress}) + '\n');- previousProgress = progress;- }- };-- res.writeHead(200, {'Content-Type': 'text/html'});- const actualChromiumOptions: ChromiumOptions = {- ...body.chromiumOptions,- // Override the `null` value, which might come from CLI with swANGLE- gl: body.chromiumOptions?.gl ?? 'swangle',- };+ try {+ const composition = await getCompositionFromBody(body);- await RenderInternals.internalRenderMedia({- composition: {- ...composition,- height: body.forceHeight ?? composition.height,- width: body.forceWidth ?? composition.width,- },- serveUrl: body.serveUrl,- codec: body.codec,- outputLocation: tempFilePath,- serializedInputPropsWithCustomSchema:- body.serializedInputPropsWithCustomSchema,- serializedResolvedPropsWithCustomSchema: Internals.serializeJSONWithDate({- data: composition.props,- indent: undefined,- staticBase: null,- }).serializedString,- jpegQuality: body.jpegQuality,- audioCodec: body.audioCodec,- audioBitrate: body.audioBitrate,- videoBitrate: body.videoBitrate,- crf: body.crf,- pixelFormat: body.pixelFormat,- imageFormat: body.imageFormat,- scale: body.scale,- proResProfile: body.proResProfile ?? undefined,- everyNthFrame: body.everyNthFrame,- numberOfGifLoops: body.numberOfGifLoops,- onProgress,- frameRange: body.frameRange,- envVariables: body.envVariables,- chromiumOptions: actualChromiumOptions,- muted: body.muted,- logLevel: body.logLevel,- browserExecutable: null,- timeoutInMilliseconds: body.delayRenderTimeoutInMilliseconds,- cancelSignal: undefined,- concurrency: body.concurrency ?? '100%',- disallowParallelEncoding: false,- enforceAudioTrack: body.enforceAudioTrack,- ffmpegOverride: undefined,- indent: false,- onBrowserLog: null,- onCtrlCExit: () => undefined,- onDownload: () => undefined,- onStart: () => undefined,- overwrite: true,- port: null,- preferLossless: body.preferLossless,- puppeteerInstance: undefined,- server: undefined,- });+ const defaultOutName = `out.${RenderInternals.getFileExtensionFromCodec(+ body.codec,+ body.audioCodec+ )}`;+ const tempFilePath = `/tmp/${defaultOutName}`;+ let previousProgress = 2;+ const onProgress: RenderMediaOnProgress = ({progress}) => {+ if (previousProgress !== progress) {+ res.write(JSON.stringify({onProgress: progress}) + '\n');+ previousProgress = progress;+ }+ };- const storage = new Storage();+ res.writeHead(200, {'Content-Type': 'text/html'});- const publicUpload = body.privacy === 'public' || !body.privacy;+ const actualChromiumOptions: ChromiumOptions = {+ ...body.chromiumOptions,+ // Override the `null` value, which might come from CLI with swANGLE+ gl: body.chromiumOptions?.gl ?? 'swangle',+ };- const uploadedResponse = await storage- .bucket(body.outputBucket)- .upload(tempFilePath, {- destination: `renders/${renderId}/${body.outName ?? defaultOutName}`,- predefinedAcl: publicUpload ? 'publicRead' : 'projectPrivate',+ await RenderInternals.internalRenderMedia({+ composition: {+ ...composition,+ height: body.forceHeight ?? composition.height,+ width: body.forceWidth ?? composition.width,+ },+ serveUrl: body.serveUrl,+ codec: body.codec,+ outputLocation: tempFilePath,+ serializedInputPropsWithCustomSchema:+ body.serializedInputPropsWithCustomSchema,+ serializedResolvedPropsWithCustomSchema: Internals.serializeJSONWithDate({+ data: composition.props,+ indent: undefined,+ staticBase: null,+ }).serializedString,+ jpegQuality: body.jpegQuality,+ audioCodec: body.audioCodec,+ audioBitrate: body.audioBitrate,+ videoBitrate: body.videoBitrate,+ crf: body.crf,+ pixelFormat: body.pixelFormat,+ imageFormat: body.imageFormat,+ scale: body.scale,+ proResProfile: body.proResProfile ?? undefined,+ everyNthFrame: body.everyNthFrame,+ numberOfGifLoops: body.numberOfGifLoops,+ onProgress,+ frameRange: body.frameRange,+ envVariables: body.envVariables,+ chromiumOptions: actualChromiumOptions,+ muted: body.muted,+ logLevel: body.logLevel,+ browserExecutable: null,+ timeoutInMilliseconds: body.delayRenderTimeoutInMilliseconds,+ cancelSignal: undefined,+ concurrency: body.concurrency ?? '100%',+ disallowParallelEncoding: false,+ enforceAudioTrack: body.enforceAudioTrack,+ ffmpegOverride: undefined,+ indent: false,+ onBrowserLog: null,+ onCtrlCExit: () => undefined,+ onDownload: () => undefined,+ onStart: () => undefined,+ overwrite: true,+ port: null,+ preferLossless: body.preferLossless,+ puppeteerInstance: undefined,+ server: undefined,});- const uploadedFile = uploadedResponse[0];- const renderMetadata = await uploadedFile.getMetadata();- const responseData: RenderMediaOnCloudrunOutput = {- status: 'success',- publicUrl: publicUpload ? uploadedFile.publicUrl() : null,- cloudStorageUri: uploadedFile.cloudStorageURI.href,- size: renderMetadata[0].size,- bucketName: body.outputBucket,- renderId,- privacy: publicUpload ? 'public-read' : 'project-private',- };+ const storage = new Storage();++ const publicUpload = body.privacy === 'public' || !body.privacy;++ const uploadedResponse = await storage+ .bucket(body.outputBucket)+ .upload(tempFilePath, {+ destination: `renders/${renderId}/${body.outName ?? defaultOutName}`,+ predefinedAcl: publicUpload ? 'publicRead' : 'projectPrivate',+ });- RenderInternals.Log.info('Render Completed:', responseData);- res.end(JSON.stringify({response: responseData}));+ const uploadedFile = uploadedResponse[0];+ const renderMetadata = await uploadedFile.getMetadata();+ const responseData: RenderMediaOnCloudrunOutput = {+ type: 'success',+ publicUrl: publicUpload ? uploadedFile.publicUrl() : null,+ cloudStorageUri: uploadedFile.cloudStorageURI.href,+ size: renderMetadata[0].size,+ bucketName: body.outputBucket,+ renderId,+ privacy: publicUpload ? 'public-read' : 'project-private',+ };++ RenderInternals.Log.info('Render Completed:', responseData);+ res.end(JSON.stringify({response: responseData}));+ } catch (err) {+ await writeCloudrunError({+ bucketName: body.outputBucket,+ renderId,+ errorInfo: {+ name: (err as Error).name as string,+ message: (err as Error).message as string,+ stack: (err as Error).stack as string,+ type: 'renderer',+ },+ publicUpload: body.privacy === 'public' || !body.privacy,+ });++ throw err;+ }};diff --git a/packages/cloudrun/src/functions/render-still-single-thread.ts b/packages/cloudrun/src/functions/render-still-single-thread.tsindex 4075986a07..0be63b6d0e 100644--- a/packages/cloudrun/src/functions/render-still-single-thread.ts+++ b/packages/cloudrun/src/functions/render-still-single-thread.ts@@ -90,7 +90,7 @@ export const renderStillSingleThread = async (size: renderMetadata[0].size,bucketName: body.outputBucket,renderId,- status: 'success',+ type: 'success',privacy: publicUpload ? 'public-read' : 'project-private',};diff --git a/packages/cloudrun/src/functions/write-cloudrun-error.ts b/packages/cloudrun/src/functions/write-cloudrun-error.tsnew file mode 100644index 0000000000..37fafe4070--- /dev/null+++ b/packages/cloudrun/src/functions/write-cloudrun-error.ts@@ -0,0 +1,32 @@+import {Storage} from '@google-cloud/storage';+import fs from 'node:fs';++export type CloudrunErrorInfo = {+ type: 'renderer' | 'browser' | 'stitcher' | 'webhook';+ message: string;+ name: string;+ stack: string;+};++export const writeCloudrunError = async ({+ bucketName,+ renderId,+ errorInfo,+ publicUpload,+}: {+ bucketName: string;+ renderId: string;+ errorInfo: CloudrunErrorInfo;+ publicUpload: boolean;+}) => {+ const storage = new Storage();++ const tempFilePath = '/tmp/errorInfo.txt';++ fs.writeFileSync(tempFilePath, JSON.stringify(errorInfo));++ await storage.bucket(bucketName).upload(tempFilePath, {+ destination: `renders/${renderId}/errors/error.txt`,+ predefinedAcl: publicUpload ? 'publicRead' : 'projectPrivate',+ });+};diff --git a/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar b/packages/cloudrun/src/gcpInstaller/gcpInstaller.tarindex 040ba03679..9cbb01a9d0 100644Binary files a/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar and b/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar differ