mirror of https://github.com/abpframework/abp.git
17 changed files with 1271 additions and 19 deletions
@ -0,0 +1,219 @@ |
|||
using System; |
|||
using System.IO; |
|||
using System.Threading.Tasks; |
|||
using Shouldly; |
|||
using Volo.Abp.Cli.Commands; |
|||
using Volo.Abp.Cli.Http; |
|||
using Volo.Abp.Cli.ServiceProxying.CSharp; |
|||
using Volo.Abp.Http.Modeling; |
|||
using Volo.Abp.Json; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Cli.ServiceProxying; |
|||
|
|||
public class CSharpServiceProxyGenerator_AsyncEnumerable_Tests : AbpCliTestBase |
|||
{ |
|||
[Theory] |
|||
[InlineData(false)] |
|||
[InlineData(true)] |
|||
public async Task Should_Return_IAsyncEnumerable_From_The_Generated_Proxy_And_Interface(bool withoutContracts) |
|||
{ |
|||
var workDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); |
|||
Directory.CreateDirectory(workDirectory); |
|||
await File.WriteAllTextAsync(Path.Combine(workDirectory, "MyProject.HttpApi.Client.csproj"), "<Project Sdk=\"Microsoft.NET.Sdk\" />"); |
|||
try |
|||
{ |
|||
var generator = new TestCSharpServiceProxyGenerator(GetRequiredService<CliHttpClientFactory>(), GetRequiredService<IJsonSerializer>()); |
|||
|
|||
await generator.GenerateProxyAsync(new GenerateProxyArgs( |
|||
GenerateProxyCommand.Name, workDirectory, "app", "https://localhost/", null, null, null, null, null, null, null, withoutContracts)); |
|||
|
|||
var folder = Path.Combine(workDirectory, "ClientProxies", "MyProject", "Streaming"); |
|||
var proxy = await File.ReadAllTextAsync(Path.Combine(folder, "StreamingClientProxy.Generated.cs")); |
|||
proxy.ShouldContain("public virtual IAsyncEnumerable<Int32> GetItemsAsync()"); |
|||
proxy.ShouldContain("return RequestAsyncEnumerable<Int32>(nameof(GetItemsAsync));"); |
|||
proxy.ShouldContain("public virtual IAsyncEnumerable<String> GetNamedItemsAsync(string name)"); |
|||
proxy.ShouldContain("public virtual async Task<String> GetNameAsync()"); |
|||
proxy.ShouldContain("public virtual async Task DeleteAsync()"); |
|||
proxy.ShouldContain("public virtual IAsyncEnumerable<String> GetBooks()"); |
|||
proxy.ShouldContain("return RequestAsyncEnumerable<String>(nameof(GetBooks));"); |
|||
proxy.ShouldContain("public virtual IAsyncEnumerable<Int32> Read(CancellationToken cancellationToken, int count)"); |
|||
proxy.ShouldContain("GetCount()"); |
|||
proxy.Split("NotImplementedException").Length.ShouldBe(2); |
|||
|
|||
var interfacePath = Path.Combine(folder, "IStreamingAppService.cs"); |
|||
if (withoutContracts) |
|||
{ |
|||
File.Exists(interfacePath).ShouldBeFalse(); |
|||
return; |
|||
} |
|||
|
|||
var @interface = await File.ReadAllTextAsync(interfacePath); |
|||
@interface.ShouldContain("IAsyncEnumerable<Int32> GetItemsAsync();"); |
|||
@interface.ShouldContain("IAsyncEnumerable<String> GetNamedItemsAsync(string name);"); |
|||
@interface.ShouldNotContain("Task<IAsyncEnumerable"); |
|||
@interface.ShouldContain("Task<String> GetNameAsync();"); |
|||
@interface.ShouldContain("Task DeleteAsync();"); |
|||
@interface.ShouldContain("IAsyncEnumerable<String> GetBooks();"); |
|||
@interface.ShouldContain("IAsyncEnumerable<Int32> Read(CancellationToken cancellationToken, int count);"); |
|||
@interface.ShouldContain(" GetCount();"); |
|||
@interface.ShouldNotContain("Task<Int32> GetCount"); |
|||
} |
|||
finally |
|||
{ |
|||
Directory.Delete(workDirectory, true); |
|||
} |
|||
} |
|||
|
|||
private class TestCSharpServiceProxyGenerator : CSharpServiceProxyGenerator |
|||
{ |
|||
public TestCSharpServiceProxyGenerator(CliHttpClientFactory cliHttpClientFactory, IJsonSerializer jsonSerializer) |
|||
: base(cliHttpClientFactory, jsonSerializer) |
|||
{ |
|||
} |
|||
|
|||
protected override Task<ApplicationApiDescriptionModel> GetApplicationApiDescriptionModelAsync(GenerateProxyArgs args, ApplicationApiDescriptionModelRequestDto requestDto = null) |
|||
{ |
|||
return Task.FromResult(JsonSerializer.Deserialize<ApplicationApiDescriptionModel>(ApiDefinition)); |
|||
} |
|||
} |
|||
|
|||
private const string ApiDefinition = """
|
|||
{ |
|||
"modules": { |
|||
"app": { |
|||
"rootPath": "app", |
|||
"remoteServiceName": "Default", |
|||
"controllers": { |
|||
"MyProject.Streaming.StreamingAppService": { |
|||
"controllerName": "Streaming", |
|||
"type": "MyProject.Streaming.StreamingAppService", |
|||
"interfaces": [ |
|||
{ |
|||
"type": "MyProject.Streaming.IStreamingAppService", |
|||
"name": "IStreamingAppService", |
|||
"methods": [ |
|||
{ |
|||
"name": "GetItemsAsync", |
|||
"parametersOnMethod": [], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" } |
|||
}, |
|||
{ |
|||
"name": "GetNamedItemsAsync", |
|||
"parametersOnMethod": [ { "name": "name", "type": "System.String", "typeSimple": "string" } ], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" } |
|||
}, |
|||
{ |
|||
"name": "GetNameAsync", |
|||
"parametersOnMethod": [], |
|||
"returnValue": { "type": "System.String", "typeSimple": "string" } |
|||
}, |
|||
{ |
|||
"name": "DeleteAsync", |
|||
"parametersOnMethod": [], |
|||
"returnValue": { "type": "System.Void", "typeSimple": "System.Void" } |
|||
}, |
|||
{ |
|||
"name": "GetBooks", |
|||
"parametersOnMethod": [], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" } |
|||
}, |
|||
{ |
|||
"name": "Read", |
|||
"parametersOnMethod": [ |
|||
{ "name": "cancellationToken", "type": "System.Threading.CancellationToken", "typeSimple": "System.Threading.CancellationToken" }, |
|||
{ "name": "count", "type": "System.Int32", "typeSimple": "number" } |
|||
], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" } |
|||
}, |
|||
{ |
|||
"name": "GetCount", |
|||
"parametersOnMethod": [], |
|||
"returnValue": { "type": "System.Int32", "typeSimple": "number" } |
|||
} |
|||
] |
|||
} |
|||
], |
|||
"actions": { |
|||
"GetItemsAsync": { |
|||
"uniqueName": "GetItemsAsync", |
|||
"name": "GetItemsAsync", |
|||
"httpMethod": "GET", |
|||
"url": "api/app/streaming/items", |
|||
"parametersOnMethod": [], |
|||
"parameters": [], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
}, |
|||
"GetNamedItemsAsyncByName": { |
|||
"uniqueName": "GetNamedItemsAsyncByName", |
|||
"name": "GetNamedItemsAsync", |
|||
"httpMethod": "GET", |
|||
"url": "api/app/streaming/named-items", |
|||
"parametersOnMethod": [ { "name": "name", "type": "System.String", "typeSimple": "string" } ], |
|||
"parameters": [ { "nameOnMethod": "name", "name": "name", "type": "System.String", "typeSimple": "string" } ], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
}, |
|||
"GetNameAsync": { |
|||
"uniqueName": "GetNameAsync", |
|||
"name": "GetNameAsync", |
|||
"httpMethod": "GET", |
|||
"url": "api/app/streaming/name", |
|||
"parametersOnMethod": [], |
|||
"parameters": [], |
|||
"returnValue": { "type": "System.String", "typeSimple": "string" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
}, |
|||
"DeleteAsync": { |
|||
"uniqueName": "DeleteAsync", |
|||
"name": "DeleteAsync", |
|||
"httpMethod": "DELETE", |
|||
"url": "api/app/streaming", |
|||
"parametersOnMethod": [], |
|||
"parameters": [], |
|||
"returnValue": { "type": "System.Void", "typeSimple": "System.Void" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
}, |
|||
"GetBooks": { |
|||
"uniqueName": "GetBooks", |
|||
"name": "GetBooks", |
|||
"httpMethod": "GET", |
|||
"url": "api/app/streaming/books", |
|||
"parametersOnMethod": [], |
|||
"parameters": [], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
}, |
|||
"GetCount": { |
|||
"uniqueName": "GetCount", |
|||
"name": "GetCount", |
|||
"httpMethod": "GET", |
|||
"url": "api/app/streaming/count", |
|||
"parametersOnMethod": [], |
|||
"parameters": [], |
|||
"returnValue": { "type": "System.Int32", "typeSimple": "number" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
}, |
|||
"ReadByCancellationTokenAndCount": { |
|||
"uniqueName": "ReadByCancellationTokenAndCount", |
|||
"name": "Read", |
|||
"httpMethod": "GET", |
|||
"url": "api/app/streaming/read", |
|||
"parametersOnMethod": [ |
|||
{ "name": "cancellationToken", "type": "System.Threading.CancellationToken", "typeSimple": "System.Threading.CancellationToken" }, |
|||
{ "name": "count", "type": "System.Int32", "typeSimple": "number" } |
|||
], |
|||
"parameters": [ { "nameOnMethod": "count", "name": "count", "type": "System.Int32", "typeSimple": "number" } ], |
|||
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" }, |
|||
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
|||
} |
|||
} |
|||
} |
|||
} |
|||
} |
|||
}, |
|||
"types": {} |
|||
} |
|||
""";
|
|||
} |
|||
@ -0,0 +1,57 @@ |
|||
using System.Collections.Concurrent; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Net.Http; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Http.Client.ClientProxying; |
|||
|
|||
public class RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests : AbpHttpClientTestBase |
|||
{ |
|||
[Fact] |
|||
public async Task Should_Stream_Items() |
|||
{ |
|||
var proxy = ServiceProvider.GetRequiredService<RegularTestControllerStaticClientProxy>(); |
|||
|
|||
(await ToListAsync(proxy.GetStreamAsync(3))).ShouldBe(new[] { 1, 2, 3 }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Build_A_Request_Context_For_Each_Enumeration() |
|||
{ |
|||
var proxy = ServiceProvider.GetRequiredService<RecordingStaticClientProxy>(); |
|||
var sequence = proxy.GetStreamAsync(3); |
|||
|
|||
var results = await Task.WhenAll(ToListAsync(sequence), ToListAsync(sequence)); |
|||
|
|||
results[0].ShouldBe(new[] { 1, 2, 3 }); |
|||
results[1].ShouldBe(new[] { 1, 2, 3 }); |
|||
proxy.RequestContexts.Distinct().Count().ShouldBe(2); |
|||
proxy.RequestContexts.ShouldAllBe(context => context.CancellationToken == null); |
|||
} |
|||
|
|||
private static async Task<List<int>> ToListAsync(IAsyncEnumerable<int> source) |
|||
{ |
|||
var list = new List<int>(); |
|||
await foreach (var item in source) |
|||
{ |
|||
list.Add(item); |
|||
} |
|||
|
|||
return list; |
|||
} |
|||
|
|||
public class RecordingStaticClientProxy : RegularTestControllerStaticClientProxy |
|||
{ |
|||
public ConcurrentQueue<ClientProxyRequestContext> RequestContexts { get; } = new(); |
|||
|
|||
protected override Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
|||
{ |
|||
RequestContexts.Enqueue(requestContext); |
|||
return base.RequestAsync(requestContext); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,276 @@ |
|||
using System; |
|||
using System.Collections.Concurrent; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Net.Http; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Shouldly; |
|||
using Volo.Abp.AspNetCore.TestBase; |
|||
using Volo.Abp.Http.Client.ClientProxying; |
|||
using Volo.Abp.Http.Client.DynamicProxying; |
|||
using Volo.Abp.Http.Client.Proxying; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Http.DynamicProxying; |
|||
|
|||
public abstract class AsyncEnumerableClientProxyCancellation_Tests : AbpHttpClientTestBase |
|||
{ |
|||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); |
|||
|
|||
protected IRegularTestController Controller => ServiceProvider.GetRequiredService<IRegularTestController>(); |
|||
|
|||
protected abstract bool BlockApiDefinitionRequest { get; } |
|||
|
|||
/// <summary>
|
|||
/// Released when a request reaches the blocking handler, so a test can cancel exactly at that stage.
|
|||
/// </summary>
|
|||
protected SemaphoreSlim BlockedRequests { get; } = new(0); |
|||
|
|||
protected override void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.Replace(ServiceDescriptor.Singleton<IProxyHttpClientFactory>(serviceProvider => |
|||
new BlockingProxyHttpClientFactory(serviceProvider.GetRequiredService<ITestServerAccessor>(), BlockApiDefinitionRequest, BlockedRequests))); |
|||
} |
|||
|
|||
protected async Task WaitForBlockedRequestsAsync(int count) |
|||
{ |
|||
for (var i = 0; i < count; i++) |
|||
{ |
|||
(await BlockedRequests.WaitAsync(Timeout)).ShouldBeTrue("The request did not reach the blocking handler."); |
|||
} |
|||
} |
|||
|
|||
protected async Task ShouldBeCancelledWhenBlockedAsync(Func<Task> enumerate, CancellationTokenSource cancellationTokenSource) |
|||
{ |
|||
var enumeration = enumerate(); |
|||
await WaitForBlockedRequestsAsync(1); |
|||
cancellationTokenSource.Cancel(); |
|||
await ShouldBeCancelledAsync(() => enumeration); |
|||
} |
|||
|
|||
protected static async Task ShouldBeCancelledAsync(Func<Task> enumerate) |
|||
{ |
|||
var exception = await Should.ThrowAsync<Exception>(() => enumerate().WaitAsync(Timeout)); |
|||
|
|||
exception.ShouldNotBeOfType<TimeoutException>(); |
|||
(exception is OperationCanceledException || exception.InnerException is OperationCanceledException).ShouldBeTrue(exception.ToString()); |
|||
} |
|||
|
|||
private class BlockingProxyHttpClientFactory : IProxyHttpClientFactory |
|||
{ |
|||
private readonly ITestServerAccessor _testServerAccessor; |
|||
private readonly bool _blockApiDefinitionRequest; |
|||
private readonly SemaphoreSlim _blockedRequests; |
|||
private int _count; |
|||
|
|||
public BlockingProxyHttpClientFactory(ITestServerAccessor testServerAccessor, bool blockApiDefinitionRequest, SemaphoreSlim blockedRequests) |
|||
{ |
|||
_testServerAccessor = testServerAccessor; |
|||
_blockApiDefinitionRequest = blockApiDefinitionRequest; |
|||
_blockedRequests = blockedRequests; |
|||
} |
|||
|
|||
public HttpClient Create(string name) => Create(); |
|||
|
|||
public HttpClient Create() |
|||
{ |
|||
if (Interlocked.Increment(ref _count) == 1 && !_blockApiDefinitionRequest) |
|||
{ |
|||
return _testServerAccessor.Server.CreateClient(); |
|||
} |
|||
|
|||
return new HttpClient(new BlockingHttpMessageHandler(_blockedRequests)) |
|||
{ |
|||
BaseAddress = new Uri("http://localhost/") |
|||
}; |
|||
} |
|||
} |
|||
|
|||
private class BlockingHttpMessageHandler : HttpMessageHandler |
|||
{ |
|||
private readonly SemaphoreSlim _blockedRequests; |
|||
|
|||
public BlockingHttpMessageHandler(SemaphoreSlim blockedRequests) |
|||
{ |
|||
_blockedRequests = blockedRequests; |
|||
} |
|||
|
|||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
|||
{ |
|||
_blockedRequests.Release(); |
|||
await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken); |
|||
throw new InvalidOperationException("Unreachable"); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public class AsyncEnumerableClientProxy_Request_Cancellation_Tests : AsyncEnumerableClientProxyCancellation_Tests |
|||
{ |
|||
protected override bool BlockApiDefinitionRequest => false; |
|||
|
|||
[Fact] |
|||
public async Task Should_Cancel_Request_Before_Response_Headers_When_Method_Has_Its_Own_Token() |
|||
{ |
|||
using var methodCancellationTokenSource = new CancellationTokenSource(); |
|||
using var enumerationCancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token) |
|||
.WithCancellation(enumerationCancellationTokenSource.Token)) |
|||
{ |
|||
} |
|||
}, enumerationCancellationTokenSource); |
|||
} |
|||
} |
|||
|
|||
public class AsyncEnumerableClientProxy_RequestContext_Cancellation_Tests : AsyncEnumerableClientProxyCancellation_Tests |
|||
{ |
|||
protected override bool BlockApiDefinitionRequest => false; |
|||
|
|||
protected override void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
base.ConfigureServices(services); |
|||
services.AddSingleton<RequestContextRecorder>(); |
|||
services.Replace(ServiceDescriptor.Transient<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>, RecordingClientProxy>()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Cancel_Request_With_The_Token_Of_The_Request_Context() |
|||
{ |
|||
var action = await GetActionAsync(); |
|||
using var contextCancellationTokenSource = new CancellationTokenSource(); |
|||
var requestContext = new ClientProxyRequestContext(action.Action, action.Arguments, action.ServiceType) |
|||
{ |
|||
CancellationToken = contextCancellationTokenSource.Token |
|||
}; |
|||
|
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in ClientProxy.CallRequestAsyncEnumerable<int>(requestContext)) |
|||
{ |
|||
} |
|||
}, contextCancellationTokenSource); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Isolate_Cancellation_Of_Concurrent_Enumerations_Of_The_Same_Request_Context() |
|||
{ |
|||
var action = await GetActionAsync(); |
|||
var requestContext = new ClientProxyRequestContext(action.Action, action.Arguments, action.ServiceType); |
|||
var sequence = ClientProxy.CallRequestAsyncEnumerable<int>(requestContext); |
|||
using var firstCancellationTokenSource = new CancellationTokenSource(); |
|||
using var secondCancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
var first = EnumerateAsync(sequence, firstCancellationTokenSource.Token); |
|||
var second = EnumerateAsync(sequence, secondCancellationTokenSource.Token); |
|||
await WaitForBlockedRequestsAsync(2); |
|||
|
|||
firstCancellationTokenSource.Cancel(); |
|||
await ShouldBeCancelledAsync(() => first); |
|||
await Task.Delay(200); |
|||
second.IsCompleted.ShouldBeFalse(); |
|||
|
|||
secondCancellationTokenSource.Cancel(); |
|||
await ShouldBeCancelledAsync(() => second); |
|||
requestContext.CancellationToken.ShouldBeNull(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Cancel_Request_With_Method_Token_That_Is_Not_The_Last_Argument() |
|||
{ |
|||
using var methodCancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) |
|||
{ |
|||
} |
|||
}, methodCancellationTokenSource); |
|||
} |
|||
|
|||
private DynamicHttpProxyInterceptorClientProxy<IRegularTestController> ClientProxy => |
|||
ServiceProvider.GetRequiredService<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>>(); |
|||
|
|||
private async Task<ClientProxyRequestContext> GetActionAsync() |
|||
{ |
|||
// The business request is blocked, but RequestAsync records its context before sending it.
|
|||
using var cancellationTokenSource = new CancellationTokenSource(); |
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in Controller.GetStreamAsync(1).WithCancellation(cancellationTokenSource.Token)) |
|||
{ |
|||
} |
|||
}, cancellationTokenSource); |
|||
|
|||
return ServiceProvider.GetRequiredService<RequestContextRecorder>().Contexts.Last(); |
|||
} |
|||
|
|||
private static async Task EnumerateAsync(IAsyncEnumerable<int> sequence, CancellationToken cancellationToken) |
|||
{ |
|||
await foreach (var _ in sequence.WithCancellation(cancellationToken)) |
|||
{ |
|||
} |
|||
} |
|||
|
|||
public class RequestContextRecorder |
|||
{ |
|||
public ConcurrentQueue<ClientProxyRequestContext> Contexts { get; } = new(); |
|||
} |
|||
|
|||
public class RecordingClientProxy : DynamicHttpProxyInterceptorClientProxy<IRegularTestController> |
|||
{ |
|||
protected override Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
|||
{ |
|||
LazyServiceProvider.LazyGetRequiredService<RequestContextRecorder>().Contexts.Enqueue(requestContext); |
|||
return base.RequestAsync(requestContext); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public class AsyncEnumerableClientProxy_ApiDefinition_Cancellation_Tests : AsyncEnumerableClientProxyCancellation_Tests |
|||
{ |
|||
protected override bool BlockApiDefinitionRequest => true; |
|||
|
|||
[Fact] |
|||
public async Task Should_Cancel_Api_Definition_Request_With_Method_Token() |
|||
{ |
|||
using var methodCancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token)) |
|||
{ |
|||
} |
|||
}, methodCancellationTokenSource); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Cancel_Api_Definition_Request_With_Method_Token_That_Is_Not_The_Last_Argument() |
|||
{ |
|||
using var methodCancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) |
|||
{ |
|||
} |
|||
}, methodCancellationTokenSource); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Cancel_Api_Definition_Request() |
|||
{ |
|||
using var enumerationCancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
await ShouldBeCancelledWhenBlockedAsync(async () => |
|||
{ |
|||
await foreach (var _ in Controller.GetStreamAsync(3).WithCancellation(enumerationCancellationTokenSource.Token)) |
|||
{ |
|||
} |
|||
}, enumerationCancellationTokenSource); |
|||
} |
|||
} |
|||
@ -0,0 +1,110 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Net.Http; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Shouldly; |
|||
using Volo.Abp.AspNetCore.TestBase; |
|||
using Volo.Abp.Http.Client.ClientProxying; |
|||
using Volo.Abp.Http.Client.DynamicProxying; |
|||
using Volo.Abp.Http.Client.Proxying; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Http.DynamicProxying; |
|||
|
|||
public class AsyncEnumerableClientProxy_NestedRequest_Tests : AbpHttpClientTestBase |
|||
{ |
|||
protected override void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.Replace(ServiceDescriptor.Transient<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>, NestedRequestClientProxy>()); |
|||
services.Replace(ServiceDescriptor.Singleton<IProxyHttpClientFactory>(serviceProvider => |
|||
new TokenCheckingProxyHttpClientFactory(serviceProvider.GetRequiredService<ITestServerAccessor>()))); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Keep_The_Token_Of_Another_Request_Sent_While_Sending_A_Stream() |
|||
{ |
|||
NestedRequestClientProxy.NestedRequestExceptions.Clear(); |
|||
var controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
|||
|
|||
var items = new List<int>(); |
|||
await foreach (var item in controller.GetStreamAsync(2)) |
|||
{ |
|||
items.Add(item); |
|||
} |
|||
|
|||
items.ShouldBe(new[] { 1, 2 }); |
|||
var exception = NestedRequestClientProxy.NestedRequestExceptions.ShouldHaveSingleItem(); |
|||
exception.ShouldNotBeNull(); |
|||
(exception is OperationCanceledException || exception.InnerException is OperationCanceledException).ShouldBeTrue(exception.ToString()); |
|||
} |
|||
|
|||
public class NestedRequestClientProxy : DynamicHttpProxyInterceptorClientProxy<IRegularTestController> |
|||
{ |
|||
public static List<Exception?> NestedRequestExceptions { get; } = new(); |
|||
|
|||
protected override async Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
|||
{ |
|||
if (requestContext.Action.Name == nameof(IRegularTestController.GetStreamAsync)) |
|||
{ |
|||
// Another request with its own (cancelled) token, sent before the stream request.
|
|||
var nestedRequestContext = new ClientProxyRequestContext(requestContext.Action, requestContext.Arguments, requestContext.ServiceType) |
|||
{ |
|||
CancellationToken = new CancellationToken(canceled: true) |
|||
}; |
|||
|
|||
try |
|||
{ |
|||
using (await base.RequestAsync(nestedRequestContext)) |
|||
{ |
|||
} |
|||
|
|||
NestedRequestExceptions.Add(null); |
|||
} |
|||
catch (Exception exception) |
|||
{ |
|||
NestedRequestExceptions.Add(exception); |
|||
} |
|||
} |
|||
|
|||
return await base.RequestAsync(requestContext); |
|||
} |
|||
} |
|||
|
|||
private class TokenCheckingProxyHttpClientFactory : IProxyHttpClientFactory |
|||
{ |
|||
private readonly ITestServerAccessor _testServerAccessor; |
|||
|
|||
public TokenCheckingProxyHttpClientFactory(ITestServerAccessor testServerAccessor) |
|||
{ |
|||
_testServerAccessor = testServerAccessor; |
|||
} |
|||
|
|||
public HttpClient Create(string name) => Create(); |
|||
|
|||
public HttpClient Create() |
|||
{ |
|||
return new HttpClient(new TokenCheckingHandler(_testServerAccessor.Server.CreateHandler())) |
|||
{ |
|||
BaseAddress = _testServerAccessor.Server.BaseAddress |
|||
}; |
|||
} |
|||
} |
|||
|
|||
// The test server does not observe a token that is already cancelled when the request is sent.
|
|||
private class TokenCheckingHandler : DelegatingHandler |
|||
{ |
|||
public TokenCheckingHandler(HttpMessageHandler innerHandler) |
|||
: base(innerHandler) |
|||
{ |
|||
} |
|||
|
|||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
|||
{ |
|||
cancellationToken.ThrowIfCancellationRequested(); |
|||
return base.SendAsync(request, cancellationToken); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,83 @@ |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Net.Http; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Shouldly; |
|||
using Volo.Abp.Http.Client.ClientProxying; |
|||
using Volo.Abp.Http.Client.DynamicProxying; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Http.DynamicProxying; |
|||
|
|||
public class AsyncEnumerableClientProxy_RequestOverride_Tests : AbpHttpClientTestBase |
|||
{ |
|||
protected override void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.Replace(ServiceDescriptor.Transient<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>, TrackingClientProxy>()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Use_Overridden_RequestAsync_For_Streams() |
|||
{ |
|||
TrackingClientProxy.RequestedActions.Clear(); |
|||
var controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
|||
|
|||
var items = new List<int>(); |
|||
await foreach (var item in controller.GetStreamAsync(2)) |
|||
{ |
|||
items.Add(item); |
|||
} |
|||
|
|||
items.ShouldBe(new[] { 1, 2 }); |
|||
TrackingClientProxy.RequestedActions.ShouldContain(nameof(IRegularTestController.GetStreamAsync)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Pass_The_Same_Request_Context_To_RequestAsync() |
|||
{ |
|||
TrackingClientProxy.RequestContexts.Clear(); |
|||
var controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
|||
await foreach (var _ in controller.GetStreamAsync(1)) |
|||
{ |
|||
} |
|||
|
|||
var capturedContext = TrackingClientProxy.RequestContexts.Last(); |
|||
var requestContext = new CustomRequestContext(capturedContext.Action, capturedContext.Arguments, capturedContext.ServiceType); |
|||
|
|||
var clientProxy = ServiceProvider.GetRequiredService<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>>(); |
|||
var items = new List<int>(); |
|||
await foreach (var item in clientProxy.CallRequestAsyncEnumerable<int>(requestContext)) |
|||
{ |
|||
items.Add(item); |
|||
} |
|||
|
|||
items.ShouldBe(new[] { 1 }); |
|||
TrackingClientProxy.RequestContexts.Last().ShouldBeSameAs(requestContext); |
|||
requestContext.CancellationToken.ShouldBeNull(); |
|||
} |
|||
|
|||
public class CustomRequestContext : ClientProxyRequestContext |
|||
{ |
|||
public CustomRequestContext(Volo.Abp.Http.Modeling.ActionApiDescriptionModel action, IReadOnlyDictionary<string, object?> arguments, System.Type serviceType) |
|||
: base(action, arguments, serviceType) |
|||
{ |
|||
} |
|||
} |
|||
|
|||
public class TrackingClientProxy : DynamicHttpProxyInterceptorClientProxy<IRegularTestController> |
|||
{ |
|||
public static List<string> RequestedActions { get; } = new(); |
|||
|
|||
public static List<ClientProxyRequestContext> RequestContexts { get; } = new(); |
|||
|
|||
protected override Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
|||
{ |
|||
RequestedActions.Add(requestContext.Action.Name); |
|||
RequestContexts.Add(requestContext); |
|||
return base.RequestAsync(requestContext); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,142 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Runtime.CompilerServices; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Http.Client; |
|||
using Volo.Abp.Http.Client.DynamicProxying; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Http.DynamicProxying; |
|||
|
|||
public class AsyncEnumerableClientProxy_Tests : AbpHttpClientTestBase |
|||
{ |
|||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); |
|||
|
|||
private readonly IRegularTestController _controller; |
|||
|
|||
public AsyncEnumerableClientProxy_Tests() |
|||
{ |
|||
_controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
|||
AsyncEnumerableTestGate.Reset(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Use_A_Token_That_Can_Not_Be_Cancelled() |
|||
{ |
|||
var clientProxy = ServiceProvider.GetRequiredService<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>>(); |
|||
|
|||
clientProxy.UseCancellationToken(CancellationToken.None).ShouldBeSameAs(NullDisposable.Instance); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Stream_Items() |
|||
{ |
|||
var items = new List<int>(); |
|||
await foreach (var item in _controller.GetStreamAsync(3)) |
|||
{ |
|||
items.Add(item); |
|||
} |
|||
|
|||
items.ShouldBe(new[] { 1, 2, 3 }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Receive_Items_Before_Server_Finishes() |
|||
{ |
|||
var items = new List<string>(); |
|||
|
|||
try |
|||
{ |
|||
// The server waits for the gate after the first item, so this only completes if the first item is streamed.
|
|||
await ConsumeAsync(_controller.GetGatedStreamAsync(false), item => |
|||
{ |
|||
items.Add(item); |
|||
AsyncEnumerableTestGate.Open(); |
|||
}).WaitAsync(Timeout); |
|||
} |
|||
finally |
|||
{ |
|||
AsyncEnumerableTestGate.Open(); |
|||
} |
|||
|
|||
items.ShouldBe(new[] { "first", "second" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Throw_Remote_Exception_When_Server_Fails_Before_Response_Started() |
|||
{ |
|||
var items = new List<int>(); |
|||
|
|||
var exception = await Should.ThrowAsync<AbpRemoteCallException>( |
|||
ConsumeAsync(_controller.GetStreamWithErrorAsync(), items.Add)); |
|||
|
|||
exception.Error.Message.ShouldBe("Stream failed"); |
|||
items.ShouldBeEmpty(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Throw_When_Server_Fails_After_Response_Started() |
|||
{ |
|||
var items = new List<string>(); |
|||
|
|||
Exception exception; |
|||
try |
|||
{ |
|||
exception = await Should.ThrowAsync<Exception>( |
|||
ConsumeAsync(_controller.GetGatedStreamAsync(true), item => |
|||
{ |
|||
items.Add(item); |
|||
AsyncEnumerableTestGate.Open(); |
|||
}).WaitAsync(Timeout)); |
|||
} |
|||
finally |
|||
{ |
|||
AsyncEnumerableTestGate.Open(); |
|||
} |
|||
|
|||
exception.ShouldNotBeOfType<TimeoutException>(); |
|||
items.ShouldBe(new[] { "first" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Stop_When_Cancelled_While_Waiting_For_Next_Item() |
|||
{ |
|||
var items = new List<string>(); |
|||
using var cancellationTokenSource = new CancellationTokenSource(); |
|||
|
|||
try |
|||
{ |
|||
await Should.ThrowAsync<OperationCanceledException>( |
|||
ConsumeAsync(_controller.GetGatedStreamAsync(false).WithCancellation(cancellationTokenSource.Token), item => |
|||
{ |
|||
items.Add(item); |
|||
cancellationTokenSource.Cancel(); |
|||
}).WaitAsync(Timeout)); |
|||
} |
|||
finally |
|||
{ |
|||
AsyncEnumerableTestGate.Open(); |
|||
} |
|||
|
|||
items.ShouldBe(new[] { "first" }); |
|||
} |
|||
|
|||
private static async Task ConsumeAsync<T>(IAsyncEnumerable<T> source, Action<T> onItem) |
|||
{ |
|||
await foreach (var item in source) |
|||
{ |
|||
onItem(item); |
|||
} |
|||
} |
|||
|
|||
private static async Task ConsumeAsync<T>(ConfiguredCancelableAsyncEnumerable<T> source, Action<T> onItem) |
|||
{ |
|||
await foreach (var item in source) |
|||
{ |
|||
onItem(item); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,29 @@ |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
|
|||
namespace Volo.Abp.Http.DynamicProxying; |
|||
|
|||
public static class AsyncEnumerableTestGate |
|||
{ |
|||
private static TaskCompletionSource<bool> _gate = Create(); |
|||
|
|||
public static void Reset() |
|||
{ |
|||
_gate = Create(); |
|||
} |
|||
|
|||
public static void Open() |
|||
{ |
|||
_gate.TrySetResult(true); |
|||
} |
|||
|
|||
public static Task WaitAsync(CancellationToken cancellationToken) |
|||
{ |
|||
return _gate.Task.WaitAsync(cancellationToken); |
|||
} |
|||
|
|||
private static TaskCompletionSource<bool> Create() |
|||
{ |
|||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue