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

Better error messages #86

Merged
merged 4 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
47 changes: 24 additions & 23 deletions native/yaha_native/src/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,29 +484,7 @@ pub extern "C" fn yaha_request_begin(
}
res = ctx.client.as_ref().unwrap().request(req) => {
if let Err(err) = res {
LAST_ERROR.with(|v| {
*v.borrow_mut() = Some(err.to_string());
});

// If the inner error is `hyper::Error`, use its error message instead.
let error_inner = err.source()
.and_then(|e| e.downcast_ref::<hyper::Error>());

if let Some(err) = error_inner {
LAST_ERROR.with(|v| {
*v.borrow_mut() = Some(err.to_string());
});
}

// If the `hyper::Error` has `h2::Error` as inner error, the error has HTTP/2 error code.
let reason = error_inner
.and_then(|e| e.source())
.and_then(|e| e.downcast_ref::<h2::Error>())
.and_then(|e| e.reason());

let rc = reason.map(|r| u32::from(r));

(ctx.on_complete)(seq, state, CompletionReason::Error, rc.unwrap_or_default());
complete_with_error(ctx, seq, state, err);
return;
} else {
res
Expand Down Expand Up @@ -627,6 +605,29 @@ pub extern "C" fn yaha_request_begin(
true
}

fn complete_with_error(ctx: &mut YahaNativeContextInternal, seq: i32, state: NonZeroIsize, err: hyper_util::client::legacy::Error) {
let mut h2_error_code = None;

// If the error has the inner error, use its error message instead.
if let Some(error_inner) = err.source() {
LAST_ERROR.with(|v| {
*v.borrow_mut() = Some(format!("{}: {}", err.to_string(), error_inner.to_string()));
});

// If the Error has `h2::Error` as inner error, the error has HTTP/2 error code.
h2_error_code = error_inner.source()
.and_then(|e| e.downcast_ref::<h2::Error>())
.and_then(|e| e.reason())
.map(|e| u32::from(e));
} else {
LAST_ERROR.with(|v| {
*v.borrow_mut() = Some(err.to_string());
});
}

(ctx.on_complete)(seq, state, CompletionReason::Error, h2_error_code.unwrap_or_default());
}

#[no_mangle]
pub extern "C" fn yaha_request_abort(ctx: *const YahaNativeContext, req_ctx: *const YahaNativeRequestContext) {
let req_ctx = crate::context::to_internal(req_ctx).lock().unwrap();
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
28 changes: 26 additions & 2 deletions src/YetAnotherHttpHandler/ResponseContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ public void CompleteAsFailed(string errorMessage, uint h2ErrorCode)
if (h2ErrorCode != 0)
{
#if NET7_0_OR_GREATER
ex = new HttpProtocolException(h2ErrorCode, $"The HTTP/2 server reset the stream. HTTP/2 error code (0x{h2ErrorCode:x}).", ex);
ex = new HttpProtocolException(h2ErrorCode, $"The HTTP/2 server closed the connection or reset the stream. HTTP/2 error code '{Http2ErrorCode.ToName(h2ErrorCode)}' (0x{h2ErrorCode:x}).", ex);
#else
ex = new Http2StreamException($"The HTTP/2 server reset the stream. HTTP/2 error code (0x{h2ErrorCode:x}).", ex);
ex = new Http2StreamException($"The HTTP/2 server closed the connection or reset the stream. HTTP/2 error code '{Http2ErrorCode.ToName(h2ErrorCode)}' (0x{h2ErrorCode:x}).", ex);
#endif
}

Expand Down Expand Up @@ -175,5 +175,29 @@ public async Task<HttpResponseMessage> GetResponseAsync()
throw new HttpRequestException(e.Message, e);
}
}

internal static class Http2ErrorCode
{
// https://github.com/dotnet/aspnetcore/blob/release/8.0/src/Shared/ServerInfrastructure/Http2/Http2ErrorCode.cs
// https://github.com/dotnet/runtime/blob/release/8.0/src/libraries/System.Net.Http/src/System/Net/Http/HttpProtocolException.cs#L63
public static string ToName(uint code) => code switch
{
0x0 => "NO_ERROR",
0x1 => "PROTOCOL_ERROR",
0x2 => "INTERNAL_ERROR",
0x3 => "FLOW_CONTROL_ERROR",
0x4 => "SETTINGS_TIMEOUT",
0x5 => "STREAM_CLOSED",
0x6 => "FRAME_SIZE_ERROR",
0x7 => "REFUSED_STREAM",
0x8 => "CANCEL",
0x9 => "COMPRESSION_ERROR",
0xa => "CONNECT_ERROR",
0xb => "ENHANCE_YOUR_CALM",
0xc => "INADEQUATE_SECURITY",
0xd => "HTTP_1_1_REQUIRED",
_ => "(unknown error)",
};
}
}
}
18 changes: 18 additions & 0 deletions test/YetAnotherHttpHandler.Test/Http1Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,24 @@ public async Task FailedToConnect()

