Skip to content
Open
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
4 changes: 4 additions & 0 deletions BannedSymbols.NetFx.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Banned APIs for Datadog.Trace when targeting .NET Framework

M:System.String.ToUpperInvariant;Use StringUtil.ToUpperInvariant(value) instead - on .NET Framework it avoids allocating when the string is already uppercase
M:System.String.ToLowerInvariant;Use StringUtil.ToLowerInvariant(value) instead - on .NET Framework it avoids allocating when the string is already lowercase
3 changes: 2 additions & 1 deletion docs/development/Configuration/AddingConfigurationKeys.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ Aliases use the normal `WithKeys()` fallback chain. When a key marked for redact
- **Banned API Analyzer** - Uses Microsoft's `BannedApiAnalyzers` package to prevent direct usage of `System.Environment.GetEnvironmentVariable()` throughout the codebase.

**Configuration:**
- **`BannedSymbols.txt`** (`tracer/src/Datadog.Trace.Tools.Analyzers/ConfigurationAnalyzers/BannedSymbols.txt`) - Defines banned APIs with custom error messages
- **`BannedSymbols.txt`** (repo root) - Defines banned APIs with custom error messages, applied to every project under `tracer/` that wires it up via `AdditionalFiles`
- **`BannedSymbols.NetFx.txt`** (repo root) - Additional bans applied only when building `Datadog.Trace` for `net461`
- **`.editorconfig`** - Configures RS0030 diagnostic severity as error, with exceptions for vendored code and `EnvironmentConfigurationSource.cs`

##### Diagnostic rules:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,25 +209,32 @@ public static System.Collections.Generic.KeyValuePair<string, string[]> GetInteg
};

private static System.Collections.Generic.KeyValuePair<string, string[]> GetIntegrationEnabledKeysFallback(string integrationName) =>
new(string.Format("DD_TRACE_{0}_ENABLED", integrationName.ToUpperInvariant()),
new(string.Format("DD_TRACE_{0}_ENABLED", ToUpperInvariant(integrationName)),
[
string.Format("DD_TRACE_{0}_ENABLED", integrationName),
$"DD_{integrationName}_ENABLED"
]);

private static System.Collections.Generic.KeyValuePair<string, string[]> GetIntegrationAnalyticsEnabledKeysFallback(string integrationName) =>
new(string.Format("DD_TRACE_{0}_ANALYTICS_ENABLED", integrationName.ToUpperInvariant()),
new(string.Format("DD_TRACE_{0}_ANALYTICS_ENABLED", ToUpperInvariant(integrationName)),
[
string.Format("DD_TRACE_{0}_ANALYTICS_ENABLED", integrationName),
$"DD_{integrationName}_ANALYTICS_ENABLED"
]);

private static System.Collections.Generic.KeyValuePair<string, string[]> GetIntegrationAnalyticsSampleRateKeysFallback(string integrationName) =>
new(string.Format("DD_TRACE_{0}_ANALYTICS_SAMPLE_RATE", integrationName.ToUpperInvariant()),
new(string.Format("DD_TRACE_{0}_ANALYTICS_SAMPLE_RATE", ToUpperInvariant(integrationName)),
[
string.Format("DD_TRACE_{0}_ANALYTICS_SAMPLE_RATE", integrationName),
$"DD_{integrationName}_ANALYTICS_SAMPLE_RATE"
]);

private static string ToUpperInvariant(string value) =>
#if NETFRAMEWORK
System.StringUtil.ToUpperInvariant(value);
#else
value.ToUpperInvariant();
#endif
}
}

Expand Down
20 changes: 10 additions & 10 deletions tracer/src/Datadog.Trace/Activity/OperationNameMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ internal static string GetOperationName(OpenTelemetryTags tags)
if (tags.SpanKind == SpanKinds.Client && tags.GetTag("db.system") is { Length: > 0 } dbSystem)
{
// IsDatabase
return $"{dbSystem.ToLowerInvariant()}.query";
return $"{StringUtil.ToLowerInvariant(dbSystem)}.query";
}

if (tags.SpanKind is SpanKinds.Client or SpanKinds.Server or SpanKinds.Producer or SpanKinds.Consumer
&& tags.GetTag(Tags.MessagingSystem) is { Length: > 0 } messagingSystem
&& tags.GetTag(Tags.MessagingOperation) is { Length: > 0 } messagingOperation)
{
// IsMessaging
return $"{messagingSystem}.{messagingOperation}".ToLowerInvariant();
return StringUtil.ToLowerInvariant($"{messagingSystem}.{messagingOperation}");
}

var rpcSystem = tags.GetTag(Tags.RpcSystem);
Expand All @@ -73,35 +73,35 @@ internal static string GetOperationName(OpenTelemetryTags tags)
if (tags.SpanKind == SpanKinds.Client && string.Equals(rpcSystem, "aws-api", StringComparison.OrdinalIgnoreCase))
{
// IsAwsClient
var service = tags.GetTag(Tags.RpcService)?.ToLowerInvariant();
var service = StringUtil.ToLowerInvariant(tags.GetTag(Tags.RpcService));
return !StringUtil.IsNullOrEmpty(service) ? $"aws.{service}.request" : "aws.client.request";
}

if (tags.SpanKind == SpanKinds.Client)
{
// IsRpcClient
return $"{rpcSystem.ToLowerInvariant()}.client.request";
return $"{StringUtil.ToLowerInvariant(rpcSystem)}.client.request";
}

if (tags.SpanKind == SpanKinds.Server)
{
// IsRpcServer
return $"{rpcSystem.ToLowerInvariant()}.server.request";
return $"{StringUtil.ToLowerInvariant(rpcSystem)}.server.request";
}
}

