Skip to content

🎥 Make videos programmatically with React

split into callLambdaSync(), callLambdaAsync(), callLambdaStreaming()

Jonny Burger2469b758a9c9
diff --git a/package.json b/package.json
index cd866395ca..67d441ecb5 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"ci": "turbo run make test --concurrency=1 --no-update-notifier",
"watch": "turbo watch make --concurrency=2",
"watchwebcodecs": "turbo watch make --filter='@remotion/media-parser' --filter='@remotion/webcodecs'",
+ "watchserverless": "turbo watch make --filter='@remotion/lambda' --filter='@remotion/serverless' --filter='@remotion/streaming'",
"release-alpha": "pnpm recursive publish --tag=alpha --no-git-checks && pnpm recursive run --sequential publishprivate",
"release": "pnpm recursive publish && pnpm recursive run --sequential publishprivate && git push --tags && git push",
"clean": "turbo run clean && rm -rf packages/**/dist && rm -rf packages/**/node_modules && rm -rf node_modules && rm -rf .cache && rm -rf packages/**/tsconfig.tsbuildinfo && rm -f packages/tsconfig.tsbuildinfo && rm -rf packages/**/.turbo && rm -rf .turbo"
diff --git a/packages/lambda/src/api/get-compositions-on-lambda.ts b/packages/lambda/src/api/get-compositions-on-lambda.ts
index 549926909f..537331816c 100644
--- a/packages/lambda/src/api/get-compositions-on-lambda.ts
+++ b/packages/lambda/src/api/get-compositions-on-lambda.ts
@@ -10,7 +10,7 @@ import type {VideoConfig} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
import type {AwsRegion} from '../client';
import {awsImplementation} from '../functions/aws-implementation';
-import {callLambda} from '../shared/call-lambda';
+import {callLambdaSync} from '../shared/call-lambda-sync';
export type GetCompositionsOnLambdaInput = {
chromiumOptions?: ChromiumOptions;
@@ -66,7 +66,7 @@ export const getCompositionsOnLambda = async ({
});
try {
- const res = await callLambda({
+ const res = await callLambdaSync({
functionName,
type: ServerlessRoutines.compositions,
payload: {
diff --git a/packages/lambda/src/api/get-render-progress.ts b/packages/lambda/src/api/get-render-progress.ts
index 740acff819..c8d4d3de96 100644
--- a/packages/lambda/src/api/get-render-progress.ts
+++ b/packages/lambda/src/api/get-render-progress.ts
@@ -8,7 +8,7 @@ import {
import {getProgress} from '../functions/helpers/get-progress';
import {parseFunctionName} from '../functions/helpers/parse-function-name';
import type {AwsRegion} from '../regions';
-import {callLambda} from '../shared/call-lambda';
+import {callLambdaSync} from '../shared/call-lambda-sync';
import type {RenderProgress} from '../shared/constants';
import {getRenderProgressPayload} from './make-lambda-payload';
@@ -56,7 +56,7 @@ export const getRenderProgress = async (
});
}
- const result = await callLambda<AwsProvider, ServerlessRoutines.status>({
+ const result = await callLambdaSync<AwsProvider, ServerlessRoutines.status>({
functionName: input.functionName,
type: ServerlessRoutines.status,
payload: getRenderProgressPayload(input),
diff --git a/packages/lambda/src/api/render-media-on-lambda.ts b/packages/lambda/src/api/render-media-on-lambda.ts
index fdb8f8510d..daec6f09f3 100644
--- a/packages/lambda/src/api/render-media-on-lambda.ts
+++ b/packages/lambda/src/api/render-media-on-lambda.ts
@@ -19,7 +19,7 @@ import type {
import {ServerlessRoutines} from '@remotion/serverless/client';
import type {AwsProvider} from '../functions/aws-implementation';
import type {AwsRegion} from '../regions';
-import {callLambda} from '../shared/call-lambda';
+import {callLambdaSync} from '../shared/call-lambda-sync';
import {
getCloudwatchMethodUrl,
getCloudwatchRendererUrl,
@@ -88,7 +88,7 @@ export const internalRenderMediaOnLambdaRaw = async (
const {functionName, region, rendererFunctionName} = input;
try {
- const res = await callLambda({
+ const res = await callLambdaSync({
functionName,
type: ServerlessRoutines.start,
payload: await makeLambdaRenderMediaPayload(input),
diff --git a/packages/lambda/src/api/render-still-on-lambda.ts b/packages/lambda/src/api/render-still-on-lambda.ts
index 118aae677e..7aa7caabd9 100644
--- a/packages/lambda/src/api/render-still-on-lambda.ts
+++ b/packages/lambda/src/api/render-still-on-lambda.ts
@@ -6,7 +6,7 @@ import type {
import type {BrowserSafeApis} from '@remotion/renderer/client';
import type {DownloadBehavior} from '@remotion/serverless/client';
import {ServerlessRoutines} from '@remotion/serverless/client';
-import {callLambdaWithStreaming} from '../shared/call-lambda';
+import {callLambdaWithStreaming} from '../shared/call-lambda-streaming';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
import type {
diff --git a/packages/lambda/src/functions/helpers/stream-renderer.ts b/packages/lambda/src/functions/helpers/stream-renderer.ts
index 5ae66309c9..3bc42ee319 100644
--- a/packages/lambda/src/functions/helpers/stream-renderer.ts
+++ b/packages/lambda/src/functions/helpers/stream-renderer.ts
@@ -9,7 +9,7 @@ import type {ServerlessPayload} from '@remotion/serverless/client';
import {ServerlessRoutines} from '@remotion/serverless/client';
import {writeFileSync} from 'fs';
import {join} from 'path';
-import {callLambdaWithStreaming} from '../../shared/call-lambda';
+import {callLambdaWithStreaming} from '../../shared/call-lambda-streaming';
import type {OverallProgressHelper} from './overall-render-progress';
type StreamRendererResponse =
diff --git a/packages/lambda/src/functions/start.ts b/packages/lambda/src/functions/start.ts
index aad816d126..9a8f3ad919 100644
--- a/packages/lambda/src/functions/start.ts
+++ b/packages/lambda/src/functions/start.ts
@@ -1,4 +1,3 @@
-import {InvokeCommand} from '@aws-sdk/client-lambda';
import type {CloudProvider, ProviderSpecifics} from '@remotion/serverless';
import type {ServerlessPayload} from '@remotion/serverless/client';
import {
@@ -8,7 +7,7 @@ import {
} from '@remotion/serverless/client';
import {VERSION} from 'remotion/version';
import type {AwsRegion} from '../regions';
-import {getLambdaClient} from '../shared/aws-clients';
+import {callLambdaAsync} from '../shared/call-lambda-async';
import {validateDeleteAfter} from './helpers/lifecycle';
import {makeInitialOverallRenderProgress} from './helpers/overall-render-progress';
@@ -123,29 +122,13 @@ export const startHandler = async <Provider extends CloudProvider>(
metadata: params.metadata,
};
- const stringifiedPayload = JSON.stringify(payload);
-
- if (stringifiedPayload.length > 256 * 1024) {
- throw new Error(
- `Payload is too big: ${stringifiedPayload.length} bytes. Maximum size is 256 KB. This should not happen, please report this to the Remotion team. Payload: ${stringifiedPayload}`,
- );
- }
-
- // Don't replace with callLambda(), we want to return before the render is snone
- const result = await getLambdaClient(
- providerSpecifics.getCurrentRegionInFunction() as AwsRegion,
- ).send(
- new InvokeCommand({
- FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
- Payload: stringifiedPayload,
- InvocationType: 'Event',
- }),
- );
- if (result.FunctionError) {
- throw new Error(
- `Lambda function returned error: ${result.FunctionError} ${result.LogResult}`,
- );
- }
+ await callLambdaAsync({
+ functionName: process.env.AWS_LAMBDA_FUNCTION_NAME as string,
+ type: ServerlessRoutines.launch,
+ payload,
+ region: region as AwsRegion,
+ timeoutInTest: options.timeoutInMilliseconds,
+ });
await initialFile;
diff --git a/packages/lambda/src/shared/call-lambda-async.ts b/packages/lambda/src/shared/call-lambda-async.ts
new file mode 100644
index 0000000000..f42094b172
--- /dev/null
+++ b/packages/lambda/src/shared/call-lambda-async.ts
@@ -0,0 +1,37 @@
+import {InvokeCommand} from '@aws-sdk/client-lambda';
+import type {CloudProvider} from '@remotion/serverless';
+import type {ServerlessRoutines} from '@remotion/serverless/client';
+import type {AwsRegion} from '../regions';
+import {getLambdaClient} from './aws-clients';
+import type {CallLambdaOptions} from './call-lambda';
+
+export const callLambdaAsync = async <
+ T extends ServerlessRoutines,
+ Provider extends CloudProvider,
+>({
+ functionName,
+ payload,
+ region,
+ timeoutInTest,
+}: CallLambdaOptions<T, Provider>): Promise<void> => {
+ const stringifiedPayload = JSON.stringify(payload);
+ if (stringifiedPayload.length > 256 * 1024) {
+ throw new Error(
+ `Payload is too big: ${stringifiedPayload.length} bytes. Maximum size is 256 KB. This should not happen, please report this to the Remotion team. Payload: ${stringifiedPayload}`,
+ );
+ }
+
+ const result = await getLambdaClient(region as AwsRegion, timeoutInTest).send(
+ new InvokeCommand({
+ FunctionName: functionName,
+ Payload: stringifiedPayload,
+ InvocationType: 'Event',
+ }),
+ );
+
+ if (result.FunctionError) {
+ throw new Error(
+ `Lambda function returned error: ${result.FunctionError} ${result.LogResult}`,
+ );
+ }
+};
diff --git a/packages/lambda/src/shared/call-lambda-streaming.ts b/packages/lambda/src/shared/call-lambda-streaming.ts
new file mode 100644
index 0000000000..8182cb35e9
--- /dev/null
+++ b/packages/lambda/src/shared/call-lambda-streaming.ts
@@ -0,0 +1,218 @@
+import type {InvokeWithResponseStreamCommandOutput} from '@aws-sdk/client-lambda';
+import {
+ InvokeWithResponseStreamCommand,
+ type InvokeWithResponseStreamResponseEvent,
+} from '@aws-sdk/client-lambda';
+import type {
+ CloudProvider,
+ OnMessage,
+ StreamingMessage,
+} from '@remotion/serverless';
+import type {
+ MessageTypeId,
+ ServerlessRoutines,
+} from '@remotion/serverless/client';
+import {
+ formatMap,
+ messageTypeIdToMessageType,
+} from '@remotion/serverless/client';
+import {makeStreamer} from '@remotion/streaming';
+import type {AwsRegion} from '../regions';
+import {getLambdaClient} from './aws-clients';
+import type {CallLambdaOptions} from './call-lambda';
+
+const STREAM_STALL_TIMEOUT = 30000;
+const LAMBDA_STREAM_STALL = `AWS did not invoke Lambda in ${STREAM_STALL_TIMEOUT}ms`;
+
+const parseJsonOrThrowSource = (data: Uint8Array, type: string) => {
+ const asString = new TextDecoder('utf-8').decode(data);
+ try {
+ return JSON.parse(asString);
+ } catch {
+ throw new Error(`Invalid JSON (${type}): ${asString}`);
+ }
+};
+
+const invokeStreamOrTimeout = async <Provider extends CloudProvider>({
+ region,
+ timeoutInTest,
+ functionName,
+ type,
+ payload,
+}: {
+ region: Provider['region'];
+ timeoutInTest: number;
+ functionName: string;
+ type: string;
+ payload: Record<string, unknown>;
+}) => {
+ const resProm = getLambdaClient(region as AwsRegion, timeoutInTest).send(
+ new InvokeWithResponseStreamCommand({
+ FunctionName: functionName,
+ Payload: JSON.stringify({type, ...payload}),
+ }),
+ );
+
+ let cleanup = () => undefined;
+
+ const timeout = new Promise<InvokeWithResponseStreamCommandOutput>(
+ (_resolve, reject) => {
+ const int = setTimeout(() => {
+ reject(new Error(LAMBDA_STREAM_STALL));
+ }, STREAM_STALL_TIMEOUT);
+ cleanup = () => {
+ clearTimeout(int);
+ };
+ },
+ );
+
+ const res = await Promise.race([resProm, timeout]);
+
+ cleanup();
+
+ return res;
+};
+
+const INVALID_JSON_MESSAGE = 'Cannot parse Lambda response as JSON';
+
+const callLambdaWithStreamingWithoutRetry = async <
+ T extends ServerlessRoutines,
+ Provider extends CloudProvider,
+>({
+ functionName,
+ type,
+ payload,
+ region,
+ timeoutInTest,
+ receivedStreamingPayload,
+}: CallLambdaOptions<T, Provider> & {
+ receivedStreamingPayload: OnMessage<Provider>;
+}): Promise<void> => {
+ const res = await invokeStreamOrTimeout({
+ functionName,
+ payload,
+ region,
+ timeoutInTest,
+ type,
+ });
+
+ const {onData, clear} = makeStreamer((status, messageTypeId, data) => {
+ const messageType = messageTypeIdToMessageType(
+ messageTypeId as MessageTypeId,
+ );
+ const innerPayload =
+ formatMap[messageType] === 'json'
+ ? parseJsonOrThrowSource(data, messageType)
+ : data;
+
+ const message: StreamingMessage<Provider> = {
+ successType: status,
+ message: {
+ type: messageType,
+ payload: innerPayload,
+ },
+ };
+
+ receivedStreamingPayload(message);
+ });
+
+ const dumpBuffers = () => {
+ clear();
+ };
+
+ // @ts-expect-error - We are adding a listener to a global variable
+ if (globalThis._dumpUnreleasedBuffers) {
+ // @ts-expect-error - We are adding a listener to a global variable
+ (globalThis._dumpUnreleasedBuffers as EventEmitter).addListener(
+ 'dump-unreleased-buffers',
+ dumpBuffers,
+ );
+ }
+
+ const events =
+ res.EventStream as AsyncIterable<InvokeWithResponseStreamResponseEvent>;
+
+ for await (const event of events) {
+ // There are two types of events you can get on a stream.
+
+ // `PayloadChunk`: These contain the actual raw bytes of the chunk
+ // It has a single property: `Payload`
+ if (event.PayloadChunk && event.PayloadChunk.Payload) {
+ onData(event.PayloadChunk.Payload);
+ }
+
+ if (event.InvokeComplete) {
+ if (event.InvokeComplete.ErrorCode) {
+ const logs = `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~unit~'seconds~editorString~'fields*20*40timestamp*2c*20*40requestId*2c*20*40message*0a*7c*20filter*20*40requestId*20like*20*${res.$metadata.requestId}*22*0a*7c*20sort*20*40timestamp*20asc~source~(~'*2faws*2flambda*2f${functionName}))`;
+ if (event.InvokeComplete.ErrorCode === 'Unhandled') {
+ throw new Error(
+ `Lambda function ${functionName} failed with an unhandled error: ${
+ event.InvokeComplete.ErrorDetails as string
+ } See ${logs} to see the logs of this invocation.`,
+ );
+ }
+
+ throw new Error(
+ `Lambda function ${functionName} failed with error code ${event.InvokeComplete.ErrorCode}: ${event.InvokeComplete.ErrorDetails}. See ${logs} to see the logs of this invocation.`,
+ );
+ }
+ }
+
+ // Don't put a `break` statement here, as it will cause the socket to not properly exit.
+ }
+
+ // @ts-expect-error - We are adding a listener to a global variable
+ if (globalThis._dumpUnreleasedBuffers) {
+ // @ts-expect-error - We are adding a listener to a global variable
+ (globalThis._dumpUnreleasedBuffers as EventEmitter).removeListener(
+ 'dump-unreleased-buffers',
+ dumpBuffers,
+ );
+ }
+
+ clear();
+};
+
+export const callLambdaWithStreaming = async <
+ Provider extends CloudProvider,
+ T extends ServerlessRoutines,
+>(
+ options: CallLambdaOptions<T, Provider> & {
+ receivedStreamingPayload: OnMessage<Provider>;
+ retriesRemaining: number;
+ },
+): Promise<void> => {
+ // As of August 2023, Lambda streaming sometimes misses parts of the JSON response.
+ // Handling this for now by applying a retry mechanism.
+
+ try {
+ // Do not remove this await
+ await callLambdaWithStreamingWithoutRetry<T, Provider>(options);
+ } catch (err) {
+ if ((err as Error).stack?.includes('TooManyRequestsException')) {
+ throw new Error(
+ `AWS Concurrency limit reached (Original Error: ${(err as Error).message}). See https://www.remotion.dev/docs/lambda/troubleshooting/rate-limit for tips to fix this.`,
+ );
+ }
+
+ if (
+ !(err as Error).message.includes(INVALID_JSON_MESSAGE) &&
+ !(err as Error).message.includes(LAMBDA_STREAM_STALL) &&
+ !(err as Error).message.includes('aborted')
+ ) {
+ throw err;
+ }
+
+ console.error('Retries remaining:', options.retriesRemaining);
+ if (options.retriesRemaining === 0) {
+ console.error('Throwing error:');
+ throw err;
+ }
+
+ console.error(err);
+ return callLambdaWithStreaming({
+ ...options,
+ retriesRemaining: options.retriesRemaining - 1,
+ });
+ }
+};
diff --git a/packages/lambda/src/shared/call-lambda-sync.ts b/packages/lambda/src/shared/call-lambda-sync.ts
new file mode 100644
index 0000000000..a6082375f2
--- /dev/null
+++ b/packages/lambda/src/shared/call-lambda-sync.ts
@@ -0,0 +1,54 @@
+import {InvokeCommand} from '@aws-sdk/client-lambda';
+import type {CloudProvider} from '@remotion/serverless';
+import type {ServerlessRoutines} from '@remotion/serverless/client';
+import type {OrError} from '../functions';
+import type {AwsRegion} from '../regions';
+import {getLambdaClient} from './aws-clients';
+import type {CallLambdaOptions} from './call-lambda';
+import type {LambdaReturnValues} from './return-values';
+
+const callLambdaSyncWithoutRetry = async <
+ T extends ServerlessRoutines,
+ Provider extends CloudProvider,
+>({
+ functionName,
+ type,
+ payload,
+ region,
+ timeoutInTest,
+}: CallLambdaOptions<T, Provider>): Promise<
+ OrError<LambdaReturnValues<Provider>[T]>
+> => {
+ const Payload = JSON.stringify(payload);
+ const res = await getLambdaClient(region as AwsRegion, timeoutInTest).send(
+ new InvokeCommand({
+ FunctionName: functionName,
+ Payload,
+ InvocationType: 'RequestResponse',
+ }),
+ );
+
+ const decoded = new TextDecoder('utf-8').decode(res.Payload);
+
+ try {
+ return JSON.parse(decoded) as OrError<LambdaReturnValues<Provider>[T]>;
+ } catch {
+ throw new Error(`Invalid JSON (${type}): ${JSON.stringify(decoded)}`);
+ }
+};
+
+export const callLambdaSync = async <
+ Provider extends CloudProvider,
+ T extends ServerlessRoutines,
+>(
+ options: CallLambdaOptions<T, Provider>,
+): Promise<LambdaReturnValues<Provider>[T]> => {
+ const res = await callLambdaSyncWithoutRetry<T, Provider>(options);
+ if (res.type === 'error') {
+ const err = new Error(res.message);
+ err.stack = res.stack;
+ throw err;
+ }
+
+ return res;
+};
diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.ts
index 88d0db6268..1bb8855c93 100644
--- a/packages/lambda/src/shared/call-lambda.ts
+++ b/packages/lambda/src/shared/call-lambda.ts
@@ -1,278 +1,16 @@
-/* eslint-disable @typescript-eslint/no-use-before-define */
+import type {CloudProvider} from '@remotion/serverless';
import type {
- InvokeWithResponseStreamCommandOutput,
- InvokeWithResponseStreamResponseEvent,
-} from '@aws-sdk/client-lambda';
-import {
- InvokeCommand,
- InvokeWithResponseStreamCommand,
-} from '@aws-sdk/client-lambda';
-import type {
- CloudProvider,
- OnMessage,
- StreamingMessage,
-} from '@remotion/serverless';
-import type {
- MessageTypeId,
ServerlessPayloads,
ServerlessRoutines,
} from '@remotion/serverless/client';
-import {
- formatMap,
- messageTypeIdToMessageType,
-} from '@remotion/serverless/client';
-import {makeStreamer} from '@remotion/streaming';
-import type {EventEmitter} from 'node:events';
-import type {OrError} from '../functions';
-import type {AwsRegion} from '../regions';
-import {getLambdaClient} from './aws-clients';
-import type {LambdaReturnValues} from './return-values';
-
-const INVALID_JSON_MESSAGE = 'Cannot parse Lambda response as JSON';
-type Options<T extends ServerlessRoutines, Provider extends CloudProvider> = {
+export type CallLambdaOptions<
+ T extends ServerlessRoutines,
+ Provider extends CloudProvider,
+> = {
functionName: string;
type: T;
payload: Omit<ServerlessPayloads<Provider>[T], 'type'>;
region: Provider['region'];
timeoutInTest: number;
};
-
-const parseJsonOrThrowSource = (data: Uint8Array, type: string) => {
- const asString = new TextDecoder('utf-8').decode(data);
- try {
- return JSON.parse(asString);
- } catch {
- throw new Error(`Invalid JSON (${type}): ${asString}`);
- }
-};
-
-export const callLambda = async <
- Provider extends CloudProvider,
- T extends ServerlessRoutines,
->(
- options: Options<T, Provider>,
-): Promise<LambdaReturnValues<Provider>[T]> => {
- // Do not remove this await
- const res = await callLambdaWithoutRetry<T, Provider>(options);
- if (res.type === 'error') {
- const err = new Error(res.message);
- err.stack = res.stack;
- throw err;
- }
-
- return res;
-};
-
-export const callLambdaWithStreaming = async <
- Provider extends CloudProvider,
- T extends ServerlessRoutines,
->(
- options: Options<T, Provider> & {
- receivedStreamingPayload: OnMessage<Provider>;
- retriesRemaining: number;
- },
-): Promise<void> => {
- // As of August 2023, Lambda streaming sometimes misses parts of the JSON response.
- // Handling this for now by applying a retry mechanism.
-
- try {
- // Do not remove this await
- await callLambdaWithStreamingWithoutRetry<T, Provider>(options);
- } catch (err) {
- if ((err as Error).stack?.includes('TooManyRequestsException')) {
- throw new Error(
- `AWS Concurrency limit reached (Original Error: ${(err as Error).message}). See https://www.remotion.dev/docs/lambda/troubleshooting/rate-limit for tips to fix this.`,
- );
- }
-
- if (
- !(err as Error).message.includes(INVALID_JSON_MESSAGE) &&
- !(err as Error).message.includes(LAMBDA_STREAM_STALL) &&
- !(err as Error).message.includes('aborted')
- ) {
- throw err;
- }
-
- console.error('Retries remaining:', options.retriesRemaining);
- if (options.retriesRemaining === 0) {
- console.error('Throwing error:');
- throw err;
- }
-
- console.error(err);
- return callLambdaWithStreaming({
- ...options,
- retriesRemaining: options.retriesRemaining - 1,
- });
- }
-};
-
-const callLambdaWithoutRetry = async <
- T extends ServerlessRoutines,
- Provider extends CloudProvider,
->({
- functionName,
- type,
- payload,
- region,
- timeoutInTest,
-}: Options<T, Provider>): Promise<OrError<LambdaReturnValues<Provider>[T]>> => {
- const Payload = JSON.stringify({type, ...payload});
- const res = await getLambdaClient(region as AwsRegion, timeoutInTest).send(
- new InvokeCommand({
- FunctionName: functionName,
- Payload,
- InvocationType: 'RequestResponse',
- }),
- );
-
- const decoded = new TextDecoder('utf-8').decode(res.Payload);
-
- try {
- return JSON.parse(decoded) as OrError<LambdaReturnValues<Provider>[T]>;
- } catch {
- throw new Error(`Invalid JSON (${type}): ${JSON.stringify(decoded)}`);
- }
-};
-
-const STREAM_STALL_TIMEOUT = 30000;
-const LAMBDA_STREAM_STALL = `AWS did not invoke Lambda in ${STREAM_STALL_TIMEOUT}ms`;
-
-const invokeStreamOrTimeout = async <Provider extends CloudProvider>({
- region,
- timeoutInTest,
- functionName,
- type,
- payload,
-}: {
- region: Provider['region'];
- timeoutInTest: number;
- functionName: string;
- type: string;
- payload: Record<string, unknown>;
-}) => {
- const resProm = getLambdaClient(region as AwsRegion, timeoutInTest).send(
- new InvokeWithResponseStreamCommand({
- FunctionName: functionName,
- Payload: JSON.stringify({type, ...payload}),
- }),
- );
-
- let cleanup = () => undefined;
-
- const timeout = new Promise<InvokeWithResponseStreamCommandOutput>(
- (_resolve, reject) => {
- const int = setTimeout(() => {
- reject(new Error(LAMBDA_STREAM_STALL));
- }, STREAM_STALL_TIMEOUT);
- cleanup = () => {
- clearTimeout(int);
- };
- },
- );
-
- const res = await Promise.race([resProm, timeout]);
-
- cleanup();
-
- return res;
-};
-
-const callLambdaWithStreamingWithoutRetry = async <
- T extends ServerlessRoutines,
- Provider extends CloudProvider,
->({
- functionName,
- type,
- payload,
- region,
- timeoutInTest,
- receivedStreamingPayload,
-}: Options<T, Provider> & {
- receivedStreamingPayload: OnMessage<Provider>;
-}): Promise<void> => {
- const res = await invokeStreamOrTimeout({
- functionName,
- payload,
- region,
- timeoutInTest,
- type,
- });
-
- const {onData, clear} = makeStreamer((status, messageTypeId, data) => {
- const messageType = messageTypeIdToMessageType(
- messageTypeId as MessageTypeId,
- );
- const innerPayload =
- formatMap[messageType] === 'json'
- ? parseJsonOrThrowSource(data, messageType)
- : data;
-
- const message: StreamingMessage<Provider> = {
- successType: status,
- message: {
- type: messageType,
- payload: innerPayload,
- },
- };
-
- receivedStreamingPayload(message);
- });
-
- const dumpBuffers = () => {
- clear();
- };
-
- // @ts-expect-error - We are adding a listener to a global variable
- if (globalThis._dumpUnreleasedBuffers) {
- // @ts-expect-error - We are adding a listener to a global variable
- (globalThis._dumpUnreleasedBuffers as EventEmitter).addListener(
- 'dump-unreleased-buffers',
- dumpBuffers,
- );
- }
-
- const events =
- res.EventStream as AsyncIterable<InvokeWithResponseStreamResponseEvent>;
-
- for await (const event of events) {
- // There are two types of events you can get on a stream.
-
- // `PayloadChunk`: These contain the actual raw bytes of the chunk
- // It has a single property: `Payload`
- if (event.PayloadChunk && event.PayloadChunk.Payload) {
- onData(event.PayloadChunk.Payload);
- }
-
- if (event.InvokeComplete) {
- if (event.InvokeComplete.ErrorCode) {
- const logs = `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~unit~'seconds~editorString~'fields*20*40timestamp*2c*20*40requestId*2c*20*40message*0a*7c*20filter*20*40requestId*20like*20*${res.$metadata.requestId}*22*0a*7c*20sort*20*40timestamp*20asc~source~(~'*2faws*2flambda*2f${functionName}))`;
- if (event.InvokeComplete.ErrorCode === 'Unhandled') {
- throw new Error(
- `Lambda function ${functionName} failed with an unhandled error: ${
- event.InvokeComplete.ErrorDetails as string
- } See ${logs} to see the logs of this invocation.`,
- );
- }
-
- throw new Error(
- `Lambda function ${functionName} failed with error code ${event.InvokeComplete.ErrorCode}: ${event.InvokeComplete.ErrorDetails}. See ${logs} to see the logs of this invocation.`,
- );
- }
- }
-
- // Don't put a `break` statement here, as it will cause the socket to not properly exit.
- }
-
- // @ts-expect-error - We are adding a listener to a global variable
- if (globalThis._dumpUnreleasedBuffers) {
- // @ts-expect-error - We are adding a listener to a global variable
- (globalThis._dumpUnreleasedBuffers as EventEmitter).removeListener(
- 'dump-unreleased-buffers',
- dumpBuffers,
- );
- }
-
- clear();
-};
diff --git a/packages/lambda/src/shared/get-function-version.ts b/packages/lambda/src/shared/get-function-version.ts
index 058aebfc64..1acfcc5bcf 100644
--- a/packages/lambda/src/shared/get-function-version.ts
+++ b/packages/lambda/src/shared/get-function-version.ts
@@ -1,7 +1,7 @@
import type {LogLevel} from '@remotion/renderer';
import {ServerlessRoutines} from '@remotion/serverless/client';
import type {AwsRegion} from '../regions';
-import {callLambda} from './call-lambda';
+import {callLambdaSync} from './call-lambda-sync';
import {COMMAND_NOT_FOUND} from './constants';
export const getFunctionVersion = async ({
@@ -14,7 +14,7 @@ export const getFunctionVersion = async ({
logLevel: LogLevel;
}): Promise<string> => {
try {
- const result = await callLambda({
+ const result = await callLambdaSync({
functionName,
payload: {
logLevel,
diff --git a/packages/lambda/src/test/integration/handlers.test.ts b/packages/lambda/src/test/integration/handlers.test.ts
index f1b7c3336e..5b2d144939 100644
--- a/packages/lambda/src/test/integration/handlers.test.ts
+++ b/packages/lambda/src/test/integration/handlers.test.ts
@@ -1,11 +1,11 @@
import {ServerlessRoutines} from '@remotion/serverless/client';
import {VERSION} from 'remotion/version';
import {expect, test} from 'vitest';
-import {callLambda} from '../../shared/call-lambda';
+import {callLambdaSync} from '../../shared/call-lambda-sync';
test('Call function locally', async () => {
expect(
- await callLambda({
+ await callLambdaSync({
payload: {
logLevel: 'info',
},
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 e227ff41d3..5295444dfe 100644
--- a/packages/lambda/src/test/integration/renders/old-version.test.ts
+++ b/packages/lambda/src/test/integration/renders/old-version.test.ts
@@ -1,7 +1,7 @@
import {RenderInternals} from '@remotion/renderer';
import {ServerlessRoutines} from '@remotion/serverless/client';
import {afterAll, expect, test} from 'vitest';
-import {callLambda} from '../../../shared/call-lambda';
+import {callLambdaSync} from '../../../shared/call-lambda-sync';
afterAll(async () => {
await RenderInternals.killAllBrowsers();
@@ -11,7 +11,7 @@ test('Should fail when using an incompatible version', async () => {
process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE = '2048';
try {
- const aha = await callLambda({
+ const aha = await callLambdaSync({
type: ServerlessRoutines.launch,
payload: {
serveUrl: 'https://competent-mccarthy-56f7c9.netlify.app/',
diff --git a/packages/lambda/src/test/integration/simulate-lambda-render.ts b/packages/lambda/src/test/integration/simulate-lambda-render.ts
index e150cc1e53..ac0b084212 100644
--- a/packages/lambda/src/test/integration/simulate-lambda-render.ts
+++ b/packages/lambda/src/test/integration/simulate-lambda-render.ts
@@ -6,14 +6,14 @@ import {makeLambdaRenderMediaPayload} from '../../api/make-lambda-payload';
import type {RenderMediaOnLambdaInput} from '../../api/render-media-on-lambda';
import {renderMediaOnLambdaOptionalToRequired} from '../../api/render-media-on-lambda';
import type {AwsProvider} from '../../functions/aws-implementation';
-import {callLambda} from '../../shared/call-lambda';
+import {callLambdaSync} from '../../shared/call-lambda-sync';
import {mockImplementation} from '../mock-implementation';
const functionName = 'remotion-dev-render';
const waitUntilDone = async (bucketName: string, renderId: string) => {
while (true) {
- const progress = await callLambda({
+ const progress = await callLambdaSync({
type: ServerlessRoutines.status,
payload: {
bucketName,
@@ -68,7 +68,7 @@ export const simulateLambdaRender = async (
}),
);
- const res = await callLambda<AwsProvider, ServerlessRoutines.start>({
+ const res = await callLambdaSync<AwsProvider, ServerlessRoutines.start>({
type: ServerlessRoutines.start,
payload,
functionName: 'remotion-dev-lambda',
diff --git a/packages/lambda/src/test/integration/webhooks.test.ts b/packages/lambda/src/test/integration/webhooks.test.ts
index e4a64e5bb7..80b42f8b05 100644
--- a/packages/lambda/src/test/integration/webhooks.test.ts
+++ b/packages/lambda/src/test/integration/webhooks.test.ts
@@ -3,7 +3,7 @@ import {ServerlessRoutines} from '@remotion/serverless/client';
import path from 'path';
import {VERSION} from 'remotion/version';
import {beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-import {callLambda} from '../../shared/call-lambda';
+import {callLambdaSync} from '../../shared/call-lambda-sync';
import {mockableHttpClients} from '../../shared/invoke-webhook';
const originalFetch = mockableHttpClients.http;
@@ -57,7 +57,7 @@ describe('Webhooks', () => {
forceIPv4: false,
});
- const res = await callLambda({
+ const res = await callLambdaSync({
type: ServerlessRoutines.start,
payload: {
serveUrl: `http://localhost:${port}`,
@@ -121,7 +121,7 @@ describe('Webhooks', () => {
});
const parsed = res;
- await callLambda({
+ await callLambdaSync({
type: ServerlessRoutines.status,
payload: {
bucketName: parsed.bucketName,
@@ -173,7 +173,7 @@ describe('Webhooks', () => {
forceIPv4: false,
});
- await callLambda({
+ await callLambdaSync({
functionName: 'remotion-dev-lambda',
region: 'us-east-1',
type: ServerlessRoutines.launch,
diff --git a/packages/lambda/src/test/unit/handlers.test.ts b/packages/lambda/src/test/unit/handlers.test.ts
index 03c6768379..a3a4bb0d19 100644
--- a/packages/lambda/src/test/unit/handlers.test.ts
+++ b/packages/lambda/src/test/unit/handlers.test.ts
@@ -1,9 +1,9 @@
import {ServerlessRoutines} from '@remotion/serverless/client';
import {expect, test} from 'vitest';
-import {callLambda} from '../../shared/call-lambda';
+import {callLambdaSync} from '../../shared/call-lambda-sync';
test('Info handler should return version', async () => {
- const response = await callLambda({
+ const response = await callLambdaSync({
type: ServerlessRoutines.info,
payload: {
logLevel: 'info',