Skip to content

Commit

Permalink
Consistently use #if NET (#971)
Browse files Browse the repository at this point in the history
  • Loading branch information
MihaZupan authored May 3, 2021
1 parent 80193a6 commit 0ef7c7c
Show file tree
Hide file tree
Showing 17 changed files with 44 additions and 52 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if NET5_0_OR_GREATER
#if NET

using Yarp.ReverseProxy.Telemetry.Consumption;
using Prometheus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if NET5_0_OR_GREATER
#if NET

using System;
using Yarp.ReverseProxy.Telemetry.Consumption;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if NET5_0_OR_GREATER
#if NET
using System;
using Yarp.ReverseProxy.Telemetry.Consumption;
using Prometheus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static IServiceCollection AddPrometheusProxyMetrics(this IServiceCollecti
return services;
}

#if NET5_0_OR_GREATER
#if NET
public static IServiceCollection AddPrometheusDnsMetrics(this IServiceCollection services)
{
services.AddTelemetryListeners();
Expand Down Expand Up @@ -48,7 +48,7 @@ public static IServiceCollection AddPrometheusSocketsMetrics(this IServiceCollec
public static IServiceCollection AddAllPrometheusMetrics(this IServiceCollection services)
{
services.AddPrometheusProxyMetrics();
#if NET5_0_OR_GREATER
#if NET
services.AddPrometheusDnsMetrics();
services.AddPrometheusKestrelMetrics();
services.AddPrometheusOutboundHttpMetrics();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if NET5_0_OR_GREATER
#if NET

using Yarp.ReverseProxy.Telemetry.Consumption;
using Prometheus;
Expand Down
2 changes: 1 addition & 1 deletion src/ReverseProxy.Kubernetes.Protocol/Receiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public override async Task RunAsync(CancellationToken cancellationToken)

try
{
#if NET5_0
#if NET
using var stream = await client.GetStreamAsync(_options.ControllerUrl, cancellationToken).ConfigureAwait(false);
#else
using var stream = await client.GetStreamAsync(_options.ControllerUrl).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ internal static List<RouteConfig> BuildRoutes(Uri serviceName, Dictionary<string
}
else if (propertyName.Equals("Values", StringComparison.Ordinal))
{
#if NET5_0
#if NET
headerMatches[headerIndex].Values = kvp.Value.Split(',', StringSplitOptions.TrimEntries);
#elif NETCOREAPP3_1
headerMatches[headerIndex].Values = kvp.Value.Split(',').Select(val => val.Trim()).ToList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Yarp.ReverseProxy.Telemetry.Consumption
/// </summary>
public interface IKestrelTelemetryConsumer
{
#if NET5_0
#if NET
/// <summary>
/// Called at the start of a request.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@

namespace Yarp.ReverseProxy.Telemetry.Consumption
{
#if !NET5_0
#if !NET
internal interface IKestrelMetricsConsumer { }
#endif

internal sealed class KestrelEventListenerService : EventListenerService<KestrelEventListenerService, IKestrelTelemetryConsumer, IKestrelMetricsConsumer>
{
#if NET5_0
#if NET
private KestrelMetrics _previousMetrics;
private KestrelMetrics _currentMetrics = new();
private int _eventCountersCount;
Expand All @@ -34,7 +34,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData)

if (eventData.EventId < MinEventId || eventData.EventId > MaxEventId)
{
#if NET5_0
#if NET
if (eventData.EventId == -1)
{
OnEventCounters(eventData);
Expand All @@ -51,7 +51,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData)

var payload = eventData.Payload;

#if NET5_0
#if NET
switch (eventData.EventId)
{
case 3:
Expand Down Expand Up @@ -114,7 +114,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData)
#endif
}

#if NET5_0
#if NET
private void OnEventCounters(EventWrittenEventArgs eventData)
{
if (MetricsConsumers is null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Microsoft.Extensions.DependencyInjection
{
public static class TelemetryConsumptionExtensions
{
#if NET5_0
#if NET
/// <summary>
/// Registers all telemetry listeners (Proxy, Kestrel, Http, NameResolution, NetSecurity and Sockets).
/// </summary>
Expand All @@ -22,7 +22,7 @@ public static IServiceCollection AddTelemetryListeners(this IServiceCollection s
{
services.AddHostedService<ProxyEventListenerService>();
services.AddHostedService<KestrelEventListenerService>();
#if NET5_0
#if NET
services.AddHostedService<HttpEventListenerService>();
services.AddHostedService<NameResolutionEventListenerService>();
services.AddHostedService<NetSecurityEventListenerService>();
Expand Down Expand Up @@ -50,7 +50,7 @@ public static IServiceCollection AddTelemetryConsumer(this IServiceCollection se
implementsAny = true;
}

#if NET5_0
#if NET
if (consumer is IHttpTelemetryConsumer)
{
services.TryAddEnumerable(new ServiceDescriptor(typeof(IHttpTelemetryConsumer), consumer));
Expand Down Expand Up @@ -106,7 +106,7 @@ public static IServiceCollection AddTelemetryConsumer<TConsumer>(this IServiceCo
implementsAny = true;
}

#if NET5_0
#if NET
if (typeof(IHttpTelemetryConsumer).IsAssignableFrom(typeof(TConsumer)))
{
services.AddSingleton(services => (IHttpTelemetryConsumer)services.GetRequiredService<TConsumer>());
Expand Down
4 changes: 2 additions & 2 deletions src/ReverseProxy/Configuration/CertificateConfigLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public X509Certificate2 LoadCertificate(IConfigurationSection certificateSection
}
else
{
#if NET5_0
#if NET
return LoadPEMCertificate(certificateConfig, certificatePath);
#elif NETCOREAPP3_1
throw new NotSupportedException("PEM certificate format is only supported on .NET 5 or higher.");
Expand All @@ -72,7 +72,7 @@ public X509Certificate2 LoadCertificate(IConfigurationSection certificateSection
throw new ArgumentException($"Passed {nameof(CertificateConfigData)} doesn't define a certificate in any known format.");
}

#if NET5_0
#if NET
private X509Certificate2 LoadPEMCertificate(CertificateConfigData certificateConfig, string certificatePath)
{
var certificateKeyPath = Path.Combine(_hostEnvironment.ContentRootPath, certificateConfig.KeyPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public QueryString QueryString
return _originalQueryString;
}

#if NET5_0
#if NET
var queryBuilder = new QueryBuilder(_modifiedQueryParameters);
#elif NETCOREAPP3_1
var queryBuilder = new QueryBuilder(_modifiedQueryParameters.SelectMany(kvp => kvp.Value, (kvp, v) => KeyValuePair.Create(kvp.Key, v)));
Expand Down
6 changes: 3 additions & 3 deletions src/ReverseProxy/Utilities/ProtocolHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Yarp.ReverseProxy
{
internal static class ProtocolHelper
{
#if NET5_0
#if NET
internal static readonly Version Http2Version = HttpVersion.Version20;
internal static readonly Version Http11Version = HttpVersion.Version11;
#elif NETCOREAPP3_1
Expand All @@ -22,7 +22,7 @@ internal static class ProtocolHelper

public static bool IsHttp2(string protocol)
{
#if NET5_0
#if NET
return Microsoft.AspNetCore.Http.HttpProtocol.IsHttp2(protocol);
#elif NETCOREAPP3_1
return StringComparer.OrdinalIgnoreCase.Equals("HTTP/2", protocol);
Expand All @@ -33,7 +33,7 @@ public static bool IsHttp2(string protocol)

public static bool IsHttp2OrGreater(string protocol)
{
#if NET5_0
#if NET
return Microsoft.AspNetCore.Http.HttpProtocol.IsHttp2(protocol) || Microsoft.AspNetCore.Http.HttpProtocol.IsHttp3(protocol);
#elif NETCOREAPP3_1
return StringComparer.OrdinalIgnoreCase.Equals("HTTP/2", protocol) || StringComparer.OrdinalIgnoreCase.Equals("HTTP/3", protocol);
Expand Down
18 changes: 5 additions & 13 deletions src/ReverseProxy/Utilities/TlsFrameHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ public enum ApplicationProtocolInfo
None = 0,
Http11 = 1,
Http2 = 2,
Http3 = 4,
Other = 128
}

Expand Down Expand Up @@ -168,8 +167,8 @@ public override string ToString()
private const int ProtocolVersionTlsMajorValue = 3;

// Per spec "AllowUnassigned flag MUST be set". See comment above DecodeString() for more details.
private static readonly IdnMapping IdnMapping = new IdnMapping() { AllowUnassigned = true };
private static readonly Encoding Utf8Encoding = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());
private static readonly IdnMapping s_idnMapping = new IdnMapping() { AllowUnassigned = true };
private static readonly Encoding s_encoding = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());

public static bool TryGetFrameHeader(ReadOnlySpan<byte> frame, ref TlsFrameHeader header)
{
Expand Down Expand Up @@ -207,7 +206,7 @@ public static int GetFrameSize(ReadOnlySpan<byte> frame)
{
if (frame.Length < 5 || frame[1] < 3)
{
return - 1;
return -1;
}

return ((frame[3] << 8) | frame[4]) + HeaderSize;
Expand Down Expand Up @@ -566,7 +565,6 @@ private static bool TryGetSniFromServerNameList(ReadOnlySpan<byte> serverNameLis
}

// Following can underflow but it is ok due to equality check below
int hostNameStructLength = BinaryPrimitives.ReadUInt16BigEndian(serverName) - sizeof(NameType);
NameType nameType = (NameType)serverName[NameTypeOffset];
ReadOnlySpan<byte> hostNameStruct = serverName.Slice(HostNameStructOffset);
if (nameType != NameType.HostName)
Expand Down Expand Up @@ -677,12 +675,6 @@ private static bool TryGetApplicationProtocolsFromExtension(ReadOnlySpan<byte> e
{
alpn |= ApplicationProtocolInfo.Http2;
}
#if NET5
else if (protocol.SequenceEqual(SslApplicationProtocol.Http3.Protocol.Span))
{
alpn |= ApplicationProtocolInfo.Http3;
}
#endif
else
{
alpn |= ApplicationProtocolInfo.Other;
Expand Down Expand Up @@ -740,7 +732,7 @@ private static SslProtocols TlsMinorVersionToProtocol(byte value)
string idnEncodedString;
try
{
idnEncodedString = Utf8Encoding.GetString(bytes);
idnEncodedString = s_encoding.GetString(bytes);
}
catch (DecoderFallbackException)
{
Expand All @@ -749,7 +741,7 @@ private static SslProtocols TlsMinorVersionToProtocol(byte value)

try
{
return IdnMapping.GetUnicode(idnEncodedString);
return s_idnMapping.GetUnicode(idnEncodedString);
}
catch (ArgumentException)
{
Expand Down
24 changes: 12 additions & 12 deletions test/ReverseProxy.FunctionalTests/TelemetryConsumptionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ private static void Register(IServiceCollection services, RegistrationApproach a
services.AddSingleton<TelemetryConsumer>();
services.AddSingleton(services => (IProxyTelemetryConsumer)services.GetRequiredService<TelemetryConsumer>());
services.AddSingleton(services => (IKestrelTelemetryConsumer)services.GetRequiredService<TelemetryConsumer>());
#if NET5_0
#if NET
services.AddSingleton(services => (IHttpTelemetryConsumer)services.GetRequiredService<TelemetryConsumer>());
services.AddSingleton(services => (INameResolutionTelemetryConsumer)services.GetRequiredService<TelemetryConsumer>());
services.AddSingleton(services => (INetSecurityTelemetryConsumer)services.GetRequiredService<TelemetryConsumer>());
Expand All @@ -58,7 +58,7 @@ private static void Register(IServiceCollection services, RegistrationApproach a
services.AddSingleton<SecondTelemetryConsumer>();
services.AddSingleton(services => (IProxyTelemetryConsumer)services.GetRequiredService<SecondTelemetryConsumer>());
services.AddSingleton(services => (IKestrelTelemetryConsumer)services.GetRequiredService<SecondTelemetryConsumer>());
#if NET5_0
#if NET
services.AddSingleton(services => (IHttpTelemetryConsumer)services.GetRequiredService<SecondTelemetryConsumer>());
services.AddSingleton(services => (INameResolutionTelemetryConsumer)services.GetRequiredService<SecondTelemetryConsumer>());
services.AddSingleton(services => (INetSecurityTelemetryConsumer)services.GetRequiredService<SecondTelemetryConsumer>());
Expand Down Expand Up @@ -105,7 +105,7 @@ await test.Invoke(async uri =>
"OnProxyInvoke",
"OnProxyStart",
"OnProxyStage-SendAsyncStart",
#if NET5_0
#if NET
"OnRequestStart",
"OnConnectStart",
"OnConnectStop",
Expand All @@ -132,7 +132,7 @@ await test.Invoke(async uri =>
}
}

#if NET5_0
#if NET
[Theory]
[InlineData(RegistrationApproach.WithInstanceHelper)]
[InlineData(RegistrationApproach.WithGenericHelper)]
Expand Down Expand Up @@ -179,7 +179,7 @@ private class SecondTelemetryConsumer : TelemetryConsumer { }
private class TelemetryConsumer :
IProxyTelemetryConsumer,
IKestrelTelemetryConsumer
#if NET5_0
#if NET
,
IHttpTelemetryConsumer,
INameResolutionTelemetryConsumer,
Expand Down Expand Up @@ -213,7 +213,7 @@ public void OnProxyInvoke(DateTime timestamp, string clusterId, string routeId,
AddStage(nameof(OnProxyInvoke), timestamp);
PerClusterTelemetry.TryAdd((clusterId, GetType()), _stages.Value);
}
#if NET5_0
#if NET
public void OnRequestStart(DateTime timestamp, string scheme, string host, int port, string pathAndQuery, int versionMajor, int versionMinor, HttpVersionPolicy versionPolicy)
{
AddStage(nameof(OnRequestStart), timestamp);
Expand Down Expand Up @@ -263,7 +263,7 @@ public async Task MetricsConsumptionWorks()
var services = proxyBuilder.Services;

services.AddSingleton<IProxyMetricsConsumer>(consumer);
#if NET5_0
#if NET
services.AddSingleton<IKestrelMetricsConsumer>(consumer);
services.AddSingleton<IHttpMetricsConsumer>(consumer);
services.AddSingleton<ISocketsMetricsConsumer>(consumer);
Expand All @@ -290,7 +290,7 @@ await test.Invoke(async uri =>

await Task.WhenAll(
WaitAsync(() => consumer.ProxyMetrics.LastOrDefault()?.RequestsStarted > 0, nameof(ProxyMetrics))
#if NET5_0
#if NET
,
WaitAsync(() => consumer.KestrelMetrics.LastOrDefault()?.TotalConnections > 0, nameof(KestrelMetrics)),
WaitAsync(() => consumer.HttpMetrics.LastOrDefault()?.RequestsStarted > 0, nameof(HttpMetrics)),
Expand All @@ -302,7 +302,7 @@ await Task.WhenAll(
});

VerifyTimestamp(consumer.ProxyMetrics.Last().Timestamp);
#if NET5_0
#if NET
VerifyTimestamp(consumer.KestrelMetrics.Last().Timestamp);
VerifyTimestamp(consumer.HttpMetrics.Last().Timestamp);
VerifyTimestamp(consumer.SocketsMetrics.Last().Timestamp);
Expand Down Expand Up @@ -332,7 +332,7 @@ static async Task WaitAsync(Func<bool> condition, string name)

private sealed class MetricsConsumer :
IProxyMetricsConsumer
#if NET5_0
#if NET
,
IKestrelMetricsConsumer,
IHttpMetricsConsumer,
Expand All @@ -342,7 +342,7 @@ private sealed class MetricsConsumer :
#endif
{
public readonly ConcurrentQueue<ProxyMetrics> ProxyMetrics = new ConcurrentQueue<ProxyMetrics>();
#if NET5_0
#if NET
public readonly ConcurrentQueue<KestrelMetrics> KestrelMetrics = new();
public readonly ConcurrentQueue<HttpMetrics> HttpMetrics = new();
public readonly ConcurrentQueue<SocketsMetrics> SocketsMetrics = new();
Expand All @@ -351,7 +351,7 @@ private sealed class MetricsConsumer :
#endif

public void OnProxyMetrics(ProxyMetrics oldMetrics, ProxyMetrics newMetrics) => ProxyMetrics.Enqueue(newMetrics);
#if NET5_0
#if NET
public void OnKestrelMetrics(KestrelMetrics oldMetrics, KestrelMetrics newMetrics) => KestrelMetrics.Enqueue(newMetrics);
public void OnSocketsMetrics(SocketsMetrics oldMetrics, SocketsMetrics newMetrics) => SocketsMetrics.Enqueue(newMetrics);
public void OnNetSecurityMetrics(NetSecurityMetrics oldMetrics, NetSecurityMetrics newMetrics) => NetSecurityMetrics.Enqueue(newMetrics);
Expand Down
Loading

0 comments on commit 0ef7c7c

Please sign in to comment.