Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions sampleapps/LambdaMessaging/HandlerSampleRequest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"Records": [
{
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
"receiptHandle": "MessageReceiptHandle",
"body": "{\"id\":\"d9b4bfc7-9398-44aa-8049-85c07490fb35\",\"source\":\"/AWSLambda/FunctionName\",\"specversion\":\"1.0\",\"type\":\"chatMessage\",\"time\":\"2024-03-22T21:01:03.5484607+00:00\",\"data\":\"{\\u0022MessageDescription\\u0022:\\u0022Testing!!!\\u0022}\"}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1523232000000",
"SenderId": "123456789012",
"ApproximateFirstReceiveTimestamp": "1523232000001"
},
"messageAttributes": {},
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:{partition}:sqs:{region}:123456789012:MyQueue",
"awsRegion": "{region}"
}
]
}
9 changes: 3 additions & 6 deletions sampleapps/LambdaMessaging/LambdaMessaging.csproj
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AWSProjectType>Lambda</AWSProjectType>
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<!-- Generate ready to run images during publishing to improve cold start time. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="2.2.0" />
<PackageReference Include="Amazon.Lambda.Annotations" Version="1.7.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.0" />
<PackageReference Include="Amazon.Lambda.SQSEvents" Version="2.2.0" />
<PackageReference Include="Amazon.Lambda.Annotations" Version="1.1.0" />
<PackageReference Include="Amazon.Lambda.Logging.AspNetCore" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.*" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AWS.Messaging.Lambda\AWS.Messaging.Lambda.csproj" />
Expand Down
11 changes: 7 additions & 4 deletions sampleapps/LambdaMessaging/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
{
"profiles": {
"Mock Lambda Test Tool": {
"Default": {
"workingDirectory": ".\\bin\\$(Configuration)\\net8.0",
"commandName": "Executable",
"commandLineArgs": "--port 5050",
"workingDirectory": ".\\bin\\$(Configuration)\\net6.0",
"executablePath": "%USERPROFILE%\\.dotnet\\tools\\dotnet-lambda-test-tool-6.0.exe"
"commandLineArgs": "exec --depsfile ./LambdaMessaging.deps.json --runtimeconfig ./LambdaMessaging.runtimeconfig.json %USERPROFILE%/.dotnet/tools/.store/amazon.lambda.testtool/${VERSION}/amazon.lambda.testtool/${VERSION}/content/Amazon.Lambda.RuntimeSupport/net8.0/Amazon.Lambda.RuntimeSupport.dll LambdaMessaging::LambdaMessaging.Function_FunctionHandler_Generated::FunctionHandler",
"executablePath": "dotnet",
"environmentVariables": {
"AWS_LAMBDA_RUNTIME_API": "localhost:5050/MyFunction"
}
}
}
}
79 changes: 79 additions & 0 deletions sampleapps/LambdaMessaging/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Lambda Messaging Sample Application

This sample application demonstrates how to use AWS Lambda with the AWS Message Processing Framework for .NET to process messages from SQS queues.

## Overview

This sample shows how to:
- Configure a Lambda function to process messages from SQS
- Use dependency injection with Lambda Annotations
- Handle message batch processing
- Implement partial batch failure responses
- Set up message handlers for specific message types

## Prerequisites

- .NET 8.0 or later


## Project Structure

```
LambdaMessaging/
├── Function.cs # Lambda function handler
├── Startup.cs # DI and service configuration
├── ChatMessage.cs # Message type definition
├── ChatMessageHandler.cs # Message handler implementation
├── LambdaMessaging.csproj # Project file
```


## Getting Started

In order to test the lambda function locally with the messaging processing framework, it requires installing the Lambda Test Tool https://github.com/aws/aws-lambda-dotnet/blob/master/Tools/LambdaTestTool-v2 first.

1. Build the project

```
dotnet build
```

2Install the AWS Lambda Test Tool:
```bash
dotnet tool install -g amazon.lambda.testtool
```

3. Start the Lambda Test Tool:

```bash
dotnet lambda-test-tool start --lambda-emulator-port 5050
```

4. Get the test tool version:

```
dotnet lambda-test-tool info
```

5. Run the `LambdaMessaging` project.

There are 2 ways to run it
1. Visual studio (easiest way).
1a. Update `Properties/launchSettings.json` and replace `${VERSIOMN} with the actual test tool version.
2. Via command line

```
cd bin\Debug\net8.0
$env:AWS_LAMBDA_RUNTIME_API = "localhost:5050/MyFunction"
$env:VERSION = "0.9.1" // Use the version returned from dotnet lambda-test-tool info

dotnet exec --depsfile ./LambdaMessaging.deps.json --runtimeconfig ./LambdaMessaging.runtimeconfig.json "$env:USERPROFILE\.dotnet\tools\.store\amazon.lambda.testtool\$env:VERSION\amazon.lambda.testtool\$env:VERSION\content\Amazon.Lambda.RuntimeSupport\net8.0\Amazon.Lambda.RuntimeSupport.dll" LambdaMessaging::LambdaMessaging.Function_FunctionHandler_Generated::FunctionHandler


```

6. You should now see the `MyFunction` appear in the test tools function list drop down in the top right corner. Select `MyFunction`.

7. We have provided a `HandlerSampleRequest.json` file to be used to test this function. Copy and paste this json into the test tools input window and then hit the "invoke button".

8. You should see in the console window that the `ChatMessageHandler` successfully processed the message. There should be a log statement saying `Message Description: Testing!!!`.
18 changes: 11 additions & 7 deletions sampleapps/LambdaMessaging/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
using Amazon.Lambda.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace LambdaMessaging;

[LambdaStartup]
public class Startup
{
public void ConfigureServices(IServiceCollection services)
public HostApplicationBuilder ConfigureHostBuilder()
{
services.AddLogging(builder =>
var builder = new HostApplicationBuilder();
builder.Services.AddLogging(b =>
{
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddLambdaLogger();
b.SetMinimumLevel(LogLevel.Trace);
b.AddLambdaLogger();
});
services.AddAWSMessageBus(builder =>
builder.Services.AddAWSMessageBus(b =>
{
builder.AddMessageHandler<ChatMessageHandler, ChatMessage>("chatMessage");
b.AddMessageHandler<ChatMessageHandler, ChatMessage>("chatMessage");

builder.AddLambdaMessageProcessor(options =>
b.AddLambdaMessageProcessor(options =>
{
options.MaxNumberOfConcurrentMessages = 2;
});
});

return builder;
}
}
4 changes: 2 additions & 2 deletions sampleapps/LambdaMessaging/serverless.template
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Description": "This template is partially managed by Amazon.Lambda.Annotations (v1.0.0.0).",
"Description": "This template is partially managed by Amazon.Lambda.Annotations (v1.7.0.0).",
"Resources": {
"ChatQueue": {
"Type": "AWS::SQS::Queue",
Expand All @@ -13,7 +13,7 @@
"Tool": "Amazon.Lambda.Annotations"
},
"Properties": {
"Runtime": "dotnet6",
"Runtime": "dotnet8",
"CodeUri": ".",
"MemorySize": 256,
"Timeout": 30,
Expand Down
6 changes: 3 additions & 3 deletions sampleapps/PollyIntegration/PollyIntegration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand All @@ -18,8 +18,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.*" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.6.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.6.0" />
<PackageReference Include="Polly.Core" Version="8.1.0" />
Expand Down
149 changes: 149 additions & 0 deletions sampleapps/PollyIntegration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# AWS Message Processing Framework with Polly Integration

This sample application demonstrates how to use the AWS Message Processing Framework for .NET with Polly for resilient message processing. It showcases integration between SQS message processing and Polly's retry policies.

## Overview

This sample demonstrates:
- Integration of AWS Message Processing Framework with Polly for resilient messaging
- Custom backoff handling for message processing
- SQS message processing with typed handlers
- Both code-based and configuration-based setup options

## Prerequisites

- .NET 8.0 or later
- AWS Account with appropriate permissions
- Basic understanding of Amazon SQS and AWS Message Processing Framework

## Setup

### 1. Create an SQS Queue

1. Open the AWS Management Console
2. Navigate to Amazon SQS
3. Click "Create Queue"
4. Choose "Standard Queue"
5. Enter a queue name (e.g., "MPF")
6. Keep default settings for this demo
7. Click "Create Queue"
8. Copy the Queue URL - you'll need this later

### 2. Configure Message Processing

You can choose either configuration approach:

#### Option A: Code-based Configuration

In `Program.cs`, update the queue URL and keep these lines uncommented:
```csharp
builder.AddSQSPoller("https://sqs.us-west-2.amazonaws.com/012345678910/MPF"); // Replace with your Queue URL
builder.AddMessageHandler<ChatMessageHandler, ChatMessage>("chatMessage");
```
And keep this line commented:
```
// builder.LoadConfigurationFromSettings(context.Configuration);
```

#### Option B: Configuration-based (appsettings.json)
1. Comment out the code-based configuration in Program.cs:

```
// builder.AddSQSPoller("https://sqs.us-west-2.amazonaws.com/012345678910/MPF");
// builder.AddMessageHandler<ChatMessageHandler, ChatMessage>("chatMessage");
```
2. Uncomment the configuration loading:

```
builder.LoadConfigurationFromSettings(context.Configuration);
```
3. Update appsettings.json:

```
{
"AWS.Messaging": {
"SQSPollers": [
{
"QueueUrl": "https://sqs.us-west-2.amazonaws.com/012345678910/MPF" // Replace with your Queue URL
}
],
"MessageHandlers": [
{
"HandlerType": "PollyIntegration.MessageHandlers.ChatMessageHandler",
"MessageType": "PollyIntegration.Models.ChatMessage",
"MessageTypeIdentifier": "chatMessage"
}
]
}
}

```

Choose Option A if you:

- Want configuration close to the code

- Need dynamic runtime configuration

- Are prototyping or testing


Choose Option B if you:

- Need configuration changes without recompiling

- Want environment-specific settings

- Prefer separation of configuration from code

- Need to manage multiple configurations


### 3. Configure AWS Credentials

Ensure you have AWS credentials configured either through:

- AWS CLI 

- Environment variables

- AWS credentials file

- IAM role (if running on AWS)

## Project Structure
```
PollyIntegration/
├── MessageHandlers/
│ └── ChatMessageHandler.cs # Sample message handler
├── Models/
│ └── ChatMessage.cs # Message type definition
├── Program.cs # Application entry point
├── PollyBackoffHandler.cs # Custom Polly integration
└── appsettings.json # Application configuration
```

## Running the Application
1. Build the project
```
dotnet build
```
2. Run the application
```
dotnet run
```
## Testing

### Send a Test Message

You can send a test message to your SQS queue using the AWS Console or AWS CLI:

Using AWS CLI:
```

$messageBody = "{""""type"""":""""chatMessage"""",""""id"""":""""123"""",""""source"""":""""test"""",""""specversion"""":""""1.0"""",""""time"""":""""2024-01-01T00:00:00Z"""",""""data"""":""""{\\""""messageDescription\\"""":\\""""Test message\\""""}""""}"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i was trying for an hour or so to figure out how to make this command better to create the messagebody but was having issues with the serialization. creating the string manually was the easiest way for now. will have to come back to this


aws sqs send-message --queue-url YOUR_QUEUE_URL --message-body $messageBody

```
Replace YOUR_QUEUE_URL with your actual SQS queue URL.
8 changes: 4 additions & 4 deletions sampleapps/PublisherAPI/PublisherAPI.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.6.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.6.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.11.2" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.11.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading
Loading