Show / Hide Table of Contents

Class ALambdaFunction

ALambdaFunction is the abstract base class for all AWS Lambda functions. This class takes care of initializing the function from environment variables, before invoking ProcessMessageStreamAsync(Stream).

Inheritance
System.Object
ALambdaFunction
ALambdaFunction<TRequest, TResponse>
Implements
ILambdaSharpLogger
Namespace: LambdaSharp
Assembly: LambdaSharp.dll
Syntax
public abstract class ALambdaFunction : ILambdaSharpLogger

Constructors

ALambdaFunction()

Initializes a new ALambdaFunction instance using the default implementation of ILambdaFunctionDependencyProvider.

Declaration
protected ALambdaFunction()

ALambdaFunction(ILambdaFunctionDependencyProvider)

Initializes a new ALambdaFunction instance using a custom implementation of ILambdaFunctionDependencyProvider.

Declaration
protected ALambdaFunction(ILambdaFunctionDependencyProvider provider)
Parameters
Type Name Description
ILambdaFunctionDependencyProvider provider

Custom implementation of ILambdaFunctionDependencyProvider.

Exceptions
Type Condition
System.ArgumentNullException

Thrown when provider is null.

Properties

CurrentContext

Retrieve the current Amazon.Lambda.Core.ILambdaContext for the request.

Declaration
protected ILambdaContext CurrentContext { get; }
Property Value
Type Description
Amazon.Lambda.Core.ILambdaContext

The Amazon.Lambda.Core.ILambdaContext instance.

Remarks

This property is only set during the invocation of ProcessMessageStreamAsync(Stream). Otherwise, it returns null.

DebugLoggingEnabled

The DebugLoggingEnabled property indicates if the requests received and responses emitted by this Lambda function should be shown in the CloudWatch logs. This can be useful to determine check for issues caused by inconsistencies in serialization or deserialization.

Declaration
protected virtual bool DebugLoggingEnabled { get; }
Property Value
Type Description
System.Boolean

Boolean indicating if requests and responses are logged

ErrorReportGenerator

Retrieve the ErrorReportGenerator instance used to generate error reports.

Declaration
protected ILambdaErrorReportGenerator ErrorReportGenerator { get; }
Property Value
Type Description
ILambdaErrorReportGenerator

The ErrorReportGenerator instance.

HttpClient

The HttpClient property holds a HttpClient instance that is initialized with X-Ray support.

Declaration
protected HttpClient HttpClient { get; set; }
Property Value
Type Description
System.Net.Http.HttpClient

The HttpClient instance.

Info

Retrieve the Lambda function initialization settings.

Declaration
protected ALambdaFunction.FunctionInfo Info { get; }
Property Value
Type Description
ALambdaFunction.FunctionInfo

The ALambdaFunction.FunctionInfo value.

Logger

Retrieve the ILambdaSharpLogger instance.

Declaration
protected ILambdaSharpLogger Logger { get; }
Property Value
Type Description
ILambdaSharpLogger

The ILambdaSharpLogger instance.

Provider

The ILambdaFunctionDependencyProvider instance used by the Lambda function to satisfy its required dependencies.

Declaration
protected ILambdaFunctionDependencyProvider Provider { get; }
Property Value
Type Description
ILambdaFunctionDependencyProvider

The ILambdaFunctionDependencyProvider instance.

UtcNow

Retrieves the current date-time in UTC timezone.

Declaration
protected DateTime UtcNow { get; }
Property Value
Type Description
System.DateTime

Current date-time in UTC timezone.

Methods

AddPendingTask(Task)

The AddPendingTask(Task) method adds the specified task to the list of pending tasks. The Lambda function waits until all pendings tasks have completed before responding to the active invocation.

Declaration
protected void AddPendingTask(Task task)
Parameters
Type Name Description
System.Threading.Tasks.Task task

A task to wait for before responding to the active invocation.

DecryptSecretAsync(String, Dictionary<String, String>, CancellationToken)

The DecryptSecretAsync(String, Dictionary<String, String>, CancellationToken) method decrypts a Base64-encoded string with an optional encryption context. The Lambda function requires permission to use the kms:Decrypt operation on the KMS key used to encrypt the original message.

Declaration
protected async Task<string> DecryptSecretAsync(string secret, Dictionary<string, string> encryptionContext = null, CancellationToken cancellationToken = default(CancellationToken))
Parameters
Type Name Description
System.String secret

