Skip to content

🎥 Make videos programmatically with React

lock

Jonny Burger3faf6b9c05f5
diff --git a/packages/lambda/package.json b/packages/lambda/package.json
index 38fbdadcc5..c17608d27e 100644
--- a/packages/lambda/package.json
+++ b/packages/lambda/package.json
@@ -35,10 +35,7 @@
"@remotion/streaming": "workspace:*",
"mime-types": "2.1.34",
"remotion": "workspace:*",
- "zod": "3.22.3",
- "@smithy/protocol-http": "4.0.0",
- "@smithy/querystring-builder": "3.0.0",
- "@smithy/types": "3.0.0"
+ "zod": "3.22.3"
},
"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
deleted file mode 100644
index 829c5ba063..0000000000
--- a/packages/lambda/src/functions/helpers/http-handler/custom-handler.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-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
deleted file mode 100644
index 5e36d18eaa..0000000000
--- a/packages/lambda/src/functions/helpers/http-handler/get-transformed-headers.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-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
deleted file mode 100644
index 545702c74d..0000000000
--- a/packages/lambda/src/functions/helpers/http-handler/set-connection-timeout.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-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
deleted file mode 100644
index 91169312dd..0000000000
--- a/packages/lambda/src/functions/helpers/http-handler/set-socket-keep-alive.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-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
deleted file mode 100644
index 1cf236c5e5..0000000000
--- a/packages/lambda/src/functions/helpers/http-handler/set-socket-timeout.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-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
deleted file mode 100644
index 7ca9ec2c86..0000000000
--- a/packages/lambda/src/functions/helpers/http-handler/write-request-body.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-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/shared/aws-clients.ts b/packages/lambda/src/shared/aws-clients.ts
index 658e027e3f..2e263a316f 100644
--- a/packages/lambda/src/shared/aws-clients.ts
+++ b/packages/lambda/src/shared/aws-clients.ts
@@ -5,11 +5,10 @@ import {S3Client} from '@aws-sdk/client-s3';
import {ServiceQuotasClient} from '@aws-sdk/client-service-quotas';
import {STSClient} from '@aws-sdk/client-sts';
import {fromIni} from '@aws-sdk/credential-providers';
-import {Agent} from 'https';
import {random} from 'remotion/no-react';
-import {NodeHttpHandler} from '../functions/helpers/http-handler/custom-handler';
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<
@@ -210,18 +209,11 @@ export const getServiceClient = <T extends keyof ServiceMapping>({
const lambdaOptions =
service === 'lambda'
- ? new NodeHttpHandler({
- httpsAgent: new Agent({
- keepAlive: true,
- maxSockets: 300, // default is 50 per client.
- }),
-
- // time limit (ms) for receiving response.
- requestTimeout: 30_000,
-
- // time limit (ms) for establishing connection.
- connectionTimeout: 6_000,
- })
+ ? {
+ httpsAgent: {
+ maxSockets: MAX_FUNCTIONS_PER_RENDER * 2,
+ },
+ }
: undefined;
const client = customCredentials
diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.ts
index 0c7b65f3a0..0eee2bd9cb 100644
--- a/packages/lambda/src/shared/call-lambda.ts
+++ b/packages/lambda/src/shared/call-lambda.ts
@@ -210,7 +210,6 @@ 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 a70c0b35a0..b445e3a309 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1362,15 +1362,6 @@ 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