// Assert
Assert.IsType<HttpRequestException>(ex);
Assert.Contains("(Connect): dns error", ex.Message);
}

[Fact]
public async Task FailedToConnect_VersionMismatch()
{
// Arrange
using var httpHandler = new Cysharp.Net.Http.YetAnotherHttpHandler() { Http2Only = true };
var httpClient = new HttpClient(httpHandler);
await using var server = await LaunchServerAsync<TestServerForHttp1AndHttp2>(TestWebAppServerListenMode.InsecureHttp1Only);

// Act
var ex = await Record.ExceptionAsync(async () => (await httpClient.GetAsync($"{server.BaseUri}/")).EnsureSuccessStatusCode());

// Assert
Assert.IsType<HttpRequestException>(ex);
Assert.Null(((HttpRequestException)ex).StatusCode);
Assert.Contains("'HTTP_1_1_REQUIRED' (0xd)", ex.Message);
}

[Fact]
Expand Down
16 changes: 16 additions & 0 deletions test/YetAnotherHttpHandler.Test/Http2ClearTextTest.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using Cysharp.Net.Http;
using Microsoft.AspNetCore.Builder;
using Xunit.Abstractions;
Expand All @@ -20,4 +21,19 @@ protected override Task<TestWebAppServer> LaunchServerAsyncCore<T>(Action<WebApp
return LaunchServerAsync<T>(TestWebAppServerListenMode.InsecureHttp2Only, configure);
}

[Fact]
public async Task FailedToConnect_VersionMismatch()
{
// Arrange
using var httpHandler = new Cysharp.Net.Http.YetAnotherHttpHandler() { Http2Only = false };
var httpClient = new HttpClient(httpHandler);
await using var server = await LaunchServerAsync<TestServerForHttp1AndHttp2>();

// Act
var ex = await Record.ExceptionAsync(async () => (await httpClient.GetAsync($"{server.BaseUri}/")).EnsureSuccessStatusCode());

// Assert
Assert.IsType<HttpRequestException>(ex);
Assert.Equal(HttpStatusCode.BadRequest, ((HttpRequestException)ex).StatusCode);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public static T IsAssignableFrom<T>(object actual)
return (T)actual;
}

public static void Contains(string expected, string actual)
=> NUnit.Framework.Assert.That(() => actual.Contains(expected));

public static T IsType<T>(object actual)
{
NUnit.Framework.Assert.True(actual.GetType() == typeof(T), $"Expected: {typeof(T)}\nActual: {actual.GetType()}");
Expand Down
17 changes: 17 additions & 0 deletions test/YetAnotherHttpHandler.Unity.Test/Assets/Tests/Http1Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,23 @@ public async Task FailedToConnect()

// Assert
Assert.IsType<HttpRequestException>(ex);
Assert.Contains("(Connect): dns error", ex.Message);
}

[Fact]
public async Task FailedToConnect_VersionMismatch()
{
// Arrange
using var httpHandler = new Cysharp.Net.Http.YetAnotherHttpHandler() { Http2Only = true };
var httpClient = new HttpClient(httpHandler);
await using var server = await LaunchServerAsync<TestServerForHttp1AndHttp2>(TestWebAppServerListenMode.InsecureHttp1Only);

// Act
var ex = await Record.ExceptionAsync(async () => (await httpClient.GetAsync($"{server.BaseUri}/")).EnsureSuccessStatusCode());

// Assert
Assert.IsType<HttpRequestException>(ex);
Assert.Contains("'HTTP_1_1_REQUIRED' (0xd)", ex.Message);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Threading.Tasks;
using System.Net.Http.Headers;

using Fact = NUnit.Framework.TestAttribute;
using ConditionalFact = NUnit.Framework.TestAttribute;
using Grpc.Core;
using System.IO;
Expand All @@ -17,6 +18,21 @@

public class Http2ClearTextTest : YahaUnityTestBase
{
[Fact]
public async Task FailedToConnect_VersionMismatch()
{
// Arrange
using var httpHandler = new Cysharp.Net.Http.YetAnotherHttpHandler() { Http2Only = false };
var httpClient = new HttpClient(httpHandler);
await using var server = await LaunchServerAsync<TestServerForHttp1AndHttp2>();

// Act
var ex = await Record.ExceptionAsync(async () => (await httpClient.GetAsync($"{server.BaseUri}/")).EnsureSuccessStatusCode());

// Assert
Assert.IsType<HttpRequestException>(ex);
}

[ConditionalFact]
public async Task Get_Ok()
{
Expand Down