generated from amazon-archives/__template_MIT-0
-
Notifications
You must be signed in to change notification settings - Fork 1k
adding nodejs webhook df pattern #2967
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ginjups
wants to merge
4
commits into
aws-samples:main
Choose a base branch
from
ginjups:ginjups-df-webhook-nodejs-sam
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| # Webhook Receiver with AWS Lambda durable functions - NodeJS | ||
|
|
||
| This serverless pattern demonstrates a serverless webhook receiver using AWS Lambda durable functions with NodeJS. The pattern receives webhook events via API Gateway, processes them durably with automatic checkpointing, and provides status query capabilities. | ||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/testing/patterns/lambda-durable-webhook-sam-nodejs | ||
|
|
||
| To Learn more about Lambda durable functions: | ||
| - [AWS Lambda durable functions Documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) | ||
| - [Lambda durable functions Best Practices](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions-best-practices.html) | ||
|
|
||
| Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. | ||
|
|
||
| ## Requirements | ||
|
|
||
| * [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. | ||
| * [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
| * [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
| * [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed | ||
|
|
||
| ## Architecture | ||
|
|
||
|  | ||
|
|
||
| ## How It Works | ||
|
|
||
| This pattern demonstrates a serverless webhook receiver using AWS Lambda durable functions. The pattern receives webhook events via API Gateway, processes them durably with automatic checkpointing, and provides status query capabilities. The durable function processes webhooks in 3 checkpointed steps: | ||
|
|
||
| 1. **Validate** - Verify webhook payload and structure | ||
| 2. **Process** - Execute business logic on webhook data | ||
| 3. **Finalize** - Complete processing and update final status | ||
|
|
||
| This pattern acheives the following key features: | ||
|
|
||
| - **Automatic Checkpointing** - Each processing step is checkpointed automatically | ||
| - **Failure Recovery** - Resumes from last checkpoint on failure | ||
| - **Asynchronous Processing** - Immediate 202 response, processing in background | ||
| - **State Persistence** - Execution state stored in DynamoDB with TTL | ||
| - **Status Query API** - Real-time status tracking via REST API | ||
|
|
||
| **Note:** Each step writes status updates to DynamoDB before its main work. These writes are idempotent, so retries are safe. During replay, the DynamoDB status reflects the last successfully written state—not the current replay position. Status queries should treat intermediate states as "in progress." | ||
|
|
||
| **Important:** Please check the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) for regions currently supported by AWS Lambda durable functions. | ||
|
|
||
| ## Deployment | ||
|
|
||
| 1. **Build the application**: | ||
| ```bash | ||
| sam build | ||
| ``` | ||
|
|
||
| 2. **Deploy to AWS**: | ||
marcojahn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Plese enter required `WebhookSecret` | ||
|
|
||
| ```bash | ||
| sam deploy --guided | ||
| ``` | ||
|
|
||
| Note the outputs after deployment: | ||
| - `WebhookApiUrl`: Use this for sending webhook POST requests | ||
| - `StatusQueryApiUrl`: Use this for querying execution status | ||
|
|
||
| ## Testing | ||
| To test the set-up, utilize the below curl command by replacing the WebhookApiUrl copied from the above step: | ||
|
|
||
| ```bash | ||
| # Send a test webhook | ||
| curl -X POST <WebhookApiUrl> \ | ||
| -H "Content-Type: application/json" \ | ||
| -d '{ | ||
| "type": "order", | ||
| "orderId": "123456", | ||
| "data": {"amount": 100} | ||
| }' | ||
| ``` | ||
|
|
||
| Once the Webhook is submitted, to query the status of webhook, use the following curl command by replacing the StatusQueryApiUrl: | ||
|
|
||
| ```bash | ||
| # Get execution status (use executionToken from webhook response) | ||
| curl <StatusQueryApiUrl> | ||
| ``` | ||
|
|
||
| **Success indicators:** | ||
marcojahn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| - Webhook returns 202 with `executionToken` | ||
| - Status query shows progression: `STARTED` → `VALIDATING` → `PROCESSING` → `COMPLETED` | ||
| - Execution state persists in DynamoDB with TTL | ||
|
|
||
| To simulate a validation failure, send an invalid payload (empty or missing required fields): | ||
|
|
||
| ```bash | ||
| # Send an invalid webhook (empty payload triggers validation failure) | ||
| curl -X POST <WebhookApiUrl> \ | ||
| -H "Content-Type: application/json" \ | ||
| -d '{}' | ||
| ``` | ||
|
|
||
| Query the status to see the failure: | ||
|
|
||
| ```bash | ||
| curl <StatusQueryApiUrl> | ||
| ``` | ||
|
|
||
| **Failure indicators:** | ||
| - Status query shows `FAILED` status | ||
| - Error message indicates validation failure reason | ||
| - Execution state persists in DynamoDB for debugging | ||
|
|
||
| ## Cleanup | ||
|
|
||
| ```bash | ||
| sam delete | ||
| ``` | ||
| ---- | ||
| Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| SPDX-License-Identifier: MIT-0 | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| { | ||
| "title": "Webhook Receiver with AWS Lambda durable functions - NodeJS", | ||
| "description": "This serverless pattern demonstrates building a webhook receiver using AWS Lambda durable functions with automatic checkpointing and fault tolerance, implemented in Node.js", | ||
| "language": "Node.js", | ||
| "level": "200", | ||
| "framework": "AWS SAM", | ||
| "services": ["apigateway","lambda", "dynamoDB"], | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This pattern demonstrates a serverless webhook receiver using AWS Lambda durable functions. When a webhook POST request arrives via API Gateway, it triggers a durable function that processes the webhook in 3 checkpointed steps: Validate → Process → Finalize. Each step is automatically checkpointed, allowing the workflow to resume from the last successful step if interrupted. The pattern provides immediate 202 response while processing continues in the background, stores execution state in DynamoDB with TTL, and offers real-time status tracking via a REST API." | ||
| ] | ||
| }, | ||
| "testing": { | ||
| "headline": "Testing", | ||
| "text": [ | ||
| "See the GitHub repo for detailed testing instructions." | ||
| ] | ||
| }, | ||
| "cleanup": { | ||
| "headline": "Cleanup", | ||
| "text": [ | ||
| "Delete the stack: <code>sam delete</code>." | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": [ | ||
| "sam build", | ||
| "sam deploy --guided" | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-webhook-sam-nodejs", | ||
| "templateURL":"serverless-patterns/lambda-durable-webhook-sam-nodejs", | ||
| "templateFile": "template.yaml", | ||
| "projectFolder": "lambda-durable-webhook-sam-nodejs" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "headline": "Additional resources", | ||
| "bullets": [ | ||
| { | ||
| "text": "AWS Lambda durable functions Documentation", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" | ||
| }, | ||
| { | ||
| "text": "Event Source Mappings with Lambda durable functions", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-invoking-esm.html" | ||
| }, | ||
| { | ||
| "text": "Lambda durable functions Best Practices", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions-best-practices.html" | ||
| }, | ||
| { | ||
| "text": "Node.js AWS SDK Documentation", | ||
| "link": "https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/" | ||
| } | ||
| ] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Sahithi Ginjupalli", | ||
| "image": "https://drive.google.com/file/d/1YcKYuGz3LfzSxiwb2lWJfpyi49SbvOSr/view?usp=sharing", | ||
| "bio": "Cloud Engineer at AWS with a passion for diving deep into cloud and AI services to build innovative serverless applications.", | ||
| "linkedin": "ginjupalli-sahithi-37460a18b", | ||
| "twitter": "" | ||
| } | ||
| ] | ||
| } |
100 changes: 100 additions & 0 deletions
100
lambda-durable-webhook-sam-nodejs/src/status_query/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| const { DynamoDBClient } = require('@aws-sdk/client-dynamodb'); | ||
| const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb'); | ||
|
|
||
| // Initialize AWS clients | ||
| const dynamodbClient = new DynamoDBClient({}); | ||
| const dynamodb = DynamoDBDocumentClient.from(dynamodbClient); | ||
|
|
||
| /** | ||
| * Status query function for webhook processing | ||
| * Allows real-time status tracking via REST API | ||
| */ | ||
| exports.handler = async (event, context) => { | ||
| const executionToken = event.pathParameters?.executionToken; | ||
| const eventsTableName = process.env.EVENTS_TABLE_NAME; | ||
|
|
||
| console.log(`Querying status for execution token: ${executionToken}`); | ||
|
|
||
| if (!executionToken) { | ||
| return { | ||
| statusCode: 400, | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| 'Access-Control-Allow-Origin': '*' | ||
| }, | ||
| body: JSON.stringify({ | ||
| error: 'Missing executionToken parameter' | ||
| }) | ||
| }; | ||
| } | ||
|
|
||
| try { | ||
| // Query execution state from DynamoDB | ||
| const result = await dynamodb.send(new GetCommand({ | ||
| TableName: eventsTableName, | ||
| Key: { executionToken } | ||
| })); | ||
|
|
||
| if (!result.Item) { | ||
| return { | ||
| statusCode: 404, | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| 'Access-Control-Allow-Origin': '*' | ||
| }, | ||
| body: JSON.stringify({ | ||
| error: 'Execution token not found', | ||
| executionToken: executionToken | ||
| }) | ||
| }; | ||
| } | ||
|
|
||
| // Format response based on current status | ||
| const execution = result.Item; | ||
| const response = { | ||
| executionToken: executionToken, | ||
| status: execution.status, | ||
| timestamp: execution.timestamp, | ||
| currentStep: execution.currentStep || 'unknown' | ||
| }; | ||
|
|
||
| // Add additional fields based on status | ||
| if (execution.status === 'COMPLETED') { | ||
| response.result = execution.result; | ||
| response.completedAt = execution.completedAt; | ||
| } | ||
|
|
||
| if (execution.status === 'FAILED') { | ||
| response.error = execution.error; | ||
| } | ||
|
|
||
| if (execution.payload) { | ||
| response.originalPayload = execution.payload; | ||
| } | ||
|
|
||
| return { | ||
| statusCode: 200, | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| 'Access-Control-Allow-Origin': '*' | ||
| }, | ||
| body: JSON.stringify(response) | ||
| }; | ||
|
|
||
| } catch (error) { | ||
| console.error(`Error querying status for ${executionToken}:`, error.message); | ||
|
|
||
| return { | ||
| statusCode: 500, | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| 'Access-Control-Allow-Origin': '*' | ||
| }, | ||
| body: JSON.stringify({ | ||
| error: 'Failed to query execution status', | ||
| executionToken: executionToken, | ||
| message: error.message | ||
| }) | ||
| }; | ||
| } | ||
| }; |
15 changes: 15 additions & 0 deletions
15
lambda-durable-webhook-sam-nodejs/src/status_query/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "name": "status-query-function", | ||
| "version": "1.0.0", | ||
| "description": "Status query function for webhook processing", | ||
| "main": "index.js", | ||
| "scripts": { | ||
| "test": "echo \"Error: no test specified\" && exit 1" | ||
| }, | ||
| "dependencies": { | ||
| "@aws-sdk/client-dynamodb": "^3.700.0", | ||
| "@aws-sdk/lib-dynamodb": "^3.700.0" | ||
| }, | ||
| "author": "", | ||
| "license": "MIT" | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.