| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using IceRpc.Transports; |
| | 4 | | using System.Buffers; |
| | 5 | | using System.Collections.Immutable; |
| | 6 | | using System.Diagnostics; |
| | 7 | | using System.IO.Pipelines; |
| | 8 | | using System.Security.Authentication; |
| | 9 | | using ZeroC.Slice; |
| | 10 | |
|
| | 11 | | namespace IceRpc.Internal; |
| | 12 | |
|
| | 13 | | internal sealed class IceRpcProtocolConnection : IProtocolConnection |
| | 14 | | { |
| | 15 | | private const int MaxGoAwayFrameBodySize = 16; |
| | 16 | | private const int MaxSettingsFrameBodySize = 1024; |
| | 17 | |
|
| 2913 | 18 | | private bool IsServer => _transportConnectionInformation is not null; |
| | 19 | |
|
| | 20 | | private Task? _acceptRequestsTask; |
| | 21 | |
|
| | 22 | | private Task? _connectTask; |
| | 23 | | private IConnectionContext? _connectionContext; // non-null once the connection is established |
| | 24 | | private IMultiplexedStream? _controlStream; |
| | 25 | |
|
| | 26 | | // The number of outstanding dispatches and invocations. |
| | 27 | | // DisposeAsync waits until this count reaches 0 (using _dispatchesAndInvocationsCompleted) before disposing the |
| | 28 | | // underlying transport connection. So when this count is greater than 0, we know _transportConnection and other |
| | 29 | | // fields are not disposed. |
| | 30 | | // _dispatchInvocationCount is also used for the inactivity check: the connection remains active while |
| | 31 | | // _dispatchInvocationCount > 0 or _streamInputOutputCount > 0. |
| | 32 | | private int _dispatchInvocationCount; |
| | 33 | |
|
| | 34 | | private readonly SemaphoreSlim? _dispatchSemaphore; |
| | 35 | |
|
| | 36 | | private readonly IDispatcher? _dispatcher; |
| 712 | 37 | | private readonly TaskCompletionSource _dispatchesAndInvocationsCompleted = |
| 712 | 38 | | new(TaskCreationOptions.RunContinuationsAsynchronously); |
| | 39 | |
|
| | 40 | | private Task? _disposeTask; |
| | 41 | |
|
| | 42 | | // This cancellation token source is canceled when the connection is disposed. |
| 712 | 43 | | private readonly CancellationTokenSource _disposedCts = new(); |
| | 44 | |
|
| | 45 | | // Canceled when we receive the GoAway frame from the peer. |
| 712 | 46 | | private readonly CancellationTokenSource _goAwayCts = new(); |
| | 47 | |
|
| | 48 | | // The GoAway frame received from the peer. Read it only after _goAwayCts is canceled. |
| | 49 | | private IceRpcGoAway _goAwayFrame; |
| | 50 | |
|
| | 51 | | // The number of bytes we need to encode a size up to _maxPeerHeaderSize. It's 2 for DefaultMaxIceRpcHeaderSize. |
| 712 | 52 | | private int _headerSizeLength = 2; |
| | 53 | |
|
| | 54 | | private readonly TimeSpan _inactivityTimeout; |
| | 55 | | private readonly Timer _inactivityTimeoutTimer; |
| | 56 | | private string? _invocationRefusedMessage; |
| | 57 | |
|
| | 58 | | // The ID of the last bidirectional stream accepted by this connection. It's null as long as no bidirectional stream |
| | 59 | | // was accepted. |
| | 60 | | private ulong? _lastRemoteBidirectionalStreamId; |
| | 61 | |
|
| | 62 | | // The ID of the last unidirectional stream accepted by this connection. It's null as long as no unidirectional |
| | 63 | | // stream (other than _remoteControlStream) was accepted. |
| | 64 | | private ulong? _lastRemoteUnidirectionalStreamId; |
| | 65 | |
|
| | 66 | | private readonly int _maxLocalHeaderSize; |
| 712 | 67 | | private int _maxPeerHeaderSize = ConnectionOptions.DefaultMaxIceRpcHeaderSize; |
| | 68 | |
|
| 712 | 69 | | private readonly object _mutex = new(); |
| | 70 | |
|
| | 71 | | private Task? _readGoAwayTask; |
| | 72 | |
|
| | 73 | | // A connection refuses invocations when it's disposed, shut down, shutting down or merely "shutdown requested". |
| | 74 | | private bool _refuseInvocations; |
| | 75 | |
|
| | 76 | | private IMultiplexedStream? _remoteControlStream; |
| | 77 | |
|
| | 78 | | private readonly CancellationTokenSource _shutdownOrGoAwayCts; |
| | 79 | |
|
| | 80 | | // The thread that completes this TCS can run the continuations, and as a result its result must be set without |
| | 81 | | // holding a lock on _mutex. |
| 712 | 82 | | private readonly TaskCompletionSource _shutdownRequestedTcs = new(); |
| | 83 | |
|
| | 84 | | private Task? _shutdownTask; |
| | 85 | |
|
| | 86 | | // Keeps track of the number of stream Input and Output that are not completed yet. |
| | 87 | | // It's not the same as the _dispatchInvocationCount: a dispatch or invocation can be completed while the |
| | 88 | | // application is still reading an incoming frame payload that corresponds to a stream input. |
| | 89 | | // ShutdownAsync waits for both _streamInputOutputCount and _dispatchInvocationCount to reach 0, while DisposeAsync |
| | 90 | | // only waits for _dispatchInvocationCount to reach 0. |
| | 91 | | private int _streamInputOutputCount; |
| | 92 | |
|
| | 93 | | // The streams are completed when _shutdownTask is not null and _streamInputOutputCount is 0. |
| 712 | 94 | | private readonly TaskCompletionSource _streamsCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| | 95 | |
|
| | 96 | | private readonly ITaskExceptionObserver? _taskExceptionObserver; |
| | 97 | |
|
| | 98 | | private readonly IMultiplexedConnection _transportConnection; |
| | 99 | |
|
| | 100 | | // Only set for server connections. |
| | 101 | | private readonly TransportConnectionInformation? _transportConnectionInformation; |
| | 102 | |
|
| | 103 | | public Task<(TransportConnectionInformation ConnectionInformation, Task ShutdownRequested)> ConnectAsync( |
| | 104 | | CancellationToken cancellationToken) |
| 698 | 105 | | { |
| | 106 | | Task<(TransportConnectionInformation ConnectionInformation, Task ShutdownRequested)> result; |
| | 107 | |
|
| 698 | 108 | | lock (_mutex) |
| 698 | 109 | | { |
| 698 | 110 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 111 | |
|
| 694 | 112 | | if (_connectTask is not null) |
| 0 | 113 | | { |
| 0 | 114 | | throw new InvalidOperationException("Cannot call connect more than once."); |
| | 115 | | } |
| | 116 | |
|
| 694 | 117 | | result = PerformConnectAsync(); |
| 694 | 118 | | _connectTask = result; |
| 694 | 119 | | } |
| 694 | 120 | | return result; |
| | 121 | |
|
| | 122 | | async Task<(TransportConnectionInformation ConnectionInformation, Task ShutdownRequested)> PerformConnectAsync() |
| 694 | 123 | | { |
| | 124 | | // Make sure we execute the function without holding the connection mutex lock. |
| 694 | 125 | | await Task.Yield(); |
| | 126 | |
|
| | 127 | | // _disposedCts is not disposed at this point because DisposeAsync waits for the completion of _connectTask. |
| 694 | 128 | | using var connectCts = CancellationTokenSource.CreateLinkedTokenSource( |
| 694 | 129 | | cancellationToken, |
| 694 | 130 | | _disposedCts.Token); |
| | 131 | |
|
| | 132 | | TransportConnectionInformation transportConnectionInformation; |
| | 133 | |
|
| | 134 | | try |
| 694 | 135 | | { |
| | 136 | | // If the transport connection information is null, we need to connect the transport connection. It's |
| | 137 | | // null for client connections. The transport connection of a server connection is established by |
| | 138 | | // Server. |
| 694 | 139 | | transportConnectionInformation = _transportConnectionInformation ?? |
| 694 | 140 | | await _transportConnection.ConnectAsync(connectCts.Token).ConfigureAwait(false); |
| | 141 | |
|
| 644 | 142 | | _controlStream = await _transportConnection.CreateStreamAsync( |
| 644 | 143 | | false, |
| 644 | 144 | | connectCts.Token).ConfigureAwait(false); |
| | 145 | |
|
| 633 | 146 | | var settings = new IceRpcSettings( |
| 633 | 147 | | _maxLocalHeaderSize == ConnectionOptions.DefaultMaxIceRpcHeaderSize ? |
| 633 | 148 | | ImmutableDictionary<IceRpcSettingKey, ulong>.Empty : |
| 633 | 149 | | new Dictionary<IceRpcSettingKey, ulong> |
| 633 | 150 | | { |
| 633 | 151 | | [IceRpcSettingKey.MaxHeaderSize] = (ulong)_maxLocalHeaderSize |
| 633 | 152 | | }); |
| | 153 | |
|
| | 154 | | try |
| 633 | 155 | | { |
| 633 | 156 | | await SendControlFrameAsync( |
| 633 | 157 | | IceRpcControlFrameType.Settings, |
| 633 | 158 | | settings.Encode, |
| 633 | 159 | | connectCts.Token).ConfigureAwait(false); |
| 625 | 160 | | } |
| 8 | 161 | | catch |
| 8 | 162 | | { |
| | 163 | | // If we fail to send the Settings frame, we are in an abortive closure and we close Output to allow |
| | 164 | | // the peer to continue if it's waiting for us. This could happen when the cancellation token is |
| | 165 | | // canceled. |
| 8 | 166 | | _controlStream!.Output.CompleteOutput(success: false); |
| 8 | 167 | | throw; |
| | 168 | | } |
| | 169 | |
|
| | 170 | | // Wait for the remote control stream to be accepted and read the protocol Settings frame |
| 625 | 171 | | _remoteControlStream = await _transportConnection.AcceptStreamAsync( |
| 625 | 172 | | connectCts.Token).ConfigureAwait(false); |
| | 173 | |
|
| 590 | 174 | | await ReceiveControlFrameHeaderAsync( |
| 590 | 175 | | IceRpcControlFrameType.Settings, |
| 590 | 176 | | connectCts.Token).ConfigureAwait(false); |
| | 177 | |
|
| 577 | 178 | | await ReceiveSettingsFrameBody(connectCts.Token).ConfigureAwait(false); |
| 567 | 179 | | } |
| 54 | 180 | | catch (OperationCanceledException) |
| 54 | 181 | | { |
| 54 | 182 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 183 | |
|
| 15 | 184 | | Debug.Assert(_disposedCts.Token.IsCancellationRequested); |
| 15 | 185 | | throw new IceRpcException( |
| 15 | 186 | | IceRpcError.OperationAborted, |
| 15 | 187 | | "The connection establishment was aborted because the connection was disposed."); |
| | 188 | | } |
| 14 | 189 | | catch (InvalidDataException exception) |
| 14 | 190 | | { |
| 14 | 191 | | throw new IceRpcException( |
| 14 | 192 | | IceRpcError.ConnectionAborted, |
| 14 | 193 | | "The connection establishment was aborted by an icerpc protocol error.", |
| 14 | 194 | | exception); |
| | 195 | | } |
| 2 | 196 | | catch (AuthenticationException) |
| 2 | 197 | | { |
| 2 | 198 | | throw; |
| | 199 | | } |
| 57 | 200 | | catch (IceRpcException) |
| 57 | 201 | | { |
| 57 | 202 | | throw; |
| | 203 | | } |
| 0 | 204 | | catch (Exception exception) |
| 0 | 205 | | { |
| 0 | 206 | | Debug.Fail($"ConnectAsync failed with an unexpected exception: {exception}"); |
| 0 | 207 | | throw; |
| | 208 | | } |
| | 209 | |
|
| | 210 | | // This needs to be set before starting the accept requests task below. |
| 567 | 211 | | _connectionContext = new ConnectionContext(this, transportConnectionInformation); |
| | 212 | |
|
| | 213 | | // We assign _readGoAwayTask and _acceptRequestsTask with _mutex locked to make sure this assignment |
| | 214 | | // occurs before the start of DisposeAsync. Once _disposeTask is not null, _readGoAwayTask etc are |
| | 215 | | // immutable. |
| 567 | 216 | | lock (_mutex) |
| 567 | 217 | | { |
| 567 | 218 | | if (_disposeTask is not null) |
| 0 | 219 | | { |
| 0 | 220 | | throw new IceRpcException( |
| 0 | 221 | | IceRpcError.OperationAborted, |
| 0 | 222 | | "The connection establishment was aborted because the connection was disposed."); |
| | 223 | | } |
| | 224 | |
|
| | 225 | | // Read the go away frame from the control stream. |
| 567 | 226 | | _readGoAwayTask = ReadGoAwayAsync(_disposedCts.Token); |
| | 227 | |
|
| | 228 | | // Start a task that accepts requests (the "accept requests loop") |
| 567 | 229 | | _acceptRequestsTask = AcceptRequestsAsync(_shutdownOrGoAwayCts.Token); |
| 567 | 230 | | } |
| | 231 | |
|
| | 232 | | // The _acceptRequestsTask waits for this PerformConnectAsync completion before reading anything. As soon as |
| | 233 | | // it receives a request, it will cancel this inactivity check. |
| 567 | 234 | | ScheduleInactivityCheck(); |
| | 235 | |
|
| 567 | 236 | | return (transportConnectionInformation, _shutdownRequestedTcs.Task); |
| 567 | 237 | | } |
| 694 | 238 | | } |
| | 239 | |
|
| | 240 | | public ValueTask DisposeAsync() |
| 764 | 241 | | { |
| 764 | 242 | | lock (_mutex) |
| 764 | 243 | | { |
| 764 | 244 | | if (_disposeTask is null) |
| 712 | 245 | | { |
| 712 | 246 | | RefuseNewInvocations("The connection was disposed."); |
| | 247 | |
|
| 712 | 248 | | if (_streamInputOutputCount == 0) |
| 688 | 249 | | { |
| | 250 | | // That's only for consistency. _streamsCompleted.Task matters only to ShutdownAsync. |
| 688 | 251 | | _streamsCompleted.TrySetResult(); |
| 688 | 252 | | } |
| 712 | 253 | | if (_dispatchInvocationCount == 0) |
| 695 | 254 | | { |
| 695 | 255 | | _dispatchesAndInvocationsCompleted.TrySetResult(); |
| 695 | 256 | | } |
| | 257 | |
|
| 712 | 258 | | _shutdownTask ??= Task.CompletedTask; |
| 712 | 259 | | _disposeTask = PerformDisposeAsync(); |
| 712 | 260 | | } |
| 764 | 261 | | } |
| 764 | 262 | | return new(_disposeTask); |
| | 263 | |
|
| | 264 | | async Task PerformDisposeAsync() |
| 712 | 265 | | { |
| | 266 | | // Make sure we execute the code below without holding the mutex lock. |
| 712 | 267 | | await Task.Yield(); |
| | 268 | |
|
| 712 | 269 | | _disposedCts.Cancel(); |
| | 270 | |
|
| | 271 | | // We don't lock _mutex since once _disposeTask is not null, _connectTask etc are immutable. |
| | 272 | |
|
| 712 | 273 | | if (_connectTask is not null) |
| 694 | 274 | | { |
| | 275 | | // We wait for _dispatchesAndInvocationsCompleted (since dispatches and invocations are somewhat under |
| | 276 | | // our control), but not for _streamsCompleted, since we can't make the application complete the |
| | 277 | | // incoming payload pipe readers. |
| | 278 | | try |
| 694 | 279 | | { |
| 694 | 280 | | await Task.WhenAll( |
| 694 | 281 | | _connectTask, |
| 694 | 282 | | _acceptRequestsTask ?? Task.CompletedTask, |
| 694 | 283 | | _readGoAwayTask ?? Task.CompletedTask, |
| 694 | 284 | | _shutdownTask, |
| 694 | 285 | | _dispatchesAndInvocationsCompleted.Task).ConfigureAwait(false); |
| 127 | 286 | | } |
| 567 | 287 | | catch |
| 567 | 288 | | { |
| | 289 | | // Expected if any of these tasks failed or was canceled. Each task takes care of handling |
| | 290 | | // unexpected exceptions so there's no need to handle them here. |
| 567 | 291 | | } |
| 694 | 292 | | } |
| | 293 | |
|
| | 294 | | // If the application is still reading some incoming payload, the disposal of the transport connection can |
| | 295 | | // abort this reading. |
| 712 | 296 | | await _transportConnection.DisposeAsync().ConfigureAwait(false); |
| | 297 | |
|
| | 298 | | // It's safe to complete the output since write operations have been completed by the transport connection |
| | 299 | | // disposal. |
| 712 | 300 | | _controlStream?.Output.Complete(); |
| | 301 | |
|
| | 302 | | // It's safe to complete the input since read operations have been completed by the transport connection |
| | 303 | | // disposal. |
| 712 | 304 | | _remoteControlStream?.Input.Complete(); |
| | 305 | |
|
| 712 | 306 | | _dispatchSemaphore?.Dispose(); |
| 712 | 307 | | _disposedCts.Dispose(); |
| 712 | 308 | | _goAwayCts.Dispose(); |
| 712 | 309 | | _shutdownOrGoAwayCts.Dispose(); |
| | 310 | |
|
| 712 | 311 | | await _inactivityTimeoutTimer.DisposeAsync().ConfigureAwait(false); |
| 712 | 312 | | } |
| 764 | 313 | | } |
| | 314 | |
|
| | 315 | | public Task<IncomingResponse> InvokeAsync(OutgoingRequest request, CancellationToken cancellationToken = default) |
| 2821 | 316 | | { |
| 2821 | 317 | | if (request.Protocol != Protocol.IceRpc) |
| 2 | 318 | | { |
| 2 | 319 | | throw new InvalidOperationException( |
| 2 | 320 | | $"Cannot send {request.Protocol} request on {Protocol.IceRpc} connection."); |
| | 321 | | } |
| | 322 | |
|
| 2819 | 323 | | lock (_mutex) |
| 2819 | 324 | | { |
| 2819 | 325 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 326 | |
|
| 2815 | 327 | | if (_refuseInvocations) |
| 2 | 328 | | { |
| 2 | 329 | | throw new IceRpcException(IceRpcError.InvocationRefused, _invocationRefusedMessage); |
| | 330 | | } |
| 2813 | 331 | | if (_connectTask is null) |
| 0 | 332 | | { |
| 0 | 333 | | throw new InvalidOperationException("Cannot invoke on a connection before connecting it."); |
| | 334 | | } |
| 2813 | 335 | | if (!IsServer && !_connectTask.IsCompletedSuccessfully) |
| 0 | 336 | | { |
| 0 | 337 | | throw new InvalidOperationException( |
| 0 | 338 | | "Cannot invoke on a client connection that is not fully established."); |
| | 339 | | } |
| | 340 | | // It's possible but rare to invoke on a server connection that is still connecting. |
| | 341 | |
|
| 2813 | 342 | | if (request.ServiceAddress.Fragment.Length > 0) |
| 0 | 343 | | { |
| 0 | 344 | | throw new NotSupportedException("The icerpc protocol does not support fragments."); |
| | 345 | | } |
| | 346 | |
|
| 2813 | 347 | | IncrementDispatchInvocationCount(); |
| 2813 | 348 | | } |
| | 349 | |
|
| 2813 | 350 | | return PerformInvokeAsync(); |
| | 351 | |
|
| | 352 | | async Task<IncomingResponse> PerformInvokeAsync() |
| 2813 | 353 | | { |
| | 354 | | // Since _dispatchInvocationCount > 0, _disposedCts is not disposed. |
| 2813 | 355 | | using var invocationCts = CancellationTokenSource.CreateLinkedTokenSource( |
| 2813 | 356 | | cancellationToken, |
| 2813 | 357 | | _disposedCts.Token); |
| | 358 | |
|
| 2813 | 359 | | PipeReader? streamInput = null; |
| | 360 | |
|
| | 361 | | // This try/catch block cleans up streamInput (when not null) and decrements the dispatch-invocation count. |
| | 362 | | try |
| 2813 | 363 | | { |
| | 364 | | // Create the stream. |
| | 365 | | IMultiplexedStream stream; |
| | 366 | | try |
| 2813 | 367 | | { |
| | 368 | | // We want to cancel CreateStreamAsync as soon as the connection is being shutdown or received a |
| | 369 | | // GoAway frame. |
| 2813 | 370 | | using CancellationTokenRegistration _ = _shutdownOrGoAwayCts.Token.UnsafeRegister( |
| 10 | 371 | | cts => ((CancellationTokenSource)cts!).Cancel(), |
| 2813 | 372 | | invocationCts); |
| | 373 | |
|
| 2813 | 374 | | stream = await _transportConnection.CreateStreamAsync( |
| 2813 | 375 | | bidirectional: !request.IsOneway, |
| 2813 | 376 | | invocationCts.Token).ConfigureAwait(false); |
| | 377 | |
|
| 2795 | 378 | | streamInput = stream.IsBidirectional ? stream.Input : null; |
| 2795 | 379 | | } |
| 16 | 380 | | catch (OperationCanceledException) |
| 16 | 381 | | { |
| 16 | 382 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 383 | |
|
| | 384 | | // Connection was shutdown or disposed and we did not read the payload at all. |
| 12 | 385 | | throw new IceRpcException(IceRpcError.InvocationRefused, _invocationRefusedMessage); |
| | 386 | | } |
| 2 | 387 | | catch (IceRpcException exception) |
| 2 | 388 | | { |
| 2 | 389 | | RefuseNewInvocations("The connection was lost."); |
| 2 | 390 | | throw new IceRpcException(IceRpcError.InvocationRefused, _invocationRefusedMessage, exception); |
| | 391 | | } |
| 0 | 392 | | catch (Exception exception) |
| 0 | 393 | | { |
| 0 | 394 | | Debug.Fail($"CreateStreamAsync failed with an unexpected exception: {exception}"); |
| 0 | 395 | | RefuseNewInvocations("The connection was lost."); |
| 0 | 396 | | throw new IceRpcException(IceRpcError.InvocationRefused, _invocationRefusedMessage, exception); |
| | 397 | | } |
| | 398 | |
|
| 2795 | 399 | | using CancellationTokenRegistration tokenRegistration = _goAwayCts.Token.UnsafeRegister( |
| 2795 | 400 | | OnGoAway, |
| 2795 | 401 | | invocationCts); |
| | 402 | |
|
| | 403 | | PipeWriter payloadWriter; |
| | 404 | |
|
| | 405 | | try |
| 2795 | 406 | | { |
| 2795 | 407 | | lock (_mutex) |
| 2795 | 408 | | { |
| 2795 | 409 | | if (_refuseInvocations) |
| 0 | 410 | | { |
| | 411 | | // Both stream.Output and stream.Output are completed by catch blocks below. |
| 0 | 412 | | throw new IceRpcException(IceRpcError.InvocationRefused, _invocationRefusedMessage); |
| | 413 | | } |
| | 414 | |
|
| 2795 | 415 | | IncrementStreamInputOutputCount(stream.IsBidirectional); |
| | 416 | |
|
| | 417 | | // Decorate the stream to decrement the input/output count on Complete. |
| 2795 | 418 | | stream = new MultiplexedStreamDecorator(stream, DecrementStreamInputOutputCount); |
| 2795 | 419 | | streamInput = stream.IsBidirectional ? stream.Input : null; |
| 2795 | 420 | | } |
| | 421 | |
|
| 2795 | 422 | | EncodeHeader(stream.Output); |
| 2793 | 423 | | payloadWriter = request.GetPayloadWriter(stream.Output); |
| 2793 | 424 | | } |
| 2 | 425 | | catch |
| 2 | 426 | | { |
| 2 | 427 | | stream.Output.CompleteOutput(success: false); |
| 2 | 428 | | throw; |
| | 429 | | } |
| | 430 | |
|
| | 431 | | // From now on, we only use payloadWriter to write and we make sure to complete it. |
| | 432 | |
|
| 2793 | 433 | | bool hasContinuation = request.PayloadContinuation is not null; |
| | 434 | | FlushResult flushResult; |
| | 435 | |
|
| | 436 | | try |
| 2793 | 437 | | { |
| 2793 | 438 | | flushResult = await payloadWriter.CopyFromAsync( |
| 2793 | 439 | | request.Payload, |
| 2793 | 440 | | stream.WritesClosed, |
| 2793 | 441 | | endStream: !hasContinuation, |
| 2793 | 442 | | invocationCts.Token).ConfigureAwait(false); |
| 2777 | 443 | | } |
| 16 | 444 | | catch |
| 16 | 445 | | { |
| 16 | 446 | | payloadWriter.CompleteOutput(success: false); |
| 16 | 447 | | request.PayloadContinuation?.Complete(); |
| 16 | 448 | | throw; |
| | 449 | | } |
| | 450 | | finally |
| 2793 | 451 | | { |
| 2793 | 452 | | request.Payload.Complete(); |
| 2793 | 453 | | } |
| | 454 | |
|
| 2777 | 455 | | if (flushResult.IsCompleted || flushResult.IsCanceled || !hasContinuation) |
| 2753 | 456 | | { |
| | 457 | | // The remote reader doesn't want more data, or the copying was canceled, or there is no |
| | 458 | | // continuation: we're done. |
| 2753 | 459 | | payloadWriter.CompleteOutput(!flushResult.IsCanceled); |
| 2753 | 460 | | request.PayloadContinuation?.Complete(); |
| 2753 | 461 | | } |
| | 462 | | else |
| 24 | 463 | | { |
| | 464 | | // Sends the payload continuation in a background thread. |
| 24 | 465 | | SendRequestPayloadContinuation( |
| 24 | 466 | | request, |
| 24 | 467 | | payloadWriter, |
| 24 | 468 | | stream.WritesClosed, |
| 24 | 469 | | OnGoAway, |
| 24 | 470 | | invocationCts.Token); |
| 24 | 471 | | } |
| | 472 | |
|
| 2777 | 473 | | if (request.IsOneway) |
| 2022 | 474 | | { |
| 2022 | 475 | | return new IncomingResponse(request, _connectionContext!); |
| | 476 | | } |
| | 477 | |
|
| 755 | 478 | | Debug.Assert(streamInput is not null); |
| | 479 | |
|
| | 480 | | try |
| 755 | 481 | | { |
| 755 | 482 | | ReadResult readResult = await streamInput.ReadSegmentAsync( |
| 755 | 483 | | SliceEncoding.Slice2, |
| 755 | 484 | | _maxLocalHeaderSize, |
| 755 | 485 | | invocationCts.Token).ConfigureAwait(false); |
| | 486 | |
|
| | 487 | | // Nothing cancels the stream input pipe reader. |
| 711 | 488 | | Debug.Assert(!readResult.IsCanceled); |
| | 489 | |
|
| 711 | 490 | | if (readResult.Buffer.IsEmpty) |
| 0 | 491 | | { |
| 0 | 492 | | throw new IceRpcException( |
| 0 | 493 | | IceRpcError.IceRpcError, |
| 0 | 494 | | "Received an icerpc response with an empty header."); |
| | 495 | | } |
| | 496 | |
|
| 711 | 497 | | (StatusCode statusCode, string? errorMessage, IDictionary<ResponseFieldKey, ReadOnlySequence<byte>> |
| 711 | 498 | | DecodeHeader(readResult.Buffer); |
| 711 | 499 | | stream.Input.AdvanceTo(readResult.Buffer.End); |
| | 500 | |
|
| 711 | 501 | | if (statusCode == StatusCode.TruncatedPayload && invocationCts.Token.IsCancellationRequested) |
| 0 | 502 | | { |
| | 503 | | // Canceling the sending of the payload continuation triggers the completion of the stream |
| | 504 | | // output. This may lead to a TruncatedPayload if the dispatch is currently reading the payload |
| | 505 | | // continuation. In such cases, we prioritize throwing an OperationCanceledException. |
| 0 | 506 | | fieldsPipeReader?.Complete(); |
| 0 | 507 | | invocationCts.Token.ThrowIfCancellationRequested(); |
| 0 | 508 | | } |
| | 509 | |
|
| 711 | 510 | | var response = new IncomingResponse( |
| 711 | 511 | | request, |
| 711 | 512 | | _connectionContext!, |
| 711 | 513 | | statusCode, |
| 711 | 514 | | errorMessage, |
| 711 | 515 | | fields, |
| 711 | 516 | | fieldsPipeReader) |
| 711 | 517 | | { |
| 711 | 518 | | Payload = streamInput |
| 711 | 519 | | }; |
| | 520 | |
|
| 711 | 521 | | streamInput = null; // response now owns the stream input |
| 711 | 522 | | return response; |
| | 523 | | } |
| 2 | 524 | | catch (InvalidDataException exception) |
| 2 | 525 | | { |
| 2 | 526 | | throw new IceRpcException( |
| 2 | 527 | | IceRpcError.IceRpcError, |
| 2 | 528 | | "Received an icerpc response with an invalid header.", |
| 2 | 529 | | exception); |
| | 530 | | } |
| | 531 | |
|
| | 532 | | void OnGoAway(object? cts) |
| 26 | 533 | | { |
| 26 | 534 | | if (!stream.IsStarted || |
| 26 | 535 | | stream.Id >= |
| 26 | 536 | | (stream.IsBidirectional ? |
| 26 | 537 | | _goAwayFrame.BidirectionalStreamId : |
| 26 | 538 | | _goAwayFrame.UnidirectionalStreamId)) |
| 8 | 539 | | { |
| | 540 | | // The request wasn't received by the peer so it's safe to cancel the invocation. |
| 8 | 541 | | ((CancellationTokenSource)cts!).Cancel(); |
| 8 | 542 | | } |
| 26 | 543 | | } |
| | 544 | | } |
| 32 | 545 | | catch (OperationCanceledException exception) when (exception.CancellationToken == invocationCts.Token) |
| 26 | 546 | | { |
| 26 | 547 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 548 | |
|
| 12 | 549 | | if (_disposedCts.IsCancellationRequested) |
| 6 | 550 | | { |
| | 551 | | // DisposeAsync aborted the request. |
| 6 | 552 | | throw new IceRpcException(IceRpcError.OperationAborted); |
| | 553 | | } |
| | 554 | | else |
| 6 | 555 | | { |
| 6 | 556 | | Debug.Assert(_goAwayCts.IsCancellationRequested); |
| 6 | 557 | | throw new IceRpcException(IceRpcError.InvocationCanceled, "The connection is shutting down."); |
| | 558 | | } |
| | 559 | | } |
| | 560 | | finally |
| 2813 | 561 | | { |
| 2813 | 562 | | streamInput?.Complete(); |
| 2813 | 563 | | DecrementDispatchInvocationCount(); |
| 2813 | 564 | | } |
| | 565 | |
|
| | 566 | | static (StatusCode StatusCode, string? ErrorMessage, IDictionary<ResponseFieldKey, ReadOnlySequence<byte>>, |
| | 567 | | ReadOnlySequence<byte> buffer) |
| 711 | 568 | | { |
| 711 | 569 | | var decoder = new SliceDecoder(buffer, SliceEncoding.Slice2); |
| | 570 | |
|
| 711 | 571 | | StatusCode statusCode = decoder.DecodeStatusCode(); |
| 711 | 572 | | string? errorMessage = statusCode == StatusCode.Ok ? null : decoder.DecodeString(); |
| | 573 | |
|
| 711 | 574 | | (IDictionary<ResponseFieldKey, ReadOnlySequence<byte>> fields, PipeReader? pipeReader) = |
| 711 | 575 | | DecodeFieldDictionary( |
| 711 | 576 | | ref decoder, |
| 715 | 577 | | (ref SliceDecoder decoder) => decoder.DecodeResponseFieldKey()); |
| | 578 | |
|
| 711 | 579 | | return (statusCode, errorMessage, fields, pipeReader); |
| 711 | 580 | | } |
| | 581 | |
|
| | 582 | | void EncodeHeader(PipeWriter streamOutput) |
| 2795 | 583 | | { |
| 2795 | 584 | | var encoder = new SliceEncoder(streamOutput, SliceEncoding.Slice2); |
| | 585 | |
|
| | 586 | | // Write the IceRpc request header. |
| 2795 | 587 | | Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(_headerSizeLength); |
| | 588 | |
|
| | 589 | | // We use UnflushedBytes because EncodeFieldDictionary can write directly to streamOutput. |
| 2795 | 590 | | long headerStartPos = streamOutput.UnflushedBytes; |
| | 591 | |
|
| 2795 | 592 | | var header = new IceRpcRequestHeader(request.ServiceAddress.Path, request.Operation); |
| | 593 | |
|
| 2795 | 594 | | header.Encode(ref encoder); |
| | 595 | |
|
| 2795 | 596 | | EncodeFieldDictionary( |
| 2795 | 597 | | request.Fields, |
| 15 | 598 | | (ref SliceEncoder encoder, RequestFieldKey key) => encoder.EncodeRequestFieldKey(key), |
| 2795 | 599 | | ref encoder, |
| 2795 | 600 | | streamOutput); |
| | 601 | |
|
| | 602 | | // We're done with the header encoding, write the header size. |
| 2795 | 603 | | int headerSize = (int)(streamOutput.UnflushedBytes - headerStartPos); |
| 2795 | 604 | | CheckPeerHeaderSize(headerSize); |
| 2793 | 605 | | SliceEncoder.EncodeVarUInt62((uint)headerSize, sizePlaceholder); |
| 2793 | 606 | | } |
| 2733 | 607 | | } |
| 2813 | 608 | | } |
| | 609 | |
|
| | 610 | | public Task ShutdownAsync(CancellationToken cancellationToken = default) |
| 181 | 611 | | { |
| 181 | 612 | | lock (_mutex) |
| 181 | 613 | | { |
| 181 | 614 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 615 | |
|
| 174 | 616 | | if (_shutdownTask is not null) |
| 4 | 617 | | { |
| 4 | 618 | | throw new InvalidOperationException("Cannot call ShutdownAsync more than once."); |
| | 619 | | } |
| 170 | 620 | | if (_connectTask is null || !_connectTask.IsCompletedSuccessfully) |
| 6 | 621 | | { |
| 6 | 622 | | throw new InvalidOperationException("Cannot shut down a protocol connection before it's connected."); |
| | 623 | | } |
| | 624 | |
|
| 164 | 625 | | RefuseNewInvocations("The connection was shut down."); |
| | 626 | |
|
| 164 | 627 | | if (_streamInputOutputCount == 0) |
| 119 | 628 | | { |
| 119 | 629 | | _streamsCompleted.TrySetResult(); |
| 119 | 630 | | } |
| 164 | 631 | | if (_dispatchInvocationCount == 0) |
| 115 | 632 | | { |
| 115 | 633 | | _dispatchesAndInvocationsCompleted.TrySetResult(); |
| 115 | 634 | | } |
| | 635 | |
|
| 164 | 636 | | _shutdownTask = PerformShutdownAsync(); |
| 164 | 637 | | } |
| 164 | 638 | | return _shutdownTask; |
| | 639 | |
|
| | 640 | | async Task PerformShutdownAsync() |
| 164 | 641 | | { |
| 164 | 642 | | await Task.Yield(); // exit mutex lock |
| | 643 | |
|
| 164 | 644 | | _shutdownOrGoAwayCts.Cancel(); |
| | 645 | |
|
| | 646 | | try |
| 164 | 647 | | { |
| 164 | 648 | | Debug.Assert(_acceptRequestsTask is not null); |
| 164 | 649 | | Debug.Assert(_controlStream is not null); |
| 164 | 650 | | Debug.Assert(_readGoAwayTask is not null); |
| 164 | 651 | | Debug.Assert(_remoteControlStream is not null); |
| | 652 | |
|
| 164 | 653 | | await _acceptRequestsTask.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | 654 | |
|
| 146 | 655 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposedCts.Token); |
| | 656 | |
|
| | 657 | | // Once shutdownTask is not null, _lastRemoteBidirectionalStreamId and _lastRemoteUnidirectionalStreamId |
| | 658 | | // are immutable. |
| | 659 | |
|
| | 660 | | // When this peer is the server endpoint, the first accepted bidirectional stream ID is 0. When this |
| | 661 | | // peer is the client endpoint, the first accepted bidirectional stream ID is 1. |
| 146 | 662 | | IceRpcGoAway goAwayFrame = new( |
| 146 | 663 | | _lastRemoteBidirectionalStreamId is ulong value ? value + 4 : (IsServer ? 0ul : 1ul), |
| 146 | 664 | | (_lastRemoteUnidirectionalStreamId ?? _remoteControlStream.Id) + 4); |
| | 665 | |
|
| | 666 | | try |
| 146 | 667 | | { |
| 146 | 668 | | _ = await SendControlFrameAsync( |
| 146 | 669 | | IceRpcControlFrameType.GoAway, |
| 146 | 670 | | goAwayFrame.Encode, |
| 146 | 671 | | cts.Token).ConfigureAwait(false); |
| | 672 | |
|
| | 673 | | // Wait for the peer to send back a GoAway frame. The task should already be completed if the |
| | 674 | | // shutdown was initiated by the peer. |
| 142 | 675 | | await _readGoAwayTask.WaitAsync(cts.Token).ConfigureAwait(false); |
| | 676 | |
|
| | 677 | | // Wait for all streams (other than the control streams) to have their Input and Output completed. |
| 122 | 678 | | await _streamsCompleted.Task.WaitAsync(cts.Token).ConfigureAwait(false); |
| | 679 | |
|
| | 680 | | // Close the control stream to notify the peer that on our side, all the streams completed and that |
| | 681 | | // it can close the transport connection whenever it likes. |
| 120 | 682 | | _controlStream.Output.CompleteOutput(success: true); |
| 120 | 683 | | } |
| 26 | 684 | | catch |
| 26 | 685 | | { |
| | 686 | | // If we fail to send the GoAway frame or some other failure occur (such as |
| | 687 | | // OperationCanceledException) we are in an abortive closure and we close Output to allow |
| | 688 | | // the peer to continue if it's waiting for us. |
| 26 | 689 | | _controlStream.Output.CompleteOutput(success: false); |
| 26 | 690 | | throw; |
| | 691 | | } |
| | 692 | |
|
| | 693 | | // Wait for the peer notification that on its side all the streams are completed. It's important to wait |
| | 694 | | // for this notification before closing the connection. In particular with Quic where closing the |
| | 695 | | // connection before all the streams are processed could lead to a stream failure. |
| | 696 | | try |
| 120 | 697 | | { |
| | 698 | | // Wait for the _remoteControlStream Input completion. |
| 120 | 699 | | ReadResult readResult = await _remoteControlStream.Input.ReadAsync(cts.Token).ConfigureAwait(false); |
| | 700 | |
|
| 115 | 701 | | Debug.Assert(!readResult.IsCanceled); |
| | 702 | |
|
| 115 | 703 | | if (!readResult.IsCompleted || !readResult.Buffer.IsEmpty) |
| 0 | 704 | | { |
| 0 | 705 | | throw new IceRpcException( |
| 0 | 706 | | IceRpcError.IceRpcError, |
| 0 | 707 | | "Received bytes on the control stream after receiving the GoAway frame."); |
| | 708 | | } |
| | 709 | |
|
| | 710 | | // We can now safely close the connection. |
| 115 | 711 | | await _transportConnection.CloseAsync(MultiplexedConnectionCloseError.NoError, cts.Token) |
| 115 | 712 | | .ConfigureAwait(false); |
| 114 | 713 | | } |
| 5 | 714 | | catch (IceRpcException exception) when (exception.IceRpcError == IceRpcError.ConnectionClosedByPeer) |
| 1 | 715 | | { |
| | 716 | | // Expected if the peer closed the connection first. |
| 1 | 717 | | } |
| | 718 | |
|
| | 719 | | // We wait for the completion of the dispatches that we created (and, secondarily, invocations). |
| 115 | 720 | | await _dispatchesAndInvocationsCompleted.Task.WaitAsync(cts.Token).ConfigureAwait(false); |
| 115 | 721 | | } |
| 17 | 722 | | catch (OperationCanceledException) |
| 17 | 723 | | { |
| 17 | 724 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 725 | |
|
| 7 | 726 | | Debug.Assert(_disposedCts.Token.IsCancellationRequested); |
| 7 | 727 | | throw new IceRpcException( |
| 7 | 728 | | IceRpcError.OperationAborted, |
| 7 | 729 | | "The connection shutdown was aborted because the connection was disposed."); |
| | 730 | | } |
| 0 | 731 | | catch (InvalidDataException exception) |
| 0 | 732 | | { |
| 0 | 733 | | throw new IceRpcException( |
| 0 | 734 | | IceRpcError.IceRpcError, |
| 0 | 735 | | "The connection shutdown was aborted by an icerpc protocol error.", |
| 0 | 736 | | exception); |
| | 737 | | } |
| 32 | 738 | | catch (IceRpcException) |
| 32 | 739 | | { |
| 32 | 740 | | throw; |
| | 741 | | } |
| 0 | 742 | | catch (Exception exception) |
| 0 | 743 | | { |
| 0 | 744 | | Debug.Fail($"ShutdownAsync failed with an unexpected exception: {exception}"); |
| 0 | 745 | | throw; |
| | 746 | | } |
| 115 | 747 | | } |
| 164 | 748 | | } |
| | 749 | |
|
| 712 | 750 | | internal IceRpcProtocolConnection( |
| 712 | 751 | | IMultiplexedConnection transportConnection, |
| 712 | 752 | | TransportConnectionInformation? transportConnectionInformation, |
| 712 | 753 | | ConnectionOptions options, |
| 712 | 754 | | ITaskExceptionObserver? taskExceptionObserver) |
| 712 | 755 | | { |
| 712 | 756 | | _shutdownOrGoAwayCts = CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token, _goAwayCts.Token); |
| | 757 | |
|
| 712 | 758 | | _taskExceptionObserver = taskExceptionObserver; |
| | 759 | |
|
| 712 | 760 | | _transportConnection = transportConnection; |
| 712 | 761 | | _dispatcher = options.Dispatcher; |
| 712 | 762 | | _maxLocalHeaderSize = options.MaxIceRpcHeaderSize; |
| 712 | 763 | | _transportConnectionInformation = transportConnectionInformation; |
| | 764 | |
|
| 712 | 765 | | if (options.MaxDispatches > 0) |
| 712 | 766 | | { |
| 712 | 767 | | _dispatchSemaphore = new SemaphoreSlim( |
| 712 | 768 | | initialCount: options.MaxDispatches, |
| 712 | 769 | | maxCount: options.MaxDispatches); |
| 712 | 770 | | } |
| | 771 | |
|
| 712 | 772 | | _inactivityTimeout = options.InactivityTimeout; |
| 712 | 773 | | _inactivityTimeoutTimer = new Timer(_ => |
| 10 | 774 | | { |
| 10 | 775 | | bool requestShutdown = false; |
| 712 | 776 | |
|
| 10 | 777 | | lock (_mutex) |
| 10 | 778 | | { |
| 10 | 779 | | if (_shutdownTask is null && _dispatchInvocationCount == 0 && _streamInputOutputCount == 0) |
| 10 | 780 | | { |
| 10 | 781 | | requestShutdown = true; |
| 10 | 782 | | RefuseNewInvocations( |
| 10 | 783 | | $"The connection was shut down because it was inactive for over {_inactivityTimeout.TotalSeconds |
| 10 | 784 | | } |
| 10 | 785 | | } |
| 712 | 786 | |
|
| 10 | 787 | | if (requestShutdown) |
| 10 | 788 | | { |
| 712 | 789 | | // TrySetResult must be called outside the mutex lock |
| 10 | 790 | | _shutdownRequestedTcs.TrySetResult(); |
| 10 | 791 | | } |
| 722 | 792 | | }); |
| 712 | 793 | | } |
| | 794 | |
|
| | 795 | | private static (IDictionary<TKey, ReadOnlySequence<byte>>, PipeReader?) DecodeFieldDictionary<TKey>( |
| | 796 | | ref SliceDecoder decoder, |
| | 797 | | DecodeFunc<TKey> decodeKeyFunc) where TKey : struct |
| 3480 | 798 | | { |
| 3480 | 799 | | int count = decoder.DecodeSize(); |
| | 800 | |
|
| | 801 | | IDictionary<TKey, ReadOnlySequence<byte>> fields; |
| | 802 | | PipeReader? pipeReader; |
| 3480 | 803 | | if (count == 0) |
| 3461 | 804 | | { |
| 3461 | 805 | | fields = ImmutableDictionary<TKey, ReadOnlySequence<byte>>.Empty; |
| 3461 | 806 | | pipeReader = null; |
| 3461 | 807 | | decoder.CheckEndOfBuffer(); |
| 3461 | 808 | | } |
| | 809 | | else |
| 19 | 810 | | { |
| | 811 | | // We don't use the normal collection allocation check here because SizeOf<ReadOnlySequence<byte>> is quite |
| | 812 | | // large (24). |
| | 813 | | // For example, say we decode a fields dictionary with a single field with an empty value. It's encoded |
| | 814 | | // using 1 byte (dictionary size) + 1 byte (key) + 1 byte (value size) = 3 bytes. The decoder's default max |
| | 815 | | // allocation size is 3 * 8 = 24. If we simply call IncreaseCollectionAllocation(1 * (4 + 24)), we'll exceed |
| | 816 | | // the default collection allocation limit. (sizeof TKey is currently 4 but could/should increase to 8). |
| | 817 | |
|
| | 818 | | // Each field consumes at least 2 bytes: 1 for the key and one for the value size. |
| 19 | 819 | | if (count * 2 > decoder.Remaining) |
| 0 | 820 | | { |
| 0 | 821 | | throw new InvalidDataException("Too many fields."); |
| | 822 | | } |
| | 823 | |
|
| 19 | 824 | | fields = new Dictionary<TKey, ReadOnlySequence<byte>>(count); |
| 19 | 825 | | var pipe = new Pipe(); |
| 19 | 826 | | decoder.CopyTo(pipe.Writer); |
| 19 | 827 | | pipe.Writer.Complete(); |
| | 828 | |
|
| | 829 | | try |
| 19 | 830 | | { |
| 19 | 831 | | _ = pipe.Reader.TryRead(out ReadResult readResult); |
| 19 | 832 | | var fieldsDecoder = new SliceDecoder(readResult.Buffer, SliceEncoding.Slice2); |
| | 833 | |
|
| 76 | 834 | | for (int i = 0; i < count; ++i) |
| 19 | 835 | | { |
| | 836 | | // Decode the field key. |
| 19 | 837 | | TKey key = decodeKeyFunc(ref fieldsDecoder); |
| | 838 | |
|
| | 839 | | // Decode and check the field value size. |
| | 840 | | int valueSize; |
| | 841 | | try |
| 19 | 842 | | { |
| 19 | 843 | | valueSize = checked((int)fieldsDecoder.DecodeVarUInt62()); |
| 19 | 844 | | } |
| 0 | 845 | | catch (OverflowException exception) |
| 0 | 846 | | { |
| 0 | 847 | | throw new InvalidDataException("The field size can't be larger than int.MaxValue.", exception); |
| | 848 | | } |
| | 849 | |
|
| 19 | 850 | | if (valueSize > fieldsDecoder.Remaining) |
| 0 | 851 | | { |
| 0 | 852 | | throw new InvalidDataException( |
| 0 | 853 | | $"The value of field '{key}' extends beyond the end of the buffer."); |
| | 854 | | } |
| | 855 | |
|
| | 856 | | // Create a ROS reference to the field value by slicing the fields pipe reader ROS. |
| 19 | 857 | | ReadOnlySequence<byte> value = readResult.Buffer.Slice(fieldsDecoder.Consumed, valueSize); |
| 19 | 858 | | fields.Add(key, value); |
| | 859 | |
|
| | 860 | | // Skip the field value to prepare the decoder to read the next field value. |
| 19 | 861 | | fieldsDecoder.Skip(valueSize); |
| 19 | 862 | | } |
| 19 | 863 | | fieldsDecoder.CheckEndOfBuffer(); |
| | 864 | |
|
| 19 | 865 | | pipe.Reader.AdvanceTo(readResult.Buffer.Start); // complete read without consuming anything |
| | 866 | |
|
| 19 | 867 | | pipeReader = pipe.Reader; |
| 19 | 868 | | } |
| 0 | 869 | | catch |
| 0 | 870 | | { |
| 0 | 871 | | pipe.Reader.Complete(); |
| 0 | 872 | | throw; |
| | 873 | | } |
| 19 | 874 | | } |
| | 875 | |
|
| | 876 | | // The caller is responsible for completing the pipe reader. |
| 3480 | 877 | | return (fields, pipeReader); |
| 3480 | 878 | | } |
| | 879 | |
|
| | 880 | | private async Task AcceptRequestsAsync(CancellationToken cancellationToken) |
| 567 | 881 | | { |
| 567 | 882 | | await Task.Yield(); // exit mutex lock |
| | 883 | |
|
| | 884 | | // Wait for _connectTask (which spawned the task running this method) to complete. This way, we won't dispatch |
| | 885 | | // any request until _connectTask has completed successfully, and indirectly we won't make any invocation until |
| | 886 | | // _connectTask has completed successfully. The creation of the _acceptRequestsTask is the last action taken by |
| | 887 | | // _connectTask and as a result this await can't fail. |
| 567 | 888 | | await _connectTask!.ConfigureAwait(false); |
| | 889 | |
|
| | 890 | | try |
| 567 | 891 | | { |
| | 892 | | // We check the cancellation token for each iteration because we want to exit the accept requests loop as |
| | 893 | | // soon as ShutdownAsync/GoAway requests this cancellation, even when more streams can be accepted without |
| | 894 | | // waiting. |
| 3354 | 895 | | while (!cancellationToken.IsCancellationRequested) |
| 3354 | 896 | | { |
| | 897 | | // When _dispatcher is null, the multiplexed connection MaxUnidirectionalStreams and |
| | 898 | | // MaxBidirectionalStreams options are configured to not accept any request-stream from the peer. As a |
| | 899 | | // result, when _dispatcher is null, this call will block indefinitely until the cancellation token is |
| | 900 | | // canceled by ShutdownAsync, GoAway or DisposeAsync. |
| 3354 | 901 | | IMultiplexedStream stream = await _transportConnection.AcceptStreamAsync(cancellationToken) |
| 3354 | 902 | | .ConfigureAwait(false); |
| | 903 | |
|
| 2787 | 904 | | lock (_mutex) |
| 2787 | 905 | | { |
| | 906 | | // We don't want to increment _dispatchInvocationCount/_streamInputOutputCount when the connection |
| | 907 | | // is shutting down or being disposed. |
| 2787 | 908 | | if (_shutdownTask is not null) |
| 0 | 909 | | { |
| | 910 | | // Note that cancellationToken may not be canceled yet at this point. |
| 0 | 911 | | throw new OperationCanceledException(); |
| | 912 | | } |
| | 913 | |
|
| | 914 | | // The logic in IncrementStreamInputOutputCount requires that we increment the dispatch-invocation |
| | 915 | | // count first. |
| 2787 | 916 | | IncrementDispatchInvocationCount(); |
| 2787 | 917 | | IncrementStreamInputOutputCount(stream.IsBidirectional); |
| | 918 | |
|
| | 919 | | // Decorate the stream to decrement the stream input/output count on Complete. |
| 2787 | 920 | | stream = new MultiplexedStreamDecorator(stream, DecrementStreamInputOutputCount); |
| | 921 | |
|
| | 922 | | // The multiplexed connection guarantees that the IDs of accepted streams of a given type have ever |
| | 923 | | // increasing values. |
| | 924 | |
|
| 2787 | 925 | | if (stream.IsBidirectional) |
| 767 | 926 | | { |
| 767 | 927 | | _lastRemoteBidirectionalStreamId = stream.Id; |
| 767 | 928 | | } |
| | 929 | | else |
| 2020 | 930 | | { |
| 2020 | 931 | | _lastRemoteUnidirectionalStreamId = stream.Id; |
| 2020 | 932 | | } |
| 2787 | 933 | | } |
| | 934 | |
|
| | 935 | | // Start a task to read the stream and dispatch the request. We pass CancellationToken.None to Task.Run |
| | 936 | | // because DispatchRequestAsync must clean-up the stream and the dispatch-invocation count. |
| 5574 | 937 | | _ = Task.Run(() => DispatchRequestAsync(stream), CancellationToken.None); |
| 2787 | 938 | | } |
| 0 | 939 | | } |
| 415 | 940 | | catch (OperationCanceledException) |
| 415 | 941 | | { |
| | 942 | | // Expected, the associated cancellation token source was canceled. |
| 415 | 943 | | } |
| 152 | 944 | | catch (IceRpcException) |
| 152 | 945 | | { |
| 152 | 946 | | RefuseNewInvocations("The connection was lost"); |
| 152 | 947 | | _ = _shutdownRequestedTcs.TrySetResult(); |
| 152 | 948 | | throw; |
| | 949 | | } |
| 0 | 950 | | catch (Exception exception) |
| 0 | 951 | | { |
| 0 | 952 | | Debug.Fail($"The accept stream task failed with an unexpected exception: {exception}"); |
| 0 | 953 | | RefuseNewInvocations("The connection was lost"); |
| 0 | 954 | | _ = _shutdownRequestedTcs.TrySetResult(); |
| 0 | 955 | | throw; |
| | 956 | | } |
| 415 | 957 | | } |
| | 958 | |
|
| | 959 | | private void CheckPeerHeaderSize(int headerSize) |
| 3528 | 960 | | { |
| 3528 | 961 | | if (headerSize > _maxPeerHeaderSize) |
| 4 | 962 | | { |
| 4 | 963 | | throw new IceRpcException( |
| 4 | 964 | | IceRpcError.LimitExceeded, |
| 4 | 965 | | $"The header size ({headerSize}) for an icerpc request or response is greater than the peer's max header |
| | 966 | | } |
| 3524 | 967 | | } |
| | 968 | |
|
| | 969 | | private void DecrementDispatchInvocationCount() |
| 5624 | 970 | | { |
| 5624 | 971 | | lock (_mutex) |
| 5624 | 972 | | { |
| 5624 | 973 | | if (--_dispatchInvocationCount == 0) |
| 844 | 974 | | { |
| 844 | 975 | | if (_shutdownTask is not null) |
| 60 | 976 | | { |
| 60 | 977 | | _dispatchesAndInvocationsCompleted.TrySetResult(); |
| 60 | 978 | | } |
| 784 | 979 | | else if (!_refuseInvocations && _streamInputOutputCount == 0) |
| 616 | 980 | | { |
| 616 | 981 | | ScheduleInactivityCheck(); |
| 616 | 982 | | } |
| 844 | 983 | | } |
| 5624 | 984 | | } |
| 5624 | 985 | | } |
| | 986 | |
|
| | 987 | | /// <summary>Decrements the stream input/output count.</summary> |
| | 988 | | private void DecrementStreamInputOutputCount() |
| 7112 | 989 | | { |
| 7112 | 990 | | lock (_mutex) |
| 7112 | 991 | | { |
| 7112 | 992 | | if (--_streamInputOutputCount == 0) |
| 825 | 993 | | { |
| 825 | 994 | | if (_shutdownTask is not null) |
| 55 | 995 | | { |
| 55 | 996 | | _streamsCompleted.TrySetResult(); |
| 55 | 997 | | } |
| 770 | 998 | | else if (!_refuseInvocations && _dispatchInvocationCount == 0) |
| 147 | 999 | | { |
| | 1000 | | // We enable the inactivity check in order to complete _shutdownRequestedTcs when inactive for too |
| | 1001 | | // long. _refuseInvocations is true when the connection is either about to be "shutdown requested", |
| | 1002 | | // or shut down / disposed. We don't need to complete _shutdownRequestedTcs in any of these |
| | 1003 | | // situations. |
| 147 | 1004 | | ScheduleInactivityCheck(); |
| 147 | 1005 | | } |
| 825 | 1006 | | } |
| 7112 | 1007 | | } |
| 7112 | 1008 | | } |
| | 1009 | |
|
| | 1010 | | private async Task DispatchRequestAsync(IMultiplexedStream stream) |
| 2787 | 1011 | | { |
| | 1012 | | // _disposedCts is not disposed since we own a dispatch count. |
| 2787 | 1013 | | CancellationToken cancellationToken = stream.IsBidirectional ? |
| 2787 | 1014 | | stream.WritesClosed.AsCancellationToken(_disposedCts.Token) : |
| 2787 | 1015 | | _disposedCts.Token; |
| | 1016 | |
|
| 2787 | 1017 | | PipeReader? fieldsPipeReader = null; |
| | 1018 | | IDictionary<RequestFieldKey, ReadOnlySequence<byte>> fields; |
| | 1019 | | IceRpcRequestHeader header; |
| | 1020 | |
|
| 2787 | 1021 | | PipeReader? streamInput = stream.Input; |
| 2787 | 1022 | | PipeWriter? streamOutput = stream.IsBidirectional ? stream.Output : null; |
| 2787 | 1023 | | bool success = false; |
| | 1024 | |
|
| | 1025 | | try |
| 2787 | 1026 | | { |
| | 1027 | | try |
| 2787 | 1028 | | { |
| 2787 | 1029 | | ReadResult readResult = await streamInput.ReadSegmentAsync( |
| 2787 | 1030 | | SliceEncoding.Slice2, |
| 2787 | 1031 | | _maxLocalHeaderSize, |
| 2787 | 1032 | | cancellationToken).ConfigureAwait(false); |
| | 1033 | |
|
| 2771 | 1034 | | if (readResult.Buffer.IsEmpty) |
| 2 | 1035 | | { |
| 2 | 1036 | | throw new IceRpcException(IceRpcError.IceRpcError, "Received icerpc request with empty header."); |
| | 1037 | | } |
| | 1038 | |
|
| 2769 | 1039 | | (header, fields, fieldsPipeReader) = DecodeHeader(readResult.Buffer); |
| 2769 | 1040 | | streamInput.AdvanceTo(readResult.Buffer.End); |
| 2769 | 1041 | | } |
| 6 | 1042 | | catch (InvalidDataException exception) |
| 6 | 1043 | | { |
| 6 | 1044 | | var rpcException = new IceRpcException( |
| 6 | 1045 | | IceRpcError.IceRpcError, |
| 6 | 1046 | | "Received invalid icerpc request header.", |
| 6 | 1047 | | exception); |
| | 1048 | |
|
| 6 | 1049 | | if (_taskExceptionObserver is null) |
| 2 | 1050 | | { |
| 2 | 1051 | | throw rpcException; |
| | 1052 | | } |
| | 1053 | | else |
| 4 | 1054 | | { |
| 4 | 1055 | | _taskExceptionObserver.DispatchRefused( |
| 4 | 1056 | | _connectionContext!.TransportConnectionInformation, |
| 4 | 1057 | | rpcException); |
| 4 | 1058 | | return; // success remains false |
| | 1059 | | } |
| | 1060 | | } |
| 12 | 1061 | | catch (Exception exception) when (_taskExceptionObserver is not null) |
| 8 | 1062 | | { |
| 8 | 1063 | | _taskExceptionObserver.DispatchRefused(_connectionContext!.TransportConnectionInformation, exception); |
| 8 | 1064 | | return; // success remains false |
| | 1065 | | } |
| | 1066 | |
|
| 2769 | 1067 | | using var request = new IncomingRequest(Protocol.IceRpc, _connectionContext!) |
| 2769 | 1068 | | { |
| 2769 | 1069 | | Fields = fields, |
| 2769 | 1070 | | IsOneway = !stream.IsBidirectional, |
| 2769 | 1071 | | Operation = header.Operation, |
| 2769 | 1072 | | Path = header.Path, |
| 2769 | 1073 | | Payload = streamInput |
| 2769 | 1074 | | }; |
| | 1075 | |
|
| 2769 | 1076 | | streamInput = null; // the request now owns streamInput |
| | 1077 | |
|
| | 1078 | | try |
| 2769 | 1079 | | { |
| 2769 | 1080 | | OutgoingResponse response = await PerformDispatchRequestAsync(request, cancellationToken) |
| 2769 | 1081 | | .ConfigureAwait(false); |
| | 1082 | |
|
| 2753 | 1083 | | if (!request.IsOneway) |
| 735 | 1084 | | { |
| 735 | 1085 | | Debug.Assert(streamOutput is not null); |
| 735 | 1086 | | EncodeHeader(response); |
| | 1087 | |
|
| 731 | 1088 | | PipeWriter payloadWriter = response.GetPayloadWriter(streamOutput); |
| | 1089 | |
|
| | 1090 | | // We give flushResult an initial "failed" value, in case the first CopyFromAsync throws. |
| 731 | 1091 | | var flushResult = new FlushResult(isCanceled: true, isCompleted: false); |
| | 1092 | |
|
| | 1093 | | try |
| 731 | 1094 | | { |
| | 1095 | | // We don't use cancellationToken here because it's canceled shortly afterwards by the |
| | 1096 | | // completion of writesClosed. This works around https://github.com/dotnet/runtime/issues/82704 |
| | 1097 | | // where the stream would otherwise be aborted after the successful write. It's also fine to |
| | 1098 | | // just use _disposedCts.Token: if writes are closed because the peer is not longer interested |
| | 1099 | | // in the response, the write operations will raise an IceRpcException(StreamAborted) which is |
| | 1100 | | // ignored. |
| 731 | 1101 | | bool hasContinuation = response.PayloadContinuation is not null; |
| | 1102 | |
|
| 731 | 1103 | | flushResult = await payloadWriter.CopyFromAsync( |
| 731 | 1104 | | response.Payload, |
| 731 | 1105 | | stream.WritesClosed, |
| 731 | 1106 | | endStream: !hasContinuation, |
| 731 | 1107 | | _disposedCts.Token).ConfigureAwait(false); |
| | 1108 | |
|
| 722 | 1109 | | if (!flushResult.IsCompleted && !flushResult.IsCanceled && hasContinuation) |
| 4 | 1110 | | { |
| 4 | 1111 | | flushResult = await payloadWriter.CopyFromAsync( |
| 4 | 1112 | | response.PayloadContinuation!, |
| 4 | 1113 | | stream.WritesClosed, |
| 4 | 1114 | | endStream: true, |
| 4 | 1115 | | _disposedCts.Token).ConfigureAwait(false); |
| 2 | 1116 | | } |
| 720 | 1117 | | } |
| | 1118 | | finally |
| 731 | 1119 | | { |
| 731 | 1120 | | payloadWriter.CompleteOutput(success: !flushResult.IsCanceled); |
| 731 | 1121 | | response.Payload.Complete(); |
| 731 | 1122 | | response.PayloadContinuation?.Complete(); |
| 731 | 1123 | | } |
| 720 | 1124 | | } |
| 2738 | 1125 | | } |
| 31 | 1126 | | catch (Exception exception) when (_taskExceptionObserver is not null) |
| 15 | 1127 | | { |
| 15 | 1128 | | _taskExceptionObserver.DispatchFailed( |
| 15 | 1129 | | request, |
| 15 | 1130 | | _connectionContext!.TransportConnectionInformation, |
| 15 | 1131 | | exception); |
| 15 | 1132 | | return; // success remains false |
| | 1133 | | } |
| 2738 | 1134 | | success = true; |
| 2738 | 1135 | | } |
| 2 | 1136 | | catch (IceRpcException) |
| 2 | 1137 | | { |
| | 1138 | | // Expected, with for example: |
| | 1139 | | // - IceRpcError.ConnectionAborted when the peer aborts the connection |
| | 1140 | | // - IceRpcError.IceRpcError when the request header is invalid |
| | 1141 | | // - IceRpcError.TruncatedData when the request header is truncated |
| 2 | 1142 | | } |
| 20 | 1143 | | catch (OperationCanceledException exception) when ( |
| 20 | 1144 | | exception.CancellationToken == cancellationToken || |
| 20 | 1145 | | exception.CancellationToken == _disposedCts.Token) |
| 20 | 1146 | | { |
| | 1147 | | // Expected if the dispatch is canceled by the peer or the connection is disposed. |
| 20 | 1148 | | } |
| 0 | 1149 | | catch (Exception exception) |
| 0 | 1150 | | { |
| | 1151 | | // This exception is unexpected when running the IceRPC test suite. A test that expects this exception must |
| | 1152 | | // install a task exception observer. |
| 0 | 1153 | | Debug.Fail($"icerpc dispatch failed with an unexpected exception: {exception}"); |
| | 1154 | |
|
| | 1155 | | // Generate unobserved task exception (UTE). If this exception is expected (e.g. an expected payload read |
| | 1156 | | // exception) and the application wants to avoid this UTE, it must configure a non-null logger to install |
| | 1157 | | // a task exception observer. |
| 0 | 1158 | | throw; |
| | 1159 | | } |
| | 1160 | | finally |
| 2787 | 1161 | | { |
| 2787 | 1162 | | if (!success) |
| 49 | 1163 | | { |
| | 1164 | | // We always need to complete streamOutput when an exception is thrown. For example, we received an |
| | 1165 | | // invalid request header that we could not decode. |
| 49 | 1166 | | streamOutput?.CompleteOutput(success: false); |
| 49 | 1167 | | streamInput?.Complete(); |
| 49 | 1168 | | } |
| 2787 | 1169 | | fieldsPipeReader?.Complete(); |
| | 1170 | |
|
| 2787 | 1171 | | DecrementDispatchInvocationCount(); |
| 2787 | 1172 | | } |
| | 1173 | |
|
| | 1174 | | async Task<OutgoingResponse> PerformDispatchRequestAsync( |
| | 1175 | | IncomingRequest request, |
| | 1176 | | CancellationToken cancellationToken) |
| 2769 | 1177 | | { |
| 2769 | 1178 | | Debug.Assert(_dispatcher is not null); |
| | 1179 | |
|
| | 1180 | | OutgoingResponse response; |
| | 1181 | |
|
| | 1182 | | try |
| 2769 | 1183 | | { |
| 2769 | 1184 | | if (_dispatchSemaphore is SemaphoreSlim dispatchSemaphore) |
| 2769 | 1185 | | { |
| 2769 | 1186 | | await dispatchSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 2769 | 1187 | | } |
| | 1188 | |
|
| | 1189 | | try |
| 2769 | 1190 | | { |
| 2769 | 1191 | | response = await _dispatcher.DispatchAsync(request, cancellationToken).ConfigureAwait(false); |
| 2735 | 1192 | | } |
| | 1193 | | finally |
| 2769 | 1194 | | { |
| 2769 | 1195 | | _dispatchSemaphore?.Release(); |
| 2769 | 1196 | | } |
| | 1197 | |
|
| 2735 | 1198 | | if (response != request.Response) |
| 2 | 1199 | | { |
| 2 | 1200 | | throw new InvalidOperationException( |
| 2 | 1201 | | "The dispatcher did not return the last response created for this request."); |
| | 1202 | | } |
| 2733 | 1203 | | } |
| 18 | 1204 | | catch (OperationCanceledException exception) when (cancellationToken == exception.CancellationToken) |
| 16 | 1205 | | { |
| 16 | 1206 | | throw; |
| | 1207 | | } |
| 20 | 1208 | | catch (Exception exception) |
| 20 | 1209 | | { |
| 20 | 1210 | | if (exception is not DispatchException dispatchException) |
| 16 | 1211 | | { |
| 16 | 1212 | | StatusCode statusCode = exception switch |
| 16 | 1213 | | { |
| 2 | 1214 | | InvalidDataException => StatusCode.InvalidData, |
| 8 | 1215 | | IceRpcException iceRpcException when iceRpcException.IceRpcError == IceRpcError.TruncatedData => |
| 8 | 1216 | | StatusCode.TruncatedPayload, |
| 6 | 1217 | | _ => StatusCode.InternalError |
| 16 | 1218 | | }; |
| 16 | 1219 | | dispatchException = new DispatchException(statusCode, message: null, exception); |
| 16 | 1220 | | } |
| 20 | 1221 | | response = dispatchException.ToOutgoingResponse(request); |
| 20 | 1222 | | } |
| | 1223 | |
|
| 2753 | 1224 | | return response; |
| 2753 | 1225 | | } |
| | 1226 | |
|
| | 1227 | | static (IceRpcRequestHeader, IDictionary<RequestFieldKey, ReadOnlySequence<byte>>, PipeReader?) DecodeHeader( |
| | 1228 | | ReadOnlySequence<byte> buffer) |
| 2769 | 1229 | | { |
| 2769 | 1230 | | var decoder = new SliceDecoder(buffer, SliceEncoding.Slice2); |
| 2769 | 1231 | | var header = new IceRpcRequestHeader(ref decoder); |
| 2769 | 1232 | | (IDictionary<RequestFieldKey, ReadOnlySequence<byte>> fields, PipeReader? pipeReader) = |
| 2769 | 1233 | | DecodeFieldDictionary( |
| 2769 | 1234 | | ref decoder, |
| 2784 | 1235 | | (ref SliceDecoder decoder) => decoder.DecodeRequestFieldKey()); |
| | 1236 | |
|
| 2769 | 1237 | | return (header, fields, pipeReader); |
| 2769 | 1238 | | } |
| | 1239 | |
|
| | 1240 | | void EncodeHeader(OutgoingResponse response) |
| 735 | 1241 | | { |
| 735 | 1242 | | var encoder = new SliceEncoder(streamOutput, SliceEncoding.Slice2); |
| | 1243 | |
|
| | 1244 | | // Write the IceRpc response header. |
| 735 | 1245 | | Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(_headerSizeLength); |
| | 1246 | |
|
| | 1247 | | // We use UnflushedBytes because EncodeFieldDictionary can write directly to streamOutput. |
| 735 | 1248 | | long headerStartPos = streamOutput.UnflushedBytes; |
| | 1249 | |
|
| 735 | 1250 | | encoder.EncodeStatusCode(response.StatusCode); |
| 735 | 1251 | | if (response.StatusCode > StatusCode.Ok) |
| 50 | 1252 | | { |
| 50 | 1253 | | encoder.EncodeString(response.ErrorMessage!); |
| 50 | 1254 | | } |
| | 1255 | |
|
| 735 | 1256 | | EncodeFieldDictionary( |
| 735 | 1257 | | response.Fields, |
| 8 | 1258 | | (ref SliceEncoder encoder, ResponseFieldKey key) => encoder.EncodeResponseFieldKey(key), |
| 735 | 1259 | | ref encoder, |
| 735 | 1260 | | streamOutput); |
| | 1261 | |
|
| | 1262 | | // We're done with the header encoding, write the header size. |
| 733 | 1263 | | int headerSize = (int)(streamOutput.UnflushedBytes - headerStartPos); |
| 733 | 1264 | | CheckPeerHeaderSize(headerSize); |
| 731 | 1265 | | SliceEncoder.EncodeVarUInt62((uint)headerSize, sizePlaceholder); |
| 731 | 1266 | | } |
| 2787 | 1267 | | } |
| | 1268 | |
|
| | 1269 | | /// <summary>Encodes the fields dictionary at the end of a request or response header.</summary> |
| | 1270 | | /// <remarks>This method can write bytes directly to <paramref name="output"/> without going through |
| | 1271 | | /// <paramref name="encoder"/>.</remarks> |
| | 1272 | | private void EncodeFieldDictionary<TKey>( |
| | 1273 | | IDictionary<TKey, OutgoingFieldValue> fields, |
| | 1274 | | EncodeAction<TKey> encodeKeyAction, |
| | 1275 | | ref SliceEncoder encoder, |
| | 1276 | | PipeWriter output) where TKey : struct => |
| 3530 | 1277 | | encoder.EncodeDictionary( |
| 3530 | 1278 | | fields, |
| 3530 | 1279 | | encodeKeyAction, |
| 3530 | 1280 | | (ref SliceEncoder encoder, OutgoingFieldValue value) => |
| 23 | 1281 | | { |
| 23 | 1282 | | if (value.WriteAction is Action<IBufferWriter<byte>> writeAction) |
| 12 | 1283 | | { |
| 12 | 1284 | | Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(_headerSizeLength); |
| 12 | 1285 | | long startPos = output.UnflushedBytes; |
| 12 | 1286 | | writeAction(output); |
| 10 | 1287 | | SliceEncoder.EncodeVarUInt62((ulong)(output.UnflushedBytes - startPos), sizePlaceholder); |
| 10 | 1288 | | } |
| 3530 | 1289 | | else |
| 11 | 1290 | | { |
| 11 | 1291 | | encoder.EncodeSize(checked((int)value.ByteSequence.Length)); |
| 11 | 1292 | | encoder.WriteByteSequence(value.ByteSequence); |
| 11 | 1293 | | } |
| 3551 | 1294 | | }); |
| | 1295 | |
|
| | 1296 | | /// <summary>Increments the dispatch-invocation count.</summary> |
| | 1297 | | /// <remarks>This method must be called with _mutex locked.</remarks> |
| | 1298 | | private void IncrementDispatchInvocationCount() |
| 5624 | 1299 | | { |
| 5624 | 1300 | | if (_dispatchInvocationCount++ == 0 && _streamInputOutputCount == 0) |
| 844 | 1301 | | { |
| | 1302 | | // Cancel inactivity check. |
| 844 | 1303 | | _inactivityTimeoutTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); |
| 844 | 1304 | | } |
| 5624 | 1305 | | } |
| | 1306 | |
|
| | 1307 | | /// <summary>Increments the stream input/output count.</summary> |
| | 1308 | | /// <remarks>This method must be called with _mutex locked.</remarks> |
| | 1309 | | private void IncrementStreamInputOutputCount(bool bidirectional) |
| 5582 | 1310 | | { |
| 5582 | 1311 | | Debug.Assert(_dispatchInvocationCount > 0); |
| 5582 | 1312 | | _streamInputOutputCount += bidirectional ? 2 : 1; |
| 5582 | 1313 | | } |
| | 1314 | |
|
| | 1315 | | private async Task ReadGoAwayAsync(CancellationToken cancellationToken) |
| 567 | 1316 | | { |
| 567 | 1317 | | await Task.Yield(); // exit mutex lock |
| | 1318 | |
|
| | 1319 | | // Wait for _connectTask (which spawned the task running this method) to complete. This await can't fail. |
| | 1320 | | // This guarantees this method won't request a shutdown until after _connectTask completed successfully. |
| 567 | 1321 | | await _connectTask!.ConfigureAwait(false); |
| | 1322 | |
|
| 567 | 1323 | | PipeReader remoteInput = _remoteControlStream!.Input!; |
| | 1324 | |
|
| | 1325 | | try |
| 567 | 1326 | | { |
| | 1327 | | // Wait to receive the GoAway frame. |
| 567 | 1328 | | await ReceiveControlFrameHeaderAsync(IceRpcControlFrameType.GoAway, cancellationToken) |
| 567 | 1329 | | .ConfigureAwait(false); |
| | 1330 | |
|
| 140 | 1331 | | ReadResult readResult = await remoteInput.ReadSegmentAsync( |
| 140 | 1332 | | SliceEncoding.Slice2, |
| 140 | 1333 | | MaxGoAwayFrameBodySize, |
| 140 | 1334 | | cancellationToken).ConfigureAwait(false); |
| | 1335 | |
|
| | 1336 | | // We don't call CancelPendingRead on remoteInput |
| 136 | 1337 | | Debug.Assert(!readResult.IsCanceled); |
| | 1338 | |
|
| | 1339 | | try |
| 136 | 1340 | | { |
| 136 | 1341 | | _goAwayFrame = SliceEncoding.Slice2.DecodeBuffer( |
| 136 | 1342 | | readResult.Buffer, |
| 272 | 1343 | | (ref SliceDecoder decoder) => new IceRpcGoAway(ref decoder)); |
| 134 | 1344 | | } |
| | 1345 | | finally |
| 136 | 1346 | | { |
| 136 | 1347 | | remoteInput.AdvanceTo(readResult.Buffer.End); |
| 136 | 1348 | | } |
| | 1349 | |
|
| 134 | 1350 | | RefuseNewInvocations("The connection was shut down because it received a GoAway frame from the peer."); |
| 134 | 1351 | | _goAwayCts.Cancel(); |
| 134 | 1352 | | _ = _shutdownRequestedTcs.TrySetResult(); |
| 134 | 1353 | | } |
| 259 | 1354 | | catch (OperationCanceledException) |
| 259 | 1355 | | { |
| | 1356 | | // The connection is disposed and we let this exception cancel the task. |
| 259 | 1357 | | throw; |
| | 1358 | | } |
| 164 | 1359 | | catch (IceRpcException) |
| 164 | 1360 | | { |
| | 1361 | | // We let the task complete with this expected exception. |
| 164 | 1362 | | throw; |
| | 1363 | | } |
| 10 | 1364 | | catch (InvalidDataException exception) |
| 10 | 1365 | | { |
| | 1366 | | // "expected" in the sense it should not trigger a Debug.Fail. |
| 10 | 1367 | | throw new IceRpcException( |
| 10 | 1368 | | IceRpcError.IceRpcError, |
| 10 | 1369 | | "The ReadGoAway task was aborted by an icerpc protocol error.", |
| 10 | 1370 | | exception); |
| | 1371 | | } |
| 0 | 1372 | | catch (Exception exception) |
| 0 | 1373 | | { |
| 0 | 1374 | | Debug.Fail($"The read go away task failed with an unexpected exception: {exception}"); |
| 0 | 1375 | | throw; |
| | 1376 | | } |
| 134 | 1377 | | } |
| | 1378 | |
|
| | 1379 | | private async ValueTask ReceiveControlFrameHeaderAsync( |
| | 1380 | | IceRpcControlFrameType expectedFrameType, |
| | 1381 | | CancellationToken cancellationToken) |
| 1157 | 1382 | | { |
| 1157 | 1383 | | ReadResult readResult = await _remoteControlStream!.Input.ReadAsync(cancellationToken).ConfigureAwait(false); |
| | 1384 | |
|
| | 1385 | | // We don't call CancelPendingRead on _remoteControlStream.Input. |
| 725 | 1386 | | Debug.Assert(!readResult.IsCanceled); |
| | 1387 | |
|
| 725 | 1388 | | if (readResult.Buffer.IsEmpty) |
| 2 | 1389 | | { |
| 2 | 1390 | | throw new InvalidDataException( |
| 2 | 1391 | | "Failed to read the frame type because no more data is available from the control stream."); |
| | 1392 | | } |
| | 1393 | |
|
| 723 | 1394 | | var frameType = (IceRpcControlFrameType)readResult.Buffer.FirstSpan[0]; |
| 723 | 1395 | | if (frameType != expectedFrameType) |
| 6 | 1396 | | { |
| 6 | 1397 | | throw new InvalidDataException($"Received frame type {frameType} but expected {expectedFrameType}."); |
| | 1398 | | } |
| 717 | 1399 | | _remoteControlStream!.Input.AdvanceTo(readResult.Buffer.GetPosition(1)); |
| 717 | 1400 | | } |
| | 1401 | |
|
| | 1402 | | private async ValueTask ReceiveSettingsFrameBody(CancellationToken cancellationToken) |
| 577 | 1403 | | { |
| | 1404 | | // We are still in the single-threaded initialization at this point. |
| | 1405 | |
|
| 577 | 1406 | | PipeReader input = _remoteControlStream!.Input; |
| 577 | 1407 | | ReadResult readResult = await input.ReadSegmentAsync( |
| 577 | 1408 | | SliceEncoding.Slice2, |
| 577 | 1409 | | MaxSettingsFrameBodySize, |
| 577 | 1410 | | cancellationToken).ConfigureAwait(false); |
| | 1411 | |
|
| | 1412 | | // We don't call CancelPendingRead on _remoteControlStream.Input |
| 575 | 1413 | | Debug.Assert(!readResult.IsCanceled); |
| | 1414 | |
|
| | 1415 | | try |
| 575 | 1416 | | { |
| 575 | 1417 | | IceRpcSettings settings = SliceEncoding.Slice2.DecodeBuffer( |
| 575 | 1418 | | readResult.Buffer, |
| 1150 | 1419 | | (ref SliceDecoder decoder) => new IceRpcSettings(ref decoder)); |
| | 1420 | |
|
| 569 | 1421 | | if (settings.Value.TryGetValue(IceRpcSettingKey.MaxHeaderSize, out ulong value)) |
| 6 | 1422 | | { |
| | 1423 | | // a varuint62 always fits in a long |
| | 1424 | | try |
| 6 | 1425 | | { |
| 6 | 1426 | | _maxPeerHeaderSize = ConnectionOptions.IceRpcCheckMaxHeaderSize((long)value); |
| 4 | 1427 | | } |
| 2 | 1428 | | catch (ArgumentOutOfRangeException exception) |
| 2 | 1429 | | { |
| 2 | 1430 | | throw new InvalidDataException("Received invalid maximum header size setting.", exception); |
| | 1431 | | } |
| 4 | 1432 | | _headerSizeLength = SliceEncoder.GetVarUInt62EncodedSize(value); |
| 4 | 1433 | | } |
| | 1434 | | // all other settings are unknown and ignored |
| 567 | 1435 | | } |
| | 1436 | | finally |
| 575 | 1437 | | { |
| 575 | 1438 | | input.AdvanceTo(readResult.Buffer.End); |
| 575 | 1439 | | } |
| 567 | 1440 | | } |
| | 1441 | |
|
| | 1442 | | private void RefuseNewInvocations(string message) |
| 1174 | 1443 | | { |
| 1174 | 1444 | | lock (_mutex) |
| 1174 | 1445 | | { |
| 1174 | 1446 | | _refuseInvocations = true; |
| 1174 | 1447 | | _invocationRefusedMessage ??= message; |
| 1174 | 1448 | | } |
| 1174 | 1449 | | } |
| | 1450 | |
|
| | 1451 | | // The inactivity check executes once in _inactivityTimeout. By then either: |
| | 1452 | | // - the connection is no longer inactive (and the inactivity check is canceled or being canceled) |
| | 1453 | | // - the connection is still inactive and we request shutdown |
| | 1454 | | private void ScheduleInactivityCheck() => |
| 1330 | 1455 | | _inactivityTimeoutTimer.Change(_inactivityTimeout, Timeout.InfiniteTimeSpan); |
| | 1456 | |
|
| | 1457 | | private ValueTask<FlushResult> SendControlFrameAsync( |
| | 1458 | | IceRpcControlFrameType frameType, |
| | 1459 | | EncodeAction encodeAction, |
| | 1460 | | CancellationToken cancellationToken) |
| 779 | 1461 | | { |
| 779 | 1462 | | PipeWriter output = _controlStream!.Output; |
| | 1463 | |
|
| 779 | 1464 | | EncodeFrame(output); |
| | 1465 | |
|
| 779 | 1466 | | return output.FlushAsync(cancellationToken); // Flush |
| | 1467 | |
|
| | 1468 | | void EncodeFrame(IBufferWriter<byte> buffer) |
| 779 | 1469 | | { |
| 779 | 1470 | | var encoder = new SliceEncoder(buffer, SliceEncoding.Slice2); |
| 779 | 1471 | | encoder.EncodeIceRpcControlFrameType(frameType); |
| 779 | 1472 | | Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(_headerSizeLength); |
| 779 | 1473 | | int startPos = encoder.EncodedByteCount; // does not include the size |
| 779 | 1474 | | encodeAction.Invoke(ref encoder); |
| 779 | 1475 | | int frameSize = encoder.EncodedByteCount - startPos; |
| 779 | 1476 | | SliceEncoder.EncodeVarUInt62((uint)frameSize, sizePlaceholder); |
| 779 | 1477 | | } |
| 779 | 1478 | | } |
| | 1479 | |
|
| | 1480 | | /// <summary>Sends the payload continuation of an outgoing request in the background.</summary> |
| | 1481 | | /// <remarks>We send the payload continuation on a separate thread with Task.Run: this ensures that the synchronous |
| | 1482 | | /// activity that could result from reading or writing the payload continuation doesn't delay in any way the |
| | 1483 | | /// caller. </remarks> |
| | 1484 | | /// <param name="request">The outgoing request.</param> |
| | 1485 | | /// <param name="payloadWriter">The payload writer.</param> |
| | 1486 | | /// <param name="writesClosed">A task that completes when we can no longer write to payloadWriter.</param> |
| | 1487 | | /// <param name="onGoAway">An action to execute with a CTS when we receive the GoAway frame from the peer.</param> |
| | 1488 | | /// <param name="cancellationToken">The cancellation token of the invocation; the associated CTS is disposed when |
| | 1489 | | /// the invocation completes.</param> |
| | 1490 | | private void SendRequestPayloadContinuation( |
| | 1491 | | OutgoingRequest request, |
| | 1492 | | PipeWriter payloadWriter, |
| | 1493 | | Task writesClosed, |
| | 1494 | | Action<object?> onGoAway, |
| | 1495 | | CancellationToken cancellationToken) |
| 24 | 1496 | | { |
| 24 | 1497 | | Debug.Assert(request.PayloadContinuation is not null); |
| | 1498 | |
|
| | 1499 | | // First "detach" the continuation. |
| 24 | 1500 | | PipeReader payloadContinuation = request.PayloadContinuation; |
| 24 | 1501 | | request.PayloadContinuation = null; |
| | 1502 | |
|
| 24 | 1503 | | lock (_mutex) |
| 24 | 1504 | | { |
| 24 | 1505 | | Debug.Assert(_dispatchInvocationCount > 0); // as a result, can't be disposed. |
| | 1506 | |
|
| | 1507 | | // Give the task its own dispatch-invocation count. This ensures the transport connection won't be disposed |
| | 1508 | | // while the continuation is being sent. |
| 24 | 1509 | | IncrementDispatchInvocationCount(); |
| 24 | 1510 | | } |
| | 1511 | |
|
| | 1512 | | // This background task owns payloadContinuation, payloadWriter and 1 dispatch-invocation count, and must clean |
| | 1513 | | // them up. Hence CancellationToken.None. |
| 24 | 1514 | | _ = Task.Run(PerformSendRequestPayloadContinuationAsync, CancellationToken.None); |
| | 1515 | |
|
| | 1516 | | async Task PerformSendRequestPayloadContinuationAsync() |
| 24 | 1517 | | { |
| 24 | 1518 | | bool success = false; |
| | 1519 | |
|
| | 1520 | | try |
| 24 | 1521 | | { |
| | 1522 | | // Since _dispatchInvocationCount > 0, _disposedCts is not disposed. |
| 24 | 1523 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposedCts.Token); |
| | 1524 | |
|
| | 1525 | | // This token registration is needed for one-way requests and is redundant for two-way requests. |
| | 1526 | | // We want GoAway to cancel the sending of one-way requests that have not been received by the peer, |
| | 1527 | | // especially when these requests have payload continuations. |
| 24 | 1528 | | using CancellationTokenRegistration tokenRegistration = _goAwayCts.Token.UnsafeRegister(onGoAway, cts); |
| | 1529 | |
|
| | 1530 | | try |
| 24 | 1531 | | { |
| | 1532 | | // The cancellation of the InvokeAsync's cancellationToken cancels cts only until InvokeAsync's |
| | 1533 | | // PerformInvokeAsync completes. Afterwards, the cancellation of InvokeAsync's cancellationToken has |
| | 1534 | | // no effect on cts, so it doesn't cancel the copying of payloadContinuation. |
| 24 | 1535 | | FlushResult flushResult = await payloadWriter.CopyFromAsync( |
| 24 | 1536 | | payloadContinuation, |
| 24 | 1537 | | writesClosed, |
| 24 | 1538 | | endStream: true, |
| 24 | 1539 | | cts.Token).ConfigureAwait(false); |
| | 1540 | |
|
| 10 | 1541 | | success = !flushResult.IsCanceled; |
| 10 | 1542 | | } |
| 6 | 1543 | | catch (OperationCanceledException exception) when (exception.CancellationToken == cts.Token) |
| 4 | 1544 | | { |
| | 1545 | | // Process/translate this exception primarily for the benefit of _taskExceptionObserver. |
| | 1546 | |
|
| | 1547 | | // Can be because cancellationToken was canceled by DisposeAsync or GoAway; that's fine. |
| 4 | 1548 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 1549 | |
|
| 2 | 1550 | | if (_disposedCts.IsCancellationRequested) |
| 0 | 1551 | | { |
| | 1552 | | // DisposeAsync aborted the request. |
| 0 | 1553 | | throw new IceRpcException(IceRpcError.OperationAborted); |
| | 1554 | | } |
| | 1555 | | else |
| 2 | 1556 | | { |
| | 1557 | | // When _goAwayCts is canceled and onGoAway cancels its argument: |
| | 1558 | | // - if PerformInvokeAsync is no longer running (typical for a one-way request), we get here |
| | 1559 | | // - if PerformInvokeAsync is still running, we may get here or cancellationToken gets canceled |
| | 1560 | | // first. |
| 2 | 1561 | | Debug.Assert(_goAwayCts.IsCancellationRequested); |
| 2 | 1562 | | throw new IceRpcException(IceRpcError.InvocationCanceled, "The connection is shutting down."); |
| | 1563 | | } |
| | 1564 | | } |
| 10 | 1565 | | } |
| 14 | 1566 | | catch (Exception exception) when (_taskExceptionObserver is not null) |
| 10 | 1567 | | { |
| 10 | 1568 | | _taskExceptionObserver.RequestPayloadContinuationFailed( |
| 10 | 1569 | | request, |
| 10 | 1570 | | _connectionContext!.TransportConnectionInformation, |
| 10 | 1571 | | exception); |
| 10 | 1572 | | } |
| 2 | 1573 | | catch (OperationCanceledException exception) when (exception.CancellationToken == cancellationToken) |
| 2 | 1574 | | { |
| | 1575 | | // Expected. |
| 2 | 1576 | | } |
| 2 | 1577 | | catch (IceRpcException) |
| 2 | 1578 | | { |
| | 1579 | | // Expected, with for example IceRpcError.ConnectionAborted when the peer aborts the connection. |
| 2 | 1580 | | } |
| 0 | 1581 | | catch (Exception exception) |
| 0 | 1582 | | { |
| | 1583 | | // This exception is unexpected when running the IceRPC test suite. A test that expects such an |
| | 1584 | | // exception must install a task exception observer. |
| 0 | 1585 | | Debug.Fail($"Failed to send payload continuation of request {request}: {exception}"); |
| | 1586 | |
|
| | 1587 | | // If Debug is not enabled and there is no task exception observer, we rethrow to generate an |
| | 1588 | | // Unobserved Task Exception. |
| 0 | 1589 | | throw; |
| | 1590 | | } |
| | 1591 | | finally |
| 24 | 1592 | | { |
| 24 | 1593 | | payloadWriter.CompleteOutput(success); |
| 24 | 1594 | | payloadContinuation.Complete(); |
| 24 | 1595 | | DecrementDispatchInvocationCount(); |
| 24 | 1596 | | } |
| 24 | 1597 | | } |
| 24 | 1598 | | } |
| | 1599 | | } |