diff --git a/lambda-durable-webhook-sam-nodejs/README.md b/lambda-durable-webhook-sam-nodejs/README.md new file mode 100644 index 000000000..792882433 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/README.md @@ -0,0 +1,202 @@ +# 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. + +## 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. + +### Webhook Processing Workflow (3 Steps) + +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 + +✅ Each step is automatically checkpointed, allowing the workflow to resume from the last successful step if interrupted. + +## 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 + +## Important + +⚠️ **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. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-webhook-sam-python + +## Prerequisites + +- [AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +- [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) installed +- [Node.js 24.x](https://nodejs.org/en/download/) runtime installed +- [Docker](https://docs.docker.com/get-docker/) (for containerized builds) + +## Required IAM Permissions + +Your AWS CLI user/role needs the following permissions for deployment: + +- **CloudFormation**: `cloudformation:DescribeStacks`, `cloudformation:DeleteStack` +- **Lambda**: `lambda:CreateFunction`, `lambda:InvokeFunction`, `lambda:GetFunction` +- **DynamoDB**: `dynamodb:Scan`, `dynamodb:GetItem`, `dynamodb:PutItem` +- **CloudWatch Logs**: `logs:DescribeLogGroups`, `logs:FilterLogEvents`, `logs:GetLogEvents`, `logs:TailLogEvents` + +## Deployment + +1. **Build the application**: + ```bash + sam build + ``` + +2. **Deploy to AWS**: + ```bash + sam deploy --guided + ``` + + Note the outputs after deployment: + - `WebhookApiUrl`: Use this for sending webhook POST requests + - `StatusQueryApiUrl`: Use this for querying execution status + +3. **Test the webhook**: + ```bash + # Send a test webhook + curl -X POST \ + -H "Content-Type: application/json" \ + -d '{ + "type": "order", + "orderId": "123456", + "data": {"amount": 100} + }' + ``` + +4. **Query webhook status**: + ```bash + # Get execution status (use executionToken from webhook response) + curl + ``` + + **Success indicators:** + - Webhook returns 202 with `executionToken` + - Status query shows progression: `STARTED` → `VALIDATING` → `PROCESSING` → `COMPLETED` + - Execution state persists in DynamoDB with TTL + - Failed webhooks show `FAILED` status with error details + +## Architecture + +![Architecture Diagram](architecture.png) + +## Components + +### 1. Webhook Processor Function (`src/webhook_processor/`) +- **Lambda durable function**: Main orchestrator with automatic checkpointing +- **3-Step Processing**: Validate → Process → Finalize +- **API Gateway Integration**: Receives POST requests at `/webhook` +- **State Persistence**: Stores execution state in DynamoDB +- **Dependencies**: `@aws-sdk/client-dynamodb`, `@aws-sdk/lib-dynamodb`, `aws-durable-execution-sdk` + +### 2. Webhook Validator Function (`src/webhook_validator/`) +- **Validation Logic**: Validates webhook payload structure and required fields +- **Extensible**: Easy to add custom validation rules +- **Dependencies**: None (pure Node.js) + +### 3. Status Query Function (`src/status_query/`) +- **Real-time Status**: Query execution status via GET `/status/{executionToken}` +- **CORS Enabled**: Supports browser-based queries +- **Dependencies**: `@aws-sdk/client-dynamodb`, `@aws-sdk/lib-dynamodb` + +## API Endpoints + +### POST /webhook +Receives webhook events for processing. + +**Request:** +```json +{ + "type": "order", + "orderId": "123456", + "data": {"amount": 100} +} +``` + +**Response (202):** +```json +{ + "message": "Webhook processing completed successfully", + "executionToken": "dev-esm-abc123", + "status": "COMPLETED", + "result": { ... } +} +``` + +### GET /status/{executionToken} +Query processing status of a webhook. + +**Response (200):** +```json +{ + "executionToken": "dev-esm-abc123", + "status": "COMPLETED", + "timestamp": "2023-...", + "currentStep": "finalize", + "result": { ... } +} +``` + +## Monitoring + +- **CloudWatch Logs**: Execution tracking for all functions +- **DynamoDB**: Persistent execution state with TTL (7 days) +- **API Gateway**: Request/response logging and metrics + +## Configuration + +Key environment variables: +- `ENVIRONMENT`: Deployment environment (dev/prod) +- `EVENTS_TABLE_NAME`: DynamoDB table for execution state +- `WEBHOOK_VALIDATOR_FUNCTION_ARN`: ARN of validation function +- `WEBHOOK_SECRET`: Optional secret for HMAC signature validation + +## Error Handling + +- **Automatic Retries**: Built-in retry logic with exponential backoff +- **State Recovery**: Resume from last checkpoint on failure +- **Error Tracking**: Failed executions stored with error details +- **Timeout Handling**: Configurable execution timeout (default: 1 hour) + +## Cost Optimization + +- **Pay-per-execution**: Only charged for active processing time +- **Automatic scaling**: Scales based on incoming webhook volume +- **TTL Storage**: Automatic cleanup of old execution records + +## NodeJS Implementation Notes + +- **Node.js 24.x runtime** (latest LTS) +- **AWS SDK v3** with modular imports for optimal performance +- **Modern async/await** syntax throughout +- **Command pattern** for DynamoDB operations +- **Individual package.json** files for each function + +## Security Considerations + +- **CORS Configuration**: Configurable for your domain requirements +- **Webhook Secrets**: Optional HMAC signature validation support +- **IAM Permissions**: Principle of least privilege for all functions + +## Cleanup + +```bash +sam delete +``` + +## Learn More + +- [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) +- [AWS SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- [Node.js AWS SDK v3 Documentation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/) diff --git a/lambda-durable-webhook-sam-nodejs/architecture.png b/lambda-durable-webhook-sam-nodejs/architecture.png new file mode 100644 index 000000000..985ed009b Binary files /dev/null and b/lambda-durable-webhook-sam-nodejs/architecture.png differ diff --git a/lambda-durable-webhook-sam-nodejs/example-pattern.json b/lambda-durable-webhook-sam-nodejs/example-pattern.json new file mode 100644 index 000000000..c21314a7c --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/example-pattern.json @@ -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: sam delete." + ] + }, + "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": "" + } + ] + } diff --git a/lambda-durable-webhook-sam-nodejs/src/status_query/index.js b/lambda-durable-webhook-sam-nodejs/src/status_query/index.js new file mode 100644 index 000000000..d1b08d816 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/status_query/index.js @@ -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 + }) + }; + } +}; diff --git a/lambda-durable-webhook-sam-nodejs/src/status_query/package.json b/lambda-durable-webhook-sam-nodejs/src/status_query/package.json new file mode 100644 index 000000000..a8013300e --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/status_query/package.json @@ -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" +} diff --git a/lambda-durable-webhook-sam-nodejs/src/webhook_processor/index.js b/lambda-durable-webhook-sam-nodejs/src/webhook_processor/index.js new file mode 100644 index 000000000..9357353ed --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/webhook_processor/index.js @@ -0,0 +1,230 @@ +import { withDurableExecution } from "@aws/durable-execution-sdk-js"; +import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; +import { DynamoDBDocumentClient, PutCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; +import { randomUUID } from 'crypto'; + +// Initialize AWS clients +const dynamodbClient = new DynamoDBClient({}); +const dynamodb = DynamoDBDocumentClient.from(dynamodbClient); + +export const handler = withDurableExecution( + async (event, context) => { + /** + * Webhook processor durable function with 3 checkpointed steps: + * 1. Validate webhook + * 2. Process business logic + * 3. Finalize processing + */ + + // Extract configuration from environment + const eventsTableName = process.env.EVENTS_TABLE_NAME; + const environment = process.env.ENVIRONMENT || 'dev'; + + // Parse the incoming webhook event + const webhookPayload = JSON.parse(event.body || '{}'); + + // Use executionToken from API Gateway or generate new one + const executionToken = event.executionToken || randomUUID(); + + console.log(`Processing webhook with execution token: ${executionToken}`); + console.log(`Webhook payload:`, JSON.stringify(webhookPayload, null, 2)); + + try { + // Store initial execution state + await dynamodb.send(new PutCommand({ + TableName: eventsTableName, + Item: { + executionToken: executionToken, + status: 'STARTED', + timestamp: Date.now(), + payload: webhookPayload, + ttl: Math.floor(Date.now() / 1000) + (7 * 24 * 60 * 60) // 7 days TTL + } + })); + + // Step 1: Validate webhook (checkpointed) + const validationResult = await context.step(async (stepContext) => { + stepContext.logger.info(`Validating webhook ${executionToken}`); + + // Update status to VALIDATING + await dynamodb.send(new UpdateCommand({ + TableName: eventsTableName, + Key: { executionToken }, + UpdateExpression: 'SET #status = :status, #step = :step', + ExpressionAttributeNames: { + '#status': 'status', + '#step': 'currentStep' + }, + ExpressionAttributeValues: { + ':status': 'VALIDATING', + ':step': 'validate' + } + })); + + // Call the separate webhook validator function + const { LambdaClient, InvokeCommand } = await import('@aws-sdk/client-lambda'); + const lambdaClient = new LambdaClient({}); + + const validatorFunctionArn = process.env.WEBHOOK_VALIDATOR_FUNCTION_ARN; + const invokeResponse = await lambdaClient.send(new InvokeCommand({ + FunctionName: validatorFunctionArn, + Payload: JSON.stringify({ + payload: webhookPayload, + executionToken: executionToken + }) + })); + + const validatorResult = JSON.parse(new TextDecoder().decode(invokeResponse.Payload)); + + if (!validatorResult.isValid) { + await dynamodb.send(new UpdateCommand({ + TableName: eventsTableName, + Key: { executionToken }, + UpdateExpression: 'SET #status = :status, #error = :error', + ExpressionAttributeNames: { + '#status': 'status', + '#error': 'error' + }, + ExpressionAttributeValues: { + ':status': 'FAILED', + ':error': 'Validation failed: ' + validatorResult.errors.join(', ') + } + })); + + return { + executionToken: executionToken, + status: "failed", + error: `Validation failed: ${validatorResult.errors.join(', ')}` + }; + } + + return { + executionToken: executionToken, + status: "validated", + payloadType: validatorResult.payloadType, + validatedAt: validatorResult.validatedAt + }; + }); + + // Check if validation failed + if (validationResult.status === "failed") { + return { + statusCode: 400, + body: JSON.stringify({ + executionToken: executionToken, + status: 'FAILED', + error: validationResult.error + }) + }; + } + + // Step 2: Process business logic (checkpointed) + const processingResult = await context.step(async (stepContext) => { + stepContext.logger.info(`Processing webhook ${executionToken}`); + + // Update status to PROCESSING + await dynamodb.send(new UpdateCommand({ + TableName: eventsTableName, + Key: { executionToken }, + UpdateExpression: 'SET #status = :status, #step = :step', + ExpressionAttributeNames: { + '#status': 'status', + '#step': 'currentStep' + }, + ExpressionAttributeValues: { + ':status': 'PROCESSING', + ':step': 'process' + } + })); + + // Simulate business processing logic - customize this based on your needs + return { + executionToken: executionToken, + status: "processed", + originalPayload: webhookPayload, + businessResult: `Processed webhook of type: ${webhookPayload.type || 'unknown'}`, + dataTransformed: webhookPayload.data ? JSON.stringify(webhookPayload.data).toUpperCase() : null, + processedAt: new Date().toISOString(), + metadata: { + processedBy: 'webhook-processor-nodejs', + version: '1.0.0' + } + }; + }); + + // Step 3: Finalize processing (checkpointed) + const finalResult = await context.step(async (stepContext) => { + stepContext.logger.info(`Finalizing webhook ${executionToken}`); + + // Update final status to COMPLETED + await dynamodb.send(new UpdateCommand({ + TableName: eventsTableName, + Key: { executionToken }, + UpdateExpression: 'SET #status = :status, #step = :step, #result = :result, #completedAt = :completedAt', + ExpressionAttributeNames: { + '#status': 'status', + '#step': 'currentStep', + '#result': 'result', + '#completedAt': 'completedAt' + }, + ExpressionAttributeValues: { + ':status': 'COMPLETED', + ':step': 'finalize', + ':result': processingResult, + ':completedAt': new Date().toISOString() + } + })); + + return { + executionToken: executionToken, + status: "completed", + finalResult: processingResult + }; + }); + + // Return final response + return { + statusCode: 202, + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + message: 'Webhook processing completed successfully', + executionToken: executionToken, + status: 'COMPLETED', + result: finalResult + }) + }; + + } catch (error) { + console.error(`Error processing webhook ${executionToken}:`, error.message); + + // Update error state + await dynamodb.send(new UpdateCommand({ + TableName: eventsTableName, + Key: { executionToken }, + UpdateExpression: 'SET #status = :status, #error = :error', + ExpressionAttributeNames: { + '#status': 'status', + '#error': 'error' + }, + ExpressionAttributeValues: { + ':status': 'FAILED', + ':error': error.message + } + })); + + return { + statusCode: 500, + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + message: 'Webhook processing failed', + executionToken: executionToken, + error: error.message + }) + }; + } + } +); diff --git a/lambda-durable-webhook-sam-nodejs/src/webhook_processor/package.json b/lambda-durable-webhook-sam-nodejs/src/webhook_processor/package.json new file mode 100644 index 000000000..751bd6573 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/webhook_processor/package.json @@ -0,0 +1,18 @@ +{ + "name": "webhook-processor-function", + "version": "1.0.0", + "description": "Main webhook processor durable function", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { + "@aws-sdk/client-dynamodb": "^3.700.0", + "@aws-sdk/client-lambda": "^3.700.0", + "@aws-sdk/lib-dynamodb": "^3.700.0", + "@aws/durable-execution-sdk-js": "^1.0.0" + }, + "type": "module", + "author": "", + "license": "MIT" +} diff --git a/lambda-durable-webhook-sam-nodejs/src/webhook_validator/index.js b/lambda-durable-webhook-sam-nodejs/src/webhook_validator/index.js new file mode 100644 index 000000000..dd14c94f8 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/webhook_validator/index.js @@ -0,0 +1,62 @@ +/** + * Webhook validator function that validates incoming webhook payloads + * Called by the durable webhook processor function + */ +exports.handler = async (event, context) => { + const { payload, executionToken } = event; + + console.log(`Validating webhook for execution: ${executionToken}`); + + try { + // Basic validation rules - customize based on your webhook requirements + const validationErrors = []; + + // Check if payload exists + if (!payload || typeof payload !== 'object') { + validationErrors.push('Payload is required and must be an object'); + } else { + // Check required fields - customize these based on your webhook schema + if (!payload.type) { + validationErrors.push('Payload must include a "type" field'); + } + + // Validate webhook signature/auth if needed + // if (!payload.signature) { + // validationErrors.push('Webhook signature is required'); + // } + + // Add custom validation logic here + if (payload.type && !['order', 'payment', 'user', 'system'].includes(payload.type)) { + validationErrors.push('Invalid webhook type. Must be one of: order, payment, user, system'); + } + + // Validate payload structure based on type + if (payload.type === 'order' && !payload.orderId) { + validationErrors.push('Order webhooks must include orderId'); + } + + if (payload.type === 'payment' && !payload.transactionId) { + validationErrors.push('Payment webhooks must include transactionId'); + } + } + + const isValid = validationErrors.length === 0; + + return { + isValid: isValid, + executionToken: executionToken, + errors: validationErrors, + validatedAt: new Date().toISOString(), + payloadType: payload?.type || 'unknown' + }; + + } catch (error) { + console.error(`Error validating webhook ${executionToken}:`, error.message); + return { + isValid: false, + executionToken: executionToken, + errors: [`Validation error: ${error.message}`], + error: error.message + }; + } +}; diff --git a/lambda-durable-webhook-sam-nodejs/src/webhook_validator/package.json b/lambda-durable-webhook-sam-nodejs/src/webhook_validator/package.json new file mode 100644 index 000000000..929ff79d5 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/webhook_validator/package.json @@ -0,0 +1,12 @@ +{ + "name": "webhook-validator-function", + "version": "1.0.0", + "description": "Webhook validation function", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": {}, + "author": "", + "license": "MIT" +} diff --git a/lambda-durable-webhook-sam-nodejs/template.yaml b/lambda-durable-webhook-sam-nodejs/template.yaml new file mode 100644 index 000000000..7d772809c --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/template.yaml @@ -0,0 +1,247 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: 'Webhook Receiver Pattern using AWS Lambda durable functions with Python - NodeJS version' + +Globals: + Function: + Timeout: 900 + MemorySize: 512 + Runtime: nodejs24.x + +Parameters: + Environment: + Type: String + Default: dev + Description: Environment name + WebhookSecret: + Type: String + Default: '' + Description: Secret key for HMAC signature validation (optional) + NoEcho: true + +Resources: + # DynamoDB table for storing webhook execution events + WebhookEventsTable: + Type: AWS::DynamoDB::Table + Properties: + TableName: !Sub '${Environment}-webhook-events' + BillingMode: PAY_PER_REQUEST + AttributeDefinitions: + - AttributeName: executionToken + AttributeType: S + - AttributeName: timestamp + AttributeType: N + KeySchema: + - AttributeName: executionToken + KeyType: HASH + TimeToLiveSpecification: + AttributeName: ttl + Enabled: true + GlobalSecondaryIndexes: + - IndexName: TimestampIndex + KeySchema: + - AttributeName: timestamp + KeyType: HASH + Projection: + ProjectionType: ALL + + # Webhook Validator Function + WebhookValidatorFunction: + Type: AWS::Serverless::Function + Properties: + FunctionName: !Sub '${Environment}-webhook-validator' + CodeUri: src/webhook_validator/ + Handler: index.handler + + # Main Webhook Processor Lambda durable function + WebhookProcessorFunction: + Type: AWS::Serverless::Function + Properties: + FunctionName: !Sub '${Environment}-webhook-processor' + CodeUri: src/webhook_processor/ + Handler: index.handler + Timeout: 900 + DurableConfig: + ExecutionTimeout: 3600 + RetentionPeriodInDays: 7 + Policies: + Statement: + - Effect: Allow + Action: + - lambda:CheckpointDurableExecutions + - lambda:GetDurableExecutionState + Resource: !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${Environment}-webhook-processor' + - Effect: Allow + Action: + - lambda:InvokeFunction + Resource: + - !GetAtt WebhookValidatorFunction.Arn + - Effect: Allow + Action: + - dynamodb:GetItem + - dynamodb:PutItem + - dynamodb:UpdateItem + - dynamodb:DeleteItem + - dynamodb:Query + - dynamodb:Scan + Resource: + - !GetAtt WebhookEventsTable.Arn + - !Sub '${WebhookEventsTable.Arn}/index/*' + AutoPublishAlias: live + Environment: + Variables: + WEBHOOK_VALIDATOR_FUNCTION_ARN: !GetAtt WebhookValidatorFunction.Arn + EVENTS_TABLE_NAME: !Ref WebhookEventsTable + ENVIRONMENT: !Ref Environment + WEBHOOK_SECRET: !Ref WebhookSecret + + # API Gateway Method for Webhook (Asynchronous Invocation) + WebhookMethod: + Type: AWS::ApiGateway::Method + Properties: + RestApiId: !Ref WebhookApi + ResourceId: !Ref WebhookResource + HttpMethod: POST + AuthorizationType: NONE + Integration: + Type: AWS + IntegrationHttpMethod: POST + Uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${WebhookProcessorFunction.Arn}:live/invocations' + RequestParameters: + integration.request.header.X-Amz-Invocation-Type: "'Event'" + RequestTemplates: + application/json: | + #set($executionToken = $context.requestId) + { + "body": "$util.escapeJavaScript($input.body)", + "executionToken": "$executionToken" + } + IntegrationResponses: + - StatusCode: 202 + ResponseTemplates: + application/json: | + { + "message": "Webhook accepted for processing", + "executionToken": "$context.requestId" + } + MethodResponses: + - StatusCode: 202 + + # API Gateway Resource for Webhook + WebhookResource: + Type: AWS::ApiGateway::Resource + Properties: + RestApiId: !Ref WebhookApi + ParentId: !GetAtt WebhookApi.RootResourceId + PathPart: webhook + + # Lambda Permission for API Gateway + WebhookLambdaPermission: + Type: AWS::Lambda::Permission + DependsOn: WebhookProcessorFunctionAliaslive + Properties: + FunctionName: !Sub '${WebhookProcessorFunction.Arn}:live' + Action: lambda:InvokeFunction + Principal: apigateway.amazonaws.com + SourceArn: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebhookApi}/*/*' + + # Status Query Function (without Events - using manual API Gateway) + StatusQueryFunction: + Type: AWS::Serverless::Function + Properties: + FunctionName: !Sub '${Environment}-status-query' + CodeUri: src/status_query/ + Handler: index.handler + Timeout: 30 + Environment: + Variables: + EVENTS_TABLE_NAME: !Ref WebhookEventsTable + Policies: + - DynamoDBReadPolicy: + TableName: !Ref WebhookEventsTable + + # API Gateway Resource for Status Query + StatusResource: + Type: AWS::ApiGateway::Resource + Properties: + RestApiId: !Ref WebhookApi + ParentId: !GetAtt WebhookApi.RootResourceId + PathPart: status + + # API Gateway Resource for Status Token + StatusTokenResource: + Type: AWS::ApiGateway::Resource + Properties: + RestApiId: !Ref WebhookApi + ParentId: !Ref StatusResource + PathPart: '{executionToken}' + + # API Gateway Method for Status Query + StatusQueryMethod: + Type: AWS::ApiGateway::Method + Properties: + RestApiId: !Ref WebhookApi + ResourceId: !Ref StatusTokenResource + HttpMethod: GET + AuthorizationType: NONE + Integration: + Type: AWS_PROXY + IntegrationHttpMethod: POST + Uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StatusQueryFunction.Arn}/invocations' + MethodResponses: + - StatusCode: 200 + + # Lambda Permission for Status Query + StatusQueryLambdaPermission: + Type: AWS::Lambda::Permission + Properties: + FunctionName: !GetAtt StatusQueryFunction.Arn + Action: lambda:InvokeFunction + Principal: apigateway.amazonaws.com + SourceArn: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebhookApi}/*/*' + + # API Gateway REST API + WebhookApi: + Type: AWS::ApiGateway::RestApi + Properties: + Name: !Sub '${Environment}-webhook-api' + Description: 'Webhook API for durable functions' + EndpointConfiguration: + Types: + - REGIONAL + + # API Gateway Stage + WebhookApiStage: + Type: AWS::ApiGateway::Stage + Properties: + RestApiId: !Ref WebhookApi + DeploymentId: !Ref WebhookApiDeployment + StageName: prod + Description: 'Production stage with executionToken' + + # API Gateway Deployment (depends on all methods) + WebhookApiDeployment: + Type: AWS::ApiGateway::Deployment + DependsOn: + - WebhookMethod + - StatusQueryMethod + Properties: + RestApiId: !Ref WebhookApi + Description: !Sub 'Production stage ${AWS::StackName}' + +Outputs: + WebhookApiUrl: + Description: 'API Gateway endpoint URL for webhook' + Value: !Sub 'https://${WebhookApi}.execute-api.${AWS::Region}.amazonaws.com/prod/webhook' + + StatusQueryApiUrl: + Description: 'API Gateway endpoint URL for status queries' + Value: !Sub 'https://${WebhookApi}.execute-api.${AWS::Region}.amazonaws.com/prod/status/{executionToken}' + + WebhookEventsTable: + Description: 'DynamoDB Table for webhook events' + Value: !Ref WebhookEventsTable + + WebhookProcessorFunctionArn: + Description: 'Webhook Processor Lambda durable function ARN' + Value: !GetAtt WebhookProcessorFunction.Arn