Exemplo n.º 1
0
 /// <summary>
 /// The <see cref="Serialize{T}(ILambdaSerializer, T)"/> extension method serializes
 /// n instance to a JSON <c>string</c>.
 /// </summary>
 /// <param name="serializer">The Lambda serializer.</param>
 /// <param name="value">The instance to serialize.</param>
 /// <returns>Serialized JSON <c>string</c>.</returns>
 public static string Serialize <T>(this ILambdaSerializer serializer, T value)
 {
     using (var stream = new MemoryStream()) {
         serializer.Serialize <T>(value, stream);
         return(Encoding.UTF8.GetString(stream.ToArray()));
     }
 }
Exemplo n.º 2
0
        //--- Constructors ---

        /// <summary>
        /// Create new instance of <see cref="LambdaFunctionDependencyProvider"/>, which provides the implementation for the required dependencies for <see cref="ALambdaFunction"/>.
        /// </summary>
        /// <param name="utcNowCallback">A function that return the current <c>DateTime</c> in UTC timezone. Defaults to <see cref="DateTime.UtcNow"/> when <c>null</c>.</param>
        /// <param name="logCallback">An action that logs a string message. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="configSource">A <see cref="ILambdaConfigSource"/> instance from which the Lambda function configuration is read. Defaults to <see cref="LambdaSystemEnvironmentSource"/> instance when <c>null</c>.</param>
        /// <param name="jsonSerializer">A <see cref="ILambdaSerializer"/> instance for serializing and deserializing JSON data. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="kmsClient">A <see cref="IAmazonKeyManagementService"/> client instance. Defaults to <see cref="AmazonKeyManagementServiceClient"/> when <c>null</c>.</param>
        /// <param name="sqsClient">A <see cref="IAmazonSQS"/> client instance. Defaults to <see cref="AmazonSQSClient"/> when <c>null</c>.</param>
        /// <param name="eventsClient">A <see cref="IAmazonCloudWatchEvents"/> client instance. Defaults to <see cref="AmazonCloudWatchEventsClient"/> when <c>null</c>.</param>
        /// <param name="debugLoggingEnabled">A boolean indicating if debug logging is enabled.</param>
        public LambdaFunctionDependencyProvider(
            Func <DateTime> utcNowCallback        = null,
            Action <string> logCallback           = null,
            ILambdaConfigSource configSource      = null,
            ILambdaSerializer jsonSerializer      = null,
            IAmazonKeyManagementService kmsClient = null,
            IAmazonSQS sqsClient = null,
            IAmazonCloudWatchEvents eventsClient = null,
            bool?debugLoggingEnabled             = null
            )
        {
            _nowCallback   = utcNowCallback ?? (() => DateTime.UtcNow);
            _logCallback   = logCallback ?? LambdaLogger.Log;
            ConfigSource   = configSource ?? new LambdaSystemEnvironmentSource();
            JsonSerializer = jsonSerializer ?? new LambdaJsonSerializer();
            KmsClient      = kmsClient ?? new AmazonKeyManagementServiceClient();
            SqsClient      = sqsClient ?? new AmazonSQSClient();
            EventsClient   = eventsClient ?? new AmazonCloudWatchEventsClient();

            // determine if debug logging is enabled
            if (debugLoggingEnabled.HasValue)
            {
                _debugLoggingEnabled = debugLoggingEnabled.Value;
            }
            else
            {
                // read environment variable to determine if request/response messages should be serialized to the log for debugging purposes
                var value = System.Environment.GetEnvironmentVariable("DEBUG_LOGGING_ENABLED") ?? "false";
                _debugLoggingEnabled = value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }
        }
Exemplo n.º 3
0
        //--- Constructors ---

        /// <summary>
        /// Creates new instance of <see cref="LambdaQueueFunctionDependencyProvider"/>, which provides the implementation for the required dependencies for <see cref="ALambdaQueueFunction{TMessage}"/>.
        /// </summary>
        /// <param name="utcNowCallback">A function that return the current <c>DateTime</c> in UTC timezone. Defaults to <see cref="DateTime.UtcNow"/> when <c>null</c>.</param>
        /// <param name="logCallback">An action that logs a string message. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="configSource">A <see cref="ILambdaConfigSource"/> instance from which the Lambda function configuration is read. Defaults to <see cref="LambdaSystemEnvironmentSource"/> instance when <c>null</c>.</param>
        /// <param name="jsonSerializer">A <see cref="ILambdaSerializer"/> instance for serializing and deserializing JSON data. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="kmsClient">A <see cref="IAmazonKeyManagementService"/> client instance. Defaults to <see cref="AmazonKeyManagementServiceClient"/> when <c>null</c>.</param>
        /// <param name="sqsClient">A <see cref="IAmazonSQS"/> client instance. Defaults to <see cref="AmazonSQSClient"/> when <c>null</c>.</param>
        public LambdaQueueFunctionDependencyProvider(
            Func <DateTime> utcNowCallback        = null,
            Action <string> logCallback           = null,
            ILambdaConfigSource configSource      = null,
            ILambdaSerializer jsonSerializer      = null,
            IAmazonKeyManagementService kmsClient = null,
            IAmazonSQS sqsClient = null
            ) : base(utcNowCallback, logCallback, configSource, jsonSerializer, kmsClient, sqsClient)
        {
        }
Exemplo n.º 4
0
        public static T GetJsonObject <T>(this ILambdaSerializer serializer, string snap)
        {
            T t;

            using (Stream stream = new MemoryStream(Encoding.Default.GetBytes(snap)))
            {
                t = serializer.Deserialize <T>(stream);
            }
            return(t);
        }
Exemplo n.º 5
0
 /// <summary>
 /// The <see cref="Deserialize(ILambdaSerializer, string, Type)"/> method deserializes the JSON object from a <c>string</c>.
 /// </summary>
 /// <param name="serializer">The Lambda serializer.</param>
 /// <param name="json">The <c>string</c> to deserialize.</param>
 /// <param name="type">The type to instantiate.</param>
 /// <returns>Deserialized instance.</returns>
 public static object Deserialize(this ILambdaSerializer serializer, string json, Type type)
 {
     if (serializer is LambdaJsonSerializer lambdaJsonSerializer)
     {
         return(lambdaJsonSerializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)), type));
     }
     else
     {
         return(JsonConvert.DeserializeObject(json, type));
     }
 }
Exemplo n.º 6
0
        //--- Constructors ---

        /// <summary>
        /// Create new instance of <see cref="LambdaFunctionDependencyProvider"/>, which provides the implementation for the required dependencies for <see cref="ALambdaFunction"/>.
        /// </summary>
        /// <param name="utcNowCallback">A function that return the current <c>DateTime</c> in UTC timezone. Defaults to <see cref="DateTime.UtcNow"/> when <c>null</c>.</param>
        /// <param name="logCallback">An action that logs a string message. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="configSource">A <see cref="ILambdaConfigSource"/> instance from which the Lambda function configuration is read. Defaults to <see cref="LambdaSystemEnvironmentSource"/> instance when <c>null</c>.</param>
        /// <param name="jsonSerializer">A <see cref="ILambdaSerializer"/> instance for serializing and deserializing JSON data. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="kmsClient">A <see cref="IAmazonKeyManagementService"/> client instance. Defaults to <see cref="AmazonKeyManagementServiceClient"/> when <c>null</c>.</param>
        /// <param name="sqsClient">A <see cref="IAmazonSQS"/> client instance. Defaults to <see cref="AmazonSQSClient"/> when <c>null</c>.</param>
        public LambdaFunctionDependencyProvider(
            Func <DateTime> utcNowCallback        = null,
            Action <string> logCallback           = null,
            ILambdaConfigSource configSource      = null,
            ILambdaSerializer jsonSerializer      = null,
            IAmazonKeyManagementService kmsClient = null,
            IAmazonSQS sqsClient = null
            )
        {
            _nowCallback   = utcNowCallback ?? (() => DateTime.UtcNow);
            _logCallback   = logCallback ?? LambdaLogger.Log;
            ConfigSource   = configSource ?? new LambdaSystemEnvironmentSource();
            JsonSerializer = jsonSerializer ?? new JsonSerializer();
            KmsClient      = kmsClient ?? new AmazonKeyManagementServiceClient();
            SqsClient      = sqsClient ?? new AmazonSQSClient();
        }
Exemplo n.º 7
0
        public static async Task <string> GetJsonString(this ILambdaSerializer serializer, object jsonObject)
        {
            string jsonString = null;

            using (Stream stream = new MemoryStream())
            {
                serializer.Serialize(jsonObject, stream);
                stream.Seek(0, SeekOrigin.Begin);

                using (var reader = new StreamReader(stream))
                {
                    jsonString = await reader.ReadToEndAsync();
                }
            }
            return(jsonString);
        }
Exemplo n.º 8
0
        public void Initialize()
        {
            Handler     = new THandler();
            _serializer = Handler.Serializer;

            if (_serializer != null)
            {
                this.LogDebug($"Handler provided a {_serializer.GetType().Name} serializer");
                return;
            }

            if (typeof(TInput) != typeof(Stream) || typeof(TOutput) != typeof(Stream))
            {
                throw new LambdaInitializationException(
                          $"'Serializer' property not set on handler '{Handler.GetType().FullName}'. " +
                          "To use types other than System.IO.Stream as input/output parameters, " +
                          "the 'Serializer' property must be set.");
            }

            this.LogDebug("Handler didn't provide a serializer, using StreamSerializer");
            _serializer = new StreamSerializer();
        }
Exemplo n.º 9
0
 public AzureBusSender(string connectionString, string topicName)
 {
     _client     = new MessageSender(connectionString, topicName);
     _serializer = new Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer();
     _buffer     = new byte[512];
 }
Exemplo n.º 10
0
 //--- Constructors ---
 public WriteJsonLogic(ILambdaLogLevelLogger logger, IAmazonS3 s3Client)
 {
     _logger         = logger;
     _s3Client       = s3Client;
     _jsonSerializer = new JsonSerializer();
 }
Exemplo n.º 11
0
        private static Func <APIGatewayProxyRequest, InvocationTargetState, object> CreateParameterResolver(ILambdaSerializer serializer, MethodInfo method, ParameterInfo parameter)
        {
            // check if [FromUri] or [FromBody] attributes are present
            var hasFromUriAttribute  = parameter.GetCustomAttribute <FromUriAttribute>() != null;
            var hasFromBodyAttribute = parameter.GetCustomAttribute <FromBodyAttribute>() != null;

            if (hasFromUriAttribute && hasFromBodyAttribute)
            {
                throw new ApiGatewayInvocationTargetParameterException(method, parameter, "cannot have both [FromUri] and [FromBody] attributes");
            }

            // check if parameter is a proxy request
            var isProxyRequest = parameter.ParameterType == typeof(APIGatewayProxyRequest);

            if (isProxyRequest)
            {
                // parameter is the proxy request itself
                return((request, state) => request);
            }

            // check if parameter needs to deserialized from URI or BODY
            var isSimpleType = parameter.ParameterType.IsValueType || (parameter.ParameterType == typeof(string));

            if ((isSimpleType && !hasFromBodyAttribute) || hasFromUriAttribute)
            {
                // check if parameter is read from URI string directly or if its members are read from the URI string
                if (isSimpleType)
                {
                    // create function for getting default parameter value
                    Func <object> getDefaultValue;
                    if (parameter.IsOptional)
                    {
                        getDefaultValue = () => parameter.DefaultValue;
                    }
                    else if ((Nullable.GetUnderlyingType(parameter.ParameterType) == null) && (parameter.ParameterType.IsValueType || parameter.ParameterType == typeof(string)))
                    {
                        getDefaultValue = () => throw new ApiGatewayInvocationTargetParameterException(method, parameter, "missing value");
                    }
                    else
                    {
                        getDefaultValue = () => null;
                    }

                    // create function to resolve parameter
                    return((request, state) => {
                        string value = null;

                        // attempt to resolve the parameter from stage variables, path parameters, and query string parameters
                        var success = (request.PathParameters?.TryGetValue(parameter.Name, out value) ?? false) ||
                                      (request.QueryStringParameters?.TryGetValue(parameter.Name, out value) ?? false);

                        // if resolved, return the converted value; otherwise the default value
                        if (success)
                        {
                            try {
                                return Convert.ChangeType(value, parameter.ParameterType);
                            } catch (FormatException) {
                                throw new ApiGatewayInvocationTargetParameterException(method, parameter, "invalid parameter format");
                            }
                        }
                        return getDefaultValue();
                    });
                }
                else
                {
                    var queryParameterType = parameter.ParameterType;

                    // parameter represents the query-string key-value pairs
                    return((request, state) => {
                        try {
                            // construct a unified JSON representation of the path and query-string parameters
                            if (state.PathQueryParametersJson == null)
                            {
                                var pathParameters = request.PathParameters ?? Enumerable.Empty <KeyValuePair <string, string> >();
                                var queryStringParameters = request.QueryStringParameters ?? Enumerable.Empty <KeyValuePair <string, string> >();
                                state.PathQueryParametersJson = serializer.Serialize(
                                    pathParameters.Union(queryStringParameters)
                                    .GroupBy(kv => kv.Key)
                                    .Select(grouping => grouping.First())
                                    .ToDictionary(kv => kv.Key, kv => kv.Value)
                                    );
                            }
                            return serializer.Deserialize(state.PathQueryParametersJson, parameter.ParameterType);
                        } catch {
                            throw new ApiGatewayInvocationTargetParameterException(method, parameter, "invalid path/query-string parameters format");
                        }
                    });
                }
            }
            else
            {
                // parameter represents the body of the request
                return((request, state) => {
                    try {
                        return serializer.Deserialize(request.Body, parameter.ParameterType);
                    } catch {
                        throw new ApiGatewayInvocationTargetParameterException(method, parameter, "invalid JSON document in request body");
                    }
                });
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Create a builder for creating the LambdaBootstrap.
 /// </summary>
 /// <param name="handler">The handler that will be called for each Lambda invocation</param>
 /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param>
 /// <returns></returns>
 public static LambdaBootstrapBuilder Create <TInput>(Func <TInput, Task> handler, ILambdaSerializer serializer)
 {
     return(new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper <TInput>(handler, serializer)));
 }
Exemplo n.º 13
0
 /// <summary>
 /// Create a builder for creating the LambdaBootstrap.
 /// </summary>
 /// <param name="handler">The handler that will be called for each Lambda invocation</param>
 /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param>
 /// <returns></returns>
 public static LambdaBootstrapBuilder Create <TOutput>(Func <Stream, ILambdaContext, TOutput> handler, ILambdaSerializer serializer)
 {
     return(new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper <TOutput>(handler, serializer)));
 }
