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

[repo/AwsInstrumentations] Prepare to .NET9 #2272

Merged
merged 33 commits into from
Oct 31, 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
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@ internal class AWSServiceHelper
{
internal static IReadOnlyDictionary<string, List<string>> ServiceRequestParameterMap = new Dictionary<string, List<string>>()
{
{ AWSServiceType.DynamoDbService, new List<string> { "TableName" } },
{ AWSServiceType.SQSService, new List<string> { "QueueUrl" } },
{ AWSServiceType.BedrockAgentService, new List<string> { "AgentId", "KnowledgeBaseId", "DataSourceId" } },
{ AWSServiceType.BedrockAgentRuntimeService, new List<string> { "AgentId", "KnowledgeBaseId" } },
{ AWSServiceType.BedrockRuntimeService, new List<string> { "ModelId" } },
{ AWSServiceType.DynamoDbService, ["TableName"] },
{ AWSServiceType.SQSService, ["QueueUrl"] },
{ AWSServiceType.BedrockAgentService, ["AgentId", "KnowledgeBaseId", "DataSourceId"] },
{ AWSServiceType.BedrockAgentRuntimeService, ["AgentId", "KnowledgeBaseId"] },
{ AWSServiceType.BedrockRuntimeService, ["ModelId"] },
};

internal static IReadOnlyDictionary<string, List<string>> ServiceResponseParameterMap = new Dictionary<string, List<string>>()
{
{ AWSServiceType.BedrockService, new List<string> { "GuardrailId" } },
{ AWSServiceType.BedrockAgentService, new List<string> { "AgentId", "DataSourceId" } },
{ AWSServiceType.BedrockService, ["GuardrailId"] },
{ AWSServiceType.BedrockAgentService, ["AgentId", "DataSourceId"] },
};

internal static IReadOnlyDictionary<string, string> ParameterAttributeMap = new Dictionary<string, string>()
Expand All @@ -34,8 +34,8 @@ internal class AWSServiceHelper
};

// for Bedrock Agent operations, we map each supported operation to one resource: Agent, DataSource, or KnowledgeBase
internal static List<string> BedrockAgentAgentOps = new List<string>
{
internal static List<string> BedrockAgentAgentOps =
[
"CreateAgentActionGroup",
"CreateAgentAlias",
"DeleteAgentActionGroup",
Expand All @@ -53,27 +53,27 @@ internal class AWSServiceHelper
"PrepareAgent",
"UpdateAgentActionGroup",
"UpdateAgentAlias",
"UpdateAgent",
};
"UpdateAgent"
];

internal static List<string> BedrockAgentKnowledgeBaseOps = new List<string>
{
internal static List<string> BedrockAgentKnowledgeBaseOps =
[
"AssociateAgentKnowledgeBase",
"CreateDataSource",
"DeleteKnowledgeBase",
"DisassociateAgentKnowledgeBase",
"GetAgentKnowledgeBase",
"GetKnowledgeBase",
"ListDataSources",
"UpdateAgentKnowledgeBase",
};
"UpdateAgentKnowledgeBase"
];

internal static List<string> BedrockAgentDataSourceOps = new List<string>
{
internal static List<string> BedrockAgentDataSourceOps =
[
"DeleteDataSource",
"GetDataSource",
"UpdateDataSource",
};
"UpdateDataSource"
];

