| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using IceRpc.Features; |
| | | 4 | | using IceRpc.Transports; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | using Microsoft.Extensions.Logging.Abstractions; |
| | | 7 | | using System.Collections.Immutable; |
| | | 8 | | using System.Diagnostics; |
| | | 9 | | using System.Net.Security; |
| | | 10 | | using System.Security.Authentication; |
| | | 11 | | |
| | | 12 | | namespace IceRpc; |
| | | 13 | | |
| | | 14 | | /// <summary>Represents a client connection used to send requests to a server and receive the corresponding responses. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <remarks>This client connection can also dispatch requests ("callbacks") received from the server. The client |
| | | 17 | | /// connection's underlying connection is recreated and reconnected automatically when it's closed by any event other |
| | | 18 | | /// than a call to <see cref="ShutdownAsync" /> or <see cref="DisposeAsync" />.</remarks> |
| | | 19 | | public sealed class ClientConnection : IInvoker, IAsyncDisposable |
| | | 20 | | { |
| | | 21 | | // The underlying protocol connection once successfully established. |
| | | 22 | | private (IProtocolConnection Connection, TransportConnectionInformation ConnectionInformation)? _activeConnection; |
| | | 23 | | |
| | | 24 | | private readonly IClientProtocolConnectionFactory _clientProtocolConnectionFactory; |
| | | 25 | | |
| | | 26 | | private readonly TimeSpan _connectTimeout; |
| | | 27 | | |
| | | 28 | | // A detached connection is a protocol connection that is connecting, shutting down or being disposed. Both |
| | | 29 | | // ShutdownAsync and DisposeAsync wait for detached connections to reach 0 using _detachedConnectionsTcs. Such a |
| | | 30 | | // connection is "detached" because it's not in _activeConnection. |
| | | 31 | | private int _detachedConnectionCount; |
| | | 32 | | |
| | 137 | 33 | | private readonly TaskCompletionSource _detachedConnectionsTcs = new(); |
| | | 34 | | |
| | | 35 | | // A cancellation token source that is canceled when DisposeAsync is called. |
| | 137 | 36 | | private readonly CancellationTokenSource _disposedCts = new(); |
| | | 37 | | private Task? _disposeTask; |
| | | 38 | | |
| | 137 | 39 | | private readonly object _mutex = new(); |
| | | 40 | | |
| | | 41 | | // A connection being established and its associated connect task. When non-null, _activeConnection is null. |
| | | 42 | | private (IProtocolConnection Connection, Task<TransportConnectionInformation> ConnectTask)? _pendingConnection; |
| | | 43 | | |
| | | 44 | | private Task? _shutdownTask; |
| | | 45 | | |
| | | 46 | | private readonly TimeSpan _shutdownTimeout; |
| | | 47 | | |
| | | 48 | | private readonly ServerAddress _serverAddress; |
| | | 49 | | |
| | | 50 | | /// <summary>Constructs a client connection.</summary> |
| | | 51 | | /// <param name="options">The client connection options.</param> |
| | | 52 | | /// <param name="duplexClientTransport">The duplex client transport. <see langword="null" /> is equivalent to <see |
| | | 53 | | /// cref="IDuplexClientTransport.Default" />.</param> |
| | | 54 | | /// <param name="multiplexedClientTransport">The multiplexed client transport. <see langword="null" /> is equivalent |
| | | 55 | | /// to <see cref="IMultiplexedClientTransport.Default" />.</param> |
| | | 56 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" />. |
| | | 57 | | /// </param> |
| | 137 | 58 | | public ClientConnection( |
| | 137 | 59 | | ClientConnectionOptions options, |
| | 137 | 60 | | IDuplexClientTransport? duplexClientTransport = null, |
| | 137 | 61 | | IMultiplexedClientTransport? multiplexedClientTransport = null, |
| | 137 | 62 | | ILogger? logger = null) |
| | 137 | 63 | | { |
| | 137 | 64 | | _connectTimeout = options.ConnectTimeout; |
| | 137 | 65 | | _shutdownTimeout = options.ShutdownTimeout; |
| | | 66 | | |
| | 137 | 67 | | duplexClientTransport ??= IDuplexClientTransport.Default; |
| | 137 | 68 | | multiplexedClientTransport ??= IMultiplexedClientTransport.Default; |
| | | 69 | | |
| | 137 | 70 | | _serverAddress = options.ServerAddress ?? |
| | 137 | 71 | | throw new ArgumentException( |
| | 137 | 72 | | $"{nameof(ClientConnectionOptions.ServerAddress)} is not set", |
| | 137 | 73 | | nameof(options)); |
| | | 74 | | |
| | 137 | 75 | | if (_serverAddress.Transport is null) |
| | 67 | 76 | | { |
| | 67 | 77 | | _serverAddress = _serverAddress with |
| | 67 | 78 | | { |
| | 67 | 79 | | Transport = _serverAddress.Protocol == Protocol.Ice ? |
| | 67 | 80 | | duplexClientTransport.Name : multiplexedClientTransport.Name |
| | 67 | 81 | | }; |
| | 67 | 82 | | } |
| | | 83 | | |
| | 137 | 84 | | _clientProtocolConnectionFactory = new ClientProtocolConnectionFactory( |
| | 137 | 85 | | options, |
| | 137 | 86 | | options.ClientAuthenticationOptions, |
| | 137 | 87 | | duplexClientTransport, |
| | 137 | 88 | | multiplexedClientTransport, |
| | 137 | 89 | | logger); |
| | 137 | 90 | | } |
| | | 91 | | |
| | | 92 | | /// <summary>Constructs a client connection with the specified server address and client authentication options. |
| | | 93 | | /// All other properties use the <see cref="ClientConnectionOptions" /> defaults.</summary> |
| | | 94 | | /// <param name="serverAddress">The connection's server address.</param> |
| | | 95 | | /// <param name="clientAuthenticationOptions">The SSL client authentication options. When not <see langword="null" |
| | | 96 | | /// />, <see cref="ConnectAsync(CancellationToken)" /> will either establish a secure connection or fail.</param> |
| | | 97 | | /// <param name="duplexClientTransport">The duplex client transport. <see langword="null" /> is equivalent to <see |
| | | 98 | | /// cref="IDuplexClientTransport.Default" />.</param> |
| | | 99 | | /// <param name="multiplexedClientTransport">The multiplexed client transport. <see langword="null" /> is equivalent |
| | | 100 | | /// to <see cref="IMultiplexedClientTransport.Default" />.</param> |
| | | 101 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" />. |
| | | 102 | | /// </param> |
| | | 103 | | public ClientConnection( |
| | | 104 | | ServerAddress serverAddress, |
| | | 105 | | SslClientAuthenticationOptions? clientAuthenticationOptions = null, |
| | | 106 | | IDuplexClientTransport? duplexClientTransport = null, |
| | | 107 | | IMultiplexedClientTransport? multiplexedClientTransport = null, |
| | | 108 | | ILogger? logger = null) |
| | 63 | 109 | | : this( |
| | 63 | 110 | | new ClientConnectionOptions |
| | 63 | 111 | | { |
| | 63 | 112 | | ClientAuthenticationOptions = clientAuthenticationOptions, |
| | 63 | 113 | | ServerAddress = serverAddress |
| | 63 | 114 | | }, |
| | 63 | 115 | | duplexClientTransport, |
| | 63 | 116 | | multiplexedClientTransport, |
| | 63 | 117 | | logger) |
| | 63 | 118 | | { |
| | 63 | 119 | | } |
| | | 120 | | |
| | | 121 | | /// <summary>Constructs a client connection with the specified server address URI and client authentication options. |
| | | 122 | | /// All other properties use the <see cref="ClientConnectionOptions" /> defaults.</summary> |
| | | 123 | | /// <param name="serverAddressUri">The connection's server address URI.</param> |
| | | 124 | | /// <param name="clientAuthenticationOptions">The SSL client authentication options. When not <see langword="null" |
| | | 125 | | /// />, <see cref="ConnectAsync(CancellationToken)" /> will either establish a secure connection or fail.</param> |
| | | 126 | | /// <param name="duplexClientTransport">The duplex client transport. <see langword="null" /> is equivalent to <see |
| | | 127 | | /// cref="IDuplexClientTransport.Default" />.</param> |
| | | 128 | | /// <param name="multiplexedClientTransport">The multiplexed client transport. <see langword="null" /> is equivalent |
| | | 129 | | /// to <see cref="IMultiplexedClientTransport.Default" />.</param> |
| | | 130 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" />. |
| | | 131 | | /// </param> |
| | | 132 | | public ClientConnection( |
| | | 133 | | Uri serverAddressUri, |
| | | 134 | | SslClientAuthenticationOptions? clientAuthenticationOptions = null, |
| | | 135 | | IDuplexClientTransport? duplexClientTransport = null, |
| | | 136 | | IMultiplexedClientTransport? multiplexedClientTransport = null, |
| | | 137 | | ILogger? logger = null) |
| | 3 | 138 | | : this( |
| | 3 | 139 | | new ServerAddress(serverAddressUri), |
| | 3 | 140 | | clientAuthenticationOptions, |
| | 3 | 141 | | duplexClientTransport, |
| | 3 | 142 | | multiplexedClientTransport, |
| | 3 | 143 | | logger) |
| | 3 | 144 | | { |
| | 3 | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary>Establishes the connection.</summary> |
| | | 148 | | /// <param name="cancellationToken">A cancellation token that receives the cancellation requests.</param> |
| | | 149 | | /// <returns>A task that provides the <see cref="TransportConnectionInformation" /> of the transport connection, |
| | | 150 | | /// once this connection is established. This task can also complete with one of the following exceptions: |
| | | 151 | | /// <list type="bullet"> |
| | | 152 | | /// <item><description><see cref="AuthenticationException" /> if authentication failed.</description></item> |
| | | 153 | | /// <item><description><see cref="IceRpcException" /> if the connection establishment failed.</description> |
| | | 154 | | /// </item> |
| | | 155 | | /// <item><description><see cref="OperationCanceledException" /> if cancellation was requested through the |
| | | 156 | | /// cancellation token.</description></item> |
| | | 157 | | /// <item><description><see cref="TimeoutException" /> if this connection attempt or a previous attempt exceeded |
| | | 158 | | /// <see cref="ClientConnectionOptions.ConnectTimeout" />.</description></item> |
| | | 159 | | /// </list> |
| | | 160 | | /// </returns> |
| | | 161 | | /// <exception cref="InvalidOperationException">Thrown if this client connection is shut down or shutting down. |
| | | 162 | | /// </exception> |
| | | 163 | | /// <exception cref="ObjectDisposedException">Thrown if this client connection is disposed.</exception> |
| | | 164 | | /// <remarks>This method can be called multiple times and concurrently. If the connection is not established, it |
| | | 165 | | /// will be connected or reconnected.</remarks> |
| | | 166 | | public Task<TransportConnectionInformation> ConnectAsync(CancellationToken cancellationToken = default) |
| | 98 | 167 | | { |
| | | 168 | | Task<TransportConnectionInformation> connectTask; |
| | | 169 | | |
| | 98 | 170 | | lock (_mutex) |
| | 98 | 171 | | { |
| | 98 | 172 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 98 | 173 | | if (_shutdownTask is not null) |
| | 0 | 174 | | { |
| | 0 | 175 | | throw new InvalidOperationException("Cannot connect a client connection after shutting it down."); |
| | | 176 | | } |
| | | 177 | | |
| | 98 | 178 | | if (_activeConnection is not null) |
| | 3 | 179 | | { |
| | 3 | 180 | | return Task.FromResult(_activeConnection.Value.ConnectionInformation); |
| | | 181 | | } |
| | | 182 | | |
| | 95 | 183 | | if (_pendingConnection is null) |
| | 95 | 184 | | { |
| | 95 | 185 | | IProtocolConnection newConnection = _clientProtocolConnectionFactory.CreateConnection(_serverAddress); |
| | 95 | 186 | | _detachedConnectionCount++; |
| | 95 | 187 | | connectTask = CreateConnectTask(newConnection, cancellationToken); |
| | 95 | 188 | | _pendingConnection = (newConnection, connectTask); |
| | 95 | 189 | | } |
| | | 190 | | else |
| | 0 | 191 | | { |
| | 0 | 192 | | connectTask = _pendingConnection.Value.ConnectTask.WaitAsync(cancellationToken); |
| | 0 | 193 | | } |
| | 95 | 194 | | } |
| | | 195 | | |
| | 95 | 196 | | return PerformConnectAsync(); |
| | | 197 | | |
| | | 198 | | async Task<TransportConnectionInformation> PerformConnectAsync() |
| | 95 | 199 | | { |
| | | 200 | | try |
| | 95 | 201 | | { |
| | 95 | 202 | | return await connectTask.ConfigureAwait(false); |
| | | 203 | | } |
| | 6 | 204 | | catch (OperationCanceledException) |
| | 6 | 205 | | { |
| | | 206 | | // Canceled via the cancellation token given to ConnectAsync, but not necessarily this ConnectAsync |
| | | 207 | | // call. |
| | | 208 | | |
| | 6 | 209 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 210 | | |
| | 0 | 211 | | throw new IceRpcException( |
| | 0 | 212 | | IceRpcError.ConnectionAborted, |
| | 0 | 213 | | "The connection establishment was canceled by another concurrent attempt."); |
| | | 214 | | } |
| | 53 | 215 | | } |
| | 98 | 216 | | } |
| | | 217 | | |
| | | 218 | | /// <summary>Releases all resources allocated by the connection. The connection disposes all the underlying |
| | | 219 | | /// connections it created.</summary> |
| | | 220 | | /// <returns>A value task that completes when the disposal of all the underlying connections has |
| | | 221 | | /// completed.</returns> |
| | | 222 | | /// <remarks>The disposal of an underlying connection aborts invocations, cancels dispatches and disposes the |
| | | 223 | | /// underlying transport connection without waiting for the peer. To wait for invocations and dispatches to |
| | | 224 | | /// complete, call <see cref="ShutdownAsync" /> first. If the configured dispatcher does not complete promptly when |
| | | 225 | | /// its cancellation token is canceled, the disposal can hang.</remarks> |
| | | 226 | | public ValueTask DisposeAsync() |
| | 149 | 227 | | { |
| | 149 | 228 | | lock (_mutex) |
| | 149 | 229 | | { |
| | 149 | 230 | | if (_disposeTask is null) |
| | 137 | 231 | | { |
| | 137 | 232 | | _shutdownTask ??= Task.CompletedTask; |
| | 137 | 233 | | if (_detachedConnectionCount == 0) |
| | 122 | 234 | | { |
| | 122 | 235 | | _ = _detachedConnectionsTcs.TrySetResult(); |
| | 122 | 236 | | } |
| | | 237 | | |
| | 137 | 238 | | _disposeTask = PerformDisposeAsync(); |
| | 137 | 239 | | } |
| | 149 | 240 | | } |
| | 149 | 241 | | return new(_disposeTask); |
| | | 242 | | |
| | | 243 | | async Task PerformDisposeAsync() |
| | 137 | 244 | | { |
| | 137 | 245 | | await Task.Yield(); // Exit mutex lock |
| | | 246 | | |
| | 137 | 247 | | _disposedCts.Cancel(); |
| | | 248 | | |
| | | 249 | | // Wait for shutdown before disposing connections. |
| | | 250 | | try |
| | 137 | 251 | | { |
| | 137 | 252 | | await _shutdownTask.ConfigureAwait(false); |
| | 133 | 253 | | } |
| | 4 | 254 | | catch |
| | 4 | 255 | | { |
| | | 256 | | // ignore exceptions. |
| | 4 | 257 | | } |
| | | 258 | | |
| | | 259 | | // Since a pending connection is "detached", it's disposed via the connectTask, not directly by this method. |
| | 137 | 260 | | if (_activeConnection is not null) |
| | 81 | 261 | | { |
| | 81 | 262 | | await _activeConnection.Value.Connection.DisposeAsync().ConfigureAwait(false); |
| | 81 | 263 | | } |
| | | 264 | | |
| | 137 | 265 | | await _detachedConnectionsTcs.Task.ConfigureAwait(false); |
| | | 266 | | |
| | 137 | 267 | | _disposedCts.Dispose(); |
| | 137 | 268 | | } |
| | 149 | 269 | | } |
| | | 270 | | |
| | | 271 | | /// <summary>Sends an outgoing request and returns the corresponding incoming response.</summary> |
| | | 272 | | /// <param name="request">The outgoing request being sent.</param> |
| | | 273 | | /// <param name="cancellationToken">A cancellation token that receives the cancellation requests.</param> |
| | | 274 | | /// <returns>The corresponding <see cref="IncomingResponse" />.</returns> |
| | | 275 | | /// <exception cref="InvalidOperationException">Thrown if none of the request's server addresses matches this |
| | | 276 | | /// connection's server address.</exception> |
| | | 277 | | /// <exception cref="IceRpcException">Thrown with error <see cref="IceRpcError.InvocationRefused" /> if this client |
| | | 278 | | /// connection is shutdown.</exception> |
| | | 279 | | /// <exception cref="ObjectDisposedException">Thrown if this client connection is disposed.</exception> |
| | | 280 | | /// <remarks>If the connection is not established, it will be connected or reconnected.</remarks> |
| | | 281 | | public Task<IncomingResponse> InvokeAsync(OutgoingRequest request, CancellationToken cancellationToken = default) |
| | 70 | 282 | | { |
| | 70 | 283 | | if (request.Features.Get<IServerAddressFeature>() is IServerAddressFeature serverAddressFeature) |
| | 0 | 284 | | { |
| | 0 | 285 | | if (serverAddressFeature.ServerAddress is ServerAddress mainServerAddress) |
| | 0 | 286 | | { |
| | 0 | 287 | | CheckRequestServerAddresses(mainServerAddress, serverAddressFeature.AltServerAddresses); |
| | 0 | 288 | | } |
| | 0 | 289 | | } |
| | 70 | 290 | | else if (request.ServiceAddress.ServerAddress is ServerAddress mainServerAddress) |
| | 34 | 291 | | { |
| | 34 | 292 | | CheckRequestServerAddresses(mainServerAddress, request.ServiceAddress.AltServerAddresses); |
| | 22 | 293 | | } |
| | | 294 | | // It's ok if the request has no server address at all. |
| | | 295 | | |
| | 58 | 296 | | IProtocolConnection? activeConnection = null; |
| | | 297 | | |
| | 58 | 298 | | lock (_mutex) |
| | 58 | 299 | | { |
| | 58 | 300 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | | 301 | | |
| | 58 | 302 | | if (_shutdownTask is not null) |
| | 0 | 303 | | { |
| | 0 | 304 | | throw new IceRpcException(IceRpcError.InvocationRefused, "The client connection was shut down."); |
| | | 305 | | } |
| | | 306 | | |
| | 58 | 307 | | activeConnection = _activeConnection?.Connection; |
| | 58 | 308 | | } |
| | | 309 | | |
| | 58 | 310 | | return PerformInvokeAsync(activeConnection); |
| | | 311 | | |
| | | 312 | | void CheckRequestServerAddresses( |
| | | 313 | | ServerAddress mainServerAddress, |
| | | 314 | | ImmutableList<ServerAddress> altServerAddresses) |
| | 34 | 315 | | { |
| | 34 | 316 | | if (ServerAddressComparer.OptionalTransport.Equals(mainServerAddress, _serverAddress)) |
| | 20 | 317 | | { |
| | 20 | 318 | | return; |
| | | 319 | | } |
| | | 320 | | |
| | 44 | 321 | | foreach (ServerAddress serverAddress in altServerAddresses) |
| | 2 | 322 | | { |
| | 2 | 323 | | if (ServerAddressComparer.OptionalTransport.Equals(serverAddress, _serverAddress)) |
| | 2 | 324 | | { |
| | 2 | 325 | | return; |
| | | 326 | | } |
| | 0 | 327 | | } |
| | | 328 | | |
| | 12 | 329 | | throw new InvalidOperationException( |
| | 12 | 330 | | $"None of the request's server addresses matches this connection's server address: {_serverAddress}"); |
| | 22 | 331 | | } |
| | | 332 | | |
| | | 333 | | async Task<IncomingResponse> PerformInvokeAsync(IProtocolConnection? connection) |
| | 58 | 334 | | { |
| | | 335 | | // When InvokeAsync throws an IceRpcException(InvocationRefused) we retry unless the client connection is |
| | | 336 | | // being shutdown or disposed. |
| | 58 | 337 | | while (true) |
| | 58 | 338 | | { |
| | 58 | 339 | | connection ??= await GetActiveConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | | 340 | | |
| | | 341 | | try |
| | 58 | 342 | | { |
| | 58 | 343 | | return await connection.InvokeAsync(request, cancellationToken).ConfigureAwait(false); |
| | | 344 | | } |
| | 0 | 345 | | catch (ObjectDisposedException) |
| | 0 | 346 | | { |
| | | 347 | | // This can occasionally happen if we find a connection that was just closed and then automatically |
| | | 348 | | // disposed by this client connection. |
| | 0 | 349 | | } |
| | 4 | 350 | | catch (IceRpcException exception) when (exception.IceRpcError == IceRpcError.InvocationRefused) |
| | 0 | 351 | | { |
| | | 352 | | // The connection is refusing new invocations. |
| | 0 | 353 | | } |
| | 4 | 354 | | catch (IceRpcException exception) when (exception.IceRpcError == IceRpcError.OperationAborted) |
| | 4 | 355 | | { |
| | 4 | 356 | | lock (_mutex) |
| | 4 | 357 | | { |
| | 4 | 358 | | if (_disposeTask is null) |
| | 0 | 359 | | { |
| | 0 | 360 | | throw new IceRpcException( |
| | 0 | 361 | | IceRpcError.ConnectionAborted, |
| | 0 | 362 | | "The underlying connection was disposed while the invocation was in progress."); |
| | | 363 | | } |
| | | 364 | | else |
| | 4 | 365 | | { |
| | 4 | 366 | | throw; |
| | | 367 | | } |
| | | 368 | | } |
| | | 369 | | } |
| | | 370 | | |
| | | 371 | | // Make sure connection is no longer in _activeConnection before we retry. |
| | 0 | 372 | | _ = RemoveFromActiveAsync(connection); |
| | 0 | 373 | | connection = null; |
| | 0 | 374 | | } |
| | 50 | 375 | | } |
| | 58 | 376 | | } |
| | | 377 | | |
| | | 378 | | /// <summary>Gracefully shuts down the connection. The shutdown waits for pending invocations and dispatches to |
| | | 379 | | /// complete.</summary> |
| | | 380 | | /// <param name="cancellationToken">A cancellation token that receives the cancellation requests.</param> |
| | | 381 | | /// <returns>A task that completes once the shutdown is complete. This task can also complete with one of the |
| | | 382 | | /// following exceptions: |
| | | 383 | | /// <list type="bullet"> |
| | | 384 | | /// <item><description><see cref="IceRpcException" /> if the connection shutdown failed.</description></item> |
| | | 385 | | /// <item><description><see cref="OperationCanceledException" /> if cancellation was requested through the |
| | | 386 | | /// cancellation token.</description></item> |
| | | 387 | | /// <item><description><see cref="TimeoutException" /> if this shutdown attempt or a previous attempt exceeded <see |
| | | 388 | | /// cref="ClientConnectionOptions.ShutdownTimeout" />.</description></item> |
| | | 389 | | /// </list> |
| | | 390 | | /// </returns> |
| | | 391 | | /// <exception cref="InvalidOperationException">Thrown if this connection is already shut down or shutting down. |
| | | 392 | | /// </exception> |
| | | 393 | | /// <exception cref="ObjectDisposedException">Thrown if this connection is disposed.</exception> |
| | | 394 | | public Task ShutdownAsync(CancellationToken cancellationToken = default) |
| | 16 | 395 | | { |
| | 16 | 396 | | lock (_mutex) |
| | 16 | 397 | | { |
| | 16 | 398 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | 16 | 399 | | if (_shutdownTask is not null) |
| | 0 | 400 | | { |
| | 0 | 401 | | throw new InvalidOperationException("The client connection is already shut down or shutting down."); |
| | | 402 | | } |
| | | 403 | | |
| | 16 | 404 | | if (_detachedConnectionCount == 0) |
| | 15 | 405 | | { |
| | 15 | 406 | | _ = _detachedConnectionsTcs.TrySetResult(); |
| | 15 | 407 | | } |
| | | 408 | | |
| | 16 | 409 | | _shutdownTask = PerformShutdownAsync(); |
| | 16 | 410 | | return _shutdownTask; |
| | | 411 | | } |
| | | 412 | | |
| | | 413 | | async Task PerformShutdownAsync() |
| | 16 | 414 | | { |
| | 16 | 415 | | await Task.Yield(); // exit mutex lock |
| | | 416 | | |
| | 16 | 417 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposedCts.Token); |
| | 16 | 418 | | cts.CancelAfter(_shutdownTimeout); |
| | | 419 | | |
| | | 420 | | // Since a pending connection is "detached", it's shutdown and disposed via the connectTask, not directly by |
| | | 421 | | // this method. |
| | | 422 | | try |
| | 16 | 423 | | { |
| | 16 | 424 | | if (_activeConnection is not null) |
| | 12 | 425 | | { |
| | 12 | 426 | | await _activeConnection.Value.Connection.ShutdownAsync(cts.Token).ConfigureAwait(false); |
| | 8 | 427 | | } |
| | | 428 | | |
| | 12 | 429 | | await _detachedConnectionsTcs.Task.WaitAsync(cts.Token).ConfigureAwait(false); |
| | 12 | 430 | | } |
| | 4 | 431 | | catch (OperationCanceledException) |
| | 4 | 432 | | { |
| | 4 | 433 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 434 | | |
| | 2 | 435 | | if (_disposedCts.IsCancellationRequested) |
| | 0 | 436 | | { |
| | 0 | 437 | | throw new IceRpcException( |
| | 0 | 438 | | IceRpcError.OperationAborted, |
| | 0 | 439 | | "The shutdown was aborted because the client connection was disposed."); |
| | | 440 | | } |
| | | 441 | | else |
| | 2 | 442 | | { |
| | 2 | 443 | | throw new TimeoutException( |
| | 2 | 444 | | $"The client connection shut down timed out after {_shutdownTimeout.TotalSeconds} s."); |
| | | 445 | | } |
| | | 446 | | } |
| | 0 | 447 | | catch |
| | 0 | 448 | | { |
| | | 449 | | // ignore other shutdown exception |
| | 0 | 450 | | } |
| | 12 | 451 | | } |
| | 16 | 452 | | } |
| | | 453 | | |
| | | 454 | | /// <summary>Creates the connection establishment task for a pending connection.</summary> |
| | | 455 | | /// <param name="connection">The new pending connection to connect.</param> |
| | | 456 | | /// <param name="cancellationToken">The cancellation token that can cancel this task.</param> |
| | | 457 | | /// <returns>A task that completes successfully when the connection is connected.</returns> |
| | | 458 | | private async Task<TransportConnectionInformation> CreateConnectTask( |
| | | 459 | | IProtocolConnection connection, |
| | | 460 | | CancellationToken cancellationToken) |
| | 133 | 461 | | { |
| | 133 | 462 | | await Task.Yield(); // exit mutex lock |
| | | 463 | | |
| | | 464 | | // This task "owns" a detachedConnectionCount and as a result _disposedCts can't be disposed. |
| | 133 | 465 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposedCts.Token); |
| | 133 | 466 | | cts.CancelAfter(_connectTimeout); |
| | | 467 | | |
| | | 468 | | TransportConnectionInformation connectionInformation; |
| | | 469 | | Task shutdownRequested; |
| | 133 | 470 | | Task? connectTask = null; |
| | | 471 | | |
| | | 472 | | try |
| | 133 | 473 | | { |
| | | 474 | | try |
| | 133 | 475 | | { |
| | 133 | 476 | | (connectionInformation, shutdownRequested) = await connection.ConnectAsync(cts.Token) |
| | 133 | 477 | | .ConfigureAwait(false); |
| | 91 | 478 | | } |
| | 10 | 479 | | catch (OperationCanceledException) |
| | 10 | 480 | | { |
| | 10 | 481 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 482 | | |
| | 4 | 483 | | if (_disposedCts.IsCancellationRequested) |
| | 2 | 484 | | { |
| | 2 | 485 | | throw new IceRpcException( |
| | 2 | 486 | | IceRpcError.OperationAborted, |
| | 2 | 487 | | "The connection establishment was aborted because the client connection was disposed."); |
| | | 488 | | } |
| | | 489 | | else |
| | 2 | 490 | | { |
| | 2 | 491 | | throw new TimeoutException( |
| | 2 | 492 | | $"The connection establishment timed out after {_connectTimeout.TotalSeconds} s."); |
| | | 493 | | } |
| | | 494 | | } |
| | 91 | 495 | | } |
| | 42 | 496 | | catch |
| | 42 | 497 | | { |
| | 42 | 498 | | lock (_mutex) |
| | 42 | 499 | | { |
| | 42 | 500 | | Debug.Assert(_pendingConnection is not null && _pendingConnection.Value.Connection == connection); |
| | 42 | 501 | | Debug.Assert(_activeConnection is null); |
| | | 502 | | |
| | | 503 | | // connectTask is executing this method and about to throw. |
| | 42 | 504 | | connectTask = _pendingConnection.Value.ConnectTask; |
| | 42 | 505 | | _pendingConnection = null; |
| | 42 | 506 | | } |
| | | 507 | | |
| | 42 | 508 | | _ = DisposePendingConnectionAsync(connection, connectTask); |
| | 42 | 509 | | throw; |
| | | 510 | | } |
| | | 511 | | |
| | 91 | 512 | | lock (_mutex) |
| | 91 | 513 | | { |
| | 91 | 514 | | Debug.Assert(_pendingConnection is not null && _pendingConnection.Value.Connection == connection); |
| | 91 | 515 | | Debug.Assert(_activeConnection is null); |
| | | 516 | | |
| | 91 | 517 | | if (_shutdownTask is null) |
| | 91 | 518 | | { |
| | | 519 | | // the connection is now "attached" in _activeConnection |
| | 91 | 520 | | _activeConnection = (connection, connectionInformation); |
| | 91 | 521 | | _detachedConnectionCount--; |
| | 91 | 522 | | } |
| | | 523 | | else |
| | 0 | 524 | | { |
| | 0 | 525 | | connectTask = _pendingConnection.Value.ConnectTask; |
| | 0 | 526 | | } |
| | 91 | 527 | | _pendingConnection = null; |
| | 91 | 528 | | } |
| | | 529 | | |
| | 91 | 530 | | if (connectTask is null) |
| | 91 | 531 | | { |
| | 91 | 532 | | _ = ShutdownWhenRequestedAsync(connection, shutdownRequested); |
| | 91 | 533 | | } |
| | | 534 | | else |
| | 0 | 535 | | { |
| | | 536 | | // As soon as this method completes successfully, we shut down then dispose the connection. |
| | 0 | 537 | | _ = DisposePendingConnectionAsync(connection, connectTask); |
| | 0 | 538 | | } |
| | 91 | 539 | | return connectionInformation; |
| | | 540 | | |
| | | 541 | | async Task DisposePendingConnectionAsync(IProtocolConnection connection, Task connectTask) |
| | 42 | 542 | | { |
| | | 543 | | try |
| | 42 | 544 | | { |
| | 42 | 545 | | await connectTask.ConfigureAwait(false); |
| | | 546 | | |
| | | 547 | | // Since we own a detachedConnectionCount, _disposedCts is not disposed. |
| | 0 | 548 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token); |
| | 0 | 549 | | cts.CancelAfter(_shutdownTimeout); |
| | 0 | 550 | | await connection.ShutdownAsync(cts.Token).ConfigureAwait(false); |
| | 0 | 551 | | } |
| | 42 | 552 | | catch |
| | 42 | 553 | | { |
| | | 554 | | // Observe and ignore exceptions. |
| | 42 | 555 | | } |
| | | 556 | | |
| | 42 | 557 | | await connection.DisposeAsync().ConfigureAwait(false); |
| | | 558 | | |
| | 42 | 559 | | lock (_mutex) |
| | 42 | 560 | | { |
| | 42 | 561 | | if (--_detachedConnectionCount == 0 && _shutdownTask is not null) |
| | 14 | 562 | | { |
| | 14 | 563 | | _detachedConnectionsTcs.SetResult(); |
| | 14 | 564 | | } |
| | 42 | 565 | | } |
| | 42 | 566 | | } |
| | | 567 | | |
| | | 568 | | async Task ShutdownWhenRequestedAsync(IProtocolConnection connection, Task shutdownRequested) |
| | 91 | 569 | | { |
| | 91 | 570 | | await shutdownRequested.ConfigureAwait(false); |
| | 18 | 571 | | await RemoveFromActiveAsync(connection).ConfigureAwait(false); |
| | 18 | 572 | | } |
| | 91 | 573 | | } |
| | | 574 | | |
| | | 575 | | /// <summary>Removes the connection from _activeConnection, and when successful, shuts down and disposes this |
| | | 576 | | /// connection.</summary> |
| | | 577 | | /// <param name="connection">The connected connection to shutdown and dispose.</param> |
| | | 578 | | private Task RemoveFromActiveAsync(IProtocolConnection connection) |
| | 18 | 579 | | { |
| | 18 | 580 | | lock (_mutex) |
| | 18 | 581 | | { |
| | 18 | 582 | | if (_shutdownTask is null && _activeConnection?.Connection == connection) |
| | 10 | 583 | | { |
| | 10 | 584 | | _activeConnection = null; // it's now our connection. |
| | 10 | 585 | | _detachedConnectionCount++; |
| | 10 | 586 | | } |
| | | 587 | | else |
| | 8 | 588 | | { |
| | | 589 | | // Another task owns this connection |
| | 8 | 590 | | return Task.CompletedTask; |
| | | 591 | | } |
| | 10 | 592 | | } |
| | | 593 | | |
| | 10 | 594 | | return ShutdownAndDisposeConnectionAsync(); |
| | | 595 | | |
| | | 596 | | async Task ShutdownAndDisposeConnectionAsync() |
| | 10 | 597 | | { |
| | | 598 | | // _disposedCts is not disposed since we own a detachedConnectionCount |
| | 10 | 599 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token); |
| | 10 | 600 | | cts.CancelAfter(_shutdownTimeout); |
| | | 601 | | |
| | | 602 | | try |
| | 10 | 603 | | { |
| | 10 | 604 | | await connection.ShutdownAsync(cts.Token).ConfigureAwait(false); |
| | 8 | 605 | | } |
| | 2 | 606 | | catch |
| | 2 | 607 | | { |
| | | 608 | | // Ignore connection shutdown failures |
| | 2 | 609 | | } |
| | | 610 | | |
| | 10 | 611 | | await connection.DisposeAsync().ConfigureAwait(false); |
| | | 612 | | |
| | 10 | 613 | | lock (_mutex) |
| | 10 | 614 | | { |
| | 10 | 615 | | if (--_detachedConnectionCount == 0 && _shutdownTask is not null) |
| | 2 | 616 | | { |
| | 2 | 617 | | _detachedConnectionsTcs.SetResult(); |
| | 2 | 618 | | } |
| | 10 | 619 | | } |
| | 10 | 620 | | } |
| | 18 | 621 | | } |
| | | 622 | | |
| | | 623 | | /// <summary>Gets an active connection, by creating and connecting (if necessary) a new protocol connection. |
| | | 624 | | /// </summary> |
| | | 625 | | /// <param name="cancellationToken">The cancellation token of the invocation calling this method.</param> |
| | | 626 | | /// <returns>A connected connection.</returns> |
| | | 627 | | /// <remarks>This method is called exclusively by <see cref="InvokeAsync" />.</remarks> |
| | | 628 | | private ValueTask<IProtocolConnection> GetActiveConnectionAsync(CancellationToken cancellationToken) |
| | 38 | 629 | | { |
| | | 630 | | (IProtocolConnection Connection, Task<TransportConnectionInformation> ConnectTask) pendingConnectionValue; |
| | | 631 | | |
| | 38 | 632 | | lock (_mutex) |
| | 38 | 633 | | { |
| | 38 | 634 | | if (_disposeTask is not null) |
| | 0 | 635 | | { |
| | 0 | 636 | | throw new IceRpcException(IceRpcError.OperationAborted, "The client connection was disposed."); |
| | | 637 | | } |
| | 38 | 638 | | if (_shutdownTask is not null) |
| | 0 | 639 | | { |
| | 0 | 640 | | throw new IceRpcException(IceRpcError.InvocationRefused, "The client connection was shut down."); |
| | | 641 | | } |
| | | 642 | | |
| | 38 | 643 | | if (_activeConnection is not null) |
| | 0 | 644 | | { |
| | 0 | 645 | | return new(_activeConnection.Value.Connection); |
| | | 646 | | } |
| | | 647 | | |
| | 38 | 648 | | if (_pendingConnection is null) |
| | 38 | 649 | | { |
| | 38 | 650 | | IProtocolConnection connection = _clientProtocolConnectionFactory.CreateConnection(_serverAddress); |
| | 38 | 651 | | _detachedConnectionCount++; |
| | | 652 | | |
| | | 653 | | // We pass CancellationToken.None because the invocation cancellation should not cancel the connection |
| | | 654 | | // establishment. |
| | 38 | 655 | | Task<TransportConnectionInformation> connectTask = |
| | 38 | 656 | | CreateConnectTask(connection, CancellationToken.None); |
| | 38 | 657 | | _pendingConnection = (connection, connectTask); |
| | 38 | 658 | | } |
| | 38 | 659 | | pendingConnectionValue = _pendingConnection.Value; |
| | 38 | 660 | | } |
| | | 661 | | |
| | 38 | 662 | | return PerformGetActiveConnectionAsync(); |
| | | 663 | | |
| | | 664 | | async ValueTask<IProtocolConnection> PerformGetActiveConnectionAsync() |
| | 38 | 665 | | { |
| | | 666 | | // ConnectTask itself takes care of scheduling its exception observation when it fails. |
| | | 667 | | try |
| | 38 | 668 | | { |
| | 38 | 669 | | _ = await pendingConnectionValue.ConnectTask.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | 38 | 670 | | } |
| | 0 | 671 | | catch (OperationCanceledException) |
| | 0 | 672 | | { |
| | 0 | 673 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 674 | | |
| | | 675 | | // Canceled by the cancellation token given to ClientConnection.ConnectAsync. |
| | 0 | 676 | | throw new IceRpcException( |
| | 0 | 677 | | IceRpcError.ConnectionAborted, |
| | 0 | 678 | | "The connection establishment was canceled by another concurrent attempt."); |
| | | 679 | | } |
| | 38 | 680 | | return pendingConnectionValue.Connection; |
| | 38 | 681 | | } |
| | 38 | 682 | | } |
| | | 683 | | } |