repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html /// </summary> public class CognitoCustomMessageRequest : CognitoTriggerRequest { /// <summary> /// A string for you to use as the placeholder for the verification code in the custom message. /// </summary> [DataMember(Name = "codeParameter")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("codeParameter")] #endif public string CodeParameter { get; set; } /// <summary> /// The username parameter. It is a required request parameter for the admin create user flow. /// </summary> [DataMember(Name = "usernameParameter")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("usernameParameter")] #endif public string UsernameParameter { get; set; } /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminCreateUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] #endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); } }
39
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html /// </summary> public class CognitoCustomMessageResponse : CognitoTriggerResponse { /// <summary> /// The custom SMS message to be sent to your users. Must include the codeParameter value received in the request. /// </summary> [DataMember(Name = "smsMessage")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("smsMessage")] #endif public string SmsMessage { get; set; } /// <summary> /// The custom email message to be sent to your users. Must include the codeParameter value received in the request. /// </summary> [DataMember(Name = "emailMessage")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("emailMessage")] #endif public string EmailMessage { get; set; } /// <summary> /// The subject line for the custom message. /// </summary> [DataMember(Name = "emailSubject")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("emailSubject")] #endif public string EmailSubject { get; set; } } }
38
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sms-sender.html /// </summary> public class CognitoCustomSmsSenderEvent : CognitoTriggerEvent<CognitoCustomSmsSenderRequest, CognitoCustomSmsSenderResponse> { } }
10
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sms-sender.html /// </summary> public class CognitoCustomSmsSenderRequest : CognitoTriggerRequest { /// <summary> /// The type of sender request. /// </summary> [DataMember(Name = "type")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("type")] #endif public string Type { get; set; } /// <summary> /// The encrypted temporary authorization code. /// </summary> [DataMember(Name = "code")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("code")] #endif public string Code { get; set; } } }
29
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sms-sender.html /// </summary> public class CognitoCustomSmsSenderResponse : CognitoTriggerResponse { } }
10
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html /// </summary> public class CognitoDefineAuthChallengeEvent : CognitoTriggerEvent<CognitoDefineAuthChallengeRequest, CognitoDefineAuthChallengeResponse> { } }
10
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html /// </summary> public class CognitoDefineAuthChallengeRequest : CognitoTriggerRequest { /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminCreateUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] # endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); /// <summary> /// an array of ChallengeResult elements /// </summary> [DataMember(Name = "session")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("session")] # endif public List<ChallengeResultElement> Session { get; set; } = new List<ChallengeResultElement>(); /// <summary> /// A Boolean that is populated when PreventUserExistenceErrors is set to ENABLED for your user pool client. A value of true means that the user id (user name, email address, etc.) did not match any existing users. When PreventUserExistenceErrors is set to ENABLED, the service will not report back to the app that the user does not exist. The recommended best practice is for your Lambda functions to maintain the same user experience including latency so the caller cannot detect different behavior when the user exists or doesn’t exist. /// </summary> [DataMember(Name = "userNotFound")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userNotFound")] #endif public bool UserNotFound { get; set; } } }
39
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html /// </summary> public class CognitoDefineAuthChallengeResponse : CognitoTriggerResponse { /// <summary> /// A string containing the name of the next challenge. If you want to present a new challenge to your user, specify the challenge name here. /// </summary> [DataMember(Name = "challengeName")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeName")] #endif public string ChallengeName { get; set; } /// <summary> /// Set to true if you determine that the user has been sufficiently authenticated by completing the challenges, or false otherwise. /// </summary> [DataMember(Name = "issueTokens")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("issueTokens")] #endif public bool IssueTokens { get; set; } /// <summary> /// Set to true if you want to terminate the current authentication process, or false otherwise. /// </summary> [DataMember(Name = "failAuthentication")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("failAuthentication")] #endif public bool FailAuthentication { get; set; } } }
38
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { using System; using System.Collections.Generic; /// <summary> /// AWS Cognito event /// http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-events.html /// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-cognito-sync-trigger /// </summary> public class CognitoEvent { /// <summary> /// The data set name of the event. /// </summary> public string DatasetName { get; set; } /// <summary> /// The map of data set records for the event. /// </summary> public IDictionary<string, DatasetRecord> DatasetRecords { get; set; } /// <summary> /// The event type. /// </summary> public string EventType { get; set; } /// <summary> /// The identity pool ID associated with the data set. /// </summary> public string IdentityId { get; set; } /// <summary> /// The identity pool ID associated with the data set. /// </summary> public string IdentityPoolId { get; set; } /// <summary> /// The region in which data set resides. /// </summary> public string Region { get; set; } /// <summary> /// The event version. /// </summary> public int Version { get; set; } /// <summary> /// Data set records for the event. /// </summary> public class DatasetRecord { /// <summary> /// The record's new value. /// </summary> public string NewValue { get; set; } /// <summary> /// The record's old value. /// </summary> public string OldValue { get; set; } /// <summary> /// The operation associated with the record. /// For a new record or any updates to existing record it is set to "replace". /// For deleting a record it is set to "remove". /// </summary> public string Op { get; set; } } } }
72
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html /// </summary> public class CognitoMigrateUserEvent : CognitoTriggerEvent<CognitoMigrateUserRequest, CognitoMigrateUserResponse> { } }
12
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html /// </summary> public class CognitoMigrateUserRequest : CognitoTriggerRequest { /// <summary> /// The username entered by the user. /// </summary> [DataMember(Name = "userName")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userName")] #endif public string UserName { get; set; } /// <summary> /// The password entered by the user for sign-in. It is not set in the forgot-password flow. /// </summary> [DataMember(Name = "password")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("password")] #endif public string Password { get; set; } /// <summary> /// One or more name-value pairs containing the validation data in the request to register a user. The validation data is set and then passed from the client in the request to register a user. You can pass this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and AdminInitiateAuth API actions. /// </summary> [DataMember(Name = "validationData")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("validationData")] #endif public Dictionary<string, string> ValidationData { get; set; } = new Dictionary<string, string>(); /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminCreateUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] #endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); } }
48
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html /// </summary> public class CognitoMigrateUserResponse : CognitoTriggerResponse { /// <summary> /// It must contain one or more name-value pairs representing user attributes to be stored in the user profile in your user pool. You can include both standard and custom user attributes. Custom attributes require the custom: prefix to distinguish them from standard attributes. /// </summary> [DataMember(Name = "userAttributes")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userAttributes")] #endif public Dictionary<string, string> UserAttributes { get; set; } = new Dictionary<string, string>(); /// <summary> /// During sign-in, this attribute can be set to CONFIRMED, or not set, to auto-confirm your users and allow them to sign-in with their previous passwords. This is the simplest experience for the user. /// </summary> [DataMember(Name = "finalUserStatus")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("finalUserStatus")] #endif public string FinalUserStatus { get; set; } /// <summary> /// This attribute can be set to "SUPPRESS" to suppress the welcome message usually sent by Amazon Cognito to new users. If this attribute is not returned, the welcome message will be sent. /// </summary> [DataMember(Name = "messageAction")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("messageAction")] #endif public string MessageAction { get; set; } /// <summary> /// This attribute can be set to "EMAIL" to send the welcome message by email, or "SMS" to send the welcome message by SMS. If this attribute is not returned, the welcome message will be sent by SMS. /// </summary> [DataMember(Name = "desiredDeliveryMediums")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("desiredDeliveryMediums")] #endif public List<string> DesiredDeliveryMediums { get; set; } = new List<string>(); /// <summary> /// If this parameter is set to "true" and the phone number or email address specified in the UserAttributes parameter already exists as an alias with a different user, the API call will migrate the alias from the previous user to the newly created user. The previous user will no longer be able to log in using that alias. /// </summary> [DataMember(Name = "forceAliasCreation")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("forceAliasCreation")] #endif public bool ForceAliasCreation { get; set; } } }
57
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html /// </summary> [DataContract] public class CognitoPostAuthenticationEvent : CognitoTriggerEvent<CognitoPostAuthenticationRequest, CognitoPostAuthenticationResponse> { } }
13
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html /// </summary> [DataContract] public class CognitoPostAuthenticationRequest : CognitoTriggerRequest { /// <summary> /// One or more name-value pairs containing the validation data in the request to register a user. The validation data is set and then passed from the client in the request to register a user. You can pass this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and AdminInitiateAuth API actions. /// </summary> [DataMember(Name = "validationData")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("validationData")] # endif public Dictionary<string, string> ValidationData { get; set; } = new Dictionary<string, string>(); /// <summary> /// This flag indicates if the user has signed in on a new device. It is set only if the remembered devices value of the user pool is set to Always or User Opt-In. /// </summary> [DataMember(Name = "newDeviceUsed")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("newDeviceUsed")] #endif public bool NewDevicedUsed { get; set; } /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminCreateUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] # endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); } }
40
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html /// </summary> [DataContract] public class CognitoPostAuthenticationResponse : CognitoTriggerResponse { } }
13
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html /// </summary> [DataContract] public class CognitoPostConfirmationEvent : CognitoTriggerEvent<CognitoPostConfirmationRequest, CognitoPostConfirmationResponse> { } }
13
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html /// </summary> [DataContract] public class CognitoPostConfirmationRequest : CognitoTriggerRequest { /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminCreateUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] #endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); } }
22
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html /// </summary> [DataContract] public class CognitoPostConfirmationResponse : CognitoTriggerResponse { } }
13
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html /// </summary> [DataContract] public class CognitoPreAuthenticationEvent : CognitoTriggerEvent<CognitoPreAuthenticationRequest, CognitoPreAuthenticationResponse> { } }
13
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html /// </summary> [DataContract] public class CognitoPreAuthenticationRequest : CognitoTriggerRequest { /// <summary> /// One or more name-value pairs containing the validation data in the request to register a user. The validation data is set and then passed from the client in the request to register a user. You can pass this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and AdminInitiateAuth API actions. /// </summary> [DataMember(Name = "validationData")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("validationData")] # endif public Dictionary<string, string> ValidationData { get; set; } = new Dictionary<string, string>(); /// <summary> /// This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User Pool client. /// </summary> [DataMember(Name = "userNotFound")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userNotFound")] #endif public bool UserNotFound { get; set; } } }
31
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html /// </summary> [DataContract] public class CognitoPreAuthenticationResponse : CognitoTriggerResponse { } }
13
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html /// </summary> [DataContract] public class CognitoPreSignupEvent : CognitoTriggerEvent<CognitoPreSignupRequest, CognitoPreSignupResponse> { } }
13
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html /// </summary> [DataContract] public class CognitoPreSignupRequest : CognitoTriggerRequest { /// <summary> /// One or more name-value pairs containing the validation data in the request to register a user. The validation data is set and then passed from the client in the request to register a user. You can pass this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and AdminInitiateAuth API actions. /// </summary> [DataMember(Name = "validationData")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("validationData")] #endif public Dictionary<string, string> ValidationData { get; set; } = new Dictionary<string, string>(); /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminCreateUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] #endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); } }
31
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html /// </summary> [DataContract] public class CognitoPreSignupResponse : CognitoTriggerResponse { /// <summary> /// Set to true to auto-confirm the user, or false otherwise. /// </summary> [DataMember(Name = "autoConfirmUser")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("autoConfirmUser")] #endif public bool AutoConfirmUser { get; set; } /// <summary> /// Set to true to set as verified the email of a user who is signing up, or false otherwise. If autoVerifyEmail is set to true, the email attribute must have a valid, non-null value. Otherwise an error will occur and the user will not be able to complete sign-up. /// </summary> [DataMember(Name = "autoVerifyPhone")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("autoVerifyPhone")] #endif public bool AutoVerifyPhone { get; set; } /// <summary> /// Set to true to set as verified the phone number of a user who is signing up, or false otherwise. If autoVerifyPhone is set to true, the phone_number attribute must have a valid, non-null value. Otherwise an error will occur and the user will not be able to complete sign-up. /// </summary> [DataMember(Name = "autoVerifyEmail")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("autoVerifyEmail")] #endif public bool AutoVerifyEmail { get; set; } } }
39
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html /// </summary> public class CognitoPreTokenGenerationEvent : CognitoTriggerEvent<CognitoPreTokenGenerationRequest, CognitoPreTokenGenerationResponse> { } }
10
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html /// </summary> public class CognitoPreTokenGenerationRequest : CognitoTriggerRequest { /// <summary> /// The input object containing the current group configuration. It includes groupsToOverride, iamRolesToOverride, and preferredRole. /// </summary> [DataMember(Name = "groupConfiguration")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("groupConfiguration")] # endif public GroupConfiguration GroupConfiguration { get; set; } = new GroupConfiguration(); /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminVerifyUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] # endif public Dictionary<string, string> ClientMetadata { get; set; } = new Dictionary<string, string>(); } }
30
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html /// </summary> public class CognitoPreTokenGenerationResponse : CognitoTriggerResponse { /// <summary> /// Pre token generation response parameters /// </summary> [DataMember(Name = "claimsOverrideDetails")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("claimsOverrideDetails")] # endif public ClaimOverrideDetails ClaimsOverrideDetails { get; set; } = new ClaimOverrideDetails(); } }
20
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared /// </summary> [DataContract] public class CognitoTriggerCallerContext { /// <summary> /// The AWS SDK version number. /// </summary> [DataMember(Name = "awsSdkVersion")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("awsSdkVersion")] #endif public string AwsSdkVersion { get; set; } /// <summary> /// The ID of the client associated with the user pool. /// </summary> [DataMember(Name = "clientId")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientId")] #endif public string ClientId { get; set; } } }
31
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// AWS Cognito Trigger Common Parameters /// https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared /// </summary> [DataContract] public abstract class CognitoTriggerEvent<TRequest, TResponse> where TRequest : CognitoTriggerRequest, new() where TResponse : CognitoTriggerResponse, new() { /// <summary> /// The version number of your Lambda function. /// </summary> [DataMember(Name = "version")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("version")] #endif public string Version { get; set; } /// <summary> /// The AWS Region, as an AWSRegion instance. /// </summary> [DataMember(Name = "region")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("region")] #endif public string Region { get; set; } /// <summary> /// The user pool ID for the user pool. /// </summary> [DataMember(Name = "userPoolId")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userPoolId")] #endif public string UserPoolId { get; set; } /// <summary> /// The username of the current user. /// </summary> [DataMember(Name = "userName")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userName")] #endif public string UserName { get; set; } /// <summary> /// The caller context /// </summary> [DataMember(Name = "callerContext")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("callerContext")] #endif public CognitoTriggerCallerContext CallerContext { get; set; } = new CognitoTriggerCallerContext(); /// <summary> /// The name of the event that triggered the Lambda function.For a description of each triggerSource see User pool Lambda trigger sources. /// </summary> [DataMember(Name = "triggerSource")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("triggerSource")] #endif public string TriggerSource { get; set; } /// <summary> /// The request from the Amazon Cognito service /// </summary> [DataMember(Name = "request")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("request")] #endif public TRequest Request { get; set; } = new TRequest(); /// <summary> /// The response from your Lambda trigger.The return parameters in the response depend on the triggering event. /// </summary> [DataMember(Name = "response")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("response")] #endif public TResponse Response { get; set; } = new TResponse(); } }
87
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared /// </summary> [DataContract] public abstract class CognitoTriggerRequest { /// <summary> /// One or more pairs of user attribute names and values.Each pair is in the form "name": "value". /// </summary> [DataMember(Name = "userAttributes")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userAttributes")] #endif public Dictionary<string, string> UserAttributes { get; set; } = new Dictionary<string, string>(); } }
22
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared /// </summary> [DataContract] public abstract class CognitoTriggerResponse { } }
13
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html /// </summary> public class CognitoVerifyAuthChallengeEvent : CognitoTriggerEvent<CognitoVerifyAuthChallengeRequest, CognitoVerifyAuthChallengeResponse> { } }
10
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html /// </summary> public class CognitoVerifyAuthChallengeRequest : CognitoTriggerRequest { /// <summary> /// This parameter comes from the Create Auth Challenge trigger, and is compared against a user’s challengeAnswer to determine whether the user passed the challenge. /// </summary> [DataMember(Name = "privateChallengeParameters")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("privateChallengeParameters")] # endif public Dictionary<string, string> PrivateChallengeParameters { get; set; } = new Dictionary<string, string>(); /// <summary> /// This parameter comes from the Create Auth Challenge trigger, and is compared against a user’s challengeAnswer to determine whether the user passed the challenge. /// </summary> [DataMember(Name = "challengeAnswer")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeAnswer")] # endif public string ChallengeAnswer { get; set; } = string.Empty; /// <summary> /// One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: AdminVerifyUser, AdminRespondToAuthChallenge, ForgotPassword, and SignUp. /// </summary> [DataMember(Name = "clientMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("clientMetadata")] # endif public Dictionary<string, string> ClientMetadata { get; set; } /// <summary> /// This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User Pool client. /// </summary> [DataMember(Name = "userNotFound")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("userNotFound")] # endif public bool UserNotFound { get; set; } } }
48
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html /// </summary> public class CognitoVerifyAuthChallengeResponse : CognitoTriggerResponse { /// <summary> /// Set to true if the user has successfully completed the challenge, or false otherwise. /// </summary> [DataMember(Name = "answerCorrect")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("answerCorrect")] #endif public bool AnswerCorrect { get; set; } } }
20
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html /// </summary> [DataContract] public class GroupConfiguration { /// <summary> /// A list of the group names that are associated with the user that the identity token is issued for. /// </summary> [DataMember(Name = "groupsToOverride")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("groupsToOverride")] # endif public List<string> GroupsToOverride { get; set; } = new List<string>(); /// <summary> /// A list of the current IAM roles associated with these groups. /// </summary> [DataMember(Name = "iamRolesToOverride")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("iamRolesToOverride")] # endif public List<string> IamRolesToOverride { get; set; } = new List<string>(); /// <summary> /// A string indicating the preferred IAM role. /// </summary> [DataMember(Name = "preferredRole")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("preferredRole")] # endif public string PreferredRole { get; set; } } }
40
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.CognitoEvents")] [assembly: AssemblyDescription("Lambda event interfaces for Cognito event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
13
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.ConfigEvents { using System; /// <summary> /// AWS Config event /// http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules.html /// http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_example-events.html /// </summary> public class ConfigEvent { /// <summary> /// The ID of the AWS account that owns the rule. /// </summary> public string AccountId { get; set; } /// <summary> /// The ARN that AWS Config assigned to the rule. /// </summary> public string ConfigRuleArn { get; set; } /// <summary> /// The ID that AWS Config assigned to the rule. /// </summary> public string ConfigRuleId { get; set; } /// <summary> /// The name that you assigned to the rule that caused AWS Config /// to publish the event and invoke the function. /// </summary> public string ConfigRuleName { get; set; } /// <summary> /// A Boolean value that indicates whether the AWS resource to be /// evaluated has been removed from the rule's scope. /// </summary> public bool EventLeftScope { get; set; } /// <summary> /// The ARN of the IAM role that is assigned to AWS Config. /// </summary> public string ExecutionRoleArn { get; set; } /// <summary> /// If the event is published in response to a resource configuration /// change, the value for this attribute is a string that contains /// a JSON configuration item. /// </summary> public string InvokingEvent { get; set; } /// <summary> /// A token that the function must pass to AWS Config with the /// PutEvaluations call. /// </summary> public string ResultToken { get; set; } /// <summary> /// Key/value pairs that the function processes as part of its /// evaluation logic. /// </summary> public string RuleParameters { get; set; } /// <summary> /// A version number assigned by AWS. /// The version will increment if AWS adds attributes to AWS Config /// events. /// If a function requires an attribute that is only in events that /// match or exceed a specific version, then that function can check /// the value of this attribute. /// </summary> public string Version { get; set; } } }
75
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.ConfigEvents")] [assembly: AssemblyDescription("Lambda event interfaces for Config event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
13
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.ConnectEvents { /// <summary> /// This class represents the input event from Amazon Connect ContactFlow. It is used as the input parameter /// for Lambda functions. /// https://docs.aws.amazon.com/lambda/latest/dg/services-connect.html /// https://docs.aws.amazon.com/connect/latest/adminguide/connect-lambda-functions.html /// </summary> public class ContactFlowEvent { /// <summary> /// ContactFlow Details /// </summary> public ContactFlowDetails Details { get; set; } /// <summary> /// Event Name /// </summary> public string Name { get; set; } /// <summary> /// Class represnting details of ContactFlow /// </summary> public class ContactFlowDetails { /// <summary> /// Contact data. This is always passed by Amazon Connect for every contact. /// </summary> public ContactData ContactData { get; set; } /// <summary> /// These are parameters specific to this call that were defined when you created the Lambda function. /// </summary> public IDictionary<string, string> Parameters { get; set; } } /// <summary> /// Class representing contact data. /// </summary> public class ContactData { /// <summary> /// User attributes that have been previously associated with a contact, such as when using a Set contact attributes block in a contact flow. This map may be empty if there aren't any saved attributes. /// </summary> public IDictionary<string, string> Attributes { get; set; } /// <summary> /// Channel (such as Voice, Chat or Tasks) /// </summary> public string Channel { get; set; } /// <summary> /// Contact ID /// </summary> public string ContactId { get; set; } /// <summary> /// Customer Endpoint /// </summary> public Endpoint CustomerEndpoint { get; set; } /// <summary> /// Initial Contact ID /// </summary> public string InitialContactId { get; set; } /// <summary> /// Initiation Method (INBOUND | OUTBOUND | TRANSFER | CALLBACK) /// </summary> public string InitiationMethod { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the Amazon Connect instance. /// </summary> public string InstanceARN { get; set; } /// <summary> /// Previous Contact ID /// </summary> public string PreviousContactId { get; set; } /// <summary> /// Contains information about a queue. /// </summary> public Queue Queue { get; set; } /// <summary> /// System Endpoint /// </summary> public Endpoint SystemEndpoint { get; set; } } /// <summary> /// Class representing endpoint. /// </summary> public class Endpoint { /// <summary> /// Address (such as telephone number). /// </summary> public string Address { get; set; } /// <summary> /// Endpoint Type (such as TELEPHONE_NUMBER). /// </summary> public string Type { get; set; } } /// <summary> /// Contains information about a queue. /// </summary> public class Queue { /// <summary> /// The Amazon Resource Name (ARN) for the queue. /// </summary> public string Arn { get; set; } /// <summary> /// Queue name. /// </summary> public string Name { get; set; } } } }
130
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { /// <summary> /// Information about the client application that invoked the Lambda function. /// </summary> public interface IClientApplication { /// <summary> /// The application's package name. /// </summary> string AppPackageName { get; } /// <summary> /// The application's title. /// </summary> string AppTitle { get; } /// <summary> /// The application's version code. /// </summary> string AppVersionCode { get; } /// <summary> /// The application's version. /// </summary> string AppVersionName { get; } /// <summary> /// The application's installation id. /// </summary> string InstallationId { get; } } }
33
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { using System.Collections.Generic; /// <summary> /// Information about client configuration and execution environment. /// </summary> public interface IClientContext { /// <summary> /// Environment information provided by mobile SDK. /// </summary> IDictionary<string, string> Environment { get; } /// <summary> /// The client information provided by the AWS Mobile SDK. /// </summary> IClientApplication Client { get; } /// <summary> /// Custom values set by the client application. /// </summary> IDictionary<string, string> Custom { get; } } }
25
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { /// <summary> /// Information related to Amazon Congnito identities. /// </summary> public interface ICognitoIdentity { /// <summary> /// The Amazon Cognito identity ID. /// </summary> string IdentityId { get; } /// <summary> /// The Amazon Cognito identity pool ID. /// </summary> string IdentityPoolId { get; } } }
18
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { using System; /// <summary> /// Object that allows you to access useful information available within /// the Lambda execution environment. /// </summary> public interface ILambdaContext { /// <summary> /// The AWS request ID associated with the request. /// This is the same ID returned to the client that called invoke(). /// This ID is reused for retries on the same request. /// </summary> string AwsRequestId { get; } /// <summary> /// Information about the client application and device when invoked /// through the AWS Mobile SDK. It can be null. /// Client context provides client information such as client ID, /// application title, version name, version code, and the application /// package name. /// </summary> IClientContext ClientContext { get; } /// <summary> /// Name of the Lambda function that is running. /// </summary> string FunctionName { get; } /// <summary> /// The Lambda function version that is executing. /// If an alias is used to invoke the function, then this will be /// the version the alias points to. /// </summary> string FunctionVersion { get; } /// <summary> /// Information about the Amazon Cognito identity provider when /// invoked through the AWS Mobile SDK. /// Can be null. /// </summary> ICognitoIdentity Identity { get; } /// <summary> /// The ARN used to invoke this function. /// It can be function ARN or alias ARN. /// An unqualified ARN executes the $LATEST version and aliases execute /// the function version they are pointing to. /// </summary> string InvokedFunctionArn { get; } /// <summary> /// Lambda logger associated with the Context object. /// </summary> ILambdaLogger Logger { get; } /// <summary> /// The CloudWatch log group name associated with the invoked function. /// It can be null if the IAM user provided does not have permission for /// CloudWatch actions. /// </summary> string LogGroupName { get; } /// <summary> /// The CloudWatch log stream name for this function execution. /// It can be null if the IAM user provided does not have permission /// for CloudWatch actions. /// </summary> string LogStreamName { get; } /// <summary> /// Memory limit, in MB, you configured for the Lambda function. /// </summary> int MemoryLimitInMB { get; } /// <summary> /// Remaining execution time till the function will be terminated. /// At the time you create the Lambda function you set maximum time /// limit, at which time AWS Lambda will terminate the function /// execution. /// Information about the remaining time of function execution can be /// used to specify function behavior when nearing the timeout. /// </summary> TimeSpan RemainingTime { get; } } }
88
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { #if NET6_0_OR_GREATER /// <summary> /// Log Level for logging messages /// </summary> public enum LogLevel { /// <summary> /// Trace level logging /// </summary> Trace = 0, /// <summary> /// Debug level logging /// </summary> Debug = 1, /// <summary> /// Information level logging /// </summary> Information = 2, /// <summary> /// Warning level logging /// </summary> Warning = 3, /// <summary> /// Error level logging /// </summary> Error = 4, /// <summary> /// Critical level logging /// </summary> Critical = 5 } #endif /// <summary> /// Lambda runtime logger. /// </summary> public interface ILambdaLogger { /// <summary> /// Logs a message to AWS CloudWatch Logs. /// /// Logging will not be done: /// If the role provided to the function does not have sufficient permissions. /// </summary> /// <param name="message"></param> void Log(string message); /// <summary> /// Logs a message, followed by the current line terminator, to AWS CloudWatch Logs. /// /// Logging will not be done: /// If the role provided to the function does not have sufficient permissions. /// </summary> /// <param name="message"></param> void LogLine(string message); #if NET6_0_OR_GREATER /// <summary> /// Log message catagorized by the given log level /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="level"></param> /// <param name="message"></param> void Log(string level, string message) => LogLine(message); /// <summary> /// Log message catagorized by the given log level /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="level"></param> /// <param name="message"></param> void Log(LogLevel level, string message) => Log(level.ToString(), message); /// <summary> /// Log trace message /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="message"></param> void LogTrace(string message) => Log(LogLevel.Trace.ToString(), message); /// <summary> /// Log debug message /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="message"></param> void LogDebug(string message) => Log(LogLevel.Debug.ToString(), message); /// <summary> /// Log information message /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="message"></param> void LogInformation(string message) => Log(LogLevel.Information.ToString(), message); /// <summary> /// Log warning message /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="message"></param> void LogWarning(string message) => Log(LogLevel.Warning.ToString(), message); /// <summary> /// Log error message /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="message"></param> void LogError(string message) => Log(LogLevel.Error.ToString(), message); /// <summary> /// Log critical message /// <para> /// To configure the minimum log level set the AWS_LAMBDA_HANDLER_LOG_LEVEL environment variable. The value should be set /// to one of the values in the LogLevel enumeration. The default minimum log level is "Information". /// </para> /// </summary> /// <param name="message"></param> void LogCritical(string message) => Log(LogLevel.Critical.ToString(), message); #endif } }
148
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { using System.IO; /// <summary> /// Interface that must be implemented by custom serializers that /// may need to be called during execution. /// </summary> public interface ILambdaSerializer { /// <summary> /// This method is called to deserialize the request payload from Invoke API /// into the object that is passed to the Lambda function handler. /// </summary> /// <typeparam name="T">Type of object to deserialize to.</typeparam> /// <param name="requestStream">Stream to serialize.</param> /// <returns>Deserialized object from stream.</returns> T Deserialize<T>(Stream requestStream); /// <summary> /// This method is called to serialize the result returned from /// a Lambda function handler into the response payload /// that is returned by the Invoke API. /// </summary> /// <typeparam name="T">Type of object to serialize.</typeparam> /// <param name="response">Object to serialize.</param> /// <param name="responseStream">Output stream.</param> void Serialize<T>(T response, Stream responseStream); } }
31
aws-lambda-dotnet
aws
C#
using System; namespace Amazon.Lambda.Core { /// <summary> /// Static class which sends a message to AWS CloudWatch Logs. /// When used outside of a Lambda environment, logs are written to /// Console.Out. /// </summary> public static class LambdaLogger { // Logging action, logs to Console by default private static Action<string> _loggingAction = LogToConsole; // Logs message to console private static void LogToConsole(string message) { Console.WriteLine(message); } /// <summary> /// Logs a message to AWS CloudWatch Logs. /// /// Logging will not be done: /// If the role provided to the function does not have sufficient permissions. /// </summary> /// <param name="message"></param> public static void Log(string message) { _loggingAction(message); } } }
34
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.Core { using System; /// <summary> /// This attribute is required for serialization of input/output parameters of /// a Lambda function if your Lambda function uses types other than string or /// System.IO.Stream as input/output parameters. /// /// This attribute can be applied to a method (serializer used for method input /// and output), or to an assembly (serializer used for all methods). /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Assembly, AllowMultiple = false)] public sealed class LambdaSerializerAttribute : System.Attribute { /// <summary> /// Type of the serializer. /// The custom serializer must implement Amazon.Lambda.ILambdaSerializer /// interface, or an exception will be thrown. /// </summary> public Type SerializerType { get; set; } /// <summary> /// Constructs attribute with a specific serializer type. /// </summary> /// <param name="serializerType"></param> public LambdaSerializerAttribute(Type serializerType) { this.SerializerType = serializerType; } } }
33
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.Core")] [assembly: AssemblyDescription("Core interfaces for Lambda.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
13
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.DynamoDBEvents { using Amazon.DynamoDBv2.Model; using System; using System.Collections.Generic; /// <summary> /// AWS DynamoDB event /// http://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html /// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update /// </summary> public class DynamoDBEvent { /// <summary> /// List of DynamoDB event records. /// </summary> public IList<DynamodbStreamRecord> Records { get; set; } /// <summary> /// DynamoDB stream record /// http://docs.aws.amazon.com/dynamodbstreams/latest/APIReference/API_StreamRecord.html /// </summary> public class DynamodbStreamRecord : Record { /// <summary> /// The event source arn of DynamoDB. /// </summary> public string EventSourceArn { get; set; } } } }
33
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.DynamoDBEvents { using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// This class is used as the return type for AWS Lambda functions that are invoked by DynamoDB to report batch item failures. /// https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html#services-ddb-batchfailurereporting /// </summary> [DataContract] public class StreamsEventResponse { /// <summary> /// A list of records which failed processing. Returning the first record which failed would retry all remaining records from the batch. /// </summary> [DataMember(Name = "batchItemFailures", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("batchItemFailures")] #endif public IList<BatchItemFailure> BatchItemFailures { get; set; } /// <summary> /// The class representing the BatchItemFailure. /// </summary> [DataContract] public class BatchItemFailure { /// <summary> /// Sequence number of the record which failed processing. /// </summary> [DataMember(Name = "itemIdentifier", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("itemIdentifier")] #endif public string ItemIdentifier { get; set; } } } }
38
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.DynamoDBEvents")] [assembly: AssemblyDescription("Lambda event interfaces for DynamoDB event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
13
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.KafkaEvents { using System.Collections.Generic; using System.IO; /// <summary> /// Apache Kafka event /// https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html /// https://docs.aws.amazon.com/lambda/latest/dg/with-kafka.html /// </summary> public class KafkaEvent { /// <summary> /// The source of the event. /// </summary> public string EventSource { get; set; } /// <summary> /// The ARN of the event source. /// </summary> public string EventSourceArn { get; set; } /// <summary> /// Initial list of brokers as a CSV list of broker host or host:port. /// </summary> public string BootstrapServers { get; set; } /// <summary> /// List of Kafka event records. /// </summary> public IDictionary<string, IList<KafkaEventRecord>> Records { get; set; } /// <summary> /// Kafka event record. /// </summary> public class KafkaEventRecord { /// <summary> /// The topic associated with the event record. /// </summary> public string Topic { get; set; } /// <summary> /// The partition associated with the event record. /// </summary> public int Partition { get; set; } /// <summary> /// The partition offset associated with the event record. /// </summary> public long Offset { get; set; } /// <summary> /// The Kafka event record timestamp. /// </summary> public long Timestamp { get; set; } /// <summary> /// The Kafka event record timestamp type. /// </summary> public string TimestampType { get; set; } /// <summary> /// The Kafka event record Key. /// </summary> public string Key { get; set; } /// <summary> /// The Kafka event record Value. /// </summary> public MemoryStream Value { get; set; } /// <summary> /// The Kafka event record headers. /// </summary> public IList<IDictionary<string, sbyte[]>> Headers { get; set; } } } }
80
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.KinesisAnalyticsEvents { /// <summary> /// This class represents the event from Kinesis Analytics application to preprocess Kinesis Firehose data. /// </summary> [DataContract] public class KinesisAnalyticsFirehoseInputPreprocessingEvent { /// <summary> /// Gets or sets the invocation identifier. /// </summary> /// <value> /// The invocation identifier. /// </value> [DataMember(Name = "invocationId")] public string InvocationId { get; set; } /// <summary> /// Gets or sets the application arn. /// </summary> /// <value> /// The application arn. /// </value> [DataMember(Name = "applicationArn")] public string ApplicationArn { get; set; } /// <summary> /// Gets or sets the stream arn. /// </summary> /// <value> /// The stream arn. /// </value> [DataMember(Name = "streamArn")] public string StreamArn { get; set; } /// <summary> /// Gets or sets the records. /// </summary> /// <value> /// The records. /// </value> [DataMember(Name = "records")] public IList<FirehoseRecord> Records { get; set; } /// <summary> /// /// </summary> [DataContract] public class FirehoseRecord { /// <summary> /// Gets or sets the record identifier. /// </summary> /// <value> /// The record identifier. /// </value> [DataMember(Name = "recordId")] public string RecordId { get; set; } /// <summary> /// Gets or sets the record metadata. /// </summary> /// <value> /// The record metadata. /// </value> [DataMember(Name = "kinesisFirehoseRecordMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("kinesisFirehoseRecordMetadata")] #endif public KinesisFirehoseRecordMetadata RecordMetadata { get; set; } /// <summary> /// /// </summary> [DataContract] public class KinesisFirehoseRecordMetadata { /// <summary> /// The approximate time the record was sent to Kinesis Firehose. /// </summary> [IgnoreDataMember] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonIgnore] #endif public DateTime ApproximateArrivalTimestamp { get { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return epoch.AddMilliseconds(ApproximateArrivalEpoch); } } /// <summary> /// The approximate time the record was sent to Kinesis Firehose in epoch. /// </summary> [DataMember(Name = "approximateArrivalTimestamp")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("approximateArrivalTimestamp")] #endif public long ApproximateArrivalEpoch { get; set; } } /// <summary> /// Gets or sets the base64 encoded data. /// </summary> /// <value> /// The base64 encoded data. /// </value> [DataMember(Name = "data")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string Base64EncodedData { get; set; } /// <summary> /// Base64 decodes the Base64EncodedData property. /// </summary> /// <returns></returns> public string DecodeData() { var decodedData = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(this.Base64EncodedData)); return decodedData; } } } }
134
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.KinesisAnalyticsEvents { /// <summary> /// This class represents the response from Lambda function for Kinesis Analytics input preprocessing. /// </summary> [DataContract] public class KinesisAnalyticsInputPreprocessingResponse { /// <summary> /// The record was preprocessed successfully. /// </summary> public const string OK = "Ok"; /// <summary> /// The record was dropped intentionally by your processing logic. /// </summary> public const string DROPPED = "Dropped"; /// <summary> /// The record could not be preprocessed. /// </summary> public const string PROCESSINGFAILED = "ProcessingFailed"; /// <summary> /// Gets or sets the records. /// </summary> /// <value> /// The records. /// </value> [DataMember(Name = "records")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("records")] #endif public IList<Record> Records { get; set; } /// <summary> /// /// </summary> [DataContract] public class Record { /// <summary> /// Gets or sets the record identifier. /// </summary> /// <value> /// The record identifier. /// </value> [DataMember(Name = "recordId")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("recordId")] #endif public string RecordId { get; set; } /// <summary> /// Gets or sets the result. /// </summary> /// <value> /// The result. /// </value> [DataMember(Name = "result")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("result")] #endif public string Result { get; set; } /// <summary> /// Gets or sets the base64 encoded data. /// </summary> /// <value> /// The base64 encoded data. /// </value> [DataMember(Name = "data")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string Base64EncodedData { get; set; } /// <summary> /// Encodes the data. /// </summary> /// <param name="data">The data.</param> public void EncodeData(string data) { this.Base64EncodedData = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(data)); } } } }
94
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.KinesisAnalyticsEvents { /// <summary> /// This class represents the event from Kinesis Analytics application output. /// </summary> [DataContract] public class KinesisAnalyticsOutputDeliveryEvent { /// <summary> /// Gets or sets the invocation identifier. /// </summary> /// <value> /// The invocation identifier. /// </value> [DataMember(Name = "invocationId")] public string InvocationId { get; set; } /// <summary> /// Gets or sets the application arn. /// </summary> /// <value> /// The application arn. /// </value> [DataMember(Name = "applicationArn")] public string ApplicationArn { get; set; } /// <summary> /// Gets or sets the records. /// </summary> /// <value> /// The records. /// </value> [DataMember(Name = "records")] public IList<DeliveryRecord> Records { get; set; } /// <summary> /// /// </summary> [DataContract] public class DeliveryRecord { /// <summary> /// Gets or sets the record identifier. /// </summary> /// <value> /// The record identifier. /// </value> [DataMember(Name = "recordId")] public string RecordId { get; set; } /// <summary> /// Gets or sets the record metadata. /// </summary> /// <value> /// The record metadata. /// </value> [DataMember(Name = "lambdaDeliveryRecordMetadata")] public LambdaDeliveryRecordMetadata RecordMetadata { get; set; } /// <summary> /// /// </summary> [DataContract] public class LambdaDeliveryRecordMetadata { /// <summary> /// Gets or sets the retry hint. /// </summary> /// <value> /// The retryHint is a value that increases for every delivery failure of the record. /// </value> [DataMember(Name = "retryHint")] public long RetryHint { get; set; } } /// <summary> /// Gets or sets the base64 encoded data. /// </summary> /// <value> /// The base64 encoded data. /// </value> [DataMember(Name = "data")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string Base64EncodedData { get; set; } /// <summary> /// Base64 decodes the Base64EncodedData property. /// </summary> /// <returns></returns> public string DecodeData() { var decodedData = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(this.Base64EncodedData)); return decodedData; } } } }
104
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.KinesisAnalyticsEvents { /// <summary> /// This class represents the response from Lambda function for Kinesis Analytics output delivery. /// </summary> [DataContract] public class KinesisAnalyticsOutputDeliveryResponse { /// <summary> /// The record was delivered successfully. /// </summary> public const string OK = "Ok"; /// <summary> /// The record delivery failed. /// </summary> public const string DELIVERY_FAILED = "DeliveryFailed"; /// <summary> /// Gets or sets the records. /// </summary> /// <value> /// The records. /// </value> [DataMember(Name = "records")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("records")] #endif public IList<Record> Records { get; set; } /// <summary> /// /// </summary> [DataContract] public class Record { /// <summary> /// Gets or sets the record identifier. /// </summary> /// <value> /// The record identifier. /// </value> [DataMember(Name = "recordId")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("recordId")] #endif public string RecordId { get; set; } /// <summary> /// Gets or sets the result. /// </summary> /// <value> /// The result. /// </value> [DataMember(Name = "result")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("result")] #endif public string Result { get; set; } } } }
68
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.KinesisAnalyticsEvents { /// <summary> /// This class represents the event from Kinesis Analytics application to preprocess Kinesis stream data. /// </summary> [DataContract] public class KinesisAnalyticsStreamsInputPreprocessingEvent { /// <summary> /// Gets or sets the invocation identifier. /// </summary> /// <value> /// The invocation identifier. /// </value> [DataMember(Name = "invocationId")] public string InvocationId { get; set; } /// <summary> /// Gets or sets the application arn. /// </summary> /// <value> /// The application arn. /// </value> [DataMember(Name = "applicationArn")] public string ApplicationArn { get; set; } /// <summary> /// Gets or sets the stream arn. /// </summary> /// <value> /// The stream arn. /// </value> [DataMember(Name = "streamArn")] public string StreamArn { get; set; } /// <summary> /// Gets or sets the records. /// </summary> /// <value> /// The records. /// </value> [DataMember(Name = "records")] public IList<StreamsRecord> Records { get; set; } /// <summary> /// /// </summary> [DataContract] public class StreamsRecord { /// <summary> /// Gets or sets the record identifier. /// </summary> /// <value> /// The record identifier. /// </value> [DataMember(Name = "recordId")] public string RecordId { get; set; } /// <summary> /// Gets or sets the record metadata. /// </summary> /// <value> /// The record metadata. /// </value> [DataMember(Name = "kinesisStreamRecordMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("kinesisStreamRecordMetadata")] #endif public KinesisStreamRecordMetadata RecordMetadata { get; set; } /// <summary> /// /// </summary> [DataContract] public class KinesisStreamRecordMetadata { /// <summary> /// Gets or sets the sequence number. /// </summary> /// <value> /// The sequence number. /// </value> [DataMember(Name = "sequenceNumber")] public string SequenceNumber { get; set; } /// <summary> /// Gets or sets the partition key. /// </summary> /// <value> /// The partition key. /// </value> [DataMember(Name = "partitionKey")] public string PartitionKey { get; set; } /// <summary> /// The approximate time the record was sent to Kinesis Steam. /// </summary> [IgnoreDataMember] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonIgnore] #endif public DateTime ApproximateArrivalTimestamp { get { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return epoch.AddMilliseconds(ApproximateArrivalEpoch); } } /// <summary> /// The approximate time the record was sent to Kinesis stream in epoch. /// </summary> [DataMember(Name = "approximateArrivalTimestamp")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("approximateArrivalTimestamp")] #endif public long ApproximateArrivalEpoch { get; set; } /// <summary> /// Gets or sets the shard identifier. /// </summary> /// <value> /// The shard identifier. /// </value> [DataMember(Name = "shardId")] public string ShardId { get; set; } } /// <summary> /// Gets or sets the base64 encoded data. /// </summary> /// <value> /// The base64 encoded data. /// </value> [DataMember(Name = "data")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string Base64EncodedData { get; set; } /// <summary> /// Base64 decodes the Base64EncodedData property. /// </summary> /// <returns></returns> public string DecodeData() { var decodedData = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(this.Base64EncodedData)); return decodedData; } } } }
160
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.KinesisEvents { using System; using System.Collections.Generic; /// <summary> /// AWS Kinesis stream event /// http://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html /// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-kinesis-streams /// </summary> public class KinesisEvent { /// <summary> /// List of Kinesis event records. /// </summary> public IList<KinesisEventRecord> Records { get; set; } /// <summary> /// AWS Kinesis stream record /// http://docs.aws.amazon.com/kinesis/latest/APIReference/API_Record.html /// </summary> public class Record : Amazon.Kinesis.Model.Record { /// <summary> /// The schema version for the record. /// </summary> public string KinesisSchemaVersion { get; set; } } /// <summary> /// Kinesis event record. /// </summary> public class KinesisEventRecord { /// <summary> /// The AWS region where the event originated. /// </summary> public string AwsRegion { get; set; } /// <summary> /// The event id. /// </summary> public string EventId { get; set; } /// <summary> /// The name of the event. /// </summary> public string EventName { get; set; } /// <summary> /// The source of the event. /// </summary> public string EventSource { get; set; } /// <summary> /// The ARN of the event source. /// </summary> public string EventSourceARN { get; set; } /// <summary> /// The event version. /// </summary> public string EventVersion { get; set; } /// <summary> /// The ARN for the identity used to invoke the Lambda Function. /// </summary> public string InvokeIdentityArn { get; set; } /// <summary> /// The underlying Kinesis record associated with the event. /// </summary> public Record Kinesis { get; set; } } } }
77
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.KinesisEvents")] [assembly: AssemblyDescription("Lambda event interfaces for Kinesis event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
13
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Amazon.Lambda.KinesisFirehoseEvents { /// <summary> /// This class represents the input event from Amazon Kinesis Firehose. It used as the input parameter /// for Lambda functions. /// </summary> public class KinesisFirehoseEvent { /// <summary> /// The Id of the invocation. /// </summary> public string InvocationId { get; set; } /// <summary> /// The ARN of the delivery stream sending the event. /// </summary> public string DeliveryStreamArn { get; set; } /// <summary> /// The AWS region for delivery stream. /// </summary> public string Region { get; set; } /// <summary> /// The Kinesis records to transform. /// </summary> public IList<FirehoseRecord> Records { get; set; } /// <summary> /// The records for the Kinesis Firehose event to process and transform. /// </summary> [DataContract] public class FirehoseRecord { /// <summary> ///The record ID is passed from Firehose to Lambda during the invocation. The transformed record must ///contain the same record ID. Any mismatch between the ID of the original record and the ID of the ///transformed record is treated as a data transformation failure. /// </summary> [DataMember(Name = "recordId")] public string RecordId { get; set; } /// <summary> /// The approximate time the record was sent to Kinesis Firehose as a Unix epoch. /// </summary> [DataMember(Name = "approximateArrivalTimestamp")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("approximateArrivalTimestamp")] #endif public long ApproximateArrivalEpoch { get; set; } /// <summary> /// The approximate time the record was sent to Kinesis Firehose. /// </summary> [IgnoreDataMember] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonIgnore()] #endif public DateTime ApproximateArrivalTimestamp { get { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return epoch.AddMilliseconds(ApproximateArrivalEpoch); } } /// <summary> /// The data sent through as a Kinesis Firehose record. The data is sent to the Lambda function base64 encoded. /// </summary> [DataMember(Name = "data")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string Base64EncodedData { get; set; } /// <summary> /// Base64 decodes the Base64EncodedData property. /// </summary> /// <returns></returns> public string DecodeData() { var decodedData = Encoding.UTF8.GetString(Convert.FromBase64String(this.Base64EncodedData)); return decodedData; } } } }
97
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Amazon.Lambda.KinesisFirehoseEvents { /// <summary> /// The response for the Lambda functions handling Kinesis Firehose transformations. /// </summary> [DataContract] public class KinesisFirehoseResponse { /// <summary> /// The record was transformed successfully. /// </summary> public const string TRANSFORMED_STATE_OK = "Ok"; /// <summary> /// The record was dropped intentionally by your processing logic. /// </summary> public const string TRANSFORMED_STATE_DROPPED = "Dropped"; /// <summary> /// The record could not be transformed. /// </summary> public const string TRANSFORMED_STATE_PROCESSINGFAILED = "ProcessingFailed"; /// <summary> /// The transformed records from the KinesisFirehoseEvent. /// </summary> [DataMember(Name = "records")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("records")] #endif public IList<FirehoseRecord> Records { get; set; } /// <summary> /// The transformed records after processing KinesisFirehoseEvent.Records /// </summary> [DataContract] public class FirehoseRecord { /// <summary> ///The record ID is passed from Firehose to Lambda during the invocation. The transformed record must ///contain the same record ID. Any mismatch between the ID of the original record and the ID of the ///transformed record is treated as a data transformation failure. /// </summary> [DataMember(Name = "recordId")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("recordId")] #endif public string RecordId { get; set; } /// <summary> /// The status of the data transformation of the record. The possible values are: "Ok" /// (the record was transformed successfully), "Dropped" (the record was dropped intentionally /// by your processing logic), and "ProcessingFailed" (the record could not be transformed). /// If a record has a status of "Ok" or "Dropped", Firehose considers it successfully /// processed. Otherwise, Firehose considers it unsuccessfully processed. /// /// Possible values: /// <list type="table"> /// <item> /// <term>Ok</term> /// <description>The record was transformed successfully</description> /// </item> /// <item> /// <term>Dropped</term> /// <description>The record was dropped intentionally by your processing logic</description> /// </item> /// <item> /// <term>ProcessingFailed</term> /// <description>The record could not be transformed</description> /// </item> /// </list> /// </summary> [DataMember(Name = "result")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("result")] #endif public string Result { get; set; } /// <summary> /// The transformed data payload, after base64-encoding. /// </summary> [DataMember(Name = "data")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string Base64EncodedData { get; set; } /// <summary> /// The response record metadata. /// </summary> [DataMember(Name = "metadata")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("metadata")] #endif public FirehoseResponseRecordMetadata Metadata { get; set; } /// <summary> /// Base64 encodes the data and sets the Base64EncodedData property. /// </summary> /// <param name="data">The data to be base64 encoded.</param> public void EncodeData(string data) { this.Base64EncodedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); } } /// <summary> /// The response record metadata after processing KinesisFirehoseEvent.Records /// </summary> [DataContract] public class FirehoseResponseRecordMetadata { /// <summary> /// Key Value pairs used for Dynamic Partitioning /// https://docs.aws.amazon.com/firehose/latest/dev/dynamic-partitioning.html /// </summary> [DataMember(Name = "partitionKeys")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("partitionKeys")] #endif public Dictionary<string, string> PartitionKeys { get; set; } } } }
133
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexEvents { /// <summary> /// One or more contexts that are active during this turn of a conversation with the user. /// </summary> [DataContract] public class LexActiveContext { /// <summary> /// The length of time or number of turns in the conversation with the user that the context remains active. /// </summary> [DataMember(Name = "timeToLive", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("timeToLive")] #endif public TimeToLive TimeToLive { get; set; } /// <summary> /// The name of the context. /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("name")] #endif public string Name { get; set; } /// <summary> /// A list of key/value pairs the contains the name and value of the slots from the intent that activated the context. /// </summary> [DataMember(Name = "parameters", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("parameters")] #endif public IDictionary<string, string> Parameters { get; set; } } /// <summary> /// The length of time or number of turns in the conversation with the user that the context remains active. /// </summary> [DataContract] public class TimeToLive { /// <summary> /// The length of time that the context remains active. /// </summary> [DataMember(Name = "timeToLiveInSeconds", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("timeToLiveInSeconds")] #endif public int TimeToLiveInSeconds { get; set; } /// <summary> /// The number of turns in the conversation with the user that the context remains active. /// </summary> [DataMember(Name = "turnsToLive", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("turnsToLive")] #endif public int TurnsToLive { get; set; } } }
64
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexEvents { /// <summary> /// This class represents the input event from Amazon Lex. It used as the input parameter /// for Lambda functions. /// http://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html /// </summary> public class LexEvent { /// <summary> /// Provides the intent name, slots, and confirmationStatus fields. /// </summary> public LexCurrentIntent CurrentIntent { get; set; } /// <summary> /// Provides additional information about a slot value. /// </summary> public IDictionary<string, SlotDetail> SlotDetails { get; set; } /// <summary> /// The Lex bot invoking the Lambda function /// </summary> public LexBot Bot { get; set; } /// <summary> /// This value is provided by the client application. Amazon Lex passes it to the Lambda function. /// </summary> public string UserId { get; set; } /// <summary> /// The text used to process the request. /// </summary> public string InputTranscript { get; set; } /// <summary> /// To indicate why Amazon Lex is invoking the Lambda function /// </summary> public string InvocationSource { get; set; } /// <summary> /// For each user input, the client sends the request to Amazon Lex using one of the runtime API operations, /// PostContent or PostText. From the API request parameters, Amazon Lex determines whether the response /// to the client (user) is text or voice, and sets this field accordingly. /// <para> /// The Lambda function can use this information to generate an appropriate message. /// For example, if the client expects a voice response, your Lambda function could return /// Speech Synthesis Markup LanguageSpeech Synthesis Markup Language (SSML) instead of text. /// </para> /// </summary> public string OutputDialogMode { get; set; } /// <summary> /// The version of the message that identifies the format of the event data going into the /// Lambda function and the expected format of the response from a Lambda function. /// </summary> public string MessageVersion { get; set; } /// <summary> /// Application-specific session attributes that the client sent in the request. If you want /// Amazon Lex to include them in the response to the client, your Lambda function should /// send these back to Amazon Lex in response. /// </summary> public IDictionary<string, string> SessionAttributes { get; set; } /// <summary> /// Request-specific attributes that the client sends in the request. Use request attributes to /// pass information that doesn't need to persist for the entire session. /// </summary> public IDictionary<string, string> RequestAttributes { get; set; } /// <summary> /// A List of alternative intents that are returned when the bot is in advanced mode /// </summary> public IList<LexCurrentIntent> AlternativeIntents { get; set; } /// <summary> /// The result of an Amazon Comprehend sentiment analysis of the last utterance. /// </summary> public LexSentimentResponseType SentimentResponse { get; set; } /// <summary> /// If included, sets values for one or more recent intents. You can include information for up to three intents. /// </summary> public IList<LexRecentIntentSummaryViewType> RecentIntentSummaryView { get; set; } /// <summary> /// Gets and sets the property ActiveContexts. /// A list of active contexts for the session.A context can be set when an intent is fulfilled or by calling the PostContent, PostText, or PutSession operation. /// You can use a context to control the intents that can follow up an intent, or to modify the operation of your application. /// </summary> public IList<LexActiveContext> ActiveContexts { get; set; } /// <summary> /// Class representing the sentiment response. /// </summary> public class LexSentimentResponseType { /// <summary> /// Gets and sets the SentimentLabel /// </summary> public string SentimentLabel { get; set; } /// <summary> /// Gets and sets the SentimentScore /// </summary> public string SentimentScore { get; set; } } /// <summary> /// The class representing the current intent for the Lambda function to process. /// </summary> public class LexCurrentIntent { /// <summary> /// The intent's name /// </summary> public string Name { get; set; } /// <summary> /// List of slots that are configured for the intent and values that are recognized by /// Amazon Lex in the user conversation from the beginning. Otherwise, the values are null. /// </summary> public IDictionary<string, string> Slots { get; set; } /// <summary> /// Provides additional information about a slot value. /// </summary> public IDictionary<string, SlotDetail> SlotDetails { get; set; } /// <summary> /// Gets and sets the property NluIntentConfidence. /// </summary> public double? NluIntentConfidenceScore { get; set; } /// <summary> /// The ConfirmationStatus provides the user response to a confirmation prompt, if there is one. /// </summary> public string ConfirmationStatus { get; set; } } /// <summary> /// The class representing the information for a SlotDetail /// </summary> public class SlotDetail { /// <summary> /// The resolutions array contains a list of additional values recognized for the slot. /// </summary> public IList<Dictionary<string, string>> Resolutions { get; set; } /// <summary> /// The originalValue field contains the value that was entered by the user for the slot. /// </summary> public string OriginalValue { get; set; } } /// <summary> /// The class identifies the Lex bot that is invoking the Lambda function. /// </summary> public class LexBot { /// <summary> /// The name of the Lex bot /// </summary> public string Name { get; set; } /// <summary> /// The alias of the Lex bot /// </summary> public string Alias { get; set; } /// <summary> /// The version of the Lex bot /// </summary> public string Version { get; set; } } } }
187
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexEvents { /// <summary> /// The class recent intent summary view. /// </summary> [DataContract] public class LexRecentIntentSummaryViewType { /// <summary> /// Gets and sets the IntentName /// </summary> [DataMember(Name = "intentName", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("intentName")] #endif public string IntentName { get; set; } /// <summary> /// Gets and sets the CheckpointLabel /// </summary> [DataMember(Name = "checkpointLabel", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("checkpointLabel")] #endif public string CheckpointLabel { get; set; } /// <summary> /// Gets and sets the Slots /// </summary> [DataMember(Name = "slots", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("slots")] #endif public IDictionary<string, string> Slots { get; set; } /// <summary> /// Gets and sets the ConfirmationStatus /// </summary> [DataMember(Name = "confirmationStatus", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("confirmationStatus")] #endif public string ConfirmationStatus { get; set; } /// <summary> /// Gets and sets the DialogActionType /// </summary> [DataMember(Name = "dialogActionType", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("dialogActionType")] #endif public string DialogActionType { get; set; } /// <summary> /// Gets and sets the FulfillmentState /// </summary> [DataMember(Name = "fulfillmentState", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("fulfillmentState")] #endif public string FulfillmentState { get; set; } /// <summary> /// Gets and sets the SlotToElicit /// </summary> [DataMember(Name = "slotToElicit", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("slotToElicit")] #endif public string SlotToElicit { get; set; } } }
76
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.LexEvents { using System; using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// This class is used as the return for AWS Lambda functions that are invoked by Lex to handle Bot interactions. /// http://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html /// </summary> [DataContract] public class LexResponse { /// <summary> /// Application-specific session attributes. This is an optional field. /// </summary> [DataMember(Name = "sessionAttributes", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("sessionAttributes")] #endif public IDictionary<string, string> SessionAttributes { get; set; } /// <summary> /// This is the only field that is required. The value of DialogAction.Type directs /// Amazon Lex to the next course of action, and describes what to expect from the user /// after Amazon Lex returns a response to the client. /// </summary>\ [DataMember(Name = "dialogAction", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("dialogAction")] #endif public LexDialogAction DialogAction { get; set; } /// <summary> /// If included, sets the value for one or more contexts. This is an optional field /// For example, you can include a context to make one or more intents that have that context as an input eligible for recognition in the next turn of the conversation. /// </summary> [DataMember(Name = "activeContexts", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("activeContexts")] #endif public IList<LexActiveContext> ActiveContexts { get; set; } /// <summary> /// If included, sets values for one or more recent intents. You can include information for up to three intents. /// </summary> [DataMember(Name = "recentIntentSummaryView", EmitDefaultValue = false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("recentIntentSummaryView")] #endif public IList<LexRecentIntentSummaryViewType> RecentIntentSummaryView { get; set; } /// <summary> /// The class representing the dialog action. /// </summary> [DataContract] public class LexDialogAction { /// <summary> /// The type of action for Lex to take with the response from the Lambda function. /// </summary> [DataMember(Name = "type", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("type")] #endif public string Type { get; set; } /// <summary> /// The state of the fullfillment. "Fulfilled" or "Failed" /// </summary> [DataMember(Name = "fulfillmentState", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("fulfillmentState")] #endif public string FulfillmentState { get; set; } /// <summary> /// The message to be sent to the user. /// </summary> [DataMember(Name = "message", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("message")] #endif public LexMessage Message { get; set; } /// <summary> /// The intent name you want to confirm or elicit. /// </summary> [DataMember(Name = "intentName", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("intentName")] #endif public string IntentName { get; set; } /// <summary> /// The values for all of the slots when response is of type "Delegate". /// </summary> [DataMember(Name = "slots", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("slots")] #endif public IDictionary<string, string> Slots { get; set; } /// <summary> /// The slot to elicit when the Type is "ElicitSlot" /// </summary> [DataMember(Name = "slotToElicit", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("slotToElicit")] #endif public string SlotToElicit { get; set; } /// <summary> /// The response card provides information back to the bot to display for the user. /// </summary> [DataMember(Name = "responseCard", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("responseCard")] #endif public LexResponseCard ResponseCard { get; set; } } /// <summary> /// The class represents the message that the bot will use. /// </summary> [DataContract] public class LexMessage { /// <summary> /// The content type of the message. PlainText or SSML /// </summary> [DataMember(Name = "contentType", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("contentType")] #endif public string ContentType { get; set; } /// <summary> /// The message to be asked to the user by the bot. /// </summary> [DataMember(Name = "content", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("content")] #endif public string Content { get; set; } } /// <summary> /// The class representing the response card sent back to the user. /// </summary> [DataContract] public class LexResponseCard { /// <summary> /// The version of the response card. /// </summary> [DataMember(Name = "version", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("version")] #endif public int? Version { get; set; } /// <summary> /// The content type of the response card. The default is "application/vnd.amazonaws.card.generic". /// </summary> [DataMember(Name = "contentType", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("contentType")] #endif public string ContentType { get; set; } = "application/vnd.amazonaws.card.generic"; /// <summary> /// The list of attachments sent back with the response card. /// </summary> [DataMember(Name = "genericAttachments", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("genericAttachments")] #endif public IList<LexGenericAttachments> GenericAttachments { get; set; } } /// <summary> /// The class representing generic attachments. /// </summary> [DataContract] public class LexGenericAttachments { /// <summary> /// The card's title. /// </summary> [DataMember(Name = "title", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("title")] #endif public string Title { get; set; } /// <summary> /// The card's sub title. /// </summary> [DataMember(Name = "subTitle", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("subTitle")] #endif public string SubTitle { get; set; } /// <summary> /// URL to an image to be shown. /// </summary> [DataMember(Name = "imageUrl", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("imageUrl")] #endif public string ImageUrl { get; set; } /// <summary> /// URL of the attachment to be associated with the card. /// </summary> [DataMember(Name = "attachmentLinkUrl", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("attachmentLinkUrl")] #endif public string AttachmentLinkUrl { get; set; } /// <summary> /// The list of buttons to be displayed with the response card. /// </summary> [DataMember(Name = "buttons", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("buttons")] #endif public IList<LexButton> Buttons { get; set; } } /// <summary> /// The class representing a button in the response card. /// </summary> [DataContract] public class LexButton { /// <summary> /// The text for the button. /// </summary> [DataMember(Name = "text", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("text")] #endif public string Text { get; set; } /// <summary> /// The value of the button sent back to the server. /// </summary> [DataMember(Name = "value", EmitDefaultValue=false)] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("value")] #endif public string Value { get; set; } } } }
260
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; namespace Amazon.Lambda.LexV2Events { /// <summary> /// A class that represents Kendra Response /// https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax /// </summary> public class KendraResponse { /// <summary> /// Contains the facet results. A <code>FacetResult</code> contains the counts for each /// attribute key that was specified in the <code>Facets</code> input parameter. /// </summary> public IList<FacetResult> FacetResults { get; set; } /// <summary> /// The unique identifier for the search. You use <code>QueryId</code> to identify the /// search when using the feedback API. /// </summary> public string QueryId { get; set; } /// <summary> /// Gets and sets the property ResultItems. /// <para> /// The results of the search. /// </para> /// </summary> public IList<QueryResultItem> ResultItems { get; set; } /// <summary> /// A list of information related to suggested spell corrections for a query. /// </summary> public IList<SpellCorrectedQuery> SpellCorrectedQueries { get; set; } /// <summary> /// The total number of items found by the search; however, you can only retrieve up to /// 100 items. For example, if the search found 192 items, you can only retrieve the first /// 100 of the items. /// </summary> public int TotalNumberOfResults { get; set; } /// <summary> /// A list of warning codes and their messages on problems with your query. /// /// <para> /// Amazon Kendra currently only supports one type of warning, which is a warning on invalid /// syntax used in the query. For examples of invalid query syntax, see <a href="https://docs.aws.amazon.com/kendra/latest/dg/searching-example.html#searching-index-query-syntax">Searching /// with advanced query syntax</a>. /// </para> /// </summary> public IList<Warning> Warnings { get; set; } /// <summary> /// The facet values for the documents in the response. /// </summary> public class FacetResult { /// <summary> /// The key for the facet values. This is the same as the <code>DocumentAttributeKey</code> provided in the query. /// </summary> public string DocumentAttributeKey { get; set; } /// <summary> /// An array of key/value pairs, where the key is the value of the attribute and the count is the number of documents that share the key value. /// </summary> public IList<DocumentAttributeValueCountPair> DocumentAttributeValueCountPairs { get; set; } /// <summary> /// The data type of the facet value. This is the same as the type defined for the index field when it was created. /// </summary> public string DocumentAttributeValueType { get; set; } } /// <summary> /// Provides the count of documents that match a particular attribute when doing a faceted /// search. /// </summary> public class DocumentAttributeValueCountPair { /// <summary> /// The number of documents in the response that have the attribute value for the key. /// </summary> public int? Count { get; set; } /// <summary> /// The value of the attribute. For example, "HR." /// </summary> public DocumentAttributeValue DocumentAttributeValue { get; set; } } /// <summary> /// The value of a custom document attribute. You can only provide one value for a custom /// attribute. /// </summary> public class DocumentAttributeValue { /// <summary> /// A date expressed as an ISO 8601 string. /// /// <para> /// It is important for the time zone to be included in the ISO 8601 date-time format. /// For example, 2012-03-25T12:30:10+01:00 is the ISO 8601 date-time format for March /// 25th 2012 at 12:30PM (plus 10 seconds) in Central European Time. /// </para> /// </summary> public DateTime? DateValue { get; set; } /// <summary> /// A long integer value. /// </summary> public long? LongValue { get; set; } /// <summary> /// A list of strings. /// </summary> public IList<string> StringListValue { get; set; } /// <summary> /// A string, such as "department". /// </summary> public string StringValue { get; set; } } /// <summary> /// A query with suggested spell corrections. /// </summary> public class SpellCorrectedQuery { /// <summary> /// The corrected misspelled word or words in a query. /// </summary> public IList<Correction> Corrections { get; set; } /// <summary> /// The query with the suggested spell corrections. /// </summary> public string SuggestedQueryText { get; set; } } /// <summary> /// A corrected misspelled word in a query. /// </summary> public class Correction { /// <summary> /// The zero-based location in the response string or text where the corrected word starts. /// </summary> public int? BeginOffset { get; set; } /// <summary> /// The string or text of a corrected misspelled word in a query. /// </summary> public string CorrectedTerm { get; set; } /// <summary> /// The zero-based location in the response string or text where the corrected word ends. /// </summary> public int? EndOffset { get; set; } /// <summary> /// The string or text of a misspelled word in a query. /// </summary> public string Term { get; set; } } /// <summary> /// The warning code and message that explains a problem with a query. /// </summary> public class Warning { /// <summary> /// The code used to show the type of warning for the query. /// </summary> public string Code { get; set; } /// <summary> /// The message that explains the problem with the query. /// </summary> public string Message { get; set; } } /// <summary> /// A single query result. /// /// /// <para> /// A query result contains information about a document returned by the query. This includes /// the original location of the document, a list of attributes assigned to the document, /// and relevant text from the document that satisfies the query. /// </para> /// </summary> public class QueryResultItem { /// <summary> /// Gets and sets the property AdditionalAttributes. /// <para> /// One or more additional attributes associated with the query result. /// </para> /// </summary> public IList<AdditionalResultAttribute> AdditionalAttributes { get; set; } /// <summary> /// An array of document attributes for the document that the query result maps to. For /// example, the document author (Author) or the source URI (SourceUri) of the document. /// </summary> public IList<DocumentAttribute> DocumentAttributes { get; set; } /// <summary> /// An extract of the text in the document. Contains information about highlighting the /// relevant terms in the excerpt. /// </summary> public TextWithHighlights DocumentExcerpt { get; set; } /// <summary> /// The unique identifier for the document. /// </summary> public string DocumentId { get; set; } /// <summary> /// The title of the document. Contains the text of the title and information for highlighting /// the relevant terms in the title. /// </summary> public TextWithHighlights DocumentTitle { get; set; } /// <summary> /// The URI of the original location of the document. /// </summary> public string DocumentURI { get; set; } /// <summary> /// A token that identifies a particular result from a particular query. Use this token /// to provide click-through feedback for the result. For more information, see <a href="https://docs.aws.amazon.com/kendra/latest/dg/submitting-feedback.html"> /// Submitting feedback </a>. /// </summary> public string FeedbackToken { get; set; } /// <summary> /// The unique identifier for the query result. /// </summary> public string Id { get; set; } /// <summary> /// Indicates the confidence that Amazon Kendra has that a result matches the query that /// you provided. Each result is placed into a bin that indicates the confidence, <code>VERY_HIGH</code>, /// <code>HIGH</code>, <code>MEDIUM</code> and <code>LOW</code>. You can use the score /// to determine if a response meets the confidence needed for your application. /// /// <para> /// The field is only set to <code>LOW</code> when the <code>Type</code> field is set /// to <code>DOCUMENT</code> and Amazon Kendra is not confident that the result matches /// the query. /// </para> /// </summary> public ScoreAttributes ScoreAttributes { get; set; } /// <summary> /// The type of document. /// </summary> public string Type { get; set; } } /// <summary> /// An attribute returned from an index query. /// </summary> public class AdditionalResultAttribute { /// <summary> /// The key that identifies the attribute. /// </summary> public string Key { get; set; } /// <summary> /// An object that contains the attribute value. /// </summary> public AdditionalResultAttributeValue Value { get; set; } /// <summary> /// The data type of the <code>Value</code> property. /// </summary> public string ValueType { get; set; } } /// <summary> /// An attribute returned with a document from a search. /// </summary> public class AdditionalResultAttributeValue { /// <summary> /// The text associated with the attribute and information about the highlight to apply /// to the text. /// </summary> public TextWithHighlights TextWithHighlightsValue { get; set; } } /// <summary> /// A custom attribute value assigned to a document. /// </summary> public class DocumentAttribute { /// <summary> /// The identifier for the attribute. /// </summary> public string Key { get; set; } /// <summary> /// The value of the attribute. /// </summary> public DocumentAttributeValue Value { get; set; } } /// <summary> /// Provides text and information about where to highlight the text. /// </summary> public class TextWithHighlights { /// <summary> /// The beginning and end of the text that should be highlighted. /// </summary> public IList<Highlight> Highlights { get; set; } /// <summary> /// The text to display to the user. /// </summary> public string Text { get; set; } } /// <summary> /// Provides information that you can use to highlight a search result so that your users /// can quickly identify terms in the response. /// </summary> public class Highlight { /// <summary> /// The zero-based location in the response string where the highlight starts. /// </summary> public int BeginOffset { get; set; } /// <summary> /// The zero-based location in the response string where the highlight ends. /// </summary> public int EndOffset { get; set; } /// <summary> /// Indicates whether the response is the best response. True if this is the best response; /// otherwise, false. /// </summary> public bool TopAnswer { get; set; } /// <summary> /// The highlight type. /// </summary> public string Type { get; set; } } /// <summary> /// Provides a relative ranking that indicates how confident Amazon Kendra is that the /// response matches the query. /// </summary> public class ScoreAttributes { /// <summary> /// A relative ranking for how well the response matches the query. /// </summary> public string ScoreConfidence { get; set; } } } }
369
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// Contains information about the contexts that a user is using in a session. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_ActiveContext.html /// </summary> [DataContract] public class LexV2ActiveContext { /// <summary> /// A list of contexts active for the request. A context can be activated when a previous intent is fulfilled, or by including the context in the request. /// </summary> [DataMember(Name = "contextAttributes", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("contextAttributes")] public IDictionary<string, string> ContextAttributes { get; set; } /// <summary> /// The name of the context. /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("name")] public string Name { get; set; } /// <summary> /// The number of turns that the context is active. You can specify up to 20 turns. Each request and response from the bot is a turn. /// </summary> [DataMember(Name = "timeToLive", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("timeToLive")] public ActiveContextTimeToLive TimeToLive { get; set; } /// <summary> /// The time that a context is active. You can specify the time to live in seconds or in conversation turns. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_ActiveContextTimeToLive.html /// </summary> [DataContract] public class ActiveContextTimeToLive { /// <summary> /// The number of seconds that the context is active. You can specify between 5 and 86400 seconds (24 hours). /// </summary> [DataMember(Name = "timeToLiveInSeconds", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("timeToLiveInSeconds")] public int TimeToLiveInSeconds { get; set; } /// <summary> /// The number of turns that the context is active. You can specify up to 20 turns. Each request and response from the bot is a turn. /// </summary> [DataMember(Name = "turnsToLive", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("turnsToLive")] public int TurnsToLive { get; set; } } } }
57
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class identifies the Lex V2 bot that is invoking the Lambda function. /// </summary> public class LexV2Bot { /// <summary> /// The unique identifier assigned to the bot. /// </summary> public string Id { get; set; } /// <summary> /// The name of the bot. /// </summary> public string Name { get; set; } /// <summary> /// The unique identifier assigned to the bot alias. /// </summary> public string AliasId { get; set; } /// <summary> /// The language and locale of the bot locale. /// </summary> public string LocaleId { get; set; } /// <summary> /// The numeric version of the bot. /// </summary> public string Version { get; set; } } }
34
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class that represents the next action that Amazon Lex V2 should take. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_DialogAction.html /// </summary> [DataContract] public class LexV2DialogAction { /// <summary> /// Configures the slot to use spell-by-letter or spell-by-word style. When you use a style on a slot, users can spell out their input to make it clear to your bot. /// </summary> [DataMember(Name = "slotElicitationStyle", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("slotElicitationStyle")] public string SlotElicitationStyle { get; set; } /// <summary> /// The name of the slot that should be elicited from the user. /// </summary> [DataMember(Name = "slotToElicit", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("slotToElicit")] public string SlotToElicit { get; set; } /// <summary> /// The next action that the bot should take in its interaction with the user. Could be one of <c>Close</c>, <c>ConfirmIntent</c>, <c>Delegate</c>, <c>ElicitIntent</c> or <c>ElicitSlot</c>. /// </summary> [DataMember(Name = "type", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("type")] public string Type { get; set; } } }
34
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// This class represents the input event from Amazon Lex V2. It used as the input parameter /// for Lambda functions. /// https://docs.aws.amazon.com/lexv2/latest/dg/lambda.html#lambda-input-format /// </summary> public class LexV2Event { /// <summary> /// Message Version /// </summary> public string MessageVersion { get; set; } /// <summary> /// Indicates the action that called the Lambda function. When the source is DialogCodeHook, the Lambda function was called after input from the user. /// When the source is FulfillmentCodeHook the Lambda function was called after all required slots have been filled and the intent is ready for fulfillment. /// </summary> public string InvocationSource { get; set; } /// <summary> /// Input Mode. Could be one of <c>DTMF</c>, <c>Speech</c> or <c>Text</c>. /// </summary> public string InputMode { get; set; } /// <summary> /// Indicates the type of response. Could be one of <c>CustomPayload</c>, <c>ImageResponseCard</c>, <c>PlainText</c> or <c>SSML</c>. /// </summary> public string ResponseContentType { get; set; } /// <summary> /// The identifier of the session in use. /// </summary> public string SessionId { get; set; } /// <summary> /// The text that was used to process the input from the user. /// For text or DTMF input, this is the text that the user typed. /// For speech input, this is the text that was recognized from the speech. /// </summary> public string InputTranscript { get; set; } /// <summary> /// The LexV2 bot invoking the Lambda function. /// </summary> public LexV2Bot Bot { get; set; } /// <summary> /// One or more intents that Amazon Lex V2 considers possible matches to the user's utterance. /// </summary> public IList<LexV2Interpretation> Interpretations { get; set; } /// <summary> /// The next state of the dialog between the user and the bot if the Lambda function doesn't change the flow. /// Only present when the <c>invocationSource</c> field is <c>DialogCodeHook</c> and when the predicted dialog action is <c>ElicitSlot</c>. /// </summary> public LexV2ProposedNextState ProposedNextState { get; set; } /// <summary> /// Request-specific attributes that the client sends in the request. Use request attributes to pass information /// that doesn't need to persist for the entire session. /// </summary> public IDictionary<string, string> RequestAttributes { get; set; } /// <summary> /// The current state of the conversation between the user and your Amazon Lex V2 bot. /// </summary> public LexV2SessionState SessionState { get; set; } /// <summary> /// One or more transcriptions that Amazon Lex V2 considers possible matches to the user's audio utterance. /// </summary> public IList<LexV2Transcription> Transcriptions { get; set; } } }
80
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class that represents the current intent that Amazon Lex V2 is attempting to fulfill. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_Intent.html /// </summary> [DataContract] public class LexV2Intent { /// <summary> /// Contains information about whether fulfillment of the intent has been confirmed. Could be one of <c>Confirmed</c>, <c>Denied</c> or <c>None</c>. /// </summary> [DataMember(Name = "confirmationState", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("confirmationState")] public string ConfirmationState { get; set; } /// <summary> /// The name of the intent. /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("name")] public string Name { get; set; } /// <summary> /// A map of all of the slots for the intent. The name of the slot maps to the value of the slot. If a slot has not been filled, the value is null. /// </summary> [DataMember(Name = "slots", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("slots")] public IDictionary<string, LexV2Slot> Slots { get; set; } /// <summary> /// Contains fulfillment information for the intent. Could be one of <c>Failed</c>, <c>Fulfilled</c>, <c>FulfillmentInProgress</c>, <c>InProgress</c>, <c>ReadyForFulfillment</c> or <c>Waiting</c>. /// </summary> [DataMember(Name = "state", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("state")] public string State { get; set; } /// <summary> /// Only present when intent is KendraSearchIntent. /// </summary> [DataMember(Name = "kendraResponse", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("kendraResponse")] public KendraResponse KendraResponse { get; set; } } }
49
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.LexV2Events { /// <summary> /// An intent that Amazon Lex V2 determined might satisfy the user's utterance. The intents are ordered by the confidence score. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_Interpretation.html /// </summary> public class LexV2Interpretation { /// <summary> /// Intents that might satisfy the user's utterance. /// </summary> public LexV2Intent Intent { get; set; } /// <summary> /// Represents a score that indicates the confidence that Amazon Lex V2 has that an intent is the one that satisfies the user's intent. Determines the threshold /// where Amazon Lex V2 will insert the <c>AMAZON.FallbackIntent</c>, <c>AMAZON.KendraSearchIntent</c>, or both when returning alternative intents in a response. /// <c>AMAZON.FallbackIntent</c> and <c>AMAZON.KendraSearchIntent</c> are only inserted if they are configured for the bot. /// </summary> public double? NluConfidence { get; set; } /// <summary> /// The sentiment expressed in an utterance. /// </summary> /// public LexV2SentimentResponse SentimentResponse { get; set; } } /// <summary> /// Provides information about the sentiment expressed in a user's response in a conversation. Sentiments are determined using Amazon Comprehend. /// Sentiments are only returned if they are enabled for the bot. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_SentimentResponse.html /// </summary> public class LexV2SentimentResponse { /// <summary> /// The overall sentiment expressed in the user's response. This is the sentiment most likely expressed by the user based on the analysis by Amazon Comprehend. /// </summary> public string Sentiment { get; set; } /// <summary> /// The individual sentiment responses for the utterance. /// </summary> public LexV2SentimentScore SentimentScore { get; set; } } /// <summary> /// The class that represents the individual sentiment responses for the utterance. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_SentimentScore.html /// </summary> public class LexV2SentimentScore { /// <summary> /// The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <c>MIXED</c> sentiment. /// </summary> public double? Mixed { get; set; } /// <summary> /// The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <c>NEGATIVE</c> sentiment. /// </summary> public double? Negative { get; set; } /// <summary> /// The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <c>NEUTRAL</c> sentiment. /// </summary> public double? Neutral { get; set; } /// <summary> /// The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <c>POSITIVE</c> sentiment. /// </summary> public double? Positive { get; set; } } }
73
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class that represents the container for text that is returned to the customer. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_Message.html /// </summary> [DataContract] public class LexV2Message { /// <summary> /// The text of the message. /// </summary> [DataMember(Name = "content", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("content")] public string Content { get; set; } /// <summary> /// Indicates the type of response. Could be one of <c>CustomPayload</c>, <c>ImageResponseCard</c>, <c>PlainText</c> or <c>SSML</c>. /// </summary> [DataMember(Name = "contentType", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("contentType")] public string ContentType { get; set; } /// <summary> /// A card that is shown to the user by a messaging platform. You define the contents of the card, the card is displayed by the platform. /// </summary> [DataMember(Name = "imageResponseCard", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("imageResponseCard")] public LexV2ImageResponseCard ImageResponseCard { get; set; } } /// <summary> /// The class that represents a card that is shown to the user by a messaging platform. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_ImageResponseCard.html /// </summary> [DataContract] public class LexV2ImageResponseCard { /// <summary> /// A list of buttons that should be displayed on the response card. The arrangement of the buttons is determined by the platform that displays the button. /// </summary> [DataMember(Name = "buttons", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("buttons")] public IList<LexV2Button> Buttons { get; set; } /// <summary> /// TheThe URL of an image to display on the response card. The image URL must be publicly available so that the platform displaying the response card has access to the image. /// </summary> [DataMember(Name = "imageUrl", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("imageUrl")] public string ImageUrl { get; set; } /// <summary> /// The subtitle to display on the response card. The format of the subtitle is determined by the platform displaying the response card. /// </summary> [DataMember(Name = "subtitle", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("subtitle")] public string Subtitle { get; set; } /// <summary> /// The title to display on the response card. The format of the title is determined by the platform displaying the response card. /// </summary> [DataMember(Name = "title", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("title")] public string Title { get; set; } } /// <summary> /// The class that represents a button that appears on a response card show to the user. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_Button.html /// </summary> [DataContract] public class LexV2Button { /// <summary> /// The text that is displayed on the button. /// </summary> [DataMember(Name = "text", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("text")] public string Text { get; set; } /// <summary> /// The value returned to Amazon Lex V2 when a user chooses the button. /// </summary> [DataMember(Name = "value", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("value")] public string Value { get; set; } } }
93
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.LexV2Events { /// <summary> /// Contains information about the next action that the bot will take if the Lambda function sets the dialogAction to Delegate. /// https://docs.aws.amazon.com/lexv2/latest/dg/lambda.html#request-proposednextstate /// </summary> public class LexV2ProposedNextState { /// <summary> /// Dialog action that Amazon Lex V2 will perform next. /// </summary> public LexV2DialogAction DialogAction { get; set; } /// <summary> /// Intent that the bot has determined that the user is trying to fulfill. /// </summary> public LexV2Intent Intent { get; set; } } }
20
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// This class represents response from the Lambda function. /// https://docs.aws.amazon.com/lexv2/latest/dg/lambda.html#lambda-response-format /// </summary> [DataContract] public class LexV2Response { /// <summary> /// The current state of the conversation with the user. The actual contents of the structure depends on the type of dialog action. /// </summary> [DataMember(Name = "sessionState", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("sessionState")] public LexV2SessionState SessionState { get; set; } /// <summary> /// One or more messages that Amazon Lex V2 shows to the customer to perform the next turn of the conversation. Required if <c>dialogAction.type</c> is <c>ElicitIntent</c>. /// If you don't supply messages, Amazon Lex V2 uses the appropriate message defined when the bot was created. /// </summary> [DataMember(Name = "messages", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("messages")] public IList<LexV2Message> Messages { get; set; } /// <summary> /// Request-specific attributes that the client sends in the request. /// </summary> [DataMember(Name = "requestAttributes", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("requestAttributes")] public IDictionary<string, string> RequestAttributes { get; set; } } }
37
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class that represents the state of the user's session with Amazon Lex V2. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_SessionState.html /// </summary> [DataContract] public class LexV2SessionState { /// <summary> /// One or more contexts that indicate to Amazon Lex V2 the context of a request. When a context is active, Amazon Lex V2 considers /// intents with the matching context as a trigger as the next intent in a session. /// </summary> [DataMember(Name = "activeContexts", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("activeContexts")] public IList<LexV2ActiveContext> ActiveContexts { get; set; } /// <summary> /// The next step that Amazon Lex V2 should take in the conversation with a user. /// </summary> [DataMember(Name = "dialogAction", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("dialogAction")] public LexV2DialogAction DialogAction { get; set; } /// <summary> /// The active intent that Amazon Lex V2 is processing. /// </summary> [DataMember(Name = "intent", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("intent")] public LexV2Intent Intent { get; set; } /// <summary> /// A unique identifier for a specific request. /// </summary> [DataMember(Name = "originatingRequestId", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("originatingRequestId")] public string OriginatingRequestId { get; set; } /// <summary> /// Hints for phrases that a customer is likely to use for a slot. Amazon Lex V2 uses the hints to help determine the correct value of a slot. /// </summary> [DataMember(Name = "runtimeHints", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("runtimeHints")] public LexV2RuntimeHints RuntimeHints { get; set; } /// <summary> /// Map of key/value pairs representing session-specific context information. It contains application information passed between Amazon Lex V2 and a client application. /// </summary> [DataMember(Name = "sessionAttributes", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("sessionAttributes")] public Dictionary<string, string> SessionAttributes { get; set; } } /// <summary> /// The class that represents hints to the phrases which can be provided to Amazon Lex V2 that a customer is likely to use for a slot. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_RuntimeHints.html /// </summary> [DataContract] public class LexV2RuntimeHints { /// <summary> /// A list of the slots in the intent that should have runtime hints added, and the phrases that should be added for each slot. /// </summary> [DataMember(Name = "slotHints", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("slotHints")] public IDictionary<string, Dictionary<string, RuntimeHintDetails>> SlotHints { get; set; } } /// <summary> /// Provides an array of phrases that should be given preference when resolving values for a slot. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_RuntimeHintDetails.html /// </summary> [DataContract] public class RuntimeHintDetails { /// <summary> /// One or more strings that Amazon Lex V2 should look for in the input to the bot. Each phrase is given preference when deciding on slot values. /// </summary> [DataMember(Name = "runtimeHintValues", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("runtimeHintValues")] public IList<RuntimeHintValue> RuntimeHintValues { get; set; } } /// <summary> /// Provides the phrase that Amazon Lex V2 should look for in the user's input to the bot. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_RuntimeHintValue.html /// </summary> [DataContract] public class RuntimeHintValue { /// <summary> /// The phrase that Amazon Lex V2 should look for in the user's input to the bot. /// </summary> [DataMember(Name = "phrase", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("phrase")] public string Phrase { get; set; } } }
102
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class that represents a value that Amazon Lex V2 uses to fulfill an intent. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_Slot.html /// </summary> [DataContract] public class LexV2Slot { /// <summary> /// When the shape value is List, it indicates that the values field contains a list of slot values. /// When the value is Scalar, it indicates that the value field contains a single value. /// </summary> [DataMember(Name = "shape", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("shape")] public string Shape { get; set; } /// <summary> /// The current value of the slot. /// </summary> [DataMember(Name = "value", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("value")] public LexV2SlotValue Value { get; set; } /// <summary> /// The resolutions array contains a list of additional values recognized for the slot. /// </summary> [DataMember(Name = "values", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("values")] public IList<LexV2Slot> Values { get; set; } } /// <summary> /// The class that represents the value of a slot. /// https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_Value.html /// </summary> [DataContract] public class LexV2SlotValue { /// <summary> /// The value that Amazon Lex V2 determines for the slot. The actual value depends on the setting of the value selection strategy for the bot. /// </summary> [DataMember(Name = "interpretedValue", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("interpretedValue")] public string InterpretedValue { get; set; } /// <summary> /// The text of the utterance from the user that was entered for the slot. /// </summary> [DataMember(Name = "originalValue", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("originalValue")] public string OriginalValue { get; set; } /// <summary> /// A list of additional values that have been recognized for the slot. /// </summary> [DataMember(Name = "resolvedValues", EmitDefaultValue = false)] [System.Text.Json.Serialization.JsonPropertyName("resolvedValues")] public IList<string> ResolvedValues { get; set; } } }
65
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.LexV2Events { /// <summary> /// The class that represents the Amazon Lex V2 Transcription that possibly matches to the user's audio utterance. /// https://docs.aws.amazon.com/lexv2/latest/dg/using-transcript-confidence-scores.html /// </summary> public class LexV2Transcription { /// <summary> /// Transcription Name. /// </summary> public string Transcription { get; set; } /// <summary> /// Transcription Confidence score to help determine if the transcription is the correct one. /// Ranges between 0.00 and 1.00. Higher scores indicate higher confidence.. /// </summary> public double? TranscriptionConfidence { get; set; } /// <summary> /// Resolved Context. /// </summary> public LexV2TranscriptionResolvedContext ResolvedContext { get; set; } /// <summary> /// A map of all of the resolved slots for the transcription. /// </summary> public IDictionary<string, LexV2Slot> ResolvedSlots { get; set; } /// <summary> /// The class that represents a Transcription Resolved Intent. /// </summary> public class LexV2TranscriptionResolvedContext { /// <summary> /// The name of the intent. /// </summary> public string Intent { get; set; } } } }
44
aws-lambda-dotnet
aws
C#
using Microsoft.Extensions.Logging; using System; // Same namespace as IConfiguration, to make these extensions appear // without the user needing to including our namespace first. namespace Microsoft.Extensions.Configuration { /// <summary> /// IConfiguration extensions /// </summary> public static class IConfigurationExtensions { /// <summary> /// Creates LambdaLoggerOptions instance from "Lambda.Logging" section of the /// specified configuration. /// </summary> /// <param name="configuration">Configuration to get settings from.</param> /// <returns></returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static LambdaLoggerOptions GetLambdaLoggerOptions(this IConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return new LambdaLoggerOptions(configuration); } /// <summary> /// Creates LambdaLoggerOptions instance from the specified subsection of the /// configuration section. /// </summary> /// <param name="configuration">Configuration to get settings from.</param> /// <param name="loggingSectionName">Name of section from which to get configuration data.</param> /// <returns></returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static LambdaLoggerOptions GetLambdaLoggerOptions(this IConfiguration configuration, string loggingSectionName) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (string.IsNullOrEmpty(loggingSectionName)) { throw new ArgumentNullException(nameof(loggingSectionName)); } return new LambdaLoggerOptions(configuration, loggingSectionName); } } }
53
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.Configuration; // Same namespace as ILoggingBuilder, to make these extensions appear // without the user needing to including our namespace first. namespace Microsoft.Extensions.Logging { /// <summary> /// ILoggingBuilder extensions /// </summary> public static class ILoggerBuilderExtensions { /// <summary> /// Adds a Lambda logger provider with default options. /// </summary> /// <param name="builder">ILoggingBuilder to add Lambda logger to.</param> /// <returns>Updated ILoggingBuilder.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggingBuilder AddLambdaLogger(this ILoggingBuilder builder) { var options = new LambdaLoggerOptions(); return AddLambdaLogger(builder, options); } /// <summary> /// Adds a Lambda logger provider with specified options. /// </summary> /// <param name="builder">ILoggingBuilder to add Lambda logger to.</param> /// <param name="options">Lambda logging options.</param> /// <returns>Updated ILoggingBuilder.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggingBuilder AddLambdaLogger(this ILoggingBuilder builder, LambdaLoggerOptions options) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var provider = new LambdaILoggerProvider(options); builder.AddProvider(provider); return builder; } /// <summary> /// Adds a Lambda logger provider with options loaded from the specified subsection of the /// configuration section. /// </summary> /// <param name="builder">ILoggingBuilder to add Lambda logger to.</param> /// <param name="configuration">IConfiguration to use when construction logging options.</param> /// <param name="loggingSectionName">Name of the logging section with required settings.</param> /// <returns>Updated ILoggingBuilder.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggingBuilder AddLambdaLogger(this ILoggingBuilder builder, IConfiguration configuration, string loggingSectionName) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (string.IsNullOrEmpty(loggingSectionName)) { throw new ArgumentNullException(nameof(loggingSectionName)); } var options = new LambdaLoggerOptions(configuration, loggingSectionName); var provider = new LambdaILoggerProvider(options); builder.AddProvider(provider); return builder; } } }
81
aws-lambda-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using System; // Same namespace as ILoggerFactory, to make these extensions appear // without the user needing to including our namespace first. namespace Microsoft.Extensions.Logging { /// <summary> /// ILoggerFactory extensions /// </summary> public static class ILoggerFactoryExtensions { /// <summary> /// Adds a Lambda logger provider with default options. /// </summary> /// <param name="factory">ILoggerFactory to add Lambda logger to.</param> /// <returns>Updated ILoggerFactory.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggerFactory AddLambdaLogger(this ILoggerFactory factory) { var options = new LambdaLoggerOptions(); return AddLambdaLogger(factory, options); } /// <summary> /// Adds a Lambda logger provider with specified options. /// </summary> /// <param name="factory">ILoggerFactory to add Lambda logger to.</param> /// <param name="options">Lambda logging options.</param> /// <returns>Updated ILoggerFactory.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggerFactory AddLambdaLogger(this ILoggerFactory factory, LambdaLoggerOptions options) { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var provider = new LambdaILoggerProvider(options); factory.AddProvider(provider); return factory; } /// <summary> /// Adds a Lambda logger provider with options loaded from the "Lambda.Logging" subsection /// of the specified configuration. /// </summary> /// <param name="factory">ILoggerFactory to add Lambda logger to.</param> /// <param name="configuration">IConfiguration to use when construction logging options.</param> /// <returns>Updated ILoggerFactory.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggerFactory AddLambdaLogger(this ILoggerFactory factory, IConfiguration configuration) { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } var options = new LambdaLoggerOptions(configuration); var provider = new LambdaILoggerProvider(options); factory.AddProvider(provider); return factory; } /// <summary> /// Adds a Lambda logger provider with options loaded from the specified subsection of the /// configuration section. /// </summary> /// <param name="factory">ILoggerFactory to add Lambda logger to.</param> /// <param name="configuration">IConfiguration to use when construction logging options.</param> /// <param name="loggingSectionName">Name of the logging section with required settings.</param> /// <returns>Updated ILoggerFactory.</returns> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggerFactory AddLambdaLogger(this ILoggerFactory factory, IConfiguration configuration, string loggingSectionName) { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (string.IsNullOrEmpty(loggingSectionName)) { throw new ArgumentNullException(nameof(loggingSectionName)); } var options = new LambdaLoggerOptions(configuration, loggingSectionName); var provider = new LambdaILoggerProvider(options); factory.AddProvider(provider); return factory; } } }
104
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; namespace Microsoft.Extensions.Logging { internal class LambdaILogger : ILogger { // Private fields private readonly string _categoryName; private readonly LambdaLoggerOptions _options; internal IExternalScopeProvider ScopeProvider { get; set; } // Constructor public LambdaILogger(string categoryName, LambdaLoggerOptions options) { _categoryName = categoryName; _options = options; } // ILogger methods public IDisposable BeginScope<TState>(TState state) => ScopeProvider?.Push(state) ?? new NoOpDisposable(); public bool IsEnabled(LogLevel logLevel) { return ( _options.Filter == null || _options.Filter(_categoryName, logLevel)); } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } if (!IsEnabled(logLevel)) { return; } // Format of the logged text, optional components are in {} // {[LogLevel] }{ => Scopes : }{Category: }{EventId: }MessageText {Exception}{\n} var components = new List<string>(4); if (_options.IncludeLogLevel) { components.Add($"[{logLevel}]"); } GetScopeInformation(components); if (_options.IncludeCategory) { components.Add($"{_categoryName}:"); } if (_options.IncludeEventId) { components.Add($"[{eventId}]:"); } var text = formatter.Invoke(state, exception); components.Add(text); if (_options.IncludeException) { components.Add($"{exception}"); } if (_options.IncludeNewline) { components.Add(Environment.NewLine); } var finalText = string.Join(" ", components); Amazon.Lambda.Core.LambdaLogger.Log(finalText); } private void GetScopeInformation(List<string> logMessageComponents) { var scopeProvider = ScopeProvider; if (_options.IncludeScopes && scopeProvider != null) { var initialCount = logMessageComponents.Count; scopeProvider.ForEachScope((scope, list) => { list.Add(scope.ToString()); }, (logMessageComponents)); if (logMessageComponents.Count > initialCount) { logMessageComponents.Add("=>"); } } } // Private classes private class NoOpDisposable : IDisposable { public void Dispose() { } } } }
110
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Logging.AspNetCore; using System; using System.Collections.Concurrent; namespace Microsoft.Extensions.Logging { /// <summary> /// The ILoggerProvider implementation that is added to the ASP.NET Core logging system to create loggers /// that will send the messages to the CloudWatch LogGroup associated with this Lambda function. /// </summary> internal class LambdaILoggerProvider : ILoggerProvider, ISupportExternalScope { // Private fields private readonly LambdaLoggerOptions _options; private IExternalScopeProvider _scopeProvider; private readonly ConcurrentDictionary<string, LambdaILogger> _loggers; // Constants private const string DEFAULT_CATEGORY_NAME = "Default"; /// <summary> /// Creates the provider /// </summary> /// <param name="options"></param> public LambdaILoggerProvider(LambdaLoggerOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } _options = options; _loggers = new ConcurrentDictionary<string, LambdaILogger>(); _scopeProvider = options.IncludeScopes ? new LoggerExternalScopeProvider() : NullExternalScopeProvider.Instance; } /// <summary> /// Creates the logger with the specified category. /// </summary> /// <param name="categoryName"></param> /// <returns></returns> public ILogger CreateLogger(string categoryName) { var name = string.IsNullOrEmpty(categoryName) ? DEFAULT_CATEGORY_NAME : categoryName; return _loggers.GetOrAdd(name, loggerName => new LambdaILogger(name, _options) { ScopeProvider = _scopeProvider }); } /// <inheritdoc /> public void SetScopeProvider(IExternalScopeProvider scopeProvider) { _scopeProvider = scopeProvider; foreach (var logger in _loggers) { logger.Value.ScopeProvider = _scopeProvider; } } /// <summary> /// /// </summary> public void Dispose() { } } }
71
aws-lambda-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Extensions.Logging { /// <summary> /// Options that can be used to configure Lambda logging. /// </summary> public class LambdaLoggerOptions { // Default configuration section. // Customer configuration will be fetched from this section, unless otherwise specified. internal const string DEFAULT_SECTION_NAME = "Lambda.Logging"; private const string INCLUDE_LOG_LEVEL_KEY = "IncludeLogLevel"; private const string INCLUDE_CATEGORY_KEY = "IncludeCategory"; private const string INCLUDE_NEWLINE_KEY = "IncludeNewline"; private const string INCLUDE_EXCEPTION_KEY = "IncludeException"; private const string INCLUDE_EVENT_ID_KEY = "IncludeEventId"; private const string INCLUDE_SCOPES_KEY = "IncludeScopes"; private const string LOG_LEVEL_KEY = "LogLevel"; private const string DEFAULT_CATEGORY = "Default"; /// <summary> /// Flag to indicate if LogLevel should be part of logged message. /// Default is true. /// </summary> public bool IncludeLogLevel { get; set; } /// <summary> /// Flag to indicate if Category should be part of logged message. /// Default is true. /// </summary> public bool IncludeCategory { get; set; } /// <summary> /// Flag to indicate if logged messages should have a newline appended /// to them, if one isn't already there. /// Default is true. /// </summary> public bool IncludeNewline { get; set; } /// <summary> /// Flag to indicate if Exception should be part of logged message. /// Default is false. /// </summary> public bool IncludeException { get; set; } /// <summary> /// Flag to indicate if EventId should be part of logged message. /// Default is false. /// </summary> public bool IncludeEventId { get; set; } /// <summary> /// Gets or sets a value indicating whether scopes should be included in the message. /// Defaults to <c>false</c>. /// </summary> public bool IncludeScopes { get; set; } /// <summary> /// Function used to filter events based on the log level. /// Default value is null and will instruct logger to log everything. /// </summary> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public Func<string, LogLevel, bool> Filter { get; set; } /// <summary> /// Constructs instance of LambdaLoggerOptions with default values. /// </summary> public LambdaLoggerOptions() { IncludeCategory = true; IncludeLogLevel = true; IncludeNewline = true; IncludeException = false; IncludeEventId = false; IncludeScopes = false; Filter = null; } /// <summary> /// Constructs instance of LambdaLoggerOptions with values from "Lambda.Logging" /// subsection of the specified configuration. /// The following configuration keys are supported: /// IncludeLogLevel - boolean flag indicates if LogLevel should be part of logged message. /// IncludeCategory - boolean flag indicates if Category should be part of logged message. /// LogLevels - category-to-LogLevel mapping which indicates minimum LogLevel for a category. /// </summary> /// <param name="configuration"></param> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public LambdaLoggerOptions(IConfiguration configuration) : this(configuration, DEFAULT_SECTION_NAME) { } /// <summary> /// Constructs instance of LambdaLoggerOptions with values from specified /// subsection of the configuration. /// The following configuration keys are supported: /// IncludeLogLevel - boolean flag indicates if LogLevel should be part of logged message. /// IncludeCategory - boolean flag indicates if Category should be part of logged message. /// LogLevels - category-to-LogLevel mapping which indicates minimum LogLevel for a category. /// </summary> /// <param name="configuration"></param> /// <param name="loggingSectionName"></param> [CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public LambdaLoggerOptions(IConfiguration configuration, string loggingSectionName) : this() { // Input validation if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (string.IsNullOrEmpty(loggingSectionName)) { throw new ArgumentNullException(nameof(loggingSectionName)); } var loggerConfiguration = configuration.GetSection(loggingSectionName); if (loggerConfiguration == null) { throw new ArgumentOutOfRangeException(nameof(loggingSectionName), $"Unable to find section '{loggingSectionName}' in current configuration."); } // Parse settings if (TryGetString(loggerConfiguration, INCLUDE_CATEGORY_KEY, out string includeCategoryString)) { IncludeCategory = bool.Parse(includeCategoryString); } if (TryGetString(loggerConfiguration, INCLUDE_LOG_LEVEL_KEY, out string includeLogLevelString)) { IncludeLogLevel = bool.Parse(includeLogLevelString); } if (TryGetString(loggerConfiguration, INCLUDE_EXCEPTION_KEY, out string includeExceptionString)) { IncludeException = bool.Parse(includeExceptionString); } if (TryGetString(loggerConfiguration, INCLUDE_EVENT_ID_KEY, out string includeEventIdString)) { IncludeEventId = bool.Parse(includeEventIdString); } if (TryGetString(loggerConfiguration, INCLUDE_NEWLINE_KEY, out string includeNewlineString)) { IncludeNewline = bool.Parse(includeNewlineString); } if (TryGetSection(loggerConfiguration, LOG_LEVEL_KEY, out IConfiguration logLevelsSection)) { Filter = CreateFilter(logLevelsSection); } if (TryGetString(loggerConfiguration, INCLUDE_SCOPES_KEY, out string includeScopesString)) { IncludeScopes = bool.Parse(includeScopesString); } } // Retrieves configuration value for key, if one exists private static bool TryGetString(IConfiguration configuration, string key, out string value) { value = configuration[key]; return (value != null); } // Retrieves configuration section for key, if one exists private static bool TryGetSection(IConfiguration configuration, string key, out IConfiguration value) { value = configuration.GetSection(key); return (value != null); } // Creates filter for log levels section private static Func<string, LogLevel, bool> CreateFilter(IConfiguration logLevelsSection) { // Empty section means log everything var logLevels = logLevelsSection.GetChildren().ToList(); if (logLevels.Count == 0) { return null; } // Populate mapping of category to LogLevel var logLevelsMapping = new Dictionary<string, LogLevel>(StringComparer.Ordinal); var defaultLogLevel = LogLevel.Information; foreach (var logLevel in logLevels) { var category = logLevel.Key; var minLevelValue = logLevel.Value; LogLevel minLevel; if (!Enum.TryParse(minLevelValue, out minLevel)) { throw new InvalidCastException($"Unable to convert level '{minLevelValue}' for category '{category}' to LogLevel."); } if (category.Contains("*")) { // Only 1 wildcard is supported var wildcardCount = category.Count(x => x == '*'); if (wildcardCount > 1) { throw new ArgumentOutOfRangeException($"Category '{category}' is invalid - only 1 wildcard is supported in a category."); } // Wildcards are only supported at the end of a Category name! var wildcardLocation = category.IndexOf('*'); if (wildcardLocation != category.Length - 1) { throw new ArgumentException($"Category '{category}' is invalid - wilcards are only supported at the end of a category."); } var trimmedCategory = category.TrimEnd('*'); logLevelsMapping[trimmedCategory] = minLevel; } else if (category.Equals(DEFAULT_CATEGORY, StringComparison.OrdinalIgnoreCase)) { defaultLogLevel = minLevel; } else { logLevelsMapping[category] = minLevel; } } // Extract a reverse sorted list of categories. This allows us to quickly search for most specific match to least specific. var orderedCategories = logLevelsMapping.Keys .OrderByDescending(categoryKey => categoryKey) .ToList(); // Filter lambda that examines mapping return (string category, LogLevel logLevel) => { LogLevel minLevel; // Exact match takes priority if (logLevelsMapping.TryGetValue(category, out minLevel)) { return logLevel >= minLevel; } // Find the most specific wildcard or namespace prefix category that matches the logger category var matchedCategory = orderedCategories.FirstOrDefault(category.StartsWith); if (matchedCategory != null) { // If no log filters then default to logging the log message. minLevel = logLevelsMapping[matchedCategory]; return logLevel >= minLevel; } else { // If no log filters then default to logging the log message. return (logLevel >= defaultLogLevel); } }; } } }
262
aws-lambda-dotnet
aws
C#
using Microsoft.Extensions.Logging; using System; namespace Amazon.Lambda.Logging.AspNetCore { /// <summary> /// Scope provider that does nothing. /// </summary> internal class NullExternalScopeProvider : IExternalScopeProvider { private NullExternalScopeProvider() { } /// <summary> /// Returns a cached instance of <see cref="NullExternalScopeProvider"/>. /// </summary> public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider(); /// <inheritdoc /> void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } /// <inheritdoc /> IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } private sealed class NullScope : IDisposable { public static readonly NullScope Instance = new NullScope(); private NullScope() { } public void Dispose() { } } } }
45
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.Logging.AspNetCore")] [assembly: AssemblyDescription("ASP.NET Core logging support for Lambda.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("2.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
13
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.MQEvents { using System; using System.Collections.Generic; /// <summary> /// Apache ActiveMQ event /// https://docs.aws.amazon.com/lambda/latest/dg/with-mq.html /// </summary> public class ActiveMQEvent { /// <summary> /// The source of the event. /// </summary> public string EventSource { get; set; } /// <summary> /// The ARN of the event source. /// </summary> public string EventSourceArn { get; set; } /// <summary> /// List of ActiveMQ messages. /// </summary> public IList<ActiveMQMessage> Messages { get; set; } /// <summary> /// Class that represents an ActiveMQ message. /// </summary> public class ActiveMQMessage { /// <summary> /// Message ID /// </summary> public string MessageId { get; set; } /// <summary> /// Message Type /// </summary> public string MessageType { get; set; } /// <summary> /// Data sent to Active MQ broker encoded in Base 64. /// </summary> public string Data { get; set; } /// <summary> /// Connection ID /// </summary> public string ConnectionId { get; set; } /// <summary> /// Indicates if the message was redelivered. /// </summary> public bool? Redelivered { get; set; } /// <summary> /// Indicates if the message is persistent. /// </summary> public bool? Persistent { get; set; } /// <summary> /// Message Destination /// </summary> public Destination Destination { get; set; } /// <summary> /// Message Timestamp /// </summary> public long? Timestamp { get; set; } /// <summary> /// Broker In Time /// </summary> public long? BrokerInTime { get; set; } /// <summary> /// Broker Out Time /// </summary> public long? BrokerOutTime { get; set; } /// <summary> /// Custom Properties /// </summary> public IDictionary<string, string> Properties { get; set; } } /// <summary> /// Destination queue /// </summary> public class Destination { /// <summary> /// Queue Name /// </summary> public string PhysicalName { get; set; } } } }
100
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.MQEvents { using System; using System.Collections.Generic; /// <summary> /// RabbitMQ event /// https://docs.aws.amazon.com/lambda/latest/dg/with-mq.html /// </summary> public class RabbitMQEvent { /// <summary> /// The source of the event. /// </summary> public string EventSource { get; set; } /// <summary> /// The ARN of the event source. /// </summary> public string EventSourceArn { get; set; } /// <summary> /// List of RabbitMQ messages. /// </summary> public IDictionary<string, List<RabbitMQMessage>> RmqMessagesByQueue { get; set; } /// <summary> /// Class that represents a RabbitMQ message. /// </summary> public class RabbitMQMessage { /// <summary> /// Properties of RabbitMQ message /// </summary> public BasicProperties BasicProperties { get; set; } /// <summary> /// Indicates if the message was redelivered. /// </summary> public bool? Redelivered { get; set; } /// <summary> /// Data sent to Rabbit MQ broker encoded in Base 64. /// </summary> public string Data { get; set; } } /// <summary> /// Class representing RabbitMQ message properties. /// https://rabbitmq.github.io/rabbitmq-dotnet-client/api/RabbitMQ.Client.IBasicProperties.html /// </summary> public class BasicProperties { /// <summary> /// Content Type /// </summary> public string ContentType { get; set; } /// <summary> /// Content Encoding /// </summary> public string ContentEncoding { get; set; } /// <summary> /// Message headers /// </summary> public IDictionary<string, object> Headers { get; set; } /// <summary> /// Delivery Mode /// </summary> public int DeliveryMode { get; set; } /// <summary> /// Priority /// </summary> public int Priority { get; set; } /// <summary> /// Correlation ID /// </summary> public string CorrelationId { get; set; } /// <summary> /// Reply To /// </summary> public string ReplyTo { get; set; } /// <summary> /// Expiration /// </summary> public string Expiration { get; set; } /// <summary> /// Message ID /// </summary> public string MessageId { get; set; } /// <summary> /// Timestamp /// </summary> public string Timestamp { get; set; } /// <summary> /// Message Type /// </summary> public string Type { get; set; } /// <summary> /// User ID /// </summary> public string UserId { get; set; } /// <summary> /// App ID /// </summary> public string AppId { get; set; } /// <summary> /// Cluster ID /// </summary> public string ClusterId { get; set; } /// <summary> /// Message body size /// </summary> public int BodySize { get; set; } } } }
131
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Management.Automation; using System.Globalization; namespace Amazon.Lambda.PowerShellHost { /// <summary> /// Handles converting the errors coming from PowerShell to .NET Exceptions /// </summary> public class ExceptionManager { private const string CUSTOM_EXCEPTION_FIELD = "Exception"; private const string CUSTOM_MESSAGE_FIELD = "Message"; private IDictionary<string, Type> _customExceptions; private Lazy<AssemblyBuilder> _assemblyBuilder; private Lazy<ModuleBuilder> _moduleBuilder; /// <summary> /// Default Constructor /// </summary> public ExceptionManager() { _customExceptions = new Dictionary<string, Type>(); _assemblyBuilder = new Lazy<AssemblyBuilder>( () => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run)); _moduleBuilder = new Lazy<ModuleBuilder>( () => _assemblyBuilder.Value.DefineDynamicModule("CustomExceptions")); } /// <summary> /// Given the exception from the PowerShell host that ran a PowerShell script, this method will determine what type of exception /// should be thrown back to Lambda. This can involve creating a dynamic exception if an exception type string is /// given from PowerShell. /// /// For example if the PS script executes the following command /// /// throw @{'Exception'='AccountNotFound';'Message'='The account was not found'} /// /// Then this method will create a new .NET exception type called AccountNotFound with a message of "The Acount was not found". /// The PS host can then throw this new .NET exception type. If the PowerShell-based Lambda functions is used in AWS StepFunctions /// the state machine can choose to make a choice based on the AccountNotFound error. /// </summary> /// <param name="e"></param> /// <returns></returns> public Exception DetermineExceptionToThrow(Exception e) { var runtimeException = e as RuntimeException; if (runtimeException == null) return e; if(runtimeException.ErrorRecord?.TargetObject != null) { string exceptionTypeName = null; string exceptionMessage = null; if(runtimeException.ErrorRecord.TargetObject is System.Collections.Hashtable fields && fields.ContainsKey(CUSTOM_EXCEPTION_FIELD)) { exceptionTypeName = fields[CUSTOM_EXCEPTION_FIELD] as string; exceptionMessage = fields[CUSTOM_MESSAGE_FIELD] as string ?? exceptionTypeName; } else if (runtimeException.ErrorRecord.TargetObject is string str && IsErrorCode(str)) { exceptionTypeName = str; exceptionMessage = str; } if (!string.IsNullOrEmpty(exceptionTypeName)) { var exceptionType = GetCustomExceptionType(exceptionTypeName); var constructor = exceptionType.GetConstructor(new Type[] { typeof(string) }); var obj = constructor.Invoke(new object[] { exceptionMessage }); var customException = obj as Exception; return customException; } } if(runtimeException.InnerException != null) { return runtimeException.InnerException; } if(runtimeException.ErrorRecord?.Exception != null) { return runtimeException.ErrorRecord.Exception; } return runtimeException; } /// <summary> /// For a given type name dynamically create an exception type using System.Reflection.Emit. The types are /// cached so that if the same type name is request again the type is only created once. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public Type GetCustomExceptionType(string typeName) { // If the typeName has been request in the past return the already generated type. if(_customExceptions.TryGetValue(typeName, out var type)) { return type; } try { var baseExceptionType = typeof(Exception); var baseConstructor = baseExceptionType.GetConstructor(new Type[] { typeof(string) }); var tb = _moduleBuilder.Value.DefineType(typeName, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, baseExceptionType); // Create constructor taking in a string parameter that is then passed to the base constructor var constructor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) }); var ilGenerator = constructor.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); // Adds the "this" argument ilGenerator.Emit(OpCodes.Ldarg_1); // Adds the string argument ilGenerator.Emit(OpCodes.Call, baseConstructor); // Call the base constructor using the "this" instance taking in the string argument. ilGenerator.Emit(OpCodes.Ret); var newExceptionType = tb.CreateType(); // Cache exception type _customExceptions[typeName] = newExceptionType; return newExceptionType; } catch(Exception e) { throw new LambdaPowerShellException($"Error creating customer error type for {typeName}: {e.Message}", e); } } /// <summary> /// Check to see if the string coming from a PS throw statement is an error code. That means the string /// could be used as a class name for an Exception class. /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsErrorCode(string value) { return IsValidTypeNameOrIdentifier(value, true); } // Utility methods taken from CSharpHelpers from the corefx repo // https://github.com/dotnet/corefx/blob/a10890f4ffe0fadf090c922578ba0e606ebdd16c/src/Common/src/System/CSharpHelpers.cs #region Type name validation utilities internal static bool IsValidTypeNameOrIdentifier(string value, bool isTypeName) { bool nextMustBeStartChar = true; if (value.Length == 0) return false; // each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc // for (int i = 0; i < value.Length; i++) { char ch = value[i]; UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(ch); switch (uc) { case UnicodeCategory.UppercaseLetter: // Lu case UnicodeCategory.LowercaseLetter: // Ll case UnicodeCategory.TitlecaseLetter: // Lt case UnicodeCategory.ModifierLetter: // Lm case UnicodeCategory.LetterNumber: // Lm case UnicodeCategory.OtherLetter: // Lo nextMustBeStartChar = false; break; case UnicodeCategory.NonSpacingMark: // Mn case UnicodeCategory.SpacingCombiningMark: // Mc case UnicodeCategory.ConnectorPunctuation: // Pc case UnicodeCategory.DecimalDigitNumber: // Nd // Underscore is a valid starting character, even though it is a ConnectorPunctuation. if (nextMustBeStartChar && ch != '_') return false; nextMustBeStartChar = false; break; default: // We only check the special Type chars for type names. if (isTypeName && IsSpecialTypeChar(ch, ref nextMustBeStartChar)) { break; } return false; } } return true; } // This can be a special character like a separator that shows up in a type name // This is an odd set of characters. Some come from characters that are allowed by C++, like < and >. // Others are characters that are specified in the type and assembly name grammar. internal static bool IsSpecialTypeChar(char ch, ref bool nextMustBeStartChar) { switch (ch) { case ':': case '.': case '$': case '+': case '<': case '>': case '-': case '[': case ']': case ',': case '&': case '*': nextMustBeStartChar = true; return true; case '`': return true; } return false; } #endregion } }
242
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.PowerShellHost { /// <summary> /// Exceptions thrown from errors running the PowerShell script /// </summary> public class LambdaPowerShellException : Exception { /// <summary> /// Exceptions thrown from errors running the PowerShell script /// </summary> /// <param name="message"></param> public LambdaPowerShellException(string message) : base(message) { } /// <summary> /// Exceptions thrown from errors running the PowerShell script /// </summary> /// <param name="wrappedException"></param> public LambdaPowerShellException(Exception wrappedException) : base(wrappedException.Message, wrappedException) { } /// <summary> /// Exceptions thrown from errors running the PowerShell script /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public LambdaPowerShellException(string message, Exception innerException) : base(message, innerException) { } } }
35
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using System; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Amazon.Lambda.PowerShellHost { /// <summary> /// Base class for Lambda functions hosting PowerShell Core runtime /// </summary> public abstract class PowerShellFunctionHost { readonly ExceptionManager _exceptionManager = new ExceptionManager(); /// <summary> /// When using a PowerShell function handler the function is identified in this environment variable. /// </summary> public const string POWERSHELL_FUNCTION_ENV = "AWS_POWERSHELL_FUNCTION_HANDLER"; /// <summary> /// An optional property that identifies the PowerShell function to execute once the script is loaded. /// Otherwise just the script will be executed. /// </summary> public virtual string PowerShellFunctionName {get;set;} // Resource file included with the Lambda package bundle that will be executed. private readonly string _powerShellScriptFileName; private string _powerShellScriptFileContent; // The PowerShell Object for executing PowerShell code private readonly PowerShell _ps; // Holds the PSObject Standard Output from the PowerShell execution private PSDataCollection<PSObject> _output; // Holds the exception captured from the stream capture of the PowerShell execution. This is the exception returned to Lambda // when the script execution stops. private Exception _lastException; private bool _runFirstTimeInitialization = true; // Logging messages that happen during the constructor are saved in a buffer to be written out once we have an instance of // ILambdaLogger. The preference for using ILambdaLogger over Console.WriteLine is so that tools like the console or the VS toolkit // that invoke the functions and request the tail will also get these logging messages. private StringBuilder _constructorLoggingBuffer = new StringBuilder(); private ILambdaLogger _logger; /// <summary> /// Creates an instances of the class. As part of creation it will initiate the PowerShell Core runtime and load any required PowerShell modules. /// </summary> protected PowerShellFunctionHost() { // This will only be true for local testing. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var state = InitialSessionState.CreateDefault(); state.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted; this._ps = PowerShell.Create(state); } else { this._ps = PowerShell.Create(); } this.SetupStreamHandlers(); this.LoadModules(); // Can be true if there was an exception importing modules packaged with the function. if(this._lastException != null) { Console.WriteLine(this._constructorLoggingBuffer.ToString()); throw this._lastException; } this.PowerShellFunctionName = Environment.GetEnvironmentVariable(POWERSHELL_FUNCTION_ENV); if(!string.IsNullOrEmpty(this.PowerShellFunctionName)) { this._constructorLoggingBuffer.AppendLine($"Configured to call function {this.PowerShellFunctionName} from the PowerShell script."); } } /// <inheritdoc /> /// <summary> /// Creates an instances of the class. As part of creation it will initiated the PowerShell Core runtime and load any required PowerShell modules. /// </summary> /// <param name="powerShellScriptFileName">The PowerShell script that will run as part of every Lambda invocation</param> protected PowerShellFunctionHost(string powerShellScriptFileName) : this() { this._powerShellScriptFileName = powerShellScriptFileName; } /// <summary> /// AWS Lambda function handler that will execute the PowerShell script with the PowerShell Core runtime initiated during the construction of the class. /// </summary> /// <param name="inputStream"></param> /// <param name="context"></param> /// <returns></returns> public Stream ExecuteFunction(Stream inputStream, ILambdaContext context) { this._lastException = null; if (this._runFirstTimeInitialization) { this._logger = context.Logger; if (this._constructorLoggingBuffer?.Length > 0) { context.Logger.Log(this._constructorLoggingBuffer.ToString()); this._constructorLoggingBuffer = null; } this._runFirstTimeInitialization = false; } string inputString; using (var reader = new StreamReader(inputStream)) { inputString = reader.ReadToEnd(); } var result = this.BeginInvoke(inputString, context); this.WaitPowerShellExecution(result); if (this._lastException != null || this._ps.InvocationStateInfo.State == PSInvocationState.Failed) { var exception = this._exceptionManager.DetermineExceptionToThrow(this._lastException ?? this._ps.InvocationStateInfo.Reason); throw exception; } return new MemoryStream(Encoding.UTF8.GetBytes(this.GetExecutionOutput())); } /// <summary> /// Begin the async PowerShell execution /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> private IAsyncResult BeginInvoke(string input, ILambdaContext context) { // Clear all previous PowerShell executions, variables and outputs this._ps.Commands?.Clear(); this._ps.Streams.Verbose?.Clear(); this._ps.Streams.Error?.Clear(); this._ps.Runspace?.ResetRunspaceState(); this._output.Clear(); var providedScript = LoadScript(input, context); string executingScript = @" Param( [string]$LambdaInputString, [Amazon.Lambda.Core.ILambdaContext]$LambdaContext ) $LambdaInput = ConvertFrom-Json -InputObject $LambdaInputString "; var isLambda = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TASK_ROOT")); var tempFolder = isLambda ? "/tmp" : Path.GetTempPath(); executingScript += $"{Environment.NewLine}$env:TEMP=\"{tempFolder}\""; executingScript += $"{Environment.NewLine}$env:TMP=\"{tempFolder}\""; executingScript += $"{Environment.NewLine}$env:TMPDIR=\"{tempFolder}\"{Environment.NewLine}"; if(isLambda && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HOME"))) { // Make sure to set HOME directory to avoid issue with using the -Parallel PowerShell feature. This works around // a reported issue to the PowerShell team. // https://github.com/PowerShell/PowerShell/issues/13189 Environment.SetEnvironmentVariable("HOME", $"{tempFolder}/home"); } executingScript += providedScript; if (!string.IsNullOrEmpty(this.PowerShellFunctionName)) { executingScript += $"{Environment.NewLine}{this.PowerShellFunctionName} $LambdaInput $LambdaContext{Environment.NewLine}"; } this._ps.AddScript(executingScript); this._ps.AddParameter("LambdaInputString", input); this._ps.AddParameter("LambdaContext", context); return this._ps.BeginInvoke<PSObject, PSObject>(null, this._output); } /// <summary> /// Reads the script from disk /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> protected virtual string LoadScript(string input, ILambdaContext context) { // Check to see if the file contents have already been read. if(this._powerShellScriptFileContent != null) { return this._powerShellScriptFileContent; } if(string.IsNullOrEmpty(this._powerShellScriptFileName)) { throw new LambdaPowerShellException("No PowerShell script specified to be executed. Either specify a script in the constructor or override the LoadScript method."); } if(!File.Exists(this._powerShellScriptFileName)) { throw new LambdaPowerShellException($"Failed to find PowerShell script {this._powerShellScriptFileName}. Make sure the script is included with the package bundle."); } this._powerShellScriptFileContent = File.ReadAllText(this._powerShellScriptFileName); return this._powerShellScriptFileContent; } /// <summary> /// Waits for the PowerShell execution to be completed /// </summary> private void WaitPowerShellExecution(IAsyncResult result) { while (!result.IsCompleted) { result.AsyncWaitHandle.WaitOne(500); } } /// <summary> /// Returns the string output from the PowerShell execution, or an empty string /// </summary> private string GetExecutionOutput() { var responseObject = this._output?.LastOrDefault(); if (responseObject == null) { return string.Empty; } else if(responseObject.BaseObject is string baseObj) { return baseObj; } this._ps.Commands?.Clear(); this._ps.Runspace?.ResetRunspaceState(); string executingScript = @" Param( [PSObject]$Response ) ConvertTo-Json $Response "; this._ps.AddScript(executingScript); this._ps.AddParameter("Response", responseObject); var marshalled = this._ps.Invoke(); return marshalled.FirstOrDefault()?.BaseObject as string; } private void SetupStreamHandlers() { this._output = new PSDataCollection<PSObject>(); Func<string, EventHandler<DataAddingEventArgs>> _loggerFactory = (prefix) => { EventHandler <DataAddingEventArgs> handler = (sender, e) => { var message = e?.ItemAdded?.ToString(); LogMessage(prefix, message); var errorRecord = e?.ItemAdded as ErrorRecord; if (errorRecord?.Exception != null) { this._lastException = errorRecord.Exception; } }; return handler; }; this._ps.Streams.Verbose.DataAdding += _loggerFactory("Verbose"); this._ps.Streams.Information.DataAdding += _loggerFactory("Information"); this._ps.Streams.Warning.DataAdding += _loggerFactory("Warning"); this._ps.Streams.Error.DataAdding += _loggerFactory("Error"); } private void LogMessage(string prefix, string message) { if (string.IsNullOrEmpty(message)) { return; } if(!string.IsNullOrEmpty(prefix)) { message = $"[{prefix}] - {message}"; } if (this._logger != null) { this._logger.LogLine(message); } else { this._constructorLoggingBuffer.AppendLine(message); } } /// <summary> /// Import all the bundled PowerShell modules. Bundle modules are stored under the Modules folder with the structure Module-Name/Version-Number/Module-Name.psd1. /// It is possible that developer accidently includes multiple versions of the same module. If so we default to loading the latest version. /// </summary> private void LoadModules() { if (!Directory.Exists("./Modules")) return; foreach (var moduleDir in Directory.GetDirectories("./Modules")) { var versionDir = Directory.GetDirectories(moduleDir).OrderByDescending(x => Version.TryParse(new DirectoryInfo(x).Name, out var version) ? version : new Version("0.0.0")).FirstOrDefault(); if (string.IsNullOrEmpty(versionDir)) continue; var module = new DirectoryInfo(moduleDir).Name; var psd1Path = Path.Combine(versionDir, $"{module}.psd1"); if (!File.Exists(psd1Path)) { var files = Directory.GetFiles(versionDir, "*.psd1", SearchOption.TopDirectoryOnly); if (files.Length == 1) { psd1Path = files[0]; } } if (!File.Exists(psd1Path)) { _constructorLoggingBuffer.AppendLine($"Unable to determine psd1 file for {module} ({new DirectoryInfo(versionDir).Name})"); continue; } _constructorLoggingBuffer.AppendLine($"Importing module {psd1Path}"); var result = this._ps.AddScript($"Import-Module \"{psd1Path}\"").BeginInvoke(); WaitPowerShellExecution(result); } } static PowerShellFunctionHost() { const string envName = "AWS_EXECUTION_ENV"; const string powershellEnv = "powershell"; var envValue = Environment.GetEnvironmentVariable(envName); if(!string.IsNullOrEmpty(envValue) && !envValue.Contains(powershellEnv)) { var assemblyVersion = typeof(PowerShellFunctionHost).Assembly .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) .FirstOrDefault() as AssemblyInformationalVersionAttribute; Environment.SetEnvironmentVariable(envName, $"{envValue}_{powershellEnv}_{assemblyVersion?.InformationalVersion}"); } } } }
379
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Threading.Tasks; namespace Amazon.Lambda.RuntimeSupport { class Program { private static async Task Main(string[] args) { if (args.Length == 0) { throw new ArgumentException("The function handler was not provided via command line arguments.", nameof(args)); } var handler = args[0]; RuntimeSupportInitializer runtimeSupportInitializer = new RuntimeSupportInitializer(handler); await runtimeSupportInitializer.RunLambdaBootstrap(); } } }
37
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Lambda.RuntimeSupport.Bootstrap; using Amazon.Lambda.RuntimeSupport.Helpers; using System; using System.Threading.Tasks; namespace Amazon.Lambda.RuntimeSupport { /// <summary> /// RuntimeSupportInitializer class responsible for initializing the UserCodeLoader and LambdaBootstrap given a function handler. /// </summary> public class RuntimeSupportInitializer { private readonly string _handler; private readonly InternalLogger _logger; private readonly RuntimeSupportDebugAttacher _debugAttacher; /// <summary> /// Class constructor that takes a Function Handler and initializes the class. /// </summary> public RuntimeSupportInitializer(string handler) { if (string.IsNullOrWhiteSpace(handler)) { throw new ArgumentException("Cannot initialize RuntimeSupportInitializer with a null of empty Function Handler", nameof(handler)); } _logger = InternalLogger.GetDefaultLogger(); _handler = handler; _debugAttacher = new RuntimeSupportDebugAttacher(); } /// <summary> /// Initializes the UserCodeLoader using the Function Handler and runs LambdaBootstrap asynchronously. /// </summary> public async Task RunLambdaBootstrap() { await _debugAttacher.TryAttachDebugger(); var userCodeLoader = new UserCodeLoader(_handler, _logger); var initializer = new UserCodeInitializer(userCodeLoader, _logger); using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(userCodeLoader.Invoke)) using (var bootstrap = new LambdaBootstrap(handlerWrapper, initializer.InitializeAsync)) { await bootstrap.RunAsync(); } } } }
65
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.Reflection; namespace Amazon.Lambda.RuntimeSupport.Bootstrap { internal class Constants { // For local debugging purposes this environment variable can be set to run a Lambda executable assembly and process one event // and then shut down cleanly. Useful for profiling or running local tests with the .NET Lambda Test Tool. This environment // variable should never be set when function is deployed to Lambda. internal const string ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_DEBUG_RUN_ONCE = "AWS_LAMBDA_DOTNET_DEBUG_RUN_ONCE"; internal const string ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT = "AWS_LAMBDA_DOTNET_PREJIT"; internal const string ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE = "AWS_LAMBDA_INITIALIZATION_TYPE"; internal const string ENVIRONMENT_VARIABLE_LANG = "LANG"; internal const string ENVIRONMENT_VARIABLE_TELEMETRY_LOG_FD = "_LAMBDA_TELEMETRY_LOG_FD"; internal const string AWS_LAMBDA_INITIALIZATION_TYPE_PC = "provisioned-concurrency"; internal const string AWS_LAMBDA_INITIALIZATION_TYPE_ON_DEMAND = "on-demand"; internal enum AwsLambdaDotNetPreJit { Never, Always, ProvisionedConcurrency } internal const BindingFlags DefaultFlags = BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; } }
44
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Lambda.Core; using System; using System.IO; using System.Threading.Tasks; namespace Amazon.Lambda.RuntimeSupport { /// <summary> /// This class provides methods that help you wrap existing C# Lambda implementations with LambdaBootstrapHandler delegates. /// This makes serialization and deserialization simpler and allows you to use existing functions them with an instance of LambdaBootstrap. /// </summary> public class HandlerWrapper : IDisposable { private static readonly InvocationResponse EmptyInvocationResponse = new InvocationResponse(new MemoryStream(0), false); private MemoryStream OutputStream = new MemoryStream(); public LambdaBootstrapHandler Handler { get; private set; } private HandlerWrapper(LambdaBootstrapHandler handler) { Handler = handler; } private HandlerWrapper() { } /// <summary> /// Get a HandlerWrapper that will call the given delegate on function invocation. /// </summary> /// <param name="invokeDelegate">Action called for each invocation of the Lambda function</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Action<Stream, ILambdaContext, MemoryStream> invokeDelegate) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = invocation => { handlerWrapper.OutputStream.SetLength(0); invokeDelegate(invocation.InputStream, invocation.LambdaContext, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; var response = new InvocationResponse(handlerWrapper.OutputStream, false); return Task.FromResult(response); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task Handler(); /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Task> handler) { return new HandlerWrapper(async (invocation) => { await handler(); return EmptyInvocationResponse; }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task Handler(Stream) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream, Task> handler) { return new HandlerWrapper(async (invocation) => { await handler(invocation.InputStream); return EmptyInvocationResponse; }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task Handler(PocoIn) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Func<TInput, Task> handler, ILambdaSerializer serializer) { return new HandlerWrapper(async (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); await handler(input); return EmptyInvocationResponse; }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task Handler(ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<ILambdaContext, Task> handler) { return new HandlerWrapper(async (invocation) => { await handler(invocation.LambdaContext); return EmptyInvocationResponse; }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task Handler(Stream, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream, ILambdaContext, Task> handler) { return new HandlerWrapper(async (invocation) => { await handler(invocation.InputStream, invocation.LambdaContext); return EmptyInvocationResponse; }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Func<TInput, ILambdaContext, Task> handler, ILambdaSerializer serializer) { return new HandlerWrapper(async (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); await handler(input, invocation.LambdaContext); return EmptyInvocationResponse; }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltStream&gt Handler() /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Task<Stream>> handler) { return new HandlerWrapper(async (invocation) => { return new InvocationResponse(await handler()); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltStream&gt Handler(Stream) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream, Task<Stream>> handler) { return new HandlerWrapper(async (invocation) => { return new InvocationResponse(await handler(invocation.InputStream)); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltStream&gt Handler(PocoIn) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Func<TInput, Task<Stream>> handler, ILambdaSerializer serializer) { return new HandlerWrapper(async (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); return new InvocationResponse(await handler(input)); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltStream&gt Handler(ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<ILambdaContext, Task<Stream>> handler) { return new HandlerWrapper(async (invocation) => { return new InvocationResponse(await handler(invocation.LambdaContext)); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltStream&gt Handler(Stream, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream, ILambdaContext, Task<Stream>> handler) { return new HandlerWrapper(async (invocation) => { return new InvocationResponse(await handler(invocation.InputStream, invocation.LambdaContext)); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltStream&gt Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Func<TInput, ILambdaContext, Task<Stream>> handler, ILambdaSerializer serializer) { return new HandlerWrapper(async (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); return new InvocationResponse(await handler(input, invocation.LambdaContext)); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltPocoOut&gt Handler() /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<Task<TOutput>> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = async (invocation) => { TOutput output = await handler(); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return new InvocationResponse(handlerWrapper.OutputStream, false); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltPocoOut&gt Handler(Stream) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<Stream, Task<TOutput>> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = async (invocation) => { TOutput output = await handler(invocation.InputStream); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return new InvocationResponse(handlerWrapper.OutputStream, false); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltPocoOut&gt Handler(PocoIn) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput, TOutput>(Func<TInput, Task<TOutput>> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = async (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); TOutput output = await handler(input); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return new InvocationResponse(handlerWrapper.OutputStream, false); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltPocoOut&gt Handler(ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<ILambdaContext, Task<TOutput>> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = async (invocation) => { TOutput output = await handler(invocation.LambdaContext); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; ; return new InvocationResponse(handlerWrapper.OutputStream, false); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltPocoOut&gt Handler(Stream, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<Stream, ILambdaContext, Task<TOutput>> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = async (invocation) => { TOutput output = await handler(invocation.InputStream, invocation.LambdaContext); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return new InvocationResponse(handlerWrapper.OutputStream, false); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Task&ltPocoOut&gt Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput, TOutput>(Func<TInput, ILambdaContext, Task<TOutput>> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = async (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); TOutput output = await handler(input, invocation.LambdaContext); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return new InvocationResponse(handlerWrapper.OutputStream, false); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: void Handler() /// </summary> /// <param name="handler">Action called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Action handler) { return new HandlerWrapper((invocation) => { handler(); return Task.FromResult(EmptyInvocationResponse); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: void Handler(Stream) /// </summary> /// <param name="handler">Action called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Action<Stream> handler) { return new HandlerWrapper((invocation) => { handler(invocation.InputStream); return Task.FromResult(EmptyInvocationResponse); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: void Handler(PocoIn) /// </summary> /// <param name="handler">Action called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Action<TInput> handler, ILambdaSerializer serializer) { return new HandlerWrapper((invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); handler(input); return Task.FromResult(EmptyInvocationResponse); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: void Handler(ILambdaContext) /// </summary> /// <param name="handler">Action called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Action<ILambdaContext> handler) { return new HandlerWrapper((invocation) => { handler(invocation.LambdaContext); return Task.FromResult(EmptyInvocationResponse); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: void Handler(Stream, ILambdaContext) /// </summary> /// <param name="handler">Action called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Action<Stream, ILambdaContext> handler) { return new HandlerWrapper((invocation) => { handler(invocation.InputStream, invocation.LambdaContext); return Task.FromResult(EmptyInvocationResponse); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: void Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Action called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Action<TInput, ILambdaContext> handler, ILambdaSerializer serializer) { return new HandlerWrapper((invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); handler(input, invocation.LambdaContext); return Task.FromResult(EmptyInvocationResponse); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Stream Handler() /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream> handler) { return new HandlerWrapper((invocation) => { return Task.FromResult(new InvocationResponse(handler())); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Stream Handler(Stream) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream, Stream> handler) { return new HandlerWrapper((invocation) => { return Task.FromResult(new InvocationResponse(handler(invocation.InputStream))); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Stream Handler(PocoIn) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Func<TInput, Stream> handler, ILambdaSerializer serializer) { return new HandlerWrapper((invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); return Task.FromResult(new InvocationResponse(handler(input))); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Stream Handler(ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<ILambdaContext, Stream> handler) { return new HandlerWrapper((invocation) => { return Task.FromResult(new InvocationResponse(handler(invocation.LambdaContext))); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Stream Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper(Func<Stream, ILambdaContext, Stream> handler) { return new HandlerWrapper((invocation) => { return Task.FromResult(new InvocationResponse(handler(invocation.InputStream, invocation.LambdaContext))); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: Stream Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput>(Func<TInput, ILambdaContext, Stream> handler, ILambdaSerializer serializer) { return new HandlerWrapper((invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); return Task.FromResult(new InvocationResponse(handler(input, invocation.LambdaContext))); }); } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: PocoOut Handler() /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<TOutput> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = (invocation) => { TOutput output = handler(); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: PocoOut Handler(Stream) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<Stream, TOutput> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = (invocation) => { TOutput output = handler(invocation.InputStream); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: PocoOut Handler(PocoIn) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput, TOutput>(Func<TInput, TOutput> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); TOutput output = handler(input); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: PocoOut Handler(ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<ILambdaContext, TOutput> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = (invocation) => { TOutput output = handler(invocation.LambdaContext); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; ; return Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: PocoOut Handler(Stream, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TOutput>(Func<Stream, ILambdaContext, TOutput> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = (invocation) => { TOutput output = handler(invocation.InputStream, invocation.LambdaContext); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)); }; return handlerWrapper; } /// <summary> /// Get a HandlerWrapper that will call the given method on function invocation. /// Note that you may have to cast your handler to its specific type to help the compiler. /// Example handler signature: PocoOut Handler(PocoIn, ILambdaContext) /// </summary> /// <param name="handler">Func called for each invocation of the Lambda function.</param> /// <param name="serializer">ILambdaSerializer to use when calling the handler</param> /// <returns>A HandlerWrapper</returns> public static HandlerWrapper GetHandlerWrapper<TInput, TOutput>(Func<TInput, ILambdaContext, TOutput> handler, ILambdaSerializer serializer) { var handlerWrapper = new HandlerWrapper(); handlerWrapper.Handler = (invocation) => { TInput input = serializer.Deserialize<TInput>(invocation.InputStream); TOutput output = handler(input, invocation.LambdaContext); handlerWrapper.OutputStream.SetLength(0); serializer.Serialize(output, handlerWrapper.OutputStream); handlerWrapper.OutputStream.Position = 0; return Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)); }; return handlerWrapper; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { OutputStream.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } #endregion } }
742
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport.ExceptionHandling; using Amazon.Lambda.RuntimeSupport.Helpers; using Amazon.Lambda.RuntimeSupport.Serializers; namespace Amazon.Lambda.RuntimeSupport.Bootstrap { /// <summary> /// Builds user delegate from the handler information. /// </summary> internal class InvokeDelegateBuilder { private readonly InternalLogger _logger; private readonly HandlerInfo _handler; private readonly MethodInfo _customerMethodInfo; private Type CustomerOutputType { get; set; } public InvokeDelegateBuilder(InternalLogger logger, HandlerInfo handler, MethodInfo customerMethodInfo) { _logger = logger; _handler = handler; _customerMethodInfo = customerMethodInfo; } /// <summary> /// Constructs the invoke delegate using Expressions /// /// Serialize & Deserialize calls are only made when a serializer is provided. /// Context is only passed when customer method has context parameter. /// Lambda return type can be void. /// /// (inStream, context, outStream) => /// { /// var input = serializer.Deserialize(inStream); /// var output = handler(input, context); /// return serializer.Serialize(output); /// } /// /// </summary> /// <param name="customerObject">Wrapped customer object.</param> /// <param name="customerSerializerInstance">Instance of lambda input & output serializer.</param> /// <returns>Action delegate pointing to customer's handler.</returns> public Action<Stream, ILambdaContext, Stream> ConstructInvokeDelegate(object customerObject, object customerSerializerInstance, bool isPreJit) { var inStreamParameter = Expression.Parameter(Types.StreamType, "inStream"); var outStreamParameter = Expression.Parameter(Types.StreamType, "outStream"); var contextParameter = Expression.Parameter(typeof(ILambdaContext), "context"); _logger.LogDebug($"UCL : Constructing input expression"); var inputExpression = BuildInputExpressionOrNull(customerSerializerInstance, inStreamParameter, out var iLambdaContextType); if (isPreJit) { _logger.LogInformation("PreJit: inputExpression"); UserCodeInit.InitDeserializationAssembly(inputExpression, inStreamParameter); } _logger.LogDebug($"UCL : Constructing context expression"); var contextExpression = BuildContextExpressionOrNull(iLambdaContextType, contextParameter); _logger.LogDebug($"UCL : Constructing handler expression"); var handlerExpression = CreateHandlerCallExpression(customerObject, inputExpression, contextExpression); _logger.LogDebug($"UCL : Constructing output expression"); var outputExpression = CreateOutputExpression(customerSerializerInstance, outStreamParameter, handlerExpression); if (isPreJit) { _logger.LogInformation("PreJit: outputExpression"); UserCodeInit.InitSerializationAssembly(outputExpression, outStreamParameter, CustomerOutputType); } _logger.LogDebug($"UCL : Constructing final expression"); var finalExpression = Expression.Lambda<Action<Stream, ILambdaContext, Stream>>(outputExpression, inStreamParameter, contextParameter, outStreamParameter); #if DEBUG var finalExpressionDebugView = typeof(Expression) .GetTypeInfo() .GetProperty("DebugView", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(finalExpression); _logger.LogDebug($"UCL : Constructed final expression:\n'{finalExpressionDebugView}'"); #endif _logger.LogDebug($"UCL : Compiling final expression"); return finalExpression.Compile(); } /// <summary> /// Creates an expression to convert incoming Stream to the customer method inputs. /// If customer method takes no inputs or only takes ILambdaContext, return null. /// </summary> /// <param name="customerSerializerInstance">Instance of lambda input & output serializer.</param> /// <param name="inStreamParameter">Input stream parameter.</param> /// <param name="iLambdaContextType">Type of context passed for the invocation.</param> /// <returns>Expression that deserializes incoming stream to the customer method inputs or null if customer method takes no input.</returns> /// <exception cref="LambdaValidationException">Thrown when customer method inputs don't meet lambda requirements.</exception> private Expression BuildInputExpressionOrNull(object customerSerializerInstance, Expression inStreamParameter, out Type iLambdaContextType) { Type inputType = null; iLambdaContextType = null; // get input types var inputTypes = _customerMethodInfo.GetParameters().Select(pi => pi.ParameterType).ToArray(); // check if there are too many parameters if (inputTypes.Length > 2) { throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.MethodTooManyParams, _customerMethodInfo.Name, _handler.TypeName); } // if two parameters, check that the second input is ILambdaContext if (inputTypes.Length == 2) { if (!Types.IsILambdaContext(inputTypes[1])) { throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.MethodSecondParamNotContext, _customerMethodInfo.Name, _handler.TypeName, Types.ILambdaContextTypeName); } iLambdaContextType = inputTypes[1]; inputType = inputTypes[0]; } // if one input, check if input is ILambdaContext else if (inputTypes.Length == 1) { if (Types.IsILambdaContext(inputTypes[0])) { iLambdaContextType = inputTypes[0]; } else { inputType = inputTypes[0]; } } if (inputType != null) { // deserializer.Deserialize(inStream) return CreateDeserializeExpression(customerSerializerInstance, inputType, inStreamParameter); } if (iLambdaContextType != null) { _logger.LogDebug($"UCL : Validating iLambdaContextType"); UserCodeValidator.ValidateILambdaContextType(iLambdaContextType); } return null; } /// <summary> /// Generates an expression if iLambdaContextType is not null, or returns null /// </summary> /// <param name="iLambdaContextType">Type of context passed for the invocation.</param> /// <param name="contextParameter">Expression that defines context parameter.</param> /// <returns>Expression that defines context parameter if iLambdaContextType is not null, or returns null</returns> private static Expression BuildContextExpressionOrNull(Type iLambdaContextType, Expression contextParameter) { // If the Lambda function does not have a context parameter, don't build // an expression to construct it. return iLambdaContextType == null ? null : contextParameter; } /// <summary> /// Creates expression to invoke the customer method. /// If input or context expressions are not null, those expressions are /// passed into the method. /// </summary> /// <param name="customerObject">Wrapped customer object.</param> /// <param name="inputExpression">Input expression that defines customer input.</param> /// <param name="contextExpression">Context expression that defines context passed for the invocation.</param> /// <returns>Expression that unwraps customer object.</returns> private Expression CreateHandlerCallExpression(object customerObject, Expression inputExpression, Expression contextExpression) { Expression customerObjectConstant = null; if (customerObject != null) { // code: [customerObject] customerObjectConstant = Expression.Constant(customerObject); } var inputs = new List<Expression>(); if (inputExpression != null) { inputs.Add(inputExpression); } if (contextExpression != null) { inputs.Add(contextExpression); } // [customerObject].handler([input|context|input, context]) Expression handlerCallExpression = Expression.Call(customerObjectConstant, _customerMethodInfo, inputs); var outputType = _customerMethodInfo.ReturnType; var taskTType = GetTaskTSubclassOrNull(outputType); var outputIsTaskT = taskTType != null; var outputIsTask = Types.TaskType.GetTypeInfo().IsAssignableFrom(outputType); if (outputIsTaskT) { // code: (Task<T>)[customerObject].handler(...) var handlerConvert = Expression.Convert(handlerCallExpression, taskTType); // code: [customerObject].handler(...).GetAwaiter().GetResult() handlerCallExpression = Expression.Call(Expression.Call(handlerConvert, taskTType.GetMethod("GetAwaiter"), null), "GetResult", null); } else if (outputIsTask) { // code: (Task)([customerObject].handler(...)) var handlerConvert = Expression.Convert(handlerCallExpression, Types.TaskType); // code: [customerObject].handler(...).GetAwaiter().GetResult() handlerCallExpression = Expression.Call(Expression.Call(handlerConvert, Types.TaskType.GetMethod("GetAwaiter"), null), "GetResult", null); } return handlerCallExpression; } /// <summary> /// Creates the final expression. If there is no output data, the final expression /// is just the handler call expression. Otherwise, the final expression is the /// serialization expression operating on the handler call expression. /// </summary> /// <param name="customerSerializerInstance">Instance of lambda input & output serializer.</param> /// <param name="outStreamParameter">Expression that defines customer output.</param> /// <param name="handlerCallExpression">Expression that defines customer handler call.</param> /// <returns>Expression that serializes customer method output to outgoing stream.</returns> private Expression CreateOutputExpression(object customerSerializerInstance, Expression outStreamParameter, Expression handlerCallExpression) { var outputType = _customerMethodInfo.ReturnType; var taskTType = GetTaskTSubclassOrNull(outputType); var isTaskT = taskTType != null; var isTask = Types.TaskType.GetTypeInfo().IsAssignableFrom(outputType); var isVoid = outputType == Types.VoidType; var hasData = (!isVoid && !isTask) || isTaskT; if (hasData) { if (isTaskT) { outputType = taskTType.GenericTypeArguments[0]; } // serializer.Serialize(outputData, outStream) return CreateSerializeExpression(customerSerializerInstance, outputType, handlerCallExpression, outStreamParameter); } CustomerOutputType = outputType; return handlerCallExpression; } /// <summary> /// Retrieves the Task&lt;T&gt; type that the given type subclasses, /// or null if the type does not subclass Task&lt;T&gt; /// </summary> /// <param name="type"></param> /// <returns></returns> private static Type GetTaskTSubclassOrNull(Type type) { if (type == null) return null; if (type.IsConstructedGenericType) { var genericDefinition = type.GetGenericTypeDefinition(); if (genericDefinition == Types.TaskTType) return type; } var baseType = type.GetTypeInfo().BaseType; return GetTaskTSubclassOrNull(baseType); } /// <summary> /// Generates an expression to serialize customer method result into the output stream /// </summary> /// <param name="customerSerializerInstance">Instance of lambda input & output serializer.</param> /// <param name="dataType">Customer input type.</param> /// <param name="customerObject">Expression that define customer object.</param> /// <param name="outStreamParameter">Expression that defines customer output.</param> /// <returns>Expression that serializes returned object to output stream.</returns> /// <exception cref="LambdaValidationException">Thrown when customer input is serializable & serializer instance is null.</exception> private Expression CreateSerializeExpression(object customerSerializerInstance, Type dataType, Expression customerObject, Expression outStreamParameter) { // generic types, null for String and Stream converters Type[] genericTypes = null; var converter = customerSerializerInstance; Type iLambdaSerializerType = null; // subclasses of Stream are allowed as customer method output if (Types.StreamType.GetTypeInfo().IsAssignableFrom(dataType)) { converter = StreamSerializer.Instance; } else { if (customerSerializerInstance == null) { throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.SerializeMissingAttribute, _handler.AssemblyName, _handler.MethodName, dataType.FullName, typeof(LambdaSerializerAttribute).FullName); } iLambdaSerializerType = customerSerializerInstance .GetType() .GetTypeInfo() .GetInterface(Types.ILambdaSerializerTypeName); genericTypes = new[] {dataType}; } // code: serializer Expression converterExpression = Expression.Constant(converter); if (iLambdaSerializerType != null) { // code: (ILambdaSerializer)serializer converterExpression = Expression.Convert(converterExpression, iLambdaSerializerType); } // code: [(ILambdaSerializer)]serializer.Serialize[<T>](handler(...), outStream) Expression serializeCall = Expression.Call( converterExpression, // variable "Serialize", // method name genericTypes, // generic type customerObject, // arg1 - customer object outStreamParameter); // arg2 - out stream return serializeCall; } /// <summary> /// Generates an expression to deserialize incoming data to customer method input /// </summary> /// <param name="customerSerializerInstance">Instance of lambda input & output serializer.</param> /// <param name="dataType">Customer input type.</param> /// <param name="inStream">Input expression that defines customer input.</param> /// <returns>Expression that deserializes incoming data to customer method input.</returns> /// <exception cref="LambdaValidationException">Thrown when customer serializer doesn't match with expected serializer definition</exception> private Expression CreateDeserializeExpression(object customerSerializerInstance, Type dataType, Expression inStream) { // generic types, null for String and Stream converters Type[] genericTypes = null; var converter = customerSerializerInstance; if (dataType == Types.StreamType) { converter = StreamSerializer.Instance; } else { if (customerSerializerInstance == null) { throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.DeserializeMissingAttribute, _handler.AssemblyName, _handler.MethodName, dataType.FullName, typeof(LambdaSerializerAttribute).FullName); } genericTypes = new[] {dataType}; } // code: serializer var serializer = Expression.Constant(converter); // code: serializer.Deserializer[<T>](inStream) Expression deserializeCall = Expression.Call( serializer, // variable "Deserialize", // method name genericTypes, // generic type inStream); // arg1 - input stream return deserializeCall; } } }
392
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.RuntimeSupport.Bootstrap; using Amazon.Lambda.RuntimeSupport.Helpers; namespace Amazon.Lambda.RuntimeSupport { public delegate Task<InvocationResponse> LambdaBootstrapHandler(InvocationRequest invocation); public delegate Task<bool> LambdaBootstrapInitializer(); /// <summary> /// Class to communicate with the Lambda Runtime API, handle initialization, /// and run the invoke loop for an AWS Lambda function /// </summary> public class LambdaBootstrap : IDisposable { /// <summary> /// The Lambda container freezes the process at a point where an HTTP request is in progress. /// We need to make sure we don't timeout waiting for the next invocation. /// </summary> private static readonly TimeSpan RuntimeApiHttpTimeout = TimeSpan.FromHours(12); private LambdaBootstrapInitializer _initializer; private LambdaBootstrapHandler _handler; private bool _ownsHttpClient; private InternalLogger _logger = InternalLogger.GetDefaultLogger(); private HttpClient _httpClient; internal IRuntimeApiClient Client { get; set; } /// <summary> /// Create a LambdaBootstrap that will call the given initializer and handler. /// </summary> /// <param name="httpClient">The HTTP client to use with the Lambda runtime.</param> /// <param name="handler">Delegate called for each invocation of the Lambda function.</param> /// <param name="initializer">Delegate called to initialize the Lambda function. If not provided the initialization step is skipped.</param> /// <returns></returns> public LambdaBootstrap(HttpClient httpClient, LambdaBootstrapHandler handler, LambdaBootstrapInitializer initializer = null) : this(httpClient, handler, initializer, ownsHttpClient: false) { } /// <summary> /// Create a LambdaBootstrap that will call the given initializer and handler. /// </summary> /// <param name="handler">Delegate called for each invocation of the Lambda function.</param> /// <param name="initializer">Delegate called to initialize the Lambda function. If not provided the initialization step is skipped.</param> /// <returns></returns> public LambdaBootstrap(LambdaBootstrapHandler handler, LambdaBootstrapInitializer initializer = null) : this(ConstructHttpClient(), handler, initializer, ownsHttpClient: true) { } /// <summary> /// Create a LambdaBootstrap that will call the given initializer and handler. /// </summary> /// <param name="handlerWrapper">The HandlerWrapper to call for each invocation of the Lambda function.</param> /// <param name="initializer">Delegate called to initialize the Lambda function. If not provided the initialization step is skipped.</param> /// <returns></returns> public LambdaBootstrap(HandlerWrapper handlerWrapper, LambdaBootstrapInitializer initializer = null) : this(handlerWrapper.Handler, initializer) { } /// <summary> /// Create a LambdaBootstrap that will call the given initializer and handler. /// </summary> /// <param name="httpClient">The HTTP client to use with the Lambda runtime.</param> /// <param name="handlerWrapper">The HandlerWrapper to call for each invocation of the Lambda function.</param> /// <param name="initializer">Delegate called to initialize the Lambda function. If not provided the initialization step is skipped.</param> /// <returns></returns> public LambdaBootstrap(HttpClient httpClient, HandlerWrapper handlerWrapper, LambdaBootstrapInitializer initializer = null) : this(httpClient, handlerWrapper.Handler, initializer, ownsHttpClient: false) { } /// <summary> /// Create a LambdaBootstrap that will call the given initializer and handler. /// </summary> /// <param name="httpClient">The HTTP client to use with the Lambda runtime.</param> /// <param name="handler">Delegate called for each invocation of the Lambda function.</param> /// <param name="initializer">Delegate called to initialize the Lambda function. If not provided the initialization step is skipped.</param> /// <param name="ownsHttpClient">Whether the instance owns the HTTP client and should dispose of it.</param> /// <returns></returns> private LambdaBootstrap(HttpClient httpClient, LambdaBootstrapHandler handler, LambdaBootstrapInitializer initializer, bool ownsHttpClient) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _handler = handler ?? throw new ArgumentNullException(nameof(handler)); _ownsHttpClient = ownsHttpClient; _initializer = initializer; _httpClient.Timeout = RuntimeApiHttpTimeout; Client = new RuntimeApiClient(new SystemEnvironmentVariables(), _httpClient); } /// <summary> /// Run the initialization Func if provided. /// Then run the invoke loop, calling the handler for each invocation. /// </summary> /// <param name="cancellationToken"></param> /// <returns>A Task that represents the operation.</returns> public async Task RunAsync(CancellationToken cancellationToken = default(CancellationToken)) { if(UserCodeInit.IsCallPreJit()) { this._logger.LogInformation("PreJit: CultureInfo"); UserCodeInit.LoadStringCultureInfo(); this._logger.LogInformation("PreJit: Amazon.Lambda.Core"); UserCodeInit.PreJitAssembly(typeof(Amazon.Lambda.Core.ILambdaContext).Assembly); } // For local debugging purposes this environment variable can be set to run a Lambda executable assembly and process one event // and then shut down cleanly. Useful for profiling or running local tests with the .NET Lambda Test Tool. This environment // variable should never be set when function is deployed to Lambda. var runOnce = string.Equals(Environment.GetEnvironmentVariable(Constants.ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_DEBUG_RUN_ONCE), "true", StringComparison.OrdinalIgnoreCase); bool doStartInvokeLoop = _initializer == null || await InitializeAsync(); while (doStartInvokeLoop && !cancellationToken.IsCancellationRequested) { try { await InvokeOnceAsync(cancellationToken); if(runOnce) { _logger.LogInformation("Exiting Lambda processing loop because the run once environment variable was set."); return; } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { // Loop cancelled } } } internal async Task<bool> InitializeAsync() { try { return await _initializer(); } catch (Exception exception) { WriteUnhandledExceptionToLog(exception); await Client.ReportInitializationErrorAsync(exception); throw; } } internal async Task InvokeOnceAsync(CancellationToken cancellationToken = default) { this._logger.LogInformation($"Starting InvokeOnceAsync"); using (var invocation = await Client.GetNextInvocationAsync(cancellationToken)) { InvocationResponse response = null; bool invokeSucceeded = false; try { this._logger.LogInformation($"Starting invoking handler"); response = await _handler(invocation); invokeSucceeded = true; } catch (Exception exception) { WriteUnhandledExceptionToLog(exception); await Client.ReportInvocationErrorAsync(invocation.LambdaContext.AwsRequestId, exception); } finally { this._logger.LogInformation($"Finished invoking handler"); } if (invokeSucceeded) { this._logger.LogInformation($"Starting sending response"); try { await Client.SendResponseAsync(invocation.LambdaContext.AwsRequestId, response?.OutputStream); } finally { if (response != null && response.DisposeOutputStream) { response.OutputStream?.Dispose(); } this._logger.LogInformation($"Finished sending response"); } } this._logger.LogInformation($"Finished InvokeOnceAsync"); } } /// <summary> /// Utility method for creating an HttpClient used by LambdaBootstrap to interact with the Lambda Runtime API. /// </summary> /// <returns></returns> public static HttpClient ConstructHttpClient() { var dotnetRuntimeVersion = new DirectoryInfo(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()).Name; if (dotnetRuntimeVersion == "/") { dotnetRuntimeVersion = "unknown"; } var amazonLambdaRuntimeSupport = typeof(LambdaBootstrap).Assembly.GetName().Version; #if NET6_0_OR_GREATER // Create the SocketsHttpHandler directly to avoid spending cold start time creating the wrapper HttpClientHandler var handler = new SocketsHttpHandler { // Fix for https://github.com/aws/aws-lambda-dotnet/issues/1231. HttpClient by default supports only ASCII characters in headers. Changing it to allow UTF8 characters. RequestHeaderEncodingSelector = delegate { return System.Text.Encoding.UTF8; } }; // If we are running in an AOT environment, mark it as such. var userAgentString = NativeAotHelper.IsRunningNativeAot() ? $"aws-lambda-dotnet/{dotnetRuntimeVersion}-{amazonLambdaRuntimeSupport}-aot" : $"aws-lambda-dotnet/{dotnetRuntimeVersion}-{amazonLambdaRuntimeSupport}"; var client = new HttpClient(handler); #else var userAgentString = $"aws-lambda-dotnet/{dotnetRuntimeVersion}-{amazonLambdaRuntimeSupport}"; var client = new HttpClient(); #endif client.DefaultRequestHeaders.Add("User-Agent", userAgentString); return client; } private void WriteUnhandledExceptionToLog(Exception exception) { // Console.Error.WriteLine are redirected to the IConsoleLoggerWriter which // will take care of writing to the function's log stream. Console.Error.WriteLine(exception); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing && _ownsHttpClient) { _httpClient?.Dispose(); } disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion } }
275
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Amazon.Lambda.Core; namespace Amazon.Lambda.RuntimeSupport { /// <summary> /// Class to communicate with the Lambda Runtime API, handle initialization, /// and run the invoke loop for an AWS Lambda function /// </summary> public class LambdaBootstrapBuilder { private HandlerWrapper _handlerWrapper; private HttpClient _httpClient; private LambdaBootstrapInitializer _lambdaBootstrapInitializer; private LambdaBootstrapBuilder(HandlerWrapper handlerWrapper) { this._handlerWrapper = handlerWrapper; } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Action<Stream, ILambdaContext, MemoryStream> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Task> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream, Task> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Func<TInput, Task> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<ILambdaContext, Task> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream, ILambdaContext, Task> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Func<TInput, ILambdaContext, Task> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Task<Stream>> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream, Task<Stream>> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Func<TInput, Task<Stream>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<ILambdaContext, Task<Stream>> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream, ILambdaContext, Task<Stream>> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Func<TInput, ILambdaContext, Task<Stream>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<Task<TOutput>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<Stream, Task<TOutput>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput, TOutput>(Func<TInput, Task<TOutput>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput, TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<ILambdaContext, Task<TOutput>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<Stream, ILambdaContext, Task<TOutput>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput, TOutput>(Func<TInput, ILambdaContext, Task<TOutput>> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput, TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Action handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Action<Stream> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Action<TInput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Action<ILambdaContext> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Action<Stream, ILambdaContext> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Action<TInput, ILambdaContext> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream, Stream> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Func<TInput, Stream> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<ILambdaContext, Stream> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <returns></returns> public static LambdaBootstrapBuilder Create(Func<Stream, ILambdaContext, Stream> handler) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper(handler)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput>(Func<TInput, ILambdaContext, Stream> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<TOutput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<Stream, TOutput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput, TOutput>(Func<TInput, TOutput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput, TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<ILambdaContext, TOutput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TOutput>(Func<Stream, ILambdaContext, TOutput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TOutput>(handler, serializer)); } /// <summary> /// Create a builder for creating the LambdaBootstrap. /// </summary> /// <param name="handler">The handler that will be called for each Lambda invocation</param> /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param> /// <returns></returns> public static LambdaBootstrapBuilder Create<TInput, TOutput>(Func<TInput, ILambdaContext, TOutput> handler, ILambdaSerializer serializer) { return new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper<TInput, TOutput>(handler, serializer)); } /// <summary> /// Configure the bootstrap to use a provided HttpClient /// </summary> /// <param name="httpClient"></param> /// <returns></returns> public LambdaBootstrapBuilder UseHttpClient(HttpClient httpClient) { _httpClient = httpClient; return this; } /// <summary> /// Configure a custom bootstrap initalizer delegate /// </summary> /// <param name="lambdaBootstrapInitializer"></param> /// <returns></returns> public LambdaBootstrapBuilder UseBootstrapHandler(LambdaBootstrapInitializer lambdaBootstrapInitializer) { _lambdaBootstrapInitializer = lambdaBootstrapInitializer; return this; } public LambdaBootstrap Build() { if(_httpClient == null) { return new LambdaBootstrap(_handlerWrapper, _lambdaBootstrapInitializer); } return new LambdaBootstrap(_httpClient, _handlerWrapper, _lambdaBootstrapInitializer); } } }
463
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.IO; using System.Linq.Expressions; using System.Text; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using static Amazon.Lambda.RuntimeSupport.Bootstrap.Constants; using Amazon.Lambda.RuntimeSupport.Helpers; namespace Amazon.Lambda.RuntimeSupport.Bootstrap { internal class UserCodeInit { public static bool IsCallPreJit() { #if NET6_0_OR_GREATER // If we are running in an AOT environment, there is no point in doing any prejit optmization // and will most likely cause errors using APIs that are not supported in AOT. if(NativeAotHelper.IsRunningNativeAot()) { return false; } #endif string awsLambdaDotNetPreJitStr = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT); string awsLambdaInitTypeStr = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE); AwsLambdaDotNetPreJit awsLambdaDotNetPreJit; bool isParsed = Enum.TryParse(awsLambdaDotNetPreJitStr, true, out awsLambdaDotNetPreJit); if (!isParsed) { awsLambdaDotNetPreJit = AwsLambdaDotNetPreJit.ProvisionedConcurrency; } return IsPreJitAll(awsLambdaDotNetPreJit) || (IsPCInvoke(awsLambdaInitTypeStr) && IsPreJitPC(awsLambdaDotNetPreJit)); } private static bool IsPreJitAll(AwsLambdaDotNetPreJit awsLambdaDotNetPreJit) { return AwsLambdaDotNetPreJit.Always.Equals(awsLambdaDotNetPreJit); } private static bool IsPCInvoke(string awsLambdaInitTypeStr) { return AWS_LAMBDA_INITIALIZATION_TYPE_PC.Equals(awsLambdaInitTypeStr); } private static bool IsPreJitPC(AwsLambdaDotNetPreJit awsLambdaDotNetPreJit) { return AwsLambdaDotNetPreJit.ProvisionedConcurrency.Equals(awsLambdaDotNetPreJit); } public static void InitDeserializationAssembly(Expression inputExpression, ParameterExpression inStreamParameter) { if (inputExpression != null) { try { byte[] byteArray = Encoding.ASCII.GetBytes("''"); using (Stream dummyInStream = new MemoryStream(byteArray)) { Expression.Lambda(inputExpression, inStreamParameter) .Compile() .DynamicInvoke(dummyInStream); } } catch { // An exception is expected here because the dummy JSON is unlikely to match POCO } } } public static void InitSerializationAssembly(Expression outputExpression, ParameterExpression outStreamParameter, Type customerOutputType) { if (outputExpression == null || customerOutputType == null || customerOutputType == typeof(void)) return; try { var customerObjectParameter = Expression.Parameter(customerOutputType, "customerObject"); byte[] byteArray = Encoding.ASCII.GetBytes("''"); using (Stream dummyInStream = new MemoryStream(byteArray)) { Expression.Lambda(outputExpression, customerObjectParameter, outStreamParameter) .Compile() .DynamicInvoke(null, dummyInStream); } } catch { // An exception is expected here because the dummy JSON is unlikely to match POCO } } public static void LoadStringCultureInfo() { try { string locale = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_LANG); if (!string.IsNullOrEmpty(locale)) { // The environment variable also has the text encoding (i.e. en_US.UTF-8). .NET 6 // Does not accept culture names with text encoding and throw an exception. // To avoid that strip off the text encoding. if (locale.Contains(".")) { locale = locale.Substring(0, locale.IndexOf(".")); } /*A dummy operation on string*/ "Lambdalanguages".ToUpper(new CultureInfo(locale)); } else { /*A dummy operation on string*/ "Lambdalanguages".ToUpper(); } } catch (Exception e) { InternalLogger.GetDefaultLogger().LogError(e, "PreJit: Error with LoadStringCultureInfo"); } } public static void PreJitAssembly(Assembly a) { // Storage to ensure not loading the same assembly twice and optimize calls to GetAssemblies() var loaded = new HashSet<string>(); PrepareAssembly(a); LoadReferencedAssemblies(a); // Filter to avoid loading all the .net framework bool ShouldLoad(string assemblyName) { return !loaded.Contains(assemblyName) && NotNetFramework(assemblyName); } bool NotNetFramework(string assemblyName) { return !assemblyName.StartsWith("Microsoft.") && !assemblyName.StartsWith("System.") && !assemblyName.StartsWith("Newtonsoft.") && !assemblyName.StartsWith("netstandard"); } void PrepareAssembly(Assembly assembly) { foreach (var type in assembly.GetTypes()) { foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { try { if (method.IsAbstract) continue; RuntimeHelpers.PrepareMethod( method.MethodHandle); } catch (Exception e) { InternalLogger.GetDefaultLogger().LogError(e, "PreJit: Error with PrepareAssembly"); } } } } void LoadReferencedAssemblies(Assembly assembly) { foreach (AssemblyName an in assembly.GetReferencedAssemblies().Where(x => ShouldLoad(x.FullName))) { // Load the assembly and load its dependencies Assembly loadedAssembly = Assembly.Load(an); loaded.Add(an.FullName); PrepareAssembly(loadedAssembly); LoadReferencedAssemblies(loadedAssembly); // Load the referenced assemblies } } } } }
205
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.Threading.Tasks; using Amazon.Lambda.RuntimeSupport.Helpers; namespace Amazon.Lambda.RuntimeSupport.Bootstrap { /// <summary> /// Finds and initializes user code. /// </summary> internal class UserCodeInitializer { private readonly UserCodeLoader _userCodeLoader; private readonly InternalLogger _logger; /// <summary> /// Creates an instance of UserCodeInitializer /// </summary> /// <param name="userCodeLoader">UserCodeLoader used for initialize user code</param> /// <param name="logger">Logger instance for logging initialization process logs</param> public UserCodeInitializer(UserCodeLoader userCodeLoader, InternalLogger logger) { _userCodeLoader = userCodeLoader; _logger = logger; } /// <summary> /// Finds and initializes user code. /// </summary> /// <returns></returns> public Task<bool> InitializeAsync() { _userCodeLoader.Init(_logger.LogInformation); return Task.FromResult(true); } } }
50