Skip to content

chore: Metrics - Add thread safety to AddMetric #594

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

Merged
merged 2 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ public class Metrics : IMetrics, IDisposable
/// </summary>
private readonly bool _captureColdStartEnabled;

// <summary>
// Shared synchronization object
// </summary>
private readonly object _lockObj = new();

/// <summary>
/// Creates a Metrics object that provides features to send metrics to Amazon Cloudwatch using the Embedded metric
/// format (EMF). See
Expand Down Expand Up @@ -98,17 +103,20 @@ void IMetrics.AddMetric(string key, double value, MetricUnit unit, MetricResolut
"'AddMetric' method requires a valid metrics value. Value must be >= 0.", nameof(value));
}

var metrics = _context.GetMetrics();

if (metrics.Count > 0 &&
(metrics.Count == PowertoolsConfigurations.MaxMetrics ||
metrics.FirstOrDefault(x => x.Name == key)
?.Values.Count == PowertoolsConfigurations.MaxMetrics))
lock (_lockObj)
{
_instance.Flush(true);
var metrics = _context.GetMetrics();

if (metrics.Count > 0 &&
(metrics.Count == PowertoolsConfigurations.MaxMetrics ||
metrics.FirstOrDefault(x => x.Name == key)
?.Values.Count == PowertoolsConfigurations.MaxMetrics))
{
_instance.Flush(true);
}

_context.AddMetric(key, value, unit, metricResolution);
}

_context.AddMetric(key, value, unit, metricResolution);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
* permissions and limitations under the License.
*/

using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;

namespace AWS.Lambda.Powertools.Metrics.Tests.Handlers;
Expand Down Expand Up @@ -41,4 +43,16 @@ public async Task<string> HandleTestSecondCall(string input)

return input.ToUpper(CultureInfo.InvariantCulture);
}

[Metrics(Namespace = "ns", Service = "svc")]
public async Task<string> HandleMultipleThreads(string input)
{
await Parallel.ForEachAsync(Enumerable.Range(0, Environment.ProcessorCount * 2), async (x, _) =>
{
Metrics.AddMetric("MyMetric", 1);
await Task.Delay(1);
});

return input.ToUpper(CultureInfo.InvariantCulture);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,16 @@ public async Task When_Metrics_Add_Metadata_Second_Invocation_Should_Not_Throw_E
exception = await Record.ExceptionAsync( () => handler.HandleTestSecondCall("whatever"));
Assert.Null(exception);
}

[Fact]
public async Task When_Metrics_Add_Metadata_FromMultipleThread_Should_Not_Throw_Exception()
{
// Arrange
Metrics.ResetForTest();
var handler = new FunctionHandler();

// Act
var exception = await Record.ExceptionAsync(() => handler.HandleMultipleThreads("whatever"));
Assert.Null(exception);
}
}
Loading