Skip to content

πŸŽ₯ Make videos programmatically with React

full typesafety and error handlign

Jonny Burgerce22e6a107d7
diff --git a/packages/cloudrun/src/cli/commands/render/renderMedia.ts b/packages/cloudrun/src/cli/commands/render/renderMedia.ts
index 62c917d22b..b20bfaa4e6 100644
--- a/packages/cloudrun/src/cli/commands/render/renderMedia.ts
+++ b/packages/cloudrun/src/cli/commands/render/renderMedia.ts
@@ -4,8 +4,8 @@ import type {CloudrunCodec} from '../../../shared/validate-gcp-codec';
// import {validateMaxRetries} from '../../../shared/validate-retries';
import {ConfigInternals} from '@remotion/cli/config';
import {downloadFile} from '../../../api/download-file';
-import type {RenderMediaOnCloudrunOutput} from '../../../functions/helpers/payloads';
import {parsedCloudrunCli} from '../../args';
+import {quit} from '../../helpers/quit';
import {Log} from '../../log';
import {renderArgsCheck} from './helpers/renderArgsCheck';
@@ -144,38 +144,43 @@ ${downloadName ? ` Downloaded File = ${downloadName}` : ''}
renderProgress.doneIn = Date.now() - renderStart;
updateProgress();
- const success = res as RenderMediaOnCloudrunOutput;
- Log.info(`
+ if (res.status === 'success') {
+ Log.info(`
`);
- Log.info(
- CliInternals.chalk.blueBright(
- `
+ Log.info(
+ CliInternals.chalk.blueBright(
+ `
🀘 Rendered media on Cloud Run! 🀘
- Public URL = ${decodeURIComponent(success.publicUrl)}
- Cloud Storage Uri = ${success.cloudStorageUri}
- Size (KB) = ${Math.round(Number(success.size) / 1000)}
- Bucket Name = ${success.bucketName}
- Privacy = ${success.privacy}
- Render ID = ${success.renderId}
+ Public URL = ${decodeURIComponent(res.publicUrl)}
+ Cloud Storage Uri = ${res.cloudStorageUri}
+ Size (KB) = ${Math.round(Number(res.size) / 1000)}
+ Bucket Name = ${res.bucketName}
+ Privacy = ${res.privacy}
+ Render ID = ${res.renderId}
Codec = ${codec} (${codecReason})
`.trim()
- )
- );
-
- if (downloadName) {
- Log.info('');
- Log.info('downloading file...');
-
- const destination = await downloadFile({
- bucketName: success.bucketName,
- gsutilURI: success.cloudStorageUri,
- downloadName,
- });
-
- Log.info(
- CliInternals.chalk.blueBright(`Downloaded file to ${destination}!`)
+ )
);
+
+ if (downloadName) {
+ Log.info('');
+ Log.info('downloading file...');
+
+ const destination = await downloadFile({
+ bucketName: res.bucketName,
+ gsutilURI: res.cloudStorageUri,
+ downloadName,
+ });
+
+ Log.info(
+ CliInternals.chalk.blueBright(`Downloaded file to ${destination}!`)
+ );
+ }
+ } else {
+ Log.error('Render failed with the following error: ');
+ Log.error(res.stack);
+ quit(1);
}
};
diff --git a/packages/cloudrun/src/cli/commands/render/renderStill.ts b/packages/cloudrun/src/cli/commands/render/renderStill.ts
index 47b26148ba..5ab54377b3 100644
--- a/packages/cloudrun/src/cli/commands/render/renderStill.ts
+++ b/packages/cloudrun/src/cli/commands/render/renderStill.ts
@@ -2,7 +2,7 @@ import {CliInternals} from '@remotion/cli';
import {ConfigInternals} from '@remotion/cli/config';
import {downloadFile} from '../../../api/download-file';
import {renderStillOnCloudrun} from '../../../api/render-still-on-cloudrun';
-import type {RenderStillOnCloudrunOutput} from '../../../functions/helpers/payloads';
+import {quit} from '../../helpers/quit';
import {Log} from '../../log';
import {renderArgsCheck} from './helpers/renderArgsCheck';
@@ -51,8 +51,6 @@ export const renderStillSubcommand = async (
CliInternals.Log.info(
CliInternals.chalk.gray(
`
-Sending request to Cloud Run:
-
Cloud Run Service URL = ${cloudRunUrl}
Type = still
Composition = ${composition}
@@ -107,38 +105,43 @@ ${downloadName ? ` Downloaded File = ${downloadName}` : ''}
doneIn = Date.now() - renderStart;
updateProgress();
- const success = res as RenderStillOnCloudrunOutput;
- Log.info(`
+ if (res.status === 'success') {
+ Log.info(`
`);
- Log.info(
- CliInternals.chalk.blueBright(
- `
+ Log.info(
+ CliInternals.chalk.blueBright(
+ `
🀘 Rendered still on Cloud Run! 🀘
- Public URL = ${decodeURIComponent(success.publicUrl)}
- Cloud Storage Uri = ${success.cloudStorageUri}
- Size (KB) = ${Math.round(Number(success.size) / 1000)}
- Bucket Name = ${success.bucketName}
- Privacy = ${success.privacy}
- Render ID = ${success.renderId}
+ Public URL = ${decodeURIComponent(res.publicUrl)}
+ Cloud Storage Uri = ${res.cloudStorageUri}
+ Size (KB) = ${Math.round(Number(res.size) / 1000)}
+ Bucket Name = ${res.bucketName}
+ Privacy = ${res.privacy}
+ Render ID = ${res.renderId}
Image Format = ${imageFormat} (${imageFormatReason})
`.trim()
- )
- );
+ )
+ );
- if (downloadName) {
- Log.info('');
- Log.info('downloading file...');
+ if (downloadName) {
+ Log.info('');
+ Log.info('downloading file...');
- const destination = await downloadFile({
- bucketName: success.bucketName,
- gsutilURI: success.cloudStorageUri,
- downloadName,
- });
+ const destination = await downloadFile({
+ bucketName: res.bucketName,
+ gsutilURI: res.cloudStorageUri,
+ downloadName,
+ });
- Log.info(
- CliInternals.chalk.blueBright(`Downloaded file to ${destination}!`)
- );
+ Log.info(
+ CliInternals.chalk.blueBright(`Downloaded file to ${destination}!`)
+ );
+ }
+ } else {
+ Log.error('Render failed with the following reason:');
+ Log.error(res.stack);
+ quit(1);
}
};
diff --git a/packages/cloudrun/src/functions/helpers/payloads.ts b/packages/cloudrun/src/functions/helpers/payloads.ts
index 0930986e88..140b31dfac 100644
--- a/packages/cloudrun/src/functions/helpers/payloads.ts
+++ b/packages/cloudrun/src/functions/helpers/payloads.ts
@@ -62,30 +62,45 @@ export const CloudRunPayload = z.discriminatedUnion('type', [
}),
]);
-const renderStillOnLambdaResponsePayload = z.object({
- publicUrl: z.string(),
- cloudStorageUri: z.string(),
- size: z.number(),
- bucketName: z.string(),
- renderId: z.string(),
- status: z.literal('success'),
- privacy: z.enum(['public-read', 'project-private']),
+const renderFailResponsePayload = z.object({
+ status: z.literal('error'),
+ error: z.string(),
+ stack: z.string(),
});
-const renderMediaOnLambdaResponsePayload = z.object({
- publicUrl: z.string(),
- cloudStorageUri: z.string(),
- size: z.number(),
- bucketName: z.string(),
- renderId: z.string(),
- status: z.literal('success'),
- privacy: z.enum(['public-read', 'project-private']),
-});
+const renderStillOnLambdaResponsePayload = z.discriminatedUnion('status', [
+ z.object({
+ publicUrl: z.string(),
+ cloudStorageUri: z.string(),
+ size: z.number(),
+ bucketName: z.string(),
+ renderId: z.string(),
+ status: z.literal('success'),
+ privacy: z.enum(['public-read', 'project-private']),
+ }),
+ renderFailResponsePayload,
+]);
+
+const renderMediaOnLambdaResponsePayload = z.discriminatedUnion('status', [
+ z.object({
+ publicUrl: z.string(),
+ cloudStorageUri: z.string(),
+ size: z.number(),
+ bucketName: z.string(),
+ renderId: z.string(),
+ status: z.literal('success'),
+ privacy: z.enum(['public-read', 'project-private']),
+ }),
+ renderFailResponsePayload,
+]);
export type CloudRunPayloadType = z.infer<typeof CloudRunPayload>;
+
export type RenderStillOnCloudrunOutput = z.infer<
typeof renderStillOnLambdaResponsePayload
>;
export type RenderMediaOnCloudrunOutput = z.infer<
typeof renderMediaOnLambdaResponsePayload
>;
+
+export type ErrorResponsePayload = z.infer<typeof renderFailResponsePayload>;
diff --git a/packages/cloudrun/src/functions/index.ts b/packages/cloudrun/src/functions/index.ts
index 9b284b40da..a28b94cfc1 100644
--- a/packages/cloudrun/src/functions/index.ts
+++ b/packages/cloudrun/src/functions/index.ts
@@ -1,4 +1,5 @@
import type * as ff from '@google-cloud/functions-framework';
+import type {ErrorResponsePayload} from './helpers/payloads';
import {CloudRunPayload} from './helpers/payloads';
import {renderMediaSingleThread} from './render-media-single-thread';
import {renderStillSingleThread} from './render-still-single-thread';
@@ -7,17 +8,27 @@ const renderOnCloudRun = async (req: ff.Request, res: ff.Response) => {
const body = CloudRunPayload.parse(req.body);
const renderType = body.type;
- switch (renderType) {
- case 'media':
- await renderMediaSingleThread(body, res);
- break;
- case 'still':
- await renderStillSingleThread(body, res);
- break;
- default:
- res
- .status(400)
- .send('Invalid render type, must be either "media" or "still"');
+ try {
+ switch (renderType) {
+ case 'media':
+ await renderMediaSingleThread(body, res);
+ break;
+ case 'still':
+ await renderStillSingleThread(body, res);
+ break;
+ default:
+ res
+ .status(400)
+ .send('Invalid render type, must be either "media" or "still"');
+ }
+ } catch (err) {
+ const response: ErrorResponsePayload = {
+ error: (err as Error).message,
+ status: 'error',
+ stack: (err as Error).stack ?? '',
+ };
+
+ res.status(500).send(JSON.stringify(response));
}
};
diff --git a/packages/cloudrun/src/functions/render-media-single-thread.ts b/packages/cloudrun/src/functions/render-media-single-thread.ts
index 9c62f350ef..d8c2d09102 100644
--- a/packages/cloudrun/src/functions/render-media-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-media-single-thread.ts
@@ -1,8 +1,7 @@
import type * as ff from '@google-cloud/functions-framework';
import {Storage} from '@google-cloud/storage';
import type {RenderMediaOnProgress} from '@remotion/renderer';
-import {renderMedia} from '@remotion/renderer';
-import {Log} from '../cli/log';
+import {RenderInternals, renderMedia} from '@remotion/renderer';
import {randomHash} from '../shared/random-hash';
import {getCompositionFromBody} from './helpers/get-composition-from-body';
import type {
@@ -86,6 +85,6 @@ export const renderMediaSingleThread = async (
privacy: publicUpload ? 'public-read' : 'project-private',
};
- Log.info('Render Completed:', responseData);
+ RenderInternals.Log.info('Render Completed:', responseData);
res.end(JSON.stringify({response: responseData}));
};
diff --git a/packages/cloudrun/src/functions/render-still-single-thread.ts b/packages/cloudrun/src/functions/render-still-single-thread.ts
index 1d3697441d..ed2d736ffb 100644
--- a/packages/cloudrun/src/functions/render-still-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-still-single-thread.ts
@@ -1,7 +1,6 @@
import type * as ff from '@google-cloud/functions-framework';
import {Storage} from '@google-cloud/storage';
-import {renderStill} from '@remotion/renderer';
-import {Log} from '../cli/log';
+import {RenderInternals, renderStill} from '@remotion/renderer';
import {randomHash} from '../shared/random-hash';
import {getCompositionFromBody} from './helpers/get-composition-from-body';
import type {
@@ -65,7 +64,7 @@ export const renderStillSingleThread = async (
privacy: publicUpload ? 'public-read' : 'project-private',
};
- Log.info('Render Completed:', responseData);
+ RenderInternals.Log.info('Render Completed:', responseData);
const jsonContent = JSON.stringify(responseData);