Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Mono.Android] Improve the GetHttpMessageHandler function #7214

Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 51 additions & 9 deletions src/Mono.Android/Android.Runtime/AndroidEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,18 +344,60 @@ static IWebProxy GetDefaultProxy ()
#if !MONOANDROID1_0
[DynamicDependency (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor, typeof (Xamarin.Android.Net.AndroidMessageHandler))]
#endif
static object? GetHttpMessageHandler ()
static object GetHttpMessageHandler ()
{
var envvar = Environment.GetEnvironmentVariable ("XA_HTTP_CLIENT_HANDLER_TYPE")?.Trim ();
var handlerTypeName = Environment.GetEnvironmentVariable ("XA_HTTP_CLIENT_HANDLER_TYPE")?.Trim ();
Type? handlerType = null;
if (!String.IsNullOrEmpty (envvar))
handlerType = Type.GetType (envvar, false);
else
return null;
if (handlerType == null)
return null;
if (!String.IsNullOrEmpty (handlerTypeName))
handlerType = Type.GetType (handlerTypeName, throwOnError: false);

// We don't do any type checking or casting here to avoid dependency on System.Net.Http in Mono.Android.dll
return Activator.CreateInstance (handlerType);
if (handlerType is null || !IsAcceptableHttpMessageHandlerType (handlerType)) {
handlerType = GetFallbackHttpMessageHandlerType ();
}

return Activator.CreateInstance (handlerType)
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
?? throw new InvalidOperationException ($"Could not create an instance of HTTP message handler type {handlerType.AssemblyQualifiedName}");
}

static bool IsAcceptableHttpMessageHandlerType (Type handlerType)
{
#if !MONOANDROID1_0
if (Extends (handlerType, "System.Net.Http.HttpClientHandler")) {
// It's not possible to construct HttpClientHandler in this method because it would cause infinite recursion
// as HttpClientHandler's constructor calls the GetHttpMessageHandler function
Logger.Log (LogLevel.Warn, "MonoAndroid", $"The type {handlerType.AssemblyQualifiedName} cannot be used as the native HTTP handler because it is derived from System.Net.Htt.HttpClientHandler. Use a type that extends System.Net.Http.HttpMessageHandler instead.");
return false;
}
#endif
if (!Extends (handlerType, "System.Net.Http.HttpMessageHandler")) {
Logger.Log (LogLevel.Warn, "MonoAndroid", $"The type {handlerType.AssemblyQualifiedName} set as the default HTTP handler is invalid. Use a type that extends System.Net.Http.HttpMessageHandler.");
return false;
}

return true;
}

static bool Extends (Type handlerType, string typeName, string assemblyName = "System.Net.Http")
{
while (handlerType != null) {
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
if (handlerType.FullName == typeName && handlerType.Assembly.GetName ().Name == assemblyName) {
return true;
}

handlerType = handlerType.BaseType;
}

return false;
}

static Type GetFallbackHttpMessageHandlerType (string typeName = "Xamarin.Android.Net.AndroidMessageHandler")
{
var handlerType = Type.GetType (typeName, throwOnError: false)
?? throw new InvalidOperationException ($"The {typeName} was not found. The type was probably linked away.");

Logger.Log (LogLevel.Info, "MonoAndroid", $"Using {typeName} as the native HTTP message handler.");
return handlerType;
}

internal static bool VSAndroidDesignerIsEnabled { get; } = InitializeVSAndroidDesignerIsEnabled ();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.Reflection;
using Android.Runtime;
using NUnit.Framework;

namespace Android.RuntimeTests {
[TestFixture]
public class AndroidEnvironmentTest {
const string EnvironmentVariable = "XA_HTTP_CLIENT_HANDLER_TYPE";

static object envLock = new object ();

private string? _originalValue = null;

[TestFixtureSetUp]
public void SetUp ()
{
_originalValue = Environment.GetEnvironmentVariable (EnvironmentVariable);
}

[TestFixtureTearDown]
public void TearDown ()
{
Environment.SetEnvironmentVariable (EnvironmentVariable, _originalValue);
}

[Test]
[TestCase (null)]
[TestCase ("Xamarin.Android.Net.AndroidHttpResponseMessage")] // does not extend HttpMessageHandler
#if NET
// instantiating AndroidClientHandler or HttpClientHandler (or any other type extending HttpClientHandler)
// would cause infinite recursion in the .NET build and so it is replaced with AndroidMessageHandler
[TestCase ("System.Net.Http.HttpClientHandler, System.Net.Http")]
[TestCase ("Xamarin.Android.Net.AndroidClientHandler")]
#endif
public void GetHttpMessageHandler_FallbackToAndroidMessageHandler (string? typeName)
{
var handler = GetHttpMessageHandler (typeName);

Assert.IsNotNull (handler, "GetHttpMessageHandler returned null");
Assert.IsNotNull ("Xamarin.Android.Net.AndroidMessageHandler", handler.GetType ().FullName);
}

[Test]
[TestCase ("System.Net.Http.HttpClientHandler")] // the type name doesn't contain the name of the assembly so the type won't be found
[TestCase ("Some.Nonexistent.Type")]
public void GetHttpMessageHandler_FallbackForInaccessibleTypes (string typeName)
{
var handler = GetHttpMessageHandler (typeName);

Assert.IsNotNull (handler, "GetHttpMessageHandler returned null");
Assert.IsNotNull ("Xamarin.Android.Net.AndroidMessageHandler", handler.GetType ().FullName);
}

[Test]
[TestCase ("Xamarin.Android.Net.AndroidMessageHandler")]
#if !NET
[TestCase ("Xamarin.Android.Net.AndroidClientHandler")]
[TestCase ("System.Net.Http.HttpClientHandler, System.Net.Http")]
#endif
public void GetHttpMessageHandler_OverridesDefaultValue (string typeName)
{
var handler = GetHttpMessageHandler (typeName);

Assert.IsNotNull (handler, "GetHttpMessageHandler returned null");

// type's FullName doesn't contain the assembly name
var indexOfComma = typeName.IndexOf(',');
var expectedTypeName = indexOfComma > 0 ? typeName.Substring(0, indexOfComma) : typeName;
Assert.AreEqual (expectedTypeName, handler.GetType ().FullName);
}

private static object? GetHttpMessageHandler (string? typeName)
{
var method = typeof (AndroidEnvironment).GetMethod ("GetHttpMessageHandler", BindingFlags.Static | BindingFlags.NonPublic);
lock (envLock) {
Environment.SetEnvironmentVariable (EnvironmentVariable, typeName);
return method.Invoke (null, null);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Android.Content.Res\AssetManagerTest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Android.Content\IntentTest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Android.Graphics\NinePatchTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Android.Runtime\AndroidEnvironmentTest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Android.Runtime\CharSequenceTest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Android.Runtime\InputStreamInvokerTest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Android.Runtime\JavaCollectionTest.cs" />
Expand Down