🎥 Make videos programmatically with React
lfg to the moon
Jonny Burger90a0e9cdea84
diff --git a/packages/lambda/src/functions/fire.ts b/packages/lambda/src/functions/fire.tsindex 5af1e3c641..9e7e444284 100644--- a/packages/lambda/src/functions/fire.ts+++ b/packages/lambda/src/functions/fire.ts@@ -1,7 +1,7 @@import {InvokeCommand} from '@aws-sdk/client-lambda';import {getLambdaClient} from '../shared/aws-clients';import {LambdaPayload, LambdaRoutines} from '../shared/constants';-import {getCurrentRegion} from './helpers/get-current-region';+import {getCurrentRegionInFunction} from './helpers/get-current-region';import {timer} from './helpers/timer';export const fireHandler = async (params: LambdaPayload) => {@@ -12,7 +12,7 @@ export const fireHandler = async (params: LambdaPayload) => {await Promise.all(params.payloads.map(async (payload, index) => {const callingLambdaTimer = timer('Calling lambda ' + index);- await getLambdaClient(getCurrentRegion()).send(+ await getLambdaClient(getCurrentRegionInFunction()).send(new InvokeCommand({FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,// @ts-expect-errordiff --git a/packages/lambda/src/functions/helpers/calculate-price-from-bucket.ts b/packages/lambda/src/functions/helpers/calculate-price-from-bucket.tsindex 5656e43581..9fded2f68f 100644--- a/packages/lambda/src/functions/helpers/calculate-price-from-bucket.ts+++ b/packages/lambda/src/functions/helpers/calculate-price-from-bucket.ts@@ -3,7 +3,7 @@ import {calculatePrice} from '../../pricing/calculate-price';import {lambdaTimingsPrefix, RenderMetadata} from '../../shared/constants';import {parseLambdaTimingsKey} from '../../shared/parse-lambda-timings-key';import {findOutputFileInBucket} from './find-output-file-in-bucket';-import {getCurrentRegion} from './get-current-region';+import {getCurrentRegionInFunction} from './get-current-region';import {getTimeToFinish} from './get-time-to-finish';// TODO: Should differentiate between finished and in progress@@ -62,7 +62,7 @@ export const calculatePriceFromBucket = ({const accruedSoFar = Number(calculatePrice({- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),durationInMiliseconds: totalEncodingTimings + timeElapsedOfUnfinished,memorySize,}).toPrecision(5)diff --git a/packages/lambda/src/functions/helpers/create-post-render-data.ts b/packages/lambda/src/functions/helpers/create-post-render-data.tsindex 48d9c0b708..741c3e3dfc 100644--- a/packages/lambda/src/functions/helpers/create-post-render-data.ts+++ b/packages/lambda/src/functions/helpers/create-post-render-data.ts@@ -1,16 +1,15 @@+import {_Object} from '@aws-sdk/client-s3';import {AwsRegion} from '../..';import {calculatePrice} from '../../pricing/calculate-price';import {lambdaTimingsPrefix,PostRenderData,RenderMetadata,- rendersPrefix,} from '../../shared/constants';import {parseLambdaTimingsKey} from '../../shared/parse-lambda-timings-key';import {findOutputFileInBucket} from './find-output-file-in-bucket';import {getFilesToDelete} from './get-files-to-delete';import {inspectErrors} from './inspect-errors';-import {lambdaLs} from './io';const OVERHEAD_TIME_PER_LAMBDA = 100;@@ -21,6 +20,7 @@ export const createPostRenderData = async ({region,memorySize,renderMetadata,+ contents,}: {renderId: string;bucketName: string;@@ -28,14 +28,8 @@ export const createPostRenderData = async ({region: AwsRegion;memorySize: number;renderMetadata: RenderMetadata;+ contents: _Object[];}) => {- const contents = await lambdaLs({- bucketName,- prefix: rendersPrefix(renderId),- expectedBucketOwner,- region,- });-const initializedKeys = contents.filter((c) =>c.Key?.startsWith(lambdaTimingsPrefix(renderId)));diff --git a/packages/lambda/src/functions/helpers/delete-chunks.ts b/packages/lambda/src/functions/helpers/delete-chunks.tsindex ff0497e2db..c2ddd1276f 100644--- a/packages/lambda/src/functions/helpers/delete-chunks.ts+++ b/packages/lambda/src/functions/helpers/delete-chunks.ts@@ -1,3 +1,4 @@+import {_Object} from '@aws-sdk/client-s3';import {AwsRegion} from '../..';import {cleanItems} from '../../api/clean-items';import {getFilesToDelete} from './get-files-to-delete';@@ -7,11 +8,13 @@ export const deleteChunks = async ({chunkCount,bucket,region,+ contents,}: {renderId: string;chunkCount: number;bucket: string;region: AwsRegion;+ contents: _Object[];}) => {const toDelete = getFilesToDelete({chunkCount,@@ -21,7 +24,18 @@ export const deleteChunks = async ({await cleanItems({bucket,region,- list: toDelete,+ list: toDelete.map((item) => {+ if (item.type === 'exact') {+ return item.name;+ }++ if (item.type === 'prefix') {+ return contents.find((c) => c.Key?.startsWith(item.name))+ ?.Key as string;+ }++ throw new Error('unexpected in deleteChunks()');+ }),onAfterItemDeleted: () => undefined,onBeforeItemDeleted: () => undefined,});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.tsindex 1269c43370..22ba9f0623 100644--- a/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts+++ b/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts@@ -1,6 +1,6 @@import {_Object} from '@aws-sdk/client-s3';-import {getAwsRegion} from '../../cli/get-aws-region';import {outName, RenderMetadata} from '../../shared/constants';+import {getCurrentRegionInFunction} from './get-current-region';export const findOutputFileInBucket = ({contents,@@ -34,7 +34,7 @@ export const findOutputFileInBucket = ({return {lastModified: output.LastModified?.getTime() as number,size: output.Size as number,- url: `https://s3.${getAwsRegion()}.amazonaws.com/${bucketName}/${outName(+ url: `https://s3.${getCurrentRegionInFunction()}.amazonaws.com/${bucketName}/${outName(renderId,renderMetadata.codec)}`,diff --git a/packages/lambda/src/functions/helpers/get-cleanup-progress.ts b/packages/lambda/src/functions/helpers/get-cleanup-progress.tsindex 30b8456ba0..2bf11b23f5 100644--- a/packages/lambda/src/functions/helpers/get-cleanup-progress.ts+++ b/packages/lambda/src/functions/helpers/get-cleanup-progress.ts@@ -18,9 +18,19 @@ export const getCleanupProgress = ({}const filesToDelete = getFilesToDelete({chunkCount, renderId});- const filesStillThere = contents.filter((c) =>- filesToDelete.includes(c.Key as string)- );+ const filesStillThere = contents.filter((c) => {+ return filesToDelete.find((f) => {+ if (f.type === 'exact') {+ return f.name === c.Key;+ }++ if (f.type === 'prefix') {+ return c.Key?.startsWith(f.name);+ }++ throw new Error('Unexpected in getCleanupProgress');+ });+ });const filesDeleted = filesToDelete.length - filesStillThere.length;diff --git a/packages/lambda/src/functions/helpers/get-current-region.ts b/packages/lambda/src/functions/helpers/get-current-region.tsindex 8e375a77b7..f58cd02af6 100644--- a/packages/lambda/src/functions/helpers/get-current-region.ts+++ b/packages/lambda/src/functions/helpers/get-current-region.ts@@ -1,7 +1,7 @@import {AwsRegion} from '../../pricing/aws-regions';import {isInLambda} from '../../shared/tmpdir';-export const getCurrentRegion = () => {+export const getCurrentRegionInFunction = () => {if (!isInLambda) {throw new Error('Should not call getCurrentRegion() if not inside a lambda function'diff --git a/packages/lambda/src/functions/helpers/get-files-to-delete.ts b/packages/lambda/src/functions/helpers/get-files-to-delete.tsindex ee1e89a814..da571fa8c9 100644--- a/packages/lambda/src/functions/helpers/get-files-to-delete.ts+++ b/packages/lambda/src/functions/helpers/get-files-to-delete.ts@@ -2,6 +2,7 @@ import {chunkKeyForIndex,encodingProgressKey,lambdaInitializedKey,+ lambdaTimingsPrefixForChunk,} from '../../shared/constants';export const getFilesToDelete = ({@@ -10,7 +11,10 @@ export const getFilesToDelete = ({}: {chunkCount: number;renderId: string;-}) => {+}): {+ name: string;+ type: 'exact' | 'prefix';+}[] => {const initialized = new Array(chunkCount).fill(true).map((x, i) =>lambdaInitializedKey({chunk: i,@@ -23,5 +27,31 @@ export const getFilesToDelete = ({renderId,}));- return [...initialized, ...chunks, encodingProgressKey(renderId)];+ const lambdaTimings = new Array(chunkCount)+ .fill(true)+ .map((x, i) => lambdaTimingsPrefixForChunk(renderId, i));+ return [+ ...initialized.map((i) => {+ return {+ name: i,+ type: 'exact' as const,+ };+ }),+ ...chunks.map((i) => {+ return {+ name: i,+ type: 'exact' as const,+ };+ }),+ ...lambdaTimings.map((i) => {+ return {+ name: i,+ type: 'prefix' as const,+ };+ }),+ {+ name: encodingProgressKey(renderId),+ type: 'exact',+ },+ ];};diff --git a/packages/lambda/src/functions/helpers/get-progress.ts b/packages/lambda/src/functions/helpers/get-progress.tsindex aca5ea2cb8..66b805c4ee 100644--- a/packages/lambda/src/functions/helpers/get-progress.ts+++ b/packages/lambda/src/functions/helpers/get-progress.ts@@ -10,7 +10,7 @@ import {import {calculatePriceFromBucket} from './calculate-price-from-bucket';import {findOutputFileInBucket} from './find-output-file-in-bucket';import {getCleanupProgress} from './get-cleanup-progress';-import {getCurrentRegion} from './get-current-region';+import {getCurrentRegionInFunction} from './get-current-region';import {getEncodingMetadata} from './get-encoding-metadata';import {getFinalEncodingStatus} from './get-final-encoding-status';import {getPostRenderData} from './get-post-render-data';@@ -75,7 +75,7 @@ export const getProgress = async ({const contents = await lambdaLs({bucketName,prefix: rendersPrefix(renderId),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner,});@@ -87,7 +87,7 @@ export const getProgress = async ({),bucketName,renderId,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner,}),getRenderMetadata({@@ -96,14 +96,14 @@ export const getProgress = async ({),bucketName,renderId,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner,}),inspectErrors({contents,renderId,bucket: bucketName,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner,}),]diff --git a/packages/lambda/src/functions/helpers/write-lambda-error.ts b/packages/lambda/src/functions/helpers/write-lambda-error.tsindex 8a669416fc..34ac70aac8 100644--- a/packages/lambda/src/functions/helpers/write-lambda-error.ts+++ b/packages/lambda/src/functions/helpers/write-lambda-error.ts@@ -1,6 +1,6 @@import {getErrorKeyPrefix} from '../../shared/constants';import {randomHash} from '../../shared/random-hash';-import {getCurrentRegion} from './get-current-region';+import {getCurrentRegionInFunction} from './get-current-region';import {FileNameAndSize, getFolderFiles} from './get-files-in-folder';import {lambdaWriteFile} from './io';import {errorIsOutOfSpaceError} from './is-enosp-err';@@ -52,7 +52,7 @@ export const writeLambdaError = async ({bucketName,key: `${getErrorKeyPrefix(renderId)}${randomHash()}.txt`,body: JSON.stringify(errorInfo),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),acl: 'private',expectedBucketOwner,});diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.tsindex 6e906f8853..8707669e80 100644--- a/packages/lambda/src/functions/launch.ts+++ b/packages/lambda/src/functions/launch.ts@@ -12,6 +12,7 @@ import {outName,RenderMetadata,renderMetadataKey,+ rendersPrefix,} from '../shared/constants';import {getServeUrlHash} from '../shared/make-s3-url';import {collectChunkInformation} from './chunk-optimization/collect-data';@@ -33,8 +34,8 @@ import {getBrowserInstance,quitBrowser,} from './helpers/get-browser-instance';-import {getCurrentRegion} from './helpers/get-current-region';-import {lambdaWriteFile} from './helpers/io';+import {getCurrentRegionInFunction} from './helpers/get-current-region';+import {lambdaLs, lambdaWriteFile} from './helpers/io';import {isErrInsufficientResourcesErr} from './helpers/is-enosp-err';import {timer} from './helpers/timer';import {validateComposition} from './helpers/validate-composition';@@ -65,7 +66,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {bucketName: params.bucketName,siteId: getServeUrlHash(params.serveUrl),compositionId: params.composition,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner: options.expectedBucketOwner,}),]);@@ -183,7 +184,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {bucketName: params.bucketName,key: renderMetadataKey(params.renderId),body: JSON.stringify(renderMetadata),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),acl: 'private',expectedBucketOwner: options.expectedBucketOwner,});@@ -197,7 +198,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {payloads,renderId: params.renderId,};- await getLambdaClient(getCurrentRegion()).send(+ await getLambdaClient(getCurrentRegionInFunction()).send(new InvokeCommand({FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,// @ts-expect-error@@ -220,7 +221,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {bucketName: params.bucketName,key: encodingProgressKey(params.renderId),body: JSON.stringify(encodingProgress),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),acl: 'private',expectedBucketOwner: options.expectedBucketOwner,});@@ -233,7 +234,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {onProgress,numberOfFrames: comp.durationInFrames,renderId: params.renderId,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),codec: params.codec,expectedBucketOwner: options.expectedBucketOwner,});@@ -242,14 +243,14 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {bucketName: params.bucketName,key: outName(params.renderId, params.codec),body: fs.createReadStream(out),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),acl: 'public-read',expectedBucketOwner: options.expectedBucketOwner,});const chunkData = await collectChunkInformation({bucketName: params.bucketName,renderId: params.renderId,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner: options.expectedBucketOwner,});const optimizedProfile = optimizeInvocationOrder(@@ -269,29 +270,39 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {expectedBucketOwner: options.expectedBucketOwner,compositionId: params.composition,siteId: getServeUrlHash(params.serveUrl),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),});++ const contents = await lambdaLs({+ bucketName: params.bucketName,+ prefix: rendersPrefix(params.renderId),+ expectedBucketOwner: options.expectedBucketOwner,+ region: getCurrentRegionInFunction(),+ });+// TODO: Opportunity to parallelizeconst postRenderData = await createPostRenderData({bucketName: params.bucketName,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),renderId: params.renderId,memorySize: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),renderMetadata,+ contents,});await writePostRenderData({bucketName: params.bucketName,expectedBucketOwner: options.expectedBucketOwner,postRenderData,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),renderId: params.renderId,});await deleteChunks({- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),renderId: params.renderId,bucket: params.bucketName,chunkCount,+ contents,});};diff --git a/packages/lambda/src/functions/progress.ts b/packages/lambda/src/functions/progress.tsindex 31f65f4831..a98fdb414b 100644--- a/packages/lambda/src/functions/progress.ts+++ b/packages/lambda/src/functions/progress.ts@@ -1,9 +1,9 @@-import {getAwsRegion} from '../cli/get-aws-region';import {LambdaPayload,LambdaRoutines,RenderProgress,} from '../shared/constants';+import {getCurrentRegionInFunction} from './helpers/get-current-region';import {getProgress} from './helpers/get-progress';type Options = {@@ -22,7 +22,7 @@ export const progressHandler = async (bucketName: lambdaParams.bucketName,renderId: lambdaParams.renderId,expectedBucketOwner: options.expectedBucketOwner,- region: getAwsRegion(),+ region: getCurrentRegionInFunction(),memorySize: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),});};diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.tsindex f85bf1aa34..402406539b 100644--- a/packages/lambda/src/functions/renderer.ts+++ b/packages/lambda/src/functions/renderer.ts@@ -27,7 +27,7 @@ import {} from './chunk-optimization/types';import {deletedFiles, deletedFilesSize} from './helpers/clean-tmpdir';import {closeBrowser, getBrowserInstance} from './helpers/get-browser-instance';-import {getCurrentRegion} from './helpers/get-current-region';+import {getCurrentRegionInFunction} from './helpers/get-current-region';import {getFolderFiles} from './helpers/get-files-in-folder';import {getFolderSizeRecursively} from './helpers/get-folder-size';import {lambdaWriteFile} from './helpers/io';@@ -101,7 +101,7 @@ const renderHandler = async (params: LambdaPayload, options: Options) => {renderId: params.renderId,chunk: params.chunk,}),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),expectedBucketOwner: options.expectedBucketOwner,});},@@ -190,7 +190,7 @@ const renderHandler = async (params: LambdaPayload, options: Options) => {index: params.chunk,}),body: fs.createReadStream(outputLocation),- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),acl: 'public-read',expectedBucketOwner: options.expectedBucketOwner,});@@ -206,7 +206,7 @@ const renderHandler = async (params: LambdaPayload, options: Options) => {end: Date.now(),start,})}`,- region: getCurrentRegion(),+ region: getCurrentRegionInFunction(),acl: 'private',expectedBucketOwner: options.expectedBucketOwner,}),@@ -234,7 +234,7 @@ export const rendererHandler = async (...params,retriesLeft: params.retriesLeft - 1,};- await getLambdaClient(getCurrentRegion()).send(+ await getLambdaClient(getCurrentRegionInFunction()).send(new InvokeCommand({FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,// @ts-expect-errordiff --git a/packages/lambda/src/functions/start.ts b/packages/lambda/src/functions/start.tsindex 1524a03cf0..206495081e 100644--- a/packages/lambda/src/functions/start.ts+++ b/packages/lambda/src/functions/start.ts@@ -3,14 +3,16 @@ import {getOrCreateBucket} from '../api/get-or-create-bucket';import {getLambdaClient} from '../shared/aws-clients';import {LambdaPayload, LambdaRoutines} from '../shared/constants';import {randomHash} from '../shared/random-hash';-import {getCurrentRegion} from './helpers/get-current-region';+import {getCurrentRegionInFunction} from './helpers/get-current-region';export const startHandler = async (params: LambdaPayload) => {if (params.type !== LambdaRoutines.start) {throw new TypeError('Expected type start');}- const bucketName = await getOrCreateBucket({region: getCurrentRegion()});+ const bucketName = await getOrCreateBucket({+ region: getCurrentRegionInFunction(),+ });const renderId = randomHash();const payload: LambdaPayload = {@@ -30,7 +32,7 @@ export const startHandler = async (params: LambdaPayload) => {quality: params.quality,maxRetries: params.maxRetries,};- await getLambdaClient(getCurrentRegion()).send(+ await getLambdaClient(getCurrentRegionInFunction()).send(new InvokeCommand({FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,// @ts-expect-errordiff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.tsindex 5e68c1525d..84dfe6da12 100644--- a/packages/lambda/src/shared/constants.ts+++ b/packages/lambda/src/shared/constants.ts@@ -28,7 +28,7 @@ export const rendersPrefix = (renderId: string) => `renders/${renderId}`;export const encodingProgressKey = (renderId: string) =>`${rendersPrefix(renderId)}/encoding-progress.json`;export const renderMetadataKey = (renderId: string) =>- `${rendersPrefix(renderId)}/render-metadata.json`;+ `${rendersPrefix(renderId)}/pre-render-metadata.json`;export const lambdaInitializedPrefix = (renderId: string) =>`${rendersPrefix(renderId)}/lambda-initialized`;export const lambdaInitializedKey = ({@@ -39,7 +39,10 @@ export const lambdaInitializedKey = ({chunk: number;}) => `${lambdaInitializedPrefix(renderId)}-${chunk}.txt`;export const lambdaTimingsPrefix = (renderId: string) =>- `${rendersPrefix(renderId)}/lambda-timings`;+ `${rendersPrefix(renderId)}/lambda-timings/chunk:`;++export const lambdaTimingsPrefixForChunk = (renderId: string, chunk: number) =>+ lambdaTimingsPrefix(renderId) + String(chunk).padStart(8, '0');export const lambdaTimingsKey = ({renderId,chunk,@@ -51,9 +54,10 @@ export const lambdaTimingsKey = ({start: number;end: number;}) =>- `${lambdaTimingsPrefix(- renderId- )}/chunk:${chunk}-start:${start}-end:${end}.txt`;+ `${lambdaTimingsPrefixForChunk(+ renderId,+ chunk+ )}-start:${start}-end:${end}.txt`;export const chunkKey = (renderId: string) =>`${rendersPrefix(renderId)}/chunks/chunk-`;export const chunkKeyForIndex = ({diff --git a/packages/lambda/src/test/lambda-timing-file-name.test.ts b/packages/lambda/src/test/lambda-timing-file-name.test.tsindex 8c37d11a3a..7f1f401c24 100644--- a/packages/lambda/src/test/lambda-timing-file-name.test.ts+++ b/packages/lambda/src/test/lambda-timing-file-name.test.ts@@ -2,7 +2,7 @@ import {lambdaTimingsKey} from '../shared/constants';import {parseLambdaTimingsKey} from '../shared/parse-lambda-timings-key';const EXPECTED =- 'renders/8dakdd/lambda-timings/chunk:88-start:1625579377044-end:1625579387219.txt';+ 'renders/8dakdd/lambda-timings/chunk:00000088-start:1625579377044-end:1625579387219.txt';test('Should give expected file name', () => {expect(