Skip to content

Commit 6a46c4e

Browse files
authored
Merge pull request #287 from swimming-potato/develop
2 parents 4ba5210 + 29bda6b commit 6a46c4e

21 files changed

+774
-1
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ deploy/**
1010
.idea
1111
.vscode
1212
.vs/
13+
.aws-sam
1314

1415
examples/SimpleLambda/.aws-sam
1516
examples/SimpleLambda/samconfig.toml
@@ -20,4 +21,5 @@ AWS.Lambda.Powertools.sln.DotSettings.user
2021
.DS_Store
2122

2223
dist/
23-
site/
24+
site/
25+
samconfig.toml

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ We have provided examples focused specifically on each of the utilities. Each so
5555
* **[Logging example](examples/Logging/)**
5656
* **[Metrics example](examples/Metrics/)**
5757
* **[Tracing example](examples/Tracing/)**
58+
* **[Serverless API example](examples/ServerlessApi/)**
59+
5860
* **[Parameters example](examples/Parameters/)**
5961
* **[Idempotency example](examples/Idempotency)**
6062

docs/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ We have provided a few examples that should you how to use the each of the core
104104
* [Tracing](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Tracing){target="_blank"}
105105
* [Logging](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Logging/){target="_blank"}
106106
* [Metrics](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Metrics/){target="_blank"}
107+
* [Serverless API example](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/ServerlessApi/){target="_blank"}
107108
* [Parameters](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Parameters/){target="_blank"}
108109
* [Idempotency](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Idempotency/){target="_blank"}
109110

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.0.31903.59
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{97038683-80A8-4DEC-B494-E774D5D7CA8E}"
7+
EndProject
8+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaPowertoolsAPI", "src\LambdaPowertoolsAPI\LambdaPowertoolsAPI.csproj", "{07541883-22A3-49AB-9A7B-3E2C8CC347F5}"
9+
EndProject
10+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{744F4880-67A3-4BC9-B4E7-D879EC646492}"
11+
EndProject
12+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaPowertoolsAPI.Tests", "test\LambdaPowertoolsAPI.Tests\LambdaPowertoolsAPI.Tests.csproj", "{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}"
13+
EndProject
14+
Global
15+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
16+
Debug|Any CPU = Debug|Any CPU
17+
Release|Any CPU = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
23+
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24+
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Debug|Any CPU.Build.0 = Debug|Any CPU
25+
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Release|Any CPU.ActiveCfg = Release|Any CPU
26+
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Release|Any CPU.Build.0 = Release|Any CPU
27+
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
28+
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Debug|Any CPU.Build.0 = Debug|Any CPU
29+
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Release|Any CPU.ActiveCfg = Release|Any CPU
30+
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Release|Any CPU.Build.0 = Release|Any CPU
31+
EndGlobalSection
32+
GlobalSection(NestedProjects) = preSolution
33+
{07541883-22A3-49AB-9A7B-3E2C8CC347F5} = {97038683-80A8-4DEC-B494-E774D5D7CA8E}
34+
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F} = {744F4880-67A3-4BC9-B4E7-D879EC646492}
35+
EndGlobalSection
36+
EndGlobal

examples/ServerlessApi/Readme.md

Lines changed: 243 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"resource": "/{proxy+}",
3+
"path": "api/values",
4+
"httpMethod": "GET",
5+
"body": "{\r\n\t\"message\": \"Hello\"\r\n}",
6+
"isBase64Encoded": false,
7+
"requestContext": {
8+
"requestId": "4749a5a8-93ea-464e-8778-3bffc5f9a35d"
9+
}
10+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"resource": "/{proxy+}",
3+
"path": "api/values/5",
4+
"httpMethod": "GET",
5+
"body": "{\r\n\t\"message\": \"Hello\"\r\n}",
6+
"isBase64Encoded": false,
7+
"requestContext": {
8+
"requestId": "4749a5a8-93ea-464e-8778-3bffc5f9a35d"
9+
}
10+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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 Microsoft.AspNetCore.Mvc;
17+
using System;
18+
using AWS.Lambda.Powertools.Logging;
19+
using AWS.Lambda.Powertools.Tracing;
20+
using AWS.Lambda.Powertools.Metrics;
21+
22+
namespace LambdaPowertoolsAPI.Controllers;
23+
24+
[Route("api/[controller]")]
25+
public class ValuesController : ControllerBase
26+
{
27+
// GET api/values
28+
[HttpGet]
29+
[Tracing(SegmentName = "Values::Get")]
30+
public IEnumerable<string> Get()
31+
{
32+
Logger.LogInformation("Log entry information only about getting values? Or maybe something more ");
33+
34+
return new string[] { "value1", "value2" };
35+
}
36+
37+
// GET api/values/5
38+
[HttpGet("{id}")]
39+
[Tracing(SegmentName = "Values::GetById")]
40+
public string Get(int id)
41+
{
42+
43+
try
44+
{
45+
Metrics.AddMetric("SuccessfulRetrieval", 1, MetricUnit.Count);
46+
}
47+
catch (Exception e)
48+
{
49+
Logger.LogError("Failed to add metric", e);
50+
}
51+
return "value";
52+
}
53+
54+
// POST api/values
55+
[HttpPost]
56+
public void Post([FromBody] string value)
57+
{
58+
}
59+
60+
// PUT api/values/5
61+
[HttpPut("{id}")]
62+
public void Put(int id, [FromBody] string value)
63+
{
64+
}
65+
66+
// DELETE api/values/5
67+
[HttpDelete("{id}")]
68+
public void Delete(int id)
69+
{
70+
}
71+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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 Amazon.Lambda.APIGatewayEvents;
17+
using Amazon.Lambda.Core;
18+
using Amazon.Lambda.Serialization.SystemTextJson;
19+
using AWS.Lambda.Powertools.Logging; // We are adding logging
20+
using AWS.Lambda.Powertools.Tracing; // We are adding tracing
21+
using AWS.Lambda.Powertools.Metrics; // We are adding metrics
22+
23+
namespace LambdaPowertoolsAPI;
24+
25+
/// <summary>
26+
/// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the
27+
/// actual Lambda function entry point. The Lambda handler field should be set to
28+
///
29+
/// LambdaPowertoolsAPI::LambdaPowertoolsAPI.LambdaEntryPoint::FunctionHandlerAsync
30+
/// </summary>
31+
public class LambdaEntryPoint :
32+
33+
// The base class must be set to match the AWS service invoking the Lambda function. If not Amazon.Lambda.AspNetCoreServer
34+
// will fail to convert the incoming request correctly into a valid ASP.NET Core request.
35+
//
36+
// API Gateway REST API -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
37+
// API Gateway HTTP API payload version 1.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
38+
// API Gateway HTTP API payload version 2.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction
39+
// Application Load Balancer -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction
40+
//
41+
// Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0
42+
// will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class.
43+
44+
Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
45+
{
46+
/// <summary>
47+
/// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
48+
/// needs to be configured in this method using the UseStartup<>() method.
49+
/// </summary>
50+
/// <param name="builder"></param>
51+
protected override void Init(IWebHostBuilder builder)
52+
{
53+
builder
54+
.UseStartup<Startup>();
55+
56+
57+
Console.WriteLine("Startup done");
58+
}
59+
60+
61+
// We are defining some default dimensions.
62+
private Dictionary<string, string> _defaultDimensions = new Dictionary<string, string>{
63+
{"Environment", Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "Unknown"},
64+
{"Runtime",Environment.Version.ToString()}
65+
};
66+
67+
[LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]
68+
[Logging(CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest, LogEvent = true)] // we are enabling logging, it needs to be added on method which have Lambda event
69+
[Tracing] // Adding a tracing attribute here we will see additional function call which might be important in terms of debugging
70+
[Metrics] // Metrics need to be initialized the best place is entry point in opposite on adding attribute on each controller.
71+
public override Task<APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext lambdaContext)
72+
{
73+
74+
if (!_defaultDimensions.ContainsKey("Version"))
75+
_defaultDimensions.Add("Version", lambdaContext.FunctionVersion ?? "Unknown");
76+
77+
// Setting the default dimensions. They will be added to every emitted metric.
78+
Metrics.SetDefaultDimensions(_defaultDimensions);
79+
return base.FunctionHandlerAsync(request, lambdaContext);
80+
}
81+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
<PropertyGroup>
3+
<OutputType>Exe</OutputType>
4+
<TargetFramework>net6.0</TargetFramework>
5+
<ImplicitUsings>enable</ImplicitUsings>
6+
<Nullable>enable</Nullable>
7+
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
8+
<AWSProjectType>Lambda</AWSProjectType>
9+
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
10+
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
11+
<!-- Generate ready to run images during publishing to improve cold start time. -->
12+
<PublishReadyToRun>true</PublishReadyToRun>
13+
</PropertyGroup>
14+
<ItemGroup>
15+
<PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="8.1.0" />
16+
<PackageReference Include="AWS.Lambda.Powertools.Logging" Version="1.1.0" />
17+
<PackageReference Include="AWS.Lambda.Powertools.Metrics" Version="1.2.0" />
18+
<PackageReference Include="AWS.Lambda.Powertools.Tracing" Version="1.1.0" />
19+
</ItemGroup>
20+
</Project>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
namespace LambdaPowertoolsAPI;
17+
18+
/// <summary>
19+
/// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver.
20+
/// </summary>
21+
public class LocalEntryPoint
22+
{
23+
public static void Main(string[] args)
24+
{
25+
CreateHostBuilder(args).Build().Run();
26+
}
27+
28+
public static IHostBuilder CreateHostBuilder(string[] args) =>
29+
Host.CreateDefaultBuilder(args)
30+
.ConfigureWebHostDefaults(webBuilder =>
31+
{
32+
webBuilder.UseStartup<Startup>();
33+
});
34+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
namespace LambdaPowertoolsAPI;
17+
18+
public class Startup
19+
{
20+
public Startup(IConfiguration configuration)
21+
{
22+
Configuration = configuration;
23+
}
24+
25+
public IConfiguration Configuration { get; }
26+
27+
// This method gets called by the runtime. Use this method to add services to the container
28+
public void ConfigureServices(IServiceCollection services)
29+
{
30+
services.AddControllers();
31+
}
32+
33+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
34+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
35+
{
36+
if (env.IsDevelopment())
37+
{
38+
app.UseDeveloperExceptionPage();
39+
}
40+
41+
app.UseHttpsRedirection();
42+
43+
app.UseRouting();
44+
45+
app.UseEndpoints(endpoints =>
46+
{
47+
endpoints.MapControllers();
48+
});
49+
50+
}
51+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"AWS": {
3+
"Region": ""
4+
}
5+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Debug",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
"s3-prefix": "LambdaPowertoolsAPI/",
12+
"template": "serverless.template",
13+
"template-parameters": ""
14+
}

0 commit comments

Comments
 (0)