if (tags.SpanKind == SpanKinds.Server && tags.GetTag("faas.trigger") is { Length: > 0 } faasTrigger)
{
// IsFaasServer
return $"{faasTrigger.ToLowerInvariant()}.invoke";
return $"{StringUtil.ToLowerInvariant(faasTrigger)}.invoke";
}

if (tags.SpanKind == SpanKinds.Client
&& tags.GetTag("faas.invoked_provider") is { Length: > 0 } faasInvokedProvider
&& tags.GetTag("faas.invoked_name") is { Length: > 0 } faasInvokedName)
{
// IsFaasClient
return $"{faasInvokedProvider}.{faasInvokedName}.invoke".ToLowerInvariant();
return StringUtil.ToLowerInvariant($"{faasInvokedProvider}.{faasInvokedName}.invoke");
}

if (tags.SpanKind == SpanKinds.Server && !StringUtil.IsNullOrEmpty(tags.GetTag("graphql.operation.type")))
Expand All @@ -114,19 +114,19 @@ internal static string GetOperationName(OpenTelemetryTags tags)
{
// IsGenericServer
var name = tags.GetTag("network.protocol.name");
return !StringUtil.IsNullOrEmpty(name) ? $"{name.ToLowerInvariant()}.server.request" : "server.request";
return !StringUtil.IsNullOrEmpty(name) ? $"{StringUtil.ToLowerInvariant(name)}.server.request" : "server.request";
}

if (tags.SpanKind == SpanKinds.Client)
{
// IsGenericClient
var name = tags.GetTag("network.protocol.name");
return !StringUtil.IsNullOrEmpty(name) ? $"{name.ToLowerInvariant()}.client.request" : "client.request";
return !StringUtil.IsNullOrEmpty(name) ? $"{StringUtil.ToLowerInvariant(name)}.client.request" : "client.request";
}

