🎥 Make videos programmatically with React
`@remotion/lambda`: Support AWS China regions (#10383)
anthod4cba93de6aa2
diff --git a/packages/docs/docs/lambda/aws-china-regions.mdx b/packages/docs/docs/lambda/aws-china-regions.mdxnew file mode 100644index 0000000000..d841b4f405--- /dev/null+++ b/packages/docs/docs/lambda/aws-china-regions.mdx@@ -0,0 +1,62 @@+---+image: /generated/articles-docs-lambda-aws-china-regions.png+title: AWS China regions+slug: /lambda/aws-china-regions+crumb: 'Lambda'+---++# AWS China regions<AvailableFrom v="4.0.510" />++Remotion Lambda supports these AWS China regions:++- Beijing: `cn-north-1`+- Ningxia: `cn-northwest-1`++Use credentials from an AWS China account. AWS accounts and resources from the standard `aws` partition cannot be used in the `aws-cn` partition.++## Custom Layers++Remotion-hosted Lambda Layers are not available in AWS China regions. Build and publish the required Layers in the same AWS China region, then pass their version ARNs to [`deployFunction()`](/docs/lambda/deployfunction#customlayerarns):++```ts twoslash title="deploy-lambda.ts"+import {deployFunction} from '@remotion/lambda';++await deployFunction({+ region: 'cn-north-1',+ timeoutInSeconds: 120,+ memorySizeInMb: 2048,+ createCloudWatchLogGroup: true,+ customLayerArns: [+ 'arn:aws-cn:lambda:cn-north-1:123456789012:layer:custom-chromium:1',+ 'arn:aws-cn:lambda:cn-north-1:123456789012:layer:custom-fonts:1',+ ],+});+```++The Layer ARNs must start with `arn:aws-cn:` and match the selected region. See [Custom Layers](/docs/lambda/custom-layers) for build instructions and size limits.++## IAM policies++Generate policies for the `aws-cn` partition:++```ts twoslash title="policies.ts"+import {getRolePolicy, getUserPolicy} from '@remotion/lambda';++const userPolicy = getUserPolicy({partition: 'aws-cn'});+const rolePolicy = getRolePolicy({partition: 'aws-cn'});+```++The CLI selects the partition from the configured region:++```sh title="Generate AWS China policies"+npx remotion lambda policies user --region=cn-north-1+npx remotion lambda policies role --region=cn-north-1+```++Permissions for custom Layer ARNs must be configured separately. See [Custom Layers](/docs/lambda/custom-layers#specify-custom-layers-while-deploying).++## Rendering++[`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda) and [`renderStillOnLambda()`](/docs/lambda/renderstillonlambda) require no China-specific options.++S3 and Console URLs use the AWS China domains, such as `amazonaws.com.cn` and `console.amazonaws.cn`. Estimated Lambda costs are returned in CNY.diff --git a/packages/docs/docs/lambda/cli/functions/deploy.mdx b/packages/docs/docs/lambda/cli/functions/deploy.mdxindex 3c622ac4f1..be8b57e017 100644--- a/packages/docs/docs/lambda/cli/functions/deploy.mdx+++ b/packages/docs/docs/lambda/cli/functions/deploy.mdx@@ -80,6 +80,12 @@ Retention period for the CloudWatch Logs in days. Default: <DefaultLogRetentionUse a custom role for the function instead of the default (`arn:aws:iam::[aws-account-id]:role/remotion-lambda-role`)+## `--custom-layer-arns`<AvailableFrom v="4.0.510" />++A comma-separated list of complete Lambda Layer version ARNs. The specified Layers replace all Remotion-hosted runtime Layers.++See [Custom Layers](/docs/lambda/custom-layers). This flag is required in [AWS China regions](/docs/lambda/aws-china-regions).+## `--quiet`, `-q`Only logs the function name.diff --git a/packages/docs/docs/lambda/cli/regions.mdx b/packages/docs/docs/lambda/cli/regions.mdxindex 521890325a..770d704d32 100644--- a/packages/docs/docs/lambda/cli/regions.mdx+++ b/packages/docs/docs/lambda/cli/regions.mdx@@ -14,7 +14,7 @@ npx remotion lambda regions<details><summary>Show output</summary>- <pre>eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-south-1 eu-north-1 us-east-1 us-east-2 us-west-1 us-west-2 af-south-1 ap-south-1 ap-east-1 ap-southeast-1 ap-southeast-2 ap-northeast-3 ap-northeast-1 ap-northeast-2 ca-central-1 sa-east-1</pre>+ <pre>eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-south-1 eu-north-1 us-east-1 us-east-2 us-west-1 us-west-2 af-south-1 ap-south-1 ap-east-1 ap-southeast-1 ap-southeast-2 ap-northeast-3 ap-northeast-1 ap-northeast-2 ca-central-1 cn-north-1 cn-northwest-1 sa-east-1</pre></details>## Flagsdiff --git a/packages/docs/docs/lambda/custom-layers.mdx b/packages/docs/docs/lambda/custom-layers.mdxindex 199410bb28..69064f4d05 100644--- a/packages/docs/docs/lambda/custom-layers.mdx+++ b/packages/docs/docs/lambda/custom-layers.mdx@@ -96,6 +96,14 @@ This will zip the layers and put them as artifacts in the `out` directory.You need to do this for every AWS region you want to use Remotion Lambda in.:::+## Specify custom Layers while deploying<AvailableFrom v="4.0.510" />++Pass every runtime Layer to [`deployFunction()`](/docs/lambda/deployfunction#customlayerarns) or [`--custom-layer-arns`](/docs/lambda/cli/functions/deploy#--custom-layer-arns). The list replaces all Remotion-hosted Layers.++Credentials used to deploy custom Layers need `lambda:GetLayerVersion` permission for the specified Layer ARNs. Updating an existing function additionally needs `lambda:GetFunctionConfiguration` and `lambda:UpdateFunctionConfiguration`.++Custom Layers are required in [AWS China regions](/docs/lambda/aws-china-regions).+## Update the Lambda functionBefore you continue, make sure a Remotion Lambda function is deployed.diff --git a/packages/docs/docs/lambda/deployfunction.mdx b/packages/docs/docs/lambda/deployfunction.mdxindex ef9f877e5e..60d43e17c3 100644--- a/packages/docs/docs/lambda/deployfunction.mdx+++ b/packages/docs/docs/lambda/deployfunction.mdx@@ -63,6 +63,16 @@ Sets the amount of disk storage that is available in the Lambda function. Must bUse a custom role for the function instead of the default (`arn:aws:iam::[aws-account-id]:role/remotion-lambda-role`)+### `customLayerArns?`<AvailableFrom v="4.0.510" />++An ordered, non-empty array of complete Lambda Layer version ARNs. The specified Layers replace all Remotion-hosted runtime Layers.++Each ARN must include a numeric version and use the function's AWS region and AWS partition. If omitted, Remotion-hosted Layers continue to be selected using `runtimePreference`. Non-default `runtimePreference` values cannot be combined with custom Layers.++This option is required in [AWS China regions](/docs/lambda/aws-china-regions), where Remotion-hosted Layers are unavailable.++See [Custom Layers](/docs/lambda/custom-layers) for usage, limits, compatibility, and IAM requirements.+### `enableLambdaInsights?`<AvailableFrom v="4.0.61" /><Options id="enable-lambda-insights" />diff --git a/packages/docs/docs/lambda/getrolepolicy.mdx b/packages/docs/docs/lambda/getrolepolicy.mdxindex ff86c42b97..462462ea47 100644--- a/packages/docs/docs/lambda/getrolepolicy.mdx+++ b/packages/docs/docs/lambda/getrolepolicy.mdx@@ -27,6 +27,12 @@ console.log(getRolePolicy()); /* `` */```+## API++### `partition?`<AvailableFrom v="4.0.510" />++The AWS partition for which to generate the policy. Accepts `"aws"` (default) or `"aws-cn"`. See [AWS China regions](/docs/lambda/aws-china-regions).+## See also- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/lambda/src/api/iam-validation/suggested-policy.ts)diff --git a/packages/docs/docs/lambda/getuserpolicy.mdx b/packages/docs/docs/lambda/getuserpolicy.mdxindex 6284510e59..429090c674 100644--- a/packages/docs/docs/lambda/getuserpolicy.mdx+++ b/packages/docs/docs/lambda/getuserpolicy.mdx@@ -25,6 +25,12 @@ console.log(getUserPolicy()); /* `` */```+## API++### `partition?`<AvailableFrom v="4.0.510" />++The AWS partition for which to generate the policy. Accepts `"aws"` (default) or `"aws-cn"`. See [AWS China regions](/docs/lambda/aws-china-regions).+## See also- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/lambda/src/api/iam-validation/suggested-policy.ts)diff --git a/packages/docs/docs/lambda/region-selection.mdx b/packages/docs/docs/lambda/region-selection.mdxindex db0016393b..9375f1c0ae 100644--- a/packages/docs/docs/lambda/region-selection.mdx+++ b/packages/docs/docs/lambda/region-selection.mdx@@ -24,6 +24,10 @@ You can call [`getRegions()`](/docs/lambda/getregions) or type [`npx remotion laSupport for regions `eu-west-3`, `eu-south-1`, `eu-north-1`, `us-west-1`, `af-south-1`, `ap-east-1`, `ap-northeast-2`, `ap-northeast-3`, `ca-central-1`, `sa-east-1` has been added in v3.3.7.:::+:::note+The AWS China regions `cn-north-1` and `cn-northwest-1` are supported from <AvailableFrom v="4.0.510" inline /> and require additional setup. See [AWS China regions](/docs/lambda/aws-china-regions).+:::+## Default regionThe default region is `us-east-1`.diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 737dbb0910..989da048b5 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -1267,6 +1267,7 @@ const sidebars: SidebarsConfig = {'lambda/authentication','lambda/permissions','lambda/region-selection',+ 'lambda/aws-china-regions','lambda/concurrency','lambda/runtime','lambda/disk-size',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 14e85f7355..5700a3bbb2 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -3032,6 +3032,15 @@ export const articles = [noAi: false,slug: 'lambda/autodelete',},+ {+ id: 'lambda/aws-china-regions',+ title: 'AWS China regions',+ relativePath: 'docs/lambda/aws-china-regions.mdx',+ compId: 'articles-docs-lambda-aws-china-regions',+ crumb: 'Lambda',+ noAi: false,+ slug: 'lambda/aws-china-regions',+ },{id: 'lambda/bucket-naming',title: 'Bucket names in Remotion Lambda',diff --git a/packages/docs/static/generated/articles-docs-lambda-aws-china-regions.png b/packages/docs/static/generated/articles-docs-lambda-aws-china-regions.pngnew file mode 100644index 0000000000..1933d2aee0Binary files /dev/null and b/packages/docs/static/generated/articles-docs-lambda-aws-china-regions.png differdiff --git a/packages/lambda-client/src/aws-provider.ts b/packages/lambda-client/src/aws-provider.tsindex 259a81cf45..34caed2f5e 100644--- a/packages/lambda-client/src/aws-provider.ts+++ b/packages/lambda-client/src/aws-provider.ts@@ -13,6 +13,7 @@ export type AwsProvider = {alreadyCreated: boolean;retentionInDays: number;customRoleArn: string;+ customLayerArns: string[] | null;enableLambdaInsights: boolean;vpcSubnetIds: string;vpcSecurityGroupIds: string;@@ -26,6 +27,7 @@ import {EventEmitter} from 'node:events';import type {StorageClass} from '@aws-sdk/client-s3';import type {ProviderSpecifics} from '@remotion/serverless-client';import {expiryDays} from '@remotion/serverless-client';+import {getAwsRegionMetadata} from './aws-region-metadata';import {bucketExistsInRegionImplementation} from './bucket-exists';import {callFunctionAsyncImplementation} from './call-lambda-async';import {callFunctionWithStreamingImplementation} from './call-lambda-streaming';@@ -123,6 +125,12 @@ export const awsImplementation: ProviderSpecifics<AwsProvider> = {return MAX_EPHEMERAL_STORAGE_IN_MB;},estimatePrice,+ getBillingCurrency: (region) => getAwsRegionMetadata(region).billingCurrency,+ getRendererFunctionTransport: (region) =>+ getAwsRegionMetadata(region).partition === 'aws-cn'+ ? 's3'+ : 'response-streaming',+ getServiceDnsSuffix: (region) => getAwsRegionMetadata(region).dnsSuffix,getLoggingUrlForMethod: getCloudwatchMethodUrl,getLoggingUrlForRendererFunction: getCloudwatchRendererUrl,isFlakyError,diff --git a/packages/lambda-client/src/aws-region-metadata.ts b/packages/lambda-client/src/aws-region-metadata.tsnew file mode 100644index 0000000000..bab59b8b81--- /dev/null+++ b/packages/lambda-client/src/aws-region-metadata.ts@@ -0,0 +1,61 @@+import type {AwsRegion} from './regions';++export type AwsPartition = 'aws' | 'aws-cn';+export type AwsBillingCurrency = 'USD' | 'CNY';++export type AwsRegionMetadata = {+ partition: AwsPartition;+ dnsSuffix: 'amazonaws.com' | 'amazonaws.com.cn';+ consoleDomain: 'console.aws.amazon.com' | 'console.amazonaws.cn';+ billingCurrency: AwsBillingCurrency;+};++const regionPartitions: {[region in AwsRegion]: AwsPartition} = {+ 'af-south-1': 'aws',+ 'ap-east-1': 'aws',+ 'ap-northeast-1': 'aws',+ 'ap-northeast-2': 'aws',+ 'ap-northeast-3': 'aws',+ 'ap-south-1': 'aws',+ 'ap-southeast-1': 'aws',+ 'ap-southeast-2': 'aws',+ 'ap-southeast-4': 'aws',+ 'ap-southeast-5': 'aws',+ 'ca-central-1': 'aws',+ 'cn-north-1': 'aws-cn',+ 'cn-northwest-1': 'aws-cn',+ 'eu-central-1': 'aws',+ 'eu-central-2': 'aws',+ 'eu-north-1': 'aws',+ 'eu-south-1': 'aws',+ 'eu-west-1': 'aws',+ 'eu-west-2': 'aws',+ 'eu-west-3': 'aws',+ 'sa-east-1': 'aws',+ 'us-east-1': 'aws',+ 'us-east-2': 'aws',+ 'us-west-1': 'aws',+ 'us-west-2': 'aws',+};++const partitionMetadata: {[partition in AwsPartition]: AwsRegionMetadata} = {+ aws: {+ partition: 'aws',+ dnsSuffix: 'amazonaws.com',+ consoleDomain: 'console.aws.amazon.com',+ billingCurrency: 'USD',+ },+ 'aws-cn': {+ partition: 'aws-cn',+ dnsSuffix: 'amazonaws.com.cn',+ consoleDomain: 'console.amazonaws.cn',+ billingCurrency: 'CNY',+ },+};++export const getAwsPartitionMetadata = (+ partition: AwsPartition,+): AwsRegionMetadata => partitionMetadata[partition];++export const getAwsRegionMetadata = (region: AwsRegion): AwsRegionMetadata =>+ getAwsPartitionMetadata(regionPartitions[region]);diff --git a/packages/lambda-client/src/call-lambda-streaming.ts b/packages/lambda-client/src/call-lambda-streaming.tsindex af1f430c83..f54fadd5c8 100644--- a/packages/lambda-client/src/call-lambda-streaming.ts+++ b/packages/lambda-client/src/call-lambda-streaming.ts@@ -18,6 +18,7 @@ import {messageTypeIdToMessageType,} from '@remotion/serverless-client';import {getLambdaClient} from './aws-clients';+import {getAwsRegionMetadata} from './aws-region-metadata';import type {AwsRegion} from './regions';const STREAM_STALL_TIMEOUT = 30000;@@ -146,7 +147,8 @@ const callLambdaWithStreamingWithoutRetry = async <if (event.InvokeComplete) {if (event.InvokeComplete.ErrorCode) {- const logs = `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~unit~'seconds~editorString~'fields*20*40timestamp*2c*20*40requestId*2c*20*40message*0a*7c*20filter*20*40requestId*20like*20*${res.$metadata.requestId}*22*0a*7c*20sort*20*40timestamp*20asc~source~(~'*2faws*2flambda*2f${functionName}))`;+ const {consoleDomain} = getAwsRegionMetadata(region as AwsRegion);+ const logs = `https://${region}.${consoleDomain}/cloudwatch/home?region=${region}#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~unit~'seconds~editorString~'fields*20*40timestamp*2c*20*40requestId*2c*20*40message*0a*7c*20filter*20*40requestId*20like*20*${res.$metadata.requestId}*22*0a*7c*20sort*20*40timestamp*20asc~source~(~'*2faws*2flambda*2f${functionName}))`;if (event.InvokeComplete.ErrorCode === 'Unhandled') {throw new Error(`Lambda function ${functionName} failed with an unhandled error: ${diff --git a/packages/lambda-client/src/convert-to-serve-url.ts b/packages/lambda-client/src/convert-to-serve-url.tsindex 33b0e9eaaf..83cfa50962 100644--- a/packages/lambda-client/src/convert-to-serve-url.ts+++ b/packages/lambda-client/src/convert-to-serve-url.ts@@ -1,4 +1,5 @@import {DOCS_URL} from '@remotion/serverless-client';+import {getAwsRegionMetadata} from './aws-region-metadata';import type {AwsRegion} from './regions';export const convertToServeUrlImplementation = ({@@ -20,5 +21,6 @@ export const convertToServeUrlImplementation = ({return urlOrId;}- return `https://${bucketName}.s3.${region}.amazonaws.com/sites/${urlOrId}/index.html`;+ const {dnsSuffix} = getAwsRegionMetadata(region);+ return `https://${bucketName}.s3.${region}.${dnsSuffix}/sites/${urlOrId}/index.html`;};diff --git a/packages/lambda-client/src/create-bucket.ts b/packages/lambda-client/src/create-bucket.tsindex 16581f63d1..2c66fc4c67 100644--- a/packages/lambda-client/src/create-bucket.ts+++ b/packages/lambda-client/src/create-bucket.ts@@ -7,6 +7,7 @@ import {} from '@aws-sdk/client-s3';import type {ProviderSpecifics} from '@remotion/serverless-client';import type {AwsProvider} from './aws-provider';+import {getAwsRegionMetadata} from './aws-region-metadata';import {getS3Client} from './get-s3-client';export const createBucket: ProviderSpecifics<AwsProvider>['createBucket'] =@@ -66,6 +67,7 @@ export const createBucket: ProviderSpecifics<AwsProvider>['createBucket'] =let usedBucketPolicy = false;try {+ const {partition} = getAwsRegionMetadata(region);const policy = JSON.stringify({Version: '2012-10-17',Statement: [@@ -74,7 +76,7 @@ export const createBucket: ProviderSpecifics<AwsProvider>['createBucket'] =Effect: 'Allow',Principal: '*',Action: 's3:GetObject',- Resource: `arn:aws:s3:::${bucketName}/*`,+ Resource: `arn:${partition}:s3:::${bucketName}/*`,},],});diff --git a/packages/lambda-client/src/get-aws-urls.ts b/packages/lambda-client/src/get-aws-urls.tsindex e0e37429d7..8fda23f27d 100644--- a/packages/lambda-client/src/get-aws-urls.ts+++ b/packages/lambda-client/src/get-aws-urls.ts@@ -3,6 +3,7 @@ import type {ServerlessRoutines,} from '@remotion/serverless-client';import type {AwsProvider} from './aws-provider';+import {getAwsRegionMetadata} from './aws-region-metadata';import {encodeAwsUrlParams} from './encode-aws-url-params';import type {AwsRegion} from './regions';@@ -15,7 +16,8 @@ const cloudWatchUrlWithQuery = ({functionNameToUse: string;query: string;}) => {- return `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${functionNameToUse}/log-events$3FfilterPattern$3D${encodeAwsUrlParams(+ const {consoleDomain} = getAwsRegionMetadata(region);+ return `https://${region}.${consoleDomain}/cloudwatch/home?region=${region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${functionNameToUse}/log-events$3FfilterPattern$3D${encodeAwsUrlParams(query,)}`;};@@ -46,7 +48,8 @@ export const getLambdaInsightsUrl = ({region: AwsRegion;functionName: string;}) => {- return `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#lambda-insights:functions/${functionName}`;+ const {consoleDomain} = getAwsRegionMetadata(region);+ return `https://${region}.${consoleDomain}/cloudwatch/home?region=${region}#lambda-insights:functions/${functionName}`;};export const getCloudwatchRendererUrl: GetLoggingUrlForRendererFunction<@@ -69,7 +72,10 @@ export const getS3RenderUrl = ({region: AwsRegion;bucketName: string;}) => {- return `https://s3.console.aws.amazon.com/s3/buckets/${bucketName}?region=${region}&prefix=renders/${renderId}/`;+ const {consoleDomain, partition} = getAwsRegionMetadata(region);+ const consoleHost =+ partition === 'aws' ? `s3.${consoleDomain}` : `${region}.${consoleDomain}`;+ return `https://${consoleHost}/s3/buckets/${bucketName}?region=${region}&prefix=renders/${renderId}/`;};export const getProgressJsonUrl = ({@@ -81,5 +87,28 @@ export const getProgressJsonUrl = ({bucketName: string;renderId: string;}) => {- return `https://${region}.console.aws.amazon.com/s3/object/${bucketName}?region=${region}&bucketType=general&prefix=renders/${renderId}/progress.json`;+ const {consoleDomain} = getAwsRegionMetadata(region);+ return `https://${region}.${consoleDomain}/s3/object/${bucketName}?region=${region}&bucketType=general&prefix=renders/${renderId}/progress.json`;+};++export const getLambdaFunctionUrl = ({+ region,+ functionName,+}: {+ region: AwsRegion;+ functionName: string;+}) => {+ const {consoleDomain} = getAwsRegionMetadata(region);+ return `https://${region}.${consoleDomain}/lambda/home#/functions/${functionName}?tab=code`;+};++export const getS3BucketUrl = ({+ region,+ bucketName,+}: {+ region: AwsRegion;+ bucketName: string;+}) => {+ const {consoleDomain} = getAwsRegionMetadata(region);+ return `https://${region}.${consoleDomain}/s3/buckets/${bucketName}/?region=${region}`;};diff --git a/packages/lambda-client/src/get-output-url-from-metadata.ts b/packages/lambda-client/src/get-output-url-from-metadata.tsindex 21ce95f17d..f52ca16442 100644--- a/packages/lambda-client/src/get-output-url-from-metadata.ts+++ b/packages/lambda-client/src/get-output-url-from-metadata.ts@@ -1,6 +1,7 @@import type {GetOutputUrl} from '@remotion/serverless-client';import {getExpectedOutName} from '@remotion/serverless-client';import type {AwsProvider} from './aws-provider';+import {getAwsRegionMetadata} from './aws-region-metadata';import {REMOTION_BUCKET_PREFIX} from './constants';export const getOutputUrlFromMetadata: GetOutputUrl<AwsProvider> = ({@@ -16,8 +17,9 @@ export const getOutputUrlFromMetadata: GetOutputUrl<AwsProvider> = ({bucketNamePrefix: REMOTION_BUCKET_PREFIX,});+ const {dnsSuffix} = getAwsRegionMetadata(currentRegion);return {- url: `https://s3.${currentRegion}.amazonaws.com/${renderBucketName}/${key}`,+ url: `https://s3.${currentRegion}.${dnsSuffix}/${renderBucketName}/${key}`,key,};};diff --git a/packages/lambda-client/src/index.ts b/packages/lambda-client/src/index.tsindex f88e4b471c..9e92eab1d1 100644--- a/packages/lambda-client/src/index.ts+++ b/packages/lambda-client/src/index.ts@@ -12,6 +12,10 @@ import {getStsClient,} from './aws-clients';import {awsImplementation} from './aws-provider';+import {+ getAwsPartitionMetadata,+ getAwsRegionMetadata,+} from './aws-region-metadata';import {parseJsonOrThrowSource} from './call-lambda-streaming';import {cleanItems} from './clean-items';import {@@ -24,6 +28,8 @@ import {internalDeleteRender} from './delete-render';import {getCloudwatchMethodUrl,getCloudwatchRendererUrl,+ getLambdaFunctionUrl,+ getS3BucketUrl,getS3RenderUrl,} from './get-aws-urls';import {getEnvVariable} from './get-env-variable';@@ -67,6 +73,11 @@ export type {} from '@remotion/serverless-client';export {appRouterWebhook, NextWebhookArgs} from './app-router-webhook';export {AwsProvider} from './aws-provider';+export type {+ AwsBillingCurrency,+ AwsPartition,+ AwsRegionMetadata,+} from './aws-region-metadata';export type {RenderProgress} from './constants';export {deleteFunction, DeleteFunctionInput} from './delete-function';export {deleteRender, type DeleteRenderInput} from './delete-render';@@ -120,6 +131,8 @@ export const LambdaClientInternals: {parseJsonOrThrowSource: typeof parseJsonOrThrowSource;getCloudwatchMethodUrl: typeof getCloudwatchMethodUrl;getCloudwatchRendererUrl: typeof getCloudwatchRendererUrl;+ getLambdaFunctionUrl: typeof getLambdaFunctionUrl;+ getS3BucketUrl: typeof getS3BucketUrl;MAX_EPHEMERAL_STORAGE_IN_MB: typeof MAX_EPHEMERAL_STORAGE_IN_MB;parseFunctionName: typeof parseFunctionName;isFlakyError: typeof isFlakyError;@@ -149,6 +162,8 @@ export const LambdaClientInternals: {makeLambdaRenderStillPayload: typeof makeLambdaRenderStillPayload;getRenderProgressPayload: typeof getRenderProgressPayload;innerSpeculateFunctionName: typeof innerSpeculateFunctionName;+ getAwsPartitionMetadata: typeof getAwsPartitionMetadata;+ getAwsRegionMetadata: typeof getAwsRegionMetadata;} = {generateRandomHashWithLifeCycleRule,getLambdaClient,@@ -161,6 +176,8 @@ export const LambdaClientInternals: {parseJsonOrThrowSource,getCloudwatchMethodUrl,getCloudwatchRendererUrl,+ getLambdaFunctionUrl,+ getS3BucketUrl,MAX_EPHEMERAL_STORAGE_IN_MB,parseFunctionName,isFlakyError,@@ -190,4 +207,6 @@ export const LambdaClientInternals: {makeLambdaRenderStillPayload,getRenderProgressPayload,innerSpeculateFunctionName,+ getAwsPartitionMetadata,+ getAwsRegionMetadata,};diff --git a/packages/lambda-client/src/make-lambda-payload.ts b/packages/lambda-client/src/make-lambda-payload.tsindex 00a84b4574..214261e8bf 100644--- a/packages/lambda-client/src/make-lambda-payload.ts+++ b/packages/lambda-client/src/make-lambda-payload.ts@@ -340,7 +340,9 @@ export const makeLambdaRenderStillPayload = async ({offthreadVideoCacheSizeInBytes,deleteAfter,type: ServerlessRoutines.still,- streamed: true,+ streamed:+ awsImplementation.getRendererFunctionTransport(region) ===+ 'response-streaming',forcePathStyle,licenseKey: licenseKey ?? null,offthreadVideoThreads: offthreadVideoThreads ?? null,diff --git a/packages/lambda-client/src/make-s3-url.ts b/packages/lambda-client/src/make-s3-url.tsindex bab1ca4747..d4573bb6c4 100644--- a/packages/lambda-client/src/make-s3-url.ts+++ b/packages/lambda-client/src/make-s3-url.ts@@ -1,3 +1,4 @@+import {getAwsRegionMetadata} from './aws-region-metadata';import type {AwsRegion} from './regions';export const makeS3ServeUrl = ({@@ -9,5 +10,6 @@ export const makeS3ServeUrl = ({subFolder: string;region: AwsRegion;}): string => {- return `https://${bucketName}.s3.${region}.amazonaws.com/${subFolder}/index.html`;+ const {dnsSuffix} = getAwsRegionMetadata(region);+ return `https://${bucketName}.s3.${region}.${dnsSuffix}/${subFolder}/index.html`;};diff --git a/packages/lambda-client/src/price-per-1s.ts b/packages/lambda-client/src/price-per-1s.tsindex cbe30dd296..837e2011cb 100644--- a/packages/lambda-client/src/price-per-1s.ts+++ b/packages/lambda-client/src/price-per-1s.ts@@ -2,42 +2,29 @@import type {AwsRegion} from './regions';+type Price = {+ rateCode?: string;+ price: string;+};+export const pricing: {[key in AwsRegion]: {- 'Lambda Duration': {- rateCode: string;- price: string;- };- 'Lambda Duration-Provisioned': {- rateCode: string;- price: string;- };- 'Lambda Provisioned-Concurrency': {- rateCode: string;- price: string;- };- 'Lambda Requests': {- rateCode: string;- price: string;- };- 'Lambda Duration-ARM': {- rateCode: string;- price: string;- };- 'Lambda Requests-ARM': {- rateCode: string;- price: string;- };- 'Lambda Storage-Duration': {- rateCode: string;- price: string;- };- 'Lambda Storage-Duration-ARM': {- rateCode: string;- price: string;- };+ 'Lambda Requests': Price;+ 'Lambda Duration-ARM': Price;+ 'Lambda Storage-Duration-ARM': Price;+ [key: string]: Price;};} = {+ 'cn-north-1': {+ 'Lambda Requests': {price: '0.00000136'},+ 'Lambda Duration-ARM': {price: '0.000090800'},+ 'Lambda Storage-Duration-ARM': {price: '0.0000002303'},+ },+ 'cn-northwest-1': {+ 'Lambda Requests': {price: '0.00000136'},+ 'Lambda Duration-ARM': {price: '0.000090800'},+ 'Lambda Storage-Duration-ARM': {price: '0.0000002049'},+ },'af-south-1': {'Lambda Duration-Provisioned': {rateCode: 'X7CK6KFXNWY9RF6Z.JRTCKXETXF.6YS6EN2CT7',diff --git a/packages/lambda-client/src/regions.ts b/packages/lambda-client/src/regions.tsindex 3659dc2a6c..10d77629b5 100644--- a/packages/lambda-client/src/regions.ts+++ b/packages/lambda-client/src/regions.ts@@ -41,6 +41,8 @@ export const AWS_REGIONS = ['ap-southeast-4','ap-southeast-5','ca-central-1',+ 'cn-north-1',+ 'cn-northwest-1','sa-east-1',] as const;diff --git a/packages/lambda-client/src/render-still-on-lambda.ts b/packages/lambda-client/src/render-still-on-lambda.tsindex 7730715188..17c6ed534b 100644--- a/packages/lambda-client/src/render-still-on-lambda.ts+++ b/packages/lambda-client/src/render-still-on-lambda.ts@@ -81,52 +81,75 @@ const innerRenderStillOnLambda = async (const {functionName, region, onInit} = input;try {const payload = await makeLambdaRenderStillPayload(input);- const res = await new Promise<- RenderStillFunctionResponsePayload<AwsProvider>- >((resolve, reject) => {- awsImplementation- .callFunctionStreaming<ServerlessRoutines.still>({+ const res = payload.streamed+ ? await new Promise<RenderStillFunctionResponsePayload<AwsProvider>>(+ (resolve, reject) => {+ awsImplementation+ .callFunctionStreaming<ServerlessRoutines.still>({+ functionName,+ type: ServerlessRoutines.still,+ payload,+ region,+ receivedStreamingPayload: ({message}) => {+ if (message.type === 'render-id-determined') {+ onInit?.({+ renderId: message.payload.renderId,+ cloudWatchLogs: getCloudwatchMethodUrl({+ functionName,+ method: ServerlessRoutines.still,+ region,+ rendererFunctionName: null,+ renderId: message.payload.renderId,+ }),+ lambdaInsightsUrl: getLambdaInsightsUrl({+ functionName,+ region,+ }),+ });+ }++ if (message.type === 'error-occurred') {+ reject(new Error(message.payload.error));+ }++ if (message.type === 'still-rendered') {+ resolve(message.payload);+ }+ },+ timeoutInTest: 120000,+ retriesRemaining: input.maxRetries,+ requestHandler: input.requestHandler,+ })+ .then(() => {+ reject(new Error('Expected response to be streamed'));+ })+ .catch((err) => {+ reject(err);+ });+ },+ )+ : ((await awsImplementation.callFunctionSync<ServerlessRoutines.still>({functionName,type: ServerlessRoutines.still,payload,region,- receivedStreamingPayload: ({message}) => {- if (message.type === 'render-id-determined') {- onInit?.({- renderId: message.payload.renderId,- cloudWatchLogs: getCloudwatchMethodUrl({- functionName,- method: ServerlessRoutines.still,- region,- rendererFunctionName: null,- renderId: message.payload.renderId,- }),- lambdaInsightsUrl: getLambdaInsightsUrl({- functionName,- region,- }),- });- }-- if (message.type === 'error-occurred') {- reject(new Error(message.payload.error));- }-- if (message.type === 'still-rendered') {- resolve(message.payload);- }- },timeoutInTest: 120000,- retriesRemaining: input.maxRetries,requestHandler: input.requestHandler,- })- .then(() => {- reject(new Error('Expected response to be streamed'));- })- .catch((err) => {- reject(err);- });- });+ })) as unknown as RenderStillFunctionResponsePayload<AwsProvider>);++ if (!payload.streamed) {+ onInit?.({+ renderId: res.renderId,+ cloudWatchLogs: getCloudwatchMethodUrl({+ functionName,+ method: ServerlessRoutines.still,+ region,+ rendererFunctionName: null,+ renderId: res.renderId,+ }),+ lambdaInsightsUrl: getLambdaInsightsUrl({functionName, region}),+ });+ }return {estimatedPrice: res.estimatedPrice,diff --git a/packages/lambda-client/src/test/aws-china-regions.test.ts b/packages/lambda-client/src/test/aws-china-regions.test.tsnew file mode 100644index 0000000000..3144e13853--- /dev/null+++ b/packages/lambda-client/src/test/aws-china-regions.test.ts@@ -0,0 +1,158 @@+import {expect, test} from 'bun:test';+import {ServerlessRoutines} from '@remotion/serverless-client';+import {awsImplementation} from '../aws-provider';+import {getAwsRegionMetadata} from '../aws-region-metadata';+import {convertToServeUrlImplementation} from '../convert-to-serve-url';+import {+ getCloudwatchMethodUrl,+ getLambdaFunctionUrl,+ getLambdaInsightsUrl,+ getProgressJsonUrl,+ getS3BucketUrl,+ getS3RenderUrl,+} from '../get-aws-urls';+import {getOutputUrlFromMetadata} from '../get-output-url-from-metadata';+import {makeLambdaRenderStillPayload} from '../make-lambda-payload';+import {makeS3ServeUrl} from '../make-s3-url';+import {AWS_REGIONS, DEFAULT_AWS_REGIONS} from '../regions';++const chinaMetadata = {+ partition: 'aws-cn',+ dnsSuffix: 'amazonaws.com.cn',+ consoleDomain: 'console.amazonaws.cn',+ billingCurrency: 'CNY',+} as const;++test('AWS region metadata is exhaustive for China without changing defaults', () => {+ expect(getAwsRegionMetadata('cn-north-1')).toEqual(chinaMetadata);+ expect(getAwsRegionMetadata('cn-northwest-1')).toEqual(chinaMetadata);+ expect(getAwsRegionMetadata('us-east-1')).toEqual({+ partition: 'aws',+ dnsSuffix: 'amazonaws.com',+ consoleDomain: 'console.aws.amazon.com',+ billingCurrency: 'USD',+ });+ expect(AWS_REGIONS).toContain('cn-north-1');+ expect(AWS_REGIONS).toContain('cn-northwest-1');+ expect(DEFAULT_AWS_REGIONS).not.toContain('cn-north-1' as never);+ expect(awsImplementation.getRendererFunctionTransport('cn-north-1')).toBe(+ 's3',+ );+ expect(awsImplementation.getRendererFunctionTransport('cn-northwest-1')).toBe(+ 's3',+ );+ expect(awsImplementation.getRendererFunctionTransport('us-east-1')).toBe(+ 'response-streaming',+ );+});++test('China still payload uses buffered invocation', async () => {+ const base = {+ functionName: 'function',+ serveUrl: 'https://example.com',+ composition: 'composition',+ inputProps: {},+ imageFormat: 'png',+ privacy: 'private',+ maxRetries: 1,+ envVariables: {},+ frame: 0,+ outName: null,+ chromiumOptions: {},+ downloadBehavior: {type: 'play-in-browser'},+ forceWidth: null,+ forceHeight: null,+ forceFps: null,+ forceDurationInFrames: null,+ forceBucketName: null,+ onInit: () => undefined,+ indent: false,+ forcePathStyle: false,+ storageClass: null,+ requestHandler: null,+ isProduction: null,+ jpegQuality: 80,+ logLevel: 'info',+ offthreadVideoCacheSizeInBytes: null,+ scale: 1,+ timeoutInMilliseconds: 30000,+ licenseKey: null,+ offthreadVideoThreads: null,+ mediaCacheSizeInBytes: null,+ deleteAfter: null,+ } as const;+ const china = await makeLambdaRenderStillPayload({+ ...base,+ region: 'cn-north-1',+ });+ const standard = await makeLambdaRenderStillPayload({+ ...base,+ region: 'us-east-1',+ });++ expect(china.streamed).toBe(false);+ expect(standard.streamed).toBe(true);+});++test('AWS service and Console URLs use the region partition metadata', () => {+ expect(+ makeS3ServeUrl({+ bucketName: 'bucket',+ subFolder: 'sites/site',+ region: 'cn-north-1',+ }),+ ).toBe('https://bucket.s3.cn-north-1.amazonaws.com.cn/sites/site/index.html');+ expect(+ convertToServeUrlImplementation({+ bucketName: 'bucket',+ urlOrId: 'site',+ region: 'cn-north-1',+ }),+ ).toBe('https://bucket.s3.cn-north-1.amazonaws.com.cn/sites/site/index.html');+ expect(+ getOutputUrlFromMetadata({+ bucketName: 'bucket',+ customCredentials: null,+ currentRegion: 'cn-north-1',+ renderMetadata: {+ outName: 'out.mp4',+ privacy: 'public',+ renderId: 'render-id',+ } as never,+ }),+ ).toEqual({+ key: 'renders/render-id/out.mp4',+ url: 'https://s3.cn-north-1.amazonaws.com.cn/bucket/renders/render-id/out.mp4',+ });++ const consoleUrls = [+ getCloudwatchMethodUrl({+ region: 'cn-north-1',+ functionName: 'fn',+ method: ServerlessRoutines.start,+ rendererFunctionName: null,+ renderId: 'render-id',+ }),+ getLambdaInsightsUrl({region: 'cn-north-1', functionName: 'fn'}),+ getS3RenderUrl({+ region: 'cn-north-1',+ bucketName: 'bucket',+ renderId: 'render-id',+ }),+ getProgressJsonUrl({+ region: 'cn-north-1',+ bucketName: 'bucket',+ renderId: 'render-id',+ }),+ getLambdaFunctionUrl({region: 'cn-north-1', functionName: 'fn'}),+ getS3BucketUrl({region: 'cn-north-1', bucketName: 'bucket'}),+ ];+ for (const url of consoleUrls) {+ expect(url).toContain('console.amazonaws.cn');+ expect(url).toContain('cn-north-1');+ }++ expect(getLambdaFunctionUrl({region: 'us-east-1', functionName: 'fn'})).toBe(+ 'https://us-east-1.console.aws.amazon.com/lambda/home#/functions/fn?tab=code',+ );+});diff --git a/packages/lambda-client/src/test/price-calculation.test.ts b/packages/lambda-client/src/test/price-calculation.test.tsindex a5625913f7..0a315e4fec 100644--- a/packages/lambda-client/src/test/price-calculation.test.ts+++ b/packages/lambda-client/src/test/price-calculation.test.ts@@ -1,6 +1,7 @@import {expect, test} from 'bun:test';import {estimatePriceFromMetadata} from '@remotion/serverless-client';import {awsImplementation} from '../aws-provider';+import {estimatePrice} from '../estimate-price';test('Should not throw while calculating prices when time shifts occur', () => {const aDate = Date.now();@@ -61,3 +62,22 @@ test('Should not throw while calculating prices when time shifts occur', () => {});expect(price?.accruedSoFar).toBeGreaterThanOrEqual(0);});++test('China prices use CNY ARM duration, request, and regional storage rates', () => {+ const input = {+ memorySizeInMb: 1024,+ diskSizeInMb: 10240,+ lambdasInvoked: 100,+ durationInMilliseconds: 1_000_000,+ };+ const beijing = estimatePrice({...input, region: 'cn-north-1'});+ const ningxia = estimatePrice({...input, region: 'cn-northwest-1'});++ expect(beijing).toBe(0.09312);+ expect(ningxia).toBe(0.09288);+ expect(beijing).toBeGreaterThan(ningxia);++ expect(+ estimatePrice({...input, diskSizeInMb: 512, region: 'cn-north-1'}),+ ).toBe(0.09094);+});diff --git a/packages/lambda/src/admin/make-layer-public.ts b/packages/lambda/src/admin/make-layer-public.tsindex 9ba53dcfa1..19c09749ea 100644--- a/packages/lambda/src/admin/make-layer-public.ts+++ b/packages/lambda/src/admin/make-layer-public.ts@@ -82,7 +82,7 @@ const makeLayerPublic = async () => {const skipRegions = parseSkipFlag();const regions = onlyRegion? [onlyRegion]- : getRegions().filter((r) => !skipRegions.includes(r));+ : getRegions().filter((r) => r in layerInfo && !skipRegions.includes(r));if (onlyRegion) {console.log(`Filtering to region: ${onlyRegion}`);}@@ -92,6 +92,11 @@ const makeLayerPublic = async () => {}for (const region of regions) {+ if (!(region in layerInfo)) {+ throw new Error(`Remotion-hosted Layers are not supported in ${region}.`);+ }++ const hostedLayerRegion = region as keyof HostedLayers;for (const layer of layers) {const layerName = `remotion-binaries-${layer}-arm64`;const {Version, LayerArn} = await LambdaClientInternals.getLambdaClient(@@ -132,10 +137,6 @@ const makeLayerPublic = async () => {StatementId: 'public-layer',}),);- if (!layerInfo[region as AwsRegion]) {- layerInfo[region as AwsRegion] = [];- }-if (!LayerArn) {throw new Error('layerArn is null');}@@ -144,7 +145,7 @@ const makeLayerPublic = async () => {throw new Error('Version is null');}- layerInfo[region].push({+ layerInfo[hostedLayerRegion].push({layerArn: LayerArn,version: Version,});diff --git a/packages/lambda/src/api/create-function.ts b/packages/lambda/src/api/create-function.tsindex 8c7d5e4a0a..7db7deb1d1 100644--- a/packages/lambda/src/api/create-function.ts+++ b/packages/lambda/src/api/create-function.ts@@ -7,9 +7,11 @@ import type {VpcConfig} from '@aws-sdk/client-lambda';import {CreateFunctionCommand,GetFunctionCommand,+ GetFunctionConfigurationCommand,PutFunctionEventInvokeConfigCommand,PutRuntimeManagementConfigCommand,TagResourceCommand,+ UpdateFunctionConfigurationCommand,} from '@aws-sdk/client-lambda';import type {RequestHandler} from '@remotion/lambda-client';import {@@ -37,6 +39,7 @@ type CreateFunctionInput = {retentionInDays: number;ephemerealStorageInMb: number;customRoleArn: string;+ customLayerArns: string[] | null;enableLambdaInsights: boolean;logLevel: LogLevel;vpcSubnetIds: string;@@ -57,6 +60,7 @@ export const createFunction = async ({retentionInDays,ephemerealStorageInMb,customRoleArn,+ customLayerArns,enableLambdaInsights,logLevel,vpcSubnetIds,@@ -113,20 +117,93 @@ export const createFunction = async ({);}+ const insightsLayer = enableLambdaInsights+ ? lambdaInsightsExtensions[region]+ : null;+ if (enableLambdaInsights && !insightsLayer) {+ throw new Error(+ `Lambda Insights is not supported by AWS in region ${region}. Please disable Lambda Insights. See http://remotion.dev/docs/lambda/insights#unsupported-regions`,+ );+ }++ const layers = (+ customLayerArns ??+ getLayers({+ option: runtimePreference,+ region,+ }).map(({layerArn, version}) => `${layerArn}:${version}`)+ ).concat(insightsLayer ? [insightsLayer] : []);+if (alreadyCreated) {RenderInternals.Log.verbose({indent: false, logLevel},`Function ${functionName} already existed`,);++ if (customLayerArns === null) {+ return {FunctionName: functionName};+ }++ const lambdaClient = LambdaClientInternals.getLambdaClient(+ region,+ undefined,+ requestHandler,+ );+ const currentConfiguration = await lambdaClient.send(+ new GetFunctionConfigurationCommand({FunctionName: functionName}),+ );+ const currentLayers = (currentConfiguration.Layers ?? []).map(+ (layer) => layer.Arn as string,+ );+ const layersAreEqual =+ currentLayers.length === layers.length &&+ currentLayers.every((layer, index) => layer === layers[index]);++ if (layersAreEqual) {+ return {FunctionName: functionName};+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `Updating Layers for function ${functionName}`,+ );+ await lambdaClient.send(+ new UpdateFunctionConfigurationCommand({+ FunctionName: functionName,+ Layers: layers,+ }),+ );++ while (true) {+ const configuration = await lambdaClient.send(+ new GetFunctionConfigurationCommand({FunctionName: functionName}),+ );+ if (+ configuration.State === 'Failed' ||+ configuration.LastUpdateStatus === 'Failed'+ ) {+ throw new Error(+ `Failed to update Layers for function ${functionName}: ${configuration.StateReason ?? configuration.LastUpdateStatusReason ?? 'Unknown reason'}`,+ );+ }++ if (+ configuration.State === 'Active' &&+ configuration.LastUpdateStatus !== 'InProgress'+ ) {+ break;+ }++ await new Promise<void>((resolve) => {+ setTimeout(resolve, 1000);+ });+ }+return {FunctionName: functionName};}- const defaultRoleName = `arn:aws:iam::${accountId}:role/${ROLE_NAME}`;-- const layers = getLayers({- option: runtimePreference,- region,- });+ const {partition} = LambdaClientInternals.getAwsRegionMetadata(region);+ const defaultRoleName = `arn:${partition}:iam::${accountId}:role/${ROLE_NAME}`;let vpcConfig: VpcConfig | undefined;if (vpcSubnetIds && vpcSecurityGroupIds) {@@ -141,15 +218,6 @@ export const createFunction = async ({'Deploying new Lambda function',);- const insightsLayer = enableLambdaInsights- ? lambdaInsightsExtensions[region]- : null;- if (enableLambdaInsights && !insightsLayer) {- throw new Error(- `Lambda Insights is not supported by AWS in region ${region}. Please disable Lambda Insights. See http://remotion.dev/docs/lambda/insights#unsupported-regions`,- );- }-const {FunctionName, FunctionArn} =await LambdaClientInternals.getLambdaClient(region,@@ -167,9 +235,7 @@ export const createFunction = async ({Description: 'Renders a Remotion video.',MemorySize: memorySizeInMb,Timeout: timeoutInSeconds,- Layers: layers- .map(({layerArn, version}) => `${layerArn}:${version}`)- .concat(insightsLayer ? [insightsLayer] : []),+ Layers: layers,Architectures: ['arm64'],EphemeralStorage: {Size: ephemerealStorageInMb,@@ -236,6 +302,7 @@ export const createFunction = async ({);let state = 'Pending';+ let currentRuntimeVersionArn: string | null = null;while (state === 'Pending') {const getFn = await LambdaClientInternals.getLambdaClient(@@ -251,6 +318,8 @@ export const createFunction = async ({setTimeout(() => resolve(), 1000);});state = getFn.Configuration?.State as string;+ currentRuntimeVersionArn =+ getFn.Configuration?.RuntimeVersionConfig?.RuntimeVersionArn ?? null;}RenderInternals.Log.verbose(@@ -263,9 +332,16 @@ export const createFunction = async ({'Locking the runtime version of the function...',);- const RuntimeVersionArn = `arn:aws:lambda:${region}::runtime:58a37e8413ed69058c4ac3b1df642118591f17d40def93d6101f867c72cd03c2`;+ const runtimeVersionArn =+ partition === 'aws-cn'+ ? currentRuntimeVersionArn+ : `arn:aws:lambda:${region}::runtime:58a37e8413ed69058c4ac3b1df642118591f17d40def93d6101f867c72cd03c2`;try {+ if (!runtimeVersionArn) {+ throw new Error('AWS did not return a runtime version ARN.');+ }+await LambdaClientInternals.getLambdaClient(region,undefined,@@ -274,19 +350,19 @@ export const createFunction = async ({new PutRuntimeManagementConfigCommand({FunctionName,UpdateRuntimeOn: 'Manual',- RuntimeVersionArn,+ RuntimeVersionArn: runtimeVersionArn,}),);++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `Function runtime is locked to ${runtimeVersionArn}`,+ );} catch {console.warn('⚠️ Could not lock the runtime version. We recommend to update your policies to prevent your functions from breaking in the future in case the AWS runtime changes. See https://remotion.dev/docs/lambda/feb-2023-incident for an example on how to update your policy.',);}- RenderInternals.Log.verbose(- {indent: false, logLevel},- `Function runtime is locked to ${RuntimeVersionArn}`,- );-return {FunctionName: FunctionName as string};};diff --git a/packages/lambda/src/api/deploy-function.ts b/packages/lambda/src/api/deploy-function.tsindex d921e9869f..ad2e7272ce 100644--- a/packages/lambda/src/api/deploy-function.ts+++ b/packages/lambda/src/api/deploy-function.ts@@ -16,6 +16,7 @@ import {VERSION} from 'remotion/version';import {awsFullClientSpecifics} from '../functions/full-client-implementation';import {FUNCTION_ZIP_ARM64} from '../shared/function-zip-path';import {validateRuntimePreference} from '../shared/get-layers';+import {validateCustomLayerArns} from '../shared/validate-custom-layer-arns';import {validateCustomRoleArn} from '../shared/validate-custom-role-arn';import {validateCloudWatchRetentionPeriod} from '../shared/validate-retention-period';import {validateTimeout} from '../shared/validate-timeout';@@ -41,7 +42,9 @@ type OptionalParameters = {};export type DeployFunctionInput = MandatoryParameters &- Partial<OptionalParameters>;+ Partial<OptionalParameters> & {+ customLayerArns?: string[];+ };export type DeployFunctionOutput = {functionName: string;@@ -51,6 +54,7 @@ export type DeployFunctionOutput = {export const internalDeployFunction = async <Provider extends CloudProvider>(params: MandatoryParameters &OptionalParameters & {+ customLayerArns: string[] | null;providerSpecifics: ProviderSpecifics<Provider>;fullClientSpecifics: FullClientSpecifics<Provider>;},@@ -62,6 +66,12 @@ export const internalDeployFunction = async <Provider extends CloudProvider>(LambdaClientInternals.validateDiskSizeInMb(params.diskSizeInMb);validateCustomRoleArn(params.customRoleArn);validateRuntimePreference(params.runtimePreference);+ validateCustomLayerArns({+ customLayerArns: params.customLayerArns,+ enableLambdaInsights: params.enableLambdaInsights,+ region: params.region,+ runtimePreference: params.runtimePreference,+ });const functionName = speculateFunctionName({diskSizeInMb: params.diskSizeInMb,@@ -99,6 +109,7 @@ export const internalDeployFunction = async <Provider extends CloudProvider>(alreadyCreated: Boolean(alreadyDeployed),ephemerealStorageInMb: params.diskSizeInMb,customRoleArn: params.customRoleArn as string,+ customLayerArns: params.customLayerArns,enableLambdaInsights: params.enableLambdaInsights ?? false,logLevel: params.logLevel,vpcSubnetIds: params.vpcSubnetIds as string,@@ -130,6 +141,7 @@ export const deployFunction = ({timeoutInSeconds,cloudWatchLogRetentionPeriodInDays,customRoleArn,+ customLayerArns,enableLambdaInsights,indent,logLevel,@@ -154,6 +166,7 @@ export const deployFunction = ({logLevel: logLevel ?? 'info',createCloudWatchLogGroup,customRoleArn: customRoleArn ?? undefined,+ customLayerArns: customLayerArns ?? null,diskSizeInMb: diskSizeInMb ?? DEFAULT_EPHEMERAL_STORAGE_IN_MB,enableLambdaInsights: enableLambdaInsights ?? false,memorySizeInMb,diff --git a/packages/lambda/src/api/iam-validation/resolve-caller-arn.ts b/packages/lambda/src/api/iam-validation/resolve-caller-arn.tsnew file mode 100644index 0000000000..8e2ea85391--- /dev/null+++ b/packages/lambda/src/api/iam-validation/resolve-caller-arn.ts@@ -0,0 +1,45 @@+import type {AwsPartition, AwsRegion} from '@remotion/lambda-client';++export const resolveCallerArnForSimulation = ({+ callerIdentityArn,+ region,+ regionPartition,+}: {+ callerIdentityArn: string;+ region: AwsRegion;+ regionPartition: AwsPartition;+}): string => {+ const components = callerIdentityArn.match(+ /^arn:([^:]+):([^:]+)::(\d+):([^/]+)(.*)$/,+ );+ if (!components) {+ throw new Error('Unknown AWS Caller Identity ARN detected');+ }++ const callerPartition = components[1];+ if (callerPartition !== regionPartition) {+ throw new Error(+ `AWS Caller Identity partition ${callerPartition} does not match region ${region}, which uses partition ${regionPartition}.`,+ );+ }++ const service = components[2];+ const accountId = components[3];+ const resourceType = components[4];+ if (service === 'iam' && resourceType === 'user') {+ return callerIdentityArn;+ }++ if (service === 'sts' && resourceType === 'assumed-role') {+ const assumedRoleComponents = components[5].match(/^\/([^/]+)\/(.*)$/);+ if (!assumedRoleComponents) {+ throw new Error(+ 'Unsupported AWS Caller Identity as Assumed-Role ARN detected',+ );+ }++ return `arn:${callerPartition}:iam::${accountId}:role/${assumedRoleComponents[1]}`;+ }++ throw new Error('Unsupported AWS Caller Identity ARN detected');+};diff --git a/packages/lambda/src/api/iam-validation/role-permissions.ts b/packages/lambda/src/api/iam-validation/role-permissions.tsindex df0b5d24d4..69d03a553d 100644--- a/packages/lambda/src/api/iam-validation/role-permissions.ts+++ b/packages/lambda/src/api/iam-validation/role-permissions.ts@@ -1,3 +1,4 @@+import type {AwsPartition} from '@remotion/lambda-client';import {LAMBDA_INSIGHTS_PREFIX,LOG_GROUP_PREFIX,@@ -5,10 +6,14 @@ import {RENDER_FN_PREFIX,} from '@remotion/lambda-client/constants';-export const rolePermissions: {+export type RolePermission = {actions: string[];resource: string[];-}[] = [+};++export const getRolePermissions = (+ partition: AwsPartition,+): RolePermission[] => [{actions: ['s3:ListAllMyBuckets'],resource: ['*'],@@ -24,21 +29,23 @@ export const rolePermissions: {'s3:PutObject','s3:GetBucketLocation',],- resource: [`arn:aws:s3:::${REMOTION_BUCKET_PREFIX}*`],+ resource: [`arn:${partition}:s3:::${REMOTION_BUCKET_PREFIX}*`],},{actions: ['lambda:InvokeFunction'],- resource: [`arn:aws:lambda:*:*:function:${RENDER_FN_PREFIX}*`],+ resource: [`arn:${partition}:lambda:*:*:function:${RENDER_FN_PREFIX}*`],},{actions: ['logs:CreateLogGroup'],- resource: [`arn:aws:logs:*:*:log-group:${LAMBDA_INSIGHTS_PREFIX}`],+ resource: [`arn:${partition}:logs:*:*:log-group:${LAMBDA_INSIGHTS_PREFIX}`],},{actions: ['logs:CreateLogStream', 'logs:PutLogEvents'],resource: [- `arn:aws:logs:*:*:log-group:${LOG_GROUP_PREFIX}${RENDER_FN_PREFIX}*`,- `arn:aws:logs:*:*:log-group:${LAMBDA_INSIGHTS_PREFIX}:*`,+ `arn:${partition}:logs:*:*:log-group:${LOG_GROUP_PREFIX}${RENDER_FN_PREFIX}*`,+ `arn:${partition}:logs:*:*:log-group:${LAMBDA_INSIGHTS_PREFIX}:*`,],},];++export const rolePermissions = getRolePermissions('aws');diff --git a/packages/lambda/src/api/iam-validation/simulate.ts b/packages/lambda/src/api/iam-validation/simulate.tsindex d2c9db5982..039198e39b 100644--- a/packages/lambda/src/api/iam-validation/simulate.ts+++ b/packages/lambda/src/api/iam-validation/simulate.ts@@ -1,9 +1,10 @@import {GetCallerIdentityCommand} from '@aws-sdk/client-sts';import type {AwsRegion, RequestHandler} from '@remotion/lambda-client';import {LambdaClientInternals} from '@remotion/lambda-client';+import {resolveCallerArnForSimulation} from './resolve-caller-arn';import type {EvalDecision, SimulationResult} from './simulate-rule';import {simulateRule} from './simulate-rule';-import {requiredPermissions} from './user-permissions';+import {getRequiredPermissions} from './user-permissions';const getEmojiForStatus = (decision: EvalDecision) => {switch (decision) {@@ -44,41 +45,17 @@ export const simulatePermissions = async (throw new Error('No valid AWS Caller Identity detected');}- const callerIdentityArnComponents = callerIdentity.Arn.match(- /arn:aws:([^:]+)::(\d+):([^/]+)(.*)/,- );- if (!callerIdentityArnComponents) {- throw new Error('Unknown AWS Caller Identity ARN detected');- }-- const callerIdentityArnType = callerIdentityArnComponents[1];-- let callerArn;- if (- callerIdentityArnType === 'iam' &&- callerIdentityArnComponents[3] === 'user'- ) {- callerArn = callerIdentity.Arn as string;- } else if (- callerIdentityArnType === 'sts' &&- callerIdentityArnComponents[3] === 'assumed-role'- ) {- const assumedRoleComponents =- callerIdentityArnComponents[4].match(/\/([^/]+)\/(.*)/);- if (!assumedRoleComponents) {- throw new Error(- 'Unsupported AWS Caller Identity as Assumed-Role ARN detected',- );- }-- callerArn = `arn:aws:iam::${callerIdentityArnComponents[2]}:role/${assumedRoleComponents[1]}`;- } else {- throw new Error('Unsupported AWS Caller Identity ARN detected');- }+ const {partition: regionPartition} =+ LambdaClientInternals.getAwsRegionMetadata(options.region);+ const callerArn = resolveCallerArnForSimulation({+ callerIdentityArn: callerIdentity.Arn,+ region: options.region,+ regionPartition,+ });const results: SimulationResult[] = [];- for (const per of requiredPermissions) {+ for (const per of getRequiredPermissions(regionPartition)) {const result = await simulateRule({actionNames: per.actions,arn: callerArn,diff --git a/packages/lambda/src/api/iam-validation/suggested-policy.ts b/packages/lambda/src/api/iam-validation/suggested-policy.tsindex 8978953c5b..07c928df5b 100644--- a/packages/lambda/src/api/iam-validation/suggested-policy.ts+++ b/packages/lambda/src/api/iam-validation/suggested-policy.ts@@ -1,40 +1,41 @@-import {rolePermissions} from './role-permissions';-import {requiredPermissions} from './user-permissions';+import type {AwsPartition} from '@remotion/lambda-client';+import {getRolePermissions} from './role-permissions';+import {getRequiredPermissions} from './user-permissions';-const suggestedPolicy = {- Version: '2012-10-17',- Statement: [- ...requiredPermissions.map((per) => {- return {- Sid: per.id,- Effect: 'Allow',- Action: per.actions,- Resource: per.resource,- };- }),- ],+export type GetPolicyOptions = {+ partition?: AwsPartition;};-const suggestedRolePolicy = {+const makePolicy = (partition: AwsPartition) => ({Version: '2012-10-17',- Statement: [- ...rolePermissions.map((per, i) => {- return {- Sid: String(i),- Effect: 'Allow',- Action: per.actions,- Resource: per.resource,- };- }),- ],-};+ Statement: getRequiredPermissions(partition).map((per) => {+ return {+ Sid: per.id,+ Effect: 'Allow',+ Action: per.actions,+ Resource: per.resource,+ };+ }),+});++const makeRolePolicy = (partition: AwsPartition) => ({+ Version: '2012-10-17',+ Statement: getRolePermissions(partition).map((per, i) => {+ return {+ Sid: String(i),+ Effect: 'Allow',+ Action: per.actions,+ Resource: per.resource,+ };+ }),+});/** @description Returns an inline JSON policy to be assigned to the AWS user whose credentials are being used for executing CLI commands or calling Node.JS functions.* @see [Documentation](https://remotion.dev/docs/lambda/getuserpolicy)*/--export const getUserPolicy = () => JSON.stringify(suggestedPolicy, null, 2);+export const getUserPolicy = (options?: GetPolicyOptions) =>+ JSON.stringify(makePolicy(options?.partition ?? 'aws'), null, 2);export const ROLE_NAME = 'remotion-lambda-role';@@ -42,4 +43,5 @@ export const ROLE_NAME = 'remotion-lambda-role';* @description Returns an inline JSON policy to be assigned to the 'remotion-lambda-role' role that needs to be created in your AWS account.* @see [Documentation](https://remotion.dev/docs/lambda/getrolepolicy)*/-export const getRolePolicy = () => JSON.stringify(suggestedRolePolicy, null, 2);+export const getRolePolicy = (options?: GetPolicyOptions) =>+ JSON.stringify(makeRolePolicy(options?.partition ?? 'aws'), null, 2);diff --git a/packages/lambda/src/api/iam-validation/user-permissions.ts b/packages/lambda/src/api/iam-validation/user-permissions.tsindex 918d3a0a08..29a6f21ae1 100644--- a/packages/lambda/src/api/iam-validation/user-permissions.ts+++ b/packages/lambda/src/api/iam-validation/user-permissions.ts@@ -1,3 +1,4 @@+import type {AwsPartition} from '@remotion/lambda-client';import {LOG_GROUP_PREFIX,REMOTION_BUCKET_PREFIX,@@ -5,11 +6,15 @@ import {} from '@remotion/lambda-client/constants';import {REMOTION_HOSTED_LAYER_ARN} from '../../shared/hosted-layers';-export const requiredPermissions: {+export type RequiredPermission = {actions: string[];resource: string[];id: string;-}[] = [+};++export const getRequiredPermissions = (+ partition: AwsPartition,+): RequiredPermission[] => [{id: 'HandleQuotas',actions: [@@ -28,7 +33,7 @@ export const requiredPermissions: {{id: 'LambdaInvokation',actions: ['iam:PassRole'],- resource: ['arn:aws:iam::*:role/remotion-lambda-role'],+ resource: [`arn:${partition}:iam::*:role/remotion-lambda-role`],},{id: 'Storage',@@ -47,7 +52,7 @@ export const requiredPermissions: {'s3:PutBucketPolicy','s3:PutLifecycleConfiguration',],- resource: [`arn:aws:s3:::${REMOTION_BUCKET_PREFIX}*`],+ resource: [`arn:${partition}:s3:::${REMOTION_BUCKET_PREFIX}*`],},{id: 'BucketListing',@@ -70,21 +75,26 @@ export const requiredPermissions: {'lambda:PutRuntimeManagementConfig','lambda:TagResource',],- resource: [`arn:aws:lambda:*:*:function:${RENDER_FN_PREFIX}*`],+ resource: [`arn:${partition}:lambda:*:*:function:${RENDER_FN_PREFIX}*`],},{id: 'LogsRetention',actions: ['logs:CreateLogGroup', 'logs:PutRetentionPolicy'],resource: [- `arn:aws:logs:*:*:log-group:${LOG_GROUP_PREFIX}${RENDER_FN_PREFIX}*`,+ `arn:${partition}:logs:*:*:log-group:${LOG_GROUP_PREFIX}${RENDER_FN_PREFIX}*`,],},{id: 'FetchBinaries',actions: ['lambda:GetLayerVersion'],- resource: [- REMOTION_HOSTED_LAYER_ARN,- 'arn:aws:lambda:*:580247275435:layer:LambdaInsightsExtension*',- ],+ resource:+ partition === 'aws-cn'+ ? ['arn:aws-cn:lambda:*:488211338238:layer:LambdaInsightsExtension*']+ : [+ REMOTION_HOSTED_LAYER_ARN,+ 'arn:aws:lambda:*:580247275435:layer:LambdaInsightsExtension*',+ ],},];++export const requiredPermissions = getRequiredPermissions('aws');diff --git a/packages/lambda/src/cli/args.ts b/packages/lambda/src/cli/args.tsindex 6c6db77dc1..ea1b477ee8 100644--- a/packages/lambda/src/cli/args.ts+++ b/packages/lambda/src/cli/args.ts@@ -41,6 +41,7 @@ type LambdaCommandLineOptions = {['s3-output-provider-region']: AwsRegion | (string & {}) | undefined;['s3-output-provider-force-path-style']: boolean;['custom-role-arn']: string | undefined;+ ['custom-layer-arns']: string | undefined;privacy: Privacy;webhook: string | undefined;['webhook-secret']: string | undefined;diff --git a/packages/lambda/src/cli/commands/functions/deploy.ts b/packages/lambda/src/cli/commands/functions/deploy.tsindex 2345a0675a..f324ee5432 100644--- a/packages/lambda/src/cli/commands/functions/deploy.ts+++ b/packages/lambda/src/cli/commands/functions/deploy.ts@@ -34,6 +34,12 @@ export const functionsDeploySubcommand = async ({const memorySizeInMb = parsedLambdaCli.memory ?? DEFAULT_MEMORY_SIZE;const diskSizeInMb = parsedLambdaCli.disk ?? DEFAULT_EPHEMERAL_STORAGE_IN_MB;const customRoleArn = parsedLambdaCli['custom-role-arn'] ?? undefined;+ const customLayerArns =+ parsedLambdaCli['custom-layer-arns'] === undefined+ ? null+ : parsedLambdaCli['custom-layer-arns']+ .split(',')+ .map((arn) => arn.trim());const createCloudWatchLogGroup = !parsedLambdaCli['disable-cloudwatch'];const enableLambdaInsights =parsedLambdaCli['enable-lambda-insights'] ?? false;@@ -70,6 +76,7 @@ Version = ${VERSION}CloudWatch Logging Enabled = ${createCloudWatchLogGroup}CloudWatch Retention Period = ${cloudWatchLogRetentionPeriodInDays} daysLambda Insights Enabled = ${enableLambdaInsights}+Custom Layers = ${customLayerArns === null ? 'Not specified' : customLayerArns.length}`.trim(),),@@ -102,6 +109,7 @@ VPC Security Group IDs = ${vpcSecurityGroupIds}cloudWatchLogRetentionPeriodInDays,diskSizeInMb,customRoleArn,+ customLayerArns,enableLambdaInsights,indent: false,logLevel,diff --git a/packages/lambda/src/cli/commands/policies/role.ts b/packages/lambda/src/cli/commands/policies/role.tsindex 616b91258f..3f7764058a 100644--- a/packages/lambda/src/cli/commands/policies/role.ts+++ b/packages/lambda/src/cli/commands/policies/role.ts@@ -1,8 +1,12 @@+import {LambdaClientInternals} from '@remotion/lambda-client';import type {LogLevel} from '@remotion/renderer';import {getRolePolicy} from '../../../api/iam-validation/suggested-policy';+import {getAwsRegion} from '../../get-aws-region';import {Log} from '../../log';export const ROLE_SUBCOMMAND = 'role';export const roleSubcommand = (logLevel: LogLevel) => {- Log.info({indent: false, logLevel}, getRolePolicy());+ const region = getAwsRegion();+ const {partition} = LambdaClientInternals.getAwsRegionMetadata(region);+ Log.info({indent: false, logLevel}, getRolePolicy({partition}));};diff --git a/packages/lambda/src/cli/commands/policies/user.ts b/packages/lambda/src/cli/commands/policies/user.tsindex 414521fac2..b46ff8b78f 100644--- a/packages/lambda/src/cli/commands/policies/user.ts+++ b/packages/lambda/src/cli/commands/policies/user.ts@@ -1,9 +1,13 @@+import {LambdaClientInternals} from '@remotion/lambda-client';import type {LogLevel} from '@remotion/renderer';import {getUserPolicy} from '../../../api/iam-validation/suggested-policy';+import {getAwsRegion} from '../../get-aws-region';import {Log} from '../../log';export const USER_SUBCOMMAND = 'user';export const userSubcommand = (logLevel: LogLevel) => {- Log.info({indent: false, logLevel}, getUserPolicy());+ const region = getAwsRegion();+ const {partition} = LambdaClientInternals.getAwsRegionMetadata(region);+ Log.info({indent: false, logLevel}, getUserPolicy({partition}));};diff --git a/packages/lambda/src/cli/commands/quotas/increase.ts b/packages/lambda/src/cli/commands/quotas/increase.tsindex 8d7586fced..7189a22609 100644--- a/packages/lambda/src/cli/commands/quotas/increase.ts+++ b/packages/lambda/src/cli/commands/quotas/increase.ts@@ -31,7 +31,8 @@ const makeQuotaUrl = ({region: AwsRegion;quotaId: string;}) => {- return `https://${region}.console.aws.amazon.com/servicequotas/home/services/lambda/quotas/${quotaId}`;+ const {consoleDomain} = LambdaClientInternals.getAwsRegionMetadata(region);+ return `https://${region}.${consoleDomain}/servicequotas/home/services/lambda/quotas/${quotaId}`;};export async function quotasIncreaseCommand(@@ -39,6 +40,7 @@ export async function quotasIncreaseCommand(requestHandler: RequestHandler | null,): Promise<void> {const region = getAwsRegion();+ const {consoleDomain} = LambdaClientInternals.getAwsRegionMetadata(region);const [concurrencyLimit, defaultConcurrencyLimit, changes] =await Promise.all([@@ -76,7 +78,7 @@ export async function quotasIncreaseCommand();Log.warn(logOptions,- `https://${region}.console.aws.amazon.com/support/home#/case/?displayId=${openCase.CaseId}`,+ `https://${region}.${consoleDomain}/support/home#/case/?displayId=${openCase.CaseId}`,);exit(1);}diff --git a/packages/lambda/src/cli/commands/quotas/list.ts b/packages/lambda/src/cli/commands/quotas/list.tsindex c612732e0c..1470e2eaf0 100644--- a/packages/lambda/src/cli/commands/quotas/list.ts+++ b/packages/lambda/src/cli/commands/quotas/list.ts@@ -17,6 +17,7 @@ import {INCREASE_SUBCOMMAND} from './increase';export const quotasListCommand = async (logLevel: LogLevel) => {const region = getAwsRegion();+ const {consoleDomain} = LambdaClientInternals.getAwsRegionMetadata(region);Log.info({indent: false, logLevel},CliInternals.chalk.gray(`Region = ${region}`),@@ -76,7 +77,7 @@ export const quotasListCommand = async (logLevel: LogLevel) => {);Log.warn({indent: false, logLevel},- `https://${region}.console.aws.amazon.com/support/home#/case/?displayId=${openCase.CaseId}`,+ `https://${region}.${consoleDomain}/support/home#/case/?displayId=${openCase.CaseId}`,);}diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.tsindex 8bb1ac3198..160f25eea6 100644--- a/packages/lambda/src/cli/commands/render/render.ts+++ b/packages/lambda/src/cli/commands/render/render.ts@@ -461,13 +461,13 @@ export const renderCommand = async ({Log.info({indent: false, logLevel},CliInternals.chalk.gray(- `Bucket: ${CliInternals.makeHyperlink({text: res.bucketName, fallback: res.bucketName, url: `https://${getAwsRegion()}.console.aws.amazon.com/s3/buckets/${res.bucketName}/?region=${getAwsRegion()}`})}`,+ `Bucket: ${CliInternals.makeHyperlink({text: res.bucketName, fallback: res.bucketName, url: LambdaClientInternals.getS3BucketUrl({region: getAwsRegion(), bucketName: res.bucketName})})}`,),);Log.info({indent: false, logLevel},CliInternals.chalk.gray(- `Function: ${CliInternals.makeHyperlink({text: functionName, fallback: functionName, url: `https://${getAwsRegion()}.console.aws.amazon.com/lambda/home#/functions/${functionName}?tab=code`})}`,+ `Function: ${CliInternals.makeHyperlink({text: functionName, fallback: functionName, url: LambdaClientInternals.getLambdaFunctionUrl({region: getAwsRegion(), functionName})})}`,),);Log.info(diff --git a/packages/lambda/src/cli/commands/still.ts b/packages/lambda/src/cli/commands/still.tsindex 39547ae634..d51e541aa9 100644--- a/packages/lambda/src/cli/commands/still.ts+++ b/packages/lambda/src/cli/commands/still.ts@@ -258,7 +258,7 @@ export const stillCommand = async ({Log.info({indent: false, logLevel},CliInternals.chalk.gray(- `Function: ${CliInternals.makeHyperlink({text: functionName, fallback: functionName, url: `https://${getAwsRegion()}.console.aws.amazon.com/lambda/home#/functions/${functionName}?tab=code`})}`,+ `Function: ${CliInternals.makeHyperlink({text: functionName, fallback: functionName, url: LambdaClientInternals.getLambdaFunctionUrl({region: getAwsRegion(), functionName})})}`,),);@@ -341,7 +341,7 @@ export const stillCommand = async ({Log.info({indent: false, logLevel},CliInternals.chalk.gray(- `Bucket: ${CliInternals.makeHyperlink({text: res.bucketName, fallback: res.bucketName, url: `https://${getAwsRegion()}.console.aws.amazon.com/s3/buckets/${res.bucketName}/?region=${getAwsRegion()}`})}`,+ `Bucket: ${CliInternals.makeHyperlink({text: res.bucketName, fallback: res.bucketName, url: LambdaClientInternals.getS3BucketUrl({region: getAwsRegion(), bucketName: res.bucketName})})}`,),);diff --git a/packages/lambda/src/functions/helpers/make-aws-artifact.ts b/packages/lambda/src/functions/helpers/make-aws-artifact.tsindex dd08b69b2d..d8498b70ce 100644--- a/packages/lambda/src/functions/helpers/make-aws-artifact.ts+++ b/packages/lambda/src/functions/helpers/make-aws-artifact.ts@@ -1,4 +1,4 @@-import type {AwsProvider} from '@remotion/lambda-client';+import {LambdaClientInternals, type AwsProvider} from '@remotion/lambda-client';import type {MakeArtifactWithDetails} from '@remotion/serverless';export const makeAwsArtifact: MakeArtifactWithDetails<AwsProvider> = ({@@ -7,10 +7,11 @@ export const makeAwsArtifact: MakeArtifactWithDetails<AwsProvider> = ({storageKey,artifact,}) => {+ const {dnsSuffix} = LambdaClientInternals.getAwsRegionMetadata(region);return {filename: artifact.filename,sizeInBytes: artifact.content.length,- s3Url: `https://s3.${region}.amazonaws.com/${renderBucketName}/${storageKey}`,+ s3Url: `https://s3.${region}.${dnsSuffix}/${renderBucketName}/${storageKey}`,s3Key: storageKey,};};diff --git a/packages/lambda/src/index.ts b/packages/lambda/src/index.tsindex edfd6bddb8..6b1ccb026a 100644--- a/packages/lambda/src/index.ts+++ b/packages/lambda/src/index.ts@@ -1,4 +1,5 @@import type {+ AwsPartition,AwsRegion,CustomCredentials,DeleteFunctionInput,@@ -166,6 +167,7 @@ export {validateWebhookSignature,};export type {+ AwsPartition,AwsRegion,CustomCredentials,DeleteFunctionInput,@@ -203,4 +205,5 @@ export type {SimulatePermissionsOutput,};+export type {GetPolicyOptions} from './api/iam-validation/suggested-policy';export {_InternalOverallRenderProgress};diff --git a/packages/lambda/src/shared/get-layers.ts b/packages/lambda/src/shared/get-layers.tsindex 352c73b113..75470a383e 100644--- a/packages/lambda/src/shared/get-layers.ts+++ b/packages/lambda/src/shared/get-layers.ts@@ -1,6 +1,6 @@import type {AwsRegion, RuntimePreference} from '@remotion/lambda-client';import {LambdaClientInternals} from '@remotion/lambda-client';-import type {AwsLayer} from './hosted-layers';+import type {AwsLayer, HostedLayerRegion} from './hosted-layers';import {hostedLayers} from './hosted-layers';export const validateRuntimePreference = (option: unknown) => {@@ -28,8 +28,11 @@ export const getLayers = ({option: RuntimePreference;region: AwsRegion;}): AwsLayer[] => {- const layers = hostedLayers[region];- return layers.filter((layer) => {+ if (!(region in hostedLayers)) {+ throw new Error(`Remotion-hosted Layers are not available in ${region}.`);+ }++ return hostedLayers[region as HostedLayerRegion].filter((layer) => {if (layer.layerArn.includes('emoji-apple')) {return option === 'apple-emojis';}diff --git a/packages/lambda/src/shared/hosted-layers.ts b/packages/lambda/src/shared/hosted-layers.tsindex 955cb5fd0b..0ee487a0d7 100644--- a/packages/lambda/src/shared/hosted-layers.ts+++ b/packages/lambda/src/shared/hosted-layers.ts@@ -7,8 +7,13 @@ export type AwsLayer = {version: number;};+export type HostedLayerRegion = Exclude<+ AwsRegion,+ 'cn-north-1' | 'cn-northwest-1'+>;+export type HostedLayers = {- [region in AwsRegion]: AwsLayer[];+ [region in HostedLayerRegion]: AwsLayer[];};export const hostedLayers: HostedLayers = {diff --git a/packages/lambda/src/shared/lambda-insights-extensions.ts b/packages/lambda/src/shared/lambda-insights-extensions.tsindex 87f1c6bc84..28204afa53 100644--- a/packages/lambda/src/shared/lambda-insights-extensions.ts+++ b/packages/lambda/src/shared/lambda-insights-extensions.ts@@ -45,4 +45,8 @@ export const lambdaInsightsExtensions: {[region in AwsRegion]: string | null} ='ap-southeast-4': null,'ap-southeast-5': null,'eu-central-2': null,+ 'cn-north-1':+ 'arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension-Arm64:4',+ 'cn-northwest-1':+ 'arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension-Arm64:4',};diff --git a/packages/lambda/src/shared/validate-custom-layer-arns.ts b/packages/lambda/src/shared/validate-custom-layer-arns.tsnew file mode 100644index 0000000000..64074bde6e--- /dev/null+++ b/packages/lambda/src/shared/validate-custom-layer-arns.ts@@ -0,0 +1,81 @@+import {+ LambdaClientInternals,+ type AwsRegion,+ type RuntimePreference,+} from '@remotion/lambda-client';++const layerVersionArnRegex =+ /^arn:([a-z0-9][a-z0-9-]*):lambda:([a-z0-9-]+):(\d{12}):layer:([A-Za-z0-9-_]+):(\d+)$/;++export const validateCustomLayerArns = ({+ customLayerArns,+ enableLambdaInsights,+ region,+ runtimePreference,+}: {+ customLayerArns: string[] | null;+ enableLambdaInsights: boolean;+ region: AwsRegion;+ runtimePreference: RuntimePreference;+}) => {+ const {partition} = LambdaClientInternals.getAwsRegionMetadata(region);+ if (customLayerArns === null) {+ if (partition === 'aws-cn') {+ throw new Error(+ 'customLayerArns must be specified when deploying to AWS China regions because Remotion-hosted Layers are not available in the aws-cn partition.',+ );+ }++ return;+ }++ if (!Array.isArray(customLayerArns) || customLayerArns.length === 0) {+ throw new TypeError('customLayerArns must contain at least one Layer ARN.');+ }++ if (runtimePreference !== 'default') {+ throw new Error(+ 'customLayerArns cannot be combined with a non-default runtimePreference.',+ );+ }++ if (customLayerArns.length + (enableLambdaInsights ? 1 : 0) > 5) {+ throw new Error(+ 'Lambda functions support at most 5 Layers, including the Lambda Insights Layer.',+ );+ }++ const seen = new Set<string>();+ for (const layerArn of customLayerArns) {+ if (typeof layerArn !== 'string' || layerArn.length === 0) {+ throw new TypeError(+ 'Each customLayerArns entry must be a non-empty string.',+ );+ }++ const match = layerArn.match(layerVersionArnRegex);+ if (!match) {+ throw new TypeError(+ `Invalid Lambda Layer version ARN: ${layerArn}. Expected arn:<partition>:lambda:<region>:<12-digit-account-id>:layer:<layer-name>:<numeric-version>.`,+ );+ }++ if (match[1] !== partition) {+ throw new Error(+ `The custom Layer ARN ${layerArn} uses partition ${match[1]}, but region ${region} uses partition ${partition}.`,+ );+ }++ if (match[2] !== region) {+ throw new Error(+ `The custom Layer ARN ${layerArn} is in region ${match[2]}, but the function is being deployed to ${region}.`,+ );+ }++ if (seen.has(layerArn)) {+ throw new Error(`Duplicate custom Layer ARN: ${layerArn}.`);+ }++ seen.add(layerArn);+ }+};diff --git a/packages/lambda/src/test/integration/cli.test.ts b/packages/lambda/src/test/integration/cli.test.tsindex ea0f9178bd..b549a25e36 100644--- a/packages/lambda/src/test/integration/cli.test.ts+++ b/packages/lambda/src/test/integration/cli.test.ts@@ -7,8 +7,13 @@ import {DEFAULT_MEMORY_SIZE,DEFAULT_TIMEOUT,} from '@remotion/lambda-client/constants';+import {parsedLambdaCli} from '../../cli/args';import {LambdaInternals} from '../../internals';import {mockFullClientSpecifics} from '../mock-implementation';+import {+ clearMockCreateFunctionCalls,+ getMockCreateFunctionCalls,+} from '../mocks/mock-create-function';import {mockImplementation} from '../mocks/mock-implementation';import {doAfter, doBefore, getProcessWriteOutput} from './console-hooks';@@ -16,6 +21,7 @@ const remotionRoot = process.cwd();beforeEach(() => {doBefore();+ parsedLambdaCli['custom-layer-arns'] = undefined;});afterEach(() => {@@ -74,6 +80,27 @@ test('Deploy function and it already exists should fail', async () => {expect(getProcessWriteOutput()).toMatch(/Already exists as remotion-render/);});+test('Deploy function with custom Layer ARNs', async () => {+ clearMockCreateFunctionCalls();+ parsedLambdaCli['custom-layer-arns'] =+ 'arn:aws:lambda:us-east-1:123456789012:layer:chromium:1, arn:aws:lambda:us-east-1:123456789012:layer:fonts:2';++ await LambdaInternals.executeCommand(+ ['functions', 'deploy'],+ remotionRoot,+ 'info',+ mockImplementation,+ mockFullClientSpecifics,+ );++ expect(getMockCreateFunctionCalls().at(-1)?.customLayerArns).toEqual([+ 'arn:aws:lambda:us-east-1:123456789012:layer:chromium:1',+ 'arn:aws:lambda:us-east-1:123456789012:layer:fonts:2',+ ]);+ expect(getProcessWriteOutput()).toContain('Custom Layers = 2');+ expect(getProcessWriteOutput()).not.toContain('123456789012');+});+test('If no functions are there and is quiet, should return "()"', async () => {CliInternals.parsedCli.q = true;await LambdaInternals.executeCommand(diff --git a/packages/lambda/src/test/integration/deploy-function.test.ts b/packages/lambda/src/test/integration/deploy-function.test.tsindex 81119c3ab4..cc88e799f9 100644--- a/packages/lambda/src/test/integration/deploy-function.test.ts+++ b/packages/lambda/src/test/integration/deploy-function.test.ts@@ -5,7 +5,12 @@ import {} from '@remotion/lambda-client';import {VERSION} from 'remotion/version';import {internalDeployFunction} from '../../api/deploy-function';+import {lambdaInsightsExtensions} from '../../shared/lambda-insights-extensions';import {mockFullClientSpecifics} from '../mock-implementation';+import {+ clearMockCreateFunctionCalls,+ getMockCreateFunctionCalls,+} from '../mocks/mock-create-function';import {cleanFnStore,markFunctionAsIncompatible,@@ -14,6 +19,10 @@ import {mockImplementation} from '../mocks/mock-implementation';const {DEFAULT_EPHEMERAL_STORAGE_IN_MB} = LambdaClientInternals;+const chromiumLayer =+ 'arn:aws:lambda:us-east-1:123456789012:layer:custom-chromium:1';+const fontsLayer = 'arn:aws:lambda:us-east-1:123456789012:layer:custom-fonts:3';+test('Should be able to deploy function', async () => {const {functionName} = await internalDeployFunction({memorySizeInMb: 2048,@@ -21,6 +30,7 @@ test('Should be able to deploy function', async () => {timeoutInSeconds: 120,createCloudWatchLogGroup: true,customRoleArn: undefined,+ customLayerArns: null,diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,enableLambdaInsights: true,indent: false,@@ -51,6 +61,7 @@ test('Should be able to get the function afterwards', async () => {timeoutInSeconds: 120,createCloudWatchLogGroup: true,customRoleArn: undefined,+ customLayerArns: null,diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,enableLambdaInsights: true,indent: false,@@ -103,6 +114,7 @@ test('Should be able to delete the function', async () => {timeoutInSeconds: 120,createCloudWatchLogGroup: true,customRoleArn: undefined,+ customLayerArns: null,diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,enableLambdaInsights: true,indent: false,@@ -137,6 +149,191 @@ test('Should be able to delete the function', async () => {expect(fns).toEqual([]);});+test('Should apply custom Layers when creating and reusing a function', async () => {+ cleanFnStore();+ clearMockCreateFunctionCalls();++ const input = {+ memorySizeInMb: 2048,+ region: 'us-east-1' as const,+ timeoutInSeconds: 120,+ createCloudWatchLogGroup: true,+ customRoleArn: undefined,+ diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,+ enableLambdaInsights: false,+ indent: false,+ logLevel: 'info' as const,+ providerSpecifics: mockImplementation,+ fullClientSpecifics: mockFullClientSpecifics,+ runtimePreference: 'default' as const,+ vpcSecurityGroupIds: undefined,+ vpcSubnetIds: undefined,+ cloudWatchLogRetentionPeriodInDays: undefined,+ requestHandler: null,+ };++ const first = await internalDeployFunction({+ ...input,+ customLayerArns: [chromiumLayer, fontsLayer],+ });+ const updatedLayers = [chromiumLayer.replace(/:1$/, ':2'), fontsLayer];+ const second = await internalDeployFunction({+ ...input,+ customLayerArns: updatedLayers,+ });++ expect(first.alreadyExisted).toBe(false);+ expect(second.alreadyExisted).toBe(true);+ expect(getMockCreateFunctionCalls()).toHaveLength(2);+ expect(getMockCreateFunctionCalls()[0].customLayerArns).toEqual([+ chromiumLayer,+ fontsLayer,+ ]);+ expect(getMockCreateFunctionCalls()[0].alreadyCreated).toBe(false);+ expect(getMockCreateFunctionCalls()[1].customLayerArns).toEqual(+ updatedLayers,+ );+ expect(getMockCreateFunctionCalls()[1].alreadyCreated).toBe(true);+});++test('Should validate custom Layers before calling the Provider', async () => {+ let providerCalls = 0;+ const providerSpecifics = {+ ...mockImplementation,+ getAccountId: () => {+ providerCalls++;+ return Promise.resolve('123456789012');+ },+ };+ const invalidInputs = [+ {customLayerArns: [chromiumLayer.slice(0, -2)]},+ {customLayerArns: [chromiumLayer.replace(':lambda:', ':s3:')]},+ {customLayerArns: [chromiumLayer.replace('us-east-1', 'eu-west-1')]},+ {customLayerArns: []},+ {customLayerArns: [chromiumLayer, chromiumLayer]},+ {+ customLayerArns: Array.from({length: 5}, (_, index) =>+ chromiumLayer.replace(/:1$/, `:${index + 1}`),+ ),+ enableLambdaInsights: true,+ },+ {customLayerArns: [chromiumLayer], runtimePreference: 'cjk' as const},+ ];++ for (const invalidInput of invalidInputs) {+ await expect(+ internalDeployFunction({+ memorySizeInMb: 2048,+ region: 'us-east-1',+ timeoutInSeconds: 120,+ createCloudWatchLogGroup: true,+ customRoleArn: undefined,+ customLayerArns: invalidInput.customLayerArns,+ diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,+ enableLambdaInsights: invalidInput.enableLambdaInsights ?? false,+ indent: false,+ logLevel: 'info',+ providerSpecifics,+ fullClientSpecifics: mockFullClientSpecifics,+ runtimePreference: invalidInput.runtimePreference ?? 'default',+ vpcSecurityGroupIds: undefined,+ vpcSubnetIds: undefined,+ cloudWatchLogRetentionPeriodInDays: undefined,+ requestHandler: null,+ }),+ ).rejects.toThrow();+ }++ expect(providerCalls).toBe(0);+});++test('AWS China requires partition-matching custom Layers before Provider calls', async () => {+ for (const region of ['cn-north-1', 'cn-northwest-1'] as const) {+ let providerCalls = 0;+ const providerSpecifics = {+ ...mockImplementation,+ getAccountId: () => {+ providerCalls++;+ return Promise.resolve('123456789012');+ },+ };+ const input = {+ memorySizeInMb: 2048,+ region,+ timeoutInSeconds: 120,+ createCloudWatchLogGroup: true,+ customRoleArn: undefined,+ diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,+ enableLambdaInsights: true,+ indent: false,+ logLevel: 'info' as const,+ providerSpecifics,+ fullClientSpecifics: mockFullClientSpecifics,+ runtimePreference: 'default' as const,+ vpcSecurityGroupIds: undefined,+ vpcSubnetIds: undefined,+ cloudWatchLogRetentionPeriodInDays: undefined,+ requestHandler: null,+ };++ await expect(+ internalDeployFunction({...input, customLayerArns: null}),+ ).rejects.toThrow(+ 'customLayerArns must be specified when deploying to AWS China regions',+ );+ await expect(+ internalDeployFunction({+ ...input,+ customLayerArns: [+ `arn:aws:lambda:${region}:123456789012:layer:chromium:1`,+ ],+ }),+ ).rejects.toThrow(`region ${region} uses partition aws-cn`);+ expect(providerCalls).toBe(0);++ cleanFnStore();+ clearMockCreateFunctionCalls();+ const customLayerArns = [+ `arn:aws-cn:lambda:${region}:123456789012:layer:chromium:1`,+ `arn:aws-cn:lambda:${region}:123456789012:layer:fonts:2`,+ ];+ await internalDeployFunction({...input, customLayerArns});+ expect(getMockCreateFunctionCalls()[0].customLayerArns).toEqual(+ customLayerArns,+ );+ expect(lambdaInsightsExtensions[region]).toBe(+ `arn:aws-cn:lambda:${region}:488211338238:layer:LambdaInsightsExtension-Arm64:4`,+ );+ }+});++test('Should pass null to the hosted Layer path by default', async () => {+ cleanFnStore();+ clearMockCreateFunctionCalls();++ await internalDeployFunction({+ memorySizeInMb: 2048,+ region: 'us-east-1',+ timeoutInSeconds: 120,+ createCloudWatchLogGroup: true,+ customRoleArn: undefined,+ customLayerArns: null,+ diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,+ enableLambdaInsights: false,+ indent: false,+ logLevel: 'info',+ providerSpecifics: mockImplementation,+ fullClientSpecifics: mockFullClientSpecifics,+ runtimePreference: 'default',+ vpcSecurityGroupIds: undefined,+ vpcSubnetIds: undefined,+ cloudWatchLogRetentionPeriodInDays: undefined,+ requestHandler: null,+ });++ expect(getMockCreateFunctionCalls()[0].customLayerArns).toBeNull();+});+test('Should be able to get the function afterwards', async () => {cleanFnStore();@@ -146,6 +343,7 @@ test('Should be able to get the function afterwards', async () => {timeoutInSeconds: 120,createCloudWatchLogGroup: true,customRoleArn: undefined,+ customLayerArns: null,diskSizeInMb: 10240,enableLambdaInsights: true,indent: false,diff --git a/packages/lambda/src/test/mocks/mock-create-function.ts b/packages/lambda/src/test/mocks/mock-create-function.tsindex a203176214..d763b17d0e 100644--- a/packages/lambda/src/test/mocks/mock-create-function.ts+++ b/packages/lambda/src/test/mocks/mock-create-function.ts@@ -3,7 +3,24 @@ import type {CreateFunction} from '@remotion/serverless';import {VERSION} from 'remotion/version';import {addFunction} from './mock-functions';+type MockCreateFunctionCall = {+ alreadyCreated: boolean;+ customLayerArns: string[] | null;+};++const calls: MockCreateFunctionCall[] = [];++export const getMockCreateFunctionCalls = () => calls;++export const clearMockCreateFunctionCalls = () => {+ calls.length = 0;+};+export const mockCreateFunction: CreateFunction<AwsProvider> = (input) => {+ calls.push({+ alreadyCreated: input.alreadyCreated,+ customLayerArns: input.customLayerArns,+ });if (!input.alreadyCreated) {addFunction({diff --git a/packages/lambda/src/test/mocks/mock-implementation.ts b/packages/lambda/src/test/mocks/mock-implementation.tsindex 92724143cb..16c7333240 100644--- a/packages/lambda/src/test/mocks/mock-implementation.ts+++ b/packages/lambda/src/test/mocks/mock-implementation.ts@@ -35,6 +35,14 @@ export const mockImplementation: ProviderSpecifics<AwsProvider> = {},getEphemeralStorageForPriceCalculation: () =>LambdaClientInternals.MAX_EPHEMERAL_STORAGE_IN_MB,+ getBillingCurrency: (region) =>+ LambdaClientInternals.getAwsRegionMetadata(region).billingCurrency,+ getRendererFunctionTransport: (region) =>+ LambdaClientInternals.getAwsRegionMetadata(region).partition === 'aws-cn'+ ? 's3'+ : 'response-streaming',+ getServiceDnsSuffix: (region) =>+ LambdaClientInternals.getAwsRegionMetadata(region).dnsSuffix,getLoggingUrlForMethod: LambdaClientInternals.getCloudwatchMethodUrl,getLoggingUrlForRendererFunction:LambdaClientInternals.getCloudwatchRendererUrl,diff --git a/packages/lambda/src/test/unit/aws-china-policy.test.ts b/packages/lambda/src/test/unit/aws-china-policy.test.tsnew file mode 100644index 0000000000..f1df238279--- /dev/null+++ b/packages/lambda/src/test/unit/aws-china-policy.test.ts@@ -0,0 +1,31 @@+import {expect, test} from 'bun:test';+import {+ getRolePolicy,+ getUserPolicy,+} from '../../api/iam-validation/suggested-policy';++const arnResources = (policy: string) =>+ JSON.parse(policy)+ .Statement.flatMap((statement: {Resource: string[]}) => statement.Resource)+ .filter((resource: string) => resource.startsWith('arn:')) as string[];++test('policy APIs default to aws and generate aws-cn resources on request', () => {+ expect(getUserPolicy()).toBe(getUserPolicy({partition: 'aws'}));+ expect(getRolePolicy()).toBe(getRolePolicy({partition: 'aws'}));++ const chinaUserPolicy = getUserPolicy({partition: 'aws-cn'});+ const chinaRolePolicy = getRolePolicy({partition: 'aws-cn'});+ const resources = [+ ...arnResources(chinaUserPolicy),+ ...arnResources(chinaRolePolicy),+ ];++ expect(resources.length).toBeGreaterThan(0);+ expect(+ resources.every((resource) => resource.startsWith('arn:aws-cn:')),+ ).toBe(true);+ expect(chinaUserPolicy).not.toContain('678892195805');+ expect(chinaUserPolicy).toContain(+ 'arn:aws-cn:lambda:*:488211338238:layer:LambdaInsightsExtension*',+ );+});diff --git a/packages/lambda/src/test/unit/aws-china-simulation.test.ts b/packages/lambda/src/test/unit/aws-china-simulation.test.tsnew file mode 100644index 0000000000..edc8908f46--- /dev/null+++ b/packages/lambda/src/test/unit/aws-china-simulation.test.ts@@ -0,0 +1,35 @@+import {expect, test} from 'bun:test';+import {resolveCallerArnForSimulation} from '../../api/iam-validation/resolve-caller-arn';++test('permission simulation resolves users and assumed roles in both partitions', () => {+ expect(+ resolveCallerArnForSimulation({+ callerIdentityArn: 'arn:aws-cn:iam::123456789012:user/example',+ region: 'cn-north-1',+ regionPartition: 'aws-cn',+ }),+ ).toBe('arn:aws-cn:iam::123456789012:user/example');+ expect(+ resolveCallerArnForSimulation({+ callerIdentityArn:+ 'arn:aws-cn:sts::123456789012:assumed-role/example/session',+ region: 'cn-northwest-1',+ regionPartition: 'aws-cn',+ }),+ ).toBe('arn:aws-cn:iam::123456789012:role/example');+ expect(+ resolveCallerArnForSimulation({+ callerIdentityArn:+ 'arn:aws:sts::123456789012:assumed-role/example/session',+ region: 'us-east-1',+ regionPartition: 'aws',+ }),+ ).toBe('arn:aws:iam::123456789012:role/example');+ expect(() =>+ resolveCallerArnForSimulation({+ callerIdentityArn: 'arn:aws:iam::123456789012:user/example',+ region: 'cn-north-1',+ regionPartition: 'aws-cn',+ }),+ ).toThrow('does not match region cn-north-1');+});diff --git a/packages/lambda/src/test/unit/quota-console-urls.test.ts b/packages/lambda/src/test/unit/quota-console-urls.test.tsnew file mode 100644index 0000000000..7501096adc--- /dev/null+++ b/packages/lambda/src/test/unit/quota-console-urls.test.ts@@ -0,0 +1,85 @@+import {expect, spyOn, test} from 'bun:test';+import {+ GetAWSDefaultServiceQuotaCommand,+ GetServiceQuotaCommand,+ ListRequestedServiceQuotaChangeHistoryByQuotaCommand,+} from '@aws-sdk/client-service-quotas';+import {LambdaClientInternals} from '@remotion/lambda-client';+import {parsedLambdaCli} from '../../cli/args';+import {quotasIncreaseCommand} from '../../cli/commands/quotas/increase';+import {quotasListCommand} from '../../cli/commands/quotas/list';+import {+ doAfter,+ doBefore,+ getProcessWriteOutput,+} from '../integration/console-hooks';++test('quota CLI links use the AWS China console domain', async () => {+ const originalRegion = parsedLambdaCli.region;+ let requestedQuotas = [+ {+ Status: 'CASE_OPENED' as const,+ DesiredValue: 10_000,+ CaseId: 'china-support-case',+ },+ ];+ const serviceQuotasClientSpy = spyOn(+ LambdaClientInternals,+ 'getServiceQuotasClient',+ ).mockReturnValue({+ send: (command: unknown) => {+ if (command instanceof GetServiceQuotaCommand) {+ return Promise.resolve({Quota: {Value: 6_000}});+ }++ if (command instanceof GetAWSDefaultServiceQuotaCommand) {+ return Promise.resolve({Quota: {Value: 1_000}});+ }++ if (+ command instanceof ListRequestedServiceQuotaChangeHistoryByQuotaCommand+ ) {+ return Promise.resolve({RequestedQuotas: requestedQuotas});+ }++ return Promise.reject(+ new Error(`Unexpected command: ${String(command)}`),+ );+ },+ } as never);+ const exitSpy = spyOn(process, 'exit').mockImplementation((code) => {+ throw new Error(`process.exit(${code})`);+ });++ parsedLambdaCli.region = 'cn-north-1';+ doBefore();+ const warnings: string[] = [];+ const warnSpy = spyOn(console, 'warn').mockImplementation((...args) => {+ warnings.push(args.join(' '));+ });+ try {+ await quotasListCommand('info');+ requestedQuotas = [];+ await expect(quotasIncreaseCommand('info', null)).rejects.toThrow(+ 'process.exit(1)',+ );++ const stdout = getProcessWriteOutput();+ const warningOutput = warnings.join('\n');+ expect(warningOutput).toContain(+ 'https://cn-north-1.console.amazonaws.cn/support/home#/case/?displayId=china-support-case',+ );+ expect(stdout).toContain(+ 'https://cn-north-1.console.amazonaws.cn/servicequotas/home/services/lambda/quotas/L-B99A9384',+ );+ expect(`${stdout}\n${warningOutput}`).not.toContain(+ 'console.aws.amazon.com',+ );+ } finally {+ doAfter();+ parsedLambdaCli.region = originalRegion;+ serviceQuotasClientSpy.mockRestore();+ exitSpy.mockRestore();+ warnSpy.mockRestore();+ }+});diff --git a/packages/serverless-client/src/check-bucket-listing.ts b/packages/serverless-client/src/check-bucket-listing.tsindex 32c2dd6cdb..8c3b972dcb 100644--- a/packages/serverless-client/src/check-bucket-listing.ts+++ b/packages/serverless-client/src/check-bucket-listing.ts@@ -1,14 +1,14 @@export const checkBucketListing = async ({bucketName,region,+ dnsSuffix,}: {bucketName: string;region: string;+ dnsSuffix: string;}) => {try {- const res = await fetch(- `https://${bucketName}.s3.${region}.amazonaws.com/`,- );+ const res = await fetch(`https://${bucketName}.s3.${region}.${dnsSuffix}/`);if (res.status === 200) {// eslint-disable-next-line no-consoleconsole.warn(diff --git a/packages/serverless-client/src/format-costs-info.ts b/packages/serverless-client/src/format-costs-info.tsindex 9a53dbbe79..ffa5b582e7 100644--- a/packages/serverless-client/src/format-costs-info.ts+++ b/packages/serverless-client/src/format-costs-info.ts@@ -1,23 +1,28 @@import type {CostsInfo} from './types';-const display = (accrued: number) => {+export type BillingCurrency = 'USD' | 'CNY';++const display = (accrued: number, currency: BillingCurrency) => {if (accrued < 0.001) {- return '<$0.001';+ return `<${currency === 'CNY' ? '¥' : '$'}0.001`;}return new Intl.NumberFormat('en-US', {- currency: 'USD',+ currency,style: 'currency',currencyDisplay: 'narrowSymbol',minimumFractionDigits: 3,}).format(accrued);};-export const formatCostsInfo = (accrued: number): CostsInfo => {+export const formatCostsInfo = (+ accrued: number,+ currency: BillingCurrency = 'USD',+): CostsInfo => {return {accruedSoFar: accrued,- displayCost: display(accrued),- currency: 'USD',+ displayCost: display(accrued, currency),+ currency,disclaimer:'Estimated cost only. Does not include charges for other AWS services.',};diff --git a/packages/serverless-client/src/get-or-create-bucket.ts b/packages/serverless-client/src/get-or-create-bucket.tsindex 053097cd93..42efa99232 100644--- a/packages/serverless-client/src/get-or-create-bucket.ts+++ b/packages/serverless-client/src/get-or-create-bucket.ts@@ -62,7 +62,11 @@ export const internalGetOrCreateBucket = async <Provider extends CloudProvider>(requestHandler: params.requestHandler,});- await checkBucketListing({bucketName: existingBucketName, region});+ await checkBucketListing({+ bucketName: existingBucketName,+ region,+ dnsSuffix: params.providerSpecifics.getServiceDnsSuffix(region),+ });return {bucketName: remotionBuckets[0].name, alreadyExisted: true};}diff --git a/packages/serverless-client/src/index.ts b/packages/serverless-client/src/index.tsindex b8c0fb5395..8f315bb9b0 100644--- a/packages/serverless-client/src/index.ts+++ b/packages/serverless-client/src/index.ts@@ -100,6 +100,18 @@ export {OverallRenderProgress} from './overall-render-progress';export {getProgress} from './progress';export * from './provider-implementation';export {RenderMetadata} from './render-metadata';+export {+ parseS3RendererStatus,+ rendererTransportArtifactKey,+ rendererTransportAttemptPrefix,+ rendererTransportAudioKey,+ rendererTransportPrefix,+ rendererTransportStatusKey,+ rendererTransportVideoKey,+ type RendererFunctionTransport,+ type S3RendererArtifactMetadata,+ type S3RendererStatus,+} from './renderer-transport';export {OrError, ServerlessReturnValues} from './return-values';export {streamToString} from './stream-to-string';export {diff --git a/packages/serverless-client/src/progress.ts b/packages/serverless-client/src/progress.tsindex 87dfc665f5..f50dbf99e8 100644--- a/packages/serverless-client/src/progress.ts+++ b/packages/serverless-client/src/progress.ts@@ -41,6 +41,7 @@ export const getProgress = async <Provider extends CloudProvider>({functionName: string;requestHandler: Provider['requestHandler'] | null;}): Promise<GenericRenderProgress<Provider>> => {+ const billingCurrency = providerSpecifics.getBillingCurrency(region);const overallProgress = await getOverallProgressFromStorage({renderId,bucketName,@@ -158,7 +159,7 @@ export const getProgress = async <Provider extends CloudProvider>({timeToCombine: overallProgress.timeToCombine,},timeToRenderFrames: overallProgress.timeToRenderFrames,- costs: formatCostsInfo(0),+ costs: formatCostsInfo(0, billingCurrency),renderId,renderMetadata,bucket: bucketName,@@ -293,8 +294,8 @@ export const getProgress = async <Provider extends CloudProvider>({minFilesToDelete: 0,},costs: priceFromBucket- ? formatCostsInfo(priceFromBucket.accruedSoFar)- : formatCostsInfo(0),+ ? formatCostsInfo(priceFromBucket.accruedSoFar, billingCurrency)+ : formatCostsInfo(0, billingCurrency),currentTime: now,done: true,encodingStatus: {@@ -358,8 +359,8 @@ export const getProgress = async <Provider extends CloudProvider>({},timeToRenderFrames: overallProgress.timeToRenderFrames,costs: priceFromBucket- ? formatCostsInfo(priceFromBucket.accruedSoFar)- : formatCostsInfo(0),+ ? formatCostsInfo(priceFromBucket.accruedSoFar, billingCurrency)+ : formatCostsInfo(0, billingCurrency),renderId,renderMetadata,bucket: bucketName,diff --git a/packages/serverless-client/src/provider-implementation.ts b/packages/serverless-client/src/provider-implementation.tsindex 58a69b1a6f..6ddf9b3e90 100644--- a/packages/serverless-client/src/provider-implementation.ts+++ b/packages/serverless-client/src/provider-implementation.ts@@ -2,7 +2,9 @@ import type {Readable} from 'node:stream';import type {LogLevel} from '@remotion/renderer';import type {DownloadBehavior} from 'remotion';import type {CustomCredentials, Privacy, ServerlessRoutines} from './constants';+import type {BillingCurrency} from './format-costs-info';import type {RenderMetadata} from './render-metadata';+import type {RendererFunctionTransport} from './renderer-transport';import type {ServerlessReturnValues} from './return-values';import type {OnMessage} from './streaming/streaming';import type {CallFunctionOptions, CloudProvider} from './types';@@ -256,6 +258,11 @@ export type ProviderSpecifics<Provider extends CloudProvider> = {getLoggingUrlForRendererFunction: GetLoggingUrlForRendererFunction<Provider>;getLoggingUrlForMethod: GetLoggingUrlForMethod<Provider>;getEphemeralStorageForPriceCalculation: () => number;+ getBillingCurrency: (region: Provider['region']) => BillingCurrency;+ getRendererFunctionTransport: (+ region: Provider['region'],+ ) => RendererFunctionTransport;+ getServiceDnsSuffix: (region: Provider['region']) => string;getOutputUrl: GetOutputUrl<Provider>;isFlakyError: (err: Error) => boolean;serverStorageProductName: () => string;diff --git a/packages/serverless-client/src/renderer-transport.ts b/packages/serverless-client/src/renderer-transport.tsnew file mode 100644index 0000000000..7444aaa95f--- /dev/null+++ b/packages/serverless-client/src/renderer-transport.ts@@ -0,0 +1,179 @@+import type {DownloadBehavior} from 'remotion/no-react';+import {rendersPrefix} from './constants';+import type {FunctionErrorInfo} from './write-error-to-storage';++export type RendererFunctionTransport = 'response-streaming' | 's3';++export type S3RendererArtifactMetadata = {+ filename: string;+ frame: number;+ binary: boolean;+ downloadBehavior: DownloadBehavior | null;+};++type S3RendererStatusBase = {+ schema: 1;+ chunk: number;+ attempt: number;+ lambdaInvoked: boolean;+ renderedFrames: number;+ encodedFrames: number;+ startedAt: number;+};++export type S3RendererStatus =+ | (S3RendererStatusBase & {+ state: 'running';+ })+ | (S3RendererStatusBase & {+ state: 'completed';+ lambdaInvoked: true;+ completedAt: number;+ videoKey: string | null;+ audioKey: string | null;+ artifacts: Array<{+ key: string;+ metadata: S3RendererArtifactMetadata;+ }>;+ })+ | (S3RendererStatusBase & {+ state: 'failed';+ failedAt: number;+ errorInfo: FunctionErrorInfo;+ shouldRetry: boolean;+ });++export const rendererTransportPrefix = (renderId: string) =>+ `${rendersPrefix(renderId)}/transport`;++export const rendererTransportAttemptPrefix = ({+ renderId,+ chunk,+ attempt,+}: {+ renderId: string;+ chunk: number;+ attempt: number;+}) => `${rendererTransportPrefix(renderId)}/chunks/${chunk}/attempt-${attempt}`;++export const rendererTransportStatusKey = (options: {+ renderId: string;+ chunk: number;+ attempt: number;+}) => `${rendererTransportAttemptPrefix(options)}/status.json`;++export const rendererTransportVideoKey = (options: {+ renderId: string;+ chunk: number;+ attempt: number;+}) => `${rendererTransportAttemptPrefix(options)}/video`;++export const rendererTransportAudioKey = (options: {+ renderId: string;+ chunk: number;+ attempt: number;+}) => `${rendererTransportAttemptPrefix(options)}/audio`;++export const rendererTransportArtifactKey = (+ options: {+ renderId: string;+ chunk: number;+ attempt: number;+ },+ artifactIndex: number,+) => `${rendererTransportAttemptPrefix(options)}/artifacts/${artifactIndex}`;++const isNumber = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value);++export const parseS3RendererStatus = ({+ value,+ expectedChunk,+ expectedAttempt,+}: {+ value: unknown;+ expectedChunk: number;+ expectedAttempt: number;+}): S3RendererStatus => {+ if (typeof value !== 'object' || value === null) {+ throw new Error('Renderer S3 status must be an object');+ }++ const status = value as Record<string, unknown>;+ if (status.schema !== 1) {+ throw new Error(+ `Unsupported renderer S3 status schema: ${String(status.schema)}`,+ );+ }++ if (status.chunk !== expectedChunk || status.attempt !== expectedAttempt) {+ throw new Error(+ `Renderer S3 status identifies chunk ${String(status.chunk)}, attempt ${String(status.attempt)}; expected chunk ${expectedChunk}, attempt ${expectedAttempt}`,+ );+ }++ if (+ typeof status.lambdaInvoked !== 'boolean' ||+ !isNumber(status.renderedFrames) ||+ !isNumber(status.encodedFrames) ||+ !isNumber(status.startedAt)+ ) {+ throw new Error('Renderer S3 status has invalid progress fields');+ }++ if (status.state === 'running') {+ return status as S3RendererStatus;+ }++ if (status.state === 'completed') {+ if (+ status.lambdaInvoked !== true ||+ !isNumber(status.completedAt) ||+ !(typeof status.videoKey === 'string' || status.videoKey === null) ||+ !(typeof status.audioKey === 'string' || status.audioKey === null) ||+ !Array.isArray(status.artifacts)+ ) {+ throw new Error('Renderer S3 completed status is invalid');+ }++ for (const artifact of status.artifacts) {+ const candidate = artifact as {+ key?: unknown;+ metadata?: Record<string, unknown>;+ };+ if (+ typeof artifact !== 'object' ||+ artifact === null ||+ typeof candidate.key !== 'string' ||+ typeof candidate.metadata !== 'object' ||+ candidate.metadata === null ||+ typeof candidate.metadata.filename !== 'string' ||+ !isNumber(candidate.metadata.frame) ||+ typeof candidate.metadata.binary !== 'boolean' ||+ !(+ candidate.metadata.downloadBehavior === null ||+ typeof candidate.metadata.downloadBehavior === 'object'+ )+ ) {+ throw new Error('Renderer S3 completed status has an invalid artifact');+ }+ }++ return status as S3RendererStatus;+ }++ if (status.state === 'failed') {+ if (+ !isNumber(status.failedAt) ||+ typeof status.shouldRetry !== 'boolean' ||+ typeof status.errorInfo !== 'object' ||+ status.errorInfo === null+ ) {+ throw new Error('Renderer S3 failed status is invalid');+ }++ return status as S3RendererStatus;+ }++ throw new Error(`Unknown renderer S3 status state: ${String(status.state)}`);+};diff --git a/packages/serverless-client/src/test/format-costs-info.test.ts b/packages/serverless-client/src/test/format-costs-info.test.tsnew file mode 100644index 0000000000..925a003950--- /dev/null+++ b/packages/serverless-client/src/test/format-costs-info.test.ts@@ -0,0 +1,20 @@+import {expect, test} from 'bun:test';+import {formatCostsInfo} from '../format-costs-info';++test('formats costs in USD by default and supports CNY', () => {+ expect(formatCostsInfo(1.234)).toEqual({+ accruedSoFar: 1.234,+ displayCost: '$1.234',+ currency: 'USD',+ disclaimer:+ 'Estimated cost only. Does not include charges for other AWS services.',+ });+ expect(formatCostsInfo(1.234, 'CNY')).toEqual({+ accruedSoFar: 1.234,+ displayCost: '¥1.234',+ currency: 'CNY',+ disclaimer:+ 'Estimated cost only. Does not include charges for other AWS services.',+ });+ expect(formatCostsInfo(0, 'CNY').displayCost).toBe('<¥0.001');+});diff --git a/packages/serverless-client/src/test/progress.test.ts b/packages/serverless-client/src/test/progress.test.tsindex 073295df53..643df5380d 100644--- a/packages/serverless-client/src/test/progress.test.ts+++ b/packages/serverless-client/src/test/progress.test.ts@@ -93,9 +93,11 @@ const progress: OverallRenderProgress<MockProvider> = {const makeProviderSpecifics = ({onEstimatePrice,onHeadFile,+ billingCurrency = 'USD',}: {onEstimatePrice?: (input: EstimatePriceInput<MockProvider>) => number;onHeadFile: ProviderSpecifics<MockProvider>['headFile'];+ billingCurrency?: 'USD' | 'CNY';}): ProviderSpecifics<MockProvider> => {return {applyLifeCycle: () => Promise.resolve(),@@ -114,6 +116,9 @@ const makeProviderSpecifics = ({getBuckets: () => Promise.resolve([]),getChromiumPath: () => null,getEphemeralStorageForPriceCalculation: () => 512,+ getBillingCurrency: () => billingCurrency,+ getRendererFunctionTransport: () => 'response-streaming',+ getServiceDnsSuffix: () => 'example.com',getFunctions: () => Promise.resolve([]),getLoggingUrlForMethod: () => 'logs',getLoggingUrlForRendererFunction: () => 'logs',@@ -161,6 +166,7 @@ const makeProviderSpecifics = ({test('getProgress treats an existing output file as finished if postRenderData was not persisted', async () => {const headedFiles: {bucketName: string; key: string}[] = [];const providerSpecifics = makeProviderSpecifics({+ billingCurrency: 'CNY',onHeadFile: ({bucketName: headedBucketName, key}) => {headedFiles.push({bucketName: headedBucketName, key});return Promise.resolve({ContentLength: 1234});@@ -190,6 +196,8 @@ test('getProgress treats an existing output file as finished if postRenderData w);expect(renderProgress.outputSizeInBytes).toBe(1234);expect(renderProgress.errors).toEqual([]);+ expect(renderProgress.costs.currency).toBe('CNY');+ expect(renderProgress.costs.displayCost).toBe('¥0.010');});test('getProgress estimates costs from invoked lambdas only', async () => {diff --git a/packages/serverless-client/src/test/renderer-transport.test.ts b/packages/serverless-client/src/test/renderer-transport.test.tsnew file mode 100644index 0000000000..3372bea02d--- /dev/null+++ b/packages/serverless-client/src/test/renderer-transport.test.ts@@ -0,0 +1,56 @@+import {expect, test} from 'bun:test';+import {+ parseS3RendererStatus,+ rendererTransportArtifactKey,+ type S3RendererStatus,+ rendererTransportStatusKey,+} from '../renderer-transport';++const completedStatus: S3RendererStatus = {+ schema: 1,+ state: 'completed',+ chunk: 2,+ attempt: 3,+ lambdaInvoked: true,+ renderedFrames: 20,+ encodedFrames: 20,+ startedAt: 100,+ completedAt: 200,+ videoKey: 'video',+ audioKey: null,+ artifacts: [],+};++test('renderer transport keys isolate chunks and attempts', () => {+ expect(+ rendererTransportStatusKey({renderId: 'render', chunk: 2, attempt: 3}),+ ).toBe('renders/render/transport/chunks/2/attempt-3/status.json');+ expect(+ rendererTransportArtifactKey({renderId: 'render', chunk: 2, attempt: 3}, 4),+ ).toBe('renders/render/transport/chunks/2/attempt-3/artifacts/4');+});++test('renderer status parser accepts only the requested protocol identity', () => {+ expect(+ parseS3RendererStatus({+ value: completedStatus,+ expectedChunk: 2,+ expectedAttempt: 3,+ }),+ ).toEqual(completedStatus);++ expect(() =>+ parseS3RendererStatus({+ value: completedStatus,+ expectedChunk: 2,+ expectedAttempt: 2,+ }),+ ).toThrow('expected chunk 2, attempt 2');+ expect(() =>+ parseS3RendererStatus({+ value: {...completedStatus, schema: 2},+ expectedChunk: 2,+ expectedAttempt: 3,+ }),+ ).toThrow('Unsupported renderer S3 status schema');+});diff --git a/packages/serverless/src/create-post-render-data.ts b/packages/serverless/src/create-post-render-data.tsindex 5e3e2d7957..1b4e3f1fe5 100644--- a/packages/serverless/src/create-post-render-data.ts+++ b/packages/serverless/src/create-post-render-data.ts@@ -61,6 +61,7 @@ export const createPostRenderData = <Provider extends CloudProvider>({}const endTime = Date.now();+ const billingCurrency = providerSpecifics.getBillingCurrency(region);if (overallProgress.timeToEncode === null) {throw new Error('Expected time to encode to be set');@@ -72,14 +73,17 @@ export const createPostRenderData = <Provider extends CloudProvider>({return {cost: {- currency: 'USD',+ currency: billingCurrency,disclaimer:'Estimated cost for function invocations only. Does not include cost for storage and data transfer.',estimatedCost: cost,- estimatedDisplayCost: `$${new Intl.NumberFormat('en-US', {- currency: 'USD',- currencyDisplay: 'narrowSymbol',- }).format(cost)}`,+ estimatedDisplayCost: `${billingCurrency === 'CNY' ? '¥' : '$'}${new Intl.NumberFormat(+ 'en-US',+ {+ currency: billingCurrency,+ currencyDisplay: 'narrowSymbol',+ },+ ).format(cost)}`,},outputFile: outputFile.url,timeToFinish,diff --git a/packages/serverless/src/handlers/launch.ts b/packages/serverless/src/handlers/launch.tsindex 4ee0fcfe68..0aa5ffc86e 100644--- a/packages/serverless/src/handlers/launch.ts+++ b/packages/serverless/src/handlers/launch.ts@@ -21,6 +21,7 @@ import {getExpectedOutName,getNeedsToUpload,MAX_FUNCTIONS_PER_RENDER,+ rendererTransportPrefix,serializeOrThrow,ServerlessRoutines,validateFramesPerFunction,@@ -37,7 +38,7 @@ import {makeOverallRenderProgress} from '../overall-render-progress';import {planFrameRanges} from '../plan-frame-ranges';import type {InsideFunctionSpecifics} from '../provider-implementation';import {removeOutnameCredentials} from '../remove-outname-credentials';-import {streamRendererFunctionWithRetry} from '../stream-renderer';+import {renderRendererFunctionWithRetry} from '../stream-renderer';import {validateComposition} from '../validate-composition';import {sendTelemetryEvent} from './send-telemetry-event';@@ -491,7 +492,7 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({await Promise.all(lambdaPayloads.map(async (payload) => {- await streamRendererFunctionWithRetry({+ await renderRendererFunctionWithRetry({files,functionName: rendererFunctionName,outdir,@@ -502,6 +503,7 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({providerSpecifics,insideFunctionSpecifics,requestHandler: null,+ expectedBucketOwner: options.expectedBucketOwner,});}),);@@ -544,6 +546,41 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({sampleRate: params.sampleRate,});+ if (+ providerSpecifics.getRendererFunctionTransport(+ insideFunctionSpecifics.getCurrentRegionInFunction(),+ ) === 's3'+ ) {+ try {+ const transportObjects = await providerSpecifics.listObjects({+ bucketName: params.bucketName,+ prefix: rendererTransportPrefix(params.renderId),+ region: insideFunctionSpecifics.getCurrentRegionInFunction(),+ expectedBucketOwner: options.expectedBucketOwner,+ forcePathStyle: params.forcePathStyle,+ requestHandler: null,+ });+ await Promise.all(+ transportObjects.map((object) =>+ providerSpecifics.deleteFile({+ bucketName: params.bucketName,+ key: object.Key,+ region: insideFunctionSpecifics.getCurrentRegionInFunction(),+ customCredentials: null,+ forcePathStyle: params.forcePathStyle,+ requestHandler: null,+ }),+ ),+ );+ } catch (err) {+ RenderInternals.Log.warn(+ {indent: false, logLevel: params.logLevel},+ 'Could not clean up renderer transport objects',+ err,+ );+ }+ }+return postRenderData;};diff --git a/packages/serverless/src/handlers/renderer.ts b/packages/serverless/src/handlers/renderer.tsindex 9ee3ce8229..49acca32d0 100644--- a/packages/serverless/src/handlers/renderer.ts+++ b/packages/serverless/src/handlers/renderer.ts@@ -49,6 +49,7 @@ const renderHandler = async <Provider extends CloudProvider>({providerSpecifics,insideFunctionSpecifics,onBrowserInstance,+ onMediaFiles,}: {params: ServerlessPayload<Provider>;options: Options;@@ -57,6 +58,14 @@ const renderHandler = async <Provider extends CloudProvider>({providerSpecifics: ProviderSpecifics<Provider>;insideFunctionSpecifics: InsideFunctionSpecifics<Provider>;onBrowserInstance: (browserInstance: LaunchedBrowser) => void;+ onMediaFiles:+ | ((options: {+ videoOutputLocation: string;+ audioOutputLocation: string | null;+ isAudioOnly: boolean;+ completedAt: number;+ }) => Promise<void>)+ | null;}): Promise<{}> => {if (params.type !== ServerlessRoutines.renderer) {throw new Error('Params must be renderer');@@ -381,19 +390,27 @@ const renderHandler = async <Provider extends CloudProvider>({params.logLevel,);- if (audioOutputLocation) {- const audioChunkTimer = insideFunctionSpecifics.timer(- 'Sending audio chunk',- params.logLevel,- );- await onStream({- type: 'audio-chunk-rendered',- payload: new Uint8Array(fs.readFileSync(audioOutputLocation)),+ const endRendered = Date.now();+ if (onMediaFiles) {+ await onMediaFiles({+ videoOutputLocation,+ audioOutputLocation,+ isAudioOnly: NoReactAPIs.isAudioCodec(params.codec),+ completedAt: endRendered,});- audioChunkTimer.end();- }+ } else {+ if (audioOutputLocation) {+ const audioChunkTimer = insideFunctionSpecifics.timer(+ 'Sending audio chunk',+ params.logLevel,+ );+ await onStream({+ type: 'audio-chunk-rendered',+ payload: new Uint8Array(fs.readFileSync(audioOutputLocation)),+ });+ audioChunkTimer.end();+ }- if (videoOutputLocation) {const videoChunkTimer = insideFunctionSpecifics.timer('Sending main chunk',params.logLevel,@@ -407,8 +424,6 @@ const renderHandler = async <Provider extends CloudProvider>({videoChunkTimer.end();}- const endRendered = Date.now();-await onStream({type: 'chunk-complete',payload: {@@ -450,6 +465,7 @@ export const rendererHandler = async <Provider extends CloudProvider>({providerSpecifics,requestContext,insideFunctionSpecifics,+ onMediaFiles,}: {params: ServerlessPayload<Provider>;options: Options;@@ -457,6 +473,14 @@ export const rendererHandler = async <Provider extends CloudProvider>({requestContext: RequestContext;providerSpecifics: ProviderSpecifics<Provider>;insideFunctionSpecifics: InsideFunctionSpecifics<Provider>;+ onMediaFiles:+ | ((options: {+ videoOutputLocation: string;+ audioOutputLocation: string | null;+ isAudioOnly: boolean;+ completedAt: number;+ }) => Promise<void>)+ | null;}): Promise<void> => {if (params.type !== ServerlessRoutines.renderer) {throw new Error('Params must be renderer');@@ -479,6 +503,7 @@ export const rendererHandler = async <Provider extends CloudProvider>({onBrowserInstance: (browserInstance) => {instance = browserInstance;},+ onMediaFiles,});} catch (err) {if (process.env.NODE_ENV === 'test') {@@ -508,7 +533,7 @@ export const rendererHandler = async <Provider extends CloudProvider>({(err as Error).stack,);- onStream({+ await onStream({type: 'error-occurred',payload: {error: (err as Error).stack as string,diff --git a/packages/serverless/src/handlers/still.ts b/packages/serverless/src/handlers/still.tsindex 6f7d719f53..a25381d11f 100644--- a/packages/serverless/src/handlers/still.ts+++ b/packages/serverless/src/handlers/still.ts@@ -395,7 +395,12 @@ const innerStillHandler = async <Provider extends CloudProvider>(size,sizeInBytes: size,bucketName,- estimatedPrice: formatCostsInfo(estimatedPrice),+ estimatedPrice: formatCostsInfo(+ estimatedPrice,+ providerSpecifics.getBillingCurrency(+ insideFunctionSpecifics.getCurrentRegionInFunction(),+ ),+ ),renderId,outKey,receivedArtifacts: receivedArtifact,diff --git a/packages/serverless/src/inner-routine.ts b/packages/serverless/src/inner-routine.tsindex a5f6425226..273831f08e 100644--- a/packages/serverless/src/inner-routine.ts+++ b/packages/serverless/src/inner-routine.ts@@ -23,6 +23,7 @@ import {getWarm, setWarm} from './is-warm';import {setCurrentRequestId, stopLeakDetection} from './leak-detection';import {printLoggingGrepHelper} from './print-logging-grep-helper';import type {InsideFunctionSpecifics} from './provider-implementation';+import {makeS3RendererOutput} from './s3-renderer-output';import type {ResponseStreamWriter} from './streaming/stream-writer';export const innerHandler = async <Provider extends CloudProvider>({@@ -127,6 +128,15 @@ export const innerHandler = async <Provider extends CloudProvider>({providerSpecifics,insideFunctionSpecifics,})+ .then((r) => {+ if (!params.streamed && r.type === 'error') {+ return responseWriter+ .write(new TextEncoder().encode(JSON.stringify(r)))+ .then(() => r);+ }++ return r;+ }).then((r) => {resolve(r);})@@ -265,6 +275,19 @@ export const innerHandler = async <Provider extends CloudProvider>({);}+ const region = insideFunctionSpecifics.getCurrentRegionInFunction();+ const transport = providerSpecifics.getRendererFunctionTransport(region);+ const s3Output =+ transport === 's3'+ ? makeS3RendererOutput({+ params,+ expectedBucketOwner: currentUserId,+ region,+ providerSpecifics,+ })+ : null;+ await s3Output?.initialize();+await new Promise((resolve, reject) => {rendererHandler({params,@@ -272,24 +295,27 @@ export const innerHandler = async <Provider extends CloudProvider>({expectedBucketOwner: currentUserId,isWarm,},- onStream: (payload) => {- const message = makeStreamPayload({- message: payload,- });-- const writeProm = responseWriter.write(message);+ onStream: s3Output+ ? s3Output.onStream+ : (payload) => {+ const message = makeStreamPayload({+ message: payload,+ });- return new Promise<void>((innerResolve, innerReject) => {- writeProm- .then(() => {- innerResolve();- })- .catch((err) => {- reject(err);- innerReject(err);+ const writeProm = responseWriter.write(message);++ return new Promise<void>((innerResolve, innerReject) => {+ writeProm+ .then(() => {+ innerResolve();+ })+ .catch((err) => {+ reject(err);+ innerReject(err);+ });});- });- },+ },+ onMediaFiles: s3Output?.uploadMediaAndComplete ?? null,requestContext: context,providerSpecifics,insideFunctionSpecifics,diff --git a/packages/serverless/src/s3-renderer-output.ts b/packages/serverless/src/s3-renderer-output.tsnew file mode 100644index 0000000000..98030bf06e--- /dev/null+++ b/packages/serverless/src/s3-renderer-output.ts@@ -0,0 +1,251 @@+import {createReadStream} from 'node:fs';+import type {EmittedArtifact} from '@remotion/renderer';+import type {+ CloudProvider,+ OnStream,+ ProviderSpecifics,+ S3RendererArtifactMetadata,+ S3RendererStatus,+ ServerlessPayload,+} from '@remotion/serverless-client';+import {+ deserializeArtifact,+ rendererTransportArtifactKey,+ rendererTransportAudioKey,+ rendererTransportStatusKey,+ rendererTransportVideoKey,+ ServerlessRoutines,+} from '@remotion/serverless-client';++export const makeS3RendererOutput = <Provider extends CloudProvider>({+ params,+ expectedBucketOwner,+ region,+ providerSpecifics,+}: {+ params: ServerlessPayload<Provider>;+ expectedBucketOwner: string;+ region: Provider['region'];+ providerSpecifics: ProviderSpecifics<Provider>;+}) => {+ if (params.type !== ServerlessRoutines.renderer) {+ throw new Error('Expected renderer payload');+ }++ const startedAt = Date.now();+ let lambdaInvoked = true;+ let renderedFrames = 0;+ let encodedFrames = 0;+ let writeQueue = Promise.resolve();+ const artifacts: Array<{+ key: string;+ metadata: S3RendererArtifactMetadata;+ }> = [];+ const artifactUploads: Promise<void>[] = [];++ const statusKey = rendererTransportStatusKey({+ renderId: params.renderId,+ chunk: params.chunk,+ attempt: params.attempt,+ });++ const writeStatus = (status: S3RendererStatus) => {+ writeQueue = writeQueue.then(() =>+ providerSpecifics.writeFile({+ bucketName: params.bucketName,+ key: statusKey,+ body: JSON.stringify(status),+ region,+ privacy: 'private',+ expectedBucketOwner,+ downloadBehavior: null,+ customCredentials: null,+ forcePathStyle: params.forcePathStyle,+ storageClass: null,+ requestHandler: null,+ }),+ );+ return writeQueue;+ };++ const runningStatus = (): S3RendererStatus => ({+ schema: 1,+ state: 'running',+ chunk: params.chunk,+ attempt: params.attempt,+ lambdaInvoked,+ renderedFrames,+ encodedFrames,+ startedAt,+ });++ const initialize = () => writeStatus(runningStatus());++ const onStream: OnStream<Provider> = async (message) => {+ if (message.type === 'lambda-invoked') {+ lambdaInvoked = true;+ await writeStatus(runningStatus());+ return;+ }++ if (message.type === 'frames-rendered') {+ renderedFrames = Math.max(renderedFrames, message.payload.rendered);+ encodedFrames = Math.max(encodedFrames, message.payload.encoded);+ await writeStatus(runningStatus());+ return;+ }++ if (message.type === 'artifact-emitted') {+ const artifact = deserializeArtifact(message.payload.artifact);+ const key = rendererTransportArtifactKey(+ {+ renderId: params.renderId,+ chunk: params.chunk,+ attempt: params.attempt,+ },+ artifacts.length,+ );+ const metadata: S3RendererArtifactMetadata = {+ filename: artifact.filename,+ frame: artifact.frame,+ binary: artifact.content instanceof Uint8Array,+ downloadBehavior: artifact.downloadBehavior,+ };+ artifacts.push({key, metadata});+ const upload = providerSpecifics.writeFile({+ bucketName: params.bucketName,+ key,+ body: artifact.content,+ region,+ privacy: 'private',+ expectedBucketOwner,+ downloadBehavior: null,+ customCredentials: null,+ forcePathStyle: params.forcePathStyle,+ storageClass: null,+ requestHandler: null,+ });+ artifactUploads.push(upload);+ await upload;+ return;+ }++ if (message.type === 'error-occurred') {+ await writeStatus({+ schema: 1,+ state: 'failed',+ chunk: params.chunk,+ attempt: params.attempt,+ lambdaInvoked,+ renderedFrames,+ encodedFrames,+ startedAt,+ failedAt: Date.now(),+ errorInfo: message.payload.errorInfo,+ shouldRetry: message.payload.shouldRetry,+ });+ return;+ }++ if (message.type === 'chunk-complete') {+ return;+ }++ throw new Error(+ `Unexpected ${message.type} event in S3 renderer transport`,+ );+ };++ const uploadMediaAndComplete = async ({+ videoOutputLocation,+ audioOutputLocation,+ isAudioOnly,+ completedAt,+ }: {+ videoOutputLocation: string;+ audioOutputLocation: string | null;+ isAudioOnly: boolean;+ completedAt: number;+ }) => {+ const videoKey = isAudioOnly+ ? null+ : rendererTransportVideoKey({+ renderId: params.renderId,+ chunk: params.chunk,+ attempt: params.attempt,+ });+ const audioKey =+ audioOutputLocation || isAudioOnly+ ? rendererTransportAudioKey({+ renderId: params.renderId,+ chunk: params.chunk,+ attempt: params.attempt,+ })+ : null;++ await Promise.all([+ ...artifactUploads,+ videoKey+ ? providerSpecifics.writeFile({+ bucketName: params.bucketName,+ key: videoKey,+ body: createReadStream(videoOutputLocation),+ region,+ privacy: 'private',+ expectedBucketOwner,+ downloadBehavior: null,+ customCredentials: null,+ forcePathStyle: params.forcePathStyle,+ storageClass: null,+ requestHandler: null,+ })+ : null,+ audioKey+ ? providerSpecifics.writeFile({+ bucketName: params.bucketName,+ key: audioKey,+ body: createReadStream(audioOutputLocation ?? videoOutputLocation),+ region,+ privacy: 'private',+ expectedBucketOwner,+ downloadBehavior: null,+ customCredentials: null,+ forcePathStyle: params.forcePathStyle,+ storageClass: null,+ requestHandler: null,+ })+ : null,+ ]);++ lambdaInvoked = true;+ await writeStatus({+ schema: 1,+ state: 'completed',+ chunk: params.chunk,+ attempt: params.attempt,+ lambdaInvoked: true,+ renderedFrames,+ encodedFrames,+ startedAt,+ completedAt,+ videoKey,+ audioKey,+ artifacts,+ });+ };++ return {initialize, onStream, uploadMediaAndComplete};+};++export const artifactFromS3 = ({+ metadata,+ content,+}: {+ metadata: S3RendererArtifactMetadata;+ content: Uint8Array;+}): EmittedArtifact => ({+ filename: metadata.filename,+ frame: metadata.frame,+ downloadBehavior: metadata.downloadBehavior,+ content: metadata.binary ? content : new TextDecoder().decode(content),+});diff --git a/packages/serverless/src/stream-renderer.ts b/packages/serverless/src/stream-renderer.tsindex 6fb907aa25..61467536b5 100644--- a/packages/serverless/src/stream-renderer.ts+++ b/packages/serverless/src/stream-renderer.ts@@ -1,4 +1,5 @@-import {writeFileSync} from 'fs';+import {createWriteStream, writeFileSync} from 'fs';+import {pipeline} from 'node:stream/promises';import {join} from 'path';import type {EmittedArtifact, LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';@@ -10,10 +11,14 @@ import type {} from '@remotion/serverless-client';import {deserializeArtifact,+ parseS3RendererStatus,+ rendererTransportStatusKey,ServerlessRoutines,+ streamToString,} from '@remotion/serverless-client';import type {OverallProgressHelper} from './overall-render-progress';import type {InsideFunctionSpecifics} from './provider-implementation';+import {artifactFromS3} from './s3-renderer-output';type StreamRendererResponse =| {@@ -47,6 +52,7 @@ const streamRenderer = <Provider extends CloudProvider>({providerSpecifics: ProviderSpecifics<Provider>;insideFunctionSpecifics: InsideFunctionSpecifics<Provider>;requestHandler: Provider['requestHandler'] | null;+ expectedBucketOwner: string;}) => {if (payload.type !== ServerlessRoutines.renderer) {throw new Error('Expected renderer type');@@ -198,7 +204,300 @@ const streamRenderer = <Provider extends CloudProvider>({});};-export const streamRendererFunctionWithRetry = async <+const wait = (duration: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, duration));++const isMissingObjectError = (err: unknown) => {+ const error = err as {name?: string; Code?: string; code?: string};+ return (+ error.name === 'NoSuchKey' ||+ error.name === 'NotFound' ||+ error.Code === 'NoSuchKey' ||+ error.code === 'NoSuchKey'+ );+};++const readStreamAsBytes = async (+ stream: NodeJS.ReadableStream,+): Promise<Uint8Array> => {+ const chunks: Uint8Array[] = [];+ for await (const chunk of stream) {+ chunks.push(+ typeof chunk === 'string'+ ? new TextEncoder().encode(chunk)+ : new Uint8Array(chunk),+ );+ }++ const size = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);+ const result = new Uint8Array(size);+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return result;+};++const s3Renderer = async <Provider extends CloudProvider>({+ payload,+ functionName,+ outdir,+ overallProgress,+ files,+ logLevel,+ onArtifact,+ providerSpecifics,+ insideFunctionSpecifics,+ requestHandler,+ expectedBucketOwner,+}: {+ payload: ServerlessPayload<Provider>;+ functionName: string;+ outdir: string;+ overallProgress: OverallProgressHelper<Provider>;+ files: string[];+ logLevel: LogLevel;+ onArtifact: (asset: EmittedArtifact) => {alreadyExisted: boolean};+ providerSpecifics: ProviderSpecifics<Provider>;+ insideFunctionSpecifics: InsideFunctionSpecifics<Provider>;+ requestHandler: Provider['requestHandler'] | null;+ expectedBucketOwner: string;+}): Promise<StreamRendererResponse> => {+ if (payload.type !== ServerlessRoutines.renderer) {+ throw new Error('Expected renderer type');+ }++ const region = insideFunctionSpecifics.getCurrentRegionInFunction();+ try {+ await providerSpecifics.callFunctionAsync({+ functionName,+ payload,+ region,+ timeoutInTest: 12000,+ type: ServerlessRoutines.renderer,+ requestHandler,+ });+ } catch (err) {+ return {+ type: 'error',+ error: (err as Error).stack ?? (err as Error).message,+ shouldRetry: providerSpecifics.isFlakyError(err as Error),+ };+ }++ const statusKey = rendererTransportStatusKey({+ renderId: payload.renderId,+ chunk: payload.chunk,+ attempt: payload.attempt,+ });+ let lastRendered = 0;+ let lastEncoded = 0;+ let lambdaInvoked = false;+ let pollingInterval = 250;+ const timeoutTimestamp = overallProgress.get().timeoutTimestamp - 1000;++ while (Date.now() < timeoutTimestamp) {+ try {+ const statusStream = await providerSpecifics.readFile({+ bucketName: payload.bucketName,+ key: statusKey,+ region,+ expectedBucketOwner,+ forcePathStyle: payload.forcePathStyle,+ requestHandler,+ });+ const status = parseS3RendererStatus({+ value: JSON.parse(await streamToString(statusStream)),+ expectedChunk: payload.chunk,+ expectedAttempt: payload.attempt,+ });++ if (status.lambdaInvoked && !lambdaInvoked) {+ lambdaInvoked = true;+ overallProgress.setLambdaInvoked(payload.chunk);+ }++ if (+ status.renderedFrames > lastRendered ||+ status.encodedFrames > lastEncoded+ ) {+ lastRendered = Math.max(lastRendered, status.renderedFrames);+ lastEncoded = Math.max(lastEncoded, status.encodedFrames);+ overallProgress.setFrames({+ index: payload.chunk,+ rendered: lastRendered,+ encoded: lastEncoded,+ });+ }++ if (status.state === 'failed') {+ overallProgress.addErrorWithoutUpload(status.errorInfo);+ overallProgress.setFrames({+ encoded: 0,+ index: payload.chunk,+ rendered: 0,+ });+ await providerSpecifics+ .deleteFile({+ bucketName: payload.bucketName,+ key: statusKey,+ region,+ customCredentials: null,+ forcePathStyle: payload.forcePathStyle,+ requestHandler,+ })+ .catch(() => undefined);+ return {+ type: 'error',+ error: status.errorInfo.stack,+ shouldRetry: status.shouldRetry,+ };+ }++ if (status.state === 'completed') {+ const downloadedKeys: string[] = [];+ const emittedArtifacts: EmittedArtifact[] = [];+ for (const artifact of status.artifacts) {+ let artifactStream;+ try {+ artifactStream = await providerSpecifics.readFile({+ bucketName: payload.bucketName,+ key: artifact.key,+ region,+ expectedBucketOwner,+ forcePathStyle: payload.forcePathStyle,+ requestHandler,+ });+ } catch (err) {+ if (isMissingObjectError(err)) {+ throw new Error(+ `Renderer completed manifest references missing artifact object ${artifact.key}`,+ );+ }++ throw err;+ }++ emittedArtifacts.push(+ artifactFromS3({+ metadata: artifact.metadata,+ content: await readStreamAsBytes(artifactStream),+ }),+ );+ downloadedKeys.push(artifact.key);+ }++ const downloadedFiles: string[] = [];+ for (const [type, key] of [+ ['video', status.videoKey],+ ['audio', status.audioKey],+ ] as const) {+ if (!key) {+ continue;+ }++ const filename = join(+ outdir,+ `chunk-${String(payload.chunk).padStart(8, '0')}-${type}`,+ );+ let media;+ try {+ media = await providerSpecifics.readFile({+ bucketName: payload.bucketName,+ key,+ region,+ expectedBucketOwner,+ forcePathStyle: payload.forcePathStyle,+ requestHandler,+ });+ } catch (err) {+ if (isMissingObjectError(err)) {+ throw new Error(+ `Renderer completed manifest references missing media object ${key}`,+ );+ }++ throw err;+ }++ await pipeline(media, createWriteStream(filename));+ downloadedFiles.push(filename);+ downloadedKeys.push(key);+ }++ for (const emittedArtifact of emittedArtifacts) {+ const {alreadyExisted} = onArtifact(emittedArtifact);+ if (alreadyExisted) {+ return {+ type: 'error',+ error: `Chunk ${payload.chunk} emitted an asset filename ${emittedArtifact.filename} at frame ${emittedArtifact.frame} but there is already another artifact with the same name. https://remotion.dev/docs/artifacts`,+ shouldRetry: false,+ };+ }+ }++ files.push(...downloadedFiles);+ overallProgress.addChunkCompleted(+ payload.chunk,+ status.startedAt,+ status.completedAt,+ );+ for (const key of [...downloadedKeys, statusKey]) {+ await providerSpecifics+ .deleteFile({+ bucketName: payload.bucketName,+ key,+ region,+ customCredentials: null,+ forcePathStyle: payload.forcePathStyle,+ requestHandler,+ })+ .catch((err) => {+ RenderInternals.Log.warn(+ {indent: false, logLevel},+ `Could not clean up renderer transport object ${key}`,+ err,+ );+ });+ }++ return {type: 'success'};+ }+ } catch (err) {+ if (+ !isMissingObjectError(err) &&+ !providerSpecifics.isFlakyError(err as Error)+ ) {+ return {+ type: 'error',+ error: (err as Error).stack ?? (err as Error).message,+ shouldRetry: false,+ };+ }+ }++ await wait(pollingInterval);+ pollingInterval = Math.min(2000, Math.round(pollingInterval * 1.5));+ }++ return {+ type: 'error',+ error: `Renderer chunk ${payload.chunk}, attempt ${payload.attempt} did not publish a status before the launcher deadline. Logs: ${providerSpecifics.getLoggingUrlForRendererFunction(+ {+ region,+ functionName,+ rendererFunctionName: functionName,+ renderId: payload.renderId,+ chunk: payload.chunk,+ },+ )}`,+ shouldRetry: false,+ };+};++export const renderRendererFunctionWithRetry = async <Provider extends CloudProvider,>({payload,@@ -211,6 +510,7 @@ export const streamRendererFunctionWithRetry = async <providerSpecifics,insideFunctionSpecifics,requestHandler,+ expectedBucketOwner,}: {payload: ServerlessPayload<Provider>;functionName: string;@@ -222,12 +522,16 @@ export const streamRendererFunctionWithRetry = async <providerSpecifics: ProviderSpecifics<Provider>;insideFunctionSpecifics: InsideFunctionSpecifics<Provider>;requestHandler: Provider['requestHandler'] | null;+ expectedBucketOwner: string;}): Promise<unknown> => {if (payload.type !== ServerlessRoutines.renderer) {throw new Error('Expected renderer type');}- const result = await streamRenderer({+ const transport = providerSpecifics.getRendererFunctionTransport(+ insideFunctionSpecifics.getCurrentRegionInFunction(),+ );+ const result = await (transport === 's3' ? s3Renderer : streamRenderer)({files,functionName,outdir,@@ -238,10 +542,11 @@ export const streamRendererFunctionWithRetry = async <providerSpecifics,insideFunctionSpecifics,requestHandler,+ expectedBucketOwner,});if (result.type === 'error') {- if (!result.shouldRetry) {+ if (!result.shouldRetry || payload.retriesLeft <= 0) {throw new Error(result.error);}@@ -251,7 +556,7 @@ export const streamRendererFunctionWithRetry = async <chunk: payload.chunk,});- return streamRendererFunctionWithRetry({+ return renderRendererFunctionWithRetry({files,functionName,outdir,@@ -266,6 +571,7 @@ export const streamRendererFunctionWithRetry = async <providerSpecifics,insideFunctionSpecifics,requestHandler,+ expectedBucketOwner,});}};diff --git a/packages/serverless/src/test/inner-routine.test.ts b/packages/serverless/src/test/inner-routine.test.tsnew file mode 100644index 0000000000..5f8b013e76--- /dev/null+++ b/packages/serverless/src/test/inner-routine.test.ts@@ -0,0 +1,76 @@+import {expect, test} from 'bun:test';+import type {+ CloudProvider,+ ProviderSpecifics,+} from '@remotion/serverless-client';+import {VERSION} from '@remotion/serverless-client';+import {innerHandler} from '../inner-routine';+import type {InsideFunctionSpecifics} from '../provider-implementation';++type MockProvider = CloudProvider<+ 'mock-region',+ Record<string, never>,+ Record<string, never>,+ 'normal',+ Record<string, never>+>;++test('buffered still errors are written to the response', async () => {+ const chunks: Uint8Array[] = [];+ let ended = false;++ await innerHandler<MockProvider>({+ params: {+ type: 'still',+ streamed: false,+ version: VERSION,+ downloadBehavior: 'invalid',+ deleteAfter: null,+ maxRetries: 0,+ frame: 0,+ attempt: 1,+ logLevel: 'error',+ } as never,+ responseWriter: {+ write: (message) => {+ chunks.push(message);+ return Promise.resolve();+ },+ end: () => {+ ended = true;+ return Promise.resolve();+ },+ },+ context: {+ awsRequestId: 'request-id',+ invokedFunctionArn:+ 'arn:aws:lambda:mock-region:123456789012:function:test',+ getRemainingTimeInMillis: () => 120_000,+ },+ providerSpecifics: {+ isFlakyError: () => false,+ printLoggingHelper: false,+ randomHash: () => 'random-hash',+ validateDeleteAfter: () => undefined,+ } as unknown as ProviderSpecifics<MockProvider>,+ insideFunctionSpecifics: {+ deleteTmpDir: () => Promise.resolve(),+ generateRandomId: () => 'render-id',+ } as unknown as InsideFunctionSpecifics<MockProvider>,+ });++ expect(ended).toBe(true);+ expect(chunks).toHaveLength(1);+ const response = JSON.parse(new TextDecoder().decode(chunks[0])) as {+ type: string;+ message: string;+ stack: string;+ };+ expect(response).toMatchObject({+ type: 'error',+ message: 'downloadBehavior must be null or an object',+ });+ expect(response.stack).toContain(+ 'Error: downloadBehavior must be null or an object',+ );+});diff --git a/packages/serverless/src/test/overall-render-progress.test.ts b/packages/serverless/src/test/overall-render-progress.test.tsindex dea49f0a5e..bf07e403c6 100644--- a/packages/serverless/src/test/overall-render-progress.test.ts+++ b/packages/serverless/src/test/overall-render-progress.test.ts@@ -36,6 +36,9 @@ const makeProviderSpecifics = ({getBuckets: () => Promise.resolve([]),getChromiumPath: () => null,getEphemeralStorageForPriceCalculation: () => 512,+ getBillingCurrency: () => 'USD',+ getRendererFunctionTransport: () => 'response-streaming',+ getServiceDnsSuffix: () => 'example.com',getFunctions: () => Promise.resolve([]),getLoggingUrlForMethod: () => 'logs',getLoggingUrlForRendererFunction: () => 'logs',diff --git a/packages/serverless/src/test/s3-renderer-launcher.test.ts b/packages/serverless/src/test/s3-renderer-launcher.test.tsnew file mode 100644index 0000000000..41e0ce1c9f--- /dev/null+++ b/packages/serverless/src/test/s3-renderer-launcher.test.ts@@ -0,0 +1,168 @@+import {expect, test} from 'bun:test';+import {mkdtemp, readFile, rm} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {Readable} from 'node:stream';+import type {EmittedArtifact} from '@remotion/renderer';+import type {+ ProviderSpecifics,+ S3RendererStatus,+} from '@remotion/serverless-client';+import {+ rendererTransportArtifactKey,+ rendererTransportStatusKey,+ rendererTransportVideoKey,+} from '@remotion/serverless-client';+import type {OverallProgressHelper} from '../overall-render-progress';+import type {InsideFunctionSpecifics} from '../provider-implementation';+import {renderRendererFunctionWithRetry} from '../stream-renderer';++type MockProvider = {+ type: 'mock';+ region: 'mock-region';+ receivedArtifactType: never;+ creationFunctionOptions: never;+ storageClass: never;+ requestHandler: never;+};++test('S3 launcher invokes, polls, downloads, and normalizes a renderer result', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'remotion-s3-launcher-'));+ try {+ const objects = new Map<string, Uint8Array>();+ const deleted: string[] = [];+ let asyncInvocations = 0;+ const videoKey = rendererTransportVideoKey({+ renderId: 'render-id',+ chunk: 0,+ attempt: 1,+ });+ const artifactKey = rendererTransportArtifactKey(+ {renderId: 'render-id', chunk: 0, attempt: 1},+ 0,+ );+ const statusKey = rendererTransportStatusKey({+ renderId: 'render-id',+ chunk: 0,+ attempt: 1,+ });+ const status: S3RendererStatus = {+ schema: 1,+ state: 'completed',+ chunk: 0,+ attempt: 1,+ lambdaInvoked: true,+ renderedFrames: 12,+ encodedFrames: 12,+ startedAt: 100,+ completedAt: 200,+ videoKey,+ audioKey: null,+ artifacts: [+ {+ key: artifactKey,+ metadata: {+ filename: 'artifact.txt',+ frame: 3,+ binary: false,+ downloadBehavior: null,+ },+ },+ ],+ };+ const providerSpecifics = {+ getRendererFunctionTransport: () => 's3',+ callFunctionAsync: () => {+ asyncInvocations++;+ objects.set(videoKey, new TextEncoder().encode('video'));+ objects.set(artifactKey, new TextEncoder().encode('artifact'));+ objects.set(+ statusKey,+ new TextEncoder().encode(JSON.stringify(status)),+ );+ return Promise.resolve();+ },+ readFile: ({key}: {key: string}) => {+ const value = objects.get(key);+ if (!value) {+ const error = new Error(`Missing ${key}`);+ error.name = 'NoSuchKey';+ throw error;+ }++ return Promise.resolve(Readable.from([value]));+ },+ deleteFile: ({key}: {key: string}) => {+ deleted.push(key);+ objects.delete(key);+ return Promise.resolve();+ },+ isFlakyError: () => false,+ getLoggingUrlForRendererFunction: () => 'https://logs.example.com',+ } as unknown as ProviderSpecifics<MockProvider>;++ const frames: Array<{rendered: number; encoded: number}> = [];+ let lambdasInvoked = 0;+ let completedChunks = 0;+ const overallProgress = {+ get: () => ({timeoutTimestamp: Date.now() + 10_000}),+ setLambdaInvoked: () => {+ lambdasInvoked++;+ },+ setFrames: ({rendered, encoded}: {rendered: number; encoded: number}) => {+ frames.push({rendered, encoded});+ },+ addChunkCompleted: () => {+ completedChunks++;+ },+ } as unknown as OverallProgressHelper<MockProvider>;+ const insideFunctionSpecifics = {+ getCurrentRegionInFunction: () => 'mock-region',+ } as unknown as InsideFunctionSpecifics<MockProvider>;+ const files: string[] = [];+ const artifacts: EmittedArtifact[] = [];++ await renderRendererFunctionWithRetry({+ payload: {+ type: 'renderer',+ bucketName: 'bucket',+ renderId: 'render-id',+ chunk: 0,+ attempt: 1,+ retriesLeft: 1,+ forcePathStyle: false,+ } as never,+ files,+ functionName: 'renderer-function',+ outdir: directory,+ overallProgress,+ logLevel: 'info',+ onArtifact: (artifact) => {+ artifacts.push(artifact);+ return {alreadyExisted: false};+ },+ providerSpecifics,+ insideFunctionSpecifics,+ requestHandler: null,+ expectedBucketOwner: 'owner',+ });++ expect(asyncInvocations).toBe(1);+ expect(lambdasInvoked).toBe(1);+ expect(frames).toEqual([{rendered: 12, encoded: 12}]);+ expect(completedChunks).toBe(1);+ expect(artifacts).toEqual([+ {+ filename: 'artifact.txt',+ frame: 3,+ content: 'artifact',+ downloadBehavior: null,+ },+ ]);+ expect(files).toHaveLength(1);+ expect(await readFile(files[0]!, 'utf8')).toBe('video');+ expect(deleted.sort()).toEqual([artifactKey, statusKey, videoKey].sort());+ } finally {+ await rm(directory, {recursive: true, force: true});+ }+});diff --git a/packages/serverless/src/test/s3-renderer-output.test.ts b/packages/serverless/src/test/s3-renderer-output.test.tsnew file mode 100644index 0000000000..bad3a7060d--- /dev/null+++ b/packages/serverless/src/test/s3-renderer-output.test.ts@@ -0,0 +1,147 @@+import {expect, test} from 'bun:test';+import {mkdtemp, rm, writeFile} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import type {Readable} from 'node:stream';+import type {ProviderSpecifics} from '@remotion/serverless-client';+import {makeS3RendererOutput} from '../s3-renderer-output';++type MockProvider = {+ type: 'mock';+ region: 'mock-region';+ receivedArtifactType: never;+ creationFunctionOptions: never;+ storageClass: never;+ requestHandler: never;+};++const bodyToBytes = async (+ body: string | Uint8Array | NodeJS.ReadableStream,+) => {+ if (typeof body === 'string') {+ return new TextEncoder().encode(body);+ }++ if (body instanceof Uint8Array) {+ return body;+ }++ const chunks: Uint8Array[] = [];+ for await (const chunk of body) {+ chunks.push(+ typeof chunk === 'string'+ ? new TextEncoder().encode(chunk)+ : new Uint8Array(chunk),+ );+ }++ const length = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);+ const result = new Uint8Array(length);+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return result;+};++test('S3 renderer output publishes media and artifacts before completion', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'remotion-s3-output-'));+ try {+ const video = join(directory, 'video');+ const audio = join(directory, 'audio');+ await writeFile(video, 'video-content');+ await writeFile(audio, 'audio-content');++ const objects = new Map<string, Uint8Array>();+ const statusWrites: Array<Record<string, unknown>> = [];+ const providerSpecifics = {+ writeFile: async ({key, body}: {key: string; body: unknown}) => {+ const bytes = await bodyToBytes(body as string | Uint8Array | Readable);+ objects.set(key, bytes);+ if (key.endsWith('/status.json')) {+ statusWrites.push(+ JSON.parse(new TextDecoder().decode(bytes)) as Record<+ string,+ unknown+ >,+ );+ }+ },+ } as unknown as ProviderSpecifics<MockProvider>;+ const output = makeS3RendererOutput({+ params: {+ type: 'renderer',+ bucketName: 'bucket',+ renderId: 'render-id',+ chunk: 1,+ attempt: 2,+ forcePathStyle: false,+ } as never,+ expectedBucketOwner: 'owner',+ region: 'mock-region',+ providerSpecifics,+ });++ await output.initialize();+ await output.onStream({+ type: 'lambda-invoked',+ payload: {attempt: 2},+ });+ await output.onStream({+ type: 'frames-rendered',+ payload: {rendered: 10, encoded: 8},+ });+ await output.onStream({+ type: 'artifact-emitted',+ payload: {+ artifact: {+ filename: 'artifact.txt',+ stringContent: 'artifact-content',+ frame: 4,+ binary: false,+ downloadBehavior: null,+ },+ },+ });+ await output.uploadMediaAndComplete({+ videoOutputLocation: video,+ audioOutputLocation: audio,+ isAudioOnly: false,+ completedAt: 200,+ });++ expect(statusWrites.map((status) => status.state)).toEqual([+ 'running',+ 'running',+ 'running',+ 'completed',+ ]);+ const completed = statusWrites.at(-1)!;+ expect(completed).toMatchObject({+ state: 'completed',+ chunk: 1,+ attempt: 2,+ lambdaInvoked: true,+ renderedFrames: 10,+ encodedFrames: 8,+ videoKey: 'renders/render-id/transport/chunks/1/attempt-2/video',+ audioKey: 'renders/render-id/transport/chunks/1/attempt-2/audio',+ });+ expect(+ new TextDecoder().decode(+ objects.get('renders/render-id/transport/chunks/1/attempt-2/video'),+ ),+ ).toBe('video-content');+ expect(+ new TextDecoder().decode(+ objects.get(+ 'renders/render-id/transport/chunks/1/attempt-2/artifacts/0',+ ),+ ),+ ).toBe('artifact-content');+ } finally {+ await rm(directory, {recursive: true, force: true});+ }+});