diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ServiceProxying/CSharp/CSharpServiceProxyGenerator.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ServiceProxying/CSharp/CSharpServiceProxyGenerator.cs index 70911b12b6..9f2fb6c9c1 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ServiceProxying/CSharp/CSharpServiceProxyGenerator.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ServiceProxying/CSharp/CSharpServiceProxyGenerator.cs @@ -328,7 +328,7 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase usingNamespaceList) { - var isAsyncEnumerable = returnTypeName.StartsWith("IAsyncEnumerable<"); + var isAsyncEnumerable = IsAsyncEnumerable(returnTypeName); var asyncEnumerableTypeName = isAsyncEnumerable ? returnTypeName.Substring("IAsyncEnumerable<".Length, returnTypeName.Length - "IAsyncEnumerable<".Length - 1) : null; @@ -413,7 +413,7 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase usingNamespaceList) { - var returnSign = returnTypeName == "void" ? "Task" : $"Task<{returnTypeName}>"; + var returnSign = IsAsyncEnumerable(returnTypeName) + ? returnTypeName + : returnTypeName == "void" ? "Task" : $"Task<{returnTypeName}>"; methodBuilder.AppendLine($"{returnSign} {action.Name}()"); @@ -463,6 +465,11 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase controller.Interfaces.Last().Type.EndsWith(x)); diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs index 0b7a21c71e..7df2b9f623 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; +using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; @@ -29,6 +30,9 @@ namespace Volo.Abp.Http.Client.ClientProxying; public class ClientProxyBase : ITransientDependency { + // Passes the token of a streaming request to RequestAsync without modifying its (possibly shared) context. + private readonly AsyncLocal _streamingRequest = new(); + public IAbpLazyServiceProvider LazyServiceProvider { get; set; } = default!; protected IClientProxyApiDescriptionFinder ClientProxyApiDescriptionFinder => LazyServiceProvider.LazyGetRequiredService(); @@ -60,18 +64,53 @@ public class ClientProxyBase : ITransientDependency return await RequestAsync(BuildHttpProxyClientProxyContext(methodName, arguments)); } - protected virtual async IAsyncEnumerable RequestAsyncEnumerable(string methodName, ClientProxyRequestTypeValue? arguments = null) + protected virtual IAsyncEnumerable RequestAsyncEnumerable(string methodName, ClientProxyRequestTypeValue? arguments = null) { - var requestContext = BuildHttpProxyClientProxyContext(methodName, arguments); - var responseContent = await RequestAsync(requestContext); - var options = SystemTextJsonSerializerOptions?.Value.JsonSerializerOptions; - var stream = await responseContent.ReadAsStreamAsync(); - var items = options != null - ? System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable(stream, options) - : System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable(stream); - await foreach (var item in items) + return RequestAsyncEnumerableWithNewContext(methodName, arguments); + } + + private async IAsyncEnumerable RequestAsyncEnumerableWithNewContext(string methodName, ClientProxyRequestTypeValue? arguments, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await foreach (var item in RequestAsyncEnumerable(BuildHttpProxyClientProxyContext(methodName, arguments)).WithCancellation(cancellationToken)) { - yield return item!; + yield return item; + } + } + + protected virtual async IAsyncEnumerable RequestAsyncEnumerable(ClientProxyRequestContext requestContext, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource( + requestContext.CancellationToken ?? GetCancellationToken(requestContext.Arguments), + cancellationToken); + var linkedCancellationToken = linkedCancellationTokenSource.Token; + + HttpContent responseContent; + _streamingRequest.Value = new StreamingRequest(requestContext, linkedCancellationToken); + try + { + using (CancellationTokenProvider.Use(linkedCancellationToken)) + { + responseContent = await RequestAsync(requestContext); + } + } + finally + { + _streamingRequest.Value = null; + } + + using (responseContent) + { + var options = SystemTextJsonSerializerOptions?.Value.JsonSerializerOptions; +#if NET5_0_OR_GREATER + using var stream = await responseContent.ReadAsStreamAsync(linkedCancellationToken); +#else + using var stream = await responseContent.ReadAsStreamAsync(); +#endif + var items = System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable(stream, options, linkedCancellationToken); + await foreach (var item in items.WithCancellation(linkedCancellationToken)) + { + yield return item!; + } } } @@ -209,10 +248,14 @@ public class ClientProxyBase : ITransientDependency preSendAction(clientConfig, requestContext, client); } + // Other requests sent meanwhile (e.g. by an overridden RequestAsync) keep their own token. + var streamingRequest = _streamingRequest.Value; response = await client.SendAsync( requestMessage, HttpCompletionOption.ResponseHeadersRead /*this will buffer only the headers, the content will be used as a stream*/, - GetCancellationToken(requestContext.Arguments) + streamingRequest != null && ReferenceEquals(streamingRequest.Context, requestContext) + ? streamingRequest.CancellationToken + : requestContext.CancellationToken ?? GetCancellationToken(requestContext.Arguments) ); } catch (Exception ex) @@ -479,4 +522,17 @@ public class ClientProxyBase : ITransientDependency return CancellationTokenProvider.Token; } + + private class StreamingRequest + { + public ClientProxyRequestContext Context { get; } + + public CancellationToken CancellationToken { get; } + + public StreamingRequest(ClientProxyRequestContext context, CancellationToken cancellationToken) + { + Context = context; + CancellationToken = cancellationToken; + } + } } diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestContext.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestContext.cs index 1a96dcba40..57d7cc8533 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestContext.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestContext.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading; using JetBrains.Annotations; using Volo.Abp.Http.Modeling; @@ -16,6 +17,11 @@ public class ClientProxyRequestContext [NotNull] public Type ServiceType { get; } + /// + /// Overrides the token taken from the or the ambient provider. + /// + public CancellationToken? CancellationToken { get; set; } + public ClientProxyRequestContext( [NotNull] ActionApiDescriptionModel action, [NotNull] IReadOnlyDictionary arguments, diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptor.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptor.cs index a0b60ce006..b144f4d981 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptor.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptor.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -20,11 +22,18 @@ public class DynamicHttpProxyInterceptor : AbpInterceptor, ITransientD // ReSharper disable once StaticMemberInGenericType protected static MethodInfo CallRequestAsyncMethod { get; } + // ReSharper disable once StaticMemberInGenericType + protected static MethodInfo CallRequestAsyncEnumerableMethod { get; } + static DynamicHttpProxyInterceptor() { CallRequestAsyncMethod = typeof(DynamicHttpProxyInterceptor) .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) .First(m => m.Name == nameof(CallRequestAsync) && m.IsGenericMethodDefinition); + + CallRequestAsyncEnumerableMethod = typeof(DynamicHttpProxyInterceptor) + .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) + .First(m => m.Name == nameof(CallRequestAsyncEnumerable) && m.IsGenericMethodDefinition); } public ILogger> Logger { get; set; } @@ -52,6 +61,15 @@ public class DynamicHttpProxyInterceptor : AbpInterceptor, ITransientD public override async Task InterceptAsync(IAbpMethodInvocation invocation) { + var returnType = invocation.Method.ReturnType; + if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>)) + { + invocation.ReturnValue = CallRequestAsyncEnumerableMethod + .MakeGenericMethod(returnType.GenericTypeArguments[0]) + .Invoke(this, new object[] { invocation, CancellationToken.None })!; + return; + } + var context = new ClientProxyRequestContext( await GetActionApiDescriptionModel(invocation), invocation.ArgumentsDictionary, @@ -65,12 +83,12 @@ public class DynamicHttpProxyInterceptor : AbpInterceptor, ITransientD } else { - var returnType = invocation.Method.ReturnType.GenericTypeArguments[0]; + var resultType = invocation.Method.ReturnType.GenericTypeArguments[0]; var result = (Task)CallRequestAsyncMethod - .MakeGenericMethod(returnType) + .MakeGenericMethod(resultType) .Invoke(this, new object[] { context })!; - invocation.ReturnValue = await GetResultAsync(result, returnType); + invocation.ReturnValue = await GetResultAsync(result, resultType); } } @@ -94,6 +112,46 @@ public class DynamicHttpProxyInterceptor : AbpInterceptor, ITransientD return await InterceptorClientProxy.CallRequestAsync(context); } + private static CancellationToken GetMethodCancellationToken(IAbpMethodInvocation invocation) + { + var parameters = invocation.Method.GetParameters(); + for (var i = 0; i < parameters.Length; i++) + { + if (parameters[i].ParameterType == typeof(CancellationToken)) + { + return (CancellationToken)invocation.Arguments[i]!; + } + } + + return default; + } + + protected virtual async IAsyncEnumerable CallRequestAsyncEnumerable(IAbpMethodInvocation invocation, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + var methodCancellationToken = GetMethodCancellationToken(invocation); + using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(methodCancellationToken, cancellationToken); + + ClientProxyRequestContext context; + using (InterceptorClientProxy.UseCancellationToken(linkedCancellationTokenSource.Token)) + { + context = new ClientProxyRequestContext( + await GetActionApiDescriptionModel(invocation), + invocation.ArgumentsDictionary, + typeof(TService)); + } + + if (methodCancellationToken.CanBeCanceled) + { + // Not necessarily the last argument, which is the only one checked when sending the request. + context.CancellationToken = methodCancellationToken; + } + + await foreach (var item in InterceptorClientProxy.CallRequestAsyncEnumerable(context).WithCancellation(cancellationToken)) + { + yield return item; + } + } + protected virtual async Task GetResultAsync(Task task, Type resultType) { await task; diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptorClientProxy.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptorClientProxy.cs index e89415ac1c..60b2302700 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptorClientProxy.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptorClientProxy.cs @@ -1,4 +1,7 @@ -using System.Net.Http; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; using System.Threading.Tasks; using Volo.Abp.Http.Client.ClientProxying; @@ -15,4 +18,25 @@ public class DynamicHttpProxyInterceptorClientProxy : ClientProxyBase< { return await base.RequestAsync(requestContext); } + + public virtual IAsyncEnumerable CallRequestAsyncEnumerable(ClientProxyRequestContext requestContext) + { + return base.RequestAsyncEnumerable(requestContext); + } + + public virtual IDisposable UseCancellationToken(CancellationToken cancellationToken) + { + if (!cancellationToken.CanBeCanceled) + { + return NullDisposable.Instance; + } + + var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(CancellationTokenProvider.Token, cancellationToken); + var scope = CancellationTokenProvider.Use(linkedCancellationTokenSource.Token); + return new DisposeAction(() => + { + scope.Dispose(); + linkedCancellationTokenSource.Dispose(); + }); + } } diff --git a/framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ServiceProxying/CSharpServiceProxyGenerator_AsyncEnumerable_Tests.cs b/framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ServiceProxying/CSharpServiceProxyGenerator_AsyncEnumerable_Tests.cs new file mode 100644 index 0000000000..27e8caf2f4 --- /dev/null +++ b/framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ServiceProxying/CSharpServiceProxyGenerator_AsyncEnumerable_Tests.cs @@ -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"), ""); + try + { + var generator = new TestCSharpServiceProxyGenerator(GetRequiredService(), GetRequiredService()); + + 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 GetItemsAsync()"); + proxy.ShouldContain("return RequestAsyncEnumerable(nameof(GetItemsAsync));"); + proxy.ShouldContain("public virtual IAsyncEnumerable GetNamedItemsAsync(string name)"); + proxy.ShouldContain("public virtual async Task GetNameAsync()"); + proxy.ShouldContain("public virtual async Task DeleteAsync()"); + proxy.ShouldContain("public virtual IAsyncEnumerable GetBooks()"); + proxy.ShouldContain("return RequestAsyncEnumerable(nameof(GetBooks));"); + proxy.ShouldContain("public virtual IAsyncEnumerable 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 GetItemsAsync();"); + @interface.ShouldContain("IAsyncEnumerable GetNamedItemsAsync(string name);"); + @interface.ShouldNotContain("Task GetNameAsync();"); + @interface.ShouldContain("Task DeleteAsync();"); + @interface.ShouldContain("IAsyncEnumerable GetBooks();"); + @interface.ShouldContain("IAsyncEnumerable Read(CancellationToken cancellationToken, int count);"); + @interface.ShouldContain(" GetCount();"); + @interface.ShouldNotContain("Task GetCount"); + } + finally + { + Directory.Delete(workDirectory, true); + } + } + + private class TestCSharpServiceProxyGenerator : CSharpServiceProxyGenerator + { + public TestCSharpServiceProxyGenerator(CliHttpClientFactory cliHttpClientFactory, IJsonSerializer jsonSerializer) + : base(cliHttpClientFactory, jsonSerializer) + { + } + + protected override Task GetApplicationApiDescriptionModelAsync(GenerateProxyArgs args, ApplicationApiDescriptionModelRequestDto requestDto = null) + { + return Task.FromResult(JsonSerializer.Deserialize(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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" } + }, + { + "name": "GetNamedItemsAsync", + "parametersOnMethod": [ { "name": "name", "type": "System.String", "typeSimple": "string" } ], + "returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" } + }, + { + "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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" } + }, + { + "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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" } + }, + { + "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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" }, + "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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" }, + "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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" }, + "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", "typeSimple": "System.Collections.Generic.IAsyncEnumerable" }, + "implementFrom": "MyProject.Streaming.IStreamingAppService" + } + } + } + } + } + }, + "types": {} + } + """; +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs index f0372d0d14..dc60616295 100644 --- a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Http.DynamicProxying; @@ -5,6 +6,14 @@ namespace Volo.Abp.Http.Client.ClientProxying; public class RegularTestControllerStaticClientProxy : ClientProxyBase { + public virtual IAsyncEnumerable GetStreamAsync(int count) + { + return RequestAsyncEnumerable(nameof(GetStreamAsync), new ClientProxyRequestTypeValue + { + { typeof(int), count } + }); + } + public virtual async Task GetWithStringPathAsync(string name) { return await RequestAsync(nameof(GetWithStringPathAsync), new ClientProxyRequestTypeValue diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests.cs new file mode 100644 index 0000000000..4e3eea439c --- /dev/null +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests.cs @@ -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(); + + (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(); + 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> ToListAsync(IAsyncEnumerable source) + { + var list = new List(); + await foreach (var item in source) + { + list.Add(item); + } + + return list; + } + + public class RecordingStaticClientProxy : RegularTestControllerStaticClientProxy + { + public ConcurrentQueue RequestContexts { get; } = new(); + + protected override Task RequestAsync(ClientProxyRequestContext requestContext) + { + RequestContexts.Enqueue(requestContext); + return base.RequestAsync(requestContext); + } + } +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json index c99d2a5fa5..8db1f7060f 100644 --- a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json @@ -257,6 +257,61 @@ "remarks": null, "description": null, "displayName": null + }, + "GetStreamAsyncByCount": { + "uniqueName": "GetStreamAsyncByCount", + "name": "GetStreamAsync", + "httpMethod": "GET", + "url": "api/regular-test-controller/stream", + "supportedVersions": [], + "parametersOnMethod": [ + { + "name": "count", + "typeAsString": "System.Int32, System.Private.CoreLib", + "type": "System.Int32", + "typeSimple": "number", + "isOptional": false, + "defaultValue": null, + "summary": null, + "description": null, + "displayName": null + } + ], + "parameters": [ + { + "nameOnMethod": "count", + "name": "count", + "jsonName": null, + "type": "System.Int32", + "typeSimple": "number", + "isOptional": false, + "defaultValue": null, + "constraintTypes": [], + "bindingSourceId": "ModelBinding", + "descriptorName": "", + "summary": null, + "description": null, + "displayName": null + } + ], + "returnValue": { + "type": "System.Collections.Generic.IAsyncEnumerable", + "typeSimple": "[number]", + "summary": null, + "contentTypes": [ + "text/plain", + "application/json", + "text/json" + ], + "isRemoteStream": false + }, + "allowAnonymous": null, + "authorizeDatas": [], + "implementFrom": "Volo.Abp.Http.DynamicProxying.IRegularTestController", + "summary": null, + "remarks": null, + "description": null, + "displayName": null } } } diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxyCancellation_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxyCancellation_Tests.cs new file mode 100644 index 0000000000..e29057781f --- /dev/null +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxyCancellation_Tests.cs @@ -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(); + + protected abstract bool BlockApiDefinitionRequest { get; } + + /// + /// Released when a request reaches the blocking handler, so a test can cancel exactly at that stage. + /// + protected SemaphoreSlim BlockedRequests { get; } = new(0); + + protected override void ConfigureServices(IServiceCollection services) + { + services.Replace(ServiceDescriptor.Singleton(serviceProvider => + new BlockingProxyHttpClientFactory(serviceProvider.GetRequiredService(), 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 enumerate, CancellationTokenSource cancellationTokenSource) + { + var enumeration = enumerate(); + await WaitForBlockedRequestsAsync(1); + cancellationTokenSource.Cancel(); + await ShouldBeCancelledAsync(() => enumeration); + } + + protected static async Task ShouldBeCancelledAsync(Func enumerate) + { + var exception = await Should.ThrowAsync(() => enumerate().WaitAsync(Timeout)); + + exception.ShouldNotBeOfType(); + (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 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(); + services.Replace(ServiceDescriptor.Transient, 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(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(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 ClientProxy => + ServiceProvider.GetRequiredService>(); + + private async Task 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().Contexts.Last(); + } + + private static async Task EnumerateAsync(IAsyncEnumerable sequence, CancellationToken cancellationToken) + { + await foreach (var _ in sequence.WithCancellation(cancellationToken)) + { + } + } + + public class RequestContextRecorder + { + public ConcurrentQueue Contexts { get; } = new(); + } + + public class RecordingClientProxy : DynamicHttpProxyInterceptorClientProxy + { + protected override Task RequestAsync(ClientProxyRequestContext requestContext) + { + LazyServiceProvider.LazyGetRequiredService().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); + } +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_NestedRequest_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_NestedRequest_Tests.cs new file mode 100644 index 0000000000..50b09ed4e8 --- /dev/null +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_NestedRequest_Tests.cs @@ -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, NestedRequestClientProxy>()); + services.Replace(ServiceDescriptor.Singleton(serviceProvider => + new TokenCheckingProxyHttpClientFactory(serviceProvider.GetRequiredService()))); + } + + [Fact] + public async Task Should_Keep_The_Token_Of_Another_Request_Sent_While_Sending_A_Stream() + { + NestedRequestClientProxy.NestedRequestExceptions.Clear(); + var controller = ServiceProvider.GetRequiredService(); + + var items = new List(); + 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 + { + public static List NestedRequestExceptions { get; } = new(); + + protected override async Task 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 SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return base.SendAsync(request, cancellationToken); + } + } +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_RequestOverride_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_RequestOverride_Tests.cs new file mode 100644 index 0000000000..7473f279cc --- /dev/null +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_RequestOverride_Tests.cs @@ -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, TrackingClientProxy>()); + } + + [Fact] + public async Task Should_Use_Overridden_RequestAsync_For_Streams() + { + TrackingClientProxy.RequestedActions.Clear(); + var controller = ServiceProvider.GetRequiredService(); + + var items = new List(); + 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(); + 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>(); + var items = new List(); + await foreach (var item in clientProxy.CallRequestAsyncEnumerable(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 arguments, System.Type serviceType) + : base(action, arguments, serviceType) + { + } + } + + public class TrackingClientProxy : DynamicHttpProxyInterceptorClientProxy + { + public static List RequestedActions { get; } = new(); + + public static List RequestContexts { get; } = new(); + + protected override Task RequestAsync(ClientProxyRequestContext requestContext) + { + RequestedActions.Add(requestContext.Action.Name); + RequestContexts.Add(requestContext); + return base.RequestAsync(requestContext); + } + } +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs new file mode 100644 index 0000000000..a06c7d937e --- /dev/null +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs @@ -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(); + AsyncEnumerableTestGate.Reset(); + } + + [Fact] + public void Should_Not_Use_A_Token_That_Can_Not_Be_Cancelled() + { + var clientProxy = ServiceProvider.GetRequiredService>(); + + clientProxy.UseCancellationToken(CancellationToken.None).ShouldBeSameAs(NullDisposable.Instance); + } + + [Fact] + public async Task Should_Stream_Items() + { + var items = new List(); + 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(); + + 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(); + + var exception = await Should.ThrowAsync( + 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(); + + Exception exception; + try + { + exception = await Should.ThrowAsync( + ConsumeAsync(_controller.GetGatedStreamAsync(true), item => + { + items.Add(item); + AsyncEnumerableTestGate.Open(); + }).WaitAsync(Timeout)); + } + finally + { + AsyncEnumerableTestGate.Open(); + } + + exception.ShouldNotBeOfType(); + items.ShouldBe(new[] { "first" }); + } + + [Fact] + public async Task Should_Stop_When_Cancelled_While_Waiting_For_Next_Item() + { + var items = new List(); + using var cancellationTokenSource = new CancellationTokenSource(); + + try + { + await Should.ThrowAsync( + 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(IAsyncEnumerable source, Action onItem) + { + await foreach (var item in source) + { + onItem(item); + } + } + + private static async Task ConsumeAsync(ConfiguredCancelableAsyncEnumerable source, Action onItem) + { + await foreach (var item in source) + { + onItem(item); + } + } +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableTestGate.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableTestGate.cs new file mode 100644 index 0000000000..7d829aeefd --- /dev/null +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableTestGate.cs @@ -0,0 +1,29 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.Http.DynamicProxying; + +public static class AsyncEnumerableTestGate +{ + private static TaskCompletionSource _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 Create() + { + return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/ClientProxyResponseDisposal_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/ClientProxyResponseDisposal_Tests.cs index 810781fe15..3c2e295aa7 100644 --- a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/ClientProxyResponseDisposal_Tests.cs +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/ClientProxyResponseDisposal_Tests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; @@ -76,6 +77,61 @@ public class ClientProxyResponseDisposal_Tests : AbpHttpClientTestBase content.Disposed.ShouldBeTrue(); } + [Fact] + public async Task Async_Enumerable_Response_Should_Dispose_HttpContent_When_Enumeration_Completes() + { + var content = new TrackingHttpContent("[1,2,3]"); + _factory.SetStubResponse(() => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = content + }); + + var items = new List(); + await foreach (var item in _controller.GetStreamAsync(3)) + { + items.Add(item); + } + + items.ShouldBe(new[] { 1, 2, 3 }); + content.Disposed.ShouldBeTrue(); + } + + [Fact] + public async Task Async_Enumerable_Response_Should_Dispose_HttpContent_When_Consumer_Stops_Early() + { + var content = new TrackingHttpContent("[1,2,3]"); + _factory.SetStubResponse(() => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = content + }); + + await foreach (var _ in _controller.GetStreamAsync(3)) + { + break; + } + + content.Disposed.ShouldBeTrue(); + } + + [Fact] + public async Task Async_Enumerable_Response_Should_Dispose_HttpContent_When_Json_Is_Invalid() + { + var content = new TrackingHttpContent("[1,\"invalid\"]"); + _factory.SetStubResponse(() => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = content + }); + + await Should.ThrowAsync(async () => + { + await foreach (var _ in _controller.GetStreamAsync(3)) + { + } + }); + + content.Disposed.ShouldBeTrue(); + } + class StubProxyHttpClientFactory : IProxyHttpClientFactory { private readonly ITestServerAccessor _testServerAccessor; diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs index 9f1e01266d..49a1596c6e 100644 --- a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Volo.Abp.Content; @@ -7,6 +8,16 @@ namespace Volo.Abp.Http.DynamicProxying; public interface IRegularTestController { + IAsyncEnumerable GetStreamAsync(int count); + + IAsyncEnumerable GetStreamWithErrorAsync(); + + IAsyncEnumerable GetGatedStreamAsync(bool failAfterGate); + + IAsyncEnumerable GetStreamWithCancellationTokenAsync(CancellationToken cancellationToken); + + IAsyncEnumerable GetStreamWithLeadingCancellationTokenAsync(CancellationToken cancellationToken, int count); + Task IncrementValueAsync(int value); Task GetPlainStringAsync(); diff --git a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs index 292396cfb0..05ab849a8b 100644 --- a/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs +++ b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -16,6 +17,59 @@ namespace Volo.Abp.Http.DynamicProxying; //[ApiExplorerSettings(IgnoreApi = false)] //alternative public class RegularTestController : AbpController, IRegularTestController { + [HttpGet] + [Route("stream")] + public virtual async IAsyncEnumerable GetStreamAsync(int count) + { + for (var i = 1; i <= count; i++) + { + await Task.Delay(1); + yield return i; + } + } + + [HttpGet] + [Route("stream-with-error")] + public virtual async IAsyncEnumerable GetStreamWithErrorAsync() + { + await Task.Delay(1); + yield return 1; + throw new UserFriendlyException("Stream failed"); + } + + [HttpGet] + [Route("gated-stream")] + public virtual async IAsyncEnumerable GetGatedStreamAsync(bool failAfterGate) + { + yield return "first"; + await AsyncEnumerableTestGate.WaitAsync(HttpContext.RequestAborted); + if (failAfterGate) + { + throw new UserFriendlyException("Stream failed after response started"); + } + + yield return "second"; + } + + [HttpGet] + [Route("stream-with-cancellation-token")] + public virtual async IAsyncEnumerable GetStreamWithCancellationTokenAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await Task.Delay(1, cancellationToken); + yield return 1; + } + + [HttpGet] + [Route("stream-with-leading-cancellation-token")] + public virtual async IAsyncEnumerable GetStreamWithLeadingCancellationTokenAsync([EnumeratorCancellation] CancellationToken cancellationToken, int count) + { + for (var i = 1; i <= count; i++) + { + await Task.Delay(1, cancellationToken); + yield return i; + } + } + [HttpGet] [Route("increment")] public Task IncrementValueAsync(int value)