internal static IReadOnlyDictionary<string, string> OperationNameToResourceMap()
{
Expand Down Expand Up @@ -102,8 +102,8 @@ internal static string GetAWSServiceName(IRequestContext requestContext)

internal static string GetAWSOperationName(IRequestContext requestContext)
{
string completeRequestName = requestContext.OriginalRequest.GetType().Name;
string suffix = "Request";
var completeRequestName = requestContext.OriginalRequest.GetType().Name;
var suffix = "Request";
var operationName = Utils.RemoveSuffix(completeRequestName, suffix);
return operationName;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,8 @@ public override void InvokeSync(IExecutionContext executionContext)

public override async Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
T? ret = null;

var activity = this.ProcessBeginRequest(executionContext);
ret = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
var ret = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);

ProcessEndRequest(activity, executionContext);

Expand All @@ -57,7 +55,7 @@ private static void AddResponseSpecificInformation(Activity activity, IExecution

if (AWSServiceHelper.ServiceResponseParameterMap.TryGetValue(service, out var parameters))
{
AmazonWebServiceResponse response = responseContext.Response;
var response = responseContext.Response;

foreach (var parameter in parameters)
{
Expand Down Expand Up @@ -129,7 +127,7 @@ private static void AddRequestSpecificInformation(Activity activity, IRequestCon

if (AWSServiceHelper.ServiceRequestParameterMap.TryGetValue(service, out var parameters))
{
AmazonWebServiceRequest request = requestContext.OriginalRequest;
var request = requestContext.OriginalRequest;

foreach (var parameter in parameters)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ namespace OpenTelemetry.Instrumentation.AWS.Implementation.Metrics;
internal sealed class AWSHistogram<T> : Histogram<T>
where T : struct
{
private static readonly ConcurrentDictionary<string, System.Diagnostics.Metrics.Histogram<T>> HistogramsDictionary
= new ConcurrentDictionary<string, System.Diagnostics.Metrics.Histogram<T>>();
private static readonly ConcurrentDictionary<string, System.Diagnostics.Metrics.Histogram<T>> HistogramsDictionary = new();

private readonly System.Diagnostics.Metrics.Histogram<T> histogram;

Expand All @@ -21,7 +20,7 @@ public AWSHistogram(
string? units = null,
string? description = null)
{
if (HistogramsDictionary.TryGetValue(name, out System.Diagnostics.Metrics.Histogram<T>? histogram))
if (HistogramsDictionary.TryGetValue(name, out var histogram))
{
this.histogram = histogram;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace OpenTelemetry.Instrumentation.AWS.Implementation.Metrics;

internal sealed class AWSMeterProvider : MeterProvider
{
private static readonly ConcurrentDictionary<string, AWSMeter> MetersDictionary = new ConcurrentDictionary<string, AWSMeter>();
private static readonly ConcurrentDictionary<string, AWSMeter> MetersDictionary = new();

public override Meter GetMeter(string scope, Attributes? attributes = null)
{
Expand All @@ -20,7 +20,7 @@ public override Meter GetMeter(string scope, Attributes? attributes = null)
// update OpenTelemetry core component version(s) to `1.9.0` and allow passing tags to
// the meter constructor.

if (MetersDictionary.TryGetValue(scope, out AWSMeter? meter))
if (MetersDictionary.TryGetValue(scope, out var meter))
{
return meter;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ namespace OpenTelemetry.Instrumentation.AWS.Implementation.Metrics;
internal sealed class AWSMonotonicCounter<T> : MonotonicCounter<T>
where T : struct
{
private static readonly ConcurrentDictionary<string, System.Diagnostics.Metrics.Counter<T>> MonotonicCountersDictionary
= new ConcurrentDictionary<string, System.Diagnostics.Metrics.Counter<T>>();
private static readonly ConcurrentDictionary<string, System.Diagnostics.Metrics.Counter<T>> MonotonicCountersDictionary = new();

private readonly System.Diagnostics.Metrics.Counter<T> monotonicCounter;

Expand All @@ -21,7 +20,7 @@ public AWSMonotonicCounter(
string? units = null,
string? description = null)
{
if (MonotonicCountersDictionary.TryGetValue(name, out System.Diagnostics.Metrics.Counter<T>? monotonicCounter))
if (MonotonicCountersDictionary.TryGetValue(name, out var monotonicCounter))
{
this.monotonicCounter = monotonicCounter;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ namespace OpenTelemetry.Instrumentation.AWS.Implementation.Metrics;
internal sealed class AWSUpDownCounter<T> : UpDownCounter<T>
where T : struct
{
private static readonly ConcurrentDictionary<string, System.Diagnostics.Metrics.UpDownCounter<T>> UpDownCountersDictionary
= new ConcurrentDictionary<string, System.Diagnostics.Metrics.UpDownCounter<T>>();
private static readonly ConcurrentDictionary<string, System.Diagnostics.Metrics.UpDownCounter<T>> UpDownCountersDictionary = new();

private readonly System.Diagnostics.Metrics.UpDownCounter<T> upDownCounter;

Expand All @@ -21,7 +20,7 @@ public AWSUpDownCounter(
string? units = null,
string? description = null)
{
if (UpDownCountersDictionary.TryGetValue(name, out System.Diagnostics.Metrics.UpDownCounter<T>? upDownCounter))
if (UpDownCountersDictionary.TryGetValue(name, out var upDownCounter))
{
this.upDownCounter = upDownCounter;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ internal static void AddAttributes(IRequestContext context, IReadOnlyDictionary<
return;
}

if (attributes.Keys.Any(k => originalRequest.MessageAttributes.ContainsKey(k)))
if (attributes.Keys.Any(originalRequest.MessageAttributes.ContainsKey))
{
// If at least one attribute is already present in the request then we skip the injection.
return;
}

int attributesCount = originalRequest.MessageAttributes.Count;
var attributesCount = originalRequest.MessageAttributes.Count;
if (attributes.Count + attributesCount > MaxMessageAttributes)
{
// TODO: add logging (event source).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ internal static void AddAttributes(IRequestContext context, IReadOnlyDictionary<
return;
}

if (attributes.Keys.Any(k => originalRequest.MessageAttributes.ContainsKey(k)))
if (attributes.Keys.Any(originalRequest.MessageAttributes.ContainsKey))
{
// If at least one attribute is already present in the request then we skip the injection.
return;
}

int attributesCount = originalRequest.MessageAttributes.Count;
var attributesCount = originalRequest.MessageAttributes.Count;
if (attributes.Count + attributesCount > MaxMessageAttributes)
{
// TODO: add logging (event source).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ private static ActivityStatusCode ConvertToActivityStatusCode(SpanStatus status)
{
SpanStatus.OK => ActivityStatusCode.Ok,
SpanStatus.ERROR => ActivityStatusCode.Error,
SpanStatus.UNSET => ActivityStatusCode.Unset,
_ => ActivityStatusCode.Unset,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public override TraceSpan CreateSpan(
var tags = initialAttributes != null ? new ActivityTagsCollection(initialAttributes.AllAttributes) : null;
var activityKind = ConvertToActivityKind(spanKind);

ActivityContext parentActivityContext = ConvertToActivityContext(parentContext);
var parentActivityContext = ConvertToActivityContext(parentContext);
var activity = this.activitySource.StartActivity(name, activityKind, parentActivityContext, tags);

return new AWSTraceSpan(activity);
Expand Down Expand Up @@ -66,6 +66,7 @@ private static ActivityKind ConvertToActivityKind(SpanKind spanKind)
SpanKind.SERVER => ActivityKind.Server,
SpanKind.PRODUCER => ActivityKind.Producer,
SpanKind.CONSUMER => ActivityKind.Consumer,
SpanKind.INTERNAL => ActivityKind.Internal,
_ => ActivityKind.Internal,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ namespace OpenTelemetry.Instrumentation.AWS.Implementation.Tracing;

internal sealed class AWSTracerProvider : TracerProvider
{
private static readonly ConcurrentDictionary<string, AWSTracer> TracersDictionary = new ConcurrentDictionary<string, AWSTracer>();
private static readonly ConcurrentDictionary<string, AWSTracer> TracersDictionary = new();

public override Tracer GetTracer(string scope)
{
if (TracersDictionary.TryGetValue(scope, out AWSTracer? awsTracer))
if (TracersDictionary.TryGetValue(scope, out var awsTracer))
{
return awsTracer;
}
Expand Down
33 changes: 10 additions & 23 deletions src/OpenTelemetry.Instrumentation.AWS/Implementation/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ internal class Utils
{
internal static object? GetTagValue(Activity activity, string tagName)
{
foreach (KeyValuePair<string, object?> tag in activity.TagObjects)
foreach (var tag in activity.TagObjects)
{
if (tag.Key.Equals(tagName, StringComparison.Ordinal))
{
Expand All @@ -22,17 +22,12 @@ internal class Utils

internal static string RemoveSuffix(string originalString, string suffix)
{
if (string.IsNullOrEmpty(originalString))
{
return string.Empty;
}

if (originalString.EndsWith(suffix, StringComparison.Ordinal))
{
return originalString.Substring(0, originalString.Length - suffix.Length);
}

return originalString;
return string.IsNullOrEmpty(originalString)
Copy link
Member

Choose a reason for hiding this comment

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

nit: Do we have to make this change? The previous version was more readable to me.

? string.Empty
: originalString.EndsWith(suffix, StringComparison.Ordinal)
?
originalString.Substring(0, originalString.Length - suffix.Length)
: originalString;
}

/// <summary>
Expand All @@ -50,16 +45,8 @@ internal static string RemoveAmazonPrefixFromServiceName(string serviceName)

private static string RemovePrefix(string originalString, string prefix)
{
if (string.IsNullOrEmpty(originalString))
{
return string.Empty;
}

if (originalString.StartsWith(prefix, StringComparison.Ordinal))
{
return originalString.Substring(prefix.Length);
}

return originalString;
return string.IsNullOrEmpty(originalString) ? string.Empty :
originalString.StartsWith(prefix, StringComparison.Ordinal) ? originalString.Substring(prefix.Length) :
originalString;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ internal static IEnumerable<KeyValuePair<string, object>> GetHttpTags<TInput>(TI
{
var tags = new List<KeyValuePair<string, object>>();

string? httpScheme = null;
string? httpTarget = null;
string? httpMethod = null;
string? hostName = null;
int? hostPort = null;
string? httpScheme;
string? httpTarget;
string? httpMethod;
string? hostName;
int? hostPort;

switch (input)
{
Expand Down Expand Up @@ -81,6 +81,8 @@ internal static void SetHttpTagsFromResult(Activity? activity, object? result)
case ApplicationLoadBalancerResponse albResponse:
activity.SetTag(SemanticConventions.AttributeHttpStatusCode, albResponse.StatusCode);
break;
default:
break;
}
}

Expand Down Expand Up @@ -165,7 +167,7 @@ internal static (string? Host, int? Port) GetHostAndPort(string? httpScheme, str
}

#pragma warning disable CA1861 // Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array
var hostAndPort = hostHeader.Split(new char[] { ':' }, 2);
var hostAndPort = hostHeader.Split([':'], 2);
#pragma warning restore CA1861 // Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array
if (hostAndPort.Length > 1)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,7 @@ internal static class AWSLambdaUtils

private static readonly Func<IDictionary<string, string>, string, IEnumerable<string>> Getter = (headers, name) =>
{
if (headers.TryGetValue(name, out var value))
{
return new[] { value };
}

return Array.Empty<string>();
return headers.TryGetValue(name, out var value) ? [value] : [];
};

internal static ActivityContext GetXRayParentContext()
Expand Down Expand Up @@ -77,6 +72,8 @@ internal static (ActivityContext ParentContext, IEnumerable<ActivityLink>? Links
case SNSEvent.SNSRecord snsRecord:
parentContext = AWSMessagingUtils.ExtractParentContext(snsRecord);
break;
default:
break;
}

return (parentContext.ActivityContext, links);
Expand Down Expand Up @@ -179,12 +176,7 @@ internal static IEnumerable<KeyValuePair<string, object>> GetFunctionTags<TInput
// Function arn format - arn:aws:lambda:<region>:<account-id>:function:<function-name>

var items = functionArn.Split(':');
if (items.Length >= 5)
{
return items[4];
}

return null;
return items.Length >= 5 ? items[4] : null;
}

private static string GetFaasId(string functionArn)
Expand All @@ -207,7 +199,7 @@ private static string GetFaasTrigger<TInput>(TInput input) =>
IsHttpRequest(input) ? "http" : "other";

private static bool IsHttpRequest<TInput>(TInput input) =>
input is APIGatewayProxyRequest || input is APIGatewayHttpApiV2ProxyRequest || input is ApplicationLoadBalancerRequest;
input is APIGatewayProxyRequest or APIGatewayHttpApiV2ProxyRequest or ApplicationLoadBalancerRequest;

private static ActivityContext ParseXRayTraceHeader(string rawHeader)
{
Expand Down
Loading
Loading