Skip to content

🎥 Make videos programmatically with React

use custom http handler

Jonny Burger391de1ad09f4
diff --git a/packages/lambda/.eslintrc b/packages/lambda/.eslintrc
index 2653ce45dd..4b451d60d7 100644
--- a/packages/lambda/.eslintrc
+++ b/packages/lambda/.eslintrc
@@ -7,11 +7,20 @@
"error",
{
"patterns": ["@remotion/cli", "@remotion/*/src/*", "remotion/src/*"],
- "paths": ["remotion", "react", "react-dom"]
- }
- ]
+ "paths": ["remotion", "react", "react-dom"],
+ },
+ ],
},
"overrides": [
+ {
+ "files": "./src/functions/helpers/http-handler/**",
+ "rules": {
+ "new-cap": "off",
+ "prefer-const": "off",
+ "no-eq-null": "off",
+ "eqeqeq": "off",
+ },
+ },
{
"files": "./src/cli/**",
"rules": {
@@ -20,10 +29,10 @@
"error",
{
"patterns": ["@remotion/*/src/*", "remotion/src/*"],
- "paths": ["remotion", "react", "react-dom"]
- }
- ]
- }
- }
- ]
+ "paths": ["remotion", "react", "react-dom"],
+ },
+ ],
+ },
+ },
+ ],
}
diff --git a/packages/lambda/package.json b/packages/lambda/package.json
index c17608d27e..38fbdadcc5 100644
--- a/packages/lambda/package.json
+++ b/packages/lambda/package.json
@@ -35,7 +35,10 @@
"@remotion/streaming": "workspace:*",
"mime-types": "2.1.34",
"remotion": "workspace:*",
- "zod": "3.22.3"
+ "zod": "3.22.3",
+ "@smithy/protocol-http": "4.0.0",
+ "@smithy/querystring-builder": "3.0.0",
+ "@smithy/types": "3.0.0"
},
"devDependencies": {
"@jonny/eslint-config": "3.0.281",
diff --git a/packages/lambda/src/functions/helpers/http-handler/custom-handler.ts b/packages/lambda/src/functions/helpers/http-handler/custom-handler.ts
new file mode 100644
index 0000000000..829c5ba063
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/http-handler/custom-handler.ts
@@ -0,0 +1,325 @@
+import type {HttpHandler, HttpRequest} from '@smithy/protocol-http';
+import {HttpResponse} from '@smithy/protocol-http';
+import {buildQueryString} from '@smithy/querystring-builder';
+import type {
+ HttpHandlerOptions,
+ NodeHttpHandlerOptions,
+ Provider,
+} from '@smithy/types';
+import {Agent as hAgent, request as hRequest} from 'http';
+import type {RequestOptions} from 'https';
+import {Agent as hsAgent, request as hsRequest} from 'https';
+
+import {getTransformedHeaders} from './get-transformed-headers';
+import {setConnectionTimeout} from './set-connection-timeout';
+import {setSocketKeepAlive} from './set-socket-keep-alive';
+import {setSocketTimeout} from './set-socket-timeout';
+import {writeRequestBody} from './write-request-body';
+
+/**
+ * Node.js system error codes that indicate timeout.
+ * @deprecated use NODEJS_TIMEOUT_ERROR_CODES from @smithy/service-error-classification/constants
+ */
+export const NODEJS_TIMEOUT_ERROR_CODES = ['ECONNRESET', 'EPIPE', 'ETIMEDOUT'];
+export {NodeHttpHandlerOptions};
+
+interface ResolvedNodeHttpHandlerConfig
+ extends Omit<NodeHttpHandlerOptions, 'httpAgent' | 'httpsAgent'> {
+ httpAgent: hAgent;
+ httpsAgent: hsAgent;
+}
+
+export const DEFAULT_REQUEST_TIMEOUT = 0;
+
+export class NodeHttpHandler implements HttpHandler<NodeHttpHandlerOptions> {
+ private config?: ResolvedNodeHttpHandlerConfig;
+ private configProvider: Promise<ResolvedNodeHttpHandlerConfig>;
+ private socketWarningTimestamp = 0;
+
+ // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286
+ public readonly metadata = {handlerProtocol: 'http/1.1'};
+
+ /**
+ * @returns the input if it is an HttpHandler of any class,
+ * or instantiates a new instance of this handler.
+ */
+ public static create(
+ instanceOrOptions?:
+ | HttpHandler<any>
+ | NodeHttpHandlerOptions
+ | Provider<NodeHttpHandlerOptions | void>,
+ ) {
+ if (typeof (instanceOrOptions as any)?.handle === 'function') {
+ // is already an instance of HttpHandler.
+ return instanceOrOptions as HttpHandler<any>;
+ }
+
+ // input is ctor options or undefined.
+ return new NodeHttpHandler(instanceOrOptions as NodeHttpHandlerOptions);
+ }
+
+ /**
+ * @internal
+ *
+ * @param agent - http(s) agent in use by the NodeHttpHandler instance.
+ * @returns timestamp of last emitted warning.
+ */
+ public static checkSocketUsage(
+ agent: hAgent | hsAgent,
+ socketWarningTimestamp: number,
+ ): number {
+ // note, maxSockets is per origin.
+ const {sockets, requests, maxSockets} = agent;
+
+ if (typeof maxSockets !== 'number' || maxSockets === Infinity) {
+ return socketWarningTimestamp;
+ }
+
+ const interval = 15_000;
+ if (Date.now() - interval < socketWarningTimestamp) {
+ return socketWarningTimestamp;
+ }
+
+ if (sockets && requests) {
+ for (const origin in sockets) {
+ const socketsInUse = sockets[origin]?.length ?? 0;
+ const requestsEnqueued = requests[origin]?.length ?? 0;
+
+ /**
+ * Running at maximum socket usage can be intentional and normal.
+ * That is why this warning emits at a delay which can be seen
+ * at the call site's setTimeout wrapper. The warning will be cancelled
+ * if the request finishes in a reasonable amount of time regardless
+ * of socket saturation.
+ *
+ * Additionally, when the warning is emitted, there is an interval
+ * lockout.
+ */
+ if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
+ console.warn(
+ '@smithy/node-http-handler:WARN',
+ `socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.`,
+ 'See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html',
+ 'or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.',
+ );
+ return Date.now();
+ }
+ }
+ }
+
+ return socketWarningTimestamp;
+ }
+
+ constructor(
+ options?: NodeHttpHandlerOptions | Provider<NodeHttpHandlerOptions | void>,
+ ) {
+ this.configProvider = new Promise((resolve, reject) => {
+ if (typeof options === 'function') {
+ options()
+ .then((_options) => {
+ resolve(this.resolveDefaultConfig(_options));
+ })
+ .catch(reject);
+ } else {
+ resolve(this.resolveDefaultConfig(options));
+ }
+ });
+ }
+
+ private resolveDefaultConfig(
+ options?: NodeHttpHandlerOptions | void,
+ ): ResolvedNodeHttpHandlerConfig {
+ const {
+ requestTimeout,
+ connectionTimeout,
+ socketTimeout,
+ httpAgent,
+ httpsAgent,
+ } = options || {};
+ const keepAlive = true;
+ const maxSockets = 50;
+
+ return {
+ connectionTimeout,
+ requestTimeout: requestTimeout ?? socketTimeout,
+ httpAgent: (() => {
+ if (
+ httpAgent instanceof hAgent ||
+ typeof (httpAgent as hAgent)?.destroy === 'function'
+ ) {
+ return httpAgent as hAgent;
+ }
+
+ return new hAgent({keepAlive, maxSockets, ...httpAgent});
+ })(),
+ httpsAgent: (() => {
+ if (
+ httpsAgent instanceof hsAgent ||
+ typeof (httpsAgent as hsAgent)?.destroy === 'function'
+ ) {
+ return httpsAgent as hsAgent;
+ }
+
+ return new hsAgent({keepAlive, maxSockets, ...httpsAgent});
+ })(),
+ };
+ }
+
+ destroy(): void {
+ this.config?.httpAgent?.destroy();
+ this.config?.httpsAgent?.destroy();
+ }
+
+ async handle(
+ request: HttpRequest,
+ {abortSignal}: HttpHandlerOptions = {},
+ ): Promise<{response: HttpResponse}> {
+ if (!this.config) {
+ this.config = await this.configProvider;
+ }
+
+ let socketCheckTimeoutId: Timer;
+
+ return new Promise((_resolve, _reject) => {
+ let writeRequestBodyPromise: Promise<void> | undefined;
+ const resolve = async (arg: {response: HttpResponse}) => {
+ await writeRequestBodyPromise;
+ // if requests are still resolving, cancel the socket usage check.
+ clearTimeout(socketCheckTimeoutId);
+ _resolve(arg);
+ };
+
+ const reject = async (arg: unknown) => {
+ await writeRequestBodyPromise;
+ _reject(arg);
+ };
+
+ if (!this.config) {
+ throw new Error('Node HTTP request handler config is not resolved');
+ }
+
+ // if the request was already aborted, prevent doing extra work
+ if (abortSignal?.aborted) {
+ const abortError = new Error('Request aborted');
+ abortError.name = 'AbortError';
+ reject(abortError);
+ return;
+ }
+
+ // determine which http(s) client to use
+ const isSSL = request.protocol === 'https:';
+ const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
+
+ // If the request is taking a long time, check socket usage and potentially warn.
+ // This warning will be cancelled if the request resolves.
+ socketCheckTimeoutId = setTimeout(
+ () => {
+ this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(
+ agent,
+ this.socketWarningTimestamp,
+ );
+ },
+ this.config.socketAcquisitionWarningTimeout ??
+ (this.config.requestTimeout ?? 2000) +
+ (this.config.connectionTimeout ?? 1000),
+ );
+
+ const queryString = buildQueryString(request.query || {});
+ let auth;
+ if (request.username != null || request.password != null) {
+ const username = request.username ?? '';
+ const password = request.password ?? '';
+ auth = `${username}:${password}`;
+ }
+
+ let {path} = request;
+ if (queryString) {
+ path += `?${queryString}`;
+ }
+
+ if (request.fragment) {
+ path += `#${request.fragment}`;
+ }
+
+ const nodeHttpsOptions: RequestOptions = {
+ headers: request.headers,
+ host: request.hostname,
+ method: request.method,
+ path,
+ port: request.port,
+ agent,
+ auth,
+ };
+
+ // create the http request
+ const requestFunc = isSSL ? hsRequest : hRequest;
+
+ const req = requestFunc(nodeHttpsOptions, (res) => {
+ const httpResponse = new HttpResponse({
+ statusCode: res.statusCode || -1,
+ reason: res.statusMessage,
+ headers: getTransformedHeaders(res.headers),
+ body: res,
+ });
+ resolve({response: httpResponse});
+ });
+
+ req.on('error', (err: Error) => {
+ if (NODEJS_TIMEOUT_ERROR_CODES.includes((err as any).code)) {
+ reject(Object.assign(err, {name: 'TimeoutError'}));
+ } else {
+ reject(err);
+ }
+ });
+
+ // wire-up any timeout logic
+ setConnectionTimeout(req, reject, this.config.connectionTimeout);
+ setSocketTimeout(req, reject, this.config.requestTimeout);
+
+ // wire-up abort logic
+ if (abortSignal) {
+ abortSignal.onabort = () => {
+ // ensure request is destroyed
+ req.abort();
+ const abortError = new Error('Request aborted');
+ abortError.name = 'AbortError';
+ reject(abortError);
+ };
+ }
+
+ // Workaround for bug report in Node.js https://github.com/nodejs/node/issues/47137
+ const httpAgent = nodeHttpsOptions.agent;
+ if (typeof httpAgent === 'object' && 'keepAlive' in httpAgent) {
+ setSocketKeepAlive(req, {
+ // @ts-expect-error keepAlive is not public on httpAgent.
+ keepAlive: (httpAgent as hAgent).keepAlive,
+ // @ts-expect-error keepAliveMsecs is not public on httpAgent.
+ keepAliveMsecs: (httpAgent as hAgent).keepAliveMsecs,
+ });
+ }
+
+ writeRequestBodyPromise = writeRequestBody(
+ req,
+ request,
+ this.config.requestTimeout,
+ ).catch(_reject);
+ });
+ }
+
+ updateHttpClientConfig(
+ key: keyof NodeHttpHandlerOptions,
+ value: NodeHttpHandlerOptions[typeof key],
+ ): void {
+ this.config = undefined;
+ this.configProvider = this.configProvider.then((config) => {
+ return {
+ ...config,
+ [key]: value,
+ };
+ });
+ }
+
+ httpHandlerConfigs(): NodeHttpHandlerOptions {
+ return this.config ?? {};
+ }
+}
diff --git a/packages/lambda/src/functions/helpers/http-handler/get-transformed-headers.ts b/packages/lambda/src/functions/helpers/http-handler/get-transformed-headers.ts
new file mode 100644
index 0000000000..5e36d18eaa
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/http-handler/get-transformed-headers.ts
@@ -0,0 +1,17 @@
+import type {HeaderBag} from '@smithy/types';
+import type {IncomingHttpHeaders} from 'http2';
+
+const getTransformedHeaders = (headers: IncomingHttpHeaders) => {
+ const transformedHeaders: HeaderBag = {};
+
+ for (const name of Object.keys(headers)) {
+ const headerValues = <string>headers[name];
+ transformedHeaders[name] = Array.isArray(headerValues)
+ ? headerValues.join(',')
+ : headerValues;
+ }
+
+ return transformedHeaders;
+};
+
+export {getTransformedHeaders};
diff --git a/packages/lambda/src/functions/helpers/http-handler/set-connection-timeout.ts b/packages/lambda/src/functions/helpers/http-handler/set-connection-timeout.ts
new file mode 100644
index 0000000000..545702c74d
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/http-handler/set-connection-timeout.ts
@@ -0,0 +1,37 @@
+import type {ClientRequest} from 'http';
+import type {Socket} from 'net';
+
+export const setConnectionTimeout = (
+ request: ClientRequest,
+ reject: (err: Error) => void,
+ timeoutInMs = 0,
+) => {
+ if (!timeoutInMs) {
+ return;
+ }
+
+ // Throw a connecting timeout error unless a connection is made within time.
+ const timeoutId = setTimeout(() => {
+ request.destroy();
+ reject(
+ Object.assign(
+ new Error(
+ `Socket timed out without establishing a connection within ${timeoutInMs} ms`,
+ ),
+ {
+ name: 'TimeoutError',
+ },
+ ),
+ );
+ }, timeoutInMs);
+
+ request.on('socket', (socket: Socket) => {
+ if (socket.connecting) {
+ socket.on('connect', () => {
+ clearTimeout(timeoutId);
+ });
+ } else {
+ clearTimeout(timeoutId);
+ }
+ });
+};
diff --git a/packages/lambda/src/functions/helpers/http-handler/set-socket-keep-alive.ts b/packages/lambda/src/functions/helpers/http-handler/set-socket-keep-alive.ts
new file mode 100644
index 0000000000..91169312dd
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/http-handler/set-socket-keep-alive.ts
@@ -0,0 +1,19 @@
+import type {ClientRequest} from 'http';
+
+export interface SocketKeepAliveOptions {
+ keepAlive: boolean;
+ keepAliveMsecs?: number;
+}
+
+export const setSocketKeepAlive = (
+ request: ClientRequest,
+ {keepAlive, keepAliveMsecs}: SocketKeepAliveOptions,
+) => {
+ if (keepAlive !== true) {
+ return;
+ }
+
+ request.on('socket', (socket) => {
+ socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
+ });
+};
diff --git a/packages/lambda/src/functions/helpers/http-handler/set-socket-timeout.ts b/packages/lambda/src/functions/helpers/http-handler/set-socket-timeout.ts
new file mode 100644
index 0000000000..1cf236c5e5
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/http-handler/set-socket-timeout.ts
@@ -0,0 +1,17 @@
+import type {ClientRequest} from 'http';
+
+export const setSocketTimeout = (
+ request: ClientRequest,
+ reject: (err: Error) => void,
+ timeoutInMs = 0,
+) => {
+ request.setTimeout(timeoutInMs, () => {
+ // destroy the request
+ request.destroy();
+ reject(
+ Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), {
+ name: 'TimeoutError',
+ }),
+ );
+ });
+};
diff --git a/packages/lambda/src/functions/helpers/http-handler/write-request-body.ts b/packages/lambda/src/functions/helpers/http-handler/write-request-body.ts
new file mode 100644
index 0000000000..7ca9ec2c86
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/http-handler/write-request-body.ts
@@ -0,0 +1,91 @@
+import type {HttpRequest} from '@smithy/types';
+import type {ClientRequest} from 'http';
+import type {ClientHttp2Stream} from 'http2';
+import {Readable} from 'stream';
+
+const MIN_WAIT_TIME = 1000;
+
+/**
+ * This resolves when writeBody has been called.
+ *
+ * @param httpRequest - opened Node.js request.
+ * @param request - container with the request body.
+ * @param maxContinueTimeoutMs - maximum time to wait for the continue event. Minimum of 1000ms.
+ */
+export async function writeRequestBody(
+ httpRequest: ClientRequest | ClientHttp2Stream,
+ request: HttpRequest,
+ maxContinueTimeoutMs = MIN_WAIT_TIME,
+): Promise<void> {
+ const headers = request.headers ?? {};
+ const expect = headers.Expect || headers.expect;
+
+ let timeoutId = -1;
+ let hasError = false;
+
+ if (expect === '100-continue') {
+ await Promise.race<void>([
+ new Promise((resolve) => {
+ timeoutId = Number(
+ setTimeout(resolve, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)),
+ );
+ }),
+ new Promise((resolve) => {
+ httpRequest.on('continue', () => {
+ clearTimeout(timeoutId);
+ resolve();
+ });
+ httpRequest.on('error', () => {
+ hasError = true;
+ clearTimeout(timeoutId);
+ // this handler does not reject with the error
+ // because there is already an error listener
+ // on the request in node-http-handler
+ // and node-http2-handler.
+ resolve();
+ });
+ }),
+ ]);
+ }
+
+ if (!hasError) {
+ writeBody(httpRequest, request.body);
+ }
+}
+
+function writeBody(
+ httpRequest: ClientRequest | ClientHttp2Stream,
+ body?: string | ArrayBuffer | ArrayBufferView | Readable | Uint8Array,
+) {
+ if (body instanceof Readable) {
+ // pipe automatically handles end
+ body.pipe(httpRequest);
+ return;
+ }
+
+ if (body) {
+ if (Buffer.isBuffer(body) || typeof body === 'string') {
+ httpRequest.end(body);
+ return;
+ }
+
+ const uint8 = body as Uint8Array;
+ if (
+ typeof uint8 === 'object' &&
+ uint8.buffer &&
+ typeof uint8.byteOffset === 'number' &&
+ typeof uint8.byteLength === 'number'
+ ) {
+ // this avoids copying the array.
+ httpRequest.end(
+ Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength),
+ );
+ return;
+ }
+
+ httpRequest.end(Buffer.from(body as ArrayBuffer));
+ return;
+ }
+
+ httpRequest.end();
+}
diff --git a/packages/lambda/src/functions/index.ts b/packages/lambda/src/functions/index.ts
index aac4e76655..0cb75213af 100644
--- a/packages/lambda/src/functions/index.ts
+++ b/packages/lambda/src/functions/index.ts
@@ -145,10 +145,14 @@ const innerHandler = async ({
params.logLevel,
);
- const response = await launchHandler(params, {
- expectedBucketOwner: currentUserId,
- getRemainingTimeInMillis: context.getRemainingTimeInMillis,
- });
+ const response = await launchHandler(
+ params,
+ {
+ expectedBucketOwner: currentUserId,
+ getRemainingTimeInMillis: context.getRemainingTimeInMillis,
+ },
+ context,
+ );
await responseWriter.write(Buffer.from(JSON.stringify(response)));
await responseWriter.end();
diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.ts
index 37ce91d6d5..b894b5466f 100644
--- a/packages/lambda/src/functions/launch.ts
+++ b/packages/lambda/src/functions/launch.ts
@@ -30,6 +30,7 @@ import {
import {validateFramesPerLambda} from '../shared/validate-frames-per-lambda';
import {validateOutname} from '../shared/validate-outname';
import {validatePrivacy} from '../shared/validate-privacy';
+import {enableNodeIntrospection} from '../shared/why-is-node-running';
import {planFrameRanges} from './chunk-optimization/plan-frame-ranges';
import {bestFramesPerLambdaParam} from './helpers/best-frames-per-lambda-param';
import {cleanupProps} from './helpers/cleanup-props';
@@ -40,9 +41,11 @@ import {
getBrowserInstance,
} from './helpers/get-browser-instance';
import {getCurrentRegionInFunction} from './helpers/get-current-region';
+import {startLeakDetection} from './helpers/leak-detection';
import {mergeChunksAndFinishRender} from './helpers/merge-chunks';
import type {OverallProgressHelper} from './helpers/overall-render-progress';
import {makeOverallRenderProgress} from './helpers/overall-render-progress';
+import type {RequestContext} from './helpers/request-context';
import {streamRendererFunctionWithRetry} from './helpers/stream-renderer';
import {timer} from './helpers/timer';
import {validateComposition} from './helpers/validate-composition';
@@ -53,6 +56,8 @@ type Options = {
getRemainingTimeInMillis: () => number;
};
+const ENABLE_SLOW_LEAK_DETECTION = true;
+
const innerLaunchHandler = async ({
functionName,
params,
@@ -402,6 +407,7 @@ type CleanupTask = () => Promise<unknown>;
export const launchHandler = async (
params: LambdaPayload,
options: Options,
+ requestContext: RequestContext,
): Promise<{
type: 'success';
}> => {
@@ -424,6 +430,8 @@ export const launchHandler = async (
cleanupTasks.push(task);
};
+ const leakDetection = enableNodeIntrospection(ENABLE_SLOW_LEAK_DETECTION);
+
const onTimeout = async () => {
RenderInternals.Log.error(
{indent: false, logLevel: params.logLevel},
@@ -683,5 +691,7 @@ export const launchHandler = async (
throw err;
} finally {
forgetBrowserEventLoop(params.logLevel);
+
+ startLeakDetection(leakDetection, requestContext.awsRequestId);
}
};
diff --git a/packages/lambda/src/shared/aws-clients.ts b/packages/lambda/src/shared/aws-clients.ts
index 2e263a316f..f8d1f1b1f7 100644
--- a/packages/lambda/src/shared/aws-clients.ts
+++ b/packages/lambda/src/shared/aws-clients.ts
@@ -8,7 +8,6 @@ import {fromIni} from '@aws-sdk/credential-providers';
import {random} from 'remotion/no-react';
import type {AwsRegion} from '../pricing/aws-regions';
import {checkCredentials} from './check-credentials';
-import {MAX_FUNCTIONS_PER_RENDER} from './constants';
import {isInsideLambda} from './is-in-lambda';
const _clients: Partial<
@@ -211,7 +210,8 @@ export const getServiceClient = <T extends keyof ServiceMapping>({
service === 'lambda'
? {
httpsAgent: {
- maxSockets: MAX_FUNCTIONS_PER_RENDER * 2,
+ maxSockets: 100,
+ keepAlive: false,
},
}
: undefined;
diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.ts
index 666dabcf92..5f1a63827e 100644
--- a/packages/lambda/src/shared/call-lambda.ts
+++ b/packages/lambda/src/shared/call-lambda.ts
@@ -8,6 +8,7 @@ import {
InvokeWithResponseStreamCommand,
} from '@aws-sdk/client-lambda';
import {makeStreamer} from '@remotion/streaming';
+import {freemem} from 'os';
import type {OrError} from '../functions';
import type {
MessageTypeId,
@@ -80,6 +81,9 @@ export const callLambdaWithStreaming = async <T extends LambdaRoutines>(
throw err;
}
+ console.error(err);
+ console.error('Retries remaining', options.retriesRemaining);
+
return callLambdaWithStreaming({
...options,
retriesRemaining: options.retriesRemaining - 1,
@@ -182,6 +186,8 @@ const callLambdaWithStreamingWithoutRetry = async <T extends LambdaRoutines>({
? parseJsonOrThrowSource(data, messageType)
: data;
+ console.log('got', data.length, freemem(), process.memoryUsage());
+
const message: StreamingMessage = {
successType: status,
message: {
@@ -206,6 +212,7 @@ const callLambdaWithStreamingWithoutRetry = async <T extends LambdaRoutines>({
}
if (event.InvokeComplete) {
+ console.log('Invoke is now complete!');
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') {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b445e3a309..a70c0b35a0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1362,6 +1362,15 @@ importers:
'@smithy/abort-controller':
specifier: 3.0.0
version: 3.0.0
+ '@smithy/protocol-http':
+ specifier: 4.0.0
+ version: 4.0.0
+ '@smithy/querystring-builder':
+ specifier: 3.0.0
+ version: 3.0.0
+ '@smithy/types':
+ specifier: 3.0.0
+ version: 3.0.0
mime-types:
specifier: 2.1.34
version: 2.1.34