Skip to content

Commit

Permalink
Merge pull request #602 from hjgraca/aot-metrics-support
Browse files Browse the repository at this point in the history
chore: Metrics - Add support for AOT
  • Loading branch information
hjgraca authored Jul 3, 2024
2 parents cb11aff + d666ab2 commit 09f3e42
Show file tree
Hide file tree
Showing 23 changed files with 579 additions and 785 deletions.
1 change: 1 addition & 0 deletions docs/core/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ These metrics can be visualized through [Amazon CloudWatch Console](https://aws.
* Validating your metrics against common metric definitions mistakes (for example, metric unit, values, max dimensions, max metrics)
* Metrics are created asynchronously by the CloudWatch service. You do not need any custom stacks, and there is no impact to Lambda function latency
* Context manager to create a one off metric with a different dimension
* Ahead-of-Time compilation to native code support [AOT](https://docs.aws.amazon.com/lambda/latest/dg/dotnet-native-aot.html) from version 1.7.0

<br />

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/*
* 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
Expand All @@ -15,6 +15,7 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
Expand All @@ -32,19 +33,19 @@ public class UniversalWrapperAspect
/// <summary>
/// The delegate cache
/// </summary>
private static readonly Dictionary<MethodBase, Handler> _delegateCache = new();
private static readonly Dictionary<MethodBase, Handler> DelegateCache = new();

/// <summary>
/// The asynchronous generic handler
/// </summary>
private static readonly MethodInfo _asyncGenericHandler =
private static readonly MethodInfo AsyncGenericHandler =
typeof(UniversalWrapperAttribute).GetMethod(nameof(UniversalWrapperAttribute.WrapAsync),
BindingFlags.NonPublic | BindingFlags.Instance);

/// <summary>
/// The synchronize generic handler
/// </summary>
private static readonly MethodInfo _syncGenericHandler =
private static readonly MethodInfo SyncGenericHandler =
typeof(UniversalWrapperAttribute).GetMethod(nameof(UniversalWrapperAttribute.WrapSync),
BindingFlags.NonPublic | BindingFlags.Instance);

Expand Down Expand Up @@ -94,6 +95,7 @@ public object Handle(
/// <param name="returnType">Type of the return.</param>
/// <param name="wrappers">The wrappers.</param>
/// <returns>Handler.</returns>
[UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
private static Handler CreateMethodHandler(Type returnType, IEnumerable<UniversalWrapperAttribute> wrappers)
{
var targetParam = Expression.Parameter(typeof(Func<object[], object>), "orig");
Expand All @@ -107,13 +109,13 @@ private static Handler CreateMethodHandler(Type returnType, IEnumerable<Universa
? returnType.GenericTypeArguments[0]
: Type.GetType("System.Threading.Tasks.VoidTaskResult");
returnType = typeof(Task<>).MakeGenericType(taskType);
wrapperMethod = _asyncGenericHandler.MakeGenericMethod(taskType);
wrapperMethod = AsyncGenericHandler.MakeGenericMethod(taskType);
}
else
{
if (returnType == typeof(void))
returnType = typeof(object);
wrapperMethod = _syncGenericHandler.MakeGenericMethod(returnType);
wrapperMethod = SyncGenericHandler.MakeGenericMethod(returnType);
}

var converArgs = Expression.Parameter(typeof(object[]), "args");
Expand All @@ -128,9 +130,9 @@ private static Handler CreateMethodHandler(Type returnType, IEnumerable<Universa
argsParam);
}

var orig_args = Expression.Parameter(typeof(object[]), "orig_args");
var handler = Expression.Lambda<Handler>(Expression.Convert(Expression.Invoke(next, orig_args), typeof(object)),
targetParam, orig_args, eventArgsParam);
var origArgs = Expression.Parameter(typeof(object[]), "orig_args");
var handler = Expression.Lambda<Handler>(Expression.Convert(Expression.Invoke(next, origArgs), typeof(object)),
targetParam, origArgs, eventArgsParam);

var handlerCompiled = handler.Compile();

Expand All @@ -147,14 +149,14 @@ private static Handler CreateMethodHandler(Type returnType, IEnumerable<Universa
private static Handler GetMethodHandler(MethodBase method, Type returnType,
IEnumerable<UniversalWrapperAttribute> wrappers)
{
if (!_delegateCache.TryGetValue(method, out var handler))
lock (method)
{
if (!_delegateCache.TryGetValue(method, out handler))
_delegateCache[method] = handler = CreateMethodHandler(returnType, wrappers);
}

return handler;
lock (method)
{
if (!DelegateCache.TryGetValue(method, out var handler))
if (!DelegateCache.TryGetValue(method, out handler))
DelegateCache[method] = handler = CreateMethodHandler(returnType, wrappers);

return handler;
}
}

/// <summary>
Expand Down
13 changes: 13 additions & 0 deletions libraries/src/AWS.Lambda.Powertools.Common/Core/ISystemWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
* permissions and limitations under the License.
*/

using System.IO;

namespace AWS.Lambda.Powertools.Common;

/// <summary>
Expand Down Expand Up @@ -57,4 +59,15 @@ public interface ISystemWrapper
/// </summary>
/// <param name="type"></param>
void SetExecutionEnvironment<T>(T type);

/// <summary>
/// Sets console output
/// Useful for testing and checking the console output
/// <code>
/// var consoleOut = new StringWriter();
/// SystemWrapper.Instance.SetOut(consoleOut);
/// </code>
/// </summary>
/// <param name="writeTo">The TextWriter instance where to write to</param>
void SetOut(TextWriter writeTo);
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ public void SetExecutionEnvironment<T>(T type)
SetEnvironmentVariable(envName, envValue.ToString());
}

/// <inheritdoc />
public void SetOut(TextWriter writeTo)
{
Console.SetOut(writeTo);
}

/// <summary>
/// Parsing the name to conform with the required naming convention for the UserAgent header (PTFeature/Name/Version)
/// Fallback to Assembly Name on exception
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,4 @@
<ProjectReference Include="..\AWS.Lambda.Powertools.Common\AWS.Lambda.Powertools.Common.csproj" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<Folder Include="Serializer\" />
</ItemGroup>

</Project>
147 changes: 147 additions & 0 deletions libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspect.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* 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.Linq;
using System.Reflection;
using AspectInjector.Broker;
using AWS.Lambda.Powertools.Common;

namespace AWS.Lambda.Powertools.Metrics;

/// <summary>
/// MetricsAspect class is responsible for capturing ColdStart metric and flushing metrics on function exit.
/// Scope.Global - means aspect will operate as singleton.
/// </summary>
[Aspect(Scope.Global)]
public class MetricsAspect
{
/// <summary>
/// The is cold start
/// </summary>
private static bool _isColdStart;

/// <summary>
/// Specify to clear Lambda Context on exit
/// </summary>
private bool _clearLambdaContext;

/// <summary>
/// Gets the metrics instance.
/// </summary>
/// <value>The metrics instance.</value>
private static IMetrics _metricsInstance;

static MetricsAspect()
{
_isColdStart = true;
}

/// <summary>
/// Runs before the execution of the method marked with the Metrics Attribute
/// </summary>
/// <param name="instance"></param>
/// <param name="name"></param>
/// <param name="args"></param>
/// <param name="hostType"></param>
/// <param name="method"></param>
/// <param name="returnType"></param>
/// <param name="triggers"></param>
[Advice(Kind.Before)]
public void Before(
[Argument(Source.Instance)] object instance,
[Argument(Source.Name)] string name,
[Argument(Source.Arguments)] object[] args,
[Argument(Source.Type)] Type hostType,
[Argument(Source.Metadata)] MethodBase method,
[Argument(Source.ReturnType)] Type returnType,
[Argument(Source.Triggers)] Attribute[] triggers)
{
// Before running Function

var trigger = triggers.OfType<MetricsAttribute>().First();

_metricsInstance ??= new Metrics(
PowertoolsConfigurations.Instance,
trigger.Namespace,
trigger.Service,
trigger.RaiseOnEmptyMetrics,
trigger.CaptureColdStart
);

var eventArgs = new AspectEventArgs
{
Instance = instance,
Type = hostType,
Method = method,
Name = name,
Args = args,
ReturnType = returnType,
Triggers = triggers
};

if (trigger.CaptureColdStart && _isColdStart)
{
_isColdStart = false;

var nameSpace = _metricsInstance.GetNamespace();
var service = _metricsInstance.GetService();
Dictionary<string, string> dimensions = null;

_clearLambdaContext = PowertoolsLambdaContext.Extract(eventArgs);

if (PowertoolsLambdaContext.Instance is not null)
{
dimensions = new Dictionary<string, string>
{
{ "FunctionName", PowertoolsLambdaContext.Instance.FunctionName }
};
}

_metricsInstance.PushSingleMetric(
"ColdStart",
1.0,
MetricUnit.Count,
nameSpace,
service,
dimensions
);
}
}

/// <summary>
/// OnExit runs after the execution of the method marked with the Metrics Attribute
/// </summary>
[Advice(Kind.After)]
public void Exit()
{
_metricsInstance.Flush();
if (_clearLambdaContext)
PowertoolsLambdaContext.Clear();
}


/// <summary>
/// Reset the aspect for testing purposes.
/// </summary>
internal static void ResetForTest()
{
_metricsInstance = null;
_isColdStart = true;
Metrics.ResetForTest();
PowertoolsLambdaContext.Clear();
}
}
Loading

0 comments on commit 09f3e42

Please sign in to comment.