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#
namespace Amazon.Lambda.APIGatewayEvents { using System; using System.Collections.Generic; /// <summary> /// For request coming in from API Gateway proxy /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html /// </summary> public class APIGatewayProxyRequest { /// <summary> /// The resource path defined in API Gateway /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public string Resource { get; set; } /// <summary> /// The url path for the caller /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public string Path { get; set; } /// <summary> /// The HTTP method used /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public string HttpMethod { get; set; } /// <summary> /// The headers sent with the request. This collection will only contain a single value for a header. /// /// API Gateway will populate both the Headers and MultiValueHeaders collection for every request. If multiple values /// are set for a header then the Headers collection will just contain the last value. /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public IDictionary<string, string> Headers { get; set; } /// <summary> /// The headers sent with the request. This collection supports multiple values for a single header. /// /// API Gateway will populate both the Headers and MultiValueHeaders collection for every request. If multiple values /// are set for a header then the Headers collection will just contain the last value. /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public IDictionary<string, IList<string>> MultiValueHeaders { get; set; } /// <summary> /// The query string parameters that were part of the request. This collection will only contain a single value for a query parameter. /// /// API Gateway will populate both the QueryStringParameters and MultiValueQueryStringParameters collection for every request. If multiple values /// are set for a query parameter then the QueryStringParameters collection will just contain the last value. /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public IDictionary<string, string> QueryStringParameters { get; set; } /// <summary> /// The query string parameters that were part of the request. This collection supports multiple values for a single query parameter. /// /// API Gateway will populate both the QueryStringParameters and MultiValueQueryStringParameters collection for every request. If multiple values /// are set for a query parameter then the QueryStringParameters collection will just contain the last value. /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public IDictionary<string, IList<string>> MultiValueQueryStringParameters { get; set; } /// <summary> /// The path parameters that were part of the request /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public IDictionary<string, string> PathParameters { get; set; } /// <summary> /// The stage variables defined for the stage in API Gateway /// </summary> public IDictionary<string, string> StageVariables { get; set; } /// <summary> /// The request context for the request /// </summary> public ProxyRequestContext RequestContext { get; set; } /// <summary> /// The HTTP request body. /// </summary> public string Body { get; set; } /// <summary> /// True if the body of the request is base 64 encoded. /// </summary> public bool IsBase64Encoded { get; set; } /// <summary> /// The ProxyRequestContext contains the information to identify the AWS account and resources invoking the /// Lambda function. It also includes Cognito identity information for the caller. /// </summary> public class ProxyRequestContext { /// <summary> /// The resource full path including the API Gateway stage /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public string Path { get; set; } /// <summary> /// The account id that owns the executing Lambda function /// </summary> public string AccountId { get; set; } /// <summary> /// The resource id. /// </summary> public string ResourceId { get; set; } /// <summary> /// The API Gateway stage name /// </summary> public string Stage { get; set; } /// <summary> /// The unique request id /// </summary> public string RequestId { get; set; } /// <summary> /// The identity information for the request caller /// </summary> public RequestIdentity Identity { get; set; } /// <summary> /// The resource path defined in API Gateway /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public string ResourcePath { get; set; } /// <summary> /// The HTTP method used /// <para> /// This field is only set for REST API requests. /// </para> /// </summary> public string HttpMethod { get; set; } /// <summary> /// The API Gateway rest API Id. /// </summary> public string ApiId { get; set; } /// <summary> /// An automatically generated ID for the API call, which contains more useful information for debugging/troubleshooting. /// </summary> public string ExtendedRequestId { get; set; } /// <summary> /// The connectionId identifies a unique client connection in a WebSocket API. /// <para> /// This field is only set for WebSocket API requests. /// </para> /// </summary> public string ConnectionId { get; set; } /// <summary> /// The Epoch-formatted connection time in a WebSocket API. /// <para> /// This field is only set for WebSocket API requests. /// </para> /// </summary> public long ConnectedAt { get; set; } /// <summary> /// A domain name for the WebSocket API. This can be used to make a callback to the client (instead of a hard-coded value). /// <para> /// This field is only set for WebSocket API requests. /// </para> /// </summary> public string DomainName { get; set; } /// <summary> /// The first label of the DomainName. This is often used as a caller/customer identifier. /// </summary> public string DomainPrefix { get; set; } /// <summary> /// The event type: CONNECT, MESSAGE, or DISCONNECT. /// <para> /// This field is only set for WebSocket API requests. /// </para> /// </summary> public string EventType { get; set; } /// <summary> /// A unique server-side ID for a message. Available only when the $context.eventType is MESSAGE. /// <para> /// This field is only set for WebSocket API requests. /// </para> /// </summary> public string MessageId { get; set; } /// <summary> /// The selected route key. /// <para> /// This field is only set for WebSocket API requests. /// </para> /// </summary> public string RouteKey { get; set; } /// <summary> /// The APIGatewayCustomAuthorizerContext containing the custom properties set by a custom authorizer. /// </summary> public APIGatewayCustomAuthorizerContext Authorizer { get; set; } /// <summary> /// Gets and sets the operation name. /// </summary> public string OperationName { get; set; } /// <summary> /// Gets and sets the error. /// </summary> public string Error { get; set; } /// <summary> /// Gets and sets the integration latency. /// </summary> public string IntegrationLatency { get; set; } /// <summary> /// Gets and sets the message direction. /// </summary> public string MessageDirection { get; set; } /// <summary> /// Gets and sets the request time. /// </summary> public string RequestTime { get; set; } /// <summary> /// Gets and sets the request time as an epoch. /// </summary> public long RequestTimeEpoch { get; set; } /// <summary> /// Gets and sets the status. /// </summary> public string Status { get; set; } } /// <summary> /// The RequestIdentity contains identity information for the request caller. /// </summary> public class RequestIdentity { /// <summary> /// The Cognito identity pool id. /// </summary> public string CognitoIdentityPoolId { get; set; } /// <summary> /// The account id of the caller. /// </summary> public string AccountId { get; set; } /// <summary> /// The cognito identity id. /// </summary> public string CognitoIdentityId { get; set; } /// <summary> /// The caller /// </summary> public string Caller { get; set; } /// <summary> /// The API Key /// </summary> public string ApiKey { get; set; } /// <summary> /// The API Key ID /// </summary> public string ApiKeyId { get; set; } /// <summary> /// The Access Key /// </summary> public string AccessKey { get; set; } /// <summary> /// The source IP of the request /// </summary> public string SourceIp { get; set; } /// <summary> /// The Cognito authentication type used for authentication /// </summary> public string CognitoAuthenticationType { get; set; } /// <summary> /// The Cognito authentication provider /// </summary> public string CognitoAuthenticationProvider { get; set; } /// <summary> /// The user arn /// </summary> public string UserArn { get; set; } /// <summary> /// The user agent /// </summary> public string UserAgent { get; set; } /// <summary> /// The user /// </summary> public string User { get; set; } /// <summary> /// Properties for a client certificate. /// </summary> public ProxyRequestClientCert ClientCert { get; set; } } /// <summary> /// Container for the properties of the client certificate. /// </summary> public class ProxyRequestClientCert { /// <summary> /// The PEM-encoded client certificate that the client presented during mutual TLS authentication. /// Present when a client accesses an API by using a custom domain name that has mutual /// TLS enabled. Present only in access logs if mutual TLS authentication fails. /// </summary> public string ClientCertPem { get; set; } /// <summary> /// The distinguished name of the subject of the certificate that a client presents. /// Present when a client accesses an API by using a custom domain name that has /// mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. /// </summary> public string SubjectDN { get; set; } /// <summary> /// The distinguished name of the issuer of the certificate that a client presents. /// Present when a client accesses an API by using a custom domain name that has /// mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. /// </summary> public string IssuerDN { get; set; } /// <summary> /// The serial number of the certificate. Present when a client accesses an API by /// using a custom domain name that has mutual TLS enabled. /// Present only in access logs if mutual TLS authentication fails. /// </summary> public string SerialNumber { get; set; } /// <summary> /// The rules for when the client cert is valid. /// </summary> public ClientCertValidity Validity { get; set; } } /// <summary> /// Container for the validation properties of a client cert. /// </summary> public class ClientCertValidity { /// <summary> /// The date before which the certificate is invalid. Present when a client accesses an API by using a custom domain name /// that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. /// </summary> public string NotBefore { get; set; } /// <summary> /// The date after which the certificate is invalid. Present when a client accesses an API by using a custom domain name that /// has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. /// </summary> public string NotAfter { get; set; } } } }
406
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.APIGatewayEvents { using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// The response object for Lambda functions handling request from API Gateway proxy /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html /// </summary> [DataContract] public class APIGatewayProxyResponse { /// <summary> /// The HTTP status code for the request /// </summary> [DataMember(Name = "statusCode")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("statusCode")] #endif public int StatusCode { get; set; } /// <summary> /// The Http headers return in the response. This collection supports setting single value for the same headers. /// If both the Headers and MultiValueHeaders collections are set API Gateway will merge the collection /// before returning back the headers to the caller. /// </summary> [DataMember(Name = "headers")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("headers")] #endif public IDictionary<string, string> Headers { get; set; } /// <summary> /// The Http headers return in the response. This collection supports setting multiple values for the same headers. /// If both the Headers and MultiValueHeaders collections are set API Gateway will merge the collection /// before returning back the headers to the caller. /// </summary> [DataMember(Name = "multiValueHeaders")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("multiValueHeaders")] #endif public IDictionary<string, IList<string>> MultiValueHeaders { get; set; } /// <summary> /// The response body /// </summary> [DataMember(Name = "body")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("body")] #endif public string Body { get; set; } /// <summary> /// Flag indicating whether the body should be treated as a base64-encoded string /// </summary> [DataMember(Name = "isBase64Encoded")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("isBase64Encoded")] #endif public bool IsBase64Encoded { get; set; } } }
63
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.APIGatewayEvents")] [assembly: AssemblyDescription("Lambda event interfaces for API Gateway event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
13
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; namespace Amazon.Lambda.ApplicationLoadBalancerEvents { /// <summary> /// For request coming in from Application Load Balancer. /// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html /// </summary> public class ApplicationLoadBalancerRequest { /// <summary> /// The request context for the request /// </summary> public ALBRequestContext RequestContext { get; set; } /// <summary> /// The url path for the caller /// </summary> public string Path { get; set; } /// <summary> /// The HTTP method used /// </summary> public string HttpMethod { get; set; } /// <summary> /// The headers sent with the request /// Note: Use this property when "Multi value headers" is disabled on ELB Target Group. /// </summary> public IDictionary<string, string> Headers { get; set; } /// <summary> /// The headers sent with the request /// Note: Use this property when "Multi value headers" is enabled on ELB Target Group. /// </summary> public IDictionary<string, IList<string>> MultiValueHeaders { get; set; } /// <summary> /// The query string parameters that were part of the request /// Note: Use this property when "Multi value headers" is disabled on ELB Target Group. /// </summary> public IDictionary<string, string> QueryStringParameters { get; set; } /// <summary> /// The query string parameters that were part of the request /// Note: Use this property when "Multi value headers" is enabled on ELB Target Group. /// </summary> public IDictionary<string, IList<string>> MultiValueQueryStringParameters { get; set; } /// <summary> /// The HTTP request body. /// </summary> public string Body { get; set; } /// <summary> /// True if the body of the request is base 64 encoded. /// </summary> public bool IsBase64Encoded { get; set; } /// <summary> /// Information from the AWS resources invoke the Lambda function. /// </summary> public class ALBRequestContext { /// <summary> /// Information about the source Application Load Balancer. /// </summary> public ElbInfo Elb { get; set; } } /// <summary> /// Information from the source Elastic Load Balancer. /// </summary> public class ElbInfo { /// <summary> /// The Application Load Balancer target group arn. /// </summary> public string TargetGroupArn { get; set; } } } }
83
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Amazon.Lambda.ApplicationLoadBalancerEvents { /// <summary> /// For response object for Lambda functions handling request from Application Load Balancer. /// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html /// </summary> [DataContract] public class ApplicationLoadBalancerResponse { /// <summary> /// The HTTP status code for the request /// </summary> [DataMember(Name = "statusCode")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("statusCode")] #endif public int StatusCode { get; set; } /// <summary> /// The HTTP status description for the request /// </summary> [DataMember(Name = "statusDescription")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("statusDescription")] #endif public string StatusDescription { get; set; } /// <summary> /// The Http headers return in the response /// Note: Use this property when "Multi value headers" is disabled on ELB Target Group. /// </summary> [DataMember(Name = "headers")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("headers")] #endif public IDictionary<string, string> Headers { get; set; } /// <summary> /// The Http headers return in the response /// Note: Use this property when "Multi value headers" is enabled on ELB Target Group. /// </summary> [DataMember(Name = "multiValueHeaders")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("multiValueHeaders")] #endif public IDictionary<string, IList<string>> MultiValueHeaders { get; set; } /// <summary> /// The response body /// </summary> [DataMember(Name = "body")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("body")] #endif public string Body { get; set; } /// <summary> /// Flag indicating whether the body should be treated as a base64-encoded string /// </summary> [DataMember(Name = "isBase64Encoded")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("isBase64Encoded")] #endif public bool IsBase64Encoded { get; set; } } }
69
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer.Internal; using Amazon.Lambda.Core; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Features.Authentication; using Microsoft.Extensions.Hosting; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// Base class for ASP.NET Core Lambda functions. /// </summary> public abstract class AbstractAspNetCoreFunction { /// <summary> /// Key to access the ILambdaContext object from the HttpContext.Items collection. /// </summary> public const string LAMBDA_CONTEXT = "LambdaContext"; /// <summary> /// Key to access the Lambda request object from the HttpContext.Items collection. The object /// can be either APIGatewayProxyRequest or ApplicationLoadBalancerRequest depending on the source of the event. /// </summary> public const string LAMBDA_REQUEST_OBJECT = "LambdaRequestObject"; } /// <summary> /// Base class for ASP.NET Core Lambda functions. /// </summary> /// <typeparam name="TREQUEST"></typeparam> /// <typeparam name="TRESPONSE"></typeparam> public abstract class AbstractAspNetCoreFunction<TREQUEST, TRESPONSE> : AbstractAspNetCoreFunction { private protected IServiceProvider _hostServices; private protected LambdaServer _server; private protected ILogger _logger; private protected StartupMode _startupMode; // Defines a mapping from registered content types to the response encoding format // which dictates what transformations should be applied before returning response content private readonly Dictionary<string, ResponseContentEncoding> _responseContentEncodingForContentType = new Dictionary<string, ResponseContentEncoding> { // The complete list of registered MIME content-types can be found at: // http://www.iana.org/assignments/media-types/media-types.xhtml // Here we just include a few commonly used content types found in // Web API responses and allow users to add more as needed below ["text/plain"] = ResponseContentEncoding.Default, ["text/xml"] = ResponseContentEncoding.Default, ["application/xml"] = ResponseContentEncoding.Default, ["application/json"] = ResponseContentEncoding.Default, ["text/html"] = ResponseContentEncoding.Default, ["text/css"] = ResponseContentEncoding.Default, ["text/javascript"] = ResponseContentEncoding.Default, ["text/ecmascript"] = ResponseContentEncoding.Default, ["text/markdown"] = ResponseContentEncoding.Default, ["text/csv"] = ResponseContentEncoding.Default, ["application/octet-stream"] = ResponseContentEncoding.Base64, ["image/png"] = ResponseContentEncoding.Base64, ["image/gif"] = ResponseContentEncoding.Base64, ["image/jpeg"] = ResponseContentEncoding.Base64, ["image/jpg"] = ResponseContentEncoding.Base64, ["image/x-icon"] = ResponseContentEncoding.Base64, ["application/zip"] = ResponseContentEncoding.Base64, ["application/pdf"] = ResponseContentEncoding.Base64, }; // Defines a mapping from registered content encodings to the response encoding format // which dictates what transformations should be applied before returning response content private readonly Dictionary<string, ResponseContentEncoding> _responseContentEncodingForContentEncoding = new Dictionary<string, ResponseContentEncoding> { ["gzip"] = ResponseContentEncoding.Base64, ["deflate"] = ResponseContentEncoding.Base64, ["br"] = ResponseContentEncoding.Base64 }; /// <summary> /// Default Constructor. The ASP.NET Core Framework will be initialized as part of the construction. /// </summary> protected AbstractAspNetCoreFunction() : this(StartupMode.Constructor) { } /// <summary> /// /// </summary> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected AbstractAspNetCoreFunction(StartupMode startupMode) { _startupMode = startupMode; if (_startupMode == StartupMode.Constructor) { Start(); } } /// <summary> /// /// </summary> /// <param name="hostedServices"></param> protected AbstractAspNetCoreFunction(IServiceProvider hostedServices) { _hostServices = hostedServices; _server = this._hostServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as LambdaServer; _logger = ActivatorUtilities.CreateInstance<Logger<AbstractAspNetCoreFunction<TREQUEST, TRESPONSE>>>(this._hostServices); } /// <summary> /// Defines the default treatment of response content. /// </summary> public ResponseContentEncoding DefaultResponseContentEncoding { get; set; } = ResponseContentEncoding.Default; /// <summary> /// Registers a mapping from a MIME content type to a <see cref="ResponseContentEncoding"/>. /// </summary> /// <remarks> /// The mappings in combination with the <see cref="DefaultResponseContentEncoding"/> /// setting will dictate if and how response content should be transformed before being /// returned to the calling API Gateway instance. /// <para> /// The interface between the API Gateway and Lambda provides for repsonse content to /// be returned as a UTF-8 string. In order to return binary content without incurring /// any loss or corruption due to transformations to the UTF-8 encoding, it is necessary /// to encode the raw response content in Base64 and to annotate the response that it is /// Base64-encoded. /// </para><para> /// <b>NOTE:</b> In order to use this mechanism to return binary response content, in /// addition to registering here any binary MIME content types that will be returned by /// your application, it also necessary to register those same content types with the API /// Gateway using either the console or the REST interface. Check the developer guide for /// further information. /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-control-service-api.html /// </para> /// </remarks> public void RegisterResponseContentEncodingForContentType(string contentType, ResponseContentEncoding encoding) { _responseContentEncodingForContentType[contentType] = encoding; } /// <summary> /// Registers a mapping from a asp.net content encoding to a lambda response content type to a <see cref="ResponseContentEncoding"/>. /// </summary> /// <remarks> /// The mappings in combination with the <see cref="DefaultResponseContentEncoding"/> /// setting will dictate if and how response content should be transformed before being /// returned to the calling API Gateway instance. /// <para> /// The interface between the API Gateway and Lambda provides for repsonse content to /// be returned as a UTF-8 string. In order to return binary content without incurring /// any loss or corruption due to transformations to the UTF-8 encoding, it is necessary /// to encode the raw response content in Base64 and to annotate the response that it is /// Base64-encoded. /// </para><para> /// <b>NOTE:</b> In order to use this mechanism to return binary response content, in /// addition to registering here any binary MIME content types that will be returned by /// your application, it also necessary to register those same content types with the API /// Gateway using either the console or the REST interface. Check the developer guide for /// further information. /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-control-service-api.html /// </para> /// </remarks> public void RegisterResponseContentEncodingForContentEncoding(string contentEncoding, ResponseContentEncoding encoding) { _responseContentEncodingForContentEncoding[contentEncoding] = encoding; } /// <summary> /// If true, information about unhandled exceptions thrown during request processing /// will be included in the HTTP response. /// Defaults to false /// </summary> public bool IncludeUnhandledExceptionDetailInResponse { get; set; } /// <summary> /// Method to initialize the web builder before starting the web host. In a typical Web API this is similar to the main function. /// Setting the Startup class is required in this method. /// </summary> /// <example> /// <code> /// protected override void Init(IWebHostBuilder builder) /// { /// builder /// .UseStartup&lt;Startup&gt;(); /// } /// </code> /// </example> /// <param name="builder"></param> protected virtual void Init(IWebHostBuilder builder) { } /// <summary> /// Creates the IWebHostBuilder similar to WebHost.CreateDefaultBuilder but replacing the registration of the Kestrel web server with a /// registration for Lambda. /// </summary> /// <returns></returns> [Obsolete("Functions should migrate to CreateHostBuilder and use IHostBuilder to setup their ASP.NET Core application. In a future major version update of this library support for IWebHostBuilder will be removed for non .NET Core 2.1 Lambda functions.")] protected virtual IWebHostBuilder CreateWebHostBuilder() { var builder = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TASK_ROOT"))) { logging.AddConsole(); logging.AddDebug(); } else { logging.AddLambdaLogger(hostingContext.Configuration, "Logging"); } }) .UseDefaultServiceProvider((hostingContext, options) => { options.ValidateScopes = hostingContext.HostingEnvironment.IsDevelopment(); }); Init(builder); // Swap out Kestrel as the webserver and use our implementation of IServer builder.UseLambdaServer(); return builder; } /// <summary> /// Method to initialize the host builder before starting the host. In a typical Web API this is similar to the main function. /// Setting the Startup class is required in this method. /// <para> /// It is recommended to not configure the IWebHostBuilder from this method. Instead configure the IWebHostBuilder /// in the Init(IWebHostBuilder builder) method. If you configure the IWebHostBuilder in this method the IWebHostBuilder will be /// configured twice, here and and as part of CreateHostBuilder. /// </para> /// </summary> /// <example> /// <code> /// protected override void Init(IHostBuilder builder) /// { /// builder /// .UseStartup&lt;Startup&gt;(); /// } /// </code> /// </example> /// <param name="builder"></param> protected virtual void Init(IHostBuilder builder) { } /// <summary> /// Creates the IHostBuilder similar to Host.CreateDefaultBuilder but replacing the registration of the Kestrel web server with a /// registration for Lambda. /// <para> /// When overriding this method it is recommended that ConfigureWebHostLambdaDefaults should be called instead of ConfigureWebHostDefaults to ensure the IWebHostBuilder /// has the proper services configured for running in Lambda. That includes registering Lambda instead of Kestrel as the IServer implementation /// for processing requests. /// </para> /// </summary> /// <returns></returns> protected virtual IHostBuilder CreateHostBuilder() { var builder = Host.CreateDefaultBuilder() .ConfigureWebHostLambdaDefaults(webBuilder => { Init(webBuilder); }); Init(builder); return builder; } private protected bool IsStarted { get { return _server != null; } } /// <summary> /// Should be called in the derived constructor /// </summary> protected void Start() { // For .NET Core 3.1 and above use the IHostBuilder instead of IWebHostBuilder used in .NET Core 2.1. If the user overrode CreateWebHostBuilder // then fallback to the original .NET Core 2.1 behavior. if (this.GetType().GetMethod("CreateWebHostBuilder", BindingFlags.NonPublic | BindingFlags.Instance).DeclaringType.FullName.StartsWith("Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction")) { var builder = CreateHostBuilder(); builder.ConfigureServices(services => { Utilities.EnsureLambdaServerRegistered(services); }); var host = builder.Build(); PostCreateHost(host); host.Start(); this._hostServices = host.Services; } else { #pragma warning disable 618 var builder = CreateWebHostBuilder(); #pragma warning restore 618 var host = builder.Build(); PostCreateWebHost(host); host.Start(); this._hostServices = host.Services; } _server = this._hostServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as LambdaServer; if (_server == null) { throw new Exception("Failed to find the Lambda implementation for the IServer interface in the IServiceProvider for the Host. This happens if UseLambdaServer was " + "not called when constructing the IWebHostBuilder. If CreateHostBuilder was overridden it is recommended that ConfigureWebHostLambdaDefaults should be used " + "instead of ConfigureWebHostDefaults to make sure the property Lambda services are registered."); } _logger = ActivatorUtilities.CreateInstance<Logger<AbstractAspNetCoreFunction<TREQUEST, TRESPONSE>>>(this._hostServices); } /// <summary> /// Creates a context object using the <see cref="LambdaServer"/> field in the class. /// </summary> /// <param name="features"><see cref="IFeatureCollection"/> implementation.</param> protected object CreateContext(IFeatureCollection features) { return _server.Application.CreateContext(features); } /// <summary> /// Gets the response content encoding for a content type. /// </summary> /// <param name="contentType"></param> /// <returns></returns> public ResponseContentEncoding GetResponseContentEncodingForContentType(string contentType) { if (string.IsNullOrEmpty(contentType)) { return DefaultResponseContentEncoding; } // ASP.NET Core will typically return content type with encoding like this "application/json; charset=utf-8" // To find the content type in the dictionary we need to strip the encoding off. var contentTypeWithoutEncoding = contentType.Split(';')[0].Trim(); if (_responseContentEncodingForContentType.TryGetValue(contentTypeWithoutEncoding, out var encoding)) { return encoding; } return DefaultResponseContentEncoding; } /// <summary> /// Gets the response content encoding for a content encoding. /// </summary> /// <param name="contentEncoding"></param> /// <returns></returns> public ResponseContentEncoding GetResponseContentEncodingForContentEncoding(string contentEncoding) { if (string.IsNullOrEmpty(contentEncoding)) { return DefaultResponseContentEncoding; } if (_responseContentEncodingForContentEncoding.TryGetValue(contentEncoding, out var encoding)) { return encoding; } return DefaultResponseContentEncoding; } /// <summary> /// Formats an Exception into a string, including all inner exceptions. /// </summary> /// <param name="e"><see cref="Exception"/> instance.</param> protected string ErrorReport(Exception e) { var sb = new StringBuilder(); sb.AppendLine($"{e.GetType().Name}:\n{e}"); Exception inner = e; while (inner != null) { // Append the messages to the StringBuilder. sb.AppendLine($"{inner.GetType().Name}:\n{inner}"); inner = inner.InnerException; } return sb.ToString(); } /// <summary> /// This method is what the Lambda function handler points to. /// </summary> /// <param name="request"></param> /// <param name="lambdaContext"></param> /// <returns></returns> [LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] public virtual async Task<TRESPONSE> FunctionHandlerAsync(TREQUEST request, ILambdaContext lambdaContext) { if (!IsStarted) { Start(); } InvokeFeatures features = new InvokeFeatures(); MarshallRequest(features, request, lambdaContext); if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { var httpRequestFeature = (IHttpRequestFeature)features; _logger.LogDebug($"ASP.NET Core Request PathBase: {httpRequestFeature.PathBase}, Path: {httpRequestFeature.Path}"); } { var itemFeatures = (IItemsFeature)features; itemFeatures.Items = new ItemsDictionary(); itemFeatures.Items[LAMBDA_CONTEXT] = lambdaContext; itemFeatures.Items[LAMBDA_REQUEST_OBJECT] = request; PostMarshallItemsFeatureFeature(itemFeatures, request, lambdaContext); } var scope = this._hostServices.CreateScope(); try { ((IServiceProvidersFeature)features).RequestServices = scope.ServiceProvider; var context = this.CreateContext(features); var response = await this.ProcessRequest(lambdaContext, context, features); return response; } finally { scope.Dispose(); } } /// <summary> /// Processes the current request. /// </summary> /// <param name="lambdaContext"><see cref="ILambdaContext"/> implementation.</param> /// <param name="context">The hosting application request context object.</param> /// <param name="features">An <see cref="InvokeFeatures"/> instance.</param> /// <param name="rethrowUnhandledError"> /// If specified, an unhandled exception will be rethrown for custom error handling. /// Ensure that the error handling code calls 'this.MarshallResponse(features, 500);' after handling the error to return a the typed Lambda object to the user. /// </param> protected async Task<TRESPONSE> ProcessRequest(ILambdaContext lambdaContext, object context, InvokeFeatures features, bool rethrowUnhandledError = false) { var defaultStatusCode = 200; Exception ex = null; try { try { await this._server.Application.ProcessRequestAsync(context); } catch (AggregateException agex) { ex = agex; _logger.LogError(agex, $"Caught AggregateException: '{agex}'"); var sb = new StringBuilder(); foreach (var newEx in agex.InnerExceptions) { sb.AppendLine(this.ErrorReport(newEx)); } _logger.LogError(sb.ToString()); ((IHttpResponseFeature)features).StatusCode = 500; } catch (ReflectionTypeLoadException rex) { ex = rex; _logger.LogError(rex, $"Caught ReflectionTypeLoadException: '{rex}'"); var sb = new StringBuilder(); foreach (var loaderException in rex.LoaderExceptions) { var fileNotFoundException = loaderException as FileNotFoundException; if (fileNotFoundException != null && !string.IsNullOrEmpty(fileNotFoundException.FileName)) { sb.AppendLine($"Missing file: {fileNotFoundException.FileName}"); } else { sb.AppendLine(this.ErrorReport(loaderException)); } } _logger.LogError(sb.ToString()); ((IHttpResponseFeature)features).StatusCode = 500; } catch (Exception e) { ex = e; if (rethrowUnhandledError) throw; _logger.LogError(e, $"Unknown error responding to request: {this.ErrorReport(e)}"); ((IHttpResponseFeature)features).StatusCode = 500; } if (features.ResponseStartingEvents != null) { await features.ResponseStartingEvents.ExecuteAsync(); } var response = this.MarshallResponse(features, lambdaContext, defaultStatusCode); if (ex != null && IncludeUnhandledExceptionDetailInResponse) { InternalCustomResponseExceptionHandling(response, lambdaContext, ex); } if (features.ResponseCompletedEvents != null) { await features.ResponseCompletedEvents.ExecuteAsync(); } return response; } finally { this._server.Application.DisposeContext(context, ex); } } private protected virtual void InternalCustomResponseExceptionHandling(TRESPONSE lambdaReponse, ILambdaContext lambdaContext, Exception ex) { } /// <summary> /// This method is called after the IWebHost is created from the IWebHostBuilder and the services have been configured. The /// WebHost hasn't been started yet. /// </summary> /// <param name="webHost"></param> protected virtual void PostCreateWebHost(IWebHost webHost) { } /// <summary> /// This method is called after the IHost is created from the IHostBuilder and the services have been configured. The /// Host hasn't been started yet. If the CreateWebHostBuilder method is overloaded then IHostWebBuilder will be used to create /// an IWebHost and this method will not be called. /// </summary> /// <param name="webHost"></param> protected virtual void PostCreateHost(IHost webHost) { } /// <summary> /// This method is called after marshalling the incoming Lambda request /// into ASP.NET Core's IItemsFeature. Derived classes can overwrite this method to alter /// the how the marshalling was done. /// </summary> /// <param name="aspNetCoreItemFeature"></param> /// <param name="lambdaRequest"></param> /// <param name="lambdaContext"></param> protected virtual void PostMarshallItemsFeatureFeature(IItemsFeature aspNetCoreItemFeature, TREQUEST lambdaRequest, ILambdaContext lambdaContext) { } /// <summary> /// This method is called after marshalling the incoming Lambda request /// into ASP.NET Core's IHttpAuthenticationFeature. Derived classes can overwrite this method to alter /// the how the marshalling was done. /// </summary> /// <param name="aspNetCoreHttpAuthenticationFeature"></param> /// <param name="lambdaRequest"></param> /// <param name="lambdaContext"></param> protected virtual void PostMarshallHttpAuthenticationFeature(IHttpAuthenticationFeature aspNetCoreHttpAuthenticationFeature, TREQUEST lambdaRequest, ILambdaContext lambdaContext) { } /// <summary> /// This method is called after marshalling the incoming Lambda request /// into ASP.NET Core's IHttpRequestFeature. Derived classes can overwrite this method to alter /// the how the marshalling was done. /// </summary> /// <param name="aspNetCoreRequestFeature"></param> /// <param name="lambdaRequest"></param> /// <param name="lambdaContext"></param> protected virtual void PostMarshallRequestFeature(IHttpRequestFeature aspNetCoreRequestFeature, TREQUEST lambdaRequest, ILambdaContext lambdaContext) { } /// <summary> /// This method is called after marshalling the incoming Lambda request /// into ASP.NET Core's IHttpConnectionFeature. Derived classes can overwrite this method to alter /// the how the marshalling was done. /// </summary> /// <param name="aspNetCoreConnectionFeature"></param> /// <param name="lambdaRequest"></param> /// <param name="lambdaContext"></param> protected virtual void PostMarshallConnectionFeature(IHttpConnectionFeature aspNetCoreConnectionFeature, TREQUEST lambdaRequest, ILambdaContext lambdaContext) { } /// <summary> /// This method is called after marshalling the incoming Lambda request /// into ASP.NET Core's ITlsConnectionFeature. Derived classes can overwrite this method to alter /// the how the marshalling was done. /// </summary> /// <param name="aspNetCoreConnectionFeature"></param> /// <param name="lambdaRequest"></param> /// <param name="lambdaContext"></param> protected virtual void PostMarshallTlsConnectionFeature(ITlsConnectionFeature aspNetCoreConnectionFeature, TREQUEST lambdaRequest, ILambdaContext lambdaContext) { } /// <summary> /// This method is called after marshalling the IHttpResponseFeature that came /// back from making the request into ASP.NET Core into the Lamdba response object. Derived classes can overwrite this method to alter /// the how the marshalling was done. /// </summary> /// <param name="aspNetCoreResponseFeature"></param> /// <param name="lambdaResponse"></param> /// <param name="lambdaContext"></param> protected virtual void PostMarshallResponseFeature(IHttpResponseFeature aspNetCoreResponseFeature, TRESPONSE lambdaResponse, ILambdaContext lambdaContext) { } /// <summary> /// Converts the Lambda request object into ASP.NET Core InvokeFeatures used to create the HostingApplication.Context. /// </summary> /// <param name="features"></param> /// <param name="lambdaRequest"></param> /// <param name="lambdaContext"></param> protected abstract void MarshallRequest(InvokeFeatures features, TREQUEST lambdaRequest, ILambdaContext lambdaContext); /// <summary> /// Convert the ASP.NET Core response to the Lambda response object. /// </summary> /// <param name="responseFeatures"></param> /// <param name="lambdaContext"></param> /// <param name="statusCodeIfNotSet"></param> /// <returns></returns> protected abstract TRESPONSE MarshallResponse(IHttpResponseFeature responseFeatures, ILambdaContext lambdaContext, int statusCodeIfNotSet = 200); } }
685
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.AspNetCoreServer.Internal; using Microsoft.AspNetCore.Http.Features.Authentication; using System.Globalization; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// Base class for ASP.NET Core Lambda functions that are getting request from API Gateway HTTP API V2 payload format. /// </summary> public abstract class APIGatewayHttpApiV2ProxyFunction : AbstractAspNetCoreFunction<APIGatewayHttpApiV2ProxyRequest, APIGatewayHttpApiV2ProxyResponse> { /// <summary> /// Default constructor /// </summary> protected APIGatewayHttpApiV2ProxyFunction() : base() { } /// <inheritdoc/> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected APIGatewayHttpApiV2ProxyFunction(StartupMode startupMode) : base(startupMode) { } /// <summary> /// Constructor used by Amazon.Lambda.AspNetCoreServer.Hosting to support ASP.NET Core projects using the Minimal API style. /// </summary> /// <param name="hostedServices"></param> protected APIGatewayHttpApiV2ProxyFunction(IServiceProvider hostedServices) : base(hostedServices) { _hostServices = hostedServices; } private protected override void InternalCustomResponseExceptionHandling(APIGatewayHttpApiV2ProxyResponse apiGatewayResponse, ILambdaContext lambdaContext, Exception ex) { apiGatewayResponse.SetHeaderValues("ErrorType", ex.GetType().Name, false); } /// <summary> /// Convert the JSON document received from API Gateway into the InvokeFeatures object. /// InvokeFeatures is then passed into IHttpApplication to create the ASP.NET Core request objects. /// </summary> /// <param name="features"></param> /// <param name="apiGatewayRequest"></param> /// <param name="lambdaContext"></param> protected override void MarshallRequest(InvokeFeatures features, APIGatewayHttpApiV2ProxyRequest apiGatewayRequest, ILambdaContext lambdaContext) { { var authFeatures = (IHttpAuthenticationFeature)features; var authorizer = apiGatewayRequest?.RequestContext?.Authorizer; if (authorizer != null) { // handling claims output from cognito user pool authorizer if (authorizer.Jwt?.Claims != null && authorizer.Jwt.Claims.Count != 0) { var identity = new ClaimsIdentity(authorizer.Jwt.Claims.Select( entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); _logger.LogDebug( $"Configuring HttpContext.User with {authorizer.Jwt.Claims.Count} claims coming from API Gateway's Request Context"); authFeatures.User = new ClaimsPrincipal(identity); } else { // handling claims output from custom lambda authorizer var identity = new ClaimsIdentity(authorizer.Jwt?.Claims.Select(entry => new Claim(entry.Key, entry.Value)), "AuthorizerIdentity"); _logger.LogDebug( $"Configuring HttpContext.User with {identity.Claims.Count()} claims coming from API Gateway's Request Context"); authFeatures.User = new ClaimsPrincipal(identity); } } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallHttpAuthenticationFeature(authFeatures, apiGatewayRequest, lambdaContext); } { var httpInfo = apiGatewayRequest.RequestContext.Http; var requestFeatures = (IHttpRequestFeature)features; requestFeatures.Scheme = "https"; requestFeatures.Method = httpInfo.Method; if (string.IsNullOrWhiteSpace(apiGatewayRequest.RequestContext?.DomainName)) { _logger.LogWarning($"Request does not contain domain name information but is derived from {nameof(APIGatewayProxyFunction)}."); } var rawQueryString = Utilities.CreateQueryStringParametersFromHttpApiV2(apiGatewayRequest.RawQueryString); requestFeatures.RawTarget = apiGatewayRequest.RawPath + rawQueryString; requestFeatures.QueryString = rawQueryString; requestFeatures.Path = Utilities.DecodeResourcePath(httpInfo.Path); if (!requestFeatures.Path.StartsWith("/")) { requestFeatures.Path = "/" + requestFeatures.Path; } // If there is a stage name in the resource path strip it out and set the stage name as the base path. // This is required so that ASP.NET Core will route request based on the resource path without the stage name. var stageName = apiGatewayRequest.RequestContext.Stage; if (!string.IsNullOrWhiteSpace(stageName)) { if (requestFeatures.Path.StartsWith($"/{stageName}")) { requestFeatures.Path = requestFeatures.Path.Substring(stageName.Length + 1); requestFeatures.PathBase = $"/{stageName}"; } } // API Gateway HTTP API V2 format supports multiple values for headers by comma separating the values. if (apiGatewayRequest.Headers != null) { foreach(var kvp in apiGatewayRequest.Headers) { requestFeatures.Headers[kvp.Key] = new StringValues(kvp.Value?.Split(',')); } } if (!requestFeatures.Headers.ContainsKey("Host")) { requestFeatures.Headers["Host"] = apiGatewayRequest.RequestContext.DomainName; } if (apiGatewayRequest.Cookies != null) { // Add Cookies from the event requestFeatures.Headers["Cookie"] = String.Join("; ", apiGatewayRequest.Cookies); } if (!string.IsNullOrEmpty(apiGatewayRequest.Body)) { requestFeatures.Body = Utilities.ConvertLambdaRequestBodyToAspNetCoreBody(apiGatewayRequest.Body, apiGatewayRequest.IsBase64Encoded); } // Make sure the content-length header is set if header was not present. const string contentLengthHeaderName = "Content-Length"; if (!requestFeatures.Headers.ContainsKey(contentLengthHeaderName)) { requestFeatures.Headers[contentLengthHeaderName] = requestFeatures.Body == null ? "0" : requestFeatures.Body.Length.ToString(CultureInfo.InvariantCulture); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallRequestFeature(requestFeatures, apiGatewayRequest, lambdaContext); } { // set up connection features var connectionFeatures = (IHttpConnectionFeature)features; if (!string.IsNullOrEmpty(apiGatewayRequest.RequestContext?.Http?.SourceIp) && IPAddress.TryParse(apiGatewayRequest.RequestContext.Http.SourceIp, out var remoteIpAddress)) { connectionFeatures.RemoteIpAddress = remoteIpAddress; } if (apiGatewayRequest?.Headers?.TryGetValue("X-Forwarded-Port", out var port) == true) { connectionFeatures.RemotePort = int.Parse(port, CultureInfo.InvariantCulture); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallConnectionFeature(connectionFeatures, apiGatewayRequest, lambdaContext); } { var tlsConnectionFeature = (ITlsConnectionFeature)features; var clientCertPem = apiGatewayRequest?.RequestContext?.Authentication?.ClientCert?.ClientCertPem; if (clientCertPem != null) { tlsConnectionFeature.ClientCertificate = Utilities.GetX509Certificate2FromPem(clientCertPem); } PostMarshallTlsConnectionFeature(tlsConnectionFeature, apiGatewayRequest, lambdaContext); } } /// <summary> /// Convert the response coming from ASP.NET Core into APIGatewayProxyResponse which is /// serialized into the JSON object that API Gateway expects. /// </summary> /// <param name="responseFeatures"></param> /// <param name="statusCodeIfNotSet">Sometimes the ASP.NET server doesn't set the status code correctly when successful, so this parameter will be used when the value is 0.</param> /// <param name="lambdaContext"></param> /// <returns><see cref="APIGatewayProxyResponse"/></returns> protected override APIGatewayHttpApiV2ProxyResponse MarshallResponse(IHttpResponseFeature responseFeatures, ILambdaContext lambdaContext, int statusCodeIfNotSet = 200) { var response = new APIGatewayHttpApiV2ProxyResponse { StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet }; string contentType = null; string contentEncoding = null; if (responseFeatures.Headers != null) { response.Headers = new Dictionary<string, string>(); foreach (var kvp in responseFeatures.Headers) { if (kvp.Key.Equals(HeaderNames.SetCookie, StringComparison.CurrentCultureIgnoreCase)) { // Cookies must be passed through the proxy response property and not as a // header to be able to pass back multiple cookies in a single request. response.Cookies = kvp.Value.ToArray(); continue; } response.SetHeaderValues(kvp.Key, kvp.Value.ToArray(), false); // Remember the Content-Type for possible later use if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase) && response.Headers[kvp.Key]?.Length > 0) { contentType = response.Headers[kvp.Key]; } else if (kvp.Key.Equals("Content-Encoding", StringComparison.CurrentCultureIgnoreCase) && response.Headers[kvp.Key]?.Length > 0) { contentEncoding = response.Headers[kvp.Key]; } } } if (contentType == null) { response.Headers["Content-Type"] = null; } if (responseFeatures.Body != null) { // Figure out how we should treat the response content, check encoding first to see if body is compressed, then check content type var rcEncoding = GetResponseContentEncodingForContentEncoding(contentEncoding); if (rcEncoding != ResponseContentEncoding.Base64) { rcEncoding = GetResponseContentEncodingForContentType(contentType); } (response.Body, response.IsBase64Encoded) = Utilities.ConvertAspNetCoreBodyToLambdaBody(responseFeatures.Body, rcEncoding); } PostMarshallResponseFeature(responseFeatures, response, lambdaContext); _logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}"); return response; } } }
273
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Hosting; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// APIGatewayHttpApiV2ProxyFunction is the base class that is implemented in a ASP.NET Core Web API. The derived class implements /// the Init method similar to Main function in the ASP.NET Core and provides typed Startup. The function handler for /// the Lambda function will point to this base class FunctionHandlerAsync method. /// </summary> /// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam> public abstract class APIGatewayHttpApiV2ProxyFunction<TStartup> : APIGatewayHttpApiV2ProxyFunction where TStartup : class { /// <summary> /// Default Constructor. The ASP.NET Core Framework will be initialized as part of the construction. /// </summary> protected APIGatewayHttpApiV2ProxyFunction() : base() { } /// <summary> /// /// </summary> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected APIGatewayHttpApiV2ProxyFunction(StartupMode startupMode) : base(startupMode) { } /// <inheritdoc/> protected override void Init(IWebHostBuilder builder) { builder.UseStartup<TStartup>(); } } }
40
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.AspNetCoreServer.Internal; using Microsoft.AspNetCore.Http.Features.Authentication; using System.Globalization; using System.Security.Cryptography.X509Certificates; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// APIGatewayProxyFunction is the base class for Lambda functions hosting the ASP.NET Core framework and exposed to the web via API Gateway. /// /// The derived class implements the Init method similar to Main function in the ASP.NET Core. The function handler for the Lambda function will point /// to this base class FunctionHandlerAsync method. /// </summary> public abstract class APIGatewayProxyFunction : AbstractAspNetCoreFunction<APIGatewayProxyRequest, APIGatewayProxyResponse> { /// <summary> /// Key to access the ILambdaContext object from the HttpContext.Items collection. /// </summary> [Obsolete("References should be updated to Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction.LAMBDA_CONTEXT")] public new const string LAMBDA_CONTEXT = AbstractAspNetCoreFunction.LAMBDA_CONTEXT; /// <summary> /// Key to access the APIGatewayProxyRequest object from the HttpContext.Items collection. /// </summary> [Obsolete("References should be updated to Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT")] public const string APIGATEWAY_REQUEST = AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT; /// <summary> /// The modes for when the ASP.NET Core framework will be initialized. /// </summary> [Obsolete("References should be updated to Amazon.Lambda.AspNetCoreServer.StartupMode")] public enum AspNetCoreStartupMode { /// <summary> /// Initialize during the construction of APIGatewayProxyFunction /// </summary> Constructor = StartupMode.Constructor, /// <summary> /// Initialize during the first incoming request /// </summary> FirstRequest = StartupMode.FirstRequest } /// <summary> /// Default Constructor. The ASP.NET Core Framework will be initialized as part of the construction. /// </summary> protected APIGatewayProxyFunction() : base() { } /// <summary> /// /// </summary> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> [Obsolete("Calls to the constructor should be replaced with the constructor that takes a Amazon.Lambda.AspNetCoreServer.StartupMode as the parameter.")] protected APIGatewayProxyFunction(AspNetCoreStartupMode startupMode) : base((StartupMode)startupMode) { } /// <summary> /// /// </summary> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected APIGatewayProxyFunction(StartupMode startupMode) : base(startupMode) { } /// <summary> /// Constructor used by Amazon.Lambda.AspNetCoreServer.Hosting to support ASP.NET Core projects using the Minimal API style. /// </summary> /// <param name="hostedServices"></param> protected APIGatewayProxyFunction(IServiceProvider hostedServices) : base(hostedServices) { _hostServices = hostedServices; } private protected override void InternalCustomResponseExceptionHandling(APIGatewayProxyResponse apiGatewayResponse, ILambdaContext lambdaContext, Exception ex) { apiGatewayResponse.MultiValueHeaders["ErrorType"] = new List<string> { ex.GetType().Name }; } /// <summary> /// Convert the JSON document received from API Gateway into the InvokeFeatures object. /// InvokeFeatures is then passed into IHttpApplication to create the ASP.NET Core request objects. /// </summary> /// <param name="features"></param> /// <param name="apiGatewayRequest"></param> /// <param name="lambdaContext"></param> protected override void MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext) { { var authFeatures = (IHttpAuthenticationFeature)features; var authorizer = apiGatewayRequest?.RequestContext?.Authorizer; if (authorizer != null) { // handling claims output from cognito user pool authorizer if (authorizer.Claims != null && authorizer.Claims.Count != 0) { var identity = new ClaimsIdentity(authorizer.Claims.Select( entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); _logger.LogDebug( $"Configuring HttpContext.User with {authorizer.Claims.Count} claims coming from API Gateway's Request Context"); authFeatures.User = new ClaimsPrincipal(identity); } else { // handling claims output from custom lambda authorizer var identity = new ClaimsIdentity( authorizer.Where(x => x.Value != null && !string.Equals(x.Key, "claims", StringComparison.OrdinalIgnoreCase)) .Select(entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); _logger.LogDebug( $"Configuring HttpContext.User with {authorizer.Count} claims coming from API Gateway's Request Context"); authFeatures.User = new ClaimsPrincipal(identity); } } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallHttpAuthenticationFeature(authFeatures, apiGatewayRequest, lambdaContext); } { var requestFeatures = (IHttpRequestFeature)features; requestFeatures.Scheme = "https"; requestFeatures.Method = apiGatewayRequest.HttpMethod; string path = null; // Replaces {proxy+} in path, if exists if (apiGatewayRequest.PathParameters != null && apiGatewayRequest.PathParameters.TryGetValue("proxy", out var proxy) && !string.IsNullOrEmpty(apiGatewayRequest.Resource)) { var proxyPath = proxy; path = apiGatewayRequest.Resource.Replace("{proxy+}", proxyPath); // Adds all the rest of non greedy parameters in apiGateway.Resource to the path foreach (var pathParameter in apiGatewayRequest.PathParameters.Where(pp => pp.Key != "proxy")) { path = path.Replace($"{{{pathParameter.Key}}}", pathParameter.Value); } } if (string.IsNullOrEmpty(path)) { path = apiGatewayRequest.Path; } if (!path.StartsWith("/")) { path = "/" + path; } var rawQueryString = Utilities.CreateQueryStringParameters( apiGatewayRequest.QueryStringParameters, apiGatewayRequest.MultiValueQueryStringParameters, true); requestFeatures.RawTarget = apiGatewayRequest.Path + rawQueryString; requestFeatures.QueryString = rawQueryString; requestFeatures.Path = path; requestFeatures.PathBase = string.Empty; if (!string.IsNullOrEmpty(apiGatewayRequest?.RequestContext?.Path)) { // This is to cover the case where the request coming in is https://myapigatewayid.execute-api.us-west-2.amazonaws.com/Prod where // Prod is the stage name and there is no ending '/'. Path will be set to '/' so to make sure we detect the correct base path // append '/' on the end to make the later EndsWith and substring work correctly. var requestContextPath = apiGatewayRequest.RequestContext.Path; if (path.EndsWith("/") && !requestContextPath.EndsWith("/")) { requestContextPath += "/"; } else if (!path.EndsWith("/") && requestContextPath.EndsWith("/")) { // Handle a trailing slash in the request path: e.g. https://myapigatewayid.execute-api.us-west-2.amazonaws.com/Prod/foo/ requestFeatures.Path = path += "/"; } if (requestContextPath.EndsWith(path)) { requestFeatures.PathBase = requestContextPath.Substring(0, requestContextPath.Length - requestFeatures.Path.Length); } } requestFeatures.Path = Utilities.DecodeResourcePath(requestFeatures.Path); Utilities.SetHeadersCollection(requestFeatures.Headers, apiGatewayRequest.Headers, apiGatewayRequest.MultiValueHeaders); if (!requestFeatures.Headers.ContainsKey("Host")) { var apiId = apiGatewayRequest?.RequestContext?.ApiId ?? ""; var stage = apiGatewayRequest?.RequestContext?.Stage ?? ""; requestFeatures.Headers["Host"] = $"apigateway-{apiId}-{stage}"; } if (!string.IsNullOrEmpty(apiGatewayRequest.Body)) { requestFeatures.Body = Utilities.ConvertLambdaRequestBodyToAspNetCoreBody(apiGatewayRequest.Body, apiGatewayRequest.IsBase64Encoded); } // Make sure the content-length header is set if header was not present. const string contentLengthHeaderName = "Content-Length"; if (!requestFeatures.Headers.ContainsKey(contentLengthHeaderName)) { requestFeatures.Headers[contentLengthHeaderName] = requestFeatures.Body == null ? "0" : requestFeatures.Body.Length.ToString(CultureInfo.InvariantCulture); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallRequestFeature(requestFeatures, apiGatewayRequest, lambdaContext); } { // set up connection features var connectionFeatures = (IHttpConnectionFeature)features; if (!string.IsNullOrEmpty(apiGatewayRequest?.RequestContext?.Identity?.SourceIp) && IPAddress.TryParse(apiGatewayRequest.RequestContext.Identity.SourceIp, out var remoteIpAddress)) { connectionFeatures.RemoteIpAddress = remoteIpAddress; } if (apiGatewayRequest?.Headers?.TryGetValue("X-Forwarded-Port", out var forwardedPort) == true) { connectionFeatures.RemotePort = int.Parse(forwardedPort, CultureInfo.InvariantCulture); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallConnectionFeature(connectionFeatures, apiGatewayRequest, lambdaContext); } { var tlsConnectionFeature = (ITlsConnectionFeature)features; var clientCertPem = apiGatewayRequest?.RequestContext?.Identity?.ClientCert?.ClientCertPem; if (clientCertPem != null) { tlsConnectionFeature.ClientCertificate = Utilities.GetX509Certificate2FromPem(clientCertPem); } PostMarshallTlsConnectionFeature(tlsConnectionFeature, apiGatewayRequest, lambdaContext); } } /// <summary> /// Convert the response coming from ASP.NET Core into APIGatewayProxyResponse which is /// serialized into the JSON object that API Gateway expects. /// </summary> /// <param name="responseFeatures"></param> /// <param name="statusCodeIfNotSet">Sometimes the ASP.NET server doesn't set the status code correctly when successful, so this parameter will be used when the value is 0.</param> /// <param name="lambdaContext"></param> /// <returns><see cref="APIGatewayProxyResponse"/></returns> protected override APIGatewayProxyResponse MarshallResponse(IHttpResponseFeature responseFeatures, ILambdaContext lambdaContext, int statusCodeIfNotSet = 200) { var response = new APIGatewayProxyResponse { StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet }; string contentType = null; string contentEncoding = null; if (responseFeatures.Headers != null) { response.MultiValueHeaders = new Dictionary<string, IList<string>>(); response.Headers = new Dictionary<string, string>(); foreach (var kvp in responseFeatures.Headers) { response.MultiValueHeaders[kvp.Key] = kvp.Value.ToList(); // Remember the Content-Type for possible later use if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase) && response.MultiValueHeaders[kvp.Key].Count > 0) { contentType = response.MultiValueHeaders[kvp.Key][0]; } else if (kvp.Key.Equals("Content-Encoding", StringComparison.CurrentCultureIgnoreCase) && response.MultiValueHeaders[kvp.Key].Count > 0) { contentEncoding = response.MultiValueHeaders[kvp.Key][0]; } } } if (contentType == null) { response.MultiValueHeaders["Content-Type"] = new List<string>() { null }; } if (responseFeatures.Body != null) { // Figure out how we should treat the response content, check encoding first to see if body is compressed, then check content type var rcEncoding = GetResponseContentEncodingForContentEncoding(contentEncoding); if (rcEncoding != ResponseContentEncoding.Base64) { rcEncoding = GetResponseContentEncodingForContentType(contentType); } (response.Body, response.IsBase64Encoded) = Utilities.ConvertAspNetCoreBodyToLambdaBody(responseFeatures.Body, rcEncoding); } PostMarshallResponseFeature(responseFeatures, response, lambdaContext); _logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}"); return response; } } }
340
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Hosting; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// ApiGatewayProxyFunction is the base class that is implemented in a ASP.NET Core Web API. The derived class implements /// the Init method similar to Main function in the ASP.NET Core and provides typed Startup. The function handler for /// the Lambda function will point to this base class FunctionHandlerAsync method. /// </summary> /// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam> public abstract class APIGatewayProxyFunction<TStartup> : APIGatewayProxyFunction where TStartup : class { /// <summary> /// Default Constructor. The ASP.NET Core Framework will be initialized as part of the construction. /// </summary> protected APIGatewayProxyFunction() : base() { } /// <summary> /// /// </summary> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected APIGatewayProxyFunction(StartupMode startupMode) : base(startupMode) { } /// <inheritdoc/> protected override void Init(IWebHostBuilder builder) { builder.UseStartup<TStartup>(); } } }
41
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; using Amazon.Lambda.Core; using Amazon.Lambda.AspNetCoreServer.Internal; using Amazon.Lambda.ApplicationLoadBalancerEvents; using System.Net; using Microsoft.AspNetCore.Http.Features.Authentication; using Microsoft.Extensions.Primitives; using System.Globalization; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// ApplicationLoadBalancerFunction is the base class for Lambda functions hosting the ASP.NET Core framework and exposed to the web via ELB's Application Load Balancer. /// /// The derived class implements the Init method similar to Main function in the ASP.NET Core. The function handler for the Lambda function will point /// to this base class FunctionHandlerAsync method. /// </summary> public abstract class ApplicationLoadBalancerFunction : AbstractAspNetCoreFunction<ApplicationLoadBalancerRequest, ApplicationLoadBalancerResponse> { private bool _multiHeaderValuesEnabled = true; /// <inheritdoc/> protected ApplicationLoadBalancerFunction() : base() { } /// <inheritdoc/> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected ApplicationLoadBalancerFunction(StartupMode startupMode) : base(startupMode) { } /// <summary> /// Constructor used by Amazon.Lambda.AspNetCoreServer.Hosting to support ASP.NET Core projects using the Minimal API style. /// </summary> /// <param name="hostedServices"></param> protected ApplicationLoadBalancerFunction(IServiceProvider hostedServices) : base(hostedServices) { _hostServices = hostedServices; } /// <inheritdoc/> protected override void MarshallRequest(InvokeFeatures features, ApplicationLoadBalancerRequest lambdaRequest, ILambdaContext lambdaContext) { // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallHttpAuthenticationFeature(features, lambdaRequest, lambdaContext); // Request coming from Application Load Balancer will always send the headers X-Amzn-Trace-Id, X-Forwarded-For, X-Forwarded-Port, and X-Forwarded-Proto. // So this will only happen when writing tests with incomplete sample requests. if (lambdaRequest.Headers == null && lambdaRequest.MultiValueHeaders == null) { throw new Exception("Unable to determine header mode, single or multi value, because both Headers and MultiValueHeaders are null."); } if (lambdaRequest.RequestContext?.Elb?.TargetGroupArn == null) { _logger.LogWarning($"Request does not contain ELB information but is derived from {nameof(ApplicationLoadBalancerFunction)}."); } // Look to see if the request is using mutli value headers or not. This is important when // marshalling the response to know whether to fill in the the Headers or MultiValueHeaders collection. // Since a Lambda function compute environment is only one processing one event at a time it is safe to store // this as a member variable. this._multiHeaderValuesEnabled = lambdaRequest.MultiValueHeaders != null; { var requestFeatures = (IHttpRequestFeature)features; requestFeatures.Scheme = GetSingleHeaderValue(lambdaRequest, "x-forwarded-proto"); requestFeatures.Method = lambdaRequest.HttpMethod; var rawPath = lambdaRequest.Path; var rawQueryString = Utilities.CreateQueryStringParameters( lambdaRequest.QueryStringParameters, lambdaRequest.MultiValueQueryStringParameters, false); requestFeatures.RawTarget = rawPath + rawQueryString; requestFeatures.QueryString = rawQueryString; requestFeatures.Path = Utilities.DecodeResourcePath(rawPath); Utilities.SetHeadersCollection(requestFeatures.Headers, lambdaRequest.Headers, lambdaRequest.MultiValueHeaders); if (!string.IsNullOrEmpty(lambdaRequest.Body)) { requestFeatures.Body = Utilities.ConvertLambdaRequestBodyToAspNetCoreBody(lambdaRequest.Body, lambdaRequest.IsBase64Encoded); } // Make sure the content-length header is set if header was not present. const string contentLengthHeaderName = "Content-Length"; if (!requestFeatures.Headers.ContainsKey(contentLengthHeaderName)) { requestFeatures.Headers[contentLengthHeaderName] = requestFeatures.Body == null ? "0" : requestFeatures.Body.Length.ToString(CultureInfo.InvariantCulture); } var userAgent = GetSingleHeaderValue(lambdaRequest, "user-agent"); if (userAgent != null && userAgent.StartsWith("ELB-HealthChecker/", StringComparison.OrdinalIgnoreCase)) { requestFeatures.Scheme = "https"; requestFeatures.Headers["host"] = "localhost"; requestFeatures.Headers["x-forwarded-port"] = "443"; requestFeatures.Headers["x-forwarded-for"] = "127.0.0.1"; } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallRequestFeature(requestFeatures, lambdaRequest, lambdaContext); } { // set up connection features var connectionFeatures = (IHttpConnectionFeature)features; var remoteIpAddressStr = GetSingleHeaderValue(lambdaRequest, "x-forwarded-for"); if (!string.IsNullOrEmpty(remoteIpAddressStr) && IPAddress.TryParse(remoteIpAddressStr, out var remoteIpAddress)) { connectionFeatures.RemoteIpAddress = remoteIpAddress; } var remotePort = GetSingleHeaderValue(lambdaRequest, "x-forwarded-port"); if (!string.IsNullOrEmpty(remotePort)) { connectionFeatures.RemotePort = int.Parse(remotePort, CultureInfo.InvariantCulture); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallConnectionFeature(connectionFeatures, lambdaRequest, lambdaContext); } } /// <inheritdoc/> protected override ApplicationLoadBalancerResponse MarshallResponse(IHttpResponseFeature responseFeatures, ILambdaContext lambdaContext, int statusCodeIfNotSet = 200) { var response = new ApplicationLoadBalancerResponse { StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet }; response.StatusDescription = $"{response.StatusCode} {((System.Net.HttpStatusCode)response.StatusCode).ToString()}"; string contentType = null; string contentEncoding = null; if (responseFeatures.Headers != null) { if (this._multiHeaderValuesEnabled) response.MultiValueHeaders = new Dictionary<string, IList<string>>(); else response.Headers = new Dictionary<string, string>(); foreach (var kvp in responseFeatures.Headers) { if (this._multiHeaderValuesEnabled) { response.MultiValueHeaders[kvp.Key] = kvp.Value.ToList(); } else { response.Headers[kvp.Key] = kvp.Value[0]; } // Remember the Content-Type for possible later use if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase)) { contentType = kvp.Value[0]; } else if (kvp.Key.Equals("Content-Encoding", StringComparison.CurrentCultureIgnoreCase)) { contentEncoding = kvp.Value[0]; } } } if (responseFeatures.Body != null) { // Figure out how we should treat the response content, check encoding first to see if body is compressed, then check content type var rcEncoding = GetResponseContentEncodingForContentEncoding(contentEncoding); if (rcEncoding != ResponseContentEncoding.Base64) { rcEncoding = GetResponseContentEncodingForContentType(contentType); } (response.Body, response.IsBase64Encoded) = Utilities.ConvertAspNetCoreBodyToLambdaBody(responseFeatures.Body, rcEncoding); } PostMarshallResponseFeature(responseFeatures, response, lambdaContext); _logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}"); return response; } private protected override void InternalCustomResponseExceptionHandling(ApplicationLoadBalancerResponse lambdaResponse, ILambdaContext lambdaContext, Exception ex) { var errorName = ex.GetType().Name; if (this._multiHeaderValuesEnabled) { lambdaResponse.MultiValueHeaders.Add(new KeyValuePair<string, IList<string>>("ErrorType", new List<string> { errorName })); } else { lambdaResponse.Headers.Add(new KeyValuePair<string, string>("ErrorType", errorName)); } } private string GetSingleHeaderValue(ApplicationLoadBalancerRequest request, string headerName) { if (this._multiHeaderValuesEnabled) { var kvp = request.MultiValueHeaders.FirstOrDefault(x => string.Equals(x.Key, headerName, StringComparison.OrdinalIgnoreCase)); if (!kvp.Equals(default(KeyValuePair<string, IList<string>>))) { return kvp.Value.First(); } } else { var kvp = request.Headers.FirstOrDefault(x => string.Equals(x.Key, headerName, StringComparison.OrdinalIgnoreCase)); if (!kvp.Equals(default(KeyValuePair<string, string>))) { return kvp.Value; } } return null; } } }
246
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Hosting; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// ApplicationLoadBalancerFunction is the base class that is implemented in a ASP.NET Core Web API. The derived class implements /// the Init method similar to Main function in the ASP.NET Core and provides typed Startup. The function handler for /// the Lambda function will point to this base class FunctionHandlerAsync method. /// </summary> /// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam> public abstract class ApplicationLoadBalancerFunction<TStartup> : ApplicationLoadBalancerFunction where TStartup : class { /// <summary> /// Default Constructor. The ASP.NET Core Framework will be initialized as part of the construction. /// </summary> protected ApplicationLoadBalancerFunction() : base() { } /// <summary> /// /// </summary> /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param> protected ApplicationLoadBalancerFunction(StartupMode startupMode) : base(startupMode) { } /// <inheritdoc/> /// <inheritdoc/> protected override void Init(IWebHostBuilder builder) { builder.UseStartup<TStartup>(); } } }
41
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Amazon.Lambda.AspNetCoreServer.Internal; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting; using System.IO; namespace Microsoft.Extensions.Hosting { /// <summary> /// Extension methods for IHostBuilder. /// </summary> public static class HostBuilderExtensions { /// <summary> /// Configures the default settings for IWebHostBuilder when running in Lambda. The major difference between ConfigureWebHostDefaults and ConfigureWebHostLambdaDefaults /// is that it calls "webBuilder.UseLambdaServer()" to swap out Kestrel for Lambda as the IServer. /// </summary> /// <param name="builder"></param> /// <param name="configure"></param> /// <returns></returns> public static IHostBuilder ConfigureWebHostLambdaDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure) { builder.ConfigureWebHostDefaults(webBuilder => { webBuilder .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TASK_ROOT"))) { logging.AddConsole(); logging.AddDebug(); } else { logging.ClearProviders(); logging.AddLambdaLogger(hostingContext.Configuration, "Logging"); } }) .UseDefaultServiceProvider((hostingContext, options) => { options.ValidateScopes = hostingContext.HostingEnvironment.IsDevelopment(); }); // Swap out Kestrel as the webserver and use our implementation of IServer webBuilder.UseLambdaServer(); configure(webBuilder); }); return builder; } } }
64
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// Indicates how response content from a controller action should be treated, /// possibly requiring a transformation to comply with the expected binary disposition. /// </summary> public enum ResponseContentEncoding { /// Indicates the response content should already be UTF-8-friendly and should be /// returned without any further transformation or encoding. This typically /// indicates a text response. Default = 0, /// Indicates the response content should be Base64 encoded before being returned. /// This is typically used to indicate a binary response. Base64, } }
18
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// The modes for when the ASP.NET Core framework will be initialized. /// </summary> public enum StartupMode { /// <summary> /// Initialize ASP.NET Core framework during the constructor /// </summary> Constructor, /// <summary> /// Initialize ASP.NET Core framework during the first incoming request /// </summary> FirstRequest } }
23
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.AspNetCoreServer.Internal; using Microsoft.AspNetCore.Hosting.Server; namespace Microsoft.AspNetCore.Hosting { /// <summary> /// This class is a container for extensions methods to the IWebHostBuilder /// </summary> public static class WebHostBuilderExtensions { /// <summary> /// Extension method for configuring API Gateway as the server for an ASP.NET Core application. /// This is called instead of UseKestrel. If UseKestrel was called before this it will remove /// the service description that was added to the IServiceCollection. /// </summary> /// <param name="hostBuilder"></param> /// <returns></returns> [Obsolete("Calls should be replaced with UseLambdaServer")] public static IWebHostBuilder UseApiGateway(this IWebHostBuilder hostBuilder) { return UseLambdaServer(hostBuilder); } /// <summary> /// Extension method for configuring Lambda as the server for an ASP.NET Core application. /// This is called instead of UseKestrel. If UseKestrel was called before this it will remove /// the service description that was added to the IServiceCollection. /// </summary> /// <param name="hostBuilder"></param> /// <returns></returns> public static IWebHostBuilder UseLambdaServer(this IWebHostBuilder hostBuilder) { return hostBuilder.ConfigureServices(services => { Utilities.EnsureLambdaServerRegistered(services); }); } } }
47
aws-lambda-dotnet
aws
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Runtime.CompilerServices; using System.Net; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features.Authentication; #pragma warning disable 1591 namespace Amazon.Lambda.AspNetCoreServer.Internal { public class InvokeFeatures : IFeatureCollection, IItemsFeature, IHttpAuthenticationFeature, IHttpRequestFeature, IHttpResponseFeature, IHttpConnectionFeature, IServiceProvidersFeature, ITlsConnectionFeature, IHttpRequestIdentifierFeature, IHttpResponseBodyFeature #if NET6_0_OR_GREATER ,IHttpRequestBodyDetectionFeature ,IHttpActivityFeature #endif /* , IHttpUpgradeFeature, IHttpRequestLifetimeFeature*/ { private volatile int _containerRevision; public InvokeFeatures() { this[typeof(IItemsFeature)] = this; this[typeof(IHttpAuthenticationFeature)] = this; this[typeof(IHttpRequestFeature)] = this; this[typeof(IHttpResponseFeature)] = this; this[typeof(IHttpConnectionFeature)] = this; this[typeof(IServiceProvidersFeature)] = this; this[typeof(ITlsConnectionFeature)] = this; this[typeof(IHttpResponseBodyFeature)] = this; this[typeof(IHttpRequestIdentifierFeature)] = this; #if NET6_0_OR_GREATER this[typeof(IHttpRequestBodyDetectionFeature)] = this; this[typeof(IHttpActivityFeature)] = this; #endif } #region IFeatureCollection public bool IsReadOnly => false; IDictionary<Type, object> _features = new Dictionary<Type, object>(); public int Revision => _containerRevision; public object this[Type key] { get { object feature; if (_features.TryGetValue(key, out feature)) { return feature; } return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { if (_features != null && _features.Remove(key)) { _containerRevision++; } return; } if (_features == null) { _features = new Dictionary<Type, object>(); } _features[key] = value; _containerRevision++; } } public TFeature Get<TFeature>() { object feature; if (_features.TryGetValue(typeof(TFeature), out feature)) { return (TFeature)feature; } return default(TFeature); } public IEnumerator<KeyValuePair<Type, object>> GetEnumerator() { return this._features.GetEnumerator(); } public void Set<TFeature>(TFeature instance) { if (instance == null) return; this._features[typeof(TFeature)] = instance; } IEnumerator IEnumerable.GetEnumerator() { return this._features.GetEnumerator(); } #endregion #region IItemsFeature IDictionary<object, object> IItemsFeature.Items { get; set; } #endregion #region IHttpAuthenticationFeature ClaimsPrincipal IHttpAuthenticationFeature.User { get; set; } #endregion #region IHttpRequestFeature string IHttpRequestFeature.Protocol { get; set; } string IHttpRequestFeature.Scheme { get; set; } string IHttpRequestFeature.Method { get; set; } string IHttpRequestFeature.PathBase { get; set; } string IHttpRequestFeature.Path { get; set; } string IHttpRequestFeature.QueryString { get; set; } string IHttpRequestFeature.RawTarget { get; set; } IHeaderDictionary IHttpRequestFeature.Headers { get; set; } = new HeaderDictionary(); Stream IHttpRequestFeature.Body { get; set; } = new MemoryStream(); #endregion #region IHttpResponseFeature int IHttpResponseFeature.StatusCode { get; set; } = 200; string IHttpResponseFeature.ReasonPhrase { get; set; } bool IHttpResponseFeature.HasStarted { get; } IHeaderDictionary IHttpResponseFeature.Headers { get; set; } = new HeaderDictionary(); Stream IHttpResponseFeature.Body { get; set; } = new MemoryStream(); internal EventCallbacks ResponseStartingEvents { get; private set; } void IHttpResponseFeature.OnStarting(Func<object, Task> callback, object state) { if (ResponseStartingEvents == null) this.ResponseStartingEvents = new EventCallbacks(); this.ResponseStartingEvents.Add(callback, state); } internal EventCallbacks ResponseCompletedEvents { get; private set; } void IHttpResponseFeature.OnCompleted(Func<object, Task> callback, object state) { if (this.ResponseCompletedEvents == null) this.ResponseCompletedEvents = new EventCallbacks(); this.ResponseCompletedEvents.Add(callback, state); } internal class EventCallbacks { List<EventCallback> _callbacks = new List<EventCallback>(); internal void Add(Func<object, Task> callback, object state) { this._callbacks.Add(new EventCallback(callback, state)); } internal async Task ExecuteAsync() { foreach(var callback in _callbacks) { await callback.ExecuteAsync(); } } internal class EventCallback { internal EventCallback(Func<object, Task> callback, object state) { this.Callback = callback; this.State = state; } Func<object, Task> Callback { get; } object State { get; } internal Task ExecuteAsync() { var task = Callback(this.State); return task; } } } #endregion #region IHttpResponseBodyFeature Stream IHttpResponseBodyFeature.Stream => ((IHttpResponseFeature)this).Body; private PipeWriter _pipeWriter; PipeWriter IHttpResponseBodyFeature.Writer { get { if (_pipeWriter == null) { _pipeWriter = PipeWriter.Create(((IHttpResponseBodyFeature) this).Stream); } return _pipeWriter; } } Task IHttpResponseBodyFeature.CompleteAsync() { return Task.CompletedTask; } void IHttpResponseBodyFeature.DisableBuffering() { } // This code is taken from the Apache 2.0 licensed ASP.NET Core repo. // https://github.com/aspnet/AspNetCore/blob/ab02951b37ac0cb09f8f6c3ed0280b46d89b06e0/src/Http/Http/src/SendFileFallback.cs async Task IHttpResponseBodyFeature.SendFileAsync( string filePath, long offset, long? count, CancellationToken cancellationToken) { var fileInfo = new FileInfo(filePath); if (offset < 0 || offset > fileInfo.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty); } if (count.HasValue && (count.Value < 0 || count.Value > fileInfo.Length - offset)) { throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty); } cancellationToken.ThrowIfCancellationRequested(); int bufferSize = 1024 * 16; var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: bufferSize, options: FileOptions.Asynchronous | FileOptions.SequentialScan); using (fileStream) { fileStream.Seek(offset, SeekOrigin.Begin); await Utilities.CopyToAsync(fileStream, ((IHttpResponseBodyFeature)this).Stream, count, bufferSize, cancellationToken); } } Task IHttpResponseBodyFeature.StartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } #endregion #region IHttpConnectionFeature string IHttpConnectionFeature.ConnectionId { get; set; } IPAddress IHttpConnectionFeature.RemoteIpAddress { get; set; } IPAddress IHttpConnectionFeature.LocalIpAddress { get; set; } int IHttpConnectionFeature.RemotePort { get; set; } int IHttpConnectionFeature.LocalPort { get; set; } #endregion #region IServiceProvidersFeature IServiceProvider IServiceProvidersFeature.RequestServices { get; set; } #endregion #region ITlsConnectionFeatures public Task<X509Certificate2> GetClientCertificateAsync(CancellationToken cancellationToken) { return Task.FromResult(ClientCertificate); } public X509Certificate2 ClientCertificate { get; set; } #endregion #region IHttpRequestIdentifierFeature string _traceIdentifier; string IHttpRequestIdentifierFeature.TraceIdentifier { get { if(_traceIdentifier != null) { return _traceIdentifier; } var lambdaTraceId = Environment.GetEnvironmentVariable("_X_AMZN_TRACE_ID"); if (!string.IsNullOrEmpty(lambdaTraceId)) { return lambdaTraceId; } // If there is no Lambda trace id then fallback to the trace id that ASP.NET Core would have generated. _traceIdentifier = (new Microsoft.AspNetCore.Http.Features.HttpRequestIdentifierFeature()).TraceIdentifier; return _traceIdentifier; } set { this._traceIdentifier = value; } } #endregion #if NET6_0_OR_GREATER bool IHttpRequestBodyDetectionFeature.CanHaveBody { get { var requestFeature = (IHttpRequestFeature)this; return requestFeature.Body != null; } } Activity IHttpActivityFeature.Activity { get; set; } #endif } }
403
aws-lambda-dotnet
aws
C#
// This code is copy of the Apache 2 License code from the ASP.NET Core Repo. This is used to provide an easier experience for // developers by not throwing KeyNotFoundException exceptions. // https://github.com/aspnet/AspNetCore/blob/ab02951b37ac0cb09f8f6c3ed0280b46d89b06e0/src/Http/Http/src/Internal/ItemsDictionary.cs using System.Collections; using System.Collections.Generic; namespace Amazon.Lambda.AspNetCoreServer.Internal { internal class ItemsDictionary : IDictionary<object, object> { private IDictionary<object, object> _items; public ItemsDictionary() { } public ItemsDictionary(IDictionary<object, object> items) { _items = items; } public IDictionary<object, object> Items => this; // Replace the indexer with one that returns null for missing values object IDictionary<object, object>.this[object key] { get { if (_items != null && _items.TryGetValue(key, out var value)) { return value; } return null; } set { EnsureDictionary(); _items[key] = value; } } void IDictionary<object, object>.Add(object key, object value) { EnsureDictionary(); _items.Add(key, value); } bool IDictionary<object, object>.ContainsKey(object key) => _items != null && _items.ContainsKey(key); ICollection<object> IDictionary<object, object>.Keys { get { if (_items == null) { return EmptyDictionary.Dictionary.Keys; } return _items.Keys; } } bool IDictionary<object, object>.Remove(object key) => _items != null && _items.Remove(key); bool IDictionary<object, object>.TryGetValue(object key, out object value) { value = null; return _items != null && _items.TryGetValue(key, out value); } ICollection<object> IDictionary<object, object>.Values { get { if (_items == null) { return EmptyDictionary.Dictionary.Values; } return _items.Values; } } void ICollection<KeyValuePair<object, object>>.Add(KeyValuePair<object, object> item) { EnsureDictionary(); _items.Add(item); } void ICollection<KeyValuePair<object, object>>.Clear() => _items?.Clear(); bool ICollection<KeyValuePair<object, object>>.Contains(KeyValuePair<object, object> item) => _items != null && _items.Contains(item); void ICollection<KeyValuePair<object, object>>.CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) { if (_items == null) { //Delegate to Empty Dictionary to do the argument checking. EmptyDictionary.Collection.CopyTo(array, arrayIndex); } _items.CopyTo(array, arrayIndex); } int ICollection<KeyValuePair<object, object>>.Count => _items?.Count ?? 0; bool ICollection<KeyValuePair<object, object>>.IsReadOnly => _items?.IsReadOnly ?? false; bool ICollection<KeyValuePair<object, object>>.Remove(KeyValuePair<object, object> item) { if (_items == null) { return false; } if (_items.TryGetValue(item.Key, out var value) && Equals(item.Value, value)) { return _items.Remove(item.Key); } return false; } private void EnsureDictionary() { if (_items == null) { _items = new Dictionary<object, object>(); } } IEnumerator<KeyValuePair<object, object>> IEnumerable<KeyValuePair<object, object>>.GetEnumerator() => _items?.GetEnumerator() ?? EmptyEnumerator.Instance; IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator() ?? EmptyEnumerator.Instance; private class EmptyEnumerator : IEnumerator<KeyValuePair<object, object>> { // In own class so only initalized if GetEnumerator is called on an empty ItemsDictionary public readonly static IEnumerator<KeyValuePair<object, object>> Instance = new EmptyEnumerator(); public KeyValuePair<object, object> Current => default; object IEnumerator.Current => null; public void Dispose() { } public bool MoveNext() => false; public void Reset() { } } private static class EmptyDictionary { // In own class so only initalized if CopyTo is called on an empty ItemsDictionary public readonly static IDictionary<object, object> Dictionary = new Dictionary<object, object>(); public static ICollection<KeyValuePair<object, object>> Collection => Dictionary; } } }
167
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; namespace Amazon.Lambda.AspNetCoreServer.Internal { /// <summary> /// Implements the ASP.NET Core IServer interface and exposes the application object for the Lambda function /// to initiate a web request. /// </summary> public class LambdaServer : IServer { /// <summary> /// The application is used by the Lambda function to initiate a web request through the ASP.NET Core framework. /// </summary> public ApplicationWrapper Application { get; set; } public IFeatureCollection Features { get; } = new FeatureCollection(); public void Dispose() { } public virtual Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) { this.Application = new ApplicationWrapper<TContext>(application); return Task.CompletedTask; } public virtual Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public abstract class ApplicationWrapper { internal abstract object CreateContext(IFeatureCollection features); internal abstract Task ProcessRequestAsync(object context); internal abstract void DisposeContext(object context, Exception exception); } public class ApplicationWrapper<TContext> : ApplicationWrapper, IHttpApplication<TContext> { private readonly IHttpApplication<TContext> _application; public ApplicationWrapper(IHttpApplication<TContext> application) { _application = application; } internal override object CreateContext(IFeatureCollection features) { return ((IHttpApplication<TContext>)this).CreateContext(features); } TContext IHttpApplication<TContext>.CreateContext(IFeatureCollection features) { return _application.CreateContext(features); } internal override void DisposeContext(object context, Exception exception) { ((IHttpApplication<TContext>)this).DisposeContext((TContext)context, exception); } void IHttpApplication<TContext>.DisposeContext(TContext context, Exception exception) { _application.DisposeContext(context, exception); } internal override Task ProcessRequestAsync(object context) { return ((IHttpApplication<TContext>)this).ProcessRequestAsync((TContext)context); } Task IHttpApplication<TContext>.ProcessRequestAsync(TContext context) { return _application.ProcessRequestAsync(context); } } } }
90
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; namespace Amazon.Lambda.AspNetCoreServer.Internal { /// <summary> /// /// </summary> public static class Utilities { public static void EnsureLambdaServerRegistered(IServiceCollection services) { EnsureLambdaServerRegistered(services, typeof(LambdaServer)); } public static void EnsureLambdaServerRegistered(IServiceCollection services, Type serverType) { IList<ServiceDescriptor> toRemove = new List<ServiceDescriptor>(); var serviceDescriptions = services.Where(x => x.ServiceType == typeof(IServer)); int lambdaServiceCount = 0; // There can be more then one IServer implementation registered if the consumer called ConfigureWebHostDefaults in the Init override for the IHostBuilder. // This makes sure there is only one registered IServer using LambdaServer and removes any other registrations. foreach (var serviceDescription in serviceDescriptions) { if (serviceDescription.ImplementationType == serverType) { lambdaServiceCount++; // If more then one LambdaServer registration has occurred then remove the extra registrations. if (lambdaServiceCount > 1) { toRemove.Add(serviceDescription); } } // If there is an IServer registered that isn't LambdaServer then remove it. This is most likely caused // by leaving the UseKestrel call. else { toRemove.Add(serviceDescription); } } foreach (var serviceDescription in toRemove) { services.Remove(serviceDescription); } if (lambdaServiceCount == 0) { services.AddSingleton(typeof(IServer), serverType); } } internal static Stream ConvertLambdaRequestBodyToAspNetCoreBody(string body, bool isBase64Encoded) { Byte[] binaryBody; if (isBase64Encoded) { binaryBody = Convert.FromBase64String(body); } else { binaryBody = UTF8Encoding.UTF8.GetBytes(body); } return new MemoryStream(binaryBody); } internal static (string body, bool isBase64Encoded) ConvertAspNetCoreBodyToLambdaBody(Stream aspNetCoreBody, ResponseContentEncoding rcEncoding) { // Do we encode the response content in Base64 or treat it as UTF-8 if (rcEncoding == ResponseContentEncoding.Base64) { // We want to read the response content "raw" and then Base64 encode it byte[] bodyBytes; if (aspNetCoreBody is MemoryStream) { bodyBytes = ((MemoryStream)aspNetCoreBody).ToArray(); } else { using (var ms = new MemoryStream()) { aspNetCoreBody.CopyTo(ms); bodyBytes = ms.ToArray(); } } return (body: Convert.ToBase64String(bodyBytes), isBase64Encoded: true); } else if (aspNetCoreBody is MemoryStream) { return (body: UTF8Encoding.UTF8.GetString(((MemoryStream)aspNetCoreBody).ToArray()), isBase64Encoded: false); } else { aspNetCoreBody.Position = 0; using (StreamReader reader = new StreamReader(aspNetCoreBody, Encoding.UTF8)) { return (body: reader.ReadToEnd(), isBase64Encoded: false); } } } /// <summary> /// Add a '?' to the start of a non-empty query string, otherwise return null. /// </summary> /// <remarks> /// The ASP.NET MVC pipeline expects the query string to be URL-escaped. Since the value in /// <see cref="APIGatewayHttpApiV2ProxyRequest.RawQueryString"/> should already be escaped this /// method does not perform any escaping itself. This ensures identical behaviour when an MVC app /// is run through an API Gateway with this framework or in a standalone Kestrel instance. /// </remarks> /// <param name="queryString">URL-escaped query string without initial '?'</param> /// <returns></returns> public static string CreateQueryStringParametersFromHttpApiV2(string queryString) { if (string.IsNullOrEmpty(queryString)) return null; return "?" + queryString; } internal static string CreateQueryStringParameters(IDictionary<string, string> singleValues, IDictionary<string, IList<string>> multiValues, bool urlEncodeValue) { if (multiValues?.Count > 0) { StringBuilder sb = new StringBuilder("?"); foreach (var kvp in multiValues) { foreach (var value in kvp.Value) { if (sb.Length > 1) { sb.Append("&"); } sb.Append($"{kvp.Key}={(urlEncodeValue ? WebUtility.UrlEncode(value) : value)}"); } } return sb.ToString(); } else if (singleValues?.Count > 0) { var queryStringParameters = singleValues; if (queryStringParameters != null && queryStringParameters.Count > 0) { StringBuilder sb = new StringBuilder("?"); foreach (var kvp in singleValues) { if (sb.Length > 1) { sb.Append("&"); } sb.Append($"{kvp.Key}={(urlEncodeValue ? WebUtility.UrlEncode(kvp.Value) : kvp.Value)}"); } return sb.ToString(); } } return string.Empty; } internal static void SetHeadersCollection(IHeaderDictionary headers, IDictionary<string, string> singleValues, IDictionary<string, IList<string>> multiValues) { if (multiValues?.Count > 0) { foreach (var kvp in multiValues) { headers[kvp.Key] = new StringValues(kvp.Value.ToArray()); } } else if (singleValues?.Count > 0) { foreach (var kvp in singleValues) { headers[kvp.Key] = new StringValues(kvp.Value); } } } // This code is taken from the Apache 2.0 licensed ASP.NET Core repo. // https://github.com/aspnet/AspNetCore/blob/d7bfbb5824b5f8876bcd4afaa29a611efc7aa1c9/src/Http/Shared/StreamCopyOperationInternal.cs internal static async Task CopyToAsync(Stream source, Stream destination, long? count, int bufferSize, CancellationToken cancel) { long? bytesRemaining = count; var buffer = ArrayPool<byte>.Shared.Rent(bufferSize); try { Debug.Assert(source != null); Debug.Assert(destination != null); Debug.Assert(!bytesRemaining.HasValue || bytesRemaining.GetValueOrDefault() >= 0); Debug.Assert(buffer != null); while (true) { // The natural end of the range. if (bytesRemaining.HasValue && bytesRemaining.GetValueOrDefault() <= 0) { return; } cancel.ThrowIfCancellationRequested(); int readLength = buffer.Length; if (bytesRemaining.HasValue) { readLength = (int)Math.Min(bytesRemaining.GetValueOrDefault(), (long)readLength); } int read = await source.ReadAsync(buffer, 0, readLength, cancel); if (bytesRemaining.HasValue) { bytesRemaining -= read; } // End of the source stream. if (read == 0) { return; } cancel.ThrowIfCancellationRequested(); await destination.WriteAsync(buffer, 0, read, cancel); } } finally { ArrayPool<byte>.Shared.Return(buffer); } } internal static string DecodeResourcePath(string resourcePath) => WebUtility.UrlDecode(resourcePath // Convert any + signs to percent encoding before URL decoding the path. .Replace("+", "%2B") // Double-escape any %2F (encoded / characters) so that they survive URL decoding the path. .Replace("%2F", "%252F") .Replace("%2f", "%252f")); internal static X509Certificate2 GetX509Certificate2FromPem(string clientCertPem) { clientCertPem = clientCertPem.TrimEnd('\n'); if (!clientCertPem.StartsWith("-----BEGIN CERTIFICATE-----") || !clientCertPem.EndsWith("-----END CERTIFICATE-----")) { throw new InvalidOperationException( "Client certificate PEM was invalid. Expected to start with '-----BEGIN CERTIFICATE-----' " + "and end with '-----END CERTIFICATE-----'."); } // Remove "-----BEGIN CERTIFICATE-----\n" and "-----END CERTIFICATE-----" clientCertPem = clientCertPem.Substring(28, clientCertPem.Length - 53); return new X509Certificate2(Convert.FromBase64String(clientCertPem)); } } }
272
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.AspNetCoreServer")] [assembly: AssemblyDescription("Amazon.Lambda.AspNetCoreServer makes it easy to run ASP.NET Core Web API applications as AWS Lambda functions.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0")] [assembly: AssemblyFileVersion("2.0.4")]
12
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; namespace Amazon.Lambda.AspNetCoreServer.Hosting; /// <summary> /// Options for configuring AWS Lambda hosting for ASP.NET Core /// </summary> public class HostingOptions { /// <summary> /// The ILambdaSerializer used by Lambda to convert the incoming event JSON into the .NET event type and serialize the .NET response type /// back to JSON to return to Lambda. /// </summary> public ILambdaSerializer Serializer { get; set; } }
15
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer.Hosting; using Amazon.Lambda.AspNetCoreServer.Internal; using Amazon.Lambda.AspNetCoreServer.Hosting.Internal; using Amazon.Lambda.Core; using Amazon.Lambda.Serialization.SystemTextJson; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Enum for the possible event sources that will send HTTP request into the ASP.NET Core Lambda function. /// </summary> public enum LambdaEventSource { /// <summary> /// API Gateway REST API /// </summary> RestApi, /// <summary> /// API Gateway HTTP API /// </summary> HttpApi, /// <summary> /// ELB Application Load Balancer /// </summary> ApplicationLoadBalancer } /// <summary> /// Extension methods to IServiceCollection. /// </summary> public static class ServiceCollectionExtensions { /// <summary> /// Add the ability to run the ASP.NET Core Lambda function in AWS Lambda. If the project is not running in Lambda /// this method will do nothing allowing the normal Kestrel webserver to host the application. /// </summary> /// <param name="services"></param> /// <param name="eventSource"></param> /// <returns></returns> public static IServiceCollection AddAWSLambdaHosting(this IServiceCollection services, LambdaEventSource eventSource) { // Not running in Lambda so exit and let Kestrel be the web server return services.AddAWSLambdaHosting(eventSource, (Action<HostingOptions>?)null); } /// <summary> /// Add the ability to run the ASP.NET Core Lambda function in AWS Lambda. If the project is not running in Lambda /// this method will do nothing allowing the normal Kestrel webserver to host the application. /// </summary> /// <param name="services"></param> /// <param name="eventSource"></param> /// <param name="configure"></param> /// <returns></returns> public static IServiceCollection AddAWSLambdaHosting(this IServiceCollection services, LambdaEventSource eventSource, Action<HostingOptions>? configure = null) { // Not running in Lambda so exit and let Kestrel be the web server if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME"))) return services; var hostingOptions = new HostingOptions(); if (configure != null) configure.Invoke(hostingOptions); services.TryAddSingleton<ILambdaSerializer>(hostingOptions.Serializer ?? new DefaultLambdaJsonSerializer()); var serverType = eventSource switch { LambdaEventSource.HttpApi => typeof(APIGatewayHttpApiV2LambdaRuntimeSupportServer), LambdaEventSource.RestApi => typeof(APIGatewayRestApiLambdaRuntimeSupportServer), LambdaEventSource.ApplicationLoadBalancer => typeof(ApplicationLoadBalancerLambdaRuntimeSupportServer), _ => throw new ArgumentException($"Event source type {eventSource} unknown") }; Utilities.EnsureLambdaServerRegistered(services, serverType); return services; } } }
84
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer.Internal; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.Extensions.DependencyInjection; namespace Amazon.Lambda.AspNetCoreServer.Hosting.Internal { /// <summary> /// Subclass of Amazon.Lambda.AspNetCoreServer.LambdaServer that also starts /// up Amazon.Lambda.RuntimeSupport as part of the IServer startup. /// /// This is an abstract class with subclasses for each of the possible Lambda event sources. /// </summary> public abstract class LambdaRuntimeSupportServer : LambdaServer { IServiceProvider _serviceProvider; internal ILambdaSerializer Serializer; /// <summary> /// Creates an instance on the LambdaRuntimeSupportServer /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public LambdaRuntimeSupportServer(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; Serializer = serviceProvider.GetRequiredService<ILambdaSerializer>(); } /// <summary> /// Start Amazon.Lambda.RuntimeSupport to listen for Lambda events to be processed. /// </summary> /// <typeparam name="TContext"></typeparam> /// <param name="application"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) { base.StartAsync(application, cancellationToken); var handlerWrapper = CreateHandlerWrapper(_serviceProvider); var bootStrap = new LambdaBootstrap(handlerWrapper); return bootStrap.RunAsync(); } /// <summary> /// Abstract method that creates the HandlerWrapper that will be invoked for each Lambda event. /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> protected abstract HandlerWrapper CreateHandlerWrapper(IServiceProvider serviceProvider); } /// <summary> /// IServer for handlying Lambda events from an API Gateway HTTP API. /// </summary> public class APIGatewayHttpApiV2LambdaRuntimeSupportServer : LambdaRuntimeSupportServer { /// <summary> /// Create instances /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public APIGatewayHttpApiV2LambdaRuntimeSupportServer(IServiceProvider serviceProvider) : base(serviceProvider) { } /// <summary> /// Creates HandlerWrapper for processing events from API Gateway HTTP API /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> protected override HandlerWrapper CreateHandlerWrapper(IServiceProvider serviceProvider) { var handler = new APIGatewayHttpApiV2MinimalApi(serviceProvider).FunctionHandlerAsync; return HandlerWrapper.GetHandlerWrapper(handler, this.Serializer); } /// <summary> /// Create the APIGatewayHttpApiV2ProxyFunction passing in the ASP.NET Core application's IServiceProvider /// </summary> public class APIGatewayHttpApiV2MinimalApi : APIGatewayHttpApiV2ProxyFunction { /// <summary> /// Create instances /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public APIGatewayHttpApiV2MinimalApi(IServiceProvider serviceProvider) : base(serviceProvider) { } } } /// <summary> /// IServer for handlying Lambda events from an API Gateway REST API. /// </summary> public class APIGatewayRestApiLambdaRuntimeSupportServer : LambdaRuntimeSupportServer { /// <summary> /// Create instances /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public APIGatewayRestApiLambdaRuntimeSupportServer(IServiceProvider serviceProvider) : base(serviceProvider) { } /// <summary> /// Creates HandlerWrapper for processing events from API Gateway REST API /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> protected override HandlerWrapper CreateHandlerWrapper(IServiceProvider serviceProvider) { var handler = new APIGatewayRestApiMinimalApi(serviceProvider).FunctionHandlerAsync; return HandlerWrapper.GetHandlerWrapper(handler, this.Serializer); } /// <summary> /// Create the APIGatewayProxyFunction passing in the ASP.NET Core application's IServiceProvider /// </summary> public class APIGatewayRestApiMinimalApi : APIGatewayProxyFunction { /// <summary> /// Create instances /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public APIGatewayRestApiMinimalApi(IServiceProvider serviceProvider) : base(serviceProvider) { } } } /// <summary> /// IServer for handlying Lambda events from an Application Load Balancer. /// </summary> public class ApplicationLoadBalancerLambdaRuntimeSupportServer : LambdaRuntimeSupportServer { /// <summary> /// Create instances /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public ApplicationLoadBalancerLambdaRuntimeSupportServer(IServiceProvider serviceProvider) : base(serviceProvider) { } /// <summary> /// Creates HandlerWrapper for processing events from API Gateway REST API /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> protected override HandlerWrapper CreateHandlerWrapper(IServiceProvider serviceProvider) { var handler = new ApplicationLoadBalancerMinimalApi(serviceProvider).FunctionHandlerAsync; return HandlerWrapper.GetHandlerWrapper(handler, this.Serializer); } /// <summary> /// Create the ApplicationLoadBalancerFunction passing in the ASP.NET Core application's IServiceProvider /// </summary> public class ApplicationLoadBalancerMinimalApi : ApplicationLoadBalancerFunction { /// <summary> /// Create instances /// </summary> /// <param name="serviceProvider">The IServiceProvider created for the ASP.NET Core application</param> public ApplicationLoadBalancerMinimalApi(IServiceProvider serviceProvider) : base(serviceProvider) { } } } }
178
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents { using System; using System.Collections.Generic; /// <summary> /// AWS CloudWatch event /// The contents of the detail top-level field are different depending on which service generated the event and what the event is. /// The combination of the source and detail-type fields serves to identify the fields and values found in the detail field. /// Complete list of events that inherit this interface: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html /// https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html /// https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html /// </summary> public class CloudWatchEvent<T> { /// <summary> /// By default, this is set to 0 (zero) in all events. /// </summary> public string Version { get; set; } /// <summary> /// The 12-digit number identifying an AWS account. /// </summary> public string Account { get; set; } /// <summary> /// Identifies the AWS region where the event originated. /// </summary> public string Region { get; set; } /// <summary> /// A JSON object, whose content is at the discretion of the service originating the event. /// The detail content in the example above is very simple, just two fields. /// AWS API call events have detail objects with around 50 fields nested several levels deep. /// </summary> public T Detail { get; set; } /// <summary> /// Identifies, in combination with the source field, the fields and values that appear in the detail field. /// For example, ScheduledEvent will be null /// For example, ECSEvent could be "ECS Container Instance State Change" or "ECS Task State Change" /// </summary> #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("detail-type")] #endif public string DetailType { get; set; } /// <summary> /// Identifies the service that sourced the event. /// All events sourced from within AWS begin with "aws." /// Customer-generated events can have any value here, as long as it doesn't begin with "aws." /// We recommend the use of Java package-name style reverse domain-name strings. /// For example, ScheduledEvent will be "aws.events" /// For example, ECSEvent will be "aws.ecs" /// </summary> public string Source { get; set; } /// <summary> /// The event timestamp, which can be specified by the service originating the event. /// If the event spans a time interval, the service might choose to report the start time, /// so this value can be noticeably before the time the event is actually received. /// </summary> public DateTime Time { get; set; } /// <summary> /// A unique value is generated for every event. /// This can be helpful in tracing events as they move through rules to targets, and are processed. /// </summary> public string Id { get; set; } /// <summary> /// This JSON array contains ARNs that identify resources that are involved in the event. /// Inclusion of these ARNs is at the discretion of the service. /// For example, Amazon EC2 instance state-changes include Amazon EC2 instance ARNs, Auto Scaling events /// include ARNs for both instances and Auto Scaling groups, but API calls with AWS CloudTrail do not /// include resource ARNs. /// </summary> public List<string> Resources { get; set; } } }
81
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents { /// <summary> /// /// </summary> public class NameValue { /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// Value /// </summary> public string Value { get; set; } } }
19
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing the array properties of a job. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_ArrayPropertiesDetail.html /// </summary> public class ArrayPropertiesDetail { /// <summary> /// The job index within the array that is associated with this job. /// This parameter is returned for array job children. /// </summary> public int Index { get; set; } /// <summary> /// The size of the array job. This parameter is returned for parent array jobs. /// </summary> public int Size { get; set; } /// <summary> /// A summary of the number of array job children in each available job status. /// This parameter is returned for parent array jobs. /// </summary> public Dictionary<string, int> StatusSummary { get; set; } } }
28
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing the details of a container that is part of a job attempt. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_AttemptContainerDetail.html /// </summary> public class AttemptContainerDetail { /// <summary> /// The Amazon Resource Name (ARN) of the Amazon ECS container instance that hosts the job attempt. /// </summary> public string ContainerInstanceArn { get; set; } /// <summary> /// The exit code for the job attempt. A non-zero exit code is considered a failure. /// </summary> public int ExitCode { get; set; } /// <summary> /// The name of the CloudWatch Logs log stream associated with the container. The log group for /// AWS Batch jobs is /aws/batch/job. Each container attempt receives a log stream name when /// they reach the RUNNING status. /// </summary> public string LogStreamName { get; set; } /// <summary> /// Details about the network interfaces in this job attempt. /// </summary> public List<NetworkInterfaceDetail> NetworkInterfaces { get; set; } /// <summary> /// A short (255 max characters) human-readable string to provide additional /// details about a running or stopped container. /// </summary> public string Reason { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the Amazon ECS task that is associated with the job attempt. /// Each container attempt receives a task ARN when they reach the STARTING status. /// </summary> public string TaskArn { get; set; } } }
45
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing a job attempt. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_AttemptDetail.html /// </summary> public class AttemptDetail { /// <summary> /// Details about the container in this job attempt. /// </summary> public AttemptContainerDetail Container { get; set; } /// <summary> /// The Unix time stamp (in seconds and milliseconds) for when the attempt was started /// (when the attempt transitioned from the STARTING state to the RUNNING state). /// </summary> public long StartedAt { get; set; } /// <summary> /// A short, human-readable string to provide additional details about the current status of the job attempt. /// </summary> public string StatusReason { get; set; } /// <summary> /// The Unix time stamp (in seconds and milliseconds) for when the attempt was stopped /// (when the attempt transitioned from the RUNNING state to a terminal state, such as SUCCEEDED or FAILED). /// </summary> public long StoppedAt { get; set; } } }
31
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// AWS Batch Event /// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html /// </summary> public class BatchJobStateChangeEvent : CloudWatchEvent<Job> { } }
11
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing the details of a container that is part of a job. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_ContainerDetail.html /// </summary> public class ContainerDetail { /// <summary> /// The command that is passed to the container. /// </summary> public List<string> Command { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the container instance on which the container is running. /// </summary> public string ContainerInstanceArn { get; set; } /// <summary> /// The environment variables to pass to a container. /// Note: Environment variables must not start with AWS_BATCH; this naming convention is reserved /// for variables that are set by the AWS Batch service. /// </summary> public List<NameValue> Environment { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the execution role that AWS Batch can assume. /// </summary> public string ExecutionRoleArn { get; set; } /// <summary> /// The exit code to return upon completion. /// </summary> public int ExitCode { get; set; } /// <summary> /// The platform configuration for jobs that are running on Fargate resources. Jobs that are running on EC2 resources must not specify this parameter. /// </summary> public FargatePlatformConfiguration FargatePlatformConfiguration { get; set; } /// <summary> /// The image used to start the container. /// </summary> public string Image { get; set; } /// <summary> /// The instance type executing the container. /// </summary> public string InstanceType { get; set; } /// <summary> /// The Amazon Resource Name (ARN) associated with the job upon execution. /// </summary> public string JobRoleArn { get; set; } /// <summary> /// Linux-specific modifications that are applied to the container, such as details for device mappings. /// </summary> public LinuxParameters LinuxParameters { get; set; } /// <summary> /// The log configuration specification for the container. /// </summary> public LogConfiguration LogConfiguration { get; set; } /// <summary> /// The name of the CloudWatch Logs log stream associated with the container. /// The log group for AWS Batch jobs is /aws/batch/job. Each container attempt receives a /// log stream name when they reach the RUNNING status. /// </summary> public string LogStreamName { get; set; } /// <summary> /// The number of MiB of memory reserved for the job. /// </summary> public int Memory { get; set; } /// <summary> /// The mount points for data volumes in your container. /// </summary> public List<MountPoint> MountPoints { get; set; } /// <summary> /// The network configuration for jobs that are running on Fargate resources. Jobs that are running on EC2 resources must not specify this parameter. /// </summary> public NetworkConfiguration NetworkConfiguration { get; set; } /// <summary> /// Details about the network interfaces in your container. /// </summary> public List<NetworkInterfaceDetail> NetworkInterfaces { get; set; } /// <summary> /// When this parameter is true, the container is given elevated privileges on the /// host container instance (similar to the root user). /// </summary> public bool Privileged { get; set; } /// <summary> /// When this parameter is true, the container is given read-only access to its root file system. /// </summary> public bool ReadonlyRootFilesystem { get; set; } /// <summary> /// A short (255 max characters) human-readable string to provide additional /// details about a running or stopped container. /// </summary> public string Reason { get; set; } /// <summary> /// The type and amount of resources to assign to a container. The supported resources include <c>GPU</c>, <c>MEMORY</c>, and <c>VCPU</c>. /// </summary> public List<ResourceRequirement> ResourceRequirements { get; set; } /// <summary> /// The secrets to pass to the container. For more information, see <see href="https://docs.aws.amazon.com/batch/latest/userguide/specifying-sensitive-data.html">Specifying sensitive data</see> in the <i>AWS Batch User Guide</i>. /// </summary> public List<Secret> Secrets { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the Amazon ECS task that is associated with the container job. /// Each container attempt receives a task ARN when they reach the STARTING status. /// </summary> public string TaskArn { get; set; } /// <summary> /// A list of ulimit values to set in the container. /// </summary> public List<Ulimit> Ulimits { get; set; } /// <summary> /// The user name to use inside the container. /// </summary> public string User { get; set; } /// <summary> /// The number of VCPUs allocated for the job. /// </summary> public int Vcpus { get; set; } /// <summary> /// A list of volumes associated with the job. /// </summary> public List<Volume> Volumes { get; set; } } }
148
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// Container properties are used in job definitions to describe the container that's launched as part of a job. /// </summary> public class ContainerProperties { /// <summary> /// The command that is passed to the container. /// </summary> public List<string> Command { get; set; } /// <summary> /// The environment variables to pass to a container. /// Note: Environment variables must not start with AWS_BATCH; this naming convention is reserved /// for variables that are set by the AWS Batch service. /// </summary> public List<NameValue> Environment { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the execution role that AWS Batch can assume. /// </summary> public string ExecutionRoleArn { get; set; } /// <summary> /// The platform configuration for jobs that are running on Fargate resources. Jobs that are running on EC2 resources must not specify this parameter. /// </summary> public FargatePlatformConfiguration FargatePlatformConfiguration { get; set; } /// <summary> /// The image used to start the container. /// </summary> public string Image { get; set; } /// <summary> /// The instance type executing the container. /// </summary> public string InstanceType { get; set; } /// <summary> /// The Amazon Resource Name (ARN) associated with the job upon execution. /// </summary> public string JobRoleArn { get; set; } /// <summary> /// Linux-specific modifications that are applied to the container, such as details for device mappings. /// </summary> public LinuxParameters LinuxParameters { get; set; } /// <summary> /// The log configuration specification for the container. /// </summary> public LogConfiguration LogConfiguration { get; set; } /// <summary> /// The number of MiB of memory reserved for the job. /// </summary> public int Memory { get; set; } /// <summary> /// The mount points for data volumes in your container. /// </summary> public List<MountPoint> MountPoints { get; set; } /// <summary> /// The network configuration for jobs that are running on Fargate resources. Jobs that are running on EC2 resources must not specify this parameter. /// </summary> public NetworkConfiguration NetworkConfiguration { get; set; } /// <summary> /// When this parameter is true, the container is given elevated privileges on the /// host container instance (similar to the root user). /// </summary> public bool Privileged { get; set; } /// <summary> /// When this parameter is true, the container is given read-only access to its root file system. /// </summary> public bool ReadonlyRootFilesystem { get; set; } /// <summary> /// The type and amount of resources to assign to a container. The supported resources include <c>GPU</c>, <c>MEMORY</c>, and <c>VCPU</c>. /// </summary> public List<ResourceRequirement> ResourceRequirements { get; set; } /// <summary> /// The secrets to pass to the container. For more information, see <see href="https://docs.aws.amazon.com/batch/latest/userguide/specifying-sensitive-data.html">Specifying sensitive data</see> in the <i>AWS Batch User Guide</i>. /// </summary> public List<Secret> Secrets { get; set; } /// <summary> /// A list of ulimit values to set in the container. /// </summary> public List<Ulimit> Ulimits { get; set; } /// <summary> /// The user name to use inside the container. /// </summary> public string User { get; set; } /// <summary> /// The number of VCPUs allocated for the job. /// </summary> public int Vcpus { get; set; } /// <summary> /// A list of volumes associated with the job. /// </summary> public List<Volume> Volumes { get; set; } } }
114
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing a container instance host device. /// </summary> public class Device { /// <summary> /// The path inside the container that's used to expose the host device. By default, the hostPath value is used. /// </summary> public string ContainerPath { get; set; } /// <summary> /// The path for the device on the host container instance. /// </summary> public string HostPath { get; set; } /// <summary> /// The explicit permissions to provide to the container for the device. By default, the container has permissions for read, write, and mknod for the device. /// </summary> public List<string> Permissions { get; set; } } }
28
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The authorization configuration details for the Amazon EFS file system. /// </summary> public class EFSAuthorizationConfig { /// <summary> /// The Amazon EFS access point ID to use. If an access point is specified, the root directory value specified in the <c>EFSVolumeConfiguration</c> must either be omitted or set to <c>/</c> which will enforce the path set on the EFS access point. /// If an access point is used, transit encryption must be enabled in the <c>EFSVolumeConfiguration</c>. /// </summary> public string AccessPointId { get; set; } /// <summary> /// Whether or not to use the AWS Batch job IAM role defined in a job definition when mounting the Amazon EFS file system. If enabled, transit encryption must be enabled in the <c>EFSVolumeConfiguration</c>. /// If this parameter is omitted, the default value of <c>DISABLED</c> is used. /// </summary> public string Iam { get; set; } } }
21
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// This is used when you're using an Amazon Elastic File System file system for job storage. For more information, see <see href="https://docs.aws.amazon.com/batch/latest/userguide/efs-volumes.html">Amazon EFS Volumes</see> in the <i>AWS Batch User Guide</i>. /// </summary> public class EFSVolumeConfiguration { /// <summary> /// The authorization configuration details for the Amazon EFS file system. /// </summary> public EFSAuthorizationConfig AuthorizationConfig { get; set; } /// <summary> /// The Amazon EFS file system ID to use. /// </summary> public string FileSystemId { get; set; } /// <summary> /// The directory within the Amazon EFS file system to mount as the root directory inside the host. If this parameter is omitted, the root of the Amazon EFS volume is used instead. /// Specifying <c>/</c> has the same effect as omitting this parameter. The maximum length is 4,096 characters. /// </summary> public string RootDirectory { get; set; } /// <summary> /// Determines whether to enable encryption for Amazon EFS data in transit between the Amazon ECS host and the Amazon EFS server. /// Transit encryption must be enabled if Amazon EFS IAM authorization is used. If this parameter is omitted, the default value of <c>DISABLED</c> is used. /// </summary> public string TransitEncryption { get; set; } /// <summary> /// The port to use when sending encrypted data between the Amazon ECS host and the Amazon EFS server. /// If you don't specify a transit encryption port, it uses the port selection strategy that the Amazon EFS mount helper uses. /// The value must be between 0 and 65,535. /// </summary> public int TransitEncryptionPort { get; set; } } }
42
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// Specifies a set of conditions to be met, and an action to take (<c>RETRY</c> or <c>EXIT</c>) if all conditions are met. /// </summary> public class EvaluateOnExit { /// <summary> /// Specifies the action to take if all of the specified conditions (<c>onStatusReason</c>, <c>onReason</c>, and <c>onExitCode</c>) are met. The values aren't case sensitive. /// </summary> public string Action { get; set; } /// <summary> /// Contains a glob pattern to match against the decimal representation of the <c>ExitCode</c> returned for a job. The pattern can be up to 512 characters in length. /// It can contain only numbers, and can optionally end with an asterisk (*) so that only the start of the string needs to be an exact match. /// </summary> public string OnExitCode { get; set; } /// <summary> /// Contains a glob pattern to match against the <c>Reason</c> returned for a job. The pattern can be up to 512 characters in length. /// It can contain letters, numbers, periods (.), colons (:), and white space (including spaces and tabs). /// It can optionally end with an asterisk (*) so that only the start of the string needs to be an exact match. /// </summary> public string OnReason { get; set; } /// <summary> /// Contains a glob pattern to match against the <c>StatusReason</c> returned for a job. The pattern can be up to 512 characters in length. /// It can contain letters, numbers, periods (.), colons (:), and white space (including spaces or tabs). /// It can optionally end with an asterisk (*) so that only the start of the string needs to be an exact match. /// </summary> public string OnStatusReason { get; set; } } }
34
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The platform configuration for jobs that are running on Fargate resources. Jobs that run on EC2 resources must not specify this parameter. /// </summary> public class FargatePlatformConfiguration { /// <summary> /// The AWS Fargate platform version where the jobs are running. A platform version is specified only for jobs that are running on Fargate resources. /// If one isn't specified, the LATEST platform version is used by default. This uses a recent, approved version of the AWS Fargate platform for compute resources. /// </summary> public string PlatformVersion { get; set; } } }
15
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The contents of the host parameter determine whether your data volume persists on the host container /// instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host /// path for your data volume, but the data is not guaranteed to persist after the containers associated with /// it stop running. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_Host.html /// </summary> public class Host { /// <summary> /// The path on the host container instance that is presented to the container. If this parameter is empty, /// then the Docker daemon has assigned a host path for you. If the host parameter contains a sourcePath file /// location, then the data volume persists at the specified location on the host container instance until you /// delete it manually. If the sourcePath value does not exist on the host container instance, the Docker /// daemon creates it. If the location does exist, the contents of the source path folder are exported. /// </summary> public string SourcePath { get; set; } } }
21
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobDetail.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html /// </summary> public class Job { /// <summary> /// The array properties of the job, if it is an array job. /// </summary> public ArrayPropertiesDetail ArrayProperties { get; set; } /// <summary> /// A list of job attempts associated with this job. /// </summary> public List<AttemptDetail> Attempts { get; set; } /// <summary> /// An object representing the details of the container that is associated with the job. /// </summary> public ContainerDetail Container { get; set; } /// <summary> /// The Unix time stamp (in seconds and milliseconds) for when the job was created. For non-array /// jobs and parent array jobs, this is when the job entered the SUBMITTED state /// (at the time SubmitJob was called). For array child jobs, this is when the child job was /// spawned by its parent and entered the PENDING state. /// </summary> public long CreatedAt { get; set; } /// <summary> /// A list of job names or IDs on which this job depends. /// </summary> public List<JobDependency> DependsOn { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the job. /// </summary> public string JobArn { get; set; } /// <summary> /// The job definition that is used by this job. /// </summary> public string JobDefinition { get; set; } /// <summary> /// The ID for the job. /// </summary> public string JobId { get; set; } /// <summary> /// The name of the job. /// </summary> public string JobName { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the job queue with which the job is associated. /// </summary> public string JobQueue { get; set; } /// <summary> /// An object representing the details of a node that is associated with a multi-node /// parallel job. /// </summary> public NodeDetails NodeDetails { get; set; } /// <summary> /// An object representing the node properties of a multi-node parallel job. /// </summary> public NodeProperties NodeProperties { get; set; } /// <summary> /// Additional parameters passed to the job that replace parameter substitution placeholders or /// override any corresponding parameter defaults from the job definition. /// </summary> public Dictionary<string, string> Parameters { get; set; } /// <summary> /// The platform capabilities required by the job definition. If no value is specified, it defaults to <c>EC2</c>. Jobs run on Fargate resources specify <c>FARGATE</c>. /// </summary> public List<string> PlatformCapabilities { get; set; } /// <summary> /// Specifies whether to propagate the tags from the job or job definition to the corresponding Amazon ECS task. If no value is specified, the tags aren't propagated. /// Tags can only be propagated to the tasks during task creation. For tags with the same name, job tags are given priority over job definitions tags. /// If the total number of combined tags from the job and job definition is over 50, the job is moved to the <c>FAILED</c> state. /// </summary> public bool PropagateTags { get; set; } /// <summary> /// The retry strategy to use for this job if an attempt fails. /// </summary> public RetryStrategy RetryStrategy { get; set; } /// <summary> /// The Unix time stamp (in seconds and milliseconds) for when the job was started (when the job /// transitioned from the STARTING state to the RUNNING state). /// </summary> public long StartedAt { get; set; } /// <summary> /// The current status for the job. Note: If your jobs do not progress to STARTING, see Jobs Stuck /// in RUNNABLE Status in the troubleshooting section of the AWS Batch User Guide. /// </summary> public string Status { get; set; } /// <summary> /// A short, human-readable string to provide additional details about the current status of the job. /// </summary> public string StatusReason { get; set; } /// <summary> /// The Unix time stamp (in seconds and milliseconds) for when the job was stopped (when the /// job transitioned from the RUNNING state to a terminal state, such as SUCCEEDED or FAILED). /// </summary> public long StoppedAt { get; set; } /// <summary> /// The tags applied to the job. /// </summary> public Dictionary<string, string> Tags { get; set; } /// <summary> /// The timeout configuration for the job. /// </summary> public JobTimeout Timeout { get; set; } } }
132
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing an AWS Batch job dependency. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobDependency.html /// </summary> public class JobDependency { /// <summary> /// The job ID of the AWS Batch job associated with this dependency. /// </summary> public string JobId { get; set; } /// <summary> /// The type of the job dependency. /// </summary> public string Type { get; set; } } }
19
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing a job timeout configuration. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobTimeout.html /// </summary> public class JobTimeout { /// <summary> /// The time duration in seconds (measured from the job attempt's startedAt timestamp) after which /// AWS Batch terminates your jobs if they have not finished. /// </summary> public int AttemptDurationSeconds { get; set; } } }
15
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// Linux-specific modifications that are applied to the container, such as details for device mappings. /// </summary> public class LinuxParameters { /// <summary> /// Any host devices to expose to the container. This parameter maps to <c>Devices</c> in the /// <see href="https://docs.docker.com/engine/api/v1.23/#create-a-container">Create a container</see> /// section of the Docker Remote API and the <c>--device</c> option to <see href="https://docs.docker.com/engine/reference/run/">docker run</see>. /// </summary> public List<Device> Devices { get; set; } /// <summary> /// If true, run an <c>init</c> process inside the container that forwards signals and reaps processes. /// This parameter maps to the <c>--init</c> option to <see href="https://docs.docker.com/engine/reference/run/">docker run</see>. /// This parameter requires version 1.25 of the Docker Remote API or greater on your container instance. /// To check the Docker Remote API version on your container instance, log into your container instance and run the following command: /// <c>sudo docker version | grep "Server API version"</c> /// </summary> public bool InitProcessEnabled { get; set; } /// <summary> /// <para>The total amount of swap memory (in MiB) a container can use. This parameter is translated to the <c>--memory-swap</c> option to /// <see href="https://docs.docker.com/engine/reference/run/">docker run</see> where the value is the sum of the container memory plus the <c>maxSwap</c> value. /// For more information, see <see href="https://docs.docker.com/config/containers/resource_constraints/#--memory-swap-details"><c>--memory-swap</c> details</see> in the Docker documentation. /// </para> /// <para>If a <c>maxSwap</c> value of <c>0</c> is specified, the container doesn't use swap. Accepted values are <c>0</c> or any positive integer. /// If the <c>maxSwap</c> parameter is omitted, the container doesn't use the swap configuration for the container instance it is running on. A <c>maxSwap</c> /// value must be set for the <c>swappiness</c> parameter to be used. /// </para> /// </summary> public int MaxSwap { get; set; } /// <summary> /// The value for the size (in MiB) of the <c>/dev/shm</c> volume. This parameter maps to the <c>--shm-size</c> option to <see href="https://docs.docker.com/engine/reference/run/">docker run</see>. /// </summary> public int SharedMemorySize { get; set; } /// <summary> /// This allows you to tune a container's memory swappiness behavior. A <c>swappiness</c> value of <c>0</c> causes swapping not to happen unless absolutely necessary. /// A <c>swappiness</c> value of <c>100</c> causes pages to be swapped very aggressively. Accepted values are whole numbers between <c>0</c> and <c>100</c>. /// If the <c>swappiness</c> parameter isn't specified, a default value of <c>60</c> is used. If a value isn't specified for <c>maxSwap</c>, then this parameter is ignored. /// If <c>maxSwap</c> is set to 0, the container doesn't use swap. This parameter maps to the <c>--memory-swappiness</c> option to <see href="https://docs.docker.com/engine/reference/run/">docker run</see>. /// </summary> public int Swappiness { get; set; } /// <summary> /// The container path, mount options, and size (in MiB) of the tmpfs mount. This parameter maps to the <c>--tmpfs</c> option to <see href="https://docs.docker.com/engine/reference/run/">docker run</see>. /// </summary> public List<Tmpfs> Tmpfs { get; set; } } }
57
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// Log configuration options to send to a custom log driver for the container. /// </summary> public class LogConfiguration { /// <summary> /// <para>The log driver to use for the container. The valid values listed for this parameter are log drivers that the Amazon ECS container agent can communicate with by default.</para> /// <para>The supported log drivers are <c>awslogs</c>, <c>fluentd</c>, <c>gelf</c>, <c>json-file</c>, <c>journald</c>, <c>logentries</c>, <c>syslog</c>, and <c>splunk</c>.</para> /// </summary> public string LogDriver { get; set; } /// <summary> /// The configuration options to send to the log driver. This parameter requires version 1.19 of the Docker Remote API or greater on your container instance. /// To check the Docker Remote API version on your container instance, log into your container instance and run the following command: <c>sudo docker version | grep "Server API version"</c> /// </summary> public Dictionary<string, string> Options { get; set; } /// <summary> /// The secrets to pass to the log configuration. For more information, see <see href="https://docs.aws.amazon.com/batch/latest/userguide/specifying-sensitive-data.html">Specifying Sensitive Data</see> in the <i>AWS Batch User Guide</i>. /// </summary> public List<Secret> SecretOptions { get; set; } } }
28
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// Details on a Docker volume mount point that is used in a job's container properties. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_MountPoint.html /// </summary> public class MountPoint { /// <summary> /// The path on the container at which to mount the host volume. /// </summary> public string ContainerPath { get; set; } /// <summary> /// If this value is true, the container has read-only access to the volume; otherwise, /// the container can write to the volume. The default value is false. /// </summary> public bool ReadOnly { get; set; } /// <summary> /// The name of the volume to mount. /// </summary> public string SourceVolume { get; set; } } }
25
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The network configuration for jobs that are running on Fargate resources. Jobs that are running on EC2 resources must not specify this parameter. /// </summary> public class NetworkConfiguration { /// <summary> /// Indicates whether the job should have a public IP address. For a job that is running on Fargate resources in a private subnet to send outbound traffic to the internet /// (for example, to pull container images), the private subnet requires a NAT gateway be attached to route requests to the internet. For more information, /// see <see href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html">Amazon ECS task networking</see>. The default value is "DISABLED". /// </summary> public string AssignPublicIp { get; set; } } }
16
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobDetail.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html /// </summary> public class NetworkInterfaceDetail { /// <summary> /// The attachment ID for the network interface. /// </summary> public string AttachmentId { get; set; } /// <summary> /// The private IPv6 address for the network interface. /// </summary> public string Ipv6Address { get; set; } /// <summary> /// The private IPv4 address for the network interface. /// </summary> public string PrivateIpv4Address { get; set; } } }
30
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobDetail.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html /// </summary> public class NodeDetails { /// <summary> /// Specifies whether the current node is the main node for a multi-node parallel job. /// </summary> public bool IsMainNode { get; set; } /// <summary> /// The node index for the node. Node index numbering begins at zero. This index is also /// available on the node with the <c>AWS_BATCH_JOB_NODE_INDEX</c> environment variable. /// </summary> public int NodeIndex { get; set; } } }
23
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobDetail.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html /// </summary> public class NodeProperties { /// <summary> /// Specifies the node index for the main node of a multi-node parallel job. /// </summary> public int MainNode { get; set; } /// <summary> /// A list of node ranges and their properties associated with a multi-node parallel job. /// </summary> public List<NodeRangeProperty> NodeRangeProperties { get; set; } /// <summary> /// The number of nodes associated with a multi-node parallel job. /// </summary> public int NumNodes { get; set; } } }
30
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_JobDetail.html /// https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html /// </summary> public class NodeRangeProperty { /// <summary> /// The container details for the node range. /// </summary> public ContainerProperties Container { get; set; } /// <summary> /// The range of nodes, using node index values. A range of <c>0:3</c> indicates /// nodes with index values of <c>0</c> through <c>3</c>. If the starting /// range value is omitted (<c>:n</c>), then <c>0</c> is used to start the /// range. If the ending range value is omitted (<c>n:</c>), then the highest possible /// node index is used to end the range. Your accumulative node ranges must account for /// all nodes (0:n). You may nest node ranges, for example 0:10 and 4:5, in which case /// the 4:5 range properties override the 0:10 properties. /// </summary> public string TargetNodes { get; set; } } }
27
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The type and amount of a resource to assign to a container. The supported resources include <c>GPU</c>, <c>MEMORY</c>, and <c>VCPU</c>. /// </summary> public class ResourceRequirement { /// <summary> /// The type of resource to assign to a container. The supported resources include <c>GPU</c>, <c>MEMORY</c>, and <c>VCPU</c>. /// </summary> public string Type { get; set; } /// <summary> /// The quantity of the specified resource to reserve for the container. The values vary based on the <c>type</c> specified. /// </summary> public string Value { get; set; } } }
19
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The retry strategy associated with a job. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_RetryStrategy.html /// </summary> public class RetryStrategy { /// <summary> /// The number of times to move a job to the RUNNABLE status. You may specify between 1 and 10 attempts. /// If the value of attempts is greater than one, the job is retried if it fails until it has moved to /// RUNNABLE that many times. /// </summary> public int Attempts { get; set; } /// <summary> /// Array of up to 5 objects that specify conditions under which the job should be retried or failed. /// If this parameter is specified, then the <c>attempts</c> parameter must also be specified. /// </summary> public List<EvaluateOnExit> EvaluateOnExit { get; set; } } }
24
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// An object representing the secret to expose to your container. Secrets can be exposed to a container in the following ways: /// <list type="bullet"><item><description>To inject sensitive data into your containers as environment variables, use the secrets container definition parameter.</description></item> /// <item><description>To reference sensitive information in the log configuration of a container, use the secretOptions container definition parameter.</description></item></list> /// For more information, see <see href="https://docs.aws.amazon.com/batch/latest/userguide/specifying-sensitive-data.html">Specifying sensitive data</see> in the <i>AWS Batch User Guide</i>. /// </summary> public class Secret { /// <summary> /// The name of the secret. /// </summary> public string Name { get; set; } /// <summary> /// The secret to expose to the container. The supported values are either the full ARN of the AWS Secrets Manager secret or the full ARN of the parameter in the AWS Systems Manager Parameter Store. /// </summary> public string ValueFrom { get; set; } } }
22
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The container path, mount options, and size of the tmpfs mount. /// </summary> public class Tmpfs { /// <summary> /// The absolute file path in the container where the tmpfs volume is mounted. /// </summary> public string ContainerPath { get; set; } /// <summary> /// The list of tmpfs volume mount options. /// </summary> public List<string> MountOptions { get; set; } /// <summary> /// The size (in MiB) of the tmpfs volume. /// </summary> public int Size { get; set; } } }
26
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// The ulimit settings to pass to the container. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_Ulimit.html /// </summary> public class Ulimit { /// <summary> /// The hard limit for the ulimit type. /// </summary> public int HardLimit { get; set; } /// <summary> /// The type of the ulimit. /// </summary> public string Name { get; set; } /// <summary> /// The soft limit for the ulimit type. /// </summary> public int SoftLimit { get; set; } } }
24
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents { /// <summary> /// A data volume used in a job's container properties. /// https://docs.aws.amazon.com/batch/latest/APIReference/API_Volume.html /// </summary> public class Volume { /// <summary> /// This parameter is specified when you are using an Amazon Elastic File System file system for job storage. /// Jobs that are running on Fargate resources must specify a <c>platformVersion</c> of at least <c>1.4.0</c>. /// </summary> public EFSVolumeConfiguration EfsVolumeConfiguration { get; set; } /// <summary> /// The contents of the host parameter determine whether your data volume persists on the host container /// instance and where it is stored. If the host parameter is empty, then the Docker daemon assigns a host /// path for your data volume. However, the data is not guaranteed to persist after the containers associated /// with it stop running. /// </summary> public Host Host { get; set; } /// <summary> /// The name of the volume. Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are /// allowed. This name is referenced in the sourceVolume parameter of container definition mountPoints. /// </summary> public string Name { get; set; } } }
29
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// An object representing a container instance or task attachment. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Attachment.html /// </summary> public class Attachment { /// <summary> /// Details of the attachment. For elastic network interfaces, this includes the /// network interface ID, the MAC address, the subnet ID, and the private IPv4 address. /// Type of underlying object KeyValuePair (https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KeyValuePair.html) /// </summary> public List<NameValue> Details { get; set; } /// <summary> /// The unique identifier for the attachment. /// </summary> public string Id { get; set; } /// <summary> /// The status of the attachment. Valid values are PRECREATED, CREATED, ATTACHING, /// ATTACHED, DETACHING, DETACHED, and DELETED. /// </summary> public string Status { get; set; } /// <summary> /// The type of the attachment, such as ElasticNetworkInterface. /// </summary> public string Type { get; set; } } }
34
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// An attribute is a name-value pair associated with an Amazon ECS object. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Attribute.html /// </summary> public class Attribute { /// <summary> /// The name of the attribute. The name must contain between 1 and 128 characters /// and name may contain letters (uppercase and lowercase), numbers, hyphens, /// underscores, forward slashes, back slashes, or periods. /// </summary> public string Name { get; set; } /// <summary> /// The ID of the target. You can specify the short form ID for a resource or the full /// Amazon Resource Name (ARN). /// </summary> public string TargetId { get; set; } /// <summary> /// The type of the target with which to attach the attribute. This parameter is required /// if you use the short form ID for a resource instead of the full ARN. /// </summary> public string TargetType { get; set; } /// <summary> /// The value of the attribute. The value must contain between 1 and 128 characters and may /// contain letters (uppercase and lowercase), numbers, hyphens, underscores, periods, at signs (@), /// forward slashes, back slashes, colons, or spaces. The value cannot contain any leading or trailing whitespace. /// </summary> public string Value { get; set; } } }
36
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// A Docker container that is part of a task. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Container.html /// </summary> public class Container { /// <summary> /// The Amazon Resource Name (ARN) of the container. /// </summary> public string ContainerArn { get; set; } /// <summary> /// The number of CPU units set for the container. The value will be 0 if no value was specified in the container definition when the task definition was registered. /// </summary> public string Cpu { get; set; } /// <summary> /// The exit code returned from the container. /// </summary> public int ExitCode { get; set; } /// <summary> /// The IDs of each GPU assigned to the container. /// </summary> public List<string> GpuIds { get; set; } /// <summary> /// The health status of the container. If health checks are not configured for this container in its task definition, then it reports the health status as UNKNOWN. /// </summary> public string HealthStatus { get; set; } /// <summary> /// The image used for the container. /// </summary> public string Image { get; set; } /// <summary> /// The container image manifest digest. /// </summary> public string ImageDigest { get; set; } /// <summary> /// The last known status of the container. /// </summary> public string LastStatus { get; set; } /// <summary> /// The details of any Amazon ECS managed agents associated with the container. /// </summary> public List<ManagedAgent> ManagedAgents { get; set; } /// <summary> /// The hard limit (in MiB) of memory set for the container. /// </summary> public string Memory { get; set; } /// <summary> /// The soft limit (in MiB) of memory set for the container. /// </summary> public string MemoryReservation { get; set; } /// <summary> /// The name of the container. /// </summary> public string Name { get; set; } /// <summary> /// The network bindings associated with the container. /// </summary> public List<NetworkBinding> NetworkBindings { get; set; } /// <summary> /// The network interfaces associated with the container. /// </summary> public List<NetworkInterface> NetworkInterfaces { get; set; } /// <summary> /// A short (255 max characters) human-readable string to provide additional details about a running or stopped container. /// </summary> public string Reason { get; set; } /// <summary> /// The ID of the Docker container. /// </summary> public string RuntimeId { get; set; } /// <summary> /// The ARN of the task. /// </summary> public string TaskArn { get; set; } } }
97
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// An EC2 instance that is running the Amazon ECS agent and has been registered with a cluster. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerInstance.html /// </summary> public class ContainerInstance { /// <summary> /// This parameter returns true if the agent is connected to Amazon ECS. /// Registered instances with an agent that may be unhealthy or stopped return false. Instances without /// a connected agent can't accept placement requests. /// </summary> public bool AgentConnected { get; set; } /// <summary> /// The status of the most recent agent update. If an update has never been requested, this value is NULL. /// </summary> public string AgentUpdateStatus { get; set; } /// <summary> /// The elastic network interfaces associated with the container instance. /// </summary> public List<Attachment> Attachments { get; set; } /// <summary> /// The attributes set for the container instance, either by the Amazon ECS container agent at instance /// registration or manually with the PutAttributes operation. /// </summary> public List<Attribute> Attributes { get; set; } /// <summary> /// The capacity provider associated with the container instance. /// </summary> public string CapacityProviderName { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the container instance. /// The ARN contains the arn:aws:ecs namespace, followed by the region of the container instance, /// the AWS account ID of the container instance owner, the container-instance namespace, /// and then the container instance ID. /// </summary> public string ContainerInstanceArn { get; set; } /// <summary> /// The EC2 instance ID of the container instance. /// </summary> public string Ec2InstanceId { get; set; } /// <summary> /// The number of tasks on the container instance that are in the PENDING status. /// </summary> public int PendingTasksCount { get; set; } /// <summary> /// The Unix time stamp for when the container instance was registered. /// </summary> public DateTime RegisteredAt { get; set; } /// <summary> /// For CPU and memory resource types, this parameter describes the amount of each resource that was available /// on the container instance when the container agent registered it with Amazon ECS; this value represents /// the total amount of CPU and memory that can be allocated on this container instance to tasks. /// For port resource types, this parameter describes the ports that were reserved by the Amazon ECS container /// agent when it registered the container instance with Amazon ECS. /// </summary> public List<Resource> RegisteredResources { get; set; } /// <summary> /// For CPU and memory resource types, this parameter describes the remaining CPU and memory that has not /// already been allocated to tasks and is therefore available for new tasks. /// For port resource types, this parameter describes the ports that were reserved by the Amazon ECS /// container agent (at instance registration time) and any task containers that have reserved port mappings /// on the host (with the host or bridge network mode). /// Any port that is not specified here is available for new tasks. /// </summary> public List<Resource> RemainingResources { get; set; } /// <summary> /// The number of tasks on the container instance that are in the RUNNING status. /// </summary> public int RunningTasksCount { get; set; } /// <summary> /// The status of the container instance. /// The valid values are ACTIVE, INACTIVE, or DRAINING. ACTIVE indicates that the container instance /// can accept tasks. /// DRAINING indicates that new tasks are not placed on the container instance and any service tasks /// running on the container instance are removed if possible. /// </summary> public string Status { get; set; } /// <summary> /// The reason that the container instance reached its current status. /// </summary> public string StatusReason { get; set; } /// <summary> /// The metadata that you apply to the container instance to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. /// </summary> public List<KeyValuePair<string, string>> Tags { get; set; } /// <summary> /// The version counter for the container instance. /// Every time a container instance experiences a change that triggers a CloudWatch event, /// the version counter is incremented. If you are replicating your Amazon ECS container instance /// state with CloudWatch Events, you can compare the version of a container instance reported by /// the Amazon ECS APIs with the version reported in CloudWatch Events for the container instance /// (inside the detail object) to verify that the version in your event stream is current. /// </summary> public long Version { get; set; } /// <summary> /// The version information for the Amazon ECS container agent and Docker daemon running on the container instance. /// </summary> public VersionInfo VersionInfo { get; set; } // NOTE: The following properties are not present in the ContainerInstance object documentation but have // been added here for convenience. /// <summary> /// The Amazon Resource Name (ARN) of the cluster that hosts the service. /// </summary> public string ClusterArn { get; set; } /// <summary> /// The Unix time stamp for when the service was last updated. /// </summary> public DateTime UpdatedAt { get; set; } } }
134
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// The overrides that should be sent to a container. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerOverride.html /// </summary> public class ContainerOverride { /// <summary> /// The command to send to the container that overrides the default command from /// the Docker image or the task definition. You must also specify a container name. /// </summary> public List<string> Command { get; set; } /// <summary> /// The number of cpu units reserved for the container, instead of the default value /// from the task definition. You must also specify a container name. /// </summary> public int Cpu { get; set; } /// <summary> /// The environment variables to send to the container. You can add new environment variables, /// which are added to the container at launch, or you can override the existing environment /// variables from the Docker image or the task definition. You must also specify a container name. /// </summary> public List<NameValue> Environment { get; set; } /// <summary> /// The hard limit (in MiB) of memory to present to the container, instead of the default value /// from the task definition. If your container attempts to exceed the memory specified here, /// the container is killed. You must also specify a container name. /// </summary> public int Memory { get; set; } /// <summary> /// The soft limit (in MiB) of memory to reserve for the container, instead of the default value /// from the task definition. You must also specify a container name. /// </summary> public int MemoryReservation { get; set; } /// <summary> /// The name of the container that receives the override. /// This parameter is required if any override is specified. /// </summary> public string Name { get; set; } } }
52
aws-lambda-dotnet
aws
C#
using System; using Amazon.Lambda.CloudWatchEvents; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// AWS ECS 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 /// https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html /// </summary> public class ECSContainerInstanceStateChangeEvent : CloudWatchEvent<ContainerInstance> { } }
18
aws-lambda-dotnet
aws
C#
using System; using Amazon.Lambda.CloudWatchEvents; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// /// AWS ECS task state change 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 /// https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html /// </summary> public class ECSTaskStateChangeEvent : CloudWatchEvent<Task> { } }
16
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// The amount of ephemeral storage to allocate for the task. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_EphemeralStorage.html /// </summary> public class EphemeralStorage { /// <summary> /// The total amount, in GiB, of ephemeral storage to set for the task. The minimum supported value is 21 GiB and the maximum supported value is 200 GiB. /// </summary> public int SizeInGiB { get; set; } } }
15
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// Details on a Elastic Inference accelerator. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_InferenceAccelerator.html /// </summary> public class InferenceAccelerator { /// <summary> /// The Elastic Inference accelerator device name. /// </summary> public string DeviceName { get; set; } /// <summary> /// The Elastic Inference accelerator type to use. /// </summary> public string DeviceType { get; set; } } }
24
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// Details on an Elastic Inference accelerator task override. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_InferenceAcceleratorOverride.html /// </summary> public class InferenceAcceleratorOverride : InferenceAccelerator { } }
11
aws-lambda-dotnet
aws
C#
using System; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// Details about the managed agent status for the container. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ManagedAgent.html /// </summary> public class ManagedAgent { /// <summary> /// The Unix timestamp for when the managed agent was last started. /// </summary> public DateTime LastStartedAt { get; set; } /// <summary> /// The last known status of the managed agent. /// </summary> public string LastStatus { get; set; } /// <summary> /// The name of the managed agent. When the execute command feature is enabled, the managed agent name is ExecuteCommandAgent. /// </summary> public string Name { get; set; } /// <summary> /// The reason for why the managed agent is in the state it is in. /// </summary> public string Reason { get; set; } } }
32
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// Details on the network bindings between a container and its host container instance. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_NetworkBinding.html /// </summary> public class NetworkBinding { /// <summary> /// The IP address that the container is bound to on the container instance. /// </summary> public string BindIP { get; set; } /// <summary> /// The port number on the container that is used with the network binding. /// </summary> public int ContainerPort { get; set; } /// <summary> /// The port number on the host that is used with the network binding. /// </summary> public int HostPort { get; set; } /// <summary> /// The protocol used for the network binding. /// </summary> public string Protocol { get; set; } } }
30
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// An object representing the elastic network interface for tasks that use the awsvpc network mode. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_NetworkInterface.html /// </summary> public class NetworkInterface { /// <summary> /// The attachment ID for the network interface. /// </summary> public string AttachmentId { get; set; } /// <summary> /// The private IPv6 address for the network interface. /// </summary> public string Ipv6Address { get; set; } /// <summary> /// The private IPv4 address for the network interface. /// </summary> public string PrivateIpv4Address { get; set; } } }
25
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { using System.Collections.Generic; /// <summary> /// Describes the resources available for a container instance. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Resource.html /// </summary> public class Resource { /// <summary> /// When the <c>DoubleValue</c> type is set, the value of the resource must be a /// double precision floating-point type. /// </summary> public double DoubleValue { get; set; } /// <summary> /// When the <c>IntegerValue</c> type is set, the value of the resource must be /// an integer. /// </summary> public int IntegerValue { get; set; } /// <summary> /// When the <c>LongValue</c> type is set, the value of the resource must be an /// extended precision floating-point type. /// </summary> public long LongValue { get; set; } /// <summary> /// The name of the resource, such as CPU, MEMORY, PORTS, PORTS_UDP, or a user-defined resource. /// </summary> public string Name { get; set; } /// <summary> /// The type of the resource, such as INTEGER, DOUBLE, LONG, or STRINGSET. /// </summary> public string Type { get; set; } /// <summary> /// When the stringSetValue type is set, the value of the resource must be a string type. /// </summary> public List<string> StringSetValue { get; set; } } }
50
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// Details on a task in a cluster. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Task.html /// </summary> public class Task { /// <summary> /// The Elastic Network Adapter associated with the task if the task uses the awsvpc network mode. /// </summary> public List<Attachment> Attachments { get; set; } /// <summary> /// The attributes of the task. /// </summary> public List<Attribute> Attributes { get; set; } /// <summary> /// The availability zone of the task. /// </summary> public string AvailabilityZone { get; set; } /// <summary> /// The capacity provider associated with the task. /// </summary> public string CapacityProviderName { get; set; } /// <summary> /// The ARN of the cluster that hosts the task. /// </summary> public string ClusterArn { get; set; } /// <summary> /// The connectivity status of a task. /// </summary> public string Connectivity { get; set; } /// <summary> /// The Unix time stamp for when the task last went into CONNECTED status. /// </summary> public DateTime ConnectivityAt { get; set; } /// <summary> /// The ARN of the container instances that host the task. /// </summary> public string ContainerInstanceArn { get; set; } /// <summary> /// The containers associated with the task. /// </summary> public List<Container> Containers { get; set; } /// <summary> /// The number of CPU units used by the task. It can be expressed as an integer using CPU units, /// for example 1024, or as a string using vCPUs, for example 1 vCPU or 1 vcpu, in a task definition. /// String values are converted to an integer indicating the CPU units when the task definition is registered. /// See https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Task.html for extra info. /// </summary> public string Cpu { get; set; } /// <summary> /// The Unix time stamp for when the task was created (the task entered the PENDING state). /// </summary> public DateTime CreatedAt { get; set; } /// <summary> /// The desired status of the task. For more information, /// see Task Lifecycle: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_life_cycle.html. /// </summary> public string DesiredStatus { get; set; } /// <summary> /// Whether or not execute command functionality is enabled for this task. If true, this enables execute command functionality on all containers in the task. /// </summary> public bool EnableExecuteCommand { get; set; } /// <summary> /// The ephemeral storage settings for the task. /// </summary> public EphemeralStorage EphemeralStorage { get; set; } /// <summary> /// The Unix time stamp for when the task execution stopped. /// </summary> public DateTime ExecutionStoppedAt { get; set; } /// <summary> /// The name of the task group associated with the task. /// </summary> public string Group { get; set; } /// <summary> /// The health status for the task, which is determined by the health of the essential containers in the task. /// If all essential containers in the task are reporting as HEALTHY, then the task status also /// reports as HEALTHY. If any essential containers in the task are reporting as UNHEALTHY or UNKNOWN, /// then the task status also reports as UNHEALTHY or UNKNOWN, accordingly. /// See https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Task.html for extra info. /// </summary> public string HealthStatus { get; set; } /// <summary> /// The Elastic Inference accelerator associated with the task. /// </summary> public List<InferenceAccelerator> InferenceAccelerators { get; set; } /// <summary> /// The last known status of the task. For more information, /// see Task Lifecycle: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_life_cycle.html. /// </summary> public string LastStatus { get; set; } /// <summary> /// The launch type on which your task is running. /// </summary> public string LaunchType { get; set; } /// <summary> /// The amount of memory (in MiB) used by the task. It can be expressed as an integer using MiB, /// for example 1024, or as a string using GB, for example 1GB or 1 GB, in a task definition. /// String values are converted to an integer indicating the MiB when the task definition is registered. /// See https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Task.html for extra info. /// </summary> public string Memory { get; set; } /// <summary> /// One or more container overrides. /// </summary> public TaskOverride Overrides { get; set; } /// <summary> /// The platform version on which your task is running. For more information, /// see AWS Fargate Platform Versions in the Amazon Elastic Container Service Developer Guide. /// https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html /// </summary> public string PlatformVersion { get; set; } /// <summary> /// The Unix time stamp for when the container image pull began. /// </summary> public DateTime PullStartedAt { get; set; } /// <summary> /// The Unix time stamp for when the container image pull completed. /// </summary> public DateTime PullStoppedAt { get; set; } /// <summary> /// The Unix time stamp for when the task started (the task /// transitioned from the PENDING state to the RUNNING state). /// </summary> public DateTime StartedAt { get; set; } /// <summary> /// The tag specified when a task is started. If the task is started by an Amazon ECS service, /// then the startedBy parameter contains the deployment ID of the service that starts it. /// </summary> public string StartedBy { get; set; } /// <summary> /// The stop code indicating why a task was stopped. The stoppedReason may contain additional details. /// </summary> public string StopCode { get; set; } /// <summary> /// The Unix time stamp for when the task stops (transitions from the RUNNING state to STOPPED). /// </summary> public DateTime StoppedAt { get; set; } /// <summary> /// The reason that the task was stopped. /// </summary> public string StoppedReason { get; set; } /// <summary> /// The Unix timestamp for when the task stops (transitions from the RUNNING state to STOPPED). /// </summary> public DateTime StoppingAt { get; set; } /// <summary> /// The metadata that you apply to the task to help you categorize and organize them. Each tag consists /// of a key and an optional value, both of which you define. /// See https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Task.html for extra info. /// </summary> public List<KeyValuePair<string, string>> Tags { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the task. /// </summary> public string TaskArn { get; set; } /// <summary> /// The ARN of the task definition that creates the task. /// </summary> public string TaskDefinitionArn { get; set; } /// <summary> /// The version counter for the task. Every time a task experiences a change that triggers a CloudWatch event, /// the version counter is incremented. If you are replicating your Amazon ECS task state with /// CloudWatch Events, you can compare the version of a task reported by the Amazon ECS APIs with /// the version reported in CloudWatch Events for the task (inside the detail object) to verify that /// the version in your event stream is current. /// </summary> public long Version { get; set; } // NOTE: The UpdatedAt property is not present in the Task object documentation but has been // added here for convenience. /// <summary> /// The Unix time stamp for when the service was last updated. /// </summary> public DateTime UpdatedAt { get; set; } } }
217
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// The overrides associated with a task. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_TaskOverride.html /// </summary> public class TaskOverride { /// <summary> /// One or more container overrides sent to a task. /// </summary> public List<ContainerOverride> ContainerOverrides { get; set; } /// <summary> /// The cpu override for the task. /// </summary> public string Cpu { get; set; } /// <summary> /// The ephemeral storage setting override for the task. /// </summary> public EphemeralStorage EphemeralStorage { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the task execution IAM role override for the task. /// </summary> public string ExecutionRoleArn { get; set; } /// <summary> /// The Elastic Inference accelerator override for the task. /// </summary> public List<InferenceAcceleratorOverride> InferenceAcceleratorOverrides { get; set; } /// <summary> /// The memory override for the task. /// </summary> public string Memory { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the IAM role that containers in this task can assume. /// All containers in this task are granted the permissions that are specified in this role. /// </summary> public string TaskRoleArn { get; set; } } }
50
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.CloudWatchEvents.ECSEvents { /// <summary> /// The Docker and Amazon ECS container agent version information about a container instance. /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_VersionInfo.html /// </summary> public class VersionInfo { /// <summary> /// The Git commit hash for the Amazon ECS container agent build on the amazon-ecs-agent GitHub repository. /// </summary> public string AgentHash { get; set; } /// <summary> /// The version number of the Amazon ECS container agent. /// </summary> public string AgentVersion { get; set; } /// <summary> /// The Docker version running on the container instance. /// </summary> public string DockerVersion { get; set; } } }
27
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents an S3 bucket. /// </summary> public class Bucket { /// <summary> /// The name of the bucket. /// </summary> public string Name { get; set; } } }
14
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents an S3 object. /// </summary> [DataContract] public class S3Object { /// <summary> /// The key for the object stored in S3. /// </summary> [DataMember(Name = "key")] public string Key { get; set; } /// <summary> /// The size of the object. /// </summary> [DataMember(Name = "size")] public long Size { get; set; } /// <summary> /// The etag of the object. /// </summary> [DataMember(Name = "etag")] public string ETag { get; set; } /// <summary> /// The version ID of the object. /// </summary> [DataMember(Name = "version-id")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("version-id")] #endif public string VersionId { get; set; } /// <summary> /// A string used to determine event sequence in PUTs and DELETEs. /// </summary> [DataMember(Name = "sequencer")] public string Sequencer { get; set; } } }
45
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents the details of an S3 object create event sent via EventBridge. /// </summary> [DataContract] public class S3ObjectCreate : S3ObjectEventDetails { /// <summary> /// The source IP of the API request. /// </summary> [DataMember(Name = "source-ip-address")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("source-ip-address")] #endif public string SourceIpAddress { get; set; } /// <summary> /// The reason the event was fired. /// </summary> [DataMember(Name = "reason")] public string Reason { get; set; } } }
27
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.CloudWatchEvents; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents an S3 object create event sent via EventBridge. /// </summary> public class S3ObjectCreateEvent : CloudWatchEvent<S3ObjectCreate> {} }
10
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents the details of an S3 object delete event sent via EventBridge. /// </summary> [DataContract] public class S3ObjectDelete : S3ObjectEventDetails { /// <summary> /// The source IP of the API request. /// </summary> [DataMember(Name = "source-ip-address")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("source-ip-address")] #endif public string SourceIpAddress { get; set; } /// <summary> /// The reason the event was fired. /// </summary> [DataMember(Name = "reason")] public string Reason { get; set; } /// <summary> /// The type of object deletion event. /// </summary> [DataMember(Name = "deletion-type")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("deletion-type")] #endif public string DeletionType { get; set; } } }
36
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.CloudWatchEvents; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents an S3 object delete event sent via EventBridge. /// </summary> public class S3ObjectDeleteEvent : CloudWatchEvent<S3ObjectDelete> {} }
10
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents the details of an S3 object event sent via EventBridge. /// </summary> [DataContract] public class S3ObjectEventDetails { /// <summary> /// The version of the event. /// </summary> [DataMember(Name = "version")] public string Version { get; set; } /// <summary> /// The bucket details. /// </summary> [DataMember(Name = "bucket")] public Bucket Bucket { get; set; } /// <summary> /// The object details. /// </summary> [DataMember(Name = "object")] public S3Object Object { get; set; } /// <summary> /// The ID of the API request. /// </summary> [DataMember(Name = "request-id")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("request-id")] #endif public string RequestId { get; set; } /// <summary> /// The ID of the API requester. /// </summary> [DataMember(Name = "requester")] public string Requester { get; set; } } }
45
aws-lambda-dotnet
aws
C#
using System.Runtime.Serialization; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents the details of an S3 object restore event sent via EventBridge. /// </summary> [DataContract] public class S3ObjectRestore : S3ObjectEventDetails { /// <summary> /// The time when the temporary copy of the object will be deleted from S3. /// </summary> [DataMember(Name = "restore-expiry-time")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("restore-expiry-time")] #endif public string RestoreExpiryTime { get; set; } /// <summary> /// The storage class of the object being restored. /// </summary> [DataMember(Name = "source-storage-class")] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("source-storage-class")] #endif public string SourceStorageClass { get; set; } } }
30
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.CloudWatchEvents; namespace Amazon.Lambda.CloudWatchEvents.S3Events { /// <summary> /// This class represents an S3 object restore event sent via EventBridge. /// </summary> public class S3ObjectRestoreEvent : CloudWatchEvent<S3ObjectRestore> {} }
10
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ScheduledEvents { /// <summary> /// AWS Scheduled event detail /// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-scheduled-event /// </summary> public class Detail { } }
12
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.ScheduledEvents { /// <summary> /// AWS Scheduled 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 /// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-scheduled-event /// </summary> public class ScheduledEvent : CloudWatchEvent<Detail> { } }
14
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.TranscribeEvents { /// <summary> /// This class represents the details of a Transcribe Job State Change sent via EventBridge. /// For more see - https://docs.aws.amazon.com/transcribe/latest/dg/monitoring-events.html /// </summary> public class TranscribeJobStateChange { /// <summary> /// The transcription job name. /// </summary> public string TranscriptionJobName { get; set; } /// <summary> /// The transcription job status. /// </summary> public string TranscriptionJobStatus { get; set; } /// <summary> /// If the TranscriptionJobStatus is FAILED, this field contains information about the failure. /// </summary> public string FailureReason { get; set; } } }
25
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.TranscribeEvents { /// <summary> /// This class represents a Transcribe Job State Change sent via EventBridge. /// </summary> public class TranscribeJobStateChangeEvent : CloudWatchEvent<TranscribeJobStateChange>{ } }
8
aws-lambda-dotnet
aws
C#
using System; namespace Amazon.Lambda.CloudWatchEvents.TranslateEvents { /// <summary> /// This class represents the details of a Translate Parallel Data State Change // for CreateParallelData and UpdateParallelData events sent via EventBridge. /// For more see - https://docs.aws.amazon.com/translate/latest/dg/monitoring-with-eventbridge.html /// </summary> public class TranslateParallelDataStateChange { /// <summary> /// The CreateParallelData/UpdateParallelData operation. /// </summary> public string Operation { get; set; } /// <summary> /// The CreateParallelData/UpdateParallelData name. /// </summary> public string Name { get; set; } /// <summary> /// The CreateParallelData/UpdateParallelData status. /// </summary> public string Status { get; set; } /// <summary> /// The UpdateParallelData latest update attempt status. /// </summary> public string LatestUpdateAttemptStatus { get; set; } /// <summary> /// The UpdateParallelData latest update attempt at. /// </summary> public DateTime LatestUpdateAttemptAt { get; set; } } }
38
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.TranslateEvents { /// <summary> /// This class represents a Translate Parallel Data State Change sent via EventBridge. /// </summary> public class TranslateParallelDataStateChangeEvent : CloudWatchEvent<TranslateParallelDataStateChange>{ } }
8
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.TranslateEvents { /// <summary> /// This class represents the details of a Translate Text Translation Job State Change sent via EventBridge. /// For more see - https://docs.aws.amazon.com/translate/latest/dg/monitoring-with-eventbridge.html /// </summary> public class TranslateTextTranslationJobStateChange { /// <summary> /// The translation job id. /// </summary> public string JobId { get; set; } /// <summary> /// The translation job status. /// </summary> public string JobStatus { get; set; } } }
20
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchEvents.TranslateEvents { /// <summary> /// This class represents a Translate Text Translation Job State Change sent via EventBridge. /// </summary> public class TranslateTextTranslationJobStateChangeEvent : CloudWatchEvent<TranslateTextTranslationJobStateChange>{ } }
8
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CloudWatchLogsEvents { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.Serialization; using System.Text; /// <summary> /// AWS CloudWatch Logs event /// http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html /// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-cloudwatch-logs /// </summary> public class CloudWatchLogsEvent { /// <summary> /// The Log from the CloudWatch that is invoking the Lambda function. /// </summary> public Log Awslogs { get; set; } /// <summary> /// The class identifies the Log from the CloudWatch that is invoking the Lambda function. /// </summary> [DataContract] public class Log { /// <summary> /// The data that are base64 encoded and gziped messages in LogStreams. /// </summary> [DataMember(Name = "data", IsRequired = false)] #if NETCOREAPP_3_1 [System.Text.Json.Serialization.JsonPropertyName("data")] #endif public string EncodedData { get; set; } /// <summary> /// Decodes the data stored in the EncodedData property. /// </summary> public string DecodeData() { if (string.IsNullOrEmpty(this.EncodedData)) return this.EncodedData; var bytes = Convert.FromBase64String(this.EncodedData); var uncompressedStream = new MemoryStream(); using (var stream = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress)) { stream.CopyTo(uncompressedStream); uncompressedStream.Position = 0; } var decodedString = Encoding.UTF8.GetString(uncompressedStream.ToArray()); return decodedString; } } } }
61
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.CloudWatchLogsEvents")] [assembly: AssemblyDescription("Lambda event interfaces for CloudWatch Logs 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.Runtime.Serialization; namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html /// </summary> [DataContract] public class ChallengeResultElement { /// <summary> /// The challenge type.One of: CUSTOM_CHALLENGE, SRP_A, PASSWORD_VERIFIER, SMS_MFA, DEVICE_SRP_AUTH, DEVICE_PASSWORD_VERIFIER, or ADMIN_NO_SRP_AUTH. /// </summary> [DataMember(Name = "challengeName")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeName")] # endif public string ChallengeName { get; set; } /// <summary> /// Set to true if the user successfully completed the challenge, or false otherwise. /// </summary> [DataMember(Name = "challengeResult")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeResult")] # endif public bool ChallengeResult { get; set; } /// <summary> /// Your name for the custom challenge.Used only if challengeName is CUSTOM_CHALLENGE. /// </summary> [DataMember(Name = "challengeMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeMetadata")] # endif public string ChallengeMetadata { get; set; } } }
39
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 ClaimOverrideDetails { /// <summary> /// A map of one or more key-value pairs of claims to add or override. For group related claims, use groupOverrideDetails instead. /// </summary> [DataMember(Name = "claimsToAddOrOverride")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("claimsToAddOrOverride")] # endif public Dictionary<string, string> ClaimsToAddOrOverride { get; set; } = new Dictionary<string, string>(); /// <summary> /// A list that contains claims to be suppressed from the identity token. /// </summary> [DataMember(Name = "claimsToSuppress")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("claimsToSuppress")] # endif public List<string> ClaimsToSuppress { get; set; } = new List<string>(); /// <summary> /// The output object containing the current group configuration. It includes groupsToOverride, iamRolesToOverride, and preferredRole. /// </summary> [DataMember(Name = "groupOverrideDetails")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("groupOverrideDetails")] # endif public GroupConfiguration GroupOverrideDetails { get; set; } = new GroupConfiguration(); } }
40
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-create-auth-challenge.html /// </summary> public class CognitoCreateAuthChallengeEvent : CognitoTriggerEvent<CognitoCreateAuthChallengeRequest, CognitoCreateAuthChallengeResponse> { } }
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-create-auth-challenge.html /// </summary> public class CognitoCreateAuthChallengeRequest : 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> /// The name of the new challenge. /// </summary> [DataMember(Name = "challengeName")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeName")] #endif public string ChallengeName { get; set; } /// <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; } } }
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-create-auth-challenge.html /// </summary> public class CognitoCreateAuthChallengeResponse : CognitoTriggerResponse { /// <summary> /// One or more key-value pairs for the client app to use in the challenge to be presented to the user.This parameter should contain all of the necessary information to accurately present the challenge to the user. /// </summary> [DataMember(Name = "publicChallengeParameters")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("publicChallengeParameters")] #endif public Dictionary<string, string> PublicChallengeParameters { get; set; } = new Dictionary<string, string>(); /// <summary> /// This parameter is only used by the Verify Auth Challenge Response Lambda trigger. This parameter should contain all of the information that is required to validate the user's response to the challenge. In other words, the publicChallengeParameters parameter contains the question that is presented to the user and privateChallengeParameters contains the valid answers for the question. /// </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> /// Your name for the custom challenge, if this is a custom challenge. /// </summary> [DataMember(Name = "challengeMetadata")] #if NETCOREAPP3_1 [System.Text.Json.Serialization.JsonPropertyName("challengeMetadata")] #endif public string ChallengeMetadata { get; set; } } }
39
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-email-sender.html /// </summary> public class CognitoCustomEmailSenderEvent : CognitoTriggerEvent<CognitoCustomEmailSenderRequest, CognitoCustomEmailSenderResponse> { } }
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-email-sender.html /// </summary> public class CognitoCustomEmailSenderRequest : 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-email-sender.html /// </summary> public class CognitoCustomEmailSenderResponse : CognitoTriggerResponse { } }
10
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.CognitoEvents { /// <summary> /// https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html /// </summary> public class CognitoCustomMessageEvent : CognitoTriggerEvent<CognitoCustomMessageRequest, CognitoCustomMessageResponse> { } }
10