Skip to content

🎥 Make videos programmatically with React

post render data

Jonny Burger12a70e9cb1aa
diff --git a/packages/lambda/src/functions/get-progress.ts b/packages/lambda/src/functions/get-progress.ts
index 31b1d6a0f1..02ff2e0610 100644
--- a/packages/lambda/src/functions/get-progress.ts
+++ b/packages/lambda/src/functions/get-progress.ts
@@ -1,12 +1,8 @@
-import {_Object} from '@aws-sdk/client-s3';
-import {Internals} from 'remotion';
-import {AwsRegion} from '../pricing/aws-regions';
import {calculatePrice} from '../pricing/calculate-price';
import {
chunkKey,
EncodingProgress,
encodingProgressKey,
- getErrorKeyPrefix,
lambdaInitializedPrefix,
LambdaPayload,
LambdaRoutines,
@@ -17,11 +13,14 @@ import {
rendersPrefix,
} from '../shared/constants';
import {parseLambdaTimingsKey} from '../shared/parse-lambda-timings-key';
-import {streamToString} from '../shared/stream-to-string';
+import {findOutputFileInBucket} from './helpers/find-output-file-in-bucket';
import {getCleanupProgress} from './helpers/get-cleanup-progress';
import {getCurrentRegion} from './helpers/get-current-region';
+import {getEncodingMetadata} from './helpers/get-encoding-metadata';
+import {getRenderMetadata} from './helpers/get-render-metadata';
+import {getTimeToFinish} from './helpers/get-time-to-finish';
import {inspectErrors} from './helpers/inspect-errors';
-import {lambdaLs, lambdaReadFile} from './helpers/io';
+import {lambdaLs} from './helpers/io';
import {isFatalError} from './helpers/is-fatal-error';
type Options = {
@@ -50,89 +49,6 @@ const getFinalEncodingStatus = ({
return encodingProgress;
};
-const getEncodingMetadata = async ({
- exists,
- bucketName,
- renderId,
- region,
-}: {
- exists: boolean;
- bucketName: string;
- renderId: string;
- region: AwsRegion;
-}): Promise<EncodingProgress | null> => {
- if (!exists) {
- return null;
- }
-
- const Body = await lambdaReadFile({
- bucketName,
- key: encodingProgressKey(renderId),
- region,
- });
-
- try {
- const encodingProgress = JSON.parse(
- await streamToString(Body)
- ) as EncodingProgress;
-
- return encodingProgress;
- } catch (err) {
- // The file may not yet have been fully written
- return null;
- }
-};
-
-const getRenderMetadata = async ({
- exists,
- bucketName,
- renderId,
- region,
-}: {
- exists: boolean;
- bucketName: string;
- renderId: string;
- region: AwsRegion;
-}) => {
- if (!exists) {
- return null;
- }
-
- const Body = await lambdaReadFile({
- bucketName,
- key: renderMetadataKey(renderId),
- region,
- });
-
- const renderMetadataResponse = JSON.parse(
- await streamToString(Body)
- ) as RenderMetadata;
-
- return renderMetadataResponse;
-};
-
-const getTimeToFinish = ({
- renderMetadata,
- output,
-}: {
- renderMetadata: RenderMetadata | null;
- output: _Object | null;
-}) => {
- if (!output) {
- return null;
- }
-
- if (!output.LastModified) {
- return null;
- }
-
- if (!renderMetadata) {
- return null;
- }
-
- return output.LastModified.getTime() - renderMetadata.startedDate;
-};
-
export const progressHandler = async (
lambdaParams: LambdaPayload,
options: Options
@@ -173,11 +89,6 @@ export const progressHandler = async (
.map((p) => p.end - p.start)
.reduce((a, b) => a + b, 0);
- const errors = contents
- .filter((c) => c.Key?.startsWith(getErrorKeyPrefix(lambdaParams.renderId)))
- .map((c) => c.Key)
- .filter(Internals.truthy);
-
const [encodingStatus, renderMetadata, errorExplanations] = await Promise.all(
[
getEncodingMetadata({
@@ -201,7 +112,8 @@ export const progressHandler = async (
region: getCurrentRegion(),
}),
inspectErrors({
- errs: errors,
+ contents,
+ renderId: lambdaParams.renderId,
bucket: lambdaParams.bucketName,
region: getCurrentRegion(),
}),
@@ -238,21 +150,14 @@ export const progressHandler = async (
}).toPrecision(5)
);
- const getOutputFile = () => {
- if (!output) {
- return null;
- }
-
- if (!renderMetadata) {
- throw new Error('unexpectedly did not get renderMetadata');
- }
-
- return `https://s3.${process.env.AWS_REGION as AwsRegion}.amazonaws.com/${
- lambdaParams.bucketName
- }/${outName(lambdaParams.renderId, renderMetadata.codec)}`;
- };
+ const outputFile = findOutputFileInBucket({
+ bucketName: lambdaParams.bucketName,
+ output,
+ renderId: lambdaParams.renderId,
+ renderMetadata,
+ });
- const lambdasInvoked = getOutputFile()
+ const lambdasInvoked = outputFile
? renderMetadata?.totalChunks ?? 0
: contents.filter((c) =>
c.Key?.startsWith(lambdaInitializedPrefix(lambdaParams.renderId))
@@ -261,12 +166,12 @@ export const progressHandler = async (
const cleanup = getCleanupProgress({
chunkCount: renderMetadata?.totalChunks ?? 0,
contents,
- output: getOutputFile(),
+ output: outputFile,
renderId: lambdaParams.renderId,
});
return {
- chunks: chunks.length,
+ chunks: outputFile ? renderMetadata?.totalChunks ?? 0 : chunks.length,
done: Boolean(output) && cleanup?.done,
encodingStatus: getFinalEncodingStatus({
encodingStatus,
@@ -286,7 +191,7 @@ export const progressHandler = async (
renderId: lambdaParams.renderId,
renderMetadata,
bucket: lambdaParams.bucketName,
- outputFile: getOutputFile(),
+ outputFile,
timeToFinish,
errors: errorExplanations,
fatalErrorEncountered: errorExplanations.some(isFatalError),
diff --git a/packages/lambda/src/functions/helpers/create-post-render-data.ts b/packages/lambda/src/functions/helpers/create-post-render-data.ts
new file mode 100644
index 0000000000..ae4425731c
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/create-post-render-data.ts
@@ -0,0 +1,110 @@
+import {AwsRegion} from '../..';
+import {calculatePrice} from '../../pricing/calculate-price';
+import {
+ lambdaTimingsPrefix,
+ outName,
+ PostRenderData,
+ RenderMetadata,
+ rendersPrefix,
+} from '../../shared/constants';
+import {parseLambdaTimingsKey} from '../../shared/parse-lambda-timings-key';
+import {findOutputFileInBucket} from './find-output-file-in-bucket';
+import {inspectErrors} from './inspect-errors';
+import {lambdaLs} from './io';
+
+const OVERHEAD_TIME_PER_LAMBDA = 100;
+
+export const createPostRenderData = async ({
+ renderId,
+ bucketName,
+ expectedBucketOwner,
+ region,
+ memorySize,
+ renderMetadata,
+}: {
+ renderId: string;
+ bucketName: string;
+ expectedBucketOwner: string;
+ region: AwsRegion;
+ memorySize: number;
+ renderMetadata: RenderMetadata;
+}) => {
+ const contents = await lambdaLs({
+ bucketName,
+ prefix: rendersPrefix(renderId),
+ expectedBucketOwner,
+ region,
+ });
+
+ const initializedKeys = contents.filter((c) =>
+ c.Key?.startsWith(lambdaTimingsPrefix(renderId))
+ );
+
+ const parsedTimings = initializedKeys.map(({Key}) =>
+ parseLambdaTimingsKey(Key as string)
+ );
+
+ const times = parsedTimings
+ .map((p) => p.end - p.start + OVERHEAD_TIME_PER_LAMBDA)
+ .reduce((a, b) => a + b);
+
+ const cost = calculatePrice({
+ durationInMiliseconds: times,
+ memorySize,
+ region,
+ });
+
+ const output =
+ contents.find((c) =>
+ c.Key?.includes(outName(renderId, renderMetadata.codec))
+ ) ?? null;
+
+ if (!output) {
+ throw new Error(
+ 'Could not find output file. Not yet ready to call createPostRenderData()'
+ );
+ }
+
+ const outputFile = findOutputFileInBucket({
+ output,
+ bucketName,
+ renderId,
+ renderMetadata,
+ });
+
+ if (!outputFile) {
+ throw new Error('Cannot wrap up without an output file in the S3 bucket.');
+ }
+
+ const errorExplanations = await inspectErrors({
+ contents,
+ renderId,
+ bucket: bucketName,
+ region,
+ });
+
+ const endTime = Date.now();
+ const startTime = renderMetadata.startedDate;
+ const timeToFinish = endTime - startTime;
+
+ const data: PostRenderData = {
+ cost: {
+ currency: 'USD',
+ disclaimer:
+ 'Estimated cost for lambda invocations only. Does not include cost for S3 storage and data transfer.',
+ estimatedCost: cost,
+ estimatedDisplayCost: new Intl.NumberFormat('en-US', {
+ currency: 'USD',
+ currencyDisplay: 'narrowSymbol',
+ }).format(cost),
+ },
+ outputFile,
+ timeToFinish,
+ errors: errorExplanations,
+ startTime: renderMetadata.startedDate,
+ endTime,
+ outputSize: output.Size as number,
+ };
+
+ return data;
+};
diff --git a/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts b/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts
new file mode 100644
index 0000000000..6b44a7caef
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts
@@ -0,0 +1,27 @@
+import {_Object} from '@aws-sdk/client-s3';
+import {AwsRegion} from '../..';
+import {outName, RenderMetadata} from '../../shared/constants';
+
+export const findOutputFileInBucket = ({
+ output,
+ renderMetadata,
+ bucketName,
+ renderId,
+}: {
+ output: _Object | null;
+ renderMetadata: RenderMetadata | null;
+ bucketName: string;
+ renderId: string;
+}) => {
+ if (!output) {
+ return null;
+ }
+
+ if (!renderMetadata) {
+ throw new Error('unexpectedly did not get renderMetadata');
+ }
+
+ return `https://s3.${
+ process.env.AWS_REGION as AwsRegion
+ }.amazonaws.com/${bucketName}/${outName(renderId, renderMetadata.codec)}`;
+};
diff --git a/packages/lambda/src/functions/helpers/get-encoding-metadata.ts b/packages/lambda/src/functions/helpers/get-encoding-metadata.ts
new file mode 100644
index 0000000000..622faa17f5
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/get-encoding-metadata.ts
@@ -0,0 +1,37 @@
+import {EncodingProgress, encodingProgressKey} from '../../defaults';
+import {AwsRegion} from '../../pricing/aws-regions';
+import {streamToString} from '../../shared/stream-to-string';
+import {lambdaReadFile} from './io';
+
+export const getEncodingMetadata = async ({
+ exists,
+ bucketName,
+ renderId,
+ region,
+}: {
+ exists: boolean;
+ bucketName: string;
+ renderId: string;
+ region: AwsRegion;
+}): Promise<EncodingProgress | null> => {
+ if (!exists) {
+ return null;
+ }
+
+ const Body = await lambdaReadFile({
+ bucketName,
+ key: encodingProgressKey(renderId),
+ region,
+ });
+
+ try {
+ const encodingProgress = JSON.parse(
+ await streamToString(Body)
+ ) as EncodingProgress;
+
+ return encodingProgress;
+ } catch (err) {
+ // The file may not yet have been fully written
+ return null;
+ }
+};
diff --git a/packages/lambda/src/functions/helpers/get-render-metadata.ts b/packages/lambda/src/functions/helpers/get-render-metadata.ts
new file mode 100644
index 0000000000..562a730568
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/get-render-metadata.ts
@@ -0,0 +1,32 @@
+import {AwsRegion} from '../../pricing/aws-regions';
+import {RenderMetadata, renderMetadataKey} from '../../shared/constants';
+import {streamToString} from '../../shared/stream-to-string';
+import {lambdaReadFile} from './io';
+
+export const getRenderMetadata = async ({
+ exists,
+ bucketName,
+ renderId,
+ region,
+}: {
+ exists: boolean;
+ bucketName: string;
+ renderId: string;
+ region: AwsRegion;
+}) => {
+ if (!exists) {
+ return null;
+ }
+
+ const Body = await lambdaReadFile({
+ bucketName,
+ key: renderMetadataKey(renderId),
+ region,
+ });
+
+ const renderMetadataResponse = JSON.parse(
+ await streamToString(Body)
+ ) as RenderMetadata;
+
+ return renderMetadataResponse;
+};
diff --git a/packages/lambda/src/functions/helpers/get-time-to-finish.ts b/packages/lambda/src/functions/helpers/get-time-to-finish.ts
new file mode 100644
index 0000000000..145a3362f0
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/get-time-to-finish.ts
@@ -0,0 +1,24 @@
+import {_Object} from '@aws-sdk/client-s3';
+import {RenderMetadata} from '../../defaults';
+
+export const getTimeToFinish = ({
+ renderMetadata,
+ output,
+}: {
+ renderMetadata: RenderMetadata | null;
+ output: _Object | null;
+}) => {
+ if (!output) {
+ return null;
+ }
+
+ if (!output.LastModified) {
+ return null;
+ }
+
+ if (!renderMetadata) {
+ return null;
+ }
+
+ return output.LastModified.getTime() - renderMetadata.startedDate;
+};
diff --git a/packages/lambda/src/functions/helpers/inspect-errors.ts b/packages/lambda/src/functions/helpers/inspect-errors.ts
index c9d7d9ed6b..bb4ae931d8 100644
--- a/packages/lambda/src/functions/helpers/inspect-errors.ts
+++ b/packages/lambda/src/functions/helpers/inspect-errors.ts
@@ -1,4 +1,7 @@
+import {_Object} from '@aws-sdk/client-s3';
+import {Internals} from 'remotion';
import {AwsRegion} from '../../pricing/aws-regions';
+import {getErrorKeyPrefix} from '../../shared/constants';
import {streamToString} from '../../shared/stream-to-string';
import {lambdaReadFile} from './io';
import {errorIsOutOfSpaceError} from './is-enosp-err';
@@ -29,14 +32,21 @@ const getExplanation = (stack: string) => {
};
export const inspectErrors = async ({
- errs,
+ contents,
bucket,
region,
+ renderId,
}: {
- errs: string[];
+ contents: _Object[];
bucket: string;
region: AwsRegion;
+ renderId: string;
}): Promise<EnhancedErrorInfo[]> => {
+ const errs = contents
+ .filter((c) => c.Key?.startsWith(getErrorKeyPrefix(renderId)))
+ .map((c) => c.Key)
+ .filter(Internals.truthy);
+
if (errs.length === 0) {
return [];
}
diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.ts
index c356ed6c59..5fc713ccb0 100644
--- a/packages/lambda/src/shared/constants.ts
+++ b/packages/lambda/src/shared/constants.ts
@@ -5,6 +5,7 @@ import {
ProResProfile,
VideoConfig,
} from 'remotion';
+import {EnhancedErrorInfo} from '../functions/helpers/write-lambda-error';
import {AwsRegion} from '../pricing/aws-regions';
import {getFileExtensionFromCodec} from './get-file-extension-from-codec';
@@ -186,3 +187,18 @@ export type RenderMetadata = {
export type LambdaVersions = '2021-07-05' | '2021-07-02' | '2021-06-23' | 'n/a';
export const CURRENT_VERSION: LambdaVersions = '2021-07-05';
+
+export type PostRenderData = {
+ cost: {
+ estimatedCost: number;
+ estimatedDisplayCost: string;
+ currency: string;
+ disclaimer: string;
+ };
+ outputFile: string;
+ outputSize: number;
+ timeToFinish: number;
+ errors: EnhancedErrorInfo[];
+ startTime: number;
+ endTime: number;
+};