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