🎥 Make videos programmatically with React
make some tests work again
Jonny Burger4ebef2482585
diff --git a/packages/lambda/src/api/render-media-on-lambda.ts b/packages/lambda/src/api/render-media-on-lambda.tsindex cd90773b97..0beee2f62a 100644--- a/packages/lambda/src/api/render-media-on-lambda.ts+++ b/packages/lambda/src/api/render-media-on-lambda.ts@@ -9,7 +9,6 @@ import type {} from '@remotion/renderer';import type {BrowserSafeApis} from '@remotion/renderer/client';import {NoReactAPIs} from '@remotion/renderer/pure';-import type {ProviderSpecifics} from '@remotion/serverless';import type {DownloadBehavior,OutNameInput,@@ -18,7 +17,6 @@ import type {WebhookOption,} from '@remotion/serverless/client';import {ServerlessRoutines} from '@remotion/serverless/client';-import {awsImplementation} from '../functions/aws-implementation';import type {AwsRegion} from '../regions';import {callLambda} from '../shared/call-lambda';import {@@ -83,7 +81,6 @@ export type RenderMediaOnLambdaOutput = {export const internalRenderMediaOnLambdaRaw = async (input: InnerRenderMediaOnLambdaInput,- providerSpecifics: ProviderSpecifics<AwsRegion>,): Promise<RenderMediaOnLambdaOutput> => {const {functionName, region, rendererFunctionName} = input;@@ -222,10 +219,7 @@ export const renderMediaOnLambda = ();}- return wrapped(- renderMediaOnLambdaOptionalToRequired(options),- awsImplementation,- );+ return wrapped(renderMediaOnLambdaOptionalToRequired(options));};/**diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.tsindex 03b0f40e9e..d1bea0c728 100644--- a/packages/lambda/src/cli/commands/render/render.ts+++ b/packages/lambda/src/cli/commands/render/render.ts@@ -10,9 +10,7 @@ import {getRenderProgress} from '../../../api/get-render-progress';import {internalRenderMediaOnLambdaRaw} from '../../../api/render-media-on-lambda';import type {EnhancedErrorInfo} from '../../../functions/helpers/write-lambda-error';-import type {ProviderSpecifics} from '@remotion/serverless';import type {ServerlessCodec} from '@remotion/serverless/client';-import type {AwsRegion} from '../../../regions';import {BINARY_NAME,DEFAULT_MAX_RETRIES,@@ -60,7 +58,6 @@ export const renderCommand = async (args: string[],remotionRoot: string,logLevel: LogLevel,- providerSpecifics: ProviderSpecifics<AwsRegion>,) => {const serveUrl = args[0];if (!serveUrl) {@@ -270,63 +267,58 @@ export const renderCommand = async (const webhookCustomData = getWebhookCustomData(logLevel);- const res = await internalRenderMediaOnLambdaRaw(- {- functionName,- serveUrl,- inputProps,- codec: codec as ServerlessCodec,- imageFormat,- crf: crf ?? undefined,- envVariables,- pixelFormat,- proResProfile,- jpegQuality,- region,- maxRetries,- composition,- framesPerLambda: framesPerLambda ?? null,- privacy,- logLevel,- frameRange: frameRange ?? null,- outName: parsedLambdaCli['out-name'] ?? null,- timeoutInMilliseconds,- chromiumOptions,- scale,- numberOfGifLoops,- everyNthFrame,- concurrencyPerLambda: parsedLambdaCli['concurrency-per-lambda'] ?? 1,- muted,- overwrite,- audioBitrate,- videoBitrate,- encodingBufferSize,- encodingMaxRate,- forceHeight: height,- forceWidth: width,- webhook: parsedLambdaCli.webhook- ? {- url: parsedLambdaCli.webhook,- secret: parsedLambdaCli['webhook-secret'] ?? null,- customData: webhookCustomData,- }- : null,- rendererFunctionName: parsedLambdaCli['renderer-function-name'] ?? null,- forceBucketName: parsedLambdaCli['force-bucket-name'] ?? null,- audioCodec:- CliInternals.parsedCli[- BrowserSafeApis.options.audioCodecOption.cliFlag- ],- deleteAfter: deleteAfter ?? null,- colorSpace,- downloadBehavior: {type: 'play-in-browser'},- offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytes ?? null,- x264Preset: x264Preset ?? null,- preferLossless,- indent: false,- },- providerSpecifics,- );+ const res = await internalRenderMediaOnLambdaRaw({+ functionName,+ serveUrl,+ inputProps,+ codec: codec as ServerlessCodec,+ imageFormat,+ crf: crf ?? undefined,+ envVariables,+ pixelFormat,+ proResProfile,+ jpegQuality,+ region,+ maxRetries,+ composition,+ framesPerLambda: framesPerLambda ?? null,+ privacy,+ logLevel,+ frameRange: frameRange ?? null,+ outName: parsedLambdaCli['out-name'] ?? null,+ timeoutInMilliseconds,+ chromiumOptions,+ scale,+ numberOfGifLoops,+ everyNthFrame,+ concurrencyPerLambda: parsedLambdaCli['concurrency-per-lambda'] ?? 1,+ muted,+ overwrite,+ audioBitrate,+ videoBitrate,+ encodingBufferSize,+ encodingMaxRate,+ forceHeight: height,+ forceWidth: width,+ webhook: parsedLambdaCli.webhook+ ? {+ url: parsedLambdaCli.webhook,+ secret: parsedLambdaCli['webhook-secret'] ?? null,+ customData: webhookCustomData,+ }+ : null,+ rendererFunctionName: parsedLambdaCli['renderer-function-name'] ?? null,+ forceBucketName: parsedLambdaCli['force-bucket-name'] ?? null,+ audioCodec:+ CliInternals.parsedCli[BrowserSafeApis.options.audioCodecOption.cliFlag],+ deleteAfter: deleteAfter ?? null,+ colorSpace,+ downloadBehavior: {type: 'play-in-browser'},+ offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytes ?? null,+ x264Preset: x264Preset ?? null,+ preferLossless,+ indent: false,+ });const progressBar = CliInternals.createOverwriteableCliOutput({quiet: CliInternals.quietFlagProvided(),diff --git a/packages/lambda/src/cli/index.ts b/packages/lambda/src/cli/index.tsindex f772df8a1a..eb875d352c 100644--- a/packages/lambda/src/cli/index.ts+++ b/packages/lambda/src/cli/index.ts@@ -61,7 +61,7 @@ const matchCommand = (}if (args[0] === RENDER_COMMAND) {- return renderCommand(args.slice(1), remotionRoot, logLevel, implementation);+ return renderCommand(args.slice(1), remotionRoot, logLevel);}if (args[0] === STILL_COMMAND) {diff --git a/packages/lambda/src/functions/aws-implementation.ts b/packages/lambda/src/functions/aws-implementation.tsindex 91f0550f72..97ed34e73d 100644--- a/packages/lambda/src/functions/aws-implementation.ts+++ b/packages/lambda/src/functions/aws-implementation.ts@@ -3,7 +3,7 @@ import {createBucket} from '../api/create-bucket';import {getRemotionBuckets} from '../api/get-buckets';import type {AwsRegion} from '../regions';import {applyLifeCyleOperation} from '../shared/lifecycle-rules';-import {getCurrentRegionInFunction} from './helpers/get-current-region';+import {getCurrentRegionInFunctionImplementation} from './helpers/get-current-region';if (/^AWS_Lambda_nodejs(?:18|20)[.]x$/.test(@@ -21,7 +21,7 @@ export const awsImplementation: ProviderSpecifics<AwsRegion> = {getChromiumPath() {return '/opt/bin/chromium';},- getCurrentRegionInFunction,+ getCurrentRegionInFunction: getCurrentRegionInFunctionImplementation,regionType: 'us-east-1',getBuckets: getRemotionBuckets,createBucket,diff --git a/packages/lambda/src/functions/compositions.ts b/packages/lambda/src/functions/compositions.tsindex caac23e20c..1e539e20aa 100644--- a/packages/lambda/src/functions/compositions.ts+++ b/packages/lambda/src/functions/compositions.ts@@ -8,7 +8,6 @@ import {internalGetOrCreateBucket} from '../api/get-or-create-bucket';import type {AwsRegion} from '../regions';import {decompressInputProps} from '../shared/compress-props';import {convertToServeUrl} from '../shared/convert-to-serve-url';-import {getCurrentRegionInFunction} from './helpers/get-current-region';type Options = {expectedBucketOwner: string;@@ -57,7 +56,7 @@ export const compositionsHandler = async <Region extends string>(const serializedInputPropsWithCustomSchema = await decompressInputProps({bucketName: await bucketNamePromise,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),serialized: lambdaParams.inputProps,propsType: 'input-props',});diff --git a/packages/lambda/src/functions/helpers/calculate-price-from-bucket.ts b/packages/lambda/src/functions/helpers/calculate-price-from-bucket.tsindex 11143c9ff1..59fbca1809 100644--- a/packages/lambda/src/functions/helpers/calculate-price-from-bucket.ts+++ b/packages/lambda/src/functions/helpers/calculate-price-from-bucket.ts@@ -1,21 +1,24 @@+import type {ProviderSpecifics} from '@remotion/serverless';import {estimatePrice} from '../../api/estimate-price';+import type {AwsRegion} from '../../regions';import type {RenderMetadata} from '../../shared/constants';import type {ParsedTiming} from '../../shared/parse-lambda-timings-key';import {calculateChunkTimes} from './calculate-chunk-times';-import {getCurrentRegionInFunction} from './get-current-region';-export const estimatePriceFromBucket = ({+export const estimatePriceFromBucket = <Region extends string>({renderMetadata,memorySizeInMb,diskSizeInMb,lambdasInvoked,timings,+ providerSpecifics,}: {renderMetadata: RenderMetadata | null;memorySizeInMb: number;diskSizeInMb: number;lambdasInvoked: number;timings: ParsedTiming[];+ providerSpecifics: ProviderSpecifics<Region>;}) => {if (!renderMetadata) {return null;@@ -42,7 +45,7 @@ export const estimatePriceFromBucket = ({const accruedSoFar = Number(estimatePrice({- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,durationInMilliseconds: estimatedBillingDurationInMilliseconds,memorySizeInMb,diskSizeInMb,diff --git a/packages/lambda/src/functions/helpers/cleanup-props.ts b/packages/lambda/src/functions/helpers/cleanup-props.tsindex f3ccef3abe..46b61bd728 100644--- a/packages/lambda/src/functions/helpers/cleanup-props.ts+++ b/packages/lambda/src/functions/helpers/cleanup-props.ts@@ -1,23 +1,25 @@+import type {ProviderSpecifics} from '@remotion/serverless';import type {SerializedInputProps} from '@remotion/serverless/client';import {cleanupSerializedInputProps,cleanupSerializedResolvedProps,} from '../../shared/cleanup-serialized-input-props';-import {getCurrentRegionInFunction} from './get-current-region';-export const cleanupProps = ({+export const cleanupProps = <Region extends string>({serializedResolvedProps,inputProps,+ providerSpecifics,}: {serializedResolvedProps: SerializedInputProps;inputProps: SerializedInputProps;+ providerSpecifics: ProviderSpecifics<Region>;}): Promise<[number, number]> => {const cleanupSerializedInputPropsProm = cleanupSerializedInputProps({- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),serialized: inputProps,});const cleanupResolvedInputPropsProm = cleanupSerializedResolvedProps({- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),serialized: serializedResolvedProps,});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 fba71c1dbc..1216f888d4 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@@ -15,11 +15,13 @@ export const findOutputFileInBucket = async ({renderMetadata,bucketName,customCredentials,+ currentRegion,}: {region: AwsRegion;renderMetadata: RenderMetadata;bucketName: string;customCredentials: CustomCredentials<AwsRegion> | null;+ currentRegion: AwsRegion;}): Promise<OutputFileMetadata | null> => {if (!renderMetadata) {throw new Error('unexpectedly did not get renderMetadata');@@ -43,6 +45,7 @@ export const findOutputFileInBucket = async ({renderMetadata,bucketName,customCredentials,+ currentRegion,).url,};} catch (err) {diff --git a/packages/lambda/src/functions/helpers/get-current-region.ts b/packages/lambda/src/functions/helpers/get-current-region.tsindex 1acf893894..21defce7ae 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 type {AwsRegion} from '../../regions';import {isInsideLambda} from '../../shared/is-in-lambda';-export const getCurrentRegionInFunction = () => {+export const getCurrentRegionInFunctionImplementation = () => {if (!isInsideLambda()) {throw new Error('Should not call getCurrentRegion() if not inside a lambda function',diff --git a/packages/lambda/src/functions/helpers/get-output-url-from-metadata.ts b/packages/lambda/src/functions/helpers/get-output-url-from-metadata.tsindex f6a4ebb055..b8e29e86a3 100644--- a/packages/lambda/src/functions/helpers/get-output-url-from-metadata.ts+++ b/packages/lambda/src/functions/helpers/get-output-url-from-metadata.ts@@ -2,12 +2,12 @@ import type {CustomCredentials} from '@remotion/serverless/client';import type {RenderMetadata} from '../../defaults';import type {AwsRegion} from '../../regions';import {getExpectedOutName} from './expected-out-name';-import {getCurrentRegionInFunction} from './get-current-region';export const getOutputUrlFromMetadata = (renderMetadata: RenderMetadata,bucketName: string,customCredentials: CustomCredentials<AwsRegion> | null,+ currentRegion: AwsRegion,) => {const {key, renderBucketName} = getExpectedOutName(renderMetadata,@@ -15,7 +15,7 @@ export const getOutputUrlFromMetadata = (customCredentials,);return {- url: `https://s3.${getCurrentRegionInFunction()}.amazonaws.com/${renderBucketName}/${key}`,+ url: `https://s3.${currentRegion}.amazonaws.com/${renderBucketName}/${key}`,key,};};diff --git a/packages/lambda/src/functions/helpers/get-progress.ts b/packages/lambda/src/functions/helpers/get-progress.tsindex 02c3a2e2b2..9916244ed8 100644--- a/packages/lambda/src/functions/helpers/get-progress.ts+++ b/packages/lambda/src/functions/helpers/get-progress.ts@@ -1,4 +1,5 @@import {RenderInternals} from '@remotion/renderer';+import type {ProviderSpecifics} from '@remotion/serverless';import type {CustomCredentials} from '@remotion/serverless/client';import {NoReactInternals} from 'remotion/no-react';import type {AwsRegion} from '../../regions';@@ -24,6 +25,7 @@ export const getProgress = async <Region extends string>({memorySizeInMb,timeoutInMilliseconds,customCredentials,+ providerSpecifics,}: {bucketName: string;renderId: string;@@ -32,6 +34,7 @@ export const getProgress = async <Region extends string>({memorySizeInMb: number;timeoutInMilliseconds: number;customCredentials: CustomCredentials<Region> | null;+ providerSpecifics: ProviderSpecifics<Region>;}): Promise<RenderProgress> => {const overallProgress = await getOverallProgressS3({renderId,@@ -134,6 +137,7 @@ export const getProgress = async <Region extends string>({// overestimate the price, but will only have a miniscule effect (~0.2%)diskSizeInMb: MAX_EPHEMERAL_STORAGE_IN_MB,timings: overallProgress.timings ?? [],+ providerSpecifics,});const {hasAudio, hasVideo} = renderMetadata@@ -191,6 +195,7 @@ export const getProgress = async <Region extends string>({renderMetadata,renderId,missingChunks: missingChunks ?? [],+ providerSpecifics,}): null,...errorExplanations,diff --git a/packages/lambda/src/functions/helpers/make-timeout-error.ts b/packages/lambda/src/functions/helpers/make-timeout-error.tsindex a9af1d04f0..d943b5c153 100644--- a/packages/lambda/src/functions/helpers/make-timeout-error.ts+++ b/packages/lambda/src/functions/helpers/make-timeout-error.ts@@ -1,23 +1,27 @@+import type {ProviderSpecifics} from '@remotion/serverless';import type {RenderMetadata} from '../../defaults';import {makeTimeoutMessage} from './make-timeout-message';import type {EnhancedErrorInfo} from './write-lambda-error';-export const makeTimeoutError = ({+export const makeTimeoutError = <Region extends string>({timeoutInMilliseconds,missingChunks,renderMetadata,renderId,+ providerSpecifics,}: {timeoutInMilliseconds: number;renderMetadata: RenderMetadata;renderId: string;missingChunks: number[];+ providerSpecifics: ProviderSpecifics<Region>;}): EnhancedErrorInfo => {const message = makeTimeoutMessage({missingChunks,renderMetadata,timeoutInMilliseconds,renderId,+ providerSpecifics,});const error = new Error(message);diff --git a/packages/lambda/src/functions/helpers/make-timeout-message.ts b/packages/lambda/src/functions/helpers/make-timeout-message.tsindex 185c6de263..2cc4cac1ac 100644--- a/packages/lambda/src/functions/helpers/make-timeout-message.ts+++ b/packages/lambda/src/functions/helpers/make-timeout-message.ts@@ -1,20 +1,23 @@+import type {ProviderSpecifics} from '@remotion/serverless';import {ServerlessRoutines} from '@remotion/serverless/client';import type {RenderMetadata} from '../../defaults';+import type {AwsRegion} from '../../regions';import {DOCS_URL} from '../../shared/docs-url';import {getCloudwatchMethodUrl,getCloudwatchRendererUrl,} from '../../shared/get-aws-urls';-import {getCurrentRegionInFunction} from './get-current-region';const MAX_MISSING_CHUNKS = 5;-const makeChunkMissingMessage = ({+const makeChunkMissingMessage = <Region extends string>({missingChunks,renderMetadata,+ providerSpecifics,}: {missingChunks: number[];renderMetadata: RenderMetadata;+ providerSpecifics: ProviderSpecifics<Region>;}) => {if (missingChunks.length === 0) {return 'All chunks have been successfully rendered, but the main function has timed out.';@@ -42,7 +45,7 @@ const makeChunkMissingMessage = ({msg,`â–¸ Logs for chunk ${ch}: ${getCloudwatchRendererUrl({functionName: process.env.AWS_LAMBDA_FUNCTION_NAME as string,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,rendererFunctionName: null,renderId: renderMetadata.renderId,chunk: ch,@@ -53,21 +56,23 @@ const makeChunkMissingMessage = ({].join('\n');};-export const makeTimeoutMessage = ({+export const makeTimeoutMessage = <Region extends string>({timeoutInMilliseconds,missingChunks,renderMetadata,renderId,+ providerSpecifics,}: {timeoutInMilliseconds: number;missingChunks: number[];renderMetadata: RenderMetadata;renderId: string;+ providerSpecifics: ProviderSpecifics<Region>;}) => {const cloudWatchRendererUrl = getCloudwatchRendererUrl({renderId,functionName: process.env.AWS_LAMBDA_FUNCTION_NAME as string,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,rendererFunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME as string,chunk: null,});@@ -76,13 +81,13 @@ export const makeTimeoutMessage = ({renderId,functionName: process.env.AWS_LAMBDA_FUNCTION_NAME as string,method: ServerlessRoutines.launch,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,rendererFunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME as string,});const message = [`The main function timed out after ${timeoutInMilliseconds}ms.`,- makeChunkMissingMessage({missingChunks, renderMetadata}),+ makeChunkMissingMessage({missingChunks, renderMetadata, providerSpecifics}),'',`Consider increasing the timeout of your function.`,`â–¸ You can use the "--timeout" parameter when deploying a function via CLI, or the "timeoutInSeconds" parameter when using the deployFunction() API.`,diff --git a/packages/lambda/src/functions/helpers/merge-chunks.ts b/packages/lambda/src/functions/helpers/merge-chunks.tsindex d7e8b0efc5..da9b53692e 100644--- a/packages/lambda/src/functions/helpers/merge-chunks.ts+++ b/packages/lambda/src/functions/helpers/merge-chunks.ts@@ -1,4 +1,5 @@import type {AudioCodec, LogLevel} from '@remotion/renderer';+import type {ProviderSpecifics} from '@remotion/serverless';import type {CustomCredentials,DownloadBehavior,@@ -12,7 +13,6 @@ import type {PostRenderData, RenderMetadata} from '../../shared/constants';import {cleanupProps} from './cleanup-props';import {concatVideos} from './concat-videos';import {createPostRenderData} from './create-post-render-data';-import {getCurrentRegionInFunction} from './get-current-region';import {getOutputUrlFromMetadata} from './get-output-url-from-metadata';import {inspectErrors} from './inspect-errors';import {lambdaWriteFile} from './io';@@ -49,6 +49,7 @@ export const mergeChunksAndFinishRender = async <files: string[];overallProgress: OverallProgressHelper;startTime: number;+ providerSpecifics: ProviderSpecifics<Region>;}): Promise<PostRenderData> => {const onProgress = (framesEncoded: number) => {options.overallProgress.setCombinedFrames(framesEncoded);@@ -90,7 +91,7 @@ export const mergeChunksAndFinishRender = async <bucketName: options.renderBucketName,key: options.key,body: fs.createReadStream(outfile),- region: getCurrentRegionInFunction(),+ region: options.providerSpecifics.getCurrentRegionInFunction() as AwsRegion,privacy: options.privacy,expectedBucketOwner: options.expectedBucketOwner,downloadBehavior: options.downloadBehavior,@@ -106,16 +107,18 @@ export const mergeChunksAndFinishRender = async <const cleanupProm = cleanupProps({inputProps: options.inputProps,serializedResolvedProps: options.serializedResolvedProps,+ providerSpecifics: options.providerSpecifics,});const {url: outputUrl} = getOutputUrlFromMetadata(options.renderMetadata,options.bucketName,options.customCredentials as CustomCredentials<AwsRegion>,+ options.providerSpecifics.getCurrentRegionInFunction() as AwsRegion,);const postRenderData = createPostRenderData({- region: getCurrentRegionInFunction(),+ region: options.providerSpecifics.getCurrentRegionInFunction() as AwsRegion,memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),renderMetadata: options.renderMetadata,errorExplanations,diff --git a/packages/lambda/src/functions/helpers/stream-renderer.ts b/packages/lambda/src/functions/helpers/stream-renderer.tsindex d6fea0753e..9c4163b32b 100644--- a/packages/lambda/src/functions/helpers/stream-renderer.ts+++ b/packages/lambda/src/functions/helpers/stream-renderer.ts@@ -1,12 +1,12 @@import type {EmittedArtifact, LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';+import type {ProviderSpecifics} from '@remotion/serverless';import type {ServerlessPayload} from '@remotion/serverless/client';import {ServerlessRoutines} from '@remotion/serverless/client';import {writeFileSync} from 'fs';import {join} from 'path';import {callLambdaWithStreaming} from '../../shared/call-lambda';import type {OnMessage} from '../streaming/streaming';-import {getCurrentRegionInFunction} from './get-current-region';import type {OverallProgressHelper} from './overall-render-progress';import {deserializeArtifact} from './serialize-artifact';@@ -28,6 +28,7 @@ const streamRenderer = <Region extends string>({files,logLevel,onArtifact,+ providerSpecifics,}: {payload: ServerlessPayload<Region>;functionName: string;@@ -36,6 +37,7 @@ const streamRenderer = <Region extends string>({files: string[];logLevel: LogLevel;onArtifact: (asset: EmittedArtifact) => {alreadyExisted: boolean};+ providerSpecifics: ProviderSpecifics<Region>;}) => {if (payload.type !== ServerlessRoutines.renderer) {throw new Error('Expected renderer type');@@ -158,7 +160,7 @@ const streamRenderer = <Region extends string>({functionName,payload,retriesRemaining: 1,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),timeoutInTest: 12000,type: ServerlessRoutines.renderer,receivedStreamingPayload,@@ -186,6 +188,7 @@ export const streamRendererFunctionWithRetry = async <Region extends string>({overallProgress,logLevel,onArtifact,+ providerSpecifics,}: {payload: ServerlessPayload<Region>;functionName: string;@@ -194,6 +197,7 @@ export const streamRendererFunctionWithRetry = async <Region extends string>({files: string[];logLevel: LogLevel;onArtifact: (asset: EmittedArtifact) => {alreadyExisted: boolean};+ providerSpecifics: ProviderSpecifics<Region>;}): Promise<unknown> => {if (payload.type !== ServerlessRoutines.renderer) {throw new Error('Expected renderer type');@@ -207,6 +211,7 @@ export const streamRendererFunctionWithRetry = async <Region extends string>({payload,logLevel,onArtifact,+ providerSpecifics,});if (result.type === 'error') {@@ -232,6 +237,7 @@ export const streamRendererFunctionWithRetry = async <Region extends string>({},logLevel,onArtifact,+ providerSpecifics,});}};diff --git a/packages/lambda/src/functions/index.ts b/packages/lambda/src/functions/index.tsindex 28594e41f4..79d36aa69f 100644--- a/packages/lambda/src/functions/index.ts+++ b/packages/lambda/src/functions/index.ts@@ -184,6 +184,7 @@ const innerHandler = async <Region extends string>({expectedBucketOwner: currentUserId,timeoutInMilliseconds,retriesRemaining: 2,+ providerSpecifics,});await responseWriter.write(Buffer.from(JSON.stringify(response)));diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.tsindex 41b80c41ae..fa9c65f9a4 100644--- a/packages/lambda/src/functions/launch.ts+++ b/packages/lambda/src/functions/launch.ts@@ -40,7 +40,6 @@ import {bestFramesPerLambdaParam} from './helpers/best-frames-per-lambda-param';import {cleanupProps} from './helpers/cleanup-props';import {getExpectedOutName} from './helpers/expected-out-name';import {findOutputFileInBucket} from './helpers/find-output-file-in-bucket';-import {getCurrentRegionInFunction} from './helpers/get-current-region';import {lambdaWriteFile} from './helpers/io';import {mergeChunksAndFinishRender} from './helpers/merge-chunks';import type {OverallProgressHelper} from './helpers/overall-render-progress';@@ -86,7 +85,7 @@ const innerLaunchHandler = async <Region extends string>({const inputPropsPromise = decompressInputProps({bucketName: params.bucketName,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),serialized: params.inputProps,propsType: 'input-props',});@@ -220,6 +219,7 @@ const innerLaunchHandler = async <Region extends string>({return cleanupProps({serializedResolvedProps,inputProps: params.inputProps,+ providerSpecifics,});});@@ -305,7 +305,7 @@ const innerLaunchHandler = async <Region extends string>({lambdaVersion: VERSION,framesPerLambda,memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,renderId: params.renderId,outName: params.outName ?? undefined,privacy: params.privacy,@@ -336,11 +336,13 @@ const innerLaunchHandler = async <Region extends string>({bucketName: params.bucketName,customCredentials: customCredentials as CustomCredentials<AwsRegion>,renderMetadata,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,+ currentRegion:+ providerSpecifics.getCurrentRegionInFunction() as AwsRegion,});if (output) {throw new TypeError(- `Output file "${key}" in bucket "${renderBucketName}" in region "${getCurrentRegionInFunction()}" already exists. Delete it before re-rendering, or set the 'overwrite' option in renderMediaOnLambda() to overwrite it."`,+ `Output file "${key}" in bucket "${renderBucketName}" in region "${providerSpecifics.getCurrentRegionInFunction()}" already exists. Delete it before re-rendering, or set the 'overwrite' option in renderMediaOnLambda() to overwrite it."`,);}@@ -369,7 +371,7 @@ const innerLaunchHandler = async <Region extends string>({return {alreadyExisted: true};}- const region = getCurrentRegionInFunction();+ const region = providerSpecifics.getCurrentRegionInFunction();const s3Key = artifactName(renderMetadata.renderId, artifact.filename);const start = Date.now();@@ -381,7 +383,7 @@ const innerLaunchHandler = async <Region extends string>({bucketName: renderBucketName,key: s3Key,body: artifact.content,- region,+ region: region as AwsRegion,privacy: params.privacy,expectedBucketOwner: options.expectedBucketOwner,downloadBehavior: params.downloadBehavior,@@ -433,6 +435,7 @@ const innerLaunchHandler = async <Region extends string>({payload,logLevel: params.logLevel,onArtifact,+ providerSpecifics,});}),);@@ -465,6 +468,7 @@ const innerLaunchHandler = async <Region extends string>({files: files.sort(),overallProgress,startTime,+ providerSpecifics,});return postRenderData;@@ -627,7 +631,7 @@ export const launchHandler = async <Region extends string>(renderId: params.renderId,bucketName: params.bucketName,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,timeoutTimestamp: options.getRemainingTimeInMillis() + Date.now(),logLevel: params.logLevel,});diff --git a/packages/lambda/src/functions/progress.ts b/packages/lambda/src/functions/progress.tsindex fe13c6e06a..ad49d9b1d9 100644--- a/packages/lambda/src/functions/progress.ts+++ b/packages/lambda/src/functions/progress.ts@@ -1,19 +1,21 @@+import type {ProviderSpecifics} from '@remotion/serverless';import type {ServerlessPayload} from '@remotion/serverless/client';import {ServerlessRoutines} from '@remotion/serverless/client';import {VERSION} from 'remotion/version';+import type {AwsRegion} from '../regions';import type {RenderProgress} from '../shared/constants';-import {getCurrentRegionInFunction} from './helpers/get-current-region';import {getProgress} from './helpers/get-progress';-type Options = {+type Options<Region extends string> = {expectedBucketOwner: string;timeoutInMilliseconds: number;retriesRemaining: number;+ providerSpecifics: ProviderSpecifics<Region>;};export const progressHandler = async <Region extends string>(lambdaParams: ServerlessPayload<Region>,- options: Options,+ options: Options<Region>,): Promise<RenderProgress> => {if (lambdaParams.type !== ServerlessRoutines.status) {throw new TypeError('Expected status type');@@ -36,10 +38,12 @@ export const progressHandler = async <Region extends string>(bucketName: lambdaParams.bucketName,renderId: lambdaParams.renderId,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region:+ options.providerSpecifics.getCurrentRegionInFunction() as AwsRegion,memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),timeoutInMilliseconds: options.timeoutInMilliseconds,customCredentials: lambdaParams.s3OutputProvider ?? null,+ providerSpecifics: options.providerSpecifics,});return progress;} catch (err) {@@ -55,6 +59,7 @@ export const progressHandler = async <Region extends string>(expectedBucketOwner: options.expectedBucketOwner,timeoutInMilliseconds: options.timeoutInMilliseconds,retriesRemaining: options.retriesRemaining - 1,+ providerSpecifics: options.providerSpecifics,});}diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.tsindex b34c629b7a..23a3020dfe 100644--- a/packages/lambda/src/functions/renderer.ts+++ b/packages/lambda/src/functions/renderer.ts@@ -22,7 +22,6 @@ import {canConcatAudioSeamlessly,canConcatVideoSeamlessly,} from './helpers/can-concat-seamlessly';-import {getCurrentRegionInFunction} from './helpers/get-current-region';import {startLeakDetection} from './helpers/leak-detection';import {onDownloadsHelper} from './helpers/on-downloads-logger';import type {RequestContext} from './helpers/request-context';@@ -41,13 +40,13 @@ const renderHandler = async <Region extends string>({options,logs,onStream,- platformImplementation: providerSpecifics,+ providerSpecifics,}: {params: ServerlessPayload<Region>;options: Options;logs: BrowserLog[];onStream: OnStream;- platformImplementation: ProviderSpecifics<Region>;+ providerSpecifics: ProviderSpecifics<Region>;}): Promise<{}> => {if (params.type !== ServerlessRoutines.renderer) {throw new Error('Params must be renderer');@@ -62,7 +61,7 @@ const renderHandler = async <Region extends string>({const inputPropsPromise = decompressInputProps({bucketName: params.bucketName,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),serialized: params.inputProps,propsType: 'input-props',});@@ -70,7 +69,7 @@ const renderHandler = async <Region extends string>({const resolvedPropsPromise = decompressInputProps({bucketName: params.bucketName,expectedBucketOwner: options.expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction(),serialized: params.resolvedProps,propsType: 'resolved-props',});@@ -415,7 +414,7 @@ export const rendererHandler = async <Region extends string>({options,logs,onStream,- platformImplementation: providerSpecifics,+ providerSpecifics,});return {type: 'success',diff --git a/packages/lambda/src/functions/start.ts b/packages/lambda/src/functions/start.tsindex 43184f5227..346faa9c2f 100644--- a/packages/lambda/src/functions/start.ts+++ b/packages/lambda/src/functions/start.ts@@ -8,7 +8,6 @@ import type {AwsRegion} from '../regions';import {getLambdaClient} from '../shared/aws-clients';import {overallProgressKey} from '../shared/constants';import {convertToServeUrl} from '../shared/convert-to-serve-url';-import {getCurrentRegionInFunction} from './helpers/get-current-region';import {lambdaWriteFile} from './helpers/io';import {generateRandomHashWithLifeCycleRule,@@ -123,7 +122,9 @@ export const startHandler = async <Region extends string>(};// Don't replace with callLambda(), we want to return before the render is snone- const result = await getLambdaClient(getCurrentRegionInFunction()).send(+ const result = await getLambdaClient(+ providerSpecifics.getCurrentRegionInFunction() as AwsRegion,+ ).send(new InvokeCommand({FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,Payload: JSON.stringify(payload),diff --git a/packages/lambda/src/functions/still.ts b/packages/lambda/src/functions/still.tsindex 0b61e191cf..97268355cd 100644--- a/packages/lambda/src/functions/still.ts+++ b/packages/lambda/src/functions/still.ts@@ -35,7 +35,6 @@ import {getExpectedOutName,} from './helpers/expected-out-name';import {formatCostsInfo} from './helpers/format-costs-info';-import {getCurrentRegionInFunction} from './helpers/get-current-region';import {getOutputUrlFromMetadata} from './helpers/get-output-url-from-metadata';import {lambdaWriteFile} from './helpers/io';import {onDownloadsHelper} from './helpers/on-downloads-logger';@@ -108,7 +107,7 @@ const innerStillHandler = async <Region extends string>({const outputPath = path.join(outputDir, 'output');- const region = getCurrentRegionInFunction();+ const region = providerSpecifics.getCurrentRegionInFunction();const bucketName = await bucketNamePromise;const serializedInputPropsWithCustomSchema = await decompressInputProps({bucketName,@@ -120,7 +119,7 @@ const innerStillHandler = async <Region extends string>({const serveUrl = convertToServeUrl({urlOrId: lambdaParams.serveUrl,- region,+ region: region as AwsRegion,bucketName,});@@ -172,7 +171,7 @@ const innerStillHandler = async <Region extends string>({lambdaVersion: VERSION,framesPerLambda: 1,memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,renderId,outName: lambdaParams.outName ?? undefined,privacy: lambdaParams.privacy,@@ -190,7 +189,7 @@ const innerStillHandler = async <Region extends string>({bucketName,key: overallProgressKey(renderId),body: JSON.stringify(still),- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,privacy: 'private',expectedBucketOwner,downloadBehavior: null,@@ -231,7 +230,7 @@ const innerStillHandler = async <Region extends string>({bucketName: renderBucketName,key: s3Key,body: artifact.content,- region,+ region: region as AwsRegion,privacy: lambdaParams.privacy,expectedBucketOwner,downloadBehavior: lambdaParams.downloadBehavior,@@ -299,7 +298,7 @@ const innerStillHandler = async <Region extends string>({privacy: lambdaParams.privacy,body: fs.createReadStream(outputPath),expectedBucketOwner,- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,downloadBehavior: lambdaParams.downloadBehavior,customCredentials,});@@ -307,7 +306,7 @@ const innerStillHandler = async <Region extends string>({await Promise.all([fs.promises.rm(outputPath, {recursive: true}),cleanupSerializedInputProps({- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,serialized: lambdaParams.inputProps,}),server.closeServer(true),@@ -316,7 +315,7 @@ const innerStillHandler = async <Region extends string>({const estimatedPrice = estimatePrice({durationInMilliseconds: Date.now() - start + 100,memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),- region: getCurrentRegionInFunction(),+ region: providerSpecifics.getCurrentRegionInFunction() as AwsRegion,lambdasInvoked: 1,// We cannot determine the ephemeral storage size, so we// overestimate the price, but will only have a miniscule effect (~0.2%)@@ -327,6 +326,7 @@ const innerStillHandler = async <Region extends string>({renderMetadata,bucketName,customCredentials as CustomCredentials<AwsRegion>,+ providerSpecifics.getCurrentRegionInFunction() as AwsRegion,);const payload: RenderStillLambdaResponsePayload = {diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.tsindex 41ca186ce7..927e4621e1 100644--- a/packages/lambda/src/shared/call-lambda.ts+++ b/packages/lambda/src/shared/call-lambda.ts@@ -28,11 +28,11 @@ import type {LambdaReturnValues} from './return-values';const INVALID_JSON_MESSAGE = 'Cannot parse Lambda response as JSON';-type Options<T extends ServerlessRoutines> = {+type Options<T extends ServerlessRoutines, Region extends string> = {functionName: string;type: T;- payload: Omit<ServerlessPayloads<AwsRegion>[T], 'type'>;- region: AwsRegion;+ payload: Omit<ServerlessPayloads<Region>[T], 'type'>;+ region: Region;timeoutInTest: number;};@@ -45,11 +45,14 @@ const parseJsonOrThrowSource = (data: Uint8Array, type: string) => {}};-export const callLambda = async <T extends ServerlessRoutines>(- options: Options<T> & {},+export const callLambda = async <+ T extends ServerlessRoutines,+ Region extends string,+>(+ options: Options<T, Region> & {},): Promise<LambdaReturnValues[T]> => {// Do not remove this await- const res = await callLambdaWithoutRetry<T>(options);+ const res = await callLambdaWithoutRetry<T, Region>(options);if (res.type === 'error') {const err = new Error(res.message);err.stack = res.stack;@@ -59,8 +62,11 @@ export const callLambda = async <T extends ServerlessRoutines>(return res;};-export const callLambdaWithStreaming = async <T extends ServerlessRoutines>(- options: Options<T> & {+export const callLambdaWithStreaming = async <+ T extends ServerlessRoutines,+ Region extends string,+>(+ options: Options<T, Region> & {receivedStreamingPayload: OnMessage;retriesRemaining: number;},@@ -70,7 +76,7 @@ export const callLambdaWithStreaming = async <T extends ServerlessRoutines>(try {// Do not remove this await- await callLambdaWithStreamingWithoutRetry<T>(options);+ await callLambdaWithStreamingWithoutRetry<T, Region>(options);} catch (err) {if (options.retriesRemaining === 0) {throw err;@@ -94,15 +100,18 @@ export const callLambdaWithStreaming = async <T extends ServerlessRoutines>(}};-const callLambdaWithoutRetry = async <T extends ServerlessRoutines>({+const callLambdaWithoutRetry = async <+ T extends ServerlessRoutines,+ Region extends string,+>({functionName,type,payload,region,timeoutInTest,-}: Options<T>): Promise<OrError<LambdaReturnValues[T]>> => {+}: Options<T, Region>): Promise<OrError<LambdaReturnValues[T]>> => {const Payload = JSON.stringify({type, ...payload});- const res = await getLambdaClient(region, timeoutInTest).send(+ const res = await getLambdaClient(region as AwsRegion, timeoutInTest).send(new InvokeCommand({FunctionName: functionName,Payload,@@ -122,20 +131,20 @@ const callLambdaWithoutRetry = async <T extends ServerlessRoutines>({const STREAM_STALL_TIMEOUT = 30000;const LAMBDA_STREAM_STALL = `AWS did not invoke Lambda in ${STREAM_STALL_TIMEOUT}ms`;-const invokeStreamOrTimeout = async ({+const invokeStreamOrTimeout = async <Region extends string>({region,timeoutInTest,functionName,type,payload,}: {- region: AwsRegion;+ region: Region;timeoutInTest: number;functionName: string;type: string;payload: Record<string, unknown>;}) => {- const resProm = getLambdaClient(region, timeoutInTest).send(+ const resProm = getLambdaClient(region as AwsRegion, timeoutInTest).send(new InvokeWithResponseStreamCommand({FunctionName: functionName,Payload: JSON.stringify({type, ...payload}),@@ -164,6 +173,7 @@ const invokeStreamOrTimeout = async ({const callLambdaWithStreamingWithoutRetry = async <T extends ServerlessRoutines,+ Region extends string,>({functionName,type,@@ -171,7 +181,7 @@ const callLambdaWithStreamingWithoutRetry = async <region,timeoutInTest,receivedStreamingPayload,-}: Options<T> & {+}: Options<T, Region> & {receivedStreamingPayload: OnMessage;}): Promise<void> => {const res = await invokeStreamOrTimeout({diff --git a/packages/lambda/src/shared/cleanup-serialized-input-props.ts b/packages/lambda/src/shared/cleanup-serialized-input-props.tsindex fee5256200..5bde56fb0e 100644--- a/packages/lambda/src/shared/cleanup-serialized-input-props.ts+++ b/packages/lambda/src/shared/cleanup-serialized-input-props.ts@@ -6,12 +6,12 @@ import {import type {AwsRegion} from '../client';import {lambdaDeleteFile} from '../functions/helpers/io';-export const cleanupSerializedInputProps = async ({+export const cleanupSerializedInputProps = async <Region extends string>({serialized,region,}: {serialized: SerializedInputProps;- region: AwsRegion;+ region: Region;}): Promise<number> => {if (serialized.type === 'payload') {return 0;@@ -21,19 +21,19 @@ export const cleanupSerializedInputProps = async ({await lambdaDeleteFile({bucketName: serialized.bucketName,key: inputPropsKey(serialized.hash),- region,+ region: region as AwsRegion,customCredentials: null,});return Date.now() - time;};-export const cleanupSerializedResolvedProps = async ({+export const cleanupSerializedResolvedProps = async <Region extends string>({serialized,region,}: {serialized: SerializedInputProps;- region: AwsRegion;+ region: Region;}): Promise<number> => {if (serialized.type === 'payload') {return 0;@@ -43,7 +43,7 @@ export const cleanupSerializedResolvedProps = async ({await lambdaDeleteFile({bucketName: serialized.bucketName,key: resolvedPropsKey(serialized.hash),- region,+ region: region as AwsRegion,customCredentials: null,});diff --git a/packages/lambda/src/shared/compress-props.ts b/packages/lambda/src/shared/compress-props.tsindex 8646f238d4..342af1d005 100644--- a/packages/lambda/src/shared/compress-props.ts+++ b/packages/lambda/src/shared/compress-props.ts@@ -117,7 +117,7 @@ export const compressInputProps = async <Region extends string>({};};-export const decompressInputProps = async ({+export const decompressInputProps = async <Region extends string>({serialized,region,bucketName,@@ -125,7 +125,7 @@ export const decompressInputProps = async ({propsType,}: {serialized: SerializedInputProps;- region: AwsRegion;+ region: Region;bucketName: string;expectedBucketOwner: string;propsType: PropsType;@@ -139,7 +139,7 @@ export const decompressInputProps = async ({bucketName,expectedBucketOwner,key: makeKey(propsType, serialized.hash),- region,+ region: region as AwsRegion,});const body = await streamToString(response);diff --git a/packages/lambda/src/test/integration/simulate-lambda-render.ts b/packages/lambda/src/test/integration/simulate-lambda-render.tsindex 8113812ee6..701058a2b2 100644--- a/packages/lambda/src/test/integration/simulate-lambda-render.ts+++ b/packages/lambda/src/test/integration/simulate-lambda-render.ts@@ -6,6 +6,7 @@ import {makeLambdaRenderMediaPayload} from '../../api/make-lambda-payload';import type {RenderMediaOnLambdaInput} from '../../api/render-media-on-lambda';import {renderMediaOnLambdaOptionalToRequired} from '../../api/render-media-on-lambda';import {lambdaReadFile} from '../../functions/helpers/io';+import type {AwsRegion} from '../../regions';import {callLambda} from '../../shared/call-lambda';const functionName = 'remotion-dev-render';@@ -58,15 +59,17 @@ export const simulateLambdaRender = async (forceIPv4: false,});- const res = await callLambda({+ const payload = await makeLambdaRenderMediaPayload(+ renderMediaOnLambdaOptionalToRequired({+ ...input,+ serveUrl: `http://localhost:${port}`,+ functionName,+ }),+ );++ const res = await callLambda<ServerlessRoutines.start, AwsRegion>({type: ServerlessRoutines.start,- payload: await makeLambdaRenderMediaPayload(- renderMediaOnLambdaOptionalToRequired({- ...input,- serveUrl: `http://localhost:${port}`,- functionName,- }),- ),+ payload,functionName: 'remotion-dev-lambda',region: 'eu-central-1',timeoutInTest: 120000,diff --git a/packages/lambda/src/test/unit/price-calculation.test.ts b/packages/lambda/src/test/unit/price-calculation.test.tsindex 1792d45fe6..cd0e56262b 100644--- a/packages/lambda/src/test/unit/price-calculation.test.ts+++ b/packages/lambda/src/test/unit/price-calculation.test.ts@@ -1,5 +1,6 @@import {expect, test} from 'vitest';import {estimatePriceFromBucket} from '../../functions/helpers/calculate-price-from-bucket';+import {mockImplementation} from '../mock-implementation';test('Should not throw while calculating prices when time shifts occur', () => {const aDate = Date.now();@@ -47,6 +48,7 @@ test('Should not throw while calculating prices when time shifts occur', () => {start: aDate,},],+ providerSpecifics: mockImplementation,});expect(price?.accruedSoFar).toBeGreaterThanOrEqual(0);});