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# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport.ExceptionHandling;
using Amazon.Lambda.RuntimeSupport.Helpers;
namespace Amazon.Lambda.RuntimeSupport.Bootstrap
{
/// <summary>
/// Loads user code and prepares to invoke it.
/// </summary>
internal class UserCodeLoader
{
private const string UserInvokeException = "An exception occurred while invoking customer handler.";
private const string LambdaLoggingActionFieldName = "_loggingAction";
internal const string LambdaCoreAssemblyName = "Amazon.Lambda.Core";
private readonly InternalLogger _logger;
private readonly string _handlerString;
private bool _customerLoggerSetUpComplete;
private HandlerInfo _handler;
private Action<Stream, ILambdaContext, Stream> _invokeDelegate;
internal MethodInfo CustomerMethodInfo { get; private set; }
/// <summary>
/// Initializes UserCodeLoader with a given handler and internal logger.
/// </summary>
/// <param name="handler"></param>
/// <param name="logger"></param>
public UserCodeLoader(string handler, InternalLogger logger)
{
if (string.IsNullOrEmpty(handler))
{
throw new ArgumentNullException(nameof(handler));
}
_logger = logger;
_handlerString = handler;
}
/// <summary>
/// Loads customer assembly, type, and method.
/// After this call returns without errors, it is possible to invoke
/// the customer method through the Invoke method.
/// </summary>
public void Init(Action<string> customerLoggingAction)
{
Assembly customerAssembly = null;
try
{
_logger.LogDebug($"UCL : Parsing handler string '{_handlerString}'");
_handler = new HandlerInfo(_handlerString);
// Set the logging action private field on the Amazon.Lambda.Core.LambdaLogger type which is part of the
// public Amazon.Lambda.Core package when it is loaded.
AppDomain.CurrentDomain.AssemblyLoad += (sender, args) =>
{
_logger.LogInformation($"UCL : Loaded assembly {args.LoadedAssembly.FullName} into default ALC.");
if (!_customerLoggerSetUpComplete && string.Equals(LambdaCoreAssemblyName, args.LoadedAssembly.GetName().Name, StringComparison.Ordinal))
{
_logger.LogDebug(
$"UCL : Load context loading '{LambdaCoreAssemblyName}', attempting to set {Types.LambdaLoggerTypeName}.{LambdaLoggingActionFieldName} to logging action.");
SetCustomerLoggerLogAction(args.LoadedAssembly, customerLoggingAction, _logger);
_customerLoggerSetUpComplete = true;
}
};
_logger.LogDebug($"UCL : Attempting to load assembly '{_handler.AssemblyName}'");
customerAssembly = AssemblyLoadContext.Default.LoadFromAssemblyName(_handler.AssemblyName);
}
catch (FileNotFoundException fex)
{
_logger.LogError(fex, "An error occurred on UCL Init");
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.CouldNotFindHandlerAssembly, fex.FileName);
}
catch (LambdaValidationException validationException)
{
_logger.LogError(validationException, "An error occurred on UCL Init");
throw;
}
catch (Exception exception)
{
_logger.LogError(exception, "An error occurred on UCL Init");
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.UnableToLoadAssembly, _handler.AssemblyName);
}
_logger.LogDebug($"UCL : Attempting to load type '{_handler.TypeName}'");
var customerType = customerAssembly.GetType(_handler.TypeName);
if (customerType == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.UnableToLoadType, _handler.TypeName, _handler.AssemblyName);
}
_logger.LogDebug($"UCL : Attempting to find method '{_handler.MethodName}' in type '{_handler.TypeName}'");
CustomerMethodInfo = FindCustomerMethod(customerType);
_logger.LogDebug($"UCL : Located method '{CustomerMethodInfo}'");
_logger.LogDebug($"UCL : Validating method '{CustomerMethodInfo}'");
UserCodeValidator.ValidateCustomerMethod(CustomerMethodInfo);
var customerObject = GetCustomerObject(customerType);
var customerSerializerInstance = GetSerializerObject(customerAssembly);
_logger.LogDebug($"UCL : Constructing invoke delegate");
var isPreJit = UserCodeInit.IsCallPreJit();
var builder = new InvokeDelegateBuilder(_logger, _handler, CustomerMethodInfo);
_invokeDelegate = builder.ConstructInvokeDelegate(customerObject, customerSerializerInstance, isPreJit);
if (isPreJit)
{
_logger.LogInformation("PreJit: PrepareDelegate");
RuntimeHelpers.PrepareDelegate(_invokeDelegate);
}
}
/// <summary>
/// Calls into the customer method.
/// </summary>
/// <param name="lambdaData">Input stream.</param>
/// <param name="lambdaContext">Context for the invocation.</param>
/// <param name="outStream">Output stream.</param>
public void Invoke(Stream lambdaData, ILambdaContext lambdaContext, Stream outStream)
{
_invokeDelegate(lambdaData, lambdaContext, outStream);
}
internal static void SetCustomerLoggerLogAction(Assembly coreAssembly, Action<string> customerLoggingAction, InternalLogger internalLogger)
{
if (coreAssembly == null)
{
throw new ArgumentNullException(nameof(coreAssembly));
}
if (customerLoggingAction == null)
{
throw new ArgumentNullException(nameof(customerLoggingAction));
}
internalLogger.LogDebug($"UCL : Retrieving type '{Types.LambdaLoggerTypeName}'");
var lambdaILoggerType = coreAssembly.GetType(Types.LambdaLoggerTypeName);
if (lambdaILoggerType == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.Internal.UnableToLocateType, Types.LambdaLoggerTypeName);
}
internalLogger.LogDebug($"UCL : Retrieving field '{LambdaLoggingActionFieldName}'");
var loggingActionField = lambdaILoggerType.GetTypeInfo().GetField(LambdaLoggingActionFieldName, BindingFlags.NonPublic | BindingFlags.Static);
if (loggingActionField == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.Internal.UnableToRetrieveField, LambdaLoggingActionFieldName, Types.LambdaLoggerTypeName);
}
internalLogger.LogDebug($"UCL : Setting field '{LambdaLoggingActionFieldName}'");
try
{
loggingActionField.SetValue(null, customerLoggingAction);
}
catch (Exception e)
{
throw LambdaExceptions.ValidationException(e, Errors.UserCodeLoader.Internal.UnableToSetField,
Types.LambdaLoggerTypeName, LambdaLoggingActionFieldName);
}
}
/// <summary>
/// Constructs customer-specified serializer, specified either on the method,
/// the assembly, or not specified at all.
/// Returns null if serializer not specified.
/// </summary>
/// <param name="customerAssembly">Assembly that contains customer code.</param>
/// <returns>Instance of serializer object defined with LambdaSerializerAttribute</returns>
private object GetSerializerObject(Assembly customerAssembly)
{
// try looking up the LambdaSerializerAttribute on the method
_logger.LogDebug($"UCL : Searching for LambdaSerializerAttribute at method level");
var customerSerializerAttribute = CustomerMethodInfo.GetCustomAttributes().SingleOrDefault(a => Types.IsLambdaSerializerAttribute(a.GetType()));
_logger.LogDebug($"UCL : LambdaSerializerAttribute at method level {(customerSerializerAttribute != null ? "found" : "not found")}");
// only check the assembly if the LambdaSerializerAttribute does not exist on the method
if (customerSerializerAttribute == null)
{
_logger.LogDebug($"UCL : Searching for LambdaSerializerAttribute at assembly level");
customerSerializerAttribute = customerAssembly.GetCustomAttributes()
.SingleOrDefault(a => Types.IsLambdaSerializerAttribute(a.GetType()));
_logger.LogDebug($"UCL : LambdaSerializerAttribute at assembly level {(customerSerializerAttribute != null ? "found" : "not found")}");
}
var serializerAttributeExists = customerSerializerAttribute != null;
_logger.LogDebug($"UCL : LambdaSerializerAttribute {(serializerAttributeExists ? "found" : "not found")}");
if (serializerAttributeExists)
{
_logger.LogDebug($"UCL : Constructing custom serializer");
return ConstructCustomSerializer(customerSerializerAttribute);
}
else
{
return null;
}
}
/// <summary>
/// Attempts to find MethodInfo in given type
/// Returns null if no matching method was found
/// </summary>
/// <param name="type">Type that contains customer method.</param>
/// <returns>Method information of customer method.</returns>
/// <exception cref="LambdaValidationException">Thrown when failed to find customer method in container type.</exception>
private MethodInfo FindCustomerMethod(Type type)
{
// These are split because finding by name is slightly faster
// and it's also the more common case.
// RuntimeMethodInfo::ToString() always contains a ' ' character.
// So one of the two lookup methods would always return null.
var customerMethodInfo = FindCustomerMethodByName(type.GetTypeInfo()) ??
FindCustomerMethodBySignature(type.GetTypeInfo());
if (customerMethodInfo == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.NoMatchingMethod,
_handler.MethodName, _handler.TypeName, _handler.AssemblyName, _handler.MethodName);
}
return customerMethodInfo;
}
private MethodInfo FindCustomerMethodByName(TypeInfo typeInfo)
{
try
{
var mi = typeInfo.GetMethod(_handler.MethodName, Constants.DefaultFlags);
if (mi == null)
{
var parentType = typeInfo.BaseType;
// check if current type is System.Object (parentType is null) and leave
if (parentType == null)
{
return null;
}
// check base type
return FindCustomerMethodByName(parentType.GetTypeInfo());
}
return mi;
}
catch (AmbiguousMatchException)
{
throw GetMultipleMethodsValidationException(typeInfo);
}
}
private MethodInfo FindCustomerMethodBySignature(TypeInfo typeInfo)
{
// get all methods
var matchingMethods = typeInfo.GetMethods(Constants.DefaultFlags)
.Where(mi => SignatureMatches(_handler.MethodName, mi))
.ToList();
// check for single match in these methods
if (matchingMethods.Count == 1)
{
return matchingMethods[0];
}
else if (matchingMethods.Count > 1)
{
// should never happen because signatures are unique but ...
throw GetMultipleMethodsValidationException(typeInfo);
}
else
{
var parentType = typeInfo.BaseType;
// check if current type is System.Object (parentType is null) and leave
if (parentType == null)
{
return null;
}
// check base type
return FindCustomerMethodBySignature(parentType.GetTypeInfo());
}
}
private static bool SignatureMatches(string methodSignature, MethodInfo method)
{
return string.Equals(methodSignature, method.ToString(), StringComparison.Ordinal);
}
private static bool NameMatches(string methodName, MethodInfo method)
{
return string.Equals(methodName, method.Name, StringComparison.Ordinal);
}
private Exception GetMultipleMethodsValidationException(TypeInfo typeInfo)
{
var signatureList = typeInfo.GetMethods(Constants.DefaultFlags)
.Where(mi => SignatureMatches(_handler.MethodName, mi) || NameMatches(_handler.MethodName, mi))
.Select(mi => mi.ToString()).ToList();
var signatureListText = string.Join("\n", signatureList);
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.MethodHasOverloads,
_handler.MethodName, typeInfo.FullName, signatureListText);
}
/// <summary>
/// Constructs an instance of the customer-specified serializer
/// </summary>
/// <param name="serializerAttribute">Serializer attribute used to define the input/output serializer.</param>
/// <returns></returns>
/// <exception cref="LambdaValidationException">Thrown when serializer doesn't satisfy serializer type requirements.</exception>
/// <exception cref="LambdaUserCodeException">Thrown when failed to instantiate serializer type.</exception>
private object ConstructCustomSerializer(Attribute serializerAttribute)
{
var attributeType = serializerAttribute.GetType();
var serializerTypeProperty = attributeType.GetTypeInfo().GetProperty("SerializerType");
if (serializerTypeProperty == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.InvalidClassNoSerializerType, attributeType.FullName);
}
if (!Types.TypeType.GetTypeInfo().IsAssignableFrom(serializerTypeProperty.PropertyType))
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.InvalidClassSerializerTypeWrongType,
attributeType.FullName, Types.TypeType.FullName);
}
var serializerType = serializerTypeProperty.GetValue(serializerAttribute) as Type;
if (serializerType == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.SerializerTypeNotSet,
attributeType.FullName);
}
var serializerTypeInfo = serializerType.GetTypeInfo();
var constructor = serializerTypeInfo.GetConstructor(Type.EmptyTypes);
if (constructor == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.SerializerMissingConstructor, serializerType.FullName);
}
var iLambdaSerializerType = serializerTypeInfo.GetInterface(Types.ILambdaSerializerTypeName);
if (iLambdaSerializerType == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.InvalidClassNoILambdaSerializer, serializerType.FullName);
}
_logger.LogDebug($"UCL : Validating type '{iLambdaSerializerType.FullName}'");
UserCodeValidator.ValidateILambdaSerializerType(iLambdaSerializerType);
object customSerializerInstance;
customSerializerInstance = constructor.Invoke(null);
return customSerializerInstance;
}
/// <summary>
/// Constructs an instance of the customer type, or returns null
/// if the customer method is static and does not require an object
/// </summary>
/// <param name="customerType">Type of the customer handler container.</param>
/// <returns>Instance of customer handler container type</returns>
/// <exception cref="LambdaUserCodeException">Thrown when failed to instantiate customer type.</exception>
private object GetCustomerObject(Type customerType)
{
_logger.LogDebug($"UCL : Validating type '{_handler.TypeName}'");
UserCodeValidator.ValidateCustomerType(customerType, CustomerMethodInfo);
var isHandlerStatic = CustomerMethodInfo.IsStatic;
if (isHandlerStatic)
{
_logger.LogDebug($"UCL : Not constructing customer object, customer method is static");
_logger.LogDebug($"UCL : Running static constructor for type '{_handler.TypeName}'");
// Make sure the static initializer for the type runs now, during the init phase.
RuntimeHelpers.RunClassConstructor(customerType.TypeHandle);
return null;
}
_logger.LogDebug($"UCL : Instantiating type '{_handler.TypeName}'");
return Activator.CreateInstance(customerType);
}
}
}
| 411 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Amazon.Lambda.RuntimeSupport.ExceptionHandling;
using Amazon.Lambda.RuntimeSupport.Helpers;
namespace Amazon.Lambda.RuntimeSupport.Bootstrap
{
internal static class UserCodeValidator
{
/// <summary>
/// Throws exception if type is not one we can work with
/// </summary>
/// <param name="type">Container type of customer method.</param>
/// <param name="method">Method information of customer method.</param>
/// <exception cref="LambdaValidationException">Throws when customer type is not lambda compatible.</exception>
internal static void ValidateCustomerType(Type type, MethodInfo method)
{
var typeInfo = type.GetTypeInfo();
// generic customer type is not supported
if (typeInfo.IsGenericType)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerTypeGeneric,
type.FullName);
}
// abstract customer type is not support if customer method is not static
if (!method.IsStatic && typeInfo.IsAbstract)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerTypeAbstract,
method.ToString(), type.FullName);
}
var isClass = typeInfo.IsClass;
var isStruct = typeInfo.IsValueType && !typeInfo.IsPrimitive && !typeInfo.IsEnum;
// customer type must be class or struct
if (!isClass && !isStruct)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerNotClassOrStruct,
type.FullName);
}
}
/// <summary>
/// Validate customer method signature
/// Throws exception if method is not one we can work with
/// </summary>
/// <param name="method">MethodInfo of customer method</param>
/// <exception cref="LambdaValidationException">Thrown when customer method doesn't satisfy method requirements</exception>
internal static void ValidateCustomerMethod(MethodInfo method)
{
if (method.IsAbstract)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerMethodAbstract,
method.ToString());
}
if (method.IsGenericMethod)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerMethodGeneric,
method.ToString());
}
var asyncAttribute = method.GetCustomAttribute(Types.AsyncStateMachineAttributeType);
var isAsync = asyncAttribute != null;
var isVoid = method.ReturnType == Types.VoidType;
if (isVoid && isAsync)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerMethodAsyncVoid,
method.ToString());
}
var inputParameters = method.GetParameters();
if (inputParameters.Length > 0)
{
var lastParameter = inputParameters[inputParameters.Length - 1];
var paramArrayAttribute = lastParameter.GetCustomAttribute(Types.ParamArrayAttributeType);
if (paramArrayAttribute != null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerMethodParams,
method.ToString());
}
}
// detect VarArgs methods
if ((method.CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.HandlerMethodVararg,
method.ToString());
}
}
/// <summary>
/// Validates object serializer used for serialization and deserialization of input and output
/// Throws exception if the specified ILambdaSerializer is a type we can work with
/// </summary>
/// <param name="type">Type of the customer's serializer.</param>
/// <exception cref="LambdaValidationException">Thrown when customer serializer doesn't match with expected serializer definition</exception>
internal static void ValidateILambdaSerializerType(Type type)
{
var typeInfo = type.GetTypeInfo();
var mismatchReason = CheckILambdaSerializerType(typeInfo);
if (!string.IsNullOrEmpty(mismatchReason))
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.TypeNotMatchingShape,
type.FullName, Types.ILambdaSerializerTypeName, mismatchReason);
}
}
/// <summary>
/// Checks that the ILambdaSerializer type is correct, returning null if type is as expected
/// or a non-null string with the reason if type is not correct.
/// </summary>
/// <param name="typeInfo">TypeInfo of the customer serializer.</param>
/// <returns>Error string if validation fails else null.</returns>
private static string CheckILambdaSerializerType(TypeInfo typeInfo)
{
if (!typeInfo.IsInterface)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_TypeNotInterface, typeInfo.FullName);
}
// check that the Deserialize method exists and is generic
var deserializeMethodInfo = typeInfo.GetMethod("Deserialize");
if (deserializeMethodInfo == null)
{
return Errors.UserCodeLoader.ILambdaSerializerMismatch_DeserializeMethodNotFound;
}
if (!deserializeMethodInfo.IsGenericMethod)
{
return Errors.UserCodeLoader.ILambdaSerializerMismatch_DeserializeMethodNotGeneric;
}
// verify that Stream is the only input
var deserializeInputs = deserializeMethodInfo.GetParameters();
if (deserializeInputs.Length != 1)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_DeserializeMethodHasTooManyParams, deserializeInputs.Length);
}
if (deserializeInputs[0].ParameterType != Types.StreamType)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_DeserializeMethodHasWrongParam, deserializeInputs[0].ParameterType.FullName,
Types.StreamType.FullName);
}
// verify that T is the return type
var deserializeOutputType = deserializeMethodInfo.ReturnType;
var deserializeGenericArguments = deserializeMethodInfo.GetGenericArguments();
if (deserializeGenericArguments.Length != 1)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_DeserializeMethodHasWrongNumberGenericArgs,
deserializeGenericArguments.Length);
}
if (deserializeGenericArguments[0] != deserializeOutputType)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_DeserializeMethodHasWrongReturn, deserializeOutputType.FullName);
}
// check that the Serialize method exists, is generic, and returns void
var serializeMethodInfo = typeInfo.GetMethod("Serialize");
if (serializeMethodInfo == null)
{
return Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodNotFound;
}
if (!serializeMethodInfo.IsGenericMethod)
{
return Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodNotGeneric;
}
if (serializeMethodInfo.ReturnType != Types.VoidType)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodHasWrongReturn, serializeMethodInfo.ReturnType.FullName);
}
// verify that T is the first input and Stream is the second input
var serializeInputs = serializeMethodInfo.GetParameters();
var serializeGenericArguments = serializeMethodInfo.GetGenericArguments();
if (serializeInputs.Length != 2)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodHasWrongNumberOfParameters, serializeInputs.Length);
}
if (serializeGenericArguments.Length != 1)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodHasWrongNumberGenericArgs, serializeGenericArguments.Length);
}
if (serializeInputs[0].ParameterType != serializeGenericArguments[0])
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodHasWrongFirstParam, serializeInputs[0].ParameterType.FullName);
}
if (serializeInputs[1].ParameterType != Types.StreamType)
{
return LambdaExceptions.FormatMessage(Errors.UserCodeLoader.ILambdaSerializerMismatch_SerializeMethodHasWrongSecondParam, serializeInputs[1].ParameterType.FullName,
Types.StreamType.FullName);
}
// all good!
return null;
}
/// <summary>
/// Validates ILambdaContext properties and methods
/// Throws exception if context type is not one we can work with
/// This checks the set of members on the first version of ILambdaContext type.
/// DO NOT update this code when new members are added to ILambdaContext type,
/// it will break existing Lambda deployment packages which still use older version of ILambdaContext.
/// </summary>
/// <param name="iLambdaContextType">Type of context passed for the invocation.</param>
/// <exception cref="LambdaValidationException">Thrown when context doesn't contain required properties & methods.</exception>
internal static void ValidateILambdaContextType(Type iLambdaContextType)
{
if (iLambdaContextType == null)
return;
ValidateInterfaceStringProperty(iLambdaContextType, "AwsRequestId");
ValidateInterfaceStringProperty(iLambdaContextType, "FunctionName");
ValidateInterfaceStringProperty(iLambdaContextType, "FunctionVersion");
ValidateInterfaceStringProperty(iLambdaContextType, "InvokedFunctionArn");
ValidateInterfaceStringProperty(iLambdaContextType, "LogGroupName");
ValidateInterfaceStringProperty(iLambdaContextType, "LogStreamName");
ValidateInterfaceProperty<int>(iLambdaContextType, "MemoryLimitInMB");
ValidateInterfaceProperty<TimeSpan>(iLambdaContextType, "RemainingTime");
var clientContextProperty = ValidateInterfaceProperty(iLambdaContextType, "ClientContext", Types.IClientContextTypeName);
var iClientContextType = clientContextProperty.PropertyType;
ValidateInterfaceProperty<IDictionary<string, string>>(iClientContextType, "Environment");
ValidateInterfaceProperty<IDictionary<string, string>>(iClientContextType, "Custom");
ValidateInterfaceProperty(iClientContextType, "Client", Types.IClientApplicationTypeName);
var identityProperty = ValidateInterfaceProperty(iLambdaContextType, "Identity", Types.ICognitoIdentityTypeName);
var iCognitoIdentityType = identityProperty.PropertyType;
ValidateInterfaceStringProperty(iCognitoIdentityType, "IdentityId");
ValidateInterfaceStringProperty(iCognitoIdentityType, "IdentityPoolId");
var loggerProperty = ValidateInterfaceProperty(iLambdaContextType, "Logger", Types.ILambdaLoggerTypeName);
var iLambdaLoggerType = loggerProperty.PropertyType;
var logMethod = iLambdaLoggerType.GetTypeInfo().GetMethod("Log", new[] {Types.StringType}, null);
if (logMethod == null)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.TypeMissingLogMethod, iLambdaLoggerType.FullName);
}
}
private static void ValidateInterfaceStringProperty(Type type, string propName)
{
ValidateInterfaceProperty<string>(type, propName);
}
private static void ValidateInterfaceProperty<T>(Type type, string propName)
{
var propType = typeof(T);
ValidateInterfaceProperty(type, propName, propType.FullName);
}
private static PropertyInfo ValidateInterfaceProperty(Type type, string propName, string propTypeName)
{
var propertyInfo = type.GetTypeInfo().GetProperty(propName, Constants.DefaultFlags);
if (propertyInfo == null || !string.Equals(propertyInfo.PropertyType.FullName, propTypeName, StringComparison.Ordinal))
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.TypeMissingExpectedProperty, type.FullName, propName, propTypeName);
}
if (!propertyInfo.CanRead)
{
throw LambdaExceptions.ValidationException(Errors.UserCodeLoader.PropertyNotReadable, propName, type.FullName);
}
return propertyInfo;
}
}
} | 295 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Text.Json;
using System.Net;
using System.Text.Json.Serialization;
using Amazon.Lambda.RuntimeSupport.Helpers;
namespace Amazon.Lambda.RuntimeSupport
{
internal partial interface IInternalRuntimeApiClient
{
/// <summary>Non-recoverable initialization error. Runtime should exit after reporting the error. Error will be served in response to the first invoke.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ErrorAsync(string lambda_Runtime_Function_Error_Type, string errorJson);
/// <summary>Non-recoverable initialization error. Runtime should exit after reporting the error. Error will be served in response to the first invoke.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ErrorAsync(string lambda_Runtime_Function_Error_Type, string errorJson, System.Threading.CancellationToken cancellationToken);
/// <summary>Runtime makes this HTTP request when it is ready to receive and process a new invoke.</summary>
/// <returns>This is an iterator-style blocking API call. Response contains event JSON document, specific to the invoking service.</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
System.Threading.Tasks.Task<SwaggerResponse<System.IO.Stream>> NextAsync();
/// <summary>Runtime makes this HTTP request when it is ready to receive and process a new invoke.</summary>
/// <returns>This is an iterator-style blocking API call. Response contains event JSON document, specific to the invoking service.</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
System.Threading.Tasks.Task<SwaggerResponse<System.IO.Stream>> NextAsync(System.Threading.CancellationToken cancellationToken);
/// <summary>Runtime makes this request in order to submit a response.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ResponseAsync(string awsRequestId, System.IO.Stream outputStream);
/// <summary>Runtime makes this request in order to submit a response.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ResponseAsync(string awsRequestId, System.IO.Stream outputStream, System.Threading.CancellationToken cancellationToken);
/// <summary>
/// Runtime makes this request in order to submit an error response. It can be either a function error, or a runtime error. Error will be served in response to the invoke.
/// </summary>
/// <param name="awsRequestId"></param>
/// <param name="lambda_Runtime_Function_Error_Type"></param>
/// <param name="errorJson"></param>
/// <param name="xrayCause"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ErrorWithXRayCauseAsync(string awsRequestId, string lambda_Runtime_Function_Error_Type, string errorJson, string xrayCause, System.Threading.CancellationToken cancellationToken);
}
internal partial class InternalRuntimeApiClient : IInternalRuntimeApiClient
{
#if NET6_0_OR_GREATER
[JsonSerializable(typeof(StatusResponse))]
[JsonSerializable(typeof(ErrorResponse))]
public partial class RuntimeApiSerializationContext : JsonSerializerContext
{
}
#endif
private const int MAX_HEADER_SIZE_BYTES = 1024 * 1024;
private const string ErrorContentType = "application/vnd.aws.lambda.error+json";
private string _baseUrl = "/2018-06-01";
private System.Net.Http.HttpClient _httpClient;
private InternalLogger _logger;
public InternalRuntimeApiClient(System.Net.Http.HttpClient httpClient)
{
_httpClient = httpClient;
_logger = InternalLogger.GetDefaultLogger();
}
public string BaseUrl
{
get { return _baseUrl; }
set { _baseUrl = value; }
}
/// <summary>Non-recoverable initialization error. Runtime should exit after reporting the error. Error will be served in response to the first invoke.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ErrorAsync(string lambda_Runtime_Function_Error_Type, string errorJson)
{
return ErrorAsync(lambda_Runtime_Function_Error_Type, errorJson, System.Threading.CancellationToken.None);
}
/// <summary>Non-recoverable initialization error. Runtime should exit after reporting the error. Error will be served in response to the first invoke.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
public async System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ErrorAsync(string lambda_Runtime_Function_Error_Type, string errorJson, System.Threading.CancellationToken cancellationToken)
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/runtime/init/error");
var client_ = _httpClient;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
if (lambda_Runtime_Function_Error_Type != null)
request_.Headers.TryAddWithoutValidation("Lambda-Runtime-Function-Error-Type", ConvertToString(lambda_Runtime_Function_Error_Type, System.Globalization.CultureInfo.InvariantCulture));
using (var content_ = new System.Net.Http.StringContent(errorJson))
{
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(ErrorContentType);
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}
if (response_.StatusCode == HttpStatusCode.Accepted)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(StatusResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<StatusResponse>(responseData_, RuntimeApiSerializationContext.Default.StatusResponse);
#else
result_ = JsonSerializer.Deserialize<StatusResponse>(responseData_);
#endif
return new SwaggerResponse<StatusResponse>((int)response_.StatusCode, headers_, result_);
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
}
else
if (response_.StatusCode == HttpStatusCode.Forbidden)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
if (response_.StatusCode == HttpStatusCode.InternalServerError)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null);
}
else
if (response_.StatusCode != HttpStatusCode.OK && response_.StatusCode != HttpStatusCode.NoContent)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
}
return new SwaggerResponse<StatusResponse>((int)response_.StatusCode, headers_, default(StatusResponse));
}
finally
{
if (response_ != null)
response_.Dispose();
}
}
}
}
finally
{
}
}
/// <summary>Runtime makes this HTTP request when it is ready to receive and process a new invoke.</summary>
/// <returns>This is an iterator-style blocking API call. Response contains event JSON document, specific to the invoking service.</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<SwaggerResponse<System.IO.Stream>> NextAsync()
{
return NextAsync(System.Threading.CancellationToken.None);
}
/// <summary>Runtime makes this HTTP request when it is ready to receive and process a new invoke.</summary>
/// <returns>This is an iterator-style blocking API call. Response contains event JSON document, specific to the invoking service.</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
public async System.Threading.Tasks.Task<SwaggerResponse<System.IO.Stream>> NextAsync(System.Threading.CancellationToken cancellationToken)
{
this._logger.LogInformation("Starting InternalClient.NextAsync");
var client_ = _httpClient;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
var url_ = BaseUrl.TrimEnd('/') + "/runtime/invocation/next";
request_.RequestUri = new System.Uri(url_, System.UriKind.Absolute);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
if (response_.StatusCode == HttpStatusCode.OK)
{
var inputBuffer = response_.Content == null ? null : await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
return new SwaggerResponse<System.IO.Stream>((int)response_.StatusCode, headers_, new System.IO.MemoryStream(inputBuffer));
}
else if (response_.StatusCode == HttpStatusCode.Forbidden)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else if (response_.StatusCode == HttpStatusCode.InternalServerError)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null);
}
else if (response_.StatusCode != HttpStatusCode.OK && response_.StatusCode != HttpStatusCode.NoContent)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
}
return new SwaggerResponse<System.IO.Stream>((int)response_.StatusCode, headers_, new System.IO.MemoryStream(0));
}
finally
{
if (response_ != null)
response_.Dispose();
}
}
}
finally
{
this._logger.LogInformation("Finished InternalClient.NextAsync");
}
}
/// <summary>Runtime makes this request in order to submit a response.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ResponseAsync(string awsRequestId, System.IO.Stream outputStream)
{
return ResponseAsync(awsRequestId, outputStream, System.Threading.CancellationToken.None);
}
/// <summary>Runtime makes this request in order to submit a response.</summary>
/// <returns>Accepted</returns>
/// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
public async System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ResponseAsync(string awsRequestId, System.IO.Stream outputStream, System.Threading.CancellationToken cancellationToken)
{
this._logger.LogInformation("Starting InternalClient.ResponseAsync");
if (awsRequestId == null)
throw new System.ArgumentNullException("awsRequestId");
var client_ = _httpClient;
try
{
var request_ = new System.Net.Http.HttpRequestMessage();
{
var content_ = outputStream == null ?
(System.Net.Http.HttpContent)new System.Net.Http.StringContent(string.Empty) :
(System.Net.Http.HttpContent)new System.Net.Http.StreamContent(new NonDisposingStreamWrapper(outputStream));
try
{
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
var url_ = $"{BaseUrl.TrimEnd('/')}/runtime/invocation/{awsRequestId}/response";
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
this._logger.LogInformation("Return from SendAsync");
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}
if (response_.StatusCode == HttpStatusCode.Accepted)
{
return new SwaggerResponse<StatusResponse>((int)response_.StatusCode, headers_, new StatusResponse());
}
else
if (response_.StatusCode == HttpStatusCode.BadRequest)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
if (response_.StatusCode == HttpStatusCode.Forbidden)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
if (response_.StatusCode == HttpStatusCode.RequestEntityTooLarge)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Payload Too Large", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
if (response_.StatusCode == HttpStatusCode.InternalServerError)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null);
}
else
if (response_.StatusCode != HttpStatusCode.OK && response_.StatusCode != HttpStatusCode.NoContent)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
}
return new SwaggerResponse<StatusResponse>((int)response_.StatusCode, headers_, default(StatusResponse));
}
finally
{
if (response_ != null)
response_.Dispose();
}
}
finally
{
content_?.Dispose();
}
}
}
finally
{
this._logger.LogInformation("Finished InternalClient.ResponseAsync");
}
}
/// <summary>
/// This is a copy of the generated Error2Async method but adds support for the unmodeled header `Lambda-Runtime-Function-XRay-Error-Cause`.
/// </summary>
/// <param name="awsRequestId"></param>
/// <param name="lambda_Runtime_Function_Error_Type"></param>
/// <param name="errorJson"></param>
/// <param name="xrayCause"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async System.Threading.Tasks.Task<SwaggerResponse<StatusResponse>> ErrorWithXRayCauseAsync(string awsRequestId, string lambda_Runtime_Function_Error_Type, string errorJson, string xrayCause, System.Threading.CancellationToken cancellationToken)
{
if (awsRequestId == null)
throw new System.ArgumentNullException("awsRequestId");
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/runtime/invocation/{AwsRequestId}/error");
urlBuilder_.Replace("{AwsRequestId}", System.Uri.EscapeDataString(ConvertToString(awsRequestId, System.Globalization.CultureInfo.InvariantCulture)));
var client_ = _httpClient;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
if (lambda_Runtime_Function_Error_Type != null)
request_.Headers.TryAddWithoutValidation("Lambda-Runtime-Function-Error-Type", ConvertToString(lambda_Runtime_Function_Error_Type, System.Globalization.CultureInfo.InvariantCulture));
// This is the unmodeled X-Ray header to report back the cause of errors.
if (xrayCause != null && System.Text.Encoding.UTF8.GetByteCount(xrayCause) < MAX_HEADER_SIZE_BYTES)
{
// Headers can not have newlines. The X-Ray JSON writer should not have put any in but do a final check of newlines.
xrayCause = xrayCause.Replace("\r\n", "").Replace("\n", "");
try
{
request_.Headers.Add("Lambda-Runtime-Function-XRay-Error-Cause", xrayCause);
}
catch
{
// Don't prevent reporting errors to Lambda if there are any issues adding the X-Ray cause JSON as a header.
}
}
using (var content_ = new System.Net.Http.StringContent(errorJson))
{
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(ErrorContentType);
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}
if (response_.StatusCode == HttpStatusCode.Accepted)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(StatusResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<StatusResponse>(responseData_, RuntimeApiSerializationContext.Default.StatusResponse);
#else
result_ = JsonSerializer.Deserialize<StatusResponse>(responseData_);
#endif
return new SwaggerResponse<StatusResponse>((int)response_.StatusCode, headers_, result_);
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
}
else
if (response_.StatusCode == HttpStatusCode.BadRequest)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
if (response_.StatusCode == HttpStatusCode.Forbidden)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(ErrorResponse);
try
{
#if NET6_0_OR_GREATER
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_, RuntimeApiSerializationContext.Default.ErrorResponse);
#else
result_ = JsonSerializer.Deserialize<ErrorResponse>(responseData_);
#endif
}
catch (System.Exception exception_)
{
throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new RuntimeApiClientException<ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
if (response_.StatusCode == HttpStatusCode.InternalServerError)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null);
}
else
if (response_.StatusCode != HttpStatusCode.OK && response_.StatusCode != HttpStatusCode.NoContent)
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new RuntimeApiClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
}
return new SwaggerResponse<StatusResponse>((int)response_.StatusCode, headers_, default(StatusResponse));
}
finally
{
if (response_ != null)
response_.Dispose();
}
}
}
}
finally
{
}
}
private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value is System.Enum)
{
string name = System.Enum.GetName(value.GetType(), value);
if (name != null)
{
var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name);
if (field != null)
{
var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute))
as System.Runtime.Serialization.EnumMemberAttribute;
if (attribute != null)
{
return attribute.Value;
}
}
}
}
else if (value is bool)
{
return System.Convert.ToString(value, cultureInfo).ToLowerInvariant();
}
else if (value is byte[])
{
return System.Convert.ToBase64String((byte[])value);
}
else if (value != null && value.GetType().IsArray)
{
var array = System.Linq.Enumerable.OfType<object>((System.Array)value);
return string.Join(",", System.Linq.Enumerable.Select(array, o => ConvertToString(o, cultureInfo)));
}
return System.Convert.ToString(value, cultureInfo);
}
}
internal partial class StatusResponse
{
public string status { get; set; }
}
internal partial class ErrorResponse
{
public string errorMessage { get; set; }
public string errorType { get; set; }
}
internal partial class SwaggerResponse
{
public int StatusCode { get; private set; }
public System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; }
public SwaggerResponse(int statusCode, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers)
{
StatusCode = statusCode;
Headers = headers;
}
}
internal partial class SwaggerResponse<TResult> : SwaggerResponse
{
public TResult Result { get; private set; }
public SwaggerResponse(int statusCode, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, TResult result)
: base(statusCode, headers)
{
Result = result;
}
}
public partial class RuntimeApiClientException : System.Exception
{
public int StatusCode { get; private set; }
public string Response { get; private set; }
public System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; }
public RuntimeApiClientException(string message, int statusCode, string response, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Exception innerException)
: base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + response.Substring(0, response.Length >= 512 ? 512 : response.Length), innerException)
{
StatusCode = statusCode;
Response = response;
Headers = headers;
}
public override string ToString()
{
return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString());
}
}
public partial class RuntimeApiClientException<TResult> : RuntimeApiClientException
{
public TResult Result { get; private set; }
public RuntimeApiClientException(string message, int statusCode, string response, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, TResult result, System.Exception innerException)
: base(message, statusCode, response, headers, innerException)
{
Result = result;
}
}
} | 692 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.Core;
using System;
using System.IO;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Class that contains all the information necessary to handle an invocation of an AWS Lambda function.
/// </summary>
public class InvocationRequest : IDisposable
{
/// <summary>
/// Input to the function invocation.
/// </summary>
public Stream InputStream { get; internal set; }
/// <summary>
/// Context for the invocation.
/// </summary>
public ILambdaContext LambdaContext { get; internal set; }
internal InvocationRequest() { }
public void Dispose()
{
InputStream?.Dispose();
}
}
}
| 44 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.IO;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Class that contains the response for an invocation of an AWS Lambda function.
/// </summary>
public class InvocationResponse
{
/// <summary>
/// Output from the function invocation.
/// </summary>
public Stream OutputStream { get; set; }
/// <summary>
/// True if the LambdaBootstrap should dispose the stream after it's read, false otherwise.
/// Set this to false if you plan to reuse the same output stream for multiple invocations of the function.
/// </summary>
public bool DisposeOutputStream { get; private set; } = true;
public InvocationResponse(Stream outputStream)
: this(outputStream, true)
{ }
public InvocationResponse(Stream outputStream, bool disposeOutputStream)
{
OutputStream = outputStream ?? throw new ArgumentNullException(nameof(outputStream));
DisposeOutputStream = disposeOutputStream;
}
}
}
| 48 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Client to call the AWS Lambda Runtime API.
/// </summary>
public interface IRuntimeApiClient
{
/// <summary>
/// Report an initialization error as an asynchronous operation.
/// </summary>
/// <param name="exception">The exception to report.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
Task ReportInitializationErrorAsync(Exception exception, CancellationToken cancellationToken = default);
/// <summary>
/// Send an initialization error with a type string but no other information as an asynchronous operation.
/// This can be used to directly control flow in Step Functions without creating an Exception class and throwing it.
/// </summary>
/// <param name="errorType">The type of the error to report to Lambda. This does not need to be a .NET type name.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
Task ReportInitializationErrorAsync(string errorType, CancellationToken cancellationToken = default);
/// <summary>
/// Get the next function invocation from the Runtime API as an asynchronous operation.
/// Completes when the next invocation is received.
/// </summary>
/// <param name="cancellationToken">The optional cancellation token to use to stop listening for the next invocation.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
Task<InvocationRequest> GetNextInvocationAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Report an invocation error as an asynchronous operation.
/// </summary>
/// <param name="awsRequestId">The ID of the function request that caused the error.</param>
/// <param name="exception">The exception to report.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
Task ReportInvocationErrorAsync(string awsRequestId, Exception exception, CancellationToken cancellationToken = default);
/// <summary>
/// Send a response to a function invocation to the Runtime API as an asynchronous operation.
/// </summary>
/// <param name="awsRequestId">The ID of the function request being responded to.</param>
/// <param name="outputStream">The content of the response to the function invocation.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns></returns>
Task SendResponseAsync(string awsRequestId, Stream outputStream, CancellationToken cancellationToken = default);
}
} | 71 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.IO;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// This class is used to wrap the function response stream.
/// It allows the wrapped stream to be reused.
/// </summary>
internal class NonDisposingStreamWrapper : Stream
{
Stream _wrappedStream;
public NonDisposingStreamWrapper(Stream wrappedStream)
{
_wrappedStream = wrappedStream;
}
public override bool CanRead
{
get
{
return _wrappedStream.CanRead;
}
}
public override bool CanSeek
{
get
{
return _wrappedStream.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _wrappedStream.CanWrite;
}
}
public override long Length
{
get
{
return _wrappedStream.Length;
}
}
public override long Position
{
get
{
return _wrappedStream.Position;
}
set
{
_wrappedStream.Position = value;
}
}
public override void Flush()
{
_wrappedStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrappedStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrappedStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_wrappedStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_wrappedStream.Write(buffer, offset, count);
}
}
}
| 103 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.RuntimeSupport.Helpers;
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Client to call the AWS Lambda Runtime API.
/// </summary>
public class RuntimeApiClient : IRuntimeApiClient
{
private readonly HttpClient _httpClient;
private readonly IInternalRuntimeApiClient _internalClient;
#if NET6_0_OR_GREATER
private readonly IConsoleLoggerWriter _consoleLoggerRedirector = new LogLevelLoggerWriter();
#else
private readonly IConsoleLoggerWriter _consoleLoggerRedirector = new SimpleLoggerWriter();
#endif
internal Func<Exception, ExceptionInfo> ExceptionConverter { get; set; }
internal LambdaEnvironment LambdaEnvironment { get; set; }
/// <summary>
/// Create a new RuntimeApiClient
/// </summary>
/// <param name="httpClient">The HttpClient to use to communicate with the Runtime API.</param>
public RuntimeApiClient(HttpClient httpClient)
: this(new SystemEnvironmentVariables(), httpClient)
{
}
internal RuntimeApiClient(IEnvironmentVariables environmentVariables, HttpClient httpClient)
{
ExceptionConverter = ExceptionInfo.GetExceptionInfo;
_httpClient = httpClient;
LambdaEnvironment = new LambdaEnvironment(environmentVariables);
var internalClient = new InternalRuntimeApiClient(httpClient);
internalClient.BaseUrl = "http://" + LambdaEnvironment.RuntimeServerHostAndPort + internalClient.BaseUrl;
_internalClient = internalClient;
}
internal RuntimeApiClient(IEnvironmentVariables environmentVariables, IInternalRuntimeApiClient internalClient)
{
LambdaEnvironment = new LambdaEnvironment(environmentVariables);
_internalClient = internalClient;
ExceptionConverter = ExceptionInfo.GetExceptionInfo;
}
/// <summary>
/// Report an initialization error as an asynchronous operation.
/// </summary>
/// <param name="exception">The exception to report.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
public Task ReportInitializationErrorAsync(Exception exception, CancellationToken cancellationToken = default)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
return _internalClient.ErrorAsync(null, LambdaJsonExceptionWriter.WriteJson(ExceptionInfo.GetExceptionInfo(exception)), cancellationToken);
}
/// <summary>
/// Send an initialization error with a type string but no other information as an asynchronous operation.
/// This can be used to directly control flow in Step Functions without creating an Exception class and throwing it.
/// </summary>
/// <param name="errorType">The type of the error to report to Lambda. This does not need to be a .NET type name.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
public Task ReportInitializationErrorAsync(string errorType, CancellationToken cancellationToken = default)
{
if (errorType == null)
throw new ArgumentNullException(nameof(errorType));
return _internalClient.ErrorAsync(errorType, null, cancellationToken);
}
/// <summary>
/// Get the next function invocation from the Runtime API as an asynchronous operation.
/// Completes when the next invocation is received.
/// </summary>
/// <param name="cancellationToken">The optional cancellation token to use to stop listening for the next invocation.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
public async Task<InvocationRequest> GetNextInvocationAsync(CancellationToken cancellationToken = default)
{
SwaggerResponse<Stream> response = await _internalClient.NextAsync(cancellationToken);
var headers = new RuntimeApiHeaders(response.Headers);
_consoleLoggerRedirector.SetCurrentAwsRequestId(headers.AwsRequestId);
var lambdaContext = new LambdaContext(headers, LambdaEnvironment, _consoleLoggerRedirector);
return new InvocationRequest
{
InputStream = response.Result,
LambdaContext = lambdaContext,
};
}
/// <summary>
/// Report an invocation error as an asynchronous operation.
/// </summary>
/// <param name="awsRequestId">The ID of the function request that caused the error.</param>
/// <param name="exception">The exception to report.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
public Task ReportInvocationErrorAsync(string awsRequestId, Exception exception, CancellationToken cancellationToken = default)
{
if (awsRequestId == null)
throw new ArgumentNullException(nameof(awsRequestId));
if (exception == null)
throw new ArgumentNullException(nameof(exception));
var exceptionInfo = ExceptionInfo.GetExceptionInfo(exception);
var exceptionInfoJson = LambdaJsonExceptionWriter.WriteJson(exceptionInfo);
var exceptionInfoXRayJson = LambdaXRayExceptionWriter.WriteJson(exceptionInfo);
return _internalClient.ErrorWithXRayCauseAsync(awsRequestId, exceptionInfo.ErrorType, exceptionInfoJson, exceptionInfoXRayJson, cancellationToken);
}
/// <summary>
/// Send a response to a function invocation to the Runtime API as an asynchronous operation.
/// </summary>
/// <param name="awsRequestId">The ID of the function request being responded to.</param>
/// <param name="outputStream">The content of the response to the function invocation.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns></returns>
public async Task SendResponseAsync(string awsRequestId, Stream outputStream, CancellationToken cancellationToken = default)
{
await _internalClient.ResponseAsync(awsRequestId, outputStream, cancellationToken);
}
}
} | 154 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
namespace Amazon.Lambda.RuntimeSupport
{
internal class RuntimeApiHeaders
{
internal const string HeaderAwsRequestId = "Lambda-Runtime-Aws-Request-Id";
internal const string HeaderTraceId = "Lambda-Runtime-Trace-Id";
internal const string HeaderClientContext = "Lambda-Runtime-Client-Context";
internal const string HeaderCognitoIdentity = "Lambda-Runtime-Cognito-Identity";
internal const string HeaderDeadlineMs = "Lambda-Runtime-Deadline-Ms";
internal const string HeaderInvokedFunctionArn = "Lambda-Runtime-Invoked-Function-Arn";
public RuntimeApiHeaders(Dictionary<string, IEnumerable<string>> headers)
{
DeadlineMs = GetHeaderValueOrNull(headers, HeaderDeadlineMs);
AwsRequestId = GetHeaderValueRequired(headers, HeaderAwsRequestId);
ClientContextJson = GetHeaderValueOrNull(headers, HeaderClientContext);
CognitoIdentityJson = GetHeaderValueOrNull(headers, HeaderCognitoIdentity);
InvokedFunctionArn = GetHeaderValueOrNull(headers, HeaderInvokedFunctionArn);
TraceId = GetHeaderValueOrNull(headers, HeaderTraceId);
}
public string AwsRequestId { get; private set; }
public string InvokedFunctionArn { get; private set; }
public string TraceId { get; private set; }
public string ClientContextJson { get; private set; }
public string CognitoIdentityJson { get; private set; }
public string DeadlineMs { get; private set; }
private string GetHeaderValueRequired(Dictionary<string, IEnumerable<string>> headers, string header)
{
return headers[header].FirstOrDefault();
}
private string GetHeaderValueOrNull(Dictionary<string, IEnumerable<string>> headers, string header)
{
if (headers.TryGetValue(header, out var values))
{
return values.FirstOrDefault();
}
return null;
}
}
}
| 63 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.Core;
using System.Text.Json;
namespace Amazon.Lambda.RuntimeSupport
{
internal class CognitoClientApplication : IClientApplication
{
public string AppPackageName { get; internal set; }
public string AppTitle { get; internal set; }
public string AppVersionCode { get; internal set; }
public string AppVersionName { get; internal set; }
public string InstallationId { get; internal set; }
internal static CognitoClientApplication FromJsonData(JsonElement jsonData)
{
var result = new CognitoClientApplication();
if (jsonData.TryGetProperty("app_package_name", out var nameElement))
result.AppPackageName = nameElement.GetString();
if (jsonData.TryGetProperty("app_title", out var tileElement))
result.AppTitle = tileElement.GetString();
if (jsonData.TryGetProperty("app_version_code", out var codeElement))
result.AppVersionCode = codeElement.GetString();
if (jsonData.TryGetProperty("app_version_name", out var versionNameElement))
result.AppVersionName = versionNameElement.GetString();
if (jsonData.TryGetProperty("installation_id", out var installElement))
result.InstallationId = installElement.GetString();
return result;
}
}
}
| 51 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace Amazon.Lambda.RuntimeSupport
{
internal class CognitoClientContext : IClientContext
{
public IDictionary<string, string> Environment { get; internal set; }
public IClientApplication Client { get; internal set; }
public IDictionary<string, string> Custom { get; internal set; }
internal static CognitoClientContext FromJson(string json)
{
var result = new CognitoClientContext();
if (!string.IsNullOrWhiteSpace(json))
{
var jsonData = JsonDocument.Parse(json).RootElement;
if (jsonData.TryGetProperty("client", out var clientElement))
result.Client = CognitoClientApplication.FromJsonData(clientElement);
if (jsonData.TryGetProperty("custom", out var customElement))
result.Custom = GetDictionaryFromJsonData(customElement);
if (jsonData.TryGetProperty("env", out var envElement))
result.Environment = GetDictionaryFromJsonData(envElement);
return result;
}
return result;
}
private static IDictionary<string, string> GetDictionaryFromJsonData(JsonElement jsonData)
{
return jsonData.EnumerateObject().ToDictionary(properties => properties.Name, properties => properties.Value.ToString());
}
}
}
| 57 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.Core;
using System.Text.Json;
namespace Amazon.Lambda.RuntimeSupport
{
internal class CognitoIdentity : ICognitoIdentity
{
public string IdentityId { get; internal set; }
public string IdentityPoolId { get; internal set; }
internal static CognitoIdentity FromJson(string json)
{
var result = new CognitoIdentity();
if (!string.IsNullOrWhiteSpace(json))
{
var jsonData = JsonDocument.Parse(json).RootElement;
if(jsonData.TryGetProperty("cognitoIdentityId", out var cognitoIdentityId))
result.IdentityId = cognitoIdentityId.GetString();
if(jsonData.TryGetProperty("cognitoIdentityPoolId", out var cognitoIdentityPoolId))
result.IdentityPoolId = cognitoIdentityPoolId.GetString();
}
return result;
}
}
}
| 45 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Collections;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Interface to access environment variables.
/// Allows for unit testing without changing the real System environment variables.
/// </summary>
internal interface IEnvironmentVariables
{
void SetEnvironmentVariable(string variable, string value);
string GetEnvironmentVariable(string variable);
IDictionary GetEnvironmentVariables();
}
}
| 30 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport.Helpers;
using System;
namespace Amazon.Lambda.RuntimeSupport
{
internal class LambdaConsoleLogger : ILambdaLogger
{
private IConsoleLoggerWriter _consoleLoggerRedirector;
public LambdaConsoleLogger(IConsoleLoggerWriter consoleLoggerRedirector)
{
_consoleLoggerRedirector = consoleLoggerRedirector;
}
public void Log(string message)
{
Console.Write(message);
}
public void LogLine(string message)
{
_consoleLoggerRedirector.FormattedWriteLine(message);
}
public string CurrentAwsRequestId { get; set; }
#if NET6_0_OR_GREATER
public void Log(string level, string message)
{
_consoleLoggerRedirector.FormattedWriteLine(level, message);
}
#endif
}
}
| 50 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.Core;
using System;
using Amazon.Lambda.RuntimeSupport.Helpers;
namespace Amazon.Lambda.RuntimeSupport
{
internal class LambdaContext : ILambdaContext
{
internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private LambdaEnvironment _lambdaEnvironment;
private RuntimeApiHeaders _runtimeApiHeaders;
private IDateTimeHelper _dateTimeHelper;
private long _deadlineMs;
private int _memoryLimitInMB;
private Lazy<CognitoIdentity> _cognitoIdentityLazy;
private Lazy<CognitoClientContext> _cognitoClientContextLazy;
private IConsoleLoggerWriter _consoleLogger;
public LambdaContext(RuntimeApiHeaders runtimeApiHeaders, LambdaEnvironment lambdaEnvironment, IConsoleLoggerWriter consoleLogger)
: this(runtimeApiHeaders, lambdaEnvironment, new DateTimeHelper(), consoleLogger)
{
}
public LambdaContext(RuntimeApiHeaders runtimeApiHeaders, LambdaEnvironment lambdaEnvironment, IDateTimeHelper dateTimeHelper, IConsoleLoggerWriter consoleLogger)
{
_lambdaEnvironment = lambdaEnvironment;
_runtimeApiHeaders = runtimeApiHeaders;
_dateTimeHelper = dateTimeHelper;
_consoleLogger = consoleLogger;
int.TryParse(_lambdaEnvironment.FunctionMemorySize, out _memoryLimitInMB);
long.TryParse(_runtimeApiHeaders.DeadlineMs, out _deadlineMs);
_cognitoIdentityLazy = new Lazy<CognitoIdentity>(() => CognitoIdentity.FromJson(runtimeApiHeaders.CognitoIdentityJson));
_cognitoClientContextLazy = new Lazy<CognitoClientContext>(() => CognitoClientContext.FromJson(runtimeApiHeaders.ClientContextJson));
// set environment variable so that if the function uses the XRay client it will work correctly
_lambdaEnvironment.SetXAmznTraceId(_runtimeApiHeaders.TraceId);
}
// TODO If/When Amazon.Lambda.Core is major versioned, add this to ILambdaContext.
// Until then function code can access it via the _X_AMZN_TRACE_ID environment variable set by LambdaBootstrap.
public string TraceId => _runtimeApiHeaders.TraceId;
public string AwsRequestId => _runtimeApiHeaders.AwsRequestId;
public IClientContext ClientContext => _cognitoClientContextLazy.Value;
public string FunctionName => _lambdaEnvironment.FunctionName;
public string FunctionVersion => _lambdaEnvironment.FunctionVersion;
public ICognitoIdentity Identity => _cognitoIdentityLazy.Value;
public string InvokedFunctionArn => _runtimeApiHeaders.InvokedFunctionArn;
public ILambdaLogger Logger => new LambdaConsoleLogger(_consoleLogger);
public string LogGroupName => _lambdaEnvironment.LogGroupName;
public string LogStreamName => _lambdaEnvironment.LogStreamName;
public int MemoryLimitInMB => _memoryLimitInMB;
public TimeSpan RemainingTime => TimeSpan.FromMilliseconds(_deadlineMs - (_dateTimeHelper.UtcNow - UnixEpoch).TotalMilliseconds);
}
}
| 84 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Linq;
using System.Reflection;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Provides access to Environment Variables set by the Lambda runtime environment.
/// </summary>
public class LambdaEnvironment
{
internal const string EnvVarExecutionEnvironment = "AWS_EXECUTION_ENV";
internal const string EnvVarFunctionMemorySize = "AWS_LAMBDA_FUNCTION_MEMORY_SIZE";
internal const string EnvVarFunctionName = "AWS_LAMBDA_FUNCTION_NAME";
internal const string EnvVarFunctionVersion = "AWS_LAMBDA_FUNCTION_VERSION";
internal const string EnvVarHandler = "_HANDLER";
internal const string EnvVarLogGroupName = "AWS_LAMBDA_LOG_GROUP_NAME";
internal const string EnvVarLogStreamName = "AWS_LAMBDA_LOG_STREAM_NAME";
internal const string EnvVarServerHostAndPort = "AWS_LAMBDA_RUNTIME_API";
internal const string EnvVarTraceId = "_X_AMZN_TRACE_ID";
internal const string AwsLambdaDotnetCustomRuntime = "AWS_Lambda_dotnet_custom";
internal const string AmazonLambdaRuntimeSupportMarker = "amazonlambdaruntimesupport";
private IEnvironmentVariables _environmentVariables;
public LambdaEnvironment() : this(new SystemEnvironmentVariables()) { }
internal LambdaEnvironment(IEnvironmentVariables environmentVariables)
{
_environmentVariables = environmentVariables;
FunctionMemorySize = environmentVariables.GetEnvironmentVariable(EnvVarFunctionMemorySize) as string;
FunctionName = environmentVariables.GetEnvironmentVariable(EnvVarFunctionName) as string;
FunctionVersion = environmentVariables.GetEnvironmentVariable(EnvVarFunctionVersion) as string;
LogGroupName = environmentVariables.GetEnvironmentVariable(EnvVarLogGroupName) as string;
LogStreamName = environmentVariables.GetEnvironmentVariable(EnvVarLogStreamName) as string;
RuntimeServerHostAndPort = environmentVariables.GetEnvironmentVariable(EnvVarServerHostAndPort) as string;
Handler = environmentVariables.GetEnvironmentVariable(EnvVarHandler) as string;
SetExecutionEnvironment();
}
private void SetExecutionEnvironment()
{
var envValue = _environmentVariables.GetEnvironmentVariable(EnvVarExecutionEnvironment);
if (!string.IsNullOrEmpty(envValue) && envValue.Equals(AwsLambdaDotnetCustomRuntime))
{
var assemblyVersion = typeof(LambdaBootstrap).Assembly
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
.FirstOrDefault()
as AssemblyInformationalVersionAttribute;
_environmentVariables.SetEnvironmentVariable(EnvVarExecutionEnvironment,
$"{envValue}_{AmazonLambdaRuntimeSupportMarker}_{assemblyVersion?.InformationalVersion}");
}
}
internal void SetXAmznTraceId(string xAmznTraceId)
{
_environmentVariables.SetEnvironmentVariable(EnvVarTraceId, xAmznTraceId);
}
public string FunctionMemorySize { get; private set; }
public string FunctionName { get; private set; }
public string FunctionVersion { get; private set; }
public string LogGroupName { get; private set; }
public string LogStreamName { get; private set; }
public string RuntimeServerHostAndPort { get; private set; }
public string Handler { get; private set; }
public string XAmznTraceId
{
get
{
return _environmentVariables.GetEnvironmentVariable(EnvVarTraceId);
}
}
public string ExecutionEnvironment
{
get
{
return _environmentVariables.GetEnvironmentVariable(EnvVarExecutionEnvironment);
}
}
}
}
| 102 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Implementation of IEnvironmentVariables that accesses the real System.Environment
/// </summary>
internal class SystemEnvironmentVariables : IEnvironmentVariables
{
public string GetEnvironmentVariable(string variable)
{
return Environment.GetEnvironmentVariable(variable);
}
public IDictionary GetEnvironmentVariables()
{
return Environment.GetEnvironmentVariables();
}
public void SetEnvironmentVariable(string variable, string value)
{
Environment.SetEnvironmentVariable(variable, value);
}
}
}
| 41 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Amazon.Lambda.RuntimeSupport.ExceptionHandling
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
internal static class Errors
{
internal static class UserCodeLoader
{
internal static class Internal
{
public const string UnableToLocateType = "Internal error: unable to locate '{0}' type.";
public const string UnableToRetrieveField = "Internal error: unable to retrieve '{0}' field from '{1}'.";
public const string UnableToSetField = "Internal error: unable to set '{0}.{1}' field.";
}
public const string CouldNotFindHandlerAssembly = "Could not find the specified handler assembly with the file name '{0}'. The assembly should be located in the root of your uploaded .zip file.";
public const string UnableToLoadAssembly = "Unable to load assembly '{0}'.";
public const string UnableToLoadType = "Unable to load type '{0}' from assembly '{1}'.";
public const string DeserializeMissingAttribute = "Could not find the LambdaSerializerAttribute on the assembly '{0}' or method '{1}' while attempting to deserialize input data of type '{2}'. To use types other than System.IO.Stream as input/output parameters, the assembly or Lambda function should be annotated with {3}.";
public const string SerializeMissingAttribute = "Could not find the LambdaSerializerAttribute on the assembly '{0}' or method '{1}' while attempting to serialize output data of type '{2}'. To use types other than System.IO.Stream as input/output parameters, the assembly or Lambda function should be annotated with {3}.";
public const string MethodTooManyParams = "Method '{0}' of type '{1}' is not supported: the method has more than 2 parameters.";
public const string MethodSecondParamNotContext = "Method '{0}' of type '{1}' is not supported: the method has 2 parameters, but the second parameter is not of type '{2}'.";
public const string NoMatchingMethod = "Unable to find method '{0}' in type '{1}' from assembly '{2}': Found no methods matching method name '{3}'.";
public const string InvalidClassNoSerializerType = "The '{0}' class is invalid: no 'SerializerType' property detected.";
public const string InvalidClassSerializerTypeWrongType = "The '{0}' class is invalid: 'SerializerType' property cannot be converted to type '{1}'.";
public const string SerializerTypeNotSet = "The 'SerializerType' property on attribute class '{0}' is not set.";
public const string SerializerMissingConstructor = "The indicated serializer '{0}' does not define a public zero-parameter constructor.";
public const string InvalidClassNoILambdaSerializer = "The '{0}' class is invalid: it does not implement the 'ILambdaSerializer' interface.";
public const string HandlerTypeGeneric = "The type '{0}' cannot be used as a Lambda Handler type because it is generic. Handler methods cannot be located in generic types. Please specify a handler method in a non-generic type.";
public const string HandlerTypeAbstract = "The instance method '{0}' cannot be used as a Lambda Handler because its type '{1}' is abstract. Please either use a static handler or specify a type that is not abstract.";
public const string HandlerNotClassOrStruct = "The type '{0}' cannot be used as a handler type since it is not a class or a struct. Please specify a handler method on a class or struct.";
public const string HandlerMethodAbstract = "The method '{0}' cannot be used as a Lambda Handler because it is an abstract method. Handler methods cannot be abstract. Please specify a non-abstract handler method.";
public const string HandlerMethodGeneric = "The method '{0}' cannot be used as a Lambda Handler because it is a generic method. Handler methods cannot be generic. Please specify a non-generic handler method.";
public const string HandlerMethodAsyncVoid = "The method '{0}' cannot be used as a Lambda Handler because it is an 'async void' method. Handler methods cannot be 'async void'. Please specify a method that is not 'async void'.";
public const string HandlerMethodParams = "The method '{0}' cannot be used as a Lambda Handler because it is a 'params' method. Please specify a method that does not use 'params'.";
public const string HandlerMethodVararg = "The method '{0}' cannot be used as a Lambda Handler because it is a 'vararg (variable arguments)' method. Please specify a method that is not 'vararg'.";
public const string TypeMissingLogMethod = "The type '{0}' does not contain expected method 'Log'.";
public const string TypeNotMatchingShape = "The type '{0}' does not match the expected shape of '{1}': '{2}'.";
public const string TypeMissingExpectedProperty = "The type '{0}' does not contain expected property '{1}' of type '{2}'.";
public const string PropertyNotReadable = "The property '{0}' of type '{1}' is not readable.";
public const string ILambdaSerializerMismatch_TypeNotInterface = "Type {0} is not an interface.";
public const string ILambdaSerializerMismatch_DeserializeMethodNotFound = "Deserialize' method not found.";
public const string ILambdaSerializerMismatch_DeserializeMethodNotGeneric = "Deserialize' method is not generic, expected to be generic.";
public const string ILambdaSerializerMismatch_DeserializeMethodHasTooManyParams = "Deserialize' method has '{0}' parameters, expected '1'.";
public const string ILambdaSerializerMismatch_DeserializeMethodHasWrongParam = "Deserialize' method has parameter of type '{0}', expected type '{1}'.";
public const string ILambdaSerializerMismatch_DeserializeMethodHasWrongNumberGenericArgs = "Deserialize' method has '{0}' generic arguments, expected '1'.";
public const string ILambdaSerializerMismatch_DeserializeMethodHasWrongReturn = "Deserialize' method has return type of '{0}', expected 'T'.";
public const string ILambdaSerializerMismatch_SerializeMethodNotFound = "Serialize' method not found.";
public const string ILambdaSerializerMismatch_SerializeMethodNotGeneric = "Serialize' method is not generic, expected to be generic.";
public const string ILambdaSerializerMismatch_SerializeMethodHasWrongReturn = "Serialize' method has return type of '{0}', expected 'void'.";
public const string ILambdaSerializerMismatch_SerializeMethodHasWrongNumberOfParameters = "Serialize' method has '{0}' parameters, expected '2'.";
public const string ILambdaSerializerMismatch_SerializeMethodHasWrongNumberGenericArgs = "Serialize' method has '{0}' generic arguments, expected '1'.";
public const string ILambdaSerializerMismatch_SerializeMethodHasWrongFirstParam = "Serialize' method's first parameter is of type '{0}', expected 'T'.";
public const string ILambdaSerializerMismatch_SerializeMethodHasWrongSecondParam = "Serialize' method's second parameter is of type '{0}', expected '{1}'.";
public const string MethodHasOverloads = "The method '{0}' in type '{1}' appears to have a number of overloads. To call this method please specify a complete method signature. Possible candidates are:\n{2}.";
}
internal static class HandlerInfo
{
public const string EmptyHandler = "Empty lambda function handler. The valid format is 'ASSEMBLY{0}TYPE{1}METHOD'.";
public const string InvalidHandler = "Invalid lambda function handler: '{0}'. The valid format is 'ASSEMBLY{1}TYPE{2}METHOD'.";
public const string MissingAssembly = "Invalid lambda function handler: '{0}', the assembly is missing. The valid format is 'ASSEMBLY{1}TYPE{2}METHOD'.";
public const string MissingType = "Invalid lambda function handler: '{0}', the type is missing. The valid format is 'ASSEMBLY{1}TYPE{2}METHOD'.";
public const string MissingMethod = "Invalid lambda function handler: '{0}', the method is missing. The valid format is 'ASSEMBLY{1}TYPE{2}METHOD'.";
}
internal static class LambdaBootstrap
{
internal static class Internal
{
public const string LambdaResponseTooLong = "The Lambda function returned a response that is too long to serialize. The response size limit for a Lambda function is 6MB.";
}
}
}
}
| 92 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Amazon.Lambda.RuntimeSupport
{
/// <summary>
/// Class to hold basic raw information extracted from Exceptions.
/// The raw information will be formatted as JSON to be reported to the Lambda Runtime API.
/// </summary>
internal class ExceptionInfo
{
public string ErrorMessage { get; set; }
public string ErrorType { get; set; }
public StackFrameInfo[] StackFrames { get; set; }
public string StackTrace { get; set; }
public ExceptionInfo InnerException { get; set; }
public List<ExceptionInfo> InnerExceptions { get; internal set; } = new List<ExceptionInfo>();
public Exception OriginalException { get; set; }
public ExceptionInfo() { }
public ExceptionInfo(Exception exception, bool isNestedException = false)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
ErrorType = exception.GetType().Name;
ErrorMessage = exception.Message;
if (!string.IsNullOrEmpty(exception.StackTrace))
{
StackTrace stackTrace = new StackTrace(exception, true);
StackTrace = stackTrace.ToString();
// Only extract the stack frames like this for the top-level exception
// This is used for Xray Exception serialization
if (isNestedException || stackTrace?.GetFrames() == null)
{
StackFrames = new StackFrameInfo[0];
}
else
{
StackFrames = (
from sf in stackTrace.GetFrames()
where sf != null
select new StackFrameInfo(sf)
).ToArray();
}
}
if (exception.InnerException != null)
{
InnerException = new ExceptionInfo(exception.InnerException, true);
}
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null && aggregateException.InnerExceptions != null)
{
foreach (var innerEx in aggregateException.InnerExceptions)
{
InnerExceptions.Add(new ExceptionInfo(innerEx, true));
}
}
}
public static ExceptionInfo GetExceptionInfo(Exception exception)
{
return new ExceptionInfo(exception);
}
}
}
| 92 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Text;
namespace Amazon.Lambda.RuntimeSupport
{
internal class JsonExceptionWriterHelpers
{
/// <summary>
/// This method escapes a string for use as a JSON string value.
/// It was adapted from the PutString method in the LitJson.JsonWriter class.
///
/// TODO: rewrite the *JsonExceptionWriter classes to use a JSON library instead of building strings directly.
/// </summary>
/// <param name="str"></param>
public static string EscapeStringForJson(string str)
{
if (str == null)
return null;
int n = str.Length;
var sb = new StringBuilder(n * 2);
for (int i = 0; i < n; i++)
{
char c = str[i];
switch (c)
{
case '\n':
sb.Append(@"\n");
break;
case '\r':
sb.Append(@"\r");
break;
case '\t':
sb.Append(@"\t");
break;
case '"':
sb.Append(@"\""");
break;
case '\\':
sb.Append(@"\\");
break;
case '\f':
sb.Append(@"\f");
break;
case '\b':
sb.Append(@"\b");
break;
case '\u0085': // Next Line
sb.Append(@"\u0085");
break;
case '\u2028': // Line Separator
sb.Append(@"\u2028");
break;
case '\u2029': // Paragraph Separator
sb.Append(@"\u2029");
break;
default:
if (c < ' ')
{
// Turn into a \uXXXX sequence
sb.Append(@"\u");
sb.Append(IntToHex((int)c));
}
else
{
sb.Append(c);
}
break;
}
}
return sb.ToString().Trim();
}
private static char[] IntToHex(int n)
{
int num;
char[] hex = new char[4];
for (int i = 0; i < 4; i++)
{
num = n % 16;
if (num < 10)
hex[3 - i] = (char)('0' + num);
else
hex[3 - i] = (char)('A' + (num - 10));
n >>= 4;
}
return hex;
}
}
}
| 118 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Globalization;
namespace Amazon.Lambda.RuntimeSupport.ExceptionHandling
{
/// <summary>
/// Static methods for formatting and creating Lambda exceptions.
/// </summary>
internal static class LambdaExceptions
{
/// <summary>
/// Creates LambdaValidationException with specified messageFormat,
/// and arguments.
/// If an exception is encountered when formatting the string, messageFormat
/// is used as the message.
/// </summary>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
/// <returns></returns>
public static LambdaValidationException ValidationException(string messageFormat, params object[] args)
{
return new LambdaValidationException(FormatMessage(messageFormat, args));
}
/// <summary>
/// Creates LambdaValidationException with specified inner exception,
/// messageFormat, and arguments.
/// If an exception is encountered when formatting the string, messageFormat
/// is used as the message.
/// </summary>
/// <param name="innerException"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
/// <returns></returns>
public static LambdaValidationException ValidationException(Exception innerException, string messageFormat, params object[] args)
{
return new LambdaValidationException(FormatMessage(messageFormat, args), innerException);
}
/// <summary>
/// Attempts to create a string from the specified format and arguments.
/// If string.Format fails, messageFormat is returned as the message.
/// </summary>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
/// <returns></returns>
public static string FormatMessage(string messageFormat, params object[] args)
{
string message;
try
{
message = string.Format(CultureInfo.InvariantCulture, messageFormat, args);
}
catch
{
// if Format fails, go with the unformatted message, so customer at least
// has some sort of clue of what went wrong
message = messageFormat;
}
return message;
}
}
} | 79 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.Lambda.RuntimeSupport
{
// TODO rewrite using a JSON library
internal class LambdaJsonExceptionWriter
{
private static readonly Encoding TEXT_ENCODING = Encoding.UTF8;
private const int INDENT_SIZE = 2;
private const int MAX_PAYLOAD_SIZE = 256 * 1024; // 256KB
private const string ERROR_MESSAGE = "errorMessage";
private const string ERROR_TYPE = "errorType";
private const string STACK_TRACE = "stackTrace";
private const string INNER_EXCEPTION = "cause";
private const string INNER_EXCEPTIONS = "causes";
private const string TRUNCATED_MESSAGE =
"{\"" + ERROR_MESSAGE + "\": \"Exception exceeded maximum payload size of 256KB.\"}";
/// <summary>
/// Write the formatted JSON response for this exception, and all inner exceptions.
/// </summary>
/// <param name="ex">The exception response object to serialize.</param>
/// <returns>The serialized JSON string.</returns>
public static string WriteJson(ExceptionInfo ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
MeteredStringBuilder jsonBuilder = new MeteredStringBuilder(TEXT_ENCODING, MAX_PAYLOAD_SIZE);
string json = AppendJson(ex, 0, false, MAX_PAYLOAD_SIZE - jsonBuilder.SizeInBytes);
if (json != null && jsonBuilder.HasRoomForString(json))
{
jsonBuilder.Append(json);
}
else
{
jsonBuilder.Append(TRUNCATED_MESSAGE);
}
return jsonBuilder.ToString();
}
private static string AppendJson(ExceptionInfo ex, int tab, bool appendComma, int remainingRoom)
{
if (remainingRoom <= 0)
return null;
MeteredStringBuilder jsonBuilder = new MeteredStringBuilder(TEXT_ENCODING, remainingRoom);
int nextTabDepth = tab + 1;
int nextNextTabDepth = nextTabDepth + 1;
List<string> jsonElements = new List<string>();
// Grab the elements we want to capture
string message = JsonExceptionWriterHelpers.EscapeStringForJson(ex.ErrorMessage);
string type = JsonExceptionWriterHelpers.EscapeStringForJson(ex.ErrorType);
string stackTrace = ex.StackTrace;
ExceptionInfo innerException = ex.InnerException;
List<ExceptionInfo> innerExceptions = ex.InnerExceptions;
// Create the JSON lines for each non-null element
string messageJson = null;
if (message != null)
{
// Trim important for Aggregate Exceptions, whose
// message contains multiple lines by default
messageJson = TabString($"\"{ERROR_MESSAGE}\": \"{message}\"", nextTabDepth);
}
string typeJson = TabString($"\"{ERROR_TYPE}\": \"{type}\"", nextTabDepth);
string stackTraceJson = GetStackTraceJson(stackTrace, nextTabDepth);
// Add each non-null element to the json elements list
if (typeJson != null) jsonElements.Add(typeJson);
if (messageJson != null) jsonElements.Add(messageJson);
if (stackTraceJson != null) jsonElements.Add(stackTraceJson);
// Exception JSON body, comma delimited
string exceptionJsonBody = string.Join("," + Environment.NewLine, jsonElements);
jsonBuilder.AppendLine(TabString("{", tab));
jsonBuilder.Append(exceptionJsonBody);
bool hasInnerException = innerException != null;
bool hasInnerExceptionList = innerExceptions != null && innerExceptions.Count > 0;
// Before we close, check for inner exception(s)
if (hasInnerException)
{
// We have to add the inner exception, which means we need
// another comma after the exception json body
jsonBuilder.AppendLine(",");
jsonBuilder.Append(TabString($"\"{INNER_EXCEPTION}\": ", nextTabDepth));
string innerJson = AppendJson(innerException, nextTabDepth, hasInnerExceptionList, remainingRoom - jsonBuilder.SizeInBytes);
if (innerJson != null && jsonBuilder.HasRoomForString(innerJson))
{
jsonBuilder.Append(innerJson);
}
else
{
jsonBuilder.AppendLine(TRUNCATED_MESSAGE);
}
}
if (hasInnerExceptionList)
{
jsonBuilder.Append(TabString($"\"{INNER_EXCEPTIONS}\": [", nextTabDepth));
for (int i = 0; i < innerExceptions.Count; i++)
{
var isLastOne = i == innerExceptions.Count - 1;
var innerException2 = innerExceptions[i];
string innerJson = AppendJson(innerException2, nextNextTabDepth, !isLastOne, remainingRoom - jsonBuilder.SizeInBytes);
if (innerJson != null && jsonBuilder.HasRoomForString(innerJson))
{
jsonBuilder.Append(innerJson);
}
else
{
jsonBuilder.AppendLine(TabString(TRUNCATED_MESSAGE, nextNextTabDepth));
break;
}
}
jsonBuilder.AppendLine(TabString($"]", nextTabDepth));
}
if (!hasInnerException && !hasInnerExceptionList)
{
// No inner exceptions = no trailing comma needed
jsonBuilder.AppendLine();
}
jsonBuilder.AppendLine(TabString("}" + (appendComma ? "," : ""), tab));
return jsonBuilder.ToString();
}
private static string GetStackTraceJson(string stackTrace, int tab)
{
if (stackTrace == null)
{
return null;
}
string[] stackTraceElements = stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Trim())
.Where(s => !String.IsNullOrWhiteSpace(s))
.Select(s => TabString(($"\"{JsonExceptionWriterHelpers.EscapeStringForJson(s)}\""), tab + 1))
.ToArray();
if (stackTraceElements.Length == 0)
{
return null;
}
StringBuilder stackTraceBuilder = new StringBuilder();
stackTraceBuilder.AppendLine(TabString($"\"{STACK_TRACE}\": [", tab));
stackTraceBuilder.AppendLine(string.Join("," + Environment.NewLine, stackTraceElements));
stackTraceBuilder.Append(TabString("]", tab));
return stackTraceBuilder.ToString();
}
private static string TabString(string str, int tabDepth)
{
if (tabDepth == 0) return str;
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0; x < tabDepth * INDENT_SIZE; x++)
{
stringBuilder.Append(" ");
}
stringBuilder.Append(str);
return stringBuilder.ToString();
}
}
}
| 198 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
namespace Amazon.Lambda.RuntimeSupport.ExceptionHandling
{
///<summary>
/// An exception indicating that one of the inputs provided by the user
/// is not valid. This can indicate an error in the handler string (invalid format
/// or non-existent assembly/type/method), error in the type (abstract / generic),
/// error in the method (invalid signature, generic, overloads, or params/varargs),
/// or an error in the Serializer (lacking attribute, invalid type in attribute).
/// The message in this exception is retained when returning the exception to the user.
/// This exception should not have any inner exceptions.
/// Ref: https://w.amazon.com/bin/view/AWS/DeveloperResources/AWSSDKsAndTools/NetSDK/NetLambda/Design/ExceptionHandling/
/// </summary>
internal sealed class LambdaValidationException : Exception
{
/// <summary>
/// Construct instance of LambdaValidationException
/// </summary>
/// <param name="message">The message to display to the user.</param>
public LambdaValidationException(string message)
: base(message)
{
}
/// <summary>
/// Construct instance of LambdaValidationException
/// </summary>
/// <param name="message">The message to display to the user.</param>
/// <param name="innerException">The cause of this exception.</param>
public LambdaValidationException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | 51 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Linq;
using System.Text;
namespace Amazon.Lambda.RuntimeSupport
{
internal class LambdaXRayExceptionWriter
{
private const int INDENT_SIZE = 2;
private const string EXCEPTION = "exceptions";
private const string WORKING_DIR = "working_directory";
private const string PATHS = "paths";
private const string ERROR_MESSAGE = "message";
private const string ERROR_TYPE = "type";
private const string STACK_TRACE = "stack";
private const string STACK_FRAME_METHOD = "label";
private const string STACK_FRAME_FILE = "path";
private const string STACK_FRAME_LINE = "line";
public static string WriteJson(ExceptionInfo ex)
{
string workingDir = JsonExceptionWriterHelpers.EscapeStringForJson(System.IO.Directory.GetCurrentDirectory());
string exceptionTxt = CreateExceptionJson(ex, 1);
string workingDirJson = TabString($"\"{WORKING_DIR}\": \"{workingDir}\"", 1);
string exceptionJson = TabString($"\"{EXCEPTION}\": [ {exceptionTxt} ]", 1);
var paths = new string[0];
// Build the paths list by getting all the unique file names in the stack trace elements
if (ex.StackFrames != null)
{
paths = (
from sf in ex.StackFrames
where sf.Path != null
select "\"" + JsonExceptionWriterHelpers.EscapeStringForJson(sf.Path) + "\""
).Distinct().ToArray();
}
StringBuilder pathsBuilder = new StringBuilder();
pathsBuilder.Append(TabString($"\"{PATHS}\": ", 1));
pathsBuilder.Append(CombinePartsIntoJsonObject(2, '[', ']', paths));
string pathsJson = pathsBuilder.ToString();
// Add each non-null element to the json elements list
string[] jsonElements = GetNonNullElements(workingDirJson, exceptionJson, pathsJson);
return CombinePartsIntoJsonObject(1, '{', '}', jsonElements.ToArray());
}
private static string CreateExceptionJson(ExceptionInfo ex, int tab)
{
// Grab the elements we want to capture
string message = JsonExceptionWriterHelpers.EscapeStringForJson(ex.ErrorMessage);
string type = JsonExceptionWriterHelpers.EscapeStringForJson(ex.ErrorType);
var stackTrace = ex.StackFrames;
// Create the JSON lines for each non-null element
string messageJson = null;
if (message != null)
{
// Trim important for Aggregate Exceptions, whose
// message contains multiple lines by default
messageJson = TabString($"\"{ERROR_MESSAGE}\": \"{message}\"", tab + 1);
}
string typeJson = TabString($"\"{ERROR_TYPE}\": \"{type}\"", tab + 1);
string stackTraceJson = GetStackTraceJson(stackTrace, tab + 1);
// Add each non-null element to the json elements list
string[] jsonElements = GetNonNullElements(typeJson, messageJson, stackTraceJson);
return CombinePartsIntoJsonObject(tab + 1, '{', '}', jsonElements);
}
// Craft the JSON element (ex: "stack": [ {...}, {...} ]) for the stack trace
private static string GetStackTraceJson(StackFrameInfo[] stackTrace, int tab)
{
// Null stack trace means the entire stack trace json should be null, and therefore not included
if (stackTrace == null)
{
return null;
}
// Convert each ExceptionStackFrameResponse object to string using CreateStackFrameJson
string[] stackTraceElements = (
from frame in stackTrace
where frame != null
select CreateStackFrameJson(frame, tab + 1)
).ToArray();
// If there aren't any frames, return null and therefore don't include the stack trace
if (stackTraceElements.Length == 0)
{
return null;
}
// Create JSON property name and create the JSON array holding each element
StringBuilder stackTraceBuilder = new StringBuilder();
stackTraceBuilder.Append(TabString($"\"{STACK_TRACE}\": ", tab));
stackTraceBuilder.Append(CombinePartsIntoJsonObject(tab + 1, '[', ']', stackTraceElements));
return stackTraceBuilder.ToString();
}
// Craft JSON object {...} for a particular stack frame
private static string CreateStackFrameJson(StackFrameInfo stackFrame, int tab)
{
string file = JsonExceptionWriterHelpers.EscapeStringForJson(stackFrame.Path);
string label = JsonExceptionWriterHelpers.EscapeStringForJson(stackFrame.Label);
int line = stackFrame.Line;
string fileJson = null;
string lineJson = null;
if (file != null)
{
fileJson = TabString($"\"{STACK_FRAME_FILE}\": \"{file}\"", tab);
lineJson = TabString($"\"{STACK_FRAME_LINE}\": {line}", tab);
}
string labelJson = null;
if (label != null)
{
labelJson = TabString($"\"{STACK_FRAME_METHOD}\": \"{label}\"", tab);
}
string[] jsonElements = GetNonNullElements(fileJson, labelJson, lineJson);
return CombinePartsIntoJsonObject(tab, '{', '}', jsonElements);
}
private static string TabString(string str, int tabDepth)
{
if (tabDepth == 0) return str;
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0; x < tabDepth * INDENT_SIZE; x++)
{
stringBuilder.Append(" ");
}
stringBuilder.Append(str);
return stringBuilder.ToString();
}
private static string CombinePartsIntoJsonObject(int tab, char openChar, char closeChar, params string[] parts)
{
string jsonBody = string.Join(",", parts);
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append(TabString(openChar.ToString(), tab));
jsonBuilder.Append(jsonBody);
jsonBuilder.Append(TabString(closeChar.ToString(), tab));
return jsonBuilder.ToString();
}
private static string[] GetNonNullElements(params string[] elements)
{
return (from x in elements where x != null select x).ToArray();
}
}
}
| 174 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Text;
namespace Amazon.Lambda.RuntimeSupport
{
internal class MeteredStringBuilder
{
private readonly int _maxSize;
private readonly Encoding _encoding;
private readonly StringBuilder _stringBuilder;
public int SizeInBytes { get; private set; }
public MeteredStringBuilder(Encoding encoding, int maxSize)
{
if (maxSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxSize));
}
_stringBuilder = new StringBuilder();
SizeInBytes = 0;
_encoding = encoding ?? throw new ArgumentNullException(nameof(encoding));
_maxSize = maxSize;
}
public void Append(string str)
{
int strSizeInBytes = _encoding.GetByteCount(str);
_stringBuilder.Append(str);
SizeInBytes += strSizeInBytes;
}
public void AppendLine(string str)
{
string strWithLine = str + Environment.NewLine;
int strSizeInBytes = _encoding.GetByteCount(strWithLine);
_stringBuilder.Append(strWithLine);
SizeInBytes += strSizeInBytes;
}
public void AppendLine()
{
AppendLine("");
}
public bool HasRoomForString(string str)
{
return SizeInBytes + _encoding.GetByteCount(str) < _maxSize;
}
public override string ToString()
{
return _stringBuilder.ToString();
}
}
}
| 73 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Diagnostics;
namespace Amazon.Lambda.RuntimeSupport
{
internal class StackFrameInfo
{
public StackFrameInfo(string path, int line, string label)
{
Path = path;
Line = line;
Label = label;
}
public StackFrameInfo(StackFrame stackFrame)
{
Path = stackFrame.GetFileName();
Line = stackFrame.GetFileLineNumber();
var method = stackFrame.GetMethod();
if (method != null)
{
var methodTypeName = method.DeclaringType?.Name;
if (methodTypeName == null)
{
Label = method.Name;
}
else
{
Label = methodTypeName + "." + method.Name;
}
}
}
public string Path { get; }
public int Line { get; }
public string Label { get; }
}
}
| 54 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Lambda.RuntimeSupport.Bootstrap;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
/// <summary>
/// Interface used by bootstrap to format logging message as well as Console WriteLine messages.
/// </summary>
public interface IConsoleLoggerWriter
{
/// <summary>
/// The current aws request id
/// </summary>
/// <param name="awsRequestId"></param>
void SetCurrentAwsRequestId(string awsRequestId);
/// <summary>
/// Format message with default log level
/// </summary>
/// <param name="message"></param>
void FormattedWriteLine(string message);
/// <summary>
/// Format message with given log level
/// </summary>
/// <param name="level"></param>
/// <param name="message"></param>
void FormattedWriteLine(string level, string message);
}
/// <summary>
/// Simple logger to maintain compatibility with versions of .NET before .NET 6
/// </summary>
public class SimpleLoggerWriter : IConsoleLoggerWriter
{
TextWriter _writer;
public SimpleLoggerWriter()
{
// Look to see if Lambda's telemetry log file descriptor is available. If so use that for logging.
// This will make sure multiline log messages use a single CloudWatch Logs record.
var fileDescriptorLogId = Environment.GetEnvironmentVariable(Constants.ENVIRONMENT_VARIABLE_TELEMETRY_LOG_FD);
if (fileDescriptorLogId != null)
{
try
{
_writer = FileDescriptorLogFactory.GetWriter(fileDescriptorLogId);
InternalLogger.GetDefaultLogger().LogInformation("Using file descriptor stream writer for logging");
}
catch (Exception ex)
{
_writer = Console.Out;
InternalLogger.GetDefaultLogger().LogError(ex, "Error creating file descriptor log stream writer. Fallback to stdout.");
}
}
else
{
_writer = Console.Out;
InternalLogger.GetDefaultLogger().LogInformation("Using stdout for logging");
}
}
public void SetCurrentAwsRequestId(string awsRequestId)
{
}
public void FormattedWriteLine(string message)
{
_writer.WriteLine(message);
}
public void FormattedWriteLine(string level, string message)
{
_writer.WriteLine(message);
}
}
#if NET6_0_OR_GREATER
/// <summary>
/// Formats log messages with time, request id, log level and message
/// </summary>
public class LogLevelLoggerWriter : IConsoleLoggerWriter
{
/// <summary>
/// A mirror of the LogLevel defined in Amazon.Lambda.Core. The version in
/// Amazon.Lambda.Core can not be relied on because the Lambda Function could be using
/// an older version of Amazon.Lambda.Core before LogLevel existed in Amazon.Lambda.Core.
/// </summary>
enum LogLevel
{
/// <summary>
/// Trace level logging
/// </summary>
Trace = 0,
/// <summary>
/// Debug level logging
/// </summary>
Debug = 1,
/// <summary>
/// Information level logging
/// </summary>
Information = 2,
/// <summary>
/// Warning level logging
/// </summary>
Warning = 3,
/// <summary>
/// Error level logging
/// </summary>
Error = 4,
/// <summary>
/// Critical level logging
/// </summary>
Critical = 5
}
WrapperTextWriter _wrappedStdOutWriter;
WrapperTextWriter _wrappedStdErrorWriter;
/// <summary>
/// Constructor used by bootstrap to put in place a wrapper TextWriter around stdout and stderror so all Console.WriteLine calls
/// will be formatted.
///
/// Stdout will default log messages to be Information
/// Stderror will default log messages to be Error
/// </summary>
public LogLevelLoggerWriter()
{
// Look to see if Lambda's telemetry log file descriptor is available. If so use that for logging.
// This will make sure multiline log messages use a single CloudWatch Logs record.
var fileDescriptorLogId = Environment.GetEnvironmentVariable(Constants.ENVIRONMENT_VARIABLE_TELEMETRY_LOG_FD);
if (fileDescriptorLogId != null)
{
try
{
var stdOutWriter = FileDescriptorLogFactory.GetWriter(fileDescriptorLogId);
var stdErrorWriter = FileDescriptorLogFactory.GetWriter(fileDescriptorLogId);
Initialize(stdOutWriter, stdErrorWriter);
InternalLogger.GetDefaultLogger().LogInformation("Using file descriptor stream writer for logging.");
}
catch(Exception ex)
{
InternalLogger.GetDefaultLogger().LogError(ex, "Error creating file descriptor log stream writer. Fallback to stdout and stderr.");
Initialize(Console.Out, Console.Error);
}
}
else
{
Initialize(Console.Out, Console.Error);
InternalLogger.GetDefaultLogger().LogInformation("Using stdout and stderr for logging.");
}
// SetOut will wrap our WrapperTextWriter with a synchronized TextWriter. Pass in the new synchronized
// TextWriter into our writer to make sure we obtain a lock on that instance before writing to the stdout.
Console.SetOut(_wrappedStdOutWriter);
_wrappedStdOutWriter.LockObject = Console.Out;
Console.SetError(_wrappedStdErrorWriter);
_wrappedStdErrorWriter.LockObject = Console.Error;
ConfigureLoggingActionField();
}
public LogLevelLoggerWriter(TextWriter stdOutWriter, TextWriter stdErrorWriter)
{
Initialize(stdOutWriter, stdErrorWriter);
}
private void Initialize(TextWriter stdOutWriter, TextWriter stdErrorWriter)
{
_wrappedStdOutWriter = new WrapperTextWriter(stdOutWriter, LogLevel.Information.ToString());
_wrappedStdErrorWriter = new WrapperTextWriter(stdErrorWriter, LogLevel.Error.ToString());
}
/// <summary>
/// Set a special callback on Amazon.Lambda.Core.LambdaLogger to redirect its logging to FormattedWriteLine.
/// This allows outputting logging with time and request id but not have LogLevel. This is important for
/// Amazon.Lambda.Logging.AspNetCore which already provides a string with a log level.
/// </summary>
private void ConfigureLoggingActionField()
{
var lambdaILoggerType = typeof(Amazon.Lambda.Core.LambdaLogger);
if (lambdaILoggerType == null)
return;
var loggingActionField = lambdaILoggerType.GetTypeInfo().GetField("_loggingAction", BindingFlags.NonPublic | BindingFlags.Static);
if (loggingActionField == null)
return;
Action<string> callback = (message => FormattedWriteLine(null, message));
loggingActionField.SetValue(null, callback);
}
public void SetCurrentAwsRequestId(string awsRequestId)
{
_wrappedStdOutWriter.CurrentAwsRequestId = awsRequestId;
_wrappedStdErrorWriter.CurrentAwsRequestId = awsRequestId;
}
public void FormattedWriteLine(string message)
{
_wrappedStdOutWriter.FormattedWriteLine(message);
}
public void FormattedWriteLine(string level, string message)
{
_wrappedStdOutWriter.FormattedWriteLine(level, message);
}
/// <summary>
/// Wraps around a provided TextWriter. In normal usage the wrapped TextWriter will either be stdout or stderr.
/// For all calls besides WriteLine and WriteLineAsync call into the wrapped TextWriter. For the WriteLine and WriteLineAsync
/// format the message with time, request id, log level and the provided message.
/// </summary>
class WrapperTextWriter : TextWriter
{
private readonly TextWriter _innerWriter;
private string _defaultLogLevel;
const string LOG_LEVEL_ENVIRONMENT_VARIABLE = "AWS_LAMBDA_HANDLER_LOG_LEVEL";
const string LOG_FORMAT_ENVIRONMENT_VARIABLE = "AWS_LAMBDA_HANDLER_LOG_FORMAT";
private LogLevel _minmumLogLevel = LogLevel.Information;
enum LogFormatType { Default, Unformatted }
private LogFormatType _logFormatType = LogFormatType.Default;
public string CurrentAwsRequestId { get; set; } = string.Empty;
/// <summary>
/// This is typically set to either Console.Out or Console.Error to make sure we acquiring a lock
/// on that object whenever we are going through FormattedWriteLine. This is important for
/// logging that goes through ILambdaLogger that skips going through Console.WriteX. Without
/// this ILambdaLogger only acquires one lock but Console.WriteX acquires 2 locks and we can get deadlocks.
/// </summary>
internal object LockObject { get; set; } = new object();
public WrapperTextWriter(TextWriter innerWriter, string defaultLogLevel)
{
_innerWriter = innerWriter;
_defaultLogLevel = defaultLogLevel;
var envLogLevel = Environment.GetEnvironmentVariable(LOG_LEVEL_ENVIRONMENT_VARIABLE);
if (!string.IsNullOrEmpty(envLogLevel))
{
if (Enum.TryParse<LogLevel>(envLogLevel, true, out var result))
{
_minmumLogLevel = result;
}
}
var envLogFormat = Environment.GetEnvironmentVariable(LOG_FORMAT_ENVIRONMENT_VARIABLE);
if (!string.IsNullOrEmpty(envLogFormat))
{
if (Enum.TryParse<LogFormatType>(envLogFormat, true, out var result))
{
_logFormatType = result;
}
}
}
internal void FormattedWriteLine(string message)
{
FormattedWriteLine(_defaultLogLevel, message);
}
internal void FormattedWriteLine(string level, string message)
{
lock(LockObject)
{
var displayLevel = level;
if (Enum.TryParse<LogLevel>(level, true, out var levelEnum))
{
if (levelEnum < _minmumLogLevel)
return;
displayLevel = ConvertLogLevelToLabel(levelEnum);
}
if (_logFormatType == LogFormatType.Unformatted)
{
_innerWriter.WriteLine(message);
}
else
{
string line;
if (!string.IsNullOrEmpty(displayLevel))
{
line = $"{DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")}\t{CurrentAwsRequestId}\t{displayLevel}\t{message ?? string.Empty}";
}
else
{
line = $"{DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")}\t{CurrentAwsRequestId}\t{message ?? string.Empty}";
}
_innerWriter.WriteLine(line);
}
}
}
private Task FormattedWriteLineAsync(string message)
{
FormattedWriteLine(message);
return Task.CompletedTask;
}
/// <summary>
/// Convert LogLevel enums to the the same string label that console provider for Microsoft.Extensions.Logging.ILogger uses.
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
private string ConvertLogLevelToLabel(LogLevel level)
{
switch (level)
{
case LogLevel.Trace:
return "trce";
case LogLevel.Debug:
return "dbug";
case LogLevel.Information:
return "info";
case LogLevel.Warning:
return "warn";
case LogLevel.Error:
return "fail";
case LogLevel.Critical:
return "crit";
}
return level.ToString();
}
#region WriteLine redirects to formatting
[CLSCompliant(false)]
public override void WriteLine(ulong value) => FormattedWriteLine(value.ToString(FormatProvider));
[CLSCompliant(false)]
public override void WriteLine(uint value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(string format, params object[] arg) => FormattedWriteLine(string.Format(format, arg));
public override void WriteLine(string format, object arg0, object arg1, object arg2) => FormattedWriteLine(string.Format(format, arg0, arg1, arg2));
public override void WriteLine(string format, object arg0) => FormattedWriteLine(string.Format(format, arg0));
public override void WriteLine(string value) => FormattedWriteLine(value);
public override void WriteLine(float value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(string format, object arg0, object arg1) => FormattedWriteLine(string.Format(format, arg0, arg1));
public override void WriteLine(object value) => FormattedWriteLine(value == null ? String.Empty : value.ToString());
public override void WriteLine(bool value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(char value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(char[] buffer) => FormattedWriteLine(buffer == null ? String.Empty : new string(buffer));
public override void WriteLine() => FormattedWriteLine(string.Empty);
public override void WriteLine(decimal value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(double value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(int value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(long value) => FormattedWriteLine(value.ToString(FormatProvider));
public override void WriteLine(char[] buffer, int index, int count) => FormattedWriteLine(new string(buffer, index, count));
public override Task WriteLineAsync(char value) => FormattedWriteLineAsync(value.ToString());
public Task WriteLineAsync(char[] buffer) => FormattedWriteLineAsync(buffer == null ? String.Empty : new string(buffer));
public override Task WriteLineAsync(char[] buffer, int index, int count) => FormattedWriteLineAsync(new string(buffer, index, count));
public override Task WriteLineAsync(string value) => FormattedWriteLineAsync(value);
public override Task WriteLineAsync() => FormattedWriteLineAsync(string.Empty);
public override void WriteLine(StringBuilder? value) => FormattedWriteLine(value?.ToString());
public override void WriteLine(ReadOnlySpan<char> buffer) => FormattedWriteLine(new string(buffer));
public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) => FormattedWriteLineAsync(new string(buffer.Span));
public override Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default) => FormattedWriteLineAsync(value?.ToString());
#endregion
#region Simple Redirects
public override Encoding Encoding => _innerWriter.Encoding;
public override IFormatProvider FormatProvider => _innerWriter.FormatProvider;
public override string NewLine
{
get { return _innerWriter.NewLine; }
set { _innerWriter.NewLine = value; }
}
public override void Close() => _innerWriter.Close();
public override void Flush() => _innerWriter.Flush();
public override Task FlushAsync() => _innerWriter.FlushAsync();
[CLSCompliant(false)]
public override void Write(ulong value) => _innerWriter.Write(value);
[CLSCompliant(false)]
public override void Write(uint value) => _innerWriter.Write(value);
public override void Write(string format, params object[] arg) => _innerWriter.Write(format, arg);
public override void Write(string format, object arg0, object arg1, object arg2) => _innerWriter.Write(format, arg0, arg1, arg2);
public override void Write(string format, object arg0, object arg1) => _innerWriter.Write(format, arg0, arg1);
public override void Write(string format, object arg0) => _innerWriter.Write(format, arg0);
public override void Write(string value) => _innerWriter.Write(value);
public override void Write(object value) => _innerWriter.Write(value);
public override void Write(long value) => _innerWriter.Write(value);
public override void Write(int value) => _innerWriter.Write(value);
public override void Write(double value) => _innerWriter.Write(value);
public override void Write(decimal value) => _innerWriter.Write(value);
public override void Write(char[] buffer, int index, int count) => _innerWriter.Write(buffer, index, count);
public override void Write(char[] buffer) => _innerWriter.Write(buffer);
public override void Write(char value) => _innerWriter.Write(value);
public override void Write(bool value) => _innerWriter.Write(value);
public override void Write(float value) => _innerWriter.Write(value);
public override Task WriteAsync(string value) => _innerWriter.WriteAsync(value);
public override Task WriteAsync(char[] buffer, int index, int count) => _innerWriter.WriteAsync(buffer, index, count);
public Task WriteAsync(char[] buffer) => _innerWriter.WriteAsync(buffer);
public override Task WriteAsync(char value) => _innerWriter.WriteAsync(value);
protected override void Dispose(bool disposing) => _innerWriter.Dispose();
public override void Write(StringBuilder? value) => _innerWriter.Write(value);
public override void Write(ReadOnlySpan<char> buffer) => _innerWriter.Write(buffer);
public override Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default) => _innerWriter.WriteAsync(value, cancellationToken);
public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) => _innerWriter.WriteAsync(buffer, cancellationToken);
public override ValueTask DisposeAsync() => _innerWriter.DisposeAsync();
#endregion
}
}
#endif
}
| 501 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
internal class DateTimeHelper : IDateTimeHelper
{
public DateTime UtcNow => DateTime.UtcNow;
}
} | 24 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.IO;
using System.Buffers;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Concurrent;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
/// <summary>
/// This class wraps the utility of writing to the Lambda telemetry file descriptor for logging into a standard .NET Stream.
/// The message
/// </summary>
public static class FileDescriptorLogFactory
{
private readonly static ConcurrentDictionary<string, StreamWriter> _writers = new ConcurrentDictionary<string, StreamWriter>();
// max cloudwatch log event size, 256k - 26 bytes of overhead.
internal const int MaxCloudWatchLogEventSize = 256 * 1024 - 26;
internal const int LambdaTelemetryLogHeaderLength = 16;
internal const uint LambdaTelemetryLogHeaderFrameType = 0xa55a0003;
internal static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>
/// Get the StreamWriter for the particular file descriptor ID. If the same ID is passed the same StreamWriter instance is returned.
/// </summary>
/// <param name="fileDescriptorId"></param>
/// <returns></returns>
public static StreamWriter GetWriter(string fileDescriptorId)
{
var writer = _writers.GetOrAdd(fileDescriptorId,
(x) => {
SafeFileHandle handle = new SafeFileHandle(new IntPtr(int.Parse(fileDescriptorId)), false);
return InitializeWriter(new FileStream(handle, FileAccess.Write));
});
return writer;
}
/// <summary>
/// Initialize a StreamWriter for the given Stream.
/// This method is internal as it is tested in Amazon.RuntimeSupport.Tests
/// </summary>
/// <param name="fileDescriptorStream"></param>
/// <returns></returns>
internal static StreamWriter InitializeWriter(Stream fileDescriptorStream)
{
// AutoFlush must be turned out otherwise the StreamWriter might not send the data to the stream before the Lambda function completes.
// Set the buffer size to the same max size as CloudWatch Logs records.
// Encoder has encoderShouldEmitUTF8Identifier = false as Lambda FD will assume UTF-8 so there is no need to emit an extra log entry.
// In fact this extra log entry is cast to UTF-8 and results in an empty log entry which will be rejected by CloudWatch Logs.
return new NonDisposableStreamWriter(new FileDescriptorLogStream(fileDescriptorStream),
new UTF8Encoding(false), MaxCloudWatchLogEventSize)
{ AutoFlush = true };
}
/// <summary>
/// Write log message to the file descriptor which will make sure the message is recorded as a single CloudWatch Log record.
/// The format of the message must be:
/// 0 4 8 16
/// +----------------------+------------------------+-----------------------+-----------------------+
/// | Frame Type - 4 bytes | Length (len) - 4 bytes | Timestamp - 8 bytes | Message - 'len' bytes |
/// +----------------------+------------------------+-----------------------+-----------------------+
/// The first 4 bytes are the frame type. For logs with timestamps this is always 0xa55a0003.
/// The second 4 bytes are the length of the message.
/// Next is 8 bytes timestamp of emitting the message expressed as microseconds since UNIX epoch.
/// The remaining bytes are the message itself. Byte order is big-endian.
/// </summary>
private class FileDescriptorLogStream : Stream
{
private readonly Stream _fileDescriptorStream;
private readonly byte[] _frameTypeBytes;
public FileDescriptorLogStream(Stream logStream)
{
_fileDescriptorStream = logStream;
_frameTypeBytes = BitConverter.GetBytes(LambdaTelemetryLogHeaderFrameType);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(_frameTypeBytes);
}
}
public override void Flush()
{
_fileDescriptorStream.Flush();
}
public override void Write(byte[] buffer, int offset, int count)
{
var messageLengthBytes = BitConverter.GetBytes(count - offset);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(messageLengthBytes);
}
var now = (DateTimeOffset.UtcNow - UnixEpoch).Ticks / 10; // There are 10 tick per microsecond
var nowInBytes = BitConverter.GetBytes(now);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(nowInBytes);
}
var typeAndLength = ArrayPool<byte>.Shared.Rent(LambdaTelemetryLogHeaderLength);
try
{
Buffer.BlockCopy(_frameTypeBytes, 0, typeAndLength, 0, 4);
Buffer.BlockCopy(messageLengthBytes, 0, typeAndLength, 4, 4);
Buffer.BlockCopy(nowInBytes, 0, typeAndLength, 8, 8);
_fileDescriptorStream.Write(typeAndLength, 0, LambdaTelemetryLogHeaderLength);
_fileDescriptorStream.Write(buffer, offset, count);
_fileDescriptorStream.Flush();
}
finally
{
ArrayPool<byte>.Shared.Return(typeAndLength);
}
}
#region Not implemented read and seek operations
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
#endregion
}
/// <summary>
/// This class is used to ensure the StreamWriter that is returned can not be unintentionally closed/disposed by users.
/// If we allow the stream to be closed/disposed then future logging in the Lambda function will fail with object disposed exceptions.
/// This situation was discovered for a function using NUnitLite to run tests and that library would trigger a dispose on Console.Out
/// https://github.com/nunit/nunit/blob/92180f13381621e308b01f0abd1a397cc1350c12/src/NUnitFramework/nunitlite/TextRunner.cs#L104
/// </summary>
class NonDisposableStreamWriter : StreamWriter
{
public NonDisposableStreamWriter(Stream stream, Encoding encoding, int buffersize)
: base(stream, encoding, buffersize)
{
}
protected override void Dispose(bool disposing)
{
// This StreamWriter must never be disposed. If disposed logging will fail in the function.
}
public override void Close()
{
// This StreamWriter must never be disposed. If disposed logging will fail in the function.
}
}
}
}
| 189 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Reflection;
using Amazon.Lambda.RuntimeSupport.ExceptionHandling;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
internal class HandlerInfo
{
/// <summary>
/// Separator for different handler components.
/// </summary>
public const string HandlerSeparator = "::";
/// <summary>
/// Name of the user assembly.
/// Does not contain ".dll" extension.
/// </summary>
public AssemblyName AssemblyName { get; }
/// <summary>
/// Full type name.
/// </summary>
public string TypeName { get; }
/// <summary>
/// Method name.
/// This value can be equal to MethodInfo.Name (such as "DownloadManifest"),
/// or it can be equal to MethodInfo.ToString() (such as "System.Uri DownloadManifest(Int64)")
/// </summary>
public string MethodName { get; }
/// <summary>
/// Constructs an instance of HandlerInfo for a given handler string.
/// </summary>
/// <param name="handler"></param>
public HandlerInfo(string handler)
{
if (string.IsNullOrEmpty(handler))
{
throw LambdaExceptions.ValidationException(Errors.HandlerInfo.EmptyHandler, HandlerSeparator, HandlerSeparator);
}
var parts = handler.Split(new[] {HandlerSeparator}, 3, StringSplitOptions.None);
if (parts.Length != 3)
{
throw LambdaExceptions.ValidationException(Errors.HandlerInfo.InvalidHandler, handler, HandlerSeparator, HandlerSeparator);
}
var assemblyName = parts[0].Trim();
if (string.IsNullOrEmpty(assemblyName))
{
throw LambdaExceptions.ValidationException(Errors.HandlerInfo.MissingAssembly, handler, HandlerSeparator, HandlerSeparator);
}
var typeName = parts[1].Trim();
if (string.IsNullOrEmpty(typeName))
{
throw LambdaExceptions.ValidationException(Errors.HandlerInfo.MissingType, handler, HandlerSeparator, HandlerSeparator);
}
var methodName = parts[2].Trim();
if (string.IsNullOrEmpty(methodName))
{
throw LambdaExceptions.ValidationException(Errors.HandlerInfo.MissingMethod, handler, HandlerSeparator, HandlerSeparator);
}
AssemblyName = new AssemblyName(assemblyName);
TypeName = typeName;
MethodName = methodName;
}
}
} | 87 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
internal interface IDateTimeHelper
{
DateTime UtcNow { get; }
}
} | 24 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
internal class InternalLogger
{
private const string DebuggingEnvironmentVariable = "LAMBDA_RUNTIMESUPPORT_DEBUG";
public static readonly InternalLogger ConsoleLogger = new InternalLogger(Console.WriteLine);
public static readonly InternalLogger NoOpLogger = new InternalLogger(message => { });
private readonly Action<string> _internalLoggingAction;
/// <summary>
/// Constructs InternalLogger which logs to the internalLoggingAction.
/// </summary>
/// <param name="internalLoggingAction"></param>
private InternalLogger(Action<string> internalLoggingAction)
{
_internalLoggingAction = internalLoggingAction;
if (_internalLoggingAction == null)
{
throw new ArgumentNullException(nameof(internalLoggingAction));
}
}
public void LogDebug(string message)
{
_internalLoggingAction($"[Debug] {message}");
}
public void LogError(Exception exception, string message)
{
_internalLoggingAction($"[Error] {message} - {exception.ToString()}");
}
public void LogInformation(string message)
{
_internalLoggingAction($"[Info] {message}");
}
/// <summary>
/// Gets an InternalLogger with a custom logging action.
/// Mainly used for unit testing
/// </summary>
/// <param name="loggingAction"></param>
/// <returns></returns>
public static InternalLogger GetCustomInternalLogger(Action<string> loggingAction)
{
return new InternalLogger(loggingAction);
}
/// <summary>
/// Gets the default logger for the environment based on the "LAMBDA_RUNTIMESUPPORT_DEBUG" environment variable
/// </summary>
/// <returns></returns>
public static InternalLogger GetDefaultLogger()
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DebuggingEnvironmentVariable)))
{
return NoOpLogger;
}
return ConsoleLogger;
}
}
} | 82 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Runtime.CompilerServices;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
internal static class NativeAotHelper
{
public static bool IsRunningNativeAot()
{
// If dynamic code is not supported we are most likely running in an AOT environment.
#if NET6_0_OR_GREATER
return !RuntimeFeature.IsDynamicCodeSupported;
#else
return false;
#endif
}
}
}
| 33 |
aws-lambda-dotnet | aws | C# | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
/// <summary>
/// RuntimeSupportDebugAttacher class responsible for waiting for a debugger to attach.
/// </summary>
public class RuntimeSupportDebugAttacher
{
private readonly InternalLogger _internalLogger;
private const string DebuggingEnvironmentVariable = "_AWS_LAMBDA_DOTNET_DEBUGGING";
/// <summary>
/// RuntimeSupportDebugAttacher constructor.
/// </summary>
public RuntimeSupportDebugAttacher()
{
_internalLogger = InternalLogger.ConsoleLogger;
}
/// <summary>
/// The function tries to wait for a debugger to attach.
/// </summary>
public async Task TryAttachDebugger()
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DebuggingEnvironmentVariable)))
{
return;
}
try
{
_internalLogger.LogInformation("Waiting for the debugger to attach...");
var timeout = DateTimeOffset.Now.Add(TimeSpan.FromMinutes(10));
while (!Debugger.IsAttached)
{
if (DateTimeOffset.Now > timeout)
{
_internalLogger.LogInformation("Timeout. Proceeding without debugger.");
return;
}
await Task.Delay(TimeSpan.FromMilliseconds(50));
}
}
catch (Exception ex)
{
_internalLogger.LogInformation($"An exception occurred while waiting for a debugger to attach. The exception details are as follows:\n{ex}");
}
}
}
}
| 72 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
namespace Amazon.Lambda.RuntimeSupport.Helpers
{
/// <summary>
/// Static methods for working with types
/// </summary>
internal static class Types
{
// Types only available by name
public const string IClientContextTypeName = "Amazon.Lambda.Core.IClientContext";
public const string IClientApplicationTypeName = "Amazon.Lambda.Core.IClientApplication";
public const string ICognitoIdentityTypeName = "Amazon.Lambda.Core.ICognitoIdentity";
public const string ILambdaContextTypeName = "Amazon.Lambda.Core.ILambdaContext";
public const string ILambdaLoggerTypeName = "Amazon.Lambda.Core.ILambdaLogger";
public const string ILambdaSerializerTypeName = "Amazon.Lambda.Core.ILambdaSerializer";
public const string LambdaLoggerTypeName = "Amazon.Lambda.Core.LambdaLogger";
public const string LambdaSerializerAttributeTypeName = "Amazon.Lambda.Core.LambdaSerializerAttribute";
// CLR types, lazily-loaded
public static Type AsyncStateMachineAttributeType => AsyncStateMachineAttributeTypeLazy.Value;
public static Type ParamArrayAttributeType => ParamArrayAttributeTypeLazy.Value;
public static Type StreamType => StreamTypeLazy.Value;
public static Type StringType => StringTypeLazy.Value;
public static Type TaskTType => TaskTTypeLazy.Value;
public static Type TaskType => TaskTypeLazy.Value;
public static Type TypeType => TypeTypeLazy.Value;
public static Type VoidType => VoidTypeLazy.Value;
// CLR types, lazily-loaded, backing fields
private static readonly Lazy<Type> AsyncStateMachineAttributeTypeLazy =
new Lazy<Type>(() => typeof(AsyncStateMachineAttribute));
private static readonly Lazy<Type> ParamArrayAttributeTypeLazy =
new Lazy<Type>(() => typeof(ParamArrayAttribute));
private static readonly Lazy<Type> StreamTypeLazy = new Lazy<Type>(() => typeof(Stream));
private static readonly Lazy<Type> StringTypeLazy = new Lazy<Type>(() => typeof(string));
private static readonly Lazy<Type> TaskTTypeLazy = new Lazy<Type>(() => typeof(Task<>));
private static readonly Lazy<Type> TaskTypeLazy = new Lazy<Type>(() => typeof(Task));
private static readonly Lazy<Type> TypeTypeLazy = new Lazy<Type>(() => typeof(Type));
private static readonly Lazy<Type> VoidTypeLazy = new Lazy<Type>(() => typeof(void));
/// <summary>
/// Returns true if type is ILambdaContext
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsILambdaContext(Type type)
{
return typeof(ILambdaContext).IsAssignableFrom(type);
}
/// <summary>
/// Returns true if type is LambdaSerializerAttribute (but not if type extends LambdaSerializerAttribute)
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsLambdaSerializerAttribute(Type type)
{
return string.Equals(type.FullName, LambdaSerializerAttributeTypeName, StringComparison.Ordinal);
}
}
} | 93 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.IO;
using Amazon.Lambda.RuntimeSupport.ExceptionHandling;
namespace Amazon.Lambda.RuntimeSupport.Serializers
{
/// <summary>
/// Data serializer that converts stream to stream
/// </summary>
internal class StreamSerializer
{
public static StreamSerializer Instance { get; } = new StreamSerializer();
/// <summary>
/// Deserializes a Lambda stream to the input type
/// </summary>
/// <param name="lambdaData"></param>
/// <returns></returns>
public Stream Deserialize(Stream lambdaData)
{
return lambdaData;
}
/// <summary>
/// Serializes the output type to a Lambda stream
/// </summary>
/// <param name="customerData"></param>
/// <param name="outStream"></param>
/// <returns></returns>
public void Serialize(Stream customerData, Stream outStream)
{
try
{
customerData.CopyTo(outStream);
}
catch (System.NotSupportedException e)
{
if (e.Message.Contains("Unable to expand length of this stream beyond its capacity"))
{
// This exception is thrown when returned stream is bigger than the customerData stream can handle.
// The limit is defined by LAMBDA_EVENT_BODY_SIZE in runtime.h
throw new System.ArgumentException(Errors.LambdaBootstrap.Internal.LambdaResponseTooLong, e);
}
else
{
throw;
}
}
}
}
} | 65 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.S3Events
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// AWS S3 event
/// http://docs.aws.amazon.com/lambda/latest/dg/with-s3.html
/// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-s3-put
/// </summary>
public class S3Event
{
/// <summary>
/// Gets and sets the records for the S3 event notification
/// </summary>
public List<S3EventNotificationRecord> Records { get; set; }
/// <summary>
/// The class holds the user identity properties.
/// </summary>
public class UserIdentityEntity
{
/// <summary>
/// Gets and sets the PrincipalId property.
/// </summary>
public string PrincipalId { get; set; }
}
/// <summary>
/// This class contains the identity information for an S3 bucket.
/// </summary>
public class S3BucketEntity
{
/// <summary>
/// Gets and sets the name of the bucket.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets and sets the bucket owner id.
/// </summary>
public UserIdentityEntity OwnerIdentity { get; set; }
/// <summary>
/// Gets and sets the S3 bucket arn.
/// </summary>
public string Arn { get; set; }
}
/// <summary>
/// This class contains the information for an object in S3.
/// </summary>
public class S3ObjectEntity
{
/// <summary>
/// Gets and sets the key for the object stored in S3.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets and sets the size of the object in S3.
/// </summary>
public long Size { get; set; }
/// <summary>
/// Gets and sets the etag of the object. This can be used to determine if the object has changed.
/// </summary>
public string ETag { get; set; }
/// <summary>
/// Gets and sets the version id of the object in S3.
/// </summary>
public string VersionId { get; set; }
/// <summary>
/// Gets and sets the sequencer a string representation of a hexadecimal value used to determine event sequence, only used with PUTs and DELETEs.
/// </summary>
public string Sequencer { get; set; }
}
/// <summary>
/// Gets and sets the meta information describing S3.
/// </summary>
public class S3Entity
{
/// <summary>
/// Gets and sets the ConfigurationId. This ID can be found in the bucket notification configuration.
/// </summary>
public string ConfigurationId { get; set; }
/// <summary>
/// Gets and sets the Bucket property.
/// </summary>
public S3BucketEntity Bucket { get; set; }
/// <summary>
/// Gets and sets the Object property.
/// </summary>
public S3ObjectEntity Object { get; set; }
/// <summary>
/// Gets and sets the S3SchemaVersion property.
/// </summary>
public string S3SchemaVersion { get; set; }
}
/// <summary>
/// The class holds the request parameters
/// </summary>
public class RequestParametersEntity
{
/// <summary>
/// Gets and sets the SourceIPAddress. This is the ip address where the request came from.
/// </summary>
public string SourceIPAddress { get; set; }
}
/// <summary>
/// This class holds the response elements.
/// </summary>
[DataContract]
public class ResponseElementsEntity
{
/// <summary>
/// Gets and sets the XAmzId2 Property. This is the Amazon S3 host that processed the request.
/// </summary>
[DataMember(Name = "x-amz-id-2", EmitDefaultValue = false)]
[System.Text.Json.Serialization.JsonPropertyName("x-amz-id-2")]
public string XAmzId2 { get; set; }
/// <summary>
/// Gets and sets the XAmzRequestId. This is the Amazon S3 generated request ID.
/// </summary>
[DataMember(Name = "x-amz-request-id", EmitDefaultValue = false)]
[System.Text.Json.Serialization.JsonPropertyName("x-amz-request-id")]
public string XAmzRequestId { get; set; }
}
/// <summary>
/// The class holds the glacier event data elements.
/// </summary>
public class S3GlacierEventDataEntity
{
/// <summary>
/// Gets and sets the RestoreEventData property.
/// </summary>
public S3RestoreEventDataEntity RestoreEventData { get; set; }
}
/// <summary>
/// The class holds the restore event data elements.
/// </summary>
public class S3RestoreEventDataEntity
{
/// <summary>
/// Gets and sets the LifecycleRestorationExpiryTime the time when the object restoration will be expired.
/// </summary>
public DateTime LifecycleRestorationExpiryTime { get; set; }
/// <summary>
/// Gets and sets the LifecycleRestoreStorageClass the source storage class for restore.
/// </summary>
public string LifecycleRestoreStorageClass { get; set; }
}
/// <summary>
/// The class holds the event notification.
/// </summary>
public class S3EventNotificationRecord
{
/// <summary>
/// Gets and sets the AwsRegion property.
/// </summary>
public string AwsRegion { get; set; }
/// <summary>
/// Gets and sets the EventName property. This identities what type of event occurred.
/// For example for an object just put in S3 this will be set to EventType.ObjectCreatedPut.
/// </summary>
public string EventName { get; set; }
/// <summary>
/// Gets and sets the EventSource property.
/// </summary>
public string EventSource { get; set; }
/// <summary>
/// Gets and sets the EventTime property. The time when S3 finished processing the request.
/// </summary>
public DateTime EventTime { get; set; }
/// <summary>
/// Gets and sets the EventVersion property.
/// </summary>
public string EventVersion { get; set; }
/// <summary>
/// Gets and sets the RequestParameters property.
/// </summary>
public RequestParametersEntity RequestParameters { get; set; }
/// <summary>
/// Gets and sets the ResponseElements property.
/// </summary>
public ResponseElementsEntity ResponseElements { get; set; }
/// <summary>
/// Gets and sets the S3 property.
/// </summary>
public S3Entity S3 { get; set; }
/// <summary>
/// Gets and sets the UserIdentity property.
/// </summary>
public UserIdentityEntity UserIdentity { get; set; }
/// <summary>
/// Get and sets the GlacierEventData property.
/// </summary>
public S3GlacierEventDataEntity GlacierEventData { get; set; }
}
}
} | 227 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace Amazon.Lambda.S3Events
{
/// <summary>
/// Class representing the S3 Object Lambda event.
///
/// S3 Developer Guide explaining the event data.
/// https://docs.aws.amazon.com/AmazonS3/latest/userguide/olap-writing-lambda.html
/// </summary>
public class S3ObjectLambdaEvent
{
/// <summary>
/// The Amazon S3 request ID for this request. We recommend that you log this value to help with debugging.
/// </summary>
#if NETCOREAPP3_1
[System.Text.Json.Serialization.JsonPropertyName("xAmzRequestId")]
#endif
public string XAmzRequestId { get; set; }
/// <summary>
/// The input and output details for connections to Amazon S3 and S3 Object Lambda.
/// </summary>
public GetObjectContextType GetObjectContext { get; set; }
/// <summary>
/// Configuration information about the S3 Object Lambda access point.
/// </summary>
public ConfigurationType Configuration { get; set; }
/// <summary>
/// Information about the original call to S3 Object Lambda.
/// </summary>
public UserRequestType UserRequest { get; set; }
/// <summary>
/// Details about the identity that made the call to S3 Object Lambda.
/// </summary>
public UserIdentityType UserIdentity { get; set; }
/// <summary>
/// The version ID of the context provided. The format of this field is {Major Version}.{Minor Version}.
/// </summary>
public string ProtocolVersion { get; set; }
/// <summary>
/// The input and output details for connections to Amazon S3 and S3 Object Lambda.
/// </summary>
public class GetObjectContextType
{
/// <summary>
/// A presigned URL that can be used to fetch the original object from Amazon S3. The URL is signed
/// using the original caller’s identity, and their permissions will apply when the URL is used.
/// If there are signed headers in the URL, the Lambda function must include these in the call to
/// Amazon S3, except for the Host.
/// </summary>
public string InputS3Url { get; set; }
/// <summary>
/// A presigned URL that can be used to fetch the original object from Amazon S3. The URL is signed
/// using the original caller’s identity, and their permissions will apply when the URL is used. If
/// there are signed headers in the URL, the Lambda function must include these in the call to
/// Amazon S3, except for the Host.
/// </summary>
public string OutputRoute { get; set; }
/// <summary>
/// An opaque token used by S3 Object Lambda to match the WriteGetObjectResponse call with the
/// original caller.
/// </summary>
public string OutputToken { get; set; }
}
/// <summary>
/// Configuration information about the S3 Object Lambda access point.
/// </summary>
public class ConfigurationType
{
/// <summary>
/// The Amazon Resource Name (ARN) of the S3 Object Lambda access point that received this request.
/// </summary>
public string AccessPointArn { get; set; }
/// <summary>
/// The ARN of the supporting access point that is specified in the S3 Object Lambda access point configuration.
/// </summary>
public string SupportingAccessPointArn { get; set; }
/// <summary>
/// Custom data that is applied to the S3 Object Lambda access point configuration. S3 Object Lambda treats
/// this as an opaque string, so it might need to be decoded before use.
/// </summary>
public string Payload { get; set; }
}
/// <summary>
/// Information about the original call to S3 Object Lambda.
/// </summary>
public class UserRequestType
{
/// <summary>
/// The decoded URL of the request as received by S3 Object Lambda,
/// excluding any authorization-related query parameters.
/// </summary>
public string Url { get; set; }
/// <summary>
/// A map of string to strings containing the HTTP headers and their values from the original call, excluding
/// any authorization-related headers. If the same header appears multiple times, their values are
/// combined into a comma-delimited list.
/// </summary>
public IDictionary<string, string> Headers { get; set; }
}
/// <summary>
/// Details about the identity that made the call to S3 Object Lambda.
/// </summary>
public class UserIdentityType
{
/// <summary>
/// The type of identity.
/// </summary>
public string Type { get; set; }
/// <summary>
/// The unique identifier for the identity that made the call.
/// </summary>
public string PrincipalId { get; set; }
/// <summary>
/// The ARN of the principal that made the call. The last section of the ARN contains the user or role that made the call.
/// </summary>
public string Arn { get; set; }
/// <summary>
/// The AWS account to which the identity belongs.
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// The AWS Access Key Id for the identity.
/// </summary>
public string AccessKeyId { get; set; }
/// <summary>
/// If the request was made with temporary security credentials, this element provides information about the
/// session that was created for those credentials.
/// </summary>
public SessionContextType SessionContext { get; set; }
}
/// <summary>
/// The information about temporary session credentials used by the identity.
/// </summary>
public class SessionContextType
{
/// <summary>
/// Attributes for the temporary session credentials
/// </summary>
public SessionContextAttributesType Attributes { get; set; }
/// <summary>
/// If the request was made with temporary security credentials, this element provides information about how the credentials were obtained.
/// </summary>
public SessionIssuerType SessionIssuer { get; set; }
}
/// <summary>
/// Attributes of the temporary session credentials
/// </summary>
public class SessionContextAttributesType
{
/// <summary>
/// Identifies whether MFA authentication was used when obtaining temporary credentials.
/// </summary>
public string MfaAuthenticated { get; set; }
/// <summary>
/// The create date of the temporary session credentials.
/// </summary>
public string CreationDate { get; set; }
}
/// <summary>
/// Information about the issuer of the temporary session credentials.
/// </summary>
public class SessionIssuerType
{
/// <summary>
/// The type of issuer of the temporary session credentials.
/// </summary>
public string Type { get; set; }
/// <summary>
/// The principal id of the issuer of the temporary session credentials.
/// </summary>
public string PrincipalId { get; set; }
/// <summary>
/// The arn of the issuer of the temporary session credentials.
/// </summary>
public string Arn { get; set; }
/// <summary>
/// The account id of the issuer of the temporary session credentials.
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// The user name of the issuer of the temporary session credentials.
/// </summary>
public string UserName { get; set; }
}
}
}
| 219 |
aws-lambda-dotnet | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Amazon.Lambda.S3Events")]
[assembly: AssemblyDescription("Lambda event interfaces for S3 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 Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Custom contract resolver for handling special event cases.
/// </summary>
internal class AwsResolver : DefaultContractResolver
{
private JsonToMemoryStreamDataConverter jsonToMemoryStreamDataConverter;
private JsonNumberToDateTimeDataConverter jsonNumberToDateTimeDataConverter;
private JsonToMemoryStreamListDataConverter jsonToMemoryStreamListDataConverter;
JsonToMemoryStreamDataConverter StreamDataConverter
{
get
{
if (jsonToMemoryStreamDataConverter == null)
{
jsonToMemoryStreamDataConverter = new JsonToMemoryStreamDataConverter();
}
return jsonToMemoryStreamDataConverter;
}
}
JsonToMemoryStreamListDataConverter StreamListDataConverter
{
get
{
if (jsonToMemoryStreamListDataConverter == null)
{
jsonToMemoryStreamListDataConverter = new JsonToMemoryStreamListDataConverter();
}
return jsonToMemoryStreamListDataConverter;
}
}
JsonNumberToDateTimeDataConverter DateTimeConverter
{
get
{
if (jsonNumberToDateTimeDataConverter == null)
{
jsonNumberToDateTimeDataConverter = new JsonNumberToDateTimeDataConverter();
}
return jsonNumberToDateTimeDataConverter;
}
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// S3 events use non-standard key formatting for request IDs and need to be mapped to the correct properties
if (type.FullName.Equals("Amazon.S3.Util.S3EventNotification+ResponseElementsEntity", StringComparison.Ordinal))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("XAmzRequestId", StringComparison.Ordinal))
{
property.PropertyName = "x-amz-request-id";
}
else if (property.PropertyName.Equals("XAmzId2", StringComparison.Ordinal))
{
property.PropertyName = "x-amz-id-2";
}
}
}
else if (type.FullName.Equals("Amazon.Lambda.KinesisEvents.KinesisEvent+Record", StringComparison.Ordinal))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("Data", StringComparison.Ordinal))
{
property.MemberConverter = StreamDataConverter;
}
else if (property.PropertyName.Equals("ApproximateArrivalTimestamp", StringComparison.Ordinal))
{
property.MemberConverter = DateTimeConverter;
}
}
}
else if (type.FullName.Equals("Amazon.DynamoDBv2.Model.StreamRecord", StringComparison.Ordinal))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("ApproximateCreationDateTime", StringComparison.Ordinal))
{
property.MemberConverter = DateTimeConverter;
}
}
}
else if (type.FullName.Equals("Amazon.DynamoDBv2.Model.AttributeValue", StringComparison.Ordinal))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("B", StringComparison.Ordinal))
{
property.MemberConverter = StreamDataConverter;
}
else if (property.PropertyName.Equals("BS", StringComparison.Ordinal))
{
property.MemberConverter = StreamListDataConverter;
}
}
}
else if (type.FullName.Equals("Amazon.Lambda.SQSEvents.SQSEvent+MessageAttribute", StringComparison.Ordinal))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("BinaryValue", StringComparison.Ordinal))
{
property.MemberConverter = StreamDataConverter;
}
else if (property.PropertyName.Equals("BinaryListValues", StringComparison.Ordinal))
{
property.MemberConverter = StreamListDataConverter;
}
}
}
else if (type.FullName.StartsWith("Amazon.Lambda.CloudWatchEvents.")
&& (type.GetTypeInfo().BaseType?.FullName?.StartsWith("Amazon.Lambda.CloudWatchEvents.CloudWatchEvent`",
StringComparison.Ordinal) ?? false))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("DetailType", StringComparison.Ordinal))
{
property.PropertyName = "detail-type";
}
}
}
else if (type.FullName.Equals("Amazon.Lambda.KafkaEvents.KafkaEvent+KafkaEventRecord", StringComparison.Ordinal))
{
foreach (JsonProperty property in properties)
{
if (property.PropertyName.Equals("Value", StringComparison.Ordinal))
{
property.MemberConverter = StreamDataConverter;
}
}
}
return properties;
}
}
} | 153 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Common logic.
/// </summary>
internal static class Common
{
public static MemoryStream Base64ToMemoryStream(string dataBase64)
{
var dataBytes = Convert.FromBase64String(dataBase64);
MemoryStream stream = new MemoryStream(dataBytes);
return stream;
}
}
}
| 19 |
aws-lambda-dotnet | aws | C# | using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using NewtonsoftJsonSerializer = Newtonsoft.Json.JsonSerializer;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Custom JSON converter for handling special event cases.
/// </summary>
internal class JsonNumberToDateTimeDataConverter : JsonConverter
{
private static readonly TypeInfo DATETIME_TYPEINFO = typeof(DateTime).GetTypeInfo();
private static readonly DateTime EPOCH_DATETIME = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public override bool CanConvert(Type objectType)
{
return DATETIME_TYPEINFO.IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, NewtonsoftJsonSerializer serializer)
{
double seconds;
switch (reader.TokenType)
{
case JsonToken.Float:
seconds = (double)reader.Value;
break;
case JsonToken.Integer:
seconds = (long)reader.Value;
break;
default:
seconds = 0;
break;
}
var result = EPOCH_DATETIME.AddSeconds(seconds);
return result;
}
public override void WriteJson(JsonWriter writer, object value, NewtonsoftJsonSerializer serializer)
{
throw new NotSupportedException();
}
}
} | 51 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Collections.Generic;
using Amazon.Lambda.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Custom ILambdaSerializer implementation which uses Newtonsoft.Json 9.0.1
/// for serialization.
///
/// <para>
/// If the environment variable LAMBDA_NET_SERIALIZER_DEBUG is set to true the JSON coming
/// in from Lambda and being sent back to Lambda will be logged.
/// </para>
/// </summary>
public class JsonSerializer : ILambdaSerializer
{
private const string DEBUG_ENVIRONMENT_VARIABLE_NAME = "LAMBDA_NET_SERIALIZER_DEBUG";
private Newtonsoft.Json.JsonSerializer serializer;
private bool debug;
/// <summary>
/// Constructs instance of serializer.
/// </summary>
/// <param name="customizeSerializerSettings">A callback to customize the serializer settings.</param>
public JsonSerializer(Action<JsonSerializerSettings> customizeSerializerSettings)
: this(customizeSerializerSettings, null)
{
}
/// <summary>
/// Constructs instance of serializer. This constructor is usefull to
/// customize the serializer settings.
/// </summary>
/// <param name="customizeSerializerSettings">A callback to customize the serializer settings.</param>
/// <param name="namingStrategy">The naming strategy to use. This parameter makes it possible to change the naming strategy to camel case for example. When not provided, it uses the default Newtonsoft.Json DefaultNamingStrategy.</param>
public JsonSerializer(Action<JsonSerializerSettings> customizeSerializerSettings, NamingStrategy namingStrategy)
{
JsonSerializerSettings settings = new JsonSerializerSettings();
customizeSerializerSettings(settings);
// Set the contract resolver *after* the custom callback has been
// invoked. This makes sure that we always use the good resolver.
var resolver = new AwsResolver();
if (namingStrategy != null)
{
resolver.NamingStrategy = namingStrategy;
};
settings.ContractResolver = resolver;
serializer = Newtonsoft.Json.JsonSerializer.Create(settings);
if (string.Equals(Environment.GetEnvironmentVariable(DEBUG_ENVIRONMENT_VARIABLE_NAME), "true", StringComparison.OrdinalIgnoreCase))
{
this.debug = true;
}
}
/// <summary>
/// Constructs instance of serializer.
/// </summary>
public JsonSerializer()
:this(customizeSerializerSettings: _ => { /* Nothing to customize by default. */ })
{
}
/// <summary>
/// Constructs instance of serializer using custom converters.
/// </summary>
public JsonSerializer(IEnumerable<JsonConverter> converters)
:this()
{
if(converters != null)
{
foreach (var c in converters)
{
serializer.Converters.Add(c);
}
}
}
/// <summary>
/// Serializes a particular object to a stream.
/// </summary>
/// <typeparam name="T">Type of object to serialize.</typeparam>
/// <param name="response">Object to serialize.</param>
/// <param name="responseStream">Output stream.</param>
public void Serialize<T>(T response, Stream responseStream)
{
try
{
if (debug)
{
using (StringWriter debugWriter = new StringWriter())
{
serializer.Serialize(debugWriter, response);
Console.WriteLine($"Lambda Serialize {response.GetType().FullName}: {debugWriter.ToString()}");
StreamWriter writer = new StreamWriter(responseStream);
writer.Write(debugWriter.ToString());
writer.Flush();
}
}
else
{
StreamWriter writer = new StreamWriter(responseStream);
serializer.Serialize(writer, response);
writer.Flush();
}
}
catch(Exception e)
{
throw new JsonSerializerException($"Error converting the response object of type {typeof(T).FullName} from the Lambda function to JSON: {e.Message}", e);
}
}
/// <summary>
/// Deserializes a stream to a particular type.
/// </summary>
/// <typeparam name="T">Type of object to deserialize to.</typeparam>
/// <param name="requestStream">Stream to serialize.</param>
/// <returns>Deserialized object from stream.</returns>
public T Deserialize<T>(Stream requestStream)
{
try
{
TextReader reader;
if (debug)
{
var json = new StreamReader(requestStream).ReadToEnd();
Console.WriteLine($"Lambda Deserialize {typeof(T).FullName}: {json}");
reader = new StringReader(json);
}
else
{
reader = new StreamReader(requestStream);
}
JsonReader jsonReader = new JsonTextReader(reader);
return serializer.Deserialize<T>(jsonReader);
}
catch (Exception e)
{
string message;
var targetType = typeof(T);
if(targetType == typeof(string))
{
message = $"Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example \"Hello World\" in order to be converted to a string: {e.Message}";
}
else
{
message = $"Error converting the Lambda event JSON payload to type {targetType.FullName}: {e.Message}";
}
throw new JsonSerializerException(message, e);
}
}
}
}
| 164 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Exception thrown when errors occur serializing and deserializng JSON documents from the Lambda service
/// </summary>
public class JsonSerializerException : Exception
{
/// <summary>
/// Constructs instances of JsonSerializerException
/// </summary>
/// <param name="message">Exception message</param>
public JsonSerializerException(string message) : base(message) { }
/// <summary>
/// Constructs instances of JsonSerializerException
/// </summary>
/// <param name="message">Exception message</param>
/// <param name="exception">Inner exception for the JsonSerializerException</param>
public JsonSerializerException(string message, Exception exception) : base(message, exception) { }
}
}
| 26 |
aws-lambda-dotnet | aws | C# | using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using NewtonsoftJsonSerializer = Newtonsoft.Json.JsonSerializer;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Custom JSON converter for handling special event cases.
/// </summary>
internal class JsonToMemoryStreamDataConverter : JsonConverter
{
private static readonly TypeInfo MEMORYSTREAM_TYPEINFO = typeof(MemoryStream).GetTypeInfo();
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public override bool CanConvert(Type objectType)
{
return MEMORYSTREAM_TYPEINFO.IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, NewtonsoftJsonSerializer serializer)
{
var dataBase64 = reader.Value as string;
if (dataBase64 is null)
return null;
return Common.Base64ToMemoryStream(dataBase64);
}
public override void WriteJson(JsonWriter writer, object value, NewtonsoftJsonSerializer serializer)
{
throw new NotSupportedException();
}
}
} | 39 |
aws-lambda-dotnet | aws | C# | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using NewtonsoftJsonSerializer = Newtonsoft.Json.JsonSerializer;
namespace Amazon.Lambda.Serialization.Json
{
/// <summary>
/// Custom JSON converter for handling special event cases.
/// </summary>
internal class JsonToMemoryStreamListDataConverter : JsonConverter
{
private static readonly TypeInfo MEMORYSTREAM_LIST_TYPEINFO = typeof(List<MemoryStream>).GetTypeInfo();
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public override bool CanConvert(Type objectType)
{
return MEMORYSTREAM_LIST_TYPEINFO.IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, NewtonsoftJsonSerializer serializer)
{
var list = new List<MemoryStream>();
if (reader.TokenType == JsonToken.StartArray)
{
do
{
reader.Read();
if (reader.TokenType == JsonToken.String)
{
var dataBase64 = reader.Value as string;
var ms = Common.Base64ToMemoryStream(dataBase64);
list.Add(ms);
}
} while (reader.TokenType != JsonToken.EndArray);
}
return list;
}
public override void WriteJson(JsonWriter writer, object value, NewtonsoftJsonSerializer serializer)
{
throw new NotSupportedException();
}
}
} | 51 |
aws-lambda-dotnet | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Amazon.Lambda.Serialization.Json")]
[assembly: AssemblyDescription("Default serializer implementation for Lambda event sources.")]
[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.2.0")] | 13 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Serialization.SystemTextJson.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// Base class of serializers using System.Text.Json
/// </summary>
public abstract class AbstractLambdaJsonSerializer
{
private const string DEBUG_ENVIRONMENT_VARIABLE_NAME = "LAMBDA_NET_SERIALIZER_DEBUG";
private readonly bool _debug;
/// <summary>
/// Options settings used for the JSON writer
/// </summary>
protected JsonWriterOptions WriterOptions { get; }
/// <summary>
/// Create instance
/// </summary>
/// <param name="jsonWriterCustomizer"></param>
protected AbstractLambdaJsonSerializer(Action<JsonWriterOptions> jsonWriterCustomizer)
{
WriterOptions = new JsonWriterOptions()
{
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
jsonWriterCustomizer?.Invoke(this.WriterOptions);
this._debug = string.Equals(Environment.GetEnvironmentVariable(DEBUG_ENVIRONMENT_VARIABLE_NAME), "true",
StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Serializes a particular object to a stream.
/// </summary>
/// <typeparam name="T">Type of object to serialize.</typeparam>
/// <param name="response">Object to serialize.</param>
/// <param name="responseStream">Output stream.</param>
public void Serialize<T>(T response, Stream responseStream)
{
try
{
if (_debug)
{
using (var debugStream = new MemoryStream())
using (var utf8Writer = new Utf8JsonWriter(debugStream, WriterOptions))
{
InternalSerialize(utf8Writer, response);
debugStream.Position = 0;
using var debugReader = new StreamReader(debugStream);
var jsonDocument = debugReader.ReadToEnd();
Console.WriteLine($"Lambda Serialize {response.GetType().FullName}: {jsonDocument}");
var writer = new StreamWriter(responseStream);
writer.Write(jsonDocument);
writer.Flush();
}
}
else
{
using (var writer = new Utf8JsonWriter(responseStream, WriterOptions))
{
InternalSerialize(writer, response);
}
}
}
catch (Exception e)
{
throw new JsonSerializerException($"Error converting the response object of type {typeof(T).FullName} from the Lambda function to JSON: {e.Message}", e);
}
}
/// <summary>
/// Deserializes a stream to a particular type.
/// </summary>
/// <typeparam name="T">Type of object to deserialize to.</typeparam>
/// <param name="requestStream">Stream to serialize.</param>
/// <returns>Deserialized object from stream.</returns>
public T Deserialize<T>(Stream requestStream)
{
try
{
byte[] utf8Json = null;
if (_debug)
{
var json = new StreamReader(requestStream).ReadToEnd();
Console.WriteLine($"Lambda Deserialize {typeof(T).FullName}: {json}");
utf8Json = UTF8Encoding.UTF8.GetBytes(json);
}
if (utf8Json == null)
{
if (requestStream is MemoryStream ms)
{
utf8Json = ms.ToArray();
}
else
{
using (var copy = new MemoryStream())
{
requestStream.CopyTo(copy);
utf8Json = copy.ToArray();
}
}
}
return InternalDeserialize<T>(utf8Json);
}
catch (Exception e)
{
throw new JsonSerializerException($"Error converting the Lambda event JSON payload to type {typeof(T).FullName}: {e.Message}", e);
}
}
/// <summary>
/// Create the default instance of JsonSerializerOptions used in serializer
/// </summary>
/// <returns></returns>
protected virtual JsonSerializerOptions CreateDefaultJsonSerializationOptions()
{
var serializer = new JsonSerializerOptions()
{
#if NET6_0_OR_GREATER
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
#else
IgnoreNullValues = true,
#endif
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = new AwsNamingPolicy(),
Converters =
{
new DateTimeConverter(),
new MemoryStreamConverter(),
new ConstantClassConverter(),
new ByteArrayConverter()
}
};
return serializer;
}
/// <summary>
/// Perform the actual serialization after the public method had done the safety checks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="writer"></param>
/// <param name="response"></param>
protected abstract void InternalSerialize<T>(Utf8JsonWriter writer, T response);
/// <summary>
/// Perform the actual deserialization after the public method had done the safety checks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="utf8Json"></param>
/// <returns></returns>
protected abstract T InternalDeserialize<T>(byte[] utf8Json);
}
}
| 169 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text.Json;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// Custom AWS naming policy
/// </summary>
public class AwsNamingPolicy : JsonNamingPolicy
{
readonly IDictionary<string, string> _customNameMappings = new Dictionary<string, string>
{
{"XAmzId2", "x-amz-id-2" },
{"XAmzRequestId", "x-amz-request-id" }
};
private readonly JsonNamingPolicy _fallbackNamingPolicy;
/// <summary>
/// Creates the AWS Naming policy. If the name matches one of the reserved AWS words it will return the
/// appropriate mapping for it. Otherwise the name will be returned as is like the JsonDefaultNamingPolicy.
/// </summary>
public AwsNamingPolicy()
{
}
/// <summary>
/// Creates the AWS Naming policy. If the name matches one of the reserved AWS words it will return the
/// appropriate mapping for it. Otherwise the JsonNamingPolicy passed in will be used to map the name.
/// </summary>
/// <param name="fallbackNamingPolicy"></param>
public AwsNamingPolicy(JsonNamingPolicy fallbackNamingPolicy)
{
_fallbackNamingPolicy = fallbackNamingPolicy;
}
/// <summary>
/// Map names that don't camel case.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public override string ConvertName(string name)
{
if (_customNameMappings.TryGetValue(name, out var mapNamed))
{
return mapNamed;
}
// If no naming policy given then just return the name like the JsonDefaultNamingPolicy policy.
// https://github.com/dotnet/runtime/blob/master/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonDefaultNamingPolicy.cs
return _fallbackNamingPolicy?.ConvertName(name) ?? name;
}
}
}
| 57 |
aws-lambda-dotnet | aws | C# | using System.Text.Json;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// Custom ILambdaSerializer implementation which uses System.Text.Json
/// for serialization.
///
/// <para>
/// When serializing objects to JSON camel casing will be used for JSON property names.
/// </para>
/// <para>
/// If the environment variable LAMBDA_NET_SERIALIZER_DEBUG is set to true the JSON coming
/// in from Lambda and being sent back to Lambda will be logged.
/// </para>
/// </summary>
public class CamelCaseLambdaJsonSerializer : DefaultLambdaJsonSerializer
{
/// <summary>
/// Constructs instance of serializer.
/// </summary>
public CamelCaseLambdaJsonSerializer()
: base(ConfigureJsonSerializerOptions)
{
}
private static void ConfigureJsonSerializerOptions(JsonSerializerOptions options)
{
options.PropertyNamingPolicy = new AwsNamingPolicy(JsonNamingPolicy.CamelCase);
}
}
} | 33 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson.Converters;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// Custom ILambdaSerializer implementation which uses System.Text.Json
/// for serialization.
///
/// <para>
/// If the environment variable LAMBDA_NET_SERIALIZER_DEBUG is set to true the JSON coming
/// in from Lambda and being sent back to Lambda will be logged.
/// </para>
/// </summary>
public class DefaultLambdaJsonSerializer : AbstractLambdaJsonSerializer, ILambdaSerializer
{
/// <summary>
/// The options used to serialize JSON object.
/// </summary>
protected JsonSerializerOptions SerializerOptions { get; }
/// <summary>
/// Constructs instance of serializer.
/// </summary>
public DefaultLambdaJsonSerializer()
: this(null, null)
{
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonSerializerOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="customizer"></param>
public DefaultLambdaJsonSerializer(Action<JsonSerializerOptions> customizer)
: this(customizer, null)
{
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonSerializerOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="customizer"></param>
/// <param name="jsonWriterCustomizer"></param>
public DefaultLambdaJsonSerializer(Action<JsonSerializerOptions> customizer, Action<JsonWriterOptions> jsonWriterCustomizer)
: base(jsonWriterCustomizer)
{
SerializerOptions = CreateDefaultJsonSerializationOptions();
customizer?.Invoke(this.SerializerOptions);
jsonWriterCustomizer?.Invoke(this.WriterOptions);
}
/// <inheritdoc/>
protected override void InternalSerialize<T>(Utf8JsonWriter writer, T response)
{
JsonSerializer.Serialize(writer, response, SerializerOptions);
}
/// <inheritdoc/>
protected override T InternalDeserialize<T>(byte[] utf8Json)
{
return JsonSerializer.Deserialize<T>(utf8Json, SerializerOptions);
}
}
} | 74 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// Exception thrown when errors occur serializing and deserializng JSON documents from the Lambda service
/// </summary>
public class JsonSerializerException : Exception
{
/// <summary>
/// Constructs instances of JsonSerializerException
/// </summary>
/// <param name="message">Exception message</param>
public JsonSerializerException(string message) : base(message) { }
/// <summary>
/// Constructs instances of JsonSerializerException
/// </summary>
/// <param name="message">Exception message</param>
/// <param name="exception">Inner exception for the JsonSerializerException</param>
public JsonSerializerException(string message, Exception exception) : base(message, exception) { }
}
} | 23 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson.Converters;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// Custom ILambdaSerializer implementation which uses System.Text.Json
/// for serialization.
///
/// <para>
/// If the environment variable LAMBDA_NET_SERIALIZER_DEBUG is set to true the JSON coming
/// in from Lambda and being sent back to Lambda will be logged.
/// </para>
/// <para>
/// This serializer is obsolete because it uses inconsistent name casing when serializing to JSON. Fixing the
/// inconsistent casing issues would cause runtime breaking changes so the new type DefaultLambdaJsonSerializer was created.
/// https://github.com/aws/aws-lambda-dotnet/issues/624
/// </para>
/// </summary>
[Obsolete("This serializer is obsolete because it uses inconsistent name casing when serializing to JSON. Lambda functions should use the DefaultLambdaJsonSerializer type.")]
public class LambdaJsonSerializer : ILambdaSerializer
{
private const string DEBUG_ENVIRONMENT_VARIABLE_NAME = "LAMBDA_NET_SERIALIZER_DEBUG";
private readonly JsonSerializerOptions _options;
private readonly JsonWriterOptions WriterOptions;
private readonly bool _debug;
/// <summary>
/// Constructs instance of serializer.
/// </summary>
public LambdaJsonSerializer()
{
_options = new JsonSerializerOptions()
{
IgnoreNullValues = true,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = new AwsNamingPolicy(JsonNamingPolicy.CamelCase)
};
_options.Converters.Add(new DateTimeConverter());
_options.Converters.Add(new MemoryStreamConverter());
_options.Converters.Add(new ConstantClassConverter());
_options.Converters.Add(new ByteArrayConverter());
WriterOptions = new JsonWriterOptions()
{
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
if (string.Equals(Environment.GetEnvironmentVariable(DEBUG_ENVIRONMENT_VARIABLE_NAME), "true", StringComparison.OrdinalIgnoreCase))
{
this._debug = true;
}
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonSerializerOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="customizer"></param>
public LambdaJsonSerializer(Action<JsonSerializerOptions> customizer)
: this()
{
customizer?.Invoke(this._options);
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonSerializerOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="customizer"></param>
/// <param name="jsonWriterCustomizer"></param>
public LambdaJsonSerializer(Action<JsonSerializerOptions> customizer, Action<JsonWriterOptions> jsonWriterCustomizer)
: this(customizer)
{
jsonWriterCustomizer?.Invoke(this.WriterOptions);
}
/// <summary>
/// Serializes a particular object to a stream.
/// </summary>
/// <typeparam name="T">Type of object to serialize.</typeparam>
/// <param name="response">Object to serialize.</param>
/// <param name="responseStream">Output stream.</param>
public void Serialize<T>(T response, Stream responseStream)
{
try
{
if (_debug)
{
using (var debugWriter = new StringWriter())
using (var utf8Writer = new Utf8JsonWriter(responseStream, WriterOptions))
{
JsonSerializer.Serialize(utf8Writer, response);
var jsonDocument = debugWriter.ToString();
Console.WriteLine($"Lambda Serialize {response.GetType().FullName}: {jsonDocument}");
var writer = new StreamWriter(responseStream);
writer.Write(jsonDocument);
writer.Flush();
}
}
else
{
using (var writer = new Utf8JsonWriter(responseStream, WriterOptions))
{
JsonSerializer.Serialize(writer, response, _options);
}
}
}
catch(Exception e)
{
throw new JsonSerializerException($"Error converting the response object of type {typeof(T).FullName} from the Lambda function to JSON: {e.Message}", e);
}
}
/// <summary>
/// Deserializes a stream to a particular type.
/// </summary>
/// <typeparam name="T">Type of object to deserialize to.</typeparam>
/// <param name="requestStream">Stream to serialize.</param>
/// <returns>Deserialized object from stream.</returns>
public T Deserialize<T>(Stream requestStream)
{
try
{
byte[] utf8Json = null;
if (_debug)
{
var json = new StreamReader(requestStream).ReadToEnd();
Console.WriteLine($"Lambda Deserialize {typeof(T).FullName}: {json}");
utf8Json = UTF8Encoding.UTF8.GetBytes(json);
}
if (utf8Json == null)
{
if (requestStream is MemoryStream ms)
{
utf8Json = ms.ToArray();
}
else
{
using (var copy = new MemoryStream())
{
requestStream.CopyTo(copy);
utf8Json = copy.ToArray();
}
}
}
return JsonSerializer.Deserialize<T>(utf8Json, _options);
}
catch (Exception e)
{
string message;
var targetType = typeof(T);
if(targetType == typeof(string))
{
message = $"Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example \"Hello World\" in order to be converted to a string: {e.Message}";
}
else
{
message = $"Error converting the Lambda event JSON payload to type {targetType.FullName}: {e.Message}";
}
throw new JsonSerializerException(message, e);
}
}
}
} | 175 |
aws-lambda-dotnet | aws | C# | #if NET6_0_OR_GREATER
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson.Converters;
namespace Amazon.Lambda.Serialization.SystemTextJson
{
/// <summary>
/// ILambdaSerializer implementation that supports the source generator support of System.Text.Json. To use this serializer define
/// a partial JsonSerializerContext class with attributes for the types to be serialized.
///
/// [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyRequest))]
/// [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyResponse))]
/// public partial class APIGatewaySerializerContext : JsonSerializerContext
/// {
/// }
///
/// Register the serializer with the LambdaSerializer attribute specifying the defined JsonSerializerContext
///
/// [assembly: LambdaSerializer(typeof(SourceGeneratorLambdaJsonSerializer&ly;APIGatewayExampleImage.MyJsonContext>))]
///
/// When the class is compiled it will generate all of the JSON serialization code to convert between JSON and the list types. This
/// will avoid any reflection based serialization.
/// </summary>
/// <typeparam name="TSGContext"></typeparam>
public class SourceGeneratorLambdaJsonSerializer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TSGContext> : AbstractLambdaJsonSerializer, ILambdaSerializer where TSGContext : JsonSerializerContext
{
TSGContext _jsonSerializerContext;
/// <summary>
/// The options used to serialize JSON object.
/// </summary>
protected JsonSerializerOptions SerializerOptions { get; }
/// <summary>
/// Constructs instance of serializer.
/// </summary>
public SourceGeneratorLambdaJsonSerializer()
: this(null, null)
{
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonSerializerOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="customizer"></param>
public SourceGeneratorLambdaJsonSerializer(Action<JsonSerializerOptions> customizer)
: this(customizer, null)
{
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonWriterOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="jsonWriterCustomizer"></param>
public SourceGeneratorLambdaJsonSerializer(Action<JsonWriterOptions> jsonWriterCustomizer)
: this(null, jsonWriterCustomizer)
{
}
/// <summary>
/// Constructs instance of serializer with the option to customize the JsonWriterOptions after the
/// Amazon.Lambda.Serialization.SystemTextJson's default settings have been applied.
/// </summary>
/// <param name="customizer"></param>
/// <param name="jsonWriterCustomizer"></param>
public SourceGeneratorLambdaJsonSerializer(Action<JsonSerializerOptions> customizer, Action<JsonWriterOptions> jsonWriterCustomizer)
: base(jsonWriterCustomizer)
{
SerializerOptions = CreateDefaultJsonSerializationOptions();
customizer?.Invoke(this.SerializerOptions);
var constructor = typeof(TSGContext).GetConstructor(new Type[] { typeof(JsonSerializerOptions) });
if(constructor == null)
{
throw new ApplicationException($"The serializer {typeof(TSGContext).FullName} is missing a constructor that takes in JsonSerializerOptions object");
}
_jsonSerializerContext = constructor.Invoke(new object[] { this.SerializerOptions }) as TSGContext;
}
/// <inheritdoc/>
protected override void InternalSerialize<T>(Utf8JsonWriter writer, T response)
{
var jsonTypeInfo = _jsonSerializerContext.GetTypeInfo(typeof(T)) as JsonTypeInfo<T>;
if (jsonTypeInfo == null)
{
throw new JsonSerializerException($"No JsonTypeInfo registered in {_jsonSerializerContext.GetType().FullName} for type {typeof(T).FullName}.");
}
JsonSerializer.Serialize(writer, response, jsonTypeInfo);
}
/// <inheritdoc/>
protected override T InternalDeserialize<T>(byte[] utf8Json)
{
var jsonTypeInfo = _jsonSerializerContext.GetTypeInfo(typeof(T)) as JsonTypeInfo<T>;
if (jsonTypeInfo == null)
{
throw new JsonSerializerException($"No JsonTypeInfo registered in {_jsonSerializerContext.GetType().FullName} for type {typeof(T).FullName}.");
}
return JsonSerializer.Deserialize<T>(utf8Json, jsonTypeInfo);
}
}
}
#endif
| 118 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Amazon.Lambda.Serialization.SystemTextJson.Converters
{
/// <summary>
/// ByteArrayConverter for converting an JSON array of number from and to byte[].
/// </summary>
public class ByteArrayConverter : JsonConverter<byte[]>
{
/// <inheritdoc />
public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}
var byteList = new List<byte>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.Number:
byteList.Add(reader.GetByte());
break;
case JsonTokenType.EndArray:
return byteList.ToArray();
}
}
throw new JsonException("The JSON value could not be converted to byte[].");
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, byte[] values, JsonSerializerOptions options)
{
if (values == null)
{
writer.WriteNullValue();
}
else
{
writer.WriteStartArray();
foreach (var value in values)
{
writer.WriteNumberValue(value);
}
writer.WriteEndArray();
}
}
}
}
| 59 |
aws-lambda-dotnet | aws | C# | using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Collections.Generic;
namespace Amazon.Lambda.Serialization.SystemTextJson.Converters
{
/// <summary>
/// JsonConvert to handle the AWS SDK for .NET custom enum classes that derive from the class called ConstantClass.
/// </summary>
/// <remarks>
/// Because this package can not take a dependency on AWSSDK.Core we need to use name heuristics and reflection to determine if the type
/// extends from ConstantClass.
/// </remarks>
public class ConstantClassConverter : JsonConverter<object>
{
private const string CONSTANT_CLASS_NAME = "Amazon.Runtime.ConstantClass";
private readonly static HashSet<string> ConstantClassNames = new HashSet<string>
{
"Amazon.S3.EventType",
"Amazon.DynamoDBv2.OperationType",
"Amazon.DynamoDBv2.StreamViewType"
};
/// <summary>
/// Check to see if the type is derived from ConstantClass.
/// </summary>
/// <param name="typeToConvert"></param>
/// <returns></returns>
public override bool CanConvert(Type typeToConvert)
{
return ConstantClassNames.Contains(typeToConvert.FullName);
}
/// <summary>
/// Called when a JSON document is being reading and a property is being converted to a ConstantClass type.
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetString();
return Activator.CreateInstance(typeToConvert, new object[] {value});
}
/// <summary>
/// Called when writing the ConstantClass out to the JSON document.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
}
| 62 |
aws-lambda-dotnet | aws | C# | using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Amazon.Lambda.Serialization.SystemTextJson.Converters
{
/// <summary>
/// DateTime converter that handles the JSON read for deserialization might use an epoch time.
/// </summary>
public class DateTimeConverter : JsonConverter<DateTime>
{
/// <summary>
/// Converts the value to a DateTime. If the JSON type is a number then it assumes the time is represented as
/// an epoch time.
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if(reader.TokenType == JsonTokenType.String && reader.TryGetDateTime(out var date))
{
return date;
}
else if(reader.TokenType == JsonTokenType.Number)
{
if (reader.TryGetInt64(out var intSeconds))
{
return DateTime.UnixEpoch.AddSeconds(intSeconds);
}
if (reader.TryGetDouble(out var doubleSeconds))
{
return DateTime.UnixEpoch.AddSeconds(doubleSeconds);
}
}
throw new JsonSerializerException($"Unknown data type for DateTime: {reader.TokenType}");
}
/// <summary>
/// Uses System.Text.Json's default functionality to write dates to the Serialization document.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
}
| 54 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
namespace Amazon.Lambda.Serialization.SystemTextJson.Converters
{
/// <summary>
/// Handles converting MemoryStreams from and to base 64 strings.
/// </summary>
public class MemoryStreamConverter : JsonConverter<MemoryStream>
{
/// <summary>
/// Reads the value as a string assuming it is a base 64 string and converts the string to a MemoryStream.
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override MemoryStream Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dataBase64 = reader.GetString();
var dataBytes = Convert.FromBase64String(dataBase64);
var ms = new MemoryStream(dataBytes);
return ms;
}
/// <summary>
/// Writes the MemoryStream as a base 64 string.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, MemoryStream value, JsonSerializerOptions options)
{
writer.WriteStringValue(Convert.ToBase64String(value.ToArray()));
}
}
}
| 41 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.SimpleEmailEvents.Actions;
using System;
using System.Collections.Generic;
namespace Amazon.Lambda.SimpleEmailEvents
{
/// <summary>
/// Simple Email Service event
/// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ses-email-receiving
/// </summary>
public class SimpleEmailEvent<TReceiptAction> where TReceiptAction : IReceiptAction
{
/// <summary>
/// List of SES records.
/// </summary>
public IList<SimpleEmailRecord<TReceiptAction>> Records { get; set; }
/// <summary>
/// An SES record.
/// </summary>
public class SimpleEmailRecord<TReceiptAction> where TReceiptAction : IReceiptAction
{
/// <summary>
/// The event version.
/// </summary>
public string EventVersion { get; set; }
/// <summary>
/// The event source.
/// </summary>
public string EventSource { get; set; }
/// <summary>
/// The SES message.
/// </summary>
public SimpleEmailService<TReceiptAction> Ses { get; set; }
}
/// <summary>
/// An SES record.
/// </summary>
[Obsolete(
"Please move to using SimpleEmailRecord<TReceiptAction> for greater flexibility over which type of action this record refers to. For a like for like replacement on lambda actions, please use SimpleEmailRecord<LambdaReceiptAction>"
)]
public class SimpleEmailRecord : SimpleEmailRecord<LambdaReceiptAction>
{ }
/// <summary>
/// An SES message record.
/// </summary>
public class SimpleEmailService<TReceiptAction> where TReceiptAction : IReceiptAction
{
/// <summary>
/// The mail data for the SES message.
/// </summary>
public SimpleEmailMessage Mail { get; set; }
/// <summary>
/// The receipt data for the SES message.
/// </summary>
public SimpleEmailReceipt<TReceiptAction> Receipt { get; set; }
}
/// <summary>
/// The mail data for the SES message.
/// </summary>
public class SimpleEmailMessage
{
/// <summary>
/// A few of the most important headers from the message.
/// </summary>
public SimpleEmailCommonHeaders CommonHeaders { get; set; }
/// <summary>
/// The source email address of the message, i.e. SMTP FROM.
/// </summary>
public string Source { get; set; }
/// <summary>
/// The timestamp of the message.
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// The destination recipients of the message.
/// </summary>
public IList<string> Destination { get; set; }
/// <summary>
/// The headers associated with the message.
/// </summary>
public IList<SimpleEmailHeader> Headers { get; set; }
/// <summary>
/// Whether or not the Headers property is truncated.
/// </summary>
public bool HeadersTruncated { get; set; }
/// <summary>
/// The SES Message ID, which will also be the filename of the S3 object containing the message. Not to be confused with the incoming message's Message-ID header.
/// </summary>
public string MessageId { get; set; }
}
/// <summary>
/// The receipt data for the SES message.
/// </summary>
/// <typeparam name="TAction">The type of action being received in this receipt</typeparam>
public class SimpleEmailReceipt<TReceiptAction> where TReceiptAction : IReceiptAction
{
/// <summary>
/// The recipients of the message.
/// </summary>
public IList<string> Recipients { get; set; }
/// <summary>
/// The timestamp of the message.
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// The spam verdict of the message, e.g. status: PASS.
/// </summary>
public SimpleEmailVerdict SpamVerdict { get; set; }
/// <summary>
/// The DKIM verdict of the message, e.g. status: PASS.
/// </summary>
public SimpleEmailVerdict DKIMVerdict { get; set; }
/// <summary>
/// The SPF verdict of the message, e.g. status: PASS.
/// </summary>
public SimpleEmailVerdict SPFVerdict { get; set; }
/// <summary>
/// The virus verdict of the message, e.g. status: PASS.
/// </summary>
public SimpleEmailVerdict VirusVerdict { get; set; }
/// <summary>
/// The DMARC verdict of the message, e.g. status: PASS.
/// </summary>
public SimpleEmailVerdict DMARCVerdict { get; set; }
/// <summary>
/// The action of the message (i.e, which lambda was invoked, where it was stored in S3, etc)
/// </summary>
public TReceiptAction Action { get; set; }
/// <summary>
/// How long this incoming message took to process.
/// </summary>
public long ProcessingTimeMillis { get; set; }
}
/// <summary>
/// An SES message header.
/// </summary>
public class SimpleEmailHeader
{
/// <summary>
/// The header name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The header value.
/// </summary>
public string Value { get; set; }
}
}
/// <summary>
/// A few of the most important headers of the message.
/// </summary>
public class SimpleEmailCommonHeaders
{
/// <summary>
/// The From header's address(es)
/// </summary>
public IList<string> From { get; set; }
/// <summary>
/// The To header's address(es)
/// </summary>
public IList<string> To { get; set; }
/// <summary>
/// The Return-Path header.
/// </summary>
public string ReturnPath { get; set; }
/// <summary>
/// The incoming message's Message-ID header. Not to be confused with the SES messageId.
/// </summary>
public string MessageId { get; set; }
/// <summary>
/// The Date header.
/// </summary>
public string Date { get; set; }
/// <summary>
/// The Subject header.
/// </summary>
public string Subject { get; set; }
}
/// <summary>
/// Verdict to return status of Spam, DKIM, SPF, Virus, and DMARC.
/// </summary>
public class SimpleEmailVerdict
{
/// <summary>
/// The verdict status, e.g. PASS or FAIL.
/// </summary>
public string Status { get; set; }
}
/// <summary>
/// Simple Email Service event
/// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ses-email-receiving
/// </summary>
[Obsolete(
"Please move to using SimpleEmailEvent<TReceiptAction>, which allows greater flexibility over which type of event is being handled. For a like for like replacement if using a lambda event, use SimpleEmailEvent<LambdaReceiptAction>"
)]
public class SimpleEmailEvent : SimpleEmailEvent<LambdaReceiptAction>
{ }
}
| 233 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.SimpleEmailEvents.Actions
{
public interface IReceiptAction
{
string Type { get; set; }
}
} | 7 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.SimpleEmailEvents.Actions
{
/// <summary>
/// The lambda receipt's action.
/// </summary>
public class LambdaReceiptAction : IReceiptAction
{
/// <summary>
/// The type of the action, e.g. "Lambda", "S3"
/// </summary>
public string Type { get; set; }
/// <summary>
/// The type of invocation, e.g. "Event"
/// </summary>
public string InvocationType { get; set; }
/// <summary>
/// The ARN of this function.
/// </summary>
public string FunctionArn { get; set; }
}
}
| 24 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.SimpleEmailEvents.Actions
{
/// <summary>
/// The S3 action's receipt
/// </summary>
public class S3ReceiptAction : IReceiptAction
{
/// <summary>
/// The type of the action, e.g. "Lambda", "S3"
/// </summary>
public string Type { get; set; }
/// <summary>
/// The SNS topic to be posted to after the S3 action
/// </summary>
public string TopicArn { get; set; }
/// <summary>
/// The S3 bucket name where the email has been stored
/// </summary>
public string BucketName { get; set; }
/// <summary>
/// The prefix to the object's full key key (i.e folders)
/// </summary>
public string ObjectKeyPrefix { get; set; }
/// <summary>
/// The full object key
/// </summary>
public string ObjectKey { get; set; }
}
}
| 34 |
aws-lambda-dotnet | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Amazon.Lambda.SimpleEmailEvents")]
[assembly: AssemblyDescription("Lambda event interfaces for Simple Email Service (SES) event source.")]
[assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: ComVisible(false)]
[assembly: System.CLSCompliant(true)]
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 13 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.SNSEvents
{
using System;
using System.Collections.Generic;
/// <summary>
/// Simple Notification Service event
/// http://docs.aws.amazon.com/lambda/latest/dg/with-sns.html
/// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sns
/// </summary>
public class SNSEvent
{
/// <summary>
/// List of SNS records.
/// </summary>
public IList<SNSRecord> Records { get; set; }
/// <summary>
/// An SNS message record.
/// </summary>
public class SNSRecord
{
/// <summary>
/// The event source.
/// </summary>
public string EventSource { get; set; }
/// <summary>
/// The event subscription ARN.
/// </summary>
public string EventSubscriptionArn { get; set; }
/// <summary>
/// The event version.
/// </summary>
public string EventVersion { get; set; }
/// <summary>
/// The SNS message.
/// </summary>
public SNSMessage Sns { get; set; }
}
/// <summary>
/// An SNS message record.
/// </summary>
public class SNSMessage
{
/// <summary>
/// The message.
/// </summary>
public string Message { get; set; }
/// <summary>
/// The attributes associated with the message.
/// </summary>
public IDictionary<string, MessageAttribute> MessageAttributes { get; set; }
/// <summary>
/// The message id.
/// </summary>
public string MessageId { get; set; }
/// <summary>
/// The message signature.
/// </summary>
public string Signature { get; set; }
/// <summary>
/// The signature version used to sign the message.
/// </summary>
public string SignatureVersion { get; set; }
/// <summary>
/// The URL for the signing certificate.
/// </summary>
public string SigningCertUrl { get; set; }
/// <summary>
/// The subject for the message.
/// </summary>
public string Subject { get; set; }
/// <summary>
/// The message time stamp.
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// The topic ARN.
/// </summary>
public string TopicArn { get; set; }
/// <summary>
/// The message type.
/// </summary>
public string Type { get; set; }
/// <summary>
/// The message unsubscribe URL.
/// </summary>
public string UnsubscribeUrl { get; set; }
}
/// <summary>
/// An SNS message attribute.
/// </summary>
public class MessageAttribute
{
/// <summary>
/// The attribute type.
/// </summary>
public string Type { get; set; }
/// <summary>
/// The attribute value.
/// </summary>
public string Value { get; set; }
}
}
}
| 122 |
aws-lambda-dotnet | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Amazon.Lambda.SNSEvents")]
[assembly: AssemblyDescription("Lambda event interfaces for SNS 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.Collections.Generic;
using System.Runtime.Serialization;
namespace Amazon.Lambda.SQSEvents
{
/// This class can be used as the return type for Lambda functions that have partially
/// succeeded by supplying a list of message IDs that have failed to process.
/// https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#services-sqs-batchfailurereporting
[DataContract]
public class SQSBatchResponse
{
/// <summary>
/// Creates a new instance of <see cref="SQSBatchResponse"/>
/// </summary>
public SQSBatchResponse()
: this(new List<BatchItemFailure>())
{
}
/// <summary>
/// Creates a new instance of <see cref="SQSBatchResponse"/>
/// </summary>
/// <param name="batchItemFailures">A list of batch item failures</param>
public SQSBatchResponse(List<BatchItemFailure> batchItemFailures)
{
BatchItemFailures = batchItemFailures;
}
/// <summary>
/// Gets or sets the message failures within the batch failures
/// </summary>
[DataMember(Name = "batchItemFailures")]
#if NETCOREAPP3_1
[System.Text.Json.Serialization.JsonPropertyName("batchItemFailures")]
#endif
public List<BatchItemFailure> BatchItemFailures { get; set; }
/// <summary>
/// Class representing a SQS message item failure
/// </summary>
[DataContract]
public class BatchItemFailure
{
/// <summary>
/// MessageId that failed processing
/// </summary>
[DataMember(Name = "itemIdentifier")]
#if NETCOREAPP3_1
[System.Text.Json.Serialization.JsonPropertyName("itemIdentifier")]
#endif
public string ItemIdentifier { get; set; }
}
}
}
| 55 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.SQSEvents
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Simple Queue Service event
/// </summary>
public class SQSEvent
{
/// <summary>
/// Get and sets the Records
/// </summary>
public List<SQSMessage> Records { get; set; }
/// <summary>
/// Class containing the data for message attributes
/// </summary>
public class MessageAttribute
{
/// <summary>
/// Get and sets value of message attribute of type String or type Number
/// </summary>
public string StringValue { get; set; }
/// <summary>
/// Get and sets value of message attribute of type Binary
/// </summary>
public MemoryStream BinaryValue { get; set; }
/// <summary>
/// Get and sets the list of String values of message attribute
/// </summary>
public List<string> StringListValues { get; set; }
/// <summary>
/// Get and sets the list of Binary values of message attribute
/// </summary>
public List<MemoryStream> BinaryListValues { get; set; }
/// <summary>
/// Get and sets the dataType of message attribute
/// </summary>
public string DataType { get; set; }
}
/// <summary>
/// Class representing a SQS message event coming into a Lambda function
/// </summary>
public class SQSMessage
{
/// <summary>
/// Get and sets the message id
/// </summary>
public string MessageId { get; set; }
/// <summary>
/// Get and sets the receipt handle
/// </summary>
public string ReceiptHandle { get; set; }
/// <summary>
/// Get and sets the Body
/// </summary>
public string Body { get; set; }
/// <summary>
/// Get and sets the Md5OfBody
/// </summary>
public string Md5OfBody { get; set; }
/// <summary>
/// Get and sets the Md5OfMessageAttributes
/// </summary>
public string Md5OfMessageAttributes { get; set; }
/// <summary>
/// Get and sets the EventSourceArn
/// </summary>
public string EventSourceArn { get; set; }
/// <summary>
/// Get and sets the EventSource
/// </summary>
public string EventSource { get; set; }
/// <summary>
/// Get and sets the AwsRegion
/// </summary>
public string AwsRegion { get; set; }
/// <summary>
/// Get and sets the Attributes
/// </summary>
public Dictionary<string, string> Attributes { get; set; }
/// <summary>
/// Get and sets the MessageAttributes
/// </summary>
public Dictionary<string, MessageAttribute> MessageAttributes { get; set; }
}
}
}
| 107 |
aws-lambda-dotnet | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Amazon.Lambda.SQSEvents")]
[assembly: AssemblyDescription("Lambda event interfaces for SQS 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.0.0.0")] | 13 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
namespace Amazon.Lambda.TestUtilities
{
/// <summary>
/// A test implementation of the IClientApplication interface used for writing local tests of Lambda Functions.
/// </summary>
public class TestClientApplication : IClientApplication
{
/// <summary>
/// The application's package name.
/// </summary>
public string AppPackageName { get; set; }
/// <summary>
/// The application's title.
/// </summary>
public string AppTitle { get; set; }
/// <summary>
/// The application's version code.
/// </summary>
public string AppVersionCode { get; set; }
/// <summary>
/// The application's version.
/// </summary>
public string AppVersionName { get; set; }
/// <summary>
/// The application's installation id.
/// </summary>
public string InstallationId { get; set; }
}
}
| 41 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
namespace Amazon.Lambda.TestUtilities
{
/// <summary>
/// A test implementation of the IClientContext interface used for writing local tests of Lambda Functions.
/// </summary>
public class TestClientContext : IClientContext
{
/// <summary>
/// The client information provided by the AWS Mobile SDK.
/// </summary>
public IClientApplication Client { get; set; }
/// <summary>
/// Custom values set by the client application.
/// </summary>
public IDictionary<string, string> Custom { get; set; } = new Dictionary<string, string>();
/// <summary>
/// Environment information provided by mobile SDK.
/// </summary>
public IDictionary<string, string> Environment { get; set; } = new Dictionary<string, string>();
}
}
| 31 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
namespace Amazon.Lambda.TestUtilities
{
/// <summary>
/// A test implementation of the ICognitoIdentity interface used for writing local tests of Lambda Functions.
/// </summary>
public class TestCognitoIdentity : ICognitoIdentity
{
/// <summary>
/// The Amazon Cognito identity ID.
/// </summary>
public string IdentityId { get; set; }
/// <summary>
/// The Amazon Cognito identity pool ID.
/// </summary>
public string IdentityPoolId { get; set; }
}
}
| 26 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
namespace Amazon.Lambda.TestUtilities
{
/// <summary>
/// A test implementation of the ILambdaContext interface used for writing local tests of Lambda Functions.
/// </summary>
public class TestLambdaContext : ILambdaContext
{
/// <summary>
/// The AWS request ID associated with the request.
/// </summary>
public string AwsRequestId { get; set; }
/// <summary>
/// Information about the client application and device when invoked
/// through the AWS Mobile SDK.
/// </summary>
public IClientContext ClientContext { get; set; }
/// <summary>
/// Name of the Lambda function that is running.
/// </summary>
public string FunctionName { get; set; }
/// <summary>
/// The Lambda function version that is executing.
/// If an alias is used to invoke the function, then this will be
/// the version the alias points to.
/// </summary>
public string FunctionVersion { get; set; }
/// <summary>
/// Information about the Amazon Cognito identity provider when
/// invoked through the AWS Mobile SDK.
/// </summary>
public ICognitoIdentity Identity { get; set; }
/// <summary>
/// The ARN used to invoke this function.
/// </summary>
public string InvokedFunctionArn { get; set; }
/// <summary>
/// Lambda logger associated with the Context object. For the TestLambdaContext this is default to the TestLambdaLogger.
/// </summary>
public ILambdaLogger Logger { get; set; } = new TestLambdaLogger();
/// <summary>
/// The CloudWatch log group name associated with the invoked function.
/// </summary>
public string LogGroupName { get; set; }
/// <summary>
/// The CloudWatch log stream name for this function execution.
/// </summary>
public string LogStreamName { get; set; }
/// <summary>
/// Memory limit, in MB, you configured for the Lambda function.
/// </summary>
public int MemoryLimitInMB { get; set; }
/// <summary>
/// Remaining execution time till the function will be terminated.
/// </summary>
public TimeSpan RemainingTime { get; set; }
}
}
| 75 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
namespace Amazon.Lambda.TestUtilities
{
/// <summary>
/// An implementation if ILambdaLogger that stores all the messages in a buffer and writes the messages to the console.
/// </summary>
public class TestLambdaLogger : ILambdaLogger
{
/// <summary>
/// Buffer for all the log messages written to the logger.
/// </summary>
public StringBuilder Buffer { get; } = new StringBuilder();
/// <summary>
/// Write log messages to the console and the Buffer without appending a newline terminator.
/// </summary>
/// <param name="message"></param>
public void Log(string message)
{
Buffer.Append(message);
Console.Write(message);
}
/// <summary>
/// Write log messages to the console and the Buffer with a newline terminator.
/// </summary>
/// <param name="message"></param>
public void LogLine(string message)
{
Buffer.AppendLine(message);
Console.WriteLine(message);
}
}
}
| 42 |
aws-lambda-dotnet | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Amazon.Lambda.TestUtilities")]
[assembly: AssemblyDescription("Amazon.Lambda.TestUtilties includes stub implementations of interfaces defined in Amazon.Lambda.Core and helper methods.")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: ComVisible(false)]
[assembly: System.CLSCompliant(true)]
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 13 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Amazon.Lambda.Annotations;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
// This file is used to test the Lambda Annotations source generator does not run when there is a compile error.
namespace TestServerlessApp
{
public class NonCompilableCodeFile
{
[LambdaFunction]
public void SyntaxErrorFunction()
{
{
}
}
} | 22 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Immutable;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using Microsoft.Extensions.DependencyInjection;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests
{
/// <summary>
/// Source: https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md
/// </summary>
public static class CSharpSourceGeneratorVerifier<TSourceGenerator>
where TSourceGenerator : ISourceGenerator, new()
{
public class Test : CSharpSourceGeneratorTest<TSourceGenerator, XUnitVerifier>
{
public enum ReferencesMode {All, NoApiGatewayEvents}
public Test(ReferencesMode referencesMode = ReferencesMode.All)
{
if(referencesMode == ReferencesMode.NoApiGatewayEvents)
{
this.SolutionTransforms.Add((solution, projectId) =>
{
return solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ILambdaContext).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(IServiceCollection).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ServiceProvider).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(RestApiAttribute).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(DefaultLambdaJsonSerializer).Assembly.Location));
});
}
else
{
this.SolutionTransforms.Add((solution, projectId) =>
{
return solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ILambdaContext).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(APIGatewayProxyRequest).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(IServiceCollection).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ServiceProvider).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(RestApiAttribute).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(DefaultLambdaJsonSerializer).Assembly.Location));
});
}
}
protected override CompilationOptions CreateCompilationOptions()
{
var compilationOptions = base.CreateCompilationOptions();
return compilationOptions
.WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(GetNullableWarningsFromCompiler()))
.WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(EnableNullability()));
}
public LanguageVersion LanguageVersion { get; set; } = LanguageVersion.Default;
private static ImmutableDictionary<string, ReportDiagnostic> GetNullableWarningsFromCompiler()
{
string[] args = { "/warnaserror:nullable" };
var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory);
var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions;
return nullableWarnings;
}
private static ImmutableDictionary<string, ReportDiagnostic> EnableNullability()
{
string[] args = { "/p:Nullable=enable" };
var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory);
var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions;
return nullableWarnings;
}
protected override ParseOptions CreateParseOptions()
{
return ((CSharpParseOptions)base.CreateParseOptions()).WithLanguageVersion(LanguageVersion);
}
}
}
} | 87 |
aws-lambda-dotnet | aws | C# | using System;
using System.Net;
using System.Collections.Generic;
using System.Text.Json;
using Amazon.Lambda.Annotations.APIGateway;
using Xunit;
using System.IO;
using System.Linq;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests
{
public class HttpResultsTest
{
[Fact]
public void OkNoBody()
{
var result = HttpResults.Ok();
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK);
}
[Fact]
public void OkStringBody()
{
var body = "Hello World";
var result = HttpResults.Ok(body);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, body, headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "text/plain" } }
}
);
}
[Fact]
public void OverrideContentType()
{
var body = "Hello World";
var result = HttpResults.Ok(body).AddHeader("content-type", "custom/foo");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, body, headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "custom/foo" } }
}
);
}
[Fact]
public void OkByteArrayBody()
{
var body = new byte[] { 0x01, 0x02 };
var result = HttpResults.Ok(body);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, Convert.ToBase64String(body), isBase64Encoded: true, headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "application/octet-stream" } }
}
);
}
[Fact]
public void OkStreamBody()
{
var body = new byte[] { 0x01, 0x02 };
var result = HttpResults.Ok(new MemoryStream(body));
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, Convert.ToBase64String(body), isBase64Encoded: true, headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "application/octet-stream" } }
}
);
}
[Fact]
public void OkListOfBytesBody()
{
var body = new byte[] { 0x01, 0x02 };
var result = HttpResults.Ok(new List<byte>(body));
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, Convert.ToBase64String(body), isBase64Encoded: true, headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "application/octet-stream" } }
}
);
}
[Fact]
public void OkWithTypeBody()
{
var body = new FakeBody();
var result = HttpResults.Ok(body);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, "{\"Id\":1}", isBase64Encoded: false, headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "application/json" } }
}
);
}
[Fact]
public void OkWithSingleValueHeader()
{
var result = HttpResults.Ok()
.AddHeader("header1", "value1")
.AddHeader("header2", "value2");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK,
headers: new Dictionary<string, IList<string>>
{
{ "header1", new List<string> { "value1" } },
{ "header2", new List<string> { "value2" } }
}
);
}
[Fact]
public void OkWithMultiValueHeader()
{
var result = HttpResults.Ok()
.AddHeader("header1", "foo1")
.AddHeader("header1", "foo2")
.AddHeader("header2", "bar1")
.AddHeader("header2", "bar2");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK,
headers: new Dictionary<string, IList<string>>
{
{ "header1", new List<string> { "foo1", "foo2" } },
{ "header2", new List<string> { "bar1", "bar2" } }
}
);
}
[Fact]
public void Accepted()
{
var result = HttpResults.Accepted();
Assert.Equal(HttpStatusCode.Accepted, result.StatusCode);
ValidateResult(result, HttpStatusCode.Accepted);
}
[Fact]
public void BadRequest()
{
var result = HttpResults.BadRequest();
Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode);
ValidateResult(result, HttpStatusCode.BadRequest);
}
[Fact]
public void Conflict()
{
var result = HttpResults.Conflict();
Assert.Equal(HttpStatusCode.Conflict, result.StatusCode);
ValidateResult(result, HttpStatusCode.Conflict);
}
[Fact]
public void Created()
{
var result = HttpResults.Created();
Assert.Equal(HttpStatusCode.Created, result.StatusCode);
ValidateResult(result, HttpStatusCode.Created);
}
[Fact]
public void CreatedWithUriAndBody()
{
var result = HttpResults.Created("http://localhost/foo", "Resource Created");
Assert.Equal(HttpStatusCode.Created, result.StatusCode);
ValidateResult(result, HttpStatusCode.Created, "Resource Created",
headers: new Dictionary<string, IList<string>>
{
{ "content-type", new List<string> { "text/plain" } },
{ "location", new List<string> { "http://localhost/foo" } }
}
);
}
[Fact]
public void Forbid()
{
var result = HttpResults.Forbid();
Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode);
ValidateResult(result, HttpStatusCode.Forbidden);
}
[Fact]
public void Redirect_PermanentRedirect()
{
var result = HttpResults.Redirect("http://localhost/foo", permanent: true, preserveMethod: true);
Assert.Equal(HttpStatusCode.PermanentRedirect, result.StatusCode);
ValidateResult(result, HttpStatusCode.PermanentRedirect,
headers: new Dictionary<string, IList<string>>
{
{ "location", new List<string> { "http://localhost/foo" } }
}
);
}
[Fact]
public void Redirect_MovedPermanently()
{
var result = HttpResults.Redirect("http://localhost/foo", permanent: true, preserveMethod: false);
Assert.Equal(HttpStatusCode.MovedPermanently, result.StatusCode);
ValidateResult(result, HttpStatusCode.MovedPermanently,
headers: new Dictionary<string, IList<string>>
{
{ "location", new List<string> { "http://localhost/foo" } }
}
);
}
[Fact]
public void Redirect_TemporaryRedirect()
{
var result = HttpResults.Redirect("http://localhost/foo", permanent: false, preserveMethod: true);
Assert.Equal(HttpStatusCode.TemporaryRedirect, result.StatusCode);
ValidateResult(result, HttpStatusCode.TemporaryRedirect,
headers: new Dictionary<string, IList<string>>
{
{ "location", new List<string> { "http://localhost/foo" } }
}
);
}
[Fact]
public void Redirect_Redirect()
{
var result = HttpResults.Redirect("http://localhost/foo", permanent: false, preserveMethod: false);
Assert.Equal(HttpStatusCode.Redirect, result.StatusCode);
ValidateResult(result, HttpStatusCode.Redirect,
headers: new Dictionary<string, IList<string>>
{
{ "location", new List<string> { "http://localhost/foo" } }
}
);
}
[Fact]
public void NotFound()
{
var result = HttpResults.NotFound();
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
ValidateResult(result, HttpStatusCode.NotFound);
}
[Fact]
public void Unauthorized()
{
var result = HttpResults.Unauthorized();
Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
ValidateResult(result, HttpStatusCode.Unauthorized);
}
[Fact]
public void MixCaseHeaders()
{
var result = HttpResults.Ok()
.AddHeader("key", "value1")
.AddHeader("key", "value2")
.AddHeader("KEY", "VALUE3");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
ValidateResult(result, HttpStatusCode.OK, headers: new Dictionary<string, IList<string>>
{
{"key", new List<string> {"value1", "value2", "VALUE3"} }
});
}
[Fact]
public void InternalServerError()
{
var result = HttpResults.InternalServerError();
Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
ValidateResult(result, HttpStatusCode.InternalServerError);
}
[Fact]
public void BadGateway()
{
var result = HttpResults.BadGateway();
Assert.Equal(HttpStatusCode.BadGateway, result.StatusCode);
ValidateResult(result, HttpStatusCode.BadGateway);
}
[Theory]
[InlineData(null)]
[InlineData(0)]
public void ServiceUnavailable_WithoutRetryAfter(int? delay)
{
var result = HttpResults.ServiceUnavailable(delay);
Assert.Equal(HttpStatusCode.ServiceUnavailable, result.StatusCode);
ValidateResult(result, HttpStatusCode.ServiceUnavailable);
}
[Fact]
public void ServiceUnavailable_WithRetryAfter()
{
var result = HttpResults.ServiceUnavailable(100);
Assert.Equal(HttpStatusCode.ServiceUnavailable, result.StatusCode);
ValidateResult(result, HttpStatusCode.ServiceUnavailable, headers: new Dictionary<string, IList<string>>
{
{"retry-after", new List<string> {"100"} }
});
}
private void ValidateResult(IHttpResult result, HttpStatusCode statusCode, string body = null, bool isBase64Encoded = false, IDictionary<string, IList<string>> headers = null)
{
var testScenarios = new List<Tuple<HttpResultSerializationOptions.ProtocolFormat, HttpResultSerializationOptions.ProtocolVersion>>
{
new (HttpResultSerializationOptions.ProtocolFormat.RestApi, HttpResultSerializationOptions.ProtocolVersion.V1),
new (HttpResultSerializationOptions.ProtocolFormat.HttpApi, HttpResultSerializationOptions.ProtocolVersion.V1),
new (HttpResultSerializationOptions.ProtocolFormat.HttpApi, HttpResultSerializationOptions.ProtocolVersion.V2)
};
foreach(var (format, version) in testScenarios)
{
var stream = result.Serialize(new HttpResultSerializationOptions { Format = format, Version = version });
var jsonDoc = JsonDocument.Parse(stream);
if (format == HttpResultSerializationOptions.ProtocolFormat.RestApi || (format == HttpResultSerializationOptions.ProtocolFormat.HttpApi && version == HttpResultSerializationOptions.ProtocolVersion.V1))
{
Assert.Equal((int)statusCode, jsonDoc.RootElement.GetProperty("statusCode").GetInt32());
if(body != null)
{
Assert.Equal(body, jsonDoc.RootElement.GetProperty("body").GetString());
Assert.Equal(isBase64Encoded, jsonDoc.RootElement.GetProperty("isBase64Encoded").GetBoolean());
}
else
{
var bodyProperties = jsonDoc.RootElement.GetProperty("body");
Assert.Equal(JsonValueKind.Null, bodyProperties.ValueKind);
}
if (headers != null)
{
var headerProperties = jsonDoc.RootElement.GetProperty("multiValueHeaders");
Assert.Equal(headers.Count, headerProperties.EnumerateObject().Count());
foreach(var kvp in headers)
{
if(!headerProperties.TryGetProperty(kvp.Key, out var values))
{
Assert.Fail($"Fail to find header {kvp.Key}");
}
Assert.Equal(JsonValueKind.Array, values.ValueKind);
Assert.Equal(kvp.Value.Count, values.GetArrayLength());
for(var i = 0; i < kvp.Value.Count; i++)
{
Assert.Equal(kvp.Value[i], values[i].GetString());
}
}
}
else
{
var headerProperties = jsonDoc.RootElement.GetProperty("multiValueHeaders");
Assert.Equal(JsonValueKind.Null, headerProperties.ValueKind);
}
}
else
{
Assert.Equal((int)statusCode, jsonDoc.RootElement.GetProperty("statusCode").GetInt32());
if (body != null)
{
Assert.Equal(body, jsonDoc.RootElement.GetProperty("body").GetString());
Assert.Equal(isBase64Encoded, jsonDoc.RootElement.GetProperty("isBase64Encoded").GetBoolean());
}
else
{
var bodyProperties = jsonDoc.RootElement.GetProperty("body");
Assert.Equal(JsonValueKind.Null, bodyProperties.ValueKind);
}
if (headers != null)
{
var headerProperties = jsonDoc.RootElement.GetProperty("headers");
Assert.Equal(headers.Count, headerProperties.EnumerateObject().Count());
foreach (var kvp in headers)
{
var commaDelimtedValues = string.Join(",", kvp.Value);
if (!headerProperties.TryGetProperty(kvp.Key, out var values))
{
Assert.Fail($"Fail to find header {kvp.Key}");
}
Assert.Equal(commaDelimtedValues, values.GetString());
}
}
else
{
var headerProperties = jsonDoc.RootElement.GetProperty("headers");
Assert.Equal(JsonValueKind.Null, headerProperties.ValueKind);
}
}
}
}
public class FakeBody
{
public int Id { get; set; } = 1;
}
}
}
| 459 |
aws-lambda-dotnet | aws | C# | using System.Net;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Core;
using Xunit;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests
{
public class HtttpResultsStatusCodeUsage
{
[Fact]
public void UsageOfIHttpResultStatusCode()
{
var sut = new Functions();
var result = sut.GetResponse("good", null);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
result = sut.GetResponse("not good", null);
Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode);
}
}
public class Functions
{
[LambdaFunction]
[HttpApi(LambdaHttpMethod.Get, "/resource/{type}")]
public IHttpResult GetResponse(string type, ILambdaContext context)
{
return type == "good" ?
HttpResults.Ok() :
HttpResults.BadRequest();
}
}
}
| 37 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.SourceGenerator;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Amazon.Lambda.Annotations.SourceGenerator.Validation;
using Xunit;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests
{
public class RouteParameterValidatorTests
{
[Fact]
public void Validate_AllRouteParamsFound()
{
var routeParameters = new HashSet<string> {"id1", "id2"};
var lambdaMethodParams = new List<ParameterModel>
{
new ParameterModel
{
Attributes = new List<AttributeModel>
{
new AttributeModel<FromRouteAttribute>
{
Data = new FromRouteAttribute { Name = "id1"}
}
},
Name = "identifier1"
},
new ParameterModel
{
Name = "id2"
}
};
var (isValid, missingRouteParams) = RouteParametersValidator.Validate(routeParameters, lambdaMethodParams);
Assert.True(isValid);
Assert.Empty(missingRouteParams);
}
[Fact]
public void Validate_MissingRouteParam()
{
var routeParameters = new HashSet<string> {"id1", "id2"};
var lambdaMethodParams = new List<ParameterModel>
{
new ParameterModel
{
Attributes = new List<AttributeModel>
{
new AttributeModel<FromRouteAttribute>
{
Data = new FromRouteAttribute { Name = "id1"}
}
}
}
};
var (isValid, missingRouteParams) = RouteParametersValidator.Validate(routeParameters, lambdaMethodParams);
Assert.False(isValid);
Assert.NotEmpty(missingRouteParams);
Assert.Equal("id2", missingRouteParams[0]);
}
[Fact]
public void Validate_RouteParamConflictFound()
{
var routeParameters = new HashSet<string> {"id1", "id2"};
var lambdaMethodParams = new List<ParameterModel>
{
new ParameterModel
{
Attributes = new List<AttributeModel>
{
new AttributeModel<FromRouteAttribute>
{
Data = new FromRouteAttribute { Name = "identifier1"},
Type = new TypeModel { FullName = TypeFullNames.FromRouteAttribute}
}
},
Type = new TypeModel
{
FullName = "int"
}
},
new ParameterModel
{
Attributes = new List<AttributeModel>
{
new AttributeModel<FromHeaderAttribute>
{
Data = new FromHeaderAttribute { Name = "identifier2"},
Type = new TypeModel { FullName = TypeFullNames.FromHeaderAttribute}
},
},
Name = "id2",
}
};
var exception = Assert.Throws<InvalidOperationException>(() =>
{
RouteParametersValidator.Validate(routeParameters, lambdaMethodParams);
});
Assert.Equal($"Conflicting attribute(s) {TypeFullNames.FromHeaderAttribute} found on id2 method parameter.", exception.Message);
}
}
} | 109 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Text;
using Xunit;
using VerifyCS = Amazon.Lambda.Annotations.SourceGenerators.Tests.CSharpSourceGeneratorVerifier<Amazon.Lambda.Annotations.SourceGenerator.Generator>;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests
{
public class SourceGeneratorTests : IDisposable
{
[Fact]
public async Task Greeter()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "greeter.template")).ToEnvironmentLineEndings();
var expectedSayHelloGenerated = File.ReadAllText(Path.Combine("Snapshots", "Greeter_SayHello_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedSayHelloAsyncGenerated = File.ReadAllText(Path.Combine("Snapshots", "Greeter_SayHelloAsync_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "Greeter.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "Greeter.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"Greeter_SayHello_Generated.g.cs",
SourceText.From(expectedSayHelloGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"Greeter_SayHelloAsync_Generated.g.cs",
SourceText.From(expectedSayHelloAsyncGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("Greeter_SayHello_Generated.g.cs", expectedSayHelloGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("Greeter_SayHelloAsync_Generated.g.cs", expectedSayHelloAsyncGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task GeneratorDoesNotRunDueToCompileError()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "greeter.template")).ToEnvironmentLineEndings();
var expectedSayHelloGenerated = File.ReadAllText(Path.Combine("Snapshots", "Greeter_SayHello_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedSayHelloAsyncGenerated = File.ReadAllText(Path.Combine("Snapshots", "Greeter_SayHelloAsync_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "Greeter.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "Greeter.cs"))),
("NonCompilableCodeFile.cs", File.ReadAllText("NonCompilableCodeFile.cs")),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
// If the generator would have ran then we would see the generated sources from the Greeter syntax tree.
},
ExpectedDiagnostics =
{
// Now AWS Lambda Annotations INFO diagnostics were emited showing again the generator didn't run.
new DiagnosticResult("CS1513", DiagnosticSeverity.Error).WithSpan("NonCompilableCodeFile.cs", 22, 2, 22, 2)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
}
[Fact]
public async Task SimpleCalculator()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "simpleCalculator.template")).ToEnvironmentLineEndings();
var expectedAddGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_Add_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedSubtractGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_Subtract_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedMultiplyGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_Multiply_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedDivideAsyncGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_DivideAsync_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedPiGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_Pi_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedRandomGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_Random_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedRandomsGenerated = File.ReadAllText(Path.Combine("Snapshots", "SimpleCalculator_Randoms_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "SimpleCalculator.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "SimpleCalculator.cs"))),
(Path.Combine("TestServerlessApp", "Startup.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "Startup.cs"))),
(Path.Combine("TestServerlessApp", "Services", "SimpleCalculatorService.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "Services", "SimpleCalculatorService.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "FromServicesAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "FromServicesAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_Add_Generated.g.cs",
SourceText.From(expectedAddGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_Subtract_Generated.g.cs",
SourceText.From(expectedSubtractGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_Multiply_Generated.g.cs",
SourceText.From(expectedMultiplyGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_DivideAsync_Generated.g.cs",
SourceText.From(expectedDivideAsyncGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_Pi_Generated.g.cs",
SourceText.From(expectedPiGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_Random_Generated.g.cs",
SourceText.From(expectedRandomGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"SimpleCalculator_Randoms_Generated.g.cs",
SourceText.From(expectedRandomsGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_Add_Generated.g.cs", expectedAddGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_Subtract_Generated.g.cs", expectedSubtractGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_Multiply_Generated.g.cs", expectedMultiplyGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_DivideAsync_Generated.g.cs", expectedDivideAsyncGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_Pi_Generated.g.cs", expectedPiGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_Random_Generated.g.cs", expectedRandomGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("SimpleCalculator_Randoms_Generated.g.cs", expectedRandomsGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task ComplexCalculator()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "complexCalculator.template")).ToEnvironmentLineEndings();
var expectedAddGenerated = File.ReadAllText(Path.Combine("Snapshots", "ComplexCalculator_Add_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedSubtractGenerated = File.ReadAllText(Path.Combine("Snapshots", "ComplexCalculator_Subtract_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "ComplexCalculator.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "ComplexCalculator.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"ComplexCalculator_Add_Generated.g.cs",
SourceText.From(expectedAddGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"ComplexCalculator_Subtract_Generated.g.cs",
SourceText.From(expectedSubtractGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("ComplexCalculator_Add_Generated.g.cs", expectedAddGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("ComplexCalculator_Subtract_Generated.g.cs", expectedSubtractGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task VerifyFunctionInSubNamespace()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "subnamespace.template")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated = File.ReadAllText(Path.Combine("Snapshots", "Functions_ToUpper_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "Sub1", "Functions.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "Sub1", "Functions.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"Functions_ToUpper_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("Functions_ToUpper_Generated.g.cs", expectedSubNamespaceGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task VerifyFunctionReturnVoid()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "voidexample.template")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated = File.ReadAllText(Path.Combine("Snapshots", "VoidExample_VoidReturn_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "VoidExample.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "VoidExample.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"VoidExample_VoidReturn_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("VoidExample_VoidReturn_Generated.g.cs", expectedSubNamespaceGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task VerifyNoErrorWithIntrinsicInTemplate()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "intrinsicexample.template")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated = File.ReadAllText(Path.Combine("Snapshots", "IntrinsicExample_HasIntrinsic_Generated.g.cs")).ToEnvironmentLineEndings();
File.WriteAllText(Path.Combine("TestServerlessApp", "serverless.template"), expectedTemplateContent);
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "IntrinsicExample.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "IntrinsicExample.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"IntrinsicExample_HasIntrinsic_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("IntrinsicExample_HasIntrinsic_Generated.g.cs", expectedSubNamespaceGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task VerifyFunctionReturnTask()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "taskexample.template")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated = File.ReadAllText(Path.Combine("Snapshots", "TaskExample_TaskReturn_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "TaskExample.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "TaskExample.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"TaskExample_TaskReturn_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("TaskExample_TaskReturn_Generated.g.cs", expectedSubNamespaceGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task VerifyFunctionDynamic()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "dynamicexample.template")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated_DynamicReturn = File.ReadAllText(Path.Combine("Snapshots", "DynamicExample_DynamicReturn_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated_DynamicInput = File.ReadAllText(Path.Combine("Snapshots", "DynamicExample_DynamicInput_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "DynamicExample.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "DynamicExample.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"DynamicExample_DynamicReturn_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated_DynamicReturn, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"DynamicExample_DynamicInput_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated_DynamicInput, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("DynamicExample_DynamicReturn_Generated.g.cs", expectedSubNamespaceGenerated_DynamicReturn),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("DynamicExample_DynamicInput_Generated.g.cs", expectedSubNamespaceGenerated_DynamicInput)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task CustomizeResponses()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "customizeResponse.template")).ToEnvironmentLineEndings();
var expectedOkResponseWithHeaderGenerated = File.ReadAllText(Path.Combine("Snapshots", "CustomizeResponseExamples_OkResponseWithHeader_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedNotFoundResponseWithHeaderV2Generated = File.ReadAllText(Path.Combine("Snapshots", "CustomizeResponseExamples_NotFoundResponseWithHeaderV2_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedNotFoundResponseWithHeaderV1Generated = File.ReadAllText(Path.Combine("Snapshots", "CustomizeResponseExamples_NotFoundResponseWithHeaderV1_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedOkResponseWithHeaderAsyncGenerated = File.ReadAllText(Path.Combine("Snapshots", "CustomizeResponseExamples_OkResponseWithHeaderAsync_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedNotFoundResponseWithHeaderV2AsyncGenerated = File.ReadAllText(Path.Combine("Snapshots", "CustomizeResponseExamples_NotFoundResponseWithHeaderV2Async_Generated.g.cs")).ToEnvironmentLineEndings();
var expectedNotFoundResponseWithHeaderV1AsyncGenerated = File.ReadAllText(Path.Combine("Snapshots", "CustomizeResponseExamples_NotFoundResponseWithHeaderV1Async_Generated.g.cs")).ToEnvironmentLineEndings();
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "CustomizeResponseExamples.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "CustomizeResponseExamples.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"CustomizeResponseExamples_OkResponseWithHeader_Generated.g.cs",
SourceText.From(expectedOkResponseWithHeaderGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"CustomizeResponseExamples_OkResponseWithHeaderAsync_Generated.g.cs",
SourceText.From(expectedOkResponseWithHeaderAsyncGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"CustomizeResponseExamples_NotFoundResponseWithHeaderV2_Generated.g.cs",
SourceText.From(expectedNotFoundResponseWithHeaderV2Generated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"CustomizeResponseExamples_NotFoundResponseWithHeaderV2Async_Generated.g.cs",
SourceText.From(expectedNotFoundResponseWithHeaderV2AsyncGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"CustomizeResponseExamples_NotFoundResponseWithHeaderV1_Generated.g.cs",
SourceText.From(expectedNotFoundResponseWithHeaderV1Generated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
),
(
typeof(SourceGenerator.Generator),
"CustomizeResponseExamples_NotFoundResponseWithHeaderV1Async_Generated.g.cs",
SourceText.From(expectedNotFoundResponseWithHeaderV1AsyncGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomizeResponseExamples_OkResponseWithHeader_Generated.g.cs", expectedOkResponseWithHeaderGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomizeResponseExamples_OkResponseWithHeaderAsync_Generated.g.cs", expectedOkResponseWithHeaderAsyncGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomizeResponseExamples_NotFoundResponseWithHeaderV2_Generated.g.cs", expectedNotFoundResponseWithHeaderV2Generated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomizeResponseExamples_NotFoundResponseWithHeaderV2Async_Generated.g.cs", expectedNotFoundResponseWithHeaderV2AsyncGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomizeResponseExamples_NotFoundResponseWithHeaderV1_Generated.g.cs", expectedNotFoundResponseWithHeaderV1Generated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomizeResponseExamples_NotFoundResponseWithHeaderV1Async_Generated.g.cs", expectedNotFoundResponseWithHeaderV1AsyncGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task InvalidReturnTypeIHttpResult()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"))),
(Path.Combine("TestServerlessApp", "CustomizeResponseWithErrors.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "CustomizeResponseWithErrors.cs.error"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
ExpectedDiagnostics =
{
DiagnosticResult.CompilerError("AWSLambda0105").WithSpan($"TestServerlessApp{Path.DirectorySeparatorChar}CustomizeResponseWithErrors.cs", 14, 9, 21, 10).WithArguments("Error")
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
}
[Fact]
public async Task MissingResourePathMapping()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"))),
(Path.Combine("TestServerlessApp", "MissingResourePathMapping.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "MissingResourePathMapping.cs.error"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
ExpectedDiagnostics =
{
DiagnosticResult.CompilerError("AWSLambda0107").WithSpan($"TestServerlessApp{Path.DirectorySeparatorChar}MissingResourePathMapping.cs", 15, 9, 20, 10)
.WithMessage("Route template /add/{x}/{y} is invalid. Missing x parameters in method definition.")
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
}
[Fact]
public async Task VerifyApiFunctionUsingNullableParameters()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "nullreferenceexample.template")).ToEnvironmentLineEndings();
var expectedCSharpContent = File.ReadAllText(Path.Combine("Snapshots", "NullableReferenceTypeExample_NullableHeaderHttpApi_Generated.g.cs")).ToEnvironmentLineEndings();
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "NullableReferenceTypeExample.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "NullableReferenceTypeExample.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"NullableReferenceTypeExample_NullableHeaderHttpApi_Generated.g.cs",
SourceText.From(expectedCSharpContent, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("NullableReferenceTypeExample_NullableHeaderHttpApi_Generated.g.cs", expectedCSharpContent),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60,
},
};
await test.RunAsync();
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
[Fact]
public async Task VerifyNoApiGatewayEventsReference()
{
var test = new VerifyCS.Test(VerifyCS.Test.ReferencesMode.NoApiGatewayEvents)
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "FromScratch", "NoApiGatewayEventsReference.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "FromScratch", "NoApiGatewayEventsReference.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
GeneratedSources =
{
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0104", DiagnosticSeverity.Error)
.WithMessage("Your project has a missing required package dependency. Please add a reference to the following package: Amazon.Lambda.APIGatewayEvents.")
.WithSpan($"TestServerlessApp{Path.DirectorySeparatorChar}FromScratch{Path.DirectorySeparatorChar}NoApiGatewayEventsReference.cs", 9, 9, 14, 10),
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60,
},
};
await test.RunAsync();
}
[Fact]
public async Task VerifyNoSerializerAttributeReference()
{
var test = new VerifyCS.Test()
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "FromScratch", "NoSerializerAttributeReference.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "FromScratch", "NoSerializerAttributeReference.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
},
GeneratedSources =
{
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0108", DiagnosticSeverity.Error)
.WithSpan($"TestServerlessApp{Path.DirectorySeparatorChar}FromScratch{Path.DirectorySeparatorChar}NoSerializerAttributeReference.cs", 9, 9, 13, 10),
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60,
},
};
await test.RunAsync();
}
[Fact]
public async Task ComplexQueryParameters_AreNotSupported()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"))),
(Path.Combine("TestServerlessApp", "ComplexQueryParameter.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "ComplexQueryParameter.cs.error"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "RestApiAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "APIGateway", "HttpApiAttribute.cs"))),
(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "AssemblyAttributes.cs"))),
},
ExpectedDiagnostics =
{
DiagnosticResult.CompilerError("AWSLambda0109").WithSpan($"TestServerlessApp{Path.DirectorySeparatorChar}ComplexQueryParameter.cs", 11, 9, 16, 10)
.WithMessage("Unsupported query paramter 'person' of type 'TestServerlessApp.Person' encountered. Only primitive .NET types and their corresponding enumerables can be used as query parameters.")
},
ReferenceAssemblies = ReferenceAssemblies.Net.Net60
}
}.RunAsync();
}
public void Dispose()
{
File.Delete(Path.Combine("TestServerlessApp", "serverless.template"));
}
}
} | 694 |
aws-lambda-dotnet | aws | C# | using System.IO;
using Amazon.Lambda.Annotations.SourceGenerator;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Xunit;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.CloudFormationTemplateHandlerTests
{
public class DetermineProjectPathTests
{
/// <summary>
/// Tests that that we can resolve the path of the .csproj from different source files in a Lambda project
/// </summary>
[Fact]
public void DetermineProjectPath()
{
// ARRANGE
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var projectRoot = Path.Combine(tempDir, "Codebase", "Src", "MyServerlessApp");
Helpers.CreateCustomerApplication(projectRoot);
var expectedProjectPath = Path.Combine(projectRoot, "MyServerlessApp.csproj");
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
// ACT and ASSERT
Assert.Equal(expectedProjectPath, templateHandler.DetermineProjectPath(Path.Combine(projectRoot, "Models", "Cars.cs")));
Assert.Equal(expectedProjectPath, templateHandler.DetermineProjectPath(Path.Combine(projectRoot, "BusinessLogic", "Logic2.cs")));
Assert.Equal(expectedProjectPath, templateHandler.DetermineProjectPath(Path.Combine(projectRoot, "Program.cs")));
Assert.Equal(expectedProjectPath, templateHandler.DetermineProjectPath(Path.Combine(projectRoot, "MyServerlessApp.csproj")));
}
}
} | 30 |
aws-lambda-dotnet | aws | C# | using System.IO;
using Amazon.Lambda.Annotations.SourceGenerator;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Xunit;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.CloudFormationTemplateHandlerTests
{
public class DetermineTemplateFormatTests
{
[Fact]
public void DetermineTemplateFormat_NoTemplate()
{
// ARRANGE
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var templatePath = Path.Combine(tempDir, "serverless.template");
// ACT
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
var format = templateHandler.DetermineTemplateFormat(templatePath);
// ASSERT
Assert.Equal(CloudFormationTemplateFormat.Json, format);
}
[Fact]
public void DetermineTemplateFormat_EmptyTemplate()
{
// ARRANGE
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var templatePath = Path.Combine(tempDir, "serverless.template");
Helpers.CreateFile(templatePath);
// ACT
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
var format = templateHandler.DetermineTemplateFormat(templatePath);
// ASSERT
Assert.Equal(CloudFormationTemplateFormat.Json, format);
}
[Fact]
public void DetermineTemplateFormat_Json()
{
// ARRANGE
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var templatePath = Path.Combine(tempDir, "serverless.template");
Helpers.CreateFile(templatePath);
const string content = @"{
'AWSTemplateFormatVersion':'2010-09-09',
'Transform':'AWS::Serverless-2016-10-31',
'Description':'An AWS Serverless Application.',
'Parameters':{
'ArchitectureTypeParameter':{
'Type':'String',
'Default':'x86_64',
'AllowedValues':[
'x86_64',
'arm64'
]
}
}
}";
File.WriteAllText(templatePath, content);
// ACT
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
var format = templateHandler.DetermineTemplateFormat(templatePath);
// ASSERT
Assert.Equal(CloudFormationTemplateFormat.Json, format);
}
[Fact]
public void DetermineTemplateFormat_Yaml()
{
// ARRANGE
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var templatePath = Path.Combine(tempDir, "serverless.template");
Helpers.CreateFile(templatePath);
const string content = @"AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: An AWS Serverless Application.
Parameters:
ArchitectureTypeParameter:
Type: String
Default: x86_64
AllowedValues:
- x86_64
- arm64
";
File.WriteAllText(templatePath, content);
// ACT
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
var format = templateHandler.DetermineTemplateFormat(templatePath);
// ASSERT
Assert.Equal(CloudFormationTemplateFormat.Yaml, format);
}
}
} | 101 |
aws-lambda-dotnet | aws | C# | using System.IO;
using Amazon.Lambda.Annotations.SourceGenerator;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Xunit;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.CloudFormationTemplateHandlerTests
{
public class FindTemplateTests
{
[Fact]
public void FindTemplate_WithoutDefaultConfigFile()
{
// ARRANGE
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var projectRoot = Path.Combine(tempDir, "Codebase", "Src", "MyServerlessApp");
Helpers.CreateCustomerApplication(projectRoot);
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
// ACT
var templatePath = templateHandler.FindTemplate(projectRoot);
// ASSERT
var expectedPath = Path.Combine(projectRoot, "serverless.template");
Assert.Equal(expectedPath, templatePath);
Assert.True(File.Exists(templatePath));
}
[Fact]
public void FindTemplate_FromDefaultConfigFile()
{
// ARRANGE
const string content = @"{
'Information': [
'This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.',
'To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.',
'dotnet lambda help',
'All the command line options for the Lambda command can be specified in this file.'
],
'profile': 'default',
'region': 'us-west-2',
'configuration': 'Release',
'framework': 'netcoreapp3.1',
's3-prefix': 'AWSServerless1/',
'template': 'serverless.template',
'template-parameters': ''
}";
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var projectRoot = Path.Combine(tempDir, "Codebase", "Src", "MyServerlessApp");
Helpers.CreateCustomerApplication(projectRoot);
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
Helpers.CreateFile(Path.Combine(projectRoot, "Configurations", "aws-lambda-tools-defaults.json"));
File.WriteAllText(Path.Combine(projectRoot, "Configurations", "aws-lambda-tools-defaults.json"), content);
// ACT
var templatePath = templateHandler.FindTemplate(projectRoot);
// ASSERT
var expectedPath = Path.Combine(projectRoot, "Configurations", "serverless.template");
Assert.Equal(expectedPath, templatePath);
Assert.True(File.Exists(templatePath));
}
[Fact]
public void FindTemplate_DefaultConfigFileDoesNotHaveTemplateProperty()
{
// ARRANGE
const string content = @"{
'Information': [
'This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.',
'To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.',
'dotnet lambda help',
'All the command line options for the Lambda command can be specified in this file.'
],
'profile': 'default',
'region': 'us-west-2',
'configuration': 'Release',
'framework': 'netcoreapp3.1',
's3-prefix': 'AWSServerless1/'
}";
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var projectRoot = Path.Combine(tempDir, "Codebase", "Src", "MyServerlessApp");
Helpers.CreateCustomerApplication(projectRoot);
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
Helpers.CreateFile(Path.Combine(projectRoot, "Configurations", "aws-lambda-tools-defaults.json"));
File.WriteAllText(Path.Combine(projectRoot, "Configurations", "aws-lambda-tools-defaults.json"), content);
// ACT
var templatePath = templateHandler.FindTemplate(projectRoot);
// ASSERT
var expectedPath = Path.Combine(projectRoot, "serverless.template");
Assert.Equal(expectedPath, templatePath);
Assert.True(File.Exists(templatePath));
}
[Fact]
public void FindTemplate_DefaultConfigFile_Template_Is_AboveProjectRoot()
{
// ARRANGE
const string content = @"{
'profile': 'default',
'region': 'us-west-2',
'template': '../serverless.template',
}";
var tempDir = Path.Combine(Path.GetTempPath(), Helpers.GetRandomDirectoryName());
var projectRoot = Path.Combine(tempDir, "Codebase", "Src", "MyServerlessApp");
Helpers.CreateCustomerApplication(projectRoot);
var templateHandler = new CloudFormationTemplateHandler(new FileManager(), new DirectoryManager());
Helpers.CreateFile(Path.Combine(projectRoot, "aws-lambda-tools-defaults.json"));
File.WriteAllText(Path.Combine(projectRoot, "aws-lambda-tools-defaults.json"), content);
// ACT
var templatePath = templateHandler.FindTemplate(projectRoot);
// ASSERT
var expectedPath = Path.Combine(projectRoot, "..", "serverless.template");
Assert.Equal(expectedPath, templatePath);
Assert.True(File.Exists(templatePath));
}
}
} | 124 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Linq;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.CloudFormationTemplateHandlerTests
{
public static class Helpers
{
public static void CreateCustomerApplication(string projectRoot)
{
CreateFile(Path.Combine(projectRoot, "MyServerlessApp.csproj"));
CreateFile(Path.Combine(projectRoot, "Models", "Cars.cs"));
CreateFile(Path.Combine(projectRoot, "Models", "Bus.cs"));
CreateFile(Path.Combine(projectRoot, "BusinessLogic", "Logic1.cs"));
CreateFile(Path.Combine(projectRoot, "BusinessLogic", "Logic2.cs"));
CreateFile(Path.Combine(projectRoot, "Program.cs"));
}
public static void CreateFile(string filePath)
{
var directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.Create(filePath).Close();
}
public static string GetRandomDirectoryName()
{
var guid = Guid.NewGuid().ToString();
return guid.Split('-').FirstOrDefault();
}
}
} | 35 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.FileIOTests
{
public class DirectoryManagerTests
{
[Theory]
[InlineData("C:/CodeBase/Src/MyProject", "C:/CodeBase/Src/MyProject", ".")]
[InlineData("C:/CodeBase/Src/MyProject/MyFile.cs", "C:/CodeBase/Src/MyProject/MyFile.cs", ".")]
[InlineData("C:/CodeBase/Src/MyProject", "C:/CodeBase/Src/MyProject/MyProject.csproj", "MyProject.csproj")]
[InlineData("C:/CodeBase/Src/MyProject", "C:/CodeBase/Src", "..")]
[InlineData("C:/CodeBase/Src/MyProject", "C:/CodeBase/Test", "../../Test")]
[InlineData("C:/CodeBase/Src/MyProject", "C:/CodeBase/Test/TestApp.csproj", "../../Test/TestApp.csproj")]
[InlineData("C:/CodeBase/Src/MyProject", "C:/CodeBase/Src/MyProject/MyFolder/MyResources", "MyFolder/MyResources")]
[InlineData("C:/CodeBase/Src/MyProject/MyProject.csproj", "C:/CodeBase/Src/MyProject", "..")]
[InlineData("C:/CodeBase/Src/MyProject/MyProject.csproj", "C:/CodeBase/Src", "../..")]
[InlineData("MyFolder", "MyFolder", ".")]
[InlineData("C:/CodeBase/Src/MyProject/MyProject.csproj", "D:/CodeBase/Src/MyProject/MyProject.csproj", "D:/CodeBase/Src/MyProject/MyProject.csproj")]
[InlineData("C:/src/serverlessApp/..", "C:/src/serverlessApp", "serverlessApp")]
public void GetRelativePath(string relativeTo, string path, string expectedPath)
{
var directoryManager = new DirectoryManager();
var relativePath = directoryManager.GetRelativePath(relativeTo, path);
Assert.Equal(expectedPath, relativePath);
}
}
} | 33 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class ComplexCalculator_Add_Generated
{
private readonly ComplexCalculator complexCalculator;
public ComplexCalculator_Add_Generated()
{
SetExecutionEnvironment();
complexCalculator = new ComplexCalculator();
}
public Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse Add(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var complexNumbers = __request__.Body;
var response = complexCalculator.Add(complexNumbers, __context__, __request__);
var body = System.Text.Json.JsonSerializer.Serialize(response);
return new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = body,
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"}
},
StatusCode = 200
};
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 55 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class ComplexCalculator_Subtract_Generated
{
private readonly ComplexCalculator complexCalculator;
public ComplexCalculator_Subtract_Generated()
{
SetExecutionEnvironment();
complexCalculator = new ComplexCalculator();
}
public Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse Subtract(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var complexNumbers = default(System.Collections.Generic.IList<System.Collections.Generic.IList<int>>);
try
{
complexNumbers = System.Text.Json.JsonSerializer.Deserialize<System.Collections.Generic.IList<System.Collections.Generic.IList<int>>>(__request__.Body);
}
catch (Exception e)
{
validationErrors.Add($"Value {__request__.Body} at 'body' failed to satisfy constraint: {e.Message}");
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
return errorResult;
}
var response = complexCalculator.Subtract(complexNumbers);
var body = System.Text.Json.JsonSerializer.Serialize(response);
return new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = body,
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"}
},
StatusCode = 200
};
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 81 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations.APIGateway;
namespace TestServerlessApp
{
public class CustomizeResponseExamples_NotFoundResponseWithHeaderV1Async_Generated
{
private readonly CustomizeResponseExamples customizeResponseExamples;
public CustomizeResponseExamples_NotFoundResponseWithHeaderV1Async_Generated()
{
SetExecutionEnvironment();
customizeResponseExamples = new CustomizeResponseExamples();
}
public async System.Threading.Tasks.Task<System.IO.Stream> NotFoundResponseWithHeaderV1Async(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var x = default(int);
if (__request__.PathParameters?.ContainsKey("x") == true)
{
try
{
x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
var errorStream = new System.IO.MemoryStream();
System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);
return errorStream;
}
var httpResults = await customizeResponseExamples.NotFoundResponseWithHeaderV1Async(x, __context__);
HttpResultSerializationOptions.ProtocolFormat serializationFormat = HttpResultSerializationOptions.ProtocolFormat.HttpApi;
HttpResultSerializationOptions.ProtocolVersion serializationVersion = HttpResultSerializationOptions.ProtocolVersion.V1;
var serializationOptions = new HttpResultSerializationOptions { Format = serializationFormat, Version = serializationVersion };
var response = httpResults.Serialize(serializationOptions);
return response;
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations.APIGateway;
namespace TestServerlessApp
{
public class CustomizeResponseExamples_NotFoundResponseWithHeaderV1_Generated
{
private readonly CustomizeResponseExamples customizeResponseExamples;
public CustomizeResponseExamples_NotFoundResponseWithHeaderV1_Generated()
{
SetExecutionEnvironment();
customizeResponseExamples = new CustomizeResponseExamples();
}
public System.IO.Stream NotFoundResponseWithHeaderV1(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var x = default(int);
if (__request__.PathParameters?.ContainsKey("x") == true)
{
try
{
x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
var errorStream = new System.IO.MemoryStream();
System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);
return errorStream;
}
var httpResults = customizeResponseExamples.NotFoundResponseWithHeaderV1(x, __context__);
HttpResultSerializationOptions.ProtocolFormat serializationFormat = HttpResultSerializationOptions.ProtocolFormat.HttpApi;
HttpResultSerializationOptions.ProtocolVersion serializationVersion = HttpResultSerializationOptions.ProtocolVersion.V1;
var serializationOptions = new HttpResultSerializationOptions { Format = serializationFormat, Version = serializationVersion };
var response = httpResults.Serialize(serializationOptions);
return response;
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations.APIGateway;
namespace TestServerlessApp
{
public class CustomizeResponseExamples_NotFoundResponseWithHeaderV2Async_Generated
{
private readonly CustomizeResponseExamples customizeResponseExamples;
public CustomizeResponseExamples_NotFoundResponseWithHeaderV2Async_Generated()
{
SetExecutionEnvironment();
customizeResponseExamples = new CustomizeResponseExamples();
}
public async System.Threading.Tasks.Task<System.IO.Stream> NotFoundResponseWithHeaderV2Async(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var x = default(int);
if (__request__.PathParameters?.ContainsKey("x") == true)
{
try
{
x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
var errorStream = new System.IO.MemoryStream();
System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);
return errorStream;
}
var httpResults = await customizeResponseExamples.NotFoundResponseWithHeaderV2Async(x, __context__);
HttpResultSerializationOptions.ProtocolFormat serializationFormat = HttpResultSerializationOptions.ProtocolFormat.HttpApi;
HttpResultSerializationOptions.ProtocolVersion serializationVersion = HttpResultSerializationOptions.ProtocolVersion.V2;
var serializationOptions = new HttpResultSerializationOptions { Format = serializationFormat, Version = serializationVersion };
var response = httpResults.Serialize(serializationOptions);
return response;
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations.APIGateway;
namespace TestServerlessApp
{
public class CustomizeResponseExamples_NotFoundResponseWithHeaderV2_Generated
{
private readonly CustomizeResponseExamples customizeResponseExamples;
public CustomizeResponseExamples_NotFoundResponseWithHeaderV2_Generated()
{
SetExecutionEnvironment();
customizeResponseExamples = new CustomizeResponseExamples();
}
public System.IO.Stream NotFoundResponseWithHeaderV2(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var x = default(int);
if (__request__.PathParameters?.ContainsKey("x") == true)
{
try
{
x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
var errorStream = new System.IO.MemoryStream();
System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);
return errorStream;
}
var httpResults = customizeResponseExamples.NotFoundResponseWithHeaderV2(x, __context__);
HttpResultSerializationOptions.ProtocolFormat serializationFormat = HttpResultSerializationOptions.ProtocolFormat.HttpApi;
HttpResultSerializationOptions.ProtocolVersion serializationVersion = HttpResultSerializationOptions.ProtocolVersion.V2;
var serializationOptions = new HttpResultSerializationOptions { Format = serializationFormat, Version = serializationVersion };
var response = httpResults.Serialize(serializationOptions);
return response;
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations.APIGateway;
namespace TestServerlessApp
{
public class CustomizeResponseExamples_OkResponseWithHeaderAsync_Generated
{
private readonly CustomizeResponseExamples customizeResponseExamples;
public CustomizeResponseExamples_OkResponseWithHeaderAsync_Generated()
{
SetExecutionEnvironment();
customizeResponseExamples = new CustomizeResponseExamples();
}
public async System.Threading.Tasks.Task<System.IO.Stream> OkResponseWithHeaderAsync(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var x = default(int);
if (__request__.PathParameters?.ContainsKey("x") == true)
{
try
{
x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
var errorStream = new System.IO.MemoryStream();
System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);
return errorStream;
}
var httpResults = await customizeResponseExamples.OkResponseWithHeaderAsync(x, __context__);
HttpResultSerializationOptions.ProtocolFormat serializationFormat = HttpResultSerializationOptions.ProtocolFormat.RestApi;
HttpResultSerializationOptions.ProtocolVersion serializationVersion = HttpResultSerializationOptions.ProtocolVersion.V1;
var serializationOptions = new HttpResultSerializationOptions { Format = serializationFormat, Version = serializationVersion };
var response = httpResults.Serialize(serializationOptions);
return response;
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations.APIGateway;
namespace TestServerlessApp
{
public class CustomizeResponseExamples_OkResponseWithHeader_Generated
{
private readonly CustomizeResponseExamples customizeResponseExamples;
public CustomizeResponseExamples_OkResponseWithHeader_Generated()
{
SetExecutionEnvironment();
customizeResponseExamples = new CustomizeResponseExamples();
}
public System.IO.Stream OkResponseWithHeader(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var x = default(int);
if (__request__.PathParameters?.ContainsKey("x") == true)
{
try
{
x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
var errorStream = new System.IO.MemoryStream();
System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);
return errorStream;
}
var httpResults = customizeResponseExamples.OkResponseWithHeader(x, __context__);
HttpResultSerializationOptions.ProtocolFormat serializationFormat = HttpResultSerializationOptions.ProtocolFormat.RestApi;
HttpResultSerializationOptions.ProtocolVersion serializationVersion = HttpResultSerializationOptions.ProtocolVersion.V1;
var serializationOptions = new HttpResultSerializationOptions { Format = serializationFormat, Version = serializationVersion };
var response = httpResults.Serialize(serializationOptions);
return response;
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class DynamicExample_DynamicInput_Generated
{
private readonly DynamicExample dynamicExample;
public DynamicExample_DynamicInput_Generated()
{
SetExecutionEnvironment();
dynamicExample = new DynamicExample();
}
public string DynamicInput(dynamic text, Amazon.Lambda.Core.ILambdaContext __context__)
{
return dynamicExample.DynamicInput(text, __context__);
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 41 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class DynamicExample_DynamicReturn_Generated
{
private readonly DynamicExample dynamicExample;
public DynamicExample_DynamicReturn_Generated()
{
SetExecutionEnvironment();
dynamicExample = new DynamicExample();
}
public dynamic DynamicReturn(string text, Amazon.Lambda.Core.ILambdaContext __context__)
{
return dynamicExample.DynamicReturn(text, __context__);
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 41 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp.Sub1
{
public class Functions_ToUpper_Generated
{
private readonly Functions functions;
public Functions_ToUpper_Generated()
{
SetExecutionEnvironment();
functions = new Functions();
}
public string ToUpper(string text)
{
return functions.ToUpper(text);
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 41 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class Greeter_SayHelloAsync_Generated
{
private readonly Greeter greeter;
public Greeter_SayHelloAsync_Generated()
{
SetExecutionEnvironment();
greeter = new Greeter();
}
public async System.Threading.Tasks.Task<Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse> SayHelloAsync(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var firstNames = default(System.Collections.Generic.IEnumerable<string>);
if (__request__.MultiValueHeaders?.Any(x => string.Equals(x.Key, "names", StringComparison.OrdinalIgnoreCase)) == true)
{
firstNames = __request__.MultiValueHeaders.First(x => string.Equals(x.Key, "names", StringComparison.OrdinalIgnoreCase)).Value
.Select(q =>
{
try
{
return (string)Convert.ChangeType(q, typeof(string));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {q} at 'names' failed to satisfy constraint: {e.Message}");
return default;
}
})
.ToList();
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
return errorResult;
}
await greeter.SayHelloAsync(firstNames);
return new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
StatusCode = 200
};
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 83 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class Greeter_SayHello_Generated
{
private readonly Greeter greeter;
public Greeter_SayHello_Generated()
{
SetExecutionEnvironment();
greeter = new Greeter();
}
public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse SayHello(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var firstNames = default(System.Collections.Generic.IEnumerable<string>);
if (__request__.MultiValueQueryStringParameters?.ContainsKey("names") == true)
{
firstNames = __request__.MultiValueQueryStringParameters["names"]
.Select(q =>
{
try
{
return (string)Convert.ChangeType(q, typeof(string));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {q} at 'names' failed to satisfy constraint: {e.Message}");
return default;
}
})
.ToList();
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
return errorResult;
}
greeter.SayHello(firstNames, __request__, __context__);
return new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
StatusCode = 200
};
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 83 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class IntrinsicExample_HasIntrinsic_Generated
{
private readonly IntrinsicExample intrinsicExample;
public IntrinsicExample_HasIntrinsic_Generated()
{
SetExecutionEnvironment();
intrinsicExample = new IntrinsicExample();
}
public void HasIntrinsic(string text, Amazon.Lambda.Core.ILambdaContext __context__)
{
intrinsicExample.HasIntrinsic(text, __context__);
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 41 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;
namespace TestServerlessApp
{
public class NullableReferenceTypeExample_NullableHeaderHttpApi_Generated
{
private readonly NullableReferenceTypeExample nullableReferenceTypeExample;
public NullableReferenceTypeExample_NullableHeaderHttpApi_Generated()
{
SetExecutionEnvironment();
nullableReferenceTypeExample = new NullableReferenceTypeExample();
}
public Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse NullableHeaderHttpApi(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();
var text = default(string?);
if (__request__.Headers?.Any(x => string.Equals(x.Key, "MyHeader", StringComparison.OrdinalIgnoreCase)) == true)
{
try
{
text = (string?)Convert.ChangeType(__request__.Headers.First(x => string.Equals(x.Key, "MyHeader", StringComparison.OrdinalIgnoreCase)).Value, typeof(string));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($"Value {__request__.Headers.First(x => string.Equals(x.Key, "MyHeader", StringComparison.OrdinalIgnoreCase)).Value} at 'MyHeader' failed to satisfy constraint: {e.Message}");
}
}
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
return errorResult;
}
nullableReferenceTypeExample.NullableHeaderHttpApi(text, __context__);
return new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
StatusCode = 200
};
}
private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}
envValue.Append("amazon-lambda-annotations_0.13.5.0");
Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
} | 77 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.