Base64-encoded string of the encrypted value.

System.Collections.Generic.Dictionary<System.String, System.String> encryptionContext

An optional encryption context. Can be null.

System.Threading.CancellationToken cancellationToken

The token to monitor for cancellation requests.

Returns
Type Description
System.Threading.Tasks.Task<System.String>

The task object representing the asynchronous operation.

EncryptSecretAsync(String, String, Dictionary<String, String>, CancellationToken)

The EncryptSecretAsync(String, String, Dictionary<String, String>, CancellationToken) encrypts a sequence of bytes using the specified KMS key. The Lambda function requires permission to use the kms:Encrypt opeartion on the specified KMS key.

Declaration
protected async Task<string> EncryptSecretAsync(string text, string encryptionKeyId, Dictionary<string, string> encryptionContext = null, CancellationToken cancellationToken = default(CancellationToken))
Parameters
Type Name Description
System.String text

The plaintext string to encrypt.

System.String encryptionKeyId

The KMS key ID used encrypt the plaintext bytes.

System.Collections.Generic.Dictionary<System.String, System.String> encryptionContext

An optional encryption context. Can be null.

System.Threading.CancellationToken cancellationToken

The token to monitor for cancellation requests.

Returns
Type Description
System.Threading.Tasks.Task<System.String>

The task object representing the asynchronous operation.

ForceLambdaColdStart(String)

The ForceLambdaColdStart(String) method causes the Lambda runtime to re-initialize as if a cold start had occurred. This methos is useful when the global environment is corrupted and only a restart can fix it.

Declaration
protected void ForceLambdaColdStart(string reason)
Parameters
Type Name Description
System.String reason

FunctionHandlerAsync(Stream, ILambdaContext)

The FunctionHandlerAsync(Stream, ILambdaContext) method is the entry point for the Lambda function. It is responsible for initializing the Lambda function on first invocation, then invoking ProcessMessageStreamAsync(Stream) and handling any failures that occur.

Declaration
[LambdaSerializer(typeof(LambdaSystemTextJsonSerializer))]
public async Task<Stream> FunctionHandlerAsync(Stream stream, ILambdaContext context)
Parameters
Type Name Description
System.IO.Stream stream

The request stream.

Amazon.Lambda.Core.ILambdaContext context

The Amazon.Lambda.Core.ILambdaContext instance associated with this request. The instance can be retrieved using the CurrentContext property.

Returns
Type Description
System.Threading.Tasks.Task<System.IO.Stream>

The task object representing the asynchronous operation.

HandleFailedInitializationAsync(Stream)

The HandleFailedInitializationAsync(Stream) method is only invoked when an error occurs during the Lambda function initialization. This method can be overridden to provide custom behavior for how to handle such failures more gracefully.

Declaration
protected virtual async Task HandleFailedInitializationAsync(Stream stream)
Parameters
Type Name Description
System.IO.Stream stream

The stream with the request payload.

Returns
Type Description
System.Threading.Tasks.Task

The task object representing the asynchronous operation.

Remarks

Regardless of what this method does. Once completed, the Lambda function exits by rethrowing the original exception that occurred during initialization.

InitializeAsync(LambdaConfig)

The InitializeAsync(LambdaConfig) method is invoke on first request. It is responsible for initializing the Lambda function using the provided LambdaConfig instance.

Declaration
public abstract Task InitializeAsync(LambdaConfig config)
Parameters
Type Name Description
LambdaConfig config

The LambdaConfig instance to use.

Returns
Type Description
System.Threading.Tasks.Task

The task object representing the asynchronous operation.

InitializeEpilogueAsync()

The InitializeEpilogueAsync() method is invoked to complet the initialization of the Lambda function. This is the last of three methods that are invoked to initialize the Lambda function.

Declaration
protected virtual async Task InitializeEpilogueAsync()
Returns
Type Description
System.Threading.Tasks.Task

The task object representing the asynchronous operation.

InitializePrologueAsync(ILambdaConfigSource)

The InitializePrologueAsync(ILambdaConfigSource) method is invoked to prepare the Lambda function for initialization. This is the first of three methods that are invoked to initialize the Lambda function.

Declaration
protected virtual async Task InitializePrologueAsync(ILambdaConfigSource envSource)
Parameters
Type Name Description
ILambdaConfigSource envSource

The ILambdaConfigSource instance from which to read the configuration settings.

