| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using IceRpc.Transports; |
| | 4 | | using IceRpc.Transports.Internal; |
| | 5 | | using System.Buffers; |
| | 6 | | using System.Collections.Immutable; |
| | 7 | | using System.Diagnostics; |
| | 8 | | using System.IO.Pipelines; |
| | 9 | | using System.Security.Authentication; |
| | 10 | | using ZeroC.Slice; |
| | 11 | |
|
| | 12 | | namespace IceRpc.Internal; |
| | 13 | |
|
| | 14 | | /// <summary>Implements <see cref="IProtocolConnection" /> for the ice protocol.</summary> |
| | 15 | | internal sealed class IceProtocolConnection : IProtocolConnection |
| | 16 | | { |
| 1 | 17 | | private static readonly IDictionary<RequestFieldKey, ReadOnlySequence<byte>> _idempotentFields = |
| 1 | 18 | | new Dictionary<RequestFieldKey, ReadOnlySequence<byte>> |
| 1 | 19 | | { |
| 1 | 20 | | [RequestFieldKey.Idempotent] = default |
| 1 | 21 | | }.ToImmutableDictionary(); |
| | 22 | |
|
| 350 | 23 | | private bool IsServer => _transportConnectionInformation is not null; |
| | 24 | |
|
| | 25 | | private IConnectionContext? _connectionContext; // non-null once the connection is established |
| | 26 | | private Task? _connectTask; |
| | 27 | | private readonly IDispatcher _dispatcher; |
| | 28 | |
|
| | 29 | | // The number of outstanding dispatches and invocations. |
| | 30 | | private int _dispatchInvocationCount; |
| | 31 | |
|
| | 32 | | // We don't want the continuation to run from the dispatch or invocation thread. |
| 372 | 33 | | private readonly TaskCompletionSource _dispatchesAndInvocationsCompleted = |
| 372 | 34 | | new(TaskCreationOptions.RunContinuationsAsynchronously); |
| | 35 | |
|
| | 36 | | private readonly SemaphoreSlim? _dispatchSemaphore; |
| | 37 | |
|
| | 38 | | // This cancellation token source is canceled when the connection is disposed. |
| 372 | 39 | | private readonly CancellationTokenSource _disposedCts = new(); |
| | 40 | |
|
| | 41 | | private Task? _disposeTask; |
| | 42 | | private readonly IDuplexConnection _duplexConnection; |
| | 43 | | private readonly DuplexConnectionReader _duplexConnectionReader; |
| | 44 | | private readonly IceDuplexConnectionWriter _duplexConnectionWriter; |
| 372 | 45 | | private bool _heartbeatEnabled = true; |
| 372 | 46 | | private Task _heartbeatTask = Task.CompletedTask; |
| | 47 | | private readonly TimeSpan _inactivityTimeout; |
| | 48 | | private readonly Timer _inactivityTimeoutTimer; |
| | 49 | | private string? _invocationRefusedMessage; |
| | 50 | | private int _lastRequestId; |
| | 51 | | private readonly int _maxFrameSize; |
| 372 | 52 | | private readonly object _mutex = new(); |
| | 53 | | private readonly PipeOptions _pipeOptions; |
| | 54 | | private Task? _readFramesTask; |
| | 55 | |
|
| | 56 | | // A connection refuses invocations when it's disposed, shut down, shutting down or merely "shutdown requested". |
| | 57 | | private bool _refuseInvocations; |
| | 58 | |
|
| | 59 | | // Does ShutdownAsync send a close connection frame? |
| 372 | 60 | | private bool _sendCloseConnectionFrame = true; |
| | 61 | |
|
| | 62 | | private Task? _shutdownTask; |
| | 63 | |
|
| | 64 | | // The thread that completes this TCS can run the continuations, and as a result its result must be set without |
| | 65 | | // holding a lock on _mutex. |
| 372 | 66 | | private readonly TaskCompletionSource _shutdownRequestedTcs = new(); |
| | 67 | |
|
| | 68 | | // Only set for server connections. |
| | 69 | | private readonly TransportConnectionInformation? _transportConnectionInformation; |
| | 70 | |
|
| | 71 | | private readonly CancellationTokenSource _twowayDispatchesCts; |
| 372 | 72 | | private readonly Dictionary<int, TaskCompletionSource<PipeReader>> _twowayInvocations = new(); |
| | 73 | |
|
| | 74 | | private Exception? _writeException; // protected by _writeSemaphore |
| 372 | 75 | | private readonly SemaphoreSlim _writeSemaphore = new(1, 1); |
| | 76 | |
|
| | 77 | | public Task<(TransportConnectionInformation ConnectionInformation, Task ShutdownRequested)> ConnectAsync( |
| | 78 | | CancellationToken cancellationToken) |
| 370 | 79 | | { |
| | 80 | | Task<(TransportConnectionInformation ConnectionInformation, Task ShutdownRequested)> result; |
| 370 | 81 | | lock (_mutex) |
| 370 | 82 | | { |
| 370 | 83 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 84 | |
|
| 366 | 85 | | if (_connectTask is not null) |
| 0 | 86 | | { |
| 0 | 87 | | throw new InvalidOperationException("Cannot call connect more than once."); |
| | 88 | | } |
| | 89 | |
|
| 366 | 90 | | result = PerformConnectAsync(); |
| 366 | 91 | | _connectTask = result; |
| 366 | 92 | | } |
| 366 | 93 | | return result; |
| | 94 | |
|
| | 95 | | async Task<(TransportConnectionInformation ConnectionInformation, Task ShutdownRequested)> PerformConnectAsync() |
| 366 | 96 | | { |
| | 97 | | // Make sure we execute the function without holding the connection mutex lock. |
| 366 | 98 | | await Task.Yield(); |
| | 99 | |
|
| | 100 | | // _disposedCts is not disposed at this point because DisposeAsync waits for the completion of _connectTask. |
| 366 | 101 | | using var connectCts = CancellationTokenSource.CreateLinkedTokenSource( |
| 366 | 102 | | cancellationToken, |
| 366 | 103 | | _disposedCts.Token); |
| | 104 | |
|
| | 105 | | TransportConnectionInformation transportConnectionInformation; |
| | 106 | |
|
| | 107 | | try |
| 366 | 108 | | { |
| | 109 | | // If the transport connection information is null, we need to connect the transport connection. It's |
| | 110 | | // null for client connections. The transport connection of a server connection is established by |
| | 111 | | // Server. |
| 366 | 112 | | transportConnectionInformation = _transportConnectionInformation ?? |
| 366 | 113 | | await _duplexConnection.ConnectAsync(connectCts.Token).ConfigureAwait(false); |
| | 114 | |
|
| 350 | 115 | | if (IsServer) |
| 169 | 116 | | { |
| | 117 | | // Send ValidateConnection frame. |
| 169 | 118 | | await SendControlFrameAsync(EncodeValidateConnectionFrame, connectCts.Token).ConfigureAwait(false); |
| | 119 | |
|
| | 120 | | // The SendControlFrameAsync is a "write" that schedules a heartbeat when the idle timeout is not |
| | 121 | | // infinite. So no need to call ScheduleHeartbeat. |
| 165 | 122 | | } |
| | 123 | | else |
| 181 | 124 | | { |
| 181 | 125 | | ReadOnlySequence<byte> buffer = await _duplexConnectionReader.ReadAtLeastAsync( |
| 181 | 126 | | IceDefinitions.PrologueSize, |
| 181 | 127 | | connectCts.Token).ConfigureAwait(false); |
| | 128 | |
|
| 161 | 129 | | (IcePrologue validateConnectionFrame, long consumed) = DecodeValidateConnectionFrame(buffer); |
| 161 | 130 | | _duplexConnectionReader.AdvanceTo(buffer.GetPosition(consumed), buffer.End); |
| | 131 | |
|
| 161 | 132 | | IceDefinitions.CheckPrologue(validateConnectionFrame); |
| 159 | 133 | | if (validateConnectionFrame.FrameSize != IceDefinitions.PrologueSize) |
| 0 | 134 | | { |
| 0 | 135 | | throw new InvalidDataException( |
| 0 | 136 | | $"Received ice frame with only '{validateConnectionFrame.FrameSize}' bytes."); |
| | 137 | | } |
| 159 | 138 | | if (validateConnectionFrame.FrameType != IceFrameType.ValidateConnection) |
| 0 | 139 | | { |
| 0 | 140 | | throw new InvalidDataException( |
| 0 | 141 | | $"Expected '{nameof(IceFrameType.ValidateConnection)}' frame but received frame type '{valid |
| | 142 | | } |
| | 143 | |
|
| | 144 | | // The client connection is now connected, so we schedule the first heartbeat. |
| 159 | 145 | | if (_duplexConnection is IceDuplexConnectionDecorator decorator) |
| 159 | 146 | | { |
| 159 | 147 | | decorator.ScheduleHeartbeat(); |
| 159 | 148 | | } |
| 159 | 149 | | } |
| 324 | 150 | | } |
| 22 | 151 | | catch (OperationCanceledException) |
| 22 | 152 | | { |
| 22 | 153 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 154 | |
|
| 10 | 155 | | Debug.Assert(_disposedCts.Token.IsCancellationRequested); |
| 10 | 156 | | throw new IceRpcException( |
| 10 | 157 | | IceRpcError.OperationAborted, |
| 10 | 158 | | "The connection establishment was aborted because the connection was disposed."); |
| | 159 | | } |
| 2 | 160 | | catch (InvalidDataException exception) |
| 2 | 161 | | { |
| 2 | 162 | | throw new IceRpcException( |
| 2 | 163 | | IceRpcError.ConnectionAborted, |
| 2 | 164 | | "The connection was aborted by an ice protocol error.", |
| 2 | 165 | | exception); |
| | 166 | | } |
| 2 | 167 | | catch (AuthenticationException) |
| 2 | 168 | | { |
| 2 | 169 | | throw; |
| | 170 | | } |
| 16 | 171 | | catch (IceRpcException) |
| 16 | 172 | | { |
| 16 | 173 | | throw; |
| | 174 | | } |
| 0 | 175 | | catch (Exception exception) |
| 0 | 176 | | { |
| 0 | 177 | | Debug.Fail($"ConnectAsync failed with an unexpected exception: {exception}"); |
| 0 | 178 | | throw; |
| | 179 | | } |
| | 180 | |
|
| | 181 | | // We assign _readFramesTask with _mutex locked to make sure this assignment occurs before the start of |
| | 182 | | // DisposeAsync. Once _disposeTask is not null, _readFramesTask is immutable. |
| 324 | 183 | | lock (_mutex) |
| 324 | 184 | | { |
| 324 | 185 | | if (_disposeTask is not null) |
| 0 | 186 | | { |
| 0 | 187 | | throw new IceRpcException( |
| 0 | 188 | | IceRpcError.OperationAborted, |
| 0 | 189 | | "The connection establishment was aborted because the connection was disposed."); |
| | 190 | | } |
| | 191 | |
|
| | 192 | | // This needs to be set before starting the read frames task below. |
| 324 | 193 | | _connectionContext = new ConnectionContext(this, transportConnectionInformation); |
| | 194 | |
|
| 324 | 195 | | _readFramesTask = ReadFramesAsync(_disposedCts.Token); |
| 324 | 196 | | } |
| | 197 | |
|
| | 198 | | // The _readFramesTask waits for this PerformConnectAsync completion before reading anything. As soon as |
| | 199 | | // it receives a request, it will cancel this inactivity check. |
| 324 | 200 | | ScheduleInactivityCheck(); |
| | 201 | |
|
| 324 | 202 | | return (transportConnectionInformation, _shutdownRequestedTcs.Task); |
| | 203 | |
|
| | 204 | | static void EncodeValidateConnectionFrame(IBufferWriter<byte> writer) |
| 169 | 205 | | { |
| 169 | 206 | | var encoder = new SliceEncoder(writer, SliceEncoding.Slice1); |
| 169 | 207 | | IceDefinitions.ValidateConnectionFrame.Encode(ref encoder); |
| 169 | 208 | | } |
| | 209 | |
|
| | 210 | | static (IcePrologue, long) DecodeValidateConnectionFrame(ReadOnlySequence<byte> buffer) |
| 161 | 211 | | { |
| 161 | 212 | | var decoder = new SliceDecoder(buffer, SliceEncoding.Slice1); |
| 161 | 213 | | return (new IcePrologue(ref decoder), decoder.Consumed); |
| 161 | 214 | | } |
| 324 | 215 | | } |
| 366 | 216 | | } |
| | 217 | |
|
| | 218 | | public ValueTask DisposeAsync() |
| 412 | 219 | | { |
| 412 | 220 | | lock (_mutex) |
| 412 | 221 | | { |
| 412 | 222 | | if (_disposeTask is null) |
| 372 | 223 | | { |
| 372 | 224 | | RefuseNewInvocations("The connection was disposed."); |
| | 225 | |
|
| 372 | 226 | | _shutdownTask ??= Task.CompletedTask; |
| 372 | 227 | | if (_dispatchInvocationCount == 0) |
| 353 | 228 | | { |
| 353 | 229 | | _dispatchesAndInvocationsCompleted.TrySetResult(); |
| 353 | 230 | | } |
| | 231 | |
|
| 372 | 232 | | _heartbeatEnabled = false; // makes _heartbeatTask immutable |
| | 233 | |
|
| 372 | 234 | | _disposeTask = PerformDisposeAsync(); |
| 372 | 235 | | } |
| 412 | 236 | | } |
| 412 | 237 | | return new(_disposeTask); |
| | 238 | |
|
| | 239 | | async Task PerformDisposeAsync() |
| 372 | 240 | | { |
| | 241 | | // Make sure we execute the code below without holding the mutex lock. |
| 372 | 242 | | await Task.Yield(); |
| | 243 | |
|
| 372 | 244 | | _disposedCts.Cancel(); |
| | 245 | |
|
| | 246 | | // We don't lock _mutex since once _disposeTask is not null, _connectTask etc are immutable. |
| | 247 | |
|
| 372 | 248 | | if (_connectTask is not null) |
| 366 | 249 | | { |
| | 250 | | // Wait for all writes to complete. This can't take forever since all writes are canceled by |
| | 251 | | // _disposedCts.Token. |
| 366 | 252 | | await _writeSemaphore.WaitAsync().ConfigureAwait(false); |
| | 253 | |
|
| | 254 | | try |
| 366 | 255 | | { |
| 366 | 256 | | await Task.WhenAll( |
| 366 | 257 | | _connectTask, |
| 366 | 258 | | _readFramesTask ?? Task.CompletedTask, |
| 366 | 259 | | _heartbeatTask, |
| 366 | 260 | | _dispatchesAndInvocationsCompleted.Task, |
| 366 | 261 | | _shutdownTask).ConfigureAwait(false); |
| 262 | 262 | | } |
| 104 | 263 | | catch |
| 104 | 264 | | { |
| | 265 | | // Expected if any of these tasks failed or was canceled. Each task takes care of handling |
| | 266 | | // unexpected exceptions so there's no need to handle them here. |
| 104 | 267 | | } |
| 366 | 268 | | } |
| | 269 | |
|
| 372 | 270 | | _duplexConnection.Dispose(); |
| | 271 | |
|
| | 272 | | // It's safe to dispose the reader/writer since no more threads are sending/receiving data. |
| 372 | 273 | | _duplexConnectionReader.Dispose(); |
| 372 | 274 | | _duplexConnectionWriter.Dispose(); |
| | 275 | |
|
| 372 | 276 | | _disposedCts.Dispose(); |
| 372 | 277 | | _twowayDispatchesCts.Dispose(); |
| | 278 | |
|
| 372 | 279 | | _dispatchSemaphore?.Dispose(); |
| 372 | 280 | | _writeSemaphore.Dispose(); |
| 372 | 281 | | await _inactivityTimeoutTimer.DisposeAsync().ConfigureAwait(false); |
| 372 | 282 | | } |
| 412 | 283 | | } |
| | 284 | |
|
| | 285 | | public Task<IncomingResponse> InvokeAsync(OutgoingRequest request, CancellationToken cancellationToken = default) |
| 2723 | 286 | | { |
| 2723 | 287 | | if (request.Protocol != Protocol.Ice) |
| 2 | 288 | | { |
| 2 | 289 | | throw new InvalidOperationException( |
| 2 | 290 | | $"Cannot send {request.Protocol} request on {Protocol.Ice} connection."); |
| | 291 | | } |
| | 292 | |
|
| 2721 | 293 | | lock (_mutex) |
| 2721 | 294 | | { |
| 2721 | 295 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 296 | |
|
| 2719 | 297 | | if (_refuseInvocations) |
| 2 | 298 | | { |
| 2 | 299 | | throw new IceRpcException(IceRpcError.InvocationRefused, _invocationRefusedMessage); |
| | 300 | | } |
| 2717 | 301 | | if (_connectTask is null || !_connectTask.IsCompletedSuccessfully) |
| 0 | 302 | | { |
| 0 | 303 | | throw new InvalidOperationException("Cannot invoke on a connection that is not fully established."); |
| | 304 | | } |
| | 305 | |
|
| 2717 | 306 | | IncrementDispatchInvocationCount(); |
| 2717 | 307 | | } |
| | 308 | |
|
| 2717 | 309 | | return PerformInvokeAsync(); |
| | 310 | |
|
| | 311 | | async Task<IncomingResponse> PerformInvokeAsync() |
| 2717 | 312 | | { |
| | 313 | | // Since _dispatchInvocationCount > 0, _disposedCts is not disposed. |
| 2717 | 314 | | using var invocationCts = |
| 2717 | 315 | | CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token, cancellationToken); |
| | 316 | |
|
| 2717 | 317 | | PipeReader? frameReader = null; |
| 2717 | 318 | | TaskCompletionSource<PipeReader>? responseCompletionSource = null; |
| 2717 | 319 | | int requestId = 0; |
| | 320 | |
|
| | 321 | | try |
| 2717 | 322 | | { |
| | 323 | | // Read the full payload. This can take some time so this needs to be done before acquiring the write |
| | 324 | | // semaphore. |
| 2717 | 325 | | ReadOnlySequence<byte> payloadBuffer = await ReadFullPayloadAsync(request.Payload, invocationCts.Token) |
| 2717 | 326 | | .ConfigureAwait(false); |
| | 327 | |
|
| | 328 | | try |
| 2717 | 329 | | { |
| | 330 | | // Wait for the writing of other frames to complete. |
| 2717 | 331 | | using SemaphoreLock _ = await AcquireWriteLockAsync(invocationCts.Token).ConfigureAwait(false); |
| | 332 | |
|
| | 333 | | // Assign the request ID for two-way invocations and keep track of the invocation for receiving the |
| | 334 | | // response. The request ID is only assigned once the write semaphore is acquired. We don't want a |
| | 335 | | // canceled request to allocate a request ID that won't be used. |
| 2717 | 336 | | lock (_mutex) |
| 2717 | 337 | | { |
| 2717 | 338 | | if (_refuseInvocations) |
| 0 | 339 | | { |
| | 340 | | // It's InvocationCanceled and not InvocationRefused because we've read the payload. |
| 0 | 341 | | throw new IceRpcException(IceRpcError.InvocationCanceled, _invocationRefusedMessage); |
| | 342 | | } |
| | 343 | |
|
| 2717 | 344 | | if (!request.IsOneway) |
| 701 | 345 | | { |
| | 346 | | // wrap around back to 1 if we reach int.MaxValue. 0 means one-way. |
| 701 | 347 | | _lastRequestId = _lastRequestId == int.MaxValue ? 1 : _lastRequestId + 1; |
| 701 | 348 | | requestId = _lastRequestId; |
| | 349 | |
|
| | 350 | | // RunContinuationsAsynchronously because we don't want the "read frames loop" to run the |
| | 351 | | // continuation. |
| 701 | 352 | | responseCompletionSource = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 701 | 353 | | _twowayInvocations[requestId] = responseCompletionSource; |
| 701 | 354 | | } |
| 2717 | 355 | | } |
| | 356 | |
|
| 2717 | 357 | | int payloadSize = checked((int)payloadBuffer.Length); |
| | 358 | |
|
| | 359 | | try |
| 2717 | 360 | | { |
| 2717 | 361 | | EncodeRequestHeader(_duplexConnectionWriter, request, requestId, payloadSize); |
| | 362 | |
|
| | 363 | | // We write to the duplex connection with _disposedCts.Token instead of invocationCts.Token. |
| | 364 | | // Canceling this write operation is fatal to the connection. |
| 2717 | 365 | | await _duplexConnectionWriter.WriteAsync(payloadBuffer, _disposedCts.Token) |
| 2717 | 366 | | .ConfigureAwait(false); |
| 2715 | 367 | | } |
| 2 | 368 | | catch (Exception exception) |
| 2 | 369 | | { |
| 2 | 370 | | WriteFailed(exception); |
| 2 | 371 | | throw; |
| | 372 | | } |
| 2715 | 373 | | } |
| 2 | 374 | | catch (IceRpcException exception) when (exception.IceRpcError != IceRpcError.InvocationCanceled) |
| 2 | 375 | | { |
| | 376 | | // Since we could not send the request, the server cannot dispatch it and it's safe to retry. |
| | 377 | | // This includes the situation where await AcquireWriteLockAsync throws because a previous write |
| | 378 | | // failed. |
| 2 | 379 | | throw new IceRpcException( |
| 2 | 380 | | IceRpcError.InvocationCanceled, |
| 2 | 381 | | "Failed to send ice request.", |
| 2 | 382 | | exception); |
| | 383 | | } |
| | 384 | | finally |
| 2717 | 385 | | { |
| | 386 | | // We've read the payload (see ReadFullPayloadAsync) and we are now done with it. |
| 2717 | 387 | | request.Payload.Complete(); |
| 2717 | 388 | | } |
| | 389 | |
|
| 2715 | 390 | | if (request.IsOneway) |
| 2016 | 391 | | { |
| | 392 | | // We're done, there's no response for one-way requests. |
| 2016 | 393 | | return new IncomingResponse(request, _connectionContext!); |
| | 394 | | } |
| | 395 | |
|
| | 396 | | // Wait to receive the response. |
| 699 | 397 | | Debug.Assert(responseCompletionSource is not null); |
| 699 | 398 | | frameReader = await responseCompletionSource.Task.WaitAsync(invocationCts.Token).ConfigureAwait(false); |
| | 399 | |
|
| 661 | 400 | | if (!frameReader.TryRead(out ReadResult readResult)) |
| 0 | 401 | | { |
| 0 | 402 | | throw new InvalidDataException($"Received empty response frame for request with id '{requestId}'."); |
| | 403 | | } |
| | 404 | |
|
| 661 | 405 | | Debug.Assert(readResult.IsCompleted); |
| | 406 | |
|
| 661 | 407 | | (StatusCode statusCode, string? errorMessage, SequencePosition consumed) = |
| 661 | 408 | | DecodeResponseHeader(readResult.Buffer, requestId); |
| | 409 | |
|
| 661 | 410 | | frameReader.AdvanceTo(consumed); |
| | 411 | |
|
| 661 | 412 | | var response = new IncomingResponse( |
| 661 | 413 | | request, |
| 661 | 414 | | _connectionContext!, |
| 661 | 415 | | statusCode, |
| 661 | 416 | | errorMessage) |
| 661 | 417 | | { |
| 661 | 418 | | Payload = frameReader |
| 661 | 419 | | }; |
| | 420 | |
|
| 661 | 421 | | frameReader = null; // response now owns frameReader |
| 661 | 422 | | return response; |
| | 423 | | } |
| 18 | 424 | | catch (OperationCanceledException) |
| 18 | 425 | | { |
| 18 | 426 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 427 | |
|
| 6 | 428 | | Debug.Assert(_disposedCts.Token.IsCancellationRequested); |
| 6 | 429 | | throw new IceRpcException( |
| 6 | 430 | | IceRpcError.OperationAborted, |
| 6 | 431 | | "The invocation was aborted because the connection was disposed."); |
| | 432 | | } |
| | 433 | | finally |
| 2717 | 434 | | { |
| | 435 | | // If responseCompletionSource is not completed, we want to complete it to prevent another method from |
| | 436 | | // setting an unobservable exception in it. And if it's already completed with an exception, we observe |
| | 437 | | // this exception. |
| 2717 | 438 | | if (responseCompletionSource is not null && |
| 2717 | 439 | | !responseCompletionSource.TrySetResult(InvalidPipeReader.Instance)) |
| 681 | 440 | | { |
| | 441 | | try |
| 681 | 442 | | { |
| 681 | 443 | | _ = await responseCompletionSource.Task.ConfigureAwait(false); |
| 661 | 444 | | } |
| 20 | 445 | | catch |
| 20 | 446 | | { |
| | 447 | | // observe exception, if any |
| 20 | 448 | | } |
| 681 | 449 | | } |
| | 450 | |
|
| 2717 | 451 | | lock (_mutex) |
| 2717 | 452 | | { |
| | 453 | | // Unregister the two-way invocation if registered. |
| 2717 | 454 | | if (requestId > 0 && !_refuseInvocations) |
| 665 | 455 | | { |
| 665 | 456 | | _twowayInvocations.Remove(requestId); |
| 665 | 457 | | } |
| | 458 | |
|
| 2717 | 459 | | DecrementDispatchInvocationCount(); |
| 2717 | 460 | | } |
| | 461 | |
|
| 2717 | 462 | | frameReader?.Complete(); |
| 2717 | 463 | | } |
| 2677 | 464 | | } |
| 2717 | 465 | | } |
| | 466 | |
|
| | 467 | | public Task ShutdownAsync(CancellationToken cancellationToken = default) |
| 111 | 468 | | { |
| 111 | 469 | | lock (_mutex) |
| 111 | 470 | | { |
| 111 | 471 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 472 | |
|
| 109 | 473 | | if (_shutdownTask is not null) |
| 0 | 474 | | { |
| 0 | 475 | | throw new InvalidOperationException("Cannot call ShutdownAsync more than once."); |
| | 476 | | } |
| 109 | 477 | | if (_connectTask is null || !_connectTask.IsCompletedSuccessfully) |
| 6 | 478 | | { |
| 6 | 479 | | throw new InvalidOperationException("Cannot shut down a protocol connection before it's connected."); |
| | 480 | | } |
| | 481 | |
|
| 103 | 482 | | RefuseNewInvocations("The connection was shut down."); |
| | 483 | |
|
| 103 | 484 | | if (_dispatchInvocationCount == 0) |
| 76 | 485 | | { |
| 76 | 486 | | _dispatchesAndInvocationsCompleted.TrySetResult(); |
| 76 | 487 | | } |
| 103 | 488 | | _shutdownTask = PerformShutdownAsync(_sendCloseConnectionFrame); |
| 103 | 489 | | } |
| | 490 | |
|
| 103 | 491 | | return _shutdownTask; |
| | 492 | |
|
| | 493 | | async Task PerformShutdownAsync(bool sendCloseConnectionFrame) |
| 103 | 494 | | { |
| 103 | 495 | | await Task.Yield(); // exit mutex lock |
| | 496 | |
|
| | 497 | | try |
| 103 | 498 | | { |
| 103 | 499 | | Debug.Assert(_readFramesTask is not null); |
| | 500 | |
|
| | 501 | | // Since DisposeAsync waits for the _shutdownTask completion, _disposedCts is not disposed at this |
| | 502 | | // point. |
| 103 | 503 | | using var shutdownCts = CancellationTokenSource.CreateLinkedTokenSource( |
| 103 | 504 | | cancellationToken, |
| 103 | 505 | | _disposedCts.Token); |
| | 506 | |
|
| | 507 | | // Wait for dispatches and invocations to complete. |
| 103 | 508 | | await _dispatchesAndInvocationsCompleted.Task.WaitAsync(shutdownCts.Token).ConfigureAwait(false); |
| | 509 | |
|
| | 510 | | // Stops sending heartbeats. We can't do earlier: while we're waiting for dispatches and invocations to |
| | 511 | | // complete, we need to keep sending heartbeats otherwise the peer could see the connection as idle and |
| | 512 | | // abort it. |
| 95 | 513 | | lock (_mutex) |
| 95 | 514 | | { |
| 95 | 515 | | _heartbeatEnabled = false; // makes _heartbeatTask immutable |
| 95 | 516 | | } |
| | 517 | |
|
| | 518 | | // Wait for the last send heartbeat to complete before sending the CloseConnection frame or disposing |
| | 519 | | // the duplex connection. _heartbeatTask is immutable once _shutdownTask set. _heartbeatTask can be |
| | 520 | | // canceled by DisposeAsync. |
| 95 | 521 | | await _heartbeatTask.WaitAsync(shutdownCts.Token).ConfigureAwait(false); |
| | 522 | |
|
| 95 | 523 | | if (sendCloseConnectionFrame) |
| 42 | 524 | | { |
| | 525 | | // Send CloseConnection frame. |
| 42 | 526 | | await SendControlFrameAsync(EncodeCloseConnectionFrame, shutdownCts.Token).ConfigureAwait(false); |
| | 527 | |
|
| | 528 | | // Wait for the peer to abort the connection as an acknowledgment for this CloseConnection frame. |
| | 529 | | // The peer can also send us a CloseConnection frame if it started shutting down at the same time. |
| | 530 | | // We can't just return and dispose the duplex connection since the peer can still be reading frames |
| | 531 | | // (including the CloseConnection frame) and we don't want to abort this reading. |
| 38 | 532 | | await _readFramesTask.WaitAsync(shutdownCts.Token).ConfigureAwait(false); |
| 37 | 533 | | } |
| | 534 | | else |
| 53 | 535 | | { |
| | 536 | | // _readFramesTask should be already completed or nearly completed. |
| 53 | 537 | | await _readFramesTask.WaitAsync(shutdownCts.Token).ConfigureAwait(false); |
| | 538 | |
|
| | 539 | | // _readFramesTask succeeded means the peer is waiting for us to abort the duplex connection; |
| | 540 | | // we oblige. |
| 34 | 541 | | _duplexConnection.Dispose(); |
| 34 | 542 | | } |
| 71 | 543 | | } |
| 11 | 544 | | catch (OperationCanceledException) |
| 11 | 545 | | { |
| 11 | 546 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 547 | |
|
| 5 | 548 | | Debug.Assert(_disposedCts.Token.IsCancellationRequested); |
| 5 | 549 | | throw new IceRpcException( |
| 5 | 550 | | IceRpcError.OperationAborted, |
| 5 | 551 | | "The connection shutdown was aborted because the connection was disposed."); |
| | 552 | | } |
| 21 | 553 | | catch (IceRpcException) |
| 21 | 554 | | { |
| 21 | 555 | | throw; |
| | 556 | | } |
| 0 | 557 | | catch (Exception exception) |
| 0 | 558 | | { |
| 0 | 559 | | Debug.Fail($"ShutdownAsync failed with an unexpected exception: {exception}"); |
| 0 | 560 | | throw; |
| | 561 | | } |
| | 562 | |
|
| | 563 | | static void EncodeCloseConnectionFrame(IBufferWriter<byte> writer) |
| 40 | 564 | | { |
| 40 | 565 | | var encoder = new SliceEncoder(writer, SliceEncoding.Slice1); |
| 40 | 566 | | IceDefinitions.CloseConnectionFrame.Encode(ref encoder); |
| 40 | 567 | | } |
| 71 | 568 | | } |
| 103 | 569 | | } |
| | 570 | |
|
| 372 | 571 | | internal IceProtocolConnection( |
| 372 | 572 | | IDuplexConnection duplexConnection, |
| 372 | 573 | | TransportConnectionInformation? transportConnectionInformation, |
| 372 | 574 | | ConnectionOptions options) |
| 372 | 575 | | { |
| 372 | 576 | | _twowayDispatchesCts = CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token); |
| | 577 | |
|
| | 578 | | // With ice, we always listen for incoming frames (responses) so we need a dispatcher for incoming requests even |
| | 579 | | // if we don't expect any. This dispatcher throws an ice ObjectNotExistException back to the client, which makes |
| | 580 | | // more sense than throwing an UnknownException. |
| 372 | 581 | | _dispatcher = options.Dispatcher ?? NotFoundDispatcher.Instance; |
| | 582 | |
|
| 372 | 583 | | _maxFrameSize = options.MaxIceFrameSize; |
| 372 | 584 | | _transportConnectionInformation = transportConnectionInformation; |
| | 585 | |
|
| 372 | 586 | | if (options.MaxDispatches > 0) |
| 372 | 587 | | { |
| 372 | 588 | | _dispatchSemaphore = new SemaphoreSlim( |
| 372 | 589 | | initialCount: options.MaxDispatches, |
| 372 | 590 | | maxCount: options.MaxDispatches); |
| 372 | 591 | | } |
| | 592 | |
|
| 372 | 593 | | _inactivityTimeout = options.InactivityTimeout; |
| | 594 | |
|
| | 595 | | // The readerScheduler doesn't matter (we don't call pipe.Reader.ReadAsync on the resulting pipe), and the |
| | 596 | | // writerScheduler doesn't matter (pipe.Writer.FlushAsync never blocks). |
| 372 | 597 | | _pipeOptions = new PipeOptions( |
| 372 | 598 | | pool: options.Pool, |
| 372 | 599 | | minimumSegmentSize: options.MinSegmentSize, |
| 372 | 600 | | pauseWriterThreshold: 0, |
| 372 | 601 | | useSynchronizationContext: false); |
| | 602 | |
|
| 372 | 603 | | if (options.IceIdleTimeout != Timeout.InfiniteTimeSpan) |
| 372 | 604 | | { |
| 372 | 605 | | duplexConnection = new IceDuplexConnectionDecorator( |
| 372 | 606 | | duplexConnection, |
| 372 | 607 | | readIdleTimeout: options.EnableIceIdleCheck ? options.IceIdleTimeout : Timeout.InfiniteTimeSpan, |
| 372 | 608 | | writeIdleTimeout: options.IceIdleTimeout, |
| 372 | 609 | | SendHeartbeat); |
| 372 | 610 | | } |
| | 611 | |
|
| 372 | 612 | | _duplexConnection = duplexConnection; |
| 372 | 613 | | _duplexConnectionReader = new DuplexConnectionReader(_duplexConnection, options.Pool, options.MinSegmentSize); |
| 372 | 614 | | _duplexConnectionWriter = |
| 372 | 615 | | new IceDuplexConnectionWriter(_duplexConnection, options.Pool, options.MinSegmentSize); |
| | 616 | |
|
| 372 | 617 | | _inactivityTimeoutTimer = new Timer(_ => |
| 10 | 618 | | { |
| 10 | 619 | | bool requestShutdown = false; |
| 372 | 620 | |
|
| 10 | 621 | | lock (_mutex) |
| 10 | 622 | | { |
| 10 | 623 | | if (_dispatchInvocationCount == 0 && _shutdownTask is null) |
| 10 | 624 | | { |
| 10 | 625 | | requestShutdown = true; |
| 10 | 626 | | RefuseNewInvocations( |
| 10 | 627 | | $"The connection was shut down because it was inactive for over {_inactivityTimeout.TotalSeconds |
| 10 | 628 | | } |
| 10 | 629 | | } |
| 372 | 630 | |
|
| 10 | 631 | | if (requestShutdown) |
| 10 | 632 | | { |
| 372 | 633 | | // TrySetResult must be called outside the mutex lock. |
| 10 | 634 | | _shutdownRequestedTcs.TrySetResult(); |
| 10 | 635 | | } |
| 382 | 636 | | }); |
| | 637 | |
|
| | 638 | | void SendHeartbeat() |
| 23 | 639 | | { |
| 23 | 640 | | lock (_mutex) |
| 23 | 641 | | { |
| 23 | 642 | | if (_heartbeatTask.IsCompletedSuccessfully && _heartbeatEnabled) |
| 23 | 643 | | { |
| 23 | 644 | | _heartbeatTask = SendValidateConnectionFrameAsync(_disposedCts.Token); |
| 23 | 645 | | } |
| 23 | 646 | | } |
| | 647 | |
|
| | 648 | | async Task SendValidateConnectionFrameAsync(CancellationToken cancellationToken) |
| 23 | 649 | | { |
| | 650 | | // Make sure we execute the function without holding the connection mutex lock. |
| 23 | 651 | | await Task.Yield(); |
| | 652 | |
|
| | 653 | | try |
| 23 | 654 | | { |
| 23 | 655 | | await SendControlFrameAsync(EncodeValidateConnectionFrame, cancellationToken).ConfigureAwait(false); |
| 23 | 656 | | } |
| 0 | 657 | | catch (OperationCanceledException) |
| 0 | 658 | | { |
| | 659 | | // Canceled by DisposeAsync |
| 0 | 660 | | throw; |
| | 661 | | } |
| 0 | 662 | | catch (IceRpcException) |
| 0 | 663 | | { |
| | 664 | | // Expected, typically the peer aborted the connection. |
| 0 | 665 | | throw; |
| | 666 | | } |
| 0 | 667 | | catch (Exception exception) |
| 0 | 668 | | { |
| 0 | 669 | | Debug.Fail($"The heartbeat task completed due to an unhandled exception: {exception}"); |
| 0 | 670 | | throw; |
| | 671 | | } |
| | 672 | |
|
| | 673 | | static void EncodeValidateConnectionFrame(IBufferWriter<byte> writer) |
| 23 | 674 | | { |
| 23 | 675 | | var encoder = new SliceEncoder(writer, SliceEncoding.Slice1); |
| 23 | 676 | | IceDefinitions.ValidateConnectionFrame.Encode(ref encoder); |
| 23 | 677 | | } |
| 23 | 678 | | } |
| 23 | 679 | | } |
| 372 | 680 | | } |
| | 681 | |
|
| | 682 | | private static (int RequestId, IceRequestHeader Header, PipeReader? ContextReader, int Consumed) DecodeRequestIdAndH |
| | 683 | | ReadOnlySequence<byte> buffer) |
| 2713 | 684 | | { |
| 2713 | 685 | | var decoder = new SliceDecoder(buffer, SliceEncoding.Slice1); |
| | 686 | |
|
| 2713 | 687 | | int requestId = decoder.DecodeInt32(); |
| | 688 | |
|
| 2713 | 689 | | var requestHeader = new IceRequestHeader(ref decoder); |
| | 690 | |
|
| 2713 | 691 | | Pipe? contextPipe = null; |
| 2713 | 692 | | long pos = decoder.Consumed; |
| 2713 | 693 | | int count = decoder.DecodeSize(); |
| 2713 | 694 | | if (count > 0) |
| 8 | 695 | | { |
| 32 | 696 | | for (int i = 0; i < count; ++i) |
| 8 | 697 | | { |
| 8 | 698 | | decoder.Skip(decoder.DecodeSize()); // Skip the key |
| 8 | 699 | | decoder.Skip(decoder.DecodeSize()); // Skip the value |
| 8 | 700 | | } |
| 8 | 701 | | contextPipe = new Pipe(); |
| 8 | 702 | | contextPipe.Writer.Write(buffer.Slice(pos, decoder.Consumed - pos)); |
| 8 | 703 | | contextPipe.Writer.Complete(); |
| 8 | 704 | | } |
| | 705 | |
|
| 2713 | 706 | | var encapsulationHeader = new EncapsulationHeader(ref decoder); |
| | 707 | |
|
| 2713 | 708 | | if (encapsulationHeader.PayloadEncodingMajor != 1 || |
| 2713 | 709 | | encapsulationHeader.PayloadEncodingMinor != 1) |
| 0 | 710 | | { |
| 0 | 711 | | throw new InvalidDataException( |
| 0 | 712 | | $"Unsupported payload encoding '{encapsulationHeader.PayloadEncodingMajor}.{encapsulationHeader.PayloadE |
| | 713 | | } |
| | 714 | |
|
| 2713 | 715 | | int payloadSize = encapsulationHeader.EncapsulationSize - 6; |
| 2713 | 716 | | if (payloadSize != (buffer.Length - decoder.Consumed)) |
| 0 | 717 | | { |
| 0 | 718 | | throw new InvalidDataException( |
| 0 | 719 | | $"Request payload size mismatch: expected {payloadSize} bytes, read {buffer.Length - decoder.Consumed} b |
| | 720 | | } |
| | 721 | |
|
| 2713 | 722 | | return (requestId, requestHeader, contextPipe?.Reader, (int)decoder.Consumed); |
| 2713 | 723 | | } |
| | 724 | |
|
| | 725 | | private static (StatusCode StatusCode, string? ErrorMessage, SequencePosition Consumed) DecodeResponseHeader( |
| | 726 | | ReadOnlySequence<byte> buffer, |
| | 727 | | int requestId) |
| 661 | 728 | | { |
| 661 | 729 | | ReplyStatus replyStatus = ((int)buffer.FirstSpan[0]).AsReplyStatus(); |
| | 730 | |
|
| 661 | 731 | | if (replyStatus <= ReplyStatus.UserException) |
| 619 | 732 | | { |
| | 733 | | const int headerSize = 7; // reply status byte + encapsulation header |
| | 734 | |
|
| | 735 | | // read and check encapsulation header (6 bytes long) |
| | 736 | |
|
| 619 | 737 | | if (buffer.Length < headerSize) |
| 0 | 738 | | { |
| 0 | 739 | | throw new InvalidDataException($"Received invalid frame header for request with id '{requestId}'."); |
| | 740 | | } |
| | 741 | |
|
| 619 | 742 | | EncapsulationHeader encapsulationHeader = SliceEncoding.Slice1.DecodeBuffer( |
| 619 | 743 | | buffer.Slice(1, 6), |
| 1238 | 744 | | (ref SliceDecoder decoder) => new EncapsulationHeader(ref decoder)); |
| | 745 | |
|
| | 746 | | // Sanity check |
| 619 | 747 | | int payloadSize = encapsulationHeader.EncapsulationSize - 6; |
| 619 | 748 | | if (payloadSize != buffer.Length - headerSize) |
| 0 | 749 | | { |
| 0 | 750 | | throw new InvalidDataException( |
| 0 | 751 | | $"Response payload size/frame size mismatch: payload size is {payloadSize} bytes but frame has {buff |
| | 752 | | } |
| | 753 | |
|
| 619 | 754 | | SequencePosition consumed = buffer.GetPosition(headerSize); |
| | 755 | |
|
| 619 | 756 | | return replyStatus == ReplyStatus.Ok ? (StatusCode.Ok, null, consumed) : |
| 619 | 757 | | // Set the error message to the empty string, because null is not allowed for status code > Ok. |
| 619 | 758 | | (StatusCode.ApplicationError, "", consumed); |
| | 759 | | } |
| | 760 | | else |
| 42 | 761 | | { |
| | 762 | | // An ice system exception. |
| | 763 | |
|
| 42 | 764 | | StatusCode statusCode = replyStatus switch |
| 42 | 765 | | { |
| 20 | 766 | | ReplyStatus.ObjectNotExistException => StatusCode.NotFound, |
| 0 | 767 | | ReplyStatus.FacetNotExistException => StatusCode.NotFound, |
| 2 | 768 | | ReplyStatus.OperationNotExistException => StatusCode.NotImplemented, |
| 20 | 769 | | _ => StatusCode.InternalError |
| 42 | 770 | | }; |
| | 771 | |
|
| 42 | 772 | | var decoder = new SliceDecoder(buffer.Slice(1), SliceEncoding.Slice1); |
| | 773 | |
|
| | 774 | | string message; |
| 42 | 775 | | switch (replyStatus) |
| | 776 | | { |
| | 777 | | case ReplyStatus.FacetNotExistException: |
| | 778 | | case ReplyStatus.ObjectNotExistException: |
| | 779 | | case ReplyStatus.OperationNotExistException: |
| | 780 | |
|
| 22 | 781 | | var requestFailed = new RequestFailedExceptionData(ref decoder); |
| | 782 | |
|
| 22 | 783 | | string target = requestFailed.Fragment.Length > 0 ? |
| 22 | 784 | | $"{requestFailed.Identity.ToPath()}#{requestFailed.Fragment}" : requestFailed.Identity.ToPath(); |
| | 785 | |
|
| 22 | 786 | | message = |
| 22 | 787 | | $"The dispatch failed with status code {statusCode} while dispatching '{requestFailed.Operation} |
| 22 | 788 | | break; |
| | 789 | | default: |
| 20 | 790 | | message = decoder.DecodeString(); |
| 20 | 791 | | break; |
| | 792 | | } |
| 42 | 793 | | decoder.CheckEndOfBuffer(); |
| 42 | 794 | | return (statusCode, message, buffer.End); |
| | 795 | | } |
| 661 | 796 | | } |
| | 797 | |
|
| | 798 | | private static void EncodeRequestHeader( |
| | 799 | | IceDuplexConnectionWriter output, |
| | 800 | | OutgoingRequest request, |
| | 801 | | int requestId, |
| | 802 | | int payloadSize) |
| 2717 | 803 | | { |
| 2717 | 804 | | var encoder = new SliceEncoder(output, SliceEncoding.Slice1); |
| | 805 | |
|
| | 806 | | // Write the request header. |
| 2717 | 807 | | encoder.WriteByteSpan(IceDefinitions.FramePrologue); |
| 2717 | 808 | | encoder.EncodeIceFrameType(IceFrameType.Request); |
| 2717 | 809 | | encoder.EncodeUInt8(0); // compression status |
| | 810 | |
|
| 2717 | 811 | | Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(4); |
| | 812 | |
|
| 2717 | 813 | | encoder.EncodeInt32(requestId); |
| | 814 | |
|
| 2717 | 815 | | byte encodingMajor = 1; |
| 2717 | 816 | | byte encodingMinor = 1; |
| | 817 | |
|
| | 818 | | // Request header. |
| 2717 | 819 | | var requestHeader = new IceRequestHeader( |
| 2717 | 820 | | Identity.Parse(request.ServiceAddress.Path), |
| 2717 | 821 | | request.ServiceAddress.Fragment, |
| 2717 | 822 | | request.Operation, |
| 2717 | 823 | | request.Fields.ContainsKey(RequestFieldKey.Idempotent) ? OperationMode.Idempotent : OperationMode.Normal); |
| 2717 | 824 | | requestHeader.Encode(ref encoder); |
| 2717 | 825 | | int directWriteSize = 0; |
| 2717 | 826 | | if (request.Fields.TryGetValue(RequestFieldKey.Context, out OutgoingFieldValue requestField)) |
| 8 | 827 | | { |
| 8 | 828 | | if (requestField.WriteAction is Action<IBufferWriter<byte>> writeAction) |
| 8 | 829 | | { |
| | 830 | | // This writes directly to the underlying output; we measure how many bytes are written. |
| 8 | 831 | | long start = output.UnflushedBytes; |
| 8 | 832 | | writeAction(output); |
| 8 | 833 | | directWriteSize = (int)(output.UnflushedBytes - start); |
| 8 | 834 | | } |
| | 835 | | else |
| 0 | 836 | | { |
| 0 | 837 | | encoder.WriteByteSequence(requestField.ByteSequence); |
| 0 | 838 | | } |
| 8 | 839 | | } |
| | 840 | | else |
| 2709 | 841 | | { |
| 2709 | 842 | | encoder.EncodeSize(0); |
| 2709 | 843 | | } |
| | 844 | |
|
| | 845 | | // We ignore all other fields. They can't be sent over ice. |
| | 846 | |
|
| 2717 | 847 | | new EncapsulationHeader( |
| 2717 | 848 | | encapsulationSize: payloadSize + 6, |
| 2717 | 849 | | encodingMajor, |
| 2717 | 850 | | encodingMinor).Encode(ref encoder); |
| | 851 | |
|
| 2717 | 852 | | int frameSize = checked(encoder.EncodedByteCount + directWriteSize + payloadSize); |
| 2717 | 853 | | SliceEncoder.EncodeInt32(frameSize, sizePlaceholder); |
| 2717 | 854 | | } |
| | 855 | |
|
| | 856 | | private static void EncodeResponseHeader( |
| | 857 | | IBufferWriter<byte> writer, |
| | 858 | | OutgoingResponse response, |
| | 859 | | IncomingRequest request, |
| | 860 | | int requestId, |
| | 861 | | int payloadSize) |
| 2687 | 862 | | { |
| 2687 | 863 | | var encoder = new SliceEncoder(writer, SliceEncoding.Slice1); |
| | 864 | |
|
| | 865 | | // Write the response header. |
| | 866 | |
|
| 2687 | 867 | | encoder.WriteByteSpan(IceDefinitions.FramePrologue); |
| 2687 | 868 | | encoder.EncodeIceFrameType(IceFrameType.Reply); |
| 2687 | 869 | | encoder.EncodeUInt8(0); // compression status |
| 2687 | 870 | | Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(4); |
| | 871 | |
|
| 2687 | 872 | | encoder.EncodeInt32(requestId); |
| | 873 | |
|
| 2687 | 874 | | if (response.StatusCode > StatusCode.ApplicationError || |
| 2687 | 875 | | (response.StatusCode == StatusCode.ApplicationError && payloadSize == 0)) |
| 46 | 876 | | { |
| | 877 | | // system exception |
| 46 | 878 | | switch (response.StatusCode) |
| | 879 | | { |
| | 880 | | case StatusCode.NotFound: |
| | 881 | | case StatusCode.NotImplemented: |
| 26 | 882 | | encoder.EncodeReplyStatus(response.StatusCode == StatusCode.NotFound ? |
| 26 | 883 | | ReplyStatus.ObjectNotExistException : ReplyStatus.OperationNotExistException); |
| | 884 | |
|
| 26 | 885 | | new RequestFailedExceptionData(Identity.Parse(request.Path), request.Fragment, request.Operation) |
| 26 | 886 | | .Encode(ref encoder); |
| 26 | 887 | | break; |
| | 888 | | case StatusCode.InternalError: |
| 14 | 889 | | encoder.EncodeReplyStatus(ReplyStatus.UnknownException); |
| 14 | 890 | | encoder.EncodeString(response.ErrorMessage!); |
| 14 | 891 | | break; |
| | 892 | | default: |
| 6 | 893 | | encoder.EncodeReplyStatus(ReplyStatus.UnknownException); |
| 6 | 894 | | encoder.EncodeString( |
| 6 | 895 | | $"{response.ErrorMessage} {{ Original StatusCode = {response.StatusCode} }}"); |
| 6 | 896 | | break; |
| | 897 | | } |
| 46 | 898 | | } |
| | 899 | | else |
| 2641 | 900 | | { |
| 2641 | 901 | | encoder.EncodeReplyStatus((ReplyStatus)response.StatusCode); |
| | 902 | |
|
| | 903 | | // When IceRPC receives a response, it ignores the response encoding. So this "1.1" is only relevant to |
| | 904 | | // a ZeroC Ice client that decodes the response. The only Slice encoding such a client can possibly use |
| | 905 | | // to decode the response payload is 1.1 or 1.0, and we don't care about interop with 1.0. |
| 2641 | 906 | | var encapsulationHeader = new EncapsulationHeader( |
| 2641 | 907 | | encapsulationSize: payloadSize + 6, |
| 2641 | 908 | | payloadEncodingMajor: 1, |
| 2641 | 909 | | payloadEncodingMinor: 1); |
| 2641 | 910 | | encapsulationHeader.Encode(ref encoder); |
| 2641 | 911 | | } |
| | 912 | |
|
| 2687 | 913 | | int frameSize = encoder.EncodedByteCount + payloadSize; |
| 2687 | 914 | | SliceEncoder.EncodeInt32(frameSize, sizePlaceholder); |
| 2687 | 915 | | } |
| | 916 | |
|
| | 917 | | /// <summary>Reads the full Ice payload from the given pipe reader.</summary> |
| | 918 | | private static async ValueTask<ReadOnlySequence<byte>> ReadFullPayloadAsync( |
| | 919 | | PipeReader payload, |
| | 920 | | CancellationToken cancellationToken) |
| 5366 | 921 | | { |
| | 922 | | // We use ReadAtLeastAsync instead of ReadAsync to bypass the PauseWriterThreshold when the payload is |
| | 923 | | // backed by a Pipe. |
| 5366 | 924 | | ReadResult readResult = await payload.ReadAtLeastAsync(int.MaxValue, cancellationToken).ConfigureAwait(false); |
| | 925 | |
|
| 5360 | 926 | | if (readResult.IsCanceled) |
| 0 | 927 | | { |
| 0 | 928 | | throw new InvalidOperationException("Unexpected call to CancelPendingRead on ice payload."); |
| | 929 | | } |
| | 930 | |
|
| 5360 | 931 | | return readResult.IsCompleted ? readResult.Buffer : |
| 5360 | 932 | | throw new ArgumentException("The payload size is greater than int.MaxValue.", nameof(payload)); |
| 5360 | 933 | | } |
| | 934 | |
|
| | 935 | | /// <summary>Acquires exclusive access to _duplexConnectionWriter.</summary> |
| | 936 | | /// <returns>A <see cref="SemaphoreLock" /> that releases the acquired semaphore in its Dispose method.</returns> |
| | 937 | | private async ValueTask<SemaphoreLock> AcquireWriteLockAsync(CancellationToken cancellationToken) |
| 5638 | 938 | | { |
| 5638 | 939 | | SemaphoreLock semaphoreLock = await _writeSemaphore.AcquireAsync(cancellationToken).ConfigureAwait(false); |
| | 940 | |
|
| | 941 | | // _writeException is protected by _writeSemaphore |
| 5638 | 942 | | if (_writeException is not null) |
| 2 | 943 | | { |
| 2 | 944 | | semaphoreLock.Dispose(); |
| | 945 | |
|
| 2 | 946 | | throw new IceRpcException( |
| 2 | 947 | | IceRpcError.ConnectionAborted, |
| 2 | 948 | | "The connection was aborted because a previous write operation failed.", |
| 2 | 949 | | _writeException); |
| | 950 | | } |
| | 951 | |
|
| 5636 | 952 | | return semaphoreLock; |
| 5636 | 953 | | } |
| | 954 | |
|
| | 955 | | /// <summary>Creates a pipe reader to simplify the reading of a request or response frame. The frame is read fully |
| | 956 | | /// and buffered into an internal pipe.</summary> |
| | 957 | | private async ValueTask<PipeReader> CreateFrameReaderAsync(int size, CancellationToken cancellationToken) |
| 5390 | 958 | | { |
| 5390 | 959 | | var pipe = new Pipe(_pipeOptions); |
| | 960 | |
|
| | 961 | | try |
| 5390 | 962 | | { |
| 5390 | 963 | | await _duplexConnectionReader.FillBufferWriterAsync(pipe.Writer, size, cancellationToken) |
| 5390 | 964 | | .ConfigureAwait(false); |
| 5390 | 965 | | } |
| 0 | 966 | | catch |
| 0 | 967 | | { |
| 0 | 968 | | pipe.Reader.Complete(); |
| 0 | 969 | | throw; |
| | 970 | | } |
| | 971 | | finally |
| 5390 | 972 | | { |
| 5390 | 973 | | pipe.Writer.Complete(); |
| 5390 | 974 | | } |
| | 975 | |
|
| 5390 | 976 | | return pipe.Reader; |
| 5390 | 977 | | } |
| | 978 | |
|
| | 979 | | private void DecrementDispatchInvocationCount() |
| 5426 | 980 | | { |
| 5426 | 981 | | lock (_mutex) |
| 5426 | 982 | | { |
| 5426 | 983 | | if (--_dispatchInvocationCount == 0) |
| 2266 | 984 | | { |
| 2266 | 985 | | if (_shutdownTask is not null) |
| 42 | 986 | | { |
| 42 | 987 | | _dispatchesAndInvocationsCompleted.TrySetResult(); |
| 42 | 988 | | } |
| | 989 | | // We enable the inactivity check in order to complete ShutdownRequested when inactive for too long. |
| | 990 | | // _refuseInvocations is true when the connection is either about to be "shutdown requested", or shut |
| | 991 | | // down / disposed. We don't need to complete ShutdownRequested in any of these situations. |
| 2224 | 992 | | else if (!_refuseInvocations) |
| 2204 | 993 | | { |
| 2204 | 994 | | ScheduleInactivityCheck(); |
| 2204 | 995 | | } |
| 2266 | 996 | | } |
| 5426 | 997 | | } |
| 5426 | 998 | | } |
| | 999 | |
|
| | 1000 | | /// <summary>Dispatches an incoming request. This method executes in a task spawn from the read frames loop. |
| | 1001 | | /// </summary> |
| | 1002 | | private async Task DispatchRequestAsync(IncomingRequest request, int requestId, PipeReader? contextReader) |
| 2709 | 1003 | | { |
| 2709 | 1004 | | CancellationToken cancellationToken = request.IsOneway ? _disposedCts.Token : _twowayDispatchesCts.Token; |
| | 1005 | |
|
| | 1006 | | OutgoingResponse? response; |
| | 1007 | | try |
| 2709 | 1008 | | { |
| | 1009 | | // The dispatcher can complete the incoming request payload to release its memory as soon as possible. |
| | 1010 | | try |
| 2709 | 1011 | | { |
| | 1012 | | // _dispatcher.DispatchAsync may very well ignore the cancellation token and we don't want to keep |
| | 1013 | | // dispatching when the cancellation token is canceled. |
| 2709 | 1014 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 1015 | |
|
| 2709 | 1016 | | response = await _dispatcher.DispatchAsync(request, cancellationToken).ConfigureAwait(false); |
| 2679 | 1017 | | } |
| | 1018 | | finally |
| 2709 | 1019 | | { |
| 2709 | 1020 | | _dispatchSemaphore?.Release(); |
| 2709 | 1021 | | } |
| | 1022 | |
|
| 2679 | 1023 | | if (response != request.Response) |
| 2 | 1024 | | { |
| 2 | 1025 | | throw new InvalidOperationException( |
| 2 | 1026 | | "The dispatcher did not return the last response created for this request."); |
| | 1027 | | } |
| 2677 | 1028 | | } |
| 32 | 1029 | | catch when (request.IsOneway) |
| 0 | 1030 | | { |
| | 1031 | | // ignored since we're not returning anything |
| 0 | 1032 | | response = null; |
| 0 | 1033 | | } |
| 20 | 1034 | | catch (OperationCanceledException exception) when (exception.CancellationToken == cancellationToken) |
| 18 | 1035 | | { |
| | 1036 | | // expected when the connection is disposed or the request is canceled by the peer's shutdown |
| 18 | 1037 | | response = null; |
| 18 | 1038 | | } |
| 14 | 1039 | | catch (Exception exception) |
| 14 | 1040 | | { |
| 14 | 1041 | | if (exception is not DispatchException dispatchException) |
| 10 | 1042 | | { |
| 10 | 1043 | | dispatchException = new DispatchException(StatusCode.InternalError, innerException: exception); |
| 10 | 1044 | | } |
| 14 | 1045 | | response = dispatchException.ToOutgoingResponse(request); |
| 14 | 1046 | | } |
| | 1047 | | finally |
| 2709 | 1048 | | { |
| 2709 | 1049 | | request.Payload.Complete(); |
| 2709 | 1050 | | contextReader?.Complete(); |
| | 1051 | |
|
| | 1052 | | // The field values are now invalid - they point to potentially recycled and reused memory. We |
| | 1053 | | // replace Fields by an empty dictionary to prevent accidental access to this reused memory. |
| 2709 | 1054 | | request.Fields = ImmutableDictionary<RequestFieldKey, ReadOnlySequence<byte>>.Empty; |
| 2709 | 1055 | | } |
| | 1056 | |
|
| | 1057 | | try |
| 2709 | 1058 | | { |
| 2709 | 1059 | | if (response is not null) |
| 2691 | 1060 | | { |
| | 1061 | | // Read the full response payload. This can take some time so this needs to be done before acquiring |
| | 1062 | | // the write semaphore. |
| 2691 | 1063 | | ReadOnlySequence<byte> payload = ReadOnlySequence<byte>.Empty; |
| | 1064 | |
|
| 2691 | 1065 | | if (response.StatusCode <= StatusCode.ApplicationError) |
| 2649 | 1066 | | { |
| | 1067 | | try |
| 2649 | 1068 | | { |
| 2649 | 1069 | | payload = await ReadFullPayloadAsync(response.Payload, cancellationToken) |
| 2649 | 1070 | | .ConfigureAwait(false); |
| 2643 | 1071 | | } |
| 4 | 1072 | | catch (OperationCanceledException exception) when (exception.CancellationToken == cancellationToken) |
| 4 | 1073 | | { |
| 4 | 1074 | | throw; |
| | 1075 | | } |
| 2 | 1076 | | catch (Exception exception) |
| 2 | 1077 | | { |
| | 1078 | | // We "encode" the exception in the error message. |
| | 1079 | |
|
| 2 | 1080 | | response = new OutgoingResponse( |
| 2 | 1081 | | request, |
| 2 | 1082 | | StatusCode.InternalError, |
| 2 | 1083 | | "The dispatch failed to read the response payload.", |
| 2 | 1084 | | exception); |
| 2 | 1085 | | } |
| 2645 | 1086 | | } |
| | 1087 | | // else payload remains empty because the payload of a dispatch exception (if any) cannot be sent |
| | 1088 | | // over ice. |
| | 1089 | |
|
| 2687 | 1090 | | int payloadSize = checked((int)payload.Length); |
| | 1091 | |
|
| | 1092 | | // Wait for writing of other frames to complete. |
| 2687 | 1093 | | using SemaphoreLock _ = await AcquireWriteLockAsync(cancellationToken).ConfigureAwait(false); |
| | 1094 | | try |
| 2687 | 1095 | | { |
| 2687 | 1096 | | EncodeResponseHeader(_duplexConnectionWriter, response, request, requestId, payloadSize); |
| | 1097 | |
|
| | 1098 | | // We write to the duplex connection with _disposedCts.Token instead of cancellationToken. |
| | 1099 | | // Canceling this write operation is fatal to the connection. |
| 2687 | 1100 | | await _duplexConnectionWriter.WriteAsync(payload, _disposedCts.Token).ConfigureAwait(false); |
| 2685 | 1101 | | } |
| 2 | 1102 | | catch (Exception exception) |
| 2 | 1103 | | { |
| 2 | 1104 | | WriteFailed(exception); |
| 2 | 1105 | | throw; |
| | 1106 | | } |
| 2685 | 1107 | | } |
| 2703 | 1108 | | } |
| 6 | 1109 | | catch (OperationCanceledException exception) when ( |
| 6 | 1110 | | exception.CancellationToken == _disposedCts.Token || |
| 6 | 1111 | | exception.CancellationToken == cancellationToken) |
| 6 | 1112 | | { |
| | 1113 | | // expected when the connection is disposed or the request is canceled by the peer's shutdown |
| 6 | 1114 | | } |
| | 1115 | | finally |
| 2709 | 1116 | | { |
| 2709 | 1117 | | DecrementDispatchInvocationCount(); |
| 2709 | 1118 | | } |
| 2709 | 1119 | | } |
| | 1120 | |
|
| | 1121 | | /// <summary>Increments the dispatch-invocation count.</summary> |
| | 1122 | | /// <remarks>This method must be called with _mutex locked.</remarks> |
| | 1123 | | private void IncrementDispatchInvocationCount() |
| 5426 | 1124 | | { |
| 5426 | 1125 | | if (_dispatchInvocationCount++ == 0) |
| 2266 | 1126 | | { |
| | 1127 | | // Cancel inactivity check. |
| 2266 | 1128 | | _inactivityTimeoutTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); |
| 2266 | 1129 | | } |
| 5426 | 1130 | | } |
| | 1131 | |
|
| | 1132 | | private void ScheduleInactivityCheck() => |
| 2528 | 1133 | | _inactivityTimeoutTimer.Change(_inactivityTimeout, Timeout.InfiniteTimeSpan); |
| | 1134 | |
|
| | 1135 | | /// <summary>Reads incoming frames and returns successfully when a CloseConnection frame is received or when the |
| | 1136 | | /// connection is aborted during ShutdownAsync or canceled by DisposeAsync.</summary> |
| | 1137 | | private async Task ReadFramesAsync(CancellationToken cancellationToken) |
| 324 | 1138 | | { |
| 324 | 1139 | | await Task.Yield(); // exit mutex lock |
| | 1140 | |
|
| | 1141 | | // Wait for _connectTask (which spawned the task running this method) to complete. This way, we won't dispatch |
| | 1142 | | // any request until _connectTask has completed successfully, and indirectly we won't make any invocation until |
| | 1143 | | // _connectTask has completed successfully. The creation of the _readFramesTask is the last action taken by |
| | 1144 | | // _connectTask and as a result this await can't fail. |
| 324 | 1145 | | await _connectTask!.ConfigureAwait(false); |
| | 1146 | |
|
| | 1147 | | try |
| 324 | 1148 | | { |
| 5737 | 1149 | | while (!cancellationToken.IsCancellationRequested) |
| 5733 | 1150 | | { |
| 5733 | 1151 | | ReadOnlySequence<byte> buffer = await _duplexConnectionReader.ReadAtLeastAsync( |
| 5733 | 1152 | | IceDefinitions.PrologueSize, |
| 5733 | 1153 | | cancellationToken).ConfigureAwait(false); |
| | 1154 | |
|
| | 1155 | | // First decode and check the prologue. |
| | 1156 | |
|
| 5455 | 1157 | | ReadOnlySequence<byte> prologueBuffer = buffer.Slice(0, IceDefinitions.PrologueSize); |
| | 1158 | |
|
| 5455 | 1159 | | IcePrologue prologue = SliceEncoding.Slice1.DecodeBuffer( |
| 5455 | 1160 | | prologueBuffer, |
| 10910 | 1161 | | (ref SliceDecoder decoder) => new IcePrologue(ref decoder)); |
| | 1162 | |
|
| 5455 | 1163 | | _duplexConnectionReader.AdvanceTo(prologueBuffer.End); |
| | 1164 | |
|
| 5455 | 1165 | | IceDefinitions.CheckPrologue(prologue); |
| 5453 | 1166 | | if (prologue.FrameSize > _maxFrameSize) |
| 2 | 1167 | | { |
| 2 | 1168 | | throw new InvalidDataException( |
| 2 | 1169 | | $"Received frame with size ({prologue.FrameSize}) greater than max frame size."); |
| | 1170 | | } |
| | 1171 | |
|
| 5451 | 1172 | | if (prologue.CompressionStatus == 2) |
| 0 | 1173 | | { |
| | 1174 | | // The exception handler calls ReadFailed. |
| 0 | 1175 | | throw new IceRpcException( |
| 0 | 1176 | | IceRpcError.ConnectionAborted, |
| 0 | 1177 | | "The connection was aborted because it received a compressed ice frame, and IceRPC does not supp |
| | 1178 | | } |
| | 1179 | |
|
| | 1180 | | // Then process the frame based on its type. |
| 5451 | 1181 | | switch (prologue.FrameType) |
| | 1182 | | { |
| | 1183 | | case IceFrameType.CloseConnection: |
| 38 | 1184 | | { |
| 38 | 1185 | | if (prologue.FrameSize != IceDefinitions.PrologueSize) |
| 0 | 1186 | | { |
| 0 | 1187 | | throw new InvalidDataException( |
| 0 | 1188 | | $"Received {nameof(IceFrameType.CloseConnection)} frame with unexpected data."); |
| | 1189 | | } |
| | 1190 | |
|
| 38 | 1191 | | lock (_mutex) |
| 38 | 1192 | | { |
| 38 | 1193 | | RefuseNewInvocations( |
| 38 | 1194 | | "The connection was shut down because it received a CloseConnection frame from the peer. |
| | 1195 | |
|
| | 1196 | | // By exiting the "read frames loop" below, we are refusing new dispatches as well. |
| | 1197 | |
|
| | 1198 | | // Only one side sends the CloseConnection frame. |
| 38 | 1199 | | _sendCloseConnectionFrame = false; |
| 38 | 1200 | | } |
| | 1201 | |
|
| | 1202 | | // Even though we're in the "read frames loop", it's ok to cancel CTS and a "synchronous" TCS |
| | 1203 | | // below. We won't be reading anything else so it's ok to run continuations synchronously. |
| | 1204 | |
|
| | 1205 | | // Abort two-way invocations that are waiting for a response (it will never come). |
| 38 | 1206 | | AbortTwowayInvocations( |
| 38 | 1207 | | IceRpcError.InvocationCanceled, |
| 38 | 1208 | | "The invocation was canceled by the shutdown of the peer."); |
| | 1209 | |
|
| | 1210 | | // Cancel two-way dispatches since the peer is not interested in the responses. This does not |
| | 1211 | | // cancel ongoing writes to _duplexConnection: we don't send incomplete/invalid data. |
| 38 | 1212 | | _twowayDispatchesCts.Cancel(); |
| | 1213 | |
|
| | 1214 | | // We keep sending heartbeats. If the shutdown request / shutdown is not fulfilled quickly, they |
| | 1215 | | // tell the peer we're still alive and maybe stuck waiting for invocations and dispatches to |
| | 1216 | | // complete. |
| | 1217 | |
|
| | 1218 | | // We request a shutdown that will dispose _duplexConnection once all invocations and dispatches |
| | 1219 | | // have completed. |
| 38 | 1220 | | _shutdownRequestedTcs.TrySetResult(); |
| 38 | 1221 | | return; |
| | 1222 | | } |
| | 1223 | |
|
| | 1224 | | case IceFrameType.Request: |
| 2713 | 1225 | | await ReadRequestAsync(prologue.FrameSize, cancellationToken).ConfigureAwait(false); |
| 2713 | 1226 | | break; |
| | 1227 | |
|
| | 1228 | | case IceFrameType.RequestBatch: |
| | 1229 | | // The exception handler calls ReadFailed. |
| 0 | 1230 | | throw new IceRpcException( |
| 0 | 1231 | | IceRpcError.ConnectionAborted, |
| 0 | 1232 | | "The connection was aborted because it received a batch request, and IceRPC does not support |
| | 1233 | |
|
| | 1234 | | case IceFrameType.Reply: |
| 2677 | 1235 | | await ReadReplyAsync(prologue.FrameSize, cancellationToken).ConfigureAwait(false); |
| 2677 | 1236 | | break; |
| | 1237 | |
|
| | 1238 | | case IceFrameType.ValidateConnection: |
| 23 | 1239 | | { |
| 23 | 1240 | | if (prologue.FrameSize != IceDefinitions.PrologueSize) |
| 0 | 1241 | | { |
| 0 | 1242 | | throw new InvalidDataException( |
| 0 | 1243 | | $"Received {nameof(IceFrameType.ValidateConnection)} frame with unexpected data."); |
| | 1244 | | } |
| 23 | 1245 | | break; |
| | 1246 | | } |
| | 1247 | |
|
| | 1248 | | default: |
| 0 | 1249 | | { |
| 0 | 1250 | | throw new InvalidDataException( |
| 0 | 1251 | | $"Received Ice frame with unknown frame type '{prologue.FrameType}'."); |
| | 1252 | | } |
| | 1253 | | } |
| 5413 | 1254 | | } // while |
| 4 | 1255 | | } |
| 115 | 1256 | | catch (OperationCanceledException) |
| 115 | 1257 | | { |
| | 1258 | | // canceled by DisposeAsync, no need to throw anything |
| 115 | 1259 | | } |
| 163 | 1260 | | catch (IceRpcException exception) when ( |
| 163 | 1261 | | exception.IceRpcError == IceRpcError.ConnectionAborted && |
| 163 | 1262 | | _dispatchesAndInvocationsCompleted.Task.IsCompleted) |
| 118 | 1263 | | { |
| | 1264 | | // The peer acknowledged receipt of the CloseConnection frame by aborting the duplex connection. Return. |
| | 1265 | | // See ShutdownAsync. |
| 118 | 1266 | | } |
| 45 | 1267 | | catch (IceRpcException exception) |
| 45 | 1268 | | { |
| 45 | 1269 | | ReadFailed(exception); |
| 45 | 1270 | | throw; |
| | 1271 | | } |
| 4 | 1272 | | catch (InvalidDataException exception) |
| 4 | 1273 | | { |
| 4 | 1274 | | ReadFailed(exception); |
| 4 | 1275 | | throw new IceRpcException( |
| 4 | 1276 | | IceRpcError.ConnectionAborted, |
| 4 | 1277 | | "The connection was aborted by an ice protocol error.", |
| 4 | 1278 | | exception); |
| | 1279 | | } |
| 0 | 1280 | | catch (Exception exception) |
| 0 | 1281 | | { |
| 0 | 1282 | | Debug.Fail($"The read frames task completed due to an unhandled exception: {exception}"); |
| 0 | 1283 | | ReadFailed(exception); |
| 0 | 1284 | | throw; |
| | 1285 | | } |
| | 1286 | |
|
| | 1287 | | // Aborts all pending two-way invocations. Must be called outside the mutex lock after setting |
| | 1288 | | // _refuseInvocations to true. |
| | 1289 | | void AbortTwowayInvocations(IceRpcError error, string message, Exception? exception = null) |
| 87 | 1290 | | { |
| 87 | 1291 | | Debug.Assert(_refuseInvocations); |
| | 1292 | |
|
| | 1293 | | // _twowayInvocations is immutable once _refuseInvocations is true. |
| 309 | 1294 | | foreach (TaskCompletionSource<PipeReader> responseCompletionSource in _twowayInvocations.Values) |
| 24 | 1295 | | { |
| | 1296 | | // _twowayInvocations can hold completed completion sources. |
| 24 | 1297 | | _ = responseCompletionSource.TrySetException(new IceRpcException(error, message, exception)); |
| 24 | 1298 | | } |
| 87 | 1299 | | } |
| | 1300 | |
|
| | 1301 | | // Takes appropriate action after a read failure. |
| | 1302 | | void ReadFailed(Exception exception) |
| 49 | 1303 | | { |
| | 1304 | | // We also prevent new one-way invocations even though they don't need to read the connection. |
| 49 | 1305 | | RefuseNewInvocations("The connection was lost because a read operation failed."); |
| | 1306 | |
|
| | 1307 | | // It's ok to cancel CTS and a "synchronous" TCS below. We won't be reading anything else so it's ok to run |
| | 1308 | | // continuations synchronously. |
| | 1309 | |
|
| 49 | 1310 | | AbortTwowayInvocations( |
| 49 | 1311 | | IceRpcError.ConnectionAborted, |
| 49 | 1312 | | "The invocation was aborted because the connection was lost.", |
| 49 | 1313 | | exception); |
| | 1314 | |
|
| | 1315 | | // ReadFailed is called when the connection is dead or the peer sent us a non-supported frame (e.g. a |
| | 1316 | | // batch request). We don't need to allow outstanding two-way dispatches to complete in these situations, so |
| | 1317 | | // we cancel them to speed-up the shutdown. |
| 49 | 1318 | | _twowayDispatchesCts.Cancel(); |
| | 1319 | |
|
| 49 | 1320 | | lock (_mutex) |
| 49 | 1321 | | { |
| | 1322 | | // Don't send a close connection frame since we can't wait for the peer's acknowledgment. |
| 49 | 1323 | | _sendCloseConnectionFrame = false; |
| 49 | 1324 | | } |
| | 1325 | |
|
| 49 | 1326 | | _ = _shutdownRequestedTcs.TrySetResult(); |
| 49 | 1327 | | } |
| 275 | 1328 | | } |
| | 1329 | |
|
| | 1330 | | /// <summary>Reads a reply (incoming response) and completes the invocation response completion source with this |
| | 1331 | | /// response. This method executes "synchronously" in the read frames loop.</summary> |
| | 1332 | | private async Task ReadReplyAsync(int replyFrameSize, CancellationToken cancellationToken) |
| 2677 | 1333 | | { |
| | 1334 | | // Read the remainder of the frame immediately into frameReader. |
| 2677 | 1335 | | PipeReader replyFrameReader = await CreateFrameReaderAsync( |
| 2677 | 1336 | | replyFrameSize - IceDefinitions.PrologueSize, |
| 2677 | 1337 | | cancellationToken).ConfigureAwait(false); |
| | 1338 | |
|
| 2677 | 1339 | | bool completeFrameReader = true; |
| | 1340 | |
|
| | 1341 | | try |
| 2677 | 1342 | | { |
| | 1343 | | // Read and decode request ID |
| 2677 | 1344 | | if (!replyFrameReader.TryRead(out ReadResult readResult) || readResult.Buffer.Length < 4) |
| 0 | 1345 | | { |
| 0 | 1346 | | throw new InvalidDataException("Received a response with an invalid request ID."); |
| | 1347 | | } |
| | 1348 | |
|
| 2677 | 1349 | | ReadOnlySequence<byte> requestIdBuffer = readResult.Buffer.Slice(0, 4); |
| 2677 | 1350 | | int requestId = SliceEncoding.Slice1.DecodeBuffer( |
| 2677 | 1351 | | requestIdBuffer, |
| 5354 | 1352 | | (ref SliceDecoder decoder) => decoder.DecodeInt32()); |
| 2677 | 1353 | | replyFrameReader.AdvanceTo(requestIdBuffer.End); |
| | 1354 | |
|
| 2677 | 1355 | | lock (_mutex) |
| 2677 | 1356 | | { |
| 2677 | 1357 | | if (_twowayInvocations.TryGetValue( |
| 2677 | 1358 | | requestId, |
| 2677 | 1359 | | out TaskCompletionSource<PipeReader>? responseCompletionSource)) |
| 661 | 1360 | | { |
| | 1361 | | // continuation runs asynchronously |
| 661 | 1362 | | if (responseCompletionSource.TrySetResult(replyFrameReader)) |
| 661 | 1363 | | { |
| 661 | 1364 | | completeFrameReader = false; |
| 661 | 1365 | | } |
| | 1366 | | // else this invocation just completed and is about to remove itself from _twowayInvocations, |
| | 1367 | | // or _twowayInvocations is immutable and contains entries for completed invocations. |
| 661 | 1368 | | } |
| | 1369 | | // else the request ID carried by the response is bogus or corresponds to a request that was previously |
| | 1370 | | // discarded (for example, because its deadline expired). |
| 2677 | 1371 | | } |
| 2677 | 1372 | | } |
| | 1373 | | finally |
| 2677 | 1374 | | { |
| 2677 | 1375 | | if (completeFrameReader) |
| 2016 | 1376 | | { |
| 2016 | 1377 | | replyFrameReader.Complete(); |
| 2016 | 1378 | | } |
| 2677 | 1379 | | } |
| 2677 | 1380 | | } |
| | 1381 | |
|
| | 1382 | | /// <summary>Reads and then dispatches an incoming request in a separate dispatch task. This method executes |
| | 1383 | | /// "synchronously" in the read frames loop.</summary> |
| | 1384 | | private async Task ReadRequestAsync(int requestFrameSize, CancellationToken cancellationToken) |
| 2713 | 1385 | | { |
| | 1386 | | // Read the request frame. |
| 2713 | 1387 | | PipeReader requestFrameReader = await CreateFrameReaderAsync( |
| 2713 | 1388 | | requestFrameSize - IceDefinitions.PrologueSize, |
| 2713 | 1389 | | cancellationToken).ConfigureAwait(false); |
| | 1390 | |
|
| | 1391 | | // Decode its header. |
| | 1392 | | int requestId; |
| | 1393 | | IceRequestHeader requestHeader; |
| 2713 | 1394 | | PipeReader? contextReader = null; |
| | 1395 | | IDictionary<RequestFieldKey, ReadOnlySequence<byte>>? fields; |
| 2713 | 1396 | | Task? dispatchTask = null; |
| | 1397 | |
|
| | 1398 | | try |
| 2713 | 1399 | | { |
| 2713 | 1400 | | if (!requestFrameReader.TryRead(out ReadResult readResult)) |
| 0 | 1401 | | { |
| 0 | 1402 | | throw new InvalidDataException("Received an invalid request frame."); |
| | 1403 | | } |
| | 1404 | |
|
| 2713 | 1405 | | Debug.Assert(readResult.IsCompleted); |
| | 1406 | |
|
| 2713 | 1407 | | (requestId, requestHeader, contextReader, int consumed) = DecodeRequestIdAndHeader(readResult.Buffer); |
| 2713 | 1408 | | requestFrameReader.AdvanceTo(readResult.Buffer.GetPosition(consumed)); |
| | 1409 | |
|
| 2713 | 1410 | | if (contextReader is null) |
| 2705 | 1411 | | { |
| 2705 | 1412 | | fields = requestHeader.OperationMode == OperationMode.Normal ? |
| 2705 | 1413 | | ImmutableDictionary<RequestFieldKey, ReadOnlySequence<byte>>.Empty : _idempotentFields; |
| 2705 | 1414 | | } |
| | 1415 | | else |
| 8 | 1416 | | { |
| 8 | 1417 | | contextReader.TryRead(out ReadResult result); |
| 8 | 1418 | | Debug.Assert(result.Buffer.Length > 0 && result.IsCompleted); |
| 8 | 1419 | | fields = new Dictionary<RequestFieldKey, ReadOnlySequence<byte>>() |
| 8 | 1420 | | { |
| 8 | 1421 | | [RequestFieldKey.Context] = result.Buffer |
| 8 | 1422 | | }; |
| | 1423 | |
|
| 8 | 1424 | | if (requestHeader.OperationMode != OperationMode.Normal) |
| 0 | 1425 | | { |
| | 1426 | | // OperationMode can be Idempotent or Nonmutating. |
| 0 | 1427 | | fields[RequestFieldKey.Idempotent] = default; |
| 0 | 1428 | | } |
| 8 | 1429 | | } |
| | 1430 | |
|
| 2713 | 1431 | | bool releaseDispatchSemaphore = false; |
| 2713 | 1432 | | if (_dispatchSemaphore is SemaphoreSlim dispatchSemaphore) |
| 2713 | 1433 | | { |
| | 1434 | | // This prevents us from receiving any new frames if we're already dispatching the maximum number |
| | 1435 | | // of requests. We need to do this in the "accept from network loop" to apply back pressure to the |
| | 1436 | | // caller. |
| | 1437 | | try |
| 2713 | 1438 | | { |
| 2713 | 1439 | | await dispatchSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 2713 | 1440 | | releaseDispatchSemaphore = true; |
| 2713 | 1441 | | } |
| 0 | 1442 | | catch (OperationCanceledException) |
| 0 | 1443 | | { |
| | 1444 | | // and return below |
| 0 | 1445 | | } |
| 2713 | 1446 | | } |
| | 1447 | |
|
| 2713 | 1448 | | lock (_mutex) |
| 2713 | 1449 | | { |
| 2713 | 1450 | | if (_shutdownTask is not null) |
| 4 | 1451 | | { |
| | 1452 | | // The connection is (being) disposed or the connection is shutting down and received a request. |
| | 1453 | | // We simply discard it. For a graceful shutdown, the two-way invocation in the peer will throw |
| | 1454 | | // IceRpcException(InvocationCanceled). We also discard one-way requests: if we accepted them, they |
| | 1455 | | // could delay our shutdown and make it time out. |
| 4 | 1456 | | if (releaseDispatchSemaphore) |
| 4 | 1457 | | { |
| 4 | 1458 | | _dispatchSemaphore!.Release(); |
| 4 | 1459 | | } |
| 4 | 1460 | | return; |
| | 1461 | | } |
| | 1462 | |
|
| 2709 | 1463 | | IncrementDispatchInvocationCount(); |
| 2709 | 1464 | | } |
| | 1465 | |
|
| | 1466 | | // The scheduling of the task can't be canceled since we want to make sure DispatchRequestAsync will |
| | 1467 | | // cleanup (decrement _dispatchCount etc.) if DisposeAsync is called. dispatchTask takes ownership of the |
| | 1468 | | // requestFrameReader and contextReader. |
| 2709 | 1469 | | dispatchTask = Task.Run( |
| 2709 | 1470 | | async () => |
| 2709 | 1471 | | { |
| 2709 | 1472 | | using var request = new IncomingRequest(Protocol.Ice, _connectionContext!) |
| 2709 | 1473 | | { |
| 2709 | 1474 | | Fields = fields, |
| 2709 | 1475 | | Fragment = requestHeader.Fragment, |
| 2709 | 1476 | | IsOneway = requestId == 0, |
| 2709 | 1477 | | Operation = requestHeader.Operation, |
| 2709 | 1478 | | Path = requestHeader.Identity.ToPath(), |
| 2709 | 1479 | | Payload = requestFrameReader, |
| 2709 | 1480 | | }; |
| 2709 | 1481 | |
|
| 2709 | 1482 | | try |
| 2709 | 1483 | | { |
| 2709 | 1484 | | await DispatchRequestAsync( |
| 2709 | 1485 | | request, |
| 2709 | 1486 | | requestId, |
| 2709 | 1487 | | contextReader).ConfigureAwait(false); |
| 2709 | 1488 | | } |
| 0 | 1489 | | catch (IceRpcException) |
| 0 | 1490 | | { |
| 2709 | 1491 | | // expected when the peer aborts the connection. |
| 0 | 1492 | | } |
| 0 | 1493 | | catch (Exception exception) |
| 0 | 1494 | | { |
| 2709 | 1495 | | // With ice, a dispatch cannot throw an exception that comes from the application code: |
| 2709 | 1496 | | // any exception thrown when reading the response payload is converted into a DispatchException |
| 2709 | 1497 | | // response, and the response header has no fields to encode. |
| 0 | 1498 | | Debug.Fail($"ice dispatch {request} failed with an unexpected exception: {exception}"); |
| 0 | 1499 | | throw; |
| 2709 | 1500 | | } |
| 2709 | 1501 | | }, |
| 2709 | 1502 | | CancellationToken.None); |
| 2709 | 1503 | | } |
| | 1504 | | finally |
| 2713 | 1505 | | { |
| 2713 | 1506 | | if (dispatchTask is null) |
| 4 | 1507 | | { |
| 4 | 1508 | | requestFrameReader.Complete(); |
| 4 | 1509 | | contextReader?.Complete(); |
| 4 | 1510 | | } |
| 2713 | 1511 | | } |
| 2713 | 1512 | | } |
| | 1513 | |
|
| | 1514 | | private void RefuseNewInvocations(string message) |
| 582 | 1515 | | { |
| 582 | 1516 | | lock (_mutex) |
| 582 | 1517 | | { |
| 582 | 1518 | | _refuseInvocations = true; |
| 582 | 1519 | | _invocationRefusedMessage ??= message; |
| 582 | 1520 | | } |
| 582 | 1521 | | } |
| | 1522 | |
|
| | 1523 | | /// <summary>Sends a control frame. It takes care of acquiring and releasing the write lock and calls |
| | 1524 | | /// <see cref="WriteFailed" /> if a failure occurs while writing to _duplexConnectionWriter.</summary> |
| | 1525 | | /// <param name="encode">Encodes the control frame.</param> |
| | 1526 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | 1527 | | /// <remarks>If the cancellation token is canceled while writing to the duplex connection, the connection is |
| | 1528 | | /// aborted.</remarks> |
| | 1529 | | private async ValueTask SendControlFrameAsync( |
| | 1530 | | Action<IBufferWriter<byte>> encode, |
| | 1531 | | CancellationToken cancellationToken) |
| 234 | 1532 | | { |
| 234 | 1533 | | using SemaphoreLock _ = await AcquireWriteLockAsync(cancellationToken).ConfigureAwait(false); |
| | 1534 | |
|
| | 1535 | | try |
| 232 | 1536 | | { |
| 232 | 1537 | | encode(_duplexConnectionWriter); |
| 232 | 1538 | | await _duplexConnectionWriter.FlushAsync(cancellationToken).ConfigureAwait(false); |
| 226 | 1539 | | } |
| 6 | 1540 | | catch (Exception exception) |
| 6 | 1541 | | { |
| 6 | 1542 | | WriteFailed(exception); |
| 6 | 1543 | | throw; |
| | 1544 | | } |
| 226 | 1545 | | } |
| | 1546 | |
|
| | 1547 | | /// <summary>Takes appropriate action after a write failure.</summary> |
| | 1548 | | /// <remarks>Must be called outside the mutex lock but after acquiring _writeSemaphore.</remarks> |
| | 1549 | | private void WriteFailed(Exception exception) |
| 10 | 1550 | | { |
| 10 | 1551 | | Debug.Assert(_writeException is null); |
| 10 | 1552 | | _writeException = exception; // protected by _writeSemaphore |
| | 1553 | |
|
| | 1554 | | // We can't send new invocations without writing to the connection. |
| 10 | 1555 | | RefuseNewInvocations("The connection was lost because a write operation failed."); |
| | 1556 | |
|
| | 1557 | | // We can't send responses so these dispatches can be canceled. |
| 10 | 1558 | | _twowayDispatchesCts.Cancel(); |
| | 1559 | |
|
| | 1560 | | // We don't change _sendClosedConnectionFrame. If the _readFrameTask is still running, we want ShutdownAsync |
| | 1561 | | // to send CloseConnection - and fail. |
| | 1562 | |
|
| 10 | 1563 | | _ = _shutdownRequestedTcs.TrySetResult(); |
| 10 | 1564 | | } |
| | 1565 | | } |