Skip to content

Commit

Permalink
Code clean up across solution (#1530)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK committed Dec 22, 2021
1 parent 7d081d7 commit bce5852
Show file tree
Hide file tree
Showing 97 changed files with 250 additions and 191 deletions.
3 changes: 2 additions & 1 deletion examples/Racer/Server/Services/RacerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
Expand All @@ -29,7 +30,7 @@ public class RacerService : Racer.RacerBase
{
public override async Task ReadySetGo(IAsyncStreamReader<RaceMessage> requestStream, IServerStreamWriter<RaceMessage> responseStream, ServerCallContext context)
{
var raceDuration = TimeSpan.Parse(context.RequestHeaders.Single(h => h.Key == "race-duration").Value);
var raceDuration = TimeSpan.Parse(context.RequestHeaders.GetValue("race-duration"), CultureInfo.InvariantCulture);

// Read incoming messages in a background task
RaceMessage? lastMessageReceived = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public async Task<bool> MoveNext(CancellationToken cancellationToken)
{
_serverCallContext.CancellationToken.ThrowIfCancellationRequested();

if (await _channel.Reader.WaitToReadAsync() &&
if (await _channel.Reader.WaitToReadAsync(cancellationToken) &&
_channel.Reader.TryRead(out var message))
{
Current = message;
Expand Down
3 changes: 2 additions & 1 deletion examples/Worker/Client/Worker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public Worker(ILogger<Worker> logger, Counter.CounterClient counterClient)
public override async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting client streaming call at: {time}", DateTimeOffset.Now);
_clientStreamingCall = _counterClient.AccumulateCount();
// Don't pass cancellation token to the call. The call is completed in StopAsync when service stops.
_clientStreamingCall = _counterClient.AccumulateCount(cancellationToken: CancellationToken.None);

await base.StartAsync(cancellationToken);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected virtual byte[] GetMessageData(HelloReply message)
protected async Task InvokeSayHelloAsync(CallOptions options)
{
var response = await _client!.SayHelloAsync(new HelloRequest { Name = _content }, options).ResponseAsync;

if (response.Message != _content)
{
throw new InvalidOperationException("Unexpected result.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

namespace Grpc.AspNetCore.Microbenchmarks
{
[AttributeUsage(AttributeTargets.Assembly)]
public class DefaultCoreConfigAttribute : Attribute, IConfigSource
{
public IConfig Config => new DefaultCoreConfig();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespace GrpcAspNetCoreServer.Controllers
public class BenchmarkController : Controller
{
[HttpPost("unary")]
public SimpleResponse Post([FromBody]SimpleRequest request)
public SimpleResponse Post([FromBody] SimpleRequest request)
{
return BenchmarkServiceImpl.CreateResponse(request);
}
Expand Down
2 changes: 1 addition & 1 deletion perf/benchmarkapps/GrpcAspNetCoreServer/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public void Configure(IApplicationBuilder app, IHostApplicationLifetime applicat
ConfigureAuthorization(endpoints.MapGrpcService<BenchmarkServiceImpl>());
ConfigureAuthorization(endpoints.MapControllers());
ConfigureAuthorization(endpoints.MapGet("/", context =>
{
return context.Response.WriteAsync("Benchmark Server");
Expand Down
13 changes: 7 additions & 6 deletions perf/benchmarkapps/GrpcClient/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Diagnostics;
using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
Expand All @@ -43,17 +44,17 @@ class Program
private static List<List<double>> _latencyPerConnection = null!;
private static int _callsStarted;
private static double _maxLatency;
private static Stopwatch _workTimer = new Stopwatch();
private static readonly Stopwatch _workTimer = new Stopwatch();
private static volatile bool _warmingUp;
private static volatile bool _stopped;
private static SemaphoreSlim _lock = new SemaphoreSlim(1);
private static readonly SemaphoreSlim _lock = new SemaphoreSlim(1);
private static List<(double sum, int count)> _latencyAverage = null!;
private static int _totalRequests;
private static ClientOptions _options = null!;
private static ILoggerFactory? _loggerFactory;
private static SslCredentials? _credentials;
private static StringBuilder _errorStringBuilder = new StringBuilder();
private static CancellationTokenSource _cts = new CancellationTokenSource();
private static readonly StringBuilder _errorStringBuilder = new StringBuilder();
private static readonly CancellationTokenSource _cts = new CancellationTokenSource();

public static async Task<int> Main(string[] args)
{
Expand Down Expand Up @@ -170,7 +171,7 @@ private static async Task StartScenario()
var text = "Exception from test: " + ex.Message;
Log(text);
_errorStringBuilder.AppendLine();
_errorStringBuilder.Append($"[{DateTime.Now:hh:mm:ss.fff}] {text}");
_errorStringBuilder.Append(CultureInfo.InvariantCulture, $"[{DateTime.Now:hh:mm:ss.fff}] {text}");
}
}

Expand Down Expand Up @@ -463,7 +464,7 @@ private static SslCredentials GetSslCredentials()

private static void Log(string message)
{
var time = DateTime.Now.ToString("hh:mm:ss.fff");
var time = DateTime.Now.ToString("hh:mm:ss.fff", CultureInfo.InvariantCulture);
Console.WriteLine($"[{time}] {message}");
}

Expand Down
4 changes: 2 additions & 2 deletions perf/benchmarkapps/Shared/BenchmarkServiceImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

#endregion

using Grpc.Testing;
using Grpc.Core;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Testing;

class BenchmarkServiceImpl : BenchmarkService.BenchmarkServiceBase
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public ContextPropagationInterceptor(IOptions<GrpcContextPropagationOptions> opt
return new ClientInterceptorContext<TRequest, TResponse>(context.Method, context.Host, options);
}

private bool TryGetServerCallContext([NotNullWhen(true)]out ServerCallContext? serverCallContext, [NotNullWhen(false)]out string? errorMessage)
private bool TryGetServerCallContext([NotNullWhen(true)] out ServerCallContext? serverCallContext, [NotNullWhen(false)] out string? errorMessage)
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@
"000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02ba" +
"a56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667" +
"bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6" +
"a7d3113e92484cf7045cc7")]
"a7d3113e92484cf7045cc7")]
2 changes: 1 addition & 1 deletion src/Grpc.AspNetCore.Server/GrpcServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static IGrpcServerBuilder AddGrpc(this IServiceCollection services)
services.TryAddSingleton(typeof(IGrpcServiceActivator<>), typeof(DefaultGrpcServiceActivator<>));
services.TryAddSingleton(typeof(IGrpcInterceptorActivator<>), typeof(DefaultGrpcInterceptorActivator<>));
services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<GrpcServiceOptions>, GrpcServiceOptionsSetup>());

// Model
services.TryAddSingleton<ServiceMethodsRegistry>();
services.TryAddSingleton(typeof(ServiceRouteBuilder<>));
Expand Down
4 changes: 2 additions & 2 deletions src/Grpc.AspNetCore.Server/Internal/GrpcProtocolHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public static bool TryDecodeTimeout(StringValues values, out TimeSpan timeout)
return false;
}

public static bool IsInvalidContentType(HttpContext httpContext, [NotNullWhen(true)]out string? error)
public static bool IsInvalidContentType(HttpContext httpContext, [NotNullWhen(true)] out string? error)
{
if (httpContext.Request.ContentType == null)
{
Expand All @@ -95,7 +95,7 @@ public static bool IsCorsPreflightRequest(HttpContext httpContext)
return HttpMethods.IsOptions(httpContext.Request.Method) &&
httpContext.Request.Headers.ContainsKey(HeaderNames.AccessControlRequestMethod);
}

public static void BuildHttpErrorResponse(HttpResponse response, int httpStatusCode, StatusCode grpcStatusCode, string message)
{
response.StatusCode = httpStatusCode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void Configure(GrpcServiceOptions options)
}
}

internal class GrpcServiceOptionsSetup<TService> : IConfigureOptions<GrpcServiceOptions<TService>> where TService: class
internal class GrpcServiceOptionsSetup<TService> : IConfigureOptions<GrpcServiceOptions<TService>> where TService : class
{
private readonly GrpcServiceOptions _options;

Expand Down
4 changes: 2 additions & 2 deletions src/Grpc.AspNetCore.Server/Internal/PercentEncodingHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public static string PercentEncode(string value)
}

// Encode
return string.Create((int) encodedLength, value, Encode);
return string.Create((int)encodedLength, value, Encode);

static void Encode(Span<char> span, string s)
{
Expand All @@ -86,7 +86,7 @@ static void Encode(Span<char> span, string s)
if (current > AsciiMaxValue)
{
// Leave a character for possible low surrogate
const int MaxCount = MaxUnicodeCharsReallocate -1;
const int MaxCount = MaxUnicodeCharsReallocate - 1;

// Get additional unicode characters
var unicodeCharCount = GetCountOfNonAsciiUtf16CodeUnits(s, i, MaxCount);
Expand Down
4 changes: 2 additions & 2 deletions src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ public static async ValueTask<T> ReadSingleMessageAsync<T>(this PipeReader input
}
}

private static bool TryReadMessage(ref ReadOnlySequence<byte> buffer, HttpContextServerCallContext context, [NotNullWhen(true)]out ReadOnlySequence<byte>? message)
private static bool TryReadMessage(ref ReadOnlySequence<byte> buffer, HttpContextServerCallContext context, [NotNullWhen(true)] out ReadOnlySequence<byte>? message)
{
if (!TryReadHeader(buffer, out var compressed, out var messageLength))
{
Expand Down Expand Up @@ -392,7 +392,7 @@ private static bool TryReadMessage(ref ReadOnlySequence<byte> buffer, HttpContex
return true;
}

private static bool TryDecompressMessage(ILogger logger, string compressionEncoding, IReadOnlyDictionary<string, ICompressionProvider> compressionProviders, in ReadOnlySequence<byte> messageData, [NotNullWhen(true)]out ReadOnlySequence<byte>? result)
private static bool TryDecompressMessage(ILogger logger, string compressionEncoding, IReadOnlyDictionary<string, ICompressionProvider> compressionProviders, in ReadOnlySequence<byte> messageData, [NotNullWhen(true)] out ReadOnlySequence<byte>? result)
{
if (compressionProviders.TryGetValue(compressionEncoding, out var compressionProvider))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ internal class ReadOnlySequenceStream : Stream
private static readonly Task<int> TaskOfZero = Task.FromResult(0);

private Task<int>? _lastReadTask;
private ReadOnlySequence<byte> _readOnlySequence;
private readonly ReadOnlySequence<byte> _readOnlySequence;
private SequencePosition _position;

public ReadOnlySequenceStream(ReadOnlySequence<byte> readOnlySequence)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public RequestDelegate CreateUnimplementedMethod()
}

public bool IgnoreUnknownServices => _globalOptions.IgnoreUnknownServices ?? false;
public bool IgnoreUnknownMethods => _serviceOptions.IgnoreUnknownServices ?? _globalOptions.IgnoreUnknownServices ?? false;
public bool IgnoreUnknownMethods => _serviceOptions.IgnoreUnknownServices ?? _globalOptions.IgnoreUnknownServices ?? false;

public RequestDelegate CreateUnimplementedService()
{
Expand Down
2 changes: 1 addition & 1 deletion src/Grpc.AspNetCore.Server/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@
"000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02ba" +
"a56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667" +
"bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6" +
"a7d3113e92484cf7045cc7")]
"a7d3113e92484cf7045cc7")]
2 changes: 1 addition & 1 deletion src/Grpc.AspNetCore.Web/Internal/Base64PipeReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public override void Complete(Exception? exception = null)
_currentDecodedBuffer = ReadOnlySequence<byte>.Empty;
}

public async override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
public override async ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
{
// ReadAsync needs to handle some common situations:
// 1. Base64 requires are least 4 bytes to decode content. If less than 4 bytes are returned
Expand Down
2 changes: 1 addition & 1 deletion src/Grpc.AspNetCore.Web/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@
"000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02ba" +
"a56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667" +
"bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6" +
"a7d3113e92484cf7045cc7")]
"a7d3113e92484cf7045cc7")]
4 changes: 2 additions & 2 deletions src/Grpc.Net.Client.Web/Internal/GrpcWebResponseStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ internal static ReadOnlySpan<byte> Trim(ReadOnlySpan<byte> span)
var startIndex = -1;
for (var i = 0; i < span.Length; i++)
{
if (!char.IsWhiteSpace((char) span[i]))
if (!char.IsWhiteSpace((char)span[i]))
{
startIndex = i;
break;
Expand All @@ -220,7 +220,7 @@ internal static ReadOnlySpan<byte> Trim(ReadOnlySpan<byte> span)
var endIndex = span.Length - 1;
for (var i = endIndex; i >= startIndex; i--)
{
if (!char.IsWhiteSpace((char) span[i]))
if (!char.IsWhiteSpace((char)span[i]))
{
endIndex = i;
break;
Expand Down
4 changes: 2 additions & 2 deletions src/Grpc.Net.Client.Web/Internal/OperatingSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ internal interface IOperatingSystem
internal class OperatingSystem : IOperatingSystem
{
public static readonly OperatingSystem Instance = new OperatingSystem();

public bool IsBrowser { get; }

private OperatingSystem()
{
IsBrowser = RuntimeInformation.IsOSPlatform(OSPlatform.Create("browser"));
Expand Down
2 changes: 1 addition & 1 deletion src/Grpc.Net.Client.Web/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@
"000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02ba" +
"a56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667" +
"bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6" +
"a7d3113e92484cf7045cc7")]
"a7d3113e92484cf7045cc7")]
21 changes: 11 additions & 10 deletions src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -451,29 +451,30 @@ internal Task WaitForStateChangedAsync(ConnectivityState lastObservedState, Conn
}
}

return WaitForStateChangedAsyncCore(watcher, cancellationToken);
return WaitForStateChangedAsyncCore(watcher);
}

private async Task WaitForStateChangedAsyncCore(StateWatcher watcher, CancellationToken cancellationToken)
private async Task WaitForStateChangedAsyncCore(StateWatcher watcher)
{
using (cancellationToken.Register(OnCancellation, watcher))
using (watcher.CancellationToken.Register(OnCancellation, watcher))
{
await watcher.Tcs.Task.ConfigureAwait(false);
}
}

void OnCancellation(object? s)
private void OnCancellation(object? s)
{
lock (_lock)
{
lock (_lock)
StateWatcher watcher = (StateWatcher)s!;
if (_stateWatchers.Remove(watcher))
{
StateWatcher watcher = (StateWatcher)s!;
if (_stateWatchers.Remove(watcher))
{
watcher.Tcs.SetCanceled();
}
watcher.Tcs.SetCanceled(watcher.CancellationToken);
}
}
}

// Don't use a record struct here. This type is cast to object and a struct will box.
private record StateWatcher(CancellationToken CancellationToken, ConnectivityState? WaitForState, TaskCompletionSource<object?> Tcs);
}

Expand Down
32 changes: 19 additions & 13 deletions src/Grpc.Net.Client/Internal/Configuration/ConvertHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,29 @@ public static StatusCode ConvertStatusCode(string statusCode)
//
// Note that this is precise down to ticks. Fractions that are smaller than ticks will be lost.
// This shouldn't matter because timers on Windows and Linux only have millisecond precision.
if (text.Length > 0 && text[text.Length - 1] == 's' &&
decimal.TryParse(text.Substring(0, text.Length - 1), NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
if (text.Length > 0 && text[text.Length - 1] == 's')
{
try
{
var ticks = (long)(seconds * TimeSpan.TicksPerSecond);
return TimeSpan.FromTicks(ticks);
}
catch (Exception ex)
#if NET5_0_OR_GREATER
var decimalText = text.AsSpan(0, text.Length - 1);
#else
var decimalText = text.Substring(0, text.Length - 1);
#endif

if (decimal.TryParse(decimalText, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
{
throw new FormatException($"'{text}' isn't a valid duration.", ex);
try
{
var ticks = (long)(seconds * TimeSpan.TicksPerSecond);
return TimeSpan.FromTicks(ticks);
}
catch (Exception ex)
{
throw new FormatException($"'{text}' isn't a valid duration.", ex);
}
}
}
else
{
throw new FormatException($"'{text}' isn't a valid duration.");
}

throw new FormatException($"'{text}' isn't a valid duration.");
}

public static string? ToDurationText(TimeSpan? value)
Expand Down
Loading

0 comments on commit bce5852

Please sign in to comment.