Browse Source

Support IAsyncEnumerable in async interceptors

pull/26490/head
maliming 1 week ago
parent
commit
d33daa82f5
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 4
      framework/src/Volo.Abp.Castle.Core/Volo.Abp.Castle.Core.csproj
  2. 12
      framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/AbpAsyncDeterminationInterceptor.cs
  3. 127
      framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/CastleAsyncEnumerableAbpInterceptor.cs
  4. 30
      framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpInterceptionScope.cs
  5. 177
      framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions.cs
  6. 31
      framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpMethodInvocationScopeExtensions.cs
  7. 23
      framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/AbpScopeInterceptor.cs
  8. 8
      framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptedAsyncEnumerable.cs
  9. 15
      framework/src/Volo.Abp.Core/Volo/Abp/DynamicProxy/IAbpInterceptionScope.cs
  10. 5
      framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs
  11. 13
      framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_AsyncEnumerable_Interception_Test.cs
  12. 660
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpAsyncEnumerableInterceptionTestBase.cs
  13. 44
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionScope_Tests.cs
  14. 84
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpMethodInvocationAsyncEnumerableExtensions_Tests.cs
  15. 8
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableCallerContext.cs
  16. 16
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableConcurrentTestObject.cs
  17. 14
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableDecoratedTestObject.cs
  18. 15
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedScopedTestObject.cs
  19. 19
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableGatedTestObject.cs
  20. 57
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableInterceptionTargetClass.cs
  21. 13
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableNullReturnValueTestObject.cs
  22. 122
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopeInterceptorTestObject.cs
  23. 31
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableScopedTestObject.cs
  24. 15
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableThrowingInterceptorTestObject.cs
  25. 132
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableValueTaskSourceTestObject.cs
  26. 12
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AsyncEnumerableWrongReturnValueTestObject.cs
  27. 8
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/CachedTestObject.cs
  28. 77
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/EventLoggingScopeInterceptor.cs
  29. 14
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/GatedTestInterceptor.cs
  30. 21
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/MultiplyingTestInterceptor.cs
  31. 12
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/NullReturnValueTestInterceptor.cs
  32. 19
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/RetryOnceTestInterceptor.cs
  33. 10
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeEventLog.cs
  34. 50
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/ScopeTestInterceptor.cs
  35. 13
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/WrongReturnValueTestInterceptor.cs

4
framework/src/Volo.Abp.Castle.Core/Volo.Abp.Castle.Core.csproj

@ -21,6 +21,10 @@
<PackageReference Include="Castle.Core.AsyncInterceptor" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Volo.Abp.Core\Volo.Abp.Core.csproj" />
</ItemGroup>

12
framework/src/Volo.Abp.Castle.Core/Volo/Abp/Castle/DynamicProxy/AbpAsyncDeterminationInterceptor.cs

@ -6,9 +6,21 @@ namespace Volo.Abp.Castle.DynamicProxy;
public class AbpAsyncDeterminationInterceptor<TInterceptor> : AsyncDeterminationInterceptor
where TInterceptor : IAbpInterceptor
{
private readonly TInterceptor _abpInterceptor;
public AbpAsyncDeterminationInterceptor(TInterceptor abpInterceptor)
: base(new CastleAsyncAbpInterceptorAdapter<TInterceptor>(abpInterceptor))
{
_abpInterceptor = abpInterceptor;
}
public override void Intercept(IInvocation invocation)
{
if (CastleAsyncEnumerableAbpInterceptor.TryIntercept(invocation, _abpInterceptor))
{
return;
}
base.Intercept(invocation);
}
}

