Skip to content

πŸŽ₯ Make videos programmatically with React

errors propogating for stills

Matt McGillivrayd67134dddfae
diff --git a/packages/cloudrun/src/api/render-still-on-cloudrun.ts b/packages/cloudrun/src/api/render-still-on-cloudrun.ts
index 9814db20ed..fa2ba8d957 100644
--- a/packages/cloudrun/src/api/render-still-on-cloudrun.ts
+++ b/packages/cloudrun/src/api/render-still-on-cloudrun.ts
@@ -6,7 +6,9 @@ import type {
import {RenderInternals} from '@remotion/renderer';
import {Internals} from 'remotion';
import type {
+ CloudRunCrashResponse,
CloudRunPayloadType,
+ ErrorResponsePayload,
RenderStillOnCloudrunOutput,
} from '../functions/helpers/payloads';
import type {GcpRegion} from '../pricing/gcp-regions';
@@ -83,7 +85,9 @@ export const renderStillOnCloudrun = async ({
forceHeight,
logLevel,
delayRenderTimeoutInMilliseconds,
-}: RenderStillOnCloudrunInput): Promise<RenderStillOnCloudrunOutput> => {
+}: RenderStillOnCloudrunInput): Promise<
+ RenderStillOnCloudrunOutput | ErrorResponsePayload | CloudRunCrashResponse
+> => {
validateServeUrl(serveUrl);
if (privacy) validatePrivacy(privacy);
@@ -123,10 +127,75 @@ export const renderStillOnCloudrun = async ({
const client = await getAuthClientForUrl(cloudRunEndpoint);
- const renderResponse = await client.request({
+ const postResponse = await client.request({
url: cloudRunUrl,
method: 'POST',
data,
+ responseType: 'stream',
});
- return renderResponse.data as RenderStillOnCloudrunOutput;
+
+ const renderResponse = await new Promise<
+ RenderStillOnCloudrunOutput | CloudRunCrashResponse
+ >((resolve, reject) => {
+ let response:
+ | RenderStillOnCloudrunOutput
+ | ErrorResponsePayload
+ | CloudRunCrashResponse;
+
+ const startTime = Date.now();
+ const formattedStartTime = new Date().toISOString();
+
+ const stream: any = postResponse.data;
+
+ let accumulatedChunks = ''; // A buffer to accumulate chunks.
+
+ stream.on('data', (chunk: Buffer) => {
+ accumulatedChunks += chunk.toString(); // Add the new chunk to the buffer.
+ let parsedData;
+
+ try {
+ parsedData = JSON.parse(accumulatedChunks.trim());
+ accumulatedChunks = ''; // Clear the buffer after successful parsing.
+ } catch (e) {
+ // If parsing fails, it means we don't have a complete JSON string yet.
+ // We'll wait for more chunks.
+ return;
+ }
+
+ if (parsedData.response) {
+ response = parsedData.response;
+ }
+
+ if (parsedData.type === 'error') {
+ reject(parsedData);
+ }
+ });
+
+ stream.on('end', () => {
+ if (!response) {
+ const crashTime = Date.now();
+ const formattedCrashTime = new Date().toISOString();
+
+ resolve({
+ type: 'crash',
+ cloudRunEndpoint,
+ message:
+ 'Service crashed without sending a response. Check the logs in GCP console.',
+ requestStartTime: formattedStartTime,
+ requestCrashTime: formattedCrashTime,
+ requestElapsedTimeInSeconds: (crashTime - startTime) / 1000,
+ });
+ } else if (response.type !== 'success' && response.type !== 'crash') {
+ throw response;
+ }
+
+ resolve(response);
+ });
+
+ stream.on('error', (error: Error) => {
+ reject(error);
+ });
+ });
+
+ return renderResponse;
};
diff --git a/packages/cloudrun/src/cli/commands/still.ts b/packages/cloudrun/src/cli/commands/still.ts
index ac2b0ff2ab..f911192d21 100644
--- a/packages/cloudrun/src/cli/commands/still.ts
+++ b/packages/cloudrun/src/cli/commands/still.ts
@@ -3,6 +3,9 @@ import {ConfigInternals} from '@remotion/cli/config';
import {RenderInternals} from '@remotion/renderer';
import {Internals} from 'remotion';
import {downloadFile} from '../../api/download-file';
+import {extractMemoryFromURL} from '../../api/helpers/extract-mem-from-url';
+import {extractTimeoutFromURL} from '../../api/helpers/extract-time-from-url';
+import {getCloudLoggingClient} from '../../api/helpers/get-cloud-logging-client';
import {renderStillOnCloudrun} from '../../api/render-still-on-cloudrun';
import {validateServeUrl} from '../../shared/validate-serveurl';
import {Log} from '../log';
@@ -156,34 +159,105 @@ ${downloadName ? ` Downloaded File = ${downloadName}` : ''}
logLevel: ConfigInternals.Logging.getLogLevel(),
delayRenderTimeoutInMilliseconds: puppeteerTimeout,
});
- doneIn = Date.now() - renderStart;
- updateProgress(true);
+ if (res.type === 'crash') {
+ let timeoutPreMsg = '';
- Log.info(
- CliInternals.chalk.gray(`Cloud Storage Uri = ${res.cloudStorageUri}`)
- );
- Log.info(CliInternals.chalk.gray(`Render ID = ${res.renderId}`));
- Log.info(
- CliInternals.chalk.gray(
- `${Math.round(Number(res.size) / 1000)} KB, Privacy: ${
- res.privacy
- }, Bucket: ${res.bucketName}`
- )
- );
- Log.info(CliInternals.chalk.blue(`β—‹ ${res.publicUrl}`));
+ const timeout = extractTimeoutFromURL(res.cloudRunEndpoint);
+ const memoryLimit = extractMemoryFromURL(res.cloudRunEndpoint);
- if (downloadName) {
- Log.info('');
- Log.info('downloading file...');
+ if (timeout && res.requestElapsedTimeInSeconds + 10 > timeout) {
+ timeoutPreMsg = `Render call likely timed out. Service timeout is ${timeout} seconds, and render took at least ${res.requestElapsedTimeInSeconds.toFixed(
+ 1
+ )} seconds.\n`;
+ } else {
+ timeoutPreMsg = `Crash unlikely due to timeout. Render took ${res.requestElapsedTimeInSeconds.toFixed(
+ 1
+ )} seconds, below the timeout of ${timeout} seconds.\n`;
+ }
- const {outputPath: destination} = await downloadFile({
- bucketName: res.bucketName,
- gsutilURI: res.cloudStorageUri,
- downloadName,
+ Log.error(
+ `Error rendering on Cloud Run. The Cloud Run service did not return a response.\n
+${timeoutPreMsg}The crash may be due to the service exceeding its memory limit of ${memoryLimit}.
+Full logs are available at https://console.cloud.google.com/run?project=${process.env.REMOTION_GCP_PROJECT_ID}\n`
+ );
+
+ const cloudLoggingClient = getCloudLoggingClient();
+
+ const listLogEntriesRequest = {
+ resourceNames: [`projects/${process.env.REMOTION_GCP_PROJECT_ID}`],
+ filter: `logName=projects/${process.env.REMOTION_GCP_PROJECT_ID}/logs/run.googleapis.com%2Fvarlog%2Fsystem AND (severity=WARNING OR severity=ERROR) AND timestamp >= "${res.requestStartTime}"`,
+ };
+
+ const logCheckCountdown = CliInternals.createOverwriteableCliOutput({
+ quiet: CliInternals.quietFlagProvided(),
+ cancelSignal: null,
+ updatesDontOverwrite: false,
+ indent: false,
});
+ await (() => {
+ return new Promise<void>((resolve) => {
+ let timeLeft = 30;
+ const intervalId = setInterval(() => {
+ logCheckCountdown.update(
+ `GCP Cloud Logging takes time to ingest and index logs.\nFetching recent error/warning logs in ${timeLeft} seconds`,
+ false
+ );
+ timeLeft--;
+ if (timeLeft < 0) {
+ logCheckCountdown.update('Fetching logs...\n\n', false);
+ clearInterval(intervalId);
+ resolve();
+ }
+ }, 1000);
+ });
+ })();
+
+ const iterableLogListEntries = await cloudLoggingClient.listLogEntriesAsync(
+ listLogEntriesRequest
+ );
+ for await (const logResponse of iterableLogListEntries) {
+ const responseDate = new Date(
+ Number(logResponse.timestamp.seconds) * 1000 +
+ Number(logResponse.timestamp.nanos) / 1000000
+ );
+
+ const convertedDate = responseDate.toLocaleString();
+
+ Log.info(convertedDate);
+ Log.info(logResponse.textPayload);
+ Log.info();
+ }
+ } else if (res.type === 'success') {
+ doneIn = Date.now() - renderStart;
+ updateProgress(true);
+
+ Log.info(
+ CliInternals.chalk.gray(`Cloud Storage Uri = ${res.cloudStorageUri}`)
+ );
+ Log.info(CliInternals.chalk.gray(`Render ID = ${res.renderId}`));
Log.info(
- CliInternals.chalk.blueBright(`Downloaded file to ${destination}!`)
+ CliInternals.chalk.gray(
+ `${Math.round(Number(res.size) / 1000)} KB, Privacy: ${
+ res.privacy
+ }, Bucket: ${res.bucketName}`
+ )
);
+ Log.info(CliInternals.chalk.blue(`β—‹ ${res.publicUrl}`));
+
+ if (downloadName) {
+ Log.info('');
+ Log.info('downloading file...');
+
+ const {outputPath: destination} = await downloadFile({
+ bucketName: res.bucketName,
+ gsutilURI: res.cloudStorageUri,
+ downloadName,
+ });
+
+ Log.info(
+ CliInternals.chalk.blueBright(`Downloaded file to ${destination}!`)
+ );
+ }
}
};
diff --git a/packages/cloudrun/src/functions/render-still-single-thread.ts b/packages/cloudrun/src/functions/render-still-single-thread.ts
index 0be63b6d0e..9a0496e283 100644
--- a/packages/cloudrun/src/functions/render-still-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-still-single-thread.ts
@@ -10,6 +10,7 @@ import type {
CloudRunPayloadType,
RenderStillOnCloudrunOutput,
} from './helpers/payloads';
+import {writeCloudrunError} from './helpers/write-cloudrun-error';
export const renderStillSingleThread = async (
body: CloudRunPayloadType,
@@ -19,84 +20,99 @@ export const renderStillSingleThread = async (
throw new Error('expected type still');
}
- Log.verbose('Rendering still frame', body);
+ const renderId = randomHash({randomInTests: true});
- const composition = await getCompositionFromBody(body);
+ try {
+ Log.verbose('Rendering still frame', body);
- Log.verbose('Composition loaded', composition);
+ const composition = await getCompositionFromBody(body);
- const tempFilePath = '/tmp/still.png';
- const renderId = randomHash({randomInTests: true});
+ Log.verbose('Composition loaded', composition);
+
+ const tempFilePath = '/tmp/still.png';
- const actualChromiumOptions: ChromiumOptions = {
- ...body.chromiumOptions,
- // Override the `null` value, which might come from CLI with swANGLE
- gl: body.chromiumOptions?.gl ?? 'swangle',
- };
-
- await RenderInternals.internalRenderStill({
- composition: {
- ...composition,
- height: body.forceHeight ?? composition.height,
- width: body.forceWidth ?? composition.width,
- },
- serveUrl: body.serveUrl,
- output: tempFilePath,
- serializedInputPropsWithCustomSchema:
- body.serializedInputPropsWithCustomSchema,
- serializedResolvedPropsWithCustomSchema: Internals.serializeJSONWithDate({
- data: composition.props,
- indent: undefined,
- staticBase: null,
- }).serializedString,
- jpegQuality: body.jpegQuality ?? RenderInternals.DEFAULT_JPEG_QUALITY,
- imageFormat: body.imageFormat,
- scale: body.scale,
- envVariables: body.envVariables,
- chromiumOptions: actualChromiumOptions,
- frame: body.frame,
- logLevel: body.logLevel,
- browserExecutable: null,
- cancelSignal: null,
- indent: false,
- timeoutInMilliseconds: body.delayRenderTimeoutInMilliseconds,
- onBrowserLog: null,
- onDownload: null,
- overwrite: true,
- port: null,
- puppeteerInstance: null,
- server: undefined,
- });
- Log.info('Still rendered');
-
- 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 ?? 'out.png'}`,
- predefinedAcl: publicUpload ? 'publicRead' : 'projectPrivate',
+ const actualChromiumOptions: ChromiumOptions = {
+ ...body.chromiumOptions,
+ // Override the `null` value, which might come from CLI with swANGLE
+ gl: body.chromiumOptions?.gl ?? 'swangle',
+ };
+
+ await RenderInternals.internalRenderStill({
+ composition: {
+ ...composition,
+ height: body.forceHeight ?? composition.height,
+ width: body.forceWidth ?? composition.width,
+ },
+ serveUrl: body.serveUrl,
+ output: tempFilePath,
+ serializedInputPropsWithCustomSchema:
+ body.serializedInputPropsWithCustomSchema,
+ serializedResolvedPropsWithCustomSchema: Internals.serializeJSONWithDate({
+ data: composition.props,
+ indent: undefined,
+ staticBase: null,
+ }).serializedString,
+ jpegQuality: body.jpegQuality ?? RenderInternals.DEFAULT_JPEG_QUALITY,
+ imageFormat: body.imageFormat,
+ scale: body.scale,
+ envVariables: body.envVariables,
+ chromiumOptions: actualChromiumOptions,
+ frame: body.frame,
+ logLevel: body.logLevel,
+ browserExecutable: null,
+ cancelSignal: null,
+ indent: false,
+ timeoutInMilliseconds: body.delayRenderTimeoutInMilliseconds,
+ onBrowserLog: null,
+ onDownload: null,
+ overwrite: true,
+ port: null,
+ puppeteerInstance: null,
+ server: undefined,
});
+ Log.info('Still rendered');
+
+ const storage = new Storage();
- Log.info('Still uploaded');
+ const publicUpload = body.privacy === 'public' || !body.privacy;
- const uploadedFile = uploadedResponse[0];
- const renderMetadata = await uploadedFile.getMetadata();
- const responseData: RenderStillOnCloudrunOutput = {
- publicUrl: uploadedFile.publicUrl(),
- cloudStorageUri: uploadedFile.cloudStorageURI.href,
- size: renderMetadata[0].size,
- bucketName: body.outputBucket,
- renderId,
- type: 'success',
- privacy: publicUpload ? 'public-read' : 'project-private',
- };
+ const uploadedResponse = await storage
+ .bucket(body.outputBucket)
+ .upload(tempFilePath, {
+ destination: `renders/${renderId}/${body.outName ?? 'out.png'}`,
+ predefinedAcl: publicUpload ? 'publicRead' : 'projectPrivate',
+ });
- RenderInternals.Log.info('Render Completed:', responseData);
+ Log.info('Still uploaded');
- const jsonContent = JSON.stringify(responseData);
+ const uploadedFile = uploadedResponse[0];
+ const renderMetadata = await uploadedFile.getMetadata();
+ const responseData: RenderStillOnCloudrunOutput = {
+ publicUrl: uploadedFile.publicUrl(),
+ cloudStorageUri: uploadedFile.cloudStorageURI.href,
+ size: renderMetadata[0].size,
+ bucketName: body.outputBucket,
+ renderId,
+ type: 'success',
+ privacy: publicUpload ? 'public-read' : 'project-private',
+ };
- res.end(jsonContent);
+ 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/gcpInstaller/gcpInstaller.tar b/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar
index 2d5cb5260c..4c52ec20bf 100644
Binary files a/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar and b/packages/cloudrun/src/gcpInstaller/gcpInstaller.tar differ