Returns
Type Description
System.Threading.Tasks.Task

The task object representing the asynchronous operation.

LogDebug(String, Object[])

Log a debugging message. This message will only appear in the log when debug logging is enabled and will not be forwarded to an error aggregator.

Declaration
protected void LogDebug(string format, params object[] arguments)
Parameters
Type Name Description
System.String format

The message format string. If not arguments are supplied, the message format string will be printed as a plain string.

System.Object[] arguments

Optional arguments for the message string.

LogError(Exception)

Log an exception as an error. This message will be reported if an error aggregator is configured for the LambdaSharp.Core module.

Declaration
protected void LogError(Exception exception)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

LogError(Exception, String, Object[])

Log an exception with a custom message as an error. This message will be reported if an error aggregator is configured for the LambdaSharp.Core module.

Declaration
protected void LogError(Exception exception, string format, params object[] arguments)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

System.String format

Optional message to use instead of Exception.Message. This parameter can be null.

System.Object[] arguments

Optional arguments for the format parameter.

LogErrorAsInfo(Exception)

Log an exception as an information message. This message will only appear in the log and not be forwarded to an error aggregator.

Declaration
protected void LogErrorAsInfo(Exception exception)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

Remarks

Only use this method when the exception has no operational impact. Otherwise, either use LogError(Exception) or LogErrorAsWarning(Exception).

LogErrorAsInfo(Exception, String, Object[])

Log an exception with a custom message as an information message. This message will only appear in the log and not be forwarded to an error aggregator.

Declaration
protected void LogErrorAsInfo(Exception exception, string format, params object[] arguments)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

System.String format

Optional message to use instead of Exception.Message. This parameter can be null.

System.Object[] arguments

Optional arguments for the format parameter.

Remarks

Only use this method when the exception has no operational impact. Otherwise, either use LogError(Exception) or LogErrorAsWarning(Exception).

LogErrorAsWarning(Exception)

Log an exception as a warning. This message will be reported if an error aggregator is configured for the LambdaSharp.Core module.

Declaration
protected void LogErrorAsWarning(Exception exception)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

Remarks

Only use this method when the exception has no operational impact. Otherwise, either use LogError(Exception).

LogErrorAsWarning(Exception, String, Object[])

Log an exception with a custom message as a warning. This message will be reported if an error aggregator is configured for the LambdaSharp.Core module.

Declaration
protected void LogErrorAsWarning(Exception exception, string format, params object[] arguments)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

System.String format

Optional message to use instead of Exception.Message. This parameter can be null.

System.Object[] arguments

Optional arguments for the format parameter.

Remarks

Only use this method when the exception has no operational impact. Otherwise, either use LogError(Exception).

LogEvent<T>(T, IEnumerable<String>)

Send a CloudWatch event with optional event details and resources it applies to. This event is forwarded to the configured EventBridge. The 'detail-type' property is set to the full type name of the detail value.

Declaration
protected void LogEvent<T>(T detail, IEnumerable<string> resources = null)
Parameters
Type Name Description
T detail

Data-structure to serialize as a JSON string. If value is already a

string
, it is sent as-is. There is no other schema imposed. The data-structure may contain fields and nested subobjects.

System.Collections.Generic.IEnumerable<System.String> resources

Optional AWS or custom resources, identified by unique identifier (e.g. ARN), which the event primarily concerns. Any number, including zero, may be present.

Type Parameters
Name Description
T

LogEvent<T>(String, T, IEnumerable<String>)

Send a CloudWatch event with optional event details and resources it applies to. This event is forwarded to the configured EventBridge. The 'detail-type' property is set to the full type name of the detail value.

Declaration
protected void LogEvent<T>(string source, T detail, IEnumerable<string> resources = null)
Parameters
Type Name Description
System.String source

Name of the event source.

T detail

Data-structure to serialize as a JSON string. If value is already a

string
, it is sent as-is. There is no other schema imposed. The data-structure may contain fields and nested subobjects.

System.Collections.Generic.IEnumerable<System.String> resources

Optional AWS or custom resources, identified by unique identifier (e.g. ARN), which the event primarily concerns. Any number, including zero, may be present.

Type Parameters
Name Description
T

LogEvent<T>(String, String, T, IEnumerable<String>)

Send a CloudWatch event with optional event details and resources it applies to. This event is forwarded to the configured EventBridge.

