Skip to content

🎥 Make videos programmatically with React

initial draft for webhook support

Paul Kuhle16e857af492d
diff --git a/packages/docs/docs/lambda/rendermediaonlambda.md b/packages/docs/docs/lambda/rendermediaonlambda.md
index ff779a56d5..741fb1f6e9 100644
--- a/packages/docs/docs/lambda/rendermediaonlambda.md
+++ b/packages/docs/docs/lambda/rendermediaonlambda.md
@@ -223,7 +223,7 @@ The S3 bucket name in which all files are being saved.
### `cloudWatchLogs`
-_Available from v3.2.10_
+_available from v3.2.10_
A link to CloudWatch (if you haven't disabled it) that you can visit to see the logs for the render.
@@ -235,6 +235,16 @@ If a custom out name is specified and a file already exists at this key in the S
An existing file at the output S3 key will conflict with the render and must be deleted beforehand. If this setting is `false` and a conflict occurs, an error will be thrown.
+### `webhook`
+
+_optional, available from v3.2.XX_
+
+If specified, Remotion will send a POST request to the provided endpoint to notify your application when the Lambda rendering process finishes, errors out or times out.
+
+The request headers include a cryptographic signature that you can use to [validate incoming webhooks](/docs/lambda/validate-webhooks).
+
+DOCUMENT RESPONSE
+
## See also
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/lambda/src/api/render-media-on-lambda.ts)
diff --git a/packages/docs/docs/lambda/validate-webhooks.md b/packages/docs/docs/lambda/validate-webhooks.md
new file mode 100644
index 0000000000..f4504d3ef9
--- /dev/null
+++ b/packages/docs/docs/lambda/validate-webhooks.md
@@ -0,0 +1,25 @@
+---
+sidebar_label: Validate Webhooks
+title: Validate Webhooks
+slug: /lambda/validate-webhooks
+---
+
+```javascript
+import * as Crypto from "crypto";
+
+// Express API endpoint
+router.post("/my-remotion-webhook-endpoint", (req, res) => {
+ const hmac = Crypto.createHmac("sha1", REMOTION_AWS_SECRET_ACCESS_KEY);
+ const signature = `sha1=${hmac
+ .update(JSON.stringify(req.body))
+ .digest("hex")}`;
+
+ if (signature !== req.header("X-REMOTION-SIGNATURE")) {
+ // Request wasn't sent by Remotion
+ // ...
+ } else {
+ // Request was sent by Remotion
+ // ...
+ }
+});
+```
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index 1779ba7c43..11e16dbd12 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -314,6 +314,7 @@ module.exports = {
"lambda/custom-layers",
"lambda/custom-destination",
"lambda/checklist",
+ "lambda/validate-webhooks",
{
type: "category",
label: "Troubleshooting",
diff --git a/packages/lambda/src/api/render-media-on-lambda.ts b/packages/lambda/src/api/render-media-on-lambda.ts
index 211b256598..aee6c1efd2 100644
--- a/packages/lambda/src/api/render-media-on-lambda.ts
+++ b/packages/lambda/src/api/render-media-on-lambda.ts
@@ -48,6 +48,7 @@ export type RenderMediaOnLambdaInput = {
downloadBehavior?: DownloadBehavior | null;
muted?: boolean;
overwrite?: boolean;
+ webhook?: string
};
export type RenderMediaOnLambdaOutput = {
@@ -72,6 +73,7 @@ export type RenderMediaOnLambdaOutput = {
* @param params.region The AWS region in which the media should be rendered.
* @param params.maxRetries How often rendering a chunk may fail before the media render gets aborted. Default "1"
* @param params.logLevel Level of logging that Lambda function should perform. Default "info".
+ * @param params.webhook Webhook URL to be called upon completion or timeout of the rendering process.
* @returns {Promise<RenderMediaOnLambdaOutput>} See documentation for detailed structure
*/
@@ -103,6 +105,7 @@ export const renderMediaOnLambda = async ({
downloadBehavior,
muted,
overwrite,
+ webhook,
}: RenderMediaOnLambdaInput): Promise<RenderMediaOnLambdaOutput> => {
const actualCodec = validateLambdaCodec(codec);
validateServeUrl(serveUrl);
@@ -143,6 +146,7 @@ export const renderMediaOnLambda = async ({
muted: muted ?? false,
version: VERSION,
overwrite: overwrite ?? false,
+ webhook,
},
region,
});
diff --git a/packages/lambda/src/cli/args.ts b/packages/lambda/src/cli/args.ts
index 901b416182..fff0519d05 100644
--- a/packages/lambda/src/cli/args.ts
+++ b/packages/lambda/src/cli/args.ts
@@ -27,6 +27,7 @@ type LambdaCommandLineOptions = {
['architecture']: LambdaArchitecture;
['custom-role-arn']: string | undefined;
privacy: Privacy;
+ webhook: string | undefined;
};
export const parsedLambdaCli = minimist<LambdaCommandLineOptions>(
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index ad98858f3f..9167f14297 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -111,6 +111,7 @@ export const renderCommand = async (args: string[]) => {
concurrencyPerLambda: parsedLambdaCli['concurrency-per-lambda'],
muted,
overwrite,
+ webhook: parsedLambdaCli.webhook ?? undefined
});
const totalSteps = outName ? 5 : 4;
diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.ts
index 57db1069cc..b34ed58be4 100644
--- a/packages/lambda/src/functions/launch.ts
+++ b/packages/lambda/src/functions/launch.ts
@@ -18,6 +18,7 @@ import {
rendersPrefix,
} from '../shared/constants';
import {DOCS_URL} from '../shared/docs-url';
+import {invokeWebhook} from '../shared/invoke-webhook';
import {getServeUrlHash} from '../shared/make-s3-url';
import {validateFramesPerLambda} from '../shared/validate-frames-per-lambda';
import {validateOutname} from '../shared/validate-outname';
@@ -93,6 +94,18 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {
const startedDate = Date.now();
+ let webhookInvoked = false;
+ const webhookDueToTimeout = setTimeout(async () => {
+ if (params.webhook && !webhookInvoked) {
+ await invokeWebhook({
+ url: params.webhook,
+ type: 'timeout',
+ renderId: params.renderId,
+ });
+ webhookInvoked = true;
+ }
+ }, Math.max(params.timeoutInMilliseconds - 1000, 1000));
+
const [browserInstance, optimization] = await Promise.all([
getBrowserInstance(
RenderInternals.isEqualOrBelowLogLevel(params.logLevel, 'verbose'),
@@ -515,6 +528,16 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {
});
await Promise.all([cleanupChunksProm, fs.promises.rm(outfile)]);
+
+ clearTimeout(webhookDueToTimeout);
+ if (params.webhook && !webhookInvoked) {
+ await invokeWebhook({
+ url: params.webhook,
+ type: 'success',
+ renderId: params.renderId,
+ })
+ webhookInvoked = true;
+ }
};
export const launchHandler = async (
@@ -547,5 +570,12 @@ export const launchHandler = async (
expectedBucketOwner: options.expectedBucketOwner,
renderId: params.renderId,
});
+ if (params.webhook) {
+ await invokeWebhook({
+ url: params.webhook,
+ type: 'error',
+ renderId: params.renderId,
+ })
+ }
}
};
diff --git a/packages/lambda/src/functions/start.ts b/packages/lambda/src/functions/start.ts
index 6b58100d4d..ebb2192e4a 100644
--- a/packages/lambda/src/functions/start.ts
+++ b/packages/lambda/src/functions/start.ts
@@ -75,6 +75,7 @@ export const startHandler = async (params: LambdaPayload, options: Options) => {
downloadBehavior: params.downloadBehavior,
muted: params.muted,
overwrite: params.overwrite,
+ webhook: params.webhook,
};
await getLambdaClient(getCurrentRegionInFunction()).send(
new InvokeCommand({
diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.ts
index 0a182d9557..2c6a1e3e91 100644
--- a/packages/lambda/src/shared/constants.ts
+++ b/packages/lambda/src/shared/constants.ts
@@ -226,6 +226,7 @@ export type LambdaPayloads = {
muted: boolean;
version: string;
overwrite: boolean;
+ webhook: string | undefined;
};
launch: {
type: LambdaRoutines.launch;
@@ -256,6 +257,7 @@ export type LambdaPayloads = {
downloadBehavior: DownloadBehavior;
muted: boolean;
overwrite: boolean;
+ webhook: string | undefined;
};
status: {
type: LambdaRoutines.status;
diff --git a/packages/lambda/src/shared/invoke-webhook.ts b/packages/lambda/src/shared/invoke-webhook.ts
new file mode 100644
index 0000000000..8a421dde6c
--- /dev/null
+++ b/packages/lambda/src/shared/invoke-webhook.ts
@@ -0,0 +1,44 @@
+import * as Crypto from 'crypto';
+
+/**
+ * @description Calculates cryptographically secure signature for webhooks using Hmac.
+ * @link https://remotion.dev/docs/lambda/validate-webhooks
+ * @param payload Stringified request body to encode in the signature.
+ */
+export function calculateSignature(payload: string) {
+ const secret =
+ process.env.REMOTION_AWS_SECRET_ACCESS_KEY ?? 'INSECURE_DEFAULT_SECRET';
+ const hmac = Crypto.createHmac('sha1', secret);
+ const signature = 'sha1=' + hmac.update(payload).digest('hex');
+ return signature;
+}
+
+export type InvokeWebhookInput = {
+ url: string;
+ type: 'success' | 'error' | 'timeout';
+ renderId: string;
+};
+
+/**
+ * @description Calls a webhook.
+ * @link https://remotion.dev/docs/lambda/rendermediaonlambda#webhook
+ * @param params.url URL of webhook to call.
+ */
+export async function invokeWebhook({url, type, renderId}: InvokeWebhookInput) {
+ const payload = JSON.stringify({result: type, renderId});
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-REMOTION-SIGNATURE': calculateSignature(payload),
+ },
+ body: payload,
+ });
+ if (response.status > 299) {
+ // do we want to log webhook delivery failures?
+ }
+ } catch {
+ // network error ocurred. Do we log this?
+ }
+}
diff --git a/packages/lambda/src/test/integration/renders/gif.test.ts b/packages/lambda/src/test/integration/renders/gif.test.ts
index f36a3caabe..aa6fd94168 100644
--- a/packages/lambda/src/test/integration/renders/gif.test.ts
+++ b/packages/lambda/src/test/integration/renders/gif.test.ts
@@ -59,6 +59,7 @@ test('Should make a distributed GIF', async () => {
muted: false,
version: VERSION,
overwrite: true,
+ webhook: undefined,
},
extraContext
);
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 a0aea58d64..46c3d0e176 100644
--- a/packages/lambda/src/test/integration/renders/old-version.test.ts
+++ b/packages/lambda/src/test/integration/renders/old-version.test.ts
@@ -58,6 +58,7 @@ test('Should fail when using an incompatible version', async () => {
muted: false,
version: VERSION,
overwrite: true,
+ webhook: undefined,
},
extraContext
);
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 1c4f5cf02d..29ba8942c8 100644
--- a/packages/lambda/src/test/integration/renders/other-bucket.test.ts
+++ b/packages/lambda/src/test/integration/renders/other-bucket.test.ts
@@ -62,6 +62,7 @@ test('Should be able to render to another bucket', async () => {
muted: false,
version: VERSION,
overwrite: true,
+ webhook: undefined,
},
extraContext
);
diff --git a/packages/lambda/src/test/integration/renders/silent-audio.test.ts b/packages/lambda/src/test/integration/renders/silent-audio.test.ts
index ecf4efb10b..e4ef27868f 100644
--- a/packages/lambda/src/test/integration/renders/silent-audio.test.ts
+++ b/packages/lambda/src/test/integration/renders/silent-audio.test.ts
@@ -59,6 +59,7 @@ test('Should add silent audio if there is no audio', async () => {
muted: false,
version: VERSION,
overwrite: true,
+ webhook: undefined,
},
extraContext
);
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 b55684c348..7899e3999c 100644
--- a/packages/lambda/src/test/integration/renders/transparent-webm.test.ts
+++ b/packages/lambda/src/test/integration/renders/transparent-webm.test.ts
@@ -62,6 +62,7 @@ test('Should make a transparent video', async () => {
muted: false,
version: VERSION,
overwrite: true,
+ webhook: undefined,
},
extraContext
);
diff --git a/packages/lambda/src/test/integration/webhooks.test.ts b/packages/lambda/src/test/integration/webhooks.test.ts
new file mode 100644
index 0000000000..fecd0307db
--- /dev/null
+++ b/packages/lambda/src/test/integration/webhooks.test.ts
@@ -0,0 +1,168 @@
+import {RenderInternals} from '@remotion/renderer';
+import {VERSION} from 'remotion/version';
+import {LambdaRoutines} from '../../defaults';
+import {handler} from '../../functions';
+import type {LambdaReturnValues} from '../../shared/return-values';
+import {disableLogs, enableLogs} from '../disable-logs';
+
+jest.setTimeout(90000);
+
+const extraContext = {
+ invokedFunctionArn: 'arn:fake',
+ getRemainingTimeInMillis: () => 12000,
+};
+
+type Await<T> = T extends PromiseLike<infer U> ? U : T;
+
+let originalFetch = global.fetch;
+beforeEach(() => {
+ originalFetch = global.fetch;
+ global.fetch = jest.fn(() =>
+ Promise.resolve({
+ statusText: 'OK',
+ ok: true,
+ status: 201,
+ json: () => Promise.resolve({}),
+ })
+ ) as jest.Mock;
+});
+
+afterEach(() => {
+ global.fetch = originalFetch;
+});
+
+beforeAll(() => {
+ disableLogs();
+});
+
+afterAll(async () => {
+ enableLogs();
+
+ await RenderInternals.killAllBrowsers();
+});
+
+const TEST_URL = 'http://localhost:8000';
+
+describe('Webhooks', () => {
+ test('Should call webhook upon completion', async () => {
+ process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE = '2048';
+
+ const res = await handler(
+ {
+ type: LambdaRoutines.start,
+ serveUrl: 'https://gleaming-wisp-de5d2a.netlify.app/',
+ chromiumOptions: {},
+ codec: 'h264',
+ composition: 'react-svg',
+ crf: 9,
+ envVariables: {},
+ frameRange: [0, 2],
+ framesPerLambda: 8,
+ imageFormat: 'png',
+ inputProps: {},
+ logLevel: 'warn',
+ maxRetries: 3,
+ outName: 'out.mp4',
+ pixelFormat: 'yuv420p',
+ privacy: 'public',
+ proResProfile: undefined,
+ quality: undefined,
+ scale: 1,
+ timeoutInMilliseconds: 12000,
+ numberOfGifLoops: null,
+ everyNthFrame: 1,
+ concurrencyPerLambda: 1,
+ downloadBehavior: {
+ type: 'play-in-browser',
+ },
+ muted: false,
+ version: VERSION,
+ overwrite: true,
+ webhook: TEST_URL,
+ },
+ extraContext
+ );
+ const startRes = res as Await<LambdaReturnValues[LambdaRoutines.start]>;
+
+ (await handler(
+ {
+ type: LambdaRoutines.status,
+ bucketName: startRes.bucketName,
+ renderId: startRes.renderId,
+ version: VERSION,
+ },
+ extraContext
+ )) as Await<LambdaReturnValues[LambdaRoutines.status]>;
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch).toHaveBeenCalledWith(TEST_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-REMOTION-SIGNATURE': expect.stringContaining('sha1='),
+ },
+ body: expect.stringContaining('success'),
+ });
+ });
+
+ test('Should call webhook upon timeout', async () => {
+ process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE = '2048';
+
+ const res = await handler(
+ {
+ type: LambdaRoutines.start,
+ serveUrl: 'https://gleaming-wisp-de5d2a.netlify.app/',
+ chromiumOptions: {},
+ codec: 'h264',
+ composition: 'react-svg',
+ crf: 9,
+ envVariables: {},
+ frameRange: [0, 10],
+ framesPerLambda: 8,
+ imageFormat: 'png',
+ inputProps: {},
+ logLevel: 'warn',
+ maxRetries: 3,
+ outName: 'out.mp4',
+ pixelFormat: 'yuv420p',
+ privacy: 'public',
+ proResProfile: undefined,
+ quality: undefined,
+ scale: 1,
+ timeoutInMilliseconds: 1200,
+ numberOfGifLoops: null,
+ everyNthFrame: 1,
+ concurrencyPerLambda: 1,
+ downloadBehavior: {
+ type: 'play-in-browser',
+ },
+ muted: false,
+ version: VERSION,
+ overwrite: true,
+ webhook: TEST_URL,
+ },
+ extraContext
+ );
+ const startRes = res as Await<LambdaReturnValues[LambdaRoutines.start]>;
+
+ (await handler(
+ {
+ type: LambdaRoutines.status,
+ bucketName: startRes.bucketName,
+ renderId: startRes.renderId,
+ version: VERSION,
+ },
+ extraContext
+ )) as Await<LambdaReturnValues[LambdaRoutines.status]>;
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch).toHaveBeenCalledWith(TEST_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-REMOTION-SIGNATURE': expect.stringContaining('sha1='),
+ },
+ body: expect.stringContaining('timeout'),
+ });
+ });
+});
diff --git a/packages/lambda/src/test/unit/invoke-webhook.test.ts b/packages/lambda/src/test/unit/invoke-webhook.test.ts
new file mode 100644
index 0000000000..8550aff2a7
--- /dev/null
+++ b/packages/lambda/src/test/unit/invoke-webhook.test.ts
@@ -0,0 +1,8 @@
+import {calculateSignature} from '../../shared/invoke-webhook';
+
+test('calculateSignature should return correct sha1 signature', () => {
+ const signature = calculateSignature(JSON.stringify({payload: 'test'}))
+
+ expect(signature).toEqual('sha1=01b2eb8a50128fbe37f67acc440fbaff1159c454');
+ }
+);