Skip to content

fix: Metrics Race condition if using Async calls #313

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
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
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ public List<List<string>> AllDimensionKeys
return defaultKeys;
}
}

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

/// <summary>
/// Adds metric to memory
Expand All @@ -139,11 +144,14 @@ public void AddMetric(string name, double value, MetricUnit unit, MetricResoluti
{
if (Metrics.Count < PowertoolsConfigurations.MaxMetrics)
{
var metric = Metrics.FirstOrDefault(m => m.Name == name);
if (metric != null)
metric.AddValue(value);
else
Metrics.Add(new MetricDefinition(name, unit, value, metricResolution));
lock (_lockObj)
{
var metric = Metrics.FirstOrDefault(m => m.Name == name);
if (metric != null)
metric.AddValue(value);
else
Metrics.Add(new MetricDefinition(name, unit, value, metricResolution));
}
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AWS.Lambda.Powertools.Common;
using Moq;
using Xunit;
Expand Down Expand Up @@ -642,5 +643,51 @@ private List<int> AllIndexesOf(string str, string value)
}

#endregion

[Fact]
public async Task WhenMetricsAsyncRaceConditionItemSameKeyExists_ValidateLock()
{
// Arrange
var methodName = Guid.NewGuid().ToString();
var consoleOut = new StringWriter();
Console.SetOut(consoleOut);

var configurations = new Mock<IPowertoolsConfigurations>();

var metrics = new Metrics(configurations.Object,
nameSpace: "dotnet-powertools-test",
service: "testService");

var handler = new MetricsAspectHandler(metrics,
false);

var eventArgs = new AspectEventArgs { Name = methodName };

// Act
handler.OnEntry(eventArgs);

var tasks = new List<Task>();
for (var i = 0; i < 100; i++)
{
tasks.Add(Task.Run(() =>
{
Metrics.AddMetric($"Metric Name", 0, MetricUnit.Count);
}));
}

await Task.WhenAll(tasks);


handler.OnExit(eventArgs);

var metricsOutput = consoleOut.ToString();

// Assert
Assert.Contains("{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"Metric Name\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\"]]",
metricsOutput);

// Reset
handler.ResetForTest();
}
}
}