Declaration
protected void LogEvent<T>(string source, string detailType, T detail, IEnumerable<string> resources = null)
Parameters
Type Name Description
System.String source

Name of the event source.

System.String detailType

Free-form string used to decide what fields to expect in the event detail.

T detail

Data-structure to serialize as a JSON string using System.Text.Json.JsonSerializer. If value is already a

string
, it is sent as-is. There is no other schema imposed. The data-structure may contain fields and nested subobjects.

System.Collections.Generic.IEnumerable<System.String> resources

Optional AWS or custom resources, identified by unique identifier (e.g. ARN), which the event primarily concerns. Any number, including zero, may be present.

Type Parameters
Name Description
T

LogFatal(Exception, String, Object[])

Log an exception with a custom message as a fatal error. This message will be reported if an error aggregator is configured for the LambdaSharp.Core module.

Declaration
protected void LogFatal(Exception exception, string format, params object[] arguments)
Parameters
Type Name Description
System.Exception exception

The exception to log. The exception is logged with its message, stacktrace, and any nested exceptions.

System.String format

Optional message to use instead of Exception.Message. This parameter can be null.

System.Object[] arguments

Optional arguments for the format parameter.

LogInfo(String, Object[])

Log an informational message. This message will only appear in the log and not be forwarded to an error aggregator.

Declaration
protected void LogInfo(string format, params object[] arguments)
Parameters
Type Name Description
System.String format

The message format string. If not arguments are supplied, the message format string will be printed as a plain string.

System.Object[] arguments

Optional arguments for the message string.

LogMetric(IEnumerable<LambdaMetric>)

Log a CloudWatch metric. The metric is picked up by CloudWatch logs and automatically ingested as a CloudWatch metric.

Declaration
protected void LogMetric(IEnumerable<LambdaMetric> metrics)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<LambdaMetric> metrics

Enumeration of metrics, including their name, value, and unit.

LogMetric(IEnumerable<LambdaMetric>, IEnumerable<String>, Dictionary<String, String>)

Log a CloudWatch metric. The metric is picked up by CloudWatch logs and automatically ingested as a CloudWatch metric.

Declaration
protected virtual void LogMetric(IEnumerable<LambdaMetric> metrics, IEnumerable<string> dimensionNames, Dictionary<string, string> dimensionValues)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<LambdaMetric> metrics

Enumeration of metrics, including their name, value, and unit.

System.Collections.Generic.IEnumerable<System.String> dimensionNames

Metric dimensions as comma-separated list (e.g. [ "A", "A,B" ]).

System.Collections.Generic.Dictionary<System.String, System.String> dimensionValues

Dictionary of dimesion name-value pairs.

LogMetric(String, Double, LambdaMetricUnit)

Log a CloudWatch metric. The metric is picked up by CloudWatch logs and automatically ingested as a CloudWatch metric.

Declaration
protected void LogMetric(string name, double value, LambdaMetricUnit unit)
Parameters
Type Name Description
System.String name

Metric name.

System.Double value

Metric value.

LambdaMetricUnit unit

Metric unit.

LogMetric(String, Double, LambdaMetricUnit, IEnumerable<String>, Dictionary<String, String>)

Log a CloudWatch metric. The metric is picked up by CloudWatch logs and automatically ingested as a CloudWatch metric.

Declaration
protected void LogMetric(string name, double value, LambdaMetricUnit unit, IEnumerable<string> dimensionNames, Dictionary<string, string> dimensionValues)
Parameters
Type Name Description
System.String name

Metric name.

System.Double value

Metric value.

LambdaMetricUnit unit

Metric unit.

System.Collections.Generic.IEnumerable<System.String> dimensionNames

Metric dimensions as comma-separated list (e.g. [ "A", "A,B" ]).

System.Collections.Generic.Dictionary<System.String, System.String> dimensionValues

Dictionary of dimesion name-value pairs.

LogWarn(String, Object[])

Log a warning message. This message will be reported if an error aggregator is configured for the LambdaSharp.Core module.

Declaration
protected void LogWarn(string format, params object[] arguments)
Parameters
Type Name Description
System.String format

The message format string. If not arguments are supplied, the message format string will be printed as a plain string.

System.Object[] arguments

Optional arguments for the message string.

ProcessMessageStreamAsync(Stream)

The ProcessMessageStreamAsync(Stream) method is invoked for every received request. It is responsible for deserializing the stream and processing the received message. The return stream is sent as response.

