Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Metrics throws exception when decorating non handler methods #499

Merged
merged 6 commits into from
Oct 20, 2023

Conversation

hjgraca
Copy link
Contributor

@hjgraca hjgraca commented Oct 3, 2023

Please provide the issue number

Issue number: #498

Summary

Even though Metrics decorator should be used exclusively to decorate the handler, utilities should not throw exceptions when used incorrectly.

Update Metrics constructor to not return and set all values.

Current Behaviour

Currently Metrics throws NullReferenceException when decorating non handler (no Lambda context) methods.

System.NullReferenceException: Object reference not set to an instance of an object.
   at AWS.Lambda.Powertools.Metrics.Metrics.AWS.Lambda.Powertools.Metrics.IMetrics.Flush(Boolean metricsOverflow) in /aws-lambda-powertools-dotnet/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs:line 204
   at AWS.Lambda.Powertools.Metrics.MetricsAspectHandler.OnExit(AspectEventArgs eventArgs) in /aws-lambda-powertools-dotnet/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspectHandler.cs:line 71
   at AWS.Lambda.Powertools.Common.MethodAspectAttribute.WrapSync[T](Func`2 target, Object[] args, AspectEventArgs eventArgs) in /aws-lambda-powertools-dotnet/libraries/src/AWS.Lambda.Powertools.Common/Aspects/MethodAspectAttribute.cs:line 72
   at AWS.Lambda.Powertools.Common.UniversalWrapperAspect.Handle(Object instance, Type type, MethodBase method, Func`2 target, String name, Object[] args, Type returnType, Attribute[] triggers) in /aws-lambda-powertools-dotnet/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAspect.cs:line 87
   at AWS.Lambda.Powertools.Metrics.Tests.Handlers.ExceptionFunctionHandler.__a$_around_MethodDecorated_100663324_w_0(Object[] )

Flush method has a null _context

void IMetrics.Flush(bool metricsOverflow)
    {
        if (_context.GetMetrics().Count == 0
            && _raiseOnEmptyMetrics)
            throw new SchemaValidationException(true);

        if (_context.IsSerializable)
        {
            var emfPayload = _context.Serialize();

            Console.WriteLine(emfPayload);

            _context.ClearMetrics();

            if (!metricsOverflow) _context.ClearNonDefaultDimensions();
        }
        else
        {
            if (!_captureColdStartEnabled)
                Console.WriteLine(
                    "##WARNING## Metrics and Metadata have not been specified. No data will be sent to Cloudwatch Metrics.");
        }
    }

Changes

Please provide a summary of what's being changed

Fix : always set the values, but only set instance if null.

    internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string nameSpace = null, string service = null,
        bool raiseOnEmptyMetrics = false, bool captureColdStartEnabled = false)
    {
        _instance ??= this; // this line updated

        _powertoolsConfigurations = powertoolsConfigurations;
        _raiseOnEmptyMetrics = raiseOnEmptyMetrics;
        _captureColdStartEnabled = captureColdStartEnabled;
        _context = InitializeContext(nameSpace, service, null);
        
        _powertoolsConfigurations.SetExecutionEnvironment(this);
    }

User experience

Please share what the user experience looks like before and after this change

Checklist

Please leave checklist items unchecked if they do not apply to your change.

Is this a breaking change?

RFC issue number:

Checklist:

  • Migration process documented
  • Implement warnings (if it can live side by side)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

@auto-assign auto-assign bot requested a review from amirkaws October 3, 2023 11:36
@boring-cyborg boring-cyborg bot added the area/metrics Core metrics utility label Oct 3, 2023
@auto-assign auto-assign bot requested a review from sliedig October 3, 2023 11:36
@boring-cyborg boring-cyborg bot added the tests label Oct 3, 2023
@pull-request-size pull-request-size bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Oct 3, 2023
@github-actions github-actions bot added the bug Unexpected, reproducible and unintended software behaviour label Oct 3, 2023
@hjgraca hjgraca changed the title fix: Update Metrics constructor to not return and set all values. fix: Metrics throws exception when decorating non handler methods Oct 3, 2023
@codecov-commenter
Copy link

codecov-commenter commented Oct 3, 2023

Codecov Report

Attention: 17 lines in your changes are missing coverage. Please review.

Comparison is base (d8e60bf) 74.46% compared to head (95d300b) 74.79%.

❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #499      +/-   ##
===========================================
+ Coverage    74.46%   74.79%   +0.33%     
===========================================
  Files           99       99              
  Lines         4041     4047       +6     
===========================================
+ Hits          3009     3027      +18     
+ Misses        1032     1020      -12     
Flag Coverage Δ
unittests 74.79% <19.04%> (+0.33%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files Coverage Δ
...aries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs 81.63% <19.04%> (-4.19%) ⬇️

... and 4 files with indirect coverage changes

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@pull-request-size pull-request-size bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Oct 9, 2023
@sonarqubecloud
Copy link

sonarqubecloud bot commented Oct 9, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 3 Code Smells

No Coverage information No Coverage information
0.0% 0.0% Duplication

Copy link
Contributor

@amirkaws amirkaws left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@@ -23,7 +23,7 @@ namespace AWS.Lambda.Powertools.Metrics;
/// Implements the <see cref="System.IDisposable" />
/// </summary>
/// <seealso cref="System.IDisposable" />
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this line

@hjgraca hjgraca merged commit 21aff1f into aws-powertools:develop Oct 20, 2023
@hjgraca hjgraca deleted the metrics-decorator-exception branch October 20, 2023 10:48
@hjgraca hjgraca linked an issue Oct 20, 2023 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/metrics Core metrics utility bug Unexpected, reproducible and unintended software behaviour size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: Metrics throws exception when decorating non handler methods
3 participants