🎥 Make videos programmatically with React
`@remotion/lambda`: Fix lambda leak detection
Jonny Burgerb5367e2b291b
diff --git a/packages/lambda/src/functions/helpers/get-browser-instance.ts b/packages/lambda/src/functions/helpers/get-browser-instance.tsindex 5e1b7b4387..7fb83a3944 100644--- a/packages/lambda/src/functions/helpers/get-browser-instance.ts+++ b/packages/lambda/src/functions/helpers/get-browser-instance.ts@@ -44,7 +44,7 @@ const waitForLaunched = () => {};export const forgetBrowserEventLoop = (logLevel: LogLevel) => {- RenderInternals.Log.verbose(+ RenderInternals.Log.infoAdvanced({indent: false, logLevel},'Keeping browser open for next invocation',);@@ -61,6 +61,10 @@ export const getBrowserInstance = async (// Override the `null` value, which might come from CLI with swANGLEgl: chromiumOptions.gl ?? 'swangle',};+ const configurationString = makeConfigurationString(+ actualChromiumOptions,+ logLevel,+ );if (launching) {RenderInternals.Log.info('Already waiting for browser launch...');@@ -70,11 +74,6 @@ export const getBrowserInstance = async (}}- const configurationString = makeConfigurationString(- actualChromiumOptions,- logLevel,- );-if (!_browserInstance) {RenderInternals.Log.info('Cold Lambda function, launching new Lambda function',diff --git a/packages/lambda/src/functions/helpers/leak-detection.ts b/packages/lambda/src/functions/helpers/leak-detection.tsnew file mode 100644index 0000000000..fef03f1dfa--- /dev/null+++ b/packages/lambda/src/functions/helpers/leak-detection.ts@@ -0,0 +1,51 @@+import type {NodeIntrospection} from '../../shared/why-is-node-running';+import {whyIsNodeRunning} from '../../shared/why-is-node-running';++type LeakTimeout = {+ timeout: NodeJS.Timeout;+ awsRequestId: string;+};++let currentRequestId: string | null = null;+let leakDetectionTimeout: LeakTimeout | null = null;++export const stopLeakDetection = () => {+ if (leakDetectionTimeout !== null) {+ clearTimeout(leakDetectionTimeout.timeout);+ leakDetectionTimeout = null;+ }+};++export const setCurrentRequestId = (awsRequestId: string) => {+ currentRequestId = awsRequestId;+};++export const startLeakDetection = (+ leakDetection: NodeIntrospection,+ awsRequestId: string,+) => {+ currentRequestId = awsRequestId;+ leakDetectionTimeout = {+ awsRequestId,+ timeout: setTimeout(() => {+ // First allow request ID to be set+ setTimeout(() => {+ if (currentRequestId !== awsRequestId) {+ // New function, all good+ return;+ }++ console.log(+ 'Leak detected: Lambda function is still running 10s after the render has finished.',+ );+ console.log('You may report this to the Remotion team.');+ console.log('Include the logs below:');+ whyIsNodeRunning(leakDetection);+ console.log('Force-quitting the Lambda function now.');+ process.exit(0);+ }, 100);+ }, 10000),+ };++ leakDetectionTimeout.timeout.unref();+};diff --git a/packages/lambda/src/functions/helpers/request-context.ts b/packages/lambda/src/functions/helpers/request-context.tsnew file mode 100644index 0000000000..fba5d21614--- /dev/null+++ b/packages/lambda/src/functions/helpers/request-context.ts@@ -0,0 +1,5 @@+export type RequestContext = {+ invokedFunctionArn: string;+ getRemainingTimeInMillis: () => number;+ awsRequestId: string;+};diff --git a/packages/lambda/src/functions/index.ts b/packages/lambda/src/functions/index.tsindex e7d08411bb..16ee278c67 100644--- a/packages/lambda/src/functions/index.ts+++ b/packages/lambda/src/functions/index.ts@@ -5,11 +5,13 @@ import type {OrError} from '../shared/return-values';import {compositionsHandler} from './compositions';import {deleteTmpDir} from './helpers/clean-tmpdir';import {getWarm, setWarm} from './helpers/is-warm';+import {setCurrentRequestId, stopLeakDetection} from './helpers/leak-detection';import {generateRandomHashWithLifeCycleRule,validateDeleteAfter,} from './helpers/lifecycle';import {printCloudwatchHelper} from './helpers/print-cloudwatch-helper';+import type {RequestContext} from './helpers/request-context';import type {ResponseStream} from './helpers/streamify-response';import {streamifyResponse} from './helpers/streamify-response';import type {StreamingPayloads} from './helpers/streaming-payloads';@@ -25,14 +27,14 @@ import {stillHandler} from './still';const innerHandler = async (params: LambdaPayload,responseStream: ResponseStream,- context: {- invokedFunctionArn: string;- getRemainingTimeInMillis: () => number;- },+ context: RequestContext,): Promise<void> => {+ setCurrentRequestId(context.awsRequestId);process.env.__RESERVED_IS_INSIDE_REMOTION_LAMBDA = 'true';const timeoutInMilliseconds = context.getRemainingTimeInMillis();+ console.log('AWS Request ID:', context.awsRequestId);+ stopLeakDetection();if (!context?.invokedFunctionArn) {throw new Error('Lambda function unexpectedly does not have context.invokedFunctionArn',@@ -134,10 +136,14 @@ const innerHandler = async (});RenderInternals.setLogLevel(params.logLevel);- const response = await rendererHandler(params, {- expectedBucketOwner: currentUserId,- isWarm,- });+ const response = await rendererHandler(+ params,+ {+ expectedBucketOwner: currentUserId,+ isWarm,+ },+ context,+ );responseStream.write(JSON.stringify(response), () => {responseStream.end();@@ -193,10 +199,7 @@ const innerHandler = async (const routine = async (params: LambdaPayload,responseStream: ResponseStream,- context: {- invokedFunctionArn: string;- getRemainingTimeInMillis: () => number;- },+ context: RequestContext,): Promise<void> => {try {await innerHandler(params, responseStream, context);diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.tsindex 357dab0009..693ad65182 100644--- a/packages/lambda/src/functions/renderer.ts+++ b/packages/lambda/src/functions/renderer.ts@@ -14,10 +14,7 @@ import {RENDERER_PATH_TOKEN,} from '../shared/constants';import {isFlakyError} from '../shared/is-flaky-error';-import {- enableNodeIntrospection,- whyIsNodeRunning,-} from '../shared/why-is-node-running';+import {enableNodeIntrospection} from '../shared/why-is-node-running';import type {ChunkTimingData,ObjectChunkTimingData,@@ -29,7 +26,9 @@ import {import {executablePath} from './helpers/get-chromium-executable-path';import {getCurrentRegionInFunction} from './helpers/get-current-region';import {lambdaWriteFile} from './helpers/io';+import {startLeakDetection} from './helpers/leak-detection';import {onDownloadsHelper} from './helpers/on-downloads-logger';+import type {RequestContext} from './helpers/request-context';import {getTmpDirStateIfENoSp,writeLambdaError,@@ -40,8 +39,6 @@ type Options = {isWarm: boolean;};-let leakDetectionTimeout: NodeJS.Timeout | null = null;-const renderHandler = async (params: LambdaPayload,options: Options,@@ -51,11 +48,6 @@ const renderHandler = async (throw new Error('Params must be renderer');}- if (leakDetectionTimeout !== null) {- clearTimeout(leakDetectionTimeout);- leakDetectionTimeout = null;- }-if (params.launchFunctionConfig.version !== VERSION) {throw new Error(`The version of the function that was specified as "rendererFunctionName" is ${VERSION} but the version of the function that invoked the render is ${params.launchFunctionConfig.version}. Please make sure that the version of the function that is specified as "rendererFunctionName" is the same as the version of the function that is invoked.`,@@ -306,6 +298,7 @@ const renderHandler = async (export const rendererHandler = async (params: LambdaPayload,options: Options,+ requestContext: RequestContext,): Promise<{type: 'success';}> => {@@ -381,17 +374,6 @@ export const rendererHandler = async (} finally {forgetBrowserEventLoop(params.logLevel);- leakDetectionTimeout = setTimeout(() => {- console.log(- 'Leak detected: Lambda function is still running 10s after the render has finished.',- );- console.log('You may report this to the Remotion team.');- console.log('Include the logs below:');- whyIsNodeRunning(leakDetection);- console.log('Force-quitting the Lambda function now.');- process.exit(0);- }, 10000);-- leakDetectionTimeout.unref();+ startLeakDetection(leakDetection, requestContext.awsRequestId);}};diff --git a/packages/lambda/src/shared/why-is-node-running.ts b/packages/lambda/src/shared/why-is-node-running.tsindex 0057bfd896..4bf35f2ecd 100644--- a/packages/lambda/src/shared/why-is-node-running.ts+++ b/packages/lambda/src/shared/why-is-node-running.ts@@ -11,7 +11,7 @@ type Resource = {};};-type NodeIntrospection = {+export type NodeIntrospection = {hook: asyncHooks.AsyncHook;active: Map<number, Resource>;};