From d27fa82f91e438a513a6814abdf5f41abe106167 Mon Sep 17 00:00:00 2001 From: Tomasz Czubocha Date: Wed, 25 Nov 2026 23:48:26 +0000 Subject: [PATCH] feat(aws-node-eventbridge-rule): add an EventBridge rule example with a content filter and a live test --- README.md | 1 + aws-node-eventbridge-rule/.gitignore | 2 + aws-node-eventbridge-rule/README.md | 143 +++++++++++++++++++++++ aws-node-eventbridge-rule/example.json | 28 +++++ aws-node-eventbridge-rule/handler.mjs | 6 + aws-node-eventbridge-rule/serverless.yml | 25 ++++ aws-node-eventbridge-rule/test/smoke.mjs | 90 ++++++++++++++ examples.json | 12 ++ 8 files changed, 307 insertions(+) create mode 100644 aws-node-eventbridge-rule/.gitignore create mode 100644 aws-node-eventbridge-rule/README.md create mode 100644 aws-node-eventbridge-rule/example.json create mode 100644 aws-node-eventbridge-rule/handler.mjs create mode 100644 aws-node-eventbridge-rule/serverless.yml create mode 100644 aws-node-eventbridge-rule/test/smoke.mjs diff --git a/README.md b/README.md index da198b4ce..cdb1f6ff0 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ serverless deploy | [REST API with a JWT authorizer and Amazon Cognito (NodeJS)](https://github.com/serverless/examples/tree/v4/aws-node-rest-api-jwt-authorizer)
Protect API Gateway REST API endpoints with a JWT authorizer that trusts an Amazon Cognito user pool, require an OAuth scope on one of them, and read the caller's claims in Node.js. | nodeJS | | [GPU function with PyTorch on Lambda Managed Instances](https://github.com/serverless/examples/tree/v4/aws-python-gpu-managed-instances)
This example runs a Python function with PyTorch on an NVIDIA GPU, using AWS Lambda Managed Instances and the Serverless Framework. | python | | [AppSync GraphQL API with DynamoDB (NodeJS)](https://github.com/serverless/examples/tree/v4/aws-node-appsync-dynamodb)
An AWS AppSync GraphQL API with API key authentication and two JavaScript resolvers that write and read posts in a DynamoDB table, from the built-in appSync block of serverless.yml. | nodeJS | +| [Node EventBridge Rule on AWS](https://github.com/serverless/examples/tree/v4/aws-node-eventbridge-rule)
This example shows how an Amazon EventBridge rule on the default event bus invokes a Lambda function only for the events that match its content filter. | nodeJS | ## Community Examples diff --git a/aws-node-eventbridge-rule/.gitignore b/aws-node-eventbridge-rule/.gitignore new file mode 100644 index 000000000..2c4448065 --- /dev/null +++ b/aws-node-eventbridge-rule/.gitignore @@ -0,0 +1,2 @@ +node_modules +.serverless diff --git a/aws-node-eventbridge-rule/README.md b/aws-node-eventbridge-rule/README.md new file mode 100644 index 000000000..a0d83aced --- /dev/null +++ b/aws-node-eventbridge-rule/README.md @@ -0,0 +1,143 @@ + + +# Trigger a Lambda function from an EventBridge rule + +[![Verified](https://raw.githubusercontent.com/serverless/examples/verified/badges/aws-node-eventbridge-rule.svg)](https://github.com/serverless/examples/blob/verified/results.json) + +A Lambda function can react to events on an Amazon EventBridge event bus without polling and without knowing who publishes them. The [`eventBridge` event](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge) of the Serverless Framework creates a rule on the account's default event bus with an event pattern, and EventBridge invokes the function only for the events that match it. This example's pattern matches `OrderPlaced` events from the source `orders.app` whose `total` is 100 or more: an order of 250 reaches the function, an order of 40 doesn't. + +## What it deploys + +- A Lambda function, `orderPlaced`, that logs each order it receives. +- An EventBridge rule on the default event bus with the example's event pattern, the function as its target, and a Lambda permission that lets EventBridge invoke the function. +- An IAM role that lets the function write its logs, and a CloudWatch Logs log group for the function. + +The example uses the default event bus, which exists in every account and Region, so it deploys no bus. + +## Prerequisites + +- The Serverless Framework CLI: `npm i -g serverless`, which needs [Node.js](https://nodejs.org/). See [Getting started](https://www.serverless.com/framework/docs/getting-started). +- An AWS account, with credentials configured on your machine. See [AWS credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials). +- A Serverless account, or a license key in `SERVERLESS_LICENSE_KEY`. The CLI asks you to sign in the first time you run it. +- The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), to publish events. The commands in Try it are written for Bash. + +## Deploy + +Deploy from this directory: + +```bash +serverless deploy +``` + +Without options, the deploy uses the stage `dev` and the Region `us-east-1`. To change them, pass `--stage` or `--region`, and pass the same options to every later command, including `serverless remove`. Pass the same Region to the AWS CLI in Try it. + +You should see output like this: + +```text +Deploying "eventbridge-rule" to stage "dev" (us-east-1) +✔ Service deployed to stack eventbridge-rule-dev (104s) +functions: + orderPlaced: eventbridge-rule-dev-orderPlaced (5.7 kB) +``` + +## Try it + +Publish two orders to the default event bus, one with a total of 250 and one with a total of 40: + +```bash +aws events put-events --region us-east-1 --entries '[ + {"Source": "orders.app", "DetailType": "OrderPlaced", "Detail": "{\"orderId\": \"o-1001\", \"total\": 250}"}, + {"Source": "orders.app", "DetailType": "OrderPlaced", "Detail": "{\"orderId\": \"o-1002\", \"total\": 40}"} +]' +``` + +EventBridge accepts both and returns an ID for each: + +```json +{ + "FailedEntryCount": 0, + "Entries": [ + { + "EventId": "6d97f2af-9a63-4249-d5f6-b3123538ec71" + }, + { + "EventId": "4fd5e5f0-58d4-1f54-08ae-d7271cc83a56" + } + ] +} +``` + +Read the function's log: + +```bash +serverless logs --function orderPlaced +``` + +Among Lambda's own `START`, `END` and `REPORT` lines, the function's line names only the first order: + +```text +INFO Order o-1001 placed: total 250, event 6d97f2af-9a63-4249-d5f6-b3123538ec71 +``` + +The order of 40 doesn't match the pattern, so EventBridge didn't invoke the function for it. If the command prints `No existing streams for the function`, or the line isn't there yet, wait a few seconds and run it again. + +## How it works + +The `eventBridge` event in [`serverless.yml`](https://github.com/serverless/examples/blob/v4/aws-node-eventbridge-rule/serverless.yml) has no `eventBus`, so the Framework creates the rule on the default event bus. Its `pattern` becomes the rule's event pattern: an event matches when its `source`, its `detail-type` and the `total` in its `detail` all match. `numeric` compares numbers; EventBridge patterns also match exact values, prefixes, `anything-but` lists and more ([event patterns](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)): + +```yaml +functions: + orderPlaced: + handler: handler.orderPlaced + events: + - eventBridge: + pattern: + source: + - orders.app + detail-type: + - OrderPlaced + detail: + total: + - numeric: ['>=', 100] +``` + +The Framework also adds the Lambda permission that lets EventBridge invoke the function, limited to the rule's ARN. The function needs no IAM permission to receive events. + +EventBridge invokes the function asynchronously with one event per invocation. The event's own fields (`id`, `source`, `detail-type`, `time`) surround the payload in `detail`. [`handler.mjs`](https://github.com/serverless/examples/blob/v4/aws-node-eventbridge-rule/handler.mjs) logs the order from `detail` and the event's ID: + +```javascript +export const orderPlaced = async (event) => { + const { orderId, total } = event.detail; + console.log(`Order ${orderId} placed: total ${total}, event ${event.id}`); +}; +``` + +Every rule on the default bus sees every event published to it, so other consumers add their own rules for the same events without a change to the publisher. AWS services publish their events to the default bus too: a pattern with `source: [aws.s3]` or `source: [aws.ec2]` invokes a function for S3 or EC2 events in the same way. + +## Cost and cleanup + +While the example is deployed, Amazon EventBridge bills each custom event published to the bus, Lambda bills each invocation and the function's compute time, and CloudWatch Logs bills the function's stored log data. See [Amazon EventBridge pricing](https://aws.amazon.com/eventbridge/pricing/), [Lambda pricing](https://aws.amazon.com/lambda/pricing/) and [CloudWatch pricing](https://aws.amazon.com/cloudwatch/pricing/). + +Remove the rule, the function, its IAM role and its log group: + +```bash +serverless remove +``` + +The default event bus stays, as it does in every account. + +## Next steps + +- Read [EventBridge events](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge) for rules on other buses, schedules, input transformation, retry policies and dead-letter queues. +- Subscribe functions to a Custom Event Bus, with ordered and batched delivery, as the [compose-eventbridge-custom-bus example](https://github.com/serverless/examples/tree/v4/compose-eventbridge-custom-bus) does. +- Process each event once, with retries and a dead-letter queue, as the [SQS worker example](https://github.com/serverless/examples/tree/v4/aws-node-sqs-worker) does. diff --git a/aws-node-eventbridge-rule/example.json b/aws-node-eventbridge-rule/example.json new file mode 100644 index 000000000..509f9bf10 --- /dev/null +++ b/aws-node-eventbridge-rule/example.json @@ -0,0 +1,28 @@ +{ + "title": "Node EventBridge Rule on AWS", + "description": "This example shows how an Amazon EventBridge rule on the default event bus invokes a Lambda function only for the events that match its content filter.", + "language": "node", + "platform": "AWS", + "framework": "v4", + "author": { + "name": "Serverless, Inc.", + "link": "https://github.com/serverless", + "avatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" + }, + "services": [ + "lambda", + "eventbridge", + "iam", + "logs" + ], + "test": { + "tier": "fast", + "checks": [ + { + "script": { + "path": "test/smoke.mjs" + } + } + ] + } +} diff --git a/aws-node-eventbridge-rule/handler.mjs b/aws-node-eventbridge-rule/handler.mjs new file mode 100644 index 000000000..dd65fd315 --- /dev/null +++ b/aws-node-eventbridge-rule/handler.mjs @@ -0,0 +1,6 @@ +// Invoked by EventBridge with one matching event per invocation. The event's +// payload is in `detail`. +export const orderPlaced = async (event) => { + const { orderId, total } = event.detail; + console.log(`Order ${orderId} placed: total ${total}, event ${event.id}`); +}; diff --git a/aws-node-eventbridge-rule/serverless.yml b/aws-node-eventbridge-rule/serverless.yml new file mode 100644 index 000000000..e61b0b171 --- /dev/null +++ b/aws-node-eventbridge-rule/serverless.yml @@ -0,0 +1,25 @@ +service: eventbridge-rule + +frameworkVersion: '4' + +provider: + name: aws + runtime: nodejs24.x + architecture: arm64 + +functions: + orderPlaced: + handler: handler.orderPlaced + events: + # Creates a rule on the account's default event bus and lets EventBridge + # invoke the function for every event that matches the pattern. + - eventBridge: + pattern: + source: + - orders.app + detail-type: + - OrderPlaced + # Only orders with a total of 100 or more reach the function. + detail: + total: + - numeric: ['>=', 100] diff --git a/aws-node-eventbridge-rule/test/smoke.mjs b/aws-node-eventbridge-rule/test/smoke.mjs new file mode 100644 index 000000000..b1771d373 --- /dev/null +++ b/aws-node-eventbridge-rule/test/smoke.mjs @@ -0,0 +1,90 @@ +// Does what the README's Try it does: publishes two OrderPlaced events to the +// default event bus, one with a total of 250 and one with a total of 40. Then +// waits for the function's log line for the first order, and checks that the +// second, which the rule's pattern filters out, never reached the function. +// +// Run by the example test runner, with the stack outputs in EXAMPLE_OUTPUTS, +// EXAMPLE_REGION set and AWS credentials in the environment. It calls the aws +// CLI to publish the events (events put-events) and to read the function's log +// group (logs filter-log-events). + +import { execFileSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; + +const DELAY_MS = 3_000; +// A new rule can take a moment to match events, so the events are published again until one arrives. +const LOG_WAIT_MS = 180_000; +const REPUBLISH_MS = 30_000; +// After the matching order arrived, how long the filtered order has to show up if the filter didn't hold. +const FILTERED_WAIT_MS = 20_000; + +const outputs = JSON.parse(process.env.EXAMPLE_OUTPUTS ?? '{}'); +const functionArn = outputs.OrderPlacedLambdaFunctionQualifiedArn; +if (!functionArn) fail(`stack output OrderPlacedLambdaFunctionQualifiedArn needed; got ${Object.keys(outputs).join(', ')}`); +// arn:aws:lambda:::function:: +const logGroup = `/aws/lambda/${functionArn.split(':')[6]}`; +const region = ['--region', process.env.EXAMPLE_REGION ?? 'us-east-1']; + +const tag = randomBytes(4).toString('hex'); +const bigOrder = `o-${tag}-1`; +const smallOrder = `o-${tag}-2`; +const wanted = `Order ${bigOrder} placed: total 250`; +const start = Date.now(); + +let lastPublish = 0; +let text = ''; +for (;;) { + if (Date.now() - lastPublish >= REPUBLISH_MS) { + publish(); + lastPublish = Date.now(); + } + const lines = logLines(); + if (lines.some((line) => line.includes(wanted))) break; + text = lines.length ? lines.join(' | ') : 'no line for this run yet'; + if (Date.now() - start >= LOG_WAIT_MS) fail(`${logGroup}: no "${wanted}" line within ${LOG_WAIT_MS / 1000} s; last: ${text.slice(0, 300)}`); + await sleep(DELAY_MS); +} + +await sleep(FILTERED_WAIT_MS); +const filtered = logLines().filter((line) => line.includes(smallOrder)); +if (filtered.length) fail(`${logGroup}: order ${smallOrder} with a total of 40 reached the function: ${filtered[0].slice(0, 300)}`); + +console.log(`put-events -> function logged "${wanted}"; order ${smallOrder} with a total of 40 was filtered out`); + +function publish() { + const entries = [ + { orderId: bigOrder, total: 250 }, + { orderId: smallOrder, total: 40 }, + ].map((detail) => ({ Source: 'orders.app', DetailType: 'OrderPlaced', Detail: JSON.stringify(detail) })); + const out = JSON.parse(aws(['events', 'put-events', ...region, '--entries', JSON.stringify(entries), '--output', 'json'])); + if (out.FailedEntryCount) fail(`put-events: ${JSON.stringify(out.Entries).slice(0, 300)}`); +} + +function logLines() { + try { + const out = aws(['logs', 'filter-log-events', ...region, '--log-group-name', logGroup, + '--filter-pattern', `"o-${tag}"`, '--start-time', String(start - 60_000), '--output', 'json']); + return JSON.parse(out).events.map((e) => e.message.trim()); + } catch (err) { + // The log group exists only after the first invocation. + text = err.message; + return []; + } +} + +function aws(args) { + try { + return execFileSync('aws', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (err) { + throw new Error(`aws ${args.slice(0, 2).join(' ')}: exit ${err.status}, ${String(err.stderr ?? '').trim().slice(0, 300)}`); + } +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function fail(message) { + console.error(`smoke test failed: ${message}`); + process.exit(1); +} diff --git a/examples.json b/examples.json index 13f3f9f4f..f4f0daab0 100644 --- a/examples.json +++ b/examples.json @@ -2898,5 +2898,17 @@ "authorLink": "https://github.com/serverless", "authorName": "Serverless, Inc.", "authorAvatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" + }, + { + "title": "Node EventBridge Rule on AWS", + "name": "aws-node-eventbridge-rule", + "description": "This example shows how an Amazon EventBridge rule on the default event bus invokes a Lambda function only for the events that match its content filter.", + "githubUrl": "https://github.com/serverless/examples/tree/v4/aws-node-eventbridge-rule", + "framework": "v4", + "language": "node", + "platform": "aws", + "authorLink": "https://github.com/serverless", + "authorName": "Serverless, Inc.", + "authorAvatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" } ]