| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using IceRpc.Internal; |
| | | 4 | | using IceRpc.Transports; |
| | | 5 | | using IceRpc.Transports.Internal; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | using Microsoft.Extensions.Logging.Abstractions; |
| | | 8 | | using System.Diagnostics; |
| | | 9 | | using System.Net; |
| | | 10 | | using System.Net.Security; |
| | | 11 | | using System.Security.Authentication; |
| | | 12 | | |
| | | 13 | | namespace IceRpc; |
| | | 14 | | |
| | | 15 | | /// <summary>A server accepts connections from clients and dispatches the requests it receives over these connections. |
| | | 16 | | /// </summary> |
| | | 17 | | public sealed class Server : IAsyncDisposable |
| | | 18 | | { |
| | 90 | 19 | | private readonly LinkedList<IProtocolConnection> _connections = new(); |
| | | 20 | | |
| | | 21 | | private readonly TimeSpan _connectTimeout; |
| | | 22 | | |
| | | 23 | | // A detached connection is a protocol connection that we've decided to connect, or that is connecting, shutting |
| | | 24 | | // down or being disposed. It counts towards _maxConnections and both Server.ShutdownAsync and DisposeAsync wait for |
| | | 25 | | // detached connections to reach 0 using _detachedConnectionsTcs. Such a connection is "detached" because it's not |
| | | 26 | | // in _connections. |
| | | 27 | | private int _detachedConnectionCount; |
| | | 28 | | |
| | 90 | 29 | | private readonly TaskCompletionSource _detachedConnectionsTcs = new(); |
| | | 30 | | |
| | | 31 | | // A cancellation token source that is canceled by DisposeAsync. |
| | 90 | 32 | | private readonly CancellationTokenSource _disposedCts = new(); |
| | | 33 | | |
| | | 34 | | private Task? _disposeTask; |
| | | 35 | | |
| | | 36 | | private readonly Func<IConnectorListener> _listenerFactory; |
| | | 37 | | |
| | | 38 | | private Task? _listenTask; |
| | | 39 | | |
| | | 40 | | private readonly int _maxConnections; |
| | | 41 | | |
| | | 42 | | private readonly int _maxPendingConnections; |
| | | 43 | | |
| | 90 | 44 | | private readonly Lock _mutex = new(); |
| | | 45 | | |
| | | 46 | | private readonly ServerAddress _serverAddress; |
| | | 47 | | |
| | | 48 | | // A cancellation token source canceled by ShutdownAsync and DisposeAsync. |
| | | 49 | | private readonly CancellationTokenSource _shutdownCts; |
| | | 50 | | |
| | | 51 | | private Task? _shutdownTask; |
| | | 52 | | |
| | | 53 | | private readonly TimeSpan _shutdownTimeout; |
| | | 54 | | |
| | | 55 | | /// <summary>Constructs a server.</summary> |
| | | 56 | | /// <param name="options">The server options.</param> |
| | | 57 | | /// <param name="duplexServerTransport">The transport used to create ice protocol connections. The <see |
| | | 58 | | /// langword="null" /> value is equivalent to <see cref="IDuplexServerTransport.Default" />.</param> |
| | | 59 | | /// <param name="multiplexedServerTransport">The transport used to create icerpc protocol connections. The <see |
| | | 60 | | /// langword="null" /> value is equivalent to <see cref="IMultiplexedServerTransport.Default" />.</param> |
| | | 61 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" |
| | | 62 | | /// />.</param> |
| | 90 | 63 | | public Server( |
| | 90 | 64 | | ServerOptions options, |
| | 90 | 65 | | IDuplexServerTransport? duplexServerTransport = null, |
| | 90 | 66 | | IMultiplexedServerTransport? multiplexedServerTransport = null, |
| | 90 | 67 | | ILogger? logger = null) |
| | 90 | 68 | | { |
| | 90 | 69 | | if (options.ConnectionOptions.Dispatcher is null) |
| | 0 | 70 | | { |
| | 0 | 71 | | throw new ArgumentException($"{nameof(ServerOptions.ConnectionOptions.Dispatcher)} cannot be null"); |
| | | 72 | | } |
| | | 73 | | |
| | 90 | 74 | | logger ??= NullLogger.Instance; |
| | | 75 | | |
| | 90 | 76 | | _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token); |
| | | 77 | | |
| | 90 | 78 | | duplexServerTransport ??= IDuplexServerTransport.Default; |
| | 90 | 79 | | multiplexedServerTransport ??= IMultiplexedServerTransport.Default; |
| | 90 | 80 | | _maxConnections = options.MaxConnections; |
| | 90 | 81 | | _maxPendingConnections = options.MaxPendingConnections; |
| | | 82 | | |
| | 90 | 83 | | _connectTimeout = options.ConnectTimeout; |
| | 90 | 84 | | _shutdownTimeout = options.ShutdownTimeout; |
| | | 85 | | |
| | 90 | 86 | | _serverAddress = options.ServerAddress; |
| | 90 | 87 | | if (_serverAddress.Transport is null) |
| | 79 | 88 | | { |
| | 79 | 89 | | _serverAddress = _serverAddress with |
| | 79 | 90 | | { |
| | 79 | 91 | | Transport = _serverAddress.Protocol == Protocol.Ice ? |
| | 79 | 92 | | duplexServerTransport.DefaultName : multiplexedServerTransport.DefaultName |
| | 79 | 93 | | }; |
| | 79 | 94 | | } |
| | | 95 | | |
| | 90 | 96 | | if (options.ServerAuthenticationOptions?.ApplicationProtocols is not null) |
| | 0 | 97 | | { |
| | 0 | 98 | | throw new ArgumentException( |
| | 0 | 99 | | "The ApplicationProtocols property of the SSL server authentication options must be null. The ALPN is se |
| | 0 | 100 | | nameof(options)); |
| | | 101 | | } |
| | | 102 | | |
| | 90 | 103 | | var transportAddress = new TransportAddress |
| | 90 | 104 | | { |
| | 90 | 105 | | Host = _serverAddress.Host, |
| | 90 | 106 | | Port = _serverAddress.Port, |
| | 90 | 107 | | TransportName = _serverAddress.Transport, |
| | 90 | 108 | | Params = _serverAddress.Params |
| | 90 | 109 | | }; |
| | | 110 | | |
| | 90 | 111 | | _listenerFactory = () => |
| | 89 | 112 | | { |
| | 90 | 113 | | IConnectorListener listener; |
| | 90 | 114 | | |
| | 89 | 115 | | SslServerAuthenticationOptions? serverAuthenticationOptions = options.ServerAuthenticationOptions; |
| | 89 | 116 | | if (serverAuthenticationOptions is not null) |
| | 5 | 117 | | { |
| | 5 | 118 | | serverAuthenticationOptions = serverAuthenticationOptions.ShallowClone(); |
| | 5 | 119 | | serverAuthenticationOptions.ApplicationProtocols = [_serverAddress.Protocol.AlpnProtocol]; |
| | 5 | 120 | | } |
| | 90 | 121 | | |
| | 89 | 122 | | if (_serverAddress.Protocol == Protocol.Ice) |
| | 25 | 123 | | { |
| | 25 | 124 | | IListener<IDuplexConnection> transportListener = duplexServerTransport.Listen( |
| | 25 | 125 | | transportAddress, |
| | 25 | 126 | | new DuplexConnectionOptions |
| | 25 | 127 | | { |
| | 25 | 128 | | MinSegmentSize = options.ConnectionOptions.MinSegmentSize, |
| | 25 | 129 | | Pool = options.ConnectionOptions.Pool, |
| | 25 | 130 | | }, |
| | 25 | 131 | | serverAuthenticationOptions); |
| | 90 | 132 | | |
| | 25 | 133 | | listener = new IceConnectorListener(transportListener, _serverAddress, options.ConnectionOptions); |
| | 25 | 134 | | } |
| | 90 | 135 | | else |
| | 64 | 136 | | { |
| | 64 | 137 | | IListener<IMultiplexedConnection> transportListener = multiplexedServerTransport.Listen( |
| | 64 | 138 | | transportAddress, |
| | 64 | 139 | | new MultiplexedConnectionOptions |
| | 64 | 140 | | { |
| | 64 | 141 | | HandshakeTimeout = options.ConnectTimeout, |
| | 64 | 142 | | MaxBidirectionalStreams = options.ConnectionOptions.MaxIceRpcBidirectionalStreams, |
| | 64 | 143 | | // Add an additional stream for the icerpc protocol control stream. |
| | 64 | 144 | | MaxUnidirectionalStreams = options.ConnectionOptions.MaxIceRpcUnidirectionalStreams + 1, |
| | 64 | 145 | | MinSegmentSize = options.ConnectionOptions.MinSegmentSize, |
| | 64 | 146 | | Pool = options.ConnectionOptions.Pool |
| | 64 | 147 | | }, |
| | 64 | 148 | | serverAuthenticationOptions); |
| | 90 | 149 | | |
| | 64 | 150 | | listener = new IceRpcConnectorListener( |
| | 64 | 151 | | transportListener, |
| | 64 | 152 | | _serverAddress, |
| | 64 | 153 | | options.ConnectionOptions, |
| | 64 | 154 | | logger == NullLogger.Instance ? null : new LogTaskExceptionObserver(logger)); |
| | 64 | 155 | | } |
| | 90 | 156 | | |
| | 89 | 157 | | listener = new MetricsConnectorListenerDecorator(listener); |
| | 89 | 158 | | if (logger != NullLogger.Instance) |
| | 10 | 159 | | { |
| | 10 | 160 | | listener = new LogConnectorListenerDecorator(listener, logger); |
| | 10 | 161 | | } |
| | 89 | 162 | | return listener; |
| | 179 | 163 | | }; |
| | 90 | 164 | | } |
| | | 165 | | |
| | | 166 | | /// <summary>Constructs a server with the specified dispatcher and authentication options. All other properties |
| | | 167 | | /// use the <see cref="ServerOptions" /> defaults.</summary> |
| | | 168 | | /// <param name="dispatcher">The dispatcher of the server.</param> |
| | | 169 | | /// <param name="serverAuthenticationOptions">The SSL server authentication options. When not <see langword="null" |
| | | 170 | | /// />, the server will accept only secure connections.</param> |
| | | 171 | | /// <param name="duplexServerTransport">The transport used to create ice protocol connections. <see langword="null" |
| | | 172 | | /// /> is equivalent to <see cref="IDuplexServerTransport.Default" />.</param> |
| | | 173 | | /// <param name="multiplexedServerTransport">The transport used to create icerpc protocol connections. <see |
| | | 174 | | /// langword="null" /> is equivalent to <see cref="IMultiplexedServerTransport.Default" />.</param> |
| | | 175 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" |
| | | 176 | | /// />.</param> |
| | | 177 | | public Server( |
| | | 178 | | IDispatcher dispatcher, |
| | | 179 | | SslServerAuthenticationOptions? serverAuthenticationOptions = null, |
| | | 180 | | IDuplexServerTransport? duplexServerTransport = null, |
| | | 181 | | IMultiplexedServerTransport? multiplexedServerTransport = null, |
| | | 182 | | ILogger? logger = null) |
| | 1 | 183 | | : this( |
| | 1 | 184 | | new ServerOptions |
| | 1 | 185 | | { |
| | 1 | 186 | | ServerAuthenticationOptions = serverAuthenticationOptions, |
| | 1 | 187 | | ConnectionOptions = new() |
| | 1 | 188 | | { |
| | 1 | 189 | | Dispatcher = dispatcher, |
| | 1 | 190 | | } |
| | 1 | 191 | | }, |
| | 1 | 192 | | duplexServerTransport, |
| | 1 | 193 | | multiplexedServerTransport, |
| | 1 | 194 | | logger) |
| | 1 | 195 | | { |
| | 1 | 196 | | } |
| | | 197 | | |
| | | 198 | | /// <summary>Constructs a server with the specified dispatcher, server address and authentication options. All |
| | | 199 | | /// other properties use the <see cref="ServerOptions" /> defaults.</summary> |
| | | 200 | | /// <param name="dispatcher">The dispatcher of the server.</param> |
| | | 201 | | /// <param name="serverAddress">The server address of the server.</param> |
| | | 202 | | /// <param name="serverAuthenticationOptions">The SSL server authentication options. When not <see langword="null" |
| | | 203 | | /// />, the server will accept only secure connections.</param> |
| | | 204 | | /// <param name="duplexServerTransport">The transport used to create ice protocol connections. <see langword="null" |
| | | 205 | | /// /> is equivalent to <see cref="IDuplexServerTransport.Default" />.</param> |
| | | 206 | | /// <param name="multiplexedServerTransport">The transport used to create icerpc protocol connections. <see |
| | | 207 | | /// langword="null" /> is equivalent to <see cref="IMultiplexedServerTransport.Default" />.</param> |
| | | 208 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" |
| | | 209 | | /// />.</param> |
| | | 210 | | public Server( |
| | | 211 | | IDispatcher dispatcher, |
| | | 212 | | ServerAddress serverAddress, |
| | | 213 | | SslServerAuthenticationOptions? serverAuthenticationOptions = null, |
| | | 214 | | IDuplexServerTransport? duplexServerTransport = null, |
| | | 215 | | IMultiplexedServerTransport? multiplexedServerTransport = null, |
| | | 216 | | ILogger? logger = null) |
| | 34 | 217 | | : this( |
| | 34 | 218 | | new ServerOptions |
| | 34 | 219 | | { |
| | 34 | 220 | | ServerAuthenticationOptions = serverAuthenticationOptions, |
| | 34 | 221 | | ConnectionOptions = new() |
| | 34 | 222 | | { |
| | 34 | 223 | | Dispatcher = dispatcher, |
| | 34 | 224 | | }, |
| | 34 | 225 | | ServerAddress = serverAddress |
| | 34 | 226 | | }, |
| | 34 | 227 | | duplexServerTransport, |
| | 34 | 228 | | multiplexedServerTransport, |
| | 34 | 229 | | logger) |
| | 34 | 230 | | { |
| | 34 | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary>Constructs a server with the specified dispatcher, server address URI and authentication options. All |
| | | 234 | | /// other properties use the <see cref="ServerOptions" /> defaults.</summary> |
| | | 235 | | /// <param name="dispatcher">The dispatcher of the server.</param> |
| | | 236 | | /// <param name="serverAddressUri">A URI that represents the server address of the server.</param> |
| | | 237 | | /// <param name="serverAuthenticationOptions">The SSL server authentication options. When not <see langword="null" |
| | | 238 | | /// />, the server will accept only secure connections.</param> |
| | | 239 | | /// <param name="duplexServerTransport">The transport used to create ice protocol connections. <see langword="null" |
| | | 240 | | /// /> is equivalent to <see cref="IDuplexServerTransport.Default" />.</param> |
| | | 241 | | /// <param name="multiplexedServerTransport">The transport used to create icerpc protocol connections. <see |
| | | 242 | | /// langword="null" /> is equivalent to <see cref="IMultiplexedServerTransport.Default" />.</param> |
| | | 243 | | /// <param name="logger">The logger. <see langword="null" /> is equivalent to <see cref="NullLogger.Instance" |
| | | 244 | | /// />.</param> |
| | | 245 | | public Server( |
| | | 246 | | IDispatcher dispatcher, |
| | | 247 | | Uri serverAddressUri, |
| | | 248 | | SslServerAuthenticationOptions? serverAuthenticationOptions = null, |
| | | 249 | | IDuplexServerTransport? duplexServerTransport = null, |
| | | 250 | | IMultiplexedServerTransport? multiplexedServerTransport = null, |
| | | 251 | | ILogger? logger = null) |
| | 14 | 252 | | : this( |
| | 14 | 253 | | dispatcher, |
| | 14 | 254 | | new ServerAddress(serverAddressUri), |
| | 14 | 255 | | serverAuthenticationOptions, |
| | 14 | 256 | | duplexServerTransport, |
| | 14 | 257 | | multiplexedServerTransport, |
| | 14 | 258 | | logger) |
| | 14 | 259 | | { |
| | 14 | 260 | | } |
| | | 261 | | |
| | | 262 | | /// <summary>Releases all resources allocated by this server. The server stops listening for new connections and |
| | | 263 | | /// disposes the connections it accepted from clients.</summary> |
| | | 264 | | /// <returns>A value task that completes when the disposal of all connections accepted by the server has completed. |
| | | 265 | | /// This includes connections that were active when this method is called and connections whose disposal was |
| | | 266 | | /// initiated prior to this call.</returns> |
| | | 267 | | /// <remarks>The disposal of an underlying connection of the server aborts invocations, cancels dispatches and |
| | | 268 | | /// disposes the underlying transport connection without waiting for the peer. To wait for invocations and |
| | | 269 | | /// dispatches to complete, call <see cref="ShutdownAsync" /> first. If the configured dispatcher does not complete |
| | | 270 | | /// promptly when its cancellation token is canceled, the disposal can hang.</remarks> |
| | | 271 | | public ValueTask DisposeAsync() |
| | 91 | 272 | | { |
| | | 273 | | lock (_mutex) |
| | 91 | 274 | | { |
| | 91 | 275 | | if (_disposeTask is null) |
| | 90 | 276 | | { |
| | 90 | 277 | | _shutdownTask ??= Task.CompletedTask; |
| | 90 | 278 | | if (_detachedConnectionCount == 0) |
| | 82 | 279 | | { |
| | 82 | 280 | | _ = _detachedConnectionsTcs.TrySetResult(); |
| | 82 | 281 | | } |
| | | 282 | | |
| | 90 | 283 | | _disposeTask = PerformDisposeAsync(); |
| | 90 | 284 | | } |
| | 91 | 285 | | return new(_disposeTask); |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | async Task PerformDisposeAsync() |
| | 90 | 289 | | { |
| | 90 | 290 | | await Task.Yield(); // exit mutex lock |
| | | 291 | | |
| | 90 | 292 | | _disposedCts.Cancel(); |
| | | 293 | | |
| | | 294 | | // _listenTask etc are immutable when _disposeTask is not null. |
| | | 295 | | |
| | 90 | 296 | | if (_listenTask is not null) |
| | 89 | 297 | | { |
| | | 298 | | // Wait for shutdown before disposing connections. |
| | | 299 | | try |
| | 89 | 300 | | { |
| | 89 | 301 | | await Task.WhenAll(_listenTask, _shutdownTask).ConfigureAwait(false); |
| | 89 | 302 | | } |
| | 0 | 303 | | catch |
| | 0 | 304 | | { |
| | | 305 | | // Ignore exceptions. |
| | 0 | 306 | | } |
| | | 307 | | |
| | 89 | 308 | | await Task.WhenAll( |
| | 89 | 309 | | _connections |
| | 46 | 310 | | .Select(connection => connection.DisposeAsync().AsTask()) |
| | 89 | 311 | | .Append(_detachedConnectionsTcs.Task)).ConfigureAwait(false); |
| | 89 | 312 | | } |
| | | 313 | | |
| | 90 | 314 | | _disposedCts.Dispose(); |
| | 90 | 315 | | _shutdownCts.Dispose(); |
| | 90 | 316 | | } |
| | 91 | 317 | | } |
| | | 318 | | |
| | | 319 | | /// <summary>Starts accepting connections on the configured server address. Requests received over these connections |
| | | 320 | | /// are then dispatched by the configured dispatcher.</summary> |
| | | 321 | | /// <returns>The server address this server is listening on and that a client would connect to. This address is the |
| | | 322 | | /// same as the <see cref="ServerOptions.ServerAddress" /> of <see cref="ServerOptions" /> except its |
| | | 323 | | /// <see cref="ServerAddress.Transport" /> property is always non-null and its port number is never 0 when the host |
| | | 324 | | /// is an IP address.</returns> |
| | | 325 | | /// <exception cref="IceRpcException">Thrown when the server transport fails to listen on the configured <see |
| | | 326 | | /// cref="ServerOptions.ServerAddress" />.</exception> |
| | | 327 | | /// <exception cref="InvalidOperationException">Thrown when the server is already listening, shut down or shutting |
| | | 328 | | /// down.</exception> |
| | | 329 | | /// <exception cref="ObjectDisposedException">Throw when the server is disposed.</exception> |
| | | 330 | | /// <remarks><see cref="Listen" /> can also throw exceptions from the transport; for example, the transport can |
| | | 331 | | /// reject the server address.</remarks> |
| | | 332 | | public ServerAddress Listen() |
| | 91 | 333 | | { |
| | | 334 | | lock (_mutex) |
| | 91 | 335 | | { |
| | 91 | 336 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | | 337 | | |
| | 90 | 338 | | if (_shutdownTask is not null) |
| | 0 | 339 | | { |
| | 0 | 340 | | throw new InvalidOperationException($"Server '{this}' is shut down or shutting down."); |
| | | 341 | | } |
| | 90 | 342 | | if (_listenTask is not null) |
| | 1 | 343 | | { |
| | 1 | 344 | | throw new InvalidOperationException($"Server '{this}' is already listening."); |
| | | 345 | | } |
| | | 346 | | |
| | 89 | 347 | | IConnectorListener listener = _listenerFactory(); |
| | 89 | 348 | | _listenTask = ListenAsync(listener); // _listenTask owns listener and must dispose it |
| | 89 | 349 | | return listener.ServerAddress; |
| | | 350 | | } |
| | | 351 | | |
| | | 352 | | async Task ListenAsync(IConnectorListener listener) |
| | 89 | 353 | | { |
| | 89 | 354 | | await Task.Yield(); // exit mutex lock |
| | | 355 | | |
| | | 356 | | try |
| | 89 | 357 | | { |
| | 89 | 358 | | using var pendingConnectionSemaphore = new SemaphoreSlim( |
| | 89 | 359 | | _maxPendingConnections, |
| | 89 | 360 | | _maxPendingConnections); |
| | | 361 | | |
| | 176 | 362 | | while (!_shutdownCts.IsCancellationRequested) |
| | 176 | 363 | | { |
| | 176 | 364 | | await pendingConnectionSemaphore.WaitAsync(_shutdownCts.Token).ConfigureAwait(false); |
| | | 365 | | |
| | 175 | 366 | | IConnector? connector = null; |
| | | 367 | | do |
| | 345 | 368 | | { |
| | | 369 | | try |
| | 345 | 370 | | { |
| | 345 | 371 | | (connector, _) = await listener.AcceptAsync(_shutdownCts.Token).ConfigureAwait(false); |
| | 87 | 372 | | } |
| | 258 | 373 | | catch (Exception exception) when (IsRetryableAcceptException(exception)) |
| | 170 | 374 | | { |
| | | 375 | | // continue |
| | 170 | 376 | | } |
| | 257 | 377 | | } |
| | 257 | 378 | | while (connector is null); |
| | | 379 | | |
| | | 380 | | // We don't wait for the connection to be activated or shutdown. This could take a while for some |
| | | 381 | | // transports such as TLS based transports where the handshake requires few round trips between the |
| | | 382 | | // client and server. Waiting could also cause a security issue if the client doesn't respond to the |
| | | 383 | | // connection initialization as we wouldn't be able to accept new connections in the meantime. The |
| | | 384 | | // call will eventually timeout if the ConnectTimeout expires. |
| | 87 | 385 | | CancellationToken cancellationToken = _disposedCts.Token; |
| | 87 | 386 | | _ = Task.Run( |
| | 87 | 387 | | async () => |
| | 87 | 388 | | { |
| | 87 | 389 | | try |
| | 87 | 390 | | { |
| | 87 | 391 | | await ConnectAsync(connector, cancellationToken).ConfigureAwait(false); |
| | 82 | 392 | | } |
| | 5 | 393 | | catch |
| | 5 | 394 | | { |
| | 87 | 395 | | // Ignore connection establishment failure. This failures are logged by the |
| | 87 | 396 | | // LogConnectorDecorator |
| | 5 | 397 | | } |
| | 87 | 398 | | finally |
| | 87 | 399 | | { |
| | 87 | 400 | | // The connection dispose will dispose the transport connection if it has not been |
| | 87 | 401 | | // adopted by the protocol connection. |
| | 87 | 402 | | await connector.DisposeAsync().ConfigureAwait(false); |
| | 87 | 403 | | |
| | 87 | 404 | | // The pending connection semaphore is disposed by the listen task completion once |
| | 87 | 405 | | // shutdown / dispose is initiated. |
| | 87 | 406 | | lock (_mutex) |
| | 87 | 407 | | { |
| | 87 | 408 | | if (_shutdownTask is null) |
| | 83 | 409 | | { |
| | 83 | 410 | | pendingConnectionSemaphore.Release(); |
| | 83 | 411 | | } |
| | 87 | 412 | | } |
| | 87 | 413 | | } |
| | 87 | 414 | | }, |
| | 87 | 415 | | CancellationToken.None); // the task must run to dispose the connector. |
| | 87 | 416 | | } |
| | 0 | 417 | | } |
| | 89 | 418 | | catch |
| | 89 | 419 | | { |
| | | 420 | | // Ignore. Exceptions thrown by listener.AcceptAsync are logged by the log decorator when appropriate. |
| | 89 | 421 | | } |
| | | 422 | | finally |
| | 89 | 423 | | { |
| | 89 | 424 | | await listener.DisposeAsync().ConfigureAwait(false); |
| | 89 | 425 | | } |
| | | 426 | | |
| | | 427 | | async Task ConnectAsync(IConnector connector, CancellationToken cancellationToken) |
| | 87 | 428 | | { |
| | 87 | 429 | | using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | 87 | 430 | | connectCts.CancelAfter(_connectTimeout); |
| | | 431 | | |
| | | 432 | | // Connect the transport connection first. This connection establishment can be interrupted by the |
| | | 433 | | // connect timeout or the server ShutdownAsync/DisposeAsync. |
| | 87 | 434 | | TransportConnectionInformation transportConnectionInformation = |
| | 87 | 435 | | await connector.ConnectTransportConnectionAsync(connectCts.Token).ConfigureAwait(false); |
| | | 436 | | |
| | 82 | 437 | | IProtocolConnection? protocolConnection = null; |
| | 82 | 438 | | bool serverBusy = false; |
| | | 439 | | |
| | | 440 | | lock (_mutex) |
| | 82 | 441 | | { |
| | 82 | 442 | | Debug.Assert( |
| | 82 | 443 | | _maxConnections == 0 || _connections.Count + _detachedConnectionCount <= _maxConnections); |
| | | 444 | | |
| | 82 | 445 | | if (_shutdownTask is null) |
| | 82 | 446 | | { |
| | 82 | 447 | | if (_maxConnections > 0 && (_connections.Count + _detachedConnectionCount) == _maxConnections) |
| | 7 | 448 | | { |
| | 7 | 449 | | serverBusy = true; |
| | 7 | 450 | | } |
| | | 451 | | else |
| | 75 | 452 | | { |
| | | 453 | | // The protocol connection adopts the transport connection from the connector and it's |
| | | 454 | | // now responsible for disposing of it. |
| | 75 | 455 | | protocolConnection = connector.CreateProtocolConnection(transportConnectionInformation); |
| | 75 | 456 | | _detachedConnectionCount++; |
| | 75 | 457 | | } |
| | 82 | 458 | | } |
| | 82 | 459 | | } |
| | | 460 | | |
| | 82 | 461 | | if (protocolConnection is null) |
| | 7 | 462 | | { |
| | | 463 | | try |
| | 7 | 464 | | { |
| | 7 | 465 | | await connector.RefuseTransportConnectionAsync(serverBusy, connectCts.Token) |
| | 7 | 466 | | .ConfigureAwait(false); |
| | 5 | 467 | | } |
| | 2 | 468 | | catch |
| | 2 | 469 | | { |
| | | 470 | | // ignore and continue |
| | 2 | 471 | | } |
| | | 472 | | // The transport connection is disposed by the disposal of the connector. |
| | 7 | 473 | | } |
| | | 474 | | else |
| | 75 | 475 | | { |
| | | 476 | | Task shutdownRequested; |
| | | 477 | | try |
| | 75 | 478 | | { |
| | 75 | 479 | | (_, shutdownRequested) = await protocolConnection.ConnectAsync(connectCts.Token) |
| | 75 | 480 | | .ConfigureAwait(false); |
| | 75 | 481 | | } |
| | 0 | 482 | | catch |
| | 0 | 483 | | { |
| | 0 | 484 | | await DisposeDetachedConnectionAsync(protocolConnection, withShutdown: false) |
| | 0 | 485 | | .ConfigureAwait(false); |
| | 0 | 486 | | throw; |
| | | 487 | | } |
| | | 488 | | |
| | 75 | 489 | | LinkedListNode<IProtocolConnection>? listNode = null; |
| | | 490 | | |
| | | 491 | | lock (_mutex) |
| | | 492 | | { |
| | 75 | 493 | | if (_shutdownTask is null) |
| | | 494 | | { |
| | 74 | 495 | | listNode = _connections.AddLast(protocolConnection); |
| | | 496 | | |
| | | 497 | | // protocolConnection is no longer a detached connection since it's now "attached" in |
| | | 498 | | // _connections. |
| | 74 | 499 | | _detachedConnectionCount--; |
| | | 500 | | } |
| | 75 | 501 | | } |
| | | 502 | | |
| | 75 | 503 | | if (listNode is null) |
| | | 504 | | { |
| | 1 | 505 | | await DisposeDetachedConnectionAsync(protocolConnection, withShutdown: true) |
| | 1 | 506 | | .ConfigureAwait(false); |
| | | 507 | | } |
| | | 508 | | else |
| | 74 | 509 | | { |
| | | 510 | | // Schedule removal after successful ConnectAsync. |
| | 74 | 511 | | _ = ShutdownWhenRequestedAsync(protocolConnection, shutdownRequested, listNode); |
| | | 512 | | } |
| | 75 | 513 | | } |
| | | 514 | | } |
| | | 515 | | } |
| | | 516 | | |
| | | 517 | | async Task DisposeDetachedConnectionAsync(IProtocolConnection connection, bool withShutdown) |
| | 29 | 518 | | { |
| | 29 | 519 | | if (withShutdown) |
| | 29 | 520 | | { |
| | | 521 | | // _disposedCts is not disposed since we own a _backgroundConnectionDisposeCount. |
| | 29 | 522 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource(_disposedCts.Token); |
| | 29 | 523 | | cts.CancelAfter(_shutdownTimeout); |
| | | 524 | | |
| | | 525 | | try |
| | 29 | 526 | | { |
| | | 527 | | // Can be canceled by DisposeAsync or the shutdown timeout. |
| | 29 | 528 | | await connection.ShutdownAsync(cts.Token).ConfigureAwait(false); |
| | 22 | 529 | | } |
| | 7 | 530 | | catch |
| | 7 | 531 | | { |
| | | 532 | | // Ignore connection shutdown failures. connection.ShutdownAsync makes sure it's an "expected" |
| | | 533 | | // exception. |
| | 7 | 534 | | } |
| | 29 | 535 | | } |
| | | 536 | | |
| | 29 | 537 | | await connection.DisposeAsync().ConfigureAwait(false); |
| | | 538 | | lock (_mutex) |
| | 29 | 539 | | { |
| | 29 | 540 | | if (--_detachedConnectionCount == 0 && _shutdownTask is not null) |
| | 15 | 541 | | { |
| | 15 | 542 | | _detachedConnectionsTcs.SetResult(); |
| | 15 | 543 | | } |
| | 29 | 544 | | } |
| | 29 | 545 | | } |
| | | 546 | | |
| | | 547 | | // Remove the connection from _connections after a successful ConnectAsync. |
| | | 548 | | async Task ShutdownWhenRequestedAsync( |
| | | 549 | | IProtocolConnection connection, |
| | | 550 | | Task shutdownRequested, |
| | | 551 | | LinkedListNode<IProtocolConnection> listNode) |
| | 74 | 552 | | { |
| | 74 | 553 | | await shutdownRequested.ConfigureAwait(false); |
| | | 554 | | |
| | | 555 | | lock (_mutex) |
| | 61 | 556 | | { |
| | 61 | 557 | | if (_shutdownTask is null) |
| | 28 | 558 | | { |
| | 28 | 559 | | _connections.Remove(listNode); |
| | 28 | 560 | | _detachedConnectionCount++; |
| | 28 | 561 | | } |
| | | 562 | | else |
| | 33 | 563 | | { |
| | | 564 | | // _connections is immutable and ShutdownAsync/DisposeAsync is responsible to shutdown/dispose |
| | | 565 | | // this connection. |
| | 33 | 566 | | return; |
| | | 567 | | } |
| | 28 | 568 | | } |
| | | 569 | | |
| | 28 | 570 | | await DisposeDetachedConnectionAsync(connection, withShutdown: true).ConfigureAwait(false); |
| | 61 | 571 | | } |
| | 260 | 572 | | } |
| | | 573 | | |
| | | 574 | | /// <summary>Gracefully shuts down this server: the server stops accepting new connections and shuts down gracefully |
| | | 575 | | /// all its connections.</summary> |
| | | 576 | | /// <param name="cancellationToken">A cancellation token that receives the cancellation requests.</param> |
| | | 577 | | /// <returns>A task that completes successfully once the shutdown of all connections accepted by the server has |
| | | 578 | | /// completed. This includes connections that were active when this method is called and connections whose shutdown |
| | | 579 | | /// was initiated prior to this call.</returns> |
| | | 580 | | /// <exception cref="InvalidOperationException">Thrown if this method is called more than once.</exception> |
| | | 581 | | /// <exception cref="ObjectDisposedException">Thrown if the server is disposed.</exception> |
| | | 582 | | /// <remarks><para>The returned task can also complete with one of the following exceptions:</para> |
| | | 583 | | /// <list type="bullet"> |
| | | 584 | | /// <item><description><see cref="IceRpcException" /> with error <see cref="IceRpcError.OperationAborted" /> if the |
| | | 585 | | /// server is disposed while being shut down.</description></item> |
| | | 586 | | /// <item><description><see cref="OperationCanceledException" /> if cancellation was requested through the |
| | | 587 | | /// cancellation token.</description></item> |
| | | 588 | | /// <item><description><see cref="TimeoutException" /> if the shutdown timed out.</description></item> |
| | | 589 | | /// </list> |
| | | 590 | | /// </remarks> |
| | | 591 | | public Task ShutdownAsync(CancellationToken cancellationToken = default) |
| | 32 | 592 | | { |
| | | 593 | | lock (_mutex) |
| | 32 | 594 | | { |
| | 32 | 595 | | ObjectDisposedException.ThrowIf(_disposeTask is not null, this); |
| | | 596 | | |
| | 32 | 597 | | if (_shutdownTask is not null) |
| | 0 | 598 | | { |
| | 0 | 599 | | throw new InvalidOperationException($"Server '{this}' is shut down or shutting down."); |
| | | 600 | | } |
| | | 601 | | |
| | 32 | 602 | | if (_detachedConnectionCount == 0) |
| | 25 | 603 | | { |
| | 25 | 604 | | _detachedConnectionsTcs.SetResult(); |
| | 25 | 605 | | } |
| | | 606 | | |
| | 32 | 607 | | _shutdownTask = PerformShutdownAsync(); |
| | 32 | 608 | | } |
| | 32 | 609 | | return _shutdownTask; |
| | | 610 | | |
| | | 611 | | async Task PerformShutdownAsync() |
| | 32 | 612 | | { |
| | 32 | 613 | | await Task.Yield(); // exit mutex lock |
| | | 614 | | |
| | 32 | 615 | | _shutdownCts.Cancel(); |
| | | 616 | | |
| | | 617 | | // _listenTask is immutable once _shutdownTask is not null. |
| | 32 | 618 | | if (_listenTask is not null) |
| | 32 | 619 | | { |
| | | 620 | | try |
| | 32 | 621 | | { |
| | 32 | 622 | | using var cts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 32 | 623 | | cancellationToken, |
| | 32 | 624 | | _disposedCts.Token); |
| | | 625 | | |
| | 32 | 626 | | cts.CancelAfter(_shutdownTimeout); |
| | | 627 | | |
| | | 628 | | try |
| | 32 | 629 | | { |
| | 32 | 630 | | await Task.WhenAll( |
| | 32 | 631 | | _connections |
| | 12 | 632 | | .Select(connection => connection.ShutdownAsync(cts.Token)) |
| | 32 | 633 | | .Append(_listenTask.WaitAsync(cts.Token)) |
| | 32 | 634 | | .Append(_detachedConnectionsTcs.Task.WaitAsync(cts.Token))) |
| | 32 | 635 | | .ConfigureAwait(false); |
| | 32 | 636 | | } |
| | 0 | 637 | | catch (OperationCanceledException) |
| | 0 | 638 | | { |
| | 0 | 639 | | throw; |
| | | 640 | | } |
| | 0 | 641 | | catch |
| | 0 | 642 | | { |
| | | 643 | | // Ignore _listenTask and connection shutdown exceptions |
| | | 644 | | |
| | | 645 | | // Throw OperationCanceledException if this WhenAll exception is hiding an OCE. |
| | 0 | 646 | | cts.Token.ThrowIfCancellationRequested(); |
| | 0 | 647 | | } |
| | 32 | 648 | | } |
| | 0 | 649 | | catch (OperationCanceledException) |
| | 0 | 650 | | { |
| | 0 | 651 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 652 | | |
| | 0 | 653 | | if (_disposedCts.IsCancellationRequested) |
| | 0 | 654 | | { |
| | 0 | 655 | | throw new IceRpcException( |
| | 0 | 656 | | IceRpcError.OperationAborted, |
| | 0 | 657 | | "The shutdown was aborted because the server was disposed."); |
| | | 658 | | } |
| | | 659 | | else |
| | 0 | 660 | | { |
| | 0 | 661 | | throw new TimeoutException( |
| | 0 | 662 | | $"The server shut down timed out after {_shutdownTimeout.TotalSeconds} s."); |
| | | 663 | | } |
| | | 664 | | } |
| | 32 | 665 | | } |
| | 32 | 666 | | } |
| | 32 | 667 | | } |
| | | 668 | | |
| | | 669 | | /// <summary>Returns a string that represents this server.</summary> |
| | | 670 | | /// <returns>A string that represents this server.</returns> |
| | 1 | 671 | | public override string ToString() => _serverAddress.ToString(); |
| | | 672 | | |
| | | 673 | | /// <summary>Returns true if the <see cref="IConnectorListener.AcceptAsync" /> failure can be retried.</summary> |
| | | 674 | | private static bool IsRetryableAcceptException(Exception exception) => |
| | | 675 | | // Transports such as QUIC do the SSL handshake when the connection is accepted, this can throw |
| | | 676 | | // AuthenticationException if it fails. |
| | 258 | 677 | | exception is IceRpcException or AuthenticationException; |
| | | 678 | | |
| | | 679 | | /// <summary>Provides a decorator that adds logging to a <see cref="IConnectorListener" />.</summary> |
| | | 680 | | private class LogConnectorListenerDecorator : IConnectorListener |
| | | 681 | | { |
| | 46 | 682 | | public ServerAddress ServerAddress => _decoratee.ServerAddress; |
| | | 683 | | |
| | | 684 | | private readonly IConnectorListener _decoratee; |
| | | 685 | | private readonly ILogger _logger; |
| | | 686 | | |
| | | 687 | | public async Task<(IConnector, EndPoint)> AcceptAsync(CancellationToken cancellationToken) |
| | 18 | 688 | | { |
| | | 689 | | try |
| | 18 | 690 | | { |
| | 18 | 691 | | (IConnector connector, EndPoint remoteNetworkAddress) = |
| | 18 | 692 | | await _decoratee.AcceptAsync(cancellationToken).ConfigureAwait(false); |
| | | 693 | | |
| | 8 | 694 | | _logger.LogConnectionAccepted(ServerAddress, remoteNetworkAddress); |
| | 8 | 695 | | return ( |
| | 8 | 696 | | new LogConnectorDecorator(connector, ServerAddress, remoteNetworkAddress, _logger), |
| | 8 | 697 | | remoteNetworkAddress); |
| | | 698 | | } |
| | 10 | 699 | | catch (OperationCanceledException exception) when (exception.CancellationToken == cancellationToken) |
| | 10 | 700 | | { |
| | | 701 | | // Do not log this exception. The AcceptAsync call can fail with OperationCanceledException during |
| | | 702 | | // shutdown once the shutdown cancellation token is canceled. |
| | 10 | 703 | | throw; |
| | | 704 | | } |
| | 0 | 705 | | catch (ObjectDisposedException) |
| | 0 | 706 | | { |
| | | 707 | | // Do not log this exception. The AcceptAsync call can fail with ObjectDisposedException during |
| | | 708 | | // shutdown once the listener is disposed or if it is accepting a connection while the listener is |
| | | 709 | | // disposed. |
| | 0 | 710 | | throw; |
| | | 711 | | } |
| | 0 | 712 | | catch (Exception exception) when (IsRetryableAcceptException(exception)) |
| | 0 | 713 | | { |
| | 0 | 714 | | _logger.LogConnectionAcceptFailedWithRetryableException(ServerAddress, exception); |
| | 0 | 715 | | throw; |
| | | 716 | | } |
| | 0 | 717 | | catch (Exception exception) |
| | 0 | 718 | | { |
| | 0 | 719 | | _logger.LogConnectionAcceptFailed(ServerAddress, exception); |
| | 0 | 720 | | throw; |
| | | 721 | | } |
| | 8 | 722 | | } |
| | | 723 | | |
| | | 724 | | public ValueTask DisposeAsync() |
| | 10 | 725 | | { |
| | 10 | 726 | | _logger.LogStopAcceptingConnections(ServerAddress); |
| | 10 | 727 | | return _decoratee.DisposeAsync(); |
| | 10 | 728 | | } |
| | | 729 | | |
| | 10 | 730 | | internal LogConnectorListenerDecorator(IConnectorListener decoratee, ILogger logger) |
| | 10 | 731 | | { |
| | 10 | 732 | | _decoratee = decoratee; |
| | 10 | 733 | | _logger = logger; |
| | 10 | 734 | | _logger.LogStartAcceptingConnections(ServerAddress); |
| | 10 | 735 | | } |
| | | 736 | | } |
| | | 737 | | |
| | | 738 | | private class LogConnectorDecorator : IConnector |
| | | 739 | | { |
| | | 740 | | private readonly IConnector _decoratee; |
| | | 741 | | private readonly ILogger _logger; |
| | | 742 | | private readonly EndPoint _remoteNetworkAddress; |
| | | 743 | | private readonly ServerAddress _serverAddress; |
| | | 744 | | |
| | | 745 | | public async Task<TransportConnectionInformation> ConnectTransportConnectionAsync( |
| | | 746 | | CancellationToken cancellationToken) |
| | 8 | 747 | | { |
| | | 748 | | try |
| | 8 | 749 | | { |
| | 8 | 750 | | return await _decoratee.ConnectTransportConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | | 751 | | } |
| | 2 | 752 | | catch (Exception exception) |
| | 2 | 753 | | { |
| | 2 | 754 | | _logger.LogConnectionConnectFailed(_serverAddress, _remoteNetworkAddress, exception); |
| | 2 | 755 | | throw; |
| | | 756 | | } |
| | 6 | 757 | | } |
| | | 758 | | |
| | | 759 | | public IProtocolConnection CreateProtocolConnection( |
| | | 760 | | TransportConnectionInformation transportConnectionInformation) => |
| | 6 | 761 | | new LogProtocolConnectionDecorator( |
| | 6 | 762 | | _decoratee.CreateProtocolConnection(transportConnectionInformation), |
| | 6 | 763 | | _serverAddress, |
| | 6 | 764 | | _remoteNetworkAddress, |
| | 6 | 765 | | _logger); |
| | | 766 | | |
| | 8 | 767 | | public ValueTask DisposeAsync() => _decoratee.DisposeAsync(); |
| | | 768 | | |
| | | 769 | | public Task RefuseTransportConnectionAsync(bool serverBusy, CancellationToken cancel) => |
| | 0 | 770 | | _decoratee.RefuseTransportConnectionAsync(serverBusy, cancel); |
| | | 771 | | |
| | 8 | 772 | | internal LogConnectorDecorator( |
| | 8 | 773 | | IConnector decoratee, |
| | 8 | 774 | | ServerAddress serverAddress, |
| | 8 | 775 | | EndPoint remoteNetworkAddress, |
| | 8 | 776 | | ILogger logger) |
| | 8 | 777 | | { |
| | 8 | 778 | | _decoratee = decoratee; |
| | 8 | 779 | | _logger = logger; |
| | 8 | 780 | | _serverAddress = serverAddress; |
| | 8 | 781 | | _remoteNetworkAddress = remoteNetworkAddress; |
| | 8 | 782 | | } |
| | | 783 | | } |
| | | 784 | | |
| | | 785 | | /// <summary>Provides a decorator that adds metrics to a <see cref="IConnectorListener" />.</summary> |
| | | 786 | | private class MetricsConnectorListenerDecorator : IConnectorListener |
| | | 787 | | { |
| | 125 | 788 | | public ServerAddress ServerAddress => _decoratee.ServerAddress; |
| | | 789 | | |
| | | 790 | | private readonly IConnectorListener _decoratee; |
| | | 791 | | |
| | | 792 | | public async Task<(IConnector, EndPoint)> AcceptAsync( |
| | | 793 | | CancellationToken cancellationToken) |
| | 345 | 794 | | { |
| | 345 | 795 | | (IConnector connector, EndPoint remoteNetworkAddress) = |
| | 345 | 796 | | await _decoratee.AcceptAsync(cancellationToken).ConfigureAwait(false); |
| | 87 | 797 | | return (new MetricsConnectorDecorator(connector), remoteNetworkAddress); |
| | 87 | 798 | | } |
| | | 799 | | |
| | 89 | 800 | | public ValueTask DisposeAsync() => _decoratee.DisposeAsync(); |
| | | 801 | | |
| | 89 | 802 | | internal MetricsConnectorListenerDecorator(IConnectorListener decoratee) => |
| | 89 | 803 | | _decoratee = decoratee; |
| | | 804 | | } |
| | | 805 | | |
| | | 806 | | private class MetricsConnectorDecorator : IConnector |
| | | 807 | | { |
| | | 808 | | private readonly IConnector _decoratee; |
| | | 809 | | |
| | | 810 | | public async Task<TransportConnectionInformation> ConnectTransportConnectionAsync( |
| | | 811 | | CancellationToken cancellationToken) |
| | 87 | 812 | | { |
| | 87 | 813 | | Metrics.ServerMetrics.ConnectStart(); |
| | | 814 | | try |
| | 87 | 815 | | { |
| | 87 | 816 | | return await _decoratee.ConnectTransportConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | | 817 | | } |
| | 5 | 818 | | catch |
| | 5 | 819 | | { |
| | 5 | 820 | | Metrics.ServerMetrics.ConnectStop(); |
| | 5 | 821 | | Metrics.ServerMetrics.ConnectionFailure(); |
| | 5 | 822 | | throw; |
| | | 823 | | } |
| | 82 | 824 | | } |
| | | 825 | | |
| | | 826 | | public IProtocolConnection CreateProtocolConnection( |
| | | 827 | | TransportConnectionInformation transportConnectionInformation) => |
| | 75 | 828 | | new MetricsProtocolConnectionDecorator( |
| | 75 | 829 | | _decoratee.CreateProtocolConnection(transportConnectionInformation), |
| | 75 | 830 | | Metrics.ServerMetrics, |
| | 75 | 831 | | connectStarted: true); |
| | | 832 | | |
| | 87 | 833 | | public ValueTask DisposeAsync() => _decoratee.DisposeAsync(); |
| | | 834 | | |
| | | 835 | | public async Task RefuseTransportConnectionAsync(bool serverBusy, CancellationToken cancel) |
| | 7 | 836 | | { |
| | | 837 | | try |
| | 7 | 838 | | { |
| | 7 | 839 | | await _decoratee.RefuseTransportConnectionAsync(serverBusy, cancel).ConfigureAwait(false); |
| | 5 | 840 | | } |
| | | 841 | | finally |
| | 7 | 842 | | { |
| | 7 | 843 | | Metrics.ServerMetrics.ConnectionFailure(); |
| | 7 | 844 | | Metrics.ServerMetrics.ConnectStop(); |
| | 7 | 845 | | } |
| | 5 | 846 | | } |
| | | 847 | | |
| | 174 | 848 | | internal MetricsConnectorDecorator(IConnector decoratee) => _decoratee = decoratee; |
| | | 849 | | } |
| | | 850 | | |
| | | 851 | | /// <summary>A connector listener accepts a transport connection and returns a <see cref="IConnector" />. The |
| | | 852 | | /// connector is used to refuse the transport connection or obtain a protocol connection once the transport |
| | | 853 | | /// connection is connected.</summary> |
| | | 854 | | private interface IConnectorListener : IAsyncDisposable |
| | | 855 | | { |
| | | 856 | | ServerAddress ServerAddress { get; } |
| | | 857 | | |
| | | 858 | | Task<(IConnector, EndPoint)> AcceptAsync(CancellationToken cancel); |
| | | 859 | | } |
| | | 860 | | |
| | | 861 | | /// <summary>A connector is returned by <see cref="IConnectorListener" />. The connector allows to connect the |
| | | 862 | | /// transport connection. If successful, the transport connection can either be refused or accepted by creating the |
| | | 863 | | /// protocol connection out of it.</summary> |
| | | 864 | | private interface IConnector : IAsyncDisposable |
| | | 865 | | { |
| | | 866 | | Task<TransportConnectionInformation> ConnectTransportConnectionAsync(CancellationToken cancellationToken); |
| | | 867 | | |
| | | 868 | | IProtocolConnection CreateProtocolConnection(TransportConnectionInformation transportConnectionInformation); |
| | | 869 | | |
| | | 870 | | Task RefuseTransportConnectionAsync(bool serverBusy, CancellationToken cancel); |
| | | 871 | | } |
| | | 872 | | |
| | | 873 | | private class IceConnectorListener : IConnectorListener |
| | | 874 | | { |
| | 43 | 875 | | public ServerAddress ServerAddress { get; } |
| | | 876 | | |
| | | 877 | | private readonly IListener<IDuplexConnection> _listener; |
| | | 878 | | private readonly ConnectionOptions _options; |
| | | 879 | | |
| | 25 | 880 | | public ValueTask DisposeAsync() => _listener.DisposeAsync(); |
| | | 881 | | |
| | | 882 | | public async Task<(IConnector, EndPoint)> AcceptAsync(CancellationToken cancel) |
| | 51 | 883 | | { |
| | 51 | 884 | | (IDuplexConnection transportConnection, EndPoint remoteNetworkAddress) = await _listener.AcceptAsync( |
| | 51 | 885 | | cancel).ConfigureAwait(false); |
| | 26 | 886 | | return (new IceConnector(transportConnection, _options), remoteNetworkAddress); |
| | 26 | 887 | | } |
| | | 888 | | |
| | 25 | 889 | | internal IceConnectorListener( |
| | 25 | 890 | | IListener<IDuplexConnection> listener, |
| | 25 | 891 | | ServerAddress serverAddress, |
| | 25 | 892 | | ConnectionOptions options) |
| | 25 | 893 | | { |
| | 25 | 894 | | _listener = listener; |
| | 25 | 895 | | ServerAddress = serverAddress with { Port = listener.TransportAddress.Port }; |
| | 25 | 896 | | _options = options; |
| | 25 | 897 | | } |
| | | 898 | | } |
| | | 899 | | |
| | | 900 | | private class IceConnector : IConnector |
| | | 901 | | { |
| | | 902 | | private readonly ConnectionOptions _options; |
| | | 903 | | private IDuplexConnection? _transportConnection; |
| | | 904 | | |
| | | 905 | | public Task<TransportConnectionInformation> ConnectTransportConnectionAsync( |
| | | 906 | | CancellationToken cancellationToken) => |
| | 26 | 907 | | _transportConnection!.ConnectAsync(cancellationToken); |
| | | 908 | | |
| | | 909 | | public IProtocolConnection CreateProtocolConnection( |
| | | 910 | | TransportConnectionInformation transportConnectionInformation) |
| | 23 | 911 | | { |
| | | 912 | | // The protocol connection takes ownership of the transport connection. |
| | 23 | 913 | | var protocolConnection = new IceProtocolConnection( |
| | 23 | 914 | | _transportConnection!, |
| | 23 | 915 | | transportConnectionInformation, |
| | 23 | 916 | | _options); |
| | 23 | 917 | | _transportConnection = null; |
| | 23 | 918 | | return protocolConnection; |
| | 23 | 919 | | } |
| | | 920 | | |
| | | 921 | | public ValueTask DisposeAsync() |
| | 26 | 922 | | { |
| | 26 | 923 | | _transportConnection?.Dispose(); |
| | 26 | 924 | | return new(); |
| | 26 | 925 | | } |
| | | 926 | | |
| | | 927 | | public Task RefuseTransportConnectionAsync(bool serverBusy, CancellationToken cancellationToken) |
| | 2 | 928 | | { |
| | 2 | 929 | | _transportConnection!.Dispose(); |
| | 2 | 930 | | return Task.CompletedTask; |
| | 2 | 931 | | } |
| | | 932 | | |
| | 26 | 933 | | internal IceConnector(IDuplexConnection transportConnection, ConnectionOptions options) |
| | 26 | 934 | | { |
| | 26 | 935 | | _transportConnection = transportConnection; |
| | 26 | 936 | | _options = options; |
| | 26 | 937 | | } |
| | | 938 | | } |
| | | 939 | | |
| | | 940 | | private class IceRpcConnectorListener : IConnectorListener |
| | | 941 | | { |
| | 82 | 942 | | public ServerAddress ServerAddress { get; } |
| | | 943 | | |
| | | 944 | | private readonly IListener<IMultiplexedConnection> _listener; |
| | | 945 | | private readonly ConnectionOptions _options; |
| | | 946 | | private readonly ITaskExceptionObserver? _taskExceptionObserver; |
| | | 947 | | |
| | | 948 | | public async Task<(IConnector, EndPoint)> AcceptAsync(CancellationToken cancel) |
| | 294 | 949 | | { |
| | 294 | 950 | | (IMultiplexedConnection transportConnection, EndPoint remoteNetworkAddress) = await _listener.AcceptAsync( |
| | 294 | 951 | | cancel).ConfigureAwait(false); |
| | 61 | 952 | | return (new IceRpcConnector(transportConnection, _options, _taskExceptionObserver), remoteNetworkAddress); |
| | 61 | 953 | | } |
| | | 954 | | |
| | 64 | 955 | | public ValueTask DisposeAsync() => _listener.DisposeAsync(); |
| | | 956 | | |
| | 64 | 957 | | internal IceRpcConnectorListener( |
| | 64 | 958 | | IListener<IMultiplexedConnection> listener, |
| | 64 | 959 | | ServerAddress serverAddress, |
| | 64 | 960 | | ConnectionOptions options, |
| | 64 | 961 | | ITaskExceptionObserver? taskExceptionObserver) |
| | 64 | 962 | | { |
| | 64 | 963 | | _listener = listener; |
| | 64 | 964 | | ServerAddress = serverAddress with { Port = listener.TransportAddress.Port }; |
| | 64 | 965 | | _options = options; |
| | 64 | 966 | | _taskExceptionObserver = taskExceptionObserver; |
| | 64 | 967 | | } |
| | | 968 | | } |
| | | 969 | | |
| | | 970 | | private class IceRpcConnector : IConnector |
| | | 971 | | { |
| | | 972 | | private readonly ConnectionOptions _options; |
| | | 973 | | private readonly ITaskExceptionObserver? _taskExceptionObserver; |
| | | 974 | | private IMultiplexedConnection? _transportConnection; |
| | | 975 | | |
| | | 976 | | public Task<TransportConnectionInformation> ConnectTransportConnectionAsync( |
| | | 977 | | CancellationToken cancellationToken) => |
| | 61 | 978 | | _transportConnection!.ConnectAsync(cancellationToken); |
| | | 979 | | |
| | | 980 | | public IProtocolConnection CreateProtocolConnection( |
| | | 981 | | TransportConnectionInformation transportConnectionInformation) |
| | 52 | 982 | | { |
| | | 983 | | // The protocol connection takes ownership of the transport connection. |
| | 52 | 984 | | var protocolConnection = new IceRpcProtocolConnection( |
| | 52 | 985 | | _transportConnection!, |
| | 52 | 986 | | transportConnectionInformation, |
| | 52 | 987 | | _options, |
| | 52 | 988 | | _taskExceptionObserver); |
| | 52 | 989 | | _transportConnection = null; |
| | 52 | 990 | | return protocolConnection; |
| | 52 | 991 | | } |
| | | 992 | | |
| | 61 | 993 | | public ValueTask DisposeAsync() => _transportConnection?.DisposeAsync() ?? new(); |
| | | 994 | | |
| | | 995 | | public Task RefuseTransportConnectionAsync(bool serverBusy, CancellationToken cancellationToken) => |
| | 5 | 996 | | _transportConnection!.CloseAsync( |
| | 5 | 997 | | serverBusy ? MultiplexedConnectionCloseError.ServerBusy : MultiplexedConnectionCloseError.Refused, |
| | 5 | 998 | | cancellationToken); |
| | | 999 | | |
| | 61 | 1000 | | internal IceRpcConnector( |
| | 61 | 1001 | | IMultiplexedConnection transportConnection, |
| | 61 | 1002 | | ConnectionOptions options, |
| | 61 | 1003 | | ITaskExceptionObserver? taskExceptionObserver) |
| | 61 | 1004 | | { |
| | 61 | 1005 | | _transportConnection = transportConnection; |
| | 61 | 1006 | | _options = options; |
| | 61 | 1007 | | _taskExceptionObserver = taskExceptionObserver; |
| | 61 | 1008 | | } |
| | | 1009 | | } |
| | | 1010 | | } |