127
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<Type, AsyncEnumerableHandler> Handlers = new();
private static readonly ConcurrentDictionary<MethodInfo, bool> 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<T>(IInvocation invocation, IAbpInterceptor interceptor)
{
var methodInvocation = new CastleAbpMethodInvocationAdapterWithReturnValue<IAsyncEnumerable<T>>(
invocation,
invocation.CaptureProceedInfo(),
ProceedAsync<T>);
return new InterceptedAsyncEnumerable<T>(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<IAsyncEnumerable<T>> ProceedAsync<T>(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<T> next)
{
return (await next.GetResultAsync())!;
}
return (IAsyncEnumerable<T>)invocation.ReturnValue!;
}
private class InterceptedAsyncEnumerable<T> : IAsyncEnumerable<T>, IAbpInterceptedAsyncEnumerable
{
private readonly Task _interceptTask;
private readonly IAbpMethodInvocation _methodInvocation;
public InterceptedAsyncEnumerable(Task interceptTask, IAbpMethodInvocation methodInvocation)
{
_interceptTask = interceptTask;
_methodInvocation = methodInvocation;
}
public async Task<IAsyncEnumerable<T>?> GetResultAsync()
{
await _interceptTask;
return (IAsyncEnumerable<T>?)_methodInvocation.ReturnValue;
}
public Task WaitForInterceptorsAsync()
{
return GetResultAsync();
}
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return EnumerateAsync(cancellationToken).GetAsyncEnumerator(cancellationToken);
}
private async IAsyncEnumerable<T> 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;
}
}
}
}

30
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();
}
}

177
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<IAbpInterceptionScope> beginScope);
private static readonly MethodInfo WrapMethod = typeof(AbpMethodInvocationAsyncEnumerableExtensions)
.GetMethod(nameof(Wrap), BindingFlags.Static | BindingFlags.NonPublic)!;
private static readonly ConcurrentDictionary<MethodInfo, WrapHandler?> WrapHandlers = new();
/// <summary>
/// Runs each enumeration of a returned <see cref="IAsyncEnumerable{T}"/> in a new scope.
/// <paramref name="beginScope"/> must set its async local values (e.g. the ambient unit of work) synchronously.
/// </summary>
public static bool WrapAsyncEnumerable(this IAbpMethodInvocation invocation, Func<IAbpInterceptionScope> 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<T>(object source, Func<IAbpInterceptionScope> beginScope)
{
return EnumerateInScopeAsync((IAsyncEnumerable<T>)source, beginScope);
}
private static async IAsyncEnumerable<T> EnumerateInScopeAsync<T>(
IAsyncEnumerable<T> source,
Func<IAbpInterceptionScope> 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<T> 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<bool> MoveNextAsync<T>(IAsyncEnumerator<T> enumerator)
{
return await enumerator.MoveNextAsync();
}
private static async ValueTask DisposeAsync<T>(IAsyncEnumerator<T> enumerator)
{
await enumerator.DisposeAsync();
}
private static TResult Run<TResult>(ExecutionContext context, Func<TResult> func)
{
TResult result = default!;
ExecutionContext.Run(context.CreateCopy(), _ => result = func(), null);
return result;
}
}

31
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
{
/// <summary>
/// Also runs each enumeration of a returned <see cref="System.Collections.Generic.IAsyncEnumerable{T}"/> in a new scope.
/// <paramref name="beginScope"/> must set its async local values (e.g. the ambient unit of work) synchronously.
/// </summary>
public static async Task ProceedInScopeAsync(this IAbpMethodInvocation invocation, Func<IAbpInterceptionScope> beginScope)
{
using (var scope = beginScope())
{
try
{
await invocation.ProceedAsync();
}
catch (Exception exception)
{
await scope.FailAsync(exception);
throw;
}
await scope.CompleteAsync(default);
}
invocation.WrapAsyncEnumerable(beginScope);
}
}

23
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;
}
/// <summary>
/// Must set its async local values synchronously.
/// </summary>
protected abstract IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation);
}

8
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();
}

15
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
{
/// <summary>
/// Also called when the caller stops enumerating early.
/// </summary>
Task CompleteAsync(CancellationToken cancellationToken);
Task FailAsync(Exception exception);
}

5
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 &&

13
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<AutofacTestModule>
{
protected override Task<Action<AbpApplicationCreationOptions>> SetAbpApplicationCreationOptionsAsync()
{
return Task.FromResult<Action<AbpApplicationCreationOptions>>(options => options.UseAutofac());
}
}

