Skip to content

🎥 Make videos programmatically with React

@remotion/lambda: Remove the provider adapter, call AWS directly

JonnyBurgerc84ab415eb1d
diff --git a/packages/cli/src/lambda-command.ts b/packages/cli/src/lambda-command.ts
index bffcb1e55b..7e22dcd90b 100644
--- a/packages/cli/src/lambda-command.ts
+++ b/packages/cli/src/lambda-command.ts
@@ -40,13 +40,7 @@ export const lambdaCommand = async (
});
const {LambdaInternals} = require(path);
- await LambdaInternals.executeCommand(
- args,
- remotionRoot,
- logLevel,
- null,
- null,
- );
+ await LambdaInternals.executeCommand(args, remotionRoot, logLevel);
process.exit(0);
} catch (err) {
const manager = StudioServerInternals.getPackageManager({
diff --git a/packages/it-tests/src/lambda/serverless-browser-bundle.test.ts b/packages/it-tests/src/lambda/renderer-pure-browser-bundle.test.ts
similarity index 100%
rename from packages/it-tests/src/lambda/serverless-browser-bundle.test.ts
rename to packages/it-tests/src/lambda/renderer-pure-browser-bundle.test.ts
diff --git a/packages/lambda-client/src/provider-implementation.ts b/packages/lambda-client/src/aws-operations.ts
similarity index 68%
rename from packages/lambda-client/src/provider-implementation.ts
rename to packages/lambda-client/src/aws-operations.ts
index 8010ce6783..5201b8b6df 100644
--- a/packages/lambda-client/src/provider-implementation.ts
+++ b/packages/lambda-client/src/aws-operations.ts
@@ -2,10 +2,8 @@ import type {Readable} from 'node:stream';
import type {StorageClass} from '@aws-sdk/client-s3';
import type {LogLevel} from '@remotion/renderer';
import type {DownloadBehavior} from 'remotion';
-import type {BillingCurrency} from './format-costs-info';
import type {AwsRegion} from './regions';
import type {RenderMetadata} from './render-metadata';
-import type {RendererFunctionTransport} from './renderer-transport';
import type {ServerlessReturnValues} from './return-values';
import type {
CustomCredentials,
@@ -23,7 +21,7 @@ export type ParseFunctionName = (functionName: string) => {
timeoutInSeconds: number;
} | null;
-type DeleteFile = (params: {
+export type DeleteFile = (params: {
bucketName: string;
key: string;
region: AwsRegion;
@@ -38,7 +36,7 @@ export type BucketWithLocation = {
region: AwsRegion;
};
-type BucketExists = (params: {
+export type BucketExists = (params: {
bucketName: string;
region: AwsRegion;
expectedBucketOwner: string | null;
@@ -46,7 +44,7 @@ type BucketExists = (params: {
requestHandler: RequestHandler | null;
}) => Promise<boolean>;
-type ReadFile = (params: {
+export type ReadFile = (params: {
bucketName: string;
key: string;
region: AwsRegion;
@@ -55,14 +53,14 @@ type ReadFile = (params: {
requestHandler: RequestHandler | null;
}) => Promise<Readable>;
-type GetBuckets = (options: {
+export type GetBuckets = (options: {
region: AwsRegion;
forceBucketName: string | null;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
}) => Promise<BucketWithLocation[]>;
-type CreateBucket = (params: {
+export type CreateBucket = (params: {
region: AwsRegion;
bucketName: string;
forcePathStyle: boolean;
@@ -71,7 +69,7 @@ type CreateBucket = (params: {
logLevel: LogLevel;
}) => Promise<void>;
-type ApplyLifeCycle = (params: {
+export type ApplyLifeCycle = (params: {
enableFolderExpiry: boolean | null;
bucketName: string;
region: AwsRegion;
@@ -80,7 +78,7 @@ type ApplyLifeCycle = (params: {
requestHandler: RequestHandler | null;
}) => Promise<void>;
-type ListObjects = (params: {
+export type ListObjects = (params: {
bucketName: string;
prefix: string;
region: AwsRegion;
@@ -90,24 +88,24 @@ type ListObjects = (params: {
continuationToken?: string;
}) => Promise<BucketObject[]>;
-type BucketObject = {
+export type BucketObject = {
Key: string;
LastModified: Date;
ETag: string;
Size: number;
};
-type HeadFile = (params: HeadFileInput) => Promise<HeadFileOutput>;
+export type HeadFile = (params: HeadFileInput) => Promise<HeadFileOutput>;
-type RandomHash = () => string;
+export type RandomHash = () => string;
-type ConvertToServeUrl = (params: {
+export type ConvertToServeUrl = (params: {
urlOrId: string;
region: AwsRegion;
bucketName: string;
}) => string;
-type HeadFileOutput = {
+export type HeadFileOutput = {
LastModified?: Date | undefined;
ContentLength?: number | undefined;
Metadata?: Record<string, string> | undefined;
@@ -135,9 +133,9 @@ export type WriteFileInput = {
metadata?: Record<string, string> | null;
};
-type WriteFile = (params: WriteFileInput) => Promise<void>;
+export type WriteFile = (params: WriteFileInput) => Promise<void>;
-type HeadFileInput = {
+export type HeadFileInput = {
bucketName: string;
key: string;
region: AwsRegion;
@@ -228,50 +226,3 @@ export type FunctionInfo = {
export type GetFunctions = (
params: GetFunctionsInput,
) => Promise<FunctionInfo[]>;
-
-export type ProviderSpecifics = {
- getChromiumPath: () => string | null;
- getBuckets: GetBuckets;
- getBucketPrefix: () => string;
- createBucket: CreateBucket;
- applyLifeCycle: ApplyLifeCycle;
- listObjects: ListObjects;
- deleteFile: DeleteFile;
- bucketExists: BucketExists;
- randomHash: RandomHash;
- readFile: ReadFile;
- writeFile: WriteFile;
- // Whether this destination supports atomic create-only output uploads.
- supportsConditionalOutput: (params: {
- customCredentials: CustomCredentials | null;
- }) => boolean;
- writeFileIfNotExists: WriteFile | null;
- // Normalize permission failures to OutputFileAccessDeniedError and missing files
- // to an error named NotFound. Other errors must propagate unchanged.
- headFile: HeadFile;
- convertToServeUrl: ConvertToServeUrl;
- printLoggingHelper: boolean;
- validateDeleteAfter: (lifeCycleValue: unknown) => void;
- callFunctionAsync: CallFunctionAsync;
- callFunctionStreaming: CallFunctionStreaming;
- callFunctionSync: CallFunctionSync;
- estimatePrice: EstimatePrice;
- getLoggingUrlForRendererFunction: GetLoggingUrlForRendererFunction;
- getLoggingUrlForMethod: GetLoggingUrlForMethod;
- getEphemeralStorageForPriceCalculation: () => number;
- getBillingCurrency: (region: AwsRegion) => BillingCurrency;
- getRendererFunctionTransport: (
- region: AwsRegion,
- ) => RendererFunctionTransport;
- getServiceDnsSuffix: (region: AwsRegion) => string;
- getOutputUrl: GetOutputUrl;
- isFlakyError: (err: Error) => boolean;
- serverStorageProductName: () => string;
- getMaxStillInlinePayloadSize: () => number;
- getMaxNonInlinePayloadSizePerFunction: () => number;
- getAccountId: GetAccountId;
- deleteFunction: DeleteFunction;
- getFunctions: GetFunctions;
- parseFunctionName: ParseFunctionName;
- checkCredentials: () => void;
-};
diff --git a/packages/lambda-client/src/aws-provider.ts b/packages/lambda-client/src/aws-provider.ts
deleted file mode 100644
index 22e1df66d5..0000000000
--- a/packages/lambda-client/src/aws-provider.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import {EventEmitter} from 'node:events';
-import {getAwsRegionMetadata} from './aws-region-metadata';
-import {bucketExistsInRegionImplementation} from './bucket-exists';
-import {callFunctionAsyncImplementation} from './call-lambda-async';
-import {callFunctionWithStreamingImplementation} from './call-lambda-streaming';
-import {callFunctionSyncImplementation} from './call-lambda-sync';
-import {checkCredentials} from './check-credentials';
-import {MAX_EPHEMERAL_STORAGE_IN_MB, REMOTION_BUCKET_PREFIX} from './constants';
-import {convertToServeUrlImplementation} from './convert-to-serve-url';
-import {createBucket} from './create-bucket';
-import {lambdaDeleteFileImplementation} from './delete-file';
-import {deleteFunction} from './delete-function';
-import {estimatePrice} from './estimate-price';
-import {getAccountIdImplementation} from './get-account-id';
-import {getCloudwatchMethodUrl, getCloudwatchRendererUrl} from './get-aws-urls';
-import {getRemotionBuckets} from './get-buckets';
-import {getFunctions} from './get-functions';
-import {getOutputUrlFromMetadata} from './get-output-url-from-metadata';
-import {lambdaHeadFileImplementation} from './head-file';
-import {isFlakyError} from './is-flaky-error';
-import {applyLifeCyleOperation} from './lifecycle-rules';
-import {lambdaLsImplementation} from './list-objects';
-import {parseFunctionName} from './parse-function-name';
-import type {ProviderSpecifics} from './provider-implementation';
-import {randomHashImplementation} from './random-hash';
-import {lambdaReadFileImplementation} from './read-file';
-import {expiryDays} from './shared-constants';
-import {
- lambdaWriteFileImplementation,
- lambdaWriteFileIfNotExistsImplementation,
-} from './write-file';
-
-if (
- /^AWS_Lambda_nodejs(?:18|20|24)[.]x$/.test(
- process.env.AWS_EXECUTION_ENV ?? '',
- ) === true
-) {
- process.env.FONTCONFIG_PATH = '/opt';
- process.env.FONTCONFIG_FILE = '/opt/fonts.conf';
-
- process.env.DISABLE_FROM_SURFACE = '1';
- process.env.NO_COLOR = '1';
-
- // @ts-expect-error
- globalThis._dumpUnreleasedBuffers = new EventEmitter();
-
- // @ts-expect-error
- (globalThis._dumpUnreleasedBuffers as EventEmitter).setMaxListeners(201);
-}
-
-const validateDeleteAfter = (lifeCycleValue: unknown) => {
- if (lifeCycleValue === null) {
- return;
- }
-
- if (lifeCycleValue === undefined) {
- return;
- }
-
- if (typeof lifeCycleValue !== 'string') {
- throw new TypeError(
- `Expected life cycle value to be a string, got ${JSON.stringify(
- lifeCycleValue,
- )}`,
- );
- }
-
- if (!(lifeCycleValue in expiryDays)) {
- throw new TypeError(
- `Expected deleteAfter value to be one of ${Object.keys(expiryDays).join(
- ', ',
- )}, got ${lifeCycleValue}`,
- );
- }
-};
-
-export const awsImplementation: ProviderSpecifics = {
- getChromiumPath() {
- return '/opt/bin/chromium';
- },
- getBuckets: getRemotionBuckets,
- createBucket,
- applyLifeCycle: applyLifeCyleOperation,
- listObjects: lambdaLsImplementation,
- deleteFile: lambdaDeleteFileImplementation,
- bucketExists: bucketExistsInRegionImplementation,
- randomHash: randomHashImplementation,
- readFile: lambdaReadFileImplementation,
- writeFile: lambdaWriteFileImplementation,
- supportsConditionalOutput: ({customCredentials}) =>
- customCredentials === null,
- writeFileIfNotExists: lambdaWriteFileIfNotExistsImplementation,
- headFile: lambdaHeadFileImplementation,
- convertToServeUrl: convertToServeUrlImplementation,
- printLoggingHelper: true,
- validateDeleteAfter,
- callFunctionAsync: callFunctionAsyncImplementation,
- callFunctionStreaming: callFunctionWithStreamingImplementation,
- callFunctionSync: callFunctionSyncImplementation,
- getEphemeralStorageForPriceCalculation() {
- // We cannot determine the ephemeral storage size, so we
- // overestimate the price, but will only have a miniscule effect (~0.2%)
- 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,
- getOutputUrl: getOutputUrlFromMetadata,
- serverStorageProductName: () => 'S3',
- getMaxStillInlinePayloadSize: () => 5_000_000,
- getMaxNonInlinePayloadSizePerFunction: () => 200_000,
- getAccountId: getAccountIdImplementation,
- deleteFunction,
- getFunctions,
- parseFunctionName,
- checkCredentials,
- getBucketPrefix: () => REMOTION_BUCKET_PREFIX,
-};
diff --git a/packages/lambda-client/src/aws-region-metadata.ts b/packages/lambda-client/src/aws-region-metadata.ts
index bab59b8b81..7ddeea9d7f 100644
--- a/packages/lambda-client/src/aws-region-metadata.ts
+++ b/packages/lambda-client/src/aws-region-metadata.ts
@@ -59,3 +59,9 @@ export const getAwsPartitionMetadata = (
export const getAwsRegionMetadata = (region: AwsRegion): AwsRegionMetadata =>
getAwsPartitionMetadata(regionPartitions[region]);
+
+export const getBillingCurrency = (region: AwsRegion): AwsBillingCurrency =>
+ getAwsRegionMetadata(region).billingCurrency;
+
+export const getServiceDnsSuffix = (region: AwsRegion): string =>
+ getAwsRegionMetadata(region).dnsSuffix;
diff --git a/packages/lambda-client/src/bucket-exists.ts b/packages/lambda-client/src/bucket-exists.ts
index a25ec318ba..8604551947 100644
--- a/packages/lambda-client/src/bucket-exists.ts
+++ b/packages/lambda-client/src/bucket-exists.ts
@@ -1,34 +1,33 @@
import {GetBucketLocationCommand} from '@aws-sdk/client-s3';
+import type {BucketExists} from './aws-operations';
import {getS3Client} from './get-s3-client';
-import type {ProviderSpecifics} from './provider-implementation';
-export const bucketExistsInRegionImplementation: ProviderSpecifics['bucketExists'] =
- async ({
- bucketName,
- region,
- expectedBucketOwner,
- forcePathStyle,
- requestHandler,
- }) => {
- try {
- const bucket = await getS3Client({
- region,
- customCredentials: null,
- forcePathStyle,
- requestHandler,
- }).send(
- new GetBucketLocationCommand({
- Bucket: bucketName,
- ExpectedBucketOwner: expectedBucketOwner ?? undefined,
- }),
- );
+export const bucketExistsInRegionImplementation: BucketExists = async ({
+ bucketName,
+ region,
+ expectedBucketOwner,
+ forcePathStyle,
+ requestHandler,
+}) => {
+ try {
+ const bucket = await getS3Client({
+ region,
+ customCredentials: null,
+ forcePathStyle,
+ requestHandler,
+ }).send(
+ new GetBucketLocationCommand({
+ Bucket: bucketName,
+ ExpectedBucketOwner: expectedBucketOwner ?? undefined,
+ }),
+ );
- return (bucket.LocationConstraint ?? 'us-east-1') === region;
- } catch (err) {
- if ((err as {Code: string}).Code === 'NoSuchBucket') {
- return false;
- }
-
- throw err;
+ return (bucket.LocationConstraint ?? 'us-east-1') === region;
+ } catch (err) {
+ if ((err as {Code: string}).Code === 'NoSuchBucket') {
+ return false;
}
- };
+
+ throw err;
+ }
+};
diff --git a/packages/lambda-client/src/cancel-render-on-lambda.ts b/packages/lambda-client/src/cancel-render-on-lambda.ts
index bc14e894fa..0624ff57b0 100644
--- a/packages/lambda-client/src/cancel-render-on-lambda.ts
+++ b/packages/lambda-client/src/cancel-render-on-lambda.ts
@@ -1,6 +1,5 @@
-import {awsImplementation} from './aws-provider';
+import {getAccountIdImplementation} from './get-account-id';
import {getOverallProgressFromStorage} from './get-overall-progress-from-storage';
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {RequestHandler} from './types';
import {writeCancellationSignal} from './write-cancellation-signal';
@@ -19,13 +18,12 @@ type InternalCancelRenderOnLambdaInput = Omit<
> & {
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
- providerSpecifics: ProviderSpecifics;
};
export const internalCancelRenderOnLambda = async (
input: InternalCancelRenderOnLambdaInput,
): Promise<void> => {
- const expectedBucketOwner = await input.providerSpecifics.getAccountId({
+ const expectedBucketOwner = await getAccountIdImplementation({
region: input.region,
});
const progress = await getOverallProgressFromStorage({
@@ -33,7 +31,6 @@ export const internalCancelRenderOnLambda = async (
expectedBucketOwner,
region: input.region,
renderId: input.renderId,
- providerSpecifics: input.providerSpecifics,
forcePathStyle: input.forcePathStyle,
requestHandler: input.requestHandler,
});
@@ -49,7 +46,6 @@ export const internalCancelRenderOnLambda = async (
renderId: input.renderId,
region: input.region,
expectedBucketOwner,
- providerSpecifics: input.providerSpecifics,
forcePathStyle: input.forcePathStyle,
requestHandler: input.requestHandler,
});
@@ -66,6 +62,5 @@ export const cancelRenderOnLambda = (
...input,
forcePathStyle: input.forcePathStyle ?? false,
requestHandler: input.requestHandler ?? null,
- providerSpecifics: awsImplementation,
});
};
diff --git a/packages/lambda-client/src/clean-items.ts b/packages/lambda-client/src/clean-items.ts
index c1c2495d65..3069195ac4 100644
--- a/packages/lambda-client/src/clean-items.ts
+++ b/packages/lambda-client/src/clean-items.ts
@@ -1,5 +1,5 @@
+import {lambdaDeleteFileImplementation} from './delete-file';
import {pLimit} from './p-limit';
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {RequestHandler} from './types';
@@ -11,7 +11,6 @@ type CleanItemsInput = {
list: string[];
onBeforeItemDeleted: (data: {bucketName: string; itemName: string}) => void;
onAfterItemDeleted: (data: {bucketName: string; itemName: string}) => void;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
};
@@ -22,7 +21,6 @@ export const cleanItems = ({
onBeforeItemDeleted,
region,
list,
- providerSpecifics,
forcePathStyle,
requestHandler,
}: CleanItemsInput) => {
@@ -33,7 +31,7 @@ export const cleanItems = ({
bucketName: bucket,
itemName: object,
});
- await providerSpecifics.deleteFile({
+ await lambdaDeleteFileImplementation({
bucketName: bucket,
key: object,
region,
diff --git a/packages/lambda-client/src/compress-props.ts b/packages/lambda-client/src/compress-props.ts
index 5e8269a64c..a8f92a0074 100644
--- a/packages/lambda-client/src/compress-props.ts
+++ b/packages/lambda-client/src/compress-props.ts
@@ -2,12 +2,18 @@ import type {LogLevel} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {internalGetOrCreateBucket} from './get-or-create-bucket';
import {inputPropsKey, resolvedPropsKey} from './input-props-keys';
-import type {ProviderSpecifics} from './provider-implementation';
+import {randomHashImplementation} from './random-hash';
+import {lambdaReadFileImplementation} from './read-file';
import type {AwsRegion} from './regions';
+import {
+ MAX_STILL_INLINE_PAYLOAD_SIZE,
+ MAX_NON_INLINE_PAYLOAD_SIZE_PER_FUNCTION,
+} from './shared-constants';
import type {SerializedInputProps} from './shared-constants';
import {streamToString} from './stream-to-string';
import type {RequestHandler} from './types';
import {MAX_WEBHOOK_CUSTOM_DATA_SIZE} from './validate-webhook';
+import {lambdaWriteFileImplementation} from './write-file';
type PropsType = 'input-props' | 'resolved-props';
@@ -40,17 +46,15 @@ export const serializeOrThrow = (
export const getNeedsToUpload = ({
type,
sizes,
- providerSpecifics,
}: {
type: 'still' | 'video-or-audio';
sizes: number[];
- providerSpecifics: ProviderSpecifics;
}) => {
const MARGIN = 5_000 + MAX_WEBHOOK_CUSTOM_DATA_SIZE;
const MAX_INLINE_PAYLOAD_SIZE =
(type === 'still'
- ? providerSpecifics.getMaxStillInlinePayloadSize()
- : providerSpecifics.getMaxNonInlinePayloadSizePerFunction()) - MARGIN;
+ ? MAX_STILL_INLINE_PAYLOAD_SIZE
+ : MAX_NON_INLINE_PAYLOAD_SIZE_PER_FUNCTION) - MARGIN;
const sizesAlreadyUsed = sizes.reduce((a, b) => a + b);
@@ -61,7 +65,7 @@ export const getNeedsToUpload = ({
MAX_INLINE_PAYLOAD_SIZE / 1000,
)}KB (${Math.ceil(
sizesAlreadyUsed / 1024,
- )}KB) in size. Uploading them to ${providerSpecifics.serverStorageProductName()} to circumvent AWS Lambda payload size, which may lead to slowdown.`,
+ )}KB) in size. Uploading them to ${'S3'} to circumvent AWS Lambda payload size, which may lead to slowdown.`,
);
return true;
}
@@ -75,7 +79,6 @@ type CompressInputPropsInput = {
userSpecifiedBucketName: string | null;
propsType: PropsType;
needsToUpload: boolean;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
skipPutAcl: boolean;
requestHandler: RequestHandler | null;
@@ -88,13 +91,12 @@ export const compressInputProps = async ({
userSpecifiedBucketName,
propsType,
needsToUpload,
- providerSpecifics,
forcePathStyle,
skipPutAcl,
requestHandler,
logLevel,
}: CompressInputPropsInput): Promise<SerializedInputProps> => {
- const hash = providerSpecifics.randomHash();
+ const hash = randomHashImplementation();
if (needsToUpload) {
const bucketName =
@@ -104,7 +106,6 @@ export const compressInputProps = async ({
region,
enableFolderExpiry: null,
customCredentials: null,
- providerSpecifics,
forcePathStyle,
skipPutAcl,
requestHandler,
@@ -112,7 +113,7 @@ export const compressInputProps = async ({
})
).bucketName;
- await providerSpecifics.writeFile({
+ await lambdaWriteFileImplementation({
body: stringifiedInputProps,
bucketName,
region,
@@ -145,7 +146,6 @@ type DecompressInputPropsInput = {
bucketName: string;
expectedBucketOwner: string | null;
propsType: PropsType;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
};
@@ -156,7 +156,6 @@ export const decompressInputProps = async ({
bucketName,
expectedBucketOwner,
propsType,
- providerSpecifics,
forcePathStyle,
requestHandler,
}: DecompressInputPropsInput): Promise<string> => {
@@ -165,7 +164,7 @@ export const decompressInputProps = async ({
}
try {
- const response = await providerSpecifics.readFile({
+ const response = await lambdaReadFileImplementation({
bucketName,
expectedBucketOwner,
key: makeKey(propsType, serialized.hash),
diff --git a/packages/lambda-client/src/create-bucket.ts b/packages/lambda-client/src/create-bucket.ts
index b2fb8a89a8..4d79382ae7 100644
--- a/packages/lambda-client/src/create-bucket.ts
+++ b/packages/lambda-client/src/create-bucket.ts
@@ -5,11 +5,11 @@ import {
PutBucketAclCommand,
PutBucketPolicyCommand,
} from '@aws-sdk/client-s3';
+import type {CreateBucket} from './aws-operations';
import {getAwsRegionMetadata} from './aws-region-metadata';
import {getS3Client} from './get-s3-client';
-import type {ProviderSpecifics} from './provider-implementation';
-export const createBucket: ProviderSpecifics['createBucket'] = async ({
+export const createBucket: CreateBucket = async ({
region,
bucketName,
forcePathStyle,
diff --git a/packages/lambda-client/src/delete-file.ts b/packages/lambda-client/src/delete-file.ts
index 81d3b8bfc3..69afb2e715 100644
--- a/packages/lambda-client/src/delete-file.ts
+++ b/packages/lambda-client/src/delete-file.ts
@@ -1,35 +1,34 @@
import {DeleteObjectCommand} from '@aws-sdk/client-s3';
+import type {DeleteFile} from './aws-operations';
import {getS3Client} from './get-s3-client';
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {CustomCredentials} from './shared-constants';
import type {RequestHandler} from './types';
-export const lambdaDeleteFileImplementation: ProviderSpecifics['deleteFile'] =
- async ({
- bucketName,
- key,
+export const lambdaDeleteFileImplementation: DeleteFile = async ({
+ bucketName,
+ key,
+ region,
+ customCredentials,
+ forcePathStyle,
+ requestHandler,
+}: {
+ region: AwsRegion;
+ bucketName: string;
+ key: string;
+ customCredentials: CustomCredentials | null;
+ forcePathStyle: boolean;
+ requestHandler: RequestHandler | null;
+}) => {
+ await getS3Client({
region,
customCredentials,
forcePathStyle,
requestHandler,
- }: {
- region: AwsRegion;
- bucketName: string;
- key: string;
- customCredentials: CustomCredentials | null;
- forcePathStyle: boolean;
- requestHandler: RequestHandler | null;
- }) => {
- await getS3Client({
- region,
- customCredentials,
- forcePathStyle,
- requestHandler,
- }).send(
- new DeleteObjectCommand({
- Bucket: bucketName,
- Key: key,
- }),
- );
- };
+ }).send(
+ new DeleteObjectCommand({
+ Bucket: bucketName,
+ Key: key,
+ }),
+ );
+};
diff --git a/packages/lambda-client/src/delete-function.ts b/packages/lambda-client/src/delete-function.ts
index ee85895d15..5ba0f79903 100644
--- a/packages/lambda-client/src/delete-function.ts
+++ b/packages/lambda-client/src/delete-function.ts
@@ -3,7 +3,7 @@ import {getLambdaClient} from './aws-clients';
import type {
DeleteFunction,
DeleteFunctionInput as GenericDeleteFunctionInput,
-} from './provider-implementation';
+} from './aws-operations';
import type {RequestHandler} from './types';
export type DeleteFunctionInput = GenericDeleteFunctionInput & {
diff --git a/packages/lambda-client/src/delete-render.ts b/packages/lambda-client/src/delete-render.ts
index 3e6a222555..ea11113d1b 100644
--- a/packages/lambda-client/src/delete-render.ts
+++ b/packages/lambda-client/src/delete-render.ts
@@ -1,10 +1,11 @@
-import {awsImplementation} from './aws-provider';
import {cleanItems} from './clean-items';
import {REMOTION_BUCKET_PREFIX} from './constants';
+import {lambdaDeleteFileImplementation} from './delete-file';
import {getExpectedOutName} from './expected-out-name';
+import {getAccountIdImplementation} from './get-account-id';
import {getOverallProgressFromStorage} from './get-overall-progress-from-storage';
import {getImageSequenceFrameKey} from './image-sequence';
-import type {ProviderSpecifics} from './provider-implementation';
+import {lambdaLsImplementation} from './list-objects';
import type {AwsRegion} from './regions';
import {rendersPrefix, type CustomCredentials} from './shared-constants';
import type {RequestHandler} from './types';
@@ -21,11 +22,10 @@ export type DeleteRenderInput = {
export const internalDeleteRender = async (
input: DeleteRenderInput & {
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
},
) => {
- const expectedBucketOwner = await input.providerSpecifics.getAccountId({
+ const expectedBucketOwner = await getAccountIdImplementation({
region: input.region,
});
const progress = await getOverallProgressFromStorage({
@@ -33,7 +33,6 @@ export const internalDeleteRender = async (
expectedBucketOwner,
region: input.region,
renderId: input.renderId,
- providerSpecifics: input.providerSpecifics,
forcePathStyle: input.forcePathStyle,
requestHandler: input.requestHandler,
});
@@ -91,7 +90,7 @@ export const internalDeleteRender = async (
for (let index = 0; index < keys.length; index += 25) {
await Promise.all(
keys.slice(index, index + 25).map((frameKey) =>
- input.providerSpecifics.deleteFile({
+ lambdaDeleteFileImplementation({
bucketName: renderBucketName,
key: frameKey,
region: input.region,
@@ -108,7 +107,7 @@ export const internalDeleteRender = async (
mainOutput,
...(separateAudioOutput === null ? [] : [separateAudioOutput]),
]) {
- await input.providerSpecifics.deleteFile({
+ await lambdaDeleteFileImplementation({
bucketName: renderBucketName,
customCredentials,
key,
@@ -118,7 +117,7 @@ export const internalDeleteRender = async (
});
}
- let files = await input.providerSpecifics.listObjects({
+ let files = await lambdaLsImplementation({
bucketName: input.bucketName,
prefix: rendersPrefix(input.renderId),
region: input.region,
@@ -139,11 +138,10 @@ export const internalDeleteRender = async (
onAfterItemDeleted: () => undefined,
onBeforeItemDeleted: () => undefined,
region: input.region,
- providerSpecifics: input.providerSpecifics,
forcePathStyle: input.forcePathStyle,
requestHandler: input.requestHandler,
});
- files = await input.providerSpecifics.listObjects({
+ files = await lambdaLsImplementation({
bucketName: input.bucketName,
prefix: rendersPrefix(input.renderId),
region: input.region,
@@ -165,7 +163,6 @@ export const internalDeleteRender = async (
export const deleteRender = (input: DeleteRenderInput) => {
return internalDeleteRender({
...input,
- providerSpecifics: awsImplementation,
forcePathStyle: input.forcePathStyle ?? false,
});
};
diff --git a/packages/lambda-client/src/estimate-price-from-bucket.ts b/packages/lambda-client/src/estimate-price-from-bucket.ts
index 5ba4af4e1c..d5a318bace 100644
--- a/packages/lambda-client/src/estimate-price-from-bucket.ts
+++ b/packages/lambda-client/src/estimate-price-from-bucket.ts
@@ -1,5 +1,5 @@
import {calculateBillingDuration} from './calculate-billing-duration';
-import type {ProviderSpecifics} from './provider-implementation';
+import {estimatePrice} from './estimate-price';
import type {AwsRegion} from './regions';
import type {RenderMetadata} from './render-metadata';
import type {ParsedTiming} from './types';
@@ -11,7 +11,6 @@ export const estimatePriceFromMetadata = ({
functionsInvoked,
timings,
region,
- providerSpecifics,
fatalErrorTimestamp,
}: {
renderMetadata: RenderMetadata | null;
@@ -20,7 +19,6 @@ export const estimatePriceFromMetadata = ({
functionsInvoked: number;
timings: ParsedTiming[];
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
fatalErrorTimestamp: number | null;
}) => {
if (!renderMetadata) {
@@ -37,15 +35,13 @@ export const estimatePriceFromMetadata = ({
});
const accruedSoFar = Number(
- providerSpecifics
- .estimatePrice({
- region,
- durationInMilliseconds: estimatedBillingDurationInMilliseconds,
- memorySizeInMb,
- diskSizeInMb,
- lambdasInvoked: functionsInvoked,
- })
- .toPrecision(5),
+ estimatePrice({
+ region,
+ durationInMilliseconds: estimatedBillingDurationInMilliseconds,
+ memorySizeInMb,
+ diskSizeInMb,
+ lambdasInvoked: functionsInvoked,
+ }).toPrecision(5),
);
return {accruedSoFar, estimatedBillingDurationInMilliseconds};
diff --git a/packages/lambda-client/src/find-output-file-in-bucket.ts b/packages/lambda-client/src/find-output-file-in-bucket.ts
index 6f39efc103..c67edb7563 100644
--- a/packages/lambda-client/src/find-output-file-in-bucket.ts
+++ b/packages/lambda-client/src/find-output-file-in-bucket.ts
@@ -1,5 +1,7 @@
+import {REMOTION_BUCKET_PREFIX} from './constants';
import {getExpectedOutName} from './expected-out-name';
-import type {ProviderSpecifics} from './provider-implementation';
+import {getOutputUrlFromMetadata} from './get-output-url-from-metadata';
+import {lambdaHeadFileImplementation} from './head-file';
import type {AwsRegion} from './regions';
import type {RenderMetadata} from './render-metadata';
import type {CustomCredentials, RenderOutput} from './shared-constants';
@@ -34,7 +36,6 @@ type FindOutputFileInBucketInput = {
bucketName: string;
customCredentials: CustomCredentials | null;
currentRegion: AwsRegion;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
output: RenderOutput;
@@ -46,7 +47,6 @@ export const findOutputFileInBucket = async ({
bucketName,
customCredentials,
currentRegion,
- providerSpecifics,
forcePathStyle,
requestHandler,
output,
@@ -55,12 +55,12 @@ export const findOutputFileInBucket = async ({
renderMetadata,
bucketName,
customCredentials,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: REMOTION_BUCKET_PREFIX,
output,
});
try {
- const metadata = await providerSpecifics.headFile({
+ const metadata = await lambdaHeadFileImplementation({
bucketName: renderBucketName,
key,
region,
@@ -70,7 +70,7 @@ export const findOutputFileInBucket = async ({
});
return {
- url: providerSpecifics.getOutputUrl({
+ url: getOutputUrlFromMetadata({
renderMetadata,
bucketName,
customCredentials,
diff --git a/packages/lambda-client/src/get-account-id.ts b/packages/lambda-client/src/get-account-id.ts
index 22b5677242..78c8d0fd0b 100644
--- a/packages/lambda-client/src/get-account-id.ts
+++ b/packages/lambda-client/src/get-account-id.ts
@@ -1,6 +1,6 @@
import {GetCallerIdentityCommand} from '@aws-sdk/client-sts';
import {getStsClient} from './aws-clients';
-import type {GetAccountId} from './provider-implementation';
+import type {GetAccountId} from './aws-operations';
import type {AwsRegion} from './regions';
import {validateAwsRegion} from './validate-aws-region';
diff --git a/packages/lambda-client/src/get-aws-urls.ts b/packages/lambda-client/src/get-aws-urls.ts
index 13cb28e452..7bc2a7d6f3 100644
--- a/packages/lambda-client/src/get-aws-urls.ts
+++ b/packages/lambda-client/src/get-aws-urls.ts
@@ -1,6 +1,6 @@
+import type {GetLoggingUrlForRendererFunction} from './aws-operations';
import {getAwsRegionMetadata} from './aws-region-metadata';
import {encodeAwsUrlParams} from './encode-aws-url-params';
-import type {GetLoggingUrlForRendererFunction} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {ServerlessRoutines} from './shared-constants';
diff --git a/packages/lambda-client/src/get-buckets.ts b/packages/lambda-client/src/get-buckets.ts
index 1f0b7754da..448442ef63 100644
--- a/packages/lambda-client/src/get-buckets.ts
+++ b/packages/lambda-client/src/get-buckets.ts
@@ -1,7 +1,7 @@
import {GetBucketLocationCommand, ListBucketsCommand} from '@aws-sdk/client-s3';
+import type {GetBuckets} from './aws-operations';
import {REMOTION_BUCKET_PREFIX} from './constants';
import {getS3Client} from './get-s3-client';
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import {parseBucketName} from './validate-bucketname';
@@ -11,7 +11,7 @@ export type BucketWithLocation = {
region: AwsRegion;
};
-export const getRemotionBuckets: ProviderSpecifics['getBuckets'] = async ({
+export const getRemotionBuckets: GetBuckets = async ({
region,
forceBucketName,
forcePathStyle,
diff --git a/packages/lambda-client/src/get-compositions-on-lambda.ts b/packages/lambda-client/src/get-compositions-on-lambda.ts
index c9ab468a70..0aaae5e6ce 100644
--- a/packages/lambda-client/src/get-compositions-on-lambda.ts
+++ b/packages/lambda-client/src/get-compositions-on-lambda.ts
@@ -2,7 +2,7 @@ import type {ChromiumOptions, ToOptions} from '@remotion/renderer';
import type {BrowserSafeApis} from '@remotion/renderer/client';
import type {VideoConfig} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
-import {awsImplementation} from './aws-provider';
+import {callFunctionSyncImplementation} from './call-lambda-sync';
import {
compressInputProps,
getNeedsToUpload,
@@ -66,9 +66,7 @@ export const getCompositionsOnLambda = async ({
getSizeInBytes(stringifiedInputProps),
getSizeInBytes(JSON.stringify(envVariables ?? {})),
],
- providerSpecifics: awsImplementation,
}),
- providerSpecifics: awsImplementation,
forcePathStyle: forcePathStyle ?? false,
skipPutAcl: false,
requestHandler,
@@ -76,7 +74,7 @@ export const getCompositionsOnLambda = async ({
});
try {
- const res = await awsImplementation.callFunctionSync({
+ const res = await callFunctionSyncImplementation({
functionName,
type: ServerlessRoutines.compositions,
payload: {
diff --git a/packages/lambda-client/src/get-function-version.ts b/packages/lambda-client/src/get-function-version.ts
index 45cd32b7e6..253ee1eecf 100644
--- a/packages/lambda-client/src/get-function-version.ts
+++ b/packages/lambda-client/src/get-function-version.ts
@@ -1,5 +1,5 @@
import type {LogLevel} from '@remotion/renderer';
-import {awsImplementation} from './aws-provider';
+import {callFunctionSyncImplementation} from './call-lambda-sync';
import type {AwsRegion} from './regions';
import {COMMAND_NOT_FOUND, ServerlessRoutines} from './shared-constants';
import type {RequestHandler} from './types';
@@ -16,9 +16,7 @@ export async function getFunctionVersion({
requestHandler: RequestHandler | null | undefined;
}): Promise<string> {
try {
- // For now, we'll pass requestHandler to the awsImplementation if needed
- // This might require deeper changes in the serverless-client framework
- const result = await awsImplementation.callFunctionSync({
+ const result = await callFunctionSyncImplementation({
functionName,
payload: {
logLevel,
diff --git a/packages/lambda-client/src/get-functions.ts b/packages/lambda-client/src/get-functions.ts
index 40472d41ba..450ce74288 100644
--- a/packages/lambda-client/src/get-functions.ts
+++ b/packages/lambda-client/src/get-functions.ts
@@ -3,9 +3,9 @@ import {ListFunctionsCommand} from '@aws-sdk/client-lambda';
import type {LogLevel} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
import {getLambdaClient} from './aws-clients';
+import type {FunctionInfo} from './aws-operations';
import {DEFAULT_EPHEMERAL_STORAGE_IN_MB, RENDER_FN_PREFIX} from './constants';
import {getFunctionVersion} from './get-function-version';
-import type {FunctionInfo} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {RequestHandler} from './types';
diff --git a/packages/lambda-client/src/get-or-create-bucket.ts b/packages/lambda-client/src/get-or-create-bucket.ts
index cb3a0af8f2..a1b8a80f92 100644
--- a/packages/lambda-client/src/get-or-create-bucket.ts
+++ b/packages/lambda-client/src/get-or-create-bucket.ts
@@ -1,7 +1,11 @@
import type {LogLevel} from 'remotion';
+import {getServiceDnsSuffix} from './aws-region-metadata';
import {checkBucketListing} from './check-bucket-listing';
+import {REMOTION_BUCKET_PREFIX} from './constants';
+import {createBucket} from './create-bucket';
+import {getRemotionBuckets} from './get-buckets';
+import {applyLifeCyleOperation} from './lifecycle-rules';
import {makeBucketName} from './make-bucket-name';
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {CustomCredentials} from './shared-constants';
import type {RequestHandler} from './types';
@@ -10,7 +14,6 @@ type GetOrCreateBucketInputInner = {
region: AwsRegion;
enableFolderExpiry: boolean | null;
customCredentials: CustomCredentials | null;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
skipPutAcl: boolean;
logLevel: LogLevel;
@@ -34,7 +37,7 @@ export type GetOrCreateBucketOutput = {
export const internalGetOrCreateBucket = async (
params: GetOrCreateBucketInputInner,
): Promise<GetOrCreateBucketOutput> => {
- const remotionBuckets = await params.providerSpecifics.getBuckets({
+ const remotionBuckets = await getRemotionBuckets({
region: params.region,
forceBucketName: null,
forcePathStyle: params.forcePathStyle,
@@ -46,7 +49,7 @@ export const internalGetOrCreateBucket = async (
(b) => b.name,
)}) in your S3 region (${
params.region
- }) starting with "${params.providerSpecifics.getBucketPrefix()}". Please see https://remotion.dev/docs/lambda/multiple-buckets.`,
+ }) starting with "${REMOTION_BUCKET_PREFIX}". Please see https://remotion.dev/docs/lambda/multiple-buckets.`,
);
}
@@ -54,7 +57,7 @@ export const internalGetOrCreateBucket = async (
if (remotionBuckets.length === 1) {
const existingBucketName = remotionBuckets[0].name;
// apply to existing bucket
- await params.providerSpecifics.applyLifeCycle({
+ await applyLifeCyleOperation({
enableFolderExpiry: enableFolderExpiry ?? null,
bucketName: existingBucketName,
region,
@@ -66,15 +69,15 @@ export const internalGetOrCreateBucket = async (
await checkBucketListing({
bucketName: existingBucketName,
region,
- dnsSuffix: params.providerSpecifics.getServiceDnsSuffix(region),
+ dnsSuffix: getServiceDnsSuffix(region),
});
return {bucketName: remotionBuckets[0].name, alreadyExisted: true};
}
- const bucketName = makeBucketName(params.region, params.providerSpecifics);
+ const bucketName = makeBucketName(params.region);
- await params.providerSpecifics.createBucket({
+ await createBucket({
bucketName,
region: params.region,
forcePathStyle: params.forcePathStyle,
@@ -84,7 +87,7 @@ export const internalGetOrCreateBucket = async (
});
// apply to newly created bucket
- await params.providerSpecifics.applyLifeCycle({
+ await applyLifeCyleOperation({
enableFolderExpiry: enableFolderExpiry ?? null,
bucketName,
region,
diff --git a/packages/lambda-client/src/get-output-url-from-metadata.ts b/packages/lambda-client/src/get-output-url-from-metadata.ts
index 672305bc76..cdcb820d5a 100644
--- a/packages/lambda-client/src/get-output-url-from-metadata.ts
+++ b/packages/lambda-client/src/get-output-url-from-metadata.ts
@@ -1,8 +1,8 @@
import {S3Client} from '@aws-sdk/client-s3';
+import type {GetOutputUrl} from './aws-operations';
import {getAwsRegionMetadata} from './aws-region-metadata';
import {REMOTION_BUCKET_PREFIX} from './constants';
import {getExpectedOutName} from './expected-out-name';
-import type {GetOutputUrl} from './provider-implementation';
const {endpointProvider} = new S3Client({region: 'us-east-1'}).config;
diff --git a/packages/lambda-client/src/get-overall-progress-from-storage.ts b/packages/lambda-client/src/get-overall-progress-from-storage.ts
index 470ceb3f14..a01498bb71 100644
--- a/packages/lambda-client/src/get-overall-progress-from-storage.ts
+++ b/packages/lambda-client/src/get-overall-progress-from-storage.ts
@@ -1,5 +1,5 @@
import type {OverallRenderProgress} from './overall-render-progress';
-import type {ProviderSpecifics} from './provider-implementation';
+import {lambdaReadFileImplementation} from './read-file';
import type {AwsRegion} from './regions';
import {overallProgressKey} from './shared-constants';
import {streamToString} from './stream-to-string';
@@ -10,7 +10,6 @@ type GetOverallProgressFromStorageInput = {
expectedBucketOwner: string | null;
bucketName: string;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
};
@@ -20,12 +19,11 @@ export const getOverallProgressFromStorage = async ({
bucketName,
expectedBucketOwner,
region,
- providerSpecifics,
forcePathStyle,
requestHandler,
}: GetOverallProgressFromStorageInput) => {
try {
- const Body = await providerSpecifics.readFile({
+ const Body = await lambdaReadFileImplementation({
bucketName,
key: overallProgressKey(renderId),
expectedBucketOwner,
diff --git a/packages/lambda-client/src/get-render-progress.ts b/packages/lambda-client/src/get-render-progress.ts
index 4bda31b003..79219a8adb 100644
--- a/packages/lambda-client/src/get-render-progress.ts
+++ b/packages/lambda-client/src/get-render-progress.ts
@@ -1,5 +1,5 @@
import type {LogLevel} from '@remotion/renderer';
-import {awsImplementation} from './aws-provider';
+import {callFunctionSyncImplementation} from './call-lambda-sync';
import type {RenderProgress} from './constants';
import {getRenderProgressPayload} from './make-lambda-payload';
import {parseFunctionName} from './parse-function-name';
@@ -46,7 +46,6 @@ export const getRenderProgress = async (
forcePathStyle: input.forcePathStyle ?? false,
customCredentials: input.s3OutputProvider ?? null,
expectedBucketOwner: null,
- providerSpecifics: awsImplementation,
memorySizeInMb: parsed.memorySizeInMb,
timeoutInMilliseconds: parsed.timeoutInSeconds * 1000,
functionName: input.functionName,
@@ -55,7 +54,7 @@ export const getRenderProgress = async (
}
const result =
- await awsImplementation.callFunctionSync<ServerlessRoutines.status>({
+ await callFunctionSyncImplementation<ServerlessRoutines.status>({
functionName: input.functionName,
type: ServerlessRoutines.status,
payload: getRenderProgressPayload(input),
diff --git a/packages/lambda-client/src/get-sites.ts b/packages/lambda-client/src/get-sites.ts
index 242fcf348c..ea78a02469 100644
--- a/packages/lambda-client/src/get-sites.ts
+++ b/packages/lambda-client/src/get-sites.ts
@@ -1,10 +1,12 @@
import {VERSION} from 'remotion/version';
-import {awsImplementation} from './aws-provider';
import {getSitesKey} from './constants';
+import {getAccountIdImplementation} from './get-account-id';
+import {getRemotionBuckets} from './get-buckets';
import type {BucketWithLocation} from './get-buckets';
import {getRemotionVersionFromIndexHtml} from './get-remotion-version-from-index-html';
+import {lambdaLsImplementation} from './list-objects';
import {makeS3ServeUrl} from './make-s3-url';
-import type {ProviderSpecifics} from './provider-implementation';
+import {lambdaReadFileImplementation} from './read-file';
import type {AwsRegion} from './regions';
import {streamToString} from './stream-to-string';
import type {RequestHandler} from './types';
@@ -40,32 +42,29 @@ export type GetSitesOutput = {
export const internalGetSites = async ({
region,
forceBucketName,
- providerSpecifics,
forcePathStyle,
compatibleOnly,
requestHandler,
-}: GetSitesInternalInput & {
- providerSpecifics: ProviderSpecifics;
-}): Promise<GetSitesOutput> => {
+}: GetSitesInternalInput & {}): Promise<GetSitesOutput> => {
const remotionBuckets = forceBucketName
- ? await providerSpecifics.getBuckets({
+ ? await getRemotionBuckets({
region,
forceBucketName,
forcePathStyle,
requestHandler,
})
- : await providerSpecifics.getBuckets({
+ : await getRemotionBuckets({
region,
forceBucketName: null,
forcePathStyle,
requestHandler,
});
- const accountId = await providerSpecifics.getAccountId({region});
+ const accountId = await getAccountIdImplementation({region});
const sites: {[key: string]: Site} = {};
for (const bucket of remotionBuckets) {
- const ls = await providerSpecifics.listObjects({
+ const ls = await lambdaLsImplementation({
bucketName: bucket.name,
prefix: getSitesKey(''),
region,
@@ -123,7 +122,7 @@ export const internalGetSites = async ({
await Promise.all(
sitesArray.map(async (site) => {
try {
- const body = await providerSpecifics.readFile({
+ const body = await lambdaReadFileImplementation({
bucketName: site.bucketName,
key: `${getSitesKey(site.id)}/index.html`,
region,
@@ -162,7 +161,6 @@ export const getSites = ({
forceBucketName: forceBucketName ?? null,
forcePathStyle: forcePathStyle ?? false,
compatibleOnly: compatibleOnly ?? false,
- providerSpecifics: awsImplementation,
requestHandler: requestHandler ?? null,
});
};
diff --git a/packages/lambda-client/src/head-file.ts b/packages/lambda-client/src/head-file.ts
index 16a32188b2..04da0256b2 100644
--- a/packages/lambda-client/src/head-file.ts
+++ b/packages/lambda-client/src/head-file.ts
@@ -1,55 +1,54 @@
import {HeadObjectCommand} from '@aws-sdk/client-s3';
+import type {HeadFile} from './aws-operations';
import {OutputFileAccessDeniedError} from './find-output-file-in-bucket';
import {getS3Client} from './get-s3-client';
-import type {ProviderSpecifics} from './provider-implementation';
-export const lambdaHeadFileImplementation: ProviderSpecifics['headFile'] =
- async ({
- bucketName,
- key,
- region,
- customCredentials,
- forcePathStyle,
- requestHandler,
- }): Promise<{
- LastModified?: Date | undefined;
- ContentLength?: number | undefined;
- Metadata?: Record<string, string> | undefined;
- }> => {
- try {
- const head = await getS3Client({
- region,
- customCredentials,
- forcePathStyle,
- requestHandler,
- }).send(
- new HeadObjectCommand({
- Bucket: bucketName,
- Key: key,
- }),
- );
- return head;
- } catch (err) {
- if (
- (err as Error).message === 'UnknownError' ||
- (err as {$metadata: {httpStatusCode: number}}).$metadata
+export const lambdaHeadFileImplementation: HeadFile = async ({
+ bucketName,
+ key,
+ region,
+ customCredentials,
+ forcePathStyle,
+ requestHandler,
+}): Promise<{
+ LastModified?: Date | undefined;
+ ContentLength?: number | undefined;
+ Metadata?: Record<string, string> | undefined;
+}> => {
+ try {
+ const head = await getS3Client({
+ region,
+ customCredentials,
+ forcePathStyle,
+ requestHandler,
+ }).send(
+ new HeadObjectCommand({
+ Bucket: bucketName,
+ Key: key,
+ }),
+ );
+ return head;
+ } catch (err) {
+ if (
+ (err as Error).message === 'UnknownError' ||
+ (err as {$metadata: {httpStatusCode: number}}).$metadata
+ ?.httpStatusCode === 403
+ ) {
+ const ErrorClass =
+ (err as {$metadata: {httpStatusCode: number} | undefined}).$metadata
?.httpStatusCode === 403
- ) {
- const ErrorClass =
- (err as {$metadata: {httpStatusCode: number} | undefined}).$metadata
- ?.httpStatusCode === 403
- ? OutputFileAccessDeniedError
- : Error;
- throw new ErrorClass(
- `Unable to access item "${key}" from bucket "${bucketName}" ${
- customCredentials?.endpoint
- ? `(S3 Endpoint = ${customCredentials?.endpoint})`
- : ''
- } - got a 403 error when heading the file. Check your credentials and permissions. The Lambda role must have permission for both "s3:GetObject" and "s3:ListBucket" actions.`,
- {cause: err},
- );
- }
-
- throw err;
+ ? OutputFileAccessDeniedError
+ : Error;
+ throw new ErrorClass(
+ `Unable to access item "${key}" from bucket "${bucketName}" ${
+ customCredentials?.endpoint
+ ? `(S3 Endpoint = ${customCredentials?.endpoint})`
+ : ''
+ } - got a 403 error when heading the file. Check your credentials and permissions. The Lambda role must have permission for both "s3:GetObject" and "s3:ListBucket" actions.`,
+ {cause: err},
+ );
}
- };
+
+ throw err;
+ }
+};
diff --git a/packages/lambda-client/src/index.ts b/packages/lambda-client/src/index.ts
index 5e9f6df750..061d63ec04 100644
--- a/packages/lambda-client/src/index.ts
+++ b/packages/lambda-client/src/index.ts
@@ -1,141 +1,6 @@
export type {RuntimePreference} from './runtime-preference';
-import {
- getCloudWatchLogsClient,
- getIamClient,
- getLambdaClient,
- getServiceQuotasClient,
- getStsClient,
-} from './aws-clients';
-import {awsImplementation} from './aws-provider';
-import {
- getAwsPartitionMetadata,
- getAwsRegionMetadata,
-} from './aws-region-metadata';
-import {calculateBillingDuration} from './calculate-billing-duration';
-import {calculateChunkTimes} from './calculate-chunk-times';
-import {parseJsonOrThrowSource} from './call-lambda-streaming';
-import {internalCancelRenderOnLambda} from './cancel-render-on-lambda';
-import {cleanItems} from './clean-items';
-import {
- compressInputProps,
- decompressInputProps,
- getNeedsToUpload,
- serializeOrThrow,
-} from './compress-props';
-import {
- DEFAULT_CLOUDWATCH_RETENTION_PERIOD,
- DEFAULT_EPHEMERAL_STORAGE_IN_MB,
- MAX_EPHEMERAL_STORAGE_IN_MB,
-} from './constants';
-import {convertToServeUrlImplementation} from './convert-to-serve-url';
-import {internalDeleteRender} from './delete-render';
-import {DOCS_URL} from './docs-url';
-import {
- errorIsOutOfSpaceError,
- isBrowserCrashedError,
- isErrInsufficientResourcesErr,
-} from './error-category';
-import {estimatePriceFromMetadata} from './estimate-price-from-bucket';
-import {
- getCredentialsFromOutName,
- getExpectedOutName,
-} from './expected-out-name';
-import {findOutputFileInBucket} from './find-output-file-in-bucket';
-import {formatCostsInfo} from './format-costs-info';
-import {
- getCloudwatchMethodUrl,
- getCloudwatchRendererUrl,
- getLambdaFunctionUrl,
- getS3BucketUrl,
- getS3RenderUrl,
-} from './get-aws-urls';
-import {getEnvVariable} from './get-env-variable';
-import {internalGetOrCreateBucket} from './get-or-create-bucket';
-import {getOverallProgressFromStorage} from './get-overall-progress-from-storage';
-import {getRemotionVersionFromIndexHtml} from './get-remotion-version-from-index-html';
-import {getS3Client} from './get-s3-client';
-import {internalGetSites} from './get-sites';
-import {getSizeInBytes} from './get-size-in-bytes';
-import {getImageSequenceFrameKey} from './image-sequence';
-import {inputPropsKey, resolvedPropsKey} from './input-props-keys';
-import {inspectErrors} from './inspect-error';
-import {isFlakyError} from './is-flaky-error';
-import {LAMBDA_VERSION_STRING} from './lambda-version-string';
-import {
- generateRandomHashWithLifeCycleRule,
- getLifeCycleRules,
-} from './lifecycle';
-import {makeBucketName} from './make-bucket-name';
-import {
- getRenderProgressPayload,
- makeLambdaRenderMediaPayload,
- makeLambdaRenderStillPayload,
-} from './make-lambda-payload';
-import {makeS3ServeUrl} from './make-s3-url';
-import {
- getMostExpensiveChunks,
- OVERHEAD_TIME_PER_LAMBDA,
-} from './most-expensive-chunks';
-import {pLimit} from './p-limit';
-import {parseFunctionName} from './parse-function-name';
-import {getProgress} from './progress';
-import {randomHashImplementation} from './random-hash';
-import {
- internalRenderMediaOnLambdaRaw,
- renderMediaOnLambdaOptionalToRequired,
-} from './render-media-on-lambda';
-import {internalRenderStillOnLambda} from './render-still-on-lambda';
-import {
- parseS3RendererStatus,
- rendererTransportArtifactKey,
- rendererTransportAttemptPrefix,
- rendererTransportAudioKey,
- rendererTransportPrefix,
- rendererTransportStatusKey,
- rendererTransportVideoKey,
-} from './renderer-transport';
-import {runtimePreferenceOptions} from './runtime-preference';
-import {deserializeArtifact, serializeArtifact} from './serialize-artifact';
-import {
- artifactName,
- cancellationKey,
- COMMAND_NOT_FOUND,
- CONCAT_FOLDER_TOKEN,
- customOutName,
- expiryDays,
- MAX_FUNCTIONS_PER_RENDER,
- MINIMUM_FRAMES_PER_FUNCTION,
- outName,
- outStillName,
- overallProgressKey,
- REMOTION_CONCATENATED_TOKEN,
- RENDERER_PATH_TOKEN,
- rendersPrefix,
- serverlessCodecs,
-} from './shared-constants';
-import {innerSpeculateFunctionName} from './speculate-function-name';
-import {streamToString} from './stream-to-string';
-import {
- binaryPayloadSinkForStreamer,
- formatMap,
- makeStreamPayload,
- messageTypeIdToMessageType,
-} from './streaming/streaming';
-import {truthy} from './truthy';
-import {validateAwsRegion} from './validate-aws-region';
-import {validateBucketName} from './validate-bucket-name';
-import {parseBucketName} from './validate-bucketname';
-import {validateDiskSizeInMb} from './validate-disk-size-in-mb';
-import {validateDownloadBehavior} from './validate-download-behavior';
-import {validateFramesPerFunction} from './validate-frames-per-function';
-import {validateMemorySize} from './validate-memory-size';
-import {validateOutname} from './validate-outname';
-import {validatePrivacy} from './validate-privacy';
-import {validateServeUrl} from './validate-serveurl';
-import {validateWebhook} from './validate-webhook';
-import {writeCancellationSignal} from './write-cancellation-signal';
-export {appRouterWebhook, NextWebhookArgs} from './app-router-webhook';
+export {appRouterWebhook, type NextWebhookArgs} from './app-router-webhook';
export {
cancelRenderOnLambda,
type CancelRenderOnLambdaInput,
@@ -146,9 +11,9 @@ export type {
AwsRegionMetadata,
} from './aws-region-metadata';
export type {RenderProgress} from './constants';
-export {deleteFunction, DeleteFunctionInput} from './delete-function';
+export {deleteFunction, type DeleteFunctionInput} from './delete-function';
export {deleteRender, type DeleteRenderInput} from './delete-render';
-export {estimatePrice, EstimatePriceInput} from './estimate-price';
+export {estimatePrice, type EstimatePriceInput} from './estimate-price';
export {expressWebhook} from './express-webhook';
export {
getAwsClient,
@@ -227,9 +92,8 @@ export type {
GetLoggingUrlForRendererFunction,
GetOutputUrl,
ParseFunctionName,
- ProviderSpecifics,
WriteFileInput,
-} from './provider-implementation';
+} from './aws-operations';
export type {RenderMetadata} from './render-metadata';
export type {CleanupInfo, GenericRenderProgress} from './render-progress';
export type {
@@ -288,224 +152,4 @@ export type {
FunctionErrorInfo,
} from './write-error-to-storage';
-export const LambdaClientInternals: {
- generateRandomHashWithLifeCycleRule: typeof generateRandomHashWithLifeCycleRule;
- getLambdaClient: typeof getLambdaClient;
- getS3Client: typeof getS3Client;
- getS3RenderUrl: typeof getS3RenderUrl;
- getIamClient: typeof getIamClient;
- getStsClient: typeof getStsClient;
- getCloudWatchLogsClient: typeof getCloudWatchLogsClient;
- getServiceQuotasClient: typeof getServiceQuotasClient;
- 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;
- convertToServeUrlImplementation: typeof convertToServeUrlImplementation;
- randomHashImplementation: typeof randomHashImplementation;
- parseBucketName: typeof parseBucketName;
- makeLambdaRenderMediaPayload: typeof makeLambdaRenderMediaPayload;
- renderMediaOnLambdaOptionalToRequired: typeof renderMediaOnLambdaOptionalToRequired;
- internalDeleteRender: typeof internalDeleteRender;
- internalCancelRenderOnLambda: typeof internalCancelRenderOnLambda;
- internalGetSites: typeof internalGetSites;
- getLifeCycleRules: typeof getLifeCycleRules;
- awsImplementation: typeof awsImplementation;
- runtimePreferenceOptions: typeof runtimePreferenceOptions;
- validateAwsRegion: typeof validateAwsRegion;
- validateDiskSizeInMb: typeof validateDiskSizeInMb;
- validateMemorySize: typeof validateMemorySize;
- DEFAULT_CLOUDWATCH_RETENTION_PERIOD: typeof DEFAULT_CLOUDWATCH_RETENTION_PERIOD;
- DEFAULT_EPHEMERAL_STORAGE_IN_MB: typeof DEFAULT_EPHEMERAL_STORAGE_IN_MB;
- LAMBDA_VERSION_STRING: typeof LAMBDA_VERSION_STRING;
- pLimit: typeof pLimit;
- makeS3ServeUrl: typeof makeS3ServeUrl;
- validateServeUrl: typeof validateServeUrl;
- getEnvVariable: typeof getEnvVariable;
- internalRenderMediaOnLambdaRaw: typeof internalRenderMediaOnLambdaRaw;
- internalRenderStillOnLambda: typeof internalRenderStillOnLambda;
- cleanItems: typeof cleanItems;
- makeLambdaRenderStillPayload: typeof makeLambdaRenderStillPayload;
- getRenderProgressPayload: typeof getRenderProgressPayload;
- innerSpeculateFunctionName: typeof innerSpeculateFunctionName;
- getAwsPartitionMetadata: typeof getAwsPartitionMetadata;
- getAwsRegionMetadata: typeof getAwsRegionMetadata;
- artifactName: typeof artifactName;
- binaryPayloadSinkForStreamer: typeof binaryPayloadSinkForStreamer;
- calculateBillingDuration: typeof calculateBillingDuration;
- calculateChunkTimes: typeof calculateChunkTimes;
- cancellationKey: typeof cancellationKey;
- COMMAND_NOT_FOUND: typeof COMMAND_NOT_FOUND;
- compressInputProps: typeof compressInputProps;
- CONCAT_FOLDER_TOKEN: typeof CONCAT_FOLDER_TOKEN;
- customOutName: typeof customOutName;
- decompressInputProps: typeof decompressInputProps;
- deserializeArtifact: typeof deserializeArtifact;
- DOCS_URL: typeof DOCS_URL;
- errorIsOutOfSpaceError: typeof errorIsOutOfSpaceError;
- estimatePriceFromMetadata: typeof estimatePriceFromMetadata;
- expiryDays: typeof expiryDays;
- findOutputFileInBucket: typeof findOutputFileInBucket;
- formatCostsInfo: typeof formatCostsInfo;
- formatMap: typeof formatMap;
- getCredentialsFromOutName: typeof getCredentialsFromOutName;
- getExpectedOutName: typeof getExpectedOutName;
- getImageSequenceFrameKey: typeof getImageSequenceFrameKey;
- getMostExpensiveChunks: typeof getMostExpensiveChunks;
- getNeedsToUpload: typeof getNeedsToUpload;
- getOverallProgressFromStorage: typeof getOverallProgressFromStorage;
- getProgress: typeof getProgress;
- getRemotionVersionFromIndexHtml: typeof getRemotionVersionFromIndexHtml;
- getSizeInBytes: typeof getSizeInBytes;
- inputPropsKey: typeof inputPropsKey;
- inspectErrors: typeof inspectErrors;
- internalGetOrCreateBucket: typeof internalGetOrCreateBucket;
- isBrowserCrashedError: typeof isBrowserCrashedError;
- isErrInsufficientResourcesErr: typeof isErrInsufficientResourcesErr;
- makeBucketName: typeof makeBucketName;
- makeStreamPayload: typeof makeStreamPayload;
- MAX_FUNCTIONS_PER_RENDER: typeof MAX_FUNCTIONS_PER_RENDER;
- messageTypeIdToMessageType: typeof messageTypeIdToMessageType;
- MINIMUM_FRAMES_PER_FUNCTION: typeof MINIMUM_FRAMES_PER_FUNCTION;
- outName: typeof outName;
- outStillName: typeof outStillName;
- overallProgressKey: typeof overallProgressKey;
- OVERHEAD_TIME_PER_LAMBDA: typeof OVERHEAD_TIME_PER_LAMBDA;
- parseS3RendererStatus: typeof parseS3RendererStatus;
- REMOTION_CONCATENATED_TOKEN: typeof REMOTION_CONCATENATED_TOKEN;
- RENDERER_PATH_TOKEN: typeof RENDERER_PATH_TOKEN;
- rendererTransportArtifactKey: typeof rendererTransportArtifactKey;
- rendererTransportAttemptPrefix: typeof rendererTransportAttemptPrefix;
- rendererTransportAudioKey: typeof rendererTransportAudioKey;
- rendererTransportPrefix: typeof rendererTransportPrefix;
- rendererTransportStatusKey: typeof rendererTransportStatusKey;
- rendererTransportVideoKey: typeof rendererTransportVideoKey;
- rendersPrefix: typeof rendersPrefix;
- resolvedPropsKey: typeof resolvedPropsKey;
- serializeArtifact: typeof serializeArtifact;
- serializeOrThrow: typeof serializeOrThrow;
- serverlessCodecs: typeof serverlessCodecs;
- streamToString: typeof streamToString;
- truthy: typeof truthy;
- validateBucketName: typeof validateBucketName;
- validateDownloadBehavior: typeof validateDownloadBehavior;
- validateFramesPerFunction: typeof validateFramesPerFunction;
- validateOutname: typeof validateOutname;
- validatePrivacy: typeof validatePrivacy;
- validateWebhook: typeof validateWebhook;
- writeCancellationSignal: typeof writeCancellationSignal;
-} = {
- generateRandomHashWithLifeCycleRule,
- getLambdaClient,
- getS3Client,
- getS3RenderUrl,
- getIamClient,
- getStsClient,
- getCloudWatchLogsClient,
- getServiceQuotasClient,
- parseJsonOrThrowSource,
- getCloudwatchMethodUrl,
- getCloudwatchRendererUrl,
- getLambdaFunctionUrl,
- getS3BucketUrl,
- MAX_EPHEMERAL_STORAGE_IN_MB,
- parseFunctionName,
- isFlakyError,
- convertToServeUrlImplementation,
- randomHashImplementation,
- parseBucketName,
- makeLambdaRenderMediaPayload,
- renderMediaOnLambdaOptionalToRequired,
- internalDeleteRender,
- internalCancelRenderOnLambda,
- internalGetSites,
- getLifeCycleRules,
- awsImplementation,
- runtimePreferenceOptions,
- validateAwsRegion,
- validateDiskSizeInMb,
- validateMemorySize,
- DEFAULT_CLOUDWATCH_RETENTION_PERIOD,
- DEFAULT_EPHEMERAL_STORAGE_IN_MB,
- LAMBDA_VERSION_STRING,
- pLimit,
- makeS3ServeUrl,
- validateServeUrl,
- getEnvVariable,
- internalRenderMediaOnLambdaRaw,
- internalRenderStillOnLambda,
- cleanItems,
- makeLambdaRenderStillPayload,
- getRenderProgressPayload,
- innerSpeculateFunctionName,
- getAwsPartitionMetadata,
- getAwsRegionMetadata,
- artifactName,
- binaryPayloadSinkForStreamer,
- calculateBillingDuration,
- calculateChunkTimes,
- cancellationKey,
- COMMAND_NOT_FOUND,
- compressInputProps,
- CONCAT_FOLDER_TOKEN,
- customOutName,
- decompressInputProps,
- deserializeArtifact,
- DOCS_URL,
- errorIsOutOfSpaceError,
- estimatePriceFromMetadata,
- expiryDays,
- findOutputFileInBucket,
- formatCostsInfo,
- formatMap,
- getCredentialsFromOutName,
- getExpectedOutName,
- getImageSequenceFrameKey,
- getMostExpensiveChunks,
- getNeedsToUpload,
- getOverallProgressFromStorage,
- getProgress,
- getRemotionVersionFromIndexHtml,
- getSizeInBytes,
- inputPropsKey,
- inspectErrors,
- internalGetOrCreateBucket,
- isBrowserCrashedError,
- isErrInsufficientResourcesErr,
- makeBucketName,
- makeStreamPayload,
- MAX_FUNCTIONS_PER_RENDER,
- messageTypeIdToMessageType,
- MINIMUM_FRAMES_PER_FUNCTION,
- outName,
- outStillName,
- overallProgressKey,
- OVERHEAD_TIME_PER_LAMBDA,
- parseS3RendererStatus,
- REMOTION_CONCATENATED_TOKEN,
- RENDERER_PATH_TOKEN,
- rendererTransportArtifactKey,
- rendererTransportAttemptPrefix,
- rendererTransportAudioKey,
- rendererTransportPrefix,
- rendererTransportStatusKey,
- rendererTransportVideoKey,
- rendersPrefix,
- resolvedPropsKey,
- serializeArtifact,
- serializeOrThrow,
- serverlessCodecs,
- streamToString,
- truthy,
- validateBucketName,
- validateDownloadBehavior,
- validateFramesPerFunction,
- validateOutname,
- validatePrivacy,
- validateWebhook,
- writeCancellationSignal,
-};
+export * as LambdaClientInternals from './internals';
diff --git a/packages/lambda-client/src/internals.ts b/packages/lambda-client/src/internals.ts
new file mode 100644
index 0000000000..88c59b7d06
--- /dev/null
+++ b/packages/lambda-client/src/internals.ts
@@ -0,0 +1,167 @@
+// Internal API surface consumed by @remotion/lambda. Not public API.
+export {
+ getCloudWatchLogsClient,
+ getIamClient,
+ getLambdaClient,
+ getServiceQuotasClient,
+ getStsClient,
+} from './aws-clients';
+export {
+ getAwsPartitionMetadata,
+ getAwsRegionMetadata,
+ getBillingCurrency,
+ getServiceDnsSuffix,
+} from './aws-region-metadata';
+export {bucketExistsInRegionImplementation} from './bucket-exists';
+export {calculateBillingDuration} from './calculate-billing-duration';
+export {calculateChunkTimes} from './calculate-chunk-times';
+export {callFunctionAsyncImplementation} from './call-lambda-async';
+export {
+ callFunctionWithStreamingImplementation,
+ parseJsonOrThrowSource,
+} from './call-lambda-streaming';
+export {callFunctionSyncImplementation} from './call-lambda-sync';
+export {internalCancelRenderOnLambda} from './cancel-render-on-lambda';
+export {checkCredentials} from './check-credentials';
+export {cleanItems} from './clean-items';
+export {
+ compressInputProps,
+ decompressInputProps,
+ getNeedsToUpload,
+ serializeOrThrow,
+} from './compress-props';
+export {
+ DEFAULT_CLOUDWATCH_RETENTION_PERIOD,
+ DEFAULT_EPHEMERAL_STORAGE_IN_MB,
+ MAX_EPHEMERAL_STORAGE_IN_MB,
+ REMOTION_BUCKET_PREFIX,
+} from './constants';
+export {convertToServeUrlImplementation} from './convert-to-serve-url';
+export {createBucket} from './create-bucket';
+export {lambdaDeleteFileImplementation} from './delete-file';
+export {deleteFunction} from './delete-function';
+export {internalDeleteRender} from './delete-render';
+export {DOCS_URL} from './docs-url';
+export {
+ errorIsOutOfSpaceError,
+ isBrowserCrashedError,
+ isErrInsufficientResourcesErr,
+} from './error-category';
+export {estimatePrice} from './estimate-price';
+export {estimatePriceFromMetadata} from './estimate-price-from-bucket';
+export {
+ getCredentialsFromOutName,
+ getExpectedOutName,
+} from './expected-out-name';
+export {findOutputFileInBucket} from './find-output-file-in-bucket';
+export {formatCostsInfo} from './format-costs-info';
+export {getAccountIdImplementation} from './get-account-id';
+export {
+ getCloudwatchMethodUrl,
+ getCloudwatchRendererUrl,
+ getLambdaFunctionUrl,
+ getS3BucketUrl,
+ getS3RenderUrl,
+} from './get-aws-urls';
+export {getRemotionBuckets} from './get-buckets';
+export {getEnvVariable} from './get-env-variable';
+export {getFunctions} from './get-functions';
+export {internalGetOrCreateBucket} from './get-or-create-bucket';
+export {getOutputUrlFromMetadata} from './get-output-url-from-metadata';
+export {getOverallProgressFromStorage} from './get-overall-progress-from-storage';
+export {getRemotionVersionFromIndexHtml} from './get-remotion-version-from-index-html';
+export {getS3Client} from './get-s3-client';
+export {internalGetSites} from './get-sites';
+export {getSizeInBytes} from './get-size-in-bytes';
+export {lambdaHeadFileImplementation} from './head-file';
+export {getImageSequenceFrameKey} from './image-sequence';
+export {inputPropsKey, resolvedPropsKey} from './input-props-keys';
+export {inspectErrors} from './inspect-error';
+export {isFlakyError} from './is-flaky-error';
+export {isInsideLambda} from './is-in-lambda';
+export {LAMBDA_VERSION_STRING} from './lambda-version-string';
+export {
+ generateRandomHashWithLifeCycleRule,
+ getLifeCycleRules,
+} from './lifecycle';
+export {applyLifeCyleOperation} from './lifecycle-rules';
+export {lambdaLsImplementation} from './list-objects';
+export {makeBucketName} from './make-bucket-name';
+export {
+ getRenderProgressPayload,
+ makeLambdaRenderMediaPayload,
+ makeLambdaRenderStillPayload,
+} from './make-lambda-payload';
+export {makeS3ServeUrl} from './make-s3-url';
+export {
+ OVERHEAD_TIME_PER_LAMBDA,
+ getMostExpensiveChunks,
+} from './most-expensive-chunks';
+export {pLimit} from './p-limit';
+export {parseFunctionName} from './parse-function-name';
+export {getProgress} from './progress';
+export {randomHashImplementation} from './random-hash';
+export {lambdaReadFileImplementation} from './read-file';
+export {
+ internalRenderMediaOnLambdaRaw,
+ renderMediaOnLambdaOptionalToRequired,
+} from './render-media-on-lambda';
+export {internalRenderStillOnLambda} from './render-still-on-lambda';
+export {
+ getRendererFunctionTransport,
+ parseS3RendererStatus,
+ rendererTransportArtifactKey,
+ rendererTransportAttemptPrefix,
+ rendererTransportAudioKey,
+ rendererTransportPrefix,
+ rendererTransportStatusKey,
+ rendererTransportVideoKey,
+} from './renderer-transport';
+export {runtimePreferenceOptions} from './runtime-preference';
+export {deserializeArtifact, serializeArtifact} from './serialize-artifact';
+export {
+ COMMAND_NOT_FOUND,
+ CONCAT_FOLDER_TOKEN,
+ MAX_FUNCTIONS_PER_RENDER,
+ MAX_NON_INLINE_PAYLOAD_SIZE_PER_FUNCTION,
+ MAX_STILL_INLINE_PAYLOAD_SIZE,
+ MINIMUM_FRAMES_PER_FUNCTION,
+ REMOTION_CONCATENATED_TOKEN,
+ RENDERER_PATH_TOKEN,
+ artifactName,
+ cancellationKey,
+ customOutName,
+ expiryDays,
+ outName,
+ outStillName,
+ overallProgressKey,
+ rendersPrefix,
+ serverlessCodecs,
+} from './shared-constants';
+export {innerSpeculateFunctionName} from './speculate-function-name';
+export {streamToString} from './stream-to-string';
+export {
+ binaryPayloadSinkForStreamer,
+ formatMap,
+ makeStreamPayload,
+ messageTypeIdToMessageType,
+} from './streaming/streaming';
+export {truthy} from './truthy';
+export {validateAwsRegion} from './validate-aws-region';
+export {validateBucketName} from './validate-bucket-name';
+export {parseBucketName} from './validate-bucketname';
+export {validateDeleteAfter} from './validate-delete-after';
+export {validateDiskSizeInMb} from './validate-disk-size-in-mb';
+export {validateDownloadBehavior} from './validate-download-behavior';
+export {validateFramesPerFunction} from './validate-frames-per-function';
+export {validateMemorySize} from './validate-memory-size';
+export {validateOutname} from './validate-outname';
+export {validatePrivacy} from './validate-privacy';
+export {validateServeUrl} from './validate-serveurl';
+export {validateWebhook} from './validate-webhook';
+export {writeCancellationSignal} from './write-cancellation-signal';
+export {
+ lambdaWriteFileIfNotExistsImplementation,
+ lambdaWriteFileImplementation,
+ supportsConditionalOutput,
+} from './write-file';
diff --git a/packages/lambda-client/src/lifecycle.ts b/packages/lambda-client/src/lifecycle.ts
index 329a7e96db..db596af292 100644
--- a/packages/lambda-client/src/lifecycle.ts
+++ b/packages/lambda-client/src/lifecycle.ts
@@ -1,5 +1,5 @@
import type {LifecycleRule} from '@aws-sdk/client-s3';
-import type {ProviderSpecifics} from './provider-implementation';
+import type {RandomHash} from './aws-operations';
import {expiryDays, type DeleteAfter} from './shared-constants';
import {truthy} from './truthy';
@@ -33,7 +33,7 @@ export const generateRandomHashWithLifeCycleRule = ({
randomHashFn,
}: {
deleteAfter: DeleteAfter | null;
- randomHashFn: ProviderSpecifics['randomHash'];
+ randomHashFn: RandomHash;
}) => {
return [deleteAfter, randomHashFn()].filter(truthy).join('-');
};
diff --git a/packages/lambda-client/src/list-objects.ts b/packages/lambda-client/src/list-objects.ts
index fdbaf4ec50..df08654dc1 100644
--- a/packages/lambda-client/src/list-objects.ts
+++ b/packages/lambda-client/src/list-objects.ts
@@ -1,8 +1,8 @@
import {ListObjectsV2Command} from '@aws-sdk/client-s3';
+import type {ListObjects} from './aws-operations';
import {getS3Client} from './get-s3-client';
-import type {ProviderSpecifics} from './provider-implementation';
-export const lambdaLsImplementation: ProviderSpecifics['listObjects'] = async ({
+export const lambdaLsImplementation: ListObjects = async ({
bucketName,
prefix,
region,
diff --git a/packages/lambda-client/src/make-bucket-name.ts b/packages/lambda-client/src/make-bucket-name.ts
index edd8ea611c..b17fdc4c73 100644
--- a/packages/lambda-client/src/make-bucket-name.ts
+++ b/packages/lambda-client/src/make-bucket-name.ts
@@ -1,9 +1,7 @@
-import type {ProviderSpecifics} from './provider-implementation';
+import {REMOTION_BUCKET_PREFIX} from './constants';
+import {randomHashImplementation} from './random-hash';
import type {AwsRegion} from './regions';
-export const makeBucketName = (
- region: AwsRegion,
- providerSpecifics: ProviderSpecifics,
-) => {
- return `${providerSpecifics.getBucketPrefix()}${region.replace(/-/g, '')}-${providerSpecifics.randomHash()}`;
+export const makeBucketName = (region: AwsRegion) => {
+ return `${REMOTION_BUCKET_PREFIX}${region.replace(/-/g, '')}-${randomHashImplementation()}`;
};
diff --git a/packages/lambda-client/src/make-lambda-payload.ts b/packages/lambda-client/src/make-lambda-payload.ts
index cb156d5b7e..7a275212b8 100644
--- a/packages/lambda-client/src/make-lambda-payload.ts
+++ b/packages/lambda-client/src/make-lambda-payload.ts
@@ -14,7 +14,6 @@ import type {BrowserSafeApis} from '@remotion/renderer/client';
import type {_InternalTypes} from 'remotion';
import {NoReactInternals, type DownloadBehavior} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
-import {awsImplementation} from './aws-provider';
import {
compressInputProps,
getNeedsToUpload,
@@ -25,6 +24,7 @@ import {getSizeInBytes} from './get-size-in-bytes';
import type {ServerlessRenderOutput} from './image-sequence';
import type {AwsRegion} from './regions';
import type {RenderStillOnLambdaNonNullInput} from './render-still-on-lambda';
+import {getRendererFunctionTransport} from './renderer-transport';
import {
ServerlessRoutines,
type DeleteAfter,
@@ -186,11 +186,9 @@ export const makeLambdaRenderMediaPayload = async ({
getSizeInBytes(stringifiedInputProps),
getSizeInBytes(JSON.stringify(envVariables)),
],
- providerSpecifics: awsImplementation,
}),
userSpecifiedBucketName: bucketName ?? null,
propsType: 'input-props',
- providerSpecifics: awsImplementation,
forcePathStyle: forcePathStyle ?? false,
skipPutAcl: privacy === 'no-acl',
requestHandler: requestHandler ?? null,
@@ -321,11 +319,9 @@ export const makeLambdaRenderStillPayload = async ({
getSizeInBytes(stringifiedInputProps),
getSizeInBytes(JSON.stringify(envVariables)),
],
- providerSpecifics: awsImplementation,
}),
userSpecifiedBucketName: forceBucketName ?? null,
propsType: 'input-props',
- providerSpecifics: awsImplementation,
forcePathStyle,
skipPutAcl: privacy === 'no-acl',
requestHandler,
@@ -358,9 +354,7 @@ export const makeLambdaRenderStillPayload = async ({
offthreadVideoCacheSizeInBytes,
deleteAfter,
type: ServerlessRoutines.still,
- streamed:
- awsImplementation.getRendererFunctionTransport(region) ===
- 'response-streaming',
+ streamed: getRendererFunctionTransport(region) === 'response-streaming',
forcePathStyle,
licenseKey: licenseKey ?? null,
offthreadVideoThreads: offthreadVideoThreads ?? null,
diff --git a/packages/lambda-client/src/make-timeout-error.ts b/packages/lambda-client/src/make-timeout-error.ts
index 55b7c8c145..818510aeec 100644
--- a/packages/lambda-client/src/make-timeout-error.ts
+++ b/packages/lambda-client/src/make-timeout-error.ts
@@ -1,5 +1,4 @@
import {makeTimeoutMessage} from './make-timeout-message';
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import type {RenderMetadata} from './render-metadata';
import type {EnhancedErrorInfo} from './write-error-to-storage';
@@ -11,7 +10,6 @@ export const makeTimeoutError = ({
renderId,
functionName,
region,
- providerSpecifics,
}: {
timeoutInMilliseconds: number;
renderMetadata: RenderMetadata;
@@ -19,7 +17,6 @@ export const makeTimeoutError = ({
missingChunks: number[];
functionName: string;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
}): EnhancedErrorInfo => {
const message = makeTimeoutMessage({
missingChunks,
@@ -28,7 +25,6 @@ export const makeTimeoutError = ({
renderId,
functionName,
region,
- providerSpecifics,
});
const error = new Error(message);
diff --git a/packages/lambda-client/src/make-timeout-message.ts b/packages/lambda-client/src/make-timeout-message.ts
index 0b2a7ac7d6..c697abd072 100644
--- a/packages/lambda-client/src/make-timeout-message.ts
+++ b/packages/lambda-client/src/make-timeout-message.ts
@@ -1,5 +1,5 @@
import {DOCS_URL} from './docs-url';
-import type {ProviderSpecifics} from './provider-implementation';
+import {getCloudwatchRendererUrl, getCloudwatchMethodUrl} from './get-aws-urls';
import type {AwsRegion} from './regions';
import type {RenderMetadata} from './render-metadata';
import {ServerlessRoutines} from './shared-constants';
@@ -10,13 +10,11 @@ const makeChunkMissingMessage = ({
missingChunks,
renderMetadata,
region,
- providerSpecifics,
functionName,
}: {
missingChunks: number[];
renderMetadata: RenderMetadata;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
functionName: string;
}) => {
if (missingChunks.length === 0) {
@@ -43,15 +41,13 @@ const makeChunkMissingMessage = ({
return [
msg,
- `â–¸ Logs for chunk ${ch}: ${providerSpecifics.getLoggingUrlForRendererFunction(
- {
- functionName,
- region,
- rendererFunctionName: null,
- renderId: renderMetadata.renderId,
- chunk: ch,
- },
- )}`,
+ `â–¸ Logs for chunk ${ch}: ${getCloudwatchRendererUrl({
+ functionName,
+ region,
+ rendererFunctionName: null,
+ renderId: renderMetadata.renderId,
+ chunk: ch,
+ })}`,
].join('\n');
})
.slice(0, 5),
@@ -65,7 +61,6 @@ export const makeTimeoutMessage = ({
renderId,
functionName,
region,
- providerSpecifics,
}: {
timeoutInMilliseconds: number;
missingChunks: number[];
@@ -73,18 +68,16 @@ export const makeTimeoutMessage = ({
renderId: string;
region: AwsRegion;
functionName: string;
- providerSpecifics: ProviderSpecifics;
}) => {
- const cloudWatchRendererUrl =
- providerSpecifics.getLoggingUrlForRendererFunction({
- renderId,
- functionName,
- region,
- rendererFunctionName: functionName,
- chunk: null,
- });
+ const cloudWatchRendererUrl = getCloudwatchRendererUrl({
+ renderId,
+ functionName,
+ region,
+ rendererFunctionName: functionName,
+ chunk: null,
+ });
- const cloudWatchLaunchUrl = providerSpecifics.getLoggingUrlForMethod({
+ const cloudWatchLaunchUrl = getCloudwatchMethodUrl({
renderId,
functionName,
method: ServerlessRoutines.launch,
@@ -97,7 +90,6 @@ export const makeTimeoutMessage = ({
missingChunks,
renderMetadata,
region,
- providerSpecifics,
functionName,
}),
'',
diff --git a/packages/lambda-client/src/progress.ts b/packages/lambda-client/src/progress.ts
index e9456522aa..f4e37616e5 100644
--- a/packages/lambda-client/src/progress.ts
+++ b/packages/lambda-client/src/progress.ts
@@ -1,5 +1,7 @@
import {NoReactAPIs} from '@remotion/renderer/pure';
+import {getBillingCurrency} from './aws-region-metadata';
import {calculateChunkTimes} from './calculate-chunk-times';
+import {REMOTION_BUCKET_PREFIX, MAX_EPHEMERAL_STORAGE_IN_MB} from './constants';
import {estimatePriceFromMetadata} from './estimate-price-from-bucket';
import {getExpectedOutName} from './expected-out-name';
import {
@@ -11,7 +13,7 @@ import {getOverallProgress} from './get-overall-progress';
import {getOverallProgressFromStorage} from './get-overall-progress-from-storage';
import {inspectErrors} from './inspect-error';
import {makeTimeoutError} from './make-timeout-error';
-import type {ProviderSpecifics} from './provider-implementation';
+import {parseFunctionName} from './parse-function-name';
import type {AwsRegion} from './regions';
import type {CleanupInfo, GenericRenderProgress} from './render-progress';
import type {CustomCredentials} from './shared-constants';
@@ -27,7 +29,6 @@ type GetProgressInput = {
memorySizeInMb: number;
timeoutInMilliseconds: number;
customCredentials: CustomCredentials | null;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
functionName: string;
requestHandler: RequestHandler | null;
@@ -41,18 +42,16 @@ export const getProgress = async ({
memorySizeInMb,
timeoutInMilliseconds,
customCredentials,
- providerSpecifics,
forcePathStyle,
functionName,
requestHandler,
}: GetProgressInput): Promise<GenericRenderProgress> => {
- const billingCurrency = providerSpecifics.getBillingCurrency(region);
+ const billingCurrency = getBillingCurrency(region);
const overallProgress = await getOverallProgressFromStorage({
renderId,
bucketName,
expectedBucketOwner,
region,
- providerSpecifics,
forcePathStyle,
requestHandler,
});
@@ -75,7 +74,7 @@ export const getProgress = async ({
renderMetadata: overallProgress.renderMetadata,
bucketName,
customCredentials,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: REMOTION_BUCKET_PREFIX,
});
const totalFrameCount = NoReactAPIs.getFramesToRender(
@@ -222,13 +221,12 @@ export const getProgress = async ({
const priceFromBucket = estimatePriceFromMetadata({
renderMetadata,
memorySizeInMb:
- providerSpecifics.parseFunctionName(renderMetadata.rendererFunctionName)
- ?.memorySizeInMb ?? memorySizeInMb,
+ parseFunctionName(renderMetadata.rendererFunctionName)?.memorySizeInMb ??
+ memorySizeInMb,
functionsInvoked: overallProgress.lambdasInvoked ?? 0,
- diskSizeInMb: providerSpecifics.getEphemeralStorageForPriceCalculation(),
+ diskSizeInMb: MAX_EPHEMERAL_STORAGE_IN_MB,
timings: overallProgress.timings ?? [],
region,
- providerSpecifics,
fatalErrorTimestamp: overallProgress.fatalErrorTimestamp ?? null,
});
@@ -283,7 +281,6 @@ export const getProgress = async ({
renderMetadata,
region,
currentRegion: region,
- providerSpecifics,
forcePathStyle,
requestHandler,
}).catch((err) => {
@@ -303,7 +300,7 @@ export const getProgress = async ({
renderMetadata,
bucketName,
customCredentials,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: REMOTION_BUCKET_PREFIX,
});
const now = Date.now();
const timeToFinishChunks = calculateChunkTimes({
@@ -373,7 +370,6 @@ export const getProgress = async ({
missingChunks: missingChunks ?? [],
region,
functionName,
- providerSpecifics,
})
: null,
...errorExplanations,
diff --git a/packages/lambda-client/src/render-media-on-lambda.ts b/packages/lambda-client/src/render-media-on-lambda.ts
index 28a54039a1..8de9e05f0c 100644
--- a/packages/lambda-client/src/render-media-on-lambda.ts
+++ b/packages/lambda-client/src/render-media-on-lambda.ts
@@ -11,7 +11,7 @@ import type {BrowserSafeApis} from '@remotion/renderer/client';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
import type {_InternalTypes} from 'remotion';
import type {DownloadBehavior} from 'remotion/no-react';
-import {awsImplementation} from './aws-provider';
+import {callFunctionSyncImplementation} from './call-lambda-sync';
import {
getCloudwatchMethodUrl,
getCloudwatchRendererUrl,
@@ -106,7 +106,7 @@ export const internalRenderMediaOnLambdaRaw = async (
const {functionName, region, rendererFunctionName} = input;
try {
- const res = await awsImplementation.callFunctionSync({
+ const res = await callFunctionSyncImplementation({
functionName,
type: ServerlessRoutines.start,
payload: await makeLambdaRenderMediaPayload(input),
diff --git a/packages/lambda-client/src/render-still-on-lambda.ts b/packages/lambda-client/src/render-still-on-lambda.ts
index cf7071ef64..3ab73647cd 100644
--- a/packages/lambda-client/src/render-still-on-lambda.ts
+++ b/packages/lambda-client/src/render-still-on-lambda.ts
@@ -7,7 +7,8 @@ import type {
import type {BrowserSafeApis} from '@remotion/renderer/client';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
import type {DownloadBehavior} from 'remotion/no-react';
-import {awsImplementation} from './aws-provider';
+import {callFunctionWithStreamingImplementation} from './call-lambda-streaming';
+import {callFunctionSyncImplementation} from './call-lambda-sync';
import {DEFAULT_MAX_RETRIES} from './constants';
import {getCloudwatchMethodUrl, getLambdaInsightsUrl} from './get-aws-urls';
import {makeLambdaRenderStillPayload} from './make-lambda-payload';
@@ -86,43 +87,42 @@ const innerRenderStillOnLambda = async (
const res = payload.streamed
? await new Promise<RenderStillFunctionResponsePayload>(
(resolve, reject) => {
- awsImplementation
- .callFunctionStreaming<ServerlessRoutines.still>({
- functionName,
- type: ServerlessRoutines.still,
- payload,
- region,
- receivedStreamingPayload: ({message}) => {
- if (message.type === 'render-id-determined') {
- onInit?.({
+ callFunctionWithStreamingImplementation<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,
- cloudWatchLogs: getCloudwatchMethodUrl({
- functionName,
- method: ServerlessRoutines.still,
- region,
- rendererFunctionName: null,
- renderId: message.payload.renderId,
- }),
- lambdaInsightsUrl: getLambdaInsightsUrl({
- functionName,
- region,
- }),
- });
- }
+ }),
+ lambdaInsightsUrl: getLambdaInsightsUrl({
+ functionName,
+ region,
+ }),
+ });
+ }
- if (message.type === 'error-occurred') {
- reject(new Error(message.payload.error));
- }
+ if (message.type === 'error-occurred') {
+ reject(new Error(message.payload.error));
+ }
- if (message.type === 'still-rendered') {
- resolve(message.payload);
- }
- },
- timeoutInTest: 120000,
- retriesRemaining: input.maxRetries,
- getBinaryPayloadSink: null,
- requestHandler: input.requestHandler,
- })
+ if (message.type === 'still-rendered') {
+ resolve(message.payload);
+ }
+ },
+ timeoutInTest: 120000,
+ retriesRemaining: input.maxRetries,
+ getBinaryPayloadSink: null,
+ requestHandler: input.requestHandler,
+ })
.then(() => {
reject(new Error('Expected response to be streamed'));
})
@@ -131,7 +131,7 @@ const innerRenderStillOnLambda = async (
});
},
)
- : ((await awsImplementation.callFunctionSync<ServerlessRoutines.still>({
+ : ((await callFunctionSyncImplementation<ServerlessRoutines.still>({
functionName,
type: ServerlessRoutines.still,
payload,
diff --git a/packages/lambda-client/src/renderer-transport.ts b/packages/lambda-client/src/renderer-transport.ts
index c567338365..9f87a21de3 100644
--- a/packages/lambda-client/src/renderer-transport.ts
+++ b/packages/lambda-client/src/renderer-transport.ts
@@ -1,9 +1,19 @@
import type {DownloadBehavior} from 'remotion/no-react';
+import {getAwsRegionMetadata} from './aws-region-metadata';
+import type {AwsRegion} from './regions';
import {rendersPrefix} from './shared-constants';
import type {FunctionErrorInfo} from './write-error-to-storage';
export type RendererFunctionTransport = 'response-streaming' | 's3';
+// Lambda response streaming is not available in the AWS China partition.
+export const getRendererFunctionTransport = (
+ region: AwsRegion,
+): RendererFunctionTransport =>
+ getAwsRegionMetadata(region).partition === 'aws-cn'
+ ? 's3'
+ : 'response-streaming';
+
export type S3RendererArtifactMetadata = {
filename: string;
frame: number;
diff --git a/packages/lambda-client/src/shared-constants.ts b/packages/lambda-client/src/shared-constants.ts
index 0400aac22c..6891c5a60f 100644
--- a/packages/lambda-client/src/shared-constants.ts
+++ b/packages/lambda-client/src/shared-constants.ts
@@ -447,6 +447,8 @@ export type AfterRenderCost = {
export const CONCAT_FOLDER_TOKEN = 'remotion-concat';
export const MAX_FUNCTIONS_PER_RENDER = 200;
+export const MAX_STILL_INLINE_PAYLOAD_SIZE = 5_000_000;
+export const MAX_NON_INLINE_PAYLOAD_SIZE_PER_FUNCTION = 200_000;
export const MINIMUM_FRAMES_PER_FUNCTION = 5;
export const REMOTION_CONCATENATED_TOKEN = 'remotion-concatenated-token';
diff --git a/packages/lambda-client/src/test/aws-china-regions.test.ts b/packages/lambda-client/src/test/aws-china-regions.test.ts
index a3f9e490cc..0ddbfdfbbf 100644
--- a/packages/lambda-client/src/test/aws-china-regions.test.ts
+++ b/packages/lambda-client/src/test/aws-china-regions.test.ts
@@ -1,5 +1,4 @@
import {expect, test} from 'bun:test';
-import {awsImplementation} from '../aws-provider';
import {getAwsRegionMetadata} from '../aws-region-metadata';
import {convertToServeUrlImplementation} from '../convert-to-serve-url';
import {
@@ -14,6 +13,7 @@ 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';
+import {getRendererFunctionTransport} from '../renderer-transport';
import {ServerlessRoutines} from '../shared-constants';
const chinaMetadata = {
@@ -35,15 +35,9 @@ test('AWS region metadata is exhaustive for China without changing defaults', ()
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',
- );
+ expect(getRendererFunctionTransport('cn-north-1')).toBe('s3');
+ expect(getRendererFunctionTransport('cn-northwest-1')).toBe('s3');
+ expect(getRendererFunctionTransport('us-east-1')).toBe('response-streaming');
});
test('China still payload uses buffered invocation', async () => {
diff --git a/packages/lambda-client/src/test/cancel-render-on-lambda.test.ts b/packages/lambda-client/src/test/cancel-render-on-lambda.test.ts
index 9dbe27a6c2..5b9e03d63b 100644
--- a/packages/lambda-client/src/test/cancel-render-on-lambda.test.ts
+++ b/packages/lambda-client/src/test/cancel-render-on-lambda.test.ts
@@ -1,39 +1,46 @@
-import {expect, test} from 'bun:test';
+import {afterEach, expect, spyOn, test} from 'bun:test';
import {Readable} from 'node:stream';
-import {awsImplementation} from '../aws-provider';
+import type {WriteFile} from '../aws-operations';
import {internalCancelRenderOnLambda} from '../cancel-render-on-lambda';
-import type {ProviderSpecifics} from '../provider-implementation';
+import * as getAccountId from '../get-account-id';
+import * as readFile from '../read-file';
import {cancellationKey, overallProgressKey} from '../shared-constants';
+import * as writeFile from '../write-file';
-const makeProviderSpecifics = ({
+const spies: {mockRestore: () => void}[] = [];
+
+const installFakes = ({
cancellationEnabled,
onWrite,
}: {
cancellationEnabled: boolean | undefined;
- onWrite: ProviderSpecifics['writeFile'];
-}): ProviderSpecifics => {
- return {
- ...awsImplementation,
- getAccountId: () => Promise.resolve('123456789012'),
- readFile: ({key}) => {
- expect(key).toBe(overallProgressKey('render-id'));
- return Promise.resolve(
- Readable.from([
- Buffer.from(
- JSON.stringify({
- cancellationEnabled,
- }),
- ),
- ]),
- );
- },
- writeFile: onWrite,
- };
+ onWrite: WriteFile;
+}) => {
+ spies.push(
+ spyOn(getAccountId, 'getAccountIdImplementation').mockImplementation(() =>
+ Promise.resolve('123456789012'),
+ ),
+ spyOn(readFile, 'lambdaReadFileImplementation').mockImplementation(
+ ({key}) => {
+ expect(key).toBe(overallProgressKey('render-id'));
+ return Promise.resolve(
+ Readable.from([Buffer.from(JSON.stringify({cancellationEnabled}))]),
+ );
+ },
+ ),
+ spyOn(writeFile, 'lambdaWriteFileImplementation').mockImplementation(
+ onWrite,
+ ),
+ );
};
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
+
test('writes a cancellation signal for an opted-in render', async () => {
let writes = 0;
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
cancellationEnabled: true,
onWrite: (input) => {
writes++;
@@ -51,7 +58,6 @@ test('writes a cancellation signal for an opted-in render', async () => {
region: 'us-east-1',
forcePathStyle: false,
requestHandler: null,
- providerSpecifics,
});
expect(writes).toBe(1);
@@ -59,7 +65,7 @@ test('writes a cancellation signal for an opted-in render', async () => {
test('rejects cancellation if the render did not opt in', async () => {
let writes = 0;
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
cancellationEnabled: undefined,
onWrite: () => {
writes++;
@@ -74,7 +80,6 @@ test('rejects cancellation if the render did not opt in', async () => {
region: 'us-east-1',
forcePathStyle: false,
requestHandler: null,
- providerSpecifics,
}),
).rejects.toThrow('enableCancellation: true');
expect(writes).toBe(0);
diff --git a/packages/lambda-client/src/test/get-compositions-on-lambda.test.ts b/packages/lambda-client/src/test/get-compositions-on-lambda.test.ts
index 9bd1d36fa5..8d56f3ce8a 100644
--- a/packages/lambda-client/src/test/get-compositions-on-lambda.test.ts
+++ b/packages/lambda-client/src/test/get-compositions-on-lambda.test.ts
@@ -1,11 +1,11 @@
import {expect, spyOn, test} from 'bun:test';
-import {awsImplementation} from '../aws-provider';
+import * as callLambdaSync from '../call-lambda-sync';
import {getCompositionsOnLambda} from '../get-compositions-on-lambda';
test('defaults envVariables to {} when they are omitted', async () => {
const callFunctionSync = spyOn(
- awsImplementation,
- 'callFunctionSync',
+ callLambdaSync,
+ 'callFunctionSyncImplementation',
).mockResolvedValue({type: 'success', compositions: []} as never);
try {
await getCompositionsOnLambda({
diff --git a/packages/lambda-client/src/test/inline-props-size.test.ts b/packages/lambda-client/src/test/inline-props-size.test.ts
index 75d009c7e3..3919ef72e6 100644
--- a/packages/lambda-client/src/test/inline-props-size.test.ts
+++ b/packages/lambda-client/src/test/inline-props-size.test.ts
@@ -1,12 +1,13 @@
import {expect, spyOn, test} from 'bun:test';
-import {awsImplementation} from '../aws-provider';
import {makeLambdaRenderMediaPayload} from '../make-lambda-payload';
import {renderMediaOnLambdaOptionalToRequired} from '../render-media-on-lambda';
+import * as writeFileModule from '../write-file';
const makePayload = async (inputProps: Record<string, unknown>) => {
- const writeFile = spyOn(awsImplementation, 'writeFile').mockImplementation(
- () => Promise.resolve(),
- );
+ const writeFile = spyOn(
+ writeFileModule,
+ 'lambdaWriteFileImplementation',
+ ).mockImplementation(() => Promise.resolve());
try {
const payload = await makeLambdaRenderMediaPayload(
renderMediaOnLambdaOptionalToRequired({
diff --git a/packages/lambda-client/src/test/price-calculation.test.ts b/packages/lambda-client/src/test/price-calculation.test.ts
index 25fadc2506..56db5927ff 100644
--- a/packages/lambda-client/src/test/price-calculation.test.ts
+++ b/packages/lambda-client/src/test/price-calculation.test.ts
@@ -1,5 +1,4 @@
import {expect, test} from 'bun:test';
-import {awsImplementation} from '../aws-provider';
import {estimatePrice} from '../estimate-price';
import {estimatePriceFromMetadata} from '../estimate-price-from-bucket';
@@ -60,7 +59,6 @@ test('Should not throw while calculating prices when time shifts occur', () => {
},
],
region: 'eu-central-1',
- providerSpecifics: awsImplementation,
fatalErrorTimestamp: null,
});
expect(price?.accruedSoFar).toBeGreaterThanOrEqual(0);
diff --git a/packages/lambda-client/src/test/progress.test.ts b/packages/lambda-client/src/test/progress.test.ts
index b1159a9720..ad47caf1fa 100644
--- a/packages/lambda-client/src/test/progress.test.ts
+++ b/packages/lambda-client/src/test/progress.test.ts
@@ -1,13 +1,14 @@
-import {expect, test} from 'bun:test';
+import {afterEach, expect, spyOn, test} from 'bun:test';
import {Readable} from 'node:stream';
-import {getExpectedOutName} from '../expected-out-name';
+import type {HeadFile} from '../aws-operations';
+import * as awsRegionMetadata from '../aws-region-metadata';
+import * as estimatePriceModule from '../estimate-price';
+import type {EstimatePriceInput} from '../estimate-price';
import {OutputFileAccessDeniedError} from '../find-output-file-in-bucket';
+import * as headFile from '../head-file';
import type {OverallRenderProgress} from '../overall-render-progress';
import {getProgress} from '../progress';
-import type {
- EstimatePriceInput,
- ProviderSpecifics,
-} from '../provider-implementation';
+import * as readFile from '../read-file';
import type {RenderMetadata} from '../render-metadata';
import {overallProgressKey} from '../shared-constants';
@@ -89,89 +90,50 @@ const progress: OverallRenderProgress = {
],
};
-const makeProviderSpecifics = ({
- onEstimatePrice,
+const spies: {mockRestore: () => void}[] = [];
+
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
+
+const installFakes = ({
+ onEstimatePrice = null,
onHeadFile,
billingCurrency = 'USD',
renderProgress,
}: {
- onEstimatePrice?: (input: EstimatePriceInput) => number;
- onHeadFile: ProviderSpecifics['headFile'];
+ onEstimatePrice?: ((input: EstimatePriceInput) => number) | null;
+ onHeadFile: HeadFile;
billingCurrency?: 'USD' | 'CNY';
renderProgress: OverallRenderProgress | null;
-}): ProviderSpecifics => {
- return {
- applyLifeCycle: () => Promise.resolve(),
- bucketExists: () => Promise.resolve(true),
- callFunctionAsync: () => Promise.resolve(),
- callFunctionStreaming: () => Promise.resolve(),
- callFunctionSync: () => Promise.reject(new Error('Not implemented')),
- checkCredentials: () => undefined,
- convertToServeUrl: () => 'serve-url',
- createBucket: () => Promise.resolve(),
- deleteFile: () => Promise.resolve(),
- deleteFunction: () => Promise.resolve(),
- estimatePrice: (input) => onEstimatePrice?.(input) ?? 0.01,
- getAccountId: () => Promise.resolve('123456789012'),
- getBucketPrefix: () => 'remotionlambda-',
- getBuckets: () => Promise.resolve([]),
- getChromiumPath: () => null,
- getEphemeralStorageForPriceCalculation: () => 512,
- getBillingCurrency: () => billingCurrency,
- getRendererFunctionTransport: () => 'response-streaming',
- getServiceDnsSuffix: () => 'example.com',
- getFunctions: () => Promise.resolve([]),
- getLoggingUrlForMethod: () => 'logs',
- getLoggingUrlForRendererFunction: () => 'logs',
- getMaxNonInlinePayloadSizePerFunction: () => 0,
- getMaxStillInlinePayloadSize: () => 0,
- getOutputUrl: ({
- renderMetadata: metadata,
- customCredentials,
- currentRegion,
- }) => {
- const {key, renderBucketName} = getExpectedOutName({
- output: 'main',
- renderMetadata: metadata,
- bucketName,
- customCredentials,
- bucketNamePrefix: 'remotionlambda-',
- });
- return {
- key,
- url: `https://s3.${currentRegion}.amazonaws.com/${renderBucketName}/${key}`,
- };
- },
- isFlakyError: () => false,
- listObjects: () => Promise.resolve([]),
- parseFunctionName: () => ({
- diskSizeInMb: 512,
- memorySizeInMb: 2048,
- timeoutInSeconds: 120,
- version: '4.0.0',
- }),
- printLoggingHelper: false,
- randomHash: () => 'hash',
- readFile: ({key}) => {
- expect(key).toBe(overallProgressKey(renderId));
- return Promise.resolve(
- Readable.from([
- Buffer.from(JSON.stringify(renderProgress ?? progress)),
- ]),
- );
- },
- serverStorageProductName: () => 'S3',
- validateDeleteAfter: () => undefined,
- writeFile: () => Promise.resolve(),
- supportsConditionalOutput: () => true,
- writeFileIfNotExists: null,
- headFile: onHeadFile,
- };
+}) => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+ spies.push(
+ spyOn(estimatePriceModule, 'estimatePrice').mockImplementation(
+ (input) => onEstimatePrice?.(input) ?? 0.01,
+ ),
+ spyOn(awsRegionMetadata, 'getBillingCurrency').mockImplementation(
+ () => billingCurrency,
+ ),
+ spyOn(readFile, 'lambdaReadFileImplementation').mockImplementation(
+ ({key}) => {
+ expect(key).toBe(overallProgressKey(renderId));
+ return Promise.resolve(
+ Readable.from([
+ Buffer.from(JSON.stringify(renderProgress ?? progress)),
+ ]),
+ );
+ },
+ ),
+ spyOn(headFile, 'lambdaHeadFileImplementation').mockImplementation(
+ onHeadFile,
+ ),
+ );
};
test('getProgress treats an existing output file as finished if postRenderData was not persisted', async () => {
const headedFiles: {bucketName: string; key: string}[] = [];
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
billingCurrency: 'CNY',
onHeadFile: ({bucketName: headedBucketName, key}) => {
headedFiles.push({bucketName: headedBucketName, key});
@@ -190,7 +152,6 @@ test('getProgress treats an existing output file as finished if postRenderData w
forcePathStyle: false,
functionName: renderMetadata.functionName,
memorySizeInMb: 2048,
- providerSpecifics,
region: 'eu-central-1',
renderId,
requestHandler: null,
@@ -221,9 +182,13 @@ test('getProgress estimates costs from invoked lambdas only', async () => {
progress.chunks = [];
progress.lambdasInvoked = 1;
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
onEstimatePrice: (input) => {
priceInputs.push(input);
+ if (!('durationInMilliseconds' in input)) {
+ throw new Error('Expected durationInMilliseconds');
+ }
+
return input.durationInMilliseconds;
},
onHeadFile: () => Promise.resolve({ContentLength: 0}),
@@ -237,7 +202,6 @@ test('getProgress estimates costs from invoked lambdas only', async () => {
forcePathStyle: false,
functionName: renderMetadata.functionName,
memorySizeInMb: 2048,
- providerSpecifics,
region: 'eu-central-1',
renderId,
requestHandler: null,
@@ -274,7 +238,7 @@ test('getProgress keeps direct render progress finite', async () => {
},
timeToCombine: null,
};
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
onHeadFile: () => Promise.reject(new Error('Unexpected headFile call')),
renderProgress: directProgress,
});
@@ -288,7 +252,6 @@ test('getProgress keeps direct render progress finite', async () => {
forcePathStyle: false,
functionName: renderMetadata.functionName,
memorySizeInMb: 2048,
- providerSpecifics,
region: 'eu-central-1',
renderId,
requestHandler: null,
@@ -304,7 +267,7 @@ test('getProgress keeps direct render progress finite', async () => {
test('getProgress falls back to persisted progress when destination reads are denied', async () => {
let heads = 0;
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
renderProgress: null,
onHeadFile: () => {
heads++;
@@ -322,7 +285,6 @@ test('getProgress falls back to persisted progress when destination reads are de
forcePathStyle: false,
functionName: renderMetadata.functionName,
memorySizeInMb: 2048,
- providerSpecifics,
region: 'eu-central-1',
requestHandler: null,
timeoutInMilliseconds,
@@ -355,7 +317,7 @@ test('getProgress preserves upload failures and unexpected storage errors', asyn
$metadata: {httpStatusCode: 500},
});
for (const errors of [[uploadFailure], []]) {
- const providerSpecifics = makeProviderSpecifics({
+ installFakes({
renderProgress: {...progress, errors},
onHeadFile: () => {
heads++;
@@ -370,7 +332,6 @@ test('getProgress preserves upload failures and unexpected storage errors', asyn
forcePathStyle: false,
functionName: renderMetadata.functionName,
memorySizeInMb: 2048,
- providerSpecifics,
region: 'eu-central-1',
requestHandler: null,
timeoutInMilliseconds: 120000,
diff --git a/packages/lambda-client/src/validate-delete-after.ts b/packages/lambda-client/src/validate-delete-after.ts
new file mode 100644
index 0000000000..f94ec60ba9
--- /dev/null
+++ b/packages/lambda-client/src/validate-delete-after.ts
@@ -0,0 +1,27 @@
+import {expiryDays} from './shared-constants';
+
+export const validateDeleteAfter = (lifeCycleValue: unknown) => {
+ if (lifeCycleValue === null) {
+ return;
+ }
+
+ if (lifeCycleValue === undefined) {
+ return;
+ }
+
+ if (typeof lifeCycleValue !== 'string') {
+ throw new TypeError(
+ `Expected life cycle value to be a string, got ${JSON.stringify(
+ lifeCycleValue,
+ )}`,
+ );
+ }
+
+ if (!(lifeCycleValue in expiryDays)) {
+ throw new TypeError(
+ `Expected deleteAfter value to be one of ${Object.keys(expiryDays).join(
+ ', ',
+ )}, got ${lifeCycleValue}`,
+ );
+ }
+};
diff --git a/packages/lambda-client/src/write-cancellation-signal.ts b/packages/lambda-client/src/write-cancellation-signal.ts
index 360a25aff4..fbd5799fdf 100644
--- a/packages/lambda-client/src/write-cancellation-signal.ts
+++ b/packages/lambda-client/src/write-cancellation-signal.ts
@@ -1,14 +1,13 @@
-import type {ProviderSpecifics} from './provider-implementation';
import type {AwsRegion} from './regions';
import {cancellationKey} from './shared-constants';
import type {RequestHandler} from './types';
+import {lambdaWriteFileImplementation} from './write-file';
type WriteCancellationSignalInput = {
bucketName: string;
renderId: string;
region: AwsRegion;
expectedBucketOwner: string | null;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
};
@@ -18,11 +17,10 @@ export const writeCancellationSignal = async ({
renderId,
region,
expectedBucketOwner,
- providerSpecifics,
forcePathStyle,
requestHandler,
}: WriteCancellationSignalInput) => {
- await providerSpecifics.writeFile({
+ await lambdaWriteFileImplementation({
bucketName,
key: cancellationKey(renderId),
body: JSON.stringify({cancelledAt: Date.now()}),
diff --git a/packages/lambda-client/src/write-file.ts b/packages/lambda-client/src/write-file.ts
index 60695a65a9..ef77468385 100644
--- a/packages/lambda-client/src/write-file.ts
+++ b/packages/lambda-client/src/write-file.ts
@@ -5,10 +5,10 @@ import {
} from '@aws-sdk/client-s3';
import {Upload} from '@aws-sdk/lib-storage';
import mimeTypes from 'mime-types';
+/* eslint-disable no-console */
+import type {WriteFileInput} from './aws-operations';
import {getContentDispositionHeader} from './content-disposition-header';
import {getS3Client} from './get-s3-client';
-/* eslint-disable no-console */
-import type {WriteFileInput} from './provider-implementation';
import type {CustomCredentials} from './shared-constants';
// Files larger than 100MB will use multipart upload
@@ -166,3 +166,11 @@ export const lambdaWriteFileIfNotExistsImplementation = (
return writeFileWithRetries({...params, ifNotExists: true});
};
+
+// Only S3 itself is trusted to honor atomic create-only uploads;
+// custom S3-compatible output providers may not.
+export const supportsConditionalOutput = ({
+ customCredentials,
+}: {
+ customCredentials: CustomCredentials | null;
+}): boolean => customCredentials === null;
diff --git a/packages/lambda/bunfig.toml b/packages/lambda/bunfig.toml
new file mode 100644
index 0000000000..ade0bbc419
--- /dev/null
+++ b/packages/lambda/bunfig.toml
@@ -0,0 +1,2 @@
+[test]
+preload = ["./src/test/preload.ts"]
diff --git a/packages/lambda/src/api/delete-site.ts b/packages/lambda/src/api/delete-site.ts
index 19ec80b012..4328d979c8 100644
--- a/packages/lambda/src/api/delete-site.ts
+++ b/packages/lambda/src/api/delete-site.ts
@@ -1,7 +1,6 @@
import {
LambdaClientInternals,
type AwsRegion,
- type ProviderSpecifics,
type RequestHandler,
} from '@remotion/lambda-client';
import {getSitesKey} from '@remotion/lambda-client/constants';
@@ -33,15 +32,14 @@ export const internalDeleteSite = async ({
siteName,
region,
onAfterItemDeleted,
- providerSpecifics,
forcePathStyle,
requestHandler,
-}: DeleteSiteInput & {
- providerSpecifics: ProviderSpecifics;
-}): Promise<DeleteSiteOutput> => {
- const accountId = await providerSpecifics.getAccountId({region});
+}: DeleteSiteInput & {}): Promise<DeleteSiteOutput> => {
+ const accountId = await LambdaClientInternals.getAccountIdImplementation({
+ region,
+ });
- let files = await providerSpecifics.listObjects({
+ let files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
// The `/` is important to not accidentially delete sites with the same name but containing a suffix.
prefix: `${getSitesKey(siteName)}/`,
@@ -63,11 +61,10 @@ export const internalDeleteSite = async ({
onAfterItemDeleted: onAfterItemDeleted ?? (() => undefined),
onBeforeItemDeleted: () => undefined,
region,
- providerSpecifics,
forcePathStyle,
requestHandler,
});
- files = await providerSpecifics.listObjects({
+ files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
// The `/` is important to not accidentially delete sites with the same name but containing a suffix.
prefix: `${getSitesKey(siteName)}/`,
@@ -94,7 +91,6 @@ export const deleteSite = (
...props,
onAfterItemDeleted: props.onAfterItemDeleted ?? null,
forcePathStyle: props.forcePathStyle ?? false,
- providerSpecifics: LambdaClientInternals.awsImplementation,
requestHandler: props.requestHandler ?? null,
});
};
diff --git a/packages/lambda/src/api/deploy-function.ts b/packages/lambda/src/api/deploy-function.ts
index 0a72731422..605142724a 100644
--- a/packages/lambda/src/api/deploy-function.ts
+++ b/packages/lambda/src/api/deploy-function.ts
@@ -2,7 +2,6 @@ import {
LambdaClientInternals,
speculateFunctionName,
type AwsRegion,
- type ProviderSpecifics,
type RequestHandler,
type RuntimePreference,
} from '@remotion/lambda-client';
@@ -10,14 +9,13 @@ import {DEFAULT_EPHEMERAL_STORAGE_IN_MB} from '@remotion/lambda-client/constants
import type {LogLevel} from '@remotion/renderer';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
import {VERSION} from 'remotion/version';
-import {awsFullClientSpecifics} from '../functions/full-client-implementation';
-import type {FullClientSpecifics} from '../functions/provider-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';
+import {createFunction} from './create-function';
type MandatoryParameters = {
createCloudWatchLogGroup: boolean;
@@ -53,8 +51,6 @@ export const internalDeployFunction = async (
params: MandatoryParameters &
OptionalParameters & {
customLayerArns: string[] | null;
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
},
): Promise<DeployFunctionOutput> => {
LambdaClientInternals.validateMemorySize(params.memorySizeInMb);
@@ -76,11 +72,11 @@ export const internalDeployFunction = async (
memorySizeInMb: params.memorySizeInMb,
timeoutInSeconds: params.timeoutInSeconds,
});
- const accountId = await params.providerSpecifics.getAccountId({
+ const accountId = await LambdaClientInternals.getAccountIdImplementation({
region: params.region,
});
- const fns = await params.providerSpecifics.getFunctions({
+ const fns = await LambdaClientInternals.getFunctions({
compatibleOnly: true,
region: params.region,
});
@@ -93,7 +89,7 @@ export const internalDeployFunction = async (
f.diskSizeInMb === params.diskSizeInMb,
);
- const created = await params.fullClientSpecifics.createFunction({
+ const created = await createFunction({
createCloudWatchLogGroup: params.createCloudWatchLogGroup,
region: params.region,
zipFile: FUNCTION_ZIP_ARM64,
@@ -174,8 +170,6 @@ export const deployFunction = ({
vpcSubnetIds,
vpcSecurityGroupIds,
runtimePreference: runtimePreference ?? 'default',
- providerSpecifics: LambdaClientInternals.awsImplementation,
- fullClientSpecifics: awsFullClientSpecifics,
requestHandler,
});
};
diff --git a/packages/lambda/src/api/deploy-site-from-bundle.ts b/packages/lambda/src/api/deploy-site-from-bundle.ts
index 5a6ad042bf..0af93aca2c 100644
--- a/packages/lambda/src/api/deploy-site-from-bundle.ts
+++ b/packages/lambda/src/api/deploy-site-from-bundle.ts
@@ -1,14 +1,11 @@
import {
LambdaClientInternals,
type AwsRegion,
- type ProviderSpecifics,
type RequestHandler,
} from '@remotion/lambda-client';
import type {ToOptions} from '@remotion/renderer';
import type {BrowserSafeApis} from '@remotion/renderer/client';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
-import {awsFullClientSpecifics} from '../functions/full-client-implementation';
-import type {FullClientSpecifics} from '../functions/provider-implementation';
import {
deploySiteWithBundle,
type DeploySiteOutput,
@@ -38,8 +35,6 @@ export type DeploySiteFromBundleInput = MandatoryParameters &
export type InternalDeploySiteFromBundleInput = MandatoryParameters &
OptionalParameters & {
indent: boolean;
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
};
const mandatoryDeploySiteFromBundle = ({
@@ -50,9 +45,7 @@ const mandatoryDeploySiteFromBundle = ({
options,
privacy,
throwIfSiteExists,
- providerSpecifics,
forcePathStyle,
- fullClientSpecifics,
requestHandler,
}: InternalDeploySiteFromBundleInput): DeploySiteFromBundleOutput => {
const resolvedBundleDir = validateBundleDir(bundleDir);
@@ -64,9 +57,7 @@ const mandatoryDeploySiteFromBundle = ({
options,
privacy,
throwIfSiteExists,
- providerSpecifics,
forcePathStyle,
- fullClientSpecifics,
requestHandler,
getBundle: () => Promise.resolve(resolvedBundleDir),
});
@@ -89,14 +80,11 @@ export const deploySiteFromBundle = (args: DeploySiteFromBundleInput) => {
region: args.region,
options: args.options ?? {},
privacy: args.privacy ?? 'public',
- siteName:
- args.siteName ?? LambdaClientInternals.awsImplementation.randomHash(),
+ siteName: args.siteName ?? LambdaClientInternals.randomHashImplementation(),
indent: false,
logLevel: args.logLevel ?? 'info',
throwIfSiteExists: args.throwIfSiteExists ?? false,
- providerSpecifics: LambdaClientInternals.awsImplementation,
forcePathStyle: args.forcePathStyle ?? false,
- fullClientSpecifics: awsFullClientSpecifics,
requestHandler: args.requestHandler ?? null,
});
};
diff --git a/packages/lambda/src/api/deploy-site.ts b/packages/lambda/src/api/deploy-site.ts
index fefba4331d..ee1ef673bc 100644
--- a/packages/lambda/src/api/deploy-site.ts
+++ b/packages/lambda/src/api/deploy-site.ts
@@ -8,18 +8,14 @@ import {
import {
LambdaClientInternals,
type AwsRegion,
- type ProviderSpecifics,
type RequestHandler,
} from '@remotion/lambda-client';
import {getSitesKey} from '@remotion/lambda-client/constants';
import type {ToOptions} from '@remotion/renderer';
import type {BrowserSafeApis} from '@remotion/renderer/client';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
-import {awsFullClientSpecifics} from '../functions/full-client-implementation';
-import type {
- FullClientSpecifics,
- UploadDirProgress,
-} from '../functions/provider-implementation';
+import type {UploadDirProgress} from '../functions/types';
+import {bundleSite} from '../shared/bundle-site';
import {
deploySiteWithBundle,
type DeploySiteOutput,
@@ -70,15 +66,9 @@ const mandatoryDeploySite = async ({
privacy,
gitSource,
throwIfSiteExists,
- providerSpecifics,
forcePathStyle,
- fullClientSpecifics,
requestHandler,
-}: MandatoryParameters &
- OptionalParameters & {
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
- }): DeploySiteOutput => {
+}: MandatoryParameters & OptionalParameters & {}): DeploySiteOutput => {
let generatedBundleDir: string | null = null;
let deploymentOutcome:
@@ -93,12 +83,10 @@ const mandatoryDeploySite = async ({
options,
privacy,
throwIfSiteExists,
- providerSpecifics,
forcePathStyle,
- fullClientSpecifics,
requestHandler,
getBundle: async () => {
- const bundleDir = await fullClientSpecifics.bundleSite({
+ const bundleDir = await bundleSite({
publicPath: `/${getSitesKey(siteName)}/`,
bundlerOverride: options.bundlerOverride ?? ((f) => f),
rspackOverride: options.rspackOverride ?? ((f) => f),
@@ -170,10 +158,7 @@ const mandatoryDeploySite = async ({
};
export type InternalDeploySiteInput = MandatoryParameters &
- OptionalParameters & {
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
- };
+ OptionalParameters & {};
export const internalDeploySite: (
input: InternalDeploySiteInput,
@@ -191,14 +176,11 @@ export const deploySite = (args: DeploySiteInput) => {
gitSource: args.gitSource ?? null,
options: args.options ?? {},
privacy: args.privacy ?? 'public',
- siteName:
- args.siteName ?? LambdaClientInternals.awsImplementation.randomHash(),
+ siteName: args.siteName ?? LambdaClientInternals.randomHashImplementation(),
indent: false,
logLevel: 'info',
throwIfSiteExists: args.throwIfSiteExists ?? false,
- providerSpecifics: LambdaClientInternals.awsImplementation,
forcePathStyle: args.forcePathStyle ?? false,
- fullClientSpecifics: awsFullClientSpecifics,
requestHandler: args.requestHandler ?? null,
});
};
diff --git a/packages/lambda/src/api/download-media.ts b/packages/lambda/src/api/download-media.ts
index f0a018125a..42ab3a4cd0 100644
--- a/packages/lambda/src/api/download-media.ts
+++ b/packages/lambda/src/api/download-media.ts
@@ -4,7 +4,6 @@ import {
LambdaClientInternals,
type AwsRegion,
type CustomCredentials,
- type ProviderSpecifics,
type RenderOutput,
type RequestHandler,
} from '@remotion/lambda-client';
@@ -49,20 +48,19 @@ export type DownloadMediaOutput = {
export const internalDownloadMedia = async (
input: InternalDownloadMediaInput & {
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
},
): Promise<DownloadMediaOutput> => {
- const expectedBucketOwner = await input.providerSpecifics.getAccountId({
- region: input.region,
- });
+ const expectedBucketOwner =
+ await LambdaClientInternals.getAccountIdImplementation({
+ region: input.region,
+ });
const overallProgress =
await LambdaClientInternals.getOverallProgressFromStorage({
bucketName: input.bucketName,
expectedBucketOwner,
region: input.region,
renderId: input.renderId,
- providerSpecifics: input.providerSpecifics,
forcePathStyle: input.forcePathStyle,
requestHandler: input.requestHandler,
});
@@ -189,7 +187,6 @@ export const downloadMedia = (
return internalDownloadMedia({
...input,
- providerSpecifics: LambdaClientInternals.awsImplementation,
output: input.output ?? 'main',
forcePathStyle: false,
onProgress: input.onProgress ?? (() => undefined),
diff --git a/packages/lambda/src/api/get-or-create-bucket.ts b/packages/lambda/src/api/get-or-create-bucket.ts
index 001b4c9d54..7977f2f4fa 100644
--- a/packages/lambda/src/api/get-or-create-bucket.ts
+++ b/packages/lambda/src/api/get-or-create-bucket.ts
@@ -12,7 +12,6 @@ export const getOrCreateBucket = (options: GetOrCreateBucketInput) => {
region: options.region,
enableFolderExpiry: options.enableFolderExpiry ?? null,
customCredentials: options.customCredentials ?? null,
- providerSpecifics: LambdaClientInternals.awsImplementation,
forcePathStyle: false,
skipPutAcl: false,
requestHandler: options.requestHandler ?? null,
diff --git a/packages/lambda/src/api/upload-dir.ts b/packages/lambda/src/api/upload-dir.ts
index e90f7f2843..11a5720009 100644
--- a/packages/lambda/src/api/upload-dir.ts
+++ b/packages/lambda/src/api/upload-dir.ts
@@ -9,7 +9,7 @@ import {
type RequestHandler,
} from '@remotion/lambda-client';
import mimeTypes from 'mime-types';
-import type {UploadDirProgress} from '../functions/provider-implementation';
+import type {UploadDirProgress} from '../functions/types';
import {makeS3Key} from '../shared/make-s3-key';
import {multipartUploadPartSize} from '../shared/multipart-upload-part-size';
import {waitForPromisesToFinish} from '../shared/wait-for-promises-to-finish';
diff --git a/packages/lambda/src/cli/commands/compositions/index.ts b/packages/lambda/src/cli/commands/compositions/index.ts
index 4e7c074858..0ff1c949cb 100644
--- a/packages/lambda/src/cli/commands/compositions/index.ts
+++ b/packages/lambda/src/cli/commands/compositions/index.ts
@@ -2,7 +2,6 @@ import {CliInternals} from '@remotion/cli';
import {
LambdaClientInternals,
getCompositionsOnLambda,
- type ProviderSpecifics,
} from '@remotion/lambda-client';
import {BINARY_NAME} from '@remotion/lambda-client/constants';
import type {ChromiumOptions, LogLevel} from '@remotion/renderer';
@@ -30,11 +29,9 @@ const {
export const compositionsCommand = async ({
args,
logLevel,
- providerSpecifics,
}: {
args: string[];
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
}) => {
const serveUrl = args[0];
@@ -93,7 +90,7 @@ export const compositionsCommand = async ({
const region = getAwsRegion();
LambdaClientInternals.validateServeUrl(serveUrl);
- const functionName = await findFunctionName({logLevel, providerSpecifics});
+ const functionName = await findFunctionName({logLevel});
const comps = await getCompositionsOnLambda({
functionName,
diff --git a/packages/lambda/src/cli/commands/functions/deploy.ts b/packages/lambda/src/cli/commands/functions/deploy.ts
index c96287388c..635e0c8638 100644
--- a/packages/lambda/src/cli/commands/functions/deploy.ts
+++ b/packages/lambda/src/cli/commands/functions/deploy.ts
@@ -1,8 +1,5 @@
import {CliInternals} from '@remotion/cli';
-import {
- LambdaClientInternals,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals} from '@remotion/lambda-client';
import {
DEFAULT_CLOUDWATCH_RETENTION_PERIOD,
DEFAULT_EPHEMERAL_STORAGE_IN_MB,
@@ -12,7 +9,6 @@ import {
import type {LogLevel} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
import {internalDeployFunction} from '../../../api/deploy-function';
-import type {FullClientSpecifics} from '../../../functions/provider-implementation';
import {validateCustomRoleArn} from '../../../shared/validate-custom-role-arn';
import {validateTimeout} from '../../../shared/validate-timeout';
import {validateVpcSecurityGroupIds} from '../../../shared/validate-vpc-security-group-ids';
@@ -25,12 +21,8 @@ export const FUNCTIONS_DEPLOY_SUBCOMMAND = 'deploy';
export const functionsDeploySubcommand = async ({
logLevel,
- providerSpecifics,
- fullClientSpecifics,
}: {
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
}) => {
const region = getAwsRegion();
const timeoutInSeconds = parsedLambdaCli.timeout ?? DEFAULT_TIMEOUT;
@@ -119,8 +111,6 @@ VPC Security Group IDs = ${vpcSecurityGroupIds}
vpcSubnetIds,
vpcSecurityGroupIds,
runtimePreference,
- providerSpecifics,
- fullClientSpecifics,
requestHandler: null,
});
if (CliInternals.quietFlagProvided()) {
diff --git a/packages/lambda/src/cli/commands/functions/index.ts b/packages/lambda/src/cli/commands/functions/index.ts
index ef79aef356..4a7f786e7a 100644
--- a/packages/lambda/src/cli/commands/functions/index.ts
+++ b/packages/lambda/src/cli/commands/functions/index.ts
@@ -1,8 +1,6 @@
import {CliInternals} from '@remotion/cli';
-import type {ProviderSpecifics} from '@remotion/lambda-client';
import {BINARY_NAME} from '@remotion/lambda-client/constants';
import type {LogLevel} from '@remotion/renderer';
-import type {FullClientSpecifics} from '../../../functions/provider-implementation';
import {quit} from '../../helpers/quit';
import {FUNCTIONS_COMMAND} from '../command-names';
import {FUNCTIONS_DEPLOY_SUBCOMMAND, functionsDeploySubcommand} from './deploy';
@@ -60,16 +58,12 @@ const printFunctionsHelp = (logLevel: LogLevel) => {
export const functionsCommand = ({
args,
logLevel,
- fullClientSpecifics,
- providerSpecifics,
}: {
args: string[];
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
}) => {
if (args[0] === FUNCTIONS_LS_SUBCOMMAND) {
- return functionsLsCommand({logLevel, providerSpecifics});
+ return functionsLsCommand({logLevel});
}
if (args[0] === FUNCTIONS_RM_SUBCOMMAND) {
@@ -77,14 +71,12 @@ export const functionsCommand = ({
}
if (args[0] === FUNCTIONS_RMALL_SUBCOMMAND) {
- return functionsRmallCommand({logLevel, providerSpecifics});
+ return functionsRmallCommand({logLevel});
}
if (args[0] === FUNCTIONS_DEPLOY_SUBCOMMAND) {
return functionsDeploySubcommand({
logLevel,
- fullClientSpecifics,
- providerSpecifics,
});
}
diff --git a/packages/lambda/src/cli/commands/functions/ls.ts b/packages/lambda/src/cli/commands/functions/ls.ts
index ec3a816a83..50638a0357 100644
--- a/packages/lambda/src/cli/commands/functions/ls.ts
+++ b/packages/lambda/src/cli/commands/functions/ls.ts
@@ -1,5 +1,5 @@
import {CliInternals} from '@remotion/cli';
-import {type ProviderSpecifics} from '@remotion/lambda-client';
+import {LambdaClientInternals} from '@remotion/lambda-client';
import type {LogLevel} from '@remotion/renderer';
import {parsedLambdaCli} from '../../args';
import {getAwsRegion} from '../../get-aws-region';
@@ -12,13 +12,7 @@ const VERSION_COLS = 15;
export const FUNCTIONS_LS_SUBCOMMAND = 'ls';
-export const functionsLsCommand = async ({
- logLevel,
- providerSpecifics,
-}: {
- logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
-}) => {
+export const functionsLsCommand = async ({logLevel}: {logLevel: LogLevel}) => {
const region = getAwsRegion();
const fetchingOutput = CliInternals.createOverwriteableCliOutput({
quiet: CliInternals.quietFlagProvided(),
@@ -33,7 +27,7 @@ export const functionsLsCommand = async ({
const compatibleOnly = parsedLambdaCli['compatible-only'] || false;
- const functions = await providerSpecifics.getFunctions({
+ const functions = await LambdaClientInternals.getFunctions({
region,
compatibleOnly,
});
diff --git a/packages/lambda/src/cli/commands/functions/rmall.ts b/packages/lambda/src/cli/commands/functions/rmall.ts
index 0d9db68356..90be36cab8 100644
--- a/packages/lambda/src/cli/commands/functions/rmall.ts
+++ b/packages/lambda/src/cli/commands/functions/rmall.ts
@@ -1,5 +1,5 @@
import {CliInternals} from '@remotion/cli';
-import {deleteFunction, type ProviderSpecifics} from '@remotion/lambda-client';
+import {deleteFunction, LambdaClientInternals} from '@remotion/lambda-client';
import type {LogLevel} from '@remotion/renderer';
import {getFunctionInfo} from '../../../api/get-function-info';
import {getAwsRegion} from '../../get-aws-region';
@@ -10,13 +10,11 @@ const LEFT_COL = 16;
export const functionsRmallCommand = async ({
logLevel,
- providerSpecifics,
}: {
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
}) => {
const region = getAwsRegion();
- const functions = await providerSpecifics.getFunctions({
+ const functions = await LambdaClientInternals.getFunctions({
region,
compatibleOnly: false,
});
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index 4c2cc3956b..0cbdb9385a 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -5,7 +5,6 @@ import {
LambdaClientInternals,
getRenderProgress,
type EnhancedErrorInfo,
- type ProviderSpecifics,
type ServerlessCodec,
} from '@remotion/lambda-client';
import {
@@ -88,12 +87,10 @@ export const renderCommand = async ({
args,
remotionRoot,
logLevel,
- providerSpecifics,
}: {
args: string[];
remotionRoot: string;
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
}) => {
const serveUrl = args[0];
if (!serveUrl) {
@@ -388,7 +385,7 @@ export const renderCommand = async ({
throw new Error('Expected image format to be resolved');
}
- const functionName = await findFunctionName({logLevel, providerSpecifics});
+ const functionName = await findFunctionName({logLevel});
const maxRetries = parsedLambdaCli['max-retries'] ?? DEFAULT_MAX_RETRIES;
validateMaxRetries(maxRetries);
@@ -512,7 +509,6 @@ export const renderCommand = async ({
renderId: res.renderId,
forcePathStyle: parsedLambdaCli['force-path-style'] ?? false,
requestHandler: null,
- providerSpecifics,
});
} catch (err) {
Log.error(
@@ -700,7 +696,6 @@ export const renderCommand = async ({
false,
);
},
- providerSpecifics: providerSpecifics,
forcePathStyle: parsedLambdaCli['force-path-style'],
signal: new AbortController().signal,
customCredentials: s3OutputProvider,
diff --git a/packages/lambda/src/cli/commands/sites/create.ts b/packages/lambda/src/cli/commands/sites/create.ts
index b25f15a3a9..31345b7d84 100644
--- a/packages/lambda/src/cli/commands/sites/create.ts
+++ b/packages/lambda/src/cli/commands/sites/create.ts
@@ -1,15 +1,10 @@
import {CliInternals} from '@remotion/cli';
import {ConfigInternals} from '@remotion/cli/config';
-import {
- LambdaClientInternals,
- type Privacy,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals, type Privacy} from '@remotion/lambda-client';
import {BINARY_NAME} from '@remotion/lambda-client/constants';
import type {LogLevel} from '@remotion/renderer';
import {BrowserSafeApis} from '@remotion/renderer/client';
import {NoReactInternals} from 'remotion/no-react';
-import {awsFullClientSpecifics} from '../../../functions/full-client-implementation';
import {LambdaInternals} from '../../../internals';
import {validateSiteName} from '../../../shared/validate-site-name';
import {parsedLambdaCli} from '../../args';
@@ -45,7 +40,6 @@ export const sitesCreateSubcommand = async (
args: string[],
remotionRoot: string,
logLevel: LogLevel,
- implementation: ProviderSpecifics,
) => {
const {file, reason} = CliInternals.findEntryPoint({
args,
@@ -142,7 +136,6 @@ export const sitesCreateSubcommand = async (
region: getAwsRegion(),
enableFolderExpiry,
customCredentials: null,
- providerSpecifics: implementation,
forcePathStyle: false,
skipPutAcl: parsedLambdaCli.privacy === 'no-acl',
requestHandler: null,
@@ -182,7 +175,8 @@ export const sitesCreateSubcommand = async (
const {serveUrl, siteName, stats} = await LambdaInternals.internalDeploySite({
entryPoint: file,
- siteName: desiredSiteName ?? implementation.randomHash(),
+ siteName:
+ desiredSiteName ?? LambdaClientInternals.randomHashImplementation(),
bucketName,
options: {
publicDir,
@@ -239,9 +233,7 @@ export const sitesCreateSubcommand = async (
indent: false,
logLevel,
throwIfSiteExists,
- providerSpecifics: implementation,
forcePathStyle: parsedLambdaCli['force-path-style'] ?? false,
- fullClientSpecifics: awsFullClientSpecifics,
requestHandler: null,
});
diff --git a/packages/lambda/src/cli/commands/sites/index.ts b/packages/lambda/src/cli/commands/sites/index.ts
index e5246c75c8..154efcaf43 100644
--- a/packages/lambda/src/cli/commands/sites/index.ts
+++ b/packages/lambda/src/cli/commands/sites/index.ts
@@ -1,5 +1,4 @@
import {CliInternals} from '@remotion/cli';
-import {type ProviderSpecifics} from '@remotion/lambda-client';
import {BINARY_NAME} from '@remotion/lambda-client/constants';
import type {LogLevel} from '@remotion/renderer';
import {quit} from '../../helpers/quit';
@@ -60,27 +59,21 @@ export const sitesCommand = (
args: string[],
remotionRoot: string,
logLevel: LogLevel,
- providerSpecifics: ProviderSpecifics,
) => {
if (args[0] === SITES_LS_SUBCOMMAND) {
return sitesLsSubcommand(logLevel);
}
if (args[0] === SITES_RM_COMMAND) {
- return sitesRmSubcommand(args.slice(1), logLevel, providerSpecifics);
+ return sitesRmSubcommand(args.slice(1), logLevel);
}
if (args[0] === SITES_RMALL_COMMAND) {
- return sitesRmallSubcommand(logLevel, providerSpecifics);
+ return sitesRmallSubcommand(logLevel);
}
if (args[0] === SITES_CREATE_SUBCOMMAND) {
- return sitesCreateSubcommand(
- args.slice(1),
- remotionRoot,
- logLevel,
- providerSpecifics,
- );
+ return sitesCreateSubcommand(args.slice(1), remotionRoot, logLevel);
}
if (args[0]) {
diff --git a/packages/lambda/src/cli/commands/sites/rm.ts b/packages/lambda/src/cli/commands/sites/rm.ts
index 2987500b5f..57cf595505 100644
--- a/packages/lambda/src/cli/commands/sites/rm.ts
+++ b/packages/lambda/src/cli/commands/sites/rm.ts
@@ -1,9 +1,5 @@
import {CliInternals} from '@remotion/cli';
-import {
- LambdaClientInternals,
- getSites,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals, getSites} from '@remotion/lambda-client';
import type {LogLevel} from '@remotion/renderer';
import {deleteSite} from '../../../api/delete-site';
import {parsedLambdaCli} from '../../args';
@@ -13,11 +9,7 @@ import {quit} from '../../helpers/quit';
import {Log} from '../../log';
export const SITES_RM_COMMAND = 'rm';
-export const sitesRmSubcommand = async (
- args: string[],
- logLevel: LogLevel,
- implementation: ProviderSpecifics,
-) => {
+export const sitesRmSubcommand = async (args: string[], logLevel: LogLevel) => {
if (args.length === 0) {
Log.error(
{indent: false, logLevel},
@@ -44,7 +36,6 @@ export const sitesRmSubcommand = async (
region,
enableFolderExpiry: false,
customCredentials: null,
- providerSpecifics: implementation,
forcePathStyle: false,
skipPutAcl: false,
requestHandler: null,
diff --git a/packages/lambda/src/cli/commands/sites/rmall.ts b/packages/lambda/src/cli/commands/sites/rmall.ts
index b4dad90b19..d29843f21b 100644
--- a/packages/lambda/src/cli/commands/sites/rmall.ts
+++ b/packages/lambda/src/cli/commands/sites/rmall.ts
@@ -1,9 +1,5 @@
import {CliInternals} from '@remotion/cli';
-import {
- LambdaClientInternals,
- getSites,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals, getSites} from '@remotion/lambda-client';
import type {LogLevel} from '@remotion/renderer';
import {deleteSite} from '../../../api/delete-site';
import {parsedLambdaCli} from '../../args';
@@ -13,10 +9,7 @@ import {Log} from '../../log';
export const SITES_RMALL_COMMAND = 'rmall';
-export const sitesRmallSubcommand = async (
- logLevel: LogLevel,
- implementation: ProviderSpecifics,
-) => {
+export const sitesRmallSubcommand = async (logLevel: LogLevel) => {
const region = getAwsRegion();
const deployedSites = await getSites({
region,
@@ -29,7 +22,6 @@ export const sitesRmallSubcommand = async (
region,
enableFolderExpiry: false,
customCredentials: null,
- providerSpecifics: implementation,
forcePathStyle: false,
skipPutAcl: false,
requestHandler: null,
diff --git a/packages/lambda/src/cli/commands/still.ts b/packages/lambda/src/cli/commands/still.ts
index d3c9d9dc14..ddd40a0f5a 100644
--- a/packages/lambda/src/cli/commands/still.ts
+++ b/packages/lambda/src/cli/commands/still.ts
@@ -1,10 +1,7 @@
import path from 'path';
import {CliInternals} from '@remotion/cli';
import {ConfigInternals} from '@remotion/cli/config';
-import {
- LambdaClientInternals,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals} from '@remotion/lambda-client';
import {
BINARY_NAME,
DEFAULT_MAX_RETRIES,
@@ -66,12 +63,10 @@ export const stillCommand = async ({
args,
remotionRoot,
logLevel,
- providerSpecifics,
}: {
args: string[];
remotionRoot: string;
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
}) => {
const serveUrl = args[0];
@@ -236,7 +231,7 @@ export const stillCommand = async ({
s3OutputProvider,
});
- const functionName = await findFunctionName({logLevel, providerSpecifics});
+ const functionName = await findFunctionName({logLevel});
const maxRetries = parsedLambdaCli['max-retries'] ?? DEFAULT_MAX_RETRIES;
validateMaxRetries(maxRetries);
@@ -379,7 +374,6 @@ export const stillCommand = async ({
region,
renderId: res.renderId,
logLevel,
- providerSpecifics: providerSpecifics,
forcePathStyle: parsedLambdaCli['force-path-style'],
signal: new AbortController().signal,
customCredentials: s3OutputProvider,
diff --git a/packages/lambda/src/cli/helpers/find-function-name.ts b/packages/lambda/src/cli/helpers/find-function-name.ts
index ab03582f61..b63c01fe67 100644
--- a/packages/lambda/src/cli/helpers/find-function-name.ts
+++ b/packages/lambda/src/cli/helpers/find-function-name.ts
@@ -1,7 +1,4 @@
-import {
- LambdaClientInternals,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals} from '@remotion/lambda-client';
import {BINARY_NAME} from '@remotion/lambda-client/constants';
import type {LogLevel, LogOptions} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
@@ -14,14 +11,8 @@ import {getAwsRegion} from '../get-aws-region';
import {Log} from '../log';
import {quit} from './quit';
-export const findFunctionName = async ({
- logLevel,
- providerSpecifics,
-}: {
- logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
-}) => {
- const remotionLambdas = await providerSpecifics.getFunctions({
+export const findFunctionName = async ({logLevel}: {logLevel: LogLevel}) => {
+ const remotionLambdas = await LambdaClientInternals.getFunctions({
region: getAwsRegion(),
compatibleOnly: false,
});
diff --git a/packages/lambda/src/cli/index.ts b/packages/lambda/src/cli/index.ts
index 9bd789dc72..4b06e68c4d 100644
--- a/packages/lambda/src/cli/index.ts
+++ b/packages/lambda/src/cli/index.ts
@@ -1,14 +1,9 @@
import {CliInternals} from '@remotion/cli';
-import {
- LambdaClientInternals,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals} from '@remotion/lambda-client';
import {BINARY_NAME} from '@remotion/lambda-client/constants';
import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import {ROLE_NAME} from '../api/iam-validation/suggested-policy';
-import {awsFullClientSpecifics} from '../functions/full-client-implementation';
-import type {FullClientSpecifics} from '../functions/provider-implementation';
import {parsedLambdaCli} from './args';
import {
COMPOSITIONS_COMMAND,
@@ -49,14 +44,10 @@ const matchCommand = ({
args,
remotionRoot,
logLevel,
- providerSpecifics,
- fullClientSpecifics,
}: {
args: string[];
remotionRoot: string;
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
- fullClientSpecifics: FullClientSpecifics;
}) => {
if (parsedLambdaCli.help || args.length === 0) {
printHelp(args, logLevel);
@@ -64,7 +55,7 @@ const matchCommand = ({
}
if (requiresCredentials(args)) {
- providerSpecifics.checkCredentials();
+ LambdaClientInternals.checkCredentials();
}
if (args[0] === RENDER_COMMAND) {
@@ -72,7 +63,6 @@ const matchCommand = ({
args: args.slice(1),
remotionRoot,
logLevel,
- providerSpecifics,
});
}
@@ -81,7 +71,6 @@ const matchCommand = ({
args: args.slice(1),
remotionRoot,
logLevel,
- providerSpecifics: providerSpecifics,
});
}
@@ -89,7 +78,6 @@ const matchCommand = ({
return compositionsCommand({
args: args.slice(1),
logLevel,
- providerSpecifics,
});
}
@@ -97,8 +85,6 @@ const matchCommand = ({
return functionsCommand({
args: args.slice(1),
logLevel,
- fullClientSpecifics,
- providerSpecifics,
});
}
@@ -115,12 +101,7 @@ const matchCommand = ({
}
if (args[0] === SITES_COMMAND) {
- return sitesCommand(
- args.slice(1),
- remotionRoot,
- logLevel,
- providerSpecifics,
- );
+ return sitesCommand(args.slice(1), remotionRoot, logLevel);
}
if (args[0] === 'upload') {
@@ -176,18 +157,12 @@ export const executeCommand = async (
args: string[],
remotionRoot: string,
logLevel: LogLevel,
- _providerSpecifics: ProviderSpecifics | null,
- fullClientSpecifics: FullClientSpecifics | null,
) => {
try {
- const providerSpecifics =
- _providerSpecifics ?? LambdaClientInternals.awsImplementation;
await matchCommand({
args,
remotionRoot,
logLevel,
- providerSpecifics: providerSpecifics,
- fullClientSpecifics: fullClientSpecifics ?? awsFullClientSpecifics,
});
} catch (err) {
const error = err as Error;
@@ -306,11 +281,5 @@ export const cli = async (logLevel: LogLevel) => {
const remotionRoot = RenderInternals.findRemotionRoot();
await CliInternals.initializeCli(remotionRoot);
- await executeCommand(
- parsedLambdaCli._,
- remotionRoot,
- logLevel,
- LambdaClientInternals.awsImplementation,
- awsFullClientSpecifics,
- );
+ await executeCommand(parsedLambdaCli._, remotionRoot, logLevel);
};
diff --git a/packages/lambda/src/functions/aws-server-implementation.ts b/packages/lambda/src/functions/aws-server-implementation.ts
deleted file mode 100644
index 60e9e26a25..0000000000
--- a/packages/lambda/src/functions/aws-server-implementation.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import {LambdaClientInternals} from '@remotion/lambda-client';
-import {RenderInternals} from '@remotion/renderer';
-import {NoReactInternals} from 'remotion/no-react';
-import {
- closeBrowserInstanceImplementation,
- forgetBrowserEventLoopImplementation,
- getBrowserInstanceImplementation,
-} from './get-browser-instance';
-import {deleteTmpDir} from './helpers/clean-tmpdir';
-import {getCurrentRegionInFunctionImplementation} from './helpers/get-current-region';
-import {getTmpDirStateIfENoSp} from './helpers/get-tmp-dir';
-import {startLeakDetection} from './helpers/leak-detection';
-import {makeAwsArtifact} from './helpers/make-aws-artifact';
-import {timer} from './helpers/timer';
-import {enableNodeIntrospection} from './helpers/why-is-node-running';
-import {invokeWebhook} from './invoke-webhook';
-import type {InsideFunctionSpecifics} from './provider-implementation';
-
-const ENABLE_SLOW_LEAK_DETECTION = false;
-
-export const serverAwsImplementation: InsideFunctionSpecifics = {
- defaultX264Preset: NoReactInternals.ENABLE_V5_BREAKING_CHANGES
- ? 'veryfast'
- : null,
- forgetBrowserEventLoop: forgetBrowserEventLoopImplementation,
- closeBrowserInstance: closeBrowserInstanceImplementation,
- getBrowserInstance: (options) =>
- getBrowserInstanceImplementation({
- ...options,
- chromiumOptions: {
- ...options.chromiumOptions,
- // The CLI can pass null; Lambda still needs software rendering.
- gl: options.chromiumOptions.gl ?? 'swangle',
- enableMultiProcessOnLinux: false,
- },
- }),
- timer,
- getCurrentRegionInFunction: getCurrentRegionInFunctionImplementation,
-
- generateRandomId: ({deleteAfter, randomHashFn}) => {
- return LambdaClientInternals.generateRandomHashWithLifeCycleRule({
- deleteAfter,
- randomHashFn,
- });
- },
- deleteTmpDir: () => Promise.resolve(deleteTmpDir()),
- getCurrentFunctionName: () => {
- if (!process.env.AWS_LAMBDA_FUNCTION_NAME) {
- throw new Error('Expected AWS_LAMBDA_FUNCTION_NAME to be set');
- }
-
- return process.env.AWS_LAMBDA_FUNCTION_NAME;
- },
- getCurrentMemorySizeInMb: () => {
- return Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);
- },
- invokeWebhook,
- makeArtifactWithDetails: makeAwsArtifact,
- normalizeChromiumOptions: ({chromiumOptions, logLevel}) => {
- if (chromiumOptions.gl !== 'angle') {
- return chromiumOptions;
- }
-
- RenderInternals.Log.warn(
- {indent: false, logLevel},
- 'gl=angle is not supported in Lambda. Changing to gl=swangle instead.',
- );
- return {...chromiumOptions, gl: 'swangle'};
- },
- getTmpDirState: getTmpDirStateIfENoSp,
- startRendererDiagnostics: ENABLE_SLOW_LEAK_DETECTION
- ? (requestId) => {
- const diagnostics = enableNodeIntrospection(true);
- return () => startLeakDetection(diagnostics, requestId);
- }
- : null,
-};
diff --git a/packages/lambda/src/functions/cancellation-polling.ts b/packages/lambda/src/functions/cancellation-polling.ts
index 1393141f8f..dfb02933ae 100644
--- a/packages/lambda/src/functions/cancellation-polling.ts
+++ b/packages/lambda/src/functions/cancellation-polling.ts
@@ -1,8 +1,4 @@
-import {
- LambdaClientInternals,
- type ProviderSpecifics,
- type AwsRegion,
-} from '@remotion/lambda-client';
+import {LambdaClientInternals, type AwsRegion} from '@remotion/lambda-client';
import {RenderInternals, type LogLevel} from '@remotion/renderer';
const isMissingCancellationSignalError = (err: unknown) => {
@@ -19,7 +15,6 @@ export const startCancellationPolling = ({
bucketName,
renderId,
region,
- providerSpecifics,
forcePathStyle,
intervalInMilliseconds,
logLevel,
@@ -28,7 +23,6 @@ export const startCancellationPolling = ({
bucketName: string;
renderId: string;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
intervalInMilliseconds: number;
logLevel: LogLevel;
@@ -39,7 +33,7 @@ export const startCancellationPolling = ({
const poll = async () => {
try {
- await providerSpecifics.headFile({
+ await LambdaClientInternals.lambdaHeadFileImplementation({
bucketName,
key: LambdaClientInternals.cancellationKey(renderId),
region,
diff --git a/packages/lambda/src/functions/cleanup-props.ts b/packages/lambda/src/functions/cleanup-props.ts
index f9f9bc8007..375a0865b7 100644
--- a/packages/lambda/src/functions/cleanup-props.ts
+++ b/packages/lambda/src/functions/cleanup-props.ts
@@ -1,36 +1,27 @@
-import type {
- ProviderSpecifics,
- SerializedInputProps,
-} from '@remotion/lambda-client';
+import type {SerializedInputProps} from '@remotion/lambda-client';
import {
cleanupSerializedInputProps,
cleanupSerializedResolvedProps,
} from './cleanup-serialized-input-props';
-import type {InsideFunctionSpecifics} from './provider-implementation';
+import {getCurrentRegionInFunction} from './helpers/get-current-region';
export const cleanupProps = ({
serializedResolvedProps,
inputProps,
- providerSpecifics,
forcePathStyle,
- insideFunctionSpecifics,
}: {
serializedResolvedProps: SerializedInputProps;
inputProps: SerializedInputProps;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}): Promise<[number, number]> => {
const cleanupSerializedInputPropsProm = cleanupSerializedInputProps({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: inputProps,
- providerSpecifics,
forcePathStyle,
});
const cleanupResolvedInputPropsProm = cleanupSerializedResolvedProps({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: serializedResolvedProps,
- providerSpecifics,
forcePathStyle,
});
diff --git a/packages/lambda/src/functions/cleanup-serialized-input-props.ts b/packages/lambda/src/functions/cleanup-serialized-input-props.ts
index 2d01acbe0a..1026e14773 100644
--- a/packages/lambda/src/functions/cleanup-serialized-input-props.ts
+++ b/packages/lambda/src/functions/cleanup-serialized-input-props.ts
@@ -1,6 +1,5 @@
import {
LambdaClientInternals,
- type ProviderSpecifics,
type SerializedInputProps,
type AwsRegion,
} from '@remotion/lambda-client';
@@ -8,12 +7,10 @@ import {
export const cleanupSerializedInputProps = async ({
serialized,
region,
- providerSpecifics,
forcePathStyle,
}: {
serialized: SerializedInputProps;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
}): Promise<number> => {
if (serialized.type === 'payload') {
@@ -21,7 +18,7 @@ export const cleanupSerializedInputProps = async ({
}
const time = Date.now();
- await providerSpecifics.deleteFile({
+ await LambdaClientInternals.lambdaDeleteFileImplementation({
bucketName: serialized.bucketName,
key: LambdaClientInternals.inputPropsKey(serialized.hash),
region,
@@ -36,12 +33,10 @@ export const cleanupSerializedInputProps = async ({
export const cleanupSerializedResolvedProps = async ({
serialized,
region,
- providerSpecifics,
forcePathStyle,
}: {
serialized: SerializedInputProps;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
}): Promise<number> => {
if (serialized.type === 'payload') {
@@ -49,7 +44,7 @@ export const cleanupSerializedResolvedProps = async ({
}
const time = Date.now();
- await providerSpecifics.deleteFile({
+ await LambdaClientInternals.lambdaDeleteFileImplementation({
bucketName: serialized.bucketName,
key: LambdaClientInternals.resolvedPropsKey(serialized.hash),
region,
diff --git a/packages/lambda/src/functions/concat-videos.ts b/packages/lambda/src/functions/concat-videos.ts
index 5c78591342..a609f01cdf 100644
--- a/packages/lambda/src/functions/concat-videos.ts
+++ b/packages/lambda/src/functions/concat-videos.ts
@@ -12,7 +12,7 @@ import type {
LogLevel,
} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
-import type {InsideFunctionSpecifics} from './provider-implementation';
+import {timer} from './helpers/timer';
export const concatVideos = async ({
onProgress,
@@ -29,7 +29,6 @@ export const concatVideos = async ({
cancelSignal,
preferLossless,
metadata,
- insideFunctionSpecifics,
everyNthFrame,
frameRange,
compositionDurationInFrames,
@@ -51,7 +50,6 @@ export const concatVideos = async ({
cancelSignal: CancelSignal | undefined;
preferLossless: boolean;
metadata: Record<string, string> | null;
- insideFunctionSpecifics: InsideFunctionSpecifics;
compositionDurationInFrames: number;
everyNthFrame: number;
frameRange: SingleFrameRange | null;
@@ -78,7 +76,7 @@ export const concatVideos = async ({
`audio.${RenderInternals.getExtensionOfFilename(separateAudioFilename)?.toLowerCase()}`,
);
const outfile = join(outputDirectory, `concat.${extension}`);
- const combine = insideFunctionSpecifics.timer('Combine chunks', logLevel);
+ const combine = timer('Combine chunks', logLevel);
const audioFiles = files.filter((f) => f.endsWith('audio'));
const videoFiles = files.filter((f) => f.endsWith('video'));
diff --git a/packages/lambda/src/functions/create-post-render-data.ts b/packages/lambda/src/functions/create-post-render-data.ts
index d7323339c3..5436fd663e 100644
--- a/packages/lambda/src/functions/create-post-render-data.ts
+++ b/packages/lambda/src/functions/create-post-render-data.ts
@@ -3,7 +3,6 @@ import {
type EnhancedErrorInfo,
type OverallRenderProgress,
type PostRenderData,
- type ProviderSpecifics,
type RenderMetadata,
type AwsRegion,
} from '@remotion/lambda-client';
@@ -20,7 +19,6 @@ export const createPostRenderData = ({
overallProgress,
timeToFinish,
outputSize,
- providerSpecifics,
}: {
region: AwsRegion;
memorySizeInMb: number;
@@ -32,7 +30,6 @@ export const createPostRenderData = ({
overallProgress: OverallRenderProgress;
timeToFinish: number;
outputSize: number;
- providerSpecifics: ProviderSpecifics;
}): PostRenderData => {
const parsedTimings = overallProgress.timings;
@@ -43,14 +40,15 @@ export const createPostRenderData = ({
elapsedTimeOfUnfinishedChunks: 0,
});
- const cost = providerSpecifics.estimatePrice({
+ const cost = LambdaClientInternals.estimatePrice({
durationInMilliseconds: estimatedBillingDurationInMilliseconds,
memorySizeInMb:
- providerSpecifics.parseFunctionName(renderMetadata.rendererFunctionName)
- ?.memorySizeInMb ?? memorySizeInMb,
+ LambdaClientInternals.parseFunctionName(
+ renderMetadata.rendererFunctionName,
+ )?.memorySizeInMb ?? memorySizeInMb,
region,
lambdasInvoked: renderMetadata.estimatedTotalLambdaInvokations,
- diskSizeInMb: providerSpecifics.getEphemeralStorageForPriceCalculation(),
+ diskSizeInMb: LambdaClientInternals.MAX_EPHEMERAL_STORAGE_IN_MB,
});
if (!outputFile) {
@@ -58,7 +56,7 @@ export const createPostRenderData = ({
}
const endTime = Date.now();
- const billingCurrency = providerSpecifics.getBillingCurrency(region);
+ const billingCurrency = LambdaClientInternals.getBillingCurrency(region);
if (
renderMetadata.type !== 'sequence' &&
diff --git a/packages/lambda/src/functions/find-output-file-in-bucket.ts b/packages/lambda/src/functions/find-output-file-in-bucket.ts
index 91fd06fbea..c6c477a26b 100644
--- a/packages/lambda/src/functions/find-output-file-in-bucket.ts
+++ b/packages/lambda/src/functions/find-output-file-in-bucket.ts
@@ -2,7 +2,6 @@ import {
LambdaClientInternals,
type CustomCredentials,
type OutputFileMetadata,
- type ProviderSpecifics,
type RenderMetadata,
type RenderOutput,
type AwsRegion,
@@ -17,7 +16,6 @@ type FindOutputFileInBucketInput = {
bucketName: string;
customCredentials: CustomCredentials | null;
currentRegion: AwsRegion;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
output: RenderOutput;
@@ -29,7 +27,6 @@ export const findOutputFileInBucket = ({
bucketName,
customCredentials,
currentRegion,
- providerSpecifics,
forcePathStyle,
requestHandler,
output,
@@ -44,7 +41,6 @@ export const findOutputFileInBucket = ({
bucketName,
customCredentials,
currentRegion,
- providerSpecifics,
forcePathStyle,
requestHandler,
output,
diff --git a/packages/lambda/src/functions/finish-render.ts b/packages/lambda/src/functions/finish-render.ts
index fb7147ab2a..7c051b5d43 100644
--- a/packages/lambda/src/functions/finish-render.ts
+++ b/packages/lambda/src/functions/finish-render.ts
@@ -5,7 +5,6 @@ import {
type CustomCredentials,
type PostRenderData,
type Privacy,
- type ProviderSpecifics,
type RenderMetadata,
type SerializedInputProps,
type WriteFileInput,
@@ -15,8 +14,10 @@ import type {LogLevel} from '@remotion/renderer';
import type {DownloadBehavior} from 'remotion/no-react';
import {cleanupProps} from './cleanup-props';
import {createPostRenderData} from './create-post-render-data';
+import {getCurrentMemorySizeInMb} from './helpers/get-current-memory-size';
+import {getCurrentRegionInFunction} from './helpers/get-current-region';
+import {timer} from './helpers/timer';
import type {OverallProgressHelper} from './overall-render-progress';
-import type {InsideFunctionSpecifics} from './provider-implementation';
type FinishRenderInput = {
expectedBucketOwner: string | null;
@@ -31,8 +32,6 @@ type FinishRenderInput = {
logLevel: LogLevel;
overallProgress: OverallProgressHelper;
startTime: number;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
forcePathStyle: boolean;
storageClass: StorageClass | null;
requestHandler: RequestHandler | null;
@@ -56,8 +55,6 @@ export const finishRender = async ({
logLevel,
overallProgress,
startTime,
- providerSpecifics,
- insideFunctionSpecifics,
forcePathStyle,
storageClass,
requestHandler,
@@ -84,7 +81,7 @@ export const finishRender = async ({
renderMetadata,
bucketName,
customCredentials: separateAudioCredentials,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
for (const file of [
...(separateAudioFile === null || separateAudioDestination === null
@@ -107,7 +104,7 @@ export const finishRender = async ({
},
]) {
const sizeInBytes = fs.statSync(file.file).size;
- const writeToBucket = insideFunctionSpecifics.timer(
+ const writeToBucket = timer(
`Writing to bucket (${sizeInBytes} bytes)`,
logLevel,
);
@@ -116,7 +113,7 @@ export const finishRender = async ({
bucketName: file.renderBucketName,
key: file.key,
body,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
privacy,
expectedBucketOwner,
downloadBehavior:
@@ -131,15 +128,11 @@ export const finishRender = async ({
};
try {
if (file.conditional) {
- if (providerSpecifics.writeFileIfNotExists === null) {
- throw new Error(
- 'The provider does not support conditional output uploads',
- );
- }
-
- await providerSpecifics.writeFileIfNotExists(writeOptions);
+ await LambdaClientInternals.lambdaWriteFileIfNotExistsImplementation(
+ writeOptions,
+ );
} else {
- await providerSpecifics.writeFile(writeOptions);
+ await LambdaClientInternals.lambdaWriteFileImplementation(writeOptions);
}
} finally {
body.destroy();
@@ -147,12 +140,12 @@ export const finishRender = async ({
writeToBucket.end();
if (file.output === 'separate-audio') {
- const {url} = providerSpecifics.getOutputUrl({
+ const {url} = LambdaClientInternals.getOutputUrlFromMetadata({
output: 'separate-audio',
bucketName,
renderMetadata,
customCredentials: file.customCredentials,
- currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ currentRegion: getCurrentRegionInFunction(),
});
// Persist the audio upload before publishing the main file so progress
// recovery cannot finish a render with a missing audio output.
@@ -172,22 +165,20 @@ export const finishRender = async ({
const cleanupProm = cleanupProps({
inputProps,
serializedResolvedProps,
- providerSpecifics,
forcePathStyle,
- insideFunctionSpecifics,
});
- const {url: outputUrl} = providerSpecifics.getOutputUrl({
+ const {url: outputUrl} = LambdaClientInternals.getOutputUrlFromMetadata({
output: 'main',
bucketName: renderBucketName,
- currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ currentRegion: getCurrentRegionInFunction(),
customCredentials,
renderMetadata,
});
const postRenderData = createPostRenderData({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- memorySizeInMb: insideFunctionSpecifics.getCurrentMemorySizeInMb(),
+ region: getCurrentRegionInFunction(),
+ memorySizeInMb: getCurrentMemorySizeInMb(),
renderMetadata,
errorExplanations,
timeToDelete: (await cleanupProm).reduce((a, b) => Math.max(a, b), 0),
@@ -200,7 +191,6 @@ export const finishRender = async ({
timeToCombine,
overallProgress: overallProgress.get(),
timeToFinish: Date.now() - startTime,
- providerSpecifics,
});
await overallProgress.setPostRenderData(postRenderData);
diff --git a/packages/lambda/src/functions/full-client-implementation.ts b/packages/lambda/src/functions/full-client-implementation.ts
deleted file mode 100644
index 4bff9be930..0000000000
--- a/packages/lambda/src/functions/full-client-implementation.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import {bundle} from '@remotion/bundler';
-import {createFunction} from '../api/create-function';
-import {uploadDir} from '../api/upload-dir';
-import {readDirectory} from '../shared/read-dir';
-import type {FullClientSpecifics} from './provider-implementation';
-
-export const awsFullClientSpecifics: FullClientSpecifics = {
- bundleSite: bundle,
- id: '__remotion_full_client_specifics',
- readDirectory,
- uploadDir,
- createFunction,
-};
diff --git a/packages/lambda/src/functions/get-browser-instance.ts b/packages/lambda/src/functions/get-browser-instance.ts
index 082fad6489..c38252e202 100644
--- a/packages/lambda/src/functions/get-browser-instance.ts
+++ b/packages/lambda/src/functions/get-browser-instance.ts
@@ -1,13 +1,8 @@
-import type {Await, ProviderSpecifics} from '@remotion/lambda-client';
+import type {Await} from '@remotion/lambda-client';
import type {ChromiumOptions, LogLevel, openBrowser} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
-import type {
- CloseBrowserInstance,
- ForgetBrowserEventLoop,
- GetBrowserInstance,
- InsideFunctionSpecifics,
-} from './provider-implementation';
+import {getChromiumPath} from './helpers/get-chromium-path';
export type LaunchedBrowser = {
instance: Await<ReturnType<typeof openBrowser>>;
@@ -49,9 +44,12 @@ const waitForLaunched = () => {
});
};
-export const forgetBrowserEventLoopImplementation: ForgetBrowserEventLoop = ({
+export const forgetBrowserEventLoop = ({
logLevel,
launchedBrowser,
+}: {
+ logLevel: LogLevel;
+ launchedBrowser: LaunchedBrowser;
}) => {
RenderInternals.Log.info(
{indent: false, logLevel},
@@ -61,8 +59,10 @@ export const forgetBrowserEventLoopImplementation: ForgetBrowserEventLoop = ({
launchedBrowser.instance.runner.deleteBrowserCaches();
};
-export const closeBrowserInstanceImplementation: CloseBrowserInstance = async ({
+export const closeBrowserInstance = async ({
launchedBrowser,
+}: {
+ launchedBrowser: LaunchedBrowser;
}) => {
if (_browserInstance === launchedBrowser) {
_browserInstance = null;
@@ -71,21 +71,20 @@ export const closeBrowserInstanceImplementation: CloseBrowserInstance = async ({
await launchedBrowser.instance.close({silent: true});
};
-export const getBrowserInstanceImplementation: GetBrowserInstance = async ({
+export const getBrowserInstance = async ({
logLevel,
indent,
chromiumOptions,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
logLevel: LogLevel;
indent: boolean;
chromiumOptions: ChromiumOptions;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}): Promise<LaunchedBrowser> => {
const actualChromiumOptions: ChromiumOptions = {
...chromiumOptions,
+ // The CLI can pass null; Lambda still needs software rendering.
+ gl: chromiumOptions.gl ?? 'swangle',
+ enableMultiProcessOnLinux: false,
darkMode: chromiumOptions.darkMode ?? false,
disableWebSecurity: chromiumOptions.disableWebSecurity ?? false,
headless: chromiumOptions.headless ?? true,
@@ -120,7 +119,7 @@ export const getBrowserInstanceImplementation: GetBrowserInstance = async ({
launching = true;
try {
- const execPath = providerSpecifics.getChromiumPath();
+ const execPath = getChromiumPath();
const instance = await RenderInternals.internalOpenBrowser({
browser: 'chrome',
@@ -150,7 +149,7 @@ export const getBrowserInstanceImplementation: GetBrowserInstance = async ({
{indent: false, logLevel},
'Browser disconnected or crashed.',
);
- insideFunctionSpecifics.forgetBrowserEventLoop({
+ forgetBrowserEventLoop({
logLevel,
launchedBrowser,
});
@@ -177,12 +176,10 @@ export const getBrowserInstanceImplementation: GetBrowserInstance = async ({
_browserInstance.instance.runner.rememberEventLoop();
await _browserInstance.instance.close({silent: true});
_browserInstance = null;
- return insideFunctionSpecifics.getBrowserInstance({
+ return getBrowserInstance({
logLevel,
indent,
chromiumOptions,
- providerSpecifics,
- insideFunctionSpecifics,
});
}
diff --git a/packages/lambda/src/functions/handlers/check-version-mismatch.ts b/packages/lambda/src/functions/handlers/check-version-mismatch.ts
index ca9c4f52ee..63b0b21105 100644
--- a/packages/lambda/src/functions/handlers/check-version-mismatch.ts
+++ b/packages/lambda/src/functions/handlers/check-version-mismatch.ts
@@ -3,15 +3,13 @@ import {
type ServerlessPayload,
} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
-import type {InsideFunctionSpecifics} from '../provider-implementation';
+import {getCurrentFunctionName} from '../helpers/get-current-function-name';
export const checkVersionMismatch = ({
params,
- insideFunctionSpecifics,
apiName,
}: {
params: ServerlessPayload;
- insideFunctionSpecifics: InsideFunctionSpecifics;
apiName: string;
}) => {
if (params.type === ServerlessRoutines.info) {
@@ -29,14 +27,14 @@ export const checkVersionMismatch = ({
if (params.version !== VERSION) {
if (!params.version) {
throw new Error(
- `Version mismatch: When calling ${apiName}, you called the function ${insideFunctionSpecifics.getCurrentFunctionName()} which has the version ${VERSION} but the @remotion/lambda package sent an incompatible payload: ${JSON.stringify(
+ `Version mismatch: When calling ${apiName}, you called the function ${getCurrentFunctionName()} which has the version ${VERSION} but the @remotion/lambda package sent an incompatible payload: ${JSON.stringify(
params,
)}. Expected it to contain {version: ${VERSION}}`,
);
}
throw new Error(
- `Version mismatch: When calling ${apiName}, you passed ${insideFunctionSpecifics.getCurrentFunctionName()} as the function, which has the version ${VERSION}, but the @remotion/lambda package you used to invoke the function has version ${params.version}. Deploy a new function and use it to call getRenderProgress(). See: https://www.remotion.dev/docs/lambda/upgrading`,
+ `Version mismatch: When calling ${apiName}, you passed ${getCurrentFunctionName()} as the function, which has the version ${VERSION}, but the @remotion/lambda package you used to invoke the function has version ${params.version}. Deploy a new function and use it to call getRenderProgress(). See: https://www.remotion.dev/docs/lambda/upgrading`,
);
}
};
diff --git a/packages/lambda/src/functions/handlers/compositions.ts b/packages/lambda/src/functions/handlers/compositions.ts
index 9fa68846c3..3beb9f84b7 100644
--- a/packages/lambda/src/functions/handlers/compositions.ts
+++ b/packages/lambda/src/functions/handlers/compositions.ts
@@ -1,12 +1,15 @@
import {
LambdaClientInternals,
ServerlessRoutines,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
import {RenderInternals} from '@remotion/renderer';
+import {
+ forgetBrowserEventLoop,
+ getBrowserInstance,
+} from '../get-browser-instance';
import type {LaunchedBrowser} from '../get-browser-instance';
-import type {InsideFunctionSpecifics} from '../provider-implementation';
+import {getCurrentRegionInFunction} from '../helpers/get-current-region';
import {checkVersionMismatch} from './check-version-mismatch';
type Options = {
@@ -16,13 +19,9 @@ type Options = {
export const compositionsHandler = async ({
params,
options,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
options: Options;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}) => {
if (params.type !== ServerlessRoutines.compositions) {
throw new TypeError('Expected info compositions');
@@ -30,21 +29,18 @@ export const compositionsHandler = async ({
checkVersionMismatch({
apiName: 'getCompositionsOnLambda()',
- insideFunctionSpecifics,
params,
});
let instance: LaunchedBrowser | undefined;
try {
- const region = insideFunctionSpecifics.getCurrentRegionInFunction();
+ const region = getCurrentRegionInFunction();
- const browserInstancePromise = insideFunctionSpecifics.getBrowserInstance({
+ const browserInstancePromise = getBrowserInstance({
logLevel: params.logLevel,
indent: false,
chromiumOptions: params.chromiumOptions,
- providerSpecifics,
- insideFunctionSpecifics,
});
const bucketName = await (params.bucketName
? Promise.resolve(params.bucketName)
@@ -52,7 +48,6 @@ export const compositionsHandler = async ({
region,
enableFolderExpiry: null,
customCredentials: null,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
skipPutAcl: false,
requestHandler: null,
@@ -63,15 +58,14 @@ export const compositionsHandler = async ({
await LambdaClientInternals.decompressInputProps({
bucketName,
expectedBucketOwner: options.expectedBucketOwner,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: params.inputProps,
propsType: 'input-props',
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
});
- const realServeUrl = providerSpecifics.convertToServeUrl({
+ const realServeUrl = LambdaClientInternals.convertToServeUrlImplementation({
urlOrId: params.serveUrl,
region,
bucketName,
@@ -108,7 +102,7 @@ export const compositionsHandler = async ({
});
} finally {
if (instance) {
- insideFunctionSpecifics.forgetBrowserEventLoop({
+ forgetBrowserEventLoop({
logLevel: params.logLevel,
launchedBrowser: instance,
});
diff --git a/packages/lambda/src/functions/handlers/launch.ts b/packages/lambda/src/functions/handlers/launch.ts
index 581e04f310..bfe38d6392 100644
--- a/packages/lambda/src/functions/handlers/launch.ts
+++ b/packages/lambda/src/functions/handlers/launch.ts
@@ -8,7 +8,6 @@ import {
type ImageSequenceManifest,
type ImageSequenceOutput,
type PostRenderData,
- type ProviderSpecifics,
type RenderMetadata,
type RendererOutput,
type ServerlessPayload,
@@ -27,12 +26,23 @@ import {cleanupProps} from '../cleanup-props';
import {createPostRenderData} from '../create-post-render-data';
import {findOutputFileInBucket} from '../find-output-file-in-bucket';
import {finishRender} from '../finish-render';
+import {
+ forgetBrowserEventLoop,
+ getBrowserInstance,
+} from '../get-browser-instance';
import type {LaunchedBrowser} from '../get-browser-instance';
+import {getCurrentFunctionName} from '../helpers/get-current-function-name';
+import {getCurrentMemorySizeInMb} from '../helpers/get-current-memory-size';
+import {getCurrentRegionInFunction} from '../helpers/get-current-region';
+import {getTmpDirStateIfENoSp} from '../helpers/get-tmp-dir';
+import {makeAwsArtifact} from '../helpers/make-aws-artifact';
+import {normalizeChromiumOptions} from '../helpers/normalize-chromium-options';
+import {timer} from '../helpers/timer';
+import {invokeWebhook} from '../invoke-webhook';
import {mergeChunksAndFinishRender} from '../merge-chunks';
import type {OverallProgressHelper} from '../overall-render-progress';
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 {renderWithSingleFunction} from '../render-with-single-function';
import {renderRendererFunctionWithRetry} from '../stream-renderer';
@@ -51,16 +61,12 @@ const innerLaunchHandler = async ({
options,
overallProgress,
registerCleanupTask,
- providerSpecifics,
- insideFunctionSpecifics,
onBrowser,
}: {
params: ServerlessPayload;
options: Options;
overallProgress: OverallProgressHelper;
registerCleanupTask: (cleanupTask: CleanupTask) => void;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
onBrowser: (browser: LaunchedBrowser) => void;
}): Promise<PostRenderData> => {
if (params.type !== ServerlessRoutines.launch) {
@@ -130,23 +136,21 @@ const innerLaunchHandler = async ({
codec: null,
audioCodecSetting: audioCodec,
separateAudioTo: null,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
}
const startedDate = Date.now();
- const chromiumParams = insideFunctionSpecifics.normalizeChromiumOptions?.({
+ const chromiumParams = normalizeChromiumOptions({
chromiumOptions: params.chromiumOptions ?? {},
logLevel: params.logLevel,
- }) ?? {...(params.chromiumOptions ?? {})};
+ });
- const browserInstance = insideFunctionSpecifics.getBrowserInstance({
+ const browserInstance = getBrowserInstance({
logLevel: params.logLevel,
indent: false,
chromiumOptions: chromiumParams,
- providerSpecifics,
- insideFunctionSpecifics,
});
browserInstance.then((b) => {
@@ -156,10 +160,9 @@ const innerLaunchHandler = async ({
const inputPropsPromise = LambdaClientInternals.decompressInputProps({
bucketName: params.bucketName,
expectedBucketOwner: options.expectedBucketOwner,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: params.inputProps,
propsType: 'input-props',
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
});
@@ -216,7 +219,6 @@ const innerLaunchHandler = async ({
onServeUrlVisited: () => {
overallProgress.setServeUrlOpened(Date.now());
},
- providerSpecifics,
offthreadVideoThreads: params.offthreadVideoThreads,
mediaCacheSizeInBytes: params.mediaCacheSizeInBytes,
});
@@ -355,7 +357,7 @@ const innerLaunchHandler = async ({
codec: params.codec,
audioCodecSetting: audioCodec,
separateAudioTo: separateAudioFilename?.toLowerCase() ?? null,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
LambdaClientInternals.validatePrivacy(params.privacy, true);
RenderInternals.validatePuppeteerTimeout(params.timeoutInMilliseconds);
@@ -390,17 +392,15 @@ const innerLaunchHandler = async ({
: LambdaClientInternals.getSizeInBytes(params.inputProps.payload),
LambdaClientInternals.getSizeInBytes(JSON.stringify(params.envVariables)),
],
- providerSpecifics,
});
const serializedResolvedProps =
await LambdaClientInternals.compressInputProps({
propsType: 'resolved-props',
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
stringifiedInputProps: serializedResolved,
userSpecifiedBucketName: params.bucketName,
needsToUpload,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
skipPutAcl: false,
requestHandler: null,
@@ -411,9 +411,7 @@ const innerLaunchHandler = async ({
return cleanupProps({
serializedResolvedProps,
inputProps: params.inputProps,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
- insideFunctionSpecifics,
});
});
@@ -491,8 +489,7 @@ const innerLaunchHandler = async ({
);
const rendererFunctionName =
- params.rendererFunctionName ??
- insideFunctionSpecifics.getCurrentFunctionName();
+ params.rendererFunctionName ?? getCurrentFunctionName();
const shouldRenderDirectly =
rendererOutput.type === 'media' &&
params.concurrency === 1 &&
@@ -506,18 +503,16 @@ const innerLaunchHandler = async ({
separateAudioTo === null
? null
: !params.overwrite &&
- providerSpecifics.supportsConditionalOutput({
+ LambdaClientInternals.supportsConditionalOutput({
customCredentials:
LambdaClientInternals.getCredentialsFromOutName(separateAudioTo),
- }) &&
- providerSpecifics.writeFileIfNotExists !== null,
+ }),
outputFileIsConditional:
!params.overwrite &&
- providerSpecifics.supportsConditionalOutput({
+ LambdaClientInternals.supportsConditionalOutput({
customCredentials:
LambdaClientInternals.getCredentialsFromOutName(outName),
- }) &&
- providerSpecifics.writeFileIfNotExists !== null,
+ }),
startedDate,
totalChunks: chunks.length,
estimatedTotalLambdaInvokations: [
@@ -547,8 +542,8 @@ const innerLaunchHandler = async ({
inputProps: params.inputProps,
lambdaVersion: VERSION,
framesPerLambda,
- memorySizeInMb: insideFunctionSpecifics.getCurrentMemorySizeInMb(),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ memorySizeInMb: getCurrentMemorySizeInMb(),
+ region: getCurrentRegionInFunction(),
renderId: params.renderId,
outName: removeOutnameCredentials(outName ?? undefined),
privacy: params.privacy,
@@ -560,14 +555,13 @@ const innerLaunchHandler = async ({
downloadBehavior: params.downloadBehavior,
audioBitrate: params.audioBitrate,
metadata: params.metadata,
- functionName: insideFunctionSpecifics.getCurrentFunctionName(),
+ functionName: getCurrentFunctionName(),
dimensions: {
width: comp.width * (params.scale ?? 1),
height: comp.height * (params.scale ?? 1),
},
rendererFunctionName:
- params.rendererFunctionName ??
- insideFunctionSpecifics.getCurrentFunctionName(),
+ params.rendererFunctionName ?? getCurrentFunctionName(),
scale: params.scale,
};
@@ -578,7 +572,7 @@ const innerLaunchHandler = async ({
bucketName: params.bucketName,
customCredentials:
LambdaClientInternals.getCredentialsFromOutName(outName),
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
const separateAudioDestination =
separateAudioTo === null
@@ -589,7 +583,7 @@ const innerLaunchHandler = async ({
bucketName: params.bucketName,
customCredentials:
LambdaClientInternals.getCredentialsFromOutName(separateAudioTo),
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
if (
separateAudioDestination !== null &&
@@ -604,17 +598,19 @@ const innerLaunchHandler = async ({
}
if (outputSequence !== null) {
- outputSequence.manifestUrl = providerSpecifics.getOutputUrl({
- output: 'main',
- bucketName: params.bucketName,
- currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
- customCredentials,
- renderMetadata,
- }).url;
+ outputSequence.manifestUrl = LambdaClientInternals.getOutputUrlFromMetadata(
+ {
+ output: 'main',
+ bucketName: params.bucketName,
+ currentRegion: getCurrentRegionInFunction(),
+ customCredentials,
+ renderMetadata,
+ },
+ ).url;
}
if (!params.overwrite) {
- const findOutputFile = insideFunctionSpecifics.timer(
+ const findOutputFile = timer(
'Checking if output file already exists',
params.logLevel,
);
@@ -641,9 +637,8 @@ const innerLaunchHandler = async ({
bucketName: params.bucketName,
customCredentials: destination.customCredentials,
renderMetadata,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
- providerSpecifics,
+ region: getCurrentRegionInFunction(),
+ currentRegion: getCurrentRegionInFunction(),
forcePathStyle: params.forcePathStyle,
requestHandler: null,
}).catch((err) => {
@@ -659,7 +654,7 @@ const innerLaunchHandler = async ({
});
if (output) {
throw new TypeError(
- `Output file "${destination.key}" in bucket "${destination.renderBucketName}" in region "${insideFunctionSpecifics.getCurrentRegionInFunction()}" already exists. Delete it before re-rendering, or set the 'overwrite' option in ${params.output.type === 'sequence' ? 'renderFramesOnLambda()' : 'renderMediaOnLambda()'} to overwrite it.`,
+ `Output file "${destination.key}" in bucket "${destination.renderBucketName}" in region "${getCurrentRegionInFunction()}" already exists. Delete it before re-rendering, or set the 'overwrite' option in ${params.output.type === 'sequence' ? 'renderFramesOnLambda()' : 'renderMediaOnLambda()'} to overwrite it.`,
);
}
}
@@ -687,10 +682,10 @@ const innerLaunchHandler = async ({
await Promise.all(
keys.slice(index, index + 25).map(async (frameKey) => {
try {
- await providerSpecifics.headFile({
+ await LambdaClientInternals.lambdaHeadFileImplementation({
bucketName: renderBucketName,
key: frameKey,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
customCredentials,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
@@ -713,15 +708,14 @@ const innerLaunchHandler = async ({
const write =
!params.overwrite &&
- providerSpecifics.supportsConditionalOutput({customCredentials}) &&
- providerSpecifics.writeFileIfNotExists !== null
- ? providerSpecifics.writeFileIfNotExists
- : providerSpecifics.writeFile;
+ LambdaClientInternals.supportsConditionalOutput({customCredentials})
+ ? LambdaClientInternals.lambdaWriteFileIfNotExistsImplementation
+ : LambdaClientInternals.lambdaWriteFileImplementation;
await write({
bucketName: renderBucketName,
key: reservationKey,
body: JSON.stringify({renderId: params.renderId}),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
privacy: params.privacy,
expectedBucketOwner: options.expectedBucketOwner,
downloadBehavior: null,
@@ -732,10 +726,10 @@ const innerLaunchHandler = async ({
});
overallProgress.setRenderMetadata(renderMetadata);
if (params.overwrite) {
- await providerSpecifics.deleteFile({
+ await LambdaClientInternals.lambdaDeleteFileImplementation({
bucketName: renderBucketName,
key,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
customCredentials,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
@@ -759,7 +753,7 @@ const innerLaunchHandler = async ({
return artifactRegistration;
}
- const region = insideFunctionSpecifics.getCurrentRegionInFunction();
+ const region = getCurrentRegionInFunction();
const storageKey = LambdaClientInternals.artifactName(
renderMetadata.renderId,
artifact.filename,
@@ -770,20 +764,19 @@ const innerLaunchHandler = async ({
{indent: false, logLevel: params.logLevel},
'Writing artifact ' + artifact.filename + ' to S3',
);
- const artifactUpload = providerSpecifics
- .writeFile({
- bucketName: renderBucketName,
- key: storageKey,
- body: artifact.content,
- region,
- privacy: params.privacy,
- expectedBucketOwner: options.expectedBucketOwner,
- downloadBehavior: artifact.downloadBehavior ?? params.downloadBehavior,
- customCredentials,
- forcePathStyle: params.forcePathStyle,
- storageClass: params.storageClass,
- requestHandler: null,
- })
+ const artifactUpload = LambdaClientInternals.lambdaWriteFileImplementation({
+ bucketName: renderBucketName,
+ key: storageKey,
+ body: artifact.content,
+ region,
+ privacy: params.privacy,
+ expectedBucketOwner: options.expectedBucketOwner,
+ downloadBehavior: artifact.downloadBehavior ?? params.downloadBehavior,
+ customCredentials,
+ forcePathStyle: params.forcePathStyle,
+ storageClass: params.storageClass,
+ requestHandler: null,
+ })
.then(() => {
RenderInternals.Log.info(
{indent: false, logLevel: params.logLevel},
@@ -791,7 +784,7 @@ const innerLaunchHandler = async ({
);
overallProgress.addReceivedArtifact(
- insideFunctionSpecifics.makeArtifactWithDetails({
+ makeAwsArtifact({
region,
renderBucketName,
storageKey,
@@ -843,8 +836,6 @@ const innerLaunchHandler = async ({
overallProgress,
logLevel: params.logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler: null,
expectedBucketOwner: options.expectedBucketOwner,
}),
@@ -878,11 +869,11 @@ const innerLaunchHandler = async ({
})),
};
const manifestBody = JSON.stringify(manifest);
- await providerSpecifics.writeFile({
+ await LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: renderBucketName,
key,
body: manifestBody,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
privacy: params.privacy,
expectedBucketOwner: options.expectedBucketOwner,
downloadBehavior: {type: 'play-in-browser'},
@@ -894,13 +885,11 @@ const innerLaunchHandler = async ({
const cleanup = await cleanupProps({
inputProps: params.inputProps,
serializedResolvedProps,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
- insideFunctionSpecifics,
});
postRenderData = createPostRenderData({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- memorySizeInMb: insideFunctionSpecifics.getCurrentMemorySizeInMb(),
+ region: getCurrentRegionInFunction(),
+ memorySizeInMb: getCurrentMemorySizeInMb(),
renderMetadata,
errorExplanations: LambdaClientInternals.inspectErrors({
errors: progress.errors,
@@ -916,19 +905,16 @@ const innerLaunchHandler = async ({
timeToFinish: Date.now() - startTime,
outputSize:
progress.uploadedSizeInBytes + Buffer.byteLength(manifestBody),
- providerSpecifics,
});
await overallProgress.setPostRenderData(postRenderData);
- await providerSpecifics
- .deleteFile({
- bucketName: renderBucketName,
- key: `${rendererOutput.keyPrefix}.remotion-render.json`,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- customCredentials,
- forcePathStyle: params.forcePathStyle,
- requestHandler: null,
- })
- .catch(() => undefined);
+ await LambdaClientInternals.lambdaDeleteFileImplementation({
+ bucketName: renderBucketName,
+ key: `${rendererOutput.keyPrefix}.remotion-render.json`,
+ region: getCurrentRegionInFunction(),
+ customCredentials,
+ forcePathStyle: params.forcePathStyle,
+ requestHandler: null,
+ }).catch(() => undefined);
} else if (shouldRenderDirectly) {
const directRender = await renderWithSingleFunction({
params: {...params, audioCodec},
@@ -939,8 +925,6 @@ const innerLaunchHandler = async ({
chromiumOptions: chromiumParams,
overallProgress,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
});
try {
postRenderData = await finishRender({
@@ -960,8 +944,6 @@ const innerLaunchHandler = async ({
logLevel: params.logLevel,
overallProgress,
startTime,
- providerSpecifics,
- insideFunctionSpecifics,
forcePathStyle: params.forcePathStyle,
storageClass: params.storageClass,
requestHandler: null,
@@ -999,8 +981,6 @@ const innerLaunchHandler = async ({
payload,
logLevel: params.logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler: null,
expectedBucketOwner: options.expectedBucketOwner,
});
@@ -1038,9 +1018,7 @@ const innerLaunchHandler = async ({
files: files.sort(),
overallProgress,
startTime,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
- insideFunctionSpecifics,
everyNthFrame: params.everyNthFrame,
frameRange: params.frameRange,
storageClass: params.storageClass,
@@ -1051,25 +1029,28 @@ const innerLaunchHandler = async ({
if (
!shouldRenderDirectly &&
- providerSpecifics.getRendererFunctionTransport(
- insideFunctionSpecifics.getCurrentRegionInFunction(),
+ LambdaClientInternals.getRendererFunctionTransport(
+ getCurrentRegionInFunction(),
) === 's3'
) {
try {
- const transportObjects = await providerSpecifics.listObjects({
- bucketName: params.bucketName,
- prefix: LambdaClientInternals.rendererTransportPrefix(params.renderId),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- expectedBucketOwner: options.expectedBucketOwner,
- forcePathStyle: params.forcePathStyle,
- requestHandler: null,
- });
+ const transportObjects =
+ await LambdaClientInternals.lambdaLsImplementation({
+ bucketName: params.bucketName,
+ prefix: LambdaClientInternals.rendererTransportPrefix(
+ params.renderId,
+ ),
+ region: getCurrentRegionInFunction(),
+ expectedBucketOwner: options.expectedBucketOwner,
+ forcePathStyle: params.forcePathStyle,
+ requestHandler: null,
+ });
await Promise.all(
transportObjects.map((object) =>
- providerSpecifics.deleteFile({
+ LambdaClientInternals.lambdaDeleteFileImplementation({
bucketName: params.bucketName,
key: object.Key,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
customCredentials: null,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
@@ -1093,13 +1074,9 @@ type CleanupTask = () => Promise<unknown>;
export const launchHandler = async ({
params,
options,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
options: Options;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}): Promise<void> => {
if (params.type !== ServerlessRoutines.launch) {
throw new Error('Expected launch type');
@@ -1146,9 +1123,8 @@ export const launchHandler = async ({
await LambdaClientInternals.writeCancellationSignal({
bucketName: params.bucketName,
renderId: params.renderId,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
expectedBucketOwner: options.expectedBucketOwner,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
});
@@ -1201,7 +1177,7 @@ export const launchHandler = async ({
}
try {
- await insideFunctionSpecifics.invokeWebhook({
+ await invokeWebhook({
options: {
url: params.webhook.url,
secret: params.webhook.secret,
@@ -1274,10 +1250,9 @@ export const launchHandler = async ({
renderId: params.renderId,
bucketName: params.bucketName,
expectedBucketOwner: options.expectedBucketOwner,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
timeoutTimestamp: options.getRemainingTimeInMillis() + Date.now(),
logLevel: params.logLevel,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
});
@@ -1287,8 +1262,6 @@ export const launchHandler = async ({
options,
overallProgress,
registerCleanupTask,
- providerSpecifics,
- insideFunctionSpecifics,
onBrowser: (browser) => {
instance = browser;
},
@@ -1308,7 +1281,7 @@ export const launchHandler = async ({
}
try {
- await insideFunctionSpecifics.invokeWebhook({
+ await invokeWebhook({
options: {
url: params.webhook.url,
secret: params.webhook.secret,
@@ -1380,10 +1353,7 @@ export const launchHandler = async ({
stack: (err as Error).stack as string,
type: 'stitcher',
isFatal: true,
- tmpDir:
- insideFunctionSpecifics.getTmpDirState?.(
- (err as Error).stack as string,
- ) ?? null,
+ tmpDir: getTmpDirStateIfENoSp((err as Error).stack as string),
attempt: 1,
totalAttempts: 1,
willRetry: false,
@@ -1401,7 +1371,7 @@ export const launchHandler = async ({
if (params.webhook && !webhookInvoked) {
try {
- await insideFunctionSpecifics.invokeWebhook({
+ await invokeWebhook({
options: {
url: params.webhook.url,
secret: params.webhook.secret,
@@ -1449,7 +1419,7 @@ export const launchHandler = async ({
}
} finally {
if (instance) {
- insideFunctionSpecifics.forgetBrowserEventLoop({
+ forgetBrowserEventLoop({
logLevel: params.logLevel,
launchedBrowser: instance,
});
diff --git a/packages/lambda/src/functions/handlers/progress.ts b/packages/lambda/src/functions/handlers/progress.ts
index cdbf87ac6e..7d840bf93c 100644
--- a/packages/lambda/src/functions/handlers/progress.ts
+++ b/packages/lambda/src/functions/handlers/progress.ts
@@ -2,18 +2,17 @@ import {
LambdaClientInternals,
ServerlessRoutines,
type GenericRenderProgress,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
-import type {InsideFunctionSpecifics} from '../provider-implementation';
+import {getCurrentFunctionName} from '../helpers/get-current-function-name';
+import {getCurrentMemorySizeInMb} from '../helpers/get-current-memory-size';
+import {getCurrentRegionInFunction} from '../helpers/get-current-region';
import {checkVersionMismatch} from './check-version-mismatch';
type Options = {
expectedBucketOwner: string | null;
timeoutInMilliseconds: number;
retriesRemaining: number;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
};
export const progressHandler = async ({
@@ -29,7 +28,6 @@ export const progressHandler = async ({
checkVersionMismatch({
apiName: 'getRenderProgress()',
- insideFunctionSpecifics: options.insideFunctionSpecifics,
params,
});
@@ -38,14 +36,12 @@ export const progressHandler = async ({
bucketName: params.bucketName,
renderId: params.renderId,
expectedBucketOwner: options.expectedBucketOwner,
- region: options.insideFunctionSpecifics.getCurrentRegionInFunction(),
- memorySizeInMb:
- options.insideFunctionSpecifics.getCurrentMemorySizeInMb(),
+ region: getCurrentRegionInFunction(),
+ memorySizeInMb: getCurrentMemorySizeInMb(),
timeoutInMilliseconds: options.timeoutInMilliseconds,
customCredentials: params.s3OutputProvider ?? null,
- providerSpecifics: options.providerSpecifics,
forcePathStyle: params.forcePathStyle,
- functionName: options.insideFunctionSpecifics.getCurrentFunctionName(),
+ functionName: getCurrentFunctionName(),
requestHandler: null,
});
return progress;
@@ -64,8 +60,6 @@ export const progressHandler = async ({
expectedBucketOwner: options.expectedBucketOwner,
timeoutInMilliseconds: options.timeoutInMilliseconds,
retriesRemaining: options.retriesRemaining - 1,
- providerSpecifics: options.providerSpecifics,
- insideFunctionSpecifics: options.insideFunctionSpecifics,
},
});
}
diff --git a/packages/lambda/src/functions/handlers/renderer.ts b/packages/lambda/src/functions/handlers/renderer.ts
index 0be7251475..657d713074 100644
--- a/packages/lambda/src/functions/handlers/renderer.ts
+++ b/packages/lambda/src/functions/handlers/renderer.ts
@@ -5,7 +5,6 @@ import {
ServerlessRoutines,
type ObjectChunkTimingData,
type OnStream,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
import type {
@@ -19,11 +18,24 @@ import {makeCancelSignal, RenderInternals} from '@remotion/renderer';
import {NoReactAPIs} from '@remotion/renderer/pure';
import {VERSION} from 'remotion/version';
import {startCancellationPolling} from '../cancellation-polling';
+import {
+ closeBrowserInstance,
+ forgetBrowserEventLoop,
+ getBrowserInstance,
+} from '../get-browser-instance';
import type {LaunchedBrowser} from '../get-browser-instance';
+import {getChromiumPath} from '../helpers/get-chromium-path';
+import {getCurrentRegionInFunction} from '../helpers/get-current-region';
+import {getTmpDirStateIfENoSp} from '../helpers/get-tmp-dir';
+import {startLeakDetection} from '../helpers/leak-detection';
+import {normalizeChromiumOptions} from '../helpers/normalize-chromium-options';
+import {timer} from '../helpers/timer';
+import {enableNodeIntrospection} from '../helpers/why-is-node-running';
import {onDownloadsHelper} from '../on-downloads-helpers';
-import type {InsideFunctionSpecifics} from '../provider-implementation';
import {renderImageSequenceChunk} from '../render-image-sequence-chunk';
+const ENABLE_SLOW_LEAK_DETECTION = false;
+
type Options = {
expectedBucketOwner: string | null;
isWarm: boolean;
@@ -40,8 +52,6 @@ const renderHandler = async ({
options,
logs,
onStream,
- providerSpecifics,
- insideFunctionSpecifics,
onBrowserInstance,
onMediaFiles,
cancelSignal,
@@ -50,8 +60,6 @@ const renderHandler = async ({
options: Options;
logs: BrowserLog[];
onStream: OnStream;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
onBrowserInstance: (browserInstance: LaunchedBrowser) => void;
onMediaFiles:
| ((options: {
@@ -67,11 +75,10 @@ const renderHandler = async ({
throw new Error('Params must be renderer');
}
- const chromiumOptions =
- insideFunctionSpecifics.normalizeChromiumOptions?.({
- chromiumOptions: params.chromiumOptions,
- logLevel: params.logLevel,
- }) ?? params.chromiumOptions;
+ const chromiumOptions = normalizeChromiumOptions({
+ chromiumOptions: params.chromiumOptions,
+ logLevel: params.logLevel,
+ });
if (params.launchFunctionConfig.version !== VERSION) {
throw new Error(
@@ -82,10 +89,9 @@ const renderHandler = async ({
const inputPropsPromise = LambdaClientInternals.decompressInputProps({
bucketName: params.bucketName,
expectedBucketOwner: options.expectedBucketOwner,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: params.inputProps,
propsType: 'input-props',
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
});
@@ -93,10 +99,9 @@ const renderHandler = async ({
const resolvedPropsPromise = LambdaClientInternals.decompressInputProps({
bucketName: params.bucketName,
expectedBucketOwner: options.expectedBucketOwner,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: params.resolvedProps,
propsType: 'resolved-props',
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
});
@@ -106,12 +111,10 @@ const renderHandler = async ({
`Waiting for browser instance`,
);
- const browserInstance = await insideFunctionSpecifics.getBrowserInstance({
+ const browserInstance = await getBrowserInstance({
logLevel: params.logLevel,
indent: false,
chromiumOptions,
- providerSpecifics,
- insideFunctionSpecifics,
});
onBrowserInstance(browserInstance);
@@ -127,8 +130,6 @@ const renderHandler = async ({
onStream,
logs,
cancelSignal,
- providerSpecifics,
- insideFunctionSpecifics,
});
return {};
}
@@ -359,7 +360,7 @@ const renderHandler = async ({
encodingMaxRate: params.encodingMaxRate,
audioCodec,
preferLossless: params.preferLossless,
- browserExecutable: providerSpecifics.getChromiumPath(),
+ browserExecutable: getChromiumPath(),
cancelSignal: cancelSignal ?? undefined,
disallowParallelEncoding: false,
disableSharedMemoryCapture: params.disableSharedMemoryCapture,
@@ -405,7 +406,7 @@ const renderHandler = async ({
.catch((err) => reject(err));
});
- const streamTimer = insideFunctionSpecifics.timer(
+ const streamTimer = timer(
'Streaming chunk to the main function',
params.logLevel,
);
@@ -420,10 +421,7 @@ const renderHandler = async ({
});
} else {
if (audioOutputLocation) {
- const audioChunkTimer = insideFunctionSpecifics.timer(
- 'Sending audio chunk',
- params.logLevel,
- );
+ const audioChunkTimer = timer('Sending audio chunk', params.logLevel);
await onStream({
type: 'audio-chunk-rendered',
payload: new Uint8Array(fs.readFileSync(audioOutputLocation)),
@@ -431,10 +429,7 @@ const renderHandler = async ({
audioChunkTimer.end();
}
- const videoChunkTimer = insideFunctionSpecifics.timer(
- 'Sending main chunk',
- params.logLevel,
- );
+ const videoChunkTimer = timer('Sending main chunk', params.logLevel);
await onStream({
type: NoReactAPIs.isAudioCodec(params.codec)
? 'audio-chunk-rendered'
@@ -480,9 +475,7 @@ export const rendererHandler = async ({
onStream,
options,
params,
- providerSpecifics,
requestContext,
- insideFunctionSpecifics,
onMediaFiles,
executionMode,
}: {
@@ -490,8 +483,6 @@ export const rendererHandler = async ({
options: Options;
onStream: OnStream;
requestContext: RequestContext;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
onMediaFiles:
| ((options: {
videoOutputLocation: string;
@@ -508,10 +499,9 @@ export const rendererHandler = async ({
const logs: BrowserLog[] = [];
- const finishRendererDiagnostics =
- insideFunctionSpecifics.startRendererDiagnostics?.(
- requestContext.requestId,
- ) ?? null;
+ const nodeIntrospection = ENABLE_SLOW_LEAK_DETECTION
+ ? enableNodeIntrospection(true)
+ : null;
let shouldKeepBrowserOpen = true;
let instance: LaunchedBrowser | undefined;
let cancellationRequested = false;
@@ -520,8 +510,7 @@ export const rendererHandler = async ({
? startCancellationPolling({
bucketName: params.bucketName,
renderId: params.renderId,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- providerSpecifics,
+ region: getCurrentRegionInFunction(),
forcePathStyle: params.forcePathStyle,
intervalInMilliseconds: 1000,
logLevel: params.logLevel,
@@ -538,8 +527,6 @@ export const rendererHandler = async ({
options,
logs,
onStream,
- providerSpecifics,
- insideFunctionSpecifics,
onBrowserInstance: (browserInstance) => {
instance = browserInstance;
},
@@ -555,7 +542,7 @@ export const rendererHandler = async ({
// If this error is encountered, we can just retry as it
// is a very rare error to occur
- const isRetryableError = providerSpecifics.isFlakyError(err as Error);
+ const isRetryableError = LambdaClientInternals.isFlakyError(err as Error);
if (isRetryableError) {
shouldKeepBrowserOpen = false;
}
@@ -588,10 +575,7 @@ export const rendererHandler = async ({
frame: null,
type: 'renderer',
isFatal: !shouldRetry,
- tmpDir:
- insideFunctionSpecifics.getTmpDirState?.(
- (err as Error).stack as string,
- ) ?? null,
+ tmpDir: getTmpDirStateIfENoSp((err as Error).stack as string),
attempt: params.attempt,
totalAttempts: params.retriesLeft + params.attempt,
willRetry: shouldRetry,
@@ -602,7 +586,7 @@ export const rendererHandler = async ({
stopCancellationPolling();
if (!shouldKeepBrowserOpen && instance) {
try {
- await insideFunctionSpecifics.closeBrowserInstance({
+ await closeBrowserInstance({
launchedBrowser: instance,
});
} catch (err) {
@@ -617,7 +601,7 @@ export const rendererHandler = async ({
shouldKeepBrowserOpen &&
instance
) {
- insideFunctionSpecifics.forgetBrowserEventLoop({
+ forgetBrowserEventLoop({
logLevel: params.logLevel,
launchedBrowser: instance,
});
@@ -630,6 +614,8 @@ export const rendererHandler = async ({
);
}
- finishRendererDiagnostics?.();
+ if (nodeIntrospection) {
+ startLeakDetection(nodeIntrospection, requestContext.requestId);
+ }
}
};
diff --git a/packages/lambda/src/functions/handlers/start.ts b/packages/lambda/src/functions/handlers/start.ts
index e4b9b90e3d..9c2e0a9661 100644
--- a/packages/lambda/src/functions/handlers/start.ts
+++ b/packages/lambda/src/functions/handlers/start.ts
@@ -1,11 +1,12 @@
import {
LambdaClientInternals,
ServerlessRoutines,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
+import {DEFAULT_X264_PRESET} from '../helpers/default-x264-preset';
+import {getCurrentFunctionName} from '../helpers/get-current-function-name';
+import {getCurrentRegionInFunction} from '../helpers/get-current-region';
import {makeInitialOverallRenderProgress} from '../overall-render-progress';
-import type {InsideFunctionSpecifics} from '../provider-implementation';
import {checkVersionMismatch} from './check-version-mismatch';
type Options = {
@@ -17,13 +18,9 @@ type Options = {
export const startHandler = async ({
params,
options,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
options: Options;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}) => {
if (params.type !== ServerlessRoutines.start) {
throw new TypeError('Expected type start');
@@ -34,34 +31,32 @@ export const startHandler = async ({
params.output?.type === 'sequence'
? 'renderFramesOnLambda()'
: 'renderMediaOnLambda()',
- insideFunctionSpecifics,
params,
});
- const region = insideFunctionSpecifics.getCurrentRegionInFunction();
+ const region = getCurrentRegionInFunction();
const bucketName =
params.bucketName ??
(
await LambdaClientInternals.internalGetOrCreateBucket({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
enableFolderExpiry: null,
customCredentials: null,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
skipPutAcl: false,
requestHandler: null,
logLevel: params.logLevel,
})
).bucketName;
- const realServeUrl = providerSpecifics.convertToServeUrl({
+ const realServeUrl = LambdaClientInternals.convertToServeUrlImplementation({
urlOrId: params.serveUrl,
region,
bucketName,
});
- providerSpecifics.validateDeleteAfter(params.deleteAfter);
+ LambdaClientInternals.validateDeleteAfter(params.deleteAfter);
- const initialFile = providerSpecifics.writeFile({
+ const initialFile = LambdaClientInternals.lambdaWriteFileImplementation({
bucketName,
downloadBehavior: null,
region,
@@ -99,9 +94,7 @@ export const startHandler = async ({
proResProfile: params.proResProfile ?? null,
x264Preset:
params.x264Preset ??
- (params.codec === 'h264'
- ? insideFunctionSpecifics.defaultX264Preset
- : null),
+ (params.codec === 'h264' ? DEFAULT_X264_PRESET : null),
gopSize: params.gopSize ?? null,
disableSharedMemoryCapture: params.disableSharedMemoryCapture,
jpegQuality: params.jpegQuality,
@@ -145,8 +138,8 @@ export const startHandler = async ({
sampleRate: params.sampleRate ?? 48000,
};
- await providerSpecifics.callFunctionAsync({
- functionName: insideFunctionSpecifics.getCurrentFunctionName(),
+ await LambdaClientInternals.callFunctionAsyncImplementation({
+ functionName: getCurrentFunctionName(),
type: ServerlessRoutines.launch,
payload,
region,
diff --git a/packages/lambda/src/functions/handlers/still.ts b/packages/lambda/src/functions/handlers/still.ts
index 05ebe8674b..51af7895dc 100644
--- a/packages/lambda/src/functions/handlers/still.ts
+++ b/packages/lambda/src/functions/handlers/still.ts
@@ -4,7 +4,6 @@ import {
LambdaClientInternals,
ServerlessRoutines,
type OnStream,
- type ProviderSpecifics,
type ReceivedArtifact,
type RenderMetadata,
type RenderStillFunctionResponsePayload,
@@ -15,9 +14,18 @@ import {RenderInternals} from '@remotion/renderer';
import {NoReactInternals} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
import {cleanupSerializedInputProps} from '../cleanup-serialized-input-props';
+import {
+ forgetBrowserEventLoop,
+ getBrowserInstance,
+} from '../get-browser-instance';
+import {getChromiumPath} from '../helpers/get-chromium-path';
+import {getCurrentFunctionName} from '../helpers/get-current-function-name';
+import {getCurrentMemorySizeInMb} from '../helpers/get-current-memory-size';
+import {getCurrentRegionInFunction} from '../helpers/get-current-region';
+import {getTmpDirStateIfENoSp} from '../helpers/get-tmp-dir';
+import {makeAwsArtifact} from '../helpers/make-aws-artifact';
import {onDownloadsHelper} from '../on-downloads-helpers';
import {makeInitialOverallRenderProgress} from '../overall-render-progress';
-import type {InsideFunctionSpecifics} from '../provider-implementation';
import {removeOutnameCredentials} from '../remove-outname-credentials';
import {validateComposition} from '../validate-composition';
import {checkVersionMismatch} from './check-version-mismatch';
@@ -29,8 +37,6 @@ type Options = {
expectedBucketOwner: string | null;
onStream: OnStream;
timeoutInMilliseconds: number;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
};
const innerStillHandler = async (
@@ -40,8 +46,6 @@ const innerStillHandler = async (
renderId,
onStream,
timeoutInMilliseconds,
- providerSpecifics,
- insideFunctionSpecifics,
}: Options,
cleanup: CleanupFn[],
) => {
@@ -51,7 +55,6 @@ const innerStillHandler = async (
checkVersionMismatch({
apiName: 'renderStillOnLambda()',
- insideFunctionSpecifics,
params,
});
@@ -62,22 +65,20 @@ const innerStillHandler = async (
codec: null,
audioCodecSetting: null,
separateAudioTo: null,
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
const start = Date.now();
- const browserInstancePromise = insideFunctionSpecifics.getBrowserInstance({
+ const browserInstancePromise = getBrowserInstance({
logLevel: params.logLevel,
indent: false,
chromiumOptions: params.chromiumOptions,
- providerSpecifics,
- insideFunctionSpecifics,
});
browserInstancePromise.then((instance) => {
cleanup.push(() => {
- insideFunctionSpecifics.forgetBrowserEventLoop({
+ forgetBrowserEventLoop({
logLevel:
params.type === ServerlessRoutines.still ? params.logLevel : 'error',
launchedBrowser: instance,
@@ -90,10 +91,9 @@ const innerStillHandler = async (
const bucketNamePromise =
params.bucketName ??
LambdaClientInternals.internalGetOrCreateBucket({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
enableFolderExpiry: null,
customCredentials: null,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
skipPutAcl: false,
requestHandler: null,
@@ -104,7 +104,7 @@ const innerStillHandler = async (
const outputPath = path.join(outputDir, 'output');
- const region = insideFunctionSpecifics.getCurrentRegionInFunction();
+ const region = getCurrentRegionInFunction();
const bucketName = await bucketNamePromise;
const serializedInputPropsWithCustomSchema =
await LambdaClientInternals.decompressInputProps({
@@ -113,12 +113,11 @@ const innerStillHandler = async (
region,
serialized: params.inputProps,
propsType: 'input-props',
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
requestHandler: null,
});
- const serveUrl = providerSpecifics.convertToServeUrl({
+ const serveUrl = LambdaClientInternals.convertToServeUrlImplementation({
urlOrId: params.serveUrl,
region,
bucketName,
@@ -168,7 +167,6 @@ const innerStillHandler = async (
throw new Error('Should not download a browser in Lambda');
},
onServeUrlVisited: () => undefined,
- providerSpecifics,
offthreadVideoThreads: params.offthreadVideoThreads,
mediaCacheSizeInBytes: params.mediaCacheSizeInBytes,
});
@@ -189,8 +187,8 @@ const innerStillHandler = async (
inputProps: params.inputProps,
lambdaVersion: VERSION,
framesPerLambda: 1,
- memorySizeInMb: insideFunctionSpecifics.getCurrentMemorySizeInMb(),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ memorySizeInMb: getCurrentMemorySizeInMb(),
+ region: getCurrentRegionInFunction(),
renderId,
outName: removeOutnameCredentials(params.outName ?? undefined),
privacy: params.privacy,
@@ -200,8 +198,8 @@ const innerStillHandler = async (
downloadBehavior: params.downloadBehavior,
audioBitrate: null,
metadata: null,
- functionName: insideFunctionSpecifics.getCurrentFunctionName(),
- rendererFunctionName: insideFunctionSpecifics.getCurrentFunctionName(),
+ functionName: getCurrentFunctionName(),
+ rendererFunctionName: getCurrentFunctionName(),
dimensions: {
height: composition.height * params.scale,
width: composition.width * params.scale,
@@ -212,11 +210,11 @@ const innerStillHandler = async (
const still = makeInitialOverallRenderProgress(timeoutInMilliseconds, false);
still.renderMetadata = renderMetadata;
- await providerSpecifics.writeFile({
+ await LambdaClientInternals.lambdaWriteFileImplementation({
bucketName,
key: LambdaClientInternals.overallProgressKey(renderId),
body: JSON.stringify(still),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
privacy: 'private',
expectedBucketOwner,
downloadBehavior: null,
@@ -240,7 +238,7 @@ const innerStillHandler = async (
customCredentials: LambdaClientInternals.getCredentialsFromOutName(
params.outName,
),
- bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ bucketNamePrefix: LambdaClientInternals.REMOTION_BUCKET_PREFIX,
});
const onArtifact = (artifact: EmittedArtifact): {alreadyExisted: boolean} => {
@@ -254,7 +252,7 @@ const innerStillHandler = async (
);
receivedArtifact.push(
- insideFunctionSpecifics.makeArtifactWithDetails({
+ makeAwsArtifact({
storageKey,
artifact,
region,
@@ -267,20 +265,19 @@ const innerStillHandler = async (
{indent: false, logLevel: params.logLevel},
'Writing artifact ' + artifact.filename + ' to S3',
);
- providerSpecifics
- .writeFile({
- bucketName: renderBucketName,
- key: storageKey,
- body: artifact.content,
- region,
- privacy: params.privacy,
- expectedBucketOwner,
- downloadBehavior: params.downloadBehavior,
- customCredentials,
- forcePathStyle: params.forcePathStyle,
- storageClass: params.storageClass,
- requestHandler: null,
- })
+ LambdaClientInternals.lambdaWriteFileImplementation({
+ bucketName: renderBucketName,
+ key: storageKey,
+ body: artifact.content,
+ region,
+ privacy: params.privacy,
+ expectedBucketOwner,
+ downloadBehavior: params.downloadBehavior,
+ customCredentials,
+ forcePathStyle: params.forcePathStyle,
+ storageClass: params.storageClass,
+ requestHandler: null,
+ })
.then(() => {
RenderInternals.Log.info(
{indent: false, logLevel: params.logLevel},
@@ -314,7 +311,7 @@ const innerStillHandler = async (
chromiumOptions: params.chromiumOptions,
scale: params.scale,
timeoutInMilliseconds: params.timeoutInMilliseconds,
- browserExecutable: providerSpecifics.getChromiumPath(),
+ browserExecutable: getChromiumPath(),
cancelSignal: null,
indent: false,
onBrowserLog: null,
@@ -342,13 +339,13 @@ const innerStillHandler = async (
const {size} = await fs.promises.stat(outputPath);
- await providerSpecifics.writeFile({
+ await LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: renderBucketName,
key,
privacy: params.privacy,
body: fs.createReadStream(outputPath),
expectedBucketOwner,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
downloadBehavior: params.downloadBehavior,
customCredentials,
forcePathStyle: params.forcePathStyle,
@@ -359,9 +356,8 @@ const innerStillHandler = async (
await Promise.all([
fs.promises.rm(outputPath, {recursive: true}),
cleanupSerializedInputProps({
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
serialized: params.inputProps,
- providerSpecifics,
forcePathStyle: params.forcePathStyle,
}),
server.closeServer(true),
@@ -374,20 +370,20 @@ const innerStillHandler = async (
}),
]);
- const estimatedPrice = providerSpecifics.estimatePrice({
+ const estimatedPrice = LambdaClientInternals.estimatePrice({
durationInMilliseconds: Date.now() - start + 100,
- memorySizeInMb: insideFunctionSpecifics.getCurrentMemorySizeInMb(),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ memorySizeInMb: getCurrentMemorySizeInMb(),
+ region: getCurrentRegionInFunction(),
lambdasInvoked: 1,
- diskSizeInMb: providerSpecifics.getEphemeralStorageForPriceCalculation(),
+ diskSizeInMb: LambdaClientInternals.MAX_EPHEMERAL_STORAGE_IN_MB,
});
- const {key: outKey, url} = providerSpecifics.getOutputUrl({
+ const {key: outKey, url} = LambdaClientInternals.getOutputUrlFromMetadata({
output: 'main',
renderMetadata,
bucketName,
customCredentials,
- currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ currentRegion: getCurrentRegionInFunction(),
});
const payload: RenderStillFunctionResponsePayload = {
@@ -398,9 +394,7 @@ const innerStillHandler = async (
bucketName,
estimatedPrice: LambdaClientInternals.formatCostsInfo(
estimatedPrice,
- providerSpecifics.getBillingCurrency(
- insideFunctionSpecifics.getCurrentRegionInFunction(),
- ),
+ LambdaClientInternals.getBillingCurrency(getCurrentRegionInFunction()),
),
renderId,
outKey,
@@ -443,7 +437,7 @@ export const stillHandler = async (
} catch (err) {
// If this error is encountered, we can just retry as it
// is a very rare error to occur
- const isBrowserError = options.providerSpecifics.isFlakyError(err as Error);
+ const isBrowserError = LambdaClientInternals.isFlakyError(err as Error);
const willRetry = isBrowserError || params.maxRetries > 0;
RenderInternals.Log.error(
@@ -470,10 +464,7 @@ export const stillHandler = async (
frame: params.frame,
type: 'renderer',
isFatal: false,
- tmpDir:
- options.insideFunctionSpecifics.getTmpDirState?.(
- (err as Error).stack as string,
- ) ?? null,
+ tmpDir: getTmpDirStateIfENoSp((err as Error).stack as string),
attempt: params.attempt,
totalAttempts: 1 + params.maxRetries,
willRetry,
diff --git a/packages/lambda/src/functions/helpers/clean-tmpdir.ts b/packages/lambda/src/functions/helpers/clean-tmpdir.ts
index c918b40425..cecb708816 100644
--- a/packages/lambda/src/functions/helpers/clean-tmpdir.ts
+++ b/packages/lambda/src/functions/helpers/clean-tmpdir.ts
@@ -1,5 +1,6 @@
import fs from 'node:fs';
import {join} from 'node:path';
+import {LambdaClientInternals} from '@remotion/lambda-client';
const deleteAllFilesInAFolderRecursively = (path: string) => {
const files = fs.readdirSync(path);
@@ -22,6 +23,11 @@ const deleteAllFilesInAFolderRecursively = (path: string) => {
}
};
+// Lambda's /tmp is per-function scratch space. Never wipe a developer's /tmp.
export const deleteTmpDir = () => {
+ if (!LambdaClientInternals.isInsideLambda()) {
+ return;
+ }
+
deleteAllFilesInAFolderRecursively('/tmp');
};
diff --git a/packages/lambda/src/functions/helpers/default-x264-preset.ts b/packages/lambda/src/functions/helpers/default-x264-preset.ts
new file mode 100644
index 0000000000..6b8580462f
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/default-x264-preset.ts
@@ -0,0 +1,5 @@
+import type {X264Preset} from '@remotion/renderer';
+import {NoReactInternals} from 'remotion/no-react';
+
+export const DEFAULT_X264_PRESET: X264Preset | null =
+ NoReactInternals.ENABLE_V5_BREAKING_CHANGES ? 'veryfast' : null;
diff --git a/packages/lambda/src/functions/helpers/get-chromium-path.ts b/packages/lambda/src/functions/helpers/get-chromium-path.ts
new file mode 100644
index 0000000000..98c0f75082
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/get-chromium-path.ts
@@ -0,0 +1,7 @@
+import {LambdaClientInternals} from '@remotion/lambda-client';
+
+// Inside the Lambda function, Chromium is provided by the Remotion layer.
+// Outside of it (tests, local simulation), let the renderer resolve a browser.
+export const getChromiumPath = (): string | null => {
+ return LambdaClientInternals.isInsideLambda() ? '/opt/bin/chromium' : null;
+};
diff --git a/packages/lambda/src/functions/helpers/get-current-function-name.ts b/packages/lambda/src/functions/helpers/get-current-function-name.ts
new file mode 100644
index 0000000000..f5d520012a
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/get-current-function-name.ts
@@ -0,0 +1,7 @@
+export const getCurrentFunctionName = () => {
+ if (!process.env.AWS_LAMBDA_FUNCTION_NAME) {
+ throw new Error('Expected AWS_LAMBDA_FUNCTION_NAME to be set');
+ }
+
+ return process.env.AWS_LAMBDA_FUNCTION_NAME;
+};
diff --git a/packages/lambda/src/functions/helpers/get-current-memory-size.ts b/packages/lambda/src/functions/helpers/get-current-memory-size.ts
new file mode 100644
index 0000000000..1180edcac1
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/get-current-memory-size.ts
@@ -0,0 +1,3 @@
+export const getCurrentMemorySizeInMb = () => {
+ return Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);
+};
diff --git a/packages/lambda/src/functions/helpers/get-current-region.ts b/packages/lambda/src/functions/helpers/get-current-region.ts
index e973cf34e1..f11114c4d9 100644
--- a/packages/lambda/src/functions/helpers/get-current-region.ts
+++ b/packages/lambda/src/functions/helpers/get-current-region.ts
@@ -1,6 +1,6 @@
import type {AwsRegion} from '@remotion/lambda-client';
-export const getCurrentRegionInFunctionImplementation = () => {
+export const getCurrentRegionInFunction = () => {
if (!process.env.AWS_REGION) {
throw new Error('Expected process.env.AWS_REGION to be defined');
}
diff --git a/packages/lambda/src/functions/helpers/make-aws-artifact.ts b/packages/lambda/src/functions/helpers/make-aws-artifact.ts
index 3a733c0a4f..55bec5f0e8 100644
--- a/packages/lambda/src/functions/helpers/make-aws-artifact.ts
+++ b/packages/lambda/src/functions/helpers/make-aws-artifact.ts
@@ -1,5 +1,5 @@
import {LambdaClientInternals} from '@remotion/lambda-client';
-import type {MakeArtifactWithDetails} from '../provider-implementation';
+import type {MakeArtifactWithDetails} from '../types';
export const makeAwsArtifact: MakeArtifactWithDetails = ({
region,
diff --git a/packages/lambda/src/functions/helpers/normalize-chromium-options.ts b/packages/lambda/src/functions/helpers/normalize-chromium-options.ts
new file mode 100644
index 0000000000..576de3d44c
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/normalize-chromium-options.ts
@@ -0,0 +1,20 @@
+import type {ChromiumOptions, LogLevel} from '@remotion/renderer';
+import {RenderInternals} from '@remotion/renderer';
+
+export const normalizeChromiumOptions = ({
+ chromiumOptions,
+ logLevel,
+}: {
+ chromiumOptions: ChromiumOptions;
+ logLevel: LogLevel;
+}): ChromiumOptions => {
+ if (chromiumOptions.gl !== 'angle') {
+ return chromiumOptions;
+ }
+
+ RenderInternals.Log.warn(
+ {indent: false, logLevel},
+ 'gl=angle is not supported in Lambda. Changing to gl=swangle instead.',
+ );
+ return {...chromiumOptions, gl: 'swangle'};
+};
diff --git a/packages/lambda/src/functions/helpers/set-lambda-env.ts b/packages/lambda/src/functions/helpers/set-lambda-env.ts
new file mode 100644
index 0000000000..d3dfa30869
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/set-lambda-env.ts
@@ -0,0 +1,19 @@
+import {EventEmitter} from 'node:events';
+
+if (
+ /^AWS_Lambda_nodejs(?:18|20|24)[.]x$/.test(
+ process.env.AWS_EXECUTION_ENV ?? '',
+ ) === true
+) {
+ process.env.FONTCONFIG_PATH = '/opt';
+ process.env.FONTCONFIG_FILE = '/opt/fonts.conf';
+
+ process.env.DISABLE_FROM_SURFACE = '1';
+ process.env.NO_COLOR = '1';
+
+ // @ts-expect-error
+ globalThis._dumpUnreleasedBuffers = new EventEmitter();
+
+ // @ts-expect-error
+ (globalThis._dumpUnreleasedBuffers as EventEmitter).setMaxListeners(201);
+}
diff --git a/packages/lambda/src/functions/helpers/timer.ts b/packages/lambda/src/functions/helpers/timer.ts
index f0628fc8b2..c0220f2150 100644
--- a/packages/lambda/src/functions/helpers/timer.ts
+++ b/packages/lambda/src/functions/helpers/timer.ts
@@ -1,6 +1,6 @@
import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
-import type {DebuggingTimer} from '../provider-implementation';
+import type {DebuggingTimer} from '../types';
const formatTime = (time: number) => {
return time + 'ms';
diff --git a/packages/lambda/src/functions/index.ts b/packages/lambda/src/functions/index.ts
index 07f6e258d9..b7b0d0abd4 100644
--- a/packages/lambda/src/functions/index.ts
+++ b/packages/lambda/src/functions/index.ts
@@ -1,10 +1,10 @@
+// Must run before any other module is evaluated.
+import './helpers/set-lambda-env';
import {
- LambdaClientInternals,
ServerlessRoutines,
type OrError,
type ServerlessPayload,
} from '@remotion/lambda-client';
-import {serverAwsImplementation} from './aws-server-implementation';
import {setCurrentRequestId, stopLeakDetection} from './helpers/leak-detection';
import {streamifyResponse} from './helpers/streamify-response';
import {innerHandler} from './inner-routine';
@@ -52,8 +52,6 @@ export const routine = async (
expectedBucketOwner,
getRemainingTimeInMillis: () => context.getRemainingTimeInMillis(),
},
- providerSpecifics: LambdaClientInternals.awsImplementation,
- insideFunctionSpecifics: serverAwsImplementation,
});
} catch (err) {
if (!buffered) {
diff --git a/packages/lambda/src/functions/inner-routine.ts b/packages/lambda/src/functions/inner-routine.ts
index 466472fe5b..d7a5b3c04d 100644
--- a/packages/lambda/src/functions/inner-routine.ts
+++ b/packages/lambda/src/functions/inner-routine.ts
@@ -2,7 +2,6 @@ import {
LambdaClientInternals,
ServerlessRoutines,
type OrError,
- type ProviderSpecifics,
type ServerlessPayload,
type StreamingPayload,
} from '@remotion/lambda-client';
@@ -14,10 +13,11 @@ import type {RequestContext} from './handlers/renderer';
import {rendererHandler} from './handlers/renderer';
import {startHandler} from './handlers/start';
import {stillHandler} from './handlers/still';
+import {deleteTmpDir} from './helpers/clean-tmpdir';
+import {getCurrentRegionInFunction} from './helpers/get-current-region';
import {infoHandler} from './info';
import {getWarm, setWarm} from './is-warm';
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';
@@ -25,14 +25,10 @@ export const innerHandler = async ({
params,
responseWriter,
context,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
responseWriter: ResponseStreamWriter;
context: RequestContext;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}): Promise<void> => {
const timeoutInMilliseconds = context.getRemainingTimeInMillis();
@@ -42,17 +38,17 @@ export const innerHandler = async ({
context.requestId,
);
- await insideFunctionSpecifics.deleteTmpDir();
+ await deleteTmpDir();
const isWarm = getWarm();
setWarm();
if (params.type === ServerlessRoutines.still) {
- providerSpecifics.validateDeleteAfter(params.deleteAfter);
- const renderId = insideFunctionSpecifics.generateRandomId({
+ LambdaClientInternals.validateDeleteAfter(params.deleteAfter);
+ const renderId = LambdaClientInternals.generateRandomHashWithLifeCycleRule({
deleteAfter: params.deleteAfter,
- randomHashFn: providerSpecifics.randomHash,
+ randomHashFn: LambdaClientInternals.randomHashImplementation,
});
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.still,
{
@@ -107,8 +103,6 @@ export const innerHandler = async ({
renderId,
onStream,
timeoutInMilliseconds,
- providerSpecifics,
- insideFunctionSpecifics,
})
.then((r) => {
if (!params.streamed && r.type === 'error') {
@@ -137,12 +131,13 @@ export const innerHandler = async ({
if (params.type === ServerlessRoutines.start) {
try {
- const renderId = insideFunctionSpecifics.generateRandomId({
- deleteAfter: params.deleteAfter,
- randomHashFn: providerSpecifics.randomHash,
- });
+ const renderId =
+ LambdaClientInternals.generateRandomHashWithLifeCycleRule({
+ deleteAfter: params.deleteAfter,
+ randomHashFn: LambdaClientInternals.randomHashImplementation,
+ });
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.start,
{
@@ -161,8 +156,6 @@ export const innerHandler = async ({
timeoutInMilliseconds,
renderId,
},
- providerSpecifics,
- insideFunctionSpecifics,
});
await responseWriter.write(
@@ -187,7 +180,7 @@ export const innerHandler = async ({
}
if (params.type === ServerlessRoutines.launch) {
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.launch,
{
@@ -206,8 +199,6 @@ export const innerHandler = async ({
getRemainingTimeInMillis: context.getRemainingTimeInMillis,
requestContext: context,
},
- providerSpecifics,
- insideFunctionSpecifics,
});
await responseWriter.write(new TextEncoder().encode(JSON.stringify({})));
@@ -216,7 +207,7 @@ export const innerHandler = async ({
}
if (params.type === ServerlessRoutines.status) {
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.status,
{
@@ -233,8 +224,6 @@ export const innerHandler = async ({
expectedBucketOwner: context.expectedBucketOwner,
timeoutInMilliseconds,
retriesRemaining: 2,
- providerSpecifics,
- insideFunctionSpecifics,
},
});
@@ -246,7 +235,7 @@ export const innerHandler = async ({
}
if (params.type === ServerlessRoutines.renderer) {
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.renderer,
{
@@ -262,15 +251,15 @@ export const innerHandler = async ({
);
}
- const region = insideFunctionSpecifics.getCurrentRegionInFunction();
- const transport = providerSpecifics.getRendererFunctionTransport(region);
+ const region = getCurrentRegionInFunction();
+ const transport =
+ LambdaClientInternals.getRendererFunctionTransport(region);
const s3Output =
transport === 's3'
? makeS3RendererOutput({
params,
expectedBucketOwner: context.expectedBucketOwner,
region,
- providerSpecifics,
})
: null;
await s3Output?.initialize();
@@ -305,8 +294,6 @@ export const innerHandler = async ({
onMediaFiles: s3Output?.uploadMediaAndComplete ?? null,
executionMode: 'invoked',
requestContext: context,
- providerSpecifics,
- insideFunctionSpecifics,
})
.then((res) => {
resolve(res);
@@ -322,7 +309,7 @@ export const innerHandler = async ({
}
if (params.type === ServerlessRoutines.info) {
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.info,
{
@@ -341,7 +328,7 @@ export const innerHandler = async ({
}
if (params.type === ServerlessRoutines.compositions) {
- if (providerSpecifics.printLoggingHelper) {
+ if (LambdaClientInternals.isInsideLambda()) {
printLoggingGrepHelper(
ServerlessRoutines.compositions,
{
@@ -356,8 +343,6 @@ export const innerHandler = async ({
options: {
expectedBucketOwner: context.expectedBucketOwner,
},
- providerSpecifics,
- insideFunctionSpecifics,
});
await responseWriter.write(
@@ -377,22 +362,16 @@ export const innerRoutine = async ({
params,
responseWriter,
context,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
responseWriter: ResponseStreamWriter;
context: RequestContext;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}): Promise<void> => {
try {
await innerHandler({
params,
responseWriter,
context,
- providerSpecifics,
- insideFunctionSpecifics,
});
} catch (err) {
const res: OrError<0> = {
diff --git a/packages/lambda/src/functions/invoke-webhook.ts b/packages/lambda/src/functions/invoke-webhook.ts
index 5faa742837..05e168d75d 100644
--- a/packages/lambda/src/functions/invoke-webhook.ts
+++ b/packages/lambda/src/functions/invoke-webhook.ts
@@ -1,9 +1,6 @@
import * as Crypto from 'node:crypto';
import {RenderInternals} from '@remotion/renderer';
-import type {
- InvokeWebhook,
- InvokeWebhookOptions,
-} from './provider-implementation';
+import type {InvokeWebhook, InvokeWebhookOptions} from './types';
export function calculateSignature(payload: string, secret: string | null) {
if (!secret) {
diff --git a/packages/lambda/src/functions/merge-chunks.ts b/packages/lambda/src/functions/merge-chunks.ts
index 398cd436bc..6fbdeddc87 100644
--- a/packages/lambda/src/functions/merge-chunks.ts
+++ b/packages/lambda/src/functions/merge-chunks.ts
@@ -5,7 +5,6 @@ import type {
CustomCredentials,
PostRenderData,
Privacy,
- ProviderSpecifics,
RenderMetadata,
SerializedInputProps,
ServerlessCodec,
@@ -22,7 +21,6 @@ import type {DownloadBehavior} from 'remotion/no-react';
import {concatVideos} from './concat-videos';
import {finishRender} from './finish-render';
import type {OverallProgressHelper} from './overall-render-progress';
-import type {InsideFunctionSpecifics} from './provider-implementation';
type MergeChunksAndFinishRenderInput = {
bucketName: string;
@@ -52,8 +50,6 @@ type MergeChunksAndFinishRenderInput = {
files: string[];
overallProgress: OverallProgressHelper;
startTime: number;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
forcePathStyle: boolean;
everyNthFrame: number;
frameRange: SingleFrameRange | null;
@@ -96,7 +92,6 @@ export const mergeChunksAndFinishRender = async (
cancelSignal: undefined,
preferLossless: options.preferLossless,
metadata: options.renderMetadata.metadata,
- insideFunctionSpecifics: options.insideFunctionSpecifics,
compositionDurationInFrames: options.numberOfFrames,
everyNthFrame: options.everyNthFrame,
frameRange: options.frameRange,
@@ -123,8 +118,6 @@ export const mergeChunksAndFinishRender = async (
logLevel: options.logLevel,
overallProgress: options.overallProgress,
startTime: options.startTime,
- providerSpecifics: options.providerSpecifics,
- insideFunctionSpecifics: options.insideFunctionSpecifics,
forcePathStyle: options.forcePathStyle,
storageClass: options.storageClass,
requestHandler: options.requestHandler,
diff --git a/packages/lambda/src/functions/overall-render-progress.ts b/packages/lambda/src/functions/overall-render-progress.ts
index f84bbfef6d..78cc55143b 100644
--- a/packages/lambda/src/functions/overall-render-progress.ts
+++ b/packages/lambda/src/functions/overall-render-progress.ts
@@ -4,7 +4,6 @@ import {
type FunctionErrorInfo,
type OverallRenderProgress,
type PostRenderData,
- type ProviderSpecifics,
type ReceivedArtifact,
type RenderMetadata,
type SeparateAudioOutput,
@@ -95,7 +94,6 @@ export const makeOverallRenderProgress = ({
region,
timeoutTimestamp,
logLevel,
- providerSpecifics,
forcePathStyle,
cancellationEnabled,
}: {
@@ -105,7 +103,6 @@ export const makeOverallRenderProgress = ({
region: AwsRegion;
timeoutTimestamp: number;
logLevel: LogLevel;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
cancellationEnabled: boolean;
}): OverallProgressHelper => {
@@ -134,7 +131,7 @@ export const makeOverallRenderProgress = ({
for (let attempt = 1; attempt <= progressUploadAttempts; attempt++) {
const start = Date.now();
try {
- await providerSpecifics.writeFile({
+ await LambdaClientInternals.lambdaWriteFileImplementation({
body,
bucketName,
customCredentials: null,
diff --git a/packages/lambda/src/functions/provider-implementation.ts b/packages/lambda/src/functions/provider-implementation.ts
deleted file mode 100644
index aa220a6849..0000000000
--- a/packages/lambda/src/functions/provider-implementation.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import type {BundlerInternals} from '@remotion/bundler';
-import type {
- DeleteAfter,
- FunctionErrorInfo,
- Privacy,
- ProviderSpecifics,
- ReceivedArtifact,
- WebhookPayload,
- AwsRegion,
- RequestHandler,
-} from '@remotion/lambda-client';
-import type {RuntimePreference} from '@remotion/lambda-client';
-import type {
- ChromiumOptions,
- EmittedArtifact,
- LogLevel,
- X264Preset,
-} from '@remotion/renderer';
-import type {LaunchedBrowser} from './get-browser-instance';
-
-export type MakeArtifactWithDetails = (params: {
- region: AwsRegion;
- renderBucketName: string;
- storageKey: string;
- artifact: EmittedArtifact;
-}) => ReceivedArtifact;
-
-export type DebuggingTimer = (
- label: string,
- logLevel: LogLevel,
-) => {
- end: () => void;
-};
-
-export type GetBrowserInstance = ({
- logLevel,
- indent,
- chromiumOptions,
- providerSpecifics,
- insideFunctionSpecifics,
-}: {
- logLevel: LogLevel;
- indent: boolean;
- chromiumOptions: ChromiumOptions;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
-}) => Promise<LaunchedBrowser>;
-
-export type ForgetBrowserEventLoop = (options: {
- logLevel: LogLevel;
- launchedBrowser: LaunchedBrowser;
-}) => void;
-
-export type CloseBrowserInstance = (options: {
- launchedBrowser: LaunchedBrowser;
-}) => Promise<void>;
-
-export type GenerateRenderId = (options: {
- deleteAfter: DeleteAfter | null;
- randomHashFn: () => string;
-}) => string;
-
-export type ReadDir = ({
- dir,
- etags,
- originalDir,
- onProgress,
-}: {
- dir: string;
- etags: {
- [key: string]: () => Promise<string>;
- };
- originalDir: string;
- onProgress: (bytes: number) => void;
-}) => {
- [key: string]: () => Promise<string>;
-};
-
-export type UploadDirProgress = {
- totalFiles: number;
- filesUploaded: number;
- totalSize: number;
- sizeUploaded: number;
-};
-
-export type UploadDir = (options: {
- bucket: string;
- region: AwsRegion;
- localDir: string;
- keyPrefix: string;
- onProgress: (progress: UploadDirProgress) => void;
- privacy: Privacy;
- toUpload: string[];
- forcePathStyle: boolean;
- requestHandler: RequestHandler | null;
-}) => Promise<void>;
-
-type CreateFunctionOptions = {
- region: AwsRegion;
- logLevel: LogLevel;
- ephemerealStorageInMb: number;
- timeoutInSeconds: number;
- memorySizeInMb: number;
- functionName: string;
- zipFile: string;
- requestHandler: RequestHandler | null;
- createCloudWatchLogGroup: boolean;
- accountId: string;
- alreadyCreated: boolean;
- retentionInDays: number;
- customRoleArn: string;
- customLayerArns: string[] | null;
- enableLambdaInsights: boolean;
- vpcSubnetIds: string;
- vpcSecurityGroupIds: string;
- runtimePreference: RuntimePreference;
-};
-
-export type CreateFunction = (
- options: CreateFunctionOptions,
-) => Promise<{FunctionName: string}>;
-
-export type InvokeWebhookOptions = {
- payload: WebhookPayload<string | null>;
- url: string;
- secret: string | null;
-};
-
-export type InvokeWebhookParams = {
- options: InvokeWebhookOptions;
- logLevel: LogLevel;
- retries?: number;
- errors?: number;
-};
-
-export type InvokeWebhook = (params: InvokeWebhookParams) => Promise<void>;
-
-export type InsideFunctionSpecifics = {
- defaultX264Preset: X264Preset | null;
- getBrowserInstance: GetBrowserInstance;
- forgetBrowserEventLoop: ForgetBrowserEventLoop;
- closeBrowserInstance: CloseBrowserInstance;
- timer: DebuggingTimer;
- generateRandomId: GenerateRenderId;
- deleteTmpDir: () => Promise<void>;
- getCurrentFunctionName: () => string;
- getCurrentMemorySizeInMb: () => number;
- invokeWebhook: InvokeWebhook;
- getCurrentRegionInFunction: () => AwsRegion;
- makeArtifactWithDetails: MakeArtifactWithDetails;
- normalizeChromiumOptions:
- | ((options: {
- chromiumOptions: ChromiumOptions;
- logLevel: LogLevel;
- }) => ChromiumOptions)
- | null;
- getTmpDirState: ((error: string) => FunctionErrorInfo['tmpDir']) | null;
- startRendererDiagnostics: ((requestId: string) => () => void) | null;
-};
-
-export type FullClientSpecifics = {
- id: '__remotion_full_client_specifics';
- bundleSite: typeof BundlerInternals.internalBundle;
- readDirectory: ReadDir;
- uploadDir: UploadDir;
- createFunction: CreateFunction;
-};
diff --git a/packages/lambda/src/functions/render-image-sequence-chunk.ts b/packages/lambda/src/functions/render-image-sequence-chunk.ts
index 4af30b57ea..b56a487a6f 100644
--- a/packages/lambda/src/functions/render-image-sequence-chunk.ts
+++ b/packages/lambda/src/functions/render-image-sequence-chunk.ts
@@ -2,7 +2,6 @@ import {
LambdaClientInternals,
ServerlessRoutines,
type OnStream,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
import type {
@@ -12,8 +11,8 @@ import type {
HeadlessBrowser,
} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
+import {getCurrentRegionInFunction} from './helpers/get-current-region';
import {onDownloadsHelper} from './on-downloads-helpers';
-import type {InsideFunctionSpecifics} from './provider-implementation';
export const renderImageSequenceChunk = async ({
params,
@@ -25,8 +24,6 @@ export const renderImageSequenceChunk = async ({
onStream,
logs,
cancelSignal,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
browser: HeadlessBrowser;
@@ -37,8 +34,6 @@ export const renderImageSequenceChunk = async ({
onStream: OnStream;
logs: BrowserLog[];
cancelSignal: CancelSignal | null;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}) => {
if (
params.type !== ServerlessRoutines.renderer ||
@@ -94,7 +89,7 @@ export const renderImageSequenceChunk = async ({
onStart: null,
onFrameUpdate: null,
onFrameBuffer: async (buffer, frame) => {
- await providerSpecifics.writeFile({
+ await LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: output.bucketName,
key: LambdaClientInternals.getImageSequenceFrameKey({...output, frame}),
body: new Uint8Array(
@@ -102,7 +97,7 @@ export const renderImageSequenceChunk = async ({
buffer.byteOffset,
buffer.byteLength,
),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ region: getCurrentRegionInFunction(),
privacy: params.privacy,
expectedBucketOwner,
downloadBehavior: output.downloadBehavior,
diff --git a/packages/lambda/src/functions/render-with-single-function.ts b/packages/lambda/src/functions/render-with-single-function.ts
index 8dcd4d3900..319a138b2d 100644
--- a/packages/lambda/src/functions/render-with-single-function.ts
+++ b/packages/lambda/src/functions/render-with-single-function.ts
@@ -2,7 +2,6 @@ import fs from 'node:fs';
import {join} from 'node:path';
import {
ServerlessRoutines,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
import {
@@ -19,9 +18,10 @@ import type {VideoConfig} from 'remotion/no-react';
import type {OnArtifactFromRenderer} from './artifact-registry';
import {startCancellationPolling} from './cancellation-polling';
import type {LaunchedBrowser} from './get-browser-instance';
+import {getChromiumPath} from './helpers/get-chromium-path';
+import {getCurrentRegionInFunction} from './helpers/get-current-region';
import {onDownloadsHelper} from './on-downloads-helpers';
import type {OverallProgressHelper} from './overall-render-progress';
-import type {InsideFunctionSpecifics} from './provider-implementation';
export const renderWithSingleFunction = async ({
params,
@@ -32,8 +32,6 @@ export const renderWithSingleFunction = async ({
chromiumOptions,
overallProgress,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
}: {
params: ServerlessPayload;
composition: VideoConfig;
@@ -43,8 +41,6 @@ export const renderWithSingleFunction = async ({
chromiumOptions: ChromiumOptions;
overallProgress: OverallProgressHelper;
onArtifact: OnArtifactFromRenderer;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
}): Promise<{
outputFile: string;
separateAudioFile: string | null;
@@ -85,8 +81,7 @@ export const renderWithSingleFunction = async ({
? startCancellationPolling({
bucketName: params.bucketName,
renderId: params.renderId,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- providerSpecifics,
+ region: getCurrentRegionInFunction(),
forcePathStyle: params.forcePathStyle,
intervalInMilliseconds: 1000,
logLevel: params.logLevel,
@@ -132,7 +127,7 @@ export const renderWithSingleFunction = async ({
encodingMaxRate: params.encodingMaxRate as Bitrate | null,
audioCodec: params.audioCodec,
preferLossless: params.preferLossless,
- browserExecutable: providerSpecifics.getChromiumPath(),
+ browserExecutable: getChromiumPath(),
cancelSignal: params.enableCancellation ? cancelSignal : undefined,
disallowParallelEncoding: false,
disableSharedMemoryCapture: params.disableSharedMemoryCapture,
diff --git a/packages/lambda/src/functions/s3-renderer-output.ts b/packages/lambda/src/functions/s3-renderer-output.ts
index c27d416769..956bac8544 100644
--- a/packages/lambda/src/functions/s3-renderer-output.ts
+++ b/packages/lambda/src/functions/s3-renderer-output.ts
@@ -3,7 +3,6 @@ import {
LambdaClientInternals,
ServerlessRoutines,
type OnStream,
- type ProviderSpecifics,
type S3RendererArtifactMetadata,
type S3RendererStatus,
type ServerlessPayload,
@@ -15,12 +14,10 @@ export const makeS3RendererOutput = ({
params,
expectedBucketOwner,
region,
- providerSpecifics,
}: {
params: ServerlessPayload;
expectedBucketOwner: string | null;
region: AwsRegion;
- providerSpecifics: ProviderSpecifics;
}) => {
if (params.type !== ServerlessRoutines.renderer) {
throw new Error('Expected renderer payload');
@@ -47,7 +44,7 @@ export const makeS3RendererOutput = ({
const writeStatus = (status: S3RendererStatus) => {
writeQueue = writeQueue.then(() =>
- providerSpecifics.writeFile({
+ LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: params.bucketName,
key: statusKey,
body: JSON.stringify(status),
@@ -122,7 +119,7 @@ export const makeS3RendererOutput = ({
downloadBehavior: artifact.downloadBehavior,
};
artifacts.push({key, metadata});
- const upload = providerSpecifics.writeFile({
+ const upload = LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: params.bucketName,
key,
body: artifact.content,
@@ -211,7 +208,7 @@ export const makeS3RendererOutput = ({
await Promise.all([
...artifactUploads,
videoKey
- ? providerSpecifics.writeFile({
+ ? LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: params.bucketName,
key: videoKey,
body: createReadStream(videoOutputLocation),
@@ -226,7 +223,7 @@ export const makeS3RendererOutput = ({
})
: null,
audioKey
- ? providerSpecifics.writeFile({
+ ? LambdaClientInternals.lambdaWriteFileImplementation({
bucketName: params.bucketName,
key: audioKey,
body: createReadStream(audioOutputLocation ?? videoOutputLocation),
diff --git a/packages/lambda/src/functions/stream-renderer.ts b/packages/lambda/src/functions/stream-renderer.ts
index 12f4a158a4..fc4013c3a8 100644
--- a/packages/lambda/src/functions/stream-renderer.ts
+++ b/packages/lambda/src/functions/stream-renderer.ts
@@ -6,15 +6,14 @@ import {
ServerlessRoutines,
type GetBinaryPayloadSink,
type OnMessage,
- type ProviderSpecifics,
type ServerlessPayload,
type RequestHandler,
} from '@remotion/lambda-client';
import type {EmittedArtifact, LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import type {OnArtifactFromRenderer} from './artifact-registry';
+import {getCurrentRegionInFunction} from './helpers/get-current-region';
import type {OverallProgressHelper} from './overall-render-progress';
-import type {InsideFunctionSpecifics} from './provider-implementation';
import {artifactFromS3} from './s3-renderer-output';
type StreamRendererResponse =
@@ -35,8 +34,6 @@ const streamRenderer = ({
files,
logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler,
}: {
payload: ServerlessPayload;
@@ -46,8 +43,6 @@ const streamRenderer = ({
files: string[];
logLevel: LogLevel;
onArtifact: OnArtifactFromRenderer;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
requestHandler: RequestHandler | null;
expectedBucketOwner: string | null;
}) => {
@@ -227,18 +222,17 @@ const streamRenderer = ({
throw new Error(`Unknown message type ${message.type}`);
};
- providerSpecifics
- .callFunctionStreaming({
- functionName,
- payload,
- retriesRemaining: 1,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- timeoutInTest: 12000,
- type: ServerlessRoutines.renderer,
- receivedStreamingPayload,
- requestHandler,
- getBinaryPayloadSink,
- })
+ LambdaClientInternals.callFunctionWithStreamingImplementation({
+ functionName,
+ payload,
+ retriesRemaining: 1,
+ region: getCurrentRegionInFunction(),
+ timeoutInTest: 12000,
+ type: ServerlessRoutines.renderer,
+ receivedStreamingPayload,
+ requestHandler,
+ getBinaryPayloadSink,
+ })
.then(() => {
if (payload.output.type === 'sequence' && !chunkCompleted) {
resolve({
@@ -314,8 +308,6 @@ const s3Renderer = async ({
files,
logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler,
expectedBucketOwner,
}: {
@@ -326,8 +318,6 @@ const s3Renderer = async ({
files: string[];
logLevel: LogLevel;
onArtifact: OnArtifactFromRenderer;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
requestHandler: RequestHandler | null;
expectedBucketOwner: string | null;
}): Promise<StreamRendererResponse> => {
@@ -335,9 +325,9 @@ const s3Renderer = async ({
throw new Error('Expected renderer type');
}
- const region = insideFunctionSpecifics.getCurrentRegionInFunction();
+ const region = getCurrentRegionInFunction();
try {
- await providerSpecifics.callFunctionAsync({
+ await LambdaClientInternals.callFunctionAsyncImplementation({
functionName,
payload,
region,
@@ -349,7 +339,7 @@ const s3Renderer = async ({
return {
type: 'error',
error: (err as Error).stack ?? (err as Error).message,
- shouldRetry: providerSpecifics.isFlakyError(err as Error),
+ shouldRetry: LambdaClientInternals.isFlakyError(err as Error),
};
}
@@ -366,14 +356,15 @@ const s3Renderer = async ({
while (Date.now() < timeoutTimestamp) {
try {
- const statusStream = await providerSpecifics.readFile({
- bucketName: payload.bucketName,
- key: statusKey,
- region,
- expectedBucketOwner,
- forcePathStyle: payload.forcePathStyle,
- requestHandler,
- });
+ const statusStream =
+ await LambdaClientInternals.lambdaReadFileImplementation({
+ bucketName: payload.bucketName,
+ key: statusKey,
+ region,
+ expectedBucketOwner,
+ forcePathStyle: payload.forcePathStyle,
+ requestHandler,
+ });
const status = LambdaClientInternals.parseS3RendererStatus({
value: JSON.parse(
await LambdaClientInternals.streamToString(statusStream),
@@ -415,16 +406,14 @@ const s3Renderer = async ({
index: payload.chunk,
rendered: 0,
});
- await providerSpecifics
- .deleteFile({
- bucketName: payload.bucketName,
- key: statusKey,
- region,
- customCredentials: null,
- forcePathStyle: payload.forcePathStyle,
- requestHandler,
- })
- .catch(() => undefined);
+ await LambdaClientInternals.lambdaDeleteFileImplementation({
+ bucketName: payload.bucketName,
+ key: statusKey,
+ region,
+ customCredentials: null,
+ forcePathStyle: payload.forcePathStyle,
+ requestHandler,
+ }).catch(() => undefined);
return {
type: 'error',
error: status.errorInfo.stack,
@@ -438,14 +427,15 @@ const s3Renderer = async ({
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,
- });
+ artifactStream =
+ await LambdaClientInternals.lambdaReadFileImplementation({
+ bucketName: payload.bucketName,
+ key: artifact.key,
+ region,
+ expectedBucketOwner,
+ forcePathStyle: payload.forcePathStyle,
+ requestHandler,
+ });
} catch (err) {
if (isMissingObjectError(err)) {
throw new Error(
@@ -480,7 +470,7 @@ const s3Renderer = async ({
);
let media;
try {
- media = await providerSpecifics.readFile({
+ media = await LambdaClientInternals.lambdaReadFileImplementation({
bucketName: payload.bucketName,
key,
region,
@@ -532,22 +522,20 @@ const s3Renderer = async ({
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,
- );
- });
+ await LambdaClientInternals.lambdaDeleteFileImplementation({
+ 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'};
@@ -555,7 +543,7 @@ const s3Renderer = async ({
} catch (err) {
if (
!isMissingObjectError(err) &&
- !providerSpecifics.isFlakyError(err as Error)
+ !LambdaClientInternals.isFlakyError(err as Error)
) {
return {
type: 'error',
@@ -571,7 +559,7 @@ const s3Renderer = async ({
return {
type: 'error',
- error: `Renderer chunk ${payload.chunk}, attempt ${payload.attempt} did not publish a status before the launcher deadline. Logs: ${providerSpecifics.getLoggingUrlForRendererFunction(
+ error: `Renderer chunk ${payload.chunk}, attempt ${payload.attempt} did not publish a status before the launcher deadline. Logs: ${LambdaClientInternals.getCloudwatchRendererUrl(
{
region,
functionName,
@@ -592,8 +580,6 @@ type RenderRendererFunctionWithRetryInput = {
files: string[];
logLevel: LogLevel;
onArtifact: OnArtifactFromRenderer;
- providerSpecifics: ProviderSpecifics;
- insideFunctionSpecifics: InsideFunctionSpecifics;
requestHandler: RequestHandler | null;
expectedBucketOwner: string | null;
};
@@ -606,8 +592,6 @@ export const renderRendererFunctionWithRetry = async ({
overallProgress,
logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler,
expectedBucketOwner,
}: RenderRendererFunctionWithRetryInput): Promise<unknown> => {
@@ -615,8 +599,8 @@ export const renderRendererFunctionWithRetry = async ({
throw new Error('Expected renderer type');
}
- const transport = providerSpecifics.getRendererFunctionTransport(
- insideFunctionSpecifics.getCurrentRegionInFunction(),
+ const transport = LambdaClientInternals.getRendererFunctionTransport(
+ getCurrentRegionInFunction(),
);
const result = await (transport === 's3' ? s3Renderer : streamRenderer)({
files,
@@ -626,8 +610,6 @@ export const renderRendererFunctionWithRetry = async ({
payload,
logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler,
expectedBucketOwner,
});
@@ -655,8 +637,6 @@ export const renderRendererFunctionWithRetry = async ({
},
logLevel,
onArtifact,
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler,
expectedBucketOwner,
});
diff --git a/packages/lambda/src/functions/types.ts b/packages/lambda/src/functions/types.ts
new file mode 100644
index 0000000000..18ff3bd59a
--- /dev/null
+++ b/packages/lambda/src/functions/types.ts
@@ -0,0 +1,98 @@
+import type {
+ AwsRegion,
+ Privacy,
+ ReceivedArtifact,
+ RequestHandler,
+ RuntimePreference,
+ WebhookPayload,
+} from '@remotion/lambda-client';
+import type {EmittedArtifact, LogLevel} from '@remotion/renderer';
+
+export type MakeArtifactWithDetails = (params: {
+ region: AwsRegion;
+ renderBucketName: string;
+ storageKey: string;
+ artifact: EmittedArtifact;
+}) => ReceivedArtifact;
+
+export type DebuggingTimer = (
+ label: string,
+ logLevel: LogLevel,
+) => {
+ end: () => void;
+};
+
+export type ReadDir = ({
+ dir,
+ etags,
+ originalDir,
+ onProgress,
+}: {
+ dir: string;
+ etags: {
+ [key: string]: () => Promise<string>;
+ };
+ originalDir: string;
+ onProgress: (bytes: number) => void;
+}) => {
+ [key: string]: () => Promise<string>;
+};
+
+export type UploadDirProgress = {
+ totalFiles: number;
+ filesUploaded: number;
+ totalSize: number;
+ sizeUploaded: number;
+};
+
+export type UploadDir = (options: {
+ bucket: string;
+ region: AwsRegion;
+ localDir: string;
+ keyPrefix: string;
+ onProgress: (progress: UploadDirProgress) => void;
+ privacy: Privacy;
+ toUpload: string[];
+ forcePathStyle: boolean;
+ requestHandler: RequestHandler | null;
+}) => Promise<void>;
+
+type CreateFunctionOptions = {
+ region: AwsRegion;
+ logLevel: LogLevel;
+ ephemerealStorageInMb: number;
+ timeoutInSeconds: number;
+ memorySizeInMb: number;
+ functionName: string;
+ zipFile: string;
+ requestHandler: RequestHandler | null;
+ createCloudWatchLogGroup: boolean;
+ accountId: string;
+ alreadyCreated: boolean;
+ retentionInDays: number;
+ customRoleArn: string;
+ customLayerArns: string[] | null;
+ enableLambdaInsights: boolean;
+ vpcSubnetIds: string;
+ vpcSecurityGroupIds: string;
+ runtimePreference: RuntimePreference;
+};
+
+export type CreateFunction = (
+ options: CreateFunctionOptions,
+) => Promise<{FunctionName: string}>;
+
+export type InvokeWebhookOptions = {
+ payload: WebhookPayload<string | null>;
+ url: string;
+ secret: string | null;
+};
+
+export type InvokeWebhookParams = {
+ options: InvokeWebhookOptions;
+ logLevel: LogLevel;
+ retries?: number;
+ errors?: number;
+};
+
+export type InvokeWebhook = (params: InvokeWebhookParams) => Promise<void>;
diff --git a/packages/lambda/src/functions/validate-composition.ts b/packages/lambda/src/functions/validate-composition.ts
index fd59c256d5..6985704b54 100644
--- a/packages/lambda/src/functions/validate-composition.ts
+++ b/packages/lambda/src/functions/validate-composition.ts
@@ -1,4 +1,4 @@
-import type {Await, ProviderSpecifics} from '@remotion/lambda-client';
+import type {Await} from '@remotion/lambda-client';
import type {
ChromiumOptions,
LogLevel,
@@ -9,6 +9,7 @@ import type {
import {RenderInternals} from '@remotion/renderer';
import type {VideoConfig} from 'remotion/no-react';
import {NoReactInternals} from 'remotion/no-react';
+import {getChromiumPath} from './helpers/get-chromium-path';
type ValidateCompositionOptions = {
serveUrl: string;
@@ -30,7 +31,6 @@ type ValidateCompositionOptions = {
offthreadVideoThreads: number | null;
onBrowserDownload: OnBrowserDownload;
onServeUrlVisited: () => void;
- providerSpecifics: ProviderSpecifics;
};
export const validateComposition = async ({
@@ -51,7 +51,6 @@ export const validateComposition = async ({
offthreadVideoCacheSizeInBytes,
onBrowserDownload,
onServeUrlVisited,
- providerSpecifics,
offthreadVideoThreads,
mediaCacheSizeInBytes,
}: ValidateCompositionOptions): Promise<VideoConfig> => {
@@ -63,7 +62,7 @@ export const validateComposition = async ({
timeoutInMilliseconds,
chromiumOptions,
port,
- browserExecutable: providerSpecifics.getChromiumPath(),
+ browserExecutable: getChromiumPath(),
serveUrl,
logLevel,
indent: false,
diff --git a/packages/lambda/src/internals.ts b/packages/lambda/src/internals.ts
index 1a44f4144b..090451eb60 100644
--- a/packages/lambda/src/internals.ts
+++ b/packages/lambda/src/internals.ts
@@ -1,8 +1,4 @@
-import type {
- AwsRegion,
- ProviderSpecifics,
- RuntimePreference,
-} from '@remotion/lambda-client';
+import type {AwsRegion, RuntimePreference} from '@remotion/lambda-client';
import type {LogLevel} from '@remotion/renderer';
import type {
DeploySiteOutput,
@@ -10,7 +6,6 @@ import type {
} from './api/deploy-site';
import {internalDeploySite} from './api/deploy-site';
import {executeCommand} from './cli/index';
-import type {FullClientSpecifics} from './functions/provider-implementation';
import {getLayers} from './shared/get-layers';
import type {AwsLayer} from './shared/hosted-layers';
@@ -19,8 +14,6 @@ export const LambdaInternals: {
args: string[],
remotionRoot: string,
logLevel: LogLevel,
- providerSpecifics: ProviderSpecifics | null,
- fullClientSpecifics: FullClientSpecifics | null,
) => Promise<void>;
internalDeploySite: (input: InternalDeploySiteInput) => DeploySiteOutput;
getLayers: (options: {
diff --git a/packages/lambda/src/shared/deploy-site-with-bundle.ts b/packages/lambda/src/shared/deploy-site-with-bundle.ts
index 0e7e910ecd..ce6101b4e1 100644
--- a/packages/lambda/src/shared/deploy-site-with-bundle.ts
+++ b/packages/lambda/src/shared/deploy-site-with-bundle.ts
@@ -1,17 +1,14 @@
import {
LambdaClientInternals,
type AwsRegion,
- type ProviderSpecifics,
type RequestHandler,
} from '@remotion/lambda-client';
import {
getSitesKey,
REMOTION_BUCKET_PREFIX,
} from '@remotion/lambda-client/constants';
-import type {
- FullClientSpecifics,
- UploadDirProgress,
-} from '../functions/provider-implementation';
+import {uploadDir} from '../api/upload-dir';
+import type {UploadDirProgress} from '../functions/types';
import {getS3DiffOperations} from './get-s3-operations';
import {validateSiteName} from './validate-site-name';
import {waitForPromisesToFinish} from './wait-for-promises-to-finish';
@@ -39,9 +36,7 @@ export type DeploySiteWithBundleInput = {
options: DeploySiteWithBundleOptions;
privacy: 'public' | 'no-acl';
throwIfSiteExists: boolean;
- providerSpecifics: ProviderSpecifics;
forcePathStyle: boolean;
- fullClientSpecifics: FullClientSpecifics;
requestHandler: RequestHandler | null;
getBundle: () => Promise<string>;
};
@@ -57,9 +52,7 @@ export const deploySiteWithBundle: (
options,
privacy,
throwIfSiteExists,
- providerSpecifics,
forcePathStyle,
- fullClientSpecifics,
requestHandler,
getBundle,
}) => {
@@ -75,22 +68,25 @@ export const deploySiteWithBundle: (
validateSiteName(siteName);
LambdaClientInternals.validatePrivacy(privacy, false);
- const accountId = await providerSpecifics.getAccountId({region});
-
- const bucketExists = await providerSpecifics.bucketExists({
- bucketName,
+ const accountId = await LambdaClientInternals.getAccountIdImplementation({
region,
- expectedBucketOwner: accountId,
- forcePathStyle,
- requestHandler,
});
+
+ const bucketExists =
+ await LambdaClientInternals.bucketExistsInRegionImplementation({
+ bucketName,
+ region,
+ expectedBucketOwner: accountId,
+ forcePathStyle,
+ requestHandler,
+ });
if (!bucketExists) {
throw new Error(`No bucket with the name ${bucketName} exists`);
}
const subFolder = getSitesKey(siteName);
- const filesPromise = providerSpecifics.listObjects({
+ const filesPromise = LambdaClientInternals.lambdaLsImplementation({
bucketName,
expectedBucketOwner: accountId,
region,
@@ -127,7 +123,6 @@ export const deploySiteWithBundle: (
totalBytes = bytes;
options.onDiffingProgress?.(bytes, false);
},
- fullClientSpecifics,
});
options.onDiffingProgress?.(totalBytes, true);
@@ -140,7 +135,7 @@ export const deploySiteWithBundle: (
return Promise.resolve();
}
- return fullClientSpecifics.uploadDir({
+ return uploadDir({
bucket: bucketName,
region,
localDir: bundleDir,
@@ -159,7 +154,7 @@ export const deploySiteWithBundle: (
const limit = LambdaClientInternals.pLimit(deleteConcurrency);
const deletePromises = toDelete.map((d) => {
return limit(() => {
- return providerSpecifics.deleteFile({
+ return LambdaClientInternals.lambdaDeleteFileImplementation({
bucketName,
customCredentials: null,
key: d.Key as string,
diff --git a/packages/lambda/src/shared/get-s3-operations.ts b/packages/lambda/src/shared/get-s3-operations.ts
index 588657a3cd..a63b130bc1 100644
--- a/packages/lambda/src/shared/get-s3-operations.ts
+++ b/packages/lambda/src/shared/get-s3-operations.ts
@@ -1,21 +1,19 @@
import type {_Object} from '@aws-sdk/client-s3';
-import type {FullClientSpecifics} from '../functions/provider-implementation';
+import {readDirectory} from './read-dir';
export const getS3DiffOperations = async ({
objects,
bundle,
prefix,
onProgress,
- fullClientSpecifics,
}: {
objects: _Object[];
bundle: string;
prefix: string;
onProgress: (bytes: number) => void;
- fullClientSpecifics: FullClientSpecifics;
}) => {
let totalBytes = 0;
- const dir = fullClientSpecifics.readDirectory({
+ const dir = readDirectory({
dir: bundle,
etags: {},
originalDir: bundle,
diff --git a/packages/lambda/src/shared/read-dir.ts b/packages/lambda/src/shared/read-dir.ts
index 3c09b7bb75..26833048d4 100644
--- a/packages/lambda/src/shared/read-dir.ts
+++ b/packages/lambda/src/shared/read-dir.ts
@@ -1,6 +1,6 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
-import type {ReadDir} from '../functions/provider-implementation';
+import type {ReadDir} from '../functions/types';
import {getEtagOfFile} from './get-etag';
// Function to recursively read a directory and return a list of files
diff --git a/packages/lambda/src/test/integration/cli-render-cancellation.test.ts b/packages/lambda/src/test/integration/cli-render-cancellation.test.ts
index 22dfa765b6..1daf5c1093 100644
--- a/packages/lambda/src/test/integration/cli-render-cancellation.test.ts
+++ b/packages/lambda/src/test/integration/cli-render-cancellation.test.ts
@@ -2,15 +2,14 @@ import {afterEach, beforeEach, expect, test} from 'bun:test';
import {Readable} from 'node:stream';
// eslint-disable-next-line no-restricted-imports
import {CliInternals} from '@remotion/cli';
-import {LambdaClientInternals} from '@remotion/lambda-client';
import {parsedLambdaCli} from '../../cli/args';
import {renderCommand} from '../../cli/commands/render/render';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {fakeAws, useFakeAws, type FakeAwsDefaults} from '../mocks/fake-aws';
import {doAfter, doBefore, getProcessWriteOutput} from './console-hooks';
+useFakeAws();
+
const enableCancellationOption = CliInternals.parsedCli['enable-cancellation'];
-const originalCallFunctionSync =
- LambdaClientInternals.awsImplementation.callFunctionSync;
const originalFunctionName = parsedLambdaCli['function-name'];
const originalRegion = parsedLambdaCli.region;
@@ -22,8 +21,6 @@ beforeEach(() => {
});
afterEach(() => {
- LambdaClientInternals.awsImplementation.callFunctionSync =
- originalCallFunctionSync;
CliInternals.parsedCli['enable-cancellation'] = enableCancellationOption;
parsedLambdaCli['function-name'] = originalFunctionName;
parsedLambdaCli.region = originalRegion;
@@ -38,7 +35,7 @@ test('Ctrl+C cancels an opted-in Lambda CLI render', async () => {
const pendingStatus = new Promise<never>(() => undefined);
const enableCancellationInPayloads: boolean[] = [];
- LambdaClientInternals.awsImplementation.callFunctionSync = ((input) => {
+ fakeAws().callFunctionSync.mockImplementation(((input) => {
if (input.type === 'start') {
enableCancellationInPayloads.push(
(input.payload as {enableCancellation: boolean}).enableCancellation,
@@ -54,25 +51,20 @@ test('Ctrl+C cancels an opted-in Lambda CLI render', async () => {
return Promise.reject(
new Error(`Unexpected Lambda routine: ${input.type}`),
);
- }) as typeof originalCallFunctionSync;
+ }) as FakeAwsDefaults['callFunctionSync']);
let cancellationWrites = 0;
- const providerSpecifics = {
- ...mockImplementation,
- readFile: ({key}: {key: string}) => {
- expect(key).toBe('renders/render-id/progress.json');
- return Promise.resolve(
- Readable.from([
- Buffer.from(JSON.stringify({cancellationEnabled: true})),
- ]),
- );
- },
- writeFile: (input: {key: string}) => {
- expect(input.key).toBe('renders/render-id/cancel.json');
- cancellationWrites++;
- return Promise.resolve();
- },
- } as typeof mockImplementation;
+ fakeAws().readFile.mockImplementation(({key}) => {
+ expect(key).toBe('renders/render-id/progress.json');
+ return Promise.resolve(
+ Readable.from([Buffer.from(JSON.stringify({cancellationEnabled: true}))]),
+ );
+ });
+ fakeAws().writeFile.mockImplementation((input) => {
+ expect(input.key).toBe('renders/render-id/cancel.json');
+ cancellationWrites++;
+ return Promise.resolve();
+ });
let resolveExit: (exitCode: number) => void = () => undefined;
const exitCode = new Promise<number>((resolve) => {
@@ -88,7 +80,6 @@ test('Ctrl+C cancels an opted-in Lambda CLI render', async () => {
args: ['https://example.com', 'composition-id'],
remotionRoot: process.cwd(),
logLevel: 'info',
- providerSpecifics,
}).catch(() => undefined);
try {
@@ -114,7 +105,7 @@ test('Ctrl+C leaves a Lambda CLI render running without the flag', async () => {
const pendingStatus = new Promise<never>(() => undefined);
const enableCancellationInPayloads: boolean[] = [];
- LambdaClientInternals.awsImplementation.callFunctionSync = ((input) => {
+ fakeAws().callFunctionSync.mockImplementation(((input) => {
if (input.type === 'start') {
enableCancellationInPayloads.push(
(input.payload as {enableCancellation: boolean}).enableCancellation,
@@ -130,16 +121,13 @@ test('Ctrl+C leaves a Lambda CLI render running without the flag', async () => {
return Promise.reject(
new Error(`Unexpected Lambda routine: ${input.type}`),
);
- }) as typeof originalCallFunctionSync;
+ }) as FakeAwsDefaults['callFunctionSync']);
let cancellationWrites = 0;
- const providerSpecifics = {
- ...mockImplementation,
- writeFile: () => {
- cancellationWrites++;
- return Promise.resolve();
- },
- } as typeof mockImplementation;
+ fakeAws().writeFile.mockImplementation(() => {
+ cancellationWrites++;
+ return Promise.resolve();
+ });
let resolveExit: (exitCode: number) => void = () => undefined;
const exitCode = new Promise<number>((resolve) => {
@@ -155,7 +143,6 @@ test('Ctrl+C leaves a Lambda CLI render running without the flag', async () => {
args: ['https://example.com', 'composition-id'],
remotionRoot: process.cwd(),
logLevel: 'info',
- providerSpecifics,
}).catch(() => undefined);
try {
diff --git a/packages/lambda/src/test/integration/cli-render-logs.test.ts b/packages/lambda/src/test/integration/cli-render-logs.test.ts
index eda6f1d985..e599460f82 100644
--- a/packages/lambda/src/test/integration/cli-render-logs.test.ts
+++ b/packages/lambda/src/test/integration/cli-render-logs.test.ts
@@ -7,12 +7,12 @@ import {
} from '@remotion/lambda-client';
import {parsedLambdaCli} from '../../cli/args';
import {renderCommand} from '../../cli/commands/render/render';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {fakeAws, useFakeAws, type FakeAwsDefaults} from '../mocks/fake-aws';
import {doAfter, doBefore, getProcessWriteOutput} from './console-hooks';
+useFakeAws();
+
const enableCancellationOption = CliInternals.parsedCli['enable-cancellation'];
-const originalCallFunctionSync =
- LambdaClientInternals.awsImplementation.callFunctionSync;
const originalFunctionName = parsedLambdaCli['function-name'];
const originalRegion = parsedLambdaCli.region;
const originalConcurrency = parsedLambdaCli.concurrency;
@@ -28,8 +28,6 @@ beforeEach(() => {
});
afterEach(() => {
- LambdaClientInternals.awsImplementation.callFunctionSync =
- originalCallFunctionSync;
CliInternals.parsedCli['enable-cancellation'] = enableCancellationOption;
parsedLambdaCli['function-name'] = originalFunctionName;
parsedLambdaCli.region = originalRegion;
@@ -45,7 +43,7 @@ test('Only shows the main CloudWatch logs for a direct single-function render',
});
const pendingStatus = new Promise<never>(() => undefined);
- LambdaClientInternals.awsImplementation.callFunctionSync = ((input) => {
+ fakeAws().callFunctionSync.mockImplementation(((input) => {
if (input.type === 'start') {
return Promise.resolve({bucketName: 'bucket', renderId: 'render-id'});
}
@@ -58,7 +56,7 @@ test('Only shows the main CloudWatch logs for a direct single-function render',
return Promise.reject(
new Error(`Unexpected Lambda routine: ${input.type}`),
);
- }) as typeof originalCallFunctionSync;
+ }) as FakeAwsDefaults['callFunctionSync']);
let resolveExit: (exitCode: number) => void = () => undefined;
const exitCode = new Promise<number>((resolve) => {
@@ -74,7 +72,6 @@ test('Only shows the main CloudWatch logs for a direct single-function render',
args: ['https://example.com', 'composition-id'],
remotionRoot: process.cwd(),
logLevel: 'verbose',
- providerSpecifics: mockImplementation,
}).catch(() => undefined);
try {
diff --git a/packages/lambda/src/test/integration/cli.test.ts b/packages/lambda/src/test/integration/cli.test.ts
index b549a25e36..989f8d6b7e 100644
--- a/packages/lambda/src/test/integration/cli.test.ts
+++ b/packages/lambda/src/test/integration/cli.test.ts
@@ -9,14 +9,15 @@ import {
} from '@remotion/lambda-client/constants';
import {parsedLambdaCli} from '../../cli/args';
import {LambdaInternals} from '../../internals';
-import {mockFullClientSpecifics} from '../mock-implementation';
+import {useFakeAws} from '../mocks/fake-aws';
import {
clearMockCreateFunctionCalls,
getMockCreateFunctionCalls,
} from '../mocks/mock-create-function';
-import {mockImplementation} from '../mocks/mock-implementation';
import {doAfter, doBefore, getProcessWriteOutput} from './console-hooks';
+useFakeAws();
+
const remotionRoot = process.cwd();
beforeEach(() => {
@@ -33,8 +34,6 @@ test('Deploy function', async () => {
['functions', 'deploy'],
remotionRoot,
'verbose',
- mockImplementation,
- mockFullClientSpecifics,
);
expect(getProcessWriteOutput()).toContain(
`Deployed as remotion-render-${LambdaClientInternals.LAMBDA_VERSION_STRING}-mem${DEFAULT_MEMORY_SIZE}mb-disk${DEFAULT_EPHEMERAL_STORAGE_IN_MB}mb-${DEFAULT_TIMEOUT}sec\n`,
@@ -46,15 +45,11 @@ test('Deploy function and list it', async () => {
['functions', 'deploy'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
await LambdaInternals.executeCommand(
['functions', 'ls'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
expect(getProcessWriteOutput()).toContain('Getting functions...');
expect(getProcessWriteOutput()).toContain('Memory (MB)');
@@ -66,15 +61,11 @@ test('Deploy function and it already exists should fail', async () => {
['functions', 'deploy'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
await LambdaInternals.executeCommand(
['functions', 'deploy'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
expect(getProcessWriteOutput()).toMatch(/Already exists as remotion-render/);
@@ -89,8 +80,6 @@ test('Deploy function with custom Layer ARNs', async () => {
['functions', 'deploy'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
expect(getMockCreateFunctionCalls().at(-1)?.customLayerArns).toEqual([
@@ -107,8 +96,6 @@ test('If no functions are there and is quiet, should return "()"', async () => {
['functions', 'ls'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
expect(getProcessWriteOutput()).toBe('()');
});
@@ -118,8 +105,6 @@ test('Should handle functions rm called with no functions', async () => {
['functions', 'rm', '()'],
remotionRoot,
'info',
- mockImplementation,
- mockFullClientSpecifics,
);
expect(getProcessWriteOutput()).toBe('No functions to remove.');
});
diff --git a/packages/lambda/src/test/integration/delete-site.test.ts b/packages/lambda/src/test/integration/delete-site.test.ts
index 40820e3965..a7e9e5c92a 100644
--- a/packages/lambda/src/test/integration/delete-site.test.ts
+++ b/packages/lambda/src/test/integration/delete-site.test.ts
@@ -2,13 +2,13 @@ import {expect, test} from 'bun:test';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {internalDeleteSite} from '../../api/delete-site';
import {internalDeploySite} from '../../api/deploy-site';
-import {mockFullClientSpecifics} from '../mock-implementation';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {useFakeAws} from '../mocks/fake-aws';
+
+useFakeAws();
test('Return 0 total size if site did not exist', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'eu-west-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: null,
forcePathStyle: false,
@@ -21,7 +21,6 @@ test('Return 0 total size if site did not exist', async () => {
bucketName,
region: 'eu-west-1',
siteName: 'non existent',
- providerSpecifics: mockImplementation,
forcePathStyle: false,
onAfterItemDeleted: null,
requestHandler: null,
@@ -31,7 +30,6 @@ test('Return 0 total size if site did not exist', async () => {
test('Return more than 0 total size if site did not exist', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'eu-west-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: null,
forcePathStyle: false,
@@ -44,15 +42,13 @@ test('Return more than 0 total size if site did not exist', async () => {
entryPoint: 'first',
region: 'eu-west-1',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
- siteName: mockImplementation.randomHash(),
+ siteName: LambdaClientInternals.randomHashImplementation(),
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
expect(
@@ -61,7 +57,6 @@ test('Return more than 0 total size if site did not exist', async () => {
bucketName,
region: 'eu-west-1',
siteName,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
onAfterItemDeleted: null,
requestHandler: null,
diff --git a/packages/lambda/src/test/integration/deploy-function.test.ts b/packages/lambda/src/test/integration/deploy-function.test.ts
index cc88e799f9..b64bc4d20a 100644
--- a/packages/lambda/src/test/integration/deploy-function.test.ts
+++ b/packages/lambda/src/test/integration/deploy-function.test.ts
@@ -6,7 +6,7 @@ import {
import {VERSION} from 'remotion/version';
import {internalDeployFunction} from '../../api/deploy-function';
import {lambdaInsightsExtensions} from '../../shared/lambda-insights-extensions';
-import {mockFullClientSpecifics} from '../mock-implementation';
+import {fakeAws, useFakeAws} from '../mocks/fake-aws';
import {
clearMockCreateFunctionCalls,
getMockCreateFunctionCalls,
@@ -15,7 +15,8 @@ import {
cleanFnStore,
markFunctionAsIncompatible,
} from '../mocks/mock-functions';
-import {mockImplementation} from '../mocks/mock-implementation';
+
+useFakeAws();
const {DEFAULT_EPHEMERAL_STORAGE_IN_MB} = LambdaClientInternals;
@@ -35,8 +36,6 @@ test('Should be able to deploy function', async () => {
enableLambdaInsights: true,
indent: false,
logLevel: 'info',
- providerSpecifics: mockImplementation,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default',
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -66,8 +65,6 @@ test('Should be able to get the function afterwards', async () => {
enableLambdaInsights: true,
indent: false,
logLevel: 'info',
- providerSpecifics: mockImplementation,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default',
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -81,7 +78,7 @@ test('Should be able to get the function afterwards', async () => {
diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,
}),
);
- const fns = await mockImplementation.getFunctions({
+ const fns = await LambdaClientInternals.getFunctions({
region: 'us-east-1',
compatibleOnly: true,
});
@@ -98,7 +95,7 @@ test('Should be able to get the function afterwards', async () => {
diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,
},
]);
- const foreignFunctions = await mockImplementation.getFunctions({
+ const foreignFunctions = await LambdaClientInternals.getFunctions({
region: 'us-east-2',
compatibleOnly: true,
});
@@ -119,8 +116,6 @@ test('Should be able to delete the function', async () => {
enableLambdaInsights: true,
indent: false,
logLevel: 'info',
- providerSpecifics: mockImplementation,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default',
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -134,7 +129,7 @@ test('Should be able to delete the function', async () => {
diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,
}),
);
- mockImplementation.deleteFunction({
+ LambdaClientInternals.deleteFunction({
region: 'us-east-1',
functionName: speculateFunctionName({
memorySizeInMb: 2048,
@@ -142,7 +137,7 @@ test('Should be able to delete the function', async () => {
diskSizeInMb: DEFAULT_EPHEMERAL_STORAGE_IN_MB,
}),
});
- const fns = await mockImplementation.getFunctions({
+ const fns = await LambdaClientInternals.getFunctions({
region: 'us-east-1',
compatibleOnly: true,
});
@@ -163,8 +158,6 @@ test('Should apply custom Layers when creating and reusing a function', async ()
enableLambdaInsights: false,
indent: false,
logLevel: 'info' as const,
- providerSpecifics: mockImplementation,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default' as const,
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -198,13 +191,10 @@ test('Should apply custom Layers when creating and reusing a function', async ()
test('Should validate custom Layers before calling the Provider', async () => {
let providerCalls = 0;
- const providerSpecifics = {
- ...mockImplementation,
- getAccountId: () => {
- providerCalls++;
- return Promise.resolve('123456789012');
- },
- };
+ fakeAws().getAccountId.mockImplementation(() => {
+ providerCalls++;
+ return Promise.resolve('123456789012');
+ });
const invalidInputs = [
{customLayerArns: [chromiumLayer.slice(0, -2)]},
{customLayerArns: [chromiumLayer.replace(':lambda:', ':s3:')]},
@@ -233,8 +223,6 @@ test('Should validate custom Layers before calling the Provider', async () => {
enableLambdaInsights: invalidInput.enableLambdaInsights ?? false,
indent: false,
logLevel: 'info',
- providerSpecifics,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: invalidInput.runtimePreference ?? 'default',
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -250,13 +238,10 @@ test('Should validate custom Layers before calling the Provider', async () => {
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');
- },
- };
+ fakeAws().getAccountId.mockImplementation(() => {
+ providerCalls++;
+ return Promise.resolve('123456789012');
+ });
const input = {
memorySizeInMb: 2048,
region,
@@ -267,8 +252,6 @@ test('AWS China requires partition-matching custom Layers before Provider calls'
enableLambdaInsights: true,
indent: false,
logLevel: 'info' as const,
- providerSpecifics,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default' as const,
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -322,8 +305,6 @@ test('Should pass null to the hosted Layer path by default', async () => {
enableLambdaInsights: false,
indent: false,
logLevel: 'info',
- providerSpecifics: mockImplementation,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default',
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -348,8 +329,6 @@ test('Should be able to get the function afterwards', async () => {
enableLambdaInsights: true,
indent: false,
logLevel: 'info',
- providerSpecifics: mockImplementation,
- fullClientSpecifics: mockFullClientSpecifics,
runtimePreference: 'default',
vpcSecurityGroupIds: undefined,
vpcSubnetIds: undefined,
@@ -363,7 +342,7 @@ test('Should be able to get the function afterwards', async () => {
diskSizeInMb: 10240,
}),
);
- const fns = await mockImplementation.getFunctions({
+ const fns = await LambdaClientInternals.getFunctions({
region: 'us-east-1',
compatibleOnly: true,
});
@@ -387,11 +366,11 @@ test('Should be able to get the function afterwards', async () => {
diskSizeInMb: 10240,
}),
);
- const compatibleFns = await mockImplementation.getFunctions({
+ const compatibleFns = await LambdaClientInternals.getFunctions({
region: 'us-east-1',
compatibleOnly: true,
});
- const incompatibleFns = await mockImplementation.getFunctions({
+ const incompatibleFns = await LambdaClientInternals.getFunctions({
region: 'us-east-1',
compatibleOnly: false,
});
diff --git a/packages/lambda/src/test/integration/deploy-site-from-bundle.test.ts b/packages/lambda/src/test/integration/deploy-site-from-bundle.test.ts
index 1f741e5ae4..ba75a70546 100644
--- a/packages/lambda/src/test/integration/deploy-site-from-bundle.test.ts
+++ b/packages/lambda/src/test/integration/deploy-site-from-bundle.test.ts
@@ -13,10 +13,11 @@ import path from 'node:path';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
import {internalDeploySiteFromBundle} from '../../api/deploy-site-from-bundle';
-import {mockFullClientSpecifics} from '../mock-implementation';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {fakeAws, fakeAwsDefaults, useFakeAws} from '../mocks/fake-aws';
import {resetMockStore} from '../mocks/mock-store';
+useFakeAws();
+
const temporaryDirectories: string[] = [];
const relocatableIndexHtml = `<!DOCTYPE html>
@@ -47,7 +48,6 @@ const makeBundle = (files: Record<string, string>) => {
const makeBucket = async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -59,12 +59,11 @@ const makeBucket = async () => {
return bucketName;
};
-const withStaleEtags: typeof mockImplementation = {
- ...mockImplementation,
- listObjects: async (input) => {
- const objects = await mockImplementation.listObjects(input);
+const withStaleEtags = () => {
+ fakeAws().listObjects.mockImplementation(async (input) => {
+ const objects = await fakeAwsDefaults.listObjects(input);
return objects.map((object) => ({...object, ETag: 'stale-etag'}));
- },
+ });
};
const deployBundle = ({
@@ -72,29 +71,23 @@ const deployBundle = ({
bundleDir,
siteName,
throwIfSiteExists = false,
- providerSpecifics = mockImplementation,
- fullClientSpecifics = mockFullClientSpecifics,
}: {
bucketName: string;
bundleDir: string;
siteName: string;
throwIfSiteExists?: boolean;
- providerSpecifics?: typeof mockImplementation;
- fullClientSpecifics?: typeof mockFullClientSpecifics;
}) => {
return internalDeploySiteFromBundle({
bucketName,
bundleDir,
region: 'ap-northeast-1',
siteName,
- providerSpecifics,
indent: false,
logLevel: 'error',
options: {},
privacy: 'public',
throwIfSiteExists,
forcePathStyle: false,
- fullClientSpecifics,
requestHandler: null,
});
};
@@ -115,18 +108,14 @@ test('deploys a caller-owned bundle without invoking the bundler', async () => {
const bundleBefore = readFileSync(path.join(bundleDir, 'index.html'));
const bucketName = await makeBucket();
- const fullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: () => {
- throw new Error('The bundler must not be called');
- },
- };
+ fakeAws().bundleSite.mockImplementation(() => {
+ throw new Error('The bundler must not be called');
+ });
const result = await deployBundle({
bucketName,
bundleDir,
siteName: 'from-bundle-basic',
- fullClientSpecifics,
});
expect(result).toEqual({
@@ -144,7 +133,7 @@ test('deploys a caller-owned bundle without invoking the bundler', async () => {
bundleBefore,
);
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
expectedBucketOwner: null,
prefix: 'sites/from-bundle-basic/',
@@ -190,7 +179,7 @@ test('incrementally uploads and deletes files without deleting either bundle', a
expect(existsSync(firstBundle)).toBe(true);
expect(existsSync(secondBundle)).toBe(true);
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
expectedBucketOwner: null,
prefix: 'sites/from-bundle-incremental/',
@@ -223,31 +212,22 @@ test('publishes assets and index.html before deleting stale files', async () =>
});
const operations: string[] = [];
- const providerSpecifics: typeof mockImplementation = {
- ...withStaleEtags,
- deleteFile: async (input) => {
- operations.push('delete');
- await mockImplementation.deleteFile(input);
- },
- };
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- uploadDir: async (input) => {
- operations.push(
- input.toUpload.includes('index.html')
- ? 'upload-index'
- : 'upload-assets',
- );
- await mockFullClientSpecifics.uploadDir(input);
- },
- };
+ withStaleEtags();
+ fakeAws().deleteFile.mockImplementation(async (input) => {
+ operations.push('delete');
+ await fakeAwsDefaults.deleteFile(input);
+ });
+ fakeAws().uploadDir.mockImplementation(async (input) => {
+ operations.push(
+ input.toUpload.includes('index.html') ? 'upload-index' : 'upload-assets',
+ );
+ await fakeAwsDefaults.uploadDir(input);
+ });
await deployBundle({
bucketName,
bundleDir: secondBundle,
siteName: 'from-bundle-ordering',
- providerSpecifics,
- fullClientSpecifics,
});
expect(operations).toEqual(['upload-assets', 'upload-index', 'delete']);
@@ -270,33 +250,23 @@ test('does not publish index.html or delete stale files if an asset upload fails
});
const operations: string[] = [];
- const providerSpecifics: typeof mockImplementation = {
- ...withStaleEtags,
- deleteFile: async () => {
- operations.push('delete');
- },
- };
- const fullClientSpecifics = {
- ...mockFullClientSpecifics,
- uploadDir: (
- input: Parameters<typeof mockFullClientSpecifics.uploadDir>[0],
- ) => {
- operations.push(
- input.toUpload.includes('index.html')
- ? 'upload-index'
- : 'upload-assets',
- );
- return Promise.reject(new Error('Upload failed'));
- },
- };
+ withStaleEtags();
+ fakeAws().deleteFile.mockImplementation(() => {
+ operations.push('delete');
+ return Promise.resolve();
+ });
+ fakeAws().uploadDir.mockImplementation((input) => {
+ operations.push(
+ input.toUpload.includes('index.html') ? 'upload-index' : 'upload-assets',
+ );
+ return Promise.reject(new Error('Upload failed'));
+ });
await expect(
deployBundle({
bucketName,
bundleDir: secondBundle,
siteName: 'from-bundle-failure',
- providerSpecifics,
- fullClientSpecifics,
}),
).rejects.toThrow('Upload failed');
expect(operations).toEqual(['upload-assets']);
@@ -308,35 +278,28 @@ test('deletes at most 10 stale files concurrently', async () => {
const bucketName = await makeBucket();
let activeDeletes = 0;
let maxActiveDeletes = 0;
- const providerSpecifics: typeof mockImplementation = {
- ...mockImplementation,
- listObjects: () => {
- return Promise.resolve(
- Array.from({length: 25}, (_, index) => ({
- Key: `sites/from-bundle-concurrency/stale-${index}.js`,
- ETag: 'etag',
- LastModified: new Date(0),
- Size: 0,
- })),
- );
- },
- deleteFile: async () => {
- activeDeletes++;
- maxActiveDeletes = Math.max(maxActiveDeletes, activeDeletes);
- await new Promise((resolve) => setTimeout(resolve, 1));
- activeDeletes--;
- },
- };
+ fakeAws().listObjects.mockImplementation(() => {
+ return Promise.resolve(
+ Array.from({length: 25}, (_, index) => ({
+ Key: `sites/from-bundle-concurrency/stale-${index}.js`,
+ ETag: 'etag',
+ LastModified: new Date(0),
+ Size: 0,
+ })),
+ );
+ });
+ fakeAws().deleteFile.mockImplementation(async () => {
+ activeDeletes++;
+ maxActiveDeletes = Math.max(maxActiveDeletes, activeDeletes);
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ activeDeletes--;
+ });
+ fakeAws().uploadDir.mockImplementation(() => Promise.resolve());
await deployBundle({
bucketName,
bundleDir,
siteName: 'from-bundle-concurrency',
- providerSpecifics,
- fullClientSpecifics: {
- ...mockFullClientSpecifics,
- uploadDir: () => Promise.resolve(),
- },
});
expect(maxActiveDeletes).toBe(10);
@@ -365,13 +328,10 @@ test('supports throwIfSiteExists without deleting the caller bundle', async () =
test('validates the local bundle before making an AWS request', async () => {
let awsCalls = 0;
- const providerSpecifics: typeof mockImplementation = {
- ...mockImplementation,
- getAccountId: () => {
- awsCalls++;
- return Promise.resolve('123456789');
- },
- };
+ fakeAws().getAccountId.mockImplementation(() => {
+ awsCalls++;
+ return Promise.resolve('123456789');
+ });
const missingPathParent = mkdtempSync(
path.join(os.tmpdir(), 'missing-remotion-bundle-test-'),
);
@@ -383,7 +343,6 @@ test('validates the local bundle before making an AWS request', async () => {
bucketName: 'remotionlambda-testing',
bundleDir: missingPath,
siteName: 'from-bundle-validation',
- providerSpecifics,
}),
).rejects.toThrow('does not exist');
expect(awsCalls).toBe(0);
@@ -399,7 +358,6 @@ test('validates the local bundle before making an AWS request', async () => {
bucketName: 'remotionlambda-testing',
bundleDir: filePath,
siteName: 'from-bundle-validation',
- providerSpecifics,
}),
).rejects.toThrow('is not a directory');
@@ -410,7 +368,6 @@ test('validates the local bundle before making an AWS request', async () => {
bucketName: 'remotionlambda-testing',
bundleDir: withoutIndex,
siteName: 'from-bundle-validation',
- providerSpecifics,
}),
).rejects.toThrow('does not contain an index.html');
@@ -420,7 +377,6 @@ test('validates the local bundle before making an AWS request', async () => {
bucketName: 'remotionlambda-testing',
bundleDir: withoutBundleScript,
siteName: 'from-bundle-validation',
- providerSpecifics,
}),
).rejects.toThrow('does not contain a bundle.js');
@@ -434,7 +390,6 @@ test('validates the local bundle before making an AWS request', async () => {
bucketName: 'remotionlambda-testing',
bundleDir: incompatible,
siteName: 'from-bundle-validation',
- providerSpecifics,
}),
).rejects.toThrow('is not relocatable');
@@ -448,7 +403,6 @@ test('validates the local bundle before making an AWS request', async () => {
bucketName: 'remotionlambda-testing',
bundleDir: malformedPublicPath,
siteName: 'from-bundle-validation',
- providerSpecifics,
}),
).rejects.toMatchObject({
message: expect.stringContaining(
@@ -485,19 +439,15 @@ if (process.platform !== 'win32') {
'dir',
);
let awsCalls = 0;
- const providerSpecifics: typeof mockImplementation = {
- ...mockImplementation,
- getAccountId: () => {
- awsCalls++;
- return Promise.resolve('123456789');
- },
- };
+ fakeAws().getAccountId.mockImplementation(() => {
+ awsCalls++;
+ return Promise.resolve('123456789');
+ });
await expect(
deployBundle({
bucketName,
bundleDir: directoryLinkBundle,
siteName: 'from-bundle-directory-link',
- providerSpecifics,
}),
).rejects.toThrow('symbolic link to a directory');
expect(awsCalls).toBe(0);
diff --git a/packages/lambda/src/test/integration/deploy-site.test.ts b/packages/lambda/src/test/integration/deploy-site.test.ts
index 46583190a2..1a90d0538b 100644
--- a/packages/lambda/src/test/integration/deploy-site.test.ts
+++ b/packages/lambda/src/test/integration/deploy-site.test.ts
@@ -2,14 +2,15 @@ import {afterEach, expect, spyOn, test} from 'bun:test';
import fs, {existsSync, mkdtempSync, writeFileSync} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import type {BundleOptions} from '@remotion/bundler';
+import type {bundle, BundleOptions} from '@remotion/bundler';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {internalDeleteSite} from '../../api/delete-site';
import {internalDeploySite} from '../../api/deploy-site';
-import {mockFullClientSpecifics} from '../mock-implementation';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {fakeAws, useFakeAws} from '../mocks/fake-aws';
import {getDirFiles} from '../mocks/upload-dir';
+useFakeAws();
+
const temporaryDirectories: string[] = [];
const makeGeneratedBundle = () => {
@@ -25,7 +26,6 @@ const makeGeneratedBundle = () => {
const makeBucket = async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -45,23 +45,19 @@ const makeBundleSite = ({
directory: string;
getBundle: () => Promise<string>;
onStarted?: () => void;
-}): typeof mockFullClientSpecifics.bundleSite => {
- return ((options: BundleOptions) => {
+}) => {
+ fakeAws().bundleSite.mockImplementation(((options: BundleOptions) => {
options.onDirectoryCreated?.(directory);
onStarted();
return getBundle();
- }) as typeof mockFullClientSpecifics.bundleSite;
+ }) as typeof bundle);
};
const deployGeneratedBundle = ({
bucketName,
- fullClientSpecifics,
- providerSpecifics = mockImplementation,
siteName,
}: {
bucketName: string;
- fullClientSpecifics: typeof mockFullClientSpecifics;
- providerSpecifics?: typeof mockImplementation;
siteName: string;
}) => {
return internalDeploySite({
@@ -70,14 +66,12 @@ const deployGeneratedBundle = ({
region: 'ap-northeast-1',
siteName,
gitSource: null,
- providerSpecifics,
indent: false,
logLevel: 'error',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics,
requestHandler: null,
});
};
@@ -104,15 +98,13 @@ test('Should throw on wrong prefix', async () => {
entryPoint: 'first',
region: 'us-east-1',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
- siteName: mockImplementation.randomHash(),
+ siteName: LambdaClientInternals.randomHashImplementation(),
throwIfSiteExists: true,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
}),
).rejects.toThrow(/The bucketName parameter must start /);
@@ -127,14 +119,12 @@ test('Should throw if invalid region was passed', () => {
region: 'ap-northeast-9',
siteName: 'testing',
gitSource: null,
- providerSpecifics: LambdaClientInternals.awsImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: true,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
}),
).rejects.toThrow(/ap-northeast-9 is not a supported AWS region/);
});
@@ -147,14 +137,12 @@ test("Should throw if bucket doesn't exist", () => {
region: 'ap-northeast-1',
siteName: 'testing',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: true,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
}),
).rejects.toThrow(
@@ -165,7 +153,6 @@ test("Should throw if bucket doesn't exist", () => {
test('Should apply name if given', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -185,9 +172,7 @@ test('Should apply name if given', async () => {
options: {},
privacy: 'public',
throwIfSiteExists: true,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
}),
).toEqual({
@@ -205,7 +190,6 @@ test('Should apply name if given', async () => {
test('Should overwrite site if given siteName is already taken', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -221,14 +205,12 @@ test('Should overwrite site if given siteName is already taken', async () => {
region: 'ap-northeast-1',
siteName: 'testing',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
}),
).toEqual({
@@ -246,7 +228,6 @@ test('Should overwrite site if given siteName is already taken', async () => {
test('Should delete the previous site if deploying the new one', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -261,14 +242,12 @@ test('Should delete the previous site if deploying the new one', async () => {
region: 'ap-northeast-1',
siteName: 'testing',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
await internalDeploySite({
@@ -277,18 +256,16 @@ test('Should delete the previous site if deploying the new one', async () => {
region: 'ap-northeast-1',
siteName: 'testing',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
expectedBucketOwner: null,
prefix: 'sites/testing',
@@ -315,7 +292,6 @@ test('Should delete the previous site if deploying the new one', async () => {
test('Should keep the previous site if deploying the new one with different ID', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -330,14 +306,12 @@ test('Should keep the previous site if deploying the new one with different ID',
region: 'ap-northeast-1',
siteName: 'testing',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
await internalDeploySite({
@@ -346,18 +320,16 @@ test('Should keep the previous site if deploying the new one with different ID',
region: 'ap-northeast-1',
siteName: 'testing-2',
gitSource: null,
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
expectedBucketOwner: null,
prefix: 'sites/',
@@ -388,7 +360,6 @@ test('Should keep the previous site if deploying the new one with different ID',
bucketName,
region: 'ap-northeast-1',
siteName: 'testing',
- providerSpecifics: mockImplementation,
forcePathStyle: false,
onAfterItemDeleted: null,
requestHandler: null,
@@ -397,7 +368,6 @@ test('Should keep the previous site if deploying the new one with different ID',
bucketName,
region: 'ap-northeast-1',
siteName: 'testing-2',
- providerSpecifics: mockImplementation,
forcePathStyle: false,
onAfterItemDeleted: null,
requestHandler: null,
@@ -407,7 +377,6 @@ test('Should keep the previous site if deploying the new one with different ID',
test('Should not delete site with same prefix', async () => {
const {bucketName} = await LambdaClientInternals.internalGetOrCreateBucket({
region: 'ap-northeast-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: false,
forcePathStyle: false,
@@ -422,14 +391,12 @@ test('Should not delete site with same prefix', async () => {
entryPoint: 'first',
region: 'ap-northeast-1',
siteName: 'my-site',
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
await internalDeploySite({
@@ -438,14 +405,12 @@ test('Should not delete site with same prefix', async () => {
entryPoint: 'second',
region: 'ap-northeast-1',
siteName: 'my-site-staging',
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
await internalDeploySite({
@@ -454,18 +419,16 @@ test('Should not delete site with same prefix', async () => {
entryPoint: 'first',
region: 'ap-northeast-1',
siteName: 'my-site',
- providerSpecifics: mockImplementation,
indent: false,
logLevel: 'info',
options: {},
privacy: 'public',
throwIfSiteExists: false,
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName,
expectedBucketOwner: null,
prefix: 'sites/',
@@ -497,18 +460,14 @@ test('Should remove a generated bundle after bundling fails', async () => {
const directory = makeGeneratedBundle();
const bucketName = await makeBucket();
const bundlingError = new Error('Bundling failed');
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => Promise.reject(bundlingError),
- }),
- };
+ makeBundleSite({
+ directory,
+ getBundle: () => Promise.reject(bundlingError),
+ });
const error = await getRejection(
deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
siteName: 'bundling-failure',
}),
);
@@ -529,24 +488,16 @@ test('Should wait for bundling to finish after listing fails', async () => {
const bundleStarted = new Promise<void>((resolve) => {
markBundleStarted = resolve;
});
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => bundlePromise,
- onStarted: markBundleStarted,
- }),
- };
- const providerSpecifics: typeof mockImplementation = {
- ...mockImplementation,
- listObjects: () => Promise.reject(listingError),
- };
+ makeBundleSite({
+ directory,
+ getBundle: () => bundlePromise,
+ onStarted: markBundleStarted,
+ });
+ fakeAws().listObjects.mockImplementation(() => Promise.reject(listingError));
let settled = false;
const observedDeployment = deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
- providerSpecifics,
siteName: 'listing-failure',
}).then(
() => {
@@ -574,19 +525,15 @@ test('Should remove a generated bundle after uploading fails', async () => {
const directory = makeGeneratedBundle();
const bucketName = await makeBucket();
const uploadError = new Error('Uploading failed');
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => Promise.resolve(directory),
- }),
- uploadDir: () => Promise.reject(uploadError),
- };
+ makeBundleSite({
+ directory,
+ getBundle: () => Promise.resolve(directory),
+ });
+ fakeAws().uploadDir.mockImplementation(() => Promise.reject(uploadError));
const error = await getRejection(
deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
siteName: 'upload-failure',
}),
);
@@ -601,48 +548,40 @@ test('Should finish stale file deletions before removing the generated bundle',
const deletionError = new Error('Deleting failed');
let deleteCount = 0;
let bundleWasRemovedDuringDeletion = false;
- const providerSpecifics: typeof mockImplementation = {
- ...mockImplementation,
- listObjects: () => {
- return Promise.resolve(
- Array.from({length: 12}, (_, index) => ({
- Key: `sites/deletion-failure/stale-${index}.js`,
- ETag: 'stale-etag',
- LastModified: new Date(0),
- Size: 0,
- })),
- );
- },
- deleteFile: async () => {
- deleteCount++;
- if (!existsSync(directory)) {
- bundleWasRemovedDuringDeletion = true;
- }
-
- if (deleteCount === 1) {
- throw deletionError;
- }
-
- await new Promise((resolve) => setTimeout(resolve, 1));
- if (!existsSync(directory)) {
- bundleWasRemovedDuringDeletion = true;
- }
- },
- };
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => Promise.resolve(directory),
- }),
- uploadDir: () => Promise.resolve(),
- };
+ fakeAws().listObjects.mockImplementation(() => {
+ return Promise.resolve(
+ Array.from({length: 12}, (_, index) => ({
+ Key: `sites/deletion-failure/stale-${index}.js`,
+ ETag: 'stale-etag',
+ LastModified: new Date(0),
+ Size: 0,
+ })),
+ );
+ });
+ fakeAws().deleteFile.mockImplementation(async () => {
+ deleteCount++;
+ if (!existsSync(directory)) {
+ bundleWasRemovedDuringDeletion = true;
+ }
+
+ if (deleteCount === 1) {
+ throw deletionError;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ if (!existsSync(directory)) {
+ bundleWasRemovedDuringDeletion = true;
+ }
+ });
+ makeBundleSite({
+ directory,
+ getBundle: () => Promise.resolve(directory),
+ });
+ fakeAws().uploadDir.mockImplementation(() => Promise.resolve());
const error = await getRejection(
deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
- providerSpecifics,
siteName: 'deletion-failure',
}),
);
@@ -656,17 +595,13 @@ test('Should finish stale file deletions before removing the generated bundle',
test('Should remove a generated bundle after a successful deployment', async () => {
const directory = makeGeneratedBundle();
const bucketName = await makeBucket();
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => Promise.resolve(directory),
- }),
- };
+ makeBundleSite({
+ directory,
+ getBundle: () => Promise.resolve(directory),
+ });
const result = await deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
siteName: 'successful-cleanup',
});
@@ -678,13 +613,10 @@ test('Should report a cleanup failure after a successful deployment', async () =
const directory = makeGeneratedBundle();
const bucketName = await makeBucket();
const cleanupError = new Error('Cleanup failed');
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => Promise.resolve(directory),
- }),
- };
+ makeBundleSite({
+ directory,
+ getBundle: () => Promise.resolve(directory),
+ });
const cleanupSpy = spyOn(fs, 'rmSync').mockImplementation(() => {
throw cleanupError;
});
@@ -694,7 +626,6 @@ test('Should report a cleanup failure after a successful deployment', async () =
error = await getRejection(
deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
siteName: 'cleanup-failure',
}),
);
@@ -711,14 +642,11 @@ test('Should retain deployment and cleanup errors if both fail', async () => {
const bucketName = await makeBucket();
const deploymentError = new Error('Deployment failed');
const cleanupError = new Error('Cleanup failed');
- const fullClientSpecifics: typeof mockFullClientSpecifics = {
- ...mockFullClientSpecifics,
- bundleSite: makeBundleSite({
- directory,
- getBundle: () => Promise.resolve(directory),
- }),
- uploadDir: () => Promise.reject(deploymentError),
- };
+ makeBundleSite({
+ directory,
+ getBundle: () => Promise.resolve(directory),
+ });
+ fakeAws().uploadDir.mockImplementation(() => Promise.reject(deploymentError));
const cleanupSpy = spyOn(fs, 'rmSync').mockImplementation(() => {
throw cleanupError;
});
@@ -728,7 +656,6 @@ test('Should retain deployment and cleanup errors if both fail', async () => {
error = await getRejection(
deployGeneratedBundle({
bucketName,
- fullClientSpecifics,
siteName: 'deployment-and-cleanup-failure',
}),
);
diff --git a/packages/lambda/src/test/integration/get-sites.test.ts b/packages/lambda/src/test/integration/get-sites.test.ts
index 0d784e7266..d8ba461d33 100644
--- a/packages/lambda/src/test/integration/get-sites.test.ts
+++ b/packages/lambda/src/test/integration/get-sites.test.ts
@@ -2,16 +2,16 @@ import {expect, test} from 'bun:test';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
import {internalDeploySite} from '../../api/deploy-site';
-import {mockFullClientSpecifics} from '../mock-implementation';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {useFakeAws} from '../mocks/fake-aws';
import {resetMockStore} from '../mocks/mock-store';
+useFakeAws();
+
test('Should have no buckets at first', async () => {
resetMockStore();
expect(
await LambdaClientInternals.internalGetSites({
region: 'us-east-1',
- providerSpecifics: mockImplementation,
forcePathStyle: false,
forceBucketName: null,
compatibleOnly: false,
@@ -24,7 +24,6 @@ test('Should have a site after deploying', async () => {
resetMockStore();
await LambdaClientInternals.internalGetOrCreateBucket({
region: 'eu-central-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: null,
forcePathStyle: false,
@@ -41,12 +40,10 @@ test('Should have a site after deploying', async () => {
gitSource: null,
logLevel: 'info',
indent: false,
- providerSpecifics: mockImplementation,
privacy: 'public',
throwIfSiteExists: true,
options: {},
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
}),
).toEqual({
@@ -62,7 +59,6 @@ test('Should have a site after deploying', async () => {
expect(
await LambdaClientInternals.internalGetSites({
region: 'eu-central-1',
- providerSpecifics: mockImplementation,
forcePathStyle: false,
forceBucketName: null,
compatibleOnly: false,
@@ -94,7 +90,6 @@ test('Should filter sites by compatibleOnly', async () => {
resetMockStore();
await LambdaClientInternals.internalGetOrCreateBucket({
region: 'eu-central-1',
- providerSpecifics: mockImplementation,
customCredentials: null,
enableFolderExpiry: null,
forcePathStyle: false,
@@ -110,18 +105,15 @@ test('Should filter sites by compatibleOnly', async () => {
gitSource: null,
logLevel: 'info',
indent: false,
- providerSpecifics: mockImplementation,
privacy: 'public',
throwIfSiteExists: true,
options: {},
forcePathStyle: false,
- fullClientSpecifics: mockFullClientSpecifics,
requestHandler: null,
});
const {sites} = await LambdaClientInternals.internalGetSites({
region: 'eu-central-1',
- providerSpecifics: mockImplementation,
forcePathStyle: false,
forceBucketName: null,
compatibleOnly: true,
diff --git a/packages/lambda/src/test/integration/handlers.test.ts b/packages/lambda/src/test/integration/handlers.test.ts
index 17228cac6d..794a6e715c 100644
--- a/packages/lambda/src/test/integration/handlers.test.ts
+++ b/packages/lambda/src/test/integration/handlers.test.ts
@@ -1,11 +1,16 @@
import {expect, test} from 'bun:test';
-import {ServerlessRoutines} from '@remotion/lambda-client';
+import {
+ LambdaClientInternals,
+ ServerlessRoutines,
+} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {useFakeAws} from '../mocks/fake-aws';
+
+useFakeAws();
test('Call function locally', async () => {
expect(
- await mockImplementation.callFunctionSync({
+ await LambdaClientInternals.callFunctionSyncImplementation({
payload: {
type: ServerlessRoutines.info,
logLevel: 'info',
diff --git a/packages/lambda/src/test/integration/renders/gif.test.ts b/packages/lambda/src/test/integration/renders/gif.test.ts
index 5a05c854c6..90dd8fee37 100644
--- a/packages/lambda/src/test/integration/renders/gif.test.ts
+++ b/packages/lambda/src/test/integration/renders/gif.test.ts
@@ -3,8 +3,11 @@ import {createWriteStream, unlinkSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {RenderInternals} from '@remotion/renderer';
+import {useFakeAws} from '../../mocks/fake-aws';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
test('Should make a distributed GIF', async () => {
const {file, close} = await simulateLambdaRender({
codec: 'gif',
diff --git a/packages/lambda/src/test/integration/renders/muted-render.test.ts b/packages/lambda/src/test/integration/renders/muted-render.test.ts
index 47b51ee628..71659c2c8e 100644
--- a/packages/lambda/src/test/integration/renders/muted-render.test.ts
+++ b/packages/lambda/src/test/integration/renders/muted-render.test.ts
@@ -8,10 +8,12 @@ import {
} from '@remotion/lambda-client';
import {RenderInternals, getVideoMetadata} from '@remotion/renderer';
import {makeProgressString} from '../../../cli/commands/render/progress';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {useFakeAws} from '../../mocks/fake-aws';
import {getMockInvocationTypesForRender} from '../../mocks/mock-invocations';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
// Browser startup, rendering, audio encoding, and output probing can exceed 5 seconds.
test('Should directly render final media with one Lambda', async () => {
const {close, file, progress, renderId} = await simulateLambdaRender({
@@ -70,7 +72,7 @@ test('Should directly render final media with one Lambda', async () => {
unlinkSync(tmpfile);
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
@@ -85,11 +87,10 @@ test('Should directly render final media with one Lambda', async () => {
bucketName: progress.outBucket as string,
region: 'eu-central-1',
renderId,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
});
- const expectFiles = await mockImplementation.listObjects({
+ const expectFiles = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
diff --git a/packages/lambda/src/test/integration/renders/old-version.test.ts b/packages/lambda/src/test/integration/renders/old-version.test.ts
index dc977e5ac9..d40d26ed77 100644
--- a/packages/lambda/src/test/integration/renders/old-version.test.ts
+++ b/packages/lambda/src/test/integration/renders/old-version.test.ts
@@ -1,13 +1,18 @@
import {expect, test} from 'bun:test';
import path from 'path';
-import {ServerlessRoutines} from '@remotion/lambda-client';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {
+ LambdaClientInternals,
+ ServerlessRoutines,
+} from '@remotion/lambda-client';
+import {useFakeAws} from '../../mocks/fake-aws';
+
+useFakeAws();
test(
'Should fail when using an incompatible version',
async () => {
try {
- const aha = await mockImplementation.callFunctionSync({
+ const aha = await LambdaClientInternals.callFunctionSyncImplementation({
type: ServerlessRoutines.launch,
payload: {
enableCancellation: false,
diff --git a/packages/lambda/src/test/integration/renders/other-bucket.test.ts b/packages/lambda/src/test/integration/renders/other-bucket.test.ts
index 7337188f37..c18112c47a 100644
--- a/packages/lambda/src/test/integration/renders/other-bucket.test.ts
+++ b/packages/lambda/src/test/integration/renders/other-bucket.test.ts
@@ -1,9 +1,12 @@
import {expect, test} from 'bun:test';
import path from 'path';
import {$} from 'bun';
+import {useFakeAws} from '../../mocks/fake-aws';
import {streamToUint8Array} from '../../mocks/mock-store';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
test(
'Should be able to render to another bucket, and silent audio should be added',
async () => {
diff --git a/packages/lambda/src/test/integration/renders/regular-audio.test.ts b/packages/lambda/src/test/integration/renders/regular-audio.test.ts
index e4e53c85d8..400c5717bd 100644
--- a/packages/lambda/src/test/integration/renders/regular-audio.test.ts
+++ b/packages/lambda/src/test/integration/renders/regular-audio.test.ts
@@ -2,10 +2,12 @@ import {expect, test} from 'bun:test';
import {createWriteStream, unlinkSync} from 'fs';
import path from 'path';
import {LambdaClientInternals} from '@remotion/lambda-client';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {useFakeAws} from '../../mocks/fake-aws';
import {Wavedraw} from '../draw-wav';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
test(
'Should make regular (non-seamless) audio',
async () => {
@@ -53,7 +55,7 @@ test(
wd.drawWave(options); // outputs wave drawing to example1.png
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
@@ -68,11 +70,10 @@ test(
bucketName: progress.outBucket as string,
region: 'eu-central-1',
renderId,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
});
- const expectFiles = await mockImplementation.listObjects({
+ const expectFiles = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
diff --git a/packages/lambda/src/test/integration/renders/seamless-audio.test.ts b/packages/lambda/src/test/integration/renders/seamless-audio.test.ts
index 55e734bc7c..5c7f0b491b 100644
--- a/packages/lambda/src/test/integration/renders/seamless-audio.test.ts
+++ b/packages/lambda/src/test/integration/renders/seamless-audio.test.ts
@@ -3,11 +3,13 @@ import {existsSync, unlinkSync} from 'fs';
import path from 'path';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {$} from 'bun';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {useFakeAws} from '../../mocks/fake-aws';
import {streamToUint8Array} from '../../mocks/mock-store';
import {Wavedraw} from '../draw-wav';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
test(
'Should make seamless audio',
async () => {
@@ -59,7 +61,7 @@ test(
await wd.drawWave(options); // outputs wave drawing to example1.png
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
@@ -74,11 +76,10 @@ test(
bucketName: progress.outBucket as string,
region: 'eu-central-1',
renderId,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
});
- const expectFiles = await mockImplementation.listObjects({
+ const expectFiles = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
diff --git a/packages/lambda/src/test/integration/renders/slow-seamless-audio.test.ts b/packages/lambda/src/test/integration/renders/slow-seamless-audio.test.ts
index 3163f1176a..56b954b969 100644
--- a/packages/lambda/src/test/integration/renders/slow-seamless-audio.test.ts
+++ b/packages/lambda/src/test/integration/renders/slow-seamless-audio.test.ts
@@ -3,11 +3,13 @@ import {existsSync, unlinkSync} from 'fs';
import path from 'path';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {$} from 'bun';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {useFakeAws} from '../../mocks/fake-aws';
import {streamToUint8Array} from '../../mocks/mock-store';
import {Wavedraw} from '../draw-wav';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
test(
'Should make slowed down seamless audio',
async () => {
@@ -58,7 +60,7 @@ test(
wd.drawWave(options); // outputs wave drawing to example1.png
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
@@ -73,11 +75,10 @@ test(
bucketName: progress.outBucket as string,
region: 'eu-central-1',
renderId,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
});
- const expectFiles = await mockImplementation.listObjects({
+ const expectFiles = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
diff --git a/packages/lambda/src/test/integration/renders/transparent-webm.test.ts b/packages/lambda/src/test/integration/renders/transparent-webm.test.ts
index ff8255d8e3..222c777e7e 100644
--- a/packages/lambda/src/test/integration/renders/transparent-webm.test.ts
+++ b/packages/lambda/src/test/integration/renders/transparent-webm.test.ts
@@ -4,9 +4,11 @@ import os from 'node:os';
import path from 'node:path';
import {LambdaClientInternals} from '@remotion/lambda-client';
import {ensureBrowser, RenderInternals} from '@remotion/renderer';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {useFakeAws} from '../../mocks/fake-aws';
import {simulateLambdaRender} from '../simulate-lambda-render';
+useFakeAws();
+
beforeAll(async () => {
await ensureBrowser();
});
@@ -50,7 +52,7 @@ test(
expect(probe.stderr).toMatch(/Audio: opus, 48000 Hz/);
fs.unlinkSync(out);
- const files = await mockImplementation.listObjects({
+ const files = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
@@ -65,11 +67,10 @@ test(
bucketName: progress.outBucket as string,
region: 'eu-central-1',
renderId,
- providerSpecifics: mockImplementation,
forcePathStyle: false,
});
- const expectFiles = await mockImplementation.listObjects({
+ const expectFiles = await LambdaClientInternals.lambdaLsImplementation({
bucketName: progress.outBucket as string,
region: 'eu-central-1',
expectedBucketOwner: 'abc',
diff --git a/packages/lambda/src/test/integration/renders/write-only-bucket.test.ts b/packages/lambda/src/test/integration/renders/write-only-bucket.test.ts
index 77fc1f4d9e..57974aca6f 100644
--- a/packages/lambda/src/test/integration/renders/write-only-bucket.test.ts
+++ b/packages/lambda/src/test/integration/renders/write-only-bucket.test.ts
@@ -1,4 +1,4 @@
-import {expect, spyOn, test} from 'bun:test';
+import {expect, test} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -9,10 +9,12 @@ import {
ServerlessRoutines,
} from '@remotion/lambda-client';
import {RenderInternals} from '@remotion/renderer';
-import {mockImplementation} from '../../mocks/mock-implementation';
+import {fakeAws, fakeAwsDefaults, useFakeAws} from '../../mocks/fake-aws';
import {readMockS3File} from '../../mocks/mock-store';
import {waitUntilDone} from '../wait-until-done';
+useFakeAws();
+
test.each([1, 2])(
'renders to a write-only destination with concurrency %s without overwriting existing files',
async (concurrency) => {
@@ -20,23 +22,17 @@ test.each([1, 2])(
const destination = `write-only-output-${concurrency}`;
const region = 'eu-central-1';
const key = 'output.mp4';
- const originalHead = mockImplementation.headFile;
- const originalConditionalWrite = mockImplementation.writeFileIfNotExists;
- const capabilitySpy = spyOn(
- mockImplementation,
- 'supportsConditionalOutput',
- );
+ const originalHead = fakeAwsDefaults.headFile;
+ const capabilitySpy = fakeAws().supportsConditionalOutput;
let destinationChecks = 0;
- const headSpy = spyOn(mockImplementation, 'headFile').mockImplementation(
- (input) => {
- if (input.bucketName === destination) {
- destinationChecks++;
- throw new OutputFileAccessDeniedError('s3:GetObject access denied');
- }
+ const headSpy = fakeAws().headFile.mockImplementation((input) => {
+ if (input.bucketName === destination) {
+ destinationChecks++;
+ throw new OutputFileAccessDeniedError('s3:GetObject access denied');
+ }
- return originalHead(input);
- },
- );
+ return originalHead(input);
+ });
let close: (() => Promise<void>) | null = null;
try {
const serveUrl = await bundle({
@@ -74,14 +70,16 @@ test.each([1, 2])(
}),
);
const result =
- await mockImplementation.callFunctionSync<ServerlessRoutines.start>({
- type: ServerlessRoutines.start,
- payload,
- functionName: 'remotion-dev-lambda',
- region,
- timeoutInTest: 120000,
- requestHandler: null,
- });
+ await LambdaClientInternals.callFunctionSyncImplementation<ServerlessRoutines.start>(
+ {
+ type: ServerlessRoutines.start,
+ payload,
+ functionName: 'remotion-dev-lambda',
+ region,
+ timeoutInTest: 120000,
+ requestHandler: null,
+ },
+ );
return waitUntilDone(result.bucketName, result.renderId);
};
@@ -112,24 +110,13 @@ test.each([1, 2])(
await expect(render(false)).rejects.toThrow('s3:GetObject');
capabilitySpy.mockReturnValue(true);
- // Without conditional uploads, denied preflight reads must remain fatal.
- mockImplementation.writeFileIfNotExists = null;
- await expect(render(false)).rejects.toThrow('s3:GetObject');
- mockImplementation.writeFileIfNotExists = originalConditionalWrite;
-
// With read access, reject an existing file before uploading.
headSpy.mockImplementation(originalHead);
- const uploadSpy = spyOn(mockImplementation, 'writeFileIfNotExists');
- try {
- await expect(render(false)).rejects.toThrow('already exists');
- expect(uploadSpy).not.toHaveBeenCalled();
- } finally {
- uploadSpy.mockRestore();
- }
+ const uploadSpy = fakeAws().writeFileIfNotExists;
+ uploadSpy.mockClear();
+ await expect(render(false)).rejects.toThrow('already exists');
+ expect(uploadSpy).not.toHaveBeenCalled();
} finally {
- mockImplementation.writeFileIfNotExists = originalConditionalWrite;
- capabilitySpy.mockRestore();
- headSpy.mockRestore();
await close?.();
fs.rmSync(temp, {recursive: true, force: true});
}
diff --git a/packages/lambda/src/test/integration/simulate-lambda-render.ts b/packages/lambda/src/test/integration/simulate-lambda-render.ts
index 8f78f72e0d..077971598c 100644
--- a/packages/lambda/src/test/integration/simulate-lambda-render.ts
+++ b/packages/lambda/src/test/integration/simulate-lambda-render.ts
@@ -5,7 +5,6 @@ import {
type RenderMediaOnLambdaInput,
} from '@remotion/lambda-client';
import {RenderInternals} from '@remotion/renderer';
-import {mockImplementation} from '../mocks/mock-implementation';
import {waitUntilDone} from './wait-until-done';
const functionName = 'remotion-dev-render';
@@ -38,18 +37,20 @@ export const simulateLambdaRender = async (
);
const res =
- await mockImplementation.callFunctionSync<ServerlessRoutines.start>({
- type: ServerlessRoutines.start,
- payload,
- functionName: 'remotion-dev-lambda',
- region: 'eu-central-1',
- timeoutInTest: 120000,
- requestHandler: null,
- });
+ await LambdaClientInternals.callFunctionSyncImplementation<ServerlessRoutines.start>(
+ {
+ type: ServerlessRoutines.start,
+ payload,
+ functionName: 'remotion-dev-lambda',
+ region: 'eu-central-1',
+ timeoutInTest: 120000,
+ requestHandler: null,
+ },
+ );
const progress = await waitUntilDone(res.bucketName, res.renderId);
- const file = await mockImplementation.readFile({
+ const file = await LambdaClientInternals.lambdaReadFileImplementation({
bucketName: progress.outBucket as string,
key: progress.outKey as string,
expectedBucketOwner: 'abc',
diff --git a/packages/lambda/src/test/integration/wait-until-done.ts b/packages/lambda/src/test/integration/wait-until-done.ts
index 6bbf90a8c2..9972294bd8 100644
--- a/packages/lambda/src/test/integration/wait-until-done.ts
+++ b/packages/lambda/src/test/integration/wait-until-done.ts
@@ -1,25 +1,29 @@
-import {ServerlessRoutines} from '@remotion/lambda-client';
+import {
+ LambdaClientInternals,
+ ServerlessRoutines,
+} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
-import {mockImplementation} from '../mocks/mock-implementation';
export const waitUntilDone = async (bucketName: string, renderId: string) => {
while (true) {
- const progress = await mockImplementation.callFunctionSync({
- type: ServerlessRoutines.status,
- payload: {
+ const progress = await LambdaClientInternals.callFunctionSyncImplementation(
+ {
type: ServerlessRoutines.status,
- bucketName,
- renderId,
- version: VERSION,
- logLevel: 'error',
- forcePathStyle: false,
- s3OutputProvider: null,
+ payload: {
+ type: ServerlessRoutines.status,
+ bucketName,
+ renderId,
+ version: VERSION,
+ logLevel: 'error',
+ forcePathStyle: false,
+ s3OutputProvider: null,
+ },
+ functionName: 'remotion-dev-lambda',
+ region: 'eu-central-1',
+ timeoutInTest: 120000,
+ requestHandler: null,
},
- functionName: 'remotion-dev-lambda',
- region: 'eu-central-1',
- timeoutInTest: 120000,
- requestHandler: null,
- });
+ );
if (progress.done) {
return progress;
}
diff --git a/packages/lambda/src/test/integration/webhooks.test.ts b/packages/lambda/src/test/integration/webhooks.test.ts
index 8c7ecf2ee9..e6b308e8cf 100644
--- a/packages/lambda/src/test/integration/webhooks.test.ts
+++ b/packages/lambda/src/test/integration/webhooks.test.ts
@@ -1,12 +1,20 @@
import {beforeAll, expect, test} from 'bun:test';
import path from 'path';
-import {ServerlessRoutines} from '@remotion/lambda-client';
+import {
+ LambdaClientInternals,
+ ServerlessRoutines,
+} from '@remotion/lambda-client';
import {RenderInternals, ensureBrowser} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
-import {getWebhookCalls, resetWebhookCalls} from '../mock-implementation';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {
+ getWebhookCalls,
+ resetWebhookCalls,
+ useFakeAws,
+} from '../mocks/fake-aws';
import {waitUntilDone} from './wait-until-done';
+useFakeAws();
+
beforeAll(async () => {
await ensureBrowser();
});
@@ -34,7 +42,7 @@ test(
forceIPv4: false,
});
- const res = await mockImplementation.callFunctionSync({
+ const res = await LambdaClientInternals.callFunctionSyncImplementation({
type: ServerlessRoutines.start,
payload: {
enableCancellation: false,
@@ -166,7 +174,7 @@ test(
resetWebhookCalls();
- await mockImplementation.callFunctionSync({
+ await LambdaClientInternals.callFunctionSyncImplementation({
functionName: 'remotion-dev-lambda',
region: 'us-east-1',
type: ServerlessRoutines.launch,
diff --git a/packages/lambda/src/test/mock-implementation.ts b/packages/lambda/src/test/mock-implementation.ts
deleted file mode 100644
index cabbdd6ebc..0000000000
--- a/packages/lambda/src/test/mock-implementation.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import {
- LambdaClientInternals,
- speculateFunctionName,
-} from '@remotion/lambda-client';
-import {openBrowser} from '@remotion/renderer';
-import {Log} from '../cli/log';
-import {serverAwsImplementation} from '../functions/aws-server-implementation';
-import type {
- FullClientSpecifics,
- GetBrowserInstance,
- InsideFunctionSpecifics,
- InvokeWebhookParams,
-} from '../functions/provider-implementation';
-import {mockBundleSite} from './mocks/mock-bundle-site';
-import {mockCreateFunction} from './mocks/mock-create-function';
-import {mockReadDirectory} from './mocks/mock-read-dir';
-import {mockUploadDir} from './mocks/upload-dir';
-
-const browsersOpen: Map<string, boolean> = new Map();
-export const getBrowserInstance: GetBrowserInstance = async ({
- logLevel,
- indent,
-}) => {
- const instance = await openBrowser('chrome', {logLevel});
- browsersOpen.set(instance.id, true);
- Log.verbose(
- {logLevel, indent},
- `Opening new browser instance ${instance.id}. ${browsersOpen.size} browsers open`,
- );
- return {instance, configurationString: 'chrome'};
-};
-
-const paramsArray: InvokeWebhookParams[] = [];
-
-export const mockServerImplementation: InsideFunctionSpecifics = {
- defaultX264Preset: serverAwsImplementation.defaultX264Preset,
- forgetBrowserEventLoop: ({launchedBrowser}) => {
- browsersOpen.delete(launchedBrowser.instance.id);
-
- Log.verbose(
- {logLevel: 'verbose', indent: false},
- `Closing browser instance ${launchedBrowser.instance.id}. ${browsersOpen.size} browsers open`,
- );
- launchedBrowser.instance.close({silent: false});
- },
- closeBrowserInstance: async ({launchedBrowser}) => {
- browsersOpen.delete(launchedBrowser.instance.id);
- await launchedBrowser.instance.close({silent: true});
- },
- getCurrentRegionInFunction: () => 'eu-central-1',
- getBrowserInstance,
- timer: () => ({
- end: () => {},
- }),
- deleteTmpDir: () => Promise.resolve(),
- generateRandomId: LambdaClientInternals.randomHashImplementation,
- getCurrentFunctionName: () =>
- speculateFunctionName({
- diskSizeInMb: 10240,
- memorySizeInMb: 3009,
- timeoutInSeconds: 120,
- }),
- getCurrentMemorySizeInMb: () => 3009,
- invokeWebhook: (params) => {
- paramsArray.push(params);
- return Promise.resolve();
- },
- normalizeChromiumOptions: serverAwsImplementation.normalizeChromiumOptions,
- getTmpDirState: null,
- startRendererDiagnostics: null,
- makeArtifactWithDetails: () => ({
- filename: 'something',
- sizeInBytes: 0,
- s3Url: 'https://s3.af-south-1.amazonaws.com/bucket/key',
- s3Key: 'key',
- }),
-};
-
-export const resetWebhookCalls = () => {
- paramsArray.length = 0;
-};
-
-export const getWebhookCalls = () => {
- return paramsArray;
-};
-
-export const mockFullClientSpecifics: FullClientSpecifics = {
- bundleSite: mockBundleSite,
- id: '__remotion_full_client_specifics',
- readDirectory: mockReadDirectory,
- uploadDir: mockUploadDir,
- createFunction: mockCreateFunction,
-};
diff --git a/packages/lambda/src/test/mocks/aws-clients.ts b/packages/lambda/src/test/mocks/aws-clients.ts
index 375ac7e5df..b273f279f4 100644
--- a/packages/lambda/src/test/mocks/aws-clients.ts
+++ b/packages/lambda/src/test/mocks/aws-clients.ts
@@ -17,8 +17,6 @@ import {Log} from '../../cli/log';
import {innerHandler} from '../../functions/inner-routine';
import {ResponseStream} from '../../functions/streaming/response-stream';
import {streamWriter} from '../../functions/streaming/stream-writer';
-import {mockServerImplementation} from '../mock-implementation';
-import {mockImplementation} from './mock-implementation';
import {trackMockInvocation} from './mock-invocations';
export const getMockCallFunctionStreaming: CallFunctionStreaming = async <
@@ -81,8 +79,6 @@ export const getMockCallFunctionStreaming: CallFunctionStreaming = async <
getRemainingTimeInMillis: () => params.timeoutInTest ?? 120000,
requestId: 'fake',
},
- providerSpecifics: mockImplementation,
- insideFunctionSpecifics: mockServerImplementation,
});
responseStream._finish();
@@ -102,8 +98,6 @@ export const getMockCallFunctionAsync: CallFunctionAsync = async <
getRemainingTimeInMillis: () => params.timeoutInTest ?? 120000,
requestId: 'fake',
},
- providerSpecifics: mockImplementation,
- insideFunctionSpecifics: mockServerImplementation,
params: params.payload,
responseWriter: streamWriter(responseStream),
});
@@ -126,8 +120,6 @@ export const getMockCallFunctionSync: CallFunctionSync = async <
},
params: params.payload,
responseWriter: streamWriter(responseStream),
- providerSpecifics: mockImplementation,
- insideFunctionSpecifics: mockServerImplementation,
});
responseStream._finish();
diff --git a/packages/lambda/src/test/mocks/fake-aws.ts b/packages/lambda/src/test/mocks/fake-aws.ts
new file mode 100644
index 0000000000..6390538b00
--- /dev/null
+++ b/packages/lambda/src/test/mocks/fake-aws.ts
@@ -0,0 +1,329 @@
+/**
+ * Replaces the AWS-facing operations with in-memory fakes:
+ * - S3 reads and writes go to an in-memory bucket store (./mock-store.ts)
+ * - Lambda invocations run the handler in-process (./aws-clients.ts)
+ * - Function management uses an in-memory function list (./mock-functions.ts)
+ * - Site deployment skips bundling and uploads to the in-memory store
+ *
+ * Call `useFakeAws()` at the top level of a test file. To change the behavior
+ * of a single operation in a test, use `fakeAws().<operation>.mockImplementation()`;
+ * all operations are reset to their defaults after each test.
+ *
+ * Relies on ../preload.ts resolving @remotion/lambda-client to its sources.
+ */
+import {afterAll, afterEach, beforeAll, spyOn, type Mock} from 'bun:test';
+import {createReadStream, writeFileSync} from 'node:fs';
+import path from 'node:path';
+import {speculateFunctionName} from '@remotion/lambda-client';
+import {openBrowser, RenderInternals} from '@remotion/renderer';
+import * as bucketExists from '../../../../lambda-client/src/bucket-exists';
+import * as callLambdaAsync from '../../../../lambda-client/src/call-lambda-async';
+import * as callLambdaStreaming from '../../../../lambda-client/src/call-lambda-streaming';
+import * as callLambdaSync from '../../../../lambda-client/src/call-lambda-sync';
+import * as checkCredentials from '../../../../lambda-client/src/check-credentials';
+import * as createBucket from '../../../../lambda-client/src/create-bucket';
+import * as deleteFile from '../../../../lambda-client/src/delete-file';
+import * as deleteFunction from '../../../../lambda-client/src/delete-function';
+import * as getAccountId from '../../../../lambda-client/src/get-account-id';
+import * as getBuckets from '../../../../lambda-client/src/get-buckets';
+import * as getFunctions from '../../../../lambda-client/src/get-functions';
+import * as getOutputUrl from '../../../../lambda-client/src/get-output-url-from-metadata';
+import * as headFile from '../../../../lambda-client/src/head-file';
+import * as lifecycle from '../../../../lambda-client/src/lifecycle';
+import * as lifecycleRules from '../../../../lambda-client/src/lifecycle-rules';
+import * as listObjects from '../../../../lambda-client/src/list-objects';
+import * as randomHash from '../../../../lambda-client/src/random-hash';
+import * as readFile from '../../../../lambda-client/src/read-file';
+import * as writeFile from '../../../../lambda-client/src/write-file';
+import * as createFunction from '../../api/create-function';
+import * as uploadDir from '../../api/upload-dir';
+import * as browserInstance from '../../functions/get-browser-instance';
+import * as currentFunctionName from '../../functions/helpers/get-current-function-name';
+import * as currentMemorySize from '../../functions/helpers/get-current-memory-size';
+import * as currentRegion from '../../functions/helpers/get-current-region';
+import * as invokeWebhook from '../../functions/invoke-webhook';
+import type {InvokeWebhookParams} from '../../functions/types';
+import * as bundleSite from '../../shared/bundle-site';
+import * as readDir from '../../shared/read-dir';
+import {
+ getMockCallFunctionAsync,
+ getMockCallFunctionStreaming,
+ getMockCallFunctionSync,
+} from './aws-clients';
+import {mockBundleSite} from './mock-bundle-site';
+import {mockCreateFunction} from './mock-create-function';
+import {deleteMockFunction, getAllMockFunctions} from './mock-functions';
+import {mockReadDirectory} from './mock-read-dir';
+import {
+ addMockBucket,
+ getMockBuckets,
+ getS3FilesInBucket,
+ mockBucketExists,
+ mockDeleteS3File,
+ readMockS3File,
+ streamToUint8Array,
+ writeMockS3File,
+} from './mock-store';
+import {mockUploadDir} from './upload-dir';
+
+// Captured before the fakes replace it: render IDs must stay unique.
+const realRandomHash = randomHash.randomHashImplementation;
+const realGenerateRenderId = lifecycle.generateRandomHashWithLifeCycleRule;
+
+const webhookCalls: InvokeWebhookParams[] = [];
+
+export const getWebhookCalls = () => webhookCalls;
+export const resetWebhookCalls = () => {
+ webhookCalls.length = 0;
+};
+
+export type FakeAwsDefaults = {
+ randomHash: typeof randomHash.randomHashImplementation;
+ generateRenderId: typeof lifecycle.generateRandomHashWithLifeCycleRule;
+ getAccountId: typeof getAccountId.getAccountIdImplementation;
+ checkCredentials: typeof checkCredentials.checkCredentials;
+ applyLifeCycle: typeof lifecycleRules.applyLifeCyleOperation;
+ createBucket: typeof createBucket.createBucket;
+ getBuckets: typeof getBuckets.getRemotionBuckets;
+ bucketExists: typeof bucketExists.bucketExistsInRegionImplementation;
+ listObjects: typeof listObjects.lambdaLsImplementation;
+ deleteFile: typeof deleteFile.lambdaDeleteFileImplementation;
+ readFile: typeof readFile.lambdaReadFileImplementation;
+ writeFile: typeof writeFile.lambdaWriteFileImplementation;
+ writeFileIfNotExists: typeof writeFile.lambdaWriteFileIfNotExistsImplementation;
+ supportsConditionalOutput: typeof writeFile.supportsConditionalOutput;
+ headFile: typeof headFile.lambdaHeadFileImplementation;
+ getOutputUrl: typeof getOutputUrl.getOutputUrlFromMetadata;
+ callFunctionAsync: typeof callLambdaAsync.callFunctionAsyncImplementation;
+ callFunctionStreaming: typeof callLambdaStreaming.callFunctionWithStreamingImplementation;
+ callFunctionSync: typeof callLambdaSync.callFunctionSyncImplementation;
+ getFunctions: typeof getFunctions.getFunctions;
+ deleteFunction: typeof deleteFunction.deleteFunction;
+ invokeWebhook: typeof invokeWebhook.invokeWebhook;
+ bundleSite: typeof bundleSite.bundleSite;
+ readDirectory: typeof readDir.readDirectory;
+ uploadDir: typeof uploadDir.uploadDir;
+ createFunction: typeof createFunction.createFunction;
+ getBrowserInstance: typeof browserInstance.getBrowserInstance;
+ forgetBrowserEventLoop: typeof browserInstance.forgetBrowserEventLoop;
+ closeBrowserInstance: typeof browserInstance.closeBrowserInstance;
+ getCurrentRegionInFunction: typeof currentRegion.getCurrentRegionInFunction;
+ getCurrentFunctionName: typeof currentFunctionName.getCurrentFunctionName;
+ getCurrentMemorySizeInMb: typeof currentMemorySize.getCurrentMemorySizeInMb;
+};
+
+export type FakeAwsSpies = {
+ [K in keyof FakeAwsDefaults]: Mock<FakeAwsDefaults[K]>;
+};
+
+export const fakeAwsDefaults: FakeAwsDefaults = {
+ // Deterministic bucket names, but unique render IDs.
+ randomHash: () => 'abcdef',
+ generateRenderId: ({deleteAfter}) =>
+ realGenerateRenderId({deleteAfter, randomHashFn: realRandomHash}),
+ getAccountId: () => Promise.resolve('123456789'),
+ checkCredentials: () => undefined,
+ applyLifeCycle: () => Promise.resolve(),
+ createBucket: (input) => {
+ addMockBucket({
+ region: input.region,
+ creationDate: 0,
+ name: input.bucketName,
+ });
+ return Promise.resolve();
+ },
+ getBuckets: ({region}) =>
+ Promise.resolve(getMockBuckets().filter((b) => b.region === region)),
+ bucketExists: ({bucketName, region}) =>
+ Promise.resolve(mockBucketExists(bucketName, region)),
+ listObjects: (input) => {
+ const files = getS3FilesInBucket({
+ bucketName: input.bucketName,
+ region: input.region,
+ });
+
+ return Promise.resolve(
+ files
+ .filter((p) => p.key.startsWith(input.prefix))
+ .map((file) => ({
+ Key: file.key,
+ ETag: 'etag',
+ LastModified: new Date(0),
+ Size: file.content.byteLength,
+ })),
+ );
+ },
+ deleteFile: ({bucketName, key, region}) => {
+ mockDeleteS3File({bucketName, key, region});
+ return Promise.resolve();
+ },
+ readFile: ({bucketName, key, region}) => {
+ const file = readMockS3File({region, key, bucketName});
+ if (!file) {
+ throw new Error(`no file ${key}`);
+ }
+
+ const tmp = path.join(RenderInternals.tmpDir('justtest'), 'test');
+ writeFileSync(tmp, file.content);
+ return Promise.resolve(createReadStream(tmp));
+ },
+ writeFile: async ({body, bucketName, key, privacy, region}) => {
+ await writeMockS3File({body, bucketName, key, privacy, region});
+ },
+ writeFileIfNotExists: async ({body, bucketName, key, privacy, region}) => {
+ const content = await streamToUint8Array(body);
+ if (readMockS3File({region, bucketName, key})) {
+ throw new Error(
+ `Output file "${key}" in bucket "${bucketName}" already exists.`,
+ );
+ }
+
+ await writeMockS3File({body: content, bucketName, key, privacy, region});
+ },
+ supportsConditionalOutput: () => true,
+ headFile: ({bucketName, key, region}) => {
+ const read = readMockS3File({bucketName, key, region});
+ if (!read) {
+ const err = new Error('File not found');
+ err.name = 'NotFound';
+ throw err;
+ }
+
+ return Promise.resolve({
+ ContentLength: read.content.toString().length,
+ LastModified: new Date(),
+ });
+ },
+ getOutputUrl: () => ({
+ key: 'mock/mock.mp4',
+ url: 'https://s3.mock-region-1.amazonaws.com/bucket/mock.mp4',
+ }),
+ callFunctionAsync: getMockCallFunctionAsync,
+ callFunctionStreaming: getMockCallFunctionStreaming,
+ callFunctionSync: getMockCallFunctionSync,
+ getFunctions: getAllMockFunctions,
+ deleteFunction: deleteMockFunction,
+ invokeWebhook: (params) => {
+ webhookCalls.push(params);
+ return Promise.resolve();
+ },
+ bundleSite: mockBundleSite,
+ readDirectory: mockReadDirectory,
+ uploadDir: mockUploadDir,
+ createFunction: mockCreateFunction,
+ // Bun's WebSocket has no Node socket to ref()/unref(), so the warm-function
+ // browser cache cannot be exercised here. Open a browser per invocation.
+ getBrowserInstance: async ({logLevel}) => {
+ const instance = await openBrowser('chrome', {logLevel});
+ return {instance, configurationString: 'chrome'};
+ },
+ forgetBrowserEventLoop: ({launchedBrowser}) => {
+ launchedBrowser.instance.close({silent: false});
+ },
+ closeBrowserInstance: async ({launchedBrowser}) => {
+ await launchedBrowser.instance.close({silent: true});
+ },
+ // Identity of the simulated Lambda function.
+ getCurrentRegionInFunction: () => 'eu-central-1',
+ getCurrentFunctionName: () =>
+ speculateFunctionName({
+ diskSizeInMb: 10240,
+ memorySizeInMb: 3009,
+ timeoutInSeconds: 120,
+ }),
+ getCurrentMemorySizeInMb: () => 3009,
+};
+
+const makeSpies = (): FakeAwsSpies => ({
+ randomHash: spyOn(randomHash, 'randomHashImplementation'),
+ generateRenderId: spyOn(lifecycle, 'generateRandomHashWithLifeCycleRule'),
+ getAccountId: spyOn(getAccountId, 'getAccountIdImplementation'),
+ checkCredentials: spyOn(checkCredentials, 'checkCredentials'),
+ applyLifeCycle: spyOn(lifecycleRules, 'applyLifeCyleOperation'),
+ createBucket: spyOn(createBucket, 'createBucket'),
+ getBuckets: spyOn(getBuckets, 'getRemotionBuckets'),
+ bucketExists: spyOn(bucketExists, 'bucketExistsInRegionImplementation'),
+ listObjects: spyOn(listObjects, 'lambdaLsImplementation'),
+ deleteFile: spyOn(deleteFile, 'lambdaDeleteFileImplementation'),
+ readFile: spyOn(readFile, 'lambdaReadFileImplementation'),
+ writeFile: spyOn(writeFile, 'lambdaWriteFileImplementation'),
+ writeFileIfNotExists: spyOn(
+ writeFile,
+ 'lambdaWriteFileIfNotExistsImplementation',
+ ),
+ supportsConditionalOutput: spyOn(writeFile, 'supportsConditionalOutput'),
+ headFile: spyOn(headFile, 'lambdaHeadFileImplementation'),
+ getOutputUrl: spyOn(getOutputUrl, 'getOutputUrlFromMetadata'),
+ callFunctionAsync: spyOn(callLambdaAsync, 'callFunctionAsyncImplementation'),
+ callFunctionStreaming: spyOn(
+ callLambdaStreaming,
+ 'callFunctionWithStreamingImplementation',
+ ),
+ callFunctionSync: spyOn(callLambdaSync, 'callFunctionSyncImplementation'),
+ getFunctions: spyOn(getFunctions, 'getFunctions'),
+ deleteFunction: spyOn(deleteFunction, 'deleteFunction'),
+ invokeWebhook: spyOn(invokeWebhook, 'invokeWebhook'),
+ bundleSite: spyOn(bundleSite, 'bundleSite'),
+ readDirectory: spyOn(readDir, 'readDirectory'),
+ uploadDir: spyOn(uploadDir, 'uploadDir'),
+ createFunction: spyOn(createFunction, 'createFunction'),
+ getBrowserInstance: spyOn(browserInstance, 'getBrowserInstance'),
+ forgetBrowserEventLoop: spyOn(browserInstance, 'forgetBrowserEventLoop'),
+ closeBrowserInstance: spyOn(browserInstance, 'closeBrowserInstance'),
+ getCurrentRegionInFunction: spyOn(
+ currentRegion,
+ 'getCurrentRegionInFunction',
+ ),
+ getCurrentFunctionName: spyOn(currentFunctionName, 'getCurrentFunctionName'),
+ getCurrentMemorySizeInMb: spyOn(
+ currentMemorySize,
+ 'getCurrentMemorySizeInMb',
+ ),
+});
+
+let spies: FakeAwsSpies | null = null;
+
+export const resetFakeAws = () => {
+ if (!spies) {
+ return;
+ }
+
+ for (const key of Object.keys(spies) as (keyof FakeAwsSpies)[]) {
+ spies[key].mockImplementation(fakeAwsDefaults[key] as never);
+ }
+};
+
+export const installFakeAws = () => {
+ if (spies) {
+ return;
+ }
+
+ spies = makeSpies();
+ resetFakeAws();
+};
+
+export const uninstallFakeAws = () => {
+ if (!spies) {
+ return;
+ }
+
+ for (const spy of Object.values(spies)) {
+ spy.mockRestore();
+ }
+
+ spies = null;
+};
+
+export const fakeAws = (): FakeAwsSpies => {
+ if (!spies) {
+ throw new Error('Call useFakeAws() at the top of the test file first');
+ }
+
+ return spies;
+};
+
+export const useFakeAws = () => {
+ beforeAll(installFakeAws);
+ afterEach(resetFakeAws);
+ afterAll(uninstallFakeAws);
+};
diff --git a/packages/lambda/src/test/mocks/mock-create-function.ts b/packages/lambda/src/test/mocks/mock-create-function.ts
index 502510d219..e70f68df17 100644
--- a/packages/lambda/src/test/mocks/mock-create-function.ts
+++ b/packages/lambda/src/test/mocks/mock-create-function.ts
@@ -1,5 +1,5 @@
import {VERSION} from 'remotion/version';
-import type {CreateFunction} from '../../functions/provider-implementation';
+import type {CreateFunction} from '../../functions/types';
import {addFunction} from './mock-functions';
type MockCreateFunctionCall = {
diff --git a/packages/lambda/src/test/mocks/mock-implementation.ts b/packages/lambda/src/test/mocks/mock-implementation.ts
deleted file mode 100644
index f5f92bf474..0000000000
--- a/packages/lambda/src/test/mocks/mock-implementation.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import {createReadStream, writeFileSync} from 'fs';
-import path from 'path';
-import {
- LambdaClientInternals,
- estimatePrice,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
-import {REMOTION_BUCKET_PREFIX} from '@remotion/lambda-client/constants';
-import {RenderInternals} from '@remotion/renderer';
-import {
- getMockCallFunctionAsync,
- getMockCallFunctionStreaming,
- getMockCallFunctionSync,
-} from './aws-clients';
-import {deleteMockFunction, getAllMockFunctions} from './mock-functions';
-import {
- addMockBucket,
- getMockBuckets,
- getS3FilesInBucket,
- mockBucketExists,
- mockDeleteS3File,
- readMockS3File,
- streamToUint8Array,
- writeMockS3File,
-} from './mock-store';
-
-export const mockImplementation: ProviderSpecifics = {
- getAccountId: () =>
- Promise.resolve('aws:iam::123456789'.match(/aws:iam::([0-9]+)/)?.[1]!),
- getMaxNonInlinePayloadSizePerFunction: () => 200_000,
- getMaxStillInlinePayloadSize() {
- return 5_000_000;
- },
- serverStorageProductName: () => 'file system',
- applyLifeCycle: () => Promise.resolve(),
- getChromiumPath() {
- return null;
- },
- 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,
- createBucket: (input) => {
- addMockBucket({
- region: input.region,
- creationDate: 0,
- name: input.bucketName,
- });
- return Promise.resolve();
- },
- getBuckets: ({region}) =>
- Promise.resolve(getMockBuckets().filter((b) => b.region === region)),
- listObjects: (input) => {
- if (!input) {
- throw new Error('need to pass input');
- }
-
- const files = getS3FilesInBucket({
- bucketName: input.bucketName,
- region: input.region,
- });
-
- return Promise.resolve(
- files
- .filter((p) => p.key.startsWith(input.prefix))
- .map((file) => {
- const size = file.content.byteLength;
- return {
- Key: file.key,
- ETag: 'etag',
- LastModified: new Date(0),
- Owner: undefined,
- Size: size,
- StorageClass: undefined,
- };
- }),
- );
- },
- deleteFile: ({bucketName, key, region}) => {
- mockDeleteS3File({
- bucketName,
- key,
- region,
- });
- return Promise.resolve();
- },
- bucketExists: ({bucketName, region}) => {
- return Promise.resolve(mockBucketExists(bucketName, region));
- },
- randomHash: () => 'abcdef',
- readFile: ({bucketName, key, region}) => {
- const file = readMockS3File({region, key, bucketName});
- if (!file) {
- throw new Error(`no file ${key}`);
- }
-
- const tmp = path.join(RenderInternals.tmpDir('justtest'), 'test');
- writeFileSync(tmp, file.content);
- return Promise.resolve(createReadStream(tmp));
- },
- writeFile: async ({body, bucketName, key, privacy, region}) => {
- await writeMockS3File({
- body,
- bucketName,
- key,
- privacy,
- region,
- });
- return Promise.resolve(undefined);
- },
- supportsConditionalOutput: () => true,
- writeFileIfNotExists: async ({body, bucketName, key, privacy, region}) => {
- const content = await streamToUint8Array(body);
- if (readMockS3File({region, bucketName, key})) {
- throw new Error(
- `Output file "${key}" in bucket "${bucketName}" already exists.`,
- );
- }
-
- await writeMockS3File({body: content, bucketName, key, privacy, region});
- },
- headFile: ({bucketName, key, region}) => {
- const read = readMockS3File({
- bucketName,
- key,
- region,
- });
- if (!read) {
- const err = new Error('File not found');
- err.name = 'NotFound';
- throw err;
- }
-
- return Promise.resolve({
- ContentLength: read.content.toString().length,
- LastModified: new Date(),
- });
- },
- convertToServeUrl: LambdaClientInternals.convertToServeUrlImplementation,
- printLoggingHelper: false,
- validateDeleteAfter: () => {},
- callFunctionAsync: getMockCallFunctionAsync,
- callFunctionStreaming: getMockCallFunctionStreaming,
- callFunctionSync: getMockCallFunctionSync,
- estimatePrice,
- getOutputUrl: () => {
- return {
- key: 'mock/mock.mp4',
- url: 'https://s3.mock-region-1.amazonaws.com/bucket/mock.mp4',
- };
- },
- isFlakyError: LambdaClientInternals.isFlakyError,
- deleteFunction: deleteMockFunction,
- getFunctions: getAllMockFunctions,
- parseFunctionName: LambdaClientInternals.parseFunctionName,
- checkCredentials: () => Promise.resolve(),
- getBucketPrefix: () => REMOTION_BUCKET_PREFIX,
-};
diff --git a/packages/lambda/src/test/preload.ts b/packages/lambda/src/test/preload.ts
new file mode 100644
index 0000000000..bfaf7c488d
--- /dev/null
+++ b/packages/lambda/src/test/preload.ts
@@ -0,0 +1,23 @@
+import {mock} from 'bun:test';
+import path from 'node:path';
+
+// @remotion/lambda-client ships as a single bundle. Resolve it to its sources
+// in tests so that individual AWS operations (S3, Lambda invocations, ...) can
+// be replaced with in-memory fakes, see ./mocks/fake-aws.ts.
+const clientSrc = path.resolve(__dirname, '../../../lambda-client/src');
+
+mock.module('@remotion/lambda-client', () =>
+ require(path.join(clientSrc, 'index.ts')),
+);
+mock.module('@remotion/lambda-client/constants', () =>
+ require(path.join(clientSrc, 'constants.ts')),
+);
+mock.module('@remotion/lambda-client/regions', () =>
+ require(path.join(clientSrc, 'regions.ts')),
+);
+
+// @remotion/lambda runs on Node and loads the CommonJS build of
+// @remotion/renderer. Use the same build in tests: the ESM bundle has
+// environment checks (NODE_ENV) inlined at build time.
+const rendererCjs = require.resolve('@remotion/renderer');
+mock.module('@remotion/renderer', () => require(rendererCjs));
diff --git a/packages/lambda/src/test/unit/best-bucketnames.test.ts b/packages/lambda/src/test/unit/best-bucketnames.test.ts
index b9675cf6d4..47f859bc07 100644
--- a/packages/lambda/src/test/unit/best-bucketnames.test.ts
+++ b/packages/lambda/src/test/unit/best-bucketnames.test.ts
@@ -1,12 +1,11 @@
import {expect, test} from 'bun:test';
import {LambdaClientInternals} from '@remotion/lambda-client';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {useFakeAws} from '../mocks/fake-aws';
+
+useFakeAws();
test('Generate and parse bucket names correctly', () => {
- const name = LambdaClientInternals.makeBucketName(
- 'us-east-1',
- mockImplementation,
- );
+ const name = LambdaClientInternals.makeBucketName('us-east-1');
expect(name).toBe('remotionlambda-useast1-abcdef');
const parsed = LambdaClientInternals.parseBucketName(name);
diff --git a/packages/lambda/src/test/unit/cancellation-polling.test.ts b/packages/lambda/src/test/unit/cancellation-polling.test.ts
index 4a516dab2b..6de5cbb686 100644
--- a/packages/lambda/src/test/unit/cancellation-polling.test.ts
+++ b/packages/lambda/src/test/unit/cancellation-polling.test.ts
@@ -1,31 +1,37 @@
-import {expect, test} from 'bun:test';
-import {
- LambdaClientInternals,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {afterEach, expect, spyOn, test} from 'bun:test';
+import {LambdaClientInternals} from '@remotion/lambda-client';
+import * as headFile from '../../../../lambda-client/src/head-file';
import {startCancellationPolling} from '../../functions/cancellation-polling';
+const spies: {mockRestore: () => void}[] = [];
+
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
+
test('polls until the cancellation signal exists', async () => {
let checks = 0;
+ spies.push(
+ spyOn(headFile, 'lambdaHeadFileImplementation').mockImplementation(
+ ({key}) => {
+ expect(key).toBe(LambdaClientInternals.cancellationKey('render-id'));
+ checks++;
+ if (checks === 1) {
+ const error = new Error('Missing');
+ error.name = 'NotFound';
+ return Promise.reject(error);
+ }
+
+ return Promise.resolve({});
+ },
+ ),
+ );
let stop: () => void = () => undefined;
const cancelled = new Promise<void>((resolve) => {
stop = startCancellationPolling({
bucketName: 'bucket',
renderId: 'render-id',
region: 'eu-central-1',
- providerSpecifics: {
- headFile: (({key}) => {
- expect(key).toBe(LambdaClientInternals.cancellationKey('render-id'));
- checks++;
- if (checks === 1) {
- const error = new Error('Missing');
- error.name = 'NotFound';
- return Promise.reject(error);
- }
-
- return Promise.resolve({});
- }) as ProviderSpecifics['headFile'],
- } as unknown as ProviderSpecifics,
forcePathStyle: false,
intervalInMilliseconds: 1,
logLevel: 'error',
diff --git a/packages/lambda/src/test/unit/get-etag.test.ts b/packages/lambda/src/test/unit/get-etag.test.ts
index 365dfbe2f2..0feb37ee98 100644
--- a/packages/lambda/src/test/unit/get-etag.test.ts
+++ b/packages/lambda/src/test/unit/get-etag.test.ts
@@ -3,11 +3,9 @@ import {mkdtemp, rm, truncate, writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import type {_Object} from '@aws-sdk/client-s3';
-import type {FullClientSpecifics} from '../../functions/provider-implementation';
import {getEtagOfFile} from '../../shared/get-etag';
import {getS3DiffOperations} from '../../shared/get-s3-operations';
import {multipartUploadPartSize} from '../../shared/multipart-upload-part-size';
-import {readDirectory} from '../../shared/read-dir';
let temporaryDirectory: string | null = null;
@@ -43,7 +41,6 @@ test('recognizes an unchanged file above the multipart part-size boundary', asyn
bundle: temporaryDirectory as string,
prefix: 'sites/test',
onProgress: () => undefined,
- fullClientSpecifics: {readDirectory} as FullClientSpecifics,
});
expect(operations).toEqual({
diff --git a/packages/lambda/src/test/unit/handlers.test.ts b/packages/lambda/src/test/unit/handlers.test.ts
index 6a7a172979..0aa6168435 100644
--- a/packages/lambda/src/test/unit/handlers.test.ts
+++ b/packages/lambda/src/test/unit/handlers.test.ts
@@ -1,9 +1,14 @@
import {expect, test} from 'bun:test';
-import {ServerlessRoutines} from '@remotion/lambda-client';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {
+ LambdaClientInternals,
+ ServerlessRoutines,
+} from '@remotion/lambda-client';
+import {useFakeAws} from '../mocks/fake-aws';
+
+useFakeAws();
test('Info handler should return version', async () => {
- const response = await mockImplementation.callFunctionSync({
+ const response = await LambdaClientInternals.callFunctionSyncImplementation({
type: ServerlessRoutines.info,
payload: {
logLevel: 'info',
diff --git a/packages/lambda/src/test/unit/inner-routine.test.ts b/packages/lambda/src/test/unit/inner-routine.test.ts
index 354f0234f4..beed2a084f 100644
--- a/packages/lambda/src/test/unit/inner-routine.test.ts
+++ b/packages/lambda/src/test/unit/inner-routine.test.ts
@@ -1,13 +1,20 @@
-import {expect, test} from 'bun:test';
+import {afterEach, expect, spyOn, test} from 'bun:test';
import {Readable} from 'node:stream';
-import {
- ServerlessRoutines,
- type ProviderSpecifics,
-} from '@remotion/lambda-client';
+import {ServerlessRoutines} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
+import * as lifecycle from '../../../../lambda-client/src/lifecycle';
+import * as readFile from '../../../../lambda-client/src/read-file';
+import * as currentFunctionName from '../../functions/helpers/get-current-function-name';
+import * as currentMemorySize from '../../functions/helpers/get-current-memory-size';
+import * as currentRegion from '../../functions/helpers/get-current-region';
import {innerHandler, innerRoutine} from '../../functions/inner-routine';
import {makeInitialOverallRenderProgress} from '../../functions/overall-render-progress';
-import type {InsideFunctionSpecifics} from '../../functions/provider-implementation';
+
+const spies: {mockRestore: () => void}[] = [];
+
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
test('progress works without AWS context or a bucket owner', async () => {
const previousFlag = process.env.__RESERVED_IS_INSIDE_REMOTION_LAMBDA;
@@ -15,6 +22,29 @@ test('progress works without AWS context or a bucket owner', async () => {
const chunks: Uint8Array[] = [];
let ended = false;
const reads: Array<string | null> = [];
+ spies.push(
+ spyOn(readFile, 'lambdaReadFileImplementation').mockImplementation(
+ ({expectedBucketOwner}) => {
+ reads.push(expectedBucketOwner);
+ return Promise.resolve(
+ Readable.from([
+ Buffer.from(
+ JSON.stringify(
+ makeInitialOverallRenderProgress(Date.now() + 120_000, false),
+ ),
+ ),
+ ]),
+ );
+ },
+ ),
+ spyOn(currentRegion, 'getCurrentRegionInFunction').mockReturnValue(
+ 'eu-central-1',
+ ),
+ spyOn(currentMemorySize, 'getCurrentMemorySizeInMb').mockReturnValue(2048),
+ spyOn(currentFunctionName, 'getCurrentFunctionName').mockReturnValue(
+ 'render-worker',
+ ),
+ );
try {
await innerHandler({
@@ -42,28 +72,6 @@ test('progress works without AWS context or a bucket owner', async () => {
return Promise.resolve();
},
},
- providerSpecifics: {
- printLoggingHelper: false,
- getBillingCurrency: () => 'USD',
- readFile: ({expectedBucketOwner}) => {
- reads.push(expectedBucketOwner);
- return Promise.resolve(
- Readable.from([
- Buffer.from(
- JSON.stringify(
- makeInitialOverallRenderProgress(Date.now() + 120_000, false),
- ),
- ),
- ]),
- );
- },
- } as Partial<ProviderSpecifics> as ProviderSpecifics,
- insideFunctionSpecifics: {
- deleteTmpDir: () => Promise.resolve(),
- getCurrentRegionInFunction: () => 'eu-central-1',
- getCurrentMemorySizeInMb: () => 2048,
- getCurrentFunctionName: () => 'render-worker',
- } as unknown as InsideFunctionSpecifics,
});
expect(ended).toBe(true);
@@ -115,16 +123,6 @@ test('buffered still errors are written to the response', async () => {
expectedBucketOwner: null,
getRemainingTimeInMillis: () => 120_000,
},
- providerSpecifics: {
- isFlakyError: () => false,
- printLoggingHelper: false,
- randomHash: () => 'random-hash',
- validateDeleteAfter: () => undefined,
- } as unknown as ProviderSpecifics,
- insideFunctionSpecifics: {
- deleteTmpDir: () => Promise.resolve(),
- generateRandomId: () => 'render-id',
- } as unknown as InsideFunctionSpecifics,
});
expect(ended).toBe(true);
@@ -146,6 +144,13 @@ test('buffered still errors are written to the response', async () => {
test('buffered render start exceptions are written to the response', async () => {
const chunks: Uint8Array[] = [];
let ended = false;
+ spies.push(
+ spyOn(lifecycle, 'generateRandomHashWithLifeCycleRule').mockImplementation(
+ () => {
+ throw new Error('Could not generate a render ID');
+ },
+ ),
+ );
await innerRoutine({
params: {
@@ -170,16 +175,6 @@ test('buffered render start exceptions are written to the response', async () =>
expectedBucketOwner: null,
getRemainingTimeInMillis: () => 120_000,
},
- providerSpecifics: {
- printLoggingHelper: false,
- randomHash: () => 'random-hash',
- } as unknown as ProviderSpecifics,
- insideFunctionSpecifics: {
- deleteTmpDir: () => Promise.resolve(),
- generateRandomId: () => {
- throw new Error('Could not generate a render ID');
- },
- } as unknown as InsideFunctionSpecifics,
});
expect(ended).toBe(true);
diff --git a/packages/lambda/src/test/unit/output-access-error-identity.test.ts b/packages/lambda/src/test/unit/output-access-error-identity.test.ts
index 36de8d8540..10463f45ac 100644
--- a/packages/lambda/src/test/unit/output-access-error-identity.test.ts
+++ b/packages/lambda/src/test/unit/output-access-error-identity.test.ts
@@ -1,4 +1,12 @@
-import {expect, mock, spyOn, test} from 'bun:test';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ expect,
+ mock,
+ spyOn,
+ test,
+} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -8,17 +16,25 @@ import {
OutputFileAccessDeniedError,
ServerlessRoutines,
type OverallRenderProgress,
- type ProviderSpecifics,
type RenderMetadata,
type ServerlessPayloads,
} from '@remotion/lambda-client';
import {RenderInternals} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
+import * as headFileModule from '../../../../lambda-client/src/head-file';
+import * as readFileModule from '../../../../lambda-client/src/read-file';
+import * as writeFileModule from '../../../../lambda-client/src/write-file';
+import * as browserInstance from '../../functions/get-browser-instance';
import {launchHandler} from '../../functions/handlers/launch';
import {progressHandler} from '../../functions/handlers/progress';
-import type {InsideFunctionSpecifics} from '../../functions/provider-implementation';
+import * as currentFunctionName from '../../functions/helpers/get-current-function-name';
+import * as currentMemorySize from '../../functions/helpers/get-current-memory-size';
+import * as currentRegion from '../../functions/helpers/get-current-region';
import * as directRenderer from '../../functions/render-with-single-function';
+// The real implementation is needed to produce normalized storage errors.
+const realHeadFile = headFileModule.lambdaHeadFileImplementation;
+
const region = 'us-east-1';
const renderId = 'output-access-test';
const bucketName = 'render-bucket';
@@ -84,15 +100,32 @@ const params: ServerlessPayloads['launch'] = {
sampleRate: 48000,
};
-const insideFunctionSpecifics = {
- getCurrentRegionInFunction: () => region,
- getCurrentMemorySizeInMb: () => 2048,
- getCurrentFunctionName: () => 'render-worker',
- getBrowserInstance: () => Promise.resolve({instance: {}}),
- forgetBrowserEventLoop: () => undefined,
- timer: () => ({end: () => undefined}),
- normalizeChromiumOptions: null,
-} as unknown as InsideFunctionSpecifics;
+const runtimeSpies: {mockRestore: () => void}[] = [];
+const fixtureSpies: {mockRestore: () => void}[] = [];
+
+beforeAll(() => {
+ runtimeSpies.push(
+ spyOn(currentRegion, 'getCurrentRegionInFunction').mockReturnValue(region),
+ spyOn(currentMemorySize, 'getCurrentMemorySizeInMb').mockReturnValue(2048),
+ spyOn(currentFunctionName, 'getCurrentFunctionName').mockReturnValue(
+ 'render-worker',
+ ),
+ spyOn(browserInstance, 'getBrowserInstance').mockImplementation(() =>
+ Promise.resolve({instance: {}} as never),
+ ),
+ spyOn(browserInstance, 'forgetBrowserEventLoop').mockImplementation(
+ () => undefined,
+ ),
+ );
+});
+
+afterAll(() => {
+ runtimeSpies.splice(0).forEach((spy) => spy.mockRestore());
+});
+
+afterEach(() => {
+ fixtureSpies.splice(0).forEach((spy) => spy.mockRestore());
+});
const makeFixture = (headError: unknown) => {
let storedProgress: OverallRenderProgress | null = null;
@@ -126,24 +159,29 @@ const makeFixture = (headError: unknown) => {
storedProgress = JSON.parse(body as string);
},
);
- const providerSpecifics: ProviderSpecifics = {
- ...LambdaClientInternals.awsImplementation,
- headFile,
- writeFile,
- writeFileIfNotExists,
- supportsConditionalOutput: () => true,
- readFile: () =>
- Promise.resolve(
- Readable.from([Buffer.from(JSON.stringify(storedProgress))]),
- ),
- getChromiumPath: () => null,
- estimatePrice: () => 0,
- parseFunctionName: () => null,
- getEphemeralStorageForPriceCalculation: () => 512,
- getBillingCurrency: () => 'USD',
- } satisfies ProviderSpecifics;
+ fixtureSpies.splice(0).forEach((spy) => spy.mockRestore());
+ fixtureSpies.push(
+ spyOn(headFileModule, 'lambdaHeadFileImplementation').mockImplementation(
+ headFile,
+ ),
+ spyOn(writeFileModule, 'lambdaWriteFileImplementation').mockImplementation(
+ writeFile,
+ ),
+ spyOn(
+ writeFileModule,
+ 'lambdaWriteFileIfNotExistsImplementation',
+ ).mockImplementation(writeFileIfNotExists),
+ spyOn(writeFileModule, 'supportsConditionalOutput').mockImplementation(
+ () => true,
+ ),
+ spyOn(readFileModule, 'lambdaReadFileImplementation').mockImplementation(
+ () =>
+ Promise.resolve(
+ Readable.from([Buffer.from(JSON.stringify(storedProgress))]),
+ ),
+ ),
+ );
return {
- providerSpecifics,
headFile,
writeFile,
writeFileIfNotExists,
@@ -173,7 +211,7 @@ const getBundledHeadError = async (httpStatusCode: number) => {
Promise.reject(sdkError),
);
try {
- await LambdaClientInternals.awsImplementation.headFile({
+ await realHeadFile({
...input,
bucketName: destination,
key: 'output.mp4',
@@ -199,13 +237,11 @@ const getBundledHeadError = async (httpStatusCode: number) => {
};
const invokeLaunch = (
- fixture: ReturnType<typeof makeFixture>,
+ _fixture: ReturnType<typeof makeFixture>,
overwrite = false,
) =>
launchHandler({
params: {...params, overwrite},
- providerSpecifics: fixture.providerSpecifics,
- insideFunctionSpecifics,
options: {
expectedBucketOwner: null,
getRemainingTimeInMillis: () => 120000,
@@ -282,7 +318,7 @@ const completedProgress = (): OverallRenderProgress => {
};
const invokeProgress = (
- fixture: ReturnType<typeof makeFixture>,
+ _fixture: ReturnType<typeof makeFixture>,
timeoutInMilliseconds = 120000,
) =>
progressHandler({
@@ -299,8 +335,6 @@ const invokeProgress = (
expectedBucketOwner: null,
timeoutInMilliseconds,
retriesRemaining: 0,
- providerSpecifics: fixture.providerSpecifics,
- insideFunctionSpecifics,
},
});
@@ -389,17 +423,15 @@ test.each(['normalized', 'constructed'] as const)(
),
).toBe(true);
- for (const conditionalSupport of [false, true]) {
- const unsupported = makeFixture(error);
- unsupported.providerSpecifics.supportsConditionalOutput = () =>
- conditionalSupport;
- if (conditionalSupport) {
- unsupported.providerSpecifics.writeFileIfNotExists = null;
- }
-
- await expect(invokeLaunch(unsupported)).rejects.toBe(error);
- expect(unsupported.writeFileIfNotExists).not.toHaveBeenCalled();
- }
+ // Destinations without conditional uploads keep denied reads fatal.
+ const unsupported = makeFixture(error);
+ fixtureSpies.push(
+ spyOn(writeFileModule, 'supportsConditionalOutput').mockImplementation(
+ () => false,
+ ),
+ );
+ await expect(invokeLaunch(unsupported)).rejects.toBe(error);
+ expect(unsupported.writeFileIfNotExists).not.toHaveBeenCalled();
for (const unrelated of [
await getBundledHeadError(500),
diff --git a/packages/lambda/src/test/unit/overall-render-progress.test.ts b/packages/lambda/src/test/unit/overall-render-progress.test.ts
index 2dbe415a6c..a835d64904 100644
--- a/packages/lambda/src/test/unit/overall-render-progress.test.ts
+++ b/packages/lambda/src/test/unit/overall-render-progress.test.ts
@@ -1,56 +1,11 @@
-import {expect, test} from 'bun:test';
-import type {PostRenderData, ProviderSpecifics} from '@remotion/lambda-client';
+import {expect, spyOn, test} from 'bun:test';
+import type {PostRenderData} from '@remotion/lambda-client';
+import * as writeFile from '../../../../lambda-client/src/write-file';
import {
makeInitialOverallRenderProgress,
makeOverallRenderProgress,
} from '../../functions/overall-render-progress';
-const makeProviderSpecifics = ({
- writeFile,
-}: {
- writeFile: ProviderSpecifics['writeFile'];
-}): ProviderSpecifics => {
- return {
- applyLifeCycle: () => Promise.resolve(),
- bucketExists: () => Promise.resolve(true),
- callFunctionAsync: () => Promise.resolve(),
- callFunctionStreaming: () => Promise.resolve(),
- callFunctionSync: () => Promise.reject(new Error('Not implemented')),
- checkCredentials: () => undefined,
- convertToServeUrl: () => 'serve-url',
- createBucket: () => Promise.resolve(),
- deleteFile: () => Promise.resolve(),
- deleteFunction: () => Promise.resolve(),
- estimatePrice: () => 0,
- getAccountId: () => Promise.resolve('123456789012'),
- getBucketPrefix: () => 'remotionlambda-',
- getBuckets: () => Promise.resolve([]),
- getChromiumPath: () => null,
- getEphemeralStorageForPriceCalculation: () => 512,
- getBillingCurrency: () => 'USD',
- getRendererFunctionTransport: () => 'response-streaming',
- getServiceDnsSuffix: () => 'example.com',
- getFunctions: () => Promise.resolve([]),
- getLoggingUrlForMethod: () => 'logs',
- getLoggingUrlForRendererFunction: () => 'logs',
- getMaxNonInlinePayloadSizePerFunction: () => 0,
- getMaxStillInlinePayloadSize: () => 0,
- getOutputUrl: () => ({key: 'out.mp4', url: 'https://example.com/out.mp4'}),
- headFile: () => Promise.resolve({}),
- isFlakyError: () => false,
- listObjects: () => Promise.resolve([]),
- parseFunctionName: () => null,
- printLoggingHelper: false,
- randomHash: () => 'hash',
- readFile: () => Promise.reject(new Error('Not implemented')),
- serverStorageProductName: () => 'S3',
- validateDeleteAfter: () => undefined,
- writeFile,
- supportsConditionalOutput: () => true,
- writeFileIfNotExists: null,
- };
-};
-
const postRenderData: PostRenderData = {
separateAudio: null,
artifactProgress: [],
@@ -88,16 +43,17 @@ test('stores whether cancellation is enabled', () => {
test('setPostRenderData retries transient progress upload failures', async () => {
let attempts = 0;
let persistedBody: string | null = null;
- const providerSpecifics = makeProviderSpecifics({
- writeFile: ({body}) => {
- attempts++;
- if (attempts < 3) {
- return Promise.reject(new Error('Temporary progress upload failure'));
- }
+ const write = spyOn(
+ writeFile,
+ 'lambdaWriteFileImplementation',
+ ).mockImplementation(({body}) => {
+ attempts++;
+ if (attempts < 3) {
+ return Promise.reject(new Error('Temporary progress upload failure'));
+ }
- persistedBody = String(body);
- return Promise.resolve();
- },
+ persistedBody = String(body);
+ return Promise.resolve();
});
const overallProgress = makeOverallRenderProgress({
cancellationEnabled: false,
@@ -105,13 +61,16 @@ test('setPostRenderData retries transient progress upload failures', async () =>
expectedBucketOwner: '123456789012',
forcePathStyle: false,
logLevel: 'error',
- providerSpecifics,
region: 'eu-central-1',
renderId: 'render-id',
timeoutTimestamp: 1,
});
- await overallProgress.setPostRenderData(postRenderData);
+ try {
+ await overallProgress.setPostRenderData(postRenderData);
+ } finally {
+ write.mockRestore();
+ }
expect(attempts).toBe(3);
if (persistedBody === null) {
diff --git a/packages/lambda/src/test/unit/renderer-lifecycle.test.ts b/packages/lambda/src/test/unit/renderer-lifecycle.test.ts
index fb0af8507a..35cf592040 100644
--- a/packages/lambda/src/test/unit/renderer-lifecycle.test.ts
+++ b/packages/lambda/src/test/unit/renderer-lifecycle.test.ts
@@ -1,20 +1,25 @@
-import {expect, mock, spyOn, test} from 'bun:test';
+import {afterEach, expect, mock, spyOn, test} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import type {
- ProviderSpecifics,
- StreamingPayload,
-} from '@remotion/lambda-client';
+import type {StreamingPayload} from '@remotion/lambda-client';
import {RenderInternals} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
-import {
- closeBrowserInstanceImplementation,
- getBrowserInstanceImplementation,
-} from '../../functions/get-browser-instance';
+import * as isFlakyError from '../../../../lambda-client/src/is-flaky-error';
+import * as browserInstance from '../../functions/get-browser-instance';
import type {LaunchedBrowser} from '../../functions/get-browser-instance';
import {rendererHandler} from '../../functions/handlers/renderer';
-import type {InsideFunctionSpecifics} from '../../functions/provider-implementation';
+import * as chromiumPath from '../../functions/helpers/get-chromium-path';
+import * as currentRegion from '../../functions/helpers/get-current-region';
+import * as getTmpDir from '../../functions/helpers/get-tmp-dir';
+
+const spies: {mockRestore: () => void}[] = [];
+// Captured before any spy replaces the live bindings.
+const {closeBrowserInstance, getBrowserInstance} = browserInstance;
+
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
// Next.js declares process.env.NODE_ENV as readonly; the handlers branch on it.
const setNodeEnv = (value: string | undefined) => {
@@ -37,7 +42,6 @@ test.each(['browser launch', 'Chromium path lookup'] as const)(
fs.mkdtempSync(path.join(testRoot, 'render-')),
);
const launchError = new Error(`Failed ${failure}`);
- const diagnostics: string[] = [];
const tmpDirState = {
files: [{filename: 'provider-cache', size: 123}],
total: 123,
@@ -61,10 +65,38 @@ test.each(['browser launch', 'Chromium path lookup'] as const)(
slowestFrames: [],
} as never);
const onMediaFiles = mock(() => Promise.resolve());
- const forgetBrowserEventLoop = mock(() => undefined);
let launchedBrowser: LaunchedBrowser | null = null;
const scheduledCallbacks: Array<() => void> = [];
let currentInvocation = 'A';
+ const forgetBrowserEventLoop = spyOn(
+ browserInstance,
+ 'forgetBrowserEventLoop',
+ ).mockImplementation(() => undefined);
+ spies.push(
+ forgetBrowserEventLoop,
+ spyOn(isFlakyError, 'isFlakyError').mockImplementation(
+ (err) => err === launchError,
+ ),
+ spyOn(chromiumPath, 'getChromiumPath').mockImplementation(() => {
+ if (failure === 'Chromium path lookup' && currentInvocation === 'A') {
+ throw launchError;
+ }
+
+ return '/mock-chrome';
+ }),
+ spyOn(getTmpDir, 'getTmpDirStateIfENoSp').mockImplementation(
+ () => tmpDirState,
+ ),
+ spyOn(currentRegion, 'getCurrentRegionInFunction').mockReturnValue(
+ 'eu-central-1',
+ ),
+ spyOn(browserInstance, 'getBrowserInstance').mockImplementation(
+ async (options) => {
+ launchedBrowser = await getBrowserInstance(options);
+ return launchedBrowser;
+ },
+ ),
+ );
const exits: string[] = [];
const timeoutSpy = spyOn(globalThis, 'setTimeout').mockImplementation(((
callback: (...args: never[]) => void,
@@ -107,42 +139,11 @@ test.each(['browser launch', 'Chromium path lookup'] as const)(
streamedMessages.push(message);
return Promise.resolve();
},
- providerSpecifics: {
- isFlakyError: (err: Error) => err === launchError,
- getChromiumPath: () => {
- if (
- failure === 'Chromium path lookup' &&
- currentInvocation === 'A'
- ) {
- throw launchError;
- }
-
- return '/mock-chrome';
- },
- } as unknown as ProviderSpecifics,
requestContext: {
requestId: currentInvocation,
expectedBucketOwner: null,
getRemainingTimeInMillis: () => 120_000,
},
- insideFunctionSpecifics: {
- normalizeChromiumOptions: null,
- getTmpDirState: () => tmpDirState,
- startRendererDiagnostics: (requestId) => {
- diagnostics.push(`start-${requestId}`);
- return () => {
- diagnostics.push(`end-${requestId}`);
- };
- },
- getCurrentRegionInFunction: () => 'eu-central-1',
- getBrowserInstance: async (options) => {
- launchedBrowser = await getBrowserInstanceImplementation(options);
- return launchedBrowser;
- },
- closeBrowserInstance: closeBrowserInstanceImplementation,
- forgetBrowserEventLoop,
- timer: () => ({end: () => undefined}),
- } satisfies Partial<InsideFunctionSpecifics> as unknown as InsideFunctionSpecifics,
onMediaFiles,
executionMode: 'invoked',
});
@@ -170,24 +171,26 @@ test.each(['browser launch', 'Chromium path lookup'] as const)(
failure === 'browser launch' ? 2 : 1,
);
expect(renderMediaSpy).toHaveBeenCalledTimes(1);
- for (const spy of [openBrowserSpy, renderMediaSpy]) {
- expect(spy).toHaveBeenLastCalledWith(
- expect.objectContaining({
- chromiumOptions: expect.objectContaining({
- gl: 'angle',
- enableMultiProcessOnLinux: true,
- }),
+ // Lambda renders with software GL in a single browser process.
+ expect(openBrowserSpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ chromiumOptions: expect.objectContaining({
+ gl: 'swangle',
+ enableMultiProcessOnLinux: false,
}),
- );
- }
-
- expect(diagnostics).toEqual(['start-A', 'end-A', 'start-B', 'end-B']);
+ }),
+ );
+ expect(renderMediaSpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ chromiumOptions: expect.objectContaining({gl: 'swangle'}),
+ }),
+ );
expect(onMediaFiles).toHaveBeenCalledTimes(1);
expect(forgetBrowserEventLoop).toHaveBeenCalledTimes(1);
expect(exits).toEqual([]);
} finally {
if (launchedBrowser) {
- await closeBrowserInstanceImplementation({launchedBrowser});
+ await closeBrowserInstance({launchedBrowser});
}
tmpDirSpy.mockRestore();
@@ -221,10 +224,23 @@ test('a flaky renderer invocation closes its browser before returning', async ()
failClosing = () => reject(new Error('Could not close browser'));
});
const streamedMessages: StreamingPayload[] = [];
- const closeBrowserInstance = mock(() => {
+ const closeBrowser = spyOn(
+ browserInstance,
+ 'closeBrowserInstance',
+ ).mockImplementation(() => {
notifyCloseStarted();
return closing;
});
+ spies.push(
+ closeBrowser,
+ spyOn(isFlakyError, 'isFlakyError').mockImplementation(() => true),
+ spyOn(currentRegion, 'getCurrentRegionInFunction').mockReturnValue(
+ 'eu-central-1',
+ ),
+ spyOn(browserInstance, 'getBrowserInstance').mockImplementation(() =>
+ Promise.resolve(browser as never),
+ ),
+ );
try {
setNodeEnv('production');
@@ -248,19 +264,11 @@ test('a flaky renderer invocation closes its browser before returning', async ()
streamedMessages.push(message);
return Promise.resolve();
},
- providerSpecifics: {
- isFlakyError: () => true,
- } as unknown as ProviderSpecifics,
requestContext: {
requestId: 'invocation-a',
expectedBucketOwner: null,
getRemainingTimeInMillis: () => 120_000,
},
- insideFunctionSpecifics: {
- getCurrentRegionInFunction: () => 'eu-central-1',
- getBrowserInstance: () => Promise.resolve(browser as never),
- closeBrowserInstance,
- } as unknown as InsideFunctionSpecifics,
onMediaFiles: null,
executionMode: 'invoked',
});
@@ -271,8 +279,8 @@ test('a flaky renderer invocation closes its browser before returning', async ()
handlerPromise.then(() => 'handler-returned'),
]),
).toBe('close-started');
- expect(closeBrowserInstance).toHaveBeenCalledTimes(1);
- expect(closeBrowserInstance).toHaveBeenCalledWith({
+ expect(closeBrowser).toHaveBeenCalledTimes(1);
+ expect(closeBrowser).toHaveBeenCalledWith({
launchedBrowser: browser,
});
@@ -333,30 +341,25 @@ test('closing a cached browser makes the next invocation launch a new one', asyn
openBrowserSpy.mockImplementationOnce(() =>
Promise.resolve(secondBrowser as never),
);
- const providerSpecifics = {
- getChromiumPath: () => '/mock-chrome',
- } as unknown as ProviderSpecifics;
- const insideFunctionSpecifics = {
- getBrowserInstance: getBrowserInstanceImplementation,
- } as unknown as InsideFunctionSpecifics;
+ spies.push(
+ spyOn(chromiumPath, 'getChromiumPath').mockImplementation(
+ () => '/mock-chrome',
+ ),
+ );
let first: LaunchedBrowser | null = null;
let second: LaunchedBrowser | null = null;
try {
- first = await getBrowserInstanceImplementation({
+ first = await getBrowserInstance({
logLevel: 'error',
indent: false,
chromiumOptions: {},
- providerSpecifics,
- insideFunctionSpecifics,
});
- await closeBrowserInstanceImplementation({launchedBrowser: first});
- second = await getBrowserInstanceImplementation({
+ await closeBrowserInstance({launchedBrowser: first});
+ second = await getBrowserInstance({
logLevel: 'error',
indent: false,
chromiumOptions: {},
- providerSpecifics,
- insideFunctionSpecifics,
});
expect(openBrowserSpy).toHaveBeenCalledTimes(2);
@@ -364,11 +367,11 @@ test('closing a cached browser makes the next invocation launch a new one', asyn
expect(second.instance as unknown).toBe(secondBrowser);
} finally {
if (second) {
- await closeBrowserInstanceImplementation({launchedBrowser: second});
+ await closeBrowserInstance({launchedBrowser: second});
}
if (first) {
- await closeBrowserInstanceImplementation({launchedBrowser: first});
+ await closeBrowserInstance({launchedBrowser: first});
}
openBrowserSpy.mockRestore();
diff --git a/packages/lambda/src/test/unit/routine.test.ts b/packages/lambda/src/test/unit/routine.test.ts
index 94837cff56..50ac64da6d 100644
--- a/packages/lambda/src/test/unit/routine.test.ts
+++ b/packages/lambda/src/test/unit/routine.test.ts
@@ -1,37 +1,37 @@
import {expect, spyOn, test} from 'bun:test';
-import {
- LambdaClientInternals,
- ServerlessRoutines,
-} from '@remotion/lambda-client';
+import {ServerlessRoutines} from '@remotion/lambda-client';
import {VERSION} from 'remotion/version';
+import * as readFile from '../../../../lambda-client/src/read-file';
import {routine} from '../../functions';
-import {serverAwsImplementation} from '../../functions/aws-server-implementation';
+import * as cleanTmpdir from '../../functions/helpers/clean-tmpdir';
+import * as currentFunctionName from '../../functions/helpers/get-current-function-name';
+import * as currentMemorySize from '../../functions/helpers/get-current-memory-size';
+import * as currentRegion from '../../functions/helpers/get-current-region';
import {ResponseStream} from '../../functions/streaming/response-stream';
test('Lambda context is normalized while preserving storage ownership', async () => {
const previousFlag = process.env.__RESERVED_IS_INSIDE_REMOTION_LAMBDA;
// Replace Lambda's filesystem and runtime environment, keeping dispatch and
// progress handling real. The real cleanup deletes the Lambda /tmp directory.
- const cleanup = spyOn(
- serverAwsImplementation,
- 'deleteTmpDir',
- ).mockResolvedValue();
+ const cleanup = spyOn(cleanTmpdir, 'deleteTmpDir').mockImplementation(
+ () => undefined,
+ );
const region = spyOn(
- serverAwsImplementation,
+ currentRegion,
'getCurrentRegionInFunction',
).mockReturnValue('us-east-1');
const memory = spyOn(
- serverAwsImplementation,
+ currentMemorySize,
'getCurrentMemorySizeInMb',
).mockReturnValue(2048);
const name = spyOn(
- serverAwsImplementation,
+ currentFunctionName,
'getCurrentFunctionName',
).mockReturnValue('render-worker');
const storageError = new Error('Storage unavailable');
const read = spyOn(
- LambdaClientInternals.awsImplementation,
- 'readFile',
+ readFile,
+ 'lambdaReadFileImplementation',
).mockRejectedValue(storageError);
const context = {
awsRequestId: 'request-id',
diff --git a/packages/lambda/src/test/unit/runtime-policies.test.ts b/packages/lambda/src/test/unit/runtime-policies.test.ts
index b74bec75e9..929201ed19 100644
--- a/packages/lambda/src/test/unit/runtime-policies.test.ts
+++ b/packages/lambda/src/test/unit/runtime-policies.test.ts
@@ -2,14 +2,12 @@ import {expect, mock, spyOn, test} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import {
- LambdaClientInternals,
- type StreamingPayload,
-} from '@remotion/lambda-client';
+import type {StreamingPayload} from '@remotion/lambda-client';
import {RenderInternals} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
-import {serverAwsImplementation} from '../../functions/aws-server-implementation';
+import * as browserInstance from '../../functions/get-browser-instance';
import {rendererHandler} from '../../functions/handlers/renderer';
+import * as currentRegion from '../../functions/helpers/get-current-region';
test.each(['angle', null] as const)(
'Lambda renders with software GL and one browser process for gl=%s',
@@ -37,9 +35,21 @@ test.each(['angle', null] as const)(
'internalRenderMedia',
).mockResolvedValue({slowestFrames: []} as never);
const messages: StreamingPayload[] = [];
+ const originalGetBrowserInstance = browserInstance.getBrowserInstance;
let launchedBrowser: Awaited<
- ReturnType<typeof serverAwsImplementation.getBrowserInstance>
+ ReturnType<typeof originalGetBrowserInstance>
> | null = null;
+ const regionSpy = spyOn(
+ currentRegion,
+ 'getCurrentRegionInFunction',
+ ).mockReturnValue('us-east-1');
+ const browserSpy = spyOn(
+ browserInstance,
+ 'getBrowserInstance',
+ ).mockImplementation(async (options) => {
+ launchedBrowser = await originalGetBrowserInstance(options);
+ return launchedBrowser;
+ });
const chromiumOptions = {gl, enableMultiProcessOnLinux: true};
try {
@@ -69,16 +79,6 @@ test.each(['angle', null] as const)(
messages.push(message);
return Promise.resolve();
},
- providerSpecifics: LambdaClientInternals.awsImplementation,
- insideFunctionSpecifics: {
- ...serverAwsImplementation,
- getCurrentRegionInFunction: () => 'us-east-1',
- getBrowserInstance: async (options) => {
- launchedBrowser =
- await serverAwsImplementation.getBrowserInstance(options);
- return launchedBrowser;
- },
- },
requestContext: {
requestId: 'request-id',
expectedBucketOwner: '123456789012',
@@ -107,12 +107,13 @@ test.each(['angle', null] as const)(
}),
);
expect(chromiumOptions).toEqual({gl, enableMultiProcessOnLinux: true});
- expect(serverAwsImplementation.startRendererDiagnostics).toBeNull();
} finally {
if (launchedBrowser) {
- await serverAwsImplementation.closeBrowserInstance({launchedBrowser});
+ await browserInstance.closeBrowserInstance({launchedBrowser});
}
+ regionSpy.mockRestore();
+ browserSpy.mockRestore();
tmpDirSpy.mockRestore();
openBrowserSpy.mockRestore();
renderMediaSpy.mockRestore();
diff --git a/packages/lambda/src/test/unit/s3-renderer-launcher.test.ts b/packages/lambda/src/test/unit/s3-renderer-launcher.test.ts
index faa3797e9d..8d3302fd68 100644
--- a/packages/lambda/src/test/unit/s3-renderer-launcher.test.ts
+++ b/packages/lambda/src/test/unit/s3-renderer-launcher.test.ts
@@ -1,18 +1,27 @@
-import {expect, test} from 'bun:test';
+import {afterEach, expect, spyOn, 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 {
LambdaClientInternals,
- type ProviderSpecifics,
type S3RendererStatus,
} from '@remotion/lambda-client';
import type {EmittedArtifact} from '@remotion/renderer';
+import * as callLambdaAsync from '../../../../lambda-client/src/call-lambda-async';
+import * as deleteFile from '../../../../lambda-client/src/delete-file';
+import * as readFileModule from '../../../../lambda-client/src/read-file';
+import * as rendererTransport from '../../../../lambda-client/src/renderer-transport';
+import * as currentRegion from '../../functions/helpers/get-current-region';
import type {OverallProgressHelper} from '../../functions/overall-render-progress';
-import type {InsideFunctionSpecifics} from '../../functions/provider-implementation';
import {renderRendererFunctionWithRetry} from '../../functions/stream-renderer';
+const spies: {mockRestore: () => void}[] = [];
+
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
+
test('S3 launcher invokes, polls, downloads, and normalizes a renderer result', async () => {
const directory = await mkdtemp(join(tmpdir(), 'remotion-s3-launcher-'));
try {
@@ -59,9 +68,15 @@ test('S3 launcher invokes, polls, downloads, and normalizes a renderer result',
},
],
};
- const providerSpecifics = {
- getRendererFunctionTransport: () => 's3',
- callFunctionAsync: () => {
+ spies.push(
+ spyOn(
+ rendererTransport,
+ 'getRendererFunctionTransport',
+ ).mockImplementation(() => 's3'),
+ spyOn(
+ callLambdaAsync,
+ 'callFunctionAsyncImplementation',
+ ).mockImplementation(() => {
asyncInvocations++;
objects.set(videoKey, new TextEncoder().encode('video'));
objects.set(artifactKey, new TextEncoder().encode('artifact'));
@@ -70,25 +85,30 @@ test('S3 launcher invokes, polls, downloads, and normalizes a renderer result',
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;
- }
+ }),
+ spyOn(readFileModule, 'lambdaReadFileImplementation').mockImplementation(
+ ({key}) => {
+ 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;
+ return Promise.resolve(Readable.from([value]));
+ },
+ ),
+ spyOn(deleteFile, 'lambdaDeleteFileImplementation').mockImplementation(
+ ({key}) => {
+ deleted.push(key);
+ objects.delete(key);
+ return Promise.resolve();
+ },
+ ),
+ spyOn(currentRegion, 'getCurrentRegionInFunction').mockImplementation(
+ () => 'eu-central-1',
+ ),
+ );
const frames: Array<{rendered: number; encoded: number}> = [];
let lambdasInvoked = 0;
@@ -105,9 +125,6 @@ test('S3 launcher invokes, polls, downloads, and normalizes a renderer result',
completedChunks++;
},
} as unknown as OverallProgressHelper;
- const insideFunctionSpecifics = {
- getCurrentRegionInFunction: () => 'eu-central-1',
- } as unknown as InsideFunctionSpecifics;
const files: string[] = [];
const artifacts: EmittedArtifact[] = [];
const artifactSources: Array<{chunk: number; attempt: number}> = [];
@@ -133,8 +150,6 @@ test('S3 launcher invokes, polls, downloads, and normalizes a renderer result',
artifactSources.push({chunk, attempt});
return {type: 'accepted'};
},
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler: null,
expectedBucketOwner: 'owner',
});
diff --git a/packages/lambda/src/test/unit/s3-renderer-output.test.ts b/packages/lambda/src/test/unit/s3-renderer-output.test.ts
index 595836c07f..f545d54106 100644
--- a/packages/lambda/src/test/unit/s3-renderer-output.test.ts
+++ b/packages/lambda/src/test/unit/s3-renderer-output.test.ts
@@ -1,9 +1,9 @@
-import {expect, test} from 'bun:test';
+import {expect, spyOn, 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/lambda-client';
+import * as writeFileModule from '../../../../lambda-client/src/write-file';
import {makeS3RendererOutput} from '../../functions/s3-renderer-output';
const bodyToBytes = async (
@@ -39,28 +39,26 @@ const bodyToBytes = async (
test('S3 renderer output publishes media and artifacts before completion', async () => {
const directory = await mkdtemp(join(tmpdir(), 'remotion-s3-output-'));
+ const objects = new Map<string, Uint8Array>();
+ const statusWrites: Array<Record<string, unknown>> = [];
+ const write = spyOn(
+ writeFileModule,
+ 'lambdaWriteFileImplementation',
+ ).mockImplementation(async ({key, body}) => {
+ 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>,
+ );
+ }
+ });
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;
const output = makeS3RendererOutput({
params: {
type: 'renderer',
@@ -73,7 +71,6 @@ test('S3 renderer output publishes media and artifacts before completion', async
} as never,
expectedBucketOwner: 'owner',
region: 'eu-central-1',
- providerSpecifics,
});
await output.initialize();
@@ -136,6 +133,7 @@ test('S3 renderer output publishes media and artifacts before completion', async
),
).toBe('artifact-content');
} finally {
+ write.mockRestore();
await rm(directory, {recursive: true, force: true});
}
});
diff --git a/packages/lambda/src/test/unit/streaming-renderer-launcher.test.ts b/packages/lambda/src/test/unit/streaming-renderer-launcher.test.ts
index 6ac5553b1c..8e7c12dc70 100644
--- a/packages/lambda/src/test/unit/streaming-renderer-launcher.test.ts
+++ b/packages/lambda/src/test/unit/streaming-renderer-launcher.test.ts
@@ -1,74 +1,94 @@
-import {expect, test} from 'bun:test';
+import {afterEach, expect, spyOn, test} from 'bun:test';
import {join} from 'node:path';
import {
LambdaClientInternals,
ServerlessRoutines,
type OnMessage,
- type ProviderSpecifics,
type ServerlessPayload,
} from '@remotion/lambda-client';
import type {EmittedArtifact} from '@remotion/renderer';
+import * as callLambdaStreaming from '../../../../lambda-client/src/call-lambda-streaming';
+import * as rendererTransport from '../../../../lambda-client/src/renderer-transport';
import {makeArtifactRegistry} from '../../functions/artifact-registry';
+import * as currentRegion from '../../functions/helpers/get-current-region';
import type {OverallProgressHelper} from '../../functions/overall-render-progress';
-import type {InsideFunctionSpecifics} from '../../functions/provider-implementation';
import {renderRendererFunctionWithRetry} from '../../functions/stream-renderer';
+const spies: {mockRestore: () => void}[] = [];
+
+afterEach(() => {
+ spies.splice(0).forEach((spy) => spy.mockRestore());
+});
+
+const useStreamingTransport = (
+ callFunctionStreaming: (options: {
+ payload: ServerlessPayload;
+ receivedStreamingPayload: OnMessage;
+ }) => Promise<void>,
+) => {
+ spies.push(
+ spyOn(rendererTransport, 'getRendererFunctionTransport').mockImplementation(
+ () => 'response-streaming',
+ ),
+ spyOn(
+ callLambdaStreaming,
+ 'callFunctionWithStreamingImplementation',
+ ).mockImplementation(
+ callFunctionStreaming as typeof callLambdaStreaming.callFunctionWithStreamingImplementation,
+ ),
+ spyOn(currentRegion, 'getCurrentRegionInFunction').mockImplementation(
+ () => 'eu-central-1',
+ ),
+ );
+};
+
test('an artifact replayed by a retried streaming chunk is idempotent', async () => {
const attempts: number[] = [];
- const providerSpecifics = {
- getRendererFunctionTransport: () => 'response-streaming',
- callFunctionStreaming: ({
- payload,
- receivedStreamingPayload,
- }: {
- payload: ServerlessPayload;
- receivedStreamingPayload: OnMessage;
- }) => {
- if (payload.type !== ServerlessRoutines.renderer) {
- throw new Error('Expected renderer payload');
- }
+ useStreamingTransport(({payload, receivedStreamingPayload}) => {
+ if (payload.type !== ServerlessRoutines.renderer) {
+ throw new Error('Expected renderer payload');
+ }
- attempts.push(payload.attempt);
+ attempts.push(payload.attempt);
+ receivedStreamingPayload({
+ successType: 'success',
+ message: {
+ type: 'artifact-emitted',
+ payload: {
+ artifact: LambdaClientInternals.serializeArtifact({
+ filename: 'thumbnail.jpeg',
+ frame: 0,
+ content: 'thumbnail',
+ downloadBehavior: null,
+ }),
+ },
+ },
+ });
+
+ if (payload.attempt === 1) {
receivedStreamingPayload({
- successType: 'success',
+ successType: 'error',
message: {
- type: 'artifact-emitted',
+ type: 'error-occurred',
payload: {
- artifact: LambdaClientInternals.serializeArtifact({
- filename: 'thumbnail.jpeg',
- frame: 0,
- content: 'thumbnail',
- downloadBehavior: null,
- }),
+ error: 'Flaky renderer error',
+ shouldRetry: true,
+ errorInfo: {} as never,
},
},
});
+ } else {
+ receivedStreamingPayload({
+ successType: 'success',
+ message: {
+ type: 'chunk-complete',
+ payload: {start: 100, rendered: 200},
+ },
+ });
+ }
- if (payload.attempt === 1) {
- receivedStreamingPayload({
- successType: 'error',
- message: {
- type: 'error-occurred',
- payload: {
- error: 'Flaky renderer error',
- shouldRetry: true,
- errorInfo: {} as never,
- },
- },
- });
- } else {
- receivedStreamingPayload({
- successType: 'success',
- message: {
- type: 'chunk-complete',
- payload: {start: 100, rendered: 200},
- },
- });
- }
-
- return Promise.resolve();
- },
- } as unknown as ProviderSpecifics;
+ return Promise.resolve();
+ });
const retries: number[] = [];
let completedChunks = 0;
const overallProgress = {
@@ -79,9 +99,6 @@ test('an artifact replayed by a retried streaming chunk is idempotent', async ()
completedChunks++;
},
} as unknown as OverallProgressHelper;
- const insideFunctionSpecifics = {
- getCurrentRegionInFunction: () => 'eu-central-1',
- } as unknown as InsideFunctionSpecifics;
const artifactRegistry = makeArtifactRegistry();
const acceptedArtifacts: EmittedArtifact[] = [];
@@ -114,8 +131,6 @@ test('an artifact replayed by a retried streaming chunk is idempotent', async ()
return result;
},
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler: null,
expectedBucketOwner: 'owner',
});
@@ -134,50 +149,38 @@ test('an artifact replayed by a retried streaming chunk is idempotent', async ()
});
test('a chunk file replayed by a retried streaming chunk is only merged once', async () => {
- const providerSpecifics = {
- getRendererFunctionTransport: () => 'response-streaming',
- callFunctionStreaming: ({
- payload,
- receivedStreamingPayload,
- }: {
- payload: ServerlessPayload;
- receivedStreamingPayload: OnMessage;
- }) => {
- if (payload.type !== ServerlessRoutines.renderer) {
- throw new Error('Expected renderer payload');
- }
+ useStreamingTransport(({payload, receivedStreamingPayload}) => {
+ if (payload.type !== ServerlessRoutines.renderer) {
+ throw new Error('Expected renderer payload');
+ }
- receivedStreamingPayload({
- successType: 'success',
- message: {type: 'audio-chunk-rendered', payload: new Uint8Array()},
- });
+ receivedStreamingPayload({
+ successType: 'success',
+ message: {type: 'audio-chunk-rendered', payload: new Uint8Array()},
+ });
- if (payload.attempt === 1) {
- return Promise.reject(new Error('socket hang up'));
- }
+ if (payload.attempt === 1) {
+ return Promise.reject(new Error('socket hang up'));
+ }
- receivedStreamingPayload({
- successType: 'success',
- message: {type: 'video-chunk-rendered', payload: new Uint8Array()},
- });
- receivedStreamingPayload({
- successType: 'success',
- message: {
- type: 'chunk-complete',
- payload: {start: 100, rendered: 200},
- },
- });
+ receivedStreamingPayload({
+ successType: 'success',
+ message: {type: 'video-chunk-rendered', payload: new Uint8Array()},
+ });
+ receivedStreamingPayload({
+ successType: 'success',
+ message: {
+ type: 'chunk-complete',
+ payload: {start: 100, rendered: 200},
+ },
+ });
- return Promise.resolve();
- },
- } as unknown as ProviderSpecifics;
+ return Promise.resolve();
+ });
const overallProgress = {
addRetry: () => undefined,
addChunkCompleted: () => undefined,
} as unknown as OverallProgressHelper;
- const insideFunctionSpecifics = {
- getCurrentRegionInFunction: () => 'eu-central-1',
- } as unknown as InsideFunctionSpecifics;
const files: string[] = [];
await renderRendererFunctionWithRetry({
@@ -199,8 +202,6 @@ test('a chunk file replayed by a retried streaming chunk is only merged once', a
onArtifact: () => {
throw new Error('No artifacts expected');
},
- providerSpecifics,
- insideFunctionSpecifics,
requestHandler: null,
expectedBucketOwner: 'owner',
});
diff --git a/packages/lambda/src/test/unit/x264-preset-default.test.ts b/packages/lambda/src/test/unit/x264-preset-default.test.ts
index 8f7101b52b..c4d4e020c0 100644
--- a/packages/lambda/src/test/unit/x264-preset-default.test.ts
+++ b/packages/lambda/src/test/unit/x264-preset-default.test.ts
@@ -1,16 +1,16 @@
import {expect, test} from 'bun:test';
import {
ServerlessRoutines,
- type ProviderSpecifics,
type ServerlessPayload,
type ServerlessStartPayload,
} from '@remotion/lambda-client';
import {NoReactInternals} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
-import {serverAwsImplementation} from '../../functions/aws-server-implementation';
import {startHandler} from '../../functions/handlers/start';
-import {mockServerImplementation} from '../mock-implementation';
-import {mockImplementation} from '../mocks/mock-implementation';
+import {DEFAULT_X264_PRESET} from '../../functions/helpers/default-x264-preset';
+import {fakeAws, useFakeAws} from '../mocks/fake-aws';
+
+useFakeAws();
const makeStartPayload = ({
codec,
@@ -80,13 +80,10 @@ const makeStartPayload = ({
test('resolves the Lambda x264 preset at the runtime boundary', async () => {
const launchedPayloads: ServerlessPayload[] = [];
- const providerSpecifics = {
- ...mockImplementation,
- callFunctionAsync: ({payload}) => {
- launchedPayloads.push(payload);
- return Promise.resolve();
- },
- } satisfies ProviderSpecifics;
+ fakeAws().callFunctionAsync.mockImplementation(({payload}) => {
+ launchedPayloads.push(payload);
+ return Promise.resolve();
+ });
for (const payload of [
makeStartPayload({codec: 'h264', x264Preset: null}),
@@ -100,8 +97,6 @@ test('resolves the Lambda x264 preset at the runtime boundary', async () => {
timeoutInMilliseconds: 120_000,
renderId: 'test-render',
},
- providerSpecifics,
- insideFunctionSpecifics: mockServerImplementation,
});
}
@@ -113,7 +108,7 @@ test('resolves the Lambda x264 preset at the runtime boundary', async () => {
return payload;
});
- expect(serverAwsImplementation.defaultX264Preset).toBe(
+ expect(DEFAULT_X264_PRESET).toBe(
NoReactInternals.ENABLE_V5_BREAKING_CHANGES ? 'veryfast' : null,
);
expect(launchPayloads[0].x264Preset).toBe(