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