Declaration
public abstract Task<Stream> ProcessMessageStreamAsync(Stream stream)
Parameters
Type Name Description
System.IO.Stream stream

The stream with the request payload.

Returns
Type Description
System.Threading.Tasks.Task<System.IO.Stream>

The task object representing the asynchronous operation.

RecordErrorReport(LambdaErrorReport)

The RecordErrorReport(LambdaErrorReport) method is invoked record errors for later reporting.

Declaration
protected virtual void RecordErrorReport(LambdaErrorReport report)
Parameters
Type Name Description
LambdaErrorReport report

The LambdaErrorReport to record.

RecordException(Exception)

The RecordException(Exception) method is only invoked when Lambda function ErrorReportGenerator instance has not yet been initialized of if an exception occurred while invoking RecordErrorReport(LambdaErrorReport).

Declaration
protected virtual void RecordException(Exception exception)
Parameters
Type Name Description
System.Exception exception

Exception to record.

RecordFailedMessageAsync(LambdaLogLevel, ALambdaFunction.FailedMessageOrigin, String, Exception)

The RecordFailedMessageAsync(LambdaLogLevel, ALambdaFunction.FailedMessageOrigin, String, Exception) method is invoked when a permanent failure is detected during processing and the message should be sent to the dead-letter queue if possible. If no dead-letter queue is configured, the original exception is rethrown instead.

Declaration
protected virtual async Task RecordFailedMessageAsync(LambdaLogLevel level, ALambdaFunction.FailedMessageOrigin origin, string message, Exception exception)
Parameters
Type Name Description
LambdaLogLevel level

The severity level of the failure. This should either be ERROR or FATAL.

ALambdaFunction.FailedMessageOrigin origin

The origin of the failed message.

System.String message

The failed message.

System.Exception exception

The exception that was triggered by the failed message.

Returns
Type Description
System.Threading.Tasks.Task

The task object representing the asynchronous operation.

RunTask(Action, CancellationToken)

The RunTask(Action, CancellationToken) method queues the specified work for background execution. The Lambda function waits until all queued background work has completed before completing the active invocation.

Declaration
protected void RunTask(Action action, CancellationToken cancellationToken = default(CancellationToken))
Parameters
Type Name Description
System.Action action

The work to execute asynchronously.

System.Threading.CancellationToken cancellationToken

An optional cancellation token that can be used to cancel the work.

RunTask(Func<Task>, CancellationToken)

The RunTask(Func<Task>, CancellationToken) method queues the specified work for background execution. The Lambda function waits until all queued background work has completed before completing the active invocation.

Declaration
protected void RunTask(Func<Task> function, CancellationToken cancellationToken = default(CancellationToken))
Parameters
Type Name Description
System.Func<System.Threading.Tasks.Task> function

The work to execute asynchronously.

System.Threading.CancellationToken cancellationToken

An optional cancellation token that can be used to cancel the work.

TerminateLambdaInstance(String)

The TerminateLambdaInstance(String) method forces the Lambda instance to terminate and perform a cold start on next invocation. This method should only be used when the processing environment has become corrupted beyond repair.

Declaration
protected void TerminateLambdaInstance(string reason = null)
Parameters
Type Name Description
System.String reason

Optional message shown as reason for terminating the Lambda instance.

Explicit Interface Implementations

ILambdaSharpLogger.DebugLoggingEnabled

Declaration
bool ILambdaSharpLogger.DebugLoggingEnabled { get; }
Returns
Type Description
System.Boolean

ILambdaSharpLogger.Info

Declaration
ILambdaSharpInfo ILambdaSharpLogger.Info { get; }
Returns
Type Description
ILambdaSharpInfo

ILambdaSharpLogger.Log(LambdaLogLevel, Exception, String, Object[])

Declaration
void ILambdaSharpLogger.Log(LambdaLogLevel level, Exception exception, string format, params object[] arguments)
Parameters
Type Name Description
LambdaLogLevel level
System.Exception exception
System.String format
System.Object[] arguments

ILambdaSharpLogger.LogRecord(ALambdaLogRecord)

Declaration
void ILambdaSharpLogger.LogRecord(ALambdaLogRecord record)
Parameters
Type Name Description
ALambdaLogRecord record

Implements

ILambdaSharpLogger
In This Article
Back to top Generated by DocFX