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