660
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<TStartupModule> : AbpAsyncIntegratedTest<TStartupModule>, IAsyncLifetime
where TStartupModule : IAbpModule
{
protected override Task BeforeAddApplicationAsync(IServiceCollection services)
{
services.AddTransient<SimpleAsyncInterceptor>();
services.AddTransient<SimpleAsyncInterceptor2>();
services.AddTransient<SimpleResultCacheTestInterceptor>();
services.AddTransient<AlwaysExceptionAsyncInterceptor>();
services.AddSingleton<GatedTestInterceptor>();
services.AddTransient<MultiplyingTestInterceptor>();
services.AddTransient<RetryOnceTestInterceptor>();
services.AddTransient<AsyncEnumerableInterceptionTargetClass>();
services.AddTransient<AsyncEnumerableGatedTestObject>();
services.AddTransient<AsyncEnumerableGatedScopedTestObject>();
services.AddTransient<AsyncEnumerableConcurrentTestObject>();
services.AddTransient<ScopeTestInterceptor>();
services.AddSingleton<ScopeEventLog>();
services.AddTransient<EventLoggingScopeInterceptor>();
services.AddTransient<AsyncEnumerableScopeInterceptorTestObject>();
services.AddTransient<AsyncEnumerableScopedTestObject>();
services.AddTransient<AsyncEnumerableValueTaskSourceTestObject>();
services.AddTransient<AsyncEnumerableThrowingInterceptorTestObject>();
services.AddTransient<WrongReturnValueTestInterceptor>();
services.AddTransient<AsyncEnumerableWrongReturnValueTestObject>();
services.AddTransient<NullReturnValueTestInterceptor>();
services.AddTransient<AsyncEnumerableNullReturnValueTestObject>();
services.AddTransient<AsyncEnumerableDecoratedTestObject>();
services.AddTransient<CachedTestObject>();
services.OnRegistered(registration =>
{
if (typeof(AsyncEnumerableInterceptionTargetClass) == registration.ImplementationType)
{
registration.Interceptors.Add<SimpleAsyncInterceptor>();
registration.Interceptors.Add<SimpleAsyncInterceptor2>();
registration.Interceptors.Add<RetryOnceTestInterceptor>();
}
if (typeof(AsyncEnumerableScopeInterceptorTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<EventLoggingScopeInterceptor>();
}
if (typeof(AsyncEnumerableScopedTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<SimpleAsyncInterceptor>();
registration.Interceptors.Add<ScopeTestInterceptor>();
}
if (typeof(AsyncEnumerableValueTaskSourceTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<ScopeTestInterceptor>();
}
if (typeof(AsyncEnumerableConcurrentTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<SimpleAsyncInterceptor>();
registration.Interceptors.Add<SimpleAsyncInterceptor2>();
}
if (typeof(AsyncEnumerableGatedTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<GatedTestInterceptor>();
}
if (typeof(AsyncEnumerableGatedScopedTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<GatedTestInterceptor>();
registration.Interceptors.Add<ScopeTestInterceptor>();
}
if (typeof(AsyncEnumerableWrongReturnValueTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<WrongReturnValueTestInterceptor>();
}
if (typeof(AsyncEnumerableNullReturnValueTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<NullReturnValueTestInterceptor>();
}
if (typeof(AsyncEnumerableThrowingInterceptorTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<AlwaysExceptionAsyncInterceptor>();
}
if (typeof(AsyncEnumerableDecoratedTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<MultiplyingTestInterceptor>();
}
if (typeof(CachedTestObject) == registration.ImplementationType)
{
registration.Interceptors.Add<SimpleResultCacheTestInterceptor>();
}
});
return Task.CompletedTask;
}
[Fact]
public async Task Should_Intercept_The_Call_And_Enumerate_Lazily()
{
var target = ServiceProvider.GetRequiredService<AsyncEnumerableInterceptionTargetClass>();
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<AsyncEnumerableGatedTestObject>();
var interceptor = ServiceProvider.GetRequiredService<GatedTestInterceptor>();
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<AsyncEnumerableThrowingInterceptorTestObject>();
var sequence = target.GetItemsAsync();
await Should.ThrowAsync<AbpException>(ToListAsync(sequence));
target.Invoked.ShouldBeFalse();
}
[Fact]
public async Task Should_Throw_If_Interceptor_Sets_Wrong_Return_Value_Type()
{
var target = ServiceProvider.GetRequiredService<AsyncEnumerableWrongReturnValueTestObject>();
await Should.ThrowAsync<InvalidCastException>(ToListAsync(target.GetItemsAsync()));
}
[Fact]
public async Task Should_Enumerate_Return_Value_Replaced_By_Interceptor()
{
var target = ServiceProvider.GetRequiredService<AsyncEnumerableDecoratedTestObject>();
(await ToListAsync(target.GetItemsAsync())).ShouldBe(new[] { 10, 20 });
}
[Fact]
public async Task Should_Enumerate_Return_Value_Of_Short_Circuiting_Interceptor()
{
var target = ServiceProvider.GetRequiredService<CachedTestObject>();
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<AsyncEnumerableInterceptionTargetClass>();
(await ToListAsync(target.GetItemsCreatedOnSecondAttempt())).ShouldBe(new[] { 1 });
}
[Fact]
public async Task Should_Propagate_Exception_Thrown_After_Items_Were_Delivered()
{
var target = ServiceProvider.GetRequiredService<AsyncEnumerableInterceptionTargetClass>();
var items = new List<int>();
var exception = await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableInterceptionTargetClass>();
var items = new List<int>();
using var cancellationTokenSource = new CancellationTokenSource();
await Should.ThrowAsync<OperationCanceledException>(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<AsyncEnumerableInterceptionTargetClass>();
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<AsyncEnumerableConcurrentTestObject>();
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<AsyncEnumerableScopedTestObject>();
var values = new List<string?>();
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<AsyncEnumerableValueTaskSourceTestObject>();
var enumerator = target.GetScopeValuesAsync(fail: false).GetAsyncEnumerator();
ValueTask<bool> moveNext;
using (ExecutionContext.SuppressFlow())
{
moveNext = enumerator.MoveNextAsync();
ExecutionContext.IsFlowSuppressed().ShouldBeTrue();
ScopeTestInterceptor.ScopeValue.Value.ShouldBeNull();
}
var values = new List<string?>();
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<AsyncEnumerableGatedTestObject>();
var interceptor = ServiceProvider.GetRequiredService<GatedTestInterceptor>();
var enumerator = target.GetCallerValueAsync().GetAsyncEnumerator();
AsyncEnumerableCallerContext.Value.Value = "enumeration";
ValueTask<bool> 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<AsyncEnumerableGatedScopedTestObject>();
var interceptor = ServiceProvider.GetRequiredService<GatedTestInterceptor>();
var enumerator = target.GetCallerAndScopeValuesAsync().GetAsyncEnumerator();
AsyncEnumerableCallerContext.Value.Value = "enumeration";
ValueTask<bool> moveNext;
using (ExecutionContext.SuppressFlow())
{
moveNext = enumerator.MoveNextAsync();
ExecutionContext.IsFlowSuppressed().ShouldBeTrue();
}
AsyncEnumerableCallerContext.Value.Value = "changed";
interceptor.Gate.SetResult(true);
var values = new List<string>();
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<AsyncEnumerableScopedTestObject>();
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<AsyncEnumerableValueTaskSourceTestObject>();
var items = new List<int>();
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<AsyncEnumerableValueTaskSourceTestObject>();
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<AsyncEnumerableValueTaskSourceTestObject>();
var items = new List<int>();
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<AsyncEnumerableScopedTestObject>();
await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopedTestObject>();
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<AsyncEnumerableNullReturnValueTestObject>();
(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
var exception = await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
var exception = await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
var exception = await Should.ThrowAsync<InvalidOperationException>(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<AsyncEnumerableScopeInterceptorTestObject>();
var log = ServiceProvider.GetRequiredService<ScopeEventLog>();
// Stopping early runs the finally block of the source in DisposeAsync, not in MoveNextAsync.
await Should.ThrowAsync<InvalidOperationException>(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<List<T>> ToListAsync<T>(IAsyncEnumerable<T> source)
{
var list = new List<T>();
await foreach (var item in source)
{
list.Add(item);
}
return list;
}
}

44
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;
}
}
}

84
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<string?> 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<string?>)invocation.ReturnValue).GetAsyncEnumerator();
ValueTask<bool> moveNext;
using (ExecutionContext.SuppressFlow())
{
moveNext = enumerator.MoveNextAsync();
ExecutionContext.IsFlowSuppressed().ShouldBeTrue();
ScopeValue.Value.ShouldBeNull();
}
var values = new List<string?>();
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<string?> 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<object?>();
public IReadOnlyDictionary<string, object?> ArgumentsDictionary => new Dictionary<string, object?>();
public Type[]? GenericArguments => null;
public object? TargetObject => null;
public MethodInfo Method { get; }
public object ReturnValue { get; set; } = default!;
public Task ProceedAsync()
{
return Task.CompletedTask;
}
}
}

8
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<string?> Value = new();
}

16
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<int> GetItemsAsync(int count)
{
for (var i = 1; i <= count; i++)
{
await Task.Yield();
yield return i;
}
}
}

14
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<int> GetItemsAsync()
{
await Task.Yield();
yield return 1;
yield return 2;
}
}

15
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<string> GetCallerAndScopeValuesAsync()
{
await Task.Yield();
yield return $"{AsyncEnumerableCallerContext.Value.Value}:{ScopeTestInterceptor.ScopeValue.Value}";
await Task.Yield();
yield return $"{AsyncEnumerableCallerContext.Value.Value}:{ScopeTestInterceptor.ScopeValue.Value}";
}
}

19
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<int> GetItemsAsync()
{
await Task.Yield();
yield return 1;
}
public virtual async IAsyncEnumerable<string?> GetCallerValueAsync()
{
await Task.Yield();
yield return AsyncEnumerableCallerContext.Value.Value;
}
}

57
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<string> Logs { get; } = new List<string>();
public virtual async IAsyncEnumerable<int> 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<int> GetOneThenWaitAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.Yield();
yield return 1;
await Task.Delay(Timeout.Infinite, cancellationToken);
yield return 2;
}
public virtual async IAsyncEnumerable<int> GetOneThenThrowAsync()
{
await Task.Yield();
yield return 1;
throw new InvalidOperationException("Failed after first item");
}
public virtual IAsyncEnumerable<int> GetItemsCreatedOnSecondAttempt()
{
if (Interlocked.Increment(ref _createAttempts) == 1)
{
throw new InvalidOperationException("First attempt failed");
}
return GetItemsAsync(1);
}
public virtual IAsyncEnumerable<int> GetItemsWithOutParameter(out int value)
{
value = 42;
return GetItemsAsync(1);
}
}

13
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<int> GetItemsAsync()
{
await Task.Yield();
yield return 1;
}
}

