Browse Source

Support IAsyncEnumerable in C# client proxies

pull/26490/head
maliming 2 days ago
parent
commit
dbf2f824ca
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 15
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ServiceProxying/CSharp/CSharpServiceProxyGenerator.cs
  2. 78
      framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs
  3. 6
      framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestContext.cs
  4. 64
      framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptor.cs
  5. 26
      framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/DynamicProxying/DynamicHttpProxyInterceptorClientProxy.cs
  6. 219
      framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ServiceProxying/CSharpServiceProxyGenerator_AsyncEnumerable_Tests.cs
  7. 9
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs
  8. 57
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests.cs
  9. 55
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json
  10. 276
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxyCancellation_Tests.cs
  11. 110
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_NestedRequest_Tests.cs
  12. 83
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_RequestOverride_Tests.cs
  13. 142
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs
  14. 29
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableTestGate.cs
  15. 56
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/ClientProxyResponseDisposal_Tests.cs
  16. 11
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs
  17. 54
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs

15
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ServiceProxying/CSharp/CSharpServiceProxyGenerator.cs

@ -328,7 +328,7 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase<CSharpServi
{
var methodBuilder = new StringBuilder();
var returnTypeName = GetTypeReference(action.ReturnValue.Type, usingNamespaceList);
if (action.Name.EndsWith("Async"))
if (action.Name.EndsWith("Async") || IsAsyncEnumerable(returnTypeName))
{
GenerateAsyncClassMethod(action, returnTypeName, methodBuilder, usingNamespaceList);
}
@ -364,7 +364,7 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase<CSharpServi
StringBuilder methodBuilder,
List<string> 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<CSharpServi
var returnTypeName = GetTypeReference(action.ReturnValue.Type, usingNamespaceList);
if (action.Name.EndsWith("Async"))
if (action.Name.EndsWith("Async") || IsAsyncEnumerable(returnTypeName))
{
GenerateAsyncInterfaceMethod(action, returnTypeName, methodBuilder, usingNamespaceList);
}
@ -445,7 +445,9 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase<CSharpServi
private void GenerateAsyncInterfaceMethod(InterfaceMethodApiDescriptionModel action, string returnTypeName, StringBuilder methodBuilder, List<string> usingNamespaceList)
{
var returnSign = returnTypeName == "void" ? "Task" : $"Task<{returnTypeName}>";
var returnSign = IsAsyncEnumerable(returnTypeName)
? returnTypeName
: returnTypeName == "void" ? "Task" : $"Task<{returnTypeName}>";
methodBuilder.AppendLine($"{returnSign} {action.Name}(<args>)");
@ -463,6 +465,11 @@ public class CSharpServiceProxyGenerator : ServiceProxyGeneratorBase<CSharpServi
methodBuilder.Replace(", )", ");");
}
private static bool IsAsyncEnumerable(string returnTypeName)
{
return returnTypeName.StartsWith("IAsyncEnumerable<");
}
private static bool ShouldGenerateController(ControllerApiDescriptionModel controller)
{
return controller.Interfaces.Any() && ServicePostfixes.Any(x => controller.Interfaces.Last().Type.EndsWith(x));

78
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<TService> : ITransientDependency
{
// Passes the token of a streaming request to RequestAsync without modifying its (possibly shared) context.
private readonly AsyncLocal<StreamingRequest?> _streamingRequest = new();
public IAbpLazyServiceProvider LazyServiceProvider { get; set; } = default!;
protected IClientProxyApiDescriptionFinder ClientProxyApiDescriptionFinder => LazyServiceProvider.LazyGetRequiredService<IClientProxyApiDescriptionFinder>();
@ -60,18 +64,53 @@ public class ClientProxyBase<TService> : ITransientDependency
return await RequestAsync<T>(BuildHttpProxyClientProxyContext(methodName, arguments));
}
protected virtual async IAsyncEnumerable<T> RequestAsyncEnumerable<T>(string methodName, ClientProxyRequestTypeValue? arguments = null)
protected virtual IAsyncEnumerable<T> RequestAsyncEnumerable<T>(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<T>(stream, options)
: System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable<T>(stream);
await foreach (var item in items)
return RequestAsyncEnumerableWithNewContext<T>(methodName, arguments);
}
private async IAsyncEnumerable<T> RequestAsyncEnumerableWithNewContext<T>(string methodName, ClientProxyRequestTypeValue? arguments, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var item in RequestAsyncEnumerable<T>(BuildHttpProxyClientProxyContext(methodName, arguments)).WithCancellation(cancellationToken))
{
yield return item!;
yield return item;
}
}
protected virtual async IAsyncEnumerable<T> RequestAsyncEnumerable<T>(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<T>(stream, options, linkedCancellationToken);
await foreach (var item in items.WithCancellation(linkedCancellationToken))
{
yield return item!;
}
}
}
@ -209,10 +248,14 @@ public class ClientProxyBase<TService> : 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<TService> : 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;
}
}
}

