From d33daa82f5c94910a22109c05d439c616a4e6547 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 16 Nov 2026 10:01:55 +0800 Subject: [PATCH] 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; + } +}