🎥 Make videos programmatically with React
lfg
Jonny Burgerf5bd68863a5c
diff --git a/packages/lambda/.eslintrc b/packages/lambda/.eslintrcindex 92b10568b4..a31afcb8e8 100644--- a/packages/lambda/.eslintrc+++ b/packages/lambda/.eslintrc@@ -4,7 +4,15 @@"project": "./tsconfig.json"},"rules": {- "no-console": "error",+ "no-console": "off","ts-exports/unused-exports": "off"- }+ },+ "overrides": [+ {+ "files": "./src/cli/**",+ "rules": {+ "no-console": "error"+ }+ }+ ]}diff --git a/packages/lambda/src/api/bundle-lambda.ts b/packages/lambda/src/api/bundle-lambda.tsindex 287a623674..339305d961 100644--- a/packages/lambda/src/api/bundle-lambda.ts+++ b/packages/lambda/src/api/bundle-lambda.ts@@ -4,8 +4,8 @@ import {tmpDir} from '../shared/tmpdir';import esbuild = require('esbuild');import zl = require('zip-lib');-export const bundleLambda = async (type: 'render') => {- const outdir = path.join(__dirname, '..', `build-${type}`);+export const bundleLambda = async () => {+ const outdir = path.join(__dirname, '..', `build-render`);fs.mkdirSync(outdir, {recursive: true,});@@ -19,13 +19,18 @@ export const bundleLambda = async (type: 'render') => {await esbuild.build({platform: 'node',- target: 'node12',+ target: 'node14',bundle: true,outfile,entryPoints: [template],+ banner: {+ js: `+global.+ `,+ },});- const out = path.join(tmpDir('remotion-fn'), `function-${type}.zip`);+ const out = path.join(tmpDir('remotion-fn'), `function-render.zip`);await zl.archiveFolder(outdir, out);return out;};diff --git a/packages/lambda/src/api/bundle-remotion.ts b/packages/lambda/src/api/bundle-remotion.tsindex cdcda85f3a..5e2e7a20d8 100644--- a/packages/lambda/src/api/bundle-remotion.ts+++ b/packages/lambda/src/api/bundle-remotion.ts@@ -1,8 +1,5 @@import {bundle} from '@remotion/bundler';-// TODO: not here-export const BINARY_NAME = 'remotion-lambda';-// TODO: Necessary? Noexport const bundleRemotion = ({entryFile,diff --git a/packages/lambda/src/api/deploy-lambda.ts b/packages/lambda/src/api/deploy-lambda.tsindex a5c7c1a468..be77a88836 100644--- a/packages/lambda/src/api/deploy-lambda.ts+++ b/packages/lambda/src/api/deploy-lambda.ts@@ -1,10 +1,13 @@-import {GetUserCommand} from '@aws-sdk/client-iam';import {CreateFunctionCommand} from '@aws-sdk/client-lambda';import {readFileSync} from 'fs';import {AwsRegion} from '../pricing/aws-regions';-import {getIamClient, getLambdaClient} from '../shared/aws-clients';+import {getLambdaClient} from '../shared/aws-clients';import {RENDER_FN_PREFIX} from '../shared/constants';+import {getAccountId} from '../shared/get-account-id';import {randomHash} from '../shared/random-hash';+import {validateAwsRegion} from '../shared/validate-aws-region';+import {validateMemorySize} from '../shared/validate-memory-size';+import {validateTimeout} from '../shared/validate-timeout';import {bundleLambda} from './bundle-lambda';export const deployLambda = async (options: {@@ -13,20 +16,16 @@ export const deployLambda = async (options: {timeoutInSeconds: number;memorySize: number;}) => {- // TODO: Validate memory size- // TODO: Validate parameters and enforce timeout below 900 seconds.+ validateMemorySize(options.memorySize);+ validateTimeout(options.timeoutInSeconds);+ validateAwsRegion(options.region);+const fnNameRender = RENDER_FN_PREFIX + randomHash();- const [renderOut, user] = await Promise.all([- bundleLambda('render'),- getIamClient(options.region).send(new GetUserCommand({})),+ const [renderOut, accountId] = await Promise.all([+ bundleLambda(),+ getAccountId({region: options.region}),]);- const accountId = user.User?.Arn?.match(/aws:iam::([0-9]+)/);-- if (!accountId) {- throw new Error('Cannot get account ID');- }-const created = await getLambdaClient(options.region).send(new CreateFunctionCommand({Code: {@@ -44,8 +43,6 @@ export const deployLambda = async (options: {}));- console.log('lambdas created');-if (!created.FunctionName) {throw new Error('Lambda was created but has no name');}diff --git a/packages/lambda/src/cli/args.ts b/packages/lambda/src/cli/args.tsindex d789c29620..122503046a 100644--- a/packages/lambda/src/cli/args.ts+++ b/packages/lambda/src/cli/args.ts@@ -4,6 +4,8 @@ import {AwsRegion} from '../pricing/aws-regions';type LambdaCommandLineOptions = {help: boolean;region: AwsRegion;+ memory: number;+ timeout: number;};export const parsedLambdaCli = minimist<LambdaCommandLineOptions>(diff --git a/packages/lambda/src/cli/cleanup.ts b/packages/lambda/src/cli/cleanup.tsindex deb2abcb14..64d8517d3a 100644--- a/packages/lambda/src/cli/cleanup.ts+++ b/packages/lambda/src/cli/cleanup.ts@@ -1,12 +1,12 @@import {LambdaClient} from '@aws-sdk/client-lambda';import {CliInternals} from '@remotion/cli';-import {BINARY_NAME} from '../api/bundle-remotion';import {getRemotionS3Buckets} from '../api/get-buckets';import {cleanupLambdas, getRemotionLambdas} from '../cleanup/cleanup-lambdas';import {cleanUpBuckets} from '../cleanup/s3-buckets';import {AwsRegion} from '../pricing/aws-regions';import {getLambdaClient} from '../shared/aws-clients';import {chunk} from '../shared/chunk';+import {BINARY_NAME} from '../shared/constants';import {getAwsRegion} from './get-aws-region';import {Log} from './log';diff --git a/packages/lambda/src/cli/deploy.ts b/packages/lambda/src/cli/deploy.tsindex 88689c4bcb..423bc67c01 100644--- a/packages/lambda/src/cli/deploy.ts+++ b/packages/lambda/src/cli/deploy.ts@@ -1,21 +1,21 @@import {deployLambda} from '../api/deploy-lambda';import {ensureLambdaBinaries} from '../api/ensure-lambda-binaries';+import {DEFAULT_MEMORY_SIZE, DEFAULT_TIMEOUT} from '../shared/constants';+import {parsedLambdaCli} from './args';import {getAwsRegion} from './get-aws-region';import {Log} from './log';export const DEPLOY_COMMAND = 'deploy';export const deployCommand = async () => {- // TODO: Unhardcode timeout- const TIMEOUT_HARDCODED = 120;- // TODO: Unhardcode memory- const MEMORY_SIZE = 1024;+ const timeoutInSeconds = parsedLambdaCli.timeout ?? DEFAULT_TIMEOUT;+ const memorySize = parsedLambdaCli.memory ?? DEFAULT_MEMORY_SIZE;const {layerArn} = await ensureLambdaBinaries(getAwsRegion());const {functionName} = await deployLambda({region: getAwsRegion(),- timeoutInSeconds: TIMEOUT_HARDCODED,+ timeoutInSeconds,layerArn,- memorySize: MEMORY_SIZE,+ memorySize,});Log.info(`Deployed to ${functionName}`);};diff --git a/packages/lambda/src/cli/get-aws-region.ts b/packages/lambda/src/cli/get-aws-region.tsindex fc66ae90a2..f9416c8f1c 100644--- a/packages/lambda/src/cli/get-aws-region.ts+++ b/packages/lambda/src/cli/get-aws-region.ts@@ -1,19 +1,10 @@-import {AwsRegion, AWS_REGIONS} from '../pricing/aws-regions';+import {AwsRegion} from '../pricing/aws-regions';import {isInLambda} from '../shared/tmpdir';+import {validateAwsRegion} from '../shared/validate-aws-region';import {parsedLambdaCli} from './args';const DEFAULT_REGION: AwsRegion = 'us-east-1';-function validateAwsRegion(region: unknown): asserts region is AwsRegion {- if (!AWS_REGIONS.includes(region as AwsRegion)) {- throw new TypeError(- `${region} is not a valid AWS region. Must be one of: ${AWS_REGIONS.join(- ', '- )}`- );- }-}-export const getAwsRegion = (): AwsRegion => {if (isInLambda) {throw new Error('Should not call getAwsRegion() if in lambda');diff --git a/packages/lambda/src/cli/help.ts b/packages/lambda/src/cli/help.tsindex 88f5c2ca54..d35565033e 100644--- a/packages/lambda/src/cli/help.ts+++ b/packages/lambda/src/cli/help.ts@@ -1,5 +1,5 @@import chalk from 'chalk';-import {BINARY_NAME} from '../api/bundle-remotion';+import {BINARY_NAME} from '../shared/constants';import {CLEANUP_COMMAND} from './cleanup';import {Log} from './log';import {RENDER_COMMAND} from './render';diff --git a/packages/lambda/src/cli/policies.ts b/packages/lambda/src/cli/policies.tsindex 36b56a1bf8..22a7da9014 100644--- a/packages/lambda/src/cli/policies.ts+++ b/packages/lambda/src/cli/policies.ts@@ -1,10 +1,10 @@import {CliInternals} from '@remotion/cli';-import {BINARY_NAME} from '../api/bundle-remotion';import {simulatePermissions} from '../api/iam-validation/simulate';import {getRolePolicy,getUserPolicy,} from '../api/iam-validation/suggested-policy';+import {BINARY_NAME} from '../shared/constants';import {getAwsRegion} from './get-aws-region';import {Log} from './log';diff --git a/packages/lambda/src/cli/render.ts b/packages/lambda/src/cli/render.tsindex 49c4793e0d..8549f97cd0 100644--- a/packages/lambda/src/cli/render.ts+++ b/packages/lambda/src/cli/render.ts@@ -1,8 +1,8 @@import {CliInternals} from '@remotion/cli';-import {BINARY_NAME} from '../api/bundle-remotion';import {getDeployedLambdas} from '../api/get-deployed-lambdas';import {getRenderProgress} from '../api/get-render-progress';import {renderVideoOnLambda} from '../api/render-video-on-lambda';+import {BINARY_NAME} from '../shared/constants';import {sleep} from '../shared/sleep';import {parsedLambdaCli} from './args';import {CLEANUP_COMMAND, CLEANUP_LAMBDAS_SUBCOMMAND} from './cleanup';@@ -82,9 +82,9 @@ export const renderCommand = async () => {renderId: res.renderId,region: getAwsRegion(),});- console.log(status);+ Log.info(status);if (status.done) {- console.log('Done! ' + res.bucketName);+ Log.info('Done! ' + res.bucketName);process.exit(0);}}diff --git a/packages/lambda/src/cli/upload.ts b/packages/lambda/src/cli/upload.tsindex f11b0cdd8c..cb0fa382c2 100644--- a/packages/lambda/src/cli/upload.ts+++ b/packages/lambda/src/cli/upload.ts@@ -1,9 +1,9 @@import {CliInternals} from '@remotion/cli';import {existsSync, lstatSync} from 'fs';import path from 'path';-import {BINARY_NAME} from '../api/bundle-remotion';import {deployProject} from '../api/deploy-project';import {getOrCreateBucket} from '../api/get-or-create-bucket';+import {BINARY_NAME} from '../shared/constants';import {parsedLambdaCli} from './args';import {getAwsRegion} from './get-aws-region';import {diff --git a/packages/lambda/src/functions/get-progress.ts b/packages/lambda/src/functions/get-progress.tsindex e510990ab3..dfe9323fe5 100644--- a/packages/lambda/src/functions/get-progress.ts+++ b/packages/lambda/src/functions/get-progress.ts@@ -11,7 +11,6 @@ import {lambdaInitializedKey,LambdaPayload,LambdaRoutines,- MEMORY_SIZE,outName,RenderMetadata,renderMetadataKey,@@ -221,8 +220,8 @@ export const progressHandler = async (lambdaParams: LambdaPayload) => {(calculatePrice({region: getCurrentRegion(),- durationMs: elapsedTime,- memory: MEMORY_SIZE,+ durationInMiliseconds: elapsedTime,+ memorySize: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),}) * (renderMetadata?.estimatedLambdaInvokations ?? 0)).toPrecision(5));@@ -266,7 +265,7 @@ export const progressHandler = async (lambdaParams: LambdaPayload) => {// TODO: Only fetch optimization if actually shownoptimizationForNextRender: optimization,timeToFinish,- // errors,+ errors,errorExplanations,currentTime: Date.now(),bucketSize,diff --git a/packages/lambda/src/pricing/calculate-price.ts b/packages/lambda/src/pricing/calculate-price.tsindex fffa6a35ed..53d3f701da 100644--- a/packages/lambda/src/pricing/calculate-price.ts+++ b/packages/lambda/src/pricing/calculate-price.ts@@ -1,18 +1,46 @@+import {validateAwsRegion} from '../shared/validate-aws-region';+import {validateMemorySize} from '../shared/validate-memory-size';import {AwsRegion} from './aws-regions';import {pricing} from './price-per-1-s';export const calculatePrice = ({region,- durationMs,- memory,+ durationInMiliseconds,+ memorySize: memory,}: {region: AwsRegion;- durationMs: number;- memory: number;+ durationInMiliseconds: number;+ memorySize: number;}) => {+ validateMemorySize(memory);+ validateAwsRegion(region);+ if (typeof durationInMiliseconds !== 'number') {+ throw new TypeError(+ `Parameter 'durationInMiliseconds' must be a number but got ${typeof durationInMiliseconds}`+ );+ }++ if (Number.isNaN(durationInMiliseconds)) {+ throw new TypeError(+ `Parameter 'durationInMiliseconds' must not be NaN but it is.`+ );+ }++ if (!Number.isFinite(durationInMiliseconds)) {+ throw new TypeError(+ `Parameter 'durationInMiliseconds' must be finite but it is ${durationInMiliseconds}`+ );+ }++ if (durationInMiliseconds < 0) {+ throw new TypeError(+ `Parameter 'durationInMiliseconds' must be over 0 but it is ${durationInMiliseconds}.`+ );+ }+const timeCostDollars =Number(pricing[region]['Lambda Duration'].price) *- ((memory * durationMs) / 1000 / 1024);+ ((memory * durationInMiliseconds) / 1000 / 1024);const invocationCost = Number(pricing[region]['Lambda Requests'].price);diff --git a/packages/lambda/src/run.ts b/packages/lambda/src/run.tsindex 36bc78c1b8..d5d75ea69d 100644--- a/packages/lambda/src/run.ts+++ b/packages/lambda/src/run.ts@@ -100,7 +100,7 @@ CliInternals.xns(async () => {},region: 'eu-central-1',});- console.log(bucketUrl);+ Log.info(bucketUrl);for (let i = 0; i < 3000; i++) {await sleep(1000);const status = await getRenderProgress({diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.tsindex f251b0f870..2678d13c74 100644--- a/packages/lambda/src/shared/constants.ts+++ b/packages/lambda/src/shared/constants.ts@@ -2,7 +2,16 @@ import {Codec, ImageFormat, PixelFormat, ProResProfile} from 'remotion';import {AwsRegion} from '../pricing/aws-regions';import {getFileExtensionFromCodec} from './get-file-extension-from-codec';-export const MEMORY_SIZE = 2048;+export const MIN_MEMORY = 512;+export const MAX_MEMORY = 10240;+export const DEFAULT_MEMORY_SIZE = 1024;++export const DEFAULT_TIMEOUT = 120;+export const MIN_TIMEOUT = 15;+export const MAX_TIMEOUT = 900;++export const BINARY_NAME = 'remotion-lambda';+// TODO: Rename other buckets in Jonnys accoudn firstexport const REMOTION_BUCKET_PREFIX = 'remotionlambda-';export const RENDER_FN_PREFIX = 'remotion-render-';diff --git a/packages/lambda/src/shared/get-account-id.ts b/packages/lambda/src/shared/get-account-id.tsnew file mode 100644index 0000000000..9fce46ebc2--- /dev/null+++ b/packages/lambda/src/shared/get-account-id.ts@@ -0,0 +1,17 @@+import {GetUserCommand} from '@aws-sdk/client-iam';+import {AwsRegion} from '../pricing/aws-regions';+import {getIamClient} from './aws-clients';+import {validateAwsRegion} from './validate-aws-region';++export const getAccountId = async (options: {region: AwsRegion}) => {+ validateAwsRegion(options.region);++ const user = await getIamClient(options.region).send(new GetUserCommand({}));+ const accountId = user.User?.Arn?.match(/aws:iam::([0-9]+)/);++ if (!accountId) {+ throw new Error('Cannot get account ID');+ }++ return accountId;+};diff --git a/packages/lambda/src/shared/validate-aws-region.ts b/packages/lambda/src/shared/validate-aws-region.tsnew file mode 100644index 0000000000..54fca5d121--- /dev/null+++ b/packages/lambda/src/shared/validate-aws-region.ts@@ -0,0 +1,13 @@+import {AwsRegion, AWS_REGIONS} from '../pricing/aws-regions';++export function validateAwsRegion(+ region: unknown+): asserts region is AwsRegion {+ if (!AWS_REGIONS.includes(region as AwsRegion)) {+ throw new TypeError(+ `${region} is not a valid AWS region. Must be one of: ${AWS_REGIONS.join(+ ', '+ )}`+ );+ }+}diff --git a/packages/lambda/src/shared/validate-memory-size.ts b/packages/lambda/src/shared/validate-memory-size.tsnew file mode 100644index 0000000000..7c217e7afe--- /dev/null+++ b/packages/lambda/src/shared/validate-memory-size.ts@@ -0,0 +1,31 @@+import {MAX_MEMORY, MIN_MEMORY} from './constants';++export const validateMemorySize = (memorySize: unknown) => {+ if (typeof memorySize !== 'number') {+ throw new TypeError(+ `parameter 'memorySize' must be a number, got a ${typeof memorySize}`+ );+ }++ if (Number.isNaN(memorySize)) {+ throw new TypeError(`parameter 'memorySize' must not be NaN, but is`);+ }++ if (!Number.isFinite(memorySize)) {+ throw new TypeError(+ `parameter 'memorySize' must be finite, but is ${memorySize}`+ );+ }++ if (memorySize < MIN_MEMORY || memorySize > MAX_MEMORY) {+ throw new TypeError(+ `parameter 'memorySize' must be between ${MIN_MEMORY} and ${MAX_MEMORY}, but got ${memorySize}`+ );+ }++ if (memorySize % 1 !== 0) {+ throw new TypeError(+ `parameter 'memorySize' must be an integer but got ${memorySize}`+ );+ }+};diff --git a/packages/lambda/src/shared/validate-timeout.ts b/packages/lambda/src/shared/validate-timeout.tsnew file mode 100644index 0000000000..58e86dbe53--- /dev/null+++ b/packages/lambda/src/shared/validate-timeout.ts@@ -0,0 +1,31 @@+import {MAX_TIMEOUT, MIN_TIMEOUT} from './constants';++export const validateTimeout = (timeoutInSeconds: unknown) => {+ if (typeof timeoutInSeconds !== 'number') {+ throw new TypeError(+ `parameter 'timeoutInSeconds' must be a number, but got a ${typeof timeoutInSeconds}`+ );+ }++ if (Number.isNaN(timeoutInSeconds)) {+ throw new TypeError(`parameter 'timeoutInSeconds' must not be NaN, but is`);+ }++ if (!Number.isFinite(timeoutInSeconds)) {+ throw new TypeError(+ `parameter 'timeoutInSeconds' must be finite, but is ${timeoutInSeconds}`+ );+ }++ if (timeoutInSeconds < MIN_TIMEOUT || timeoutInSeconds > MAX_TIMEOUT) {+ throw new TypeError(+ `parameter 'timeoutInSeconds' must be between ${MIN_TIMEOUT} and ${MAX_TIMEOUT}, but got ${timeoutInSeconds}`+ );+ }++ if (timeoutInSeconds % 1 !== 0) {+ throw new TypeError(+ `parameter 'timeoutInSeconds' must be an integer but got ${timeoutInSeconds}`+ );+ }+};diff --git a/packages/lambda/src/test/pricing.test.ts b/packages/lambda/src/test/pricing.test.tsindex 67a43a18a5..4c94aaf578 100644--- a/packages/lambda/src/test/pricing.test.ts+++ b/packages/lambda/src/test/pricing.test.ts@@ -4,15 +4,15 @@ test('Should calculate costs accurately', () => {expect(calculatePrice({region: 'us-east-1',- durationMs: 20000,- memory: 2048,+ durationInMiliseconds: 20000,+ memorySize: 2048,})).toEqual(0.00067);expect(calculatePrice({region: 'us-east-1',- durationMs: 20000,- memory: 1024,+ durationInMiliseconds: 20000,+ memorySize: 1024,})).toEqual(0.00033);});