6
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; }
/// <summary>
/// Overrides the token taken from the <see cref="Arguments"/> or the ambient provider.
/// </summary>
public CancellationToken? CancellationToken { get; set; }
public ClientProxyRequestContext(
[NotNull] ActionApiDescriptionModel action,
[NotNull] IReadOnlyDictionary<string, object?> arguments,

64
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<TService> : 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<TService>)
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.First(m => m.Name == nameof(CallRequestAsync) && m.IsGenericMethodDefinition);
CallRequestAsyncEnumerableMethod = typeof(DynamicHttpProxyInterceptor<TService>)
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.First(m => m.Name == nameof(CallRequestAsyncEnumerable) && m.IsGenericMethodDefinition);
}
public ILogger<DynamicHttpProxyInterceptor<TService>> Logger { get; set; }
@ -52,6 +61,15 @@ public class DynamicHttpProxyInterceptor<TService> : 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<TService> : 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<TService> : AbpInterceptor, ITransientD
return await InterceptorClientProxy.CallRequestAsync<T>(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<T> CallRequestAsyncEnumerable<T>(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<T>(context).WithCancellation(cancellationToken))
{
yield return item;
}
}
protected virtual async Task<object> GetResultAsync(Task task, Type resultType)
{
await task;

26
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<TService> : ClientProxyBase<
{
return await base.RequestAsync(requestContext);
}
public virtual IAsyncEnumerable<T> CallRequestAsyncEnumerable<T>(ClientProxyRequestContext requestContext)
{
return base.RequestAsyncEnumerable<T>(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();
});
}
}

219
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"), "<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": {}
}
""";
}

9
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<IRegularTestController>
{
public virtual IAsyncEnumerable<int> GetStreamAsync(int count)
{
return RequestAsyncEnumerable<int>(nameof(GetStreamAsync), new ClientProxyRequestTypeValue
{
{ typeof(int), count }
});
}
public virtual async Task<string> GetWithStringPathAsync(string name)
{
return await RequestAsync<string>(nameof(GetWithStringPathAsync), new ClientProxyRequestTypeValue

57
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<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);
}
}
}

55
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<System.Int32>",
"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
}
}
}

276
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<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);
}
}

110
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<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);
}
}
}

83
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<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);
}
}
}

142
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<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);
}
}
}

29
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<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);
}
}

56
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<int>();
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<System.Text.Json.JsonException>(async () =>
{
await foreach (var _ in _controller.GetStreamAsync(3))
{
}
});
content.Disposed.ShouldBeTrue();
}
class StubProxyHttpClientFactory : IProxyHttpClientFactory
{
private readonly ITestServerAccessor _testServerAccessor;

11
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<int> GetStreamAsync(int count);
IAsyncEnumerable<int> GetStreamWithErrorAsync();
IAsyncEnumerable<string> GetGatedStreamAsync(bool failAfterGate);
IAsyncEnumerable<int> GetStreamWithCancellationTokenAsync(CancellationToken cancellationToken);
IAsyncEnumerable<int> GetStreamWithLeadingCancellationTokenAsync(CancellationToken cancellationToken, int count);
Task<int> IncrementValueAsync(int value);
Task<string> GetPlainStringAsync();

54
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<int> 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<int> GetStreamWithErrorAsync()
{
await Task.Delay(1);
yield return 1;
throw new UserFriendlyException("Stream failed");
}
[HttpGet]
[Route("gated-stream")]
public virtual async IAsyncEnumerable<string> 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<int> GetStreamWithCancellationTokenAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await Task.Delay(1, cancellationToken);
yield return 1;
}
[HttpGet]
[Route("stream-with-leading-cancellation-token")]
public virtual async IAsyncEnumerable<int> 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<int> IncrementValueAsync(int value)

Loading…
Cancel
Save