private ValueTask <HttpConnection> GetOrCreateConnection(HttpRequestMessage request, Uri proxyUri)
        {
            var key = new HttpConnectionKey(proxyUri);
            HttpConnectionPool pool = _connectionPools.GetOrAddPool(key);

            return(pool.GetConnectionAsync(async state =>
            {
                Stream stream = await ConnectHelper.ConnectAsync(state.proxyUri.IdnHost, state.proxyUri.Port).ConfigureAwait(false);
                return new HttpConnection(state.pool, state.key, null, stream, null, true);
            }, (pool: pool, key: key, request: request, proxyUri: proxyUri)));
        }
        public override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var key = new HttpConnectionKey(request.RequestUri);

            HttpConnectionPool         pool           = _connectionPools.GetOrAddPool(key);
            ValueTask <HttpConnection> connectionTask = pool.GetConnectionAsync(
                state => state.handler.CreateConnection(state.request, state.key, state.pool, cancellationToken),
                (handler: this, request: request, key: key, pool: pool));

            return(connectionTask.IsCompletedSuccessfully ?
                   connectionTask.Result.SendAsync(request, cancellationToken) :
                   SendAsyncWithAwaitedConnection(connectionTask, request, cancellationToken));
        }
        private async ValueTask <HttpConnection> CreateConnection(HttpRequestMessage request, HttpConnectionKey key, HttpConnectionPool pool, CancellationToken cancellationToken)
        {
            logger.Trace("HTTP connection handler: Create connection");

            Uri uri = request.RequestUri;

            Stream stream = await ConnectHelper.ConnectAsync(uri.IdnHost, uri.Port).ConfigureAwait(false);

            TransportContext transportContext = null;

            if (uri.Scheme == UriScheme.Https)
            {
                stream = await this.EstablishSslConnection(uri.IdnHost, request, stream, cancellationToken).ConfigureAwait(false);
            }

            return(new HttpConnection(pool, key, uri.IdnHost, stream, transportContext, false));
        }