diff --git a/lambda-durable-webhook-sam-nodejs/README.md b/lambda-durable-webhook-sam-nodejs/README.md new file mode 100644 index 000000000..5622d4a03 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/README.md @@ -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 + +![Architecture Diagram](architecture.png) + +## 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**: +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 \ + -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 + ``` + + **Success indicators:** + - 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 \ + -H "Content-Type: application/json" \ + -d '{}' + ``` + +Query the status to see the failure: + + ```bash + curl + ``` + + **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 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..fde5bf768 --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/src/webhook_processor/index.js @@ -0,0 +1,254 @@ +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 { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda'; +import { randomUUID } from 'crypto'; + +// Initialize AWS clients at module scope for connection reuse +const dynamodbClient = new DynamoDBClient({}); +const dynamodb = DynamoDBDocumentClient.from(dynamodbClient); +const lambdaClient = new LambdaClient({}); + +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 + * + * Design Note: Each step writes a status update to DynamoDB before doing its main work. + * DynamoDB UpdateCommand is naturally idempotent for these status writes. + * The DynamoDB status reflects the last successfully written status, not necessarily + * the current replay position. + */ + + // 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 || '{}'); + + // Step 0: Initialize execution (checkpointed) - handles non-deterministic operations + const initResult = await context.step('initialize-execution', async (stepContext) => { + // Generate executionToken inside step to ensure determinism on replay + const token = event.executionToken || randomUUID(); + const startTimestamp = Date.now(); + + stepContext.logger.info(`Initializing webhook processing with token: ${token}`); + stepContext.logger.info(`Webhook payload: ${JSON.stringify(webhookPayload)}`); + + // Store initial execution state + await dynamodb.send(new PutCommand({ + TableName: eventsTableName, + Item: { + executionToken: token, + status: 'STARTED', + timestamp: startTimestamp, + payload: webhookPayload, + ttl: Math.floor(startTimestamp / 1000) + (7 * 24 * 60 * 60) // 7 days TTL + } + })); + + return { + executionToken: token, + startTimestamp: startTimestamp + }; + }); + + const executionToken = initResult.executionToken; + + try { + // Step 1: Validate webhook (checkpointed) + const validationResult = await context.step('validate-webhook', 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 validatorFunctionArn = process.env.WEBHOOK_VALIDATOR_FUNCTION_ARN; + const invokeResponse = await lambdaClient.send(new InvokeCommand({ + FunctionName: validatorFunctionArn, + InvocationType: 'RequestResponse', + 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('process-webhook', async (stepContext) => { + stepContext.logger.info(`Processing webhook ${executionToken}`); + + // Generate timestamp once at start of step for consistency + const processedAt = new Date().toISOString(); + + // 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 + // Keep state minimal - store IDs and references, not full objects + return { + executionToken, + status: "processed", + payloadType: webhookPayload.type || 'unknown', + processedAt: processedAt + }; + }); + + // Step 3: Finalize processing (checkpointed) + const finalResult = await context.step('finalize-webhook', async (stepContext) => { + stepContext.logger.info(`Finalizing webhook ${executionToken}`); + + // Generate timestamp once at start of step for consistency + const completedAt = new Date().toISOString(); + + // 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': completedAt + } + })); + + return { + executionToken: executionToken, + status: "completed", + completedAt: completedAt + }; + }); + + // 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) { + // Wrap error handling in a step to ensure proper checkpoint behavior + const errorResult = await context.step('handle-error', async (stepContext) => { + stepContext.logger.error(`Error processing webhook ${executionToken}: ${error.message}`); + + 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 { + status: 'FAILED', + error: error.message + }; + }); + + return { + statusCode: 500, + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + message: 'Webhook processing failed', + executionToken: executionToken, + ...errorResult + }) + }; + } + } +); \ No newline at end of file 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..65e616b6c --- /dev/null +++ b/lambda-durable-webhook-sam-nodejs/template.yaml @@ -0,0 +1,244 @@ +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: + - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole + - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy + - Statement: + - 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