Microsoft.AspNetCore.Http.Connections.Client refactors (#1995)
This commit is contained in:
parent
83dec1093a
commit
198013bfa3
|
|
@ -42,8 +42,8 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
private static readonly Action<ILogger, Uri, Exception> _errorWithNegotiation =
|
private static readonly Action<ILogger, Uri, Exception> _errorWithNegotiation =
|
||||||
LoggerMessage.Define<Uri>(LogLevel.Error, new EventId(10, "ErrorWithNegotiation"), "Failed to start connection. Error getting negotiation response from '{Url}'.");
|
LoggerMessage.Define<Uri>(LogLevel.Error, new EventId(10, "ErrorWithNegotiation"), "Failed to start connection. Error getting negotiation response from '{Url}'.");
|
||||||
|
|
||||||
private static readonly Action<ILogger, string, Exception> _errorStartingTransport =
|
private static readonly Action<ILogger, HttpTransportType, Exception> _errorStartingTransport =
|
||||||
LoggerMessage.Define<string>(LogLevel.Error, new EventId(11, "ErrorStartingTransport"), "Failed to start connection. Error starting transport '{Transport}'.");
|
LoggerMessage.Define<HttpTransportType>(LogLevel.Error, new EventId(11, "ErrorStartingTransport"), "Failed to start connection. Error starting transport '{Transport}'.");
|
||||||
|
|
||||||
private static readonly Action<ILogger, string, Exception> _transportNotSupported =
|
private static readonly Action<ILogger, string, Exception> _transportNotSupported =
|
||||||
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(12, "TransportNotSupported"), "Skipping transport {TransportName} because it is not supported by this client.");
|
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(12, "TransportNotSupported"), "Skipping transport {TransportName} because it is not supported by this client.");
|
||||||
|
|
@ -63,8 +63,8 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
private static readonly Action<ILogger, Exception> _transportThrewExceptionOnStop =
|
private static readonly Action<ILogger, Exception> _transportThrewExceptionOnStop =
|
||||||
LoggerMessage.Define(LogLevel.Error, new EventId(17, "TransportThrewExceptionOnStop"), "The transport threw an exception while stopping.");
|
LoggerMessage.Define(LogLevel.Error, new EventId(17, "TransportThrewExceptionOnStop"), "The transport threw an exception while stopping.");
|
||||||
|
|
||||||
private static readonly Action<ILogger, string, Exception> _transportStarted =
|
private static readonly Action<ILogger, HttpTransportType, Exception> _transportStarted =
|
||||||
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(18, "TransportStarted"), "Transport '{Transport}' started.");
|
LoggerMessage.Define<HttpTransportType>(LogLevel.Debug, new EventId(18, "TransportStarted"), "Transport '{Transport}' started.");
|
||||||
|
|
||||||
public static void Starting(ILogger logger)
|
public static void Starting(ILogger logger)
|
||||||
{
|
{
|
||||||
|
|
@ -119,12 +119,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
_errorWithNegotiation(logger, url, exception);
|
_errorWithNegotiation(logger, url, exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void ErrorStartingTransport(ILogger logger, ITransport transport, Exception exception)
|
public static void ErrorStartingTransport(ILogger logger, HttpTransportType transportType, Exception exception)
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Error))
|
_errorStartingTransport(logger, transportType, exception);
|
||||||
{
|
|
||||||
_errorStartingTransport(logger, transport.GetType().Name, exception);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void TransportNotSupported(ILogger logger, string transport)
|
public static void TransportNotSupported(ILogger logger, string transport)
|
||||||
|
|
@ -166,12 +163,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
_transportThrewExceptionOnStop(logger, ex);
|
_transportThrewExceptionOnStop(logger, ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void TransportStarted(ILogger logger, ITransport transport)
|
public static void TransportStarted(ILogger logger, HttpTransportType transportType)
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
_transportStarted(logger, transportType, null);
|
||||||
{
|
|
||||||
_transportStarted(logger, transport.GetType().Name, null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -342,7 +342,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Log.ErrorStartingTransport(_logger, transport, ex);
|
Log.ErrorStartingTransport(_logger, transportType, ex);
|
||||||
|
|
||||||
_transport = null;
|
_transport = null;
|
||||||
throw;
|
throw;
|
||||||
|
|
@ -357,7 +357,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
// We successfully started, set the transport properties (we don't want to set these until the transport is definitely running).
|
// We successfully started, set the transport properties (we don't want to set these until the transport is definitely running).
|
||||||
_transport = transport;
|
_transport = transport;
|
||||||
|
|
||||||
Log.TransportStarted(_logger, _transport);
|
Log.TransportStarted(_logger, transportType);
|
||||||
}
|
}
|
||||||
|
|
||||||
private HttpClient CreateHttpClient()
|
private HttpClient CreateHttpClient()
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,6 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
|
||||||
/// This delegate is invoked after headers from <see cref="Headers"/> and the access token from <see cref="AccessTokenProvider"/>
|
/// This delegate is invoked after headers from <see cref="Headers"/> and the access token from <see cref="AccessTokenProvider"/>
|
||||||
/// has been applied.
|
/// has been applied.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public Action<ClientWebSocketOptions> WebSocketOptions { get; set; }
|
public Action<ClientWebSocketOptions> WebSocketConfiguration { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,16 +11,16 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
|
||||||
{
|
{
|
||||||
public class AccessTokenHttpMessageHandler : DelegatingHandler
|
public class AccessTokenHttpMessageHandler : DelegatingHandler
|
||||||
{
|
{
|
||||||
private readonly Func<Task<string>> _accessTokenFactory;
|
private readonly Func<Task<string>> _accessTokenProvider;
|
||||||
|
|
||||||
public AccessTokenHttpMessageHandler(HttpMessageHandler inner, Func<Task<string>> accessTokenFactory) : base(inner)
|
public AccessTokenHttpMessageHandler(HttpMessageHandler inner, Func<Task<string>> accessTokenProvider) : base(inner)
|
||||||
{
|
{
|
||||||
_accessTokenFactory = accessTokenFactory ?? throw new ArgumentNullException(nameof(accessTokenFactory));
|
_accessTokenProvider = accessTokenProvider ?? throw new ArgumentNullException(nameof(accessTokenProvider));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var accessToken = await _accessTokenFactory();
|
var accessToken = await _accessTokenProvider();
|
||||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||||
|
|
||||||
return await base.SendAsync(request, cancellationToken);
|
return await base.SendAsync(request, cancellationToken);
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
|
||||||
public partial class WebSocketsTransport : ITransport
|
public partial class WebSocketsTransport : ITransport
|
||||||
{
|
{
|
||||||
private readonly ClientWebSocket _webSocket;
|
private readonly ClientWebSocket _webSocket;
|
||||||
private readonly Func<Task<string>> _accessTokenFactory;
|
private readonly Func<Task<string>> _accessTokenProvider;
|
||||||
private IDuplexPipe _application;
|
private IDuplexPipe _application;
|
||||||
private WebSocketMessageType _webSocketMessageType;
|
private WebSocketMessageType _webSocketMessageType;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
@ -81,10 +81,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
|
||||||
|
|
||||||
if (httpConnectionOptions.AccessTokenProvider != null)
|
if (httpConnectionOptions.AccessTokenProvider != null)
|
||||||
{
|
{
|
||||||
_accessTokenFactory = httpConnectionOptions.AccessTokenProvider;
|
_accessTokenProvider = httpConnectionOptions.AccessTokenProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
httpConnectionOptions.WebSocketOptions?.Invoke(_webSocket.Options);
|
httpConnectionOptions.WebSocketConfiguration?.Invoke(_webSocket.Options);
|
||||||
|
|
||||||
_closeTimeout = httpConnectionOptions.CloseTimeout;
|
_closeTimeout = httpConnectionOptions.CloseTimeout;
|
||||||
}
|
}
|
||||||
|
|
@ -116,9 +116,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
|
||||||
|
|
||||||
Log.StartTransport(_logger, transferFormat, resolvedUrl);
|
Log.StartTransport(_logger, transferFormat, resolvedUrl);
|
||||||
|
|
||||||
if (_accessTokenFactory != null)
|
if (_accessTokenProvider != null)
|
||||||
{
|
{
|
||||||
var accessToken = await _accessTokenFactory();
|
var accessToken = await _accessTokenProvider();
|
||||||
_webSocket.Options.SetRequestHeader("Authorization", $"Bearer {accessToken}");
|
_webSocket.Options.SetRequestHeader("Authorization", $"Bearer {accessToken}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -706,7 +706,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests
|
||||||
{
|
{
|
||||||
using (StartLog(out var loggerFactory, $"{nameof(ClientCanUseJwtBearerTokenForAuthentication)}_{transportType}"))
|
using (StartLog(out var loggerFactory, $"{nameof(ClientCanUseJwtBearerTokenForAuthentication)}_{transportType}"))
|
||||||
{
|
{
|
||||||
async Task<string> AccessTokenFactory()
|
async Task<string> AccessTokenProvider()
|
||||||
{
|
{
|
||||||
var httpResponse = await new HttpClient().GetAsync(_serverFixture.Url + "/generateJwtToken");
|
var httpResponse = await new HttpClient().GetAsync(_serverFixture.Url + "/generateJwtToken");
|
||||||
httpResponse.EnsureSuccessStatusCode();
|
httpResponse.EnsureSuccessStatusCode();
|
||||||
|
|
@ -717,7 +717,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests
|
||||||
.WithLoggerFactory(loggerFactory)
|
.WithLoggerFactory(loggerFactory)
|
||||||
.WithUrl(_serverFixture.Url + "/authorizedhub", transportType, options =>
|
.WithUrl(_serverFixture.Url + "/authorizedhub", transportType, options =>
|
||||||
{
|
{
|
||||||
options.AccessTokenProvider = AccessTokenFactory;
|
options.AccessTokenProvider = AccessTokenProvider;
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
try
|
try
|
||||||
|
|
@ -784,7 +784,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests
|
||||||
.WithLoggerFactory(loggerFactory)
|
.WithLoggerFactory(loggerFactory)
|
||||||
.WithUrl(_serverFixture.Url + "/default", HttpTransportType.WebSockets, options =>
|
.WithUrl(_serverFixture.Url + "/default", HttpTransportType.WebSockets, options =>
|
||||||
{
|
{
|
||||||
options.WebSocketOptions = o => o.Cookies = cookieJar;
|
options.WebSocketConfiguration = o => o.Cookies = cookieJar;
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
try
|
try
|
||||||
|
|
|
||||||
|
|
@ -22,13 +22,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
|
||||||
ITransport transport = null,
|
ITransport transport = null,
|
||||||
ITransportFactory transportFactory = null,
|
ITransportFactory transportFactory = null,
|
||||||
HttpTransportType? transportType = null,
|
HttpTransportType? transportType = null,
|
||||||
Func<Task<string>> accessTokenFactory = null)
|
Func<Task<string>> accessTokenProvider = null)
|
||||||
{
|
{
|
||||||
var httpOptions = new HttpConnectionOptions
|
var httpOptions = new HttpConnectionOptions
|
||||||
{
|
{
|
||||||
Transports = transportType ?? HttpTransportType.LongPolling,
|
Transports = transportType ?? HttpTransportType.LongPolling,
|
||||||
HttpMessageHandlerFactory = (httpMessageHandler) => httpHandler ?? TestHttpMessageHandler.CreateDefault(),
|
HttpMessageHandlerFactory = (httpMessageHandler) => httpHandler ?? TestHttpMessageHandler.CreateDefault(),
|
||||||
AccessTokenProvider = accessTokenFactory,
|
AccessTokenProvider = accessTokenProvider,
|
||||||
};
|
};
|
||||||
if (url != null)
|
if (url != null)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ using System.Net;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Connections;
|
using Microsoft.AspNetCore.Connections;
|
||||||
using Microsoft.AspNetCore.Http.Connections;
|
using Microsoft.AspNetCore.Http.Connections;
|
||||||
|
using Microsoft.AspNetCore.Http.Connections.Client;
|
||||||
using Microsoft.AspNetCore.Http.Connections.Client.Internal;
|
using Microsoft.AspNetCore.Http.Connections.Client.Internal;
|
||||||
using Moq;
|
using Moq;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
|
|
||||||
|
|
@ -51,14 +51,14 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
|
||||||
return await next();
|
return await next();
|
||||||
});
|
});
|
||||||
|
|
||||||
Task<string> AccessTokenFactory()
|
Task<string> AccessTokenProvider()
|
||||||
{
|
{
|
||||||
callCount++;
|
callCount++;
|
||||||
return Task.FromResult(callCount.ToString());
|
return Task.FromResult(callCount.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
await WithConnectionAsync(
|
await WithConnectionAsync(
|
||||||
CreateConnection(testHttpHandler, transportType: transportType, accessTokenFactory: AccessTokenFactory),
|
CreateConnection(testHttpHandler, transportType: transportType, accessTokenProvider: AccessTokenProvider),
|
||||||
async (connection) =>
|
async (connection) =>
|
||||||
{
|
{
|
||||||
await connection.StartAsync(TransferFormat.Text).OrTimeout();
|
await connection.StartAsync(TransferFormat.Text).OrTimeout();
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests
|
||||||
httpOptions.UseDefaultCredentials = false;
|
httpOptions.UseDefaultCredentials = false;
|
||||||
httpOptions.Credentials = Mock.Of<ICredentials>();
|
httpOptions.Credentials = Mock.Of<ICredentials>();
|
||||||
httpOptions.Proxy = Mock.Of<IWebProxy>();
|
httpOptions.Proxy = Mock.Of<IWebProxy>();
|
||||||
httpOptions.WebSocketOptions = options => webSocketsOptions = options;
|
httpOptions.WebSocketConfiguration = options => webSocketsOptions = options;
|
||||||
|
|
||||||
var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: httpOptions, loggerFactory: null);
|
var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: httpOptions, loggerFactory: null);
|
||||||
Assert.NotNull(webSocketsTransport);
|
Assert.NotNull(webSocketsTransport);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue