From d33daa82f5c94910a22109c05d439c616a4e6547 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:01:55 +0800 Subject: [PATCH 01/10] Support IAsyncEnumerable in async interceptors --- .../Volo.Abp.Castle.Core.csproj | 4 + .../AbpAsyncDeterminationInterceptor.cs | 12 + .../CastleAsyncEnumerableAbpInterceptor.cs | 127 ++++ .../Abp/DynamicProxy/AbpInterceptionScope.cs | 30 + ...thodInvocationAsyncEnumerableExtensions.cs | 177 +++++ .../AbpMethodInvocationScopeExtensions.cs | 31 + .../Abp/DynamicProxy/AbpScopeInterceptor.cs | 23 + .../IAbpInterceptedAsyncEnumerable.cs | 8 + .../Abp/DynamicProxy/IAbpInterceptionScope.cs | 15 + .../Volo/Abp/Reflection/TypeHelper.cs | 5 + ...tofac_AsyncEnumerable_Interception_Test.cs | 13 + .../AbpAsyncEnumerableInterceptionTestBase.cs | 660 ++++++++++++++++++ .../AbpInterceptionScope_Tests.cs | 44 ++ ...vocationAsyncEnumerableExtensions_Tests.cs | 84 +++ .../AsyncEnumerableCallerContext.cs | 8 + .../AsyncEnumerableConcurrentTestObject.cs | 16 + .../AsyncEnumerableDecoratedTestObject.cs | 14 + .../AsyncEnumerableGatedScopedTestObject.cs | 15 + .../AsyncEnumerableGatedTestObject.cs | 19 + .../AsyncEnumerableInterceptionTargetClass.cs | 57 ++ ...syncEnumerableNullReturnValueTestObject.cs | 13 + ...yncEnumerableScopeInterceptorTestObject.cs | 122 ++++ .../AsyncEnumerableScopedTestObject.cs | 31 + ...EnumerableThrowingInterceptorTestObject.cs | 15 + ...syncEnumerableValueTaskSourceTestObject.cs | 132 ++++ ...yncEnumerableWrongReturnValueTestObject.cs | 12 + .../Volo/Abp/DynamicProxy/CachedTestObject.cs | 8 + .../EventLoggingScopeInterceptor.cs | 77 ++ .../Abp/DynamicProxy/GatedTestInterceptor.cs | 14 + .../MultiplyingTestInterceptor.cs | 21 + .../NullReturnValueTestInterceptor.cs | 12 + .../DynamicProxy/RetryOnceTestInterceptor.cs | 19 + .../Volo/Abp/DynamicProxy/ScopeEventLog.cs | 10 + .../Abp/DynamicProxy/ScopeTestInterceptor.cs | 50 ++ .../WrongReturnValueTestInterceptor.cs | 13 + 35 files changed, 1911 insertions(+) create mode 100644 framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/CastleAsyncEnumerableAbpInterceptor.cs create mode 100644 framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpInterceptionScope.cs create mode 100644 framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions.cs create mode 100644 framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationScopeExtensions.cs create mode 100644 framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpScopeInterceptor.cs create mode 100644 framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptedAsyncEnumerable.cs create mode 100644 framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptionScope.cs create mode 100644 framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_AsyncEnumerable_Interception_Test.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionScope_Tests.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions_Tests.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableCallerContext.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableDecoratedTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedScopedTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableInterceptionTargetClass.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableNullReturnValueTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopeInterceptorTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopedTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableThrowingInterceptorTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableValueTaskSourceTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableWrongReturnValueTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/EventLoggingScopeInterceptor.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/GatedTestInterceptor.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/MultiplyingTestInterceptor.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/NullReturnValueTestInterceptor.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/RetryOnceTestInterceptor.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeEventLog.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeTestInterceptor.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/WrongReturnValueTestInterceptor.cs diff --git a/framework/src/Volo.Abp.Castle.Core/Volo.Abp.Castle.Core.csproj b/framework/src/Volo.Abp.Castle.Core/Volo.Abp.Castle.Core.csproj index 421261225f..35e61a6fe5 100644 --- a/framework/src/Volo.Abp.Castle.Core/Volo.Abp.Castle.Core.csproj +++ b/framework/src/Volo.Abp.Castle.Core/Volo.Abp.Castle.Core.csproj @@ -21,6 +21,10 @@ + + + + diff --git a/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/AbpAsyncDeterminationInterceptor.cs b/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/AbpAsyncDeterminationInterceptor.cs index 3f15ad631a..022f9a4e28 100644 --- a/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/AbpAsyncDeterminationInterceptor.cs +++ b/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/AbpAsyncDeterminationInterceptor.cs @@ -6,9 +6,21 @@ namespace Volo.Abp.Castle.DynamicProxy; public class AbpAsyncDeterminationInterceptor : AsyncDeterminationInterceptor where TInterceptor : IAbpInterceptor { + private readonly TInterceptor _abpInterceptor; + public AbpAsyncDeterminationInterceptor(TInterceptor abpInterceptor) : base(new CastleAsyncAbpInterceptorAdapter(abpInterceptor)) { + _abpInterceptor = abpInterceptor; + } + + public override void Intercept(IInvocation invocation) + { + if (CastleAsyncEnumerableAbpInterceptor.TryIntercept(invocation, _abpInterceptor)) + { + return; + } + base.Intercept(invocation); } } diff --git a/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/CastleAsyncEnumerableAbpInterceptor.cs b/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/CastleAsyncEnumerableAbpInterceptor.cs new file mode 100644 index 0000000000..ce2727248d --- /dev/null +++ b/framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/CastleAsyncEnumerableAbpInterceptor.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Castle.DynamicProxy; +using Volo.Abp.DynamicProxy; +using Volo.Abp.Reflection; + +namespace Volo.Abp.Castle.DynamicProxy; + +internal static class CastleAsyncEnumerableAbpInterceptor +{ + private delegate object AsyncEnumerableHandler(IInvocation invocation, IAbpInterceptor interceptor); + + private static readonly MethodInfo InterceptMethod = typeof(CastleAsyncEnumerableAbpInterceptor) + .GetMethod(nameof(Intercept), BindingFlags.Static | BindingFlags.NonPublic)!; + + private static readonly ConcurrentDictionary Handlers = new(); + + private static readonly ConcurrentDictionary MethodsWithByRefParameters = new(); + + public static bool TryIntercept(IInvocation invocation, IAbpInterceptor interceptor) + { + var returnType = invocation.Method.ReturnType; + if (!TypeHelper.IsAsyncEnumerable(returnType)) + { + return false; + } + + if (MethodsWithByRefParameters.GetOrAdd(invocation.Method, method => method.GetParameters().Any(p => p.ParameterType.IsByRef))) + { + return false; + } + + invocation.ReturnValue = Handlers.GetOrAdd(returnType, CreateHandler)(invocation, interceptor); + return true; + } + + private static AsyncEnumerableHandler CreateHandler(Type returnType) + { + return (AsyncEnumerableHandler)InterceptMethod + .MakeGenericMethod(returnType.GetGenericArguments()[0]) + .CreateDelegate(typeof(AsyncEnumerableHandler)); + } + + private static object Intercept(IInvocation invocation, IAbpInterceptor interceptor) + { + var methodInvocation = new CastleAbpMethodInvocationAdapterWithReturnValue>( + invocation, + invocation.CaptureProceedInfo(), + ProceedAsync); + + return new InterceptedAsyncEnumerable(InterceptAsync(interceptor, methodInvocation), methodInvocation); + } + + private static async Task InterceptAsync(IAbpInterceptor interceptor, IAbpMethodInvocation methodInvocation) + { + // Also captures a synchronous exception of the interceptor, so it is thrown when enumerating, like for a Task. + await interceptor.InterceptAsync(methodInvocation); + } + + private static async Task> ProceedAsync(IInvocation invocation, IInvocationProceedInfo proceedInfo) + { + proceedInfo.Invoke(); + + // Waits for the next interceptor, like awaiting the task of a Task-returning method. + if (invocation.ReturnValue is InterceptedAsyncEnumerable next) + { + return (await next.GetResultAsync())!; + } + + return (IAsyncEnumerable)invocation.ReturnValue!; + } + + private class InterceptedAsyncEnumerable : IAsyncEnumerable, IAbpInterceptedAsyncEnumerable + { + private readonly Task _interceptTask; + private readonly IAbpMethodInvocation _methodInvocation; + + public InterceptedAsyncEnumerable(Task interceptTask, IAbpMethodInvocation methodInvocation) + { + _interceptTask = interceptTask; + _methodInvocation = methodInvocation; + } + + public async Task?> GetResultAsync() + { + await _interceptTask; + return (IAsyncEnumerable?)_methodInvocation.ReturnValue; + } + + public Task WaitForInterceptorsAsync() + { + return GetResultAsync(); + } + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return EnumerateAsync(cancellationToken).GetAsyncEnumerator(cancellationToken); + } + + private async IAsyncEnumerable EnumerateAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) + { + // Keeps the execution context of the caller for the await below even if the caller suppresses its flow. + // The caller is not affected, as its execution context is restored when this step of the async iterator returns. + if (ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.RestoreFlow(); + } + + var source = await GetResultAsync(); + if (source == null) + { + yield break; + } + + await foreach (var item in source.WithCancellation(cancellationToken)) + { + yield return item; + } + } + } +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpInterceptionScope.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpInterceptionScope.cs new file mode 100644 index 0000000000..6dbd415c8e --- /dev/null +++ b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpInterceptionScope.cs @@ -0,0 +1,30 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AbpInterceptionScope : IAbpInterceptionScope +{ + private readonly IDisposable? _disposable; + + public AbpInterceptionScope(IDisposable? disposable = null) + { + _disposable = disposable; + } + + public virtual Task CompleteAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public virtual Task FailAsync(Exception exception) + { + return Task.CompletedTask; + } + + public virtual void Dispose() + { + _disposable?.Dispose(); + } +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions.cs new file mode 100644 index 0000000000..4941240eaa --- /dev/null +++ b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Volo.Abp.Reflection; + +namespace Volo.Abp.DynamicProxy; + +public static class AbpMethodInvocationAsyncEnumerableExtensions +{ + private delegate object WrapHandler(object source, Func beginScope); + + private static readonly MethodInfo WrapMethod = typeof(AbpMethodInvocationAsyncEnumerableExtensions) + .GetMethod(nameof(Wrap), BindingFlags.Static | BindingFlags.NonPublic)!; + + private static readonly ConcurrentDictionary WrapHandlers = new(); + + /// + /// Runs each enumeration of a returned in a new scope. + /// must set its async local values (e.g. the ambient unit of work) synchronously. + /// + public static bool WrapAsyncEnumerable(this IAbpMethodInvocation invocation, Func beginScope) + { + var handler = WrapHandlers.GetOrAdd(invocation.Method, CreateHandler); + if (handler == null || invocation.ReturnValue == null) + { + return false; + } + + invocation.ReturnValue = handler(invocation.ReturnValue, beginScope); + return true; + } + + private static WrapHandler? CreateHandler(MethodInfo method) + { + // The return value of a method with ref or out parameters cannot be replaced, as it is not intercepted asynchronously. + var returnType = method.ReturnType; + if (!TypeHelper.IsAsyncEnumerable(returnType) || + method.GetParameters().Any(p => p.ParameterType.IsByRef)) + { + return null; + } + + return (WrapHandler)WrapMethod + .MakeGenericMethod(returnType.GenericTypeArguments[0]) + .CreateDelegate(typeof(WrapHandler)); + } + + private static object Wrap(object source, Func beginScope) + { + return EnumerateInScopeAsync((IAsyncEnumerable)source, beginScope); + } + + private static async IAsyncEnumerable EnumerateInScopeAsync( + IAsyncEnumerable source, + Func beginScope, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + var scope = beginScope(); + + // Each step of an async iterator runs in the execution context of its caller, without the async local values set by beginScope. + var context = CaptureExecutionContext(); + + try + { + IAsyncEnumerator enumerator; + try + { + enumerator = Run(context, () => source.GetAsyncEnumerator(cancellationToken)); + } + catch (Exception exception) + { + await Run(context, () => scope.FailAsync(exception)); + throw; + } + + Exception? sourceException = null; + + try + { + while (true) + { + bool hasNext; + T current = default!; + try + { + hasNext = await Run(context, () => MoveNextAsync(enumerator)); + if (hasNext) + { + current = Run(context, () => enumerator.Current); + } + } + catch (Exception exception) + { + sourceException = exception; + throw; + } + + if (!hasNext) + { + break; + } + + yield return current; + } + } + finally + { + // The source is disposed first, so the scope covers its cleanup. + try + { + await Run(context, () => DisposeAsync(enumerator)); + } + catch (Exception exception) + { + // It replaces the exception of the source, if any, as the one thrown to the caller. + sourceException = exception; + throw; + } + finally + { + if (sourceException != null) + { + await Run(context, () => scope.FailAsync(sourceException)); + } + else + { + // Also when the caller stops early, like a method that has returned. + await Run(context, () => scope.CompleteAsync(cancellationToken)); + } + } + } + } + finally + { + Run(context, () => + { + scope.Dispose(); + return true; + }); + } + } + + private static ExecutionContext CaptureExecutionContext() + { + // Capture returns null while the flow is suppressed. Restoring it does not affect the caller, + // whose execution context is restored when this step of the async iterator returns. + if (ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.RestoreFlow(); + } + + return ExecutionContext.Capture()!; + } + + // The value task of the source (e.g. an IValueTaskSource) can also run its code when completed and when its result is read. + private static async ValueTask MoveNextAsync(IAsyncEnumerator enumerator) + { + return await enumerator.MoveNextAsync(); + } + + private static async ValueTask DisposeAsync(IAsyncEnumerator enumerator) + { + await enumerator.DisposeAsync(); + } + + private static TResult Run(ExecutionContext context, Func func) + { + TResult result = default!; + ExecutionContext.Run(context.CreateCopy(), _ => result = func(), null); + return result; + } +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationScopeExtensions.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationScopeExtensions.cs new file mode 100644 index 0000000000..b9ceb10b66 --- /dev/null +++ b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationScopeExtensions.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public static class AbpMethodInvocationScopeExtensions +{ + /// + /// Also runs each enumeration of a returned in a new scope. + /// must set its async local values (e.g. the ambient unit of work) synchronously. + /// + public static async Task ProceedInScopeAsync(this IAbpMethodInvocation invocation, Func beginScope) + { + using (var scope = beginScope()) + { + try + { + await invocation.ProceedAsync(); + } + catch (Exception exception) + { + await scope.FailAsync(exception); + throw; + } + + await scope.CompleteAsync(default); + } + + invocation.WrapAsyncEnumerable(beginScope); + } +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpScopeInterceptor.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpScopeInterceptor.cs new file mode 100644 index 0000000000..86c423a78d --- /dev/null +++ b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpScopeInterceptor.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public abstract class AbpScopeInterceptor : AbpInterceptor +{ + public override Task InterceptAsync(IAbpMethodInvocation invocation) + { + return ShouldIntercept(invocation) + ? invocation.ProceedInScopeAsync(() => BeginScope(invocation)) + : invocation.ProceedAsync(); + } + + protected virtual bool ShouldIntercept(IAbpMethodInvocation invocation) + { + return true; + } + + /// + /// Must set its async local values synchronously. + /// + protected abstract IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation); +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptedAsyncEnumerable.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptedAsyncEnumerable.cs new file mode 100644 index 0000000000..a9f5a931f0 --- /dev/null +++ b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptedAsyncEnumerable.cs @@ -0,0 +1,8 @@ +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public interface IAbpInterceptedAsyncEnumerable +{ + Task WaitForInterceptorsAsync(); +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptionScope.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptionScope.cs new file mode 100644 index 0000000000..cc2695c018 --- /dev/null +++ b/framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptionScope.cs @@ -0,0 +1,15 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public interface IAbpInterceptionScope : IDisposable +{ + /// + /// Also called when the caller stops enumerating early. + /// + Task CompleteAsync(CancellationToken cancellationToken); + + Task FailAsync(Exception exception); +} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs index eec4da40e1..3ae97879ec 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs @@ -156,6 +156,11 @@ public static class TypeHelper return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } + public static bool IsAsyncEnumerable(Type type) + { + return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>); + } + public static bool IsNullableEnum(Type type) { return type.IsGenericType && diff --git a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_AsyncEnumerable_Interception_Test.cs b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_AsyncEnumerable_Interception_Test.cs new file mode 100644 index 0000000000..5654f52f31 --- /dev/null +++ b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_AsyncEnumerable_Interception_Test.cs @@ -0,0 +1,13 @@ +using System; +using System.Threading.Tasks; +using Volo.Abp.DynamicProxy; + +namespace Volo.Abp.Autofac.Interception; + +public class Autofac_AsyncEnumerable_Interception_Test : AbpAsyncEnumerableInterceptionTestBase +{ + protected override Task> SetAbpApplicationCreationOptionsAsync() + { + return Task.FromResult>(options => options.UseAutofac()); + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs new file mode 100644 index 0000000000..eba4228bb0 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs @@ -0,0 +1,660 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Volo.Abp.Modularity; +using Volo.Abp.Testing; +using Xunit; + +namespace Volo.Abp.DynamicProxy; + +public abstract class AbpAsyncEnumerableInterceptionTestBase : AbpAsyncIntegratedTest, IAsyncLifetime + where TStartupModule : IAbpModule +{ + protected override Task BeforeAddApplicationAsync(IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.OnRegistered(registration => + { + if (typeof(AsyncEnumerableInterceptionTargetClass) == registration.ImplementationType) + { + registration.Interceptors.Add(); + registration.Interceptors.Add(); + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableScopeInterceptorTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableScopedTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableValueTaskSourceTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableConcurrentTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableGatedTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableGatedScopedTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableWrongReturnValueTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableNullReturnValueTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableThrowingInterceptorTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(AsyncEnumerableDecoratedTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + + if (typeof(CachedTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + }); + + return Task.CompletedTask; + } + + [Fact] + public async Task Should_Intercept_The_Call_And_Enumerate_Lazily() + { + var target = ServiceProvider.GetRequiredService(); + + var items = await ToListAsync(target.GetItemsAsync(2)); + + items.ShouldBe(new[] { 1, 2 }); + target.Logs.ShouldBe(new[] + { + "SimpleAsyncInterceptor_InterceptAsync_BeforeInvocation", + "SimpleAsyncInterceptor2_InterceptAsync_BeforeInvocation", + "SimpleAsyncInterceptor2_InterceptAsync_AfterInvocation", + "SimpleAsyncInterceptor_InterceptAsync_AfterInvocation", + "Produce1", + "Produce2" + }); + } + + [Fact] + public async Task Should_Not_Block_The_Call_While_Interceptor_Is_Awaiting() + { + var target = ServiceProvider.GetRequiredService(); + var interceptor = ServiceProvider.GetRequiredService(); + + try + { + // Called on another thread, so a call blocking on the interceptor fails the test instead of hanging it. + var sequence = await Task.Run(() => target.GetItemsAsync()).WaitAsync(TimeSpan.FromSeconds(10)); + var enumeration = ToListAsync(sequence); + enumeration.IsCompleted.ShouldBeFalse(); + + interceptor.Gate.SetResult(true); + (await enumeration.WaitAsync(TimeSpan.FromSeconds(10))).ShouldBe(new[] { 1 }); + } + finally + { + interceptor.Gate.TrySetResult(true); + } + } + + [Fact] + public async Task Should_Throw_Synchronous_Interceptor_Exception_When_Enumerating() + { + var target = ServiceProvider.GetRequiredService(); + + var sequence = target.GetItemsAsync(); + + await Should.ThrowAsync(ToListAsync(sequence)); + target.Invoked.ShouldBeFalse(); + } + + [Fact] + public async Task Should_Throw_If_Interceptor_Sets_Wrong_Return_Value_Type() + { + var target = ServiceProvider.GetRequiredService(); + + await Should.ThrowAsync(ToListAsync(target.GetItemsAsync())); + } + + [Fact] + public async Task Should_Enumerate_Return_Value_Replaced_By_Interceptor() + { + var target = ServiceProvider.GetRequiredService(); + + (await ToListAsync(target.GetItemsAsync())).ShouldBe(new[] { 10, 20 }); + } + + [Fact] + public async Task Should_Enumerate_Return_Value_Of_Short_Circuiting_Interceptor() + { + var target = ServiceProvider.GetRequiredService(); + + var first = await ToListAsync(target.GetValuesAsync(42)); + + // The test cache interceptor caches by method, so a different argument only returns 42 if it short-circuits. + var second = await ToListAsync(target.GetValuesAsync(1)); + + first.ShouldBe(new[] { 42, 43 }); + second.ShouldBe(new[] { 42, 43 }); + } + + [Fact] + public async Task Should_Allow_Interceptor_To_Proceed_Again() + { + var target = ServiceProvider.GetRequiredService(); + + (await ToListAsync(target.GetItemsCreatedOnSecondAttempt())).ShouldBe(new[] { 1 }); + } + + [Fact] + public async Task Should_Propagate_Exception_Thrown_After_Items_Were_Delivered() + { + var target = ServiceProvider.GetRequiredService(); + var items = new List(); + + var exception = await Should.ThrowAsync(async () => + { + await foreach (var item in target.GetOneThenThrowAsync()) + { + items.Add(item); + } + }); + + exception.Message.ShouldBe("Failed after first item"); + items.ShouldBe(new[] { 1 }); + } + + [Fact] + public async Task Should_Pass_Cancellation_To_The_Source() + { + var target = ServiceProvider.GetRequiredService(); + var items = new List(); + using var cancellationTokenSource = new CancellationTokenSource(); + + await Should.ThrowAsync(async () => + { + await foreach (var item in target.GetOneThenWaitAsync().WithCancellation(cancellationTokenSource.Token)) + { + items.Add(item); + cancellationTokenSource.CancelAfter(50); + } + }).WaitAsync(TimeSpan.FromSeconds(10)); + + items.ShouldBe(new[] { 1 }); + } + + [Fact] + public async Task Should_Set_Out_Parameters_When_Called() + { + var target = ServiceProvider.GetRequiredService(); + + var sequence = target.GetItemsWithOutParameter(out var value); + + value.ShouldBe(42); + (await ToListAsync(sequence)).ShouldBe(new[] { 1 }); + } + + [Fact] + public async Task Should_Support_Concurrent_Enumerations_Of_The_Same_Sequence() + { + // A source without shared mutable state, so the test only checks the interception wrapper. + var target = ServiceProvider.GetRequiredService(); + var sequence = target.GetItemsAsync(3); + + var results = await Task.WhenAll( + Task.Run(() => ToListAsync(sequence)), + Task.Run(() => ToListAsync(sequence))); + + results[0].ShouldBe(new[] { 1, 2, 3 }); + results[1].ShouldBe(new[] { 1, 2, 3 }); + } + + [Fact] + public async Task Should_Keep_The_Scope_Of_The_Interceptor_For_Every_Step_Of_The_Enumeration() + { + var target = ServiceProvider.GetRequiredService(); + + var values = new List(); + await foreach (var value in target.GetScopeValuesAsync(fail: false)) + { + // The caller is not affected by the scope. + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + values.Add(value); + } + + values.ShouldBe(new[] { "in-scope", "in-scope" }); + target.Logs.ShouldBe(new[] { "Completed:in-scope", "Disposed" }); + } + + [Fact] + public async Task Should_Keep_The_Scope_When_The_Enumeration_Is_Started_With_A_Suppressed_Flow() + { + // No asynchronous interceptor, so the scope begins synchronously while the flow is suppressed. + var target = ServiceProvider.GetRequiredService(); + var enumerator = target.GetScopeValuesAsync(fail: false).GetAsyncEnumerator(); + + ValueTask moveNext; + using (ExecutionContext.SuppressFlow()) + { + moveNext = enumerator.MoveNextAsync(); + + ExecutionContext.IsFlowSuppressed().ShouldBeTrue(); + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + } + + var values = new List(); + while (await moveNext) + { + values.Add(enumerator.Current); + moveNext = enumerator.MoveNextAsync(); + } + + await enumerator.DisposeAsync(); + + ExecutionContext.IsFlowSuppressed().ShouldBeFalse(); + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + values.ShouldBe(new[] { "in-scope", "in-scope" }); + target.Logs.ShouldBe(new[] { "Completed:in-scope", "Disposed" }); + } + + [Fact] + public async Task Should_Keep_The_Context_Of_The_Caller_When_The_Enumeration_Is_Started_With_A_Suppressed_Flow_Before_The_Interceptors_Complete() + { + var target = ServiceProvider.GetRequiredService(); + var interceptor = ServiceProvider.GetRequiredService(); + var enumerator = target.GetCallerValueAsync().GetAsyncEnumerator(); + + AsyncEnumerableCallerContext.Value.Value = "enumeration"; + ValueTask moveNext; + using (ExecutionContext.SuppressFlow()) + { + moveNext = enumerator.MoveNextAsync(); + + ExecutionContext.IsFlowSuppressed().ShouldBeTrue(); + } + + AsyncEnumerableCallerContext.Value.Value = null; + interceptor.Gate.SetResult(true); + + (await moveNext).ShouldBeTrue(); + enumerator.Current.ShouldBe("enumeration"); + await enumerator.DisposeAsync(); + } + + [Fact] + public async Task Should_Keep_The_Context_Of_The_Caller_And_The_Scope_When_The_Enumeration_Is_Started_With_A_Suppressed_Flow_Before_The_Interceptors_Complete() + { + var target = ServiceProvider.GetRequiredService(); + var interceptor = ServiceProvider.GetRequiredService(); + var enumerator = target.GetCallerAndScopeValuesAsync().GetAsyncEnumerator(); + + AsyncEnumerableCallerContext.Value.Value = "enumeration"; + ValueTask moveNext; + using (ExecutionContext.SuppressFlow()) + { + moveNext = enumerator.MoveNextAsync(); + + ExecutionContext.IsFlowSuppressed().ShouldBeTrue(); + } + + AsyncEnumerableCallerContext.Value.Value = "changed"; + interceptor.Gate.SetResult(true); + + var values = new List(); + while (await moveNext) + { + values.Add(enumerator.Current); + moveNext = enumerator.MoveNextAsync(); + } + + await enumerator.DisposeAsync(); + + values.ShouldBe(new[] { "enumeration:in-scope", "enumeration:in-scope" }); + target.Logs.ShouldBe(new[] { "Completed:in-scope", "Disposed" }); + AsyncEnumerableCallerContext.Value.Value.ShouldBe("changed"); + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + } + + [Fact] + public async Task Should_Keep_The_Context_Of_The_First_Step_For_Every_Step_Of_The_Enumeration() + { + var target = ServiceProvider.GetRequiredService(); + var enumerator = target.GetCallerValuesAsync().GetAsyncEnumerator(); + + AsyncEnumerableCallerContext.Value.Value = "first"; + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + enumerator.Current.ShouldBe("first"); + + AsyncEnumerableCallerContext.Value.Value = "second"; + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + enumerator.Current.ShouldBe("first"); + + await enumerator.DisposeAsync(); + AsyncEnumerableCallerContext.Value.Value.ShouldBe("second"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Should_Keep_The_Scope_When_The_Value_Tasks_Of_The_Source_Complete(bool completeAsynchronously) + { + var target = ServiceProvider.GetRequiredService(); + + var items = new List(); + await foreach (var item in target.GetItemsAsync(completeAsynchronously)) + { + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + items.Add(item); + } + + items.ShouldBe(new[] { 1, 2 }); + target.Logs.ShouldBe(new[] + { + "MoveNext:in-scope", "MoveNext:in-scope", "MoveNext:in-scope", "Dispose:in-scope", "Completed:in-scope", "Disposed" + }); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Should_Keep_The_Scope_When_The_Value_Task_Of_Disposing_The_Source_Completes(bool completeAsynchronously) + { + var target = ServiceProvider.GetRequiredService(); + + await foreach (var _ in target.GetItemsAsync(completeAsynchronously)) + { + break; + } + + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + target.Logs.ShouldBe(new[] { "MoveNext:in-scope", "Dispose:in-scope", "Completed:in-scope", "Disposed" }); + } + + [Fact] + public async Task Should_Keep_The_Scope_When_The_Value_Tasks_Of_The_Source_Are_Completed_Without_The_Execution_Context() + { + var target = ServiceProvider.GetRequiredService(); + + var items = new List(); + await foreach (var item in target.GetItemsCompletedWithoutExecutionContextAsync()) + { + ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull(); + items.Add(item); + } + + items.ShouldBe(new[] { 1, 2 }); + target.Logs.ShouldBe(new[] + { + "OnCompleted:in-scope", "SetResult:", "MoveNext:in-scope", + "OnCompleted:in-scope", "SetResult:", "MoveNext:in-scope", + "OnCompleted:in-scope", "SetResult:", "MoveNext:in-scope", + "OnCompleted:in-scope", "SetResult:", "Dispose:in-scope", + "Completed:in-scope", "Disposed" + }); + } + + [Fact] + public async Task Should_Fail_And_Dispose_The_Scope_When_The_Sequence_Throws() + { + var target = ServiceProvider.GetRequiredService(); + + await Should.ThrowAsync(ToListAsync(target.GetScopeValuesAsync(fail: true))); + + target.Logs.ShouldBe(new[] { "Failed:Failed in scope", "Disposed" }); + } + + [Fact] + public async Task Should_Complete_And_Dispose_The_Scope_When_The_Caller_Stops_Early() + { + var target = ServiceProvider.GetRequiredService(); + + await foreach (var _ in target.GetScopeValuesAsync(fail: true)) + { + break; + } + + target.Logs.ShouldBe(new[] { "Completed:in-scope", "Disposed" }); + } + + [Fact] + public async Task Should_Enumerate_A_Null_Return_Value_As_An_Empty_Sequence() + { + var target = ServiceProvider.GetRequiredService(); + + (await ToListAsync(target.GetItemsAsync())).ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Not_Run_A_Scope_For_A_Method_The_Scope_Interceptor_Does_Not_Intercept() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + (await ToListAsync(target.GetItemsWithoutScopeAsync())).ShouldBe(new[] { 1 }); + + log.Events.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Run_One_Scope_Around_A_Task_Method() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + (await target.GetValueAsync()).ShouldBe(42); + + log.Events.ShouldBe(new[] { "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose" }); + } + + [Fact] + public async Task Should_Run_A_Scope_Around_The_Call_And_A_New_One_Around_Each_Enumeration() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + var sequence = target.GetItemsAsync(); + (await ToListAsync(sequence)).ShouldBe(new[] { 1 }); + (await ToListAsync(sequence)).ShouldBe(new[] { 1 }); + + log.TargetInvocations.ShouldBe(1); + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Scope2.Complete", "Scope2.Dispose", + "Scope3.Begin", "Scope3.Complete", "Scope3.Dispose" + }); + } + + [Fact] + public async Task Should_Not_Begin_An_Enumeration_Scope_Until_The_Sequence_Is_Enumerated() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + var sequence = target.GetItemsAsync(); + await using (sequence.GetAsyncEnumerator()) + { + } + + // Only the scope of the call: getting and disposing the enumerator does not start an enumeration. + log.Events.ShouldBe(new[] { "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose" }); + } + + [Fact] + public async Task Should_Fail_The_Scope_Of_The_Call_And_Not_Wrap_The_Sequence() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + await Should.ThrowAsync(ToListAsync(target.GetItemsAsync(throwOnCall: true))); + + log.Events.ShouldBe(new[] { "Scope1.Begin", "Scope1.Fail:Failed on call", "Scope1.Dispose" }); + } + + [Fact] + public async Task Should_Fail_The_Enumeration_Scope_When_The_Source_Throws_On_GetAsyncEnumerator() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + await Should.ThrowAsync(ToListAsync(target.GetItemsThrowingOnGetAsyncEnumerator())); + + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Scope2.Fail:Failed on GetAsyncEnumerator", "Scope2.Dispose" + }); + } + + [Fact] + public async Task Should_Fail_The_Enumeration_Scope_After_The_Failed_Source_Has_Been_Disposed() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + await Should.ThrowAsync(ToListAsync(target.GetItemsThrowingOnCurrent())); + + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Source.Dispose", "Scope2.Fail:Failed on Current", "Scope2.Dispose" + }); + } + + [Fact] + public async Task Should_Fail_The_Enumeration_Scope_With_The_Exception_Thrown_When_Disposing_The_Failed_Source_Throws() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + var exception = await Should.ThrowAsync(ToListAsync(target.GetItemsThrowingOnCurrent(throwOnDispose: true))); + + exception.Message.ShouldBe("Failed on dispose"); + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Source.Dispose", "Scope2.Fail:Failed on dispose", "Scope2.Dispose" + }); + } + + [Fact] + public async Task Should_Dispose_But_Not_Fail_The_Enumeration_Scope_When_Completing_It_Throws() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + var exception = await Should.ThrowAsync(ToListAsync(target.GetItemsWithFailingCompleteAsync())); + + exception.Message.ShouldBe("Complete failed"); + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Scope2.Complete", "Scope2.Dispose" + }); + } + + [Fact] + public async Task Should_Dispose_The_Enumeration_Scope_When_Failing_It_Throws() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + var exception = await Should.ThrowAsync(ToListAsync(target.GetItemsWithFailingFailAsync())); + + exception.Message.ShouldBe("Fail failed"); + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Scope2.Fail:Source failed", "Scope2.Dispose" + }); + } + + [Fact] + public async Task Should_Fail_The_Enumeration_Scope_When_The_Source_Throws_On_Dispose() + { + var target = ServiceProvider.GetRequiredService(); + var log = ServiceProvider.GetRequiredService(); + + // Stopping early runs the finally block of the source in DisposeAsync, not in MoveNextAsync. + await Should.ThrowAsync(async () => + { + await foreach (var _ in target.GetItemsAsync(throwOnDispose: true)) + { + break; + } + }); + + log.Events.ShouldBe(new[] + { + "Scope1.Begin", "Scope1.Complete", "Scope1.Dispose", + "Scope2.Begin", "Scope2.Fail:Failed on dispose", "Scope2.Dispose" + }); + } + + private static async Task> ToListAsync(IAsyncEnumerable source) + { + var list = new List(); + await foreach (var item in source) + { + list.Add(item); + } + + return list; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionScope_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionScope_Tests.cs new file mode 100644 index 0000000000..c8eab5fc6d --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionScope_Tests.cs @@ -0,0 +1,44 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +namespace Volo.Abp.DynamicProxy; + +public class AbpInterceptionScope_Tests +{ + [Fact] + public async Task Should_Dispose_The_Given_Object_When_Disposed() + { + var disposable = new TestDisposable(); + var scope = new AbpInterceptionScope(disposable); + + await scope.CompleteAsync(CancellationToken.None); + await scope.FailAsync(new InvalidOperationException()); + disposable.IsDisposed.ShouldBeFalse(); + + scope.Dispose(); + disposable.IsDisposed.ShouldBeTrue(); + } + + [Fact] + public async Task Should_Work_Without_A_Disposable() + { + var scope = new AbpInterceptionScope(); + + await scope.CompleteAsync(CancellationToken.None); + await scope.FailAsync(new InvalidOperationException()); + scope.Dispose(); + } + + private class TestDisposable : IDisposable + { + public bool IsDisposed { get; private set; } + + public void Dispose() + { + IsDisposed = true; + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions_Tests.cs new file mode 100644 index 0000000000..6007bda92e --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions_Tests.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +namespace Volo.Abp.DynamicProxy; + +public class AbpMethodInvocationAsyncEnumerableExtensions_Tests +{ + private static readonly AsyncLocal ScopeValue = new(); + + [Fact] + public async Task Should_Keep_The_Scope_When_The_Enumeration_Is_Started_With_A_Suppressed_Flow() + { + var invocation = new TestMethodInvocation(typeof(AbpMethodInvocationAsyncEnumerableExtensions_Tests).GetMethod(nameof(GetScopeValuesAsync))!) + { + ReturnValue = GetScopeValuesAsync() + }; + + invocation.WrapAsyncEnumerable(() => + { + ScopeValue.Value = "in-scope"; + return new AbpInterceptionScope(); + }).ShouldBeTrue(); + + var enumerator = ((IAsyncEnumerable)invocation.ReturnValue).GetAsyncEnumerator(); + ValueTask moveNext; + using (ExecutionContext.SuppressFlow()) + { + moveNext = enumerator.MoveNextAsync(); + + ExecutionContext.IsFlowSuppressed().ShouldBeTrue(); + ScopeValue.Value.ShouldBeNull(); + } + + var values = new List(); + while (await moveNext) + { + values.Add(enumerator.Current); + moveNext = enumerator.MoveNextAsync(); + } + + await enumerator.DisposeAsync(); + + values.ShouldBe(new[] { "in-scope", "in-scope" }); + ScopeValue.Value.ShouldBeNull(); + } + + public static async IAsyncEnumerable GetScopeValuesAsync() + { + await Task.Delay(1); + yield return ScopeValue.Value; + await Task.Delay(1); + yield return ScopeValue.Value; + } + + private class TestMethodInvocation : IAbpMethodInvocation + { + public TestMethodInvocation(MethodInfo method) + { + Method = method; + } + + public object?[] Arguments => Array.Empty(); + + public IReadOnlyDictionary ArgumentsDictionary => new Dictionary(); + + public Type[]? GenericArguments => null; + + public object? TargetObject => null; + + public MethodInfo Method { get; } + + public object ReturnValue { get; set; } = default!; + + public Task ProceedAsync() + { + return Task.CompletedTask; + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableCallerContext.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableCallerContext.cs new file mode 100644 index 0000000000..808094f69f --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableCallerContext.cs @@ -0,0 +1,8 @@ +using System.Threading; + +namespace Volo.Abp.DynamicProxy; + +public static class AsyncEnumerableCallerContext +{ + public static readonly AsyncLocal Value = new(); +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentTestObject.cs new file mode 100644 index 0000000000..8c49fe281a --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentTestObject.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableConcurrentTestObject +{ + public virtual async IAsyncEnumerable GetItemsAsync(int count) + { + for (var i = 1; i <= count; i++) + { + await Task.Yield(); + yield return i; + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableDecoratedTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableDecoratedTestObject.cs new file mode 100644 index 0000000000..68d12af490 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableDecoratedTestObject.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableDecoratedTestObject +{ + public virtual async IAsyncEnumerable GetItemsAsync() + { + await Task.Yield(); + yield return 1; + yield return 2; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedScopedTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedScopedTestObject.cs new file mode 100644 index 0000000000..3f2eeb4bc1 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedScopedTestObject.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableGatedScopedTestObject : AsyncEnumerableScopedTestObject +{ + public virtual async IAsyncEnumerable GetCallerAndScopeValuesAsync() + { + await Task.Yield(); + yield return $"{AsyncEnumerableCallerContext.Value.Value}:{ScopeTestInterceptor.ScopeValue.Value}"; + await Task.Yield(); + yield return $"{AsyncEnumerableCallerContext.Value.Value}:{ScopeTestInterceptor.ScopeValue.Value}"; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedTestObject.cs new file mode 100644 index 0000000000..b28314e45a --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedTestObject.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableGatedTestObject +{ + public virtual async IAsyncEnumerable GetItemsAsync() + { + await Task.Yield(); + yield return 1; + } + + public virtual async IAsyncEnumerable GetCallerValueAsync() + { + await Task.Yield(); + yield return AsyncEnumerableCallerContext.Value.Value; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableInterceptionTargetClass.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableInterceptionTargetClass.cs new file mode 100644 index 0000000000..1d893e3ad5 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableInterceptionTargetClass.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Volo.Abp.TestBase.Logging; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableInterceptionTargetClass : ICanLogOnObject +{ + private int _createAttempts; + + public List Logs { get; } = new List(); + + public virtual async IAsyncEnumerable GetItemsAsync(int count, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + for (var i = 1; i <= count; i++) + { + await Task.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + Logs.Add($"Produce{i}"); + yield return i; + } + } + + public virtual async IAsyncEnumerable GetOneThenWaitAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.Yield(); + yield return 1; + await Task.Delay(Timeout.Infinite, cancellationToken); + yield return 2; + } + + public virtual async IAsyncEnumerable GetOneThenThrowAsync() + { + await Task.Yield(); + yield return 1; + throw new InvalidOperationException("Failed after first item"); + } + + public virtual IAsyncEnumerable GetItemsCreatedOnSecondAttempt() + { + if (Interlocked.Increment(ref _createAttempts) == 1) + { + throw new InvalidOperationException("First attempt failed"); + } + + return GetItemsAsync(1); + } + + public virtual IAsyncEnumerable GetItemsWithOutParameter(out int value) + { + value = 42; + return GetItemsAsync(1); + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableNullReturnValueTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableNullReturnValueTestObject.cs new file mode 100644 index 0000000000..b801076605 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableNullReturnValueTestObject.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableNullReturnValueTestObject +{ + public virtual async IAsyncEnumerable GetItemsAsync() + { + await Task.Yield(); + yield return 1; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopeInterceptorTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopeInterceptorTestObject.cs new file mode 100644 index 0000000000..96f1e6fdc9 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopeInterceptorTestObject.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableScopeInterceptorTestObject +{ + private readonly ScopeEventLog _log; + + public AsyncEnumerableScopeInterceptorTestObject(ScopeEventLog log) + { + _log = log; + } + + public virtual Task GetValueAsync() + { + Interlocked.Increment(ref _log.TargetInvocations); + return Task.FromResult(42); + } + + public virtual async IAsyncEnumerable GetItemsWithoutScopeAsync() + { + await Task.Yield(); + yield return 1; + } + + public virtual IAsyncEnumerable GetItemsAsync(bool throwOnCall = false, bool throwOnDispose = false) + { + Interlocked.Increment(ref _log.TargetInvocations); + if (throwOnCall) + { + throw new InvalidOperationException("Failed on call"); + } + + return ProduceAsync(throwOnDispose); + } + + public virtual IAsyncEnumerable GetItemsThrowingOnGetAsyncEnumerator() + { + Interlocked.Increment(ref _log.TargetInvocations); + return new ThrowingOnGetAsyncEnumeratorSequence(); + } + + public virtual IAsyncEnumerable GetItemsThrowingOnCurrent(bool throwOnDispose = false) + { + Interlocked.Increment(ref _log.TargetInvocations); + return new ThrowingOnCurrentSequence(_log, throwOnDispose); + } + + public virtual async IAsyncEnumerable GetItemsWithFailingCompleteAsync() + { + await Task.Yield(); + yield return 1; + } + + public virtual async IAsyncEnumerable GetItemsWithFailingFailAsync() + { + await Task.Yield(); + yield return 1; + throw new InvalidOperationException("Source failed"); + } + + private class ThrowingOnCurrentSequence : IAsyncEnumerable, IAsyncEnumerator + { + private readonly ScopeEventLog _log; + private readonly bool _throwOnDispose; + + public ThrowingOnCurrentSequence(ScopeEventLog log, bool throwOnDispose) + { + _log = log; + _throwOnDispose = throwOnDispose; + } + + public int Current => throw new InvalidOperationException("Failed on Current"); + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this; + } + + public ValueTask MoveNextAsync() + { + return new ValueTask(true); + } + + public async ValueTask DisposeAsync() + { + await Task.Yield(); + _log.Events.Add("Source.Dispose"); + if (_throwOnDispose) + { + throw new InvalidOperationException("Failed on dispose"); + } + } + } + + private class ThrowingOnGetAsyncEnumeratorSequence : IAsyncEnumerable + { + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + throw new InvalidOperationException("Failed on GetAsyncEnumerator"); + } + } + + private static async IAsyncEnumerable ProduceAsync(bool throwOnDispose) + { + try + { + await Task.Yield(); + yield return 1; + } + finally + { + if (throwOnDispose) + { + throw new InvalidOperationException("Failed on dispose"); + } + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopedTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopedTestObject.cs new file mode 100644 index 0000000000..44d8a4fe78 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopedTestObject.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableScopedTestObject +{ + public List Logs { get; } = new(); + + public virtual async IAsyncEnumerable GetCallerValuesAsync() + { + await Task.Yield(); + yield return AsyncEnumerableCallerContext.Value.Value; + await Task.Yield(); + yield return AsyncEnumerableCallerContext.Value.Value; + } + + public virtual async IAsyncEnumerable GetScopeValuesAsync(bool fail) + { + await Task.Delay(1).ConfigureAwait(false); + yield return ScopeTestInterceptor.ScopeValue.Value; + await Task.Delay(1).ConfigureAwait(false); + if (fail) + { + throw new InvalidOperationException("Failed in scope"); + } + + yield return ScopeTestInterceptor.ScopeValue.Value; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableThrowingInterceptorTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableThrowingInterceptorTestObject.cs new file mode 100644 index 0000000000..b6cace9bdb --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableThrowingInterceptorTestObject.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableThrowingInterceptorTestObject +{ + public bool Invoked { get; private set; } + + public virtual IAsyncEnumerable GetItemsAsync() + { + Invoked = true; + return AsyncEnumerable.Empty(); + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableValueTaskSourceTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableValueTaskSourceTestObject.cs new file mode 100644 index 0000000000..a28b1ee9f4 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableValueTaskSourceTestObject.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableValueTaskSourceTestObject : AsyncEnumerableScopedTestObject +{ + public virtual IAsyncEnumerable GetItemsAsync(bool completeAsynchronously) + { + return new ValueTaskSourceSequence(Logs, completeAsynchronously, completeWithoutExecutionContext: false); + } + + public virtual IAsyncEnumerable GetItemsCompletedWithoutExecutionContextAsync() + { + return new ValueTaskSourceSequence(Logs, completeAsynchronously: true, completeWithoutExecutionContext: true); + } + + /// + /// Records the scope value when its value tasks are completed and their results are read. + /// + private class ValueTaskSourceSequence : IAsyncEnumerable, IAsyncEnumerator, IValueTaskSource, IValueTaskSource + { + private readonly List _logs; + private readonly bool _completeAsynchronously; + private readonly bool _completeWithoutExecutionContext; + private ManualResetValueTaskSourceCore _core; + private bool _result; + private int _current; + + public ValueTaskSourceSequence(List logs, bool completeAsynchronously, bool completeWithoutExecutionContext) + { + _logs = logs; + _completeAsynchronously = completeAsynchronously; + _completeWithoutExecutionContext = completeWithoutExecutionContext; + } + + public int Current => _current; + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this; + } + + public ValueTask MoveNextAsync() + { + _core.Reset(); + Complete(++_current <= 2); + return new ValueTask(this, _core.Version); + } + + public ValueTask DisposeAsync() + { + _core.Reset(); + Complete(false); + return new ValueTask(this, _core.Version); + } + + private void Complete(bool result) + { + if (_completeWithoutExecutionContext) + { + // Completed when the continuation is registered, so it is always registered first. + _result = result; + return; + } + + if (!_completeAsynchronously) + { + _core.SetResult(result); + return; + } + + Task.Run(async () => + { + await Task.Delay(10); + _core.SetResult(result); + }); + } + + bool IValueTaskSource.GetResult(short token) + { + _logs.Add($"MoveNext:{ScopeTestInterceptor.ScopeValue.Value}"); + return _core.GetResult(token); + } + + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _core.GetStatus(token); + + void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + OnCompleted(continuation, state, token, flags); + } + + void IValueTaskSource.GetResult(short token) + { + _logs.Add($"Dispose:{ScopeTestInterceptor.ScopeValue.Value}"); + _core.GetResult(token); + } + + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _core.GetStatus(token); + + void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + OnCompleted(continuation, state, token, flags); + } + + private void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + _core.OnCompleted(continuation, state, token, flags); + + if (!_completeWithoutExecutionContext) + { + return; + } + + _logs.Add($"OnCompleted:{ScopeTestInterceptor.ScopeValue.Value}"); + + // Like an I/O completion, the value task is completed on a thread without the execution context of the awaiter. + using (ExecutionContext.SuppressFlow()) + { + Task.Run(async () => + { + await Task.Delay(10); + _logs.Add($"SetResult:{ScopeTestInterceptor.ScopeValue.Value}"); + _core.SetResult(_result); + }); + } + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableWrongReturnValueTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableWrongReturnValueTestObject.cs new file mode 100644 index 0000000000..161f733fc5 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableWrongReturnValueTestObject.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableWrongReturnValueTestObject +{ + public virtual IAsyncEnumerable GetItemsAsync() + { + return AsyncEnumerable.Empty(); + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/CachedTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/CachedTestObject.cs index 6bfc808d0e..dac91e767e 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/CachedTestObject.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/CachedTestObject.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -16,4 +17,11 @@ public class CachedTestObject await Task.Delay(5); return v; } + + public virtual async IAsyncEnumerable GetValuesAsync(int v) + { + await Task.Delay(5); + yield return v; + yield return v + 1; + } } diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/EventLoggingScopeInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/EventLoggingScopeInterceptor.cs new file mode 100644 index 0000000000..e89be8e7db --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/EventLoggingScopeInterceptor.cs @@ -0,0 +1,77 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class EventLoggingScopeInterceptor : AbpScopeInterceptor +{ + private readonly ScopeEventLog _log; + private int _scopeCount; + + public EventLoggingScopeInterceptor(ScopeEventLog log) + { + _log = log; + } + + protected override bool ShouldIntercept(IAbpMethodInvocation invocation) + { + return invocation.Method.Name != nameof(AsyncEnumerableScopeInterceptorTestObject.GetItemsWithoutScopeAsync) && + base.ShouldIntercept(invocation); + } + + protected override IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation) + { + var name = $"Scope{Interlocked.Increment(ref _scopeCount)}"; + _log.Events.Add($"{name}.Begin"); + + // Only the scopes of the enumerations fail, so the call succeeds. + var isEnumeration = name != "Scope1"; + return new EventLoggingScope( + _log, + name, + failOnComplete: isEnumeration && invocation.Method.Name == nameof(AsyncEnumerableScopeInterceptorTestObject.GetItemsWithFailingCompleteAsync), + failOnFail: isEnumeration && invocation.Method.Name == nameof(AsyncEnumerableScopeInterceptorTestObject.GetItemsWithFailingFailAsync)); + } + + private class EventLoggingScope : IAbpInterceptionScope + { + private readonly ScopeEventLog _log; + private readonly string _name; + private readonly bool _failOnComplete; + private readonly bool _failOnFail; + + public EventLoggingScope(ScopeEventLog log, string name, bool failOnComplete, bool failOnFail) + { + _log = log; + _name = name; + _failOnComplete = failOnComplete; + _failOnFail = failOnFail; + } + + public async Task CompleteAsync(CancellationToken cancellationToken) + { + _log.Events.Add($"{_name}.Complete"); + if (_failOnComplete) + { + await Task.Yield(); + throw new InvalidOperationException("Complete failed"); + } + } + + public async Task FailAsync(Exception exception) + { + _log.Events.Add($"{_name}.Fail:{exception.Message}"); + if (_failOnFail) + { + await Task.Yield(); + throw new InvalidOperationException("Fail failed"); + } + } + + public void Dispose() + { + _log.Events.Add($"{_name}.Dispose"); + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/GatedTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/GatedTestInterceptor.cs new file mode 100644 index 0000000000..5a8fc3bef9 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/GatedTestInterceptor.cs @@ -0,0 +1,14 @@ +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class GatedTestInterceptor : AbpInterceptor +{ + public TaskCompletionSource Gate { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override async Task InterceptAsync(IAbpMethodInvocation invocation) + { + await Gate.Task; + await invocation.ProceedAsync(); + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/MultiplyingTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/MultiplyingTestInterceptor.cs new file mode 100644 index 0000000000..2f00c5f307 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/MultiplyingTestInterceptor.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class MultiplyingTestInterceptor : AbpInterceptor +{ + public override async Task InterceptAsync(IAbpMethodInvocation invocation) + { + await invocation.ProceedAsync(); + invocation.ReturnValue = MultiplyAsync((IAsyncEnumerable)invocation.ReturnValue); + } + + private static async IAsyncEnumerable MultiplyAsync(IAsyncEnumerable source) + { + await foreach (var item in source) + { + yield return item * 10; + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/NullReturnValueTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/NullReturnValueTestInterceptor.cs new file mode 100644 index 0000000000..f7509c6023 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/NullReturnValueTestInterceptor.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class NullReturnValueTestInterceptor : AbpInterceptor +{ + public override Task InterceptAsync(IAbpMethodInvocation invocation) + { + invocation.ReturnValue = null; + return Task.CompletedTask; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/RetryOnceTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/RetryOnceTestInterceptor.cs new file mode 100644 index 0000000000..2e9903c8d6 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/RetryOnceTestInterceptor.cs @@ -0,0 +1,19 @@ +using System; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class RetryOnceTestInterceptor : AbpInterceptor +{ + public override async Task InterceptAsync(IAbpMethodInvocation invocation) + { + try + { + await invocation.ProceedAsync(); + } + catch (InvalidOperationException e) when (e.Message == "First attempt failed") + { + await invocation.ProceedAsync(); + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeEventLog.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeEventLog.cs new file mode 100644 index 0000000000..889cb61958 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeEventLog.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace Volo.Abp.DynamicProxy; + +public class ScopeEventLog +{ + public List Events { get; } = new(); + + public int TargetInvocations; +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeTestInterceptor.cs new file mode 100644 index 0000000000..685c3fcb83 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeTestInterceptor.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class ScopeTestInterceptor : AbpInterceptor +{ + public static readonly AsyncLocal ScopeValue = new(); + + public override async Task InterceptAsync(IAbpMethodInvocation invocation) + { + await invocation.ProceedAsync(); + + var logs = ((AsyncEnumerableScopedTestObject)invocation.TargetObject).Logs; + invocation.WrapAsyncEnumerable(() => + { + ScopeValue.Value = "in-scope"; + return new LoggingScope(logs); + }); + } + + private class LoggingScope : IAbpInterceptionScope + { + private readonly List _logs; + + public LoggingScope(List logs) + { + _logs = logs; + } + + public Task CompleteAsync(CancellationToken cancellationToken) + { + _logs.Add($"Completed:{ScopeValue.Value}"); + return Task.CompletedTask; + } + + public Task FailAsync(Exception exception) + { + _logs.Add($"Failed:{exception.Message}"); + return Task.CompletedTask; + } + + public void Dispose() + { + _logs.Add("Disposed"); + } + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/WrongReturnValueTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/WrongReturnValueTestInterceptor.cs new file mode 100644 index 0000000000..710cec51f7 --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/WrongReturnValueTestInterceptor.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class WrongReturnValueTestInterceptor : AbpInterceptor +{ + public override Task InterceptAsync(IAbpMethodInvocation invocation) + { + invocation.ReturnValue = new List { 1 }; + return Task.CompletedTask; + } +} From d8509b32b9c99a07f50e58c1d1067ee6f1a2f9ad Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:01:55 +0800 Subject: [PATCH 02/10] Support IAsyncEnumerable in unit of work and change tracking interceptors --- .../ChangeTrackingInterceptor.cs | 15 +- .../Abp/Uow/UnitOfWorkInterceptionScope.cs | 53 +++ .../Volo/Abp/Uow/UnitOfWorkInterceptor.cs | 37 +- .../AsyncEnumerable_Interception_Tests.cs | 395 ++++++++++++++++++ .../UnitOfWorkInterceptor_BeginScope_Tests.cs | 91 ++++ 5 files changed, 589 insertions(+), 2 deletions(-) create mode 100644 framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptionScope.cs create mode 100644 framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs create mode 100644 framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/UnitOfWorkInterceptor_BeginScope_Tests.cs diff --git a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/ChangeTracking/ChangeTrackingInterceptor.cs b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/ChangeTracking/ChangeTrackingInterceptor.cs index 307e2dee6a..d24dec48c9 100644 --- a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/ChangeTracking/ChangeTrackingInterceptor.cs +++ b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/ChangeTracking/ChangeTrackingInterceptor.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.DynamicProxy; +using Volo.Abp.Reflection; namespace Volo.Abp.Domain.ChangeTracking; @@ -16,15 +17,27 @@ public class ChangeTrackingInterceptor : AbpInterceptor, ITransientDependency public async override Task InterceptAsync(IAbpMethodInvocation invocation) { - if (!ChangeTrackingHelper.IsEntityChangeTrackingMethod(invocation.Method, out var changeTrackingAttribute)) + var method = invocation.Method; + if (!ChangeTrackingHelper.IsEntityChangeTrackingMethod(method, out var changeTrackingAttribute)) { await invocation.ProceedAsync(); return; } + if (TypeHelper.IsAsyncEnumerable(method.ReturnType)) + { + await InterceptAsyncEnumerableAsync(invocation, changeTrackingAttribute); + return; + } + using (_entityChangeTrackingProvider.Change(changeTrackingAttribute?.IsEnabled)) { await invocation.ProceedAsync(); } } + + private Task InterceptAsyncEnumerableAsync(IAbpMethodInvocation invocation, EntityChangeTrackingAttribute? changeTrackingAttribute) + { + return invocation.ProceedInScopeAsync(() => new AbpInterceptionScope(_entityChangeTrackingProvider.Change(changeTrackingAttribute?.IsEnabled))); + } } diff --git a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptionScope.cs b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptionScope.cs new file mode 100644 index 0000000000..a4dd600004 --- /dev/null +++ b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptionScope.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.DynamicProxy; + +namespace Volo.Abp.Uow; + +internal class UnitOfWorkInterceptionScope : IAbpInterceptionScope +{ + private readonly IServiceScope _serviceScope; + private readonly IUnitOfWorkManager _unitOfWorkManager; + + // The unit of work begun by this scope, or null if it initialized the reserved one. + private readonly IUnitOfWork? _unitOfWork; + + public UnitOfWorkInterceptionScope(IServiceScope serviceScope, IUnitOfWorkManager unitOfWorkManager, IUnitOfWork? unitOfWork) + { + _serviceScope = serviceScope; + _unitOfWorkManager = unitOfWorkManager; + _unitOfWork = unitOfWork; + } + + public async Task CompleteAsync(CancellationToken cancellationToken) + { + if (_unitOfWork != null) + { + await _unitOfWork.CompleteAsync(cancellationToken); + } + else if (_unitOfWorkManager.Current != null) + { + await _unitOfWorkManager.Current.SaveChangesAsync(cancellationToken); + } + } + + public Task FailAsync(Exception exception) + { + // Disposing the unit of work without completing it rolls it back; the owner of an outer or reserved one decides for itself. + return Task.CompletedTask; + } + + public void Dispose() + { + try + { + _unitOfWork?.Dispose(); + } + finally + { + _serviceScope.Dispose(); + } + } +} diff --git a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptor.cs b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptor.cs index 2403405fbd..2ff7d7465e 100644 --- a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptor.cs +++ b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWorkInterceptor.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp.DependencyInjection; using Volo.Abp.DynamicProxy; +using Volo.Abp.Reflection; namespace Volo.Abp.Uow; @@ -18,12 +19,19 @@ public class UnitOfWorkInterceptor : AbpInterceptor, ITransientDependency public override async Task InterceptAsync(IAbpMethodInvocation invocation) { - if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute)) + var method = invocation.Method; + if (!UnitOfWorkHelper.IsUnitOfWorkMethod(method, out var unitOfWorkAttribute)) { await invocation.ProceedAsync(); return; } + if (TypeHelper.IsAsyncEnumerable(method.ReturnType)) + { + await InterceptAsyncEnumerableAsync(invocation, unitOfWorkAttribute); + return; + } + using (var scope = _serviceScopeFactory.CreateScope()) { var options = CreateOptions(scope.ServiceProvider, invocation, unitOfWorkAttribute); @@ -51,6 +59,33 @@ public class UnitOfWorkInterceptor : AbpInterceptor, ITransientDependency } } + private Task InterceptAsyncEnumerableAsync(IAbpMethodInvocation invocation, UnitOfWorkAttribute? unitOfWorkAttribute) + { + return invocation.ProceedInScopeAsync(() => BeginScope(invocation, unitOfWorkAttribute)); + } + + private IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation, UnitOfWorkAttribute? unitOfWorkAttribute) + { + var scope = _serviceScopeFactory.CreateScope(); + try + { + var options = CreateOptions(scope.ServiceProvider, invocation, unitOfWorkAttribute); + var unitOfWorkManager = scope.ServiceProvider.GetRequiredService(); + + //Trying to begin a reserved UOW by AbpUnitOfWorkMiddleware + var unitOfWork = unitOfWorkManager.TryBeginReserved(UnitOfWork.UnitOfWorkReservationName, options) + ? null + : unitOfWorkManager.Begin(options); + + return new UnitOfWorkInterceptionScope(scope, unitOfWorkManager, unitOfWork); + } + catch + { + scope.Dispose(); + throw; + } + } + private AbpUnitOfWorkOptions CreateOptions(IServiceProvider serviceProvider, IAbpMethodInvocation invocation, UnitOfWorkAttribute? unitOfWorkAttribute) { var options = new AbpUnitOfWorkOptions(); diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs new file mode 100644 index 0000000000..8b32360f9c --- /dev/null +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs @@ -0,0 +1,395 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Volo.Abp.Application.Services; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.ChangeTracking; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.TestApp.Domain; +using Volo.Abp.Uow; +using Xunit; + +namespace Volo.Abp.EntityFrameworkCore.AsyncEnumerable; + +public interface IStreamingPeopleAppService : IApplicationService +{ + IAsyncEnumerable GetNamesAsync(); + + IAsyncEnumerable IncreaseAgesAsync(int failAfter = -1); + + IAsyncEnumerable GetUnitOfWorkIdsAsync(); + + IAsyncEnumerable GetIsTransactionalAsync(); + + IAsyncEnumerable StreamIsTransactionalAsync(); + + IAsyncEnumerable GetNamesWithWorkBeforeReturningAsync(); + + IAsyncEnumerable GetItemsWithOutParameter(out bool hadUnitOfWork); + + IAsyncEnumerable IncreaseAgeThenFailOnCurrent(); + + IAsyncEnumerable GetChangeTrackingStatesAsync(); +} + +public class StreamingTracker : ISingletonDependency +{ + public bool SourceDisposed { get; set; } + + public bool UnitOfWorkCompleted { get; set; } + + public bool CallUnitOfWorkCompleted { get; set; } +} + +public class StreamingPeopleAppService : ApplicationService, IStreamingPeopleAppService +{ + private readonly IRepository _personRepository; + private readonly StreamingTracker _tracker; + + public StreamingPeopleAppService(IRepository personRepository, StreamingTracker tracker) + { + _personRepository = personRepository; + _tracker = tracker; + } + + public virtual async IAsyncEnumerable GetNamesAsync() + { + var queryable = await _personRepository.GetQueryableAsync(); + await foreach (var person in queryable.OrderBy(p => p.Name).AsAsyncEnumerable()) + { + yield return person.Name; + } + } + + public virtual async IAsyncEnumerable IncreaseAgesAsync(int failAfter = -1) + { + CurrentUnitOfWork!.OnCompleted(() => + { + _tracker.UnitOfWorkCompleted = true; + return Task.CompletedTask; + }); + + try + { + var people = await _personRepository.GetListAsync(); + var count = 0; + foreach (var person in people.OrderBy(p => p.Name)) + { + if (++count == failAfter) + { + throw new InvalidOperationException("Failed while streaming"); + } + + person.Age += 100; + await _personRepository.UpdateAsync(person, autoSave: true); + + yield return person.Name; + } + } + finally + { + _tracker.SourceDisposed = true; + } + } + + public virtual async IAsyncEnumerable GetUnitOfWorkIdsAsync() + { + await Task.Yield(); + yield return CurrentUnitOfWork?.Id; + } + + public virtual async IAsyncEnumerable GetIsTransactionalAsync() + { + await Task.Yield(); + yield return CurrentUnitOfWork!.Options.IsTransactional; + } + + public virtual async IAsyncEnumerable StreamIsTransactionalAsync() + { + await Task.Yield(); + yield return CurrentUnitOfWork!.Options.IsTransactional; + } + + public virtual IAsyncEnumerable GetNamesWithWorkBeforeReturningAsync() + { + CurrentUnitOfWork!.OnCompleted(() => + { + _tracker.CallUnitOfWorkCompleted = true; + return Task.CompletedTask; + }); + + return GetNamesCoreAsync(); + } + + public virtual IAsyncEnumerable GetItemsWithOutParameter(out bool hadUnitOfWork) + { + hadUnitOfWork = CurrentUnitOfWork != null; + return GetOneAsync(); + } + + [DisableEntityChangeTracking] + public virtual async IAsyncEnumerable GetChangeTrackingStatesAsync() + { + var changeTrackingProvider = LazyServiceProvider.LazyGetRequiredService(); + await Task.Delay(1).ConfigureAwait(false); + yield return changeTrackingProvider.Enabled; + await Task.Delay(1).ConfigureAwait(false); + yield return changeTrackingProvider.Enabled; + } + + public virtual IAsyncEnumerable IncreaseAgeThenFailOnCurrent() + { + return new FailingCurrentEnumerable(_personRepository); + } + + private async IAsyncEnumerable GetNamesCoreAsync() + { + var queryable = await _personRepository.GetQueryableAsync(); + await foreach (var person in queryable.OrderBy(p => p.Name).AsAsyncEnumerable()) + { + yield return person.Name; + } + } + + private static async IAsyncEnumerable GetOneAsync() + { + await Task.Yield(); + yield return 1; + } + + private class FailingCurrentEnumerable : IAsyncEnumerable, IAsyncEnumerator + { + private readonly IRepository _personRepository; + + public FailingCurrentEnumerable(IRepository personRepository) + { + _personRepository = personRepository; + } + + public string Current => throw new InvalidOperationException("Failed to read the current item"); + + public IAsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken = default) => this; + + public async ValueTask MoveNextAsync() + { + foreach (var person in await _personRepository.GetListAsync()) + { + person.Age += 100; + await _personRepository.UpdateAsync(person, autoSave: true); + } + + return true; + } + + public ValueTask DisposeAsync() => default; + } +} + +public class AsyncEnumerable_Interception_Tests : EntityFrameworkCoreTestBase +{ + private readonly IStreamingPeopleAppService _appService; + private readonly IRepository _personRepository; + private readonly IUnitOfWorkManager _unitOfWorkManager; + private readonly StreamingTracker _tracker; + + public AsyncEnumerable_Interception_Tests() + { + _appService = GetRequiredService(); + _personRepository = GetRequiredService>(); + _unitOfWorkManager = GetRequiredService(); + _tracker = GetRequiredService(); + } + + [Fact] + public async Task Should_Have_Unit_Of_Work_While_Enumerating() + { + _unitOfWorkManager.Current.ShouldBeNull(); + + var ids = await _appService.GetUnitOfWorkIdsAsync().ToStreamListAsync(); + + ids.Single().ShouldNotBeNull(); + } + + [Fact] + public async Task Should_Decide_Transaction_Like_Task_Returning_Methods() + { + (await _appService.GetIsTransactionalAsync().ToStreamListAsync()).ShouldBe(new[] { false }); + (await _appService.StreamIsTransactionalAsync().ToStreamListAsync()).ShouldBe(new[] { true }); + } + + [Fact] + public async Task Should_Query_Database_While_Enumerating() + { + var names = await _appService.GetNamesAsync().ToStreamListAsync(); + + names.ShouldContain("Douglas"); + } + + [Fact] + public async Task Should_Save_Changes_After_Enumeration_Completed() + { + await InsertPersonAsync("Aaron"); + var originalAges = await GetAgesAsync(); + + var names = await _appService.IncreaseAgesAsync().ToStreamListAsync(); + + names.Count.ShouldBe(originalAges.Count); + _tracker.UnitOfWorkCompleted.ShouldBeTrue(); + var newAges = await GetAgesAsync(); + foreach (var (id, age) in originalAges) + { + newAges[id].ShouldBe(age + 100); + } + } + + [Fact] + public async Task Should_Rollback_When_Enumeration_Throws_After_Items_Were_Delivered() + { + await InsertPersonAsync("Aaron"); + var originalAges = await GetAgesAsync(); + var names = new List(); + + var exception = await Should.ThrowAsync(async () => + { + await foreach (var name in _appService.IncreaseAgesAsync(failAfter: 2)) + { + names.Add(name); + } + }); + + exception.Message.ShouldBe("Failed while streaming"); + names.ShouldBe(new[] { "Aaron" }); + _tracker.SourceDisposed.ShouldBeTrue(); + _tracker.UnitOfWorkCompleted.ShouldBeFalse(); + (await GetAgesAsync()).ShouldBe(originalAges); + } + + [Fact] + public async Task Should_Complete_Unit_Of_Work_When_Consumer_Stops_Early() + { + var aaronId = await InsertPersonAsync("Aaron"); + var originalAges = await GetAgesAsync(); + + await foreach (var name in _appService.IncreaseAgesAsync()) + { + name.ShouldBe("Aaron"); + break; + } + + _tracker.SourceDisposed.ShouldBeTrue(); + _tracker.UnitOfWorkCompleted.ShouldBeTrue(); + var newAges = await GetAgesAsync(); + foreach (var (id, age) in originalAges) + { + newAges[id].ShouldBe(id == aaronId ? age + 100 : age); + } + } + + [Fact] + public async Task Should_Join_Outer_Unit_Of_Work() + { + await WithUnitOfWorkAsync(async () => + { + var outerId = _unitOfWorkManager.Current!.Id; + + await foreach (var id in _appService.GetUnitOfWorkIdsAsync()) + { + id.ShouldBe(outerId); + } + + await foreach (var _ in _appService.GetNamesAsync()) + { + // The consumer uses the same DbContext as the stream between two items. + (await _personRepository.GetCountAsync()).ShouldBeGreaterThan(0); + } + }); + } + + [Fact] + public async Task Should_Leave_Completing_The_Reserved_Unit_Of_Work_To_Its_Owner() + { + await InsertPersonAsync("Aaron"); + var originalAges = await GetAgesAsync(); + + using (var reservedUnitOfWork = _unitOfWorkManager.Reserve(UnitOfWork.UnitOfWorkReservationName)) + { + (await _appService.IncreaseAgesAsync().ToStreamListAsync()).Count.ShouldBe(originalAges.Count); + + reservedUnitOfWork.IsCompleted.ShouldBeFalse(); + _tracker.UnitOfWorkCompleted.ShouldBeFalse(); + + await reservedUnitOfWork.CompleteAsync(); + } + + _tracker.UnitOfWorkCompleted.ShouldBeTrue(); + var newAges = await GetAgesAsync(); + foreach (var (id, age) in originalAges) + { + newAges[id].ShouldBe(age + 100); + } + } + + [Fact] + public async Task Should_Apply_Change_Tracking_Attribute_While_Enumerating() + { + (await _appService.GetChangeTrackingStatesAsync().ToStreamListAsync()).ShouldBe(new bool?[] { false, false }); + } + + [Fact] + public async Task Should_Have_Unit_Of_Work_When_Creating_The_Sequence() + { + var names = await _appService.GetNamesWithWorkBeforeReturningAsync().ToStreamListAsync(); + + names.ShouldContain("Douglas"); + _tracker.CallUnitOfWorkCompleted.ShouldBeTrue(); + } + + [Fact] + public async Task Should_Have_Unit_Of_Work_When_Calling_Method_With_Out_Parameters() + { + var sequence = _appService.GetItemsWithOutParameter(out var hadUnitOfWork); + + hadUnitOfWork.ShouldBeTrue(); + (await sequence.ToStreamListAsync()).ShouldBe(new[] { 1 }); + } + + [Fact] + public async Task Should_Rollback_When_Reading_The_Current_Item_Throws() + { + var originalAges = await GetAgesAsync(); + + await Should.ThrowAsync(_appService.IncreaseAgeThenFailOnCurrent().ToStreamListAsync()); + + (await GetAgesAsync()).ShouldBe(originalAges); + } + + private async Task InsertPersonAsync(string name) + { + var id = Guid.NewGuid(); + await WithUnitOfWorkAsync(() => _personRepository.InsertAsync(new Person(id, name, 20))); + return id; + } + + private async Task> GetAgesAsync() + { + return await WithUnitOfWorkAsync(async () => + (await _personRepository.GetListAsync(includeDetails: false)).ToDictionary(p => p.Id, p => p.Age)); + } +} + +internal static class AsyncEnumerableTestExtensions +{ + public static async Task> ToStreamListAsync(this IAsyncEnumerable source) + { + var list = new List(); + await foreach (var item in source) + { + list.Add(item); + } + + return list; + } +} diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/UnitOfWorkInterceptor_BeginScope_Tests.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/UnitOfWorkInterceptor_BeginScope_Tests.cs new file mode 100644 index 0000000000..3e5e029211 --- /dev/null +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/UnitOfWorkInterceptor_BeginScope_Tests.cs @@ -0,0 +1,91 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Shouldly; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.TestApp.Domain; +using Volo.Abp.Uow; +using Xunit; + +namespace Volo.Abp.EntityFrameworkCore.AsyncEnumerable; + +public class UnitOfWorkInterceptor_BeginScope_Tests : EntityFrameworkCoreTestBase +{ + protected override void AfterAddApplication(IServiceCollection services) + { + services.AddSingleton(); + services.Replace(ServiceDescriptor.Scoped()); + } + + [Fact] + public async Task Should_Dispose_The_Service_Scope_If_Beginning_The_Unit_Of_Work_Fails() + { + var state = GetRequiredService(); + var repository = GetRequiredService>(); + state.Fail = true; + + await Should.ThrowAsync(() => repository.GetListAsync()); + + state.IsFailedProviderDisposed.ShouldBeTrue(); + } + + [Fact] + public async Task Should_Dispose_The_Service_Scope_If_Beginning_The_Unit_Of_Work_Of_An_Enumeration_Fails() + { + var state = GetRequiredService(); + var sequence = GetRequiredService().GetNamesAsync(); + state.Fail = true; + + await Should.ThrowAsync(async () => + { + await foreach (var _ in sequence) + { + } + }); + + state.IsFailedProviderDisposed.ShouldBeTrue(); + } + + public class FailingTransactionBehaviourState + { + public bool Fail { get; set; } + + public bool IsFailedProviderDisposed { get; set; } + } + + [DisableConventionalRegistration] + public class FailingTransactionBehaviourProvider : IUnitOfWorkTransactionBehaviourProvider, IDisposable + { + private readonly FailingTransactionBehaviourState _state; + private bool _hasFailed; + + public FailingTransactionBehaviourProvider(FailingTransactionBehaviourState state) + { + _state = state; + } + + public bool? IsTransactional + { + get + { + if (_state.Fail) + { + _hasFailed = true; + throw new InvalidOperationException("Failed to get the transaction behaviour"); + } + + return null; + } + } + + public void Dispose() + { + if (_hasFailed) + { + _state.IsFailedProviderDisposed = true; + } + } + } +} From 307024eb02730bdd995372201fae51d9feaa3954 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:01:55 +0800 Subject: [PATCH 03/10] Add an audit log action for each async enumeration --- .../Abp/Auditing/AuditLogEnumerationScope.cs | 104 ++++ .../Volo/Abp/Auditing/AuditingInterceptor.cs | 70 +++ ...ting_AsyncEnumerable_ScopeFailure_Tests.cs | 131 ++++++ .../Auditing_AsyncEnumerable_Tests.cs | 443 ++++++++++++++++++ 4 files changed, 748 insertions(+) create mode 100644 framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditLogEnumerationScope.cs create mode 100644 framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_ScopeFailure_Tests.cs create mode 100644 framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs diff --git a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditLogEnumerationScope.cs b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditLogEnumerationScope.cs new file mode 100644 index 0000000000..33f320104c --- /dev/null +++ b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditLogEnumerationScope.cs @@ -0,0 +1,104 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.DynamicProxy; +using Volo.Abp.Uow; + +namespace Volo.Abp.Auditing; + +internal class AuditLogEnumerationScope : IAbpInterceptionScope +{ + private readonly IServiceScope _serviceScope; + private readonly AuditLogInfo _auditLog; + private readonly AuditLogActionInfo? _auditLogAction; + private readonly IAuditLogSaveHandle? _saveHandle; + private readonly Func> _shouldWriteAuditLog; + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); + + public AuditLogEnumerationScope( + IServiceScope serviceScope, + AuditLogInfo auditLog, + AuditLogActionInfo? auditLogAction, + IAuditLogSaveHandle? saveHandle, + Func> shouldWriteAuditLog) + { + _serviceScope = serviceScope; + _auditLog = auditLog; + _auditLogAction = auditLogAction; + _saveHandle = saveHandle; + _shouldWriteAuditLog = shouldWriteAuditLog; + } + + public Task CompleteAsync(CancellationToken cancellationToken) + { + AddAuditLogAction(); + return SaveAsync(_auditLog.Exceptions.Any()); + } + + public Task FailAsync(Exception exception) + { + AddAuditLogAction(); + if (!_auditLog.Exceptions.Contains(exception)) + { + _auditLog.Exceptions.Add(exception); + } + + return SaveAsync(hasError: true); + } + + public void Dispose() + { + try + { + _saveHandle?.Dispose(); + } + finally + { + _serviceScope.Dispose(); + } + } + + private void AddAuditLogAction() + { + _stopwatch.Stop(); + if (_auditLogAction != null) + { + _auditLogAction.ExecutionDuration = Convert.ToInt32(_stopwatch.Elapsed.TotalMilliseconds); + _auditLog.Actions.Add(_auditLogAction); + } + } + + private async Task SaveAsync(bool hasError) + { + if (_saveHandle == null) + { + return; + } + + if (!await _shouldWriteAuditLog(hasError)) + { + return; + } + + var unitOfWorkManager = _serviceScope.ServiceProvider.GetRequiredService(); + if (unitOfWorkManager.Current != null) + { + try + { + await unitOfWorkManager.Current.SaveChangesAsync(); + } + catch (Exception ex) + { + if (!_auditLog.Exceptions.Contains(ex)) + { + _auditLog.Exceptions.Add(ex); + } + } + } + + await _saveHandle.SaveAsync(); + } +} diff --git a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs index 0dd70d68e7..f27d7bf66d 100644 --- a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs +++ b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Options; using Volo.Abp.Aspects; using Volo.Abp.DependencyInjection; using Volo.Abp.DynamicProxy; +using Volo.Abp.Reflection; using Volo.Abp.Uow; using Volo.Abp.Users; @@ -14,6 +15,8 @@ namespace Volo.Abp.Auditing; public class AuditingInterceptor : AbpInterceptor, ITransientDependency { + public const string AsyncEnumerationPropertyName = "AsyncEnumeration"; + private readonly IServiceScopeFactory _serviceScopeFactory; public AuditingInterceptor(IServiceScopeFactory serviceScopeFactory) @@ -46,6 +49,11 @@ public class AuditingInterceptor : AbpInterceptor, ITransientDependency await ProcessWithNewAuditingScopeAsync(invocation, auditingOptions, currentUser, auditingManager, auditingHelper, unitOfWorkManager); } } + + if (TypeHelper.IsAsyncEnumerable(invocation.Method.ReturnType)) + { + WrapAsyncEnumerable(invocation); + } } protected virtual bool ShouldIntercept(IAbpMethodInvocation invocation, @@ -165,6 +173,68 @@ public class AuditingInterceptor : AbpInterceptor, ITransientDependency } } + private void WrapAsyncEnumerable(IAbpMethodInvocation invocation) + { + invocation.WrapAsyncEnumerable(() => BeginEnumerationScope(invocation)); + } + + private IAbpInterceptionScope BeginEnumerationScope(IAbpMethodInvocation invocation) + { + var serviceScope = _serviceScopeFactory.CreateScope(); + IAuditLogSaveHandle? saveHandle = null; + try + { + var serviceProvider = serviceScope.ServiceProvider; + var auditingHelper = serviceProvider.GetRequiredService(); + if (!auditingHelper.IsAuditingEnabled()) + { + return new AbpInterceptionScope(serviceScope); + } + + var options = serviceProvider.GetRequiredService>().Value; + var auditingManager = serviceProvider.GetRequiredService(); + + if (auditingManager.Current == null) + { + saveHandle = auditingManager.BeginScope(); + } + + var auditLog = auditingManager.Current!.Log; + + AuditLogActionInfo? auditLogAction = null; + if (!options.DisableLogActionInfo) + { + auditLogAction = auditingHelper.CreateAuditLogAction( + auditLog, + invocation.TargetObject?.GetType(), + invocation.Method, + invocation.Arguments + ); + auditLogAction.ExtraProperties[AsyncEnumerationPropertyName] = true; + } + + return new AuditLogEnumerationScope( + serviceScope, + auditLog, + auditLogAction, + saveHandle, + hasError => ShouldWriteAuditLogAsync(invocation, auditLog, options, serviceProvider.GetRequiredService(), hasError)); + } + catch + { + try + { + saveHandle?.Dispose(); + } + finally + { + serviceScope.Dispose(); + } + + throw; + } + } + private async Task ShouldWriteAuditLogAsync( IAbpMethodInvocation invocation, AuditLogInfo auditLogInfo, diff --git a/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_ScopeFailure_Tests.cs b/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_ScopeFailure_Tests.cs new file mode 100644 index 0000000000..1279d4fcbc --- /dev/null +++ b/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_ScopeFailure_Tests.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using Shouldly; +using Volo.Abp.Clients; +using Volo.Abp.DependencyInjection; +using Volo.Abp.MultiTenancy; +using Volo.Abp.Threading; +using Volo.Abp.Timing; +using Volo.Abp.Tracing; +using Volo.Abp.Users; +using Xunit; + +namespace Volo.Abp.Auditing; + +public class Auditing_AsyncEnumerable_ScopeFailure_Tests : AbpAuditingTestBase +{ + private readonly IAuditingManager _auditingManager; + private readonly FailingAuditingHelperState _state; + private readonly Auditing_AsyncEnumerable_Tests.MyStreamingAuditedObject _target; + + public Auditing_AsyncEnumerable_ScopeFailure_Tests() + { + _auditingManager = GetRequiredService(); + _state = GetRequiredService(); + _target = GetRequiredService(); + } + + protected override void AfterAddApplication(IServiceCollection services) + { + services.AddSingleton(); + services.Replace(ServiceDescriptor.Transient()); + services.Replace(ServiceDescriptor.Singleton(Substitute.For())); + } + + [Fact] + public async Task Should_Dispose_The_Scope_Of_A_New_Audit_Log_If_Beginning_The_Enumeration_Audit_Fails() + { + var sequence = _target.StreamItemsAsync(1); + _state.FailToCreateAction = true; + + await Should.ThrowAsync(ToListAsync(sequence)); + + _state.IsFailedHelperDisposed.ShouldBeTrue(); + _auditingManager.Current.ShouldBeNull(); + } + + [Fact] + public async Task Should_Dispose_The_Scope_If_Beginning_The_Enumeration_Audit_In_The_Current_Audit_Log_Fails() + { + using (_auditingManager.BeginScope()) + { + var auditLog = _auditingManager.Current!.Log; + var sequence = _target.StreamItemsAsync(1); + _state.FailToCreateAction = true; + + await Should.ThrowAsync(ToListAsync(sequence)); + + _state.IsFailedHelperDisposed.ShouldBeTrue(); + _auditingManager.Current!.Log.ShouldBeSameAs(auditLog); + } + } + + private static async Task> ToListAsync(IAsyncEnumerable source) + { + var list = new List(); + await foreach (var item in source) + { + list.Add(item); + } + + return list; + } + + public class FailingAuditingHelperState + { + public bool FailToCreateAction { get; set; } + + public bool IsFailedHelperDisposed { get; set; } + } + + [DisableConventionalRegistration] + public class FailingAuditingHelper : AuditingHelper, IDisposable + { + private readonly FailingAuditingHelperState _state; + private bool _hasFailed; + + public FailingAuditingHelper( + FailingAuditingHelperState state, + IAuditSerializer auditSerializer, + IOptions options, + ICurrentUser currentUser, + ICurrentTenant currentTenant, + ICurrentClient currentClient, + IClock clock, + IAuditingStore auditingStore, + ILogger logger, + IServiceProvider serviceProvider, + ICorrelationIdProvider correlationIdProvider, + IAmbientScopeProvider auditingDisabledState) + : base(auditSerializer, options, currentUser, currentTenant, currentClient, clock, auditingStore, logger, serviceProvider, correlationIdProvider, auditingDisabledState) + { + _state = state; + } + + public override AuditLogActionInfo CreateAuditLogAction(AuditLogInfo auditLog, Type type, MethodInfo method, object[] arguments) + { + if (_state.FailToCreateAction) + { + _hasFailed = true; + throw new InvalidOperationException("Failed to create the audit log action"); + } + + return base.CreateAuditLogAction(auditLog, type, method, arguments); + } + + public void Dispose() + { + if (_hasFailed) + { + _state.IsFailedHelperDisposed = true; + } + } + } +} diff --git a/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs b/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs new file mode 100644 index 0000000000..dd0a9cfa54 --- /dev/null +++ b/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs @@ -0,0 +1,443 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using NSubstitute; +using Shouldly; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Uow; +using Xunit; + +namespace Volo.Abp.Auditing; + +public class Auditing_AsyncEnumerable_Tests : AbpAuditingTestBase +{ + private readonly List _savedAuditLogs = new(); + private readonly List<(List Comments, int[] ActionDurations)> _savedAuditLogSnapshots = new(); + private readonly IAuditingManager _auditingManager; + private readonly MyStreamingAuditedObject _target; + + public Auditing_AsyncEnumerable_Tests() + { + _auditingManager = GetRequiredService(); + _target = GetRequiredService(); + } + + protected override void AfterAddApplication(IServiceCollection services) + { + var auditingStore = Substitute.For(); + auditingStore.SaveAsync(Arg.Do(auditLog => + { + _savedAuditLogs.Add(auditLog); + _savedAuditLogSnapshots.Add((auditLog.Comments.ToList(), auditLog.Actions.Select(a => a.ExecutionDuration).ToArray())); + })); + services.Replace(ServiceDescriptor.Singleton(auditingStore)); + } + + [Fact] + public async Task Should_Save_The_Call_And_The_Enumeration_As_Separate_Audit_Logs() + { + var sequence = _target.StreamItemsAsync(50); + + var callLog = _savedAuditLogs.ShouldHaveSingleItem(); + IsEnumeration(callLog.Actions.ShouldHaveSingleItem()).ShouldBeFalse(); + + (await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); + + _savedAuditLogs.Count.ShouldBe(2); + var enumerationAction = _savedAuditLogs[1].Actions.ShouldHaveSingleItem(); + IsEnumeration(enumerationAction).ShouldBeTrue(); + enumerationAction.MethodName.ShouldBe(nameof(MyStreamingAuditedObject.StreamItemsAsync)); + enumerationAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(80); + _savedAuditLogs[1].Exceptions.ShouldBeEmpty(); + } + + [Fact] + public void Should_Not_Save_An_Enumeration_Audit_Log_If_The_Sequence_Is_Not_Enumerated() + { + _target.StreamItemsAsync(1); + + IsEnumeration(_savedAuditLogs.ShouldHaveSingleItem().Actions.ShouldHaveSingleItem()).ShouldBeFalse(); + } + + [Fact] + public async Task Should_Save_The_Exception_Of_The_Sequence_In_The_Enumeration_Audit_Log() + { + await Should.ThrowAsync(ToListAsync(_target.StreamItemsThenThrowAsync())); + + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[0].Exceptions.ShouldBeEmpty(); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Stream failed"); + } + + [Fact] + public async Task Should_Save_An_Audit_Log_For_Each_Enumeration() + { + var sequence = _target.StreamItemsAsync(1); + + await ToListAsync(sequence); + await ToListAsync(sequence); + + _savedAuditLogs.Count.ShouldBe(3); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + IsEnumeration(_savedAuditLogs[2].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + } + + [Fact] + public async Task Should_Not_Copy_What_Was_Recorded_While_Creating_The_Sequence() + { + (await ToListAsync(_target.StreamItemsWithCommentAsync())).ShouldBe(new[] { 1, 2 }); + + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[0].Comments.ShouldContain("Created the sequence"); + _savedAuditLogs[1].Comments.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Audit_The_Enumeration_When_The_Call_Recorded_An_Exception_Without_Throwing() + { + (await ToListAsync(_target.StreamItemsAfterHandledExceptionAsync())).ShouldBe(new[] { 1, 2 }); + + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[0].Exceptions.ShouldContain(e => e.Message == "Handled while creating"); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + _savedAuditLogs[1].Exceptions.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Record_What_Happens_During_Each_Enumeration_Only_In_Its_Own_Audit_Log() + { + var sequence = _target.StreamItemsWithEntityChangeAsync(); + + await ToListAsync(sequence); + await ToListAsync(sequence); + + _savedAuditLogs.Count.ShouldBe(3); + _savedAuditLogs[0].EntityChanges.ShouldBeEmpty(); + var firstChange = _savedAuditLogs[1].EntityChanges.ShouldHaveSingleItem(); + var secondChange = _savedAuditLogs[2].EntityChanges.ShouldHaveSingleItem(); + firstChange.ShouldNotBeSameAs(secondChange); + } + + [Fact] + public async Task Should_Add_A_Nested_Sequence_To_The_Audit_Log_Of_The_Enumeration_That_Uses_It() + { + var outer = _target.StreamItemsOfNestedSequenceAsync(); + (await ToListAsync(outer)).ShouldBe(new[] { 1, 2 }); + + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[0].Actions.ShouldHaveSingleItem().MethodName.ShouldBe(nameof(MyStreamingAuditedObject.StreamItemsOfNestedSequenceAsync)); + + var actions = _savedAuditLogs[1].Actions; + actions.Select(a => (a.MethodName, IsEnumeration(a))).ShouldBe(new[] + { + (nameof(MyStreamingAuditedObject.StreamItemsAsync), false), + (nameof(MyStreamingAuditedObject.StreamItemsAsync), true), + (nameof(MyStreamingAuditedObject.StreamItemsOfNestedSequenceAsync), true) + }); + } + + [Fact] + public async Task Should_Save_The_Enumeration_Audit_Log_When_The_Source_Throws_On_GetAsyncEnumerator() + { + await Should.ThrowAsync(ToListAsync(_target.StreamItemsThrowingOnGetAsyncEnumerator())); + + _savedAuditLogs.Count.ShouldBe(2); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on GetAsyncEnumerator"); + } + + [Fact] + public async Task Should_Save_The_Enumeration_Audit_Log_When_The_Source_Throws_On_Dispose() + { + // Stopping early runs the finally block of the source in DisposeAsync, not in MoveNextAsync. + await Should.ThrowAsync(async () => + { + await foreach (var _ in _target.StreamItemsThrowingOnDisposeAsync()) + { + break; + } + }); + + _savedAuditLogs.Count.ShouldBe(2); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on dispose"); + } + + [Fact] + public async Task Should_Save_The_Enumeration_Audit_Log_After_The_Failed_Source_Has_Been_Disposed() + { + await Should.ThrowAsync(ToListAsync(_target.StreamItemsThrowingOnCurrent())); + + _savedAuditLogSnapshots.Count.ShouldBe(2); + var (comments, actionDurations) = _savedAuditLogSnapshots[1]; + comments.ShouldBe(new[] { "Disposed the source" }); + actionDurations.ShouldHaveSingleItem().ShouldBeGreaterThanOrEqualTo(40); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on Current"); + } + + [Fact] + public async Task Should_Save_The_Enumeration_Audit_Log_Without_An_Action_If_Action_Info_Is_Disabled() + { + GetRequiredService>().Value.DisableLogActionInfo = true; + + (await ToListAsync(_target.StreamItemsAsync(1))).ShouldBe(new[] { 1, 2 }); + + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[1].Actions.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Add_The_Exception_Of_Saving_Changes_To_The_Enumeration_Audit_Log() + { + using (var unitOfWork = GetRequiredService().Begin()) + { + unitOfWork.AddDatabaseApi("Failing", new FailingSaveChangesDatabaseApi()); + + (await ToListAsync(_target.StreamItemsAsync(1))).ShouldBe(new[] { 1, 2 }); + } + + _savedAuditLogs.Count.ShouldBe(2); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed to save changes"); + } + + [Fact] + public async Task Should_Save_The_Exception_Thrown_When_Disposing_The_Failed_Source_In_The_Enumeration_Audit_Log() + { + var exception = await Should.ThrowAsync(ToListAsync(_target.StreamItemsThrowingOnCurrentAndDispose())); + + exception.Message.ShouldBe("Failed on dispose"); + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on dispose"); + } + + [Fact] + public async Task Should_Not_Save_An_Enumeration_Audit_Log_While_Auditing_Is_Disabled() + { + var sequence = _target.StreamItemsAsync(1); + + using (GetRequiredService().DisableAuditing()) + { + (await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); + } + + _savedAuditLogs.ShouldHaveSingleItem(); + + (await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); + + _savedAuditLogs.Count.ShouldBe(2); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + } + + [Fact] + public async Task Should_Not_Add_The_Enumeration_To_The_Current_Audit_Log_While_Auditing_Is_Disabled() + { + using (_auditingManager.BeginScope()) + { + var sequence = _target.StreamItemsAsync(1); + + using (GetRequiredService().DisableAuditing()) + { + (await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); + } + + _auditingManager.Current!.Log.Actions.Select(IsEnumeration).ShouldBe(new[] { false }); + + (await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); + + _auditingManager.Current!.Log.Actions.Select(IsEnumeration).ShouldBe(new[] { false, true }); + } + } + + [Fact] + public async Task Should_Add_The_Call_And_The_Enumeration_To_The_Current_Audit_Log() + { + using (var scope = _auditingManager.BeginScope()) + { + (await ToListAsync(_target.StreamItemsAsync(50))).ShouldBe(new[] { 1, 2 }); + await Should.ThrowAsync(ToListAsync(_target.StreamItemsThenThrowAsync())); + + var auditLog = _auditingManager.Current!.Log; + auditLog.Actions.Select(IsEnumeration).ShouldBe(new[] { false, true, false, true }); + auditLog.Actions[1].ExecutionDuration.ShouldBeGreaterThanOrEqualTo(80); + auditLog.Exceptions.ShouldContain(e => e.Message == "Stream failed"); + + await scope.SaveAsync(); + } + + _savedAuditLogs.ShouldHaveSingleItem(); + } + + private class FailingSaveChangesDatabaseApi : IDatabaseApi, ISupportsSavingChanges + { + public Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + throw new InvalidOperationException("Failed to save changes"); + } + } + + private static bool IsEnumeration(AuditLogActionInfo action) + { + return action.ExtraProperties.TryGetValue(AuditingInterceptor.AsyncEnumerationPropertyName, out var value) && value is true; + } + + private static async Task> ToListAsync(IAsyncEnumerable source) + { + var list = new List(); + await foreach (var item in source) + { + list.Add(item); + } + + return list; + } + + public class MyStreamingAuditedObject : ITransientDependency, IAuditingEnabled + { + private readonly IAuditingManager _auditingManager; + + public MyStreamingAuditedObject(IAuditingManager auditingManager) + { + _auditingManager = auditingManager; + } + + public virtual IAsyncEnumerable StreamItemsWithCommentAsync() + { + _auditingManager.Current!.Log.Comments.Add("Created the sequence"); + return ProduceAsync(); + } + + public virtual IAsyncEnumerable StreamItemsAfterHandledExceptionAsync() + { + _auditingManager.Current!.Log.Exceptions.Add(new InvalidOperationException("Handled while creating")); + return ProduceAsync(); + } + + public virtual async IAsyncEnumerable StreamItemsAsync(int delay) + { + await Task.Delay(delay); + yield return 1; + await Task.Delay(delay); + yield return 2; + } + + public virtual async IAsyncEnumerable StreamItemsWithEntityChangeAsync() + { + await Task.Yield(); + _auditingManager.Current!.Log.EntityChanges.Add(new EntityChangeInfo { EntityId = "1" }); + yield return 1; + } + + public virtual async IAsyncEnumerable StreamItemsOfNestedSequenceAsync() + { + await foreach (var item in StreamItemsAsync(1)) + { + yield return item; + } + } + + public virtual async IAsyncEnumerable StreamItemsThenThrowAsync() + { + await Task.Yield(); + yield return 1; + throw new InvalidOperationException("Stream failed"); + } + + public virtual IAsyncEnumerable StreamItemsThrowingOnCurrent() + { + return new ThrowingOnCurrentSequence(_auditingManager); + } + + public virtual IAsyncEnumerable StreamItemsThrowingOnCurrentAndDispose() + { + return new ThrowingOnCurrentAndDisposeSequence(); + } + + public virtual IAsyncEnumerable StreamItemsThrowingOnGetAsyncEnumerator() + { + return new ThrowingOnGetAsyncEnumeratorSequence(); + } + + public virtual async IAsyncEnumerable StreamItemsThrowingOnDisposeAsync() + { + try + { + await Task.Yield(); + yield return 1; + } + finally + { + throw new InvalidOperationException("Failed on dispose"); + } + } + + private static async IAsyncEnumerable ProduceAsync() + { + await Task.Yield(); + yield return 1; + yield return 2; + } + + private class ThrowingOnCurrentSequence : IAsyncEnumerable, IAsyncEnumerator + { + private readonly IAuditingManager _auditingManager; + + public ThrowingOnCurrentSequence(IAuditingManager auditingManager) + { + _auditingManager = auditingManager; + } + + public int Current => throw new InvalidOperationException("Failed on Current"); + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this; + } + + public ValueTask MoveNextAsync() + { + return new ValueTask(true); + } + + public async ValueTask DisposeAsync() + { + await Task.Delay(50); + _auditingManager.Current!.Log.Comments.Add("Disposed the source"); + } + } + + private class ThrowingOnCurrentAndDisposeSequence : IAsyncEnumerable, IAsyncEnumerator + { + public int Current => throw new InvalidOperationException("Failed on Current"); + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this; + } + + public ValueTask MoveNextAsync() + { + return new ValueTask(true); + } + + public ValueTask DisposeAsync() + { + throw new InvalidOperationException("Failed on dispose"); + } + } + + private class ThrowingOnGetAsyncEnumeratorSequence : IAsyncEnumerable + { + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + throw new InvalidOperationException("Failed on GetAsyncEnumerator"); + } + } + } +} From 90fb7b113fcf2014a48a643d7c481754ae47f828 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:01:55 +0800 Subject: [PATCH 04/10] Wait for interceptors of async enumerable action results in MVC --- ...pInterceptedAsyncEnumerableActionFilter.cs | 35 ++++++++ .../AspNetCore/Mvc/AbpMvcOptionsExtensions.cs | 1 + .../Mvc/AbpAspNetCoreMvcTestModule.cs | 20 ++++- .../AuditingConcernProbeInterceptor.cs | 32 +++++++ .../StreamingAppService_Auditing_Tests.cs | 90 +++++++++++++++++++ .../Auditing/StreamingJsonTestController.cs | 56 ++++++++++++ .../Application/StreamingAppService.cs | 20 +++++ 7 files changed, 253 insertions(+), 1 deletion(-) create mode 100644 framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpInterceptedAsyncEnumerableActionFilter.cs create mode 100644 framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditingConcernProbeInterceptor.cs create mode 100644 framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs create mode 100644 framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingJsonTestController.cs create mode 100644 framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpInterceptedAsyncEnumerableActionFilter.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpInterceptedAsyncEnumerableActionFilter.cs new file mode 100644 index 0000000000..57ac6da6e4 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpInterceptedAsyncEnumerableActionFilter.cs @@ -0,0 +1,35 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Volo.Abp.AspNetCore.Filters; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DynamicProxy; + +namespace Volo.Abp.AspNetCore.Mvc; + +/// +/// Waits for the interceptors of a returned , so the outer action filters cover them. +/// +public class AbpInterceptedAsyncEnumerableActionFilter : IAsyncActionFilter, IAbpFilter, ITransientDependency +{ + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var executedContext = await next(); + + if ((executedContext.Exception == null || executedContext.ExceptionHandled) && + GetResultValue(executedContext.Result) is IAbpInterceptedAsyncEnumerable interceptedAsyncEnumerable) + { + await interceptedAsyncEnumerable.WaitForInterceptorsAsync(); + } + } + + protected virtual object? GetResultValue(IActionResult? result) + { + return result switch + { + ObjectResult objectResult => objectResult.Value, + JsonResult jsonResult => jsonResult.Value, + _ => null + }; + } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs index cb63a9e6c8..39f575d60f 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs @@ -63,6 +63,7 @@ internal static class AbpMvcOptionsExtensions options.Filters.AddService(typeof(AbpFeatureActionFilter)); options.Filters.AddService(typeof(AbpValidationActionFilter)); options.Filters.AddService(typeof(AbpUowActionFilter)); + options.Filters.AddService(typeof(AbpInterceptedAsyncEnumerableActionFilter)); options.Filters.AddService(typeof(AbpExceptionFilter)); } diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs index a8707a8c38..7782cc1a4b 100644 --- a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.RequestLocalization; using Volo.Abp.AspNetCore.Security.Claims; using Volo.Abp.AspNetCore.TestBase; using Volo.Abp.Authorization; +using Volo.Abp.AspNetCore.Mvc.Auditing; using Volo.Abp.Autofac; using Volo.Abp.GlobalFeatures; using Volo.Abp.Localization; @@ -50,6 +51,14 @@ public class AbpAspNetCoreMvcTestModule : AbpModule ); }); + context.Services.OnRegistered(registration => + { + if (registration.ImplementationType == typeof(StreamingAppService)) + { + registration.Interceptors.Add(); + } + }); + context.Services.PreConfigure(options => { options.ConventionalControllers.Create(typeof(TestAppModule).Assembly, opts => @@ -59,7 +68,7 @@ public class AbpAspNetCoreMvcTestModule : AbpModule ? "phones" : urlActionNameNormalizerContext.ActionNameInUrl; - opts.TypePredicate = type => type != typeof(ConventionalAppService); + opts.TypePredicate = type => type != typeof(ConventionalAppService) && type != typeof(StreamingAppService); }); options.ExposeIntegrationServices = true; @@ -68,6 +77,15 @@ public class AbpAspNetCoreMvcTestModule : AbpModule public override void ConfigureServices(ServiceConfigurationContext context) { + // Configured like the startup templates (not in PreConfigure), so the controller keeps its dynamic proxy. + Configure(options => + { + options.ConventionalControllers.Create(typeof(TestAppModule).Assembly, opts => + { + opts.TypePredicate = type => type == typeof(StreamingAppService); + }); + }); + OneTimeRunner.Run(() => { GlobalFeatureManager.Instance.Modules.GetOrAdd(AbpAspNetCoreMvcTestFeatures.ModuleName, diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditingConcernProbeInterceptor.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditingConcernProbeInterceptor.cs new file mode 100644 index 0000000000..c6a27860ab --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditingConcernProbeInterceptor.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Volo.Abp.Aspects; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DynamicProxy; + +namespace Volo.Abp.AspNetCore.Mvc.Auditing; + +public class AuditingConcernProbe : ISingletonDependency +{ + public List Results { get; } = new(); +} + +/// +/// Completes asynchronously before proceeding, and records whether the action's auditing scope is still active. +/// +public class AuditingConcernProbeInterceptor : AbpInterceptor, ITransientDependency +{ + private readonly AuditingConcernProbe _probe; + + public AuditingConcernProbeInterceptor(AuditingConcernProbe probe) + { + _probe = probe; + } + + public override async Task InterceptAsync(IAbpMethodInvocation invocation) + { + await Task.Delay(50); + _probe.Results.Add(AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Auditing)); + await invocation.ProceedAsync(); + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs new file mode 100644 index 0000000000..ffb21d2ca1 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs @@ -0,0 +1,90 @@ +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using NSubstitute; +using Shouldly; +using Volo.Abp.Auditing; +using Volo.Abp.DynamicProxy; +using Volo.Abp.TestApp.Application; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc.Auditing; + +public class StreamingAppService_Auditing_Tests : AspNetCoreMvcTestBase +{ + private readonly AbpAuditingOptions _options; + private IAuditingStore _auditingStore; + private readonly List _savedAuditLogs = new(); + + public StreamingAppService_Auditing_Tests() + { + _options = ServiceProvider.GetRequiredService>().Value; + _auditingStore = ServiceProvider.GetRequiredService(); + } + + protected override void ConfigureServices(IServiceCollection services) + { + _auditingStore = Substitute.For(); + _auditingStore.SaveAsync(Arg.Do(_savedAuditLogs.Add)); + services.Replace(ServiceDescriptor.Singleton(_auditingStore)); + base.ConfigureServices(services); + } + + [Fact] + public async Task Should_Audit_Streaming_Action_Once() + { + _options.IsEnabledForGetRequests = true; + ProxyHelper.IsProxy(ServiceProvider.GetRequiredService()).ShouldBeTrue(); + + var result = await GetResponseAsObjectAsync>("/api/app/streaming/items"); + + result.ShouldBe(new[] { 1, 2 }); + GetRequiredService().Results.ShouldBe(new[] { true }); + _savedAuditLogs.Count.ShouldBe(1); + _savedAuditLogs[0].Actions.Count(a => a.MethodName == nameof(StreamingAppService.GetItemsAsync)).ShouldBe(1); + } + + [Theory] + [InlineData("/api/app/streaming/items-with-creation-error")] + [InlineData("/api/streaming-json-test/creation-error")] + public async Task Should_Handle_Exception_Thrown_While_Creating_The_Sequence_As_An_Action_Exception(string url) + { + _options.IsEnabledForGetRequests = true; + + // AbpExceptionFilter only handles exceptions of actions returning IActionResult for AJAX requests. + using var response = await GetResponseAsync(url, HttpStatusCode.Forbidden, xmlHttpRequest: true); + + (await response.Content.ReadAsStringAsync()).ShouldContain("Failed to create the sequence"); + _savedAuditLogs.Single().Exceptions.ShouldContain(e => e.Message == "Failed to create the sequence"); + } + + [Fact] + public async Task Should_Wait_For_Interceptors_Of_A_Sequence_Returned_After_A_Handled_Exception() + { + _options.IsEnabledForGetRequests = true; + + var result = await GetResponseAsObjectAsync>("/api/streaming-json-test/handled-exception"); + + result.ShouldBe(new[] { 1, 2 }); + var controllerAction = _savedAuditLogs.Single().Actions.Single(a => a.ServiceName == typeof(StreamingJsonTestController).FullName); + controllerAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); + } + + [Fact] + public async Task Should_Wait_For_Interceptors_Of_A_Sequence_Returned_In_A_JsonResult() + { + _options.IsEnabledForGetRequests = true; + + var result = await GetResponseAsObjectAsync>("/api/streaming-json-test"); + + result.ShouldBe(new[] { 1, 2 }); + + // The interceptors of the sequence (delayed by the probe) run within the action, like for an ObjectResult. + var controllerAction = _savedAuditLogs.Single().Actions.Single(a => a.ServiceName == typeof(StreamingJsonTestController).FullName); + controllerAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingJsonTestController.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingJsonTestController.cs new file mode 100644 index 0000000000..510727206d --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingJsonTestController.cs @@ -0,0 +1,56 @@ +using System; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Auditing; +using Volo.Abp.TestApp.Application; + +namespace Volo.Abp.AspNetCore.Mvc.Auditing; + +[Route("api/streaming-json-test")] +public class StreamingJsonTestController : AbpController +{ + private readonly StreamingAppService _streamingAppService; + + public StreamingJsonTestController(StreamingAppService streamingAppService) + { + _streamingAppService = streamingAppService; + } + + [HttpGet] + [Audited] + public IActionResult Get() + { + return Json(_streamingAppService.GetItemsAsync()); + } + + [HttpGet] + [Route("handled-exception")] + [Audited] + [ReturnStreamOnException] + public IActionResult GetWithHandledException() + { + throw new InvalidOperationException("Handled by the filter"); + } + + [HttpGet] + [Route("creation-error")] + public IActionResult GetWithCreationError() + { + return Json(_streamingAppService.GetItemsWithCreationErrorAsync()); + } +} + +public class ReturnStreamOnExceptionAttribute : ActionFilterAttribute +{ + public override void OnActionExecuted(ActionExecutedContext context) + { + if (context.Exception == null) + { + return; + } + + context.ExceptionHandled = true; + context.Result = new ObjectResult(context.HttpContext.RequestServices.GetRequiredService().GetItemsAsync()); + } +} diff --git a/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs new file mode 100644 index 0000000000..7940410a07 --- /dev/null +++ b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace Volo.Abp.TestApp.Application; + +public class StreamingAppService : ApplicationService +{ + public virtual async IAsyncEnumerable GetItemsAsync() + { + await Task.Yield(); + yield return 1; + yield return 2; + } + + public virtual IAsyncEnumerable GetItemsWithCreationErrorAsync() + { + throw new UserFriendlyException("Failed to create the sequence"); + } +} From dbf2f824ca41fbcea4e99c3161fdffd19a6f97d8 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:02:05 +0800 Subject: [PATCH 05/10] Support IAsyncEnumerable in C# client proxies --- .../CSharp/CSharpServiceProxyGenerator.cs | 15 +- .../Client/ClientProxying/ClientProxyBase.cs | 78 ++++- .../ClientProxyRequestContext.cs | 6 + .../DynamicHttpProxyInterceptor.cs | 64 +++- .../DynamicHttpProxyInterceptorClientProxy.cs | 26 +- ...iceProxyGenerator_AsyncEnumerable_Tests.cs | 219 ++++++++++++++ .../RegularTestControllerStaticClientProxy.cs | 9 + ...StaticClientProxy_AsyncEnumerable_Tests.cs | 57 ++++ .../regular-test-generate-proxy.json | 55 ++++ ...EnumerableClientProxyCancellation_Tests.cs | 276 ++++++++++++++++++ ...umerableClientProxy_NestedRequest_Tests.cs | 110 +++++++ ...erableClientProxy_RequestOverride_Tests.cs | 83 ++++++ .../AsyncEnumerableClientProxy_Tests.cs | 142 +++++++++ .../AsyncEnumerableTestGate.cs | 29 ++ .../ClientProxyResponseDisposal_Tests.cs | 56 ++++ .../DynamicProxying/IRegularTestController.cs | 11 + .../DynamicProxying/RegularTestController.cs | 54 ++++ 17 files changed, 1271 insertions(+), 19 deletions(-) create mode 100644 framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ServiceProxying/CSharpServiceProxyGenerator_AsyncEnumerable_Tests.cs create mode 100644 framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests.cs create mode 100644 framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxyCancellation_Tests.cs create mode 100644 framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_NestedRequest_Tests.cs create mode 100644 framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_RequestOverride_Tests.cs create mode 100644 framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs create mode 100644 framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableTestGate.cs 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) From 137036e5ae2f395b353f90952e28edadceea043d Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:02:05 +0800 Subject: [PATCH 06/10] Fix arguments after a CancellationToken parameter in client proxies --- .../AspNetCoreApiDescriptionModelProvider.cs | 8 + .../Client/ClientProxying/ClientProxyBase.cs | 7 +- .../RegularTestControllerStaticClientProxy.cs | 19 +++ ...StaticClientProxy_AsyncEnumerable_Tests.cs | 17 ++ .../regular-test-generate-proxy.json | 147 ++++++++++++++++++ .../AsyncEnumerableClientProxy_Tests.cs | 12 ++ .../DynamicProxying/IRegularTestController.cs | 2 + .../DynamicProxying/RegularTestController.cs | 7 + 8 files changed, 218 insertions(+), 1 deletion(-) diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs index 837eb929fe..ca5f6789e5 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; +using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using JetBrains.Annotations; @@ -393,6 +394,7 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide var methodParameterNames = method .GetParameters() .Where(IsNotFromServicesParameter) + .Where(IsNotCancellationTokenParameter) .Select(GetMethodParamName) .ToArray(); @@ -430,6 +432,12 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide return !parameterInfo.IsDefined(typeof(FromServicesAttribute), true); } + // A CancellationToken parameter has no parameter description, so it must not be matched with the next parameter. + private static bool IsNotCancellationTokenParameter(ParameterInfo parameterInfo) + { + return parameterInfo.ParameterType != typeof(CancellationToken); + } + public string GetMethodParamName(ParameterInfo parameterInfo) { var modelNameProvider = parameterInfo.GetCustomAttributes() 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 7df2b9f623..1b9881366a 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 @@ -135,10 +135,15 @@ public class ClientProxyBase : ITransientDependency actionArguments.RemoveAll(x => x.Key == "api-version" || x.Key == "apiVersion"); } + // A CancellationToken argument has no request parameter, so it must not shift the arguments after it. + var requestArguments = arguments.Values.Exists(x => x.Key == typeof(CancellationToken)) + ? arguments.Values.Where(x => x.Key != typeof(CancellationToken)).ToList() + : arguments.Values; + return new ClientProxyRequestContext( action, actionArguments - .Select((x, i) => new KeyValuePair(x.Key, arguments.Values[i].Value)) + .Select((x, i) => new KeyValuePair(x.Key, requestArguments[i].Value)) .ToDictionary(x => x.Key, x => x.Value), typeof(TService)); } 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 dc60616295..da351a75cc 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,4 +1,5 @@ using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using Volo.Abp.Http.DynamicProxying; @@ -14,6 +15,15 @@ public class RegularTestControllerStaticClientProxy : ClientProxyBase GetStreamWithLeadingCancellationTokenAsync(CancellationToken cancellationToken, int count) + { + return RequestAsyncEnumerable(nameof(GetStreamWithLeadingCancellationTokenAsync), new ClientProxyRequestTypeValue + { + { typeof(CancellationToken), cancellationToken }, + { typeof(int), count } + }); + } + public virtual async Task GetWithStringPathAsync(string name) { return await RequestAsync(nameof(GetWithStringPathAsync), new ClientProxyRequestTypeValue @@ -22,6 +32,15 @@ public class RegularTestControllerStaticClientProxy : ClientProxyBase GetWithSwappedQueryNamesAsync(int first, int second) + { + return await RequestAsync(nameof(GetWithSwappedQueryNamesAsync), new ClientProxyRequestTypeValue + { + { typeof(int), first }, + { typeof(int), second } + }); + } + public virtual async Task GetWithCatchAllPathAsync(string path) { return await RequestAsync(nameof(GetWithCatchAllPathAsync), 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 index 4e3eea439c..c073e6014a 100644 --- 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 @@ -2,6 +2,7 @@ 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 Shouldly; @@ -19,6 +20,22 @@ public class RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests : AbpH (await ToListAsync(proxy.GetStreamAsync(3))).ShouldBe(new[] { 1, 2, 3 }); } + [Fact] + public async Task Should_Send_The_Arguments_After_A_Leading_CancellationToken() + { + var proxy = ServiceProvider.GetRequiredService(); + + (await ToListAsync(proxy.GetStreamWithLeadingCancellationTokenAsync(CancellationToken.None, 3))).ShouldBe(new[] { 1, 2, 3 }); + } + + [Fact] + public async Task Should_Send_The_Arguments_In_The_Order_Of_The_Request_Parameters() + { + var proxy = ServiceProvider.GetRequiredService(); + + (await proxy.GetWithSwappedQueryNamesAsync(10, 20)).ShouldBe("10-20"); + } + [Fact] public async Task Should_Build_A_Request_Context_For_Each_Enumeration() { 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 8db1f7060f..df843ac000 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 @@ -148,6 +148,87 @@ "description": null, "displayName": null }, + "GetWithSwappedQueryNamesAsyncByFirstAndSecond": { + "uniqueName": "GetWithSwappedQueryNamesAsyncByFirstAndSecond", + "name": "GetWithSwappedQueryNamesAsync", + "httpMethod": "GET", + "url": "api/regular-test-controller/get-with-swapped-query-names", + "supportedVersions": [], + "parametersOnMethod": [ + { + "name": "first", + "typeAsString": "System.Int32, System.Private.CoreLib", + "type": "System.Int32", + "typeSimple": "number", + "isOptional": false, + "defaultValue": null, + "summary": null, + "description": null, + "displayName": null + }, + { + "name": "second", + "typeAsString": "System.Int32, System.Private.CoreLib", + "type": "System.Int32", + "typeSimple": "number", + "isOptional": false, + "defaultValue": null, + "summary": null, + "description": null, + "displayName": null + } + ], + "parameters": [ + { + "nameOnMethod": "second", + "name": "second", + "jsonName": null, + "type": "System.Int32", + "typeSimple": "number", + "isOptional": false, + "defaultValue": null, + "constraintTypes": [], + "bindingSourceId": "Query", + "descriptorName": "", + "summary": null, + "description": null, + "displayName": null + }, + { + "nameOnMethod": "first", + "name": "first", + "jsonName": null, + "type": "System.Int32", + "typeSimple": "number", + "isOptional": false, + "defaultValue": null, + "constraintTypes": [], + "bindingSourceId": "Query", + "descriptorName": "", + "summary": null, + "description": null, + "displayName": null + } + ], + "returnValue": { + "type": "System.String", + "typeSimple": "string", + "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 + }, "GetWithCatchAllPathAsyncByPath": { "uniqueName": "GetWithCatchAllPathAsyncByPath", "name": "GetWithCatchAllPathAsync", @@ -312,6 +393,72 @@ "remarks": null, "description": null, "displayName": null + }, + "GetStreamWithLeadingCancellationTokenAsyncByCancellationTokenAndCount": { + "uniqueName": "GetStreamWithLeadingCancellationTokenAsyncByCancellationTokenAndCount", + "name": "GetStreamWithLeadingCancellationTokenAsync", + "httpMethod": "GET", + "url": "api/regular-test-controller/stream-with-leading-cancellation-token", + "supportedVersions": [], + "parametersOnMethod": [ + { + "name": "cancellationToken", + "typeAsString": "System.Threading.CancellationToken, System.Private.CoreLib", + "type": "System.Threading.CancellationToken", + "typeSimple": "System.Threading.CancellationToken", + "isOptional": false, + "defaultValue": null, + "summary": null, + "description": null, + "displayName": null + }, + { + "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/AsyncEnumerableClientProxy_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs index a06c7d937e..bbc048d608 100644 --- 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 @@ -31,6 +31,18 @@ public class AsyncEnumerableClientProxy_Tests : AbpHttpClientTestBase clientProxy.UseCancellationToken(CancellationToken.None).ShouldBeSameAs(NullDisposable.Instance); } + [Fact] + public async Task Should_Send_The_Arguments_After_A_Leading_CancellationToken() + { + var items = new List(); + await foreach (var item in _controller.GetStreamWithLeadingCancellationTokenAsync(CancellationToken.None, 3)) + { + items.Add(item); + } + + items.ShouldBe(new[] { 1, 2, 3 }); + } + [Fact] public async Task Should_Stream_Items() { 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 49a1596c6e..a3a5ab9ca7 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 @@ -68,6 +68,8 @@ public interface IRegularTestController Task GetWithStringPathAsync(string name); + Task GetWithSwappedQueryNamesAsync(int first, int second); + Task GetWithCatchAllPathAsync(string path); Task GetWithSingleStarCatchAllPathAsync(string path); 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 05ab849a8b..8d0ad8354c 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 @@ -257,6 +257,13 @@ public class RegularTestController : AbpController, IRegularTestController return Task.FromResult(name); } + [HttpGet] + [Route("get-with-swapped-query-names")] + public Task GetWithSwappedQueryNamesAsync([FromQuery(Name = "second")] int first, [FromQuery(Name = "first")] int second) + { + return Task.FromResult($"{first}-{second}"); + } + [HttpGet] [Route("get-with-catch-all-path/{**path}")] public Task GetWithCatchAllPathAsync(string path) From 887eeaf46ff0a8948dd2ac8a4e03b9d9c8c23e09 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:02:05 +0800 Subject: [PATCH 07/10] Document IAsyncEnumerable support in interceptors and client proxies --- .../api-development/dynamic-csharp-clients.md | 13 +++ .../api-development/static-csharp-clients.md | 13 +++ .../domain-driven-design/unit-of-work.md | 8 ++ .../framework/infrastructure/audit-logging.md | 10 +++ .../framework/infrastructure/interceptors.md | 83 +++++++++++++++++++ 5 files changed, 127 insertions(+) diff --git a/docs/en/framework/api-development/dynamic-csharp-clients.md b/docs/en/framework/api-development/dynamic-csharp-clients.md index bfacc26886..53ff6c833d 100644 --- a/docs/en/framework/api-development/dynamic-csharp-clients.md +++ b/docs/en/framework/api-development/dynamic-csharp-clients.md @@ -119,6 +119,19 @@ public class MyService : ITransientDependency This sample injects the `IBookAppService` service interface defined above. The dynamic client proxy implementation makes an HTTP call whenever a service method is called by the client. +### Streaming with IAsyncEnumerable + +Service methods returning `IAsyncEnumerable` are also supported. The HTTP request is sent when the returned sequence is enumerated, and the items are read from the response as they arrive. For example, if `IBookAppService` has an `IAsyncEnumerable GetStreamAsync()` method: + +````csharp +await foreach (var book in _bookService.GetStreamAsync().WithCancellation(cancellationToken)) +{ + Console.WriteLine($"[BOOK {book.Id}] Name={book.Name}"); +} +```` + +You can cancel the request with the token passed to the enumeration (like `WithCancellation` above) or with a `CancellationToken` parameter of the service method. + ### IHttpClientProxy Interface While you can inject `IBookAppService` like above to use the client proxy, you could inject `IHttpClientProxy` for a more explicit usage. In this case you will use the `Service` property of the `IHttpClientProxy` interface. diff --git a/docs/en/framework/api-development/static-csharp-clients.md b/docs/en/framework/api-development/static-csharp-clients.md index 7491f46d67..f7d9cae589 100644 --- a/docs/en/framework/api-development/static-csharp-clients.md +++ b/docs/en/framework/api-development/static-csharp-clients.md @@ -204,6 +204,19 @@ public class MyService : ITransientDependency This sample injects the `IBookAppService` service interface defined above. The static client proxy implementation makes an HTTP call whenever a service method is called by the client. +### Streaming with IAsyncEnumerable + +Service methods returning `IAsyncEnumerable` are also supported. The HTTP request is sent when the returned sequence is enumerated (a new request for each enumeration), and the items are read from the response as they arrive. For example, if `IBookAppService` has an `IAsyncEnumerable GetStreamAsync()` method: + +````csharp +await foreach (var book in _bookService.GetStreamAsync().WithCancellation(cancellationToken)) +{ + Console.WriteLine($"[BOOK {book.Id}] Name={book.Name}"); +} +```` + +You can cancel the request with the token passed to the enumeration, like `WithCancellation` above. + ## Configuration ### AbpRemoteServiceOptions diff --git a/docs/en/framework/architecture/domain-driven-design/unit-of-work.md b/docs/en/framework/architecture/domain-driven-design/unit-of-work.md index 6b6de422a1..d6f7b619e5 100644 --- a/docs/en/framework/architecture/domain-driven-design/unit-of-work.md +++ b/docs/en/framework/architecture/domain-driven-design/unit-of-work.md @@ -34,6 +34,14 @@ A UOW automatically begins for these methods **except** if there is already a ** All of these are automatically handled by the ABP. +### Methods Returning IAsyncEnumerable + +A method returning `IAsyncEnumerable` does its work when the returned sequence is enumerated, after the method has returned. So; + +* The method call and each enumeration of the returned sequence run in separate UOWs (or participate in the surrounding UOW, if there is one). +* The UOW of an enumeration is completed when the enumeration ends, even if the caller stops it early. It is not completed if the sequence throws an exception. +* Query the database inside the iterator method (the method body containing `yield return`). A `DbContext` or a query obtained while calling the method can not be used after the UOW of the call ends. + ### Database Transaction Behavior While the section above explains the UOW as it is database transaction, actually a UOW doesn't have to be transactional. By default; diff --git a/docs/en/framework/infrastructure/audit-logging.md b/docs/en/framework/infrastructure/audit-logging.md index dc8564ec0c..9c0eb68b9e 100644 --- a/docs/en/framework/infrastructure/audit-logging.md +++ b/docs/en/framework/infrastructure/audit-logging.md @@ -331,6 +331,16 @@ An **audit log object** is created for each **web request** by default. An audit In addition to the standard properties explained above, `AuditLogInfo`, `AuditLogActionInfo` and `EntityChangeInfo` objects implement the `IHasExtraProperties` interface, so you can add custom properties to these objects. +### Methods Returning IAsyncEnumerable + +A method returning `IAsyncEnumerable` does its work when the returned sequence is enumerated. So, if such a method is audited by the auditing interceptor, the method call and each enumeration of the returned sequence are recorded as separate actions: + +* The action of the method call is recorded like for other methods. +* The action of an enumeration has the `AsyncEnumeration` extra property set to `true`, and its `ExecutionDuration` is the duration of the whole enumeration, regardless of the number of items. The exceptions and the entity changes during the enumeration are also recorded. +* If there is no current audit log scope when the sequence is enumerated (for example, in a background job), the enumeration is saved as a separate audit log. + +A controller action (including an [Auto API Controller](../api-development/auto-controllers.md) action) returning `IAsyncEnumerable` is audited by the auditing action filter instead, and recorded as a single action of the audit log of the web request. + ## Audit Log Contributors You can extend the auditing system by creating a class that is derived from the `AuditLogContributor` class which defines the `PreContribute` and the `PostContribute` methods. diff --git a/docs/en/framework/infrastructure/interceptors.md b/docs/en/framework/infrastructure/interceptors.md index c6cedf7859..cfb6438c0d 100644 --- a/docs/en/framework/infrastructure/interceptors.md +++ b/docs/en/framework/infrastructure/interceptors.md @@ -152,6 +152,89 @@ public override void PreConfigureServices(ServiceConfigurationContext context) } ```` +## Advanced Topics + +### Intercepting Methods Returning IAsyncEnumerable + +A method returning `IAsyncEnumerable` is intercepted like a method returning `Task`: the interceptor runs when the method is called, and `invocation.ProceedAsync()` only creates the sequence. The sequence does its work later, when the caller enumerates it, so an interceptor does not cover the enumeration by default. If an interceptor throws (for example, an authorization or validation error), the exception is thrown when the sequence is enumerated. + +To also cover the enumeration, inherit your interceptor from `AbpScopeInterceptor` and return an `IAbpInterceptionScope` from the `BeginScope` method. The scope runs around the method call, and a new scope runs around each enumeration of the returned sequence. For example, you can change the `ExecutionTimeLogInterceptor` above as below to also measure the enumerations: + +````csharp +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DynamicProxy; + +public class ExecutionTimeLogInterceptor : AbpScopeInterceptor, ITransientDependency +{ + private readonly ILogger _logger; + + public ExecutionTimeLogInterceptor(ILogger logger) + { + _logger = logger; + } + + protected override IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation) + { + return new ExecutionTimeLogScope(_logger, invocation.Method.Name); + } +} + +public class ExecutionTimeLogScope : IAbpInterceptionScope +{ + private readonly ILogger _logger; + private readonly string _methodName; + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); + + public ExecutionTimeLogScope(ILogger logger, string methodName) + { + _logger = logger; + _methodName = methodName; + } + + public Task CompleteAsync(CancellationToken cancellationToken) + { + _logger.LogInformation($"Executed {_methodName} in {_stopwatch.ElapsedMilliseconds} ms"); + return Task.CompletedTask; + } + + public Task FailAsync(Exception exception) + { + _logger.LogWarning($"{_methodName} failed after {_stopwatch.ElapsedMilliseconds} ms"); + return Task.CompletedTask; + } + + public void Dispose() + { + } +} +```` + +* `CompleteAsync` is called when the method call or the enumeration completes, including when the caller stops enumerating early (for example, with `break`). +* `FailAsync` is called when the method or the sequence throws an exception. +* `Dispose` is always called at the end. + +`AbpInterceptionScope` is a default implementation that disposes a given object, which is useful to change an ambient value during the scope. For example, `new AbpInterceptionScope(_currentTenant.Change(tenantId))` switches the current tenant during the method call and each enumeration. + +If your interceptor can not inherit from `AbpScopeInterceptor`, call the `ProceedInScopeAsync` extension method in the `InterceptAsync` method instead of `invocation.ProceedAsync()`: + +````csharp +public override async Task InterceptAsync(IAbpMethodInvocation invocation) +{ + await invocation.ProceedInScopeAsync(() => BeginScope(invocation)); +} +```` + +ABP's [Unit of Work](../architecture/domain-driven-design/unit-of-work.md), [Auditing](./audit-logging.md) and entity change tracking interceptors work this way, while the authorization, validation and feature checks are only performed when the method is called. + +> `BeginScope` must set its async local values synchronously (for example, it should not be an `async` method). Otherwise, the values are not available to the method and to the enumeration. + +> Since the authorization and other checks are performed when the method is called, you should enumerate the returned sequence in the same context (the same user and tenant) as the method call. + ## Restrictions and Important Notes ### Always use asynchronous methods From 281d1ccfd416c56d27fd4575d56fbc9f36160c9d Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 17 Nov 2026 09:14:56 +0800 Subject: [PATCH 08/10] Pass the cancellation token of client proxy requests to reading errors --- .../Client/ClientProxying/ClientProxyBase.cs | 84 +++++++---- .../DynamicHttpProxyInterceptor.cs | 35 ++--- ...StaticClientProxy_AsyncEnumerable_Tests.cs | 47 ++++++ ...EnumerableClientProxyCancellation_Tests.cs | 134 ++++++++++-------- .../AsyncEnumerableClientProxy_Tests.cs | 31 ++-- .../ClientProxyResponseDisposal_Tests.cs | 63 ++++++++ 6 files changed, 269 insertions(+), 125 deletions(-) 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 1b9881366a..e1088ab76c 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 @@ -79,37 +79,41 @@ public class ClientProxyBase : ITransientDependency protected virtual async IAsyncEnumerable RequestAsyncEnumerable(ClientProxyRequestContext requestContext, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource( + using (var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource( requestContext.CancellationToken ?? GetCancellationToken(requestContext.Arguments), - cancellationToken); - var linkedCancellationToken = linkedCancellationTokenSource.Token; - - HttpContent responseContent; - _streamingRequest.Value = new StreamingRequest(requestContext, linkedCancellationToken); - try + cancellationToken)) { - using (CancellationTokenProvider.Use(linkedCancellationToken)) + var linkedCancellationToken = linkedCancellationTokenSource.Token; + + HttpContent responseContent; + _streamingRequest.Value = new StreamingRequest(requestContext, linkedCancellationToken); + try { - responseContent = await RequestAsync(requestContext); + using (CancellationTokenProvider.Use(linkedCancellationToken)) + { + responseContent = await RequestAsync(requestContext); + } + } + finally + { + _streamingRequest.Value = null; } - } - finally - { - _streamingRequest.Value = null; - } - using (responseContent) - { - var options = SystemTextJsonSerializerOptions?.Value.JsonSerializerOptions; + using (responseContent) + { + var options = SystemTextJsonSerializerOptions?.Value.JsonSerializerOptions; #if NET5_0_OR_GREATER - using var stream = await responseContent.ReadAsStreamAsync(linkedCancellationToken); + using (var stream = await responseContent.ReadAsStreamAsync(linkedCancellationToken)) #else - using var stream = await responseContent.ReadAsStreamAsync(); + 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!; + { + var items = System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable(stream, options, linkedCancellationToken); + await foreach (var item in items.WithCancellation(linkedCancellationToken)) + { + yield return item!; + } + } } } } @@ -136,16 +140,24 @@ public class ClientProxyBase : ITransientDependency } // A CancellationToken argument has no request parameter, so it must not shift the arguments after it. - var requestArguments = arguments.Values.Exists(x => x.Key == typeof(CancellationToken)) + var cancellationTokenArgument = arguments.Values.FirstOrDefault(x => x.Key == typeof(CancellationToken)); + var requestArguments = cancellationTokenArgument.Key != null ? arguments.Values.Where(x => x.Key != typeof(CancellationToken)).ToList() : arguments.Values; - return new ClientProxyRequestContext( + var requestContext = new ClientProxyRequestContext( action, actionArguments .Select((x, i) => new KeyValuePair(x.Key, requestArguments[i].Value)) .ToDictionary(x => x.Key, x => x.Value), typeof(TService)); + + if (cancellationTokenArgument.Value is CancellationToken { CanBeCanceled: true } cancellationToken) + { + requestContext.CancellationToken = cancellationToken; + } + + return requestContext; } protected virtual async Task RequestAsync(ClientProxyRequestContext requestContext) @@ -245,6 +257,12 @@ public class ClientProxyBase : ITransientDependency ); } + // Other requests sent meanwhile (e.g. by an overridden RequestAsync) keep their own token. + var streamingRequest = _streamingRequest.Value; + var cancellationToken = streamingRequest != null && ReferenceEquals(streamingRequest.Context, requestContext) + ? streamingRequest.CancellationToken + : requestContext.CancellationToken ?? GetCancellationToken(requestContext.Arguments); + HttpResponseMessage response; try { @@ -253,14 +271,10 @@ 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*/, - streamingRequest != null && ReferenceEquals(streamingRequest.Context, requestContext) - ? streamingRequest.CancellationToken - : requestContext.CancellationToken ?? GetCancellationToken(requestContext.Arguments) + cancellationToken ); } catch (Exception ex) @@ -272,7 +286,11 @@ public class ClientProxyBase : ITransientDependency { try { - await ThrowExceptionForResponseAsync(response); + // The error is read with the token of the request. + using (CancellationTokenProvider.Use(cancellationToken)) + { + await ThrowExceptionForResponseAsync(response); + } } catch { @@ -361,7 +379,11 @@ public class ClientProxyBase : ITransientDependency try { errorResponse = JsonSerializer.Deserialize( +#if NET5_0_OR_GREATER + await response.Content.ReadAsStringAsync(CancellationTokenProvider.Token) +#else await response.Content.ReadAsStringAsync() +#endif ); } catch (Exception ex) 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 b144f4d981..2a0d70f287 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 @@ -129,26 +129,27 @@ public class DynamicHttpProxyInterceptor : AbpInterceptor, ITransientD 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)) + using (var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(methodCancellationToken, cancellationToken)) { - context = new ClientProxyRequestContext( - await GetActionApiDescriptionModel(invocation), - invocation.ArgumentsDictionary, - typeof(TService)); - } + 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; - } + 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; + await foreach (var item in InterceptorClientProxy.CallRequestAsyncEnumerable(context).WithCancellation(cancellationToken)) + { + yield return item; + } } } 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 index c073e6014a..225e012d78 100644 --- 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 @@ -1,5 +1,7 @@ +using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Net.Http; using System.Threading; @@ -28,6 +30,37 @@ public class RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests : AbpH (await ToListAsync(proxy.GetStreamWithLeadingCancellationTokenAsync(CancellationToken.None, 3))).ShouldBe(new[] { 1, 2, 3 }); } + [Fact] + public async Task Should_Send_The_Request_With_The_CancellationToken_Argument() + { + var proxy = ServiceProvider.GetRequiredService(); + using (var cancellationTokenSource = new CancellationTokenSource()) + { + (await ToListAsync(proxy.GetStreamWithLeadingCancellationTokenAsync(cancellationTokenSource.Token, 3))).ShouldBe(new[] { 1, 2, 3 }); + + proxy.RequestContexts.ShouldHaveSingleItem().CancellationToken.ShouldBe(cancellationTokenSource.Token); + } + } + + [Fact] + public async Task Should_Not_Stream_Items_When_The_CancellationToken_Argument_Is_Canceled() + { + var proxy = ServiceProvider.GetRequiredService(); + + var items = new List(); + + var exception = await Should.ThrowAsync(async () => + { + await foreach (var item in proxy.GetStreamWithLeadingCancellationTokenAsync(new CancellationToken(canceled: true), 3)) + { + items.Add(item); + } + }); + + IsCanceled(exception).ShouldBeTrue(exception.ToString()); + items.ShouldBeEmpty(); + } + [Fact] public async Task Should_Send_The_Arguments_In_The_Order_Of_The_Request_Parameters() { @@ -50,6 +83,20 @@ public class RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests : AbpH proxy.RequestContexts.ShouldAllBe(context => context.CancellationToken == null); } + // The test server reports a request canceled after it is sent as an aborted response. + private static bool IsCanceled(Exception? exception) + { + for (; exception != null; exception = exception.InnerException) + { + if (exception is OperationCanceledException || exception is IOException && exception.Message.Contains("aborted")) + { + return true; + } + } + + return false; + } + private static async Task> ToListAsync(IAsyncEnumerable source) { var list = new List(); 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 index e29057781f..fbee68b0f5 100644 --- 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 @@ -114,16 +114,17 @@ public class AsyncEnumerableClientProxy_Request_Cancellation_Tests : AsyncEnumer [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 () => + using (var methodCancellationTokenSource = new CancellationTokenSource()) + using (var enumerationCancellationTokenSource = new CancellationTokenSource()) { - await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token) - .WithCancellation(enumerationCancellationTokenSource.Token)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, enumerationCancellationTokenSource); + await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token) + .WithCancellation(enumerationCancellationTokenSource.Token)) + { + } + }, enumerationCancellationTokenSource); + } } } @@ -142,18 +143,20 @@ public class AsyncEnumerableClientProxy_RequestContext_Cancellation_Tests : Asyn 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) + using (var contextCancellationTokenSource = new CancellationTokenSource()) { - CancellationToken = contextCancellationTokenSource.Token - }; + var requestContext = new ClientProxyRequestContext(action.Action, action.Arguments, action.ServiceType) + { + CancellationToken = contextCancellationTokenSource.Token + }; - await ShouldBeCancelledWhenBlockedAsync(async () => - { - await foreach (var _ in ClientProxy.CallRequestAsyncEnumerable(requestContext)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, contextCancellationTokenSource); + await foreach (var _ in ClientProxy.CallRequestAsyncEnumerable(requestContext)) + { + } + }, contextCancellationTokenSource); + } } [Fact] @@ -162,34 +165,36 @@ public class AsyncEnumerableClientProxy_RequestContext_Cancellation_Tests : Asyn 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(); + 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 () => + using (var methodCancellationTokenSource = new CancellationTokenSource()) { - await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, methodCancellationTokenSource); + await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) + { + } + }, methodCancellationTokenSource); + } } private DynamicHttpProxyInterceptorClientProxy ClientProxy => @@ -198,15 +203,17 @@ public class AsyncEnumerableClientProxy_RequestContext_Cancellation_Tests : Asyn 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 () => + using (var cancellationTokenSource = new CancellationTokenSource()) { - await foreach (var _ in Controller.GetStreamAsync(1).WithCancellation(cancellationTokenSource.Token)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, cancellationTokenSource); + await foreach (var _ in Controller.GetStreamAsync(1).WithCancellation(cancellationTokenSource.Token)) + { + } + }, cancellationTokenSource); - return ServiceProvider.GetRequiredService().Contexts.Last(); + return ServiceProvider.GetRequiredService().Contexts.Last(); + } } private static async Task EnumerateAsync(IAsyncEnumerable sequence, CancellationToken cancellationToken) @@ -238,39 +245,42 @@ public class AsyncEnumerableClientProxy_ApiDefinition_Cancellation_Tests : Async [Fact] public async Task Should_Cancel_Api_Definition_Request_With_Method_Token() { - using var methodCancellationTokenSource = new CancellationTokenSource(); - - await ShouldBeCancelledWhenBlockedAsync(async () => + using (var methodCancellationTokenSource = new CancellationTokenSource()) { - await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, methodCancellationTokenSource); + 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 () => + using (var methodCancellationTokenSource = new CancellationTokenSource()) { - await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, methodCancellationTokenSource); + 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 () => + using (var enumerationCancellationTokenSource = new CancellationTokenSource()) { - await foreach (var _ in Controller.GetStreamAsync(3).WithCancellation(enumerationCancellationTokenSource.Token)) + await ShouldBeCancelledWhenBlockedAsync(async () => { - } - }, enumerationCancellationTokenSource); + 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_Tests.cs b/framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/AsyncEnumerableClientProxy_Tests.cs index bbc048d608..ed4b35e59d 100644 --- 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 @@ -117,23 +117,24 @@ public class AsyncEnumerableClientProxy_Tests : AbpHttpClientTestBase 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 + using (var cancellationTokenSource = new CancellationTokenSource()) { - AsyncEnumerableTestGate.Open(); - } + 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" }); + items.ShouldBe(new[] { "first" }); + } } private static async Task ConsumeAsync(IAsyncEnumerable source, Action onItem) 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 3c2e295aa7..5a46307e5f 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 @@ -132,6 +132,38 @@ public class ClientProxyResponseDisposal_Tests : AbpHttpClientTestBase content.Disposed.ShouldBeTrue(); } + [Fact] + public async Task Async_Enumerable_Error_Response_Should_Stop_Reading_The_Error_And_Dispose_HttpContent_When_Canceled() + { + var content = new PendingHttpContent(); + _factory.SetStubResponse(() => + { + var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) + { + Content = content + }; + response.Headers.Add(AbpHttpConsts.AbpErrorFormat, "true"); + return response; + }); + + using (var cancellationTokenSource = new CancellationTokenSource()) + { + var enumeration = Task.Run(async () => + { + await foreach (var _ in _controller.GetStreamAsync(3).WithCancellation(cancellationTokenSource.Token)) + { + } + }); + + await content.ReadStarted.Task.WaitAsync(TimeSpan.FromSeconds(10)); + cancellationTokenSource.Cancel(); + + var exception = await Should.ThrowAsync(enumeration.WaitAsync(TimeSpan.FromSeconds(10))); + exception.InnerException.ShouldBeAssignableTo(); + content.Disposed.ShouldBeTrue(); + } + } + class StubProxyHttpClientFactory : IProxyHttpClientFactory { private readonly ITestServerAccessor _testServerAccessor; @@ -182,6 +214,37 @@ public class ClientProxyResponseDisposal_Tests : AbpHttpClientTestBase } } + // The error never ends unless the reading is canceled. + class PendingHttpContent : HttpContent + { + public TaskCompletionSource ReadStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool Disposed { get; private set; } + + protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) + { + return SerializeToStreamAsync(stream, context, CancellationToken.None); + } + + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) + { + ReadStarted.TrySetResult(); + await Task.Delay(Timeout.Infinite, cancellationToken); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + + protected override void Dispose(bool disposing) + { + Disposed = true; + base.Dispose(disposing); + } + } + class TrackingHttpContent : HttpContent { private readonly byte[] _data; From 2ed4572667c93522e31c4b481e84223aeb0399c6 Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 17 Nov 2026 09:15:12 +0800 Subject: [PATCH 09/10] Audit the enumeration of a sequence returned by an audited action --- .../framework/infrastructure/audit-logging.md | 4 +- .../Volo/Abp/Auditing/AuditingInterceptor.cs | 21 ++++++ .../StreamingAppService_Auditing_Tests.cs | 43 ++++++++++-- .../Auditing_AsyncEnumerable_Tests.cs | 65 +++++++++++++++++++ .../Application/StreamingAppService.cs | 6 ++ 5 files changed, 131 insertions(+), 8 deletions(-) diff --git a/docs/en/framework/infrastructure/audit-logging.md b/docs/en/framework/infrastructure/audit-logging.md index 9c0eb68b9e..8a21c5fac0 100644 --- a/docs/en/framework/infrastructure/audit-logging.md +++ b/docs/en/framework/infrastructure/audit-logging.md @@ -333,13 +333,13 @@ In addition to the standard properties explained above, `AuditLogInfo`, `AuditLo ### Methods Returning IAsyncEnumerable -A method returning `IAsyncEnumerable` does its work when the returned sequence is enumerated. So, if such a method is audited by the auditing interceptor, the method call and each enumeration of the returned sequence are recorded as separate actions: +A method returning `IAsyncEnumerable` does its work when the returned sequence is enumerated. So, if such a method is audited, the method call and each enumeration of the returned sequence are recorded as separate actions: * The action of the method call is recorded like for other methods. * The action of an enumeration has the `AsyncEnumeration` extra property set to `true`, and its `ExecutionDuration` is the duration of the whole enumeration, regardless of the number of items. The exceptions and the entity changes during the enumeration are also recorded. * If there is no current audit log scope when the sequence is enumerated (for example, in a background job), the enumeration is saved as a separate audit log. -A controller action (including an [Auto API Controller](../api-development/auto-controllers.md) action) returning `IAsyncEnumerable` is audited by the auditing action filter instead, and recorded as a single action of the audit log of the web request. +A controller action is audited by the auditing action filter, which records the method call, while the returned sequence is enumerated after the action, when the result is written to the response. If the controller is intercepted by the auditing interceptor (for example, an application service exposed as an [Auto API Controller](../api-development/auto-controllers.md)), the enumeration is also recorded as an action of the audit log of the web request. Otherwise (for example, a controller derived from `AbpController`), only the method call is recorded. ## Audit Log Contributors diff --git a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs index f27d7bf66d..482dafd7a1 100644 --- a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs +++ b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingInterceptor.cs @@ -34,6 +34,12 @@ public class AuditingInterceptor : AbpInterceptor, ITransientDependency if (!ShouldIntercept(invocation, auditingOptions, auditingHelper)) { await invocation.ProceedAsync(); + + if (IsAuditedByCaller(invocation, auditingOptions, auditingHelper)) + { + WrapAsyncEnumerable(invocation); + } + return; } @@ -173,6 +179,21 @@ public class AuditingInterceptor : AbpInterceptor, ITransientDependency } } + // A caller applying the auditing concern (e.g. the auditing action filter of MVC) audits the method call, + // but not the enumeration of the returned sequence, which happens after the call (e.g. when the result is written). + private static bool IsAuditedByCaller( + IAbpMethodInvocation invocation, + AbpAuditingOptions options, + IAuditingHelper auditingHelper) + { + return TypeHelper.IsAsyncEnumerable(invocation.Method.ReturnType) && + options.IsEnabled && + AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Auditing) && + auditingHelper.ShouldSaveAudit( + invocation.Method, + ignoreIntegrationServiceAttribute: options.IsEnabledForIntegrationServices); + } + private void WrapAsyncEnumerable(IAbpMethodInvocation invocation) { invocation.WrapAsyncEnumerable(() => BeginEnumerationScope(invocation)); diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs index ffb21d2ca1..9052e8c708 100644 --- a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/StreamingAppService_Auditing_Tests.cs @@ -35,7 +35,7 @@ public class StreamingAppService_Auditing_Tests : AspNetCoreMvcTestBase } [Fact] - public async Task Should_Audit_Streaming_Action_Once() + public async Task Should_Audit_The_Call_And_The_Enumeration_Of_A_Streaming_Action() { _options.IsEnabledForGetRequests = true; ProxyHelper.IsProxy(ServiceProvider.GetRequiredService()).ShouldBeTrue(); @@ -45,7 +45,32 @@ public class StreamingAppService_Auditing_Tests : AspNetCoreMvcTestBase result.ShouldBe(new[] { 1, 2 }); GetRequiredService().Results.ShouldBe(new[] { true }); _savedAuditLogs.Count.ShouldBe(1); - _savedAuditLogs[0].Actions.Count(a => a.MethodName == nameof(StreamingAppService.GetItemsAsync)).ShouldBe(1); + var actions = _savedAuditLogs[0].Actions.Where(a => a.MethodName == nameof(StreamingAppService.GetItemsAsync)).ToList(); + actions.Count.ShouldBe(2); + actions.Count(IsEnumeration).ShouldBe(1); + } + + [Fact] + public async Task Should_Record_The_Duration_Of_The_Enumeration_Of_A_Streaming_Action() + { + _options.IsEnabledForGetRequests = true; + + var result = await GetResponseAsObjectAsync>("/api/app/streaming/slow-items"); + + result.ShouldBe(new[] { 1 }); + var enumeration = _savedAuditLogs.Single().Actions.Single(a => a.MethodName == nameof(StreamingAppService.GetSlowItemsAsync) && IsEnumeration(a)); + enumeration.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); + } + + [Fact] + public async Task Should_Not_Audit_The_Enumeration_When_The_Streaming_Action_Is_Not_Audited() + { + _options.IsEnabledForGetRequests = false; + + var result = await GetResponseAsObjectAsync>("/api/app/streaming/items"); + + result.ShouldBe(new[] { 1, 2 }); + _savedAuditLogs.SelectMany(x => x.Actions).ShouldNotContain(a => a.MethodName == nameof(StreamingAppService.GetItemsAsync)); } [Theory] @@ -56,10 +81,11 @@ public class StreamingAppService_Auditing_Tests : AspNetCoreMvcTestBase _options.IsEnabledForGetRequests = true; // AbpExceptionFilter only handles exceptions of actions returning IActionResult for AJAX requests. - using var response = await GetResponseAsync(url, HttpStatusCode.Forbidden, xmlHttpRequest: true); - - (await response.Content.ReadAsStringAsync()).ShouldContain("Failed to create the sequence"); - _savedAuditLogs.Single().Exceptions.ShouldContain(e => e.Message == "Failed to create the sequence"); + using (var response = await GetResponseAsync(url, HttpStatusCode.Forbidden, xmlHttpRequest: true)) + { + (await response.Content.ReadAsStringAsync()).ShouldContain("Failed to create the sequence"); + _savedAuditLogs.Single().Exceptions.ShouldContain(e => e.Message == "Failed to create the sequence"); + } } [Fact] @@ -87,4 +113,9 @@ public class StreamingAppService_Auditing_Tests : AspNetCoreMvcTestBase var controllerAction = _savedAuditLogs.Single().Actions.Single(a => a.ServiceName == typeof(StreamingJsonTestController).FullName); controllerAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); } + + private static bool IsEnumeration(AuditLogActionInfo action) + { + return action.ExtraProperties.ContainsKey(AuditingInterceptor.AsyncEnumerationPropertyName); + } } diff --git a/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs b/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs index dd0a9cfa54..842aedae0d 100644 --- a/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs +++ b/framework/test/Volo.Abp.Auditing.Tests/Volo/Abp/Auditing/Auditing_AsyncEnumerable_Tests.cs @@ -8,7 +8,9 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using NSubstitute; using Shouldly; +using Volo.Abp.Auditing.App.Entities; using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Repositories; using Volo.Abp.Uow; using Xunit; @@ -124,6 +126,37 @@ public class Auditing_AsyncEnumerable_Tests : AbpAuditingTestBase firstChange.ShouldNotBeSameAs(secondChange); } + [Fact] + public async Task Should_Record_The_Entity_Changes_Saved_By_The_Unit_Of_Work_Of_The_Enumeration_In_Its_Audit_Log() + { + var entityId = Guid.NewGuid(); + var sequence = GetRequiredService().InsertAndStreamAsync(entityId, fail: false); + + (await ToListAsync(sequence)).ShouldBe(new[] { 1 }); + + _savedAuditLogs.Count.ShouldBe(2); + _savedAuditLogs[0].EntityChanges.ShouldBeEmpty(); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + var entityChange = _savedAuditLogs[1].EntityChanges.ShouldHaveSingleItem(); + entityChange.EntityId.ShouldBe(entityId.ToString()); + entityChange.ChangeType.ShouldBe(EntityChangeType.Created); + (await FindAppEntityWithAuditedAsync(entityId)).ShouldNotBeNull(); + } + + [Fact] + public async Task Should_Not_Save_The_Entity_Of_A_Failed_Enumeration_And_Record_The_Exception_In_Its_Audit_Log() + { + var entityId = Guid.NewGuid(); + var sequence = GetRequiredService().InsertAndStreamAsync(entityId, fail: true); + + await Should.ThrowAsync(ToListAsync(sequence)); + + _savedAuditLogs.Count.ShouldBe(2); + IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); + _savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Stream failed after inserting"); + (await FindAppEntityWithAuditedAsync(entityId)).ShouldBeNull(); + } + [Fact] public async Task Should_Add_A_Nested_Sequence_To_The_Audit_Log_Of_The_Enumeration_That_Uses_It() { @@ -282,6 +315,16 @@ public class Auditing_AsyncEnumerable_Tests : AbpAuditingTestBase } } + private async Task FindAppEntityWithAuditedAsync(Guid id) + { + using (var unitOfWork = GetRequiredService().Begin()) + { + var entity = await GetRequiredService>().FindAsync(id); + await unitOfWork.CompleteAsync(); + return entity; + } + } + private static bool IsEnumeration(AuditLogActionInfo action) { return action.ExtraProperties.TryGetValue(AuditingInterceptor.AsyncEnumerationPropertyName, out var value) && value is true; @@ -298,6 +341,28 @@ public class Auditing_AsyncEnumerable_Tests : AbpAuditingTestBase return list; } + public class MyStreamingAuditedUnitOfWorkObject : ITransientDependency, IAuditingEnabled, IUnitOfWorkEnabled + { + private readonly IBasicRepository _repository; + + public MyStreamingAuditedUnitOfWorkObject(IBasicRepository repository) + { + _repository = repository; + } + + // The entity is saved when the unit of work of the enumeration is completed. + public virtual async IAsyncEnumerable InsertAndStreamAsync(Guid id, bool fail) + { + await _repository.InsertAsync(new AppEntityWithAudited(id, "streamed")); + yield return 1; + + if (fail) + { + throw new InvalidOperationException("Stream failed after inserting"); + } + } + } + public class MyStreamingAuditedObject : ITransientDependency, IAuditingEnabled { private readonly IAuditingManager _auditingManager; diff --git a/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs index 7940410a07..1564a7c4a6 100644 --- a/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs +++ b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/StreamingAppService.cs @@ -13,6 +13,12 @@ public class StreamingAppService : ApplicationService yield return 2; } + public virtual async IAsyncEnumerable GetSlowItemsAsync() + { + await Task.Delay(50); + yield return 1; + } + public virtual IAsyncEnumerable GetItemsWithCreationErrorAsync() { throw new UserFriendlyException("Failed to create the sequence"); From d12f8acb23d95b44a13bc164b27421309f65ba00 Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 17 Nov 2026 09:15:12 +0800 Subject: [PATCH 10/10] Test the scopes of async enumerations and document their limits --- .../domain-driven-design/unit-of-work.md | 1 + .../framework/infrastructure/interceptors.md | 2 + .../AbpAsyncEnumerableInterceptionTestBase.cs | 75 ++++++++++++++++--- ...yncEnumerableConcurrentScopedTestObject.cs | 20 +++++ .../ConcurrentScopeTestInterceptor.cs | 46 ++++++++++++ .../AsyncEnumerable_Interception_Tests.cs | 24 ++++++ 6 files changed, 158 insertions(+), 10 deletions(-) create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentScopedTestObject.cs create mode 100644 framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ConcurrentScopeTestInterceptor.cs diff --git a/docs/en/framework/architecture/domain-driven-design/unit-of-work.md b/docs/en/framework/architecture/domain-driven-design/unit-of-work.md index d6f7b619e5..2580265368 100644 --- a/docs/en/framework/architecture/domain-driven-design/unit-of-work.md +++ b/docs/en/framework/architecture/domain-driven-design/unit-of-work.md @@ -40,6 +40,7 @@ A method returning `IAsyncEnumerable` does its work when the returned sequenc * The method call and each enumeration of the returned sequence run in separate UOWs (or participate in the surrounding UOW, if there is one). * The UOW of an enumeration is completed when the enumeration ends, even if the caller stops it early. It is not completed if the sequence throws an exception. +* If the work must not be saved when the caller fails while consuming the sequence (e.g. while writing the items to an HTTP response), begin a transactional UOW with `requiresNew: true` around the enumeration and complete it only after all the items are consumed. The enumeration participates in this UOW, so its changes are rolled back unless you complete it. This requires a database provider that supports transactions; changes already saved in a non-transactional UOW can not be rolled back. * Query the database inside the iterator method (the method body containing `yield return`). A `DbContext` or a query obtained while calling the method can not be used after the UOW of the call ends. ### Database Transaction Behavior diff --git a/docs/en/framework/infrastructure/interceptors.md b/docs/en/framework/infrastructure/interceptors.md index cfb6438c0d..33ec7119fe 100644 --- a/docs/en/framework/infrastructure/interceptors.md +++ b/docs/en/framework/infrastructure/interceptors.md @@ -235,6 +235,8 @@ ABP's [Unit of Work](../architecture/domain-driven-design/unit-of-work.md), [Aud > Since the authorization and other checks are performed when the method is called, you should enumerate the returned sequence in the same context (the same user and tenant) as the method call. +> A method with a `ref`, `out` or `in` parameter is intercepted only when it is called, so its enumerations are not covered by a scope. + ## Restrictions and Important Notes ### Always use asynchronous methods diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs index eba4228bb0..eaf08fbf94 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs @@ -27,6 +27,8 @@ public abstract class AbpAsyncEnumerableInterceptionTestBase : A services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddSingleton(); services.AddTransient(); @@ -72,6 +74,11 @@ public abstract class AbpAsyncEnumerableInterceptionTestBase : A registration.Interceptors.Add(); } + if (typeof(AsyncEnumerableConcurrentScopedTestObject) == registration.ImplementationType) + { + registration.Interceptors.Add(); + } + if (typeof(AsyncEnumerableGatedTestObject) == registration.ImplementationType) { registration.Interceptors.Add(); @@ -225,18 +232,19 @@ public abstract class AbpAsyncEnumerableInterceptionTestBase : A { var target = ServiceProvider.GetRequiredService(); var items = new List(); - using var cancellationTokenSource = new CancellationTokenSource(); - - await Should.ThrowAsync(async () => + using (var cancellationTokenSource = new CancellationTokenSource()) { - await foreach (var item in target.GetOneThenWaitAsync().WithCancellation(cancellationTokenSource.Token)) + await Should.ThrowAsync(async () => { - items.Add(item); - cancellationTokenSource.CancelAfter(50); - } - }).WaitAsync(TimeSpan.FromSeconds(10)); - - items.ShouldBe(new[] { 1 }); + await foreach (var item in target.GetOneThenWaitAsync().WithCancellation(cancellationTokenSource.Token)) + { + items.Add(item); + cancellationTokenSource.CancelAfter(50); + } + }).WaitAsync(TimeSpan.FromSeconds(10)); + + items.ShouldBe(new[] { 1 }); + } } [Fact] @@ -265,6 +273,53 @@ public abstract class AbpAsyncEnumerableInterceptionTestBase : A results[1].ShouldBe(new[] { 1, 2, 3 }); } + [Fact] + public async Task Should_Keep_The_Scopes_Of_Concurrent_Enumerations_Separate_When_One_Is_Canceled() + { + var target = ServiceProvider.GetRequiredService(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var sequence = target.GetScopeIdsAsync(gate.Task); + var canceledIds = new List(); + var completedIds = new List(); + var completedFirstItem = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + using (var cancellationTokenSource = new CancellationTokenSource()) + { + var canceled = Task.Run(async () => + { + await foreach (var scopeId in sequence.WithCancellation(cancellationTokenSource.Token)) + { + canceledIds.Add(scopeId); + await completedFirstItem.Task; + cancellationTokenSource.Cancel(); + } + }); + var completed = Task.Run(async () => + { + await foreach (var scopeId in sequence) + { + completedIds.Add(scopeId); + completedFirstItem.TrySetResult(); + } + }); + + await Should.ThrowAsync(canceled.WaitAsync(TimeSpan.FromSeconds(10))); + gate.SetResult(); + await completed.WaitAsync(TimeSpan.FromSeconds(10)); + } + + var canceledScopeId = canceledIds.ShouldHaveSingleItem().ShouldNotBeNull(); + completedIds.Count.ShouldBe(2); + var completedScopeId = completedIds[0].ShouldNotBeNull(); + completedIds[1].ShouldBe(completedScopeId); + completedScopeId.ShouldNotBe(canceledScopeId); + ConcurrentScopeTestInterceptor.ScopeId.Value.ShouldBeNull(); + + var events = target.Events.ToList(); + events.Where(e => e.StartsWith(canceledScopeId)).ShouldBe(new[] { $"{canceledScopeId}:Failed", $"{canceledScopeId}:Disposed" }); + events.Where(e => e.StartsWith(completedScopeId)).ShouldBe(new[] { $"{completedScopeId}:Completed", $"{completedScopeId}:Disposed" }); + } + [Fact] public async Task Should_Keep_The_Scope_Of_The_Interceptor_For_Every_Step_Of_The_Enumeration() { diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentScopedTestObject.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentScopedTestObject.cs new file mode 100644 index 0000000000..03a903372d --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentScopedTestObject.cs @@ -0,0 +1,20 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class AsyncEnumerableConcurrentScopedTestObject +{ + public ConcurrentQueue Events { get; } = new(); + + public virtual async IAsyncEnumerable GetScopeIdsAsync(Task gate, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.Yield(); + yield return ConcurrentScopeTestInterceptor.ScopeId.Value; + await gate.WaitAsync(cancellationToken); + yield return ConcurrentScopeTestInterceptor.ScopeId.Value; + } +} diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ConcurrentScopeTestInterceptor.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ConcurrentScopeTestInterceptor.cs new file mode 100644 index 0000000000..04b21b06ce --- /dev/null +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ConcurrentScopeTestInterceptor.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Volo.Abp.DynamicProxy; + +public class ConcurrentScopeTestInterceptor : AbpScopeInterceptor +{ + public static readonly AsyncLocal ScopeId = new(); + + protected override IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation) + { + var scopeId = Guid.NewGuid().ToString("N"); + ScopeId.Value = scopeId; + return new EventRecordingScope((AsyncEnumerableConcurrentScopedTestObject)invocation.TargetObject, scopeId); + } + + private class EventRecordingScope : IAbpInterceptionScope + { + private readonly AsyncEnumerableConcurrentScopedTestObject _target; + private readonly string _scopeId; + + public EventRecordingScope(AsyncEnumerableConcurrentScopedTestObject target, string scopeId) + { + _target = target; + _scopeId = scopeId; + } + + public Task CompleteAsync(CancellationToken cancellationToken) + { + _target.Events.Enqueue($"{_scopeId}:Completed"); + return Task.CompletedTask; + } + + public Task FailAsync(Exception exception) + { + _target.Events.Enqueue($"{_scopeId}:Failed"); + return Task.CompletedTask; + } + + public void Dispose() + { + _target.Events.Enqueue($"{_scopeId}:Disposed"); + } + } +} diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs index 8b32360f9c..bf7cf0132a 100644 --- a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AsyncEnumerable/AsyncEnumerable_Interception_Tests.cs @@ -288,6 +288,30 @@ public class AsyncEnumerable_Interception_Tests : EntityFrameworkCoreTestBase } } + [Fact] + public async Task Should_Roll_Back_The_Unit_Of_Work_Of_A_Consumer_That_Fails() + { + await InsertPersonAsync("Aaron"); + var originalAges = await GetAgesAsync(); + + await Should.ThrowAsync(async () => + { + using (var unitOfWork = _unitOfWorkManager.Begin(new AbpUnitOfWorkOptions(isTransactional: true), requiresNew: true)) + { + await foreach (var _ in _appService.IncreaseAgesAsync()) + { + throw new InvalidOperationException("Failed while consuming"); + } + + await unitOfWork.CompleteAsync(); + } + }); + + _tracker.SourceDisposed.ShouldBeTrue(); + _tracker.UnitOfWorkCompleted.ShouldBeFalse(); + (await GetAgesAsync()).ShouldBe(originalAges); + } + [Fact] public async Task Should_Join_Outer_Unit_Of_Work() {