Skip to content

Commit dc67c36

Browse files
authored
Merge pull request #300 from hossambarakat/feature/idempotency-example
docs: Add Idempotency example
2 parents 368b099 + 6a8d421 commit dc67c36

11 files changed

+1306
-0
lines changed

examples/Idempotency/.gitignore

Lines changed: 638 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.30114.105
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld", "src\HelloWorld\HelloWorld.csproj", "{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}"
7+
EndProject
8+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld.Tests", "test\HelloWorld.Test\HelloWorld.Tests.csproj", "{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}"
9+
EndProject
10+
Global
11+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
12+
Debug|Any CPU = Debug|Any CPU
13+
Release|Any CPU = Release|Any CPU
14+
EndGlobalSection
15+
GlobalSection(SolutionProperties) = preSolution
16+
HideSolutionNode = FALSE
17+
EndGlobalSection
18+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
19+
{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
20+
{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.Build.0 = Debug|Any CPU
21+
{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.ActiveCfg = Release|Any CPU
22+
{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.Build.0 = Release|Any CPU
23+
{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24+
{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
25+
{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
26+
{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.Build.0 = Release|Any CPU
27+
EndGlobalSection
28+
EndGlobal

examples/Idempotency/README.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Powertools for AWS Lambda (.NET) - Idempotency Example
2+
3+
This project contains source code and supporting files for a serverless application that you can deploy with the AWS Serverless Application Model Command Line Interface (AWS SAM CLI). It includes the following files and folders.
4+
5+
* src - Code for the application's Lambda function.
6+
* events - Invocation events that you can use to invoke the function.
7+
* test - Tests for the application code.
8+
* template.yaml - A template that defines the application's AWS resources.
9+
10+
The application uses several AWS resources, including Lambda function, DynamoDB table and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
11+
12+
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. The AWS Toolkit is an open source plug-in for popular IDEs that uses the AWS SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
13+
14+
* [Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
15+
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
16+
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
17+
18+
## Deploy the sample application
19+
20+
The AWS SAM CLI is an extension of the AWS Command Line Interface (AWS CLI) that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
21+
22+
To use the AWS SAM CLI, you need the following tools.
23+
24+
* AWS SAM CLI - [Install the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
25+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
26+
27+
You will need the following for local testing.
28+
* .NET 6.0 - [Install .NET 6.0](https://www.microsoft.com/net/download)
29+
30+
To build and deploy your application for the first time, run the following in your shell. Make sure the `template.yaml` file is in your current directory:
31+
32+
```bash
33+
sam build
34+
sam deploy --guided
35+
```
36+
37+
The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts:
38+
39+
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
40+
* **AWS Region**: The AWS region you want to deploy your app to.
41+
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
42+
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
43+
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
44+
45+
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
46+
47+
## Invoke Amazon API Gateway
48+
49+
Invoke the Lambda by calling the API Gateway using the following command
50+
51+
```bash
52+
curl -X POST https://[REST-API-ID].execute-api.[REGION].amazonaws.com/Prod/hello/ -H "Content-Type: application/json" -d '{"address": "https://checkip.amazonaws.com"}'
53+
```
54+
55+
## Run tests
56+
57+
Tests use the [Testcontainers for .NET](https://dotnet.testcontainers.org/) which requires a Docker-API compatible container runtime.
58+
59+
Tests are defined in the `test` folder in this project.
60+
61+
```bash
62+
$ dotnet test test/HelloWorld.Test
63+
```
64+
65+
## Cleanup
66+
67+
To delete the sample application that you created, use the AWS SAM CLI. Assuming you used your project name for the stack name, you can run the following:
68+
69+
```bash
70+
$ sam delete
71+
```
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
{
2+
"body": "{\"address\": \"https://checkip.amazonaws.com\"}",
3+
"resource": "/{proxy+}",
4+
"path": "/path/to/resource",
5+
"httpMethod": "POST",
6+
"isBase64Encoded": false,
7+
"queryStringParameters": {
8+
"foo": "bar"
9+
},
10+
"pathParameters": {
11+
"proxy": "/path/to/resource"
12+
},
13+
"stageVariables": {
14+
"baz": "qux"
15+
},
16+
"headers": {
17+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
18+
"Accept-Encoding": "gzip, deflate, sdch",
19+
"Accept-Language": "en-US,en;q=0.8",
20+
"Cache-Control": "max-age=0",
21+
"CloudFront-Forwarded-Proto": "https",
22+
"CloudFront-Is-Desktop-Viewer": "true",
23+
"CloudFront-Is-Mobile-Viewer": "false",
24+
"CloudFront-Is-SmartTV-Viewer": "false",
25+
"CloudFront-Is-Tablet-Viewer": "false",
26+
"CloudFront-Viewer-Country": "US",
27+
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
28+
"Upgrade-Insecure-Requests": "1",
29+
"User-Agent": "Custom User Agent String",
30+
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
31+
"X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
32+
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
33+
"X-Forwarded-Port": "443",
34+
"X-Forwarded-Proto": "https"
35+
},
36+
"requestContext": {
37+
"accountId": "123456789012",
38+
"resourceId": "123456",
39+
"stage": "prod",
40+
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
41+
"requestTime": "09/Apr/2015:12:34:56 +0000",
42+
"requestTimeEpoch": 1428582896000,
43+
"identity": {
44+
"cognitoIdentityPoolId": null,
45+
"accountId": null,
46+
"cognitoIdentityId": null,
47+
"caller": null,
48+
"accessKey": null,
49+
"sourceIp": "127.0.0.1",
50+
"cognitoAuthenticationType": null,
51+
"cognitoAuthenticationProvider": null,
52+
"userArn": null,
53+
"userAgent": "Custom User Agent String",
54+
"user": null
55+
},
56+
"path": "/prod/path/to/resource",
57+
"resourcePath": "/{proxy+}",
58+
"httpMethod": "POST",
59+
"apiId": "1234567890",
60+
"protocol": "HTTP/1.1"
61+
}
62+
}
63+
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
/*
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License").
5+
* You may not use this file except in compliance with the License.
6+
* A copy of the License is located at
7+
*
8+
* http://aws.amazon.com/apache2.0
9+
*
10+
* or in the "license" file accompanying this file. This file is distributed
11+
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12+
* express or implied. See the License for the specific language governing
13+
* permissions and limitations under the License.
14+
*/
15+
16+
using System;
17+
using System.Collections.Generic;
18+
using System.Net.Http;
19+
using System.Text.Json;
20+
using System.Text.Json.Serialization;
21+
using System.Threading.Tasks;
22+
using Amazon.DynamoDBv2;
23+
using Amazon.Lambda.APIGatewayEvents;
24+
using Amazon.Lambda.Core;
25+
using Amazon.Lambda.Serialization.SystemTextJson;
26+
using AWS.Lambda.Powertools.Idempotency;
27+
using AWS.Lambda.Powertools.Idempotency.Persistence;
28+
using AWS.Lambda.Powertools.Logging;
29+
30+
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
31+
[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]
32+
33+
namespace HelloWorld;
34+
35+
public class Function
36+
{
37+
private static HttpClient? _httpClient;
38+
private static AmazonDynamoDBClient? _dynamoDbClient;
39+
40+
/// <summary>
41+
/// Function constructor
42+
/// </summary>
43+
public Function()
44+
{
45+
_httpClient = new HttpClient();
46+
_dynamoDbClient = new AmazonDynamoDBClient();
47+
48+
Init(_dynamoDbClient, _httpClient);
49+
}
50+
51+
/// <summary>
52+
/// Test constructor
53+
/// </summary>
54+
public Function(AmazonDynamoDBClient amazonDynamoDb, HttpClient httpClient)
55+
{
56+
_httpClient = httpClient;
57+
_dynamoDbClient = amazonDynamoDb;
58+
Init(amazonDynamoDb, httpClient);
59+
}
60+
61+
private void Init(AmazonDynamoDBClient amazonDynamoDb, HttpClient httpClient)
62+
{
63+
ArgumentNullException.ThrowIfNull(amazonDynamoDb);
64+
ArgumentNullException.ThrowIfNull(httpClient);
65+
var tableName = Environment.GetEnvironmentVariable("TABLE_NAME");
66+
ArgumentNullException.ThrowIfNull(tableName);
67+
68+
Idempotency.Configure(builder =>
69+
builder
70+
.WithOptions(optionsBuilder =>
71+
optionsBuilder
72+
.WithEventKeyJmesPath("powertools_json(Body).address") // will retrieve the address field in the body which is a string transformed to json with `powertools_json`
73+
.WithExpiration(TimeSpan.FromSeconds(10)))
74+
.UseDynamoDb(storeBuilder =>
75+
storeBuilder
76+
.WithTableName(tableName)
77+
.WithDynamoDBClient(amazonDynamoDb)
78+
));
79+
}
80+
81+
/// <summary>
82+
/// Lambda Handler
83+
/// Try with:
84+
/// <pre>
85+
/// curl -X POST https://[REST-API-ID].execute-api.[REGION].amazonaws.com/Prod/hello/ -H "Content-Type: application/json" -d '{"address": "https://checkip.amazonaws.com"}'
86+
/// </pre>
87+
/// </summary>
88+
/// <param name="apigwProxyEvent">API Gateway Proxy event</param>
89+
/// <param name="context">AWS Lambda context</param>
90+
/// <returns>API Gateway Proxy response</returns>
91+
[Idempotent]
92+
[Logging(LogEvent = true)]
93+
public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigwProxyEvent, ILambdaContext context)
94+
{
95+
var serializationOptions = new JsonSerializerOptions
96+
{
97+
PropertyNameCaseInsensitive = true
98+
};
99+
var request = JsonSerializer.Deserialize<LookupRequest>(apigwProxyEvent.Body, serializationOptions);
100+
if (request is null)
101+
{
102+
return new APIGatewayProxyResponse
103+
{
104+
Body = "Invalid request",
105+
StatusCode = 403,
106+
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
107+
};
108+
}
109+
110+
var location = await GetCallingIp(request.Address);
111+
112+
var requestContextRequestId = apigwProxyEvent.RequestContext.RequestId;
113+
var response = new
114+
{
115+
RequestId = requestContextRequestId,
116+
Greeting = "Hello Powertools for AWS Lambda (.NET)",
117+
IpAddress = location
118+
};
119+
120+
try
121+
{
122+
return new APIGatewayProxyResponse
123+
{
124+
Body = JsonSerializer.Serialize(response),
125+
StatusCode = 200,
126+
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
127+
};
128+
}
129+
catch (Exception e)
130+
{
131+
return new APIGatewayProxyResponse
132+
{
133+
Body = e.Message,
134+
StatusCode = 500,
135+
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
136+
};
137+
}
138+
}
139+
140+
/// <summary>
141+
/// Calls location api to return IP address
142+
/// </summary>
143+
/// <param name="address">Uri of the service providing the calling IP</param>
144+
/// <returns>IP address string</returns>
145+
private static async Task<string?> GetCallingIp(string address)
146+
{
147+
if (_httpClient == null) return "0.0.0.0";
148+
_httpClient.DefaultRequestHeaders.Accept.Clear();
149+
_httpClient.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");
150+
151+
var response = await _httpClient.GetStringAsync(address).ConfigureAwait(false);
152+
var ip = response.Replace("\n", "");
153+
154+
return ip;
155+
}
156+
}
157+
158+
/// <summary>
159+
/// Record to represent the data structure of Lookup request
160+
/// </summary>
161+
[Serializable]
162+
public class LookupRequest
163+
{
164+
public string Address { get; private set; }
165+
166+
public LookupRequest(string address)
167+
{
168+
Address = address;
169+
}
170+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<TargetFramework>net6.0</TargetFramework>
4+
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
5+
<Nullable>enable</Nullable>
6+
</PropertyGroup>
7+
<ItemGroup>
8+
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
9+
<PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.5.0" />
10+
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.3.0" />
11+
<PackageReference Include="AWS.Lambda.Powertools.Idempotency" Version="0.0.1-preview" />
12+
<PackageReference Include="AWS.Lambda.Powertools.Logging" Version="1.1.0" />
13+
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.101.14" />
14+
</ItemGroup>
15+
</Project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"Information": [
3+
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
4+
"To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
5+
"dotnet lambda help",
6+
"All the command line options for the Lambda command can be specified in this file."
7+
],
8+
"profile": "",
9+
"region": "",
10+
"configuration": "Release",
11+
"template": "template.yaml"
12+
}

0 commit comments

Comments
 (0)