122
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<int> GetValueAsync()
{
Interlocked.Increment(ref _log.TargetInvocations);
return Task.FromResult(42);
}
public virtual async IAsyncEnumerable<int> GetItemsWithoutScopeAsync()
{
await Task.Yield();
yield return 1;
}
public virtual IAsyncEnumerable<int> 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<int> GetItemsThrowingOnGetAsyncEnumerator()
{
Interlocked.Increment(ref _log.TargetInvocations);
return new ThrowingOnGetAsyncEnumeratorSequence();
}
public virtual IAsyncEnumerable<int> GetItemsThrowingOnCurrent(bool throwOnDispose = false)
{
Interlocked.Increment(ref _log.TargetInvocations);
return new ThrowingOnCurrentSequence(_log, throwOnDispose);
}
public virtual async IAsyncEnumerable<int> GetItemsWithFailingCompleteAsync()
{
await Task.Yield();
yield return 1;
}
public virtual async IAsyncEnumerable<int> GetItemsWithFailingFailAsync()
{
await Task.Yield();
yield return 1;
throw new InvalidOperationException("Source failed");
}
private class ThrowingOnCurrentSequence : IAsyncEnumerable<int>, IAsyncEnumerator<int>
{
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<int> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return this;
}
public ValueTask<bool> MoveNextAsync()
{
return new ValueTask<bool>(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<int>
{
public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
throw new InvalidOperationException("Failed on GetAsyncEnumerator");
}
}
private static async IAsyncEnumerable<int> ProduceAsync(bool throwOnDispose)
{
try
{
await Task.Yield();
yield return 1;
}
finally
{
if (throwOnDispose)
{
throw new InvalidOperationException("Failed on dispose");
}
}
}
}