// when there is no SpanKind defined (possible on Activity objects without "Kind")
// fallback to using "internal" for the name.
return !StringUtil.IsNullOrEmpty(tags.SpanKind) ? tags.SpanKind.ToLowerInvariant() : SpanKinds.Internal;
return !StringUtil.IsNullOrEmpty(tags.SpanKind) ? StringUtil.ToLowerInvariant(tags.SpanKind) : SpanKinds.Internal;
}
}
}
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/Activity/OtlpHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ internal static void AgentSetOtlpTag(Span span, string key, string? value, bool
case "operation.name":
if (setKnownValues)
{
span.OperationName = value?.ToLowerInvariant();
span.OperationName = StringUtil.ToLowerInvariant(value);
}

break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,7 @@ private static string CanonicalizeSpanKind(string spanKind)
name = name.Substring(11);
}

name = name.ToUpperInvariant();
name = StringUtil.ToUpperInvariant(name);

// Accept common single-L alias and compact form
if (name == "CANCELED")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ public Dictionary<string, object> GetResponseHeadersForWaf()
var keyForDictionary = originalKey ?? string.Empty;
if (!keyForDictionary.Equals("cookie", StringComparison.OrdinalIgnoreCase))
{
keyForDictionary = keyForDictionary.ToLowerInvariant();
keyForDictionary = StringUtil.ToLowerInvariant(keyForDictionary);
if (!headersDic.ContainsKey(keyForDictionary))
{
headersDic.Add(keyForDictionary, GetHeaderAsArray(response.Headers.GetValues(originalKey)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ private void SetErrorInformation(bool isRasp, IResult? result)
var currentKey = key ?? string.Empty;
if (!currentKey.Equals("cookie", StringComparison.OrdinalIgnoreCase))
{
currentKey = currentKey.ToLowerInvariant();
currentKey = StringUtil.ToLowerInvariant(currentKey);
var value = getHeaderValue(collection, currentKey);
#if NETCOREAPP
if (!headersDic.TryAdd(currentKey, value))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ private void ApplyAsmFeatures(bool appsecCurrentlyEnabled)
}
else
{
AutoUserInstrumMode = autoUserInstrumMode?.Mode?.ToLowerInvariant();
AutoUserInstrumMode = StringUtil.ToLowerInvariant(autoUserInstrumMode?.Mode);
}
}

Expand Down
6 changes: 3 additions & 3 deletions tracer/src/Datadog.Trace/AspNet/TracingHttpModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ private static string BuildResourceName(Tracer tracer, HttpRequest httpRequest)
if (url is not null)
{
var path = UriHelpers.GetCleanUriPath(url, httpRequest.ApplicationPath);
return $"{httpRequest.HttpMethod.ToUpperInvariant()} {path.ToLowerInvariant()}";
return $"{StringUtil.ToUpperInvariant(httpRequest.HttpMethod)} {StringUtil.ToLowerInvariant(path)}";
}
else
{
return $"{httpRequest.HttpMethod.ToUpperInvariant()}";
return $"{StringUtil.ToUpperInvariant(httpRequest.HttpMethod)}";
}
}

Expand Down Expand Up @@ -182,7 +182,7 @@ private void OnBeginRequest(object sender, EventArgs eventArgs)

string host = requestHeaders.Get("Host");
var userAgent = requestHeaders.Get(HttpHeaderNames.UserAgent);
string httpMethod = httpRequest.HttpMethod.ToUpperInvariant();
string httpMethod = StringUtil.ToUpperInvariant(httpRequest.HttpMethod);
var url = httpContext.Request.GetUrlForSpan(tracer.TracerManager.QueryStringManager, tracer.Settings.BypassHttpRequestUrlCachingEnabled);
var tags = new AspNetRequestTags();
scope = tracer.StartActiveInternal(_requestOperationName, extractedContext.SpanContext, tags: tags);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ protected override void OnInitialize(IGitInfo gitInfo)
{
if (envvar?.Key is string key && key.StartsWith(PlatformKeys.Ci.Buildkite.AgentMetadata, StringComparison.OrdinalIgnoreCase))
{
var name = key.Substring(PlatformKeys.Ci.Buildkite.AgentMetadata.Length).ToLowerInvariant();
var name = StringUtil.ToLowerInvariant(key.Substring(PlatformKeys.Ci.Buildkite.AgentMetadata.Length));
var value = envvar?.Value?.ToString();
lstNodeLabels.Add($"{name}:{value}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ protected override void OnInitialize(IGitInfo gitInfo)
var jobNameParts = jobNameNoBranch.Split('/');
if (jobNameParts.Length > 1 && jobNameParts[1].Contains("="))
{
var configsStr = jobNameParts[1].ToLowerInvariant().Trim();
var configsStr = StringUtil.ToLowerInvariant(jobNameParts[1]).Trim();
var configsKeyValue = configsStr.Split(',');
foreach (var configKeyValue in configsKeyValue)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4738,7 +4738,7 @@ private bool CoverletOutputDirectoryWritesLineCapableReportPath(string outputPat
continue;
}

var fileName = $"coverage.{normalizedFormat.ToLowerInvariant()}.xml";
var fileName = $"coverage.{StringUtil.ToLowerInvariant(normalizedFormat)}.xml";
if (CoverletOutputPathsEqual(Path.Combine(outputPath, fileName), reportPath) ||
CoverletOutputDirectoryWithTargetFrameworkReferencesReportPath(outputPath, fileName, reportPath))
{
Expand Down Expand Up @@ -4840,7 +4840,7 @@ private bool CoverletOutputFileWritesLineCapableReportPath(string outputPath, st
continue;
}

var extension = $".{normalizedFormat.ToLowerInvariant()}.xml";
var extension = $".{StringUtil.ToLowerInvariant(normalizedFormat)}.xml";
if (CoverletOutputPathsEqual($"{outputPath}{extension}", reportPath) ||
CoverletOutputFileWithTargetFrameworkReferencesReportPath(outputPath, extension, reportPath))
{
Expand Down
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/Ci/GitCommandHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ internal static class GitCommandHelper
lock (Hasher)
{
var hash = Hasher.ComputeHash(Encoding.UTF8.GetBytes(arguments));
cacheKey = Path.Combine(cacheFolder, BitConverter.ToString(hash).ToLowerInvariant() + ".json");
cacheKey = Path.Combine(cacheFolder, StringUtil.ToLowerInvariant(BitConverter.ToString(hash)) + ".json");
}

if (File.Exists(cacheKey))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ internal FileTestOptimizationClient(ITestOptimizationClient testOptimizationClie
lock (Hasher)
{
var hash = Hasher.ComputeHash(Encoding.UTF8.GetBytes(salt));
salt = BitConverter.ToString(hash).ToLowerInvariant();
salt = StringUtil.ToLowerInvariant(BitConverter.ToString(hash));
}

var runFolder = CoverageBackfillDataStore.GetOrCreateRunFolder(testOptimization);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ namespace Datadog.Trace.Propagators;

internal readonly struct DictionaryGetterAndSetter : ICarrierGetter<IDictionary>, ICarrierSetter<IDictionary>
{
public static readonly Func<string, string> EnvironmentVariableKeyProcessor = key => key
.Replace(".", "_")
.Replace("-", "_")
.ToUpperInvariant();
public static readonly Func<string, string> EnvironmentVariableKeyProcessor = key => StringUtil.ToUpperInvariant(
key.Replace(".", "_")
.Replace("-", "_"));

private readonly Func<string, string>? _keyProcessor;

Expand Down
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/Ci/Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ internal Test(TestSuite suite, string name, DateTimeOffset? startDate, TraceId t
var tags = new TestSpanTags(Suite.Tags, name);
var tracer = Tracer.Instance;
var span = tracer.StartSpan(
StringUtil.IsNullOrEmpty(module.Framework) ? "test" : $"{module.Framework!.ToLowerInvariant()}.test",
StringUtil.IsNullOrEmpty(module.Framework) ? "test" : $"{StringUtil.ToLowerInvariant(module.Framework)}.test",
tags: tags,
startTime: startDate,
traceId: traceId,
Expand Down
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/Ci/TestModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ _testOptimization.SkippableFeature is { } sf
tags.TestsSkipped = "false";

var span = Tracer.Instance.StartSpan(
string.IsNullOrEmpty(framework) ? "test_module" : $"{framework!.ToLowerInvariant()}.test_module",
string.IsNullOrEmpty(framework) ? "test_module" : $"{StringUtil.ToLowerInvariant(framework)}.test_module",
tags: tags,
startTime: startDate);
TelemetryFactory.Metrics.RecordCountSpanCreated(MetricTags.IntegrationName.CiAppManual);
Expand Down
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/Ci/TestSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ _testOptimization.SkippableFeature is { } sf
tags.SetCIEnvironmentValues(ciValues);

var span = Tracer.Instance.StartSpan(
string.IsNullOrEmpty(framework) ? "test_session" : $"{framework!.ToLowerInvariant()}.test_session",
string.IsNullOrEmpty(framework) ? "test_session" : $"{StringUtil.ToLowerInvariant(framework)}.test_session",
tags: tags,
startTime: startDate);
TelemetryFactory.Metrics.RecordCountSpanCreated(MetricTags.IntegrationName.CiAppManual);
Expand Down
2 changes: 1 addition & 1 deletion tracer/src/Datadog.Trace/Ci/TestSuite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal TestSuite(TestModule module, string name, DateTimeOffset? startDate)

var tags = new TestSuiteSpanTags(module.Tags, name);
var span = Tracer.Instance.StartSpan(
string.IsNullOrEmpty(module.Framework) ? "test_suite" : $"{module.Framework!.ToLowerInvariant()}.test_suite",
string.IsNullOrEmpty(module.Framework) ? "test_suite" : $"{StringUtil.ToLowerInvariant(module.Framework)}.test_suite",
tags: tags,
startTime: startDate);
TelemetryFactory.Metrics.RecordCountSpanCreated(MetricTags.IntegrationName.CiAppManual);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ internal static TResponse OnAsyncMethodEnd<TTarget, TResponse>(TTarget instance,
{
if (state.State is IExecutionContext { RequestContext.Request: { } request })
{
tags.HttpMethod = request.HttpMethod?.ToUpperInvariant();
tags.HttpMethod = StringUtil.ToUpperInvariant(request.HttpMethod);
if (tags.HttpUrl is null)
{
var uri = request.Endpoint;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ internal static CallTargetReturn<TResponseContext> OnMethodEnd<TTarget, TRespons
{
if (state.State is IExecutionContext { RequestContext.Request: { } request })
{
tags.HttpMethod = request.HttpMethod?.ToUpperInvariant();
tags.HttpMethod = StringUtil.ToUpperInvariant(request.HttpMethod);
if (tags.HttpUrl is null)
{
var uri = request.Endpoint;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,12 @@ public static bool TryGetIntegrationDetails(
_ when namespaceName.Contains(".") && commandTypeName == commandSuffix =>
// the + 1 could be dangerous and cause IndexOutOfRangeException, but this shouldn't happen
// a period should never be the last character in a namespace
namespaceName.Substring(namespaceName.LastIndexOf('.') + 1).ToLowerInvariant(),
StringUtil.ToLowerInvariant(namespaceName.Substring(namespaceName.LastIndexOf('.') + 1)),
_ when commandTypeName == commandSuffix =>
namespaceName.ToLowerInvariant(),
StringUtil.ToLowerInvariant(namespaceName),
_ when commandTypeName.EndsWith(commandSuffix) =>
commandTypeName.Substring(0, commandTypeName.Length - commandSuffix.Length).ToLowerInvariant(),
_ => commandTypeName.ToLowerInvariant()
StringUtil.ToLowerInvariant(commandTypeName.Substring(0, commandTypeName.Length - commandSuffix.Length)),
_ => StringUtil.ToLowerInvariant(commandTypeName)
};
return true;
}
Expand Down
Loading
Loading