Skip to content

Commit

Permalink
Change nullable GetValueOrDefault to Value (#1855)
Browse files Browse the repository at this point in the history
Co-authored-by: Günther Foidl <[email protected]>
  • Loading branch information
JamesNK and gfoidl authored Aug 24, 2022
1 parent 77ae8af commit 4f06b60
Show file tree
Hide file tree
Showing 17 changed files with 106 additions and 67 deletions.
1 change: 1 addition & 0 deletions src/Grpc.AspNetCore.Server/Grpc.AspNetCore.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<Compile Include="..\Shared\Server\ServerMethodInvokerBase.cs" Link="Model\Internal\ServerMethodInvokerBase.cs" />
<Compile Include="..\Shared\Server\ServerStreamingServerMethodInvoker.cs" Link="Model\Internal\ServerStreamingServerMethodInvoker.cs" />
<Compile Include="..\Shared\Server\UnaryServerMethodInvoker.cs" Link="Model\Internal\UnaryServerMethodInvoker.cs" />
<Compile Include="..\Shared\NullableAttributes.cs" Link="Internal\NullableAttributes.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,20 @@ internal sealed class HttpContextSerializationContext : SerializationContext

public PipeWriter ResponseBufferWriter { get; set; } = default!;

private bool DirectSerializationSupported => _compressionProvider == null && _payloadLength != null;
private bool IsDirectSerializationSupported(out int payloadLength)
{
// Message can be written directly to the buffer if:
// - Its length is known.
// - There is no compression.
if (_payloadLength != null)
{
payloadLength = _payloadLength.Value;
return _compressionProvider == null;
}

payloadLength = 0;
return false;
}

public HttpContextSerializationContext(HttpContextServerCallContext serverCallContext)
{
Expand Down Expand Up @@ -130,13 +143,11 @@ public override IBufferWriter<byte> GetBufferWriter()
{
case InternalState.Initialized:
// When writing directly to the buffer the header with message size needs to be written first
if (DirectSerializationSupported)
if (IsDirectSerializationSupported(out var payloadLength))
{
Debug.Assert(_payloadLength != null, "A payload length is required for direct serialization.");
EnsureMessageSizeAllowed(payloadLength);

EnsureMessageSizeAllowed(_payloadLength.Value);

WriteHeader(ResponseBufferWriter, _payloadLength.Value, compress: false);
WriteHeader(ResponseBufferWriter, payloadLength, compress: false);
}

_state = InternalState.IncompleteBufferWriter;
Expand All @@ -151,9 +162,20 @@ public override IBufferWriter<byte> GetBufferWriter()

private IBufferWriter<byte> ResolveBufferWriter()
{
return DirectSerializationSupported
? (IBufferWriter<byte>)ResponseBufferWriter
: _bufferWriter ??= new ArrayBufferWriter<byte>();
if (IsDirectSerializationSupported(out var payloadLength))
{
return ResponseBufferWriter;
}
else if (_bufferWriter == null)
{
// Initialize buffer writer with exact length if available.
// ArrayBufferWriter doesn't allow zero initial length.
_bufferWriter = payloadLength > 0
? new ArrayBufferWriter<byte>(payloadLength)
: new ArrayBufferWriter<byte>();
}

return _bufferWriter;
}

private void EnsureMessageSizeAllowed(int payloadLength)
Expand All @@ -175,7 +197,11 @@ public override void Complete()
case InternalState.IncompleteBufferWriter:
_state = InternalState.CompleteBufferWriter;

if (!DirectSerializationSupported)
if (IsDirectSerializationSupported(out var payloadLength))
{
GrpcServerLog.SerializedMessage(_serverCallContext.Logger, _serverCallContext.ResponseType, payloadLength);
}
else
{
Debug.Assert(_bufferWriter != null, "Buffer writer has been set to get to this state.");

Expand All @@ -184,10 +210,6 @@ public override void Complete()
GrpcServerLog.SerializedMessage(_serverCallContext.Logger, _serverCallContext.ResponseType, data.Length);
WriteMessage(data);
}
else
{
GrpcServerLog.SerializedMessage(_serverCallContext.Logger, _serverCallContext.ResponseType, _payloadLength.GetValueOrDefault());
}
break;
default:
ThrowInvalidState(_state);
Expand Down
14 changes: 7 additions & 7 deletions src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ public static async ValueTask<T> ReadSingleMessageAsync<T>(this PipeReader input
if (TryReadMessage(ref buffer, serverCallContext, out var data))
{
// Finished and the complete message has arrived
GrpcServerLog.DeserializingMessage(logger, (int)data.GetValueOrDefault().Length, typeof(T));
GrpcServerLog.DeserializingMessage(logger, (int)data.Length, typeof(T));

serverCallContext.DeserializationContext.SetPayload(data);
request = deserializer(serverCallContext.DeserializationContext);
Expand Down Expand Up @@ -311,7 +311,7 @@ public static async ValueTask<T> ReadSingleMessageAsync<T>(this PipeReader input
{
completeMessage = true;

GrpcServerLog.DeserializingMessage(logger, (int)data.Value.Length, typeof(T));
GrpcServerLog.DeserializingMessage(logger, (int)data.Length, typeof(T));

serverCallContext.DeserializationContext.SetPayload(data);
var request = deserializer(serverCallContext.DeserializationContext);
Expand Down Expand Up @@ -361,11 +361,11 @@ 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, out ReadOnlySequence<byte> message)
{
if (!TryReadHeader(buffer, out var compressed, out var messageLength))
{
message = null;
message = default;
return false;
}

Expand All @@ -376,7 +376,7 @@ private static bool TryReadMessage(ref ReadOnlySequence<byte> buffer, HttpContex

if (buffer.Length < HeaderSize + messageLength)
{
message = null;
message = default;
return false;
}

Expand Down Expand Up @@ -429,7 +429,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, out ReadOnlySequence<byte> result)
{
if (compressionProviders.TryGetValue(compressionEncoding, out var compressionProvider))
{
Expand All @@ -445,7 +445,7 @@ private static bool TryDecompressMessage(ILogger logger, string compressionEncod
return true;
}

result = null;
result = default;
return false;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Grpc.Net.Client.Web/Internal/GrpcWebRequestContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ protected override bool TryComputeLength(out long length)
// to take into account base64 encoding size difference:
// Increase length by 4/3, then round up to the next multiple of 4.
length = _mode == GrpcWebMode.GrpcWebText
? ((4 * contentLength.GetValueOrDefault() / 3) + 3) & ~3
: contentLength.GetValueOrDefault();
? ((4 * contentLength.Value / 3) + 3) & ~3
: contentLength.Value;
return true;
}

Expand Down
5 changes: 2 additions & 3 deletions src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,13 @@ private void OnResolverResult(ResolverResult result)
if (_previousServiceConfig == null)
{
// Step 4.ii: If no config was provided or set previously, then treat resolution as a failure.
channelStatus = result.ServiceConfigStatus.GetValueOrDefault();
channelStatus = result.ServiceConfigStatus.Value;
}
else
{
// Step 4.i: Continue using previous service config if it was set and a new one is not provided.
workingServiceConfig = _previousServiceConfig;
ConnectionManagerLog.ResolverServiceConfigFallback(Logger, result.ServiceConfigStatus.GetValueOrDefault());
ConnectionManagerLog.ResolverServiceConfigFallback(Logger, result.ServiceConfigStatus.Value);
}
}
}
Expand All @@ -165,7 +165,6 @@ private void OnResolverResult(ResolverResult result)
_previousServiceConfig = result.ServiceConfig;
}


if (workingServiceConfig?.LoadBalancingConfigs.Count > 0)
{
if (!ChildHandlerLoadBalancer.TryGetValidServiceConfigFactory(workingServiceConfig.LoadBalancingConfigs, LoadBalancerFactories, out loadBalancingConfig, out var _))
Expand Down
4 changes: 2 additions & 2 deletions src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,11 @@ public override void UpdateChannelState(ChannelState state)
if (i != null)
{
// There is a match so take current subchannel.
newOrCurrentSubchannel = currentSubchannels[i.GetValueOrDefault()];
newOrCurrentSubchannel = currentSubchannels[i.Value];

// Remove from current collection because any subchannels
// remaining in this collection at the end will be disposed.
currentSubchannels.RemoveAt(i.GetValueOrDefault());
currentSubchannels.RemoveAt(i.Value);

SubchannelLog.SubchannelPreserved(_logger, newOrCurrentSubchannel.Subchannel.Id, address);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Grpc.Net.Client/GrpcChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ private ChannelRetryThrottling CreateChannelRetryThrottling(RetryThrottlingPolic
throw CreateException(RetryThrottlingPolicy.TokenRatioPropertyName);
}

return new ChannelRetryThrottling(retryThrottling.MaxTokens.GetValueOrDefault(), retryThrottling.TokenRatio.GetValueOrDefault(), LoggerFactory);
return new ChannelRetryThrottling(retryThrottling.MaxTokens.Value, retryThrottling.TokenRatio.Value, LoggerFactory);

static InvalidOperationException CreateException(string propertyName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public static StatusCode ConvertStatusCode(string statusCode)

// This format is based on the Protobuf duration's JSON mapping.
// https://github.com/protocolbuffers/protobuf/blob/35bdcabdd6a05ce9ee738ad7df8c1299d9c7fc4b/src/google/protobuf/duration.proto#L92
return value.GetValueOrDefault().TotalSeconds.ToString(CultureInfo.InvariantCulture) + "s";
return value.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture) + "s";
}
}
}
41 changes: 26 additions & 15 deletions src/Grpc.Net.Client/Internal/GrpcCallSerializationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,20 @@ internal sealed class GrpcCallSerializationContext : SerializationContext, IBuff
private int? _payloadLength;
private ICompressionProvider? _compressionProvider;

private bool DirectSerializationSupported => _compressionProvider == null && _payloadLength != null;
private bool IsDirectSerializationSupported(out int payloadLength)
{
// Message can be written directly to the buffer if:
// - Its length is known.
// - There is no compression.
if (_payloadLength != null)
{
payloadLength = _payloadLength.Value;
return _compressionProvider == null;
}

payloadLength = 0;
return false;
}

private ArrayBufferWriter<byte>? _bufferWriter;
private byte[]? _buffer;
Expand Down Expand Up @@ -172,13 +185,11 @@ public override IBufferWriter<byte> GetBufferWriter()
var bufferWriter = ResolveBufferWriter();

// When writing directly to the buffer the header with message size needs to be written first
if (DirectSerializationSupported)
if (IsDirectSerializationSupported(out var payloadLength))
{
CompatibilityHelpers.Assert(_payloadLength != null, "A payload length is required for direct serialization.");

EnsureMessageSizeAllowed(_payloadLength.Value);
EnsureMessageSizeAllowed(payloadLength);

WriteHeader(_buffer, _payloadLength.Value, compress: false);
WriteHeader(_buffer, payloadLength, compress: false);
_bufferPosition += GrpcProtocolConstants.HeaderSize;
}

Expand All @@ -194,11 +205,11 @@ public override IBufferWriter<byte> GetBufferWriter()

private IBufferWriter<byte> ResolveBufferWriter()
{
if (DirectSerializationSupported)
if (IsDirectSerializationSupported(out var payloadLength))
{
if (_buffer == null)
{
_buffer = ArrayPool<byte>.Shared.Rent(GrpcProtocolConstants.HeaderSize + _payloadLength.GetValueOrDefault());
_buffer = ArrayPool<byte>.Shared.Rent(GrpcProtocolConstants.HeaderSize + payloadLength);
}

return this;
Expand All @@ -207,8 +218,8 @@ private IBufferWriter<byte> ResolveBufferWriter()
{
// Initialize buffer writer with exact length if available.
// ArrayBufferWriter doesn't allow zero initial length.
_bufferWriter = _payloadLength > 0
? new ArrayBufferWriter<byte>(_payloadLength.GetValueOrDefault())
_bufferWriter = payloadLength > 0
? new ArrayBufferWriter<byte>(payloadLength)
: new ArrayBufferWriter<byte>();
}

Expand All @@ -234,7 +245,11 @@ public override void Complete()
case InternalState.IncompleteBufferWriter:
_state = InternalState.CompleteBufferWriter;

if (!DirectSerializationSupported)
if (IsDirectSerializationSupported(out var payloadLength))
{
GrpcCallLog.SerializedMessage(_call.Logger, _call.RequestType, payloadLength);
}
else
{
CompatibilityHelpers.Assert(_bufferWriter != null, "Buffer writer has been set to get to this state.");

Expand All @@ -243,10 +258,6 @@ public override void Complete()
GrpcCallLog.SerializedMessage(_call.Logger, _call.RequestType, data.Length);
WriteMessage(data);
}
else
{
GrpcCallLog.SerializedMessage(_call.Logger, _call.RequestType, _payloadLength.GetValueOrDefault());
}
break;
default:
ThrowInvalidState(_state);
Expand Down
12 changes: 6 additions & 6 deletions src/Grpc.Net.Client/Internal/GrpcMethodInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ internal static RetryPolicyInfo CreateRetryPolicy(RetryPolicy r)

return new RetryPolicyInfo
{
MaxAttempts = r.MaxAttempts.GetValueOrDefault(),
InitialBackoff = r.InitialBackoff.GetValueOrDefault(),
MaxBackoff = r.MaxBackoff.GetValueOrDefault(),
BackoffMultiplier = r.BackoffMultiplier.GetValueOrDefault(),
MaxAttempts = r.MaxAttempts.Value,
InitialBackoff = r.InitialBackoff.Value,
MaxBackoff = r.MaxBackoff.Value,
BackoffMultiplier = r.BackoffMultiplier.Value,
RetryableStatusCodes = r.RetryableStatusCodes.ToList()
};
}
Expand All @@ -105,8 +105,8 @@ internal static HedgingPolicyInfo CreateHedgingPolicy(HedgingPolicy h)

return new HedgingPolicyInfo
{
MaxAttempts = h.MaxAttempts.GetValueOrDefault(),
HedgingDelay = h.HedgingDelay.GetValueOrDefault(),
MaxAttempts = h.MaxAttempts.Value,
HedgingDelay = h.HedgingDelay ?? TimeSpan.Zero,
NonFatalStatusCodes = h.NonFatalStatusCodes.ToList()
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/Grpc.Net.Client/Internal/GrpcProtocolHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ public static Status CreateStatusFromException(string summary, Exception ex, Sta
var exceptionMessage = CommonGrpcProtocolHelpers.ConvertToRpcExceptionMessage(ex);
statusCode ??= ResolveRpcExceptionStatusCode(ex);

return new Status(statusCode.GetValueOrDefault(), summary + " " + exceptionMessage, ex);
return new Status(statusCode.Value, summary + " " + exceptionMessage, ex);
}
}
}
6 changes: 3 additions & 3 deletions src/Grpc.Net.Client/Internal/Retry/HedgingCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private async Task StartCall(Action<GrpcCall<TRequest, TResponse>> startCallFunc
{
if (retryPushbackMS >= 0)
{
_pushbackDelay = TimeSpan.FromMilliseconds(retryPushbackMS.GetValueOrDefault());
_pushbackDelay = TimeSpan.FromMilliseconds(retryPushbackMS.Value);
}
_delayInterruptTcs.TrySetResult(null);
}
Expand Down Expand Up @@ -348,7 +348,7 @@ private async Task HedgingDelayAsync(TimeSpan hedgingDelay)
if (_pushbackDelay != null)
{
// Use pushback value and delay again
hedgingDelay = _pushbackDelay.GetValueOrDefault();
hedgingDelay = _pushbackDelay.Value;

_pushbackDelay = null;
}
Expand Down Expand Up @@ -426,7 +426,7 @@ await DoClientStreamActionAsync(async calls =>
if (c.TryRegisterCancellation(cancellationToken, out var registration))
{
registrations ??= new List<CancellationTokenRegistration>(calls.Count);
registrations.Add(registration.GetValueOrDefault());
registrations.Add(registration.Value);
}
var writeTask = c.WriteClientStreamAsync(WriteNewMessage, message);
Expand Down
Loading

0 comments on commit 4f06b60

Please sign in to comment.