31
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<string> Logs { get; } = new();
public virtual async IAsyncEnumerable<string?> GetCallerValuesAsync()
{
await Task.Yield();
yield return AsyncEnumerableCallerContext.Value.Value;
await Task.Yield();
yield return AsyncEnumerableCallerContext.Value.Value;
}
public virtual async IAsyncEnumerable<string?> 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;
}
}

15
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<int> GetItemsAsync()
{
Invoked = true;
return AsyncEnumerable.Empty<int>();
}
}

132
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<int> GetItemsAsync(bool completeAsynchronously)
{
return new ValueTaskSourceSequence(Logs, completeAsynchronously, completeWithoutExecutionContext: false);
}
public virtual IAsyncEnumerable<int> GetItemsCompletedWithoutExecutionContextAsync()
{
return new ValueTaskSourceSequence(Logs, completeAsynchronously: true, completeWithoutExecutionContext: true);
}
/// <summary>
/// Records the scope value when its value tasks are completed and their results are read.
/// </summary>
private class ValueTaskSourceSequence : IAsyncEnumerable<int>, IAsyncEnumerator<int>, IValueTaskSource<bool>, IValueTaskSource
{
private readonly List<string> _logs;
private readonly bool _completeAsynchronously;
private readonly bool _completeWithoutExecutionContext;
private ManualResetValueTaskSourceCore<bool> _core;
private bool _result;
private int _current;
public ValueTaskSourceSequence(List<string> logs, bool completeAsynchronously, bool completeWithoutExecutionContext)
{
_logs = logs;
_completeAsynchronously = completeAsynchronously;
_completeWithoutExecutionContext = completeWithoutExecutionContext;
}
public int Current => _current;
public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return this;
}
public ValueTask<bool> MoveNextAsync()
{
_core.Reset();
Complete(++_current <= 2);
return new ValueTask<bool>(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<bool>.GetResult(short token)
{
_logs.Add($"MoveNext:{ScopeTestInterceptor.ScopeValue.Value}");
return _core.GetResult(token);
}
ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) => _core.GetStatus(token);
void IValueTaskSource<bool>.OnCompleted(Action<object?> 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<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
{
OnCompleted(continuation, state, token, flags);
}
private void OnCompleted(Action<object?> 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);
});
}
}
}
}

12
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<int> GetItemsAsync()
{
return AsyncEnumerable.Empty<int>();
}
}

8
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<int> GetValuesAsync(int v)
{
await Task.Delay(5);
yield return v;
yield return v + 1;
}
}

77
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");
}
}
}

14
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<bool> Gate { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override async Task InterceptAsync(IAbpMethodInvocation invocation)
{
await Gate.Task;
await invocation.ProceedAsync();
}
}

21
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<int>)invocation.ReturnValue);
}
private static async IAsyncEnumerable<int> MultiplyAsync(IAsyncEnumerable<int> source)
{
await foreach (var item in source)
{
yield return item * 10;
}
}
}

12
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;
}
}

19
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();
}
}
}

10
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<string> Events { get; } = new();
public int TargetInvocations;
}

50
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<string?> 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<string> _logs;
public LoggingScope(List<string> 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");
}
}
}

13
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<int> { 1 };
return Task.CompletedTask;
}
}
Loading…
Cancel
Save