Exemplo n.º 14
0
        /// <summary>
        /// Get a HandlerWrapper that will call the given method on function invocation.
        /// Note that you may have to cast your handler to its specific type to help the compiler.
        /// Example handler signature: PocoOut Handler(PocoIn, ILambdaContext)
        /// </summary>
        /// <param name="handler">Func called for each invocation of the Lambda function.</param>
        /// <param name="serializer">ILambdaSerializer to use when calling the handler</param>
        /// <returns>A HandlerWrapper</returns>
        public static HandlerWrapper GetHandlerWrapper <TInput, TOutput>(Func <TInput, ILambdaContext, TOutput> handler, ILambdaSerializer serializer)
        {
            var handlerWrapper = new HandlerWrapper();

            handlerWrapper.Handler = (invocation) =>
            {
                TInput  input  = serializer.Deserialize <TInput>(invocation.InputStream);
                TOutput output = handler(input, invocation.LambdaContext);
                handlerWrapper.OutputStream.SetLength(0);
                serializer.Serialize(output, handlerWrapper.OutputStream);
                handlerWrapper.OutputStream.Position = 0;
                return(Task.FromResult(new InvocationResponse(handlerWrapper.OutputStream, false)));
            };
            return(handlerWrapper);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Get a HandlerWrapper that will call the given method on function invocation.
 /// Note that you may have to cast your handler to its specific type to help the compiler.
 /// Example handler signature: Task Handler(PocoIn)
 /// </summary>
 /// <param name="handler">Func called for each invocation of the Lambda function.</param>
 /// <param name="serializer">ILambdaSerializer to use when calling the handler</param>
 /// <returns>A HandlerWrapper</returns>
 public static HandlerWrapper GetHandlerWrapper <TInput>(Func <TInput, Task> handler, ILambdaSerializer serializer)
 {
     return(new HandlerWrapper(async(invocation) =>
     {
         TInput input = serializer.Deserialize <TInput>(invocation.InputStream);
         await handler(input);
         return EmptyInvocationResponse;
     }));
 }
Exemplo n.º 16
0
 /// <summary>
 /// The <see cref="Deserialize{T}(ILambdaSerializer, string)"/> method deserializes the JSON object from a <c>string</c>.
 /// </summary>
 /// <param name="serializer">The Lambda serializer.</param>
 /// <param name="json">The <c>string</c> to deserialize.</param>
 /// <typeparam name="T">The deserialization target type.</typeparam>
 /// <returns>Deserialized instance.</returns>
 public static T Deserialize <T>(this ILambdaSerializer serializer, string json) => serializer.Deserialize <T>(new MemoryStream(Encoding.UTF8.GetBytes(json)));
Exemplo n.º 17
0
        /// <summary>
        /// Get a HandlerWrapper that will call the given method on function invocation.
        /// Note that you may have to cast your handler to its specific type to help the compiler.
        /// Example handler signature: Task&ltPocoOut&gt Handler(Stream, ILambdaContext)
        /// </summary>
        /// <param name="handler">Func called for each invocation of the Lambda function.</param>
        /// <param name="serializer">ILambdaSerializer to use when calling the handler</param>
        /// <returns>A HandlerWrapper</returns>
        public static HandlerWrapper GetHandlerWrapper <TOutput>(Func <Stream, ILambdaContext, Task <TOutput> > handler, ILambdaSerializer serializer)
        {
            var handlerWrapper = new HandlerWrapper();

            handlerWrapper.Handler = async(invocation) =>
            {
                TOutput output = await handler(invocation.InputStream, invocation.LambdaContext);

                handlerWrapper.OutputStream.SetLength(0);
                serializer.Serialize(output, handlerWrapper.OutputStream);
                handlerWrapper.OutputStream.Position = 0;
                return(new InvocationResponse(handlerWrapper.OutputStream, false));
            };
            return(handlerWrapper);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Get a HandlerWrapper that will call the given method on function invocation.
 /// Note that you may have to cast your handler to its specific type to help the compiler.
 /// Example handler signature: void Handler(PocoIn)
 /// </summary>
 /// <param name="handler">Action called for each invocation of the Lambda function.</param>
 /// <param name="serializer">ILambdaSerializer to use when calling the handler</param>
 /// <returns>A HandlerWrapper</returns>
 public static HandlerWrapper GetHandlerWrapper <TInput>(Action <TInput> handler, ILambdaSerializer serializer)
 {
     return(new HandlerWrapper((invocation) =>
     {
         TInput input = serializer.Deserialize <TInput>(invocation.InputStream);
         handler(input);
         return Task.FromResult(EmptyInvocationResponse);
     }));
 }
Exemplo n.º 19
0
 /// <summary>
 /// Get a HandlerWrapper that will call the given method on function invocation.
 /// Note that you may have to cast your handler to its specific type to help the compiler.
 /// Example handler signature: Task&ltStream&gt Handler(PocoIn, ILambdaContext)
 /// </summary>
 /// <param name="handler">Func called for each invocation of the Lambda function.</param>
 /// <param name="serializer">ILambdaSerializer to use when calling the handler</param>
 /// <returns>A HandlerWrapper</returns>
 public static HandlerWrapper GetHandlerWrapper <TInput>(Func <TInput, ILambdaContext, Task <Stream> > handler, ILambdaSerializer serializer)
 {
     return(new HandlerWrapper(async(invocation) =>
     {
         TInput input = serializer.Deserialize <TInput>(invocation.InputStream);
         return new InvocationResponse(await handler(input, invocation.LambdaContext));
     }));
 }
Exemplo n.º 20
0
 /// <summary>
 /// Create a builder for creating the LambdaBootstrap.
 /// </summary>
 /// <param name="handler">The handler that will be called for each Lambda invocation</param>
 /// <param name="serializer">The Lambda serializer that will be used to convert between Lambda's JSON documents and .NET objects.</param>
 /// <returns></returns>
 public static LambdaBootstrapBuilder Create <TInput>(Action <TInput, ILambdaContext> handler, ILambdaSerializer serializer)
 {
     return(new LambdaBootstrapBuilder(HandlerWrapper.GetHandlerWrapper <TInput>(handler, serializer)));
 }
Exemplo n.º 21
0
 //--- Constructors ---
 public WriteJsonLogic(ILambdaSharpLogger logger, IAmazonS3 s3Client, ILambdaSerializer jsonSerializer)
 {
     _logger         = logger ?? throw new ArgumentNullException(nameof(logger));
     _s3Client       = s3Client ?? throw new ArgumentNullException(nameof(s3Client));
     _jsonSerializer = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer));
 }
Exemplo n.º 22
0
 /// <summary>
 /// Get a HandlerWrapper that will call the given method on function invocation.
 /// Note that you may have to cast your handler to its specific type to help the compiler.
 /// Example handler signature: Stream Handler(PocoIn, ILambdaContext)
 /// </summary>
 /// <param name="handler">Func called for each invocation of the Lambda function.</param>
 /// <param name="serializer">ILambdaSerializer to use when calling the handler</param>
 /// <returns>A HandlerWrapper</returns>
 public static HandlerWrapper GetHandlerWrapper <TInput>(Func <TInput, ILambdaContext, Stream> handler, ILambdaSerializer serializer)
 {
     return(new HandlerWrapper((invocation) =>
     {
         TInput input = serializer.Deserialize <TInput>(invocation.InputStream);
         return Task.FromResult(new InvocationResponse(handler(input, invocation.LambdaContext)));
     }));
 }