Skip to content

CSHARP-4127: Language specific examples for AWS Lambda. #779

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 16, 2022
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
91 changes: 91 additions & 0 deletions tests/MongoDB.Driver.Examples/AwsLambda/AwsLambdaExamples.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#if NETCOREAPP3_1_OR_GREATER
Copy link
Contributor Author

Choose a reason for hiding this comment

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

LambdaSerializer is not supported for previous TFs

using Amazon.Lambda.Core;
using MongoDB.Bson;
using MongoDB.Driver;
using System;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace LambdaTest
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The scope of these code examples is limited to the instructions on:
How to share the client (“Example 1”. See first snippet in this section for structure)
How to connect to the deployment using AWS IAM authentication (“Example 2”. Same structure as “Example 1”, but see the blue note box in the docs for which lines need to be replaced to work with AWS IAM auth)

{
public class ShareMongoClientLambdaHandler
{
// Start AWS Lambda Example 1
private static MongoClient MongoClient { get; set; }
private static MongoClient CreateMongoClient()
{
var mongoClientSettings = MongoClientSettings.FromConnectionString($"<MONGODB_URI>");
mongoClientSettings.ServerApi = new ServerApi(ServerApiVersion.V1, strict: true);
return new MongoClient(mongoClientSettings);
}

static ShareMongoClientLambdaHandler()
{
MongoClient = CreateMongoClient();
Copy link
Contributor

Choose a reason for hiding this comment

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

Is it guaranteed that the ctor will be called once/not concurrently?
Or should it be static ShareMongoClientLambdaHandler ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Recommended way I found was about regular ctor, see for example here https://blog.steadycoding.com/using-singletons-in-net-core-in-aws-lambda/. The note what I didn't mention before, that there are 2 modes for AWS Lambda called "Cold" and "Warm" start ("Hot is a bit different): https://medium.com/@danielmanchev/cold-warm-and-hot-start-in-aws-lambda-bc8d64f28575. So the actually reused instance will be only after warm start. Each Cold start will create new instance of lambda handler

Copy link
Contributor

Choose a reason for hiding this comment

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

From the first glance I fail to see the reason for initializing a static property in regular ctor. Do we know why is this the recommended way, and is it AWS recommendation as well?
In AWS .Net samples static ctors are used.
Probably we'd need to look deeper into this.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As far as I understand, both ways can be used. This is what created by VS "Simple S3 function" project:
image

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, note that S3Client in this case is not static. The initialization of a static field in non-static constructor is what puzzles me, but this does not mean it's not working though. I think we have to be able to explain such unusual combination, or follow the official samples.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it's true, I forgot that suggested MongoClient is static. I think it can work in any way, but I will look at this one more time :(

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 think it's fine to take what is suggested in the VS templates (ie official place). So I removed static modifier

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 asked this in this issue just in case awsdocs/aws-lambda-developer-guide#360

}

public string HandleRequest(ILambdaContext context)
Copy link
Contributor

Choose a reason for hiding this comment

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

In all samples a came across, I see additional inputType parameter in Handler function:
https://docs.aws.amazon.com/lambda/latest/dg/csharp-handler.html

Can it be omitted, and do you happen to have some official sample without it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it can be omitted

Copy link
Contributor Author

Choose a reason for hiding this comment

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

to have some official sample without it?

I just saw that it works without this argument

{
var database = MongoClient.GetDatabase("db");
var collection = database.GetCollection<BsonDocument>("coll");
var result = collection.Find(FilterDefinition<BsonDocument>.Empty).First();
return result.ToString();
}
// End AWS Lambda Example 1
}

public class ConnectUsingAwsIamAuthenticatorLambdaHandler
{
private static MongoClient MongoClient { get; set; }
private static MongoClient CreateMongoClient()
{
// Start AWS Lambda Example 2
string username = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID");
Copy link
Contributor

Choose a reason for hiding this comment

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

Are environment variables part of the Aws Lambda auth process?
If not, maybe for simplicity just use dummy values: var username = "<username>"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it's not specified in our envs, but I saw it in other examples exactly in this form, so I would leave it as here

Copy link
Contributor

@BorisDog BorisDog Apr 28, 2022

Choose a reason for hiding this comment

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

In this case I wonder if Environment.GetEnvironmentVariable adds any additional value for the sample. Maybe we'd better keep it as simple as possible...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As far as I know, it's a common way to expect these variables filled like you can see here: https://docs.aws.amazon.com/vsts/latest/userguide/lambda-netcore-deploy.html. Additionally it simplifies using this code in the driver if we want to run it. If I recall correctly, we can even not specify these values explicitly and they still be used by the driver implicitly (but not sure off the top of my head about details). I can check it later if you think that it makes sense

Copy link
Contributor

Choose a reason for hiding this comment

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

Looks like it's only one of the options, used in case of "build agent process", not sure what it is :)
Also I don't think we should prioritize simplifying the usage of this code in our driver.

Not a big issue, I just think it introduces some "noise" to the sample, and not sure we got any use for it.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

At the very least these variables present in the examples that we needed to mimic: https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/. So I think we even have no way to not set it

string password = Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY");
Copy link
Contributor

Choose a reason for hiding this comment

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

Password should be stored in a SecureString.

Copy link
Contributor

Choose a reason for hiding this comment

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

Microsoft is no longer recommending the use of SecureString.
https://docs.microsoft.com/en-us/dotnet/api/system.security.securestring?view=net-6.0
And this rule:
https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md

Let's skip the use of SecureString that I initially suggested and keep the example easier to follow as you have it.

string awsSessionToken = Environment.GetEnvironmentVariable("AWS_SESSION_TOKEN");

var awsCredentials =
new MongoCredential("MONGODB-AWS", new MongoExternalIdentity(username), new PasswordEvidence(password))
Copy link
Contributor

Choose a reason for hiding this comment

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

PasswordEvidence has a ctor that accepts a SecureString.

.WithMechanismProperty("AWS_SESSION_TOKEN", awsSessionToken);

var mongoUrl = MongoUrl.Create($"<MONGODB_URI>");

var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);
mongoClientSettings.Credential = awsCredentials;
mongoClientSettings.ServerApi = new ServerApi(ServerApiVersion.V1, strict: true);

return new MongoClient(mongoClientSettings);
// End AWS Lambda Example 2
}

static ConnectUsingAwsIamAuthenticatorLambdaHandler()
{
MongoClient = CreateMongoClient();
}

public string HandleRequest(ILambdaContext context)
{
var database = MongoClient.GetDatabase("db");
var collection = database.GetCollection<BsonDocument>("coll");
var result = collection.Find(FilterDefinition<BsonDocument>.Empty).First();
return result.ToString();
}
}
}
#endif
5 changes: 5 additions & 0 deletions tests/MongoDB.Driver.Examples/MongoDB.Driver.Examples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<PackageReference Include="JunitXml.TestLogger" Version="2.1.81" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.2.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\MongoDB.Bson\MongoDB.Bson.csproj" />
<ProjectReference Include="..\..\src\MongoDB.Driver\MongoDB.Driver.csproj" />
Expand Down