mirror of https://github.com/abpframework/abp.git
committed by
GitHub
76 changed files with 5534 additions and 25 deletions
@ -0,0 +1,35 @@ |
|||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.AspNetCore.Mvc; |
||||
|
using Microsoft.AspNetCore.Mvc.Filters; |
||||
|
using Volo.Abp.AspNetCore.Filters; |
||||
|
using Volo.Abp.DependencyInjection; |
||||
|
using Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
namespace Volo.Abp.AspNetCore.Mvc; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// Waits for the interceptors of a returned <see cref="System.Collections.Generic.IAsyncEnumerable{T}"/>, so the outer action filters cover them.
|
||||
|
/// </summary>
|
||||
|
public class AbpInterceptedAsyncEnumerableActionFilter : IAsyncActionFilter, IAbpFilter, ITransientDependency |
||||
|
{ |
||||
|
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) |
||||
|
{ |
||||
|
var executedContext = await next(); |
||||
|
|
||||
|
if ((executedContext.Exception == null || executedContext.ExceptionHandled) && |
||||
|
GetResultValue(executedContext.Result) is IAbpInterceptedAsyncEnumerable interceptedAsyncEnumerable) |
||||
|
{ |
||||
|
await interceptedAsyncEnumerable.WaitForInterceptorsAsync(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
protected virtual object? GetResultValue(IActionResult? result) |
||||
|
{ |
||||
|
return result switch |
||||
|
{ |
||||
|
ObjectResult objectResult => objectResult.Value, |
||||
|
JsonResult jsonResult => jsonResult.Value, |
||||
|
_ => null |
||||
|
}; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,104 @@ |
|||||
|
using System; |
||||
|
using System.Diagnostics; |
||||
|
using System.Linq; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Volo.Abp.DynamicProxy; |
||||
|
using Volo.Abp.Uow; |
||||
|
|
||||
|
namespace Volo.Abp.Auditing; |
||||
|
|
||||
|
internal class AuditLogEnumerationScope : IAbpInterceptionScope |
||||
|
{ |
||||
|
private readonly IServiceScope _serviceScope; |
||||
|
private readonly AuditLogInfo _auditLog; |
||||
|
private readonly AuditLogActionInfo? _auditLogAction; |
||||
|
private readonly IAuditLogSaveHandle? _saveHandle; |
||||
|
private readonly Func<bool, Task<bool>> _shouldWriteAuditLog; |
||||
|
private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); |
||||
|
|
||||
|
public AuditLogEnumerationScope( |
||||
|
IServiceScope serviceScope, |
||||
|
AuditLogInfo auditLog, |
||||
|
AuditLogActionInfo? auditLogAction, |
||||
|
IAuditLogSaveHandle? saveHandle, |
||||
|
Func<bool, Task<bool>> shouldWriteAuditLog) |
||||
|
{ |
||||
|
_serviceScope = serviceScope; |
||||
|
_auditLog = auditLog; |
||||
|
_auditLogAction = auditLogAction; |
||||
|
_saveHandle = saveHandle; |
||||
|
_shouldWriteAuditLog = shouldWriteAuditLog; |
||||
|
} |
||||
|
|
||||
|
public Task CompleteAsync(CancellationToken cancellationToken) |
||||
|
{ |
||||
|
AddAuditLogAction(); |
||||
|
return SaveAsync(_auditLog.Exceptions.Any()); |
||||
|
} |
||||
|
|
||||
|
public Task FailAsync(Exception exception) |
||||
|
{ |
||||
|
AddAuditLogAction(); |
||||
|
if (!_auditLog.Exceptions.Contains(exception)) |
||||
|
{ |
||||
|
_auditLog.Exceptions.Add(exception); |
||||
|
} |
||||
|
|
||||
|
return SaveAsync(hasError: true); |
||||
|
} |
||||
|
|
||||
|
public void Dispose() |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
_saveHandle?.Dispose(); |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
_serviceScope.Dispose(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private void AddAuditLogAction() |
||||
|
{ |
||||
|
_stopwatch.Stop(); |
||||
|
if (_auditLogAction != null) |
||||
|
{ |
||||
|
_auditLogAction.ExecutionDuration = Convert.ToInt32(_stopwatch.Elapsed.TotalMilliseconds); |
||||
|
_auditLog.Actions.Add(_auditLogAction); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private async Task SaveAsync(bool hasError) |
||||
|
{ |
||||
|
if (_saveHandle == null) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
if (!await _shouldWriteAuditLog(hasError)) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
var unitOfWorkManager = _serviceScope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>(); |
||||
|
if (unitOfWorkManager.Current != null) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
await unitOfWorkManager.Current.SaveChangesAsync(); |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
if (!_auditLog.Exceptions.Contains(ex)) |
||||
|
{ |
||||
|
_auditLog.Exceptions.Add(ex); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
await _saveHandle.SaveAsync(); |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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(); |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -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); |
||||
|
} |
||||
|
} |
||||
@ -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); |
||||
|
} |
||||
@ -0,0 +1,8 @@ |
|||||
|
using System.Threading.Tasks; |
||||
|
|
||||
|
namespace Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
public interface IAbpInterceptedAsyncEnumerable |
||||
|
{ |
||||
|
Task WaitForInterceptorsAsync(); |
||||
|
} |
||||
@ -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); |
||||
|
} |
||||
@ -0,0 +1,53 @@ |
|||||
|
using System; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
namespace Volo.Abp.Uow; |
||||
|
|
||||
|
internal class UnitOfWorkInterceptionScope : IAbpInterceptionScope |
||||
|
{ |
||||
|
private readonly IServiceScope _serviceScope; |
||||
|
private readonly IUnitOfWorkManager _unitOfWorkManager; |
||||
|
|
||||
|
// The unit of work begun by this scope, or null if it initialized the reserved one.
|
||||
|
private readonly IUnitOfWork? _unitOfWork; |
||||
|
|
||||
|
public UnitOfWorkInterceptionScope(IServiceScope serviceScope, IUnitOfWorkManager unitOfWorkManager, IUnitOfWork? unitOfWork) |
||||
|
{ |
||||
|
_serviceScope = serviceScope; |
||||
|
_unitOfWorkManager = unitOfWorkManager; |
||||
|
_unitOfWork = unitOfWork; |
||||
|
} |
||||
|
|
||||
|
public async Task CompleteAsync(CancellationToken cancellationToken) |
||||
|
{ |
||||
|
if (_unitOfWork != null) |
||||
|
{ |
||||
|
await _unitOfWork.CompleteAsync(cancellationToken); |
||||
|
} |
||||
|
else if (_unitOfWorkManager.Current != null) |
||||
|
{ |
||||
|
await _unitOfWorkManager.Current.SaveChangesAsync(cancellationToken); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public Task FailAsync(Exception exception) |
||||
|
{ |
||||
|
// Disposing the unit of work without completing it rolls it back; the owner of an outer or reserved one decides for itself.
|
||||
|
return Task.CompletedTask; |
||||
|
} |
||||
|
|
||||
|
public void Dispose() |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
_unitOfWork?.Dispose(); |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
_serviceScope.Dispose(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,32 @@ |
|||||
|
using System.Collections.Generic; |
||||
|
using System.Threading.Tasks; |
||||
|
using Volo.Abp.Aspects; |
||||
|
using Volo.Abp.DependencyInjection; |
||||
|
using Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
namespace Volo.Abp.AspNetCore.Mvc.Auditing; |
||||
|
|
||||
|
public class AuditingConcernProbe : ISingletonDependency |
||||
|
{ |
||||
|
public List<bool> Results { get; } = new(); |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// Completes asynchronously before proceeding, and records whether the action's auditing scope is still active.
|
||||
|
/// </summary>
|
||||
|
public class AuditingConcernProbeInterceptor : AbpInterceptor, ITransientDependency |
||||
|
{ |
||||
|
private readonly AuditingConcernProbe _probe; |
||||
|
|
||||
|
public AuditingConcernProbeInterceptor(AuditingConcernProbe probe) |
||||
|
{ |
||||
|
_probe = probe; |
||||
|
} |
||||
|
|
||||
|
public override async Task InterceptAsync(IAbpMethodInvocation invocation) |
||||
|
{ |
||||
|
await Task.Delay(50); |
||||
|
_probe.Results.Add(AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Auditing)); |
||||
|
await invocation.ProceedAsync(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,121 @@ |
|||||
|
using System.Collections.Generic; |
||||
|
using System.Linq; |
||||
|
using System.Net; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Microsoft.Extensions.Options; |
||||
|
using NSubstitute; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Auditing; |
||||
|
using Volo.Abp.DynamicProxy; |
||||
|
using Volo.Abp.TestApp.Application; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.AspNetCore.Mvc.Auditing; |
||||
|
|
||||
|
public class StreamingAppService_Auditing_Tests : AspNetCoreMvcTestBase |
||||
|
{ |
||||
|
private readonly AbpAuditingOptions _options; |
||||
|
private IAuditingStore _auditingStore; |
||||
|
private readonly List<AuditLogInfo> _savedAuditLogs = new(); |
||||
|
|
||||
|
public StreamingAppService_Auditing_Tests() |
||||
|
{ |
||||
|
_options = ServiceProvider.GetRequiredService<IOptions<AbpAuditingOptions>>().Value; |
||||
|
_auditingStore = ServiceProvider.GetRequiredService<IAuditingStore>(); |
||||
|
} |
||||
|
|
||||
|
protected override void ConfigureServices(IServiceCollection services) |
||||
|
{ |
||||
|
_auditingStore = Substitute.For<IAuditingStore>(); |
||||
|
_auditingStore.SaveAsync(Arg.Do<AuditLogInfo>(_savedAuditLogs.Add)); |
||||
|
services.Replace(ServiceDescriptor.Singleton(_auditingStore)); |
||||
|
base.ConfigureServices(services); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Audit_The_Call_And_The_Enumeration_Of_A_Streaming_Action() |
||||
|
{ |
||||
|
_options.IsEnabledForGetRequests = true; |
||||
|
ProxyHelper.IsProxy(ServiceProvider.GetRequiredService<StreamingAppService>()).ShouldBeTrue(); |
||||
|
|
||||
|
var result = await GetResponseAsObjectAsync<List<int>>("/api/app/streaming/items"); |
||||
|
|
||||
|
result.ShouldBe(new[] { 1, 2 }); |
||||
|
GetRequiredService<AuditingConcernProbe>().Results.ShouldBe(new[] { true }); |
||||
|
_savedAuditLogs.Count.ShouldBe(1); |
||||
|
var actions = _savedAuditLogs[0].Actions.Where(a => a.MethodName == nameof(StreamingAppService.GetItemsAsync)).ToList(); |
||||
|
actions.Count.ShouldBe(2); |
||||
|
actions.Count(IsEnumeration).ShouldBe(1); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Record_The_Duration_Of_The_Enumeration_Of_A_Streaming_Action() |
||||
|
{ |
||||
|
_options.IsEnabledForGetRequests = true; |
||||
|
|
||||
|
var result = await GetResponseAsObjectAsync<List<int>>("/api/app/streaming/slow-items"); |
||||
|
|
||||
|
result.ShouldBe(new[] { 1 }); |
||||
|
var enumeration = _savedAuditLogs.Single().Actions.Single(a => a.MethodName == nameof(StreamingAppService.GetSlowItemsAsync) && IsEnumeration(a)); |
||||
|
enumeration.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Not_Audit_The_Enumeration_When_The_Streaming_Action_Is_Not_Audited() |
||||
|
{ |
||||
|
_options.IsEnabledForGetRequests = false; |
||||
|
|
||||
|
var result = await GetResponseAsObjectAsync<List<int>>("/api/app/streaming/items"); |
||||
|
|
||||
|
result.ShouldBe(new[] { 1, 2 }); |
||||
|
_savedAuditLogs.SelectMany(x => x.Actions).ShouldNotContain(a => a.MethodName == nameof(StreamingAppService.GetItemsAsync)); |
||||
|
} |
||||
|
|
||||
|
[Theory] |
||||
|
[InlineData("/api/app/streaming/items-with-creation-error")] |
||||
|
[InlineData("/api/streaming-json-test/creation-error")] |
||||
|
public async Task Should_Handle_Exception_Thrown_While_Creating_The_Sequence_As_An_Action_Exception(string url) |
||||
|
{ |
||||
|
_options.IsEnabledForGetRequests = true; |
||||
|
|
||||
|
// AbpExceptionFilter only handles exceptions of actions returning IActionResult for AJAX requests.
|
||||
|
using (var response = await GetResponseAsync(url, HttpStatusCode.Forbidden, xmlHttpRequest: true)) |
||||
|
{ |
||||
|
(await response.Content.ReadAsStringAsync()).ShouldContain("Failed to create the sequence"); |
||||
|
_savedAuditLogs.Single().Exceptions.ShouldContain(e => e.Message == "Failed to create the sequence"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Wait_For_Interceptors_Of_A_Sequence_Returned_After_A_Handled_Exception() |
||||
|
{ |
||||
|
_options.IsEnabledForGetRequests = true; |
||||
|
|
||||
|
var result = await GetResponseAsObjectAsync<List<int>>("/api/streaming-json-test/handled-exception"); |
||||
|
|
||||
|
result.ShouldBe(new[] { 1, 2 }); |
||||
|
var controllerAction = _savedAuditLogs.Single().Actions.Single(a => a.ServiceName == typeof(StreamingJsonTestController).FullName); |
||||
|
controllerAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Wait_For_Interceptors_Of_A_Sequence_Returned_In_A_JsonResult() |
||||
|
{ |
||||
|
_options.IsEnabledForGetRequests = true; |
||||
|
|
||||
|
var result = await GetResponseAsObjectAsync<List<int>>("/api/streaming-json-test"); |
||||
|
|
||||
|
result.ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
// The interceptors of the sequence (delayed by the probe) run within the action, like for an ObjectResult.
|
||||
|
var controllerAction = _savedAuditLogs.Single().Actions.Single(a => a.ServiceName == typeof(StreamingJsonTestController).FullName); |
||||
|
controllerAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(40); |
||||
|
} |
||||
|
|
||||
|
private static bool IsEnumeration(AuditLogActionInfo action) |
||||
|
{ |
||||
|
return action.ExtraProperties.ContainsKey(AuditingInterceptor.AsyncEnumerationPropertyName); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,56 @@ |
|||||
|
using System; |
||||
|
using Microsoft.AspNetCore.Mvc; |
||||
|
using Microsoft.AspNetCore.Mvc.Filters; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Volo.Abp.Auditing; |
||||
|
using Volo.Abp.TestApp.Application; |
||||
|
|
||||
|
namespace Volo.Abp.AspNetCore.Mvc.Auditing; |
||||
|
|
||||
|
[Route("api/streaming-json-test")] |
||||
|
public class StreamingJsonTestController : AbpController |
||||
|
{ |
||||
|
private readonly StreamingAppService _streamingAppService; |
||||
|
|
||||
|
public StreamingJsonTestController(StreamingAppService streamingAppService) |
||||
|
{ |
||||
|
_streamingAppService = streamingAppService; |
||||
|
} |
||||
|
|
||||
|
[HttpGet] |
||||
|
[Audited] |
||||
|
public IActionResult Get() |
||||
|
{ |
||||
|
return Json(_streamingAppService.GetItemsAsync()); |
||||
|
} |
||||
|
|
||||
|
[HttpGet] |
||||
|
[Route("handled-exception")] |
||||
|
[Audited] |
||||
|
[ReturnStreamOnException] |
||||
|
public IActionResult GetWithHandledException() |
||||
|
{ |
||||
|
throw new InvalidOperationException("Handled by the filter"); |
||||
|
} |
||||
|
|
||||
|
[HttpGet] |
||||
|
[Route("creation-error")] |
||||
|
public IActionResult GetWithCreationError() |
||||
|
{ |
||||
|
return Json(_streamingAppService.GetItemsWithCreationErrorAsync()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class ReturnStreamOnExceptionAttribute : ActionFilterAttribute |
||||
|
{ |
||||
|
public override void OnActionExecuted(ActionExecutedContext context) |
||||
|
{ |
||||
|
if (context.Exception == null) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
context.ExceptionHandled = true; |
||||
|
context.Result = new ObjectResult(context.HttpContext.RequestServices.GetRequiredService<StreamingAppService>().GetItemsAsync()); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,131 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Reflection; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Microsoft.Extensions.Logging; |
||||
|
using Microsoft.Extensions.Options; |
||||
|
using NSubstitute; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Clients; |
||||
|
using Volo.Abp.DependencyInjection; |
||||
|
using Volo.Abp.MultiTenancy; |
||||
|
using Volo.Abp.Threading; |
||||
|
using Volo.Abp.Timing; |
||||
|
using Volo.Abp.Tracing; |
||||
|
using Volo.Abp.Users; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Auditing; |
||||
|
|
||||
|
public class Auditing_AsyncEnumerable_ScopeFailure_Tests : AbpAuditingTestBase |
||||
|
{ |
||||
|
private readonly IAuditingManager _auditingManager; |
||||
|
private readonly FailingAuditingHelperState _state; |
||||
|
private readonly Auditing_AsyncEnumerable_Tests.MyStreamingAuditedObject _target; |
||||
|
|
||||
|
public Auditing_AsyncEnumerable_ScopeFailure_Tests() |
||||
|
{ |
||||
|
_auditingManager = GetRequiredService<IAuditingManager>(); |
||||
|
_state = GetRequiredService<FailingAuditingHelperState>(); |
||||
|
_target = GetRequiredService<Auditing_AsyncEnumerable_Tests.MyStreamingAuditedObject>(); |
||||
|
} |
||||
|
|
||||
|
protected override void AfterAddApplication(IServiceCollection services) |
||||
|
{ |
||||
|
services.AddSingleton<FailingAuditingHelperState>(); |
||||
|
services.Replace(ServiceDescriptor.Transient<IAuditingHelper, FailingAuditingHelper>()); |
||||
|
services.Replace(ServiceDescriptor.Singleton(Substitute.For<IAuditingStore>())); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Dispose_The_Scope_Of_A_New_Audit_Log_If_Beginning_The_Enumeration_Audit_Fails() |
||||
|
{ |
||||
|
var sequence = _target.StreamItemsAsync(1); |
||||
|
_state.FailToCreateAction = true; |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(sequence)); |
||||
|
|
||||
|
_state.IsFailedHelperDisposed.ShouldBeTrue(); |
||||
|
_auditingManager.Current.ShouldBeNull(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Dispose_The_Scope_If_Beginning_The_Enumeration_Audit_In_The_Current_Audit_Log_Fails() |
||||
|
{ |
||||
|
using (_auditingManager.BeginScope()) |
||||
|
{ |
||||
|
var auditLog = _auditingManager.Current!.Log; |
||||
|
var sequence = _target.StreamItemsAsync(1); |
||||
|
_state.FailToCreateAction = true; |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(sequence)); |
||||
|
|
||||
|
_state.IsFailedHelperDisposed.ShouldBeTrue(); |
||||
|
_auditingManager.Current!.Log.ShouldBeSameAs(auditLog); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static async Task<List<int>> ToListAsync(IAsyncEnumerable<int> source) |
||||
|
{ |
||||
|
var list = new List<int>(); |
||||
|
await foreach (var item in source) |
||||
|
{ |
||||
|
list.Add(item); |
||||
|
} |
||||
|
|
||||
|
return list; |
||||
|
} |
||||
|
|
||||
|
public class FailingAuditingHelperState |
||||
|
{ |
||||
|
public bool FailToCreateAction { get; set; } |
||||
|
|
||||
|
public bool IsFailedHelperDisposed { get; set; } |
||||
|
} |
||||
|
|
||||
|
[DisableConventionalRegistration] |
||||
|
public class FailingAuditingHelper : AuditingHelper, IDisposable |
||||
|
{ |
||||
|
private readonly FailingAuditingHelperState _state; |
||||
|
private bool _hasFailed; |
||||
|
|
||||
|
public FailingAuditingHelper( |
||||
|
FailingAuditingHelperState state, |
||||
|
IAuditSerializer auditSerializer, |
||||
|
IOptions<AbpAuditingOptions> options, |
||||
|
ICurrentUser currentUser, |
||||
|
ICurrentTenant currentTenant, |
||||
|
ICurrentClient currentClient, |
||||
|
IClock clock, |
||||
|
IAuditingStore auditingStore, |
||||
|
ILogger<AuditingHelper> logger, |
||||
|
IServiceProvider serviceProvider, |
||||
|
ICorrelationIdProvider correlationIdProvider, |
||||
|
IAmbientScopeProvider<AuditingDisabledState> auditingDisabledState) |
||||
|
: base(auditSerializer, options, currentUser, currentTenant, currentClient, clock, auditingStore, logger, serviceProvider, correlationIdProvider, auditingDisabledState) |
||||
|
{ |
||||
|
_state = state; |
||||
|
} |
||||
|
|
||||
|
public override AuditLogActionInfo CreateAuditLogAction(AuditLogInfo auditLog, Type type, MethodInfo method, object[] arguments) |
||||
|
{ |
||||
|
if (_state.FailToCreateAction) |
||||
|
{ |
||||
|
_hasFailed = true; |
||||
|
throw new InvalidOperationException("Failed to create the audit log action"); |
||||
|
} |
||||
|
|
||||
|
return base.CreateAuditLogAction(auditLog, type, method, arguments); |
||||
|
} |
||||
|
|
||||
|
public void Dispose() |
||||
|
{ |
||||
|
if (_hasFailed) |
||||
|
{ |
||||
|
_state.IsFailedHelperDisposed = true; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,508 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Linq; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Microsoft.Extensions.Options; |
||||
|
using NSubstitute; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Auditing.App.Entities; |
||||
|
using Volo.Abp.DependencyInjection; |
||||
|
using Volo.Abp.Domain.Repositories; |
||||
|
using Volo.Abp.Uow; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Auditing; |
||||
|
|
||||
|
public class Auditing_AsyncEnumerable_Tests : AbpAuditingTestBase |
||||
|
{ |
||||
|
private readonly List<AuditLogInfo> _savedAuditLogs = new(); |
||||
|
private readonly List<(List<string> Comments, int[] ActionDurations)> _savedAuditLogSnapshots = new(); |
||||
|
private readonly IAuditingManager _auditingManager; |
||||
|
private readonly MyStreamingAuditedObject _target; |
||||
|
|
||||
|
public Auditing_AsyncEnumerable_Tests() |
||||
|
{ |
||||
|
_auditingManager = GetRequiredService<IAuditingManager>(); |
||||
|
_target = GetRequiredService<MyStreamingAuditedObject>(); |
||||
|
} |
||||
|
|
||||
|
protected override void AfterAddApplication(IServiceCollection services) |
||||
|
{ |
||||
|
var auditingStore = Substitute.For<IAuditingStore>(); |
||||
|
auditingStore.SaveAsync(Arg.Do<AuditLogInfo>(auditLog => |
||||
|
{ |
||||
|
_savedAuditLogs.Add(auditLog); |
||||
|
_savedAuditLogSnapshots.Add((auditLog.Comments.ToList(), auditLog.Actions.Select(a => a.ExecutionDuration).ToArray())); |
||||
|
})); |
||||
|
services.Replace(ServiceDescriptor.Singleton(auditingStore)); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Call_And_The_Enumeration_As_Separate_Audit_Logs() |
||||
|
{ |
||||
|
var sequence = _target.StreamItemsAsync(50); |
||||
|
|
||||
|
var callLog = _savedAuditLogs.ShouldHaveSingleItem(); |
||||
|
IsEnumeration(callLog.Actions.ShouldHaveSingleItem()).ShouldBeFalse(); |
||||
|
|
||||
|
(await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
var enumerationAction = _savedAuditLogs[1].Actions.ShouldHaveSingleItem(); |
||||
|
IsEnumeration(enumerationAction).ShouldBeTrue(); |
||||
|
enumerationAction.MethodName.ShouldBe(nameof(MyStreamingAuditedObject.StreamItemsAsync)); |
||||
|
enumerationAction.ExecutionDuration.ShouldBeGreaterThanOrEqualTo(80); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldBeEmpty(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public void Should_Not_Save_An_Enumeration_Audit_Log_If_The_Sequence_Is_Not_Enumerated() |
||||
|
{ |
||||
|
_target.StreamItemsAsync(1); |
||||
|
|
||||
|
IsEnumeration(_savedAuditLogs.ShouldHaveSingleItem().Actions.ShouldHaveSingleItem()).ShouldBeFalse(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Exception_Of_The_Sequence_In_The_Enumeration_Audit_Log() |
||||
|
{ |
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(_target.StreamItemsThenThrowAsync())); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[0].Exceptions.ShouldBeEmpty(); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Stream failed"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_An_Audit_Log_For_Each_Enumeration() |
||||
|
{ |
||||
|
var sequence = _target.StreamItemsAsync(1); |
||||
|
|
||||
|
await ToListAsync(sequence); |
||||
|
await ToListAsync(sequence); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(3); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
IsEnumeration(_savedAuditLogs[2].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Not_Copy_What_Was_Recorded_While_Creating_The_Sequence() |
||||
|
{ |
||||
|
(await ToListAsync(_target.StreamItemsWithCommentAsync())).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[0].Comments.ShouldContain("Created the sequence"); |
||||
|
_savedAuditLogs[1].Comments.ShouldBeEmpty(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Audit_The_Enumeration_When_The_Call_Recorded_An_Exception_Without_Throwing() |
||||
|
{ |
||||
|
(await ToListAsync(_target.StreamItemsAfterHandledExceptionAsync())).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[0].Exceptions.ShouldContain(e => e.Message == "Handled while creating"); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldBeEmpty(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Record_What_Happens_During_Each_Enumeration_Only_In_Its_Own_Audit_Log() |
||||
|
{ |
||||
|
var sequence = _target.StreamItemsWithEntityChangeAsync(); |
||||
|
|
||||
|
await ToListAsync(sequence); |
||||
|
await ToListAsync(sequence); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(3); |
||||
|
_savedAuditLogs[0].EntityChanges.ShouldBeEmpty(); |
||||
|
var firstChange = _savedAuditLogs[1].EntityChanges.ShouldHaveSingleItem(); |
||||
|
var secondChange = _savedAuditLogs[2].EntityChanges.ShouldHaveSingleItem(); |
||||
|
firstChange.ShouldNotBeSameAs(secondChange); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Record_The_Entity_Changes_Saved_By_The_Unit_Of_Work_Of_The_Enumeration_In_Its_Audit_Log() |
||||
|
{ |
||||
|
var entityId = Guid.NewGuid(); |
||||
|
var sequence = GetRequiredService<MyStreamingAuditedUnitOfWorkObject>().InsertAndStreamAsync(entityId, fail: false); |
||||
|
|
||||
|
(await ToListAsync(sequence)).ShouldBe(new[] { 1 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[0].EntityChanges.ShouldBeEmpty(); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
var entityChange = _savedAuditLogs[1].EntityChanges.ShouldHaveSingleItem(); |
||||
|
entityChange.EntityId.ShouldBe(entityId.ToString()); |
||||
|
entityChange.ChangeType.ShouldBe(EntityChangeType.Created); |
||||
|
(await FindAppEntityWithAuditedAsync(entityId)).ShouldNotBeNull(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Not_Save_The_Entity_Of_A_Failed_Enumeration_And_Record_The_Exception_In_Its_Audit_Log() |
||||
|
{ |
||||
|
var entityId = Guid.NewGuid(); |
||||
|
var sequence = GetRequiredService<MyStreamingAuditedUnitOfWorkObject>().InsertAndStreamAsync(entityId, fail: true); |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(sequence)); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Stream failed after inserting"); |
||||
|
(await FindAppEntityWithAuditedAsync(entityId)).ShouldBeNull(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Add_A_Nested_Sequence_To_The_Audit_Log_Of_The_Enumeration_That_Uses_It() |
||||
|
{ |
||||
|
var outer = _target.StreamItemsOfNestedSequenceAsync(); |
||||
|
(await ToListAsync(outer)).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[0].Actions.ShouldHaveSingleItem().MethodName.ShouldBe(nameof(MyStreamingAuditedObject.StreamItemsOfNestedSequenceAsync)); |
||||
|
|
||||
|
var actions = _savedAuditLogs[1].Actions; |
||||
|
actions.Select(a => (a.MethodName, IsEnumeration(a))).ShouldBe(new[] |
||||
|
{ |
||||
|
(nameof(MyStreamingAuditedObject.StreamItemsAsync), false), |
||||
|
(nameof(MyStreamingAuditedObject.StreamItemsAsync), true), |
||||
|
(nameof(MyStreamingAuditedObject.StreamItemsOfNestedSequenceAsync), true) |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Enumeration_Audit_Log_When_The_Source_Throws_On_GetAsyncEnumerator() |
||||
|
{ |
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(_target.StreamItemsThrowingOnGetAsyncEnumerator())); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on GetAsyncEnumerator"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Enumeration_Audit_Log_When_The_Source_Throws_On_Dispose() |
||||
|
{ |
||||
|
// Stopping early runs the finally block of the source in DisposeAsync, not in MoveNextAsync.
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(async () => |
||||
|
{ |
||||
|
await foreach (var _ in _target.StreamItemsThrowingOnDisposeAsync()) |
||||
|
{ |
||||
|
break; |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on dispose"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Enumeration_Audit_Log_After_The_Failed_Source_Has_Been_Disposed() |
||||
|
{ |
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(_target.StreamItemsThrowingOnCurrent())); |
||||
|
|
||||
|
_savedAuditLogSnapshots.Count.ShouldBe(2); |
||||
|
var (comments, actionDurations) = _savedAuditLogSnapshots[1]; |
||||
|
comments.ShouldBe(new[] { "Disposed the source" }); |
||||
|
actionDurations.ShouldHaveSingleItem().ShouldBeGreaterThanOrEqualTo(40); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on Current"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Enumeration_Audit_Log_Without_An_Action_If_Action_Info_Is_Disabled() |
||||
|
{ |
||||
|
GetRequiredService<IOptions<AbpAuditingOptions>>().Value.DisableLogActionInfo = true; |
||||
|
|
||||
|
(await ToListAsync(_target.StreamItemsAsync(1))).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[1].Actions.ShouldBeEmpty(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Add_The_Exception_Of_Saving_Changes_To_The_Enumeration_Audit_Log() |
||||
|
{ |
||||
|
using (var unitOfWork = GetRequiredService<IUnitOfWorkManager>().Begin()) |
||||
|
{ |
||||
|
unitOfWork.AddDatabaseApi("Failing", new FailingSaveChangesDatabaseApi()); |
||||
|
|
||||
|
(await ToListAsync(_target.StreamItemsAsync(1))).ShouldBe(new[] { 1, 2 }); |
||||
|
} |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed to save changes"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_The_Exception_Thrown_When_Disposing_The_Failed_Source_In_The_Enumeration_Audit_Log() |
||||
|
{ |
||||
|
var exception = await Should.ThrowAsync<InvalidOperationException>(ToListAsync(_target.StreamItemsThrowingOnCurrentAndDispose())); |
||||
|
|
||||
|
exception.Message.ShouldBe("Failed on dispose"); |
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
_savedAuditLogs[1].Exceptions.ShouldContain(e => e.Message == "Failed on dispose"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Not_Save_An_Enumeration_Audit_Log_While_Auditing_Is_Disabled() |
||||
|
{ |
||||
|
var sequence = _target.StreamItemsAsync(1); |
||||
|
|
||||
|
using (GetRequiredService<IAuditingHelper>().DisableAuditing()) |
||||
|
{ |
||||
|
(await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); |
||||
|
} |
||||
|
|
||||
|
_savedAuditLogs.ShouldHaveSingleItem(); |
||||
|
|
||||
|
(await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_savedAuditLogs.Count.ShouldBe(2); |
||||
|
IsEnumeration(_savedAuditLogs[1].Actions.ShouldHaveSingleItem()).ShouldBeTrue(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Not_Add_The_Enumeration_To_The_Current_Audit_Log_While_Auditing_Is_Disabled() |
||||
|
{ |
||||
|
using (_auditingManager.BeginScope()) |
||||
|
{ |
||||
|
var sequence = _target.StreamItemsAsync(1); |
||||
|
|
||||
|
using (GetRequiredService<IAuditingHelper>().DisableAuditing()) |
||||
|
{ |
||||
|
(await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); |
||||
|
} |
||||
|
|
||||
|
_auditingManager.Current!.Log.Actions.Select(IsEnumeration).ShouldBe(new[] { false }); |
||||
|
|
||||
|
(await ToListAsync(sequence)).ShouldBe(new[] { 1, 2 }); |
||||
|
|
||||
|
_auditingManager.Current!.Log.Actions.Select(IsEnumeration).ShouldBe(new[] { false, true }); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Add_The_Call_And_The_Enumeration_To_The_Current_Audit_Log() |
||||
|
{ |
||||
|
using (var scope = _auditingManager.BeginScope()) |
||||
|
{ |
||||
|
(await ToListAsync(_target.StreamItemsAsync(50))).ShouldBe(new[] { 1, 2 }); |
||||
|
await Should.ThrowAsync<InvalidOperationException>(ToListAsync(_target.StreamItemsThenThrowAsync())); |
||||
|
|
||||
|
var auditLog = _auditingManager.Current!.Log; |
||||
|
auditLog.Actions.Select(IsEnumeration).ShouldBe(new[] { false, true, false, true }); |
||||
|
auditLog.Actions[1].ExecutionDuration.ShouldBeGreaterThanOrEqualTo(80); |
||||
|
auditLog.Exceptions.ShouldContain(e => e.Message == "Stream failed"); |
||||
|
|
||||
|
await scope.SaveAsync(); |
||||
|
} |
||||
|
|
||||
|
_savedAuditLogs.ShouldHaveSingleItem(); |
||||
|
} |
||||
|
|
||||
|
private class FailingSaveChangesDatabaseApi : IDatabaseApi, ISupportsSavingChanges |
||||
|
{ |
||||
|
public Task SaveChangesAsync(CancellationToken cancellationToken = default) |
||||
|
{ |
||||
|
throw new InvalidOperationException("Failed to save changes"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private async Task<AppEntityWithAudited?> FindAppEntityWithAuditedAsync(Guid id) |
||||
|
{ |
||||
|
using (var unitOfWork = GetRequiredService<IUnitOfWorkManager>().Begin()) |
||||
|
{ |
||||
|
var entity = await GetRequiredService<IBasicRepository<AppEntityWithAudited, Guid>>().FindAsync(id); |
||||
|
await unitOfWork.CompleteAsync(); |
||||
|
return entity; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static bool IsEnumeration(AuditLogActionInfo action) |
||||
|
{ |
||||
|
return action.ExtraProperties.TryGetValue(AuditingInterceptor.AsyncEnumerationPropertyName, out var value) && value is true; |
||||
|
} |
||||
|
|
||||
|
private static async Task<List<int>> ToListAsync(IAsyncEnumerable<int> source) |
||||
|
{ |
||||
|
var list = new List<int>(); |
||||
|
await foreach (var item in source) |
||||
|
{ |
||||
|
list.Add(item); |
||||
|
} |
||||
|
|
||||
|
return list; |
||||
|
} |
||||
|
|
||||
|
public class MyStreamingAuditedUnitOfWorkObject : ITransientDependency, IAuditingEnabled, IUnitOfWorkEnabled |
||||
|
{ |
||||
|
private readonly IBasicRepository<AppEntityWithAudited, Guid> _repository; |
||||
|
|
||||
|
public MyStreamingAuditedUnitOfWorkObject(IBasicRepository<AppEntityWithAudited, Guid> repository) |
||||
|
{ |
||||
|
_repository = repository; |
||||
|
} |
||||
|
|
||||
|
// The entity is saved when the unit of work of the enumeration is completed.
|
||||
|
public virtual async IAsyncEnumerable<int> InsertAndStreamAsync(Guid id, bool fail) |
||||
|
{ |
||||
|
await _repository.InsertAsync(new AppEntityWithAudited(id, "streamed")); |
||||
|
yield return 1; |
||||
|
|
||||
|
if (fail) |
||||
|
{ |
||||
|
throw new InvalidOperationException("Stream failed after inserting"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class MyStreamingAuditedObject : ITransientDependency, IAuditingEnabled |
||||
|
{ |
||||
|
private readonly IAuditingManager _auditingManager; |
||||
|
|
||||
|
public MyStreamingAuditedObject(IAuditingManager auditingManager) |
||||
|
{ |
||||
|
_auditingManager = auditingManager; |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> StreamItemsWithCommentAsync() |
||||
|
{ |
||||
|
_auditingManager.Current!.Log.Comments.Add("Created the sequence"); |
||||
|
return ProduceAsync(); |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> StreamItemsAfterHandledExceptionAsync() |
||||
|
{ |
||||
|
_auditingManager.Current!.Log.Exceptions.Add(new InvalidOperationException("Handled while creating")); |
||||
|
return ProduceAsync(); |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<int> StreamItemsAsync(int delay) |
||||
|
{ |
||||
|
await Task.Delay(delay); |
||||
|
yield return 1; |
||||
|
await Task.Delay(delay); |
||||
|
yield return 2; |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<int> StreamItemsWithEntityChangeAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
_auditingManager.Current!.Log.EntityChanges.Add(new EntityChangeInfo { EntityId = "1" }); |
||||
|
yield return 1; |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<int> StreamItemsOfNestedSequenceAsync() |
||||
|
{ |
||||
|
await foreach (var item in StreamItemsAsync(1)) |
||||
|
{ |
||||
|
yield return item; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<int> StreamItemsThenThrowAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return 1; |
||||
|
throw new InvalidOperationException("Stream failed"); |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> StreamItemsThrowingOnCurrent() |
||||
|
{ |
||||
|
return new ThrowingOnCurrentSequence(_auditingManager); |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> StreamItemsThrowingOnCurrentAndDispose() |
||||
|
{ |
||||
|
return new ThrowingOnCurrentAndDisposeSequence(); |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> StreamItemsThrowingOnGetAsyncEnumerator() |
||||
|
{ |
||||
|
return new ThrowingOnGetAsyncEnumeratorSequence(); |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<int> StreamItemsThrowingOnDisposeAsync() |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return 1; |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
throw new InvalidOperationException("Failed on dispose"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static async IAsyncEnumerable<int> ProduceAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return 1; |
||||
|
yield return 2; |
||||
|
} |
||||
|
|
||||
|
private class ThrowingOnCurrentSequence : IAsyncEnumerable<int>, IAsyncEnumerator<int> |
||||
|
{ |
||||
|
private readonly IAuditingManager _auditingManager; |
||||
|
|
||||
|
public ThrowingOnCurrentSequence(IAuditingManager auditingManager) |
||||
|
{ |
||||
|
_auditingManager = auditingManager; |
||||
|
} |
||||
|
|
||||
|
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.Delay(50); |
||||
|
_auditingManager.Current!.Log.Comments.Add("Disposed the source"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private class ThrowingOnCurrentAndDisposeSequence : IAsyncEnumerable<int>, IAsyncEnumerator<int> |
||||
|
{ |
||||
|
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 ValueTask DisposeAsync() |
||||
|
{ |
||||
|
throw new InvalidOperationException("Failed on dispose"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private class ThrowingOnGetAsyncEnumeratorSequence : IAsyncEnumerable<int> |
||||
|
{ |
||||
|
public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default) |
||||
|
{ |
||||
|
throw new InvalidOperationException("Failed on GetAsyncEnumerator"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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()); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,219 @@ |
|||||
|
using System; |
||||
|
using System.IO; |
||||
|
using System.Threading.Tasks; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Cli.Commands; |
||||
|
using Volo.Abp.Cli.Http; |
||||
|
using Volo.Abp.Cli.ServiceProxying.CSharp; |
||||
|
using Volo.Abp.Http.Modeling; |
||||
|
using Volo.Abp.Json; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Cli.ServiceProxying; |
||||
|
|
||||
|
public class CSharpServiceProxyGenerator_AsyncEnumerable_Tests : AbpCliTestBase |
||||
|
{ |
||||
|
[Theory] |
||||
|
[InlineData(false)] |
||||
|
[InlineData(true)] |
||||
|
public async Task Should_Return_IAsyncEnumerable_From_The_Generated_Proxy_And_Interface(bool withoutContracts) |
||||
|
{ |
||||
|
var workDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); |
||||
|
Directory.CreateDirectory(workDirectory); |
||||
|
await File.WriteAllTextAsync(Path.Combine(workDirectory, "MyProject.HttpApi.Client.csproj"), "<Project Sdk=\"Microsoft.NET.Sdk\" />"); |
||||
|
try |
||||
|
{ |
||||
|
var generator = new TestCSharpServiceProxyGenerator(GetRequiredService<CliHttpClientFactory>(), GetRequiredService<IJsonSerializer>()); |
||||
|
|
||||
|
await generator.GenerateProxyAsync(new GenerateProxyArgs( |
||||
|
GenerateProxyCommand.Name, workDirectory, "app", "https://localhost/", null, null, null, null, null, null, null, withoutContracts)); |
||||
|
|
||||
|
var folder = Path.Combine(workDirectory, "ClientProxies", "MyProject", "Streaming"); |
||||
|
var proxy = await File.ReadAllTextAsync(Path.Combine(folder, "StreamingClientProxy.Generated.cs")); |
||||
|
proxy.ShouldContain("public virtual IAsyncEnumerable<Int32> GetItemsAsync()"); |
||||
|
proxy.ShouldContain("return RequestAsyncEnumerable<Int32>(nameof(GetItemsAsync));"); |
||||
|
proxy.ShouldContain("public virtual IAsyncEnumerable<String> GetNamedItemsAsync(string name)"); |
||||
|
proxy.ShouldContain("public virtual async Task<String> GetNameAsync()"); |
||||
|
proxy.ShouldContain("public virtual async Task DeleteAsync()"); |
||||
|
proxy.ShouldContain("public virtual IAsyncEnumerable<String> GetBooks()"); |
||||
|
proxy.ShouldContain("return RequestAsyncEnumerable<String>(nameof(GetBooks));"); |
||||
|
proxy.ShouldContain("public virtual IAsyncEnumerable<Int32> Read(CancellationToken cancellationToken, int count)"); |
||||
|
proxy.ShouldContain("GetCount()"); |
||||
|
proxy.Split("NotImplementedException").Length.ShouldBe(2); |
||||
|
|
||||
|
var interfacePath = Path.Combine(folder, "IStreamingAppService.cs"); |
||||
|
if (withoutContracts) |
||||
|
{ |
||||
|
File.Exists(interfacePath).ShouldBeFalse(); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
var @interface = await File.ReadAllTextAsync(interfacePath); |
||||
|
@interface.ShouldContain("IAsyncEnumerable<Int32> GetItemsAsync();"); |
||||
|
@interface.ShouldContain("IAsyncEnumerable<String> GetNamedItemsAsync(string name);"); |
||||
|
@interface.ShouldNotContain("Task<IAsyncEnumerable"); |
||||
|
@interface.ShouldContain("Task<String> GetNameAsync();"); |
||||
|
@interface.ShouldContain("Task DeleteAsync();"); |
||||
|
@interface.ShouldContain("IAsyncEnumerable<String> GetBooks();"); |
||||
|
@interface.ShouldContain("IAsyncEnumerable<Int32> Read(CancellationToken cancellationToken, int count);"); |
||||
|
@interface.ShouldContain(" GetCount();"); |
||||
|
@interface.ShouldNotContain("Task<Int32> GetCount"); |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
Directory.Delete(workDirectory, true); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private class TestCSharpServiceProxyGenerator : CSharpServiceProxyGenerator |
||||
|
{ |
||||
|
public TestCSharpServiceProxyGenerator(CliHttpClientFactory cliHttpClientFactory, IJsonSerializer jsonSerializer) |
||||
|
: base(cliHttpClientFactory, jsonSerializer) |
||||
|
{ |
||||
|
} |
||||
|
|
||||
|
protected override Task<ApplicationApiDescriptionModel> GetApplicationApiDescriptionModelAsync(GenerateProxyArgs args, ApplicationApiDescriptionModelRequestDto requestDto = null) |
||||
|
{ |
||||
|
return Task.FromResult(JsonSerializer.Deserialize<ApplicationApiDescriptionModel>(ApiDefinition)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private const string ApiDefinition = """
|
||||
|
{ |
||||
|
"modules": { |
||||
|
"app": { |
||||
|
"rootPath": "app", |
||||
|
"remoteServiceName": "Default", |
||||
|
"controllers": { |
||||
|
"MyProject.Streaming.StreamingAppService": { |
||||
|
"controllerName": "Streaming", |
||||
|
"type": "MyProject.Streaming.StreamingAppService", |
||||
|
"interfaces": [ |
||||
|
{ |
||||
|
"type": "MyProject.Streaming.IStreamingAppService", |
||||
|
"name": "IStreamingAppService", |
||||
|
"methods": [ |
||||
|
{ |
||||
|
"name": "GetItemsAsync", |
||||
|
"parametersOnMethod": [], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" } |
||||
|
}, |
||||
|
{ |
||||
|
"name": "GetNamedItemsAsync", |
||||
|
"parametersOnMethod": [ { "name": "name", "type": "System.String", "typeSimple": "string" } ], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" } |
||||
|
}, |
||||
|
{ |
||||
|
"name": "GetNameAsync", |
||||
|
"parametersOnMethod": [], |
||||
|
"returnValue": { "type": "System.String", "typeSimple": "string" } |
||||
|
}, |
||||
|
{ |
||||
|
"name": "DeleteAsync", |
||||
|
"parametersOnMethod": [], |
||||
|
"returnValue": { "type": "System.Void", "typeSimple": "System.Void" } |
||||
|
}, |
||||
|
{ |
||||
|
"name": "GetBooks", |
||||
|
"parametersOnMethod": [], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" } |
||||
|
}, |
||||
|
{ |
||||
|
"name": "Read", |
||||
|
"parametersOnMethod": [ |
||||
|
{ "name": "cancellationToken", "type": "System.Threading.CancellationToken", "typeSimple": "System.Threading.CancellationToken" }, |
||||
|
{ "name": "count", "type": "System.Int32", "typeSimple": "number" } |
||||
|
], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" } |
||||
|
}, |
||||
|
{ |
||||
|
"name": "GetCount", |
||||
|
"parametersOnMethod": [], |
||||
|
"returnValue": { "type": "System.Int32", "typeSimple": "number" } |
||||
|
} |
||||
|
] |
||||
|
} |
||||
|
], |
||||
|
"actions": { |
||||
|
"GetItemsAsync": { |
||||
|
"uniqueName": "GetItemsAsync", |
||||
|
"name": "GetItemsAsync", |
||||
|
"httpMethod": "GET", |
||||
|
"url": "api/app/streaming/items", |
||||
|
"parametersOnMethod": [], |
||||
|
"parameters": [], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
}, |
||||
|
"GetNamedItemsAsyncByName": { |
||||
|
"uniqueName": "GetNamedItemsAsyncByName", |
||||
|
"name": "GetNamedItemsAsync", |
||||
|
"httpMethod": "GET", |
||||
|
"url": "api/app/streaming/named-items", |
||||
|
"parametersOnMethod": [ { "name": "name", "type": "System.String", "typeSimple": "string" } ], |
||||
|
"parameters": [ { "nameOnMethod": "name", "name": "name", "type": "System.String", "typeSimple": "string" } ], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
}, |
||||
|
"GetNameAsync": { |
||||
|
"uniqueName": "GetNameAsync", |
||||
|
"name": "GetNameAsync", |
||||
|
"httpMethod": "GET", |
||||
|
"url": "api/app/streaming/name", |
||||
|
"parametersOnMethod": [], |
||||
|
"parameters": [], |
||||
|
"returnValue": { "type": "System.String", "typeSimple": "string" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
}, |
||||
|
"DeleteAsync": { |
||||
|
"uniqueName": "DeleteAsync", |
||||
|
"name": "DeleteAsync", |
||||
|
"httpMethod": "DELETE", |
||||
|
"url": "api/app/streaming", |
||||
|
"parametersOnMethod": [], |
||||
|
"parameters": [], |
||||
|
"returnValue": { "type": "System.Void", "typeSimple": "System.Void" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
}, |
||||
|
"GetBooks": { |
||||
|
"uniqueName": "GetBooks", |
||||
|
"name": "GetBooks", |
||||
|
"httpMethod": "GET", |
||||
|
"url": "api/app/streaming/books", |
||||
|
"parametersOnMethod": [], |
||||
|
"parameters": [], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.String>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<string>" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
}, |
||||
|
"GetCount": { |
||||
|
"uniqueName": "GetCount", |
||||
|
"name": "GetCount", |
||||
|
"httpMethod": "GET", |
||||
|
"url": "api/app/streaming/count", |
||||
|
"parametersOnMethod": [], |
||||
|
"parameters": [], |
||||
|
"returnValue": { "type": "System.Int32", "typeSimple": "number" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
}, |
||||
|
"ReadByCancellationTokenAndCount": { |
||||
|
"uniqueName": "ReadByCancellationTokenAndCount", |
||||
|
"name": "Read", |
||||
|
"httpMethod": "GET", |
||||
|
"url": "api/app/streaming/read", |
||||
|
"parametersOnMethod": [ |
||||
|
{ "name": "cancellationToken", "type": "System.Threading.CancellationToken", "typeSimple": "System.Threading.CancellationToken" }, |
||||
|
{ "name": "count", "type": "System.Int32", "typeSimple": "number" } |
||||
|
], |
||||
|
"parameters": [ { "nameOnMethod": "count", "name": "count", "type": "System.Int32", "typeSimple": "number" } ], |
||||
|
"returnValue": { "type": "System.Collections.Generic.IAsyncEnumerable<System.Int32>", "typeSimple": "System.Collections.Generic.IAsyncEnumerable<number>" }, |
||||
|
"implementFrom": "MyProject.Streaming.IStreamingAppService" |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
}, |
||||
|
"types": {} |
||||
|
} |
||||
|
""";
|
||||
|
} |
||||
@ -0,0 +1,715 @@ |
|||||
|
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<ConcurrentScopeTestInterceptor>(); |
||||
|
services.AddTransient<AsyncEnumerableConcurrentScopedTestObject>(); |
||||
|
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(AsyncEnumerableConcurrentScopedTestObject) == registration.ImplementationType) |
||||
|
{ |
||||
|
registration.Interceptors.Add<ConcurrentScopeTestInterceptor>(); |
||||
|
} |
||||
|
|
||||
|
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_Scopes_Of_Concurrent_Enumerations_Separate_When_One_Is_Canceled() |
||||
|
{ |
||||
|
var target = ServiceProvider.GetRequiredService<AsyncEnumerableConcurrentScopedTestObject>(); |
||||
|
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
||||
|
var sequence = target.GetScopeIdsAsync(gate.Task); |
||||
|
var canceledIds = new List<string?>(); |
||||
|
var completedIds = new List<string?>(); |
||||
|
var completedFirstItem = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
||||
|
|
||||
|
using (var cancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
var canceled = Task.Run(async () => |
||||
|
{ |
||||
|
await foreach (var scopeId in sequence.WithCancellation(cancellationTokenSource.Token)) |
||||
|
{ |
||||
|
canceledIds.Add(scopeId); |
||||
|
await completedFirstItem.Task; |
||||
|
cancellationTokenSource.Cancel(); |
||||
|
} |
||||
|
}); |
||||
|
var completed = Task.Run(async () => |
||||
|
{ |
||||
|
await foreach (var scopeId in sequence) |
||||
|
{ |
||||
|
completedIds.Add(scopeId); |
||||
|
completedFirstItem.TrySetResult(); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
await Should.ThrowAsync<OperationCanceledException>(canceled.WaitAsync(TimeSpan.FromSeconds(10))); |
||||
|
gate.SetResult(); |
||||
|
await completed.WaitAsync(TimeSpan.FromSeconds(10)); |
||||
|
} |
||||
|
|
||||
|
var canceledScopeId = canceledIds.ShouldHaveSingleItem().ShouldNotBeNull(); |
||||
|
completedIds.Count.ShouldBe(2); |
||||
|
var completedScopeId = completedIds[0].ShouldNotBeNull(); |
||||
|
completedIds[1].ShouldBe(completedScopeId); |
||||
|
completedScopeId.ShouldNotBe(canceledScopeId); |
||||
|
ConcurrentScopeTestInterceptor.ScopeId.Value.ShouldBeNull(); |
||||
|
|
||||
|
var events = target.Events.ToList(); |
||||
|
events.Where(e => e.StartsWith(canceledScopeId)).ShouldBe(new[] { $"{canceledScopeId}:Failed", $"{canceledScopeId}:Disposed" }); |
||||
|
events.Where(e => e.StartsWith(completedScopeId)).ShouldBe(new[] { $"{completedScopeId}:Completed", $"{completedScopeId}:Disposed" }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Keep_The_Scope_Of_The_Interceptor_For_Every_Step_Of_The_Enumeration() |
||||
|
{ |
||||
|
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; |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,8 @@ |
|||||
|
using System.Threading; |
||||
|
|
||||
|
namespace Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
public static class AsyncEnumerableCallerContext |
||||
|
{ |
||||
|
public static readonly AsyncLocal<string?> Value = new(); |
||||
|
} |
||||
@ -0,0 +1,20 @@ |
|||||
|
using System.Collections.Concurrent; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Runtime.CompilerServices; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
|
||||
|
namespace Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
public class AsyncEnumerableConcurrentScopedTestObject |
||||
|
{ |
||||
|
public ConcurrentQueue<string> Events { get; } = new(); |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<string?> GetScopeIdsAsync(Task gate, [EnumeratorCancellation] CancellationToken cancellationToken = default) |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return ConcurrentScopeTestInterceptor.ScopeId.Value; |
||||
|
await gate.WaitAsync(cancellationToken); |
||||
|
yield return ConcurrentScopeTestInterceptor.ScopeId.Value; |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -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}"; |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -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); |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -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"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -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>(); |
||||
|
} |
||||
|
} |
||||
@ -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); |
||||
|
}); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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>(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,46 @@ |
|||||
|
using System; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
|
||||
|
namespace Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
public class ConcurrentScopeTestInterceptor : AbpScopeInterceptor |
||||
|
{ |
||||
|
public static readonly AsyncLocal<string?> ScopeId = new(); |
||||
|
|
||||
|
protected override IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation) |
||||
|
{ |
||||
|
var scopeId = Guid.NewGuid().ToString("N"); |
||||
|
ScopeId.Value = scopeId; |
||||
|
return new EventRecordingScope((AsyncEnumerableConcurrentScopedTestObject)invocation.TargetObject, scopeId); |
||||
|
} |
||||
|
|
||||
|
private class EventRecordingScope : IAbpInterceptionScope |
||||
|
{ |
||||
|
private readonly AsyncEnumerableConcurrentScopedTestObject _target; |
||||
|
private readonly string _scopeId; |
||||
|
|
||||
|
public EventRecordingScope(AsyncEnumerableConcurrentScopedTestObject target, string scopeId) |
||||
|
{ |
||||
|
_target = target; |
||||
|
_scopeId = scopeId; |
||||
|
} |
||||
|
|
||||
|
public Task CompleteAsync(CancellationToken cancellationToken) |
||||
|
{ |
||||
|
_target.Events.Enqueue($"{_scopeId}:Completed"); |
||||
|
return Task.CompletedTask; |
||||
|
} |
||||
|
|
||||
|
public Task FailAsync(Exception exception) |
||||
|
{ |
||||
|
_target.Events.Enqueue($"{_scopeId}:Failed"); |
||||
|
return Task.CompletedTask; |
||||
|
} |
||||
|
|
||||
|
public void Dispose() |
||||
|
{ |
||||
|
_target.Events.Enqueue($"{_scopeId}:Disposed"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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(); |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -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(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,10 @@ |
|||||
|
using System.Collections.Generic; |
||||
|
|
||||
|
namespace Volo.Abp.DynamicProxy; |
||||
|
|
||||
|
public class ScopeEventLog |
||||
|
{ |
||||
|
public List<string> Events { get; } = new(); |
||||
|
|
||||
|
public int TargetInvocations; |
||||
|
} |
||||
@ -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"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,419 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Linq; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.EntityFrameworkCore; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Application.Services; |
||||
|
using Volo.Abp.DependencyInjection; |
||||
|
using Volo.Abp.Domain.ChangeTracking; |
||||
|
using Volo.Abp.Domain.Repositories; |
||||
|
using Volo.Abp.TestApp.Domain; |
||||
|
using Volo.Abp.Uow; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.EntityFrameworkCore.AsyncEnumerable; |
||||
|
|
||||
|
public interface IStreamingPeopleAppService : IApplicationService |
||||
|
{ |
||||
|
IAsyncEnumerable<string> GetNamesAsync(); |
||||
|
|
||||
|
IAsyncEnumerable<string> IncreaseAgesAsync(int failAfter = -1); |
||||
|
|
||||
|
IAsyncEnumerable<Guid?> GetUnitOfWorkIdsAsync(); |
||||
|
|
||||
|
IAsyncEnumerable<bool> GetIsTransactionalAsync(); |
||||
|
|
||||
|
IAsyncEnumerable<bool> StreamIsTransactionalAsync(); |
||||
|
|
||||
|
IAsyncEnumerable<string> GetNamesWithWorkBeforeReturningAsync(); |
||||
|
|
||||
|
IAsyncEnumerable<int> GetItemsWithOutParameter(out bool hadUnitOfWork); |
||||
|
|
||||
|
IAsyncEnumerable<string> IncreaseAgeThenFailOnCurrent(); |
||||
|
|
||||
|
IAsyncEnumerable<bool?> GetChangeTrackingStatesAsync(); |
||||
|
} |
||||
|
|
||||
|
public class StreamingTracker : ISingletonDependency |
||||
|
{ |
||||
|
public bool SourceDisposed { get; set; } |
||||
|
|
||||
|
public bool UnitOfWorkCompleted { get; set; } |
||||
|
|
||||
|
public bool CallUnitOfWorkCompleted { get; set; } |
||||
|
} |
||||
|
|
||||
|
public class StreamingPeopleAppService : ApplicationService, IStreamingPeopleAppService |
||||
|
{ |
||||
|
private readonly IRepository<Person, Guid> _personRepository; |
||||
|
private readonly StreamingTracker _tracker; |
||||
|
|
||||
|
public StreamingPeopleAppService(IRepository<Person, Guid> personRepository, StreamingTracker tracker) |
||||
|
{ |
||||
|
_personRepository = personRepository; |
||||
|
_tracker = tracker; |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<string> GetNamesAsync() |
||||
|
{ |
||||
|
var queryable = await _personRepository.GetQueryableAsync(); |
||||
|
await foreach (var person in queryable.OrderBy(p => p.Name).AsAsyncEnumerable()) |
||||
|
{ |
||||
|
yield return person.Name; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<string> IncreaseAgesAsync(int failAfter = -1) |
||||
|
{ |
||||
|
CurrentUnitOfWork!.OnCompleted(() => |
||||
|
{ |
||||
|
_tracker.UnitOfWorkCompleted = true; |
||||
|
return Task.CompletedTask; |
||||
|
}); |
||||
|
|
||||
|
try |
||||
|
{ |
||||
|
var people = await _personRepository.GetListAsync(); |
||||
|
var count = 0; |
||||
|
foreach (var person in people.OrderBy(p => p.Name)) |
||||
|
{ |
||||
|
if (++count == failAfter) |
||||
|
{ |
||||
|
throw new InvalidOperationException("Failed while streaming"); |
||||
|
} |
||||
|
|
||||
|
person.Age += 100; |
||||
|
await _personRepository.UpdateAsync(person, autoSave: true); |
||||
|
|
||||
|
yield return person.Name; |
||||
|
} |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
_tracker.SourceDisposed = true; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<Guid?> GetUnitOfWorkIdsAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return CurrentUnitOfWork?.Id; |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<bool> GetIsTransactionalAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return CurrentUnitOfWork!.Options.IsTransactional; |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<bool> StreamIsTransactionalAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return CurrentUnitOfWork!.Options.IsTransactional; |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<string> GetNamesWithWorkBeforeReturningAsync() |
||||
|
{ |
||||
|
CurrentUnitOfWork!.OnCompleted(() => |
||||
|
{ |
||||
|
_tracker.CallUnitOfWorkCompleted = true; |
||||
|
return Task.CompletedTask; |
||||
|
}); |
||||
|
|
||||
|
return GetNamesCoreAsync(); |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> GetItemsWithOutParameter(out bool hadUnitOfWork) |
||||
|
{ |
||||
|
hadUnitOfWork = CurrentUnitOfWork != null; |
||||
|
return GetOneAsync(); |
||||
|
} |
||||
|
|
||||
|
[DisableEntityChangeTracking] |
||||
|
public virtual async IAsyncEnumerable<bool?> GetChangeTrackingStatesAsync() |
||||
|
{ |
||||
|
var changeTrackingProvider = LazyServiceProvider.LazyGetRequiredService<IEntityChangeTrackingProvider>(); |
||||
|
await Task.Delay(1).ConfigureAwait(false); |
||||
|
yield return changeTrackingProvider.Enabled; |
||||
|
await Task.Delay(1).ConfigureAwait(false); |
||||
|
yield return changeTrackingProvider.Enabled; |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<string> IncreaseAgeThenFailOnCurrent() |
||||
|
{ |
||||
|
return new FailingCurrentEnumerable(_personRepository); |
||||
|
} |
||||
|
|
||||
|
private async IAsyncEnumerable<string> GetNamesCoreAsync() |
||||
|
{ |
||||
|
var queryable = await _personRepository.GetQueryableAsync(); |
||||
|
await foreach (var person in queryable.OrderBy(p => p.Name).AsAsyncEnumerable()) |
||||
|
{ |
||||
|
yield return person.Name; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static async IAsyncEnumerable<int> GetOneAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return 1; |
||||
|
} |
||||
|
|
||||
|
private class FailingCurrentEnumerable : IAsyncEnumerable<string>, IAsyncEnumerator<string> |
||||
|
{ |
||||
|
private readonly IRepository<Person, Guid> _personRepository; |
||||
|
|
||||
|
public FailingCurrentEnumerable(IRepository<Person, Guid> personRepository) |
||||
|
{ |
||||
|
_personRepository = personRepository; |
||||
|
} |
||||
|
|
||||
|
public string Current => throw new InvalidOperationException("Failed to read the current item"); |
||||
|
|
||||
|
public IAsyncEnumerator<string> GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken = default) => this; |
||||
|
|
||||
|
public async ValueTask<bool> MoveNextAsync() |
||||
|
{ |
||||
|
foreach (var person in await _personRepository.GetListAsync()) |
||||
|
{ |
||||
|
person.Age += 100; |
||||
|
await _personRepository.UpdateAsync(person, autoSave: true); |
||||
|
} |
||||
|
|
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
public ValueTask DisposeAsync() => default; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class AsyncEnumerable_Interception_Tests : EntityFrameworkCoreTestBase |
||||
|
{ |
||||
|
private readonly IStreamingPeopleAppService _appService; |
||||
|
private readonly IRepository<Person, Guid> _personRepository; |
||||
|
private readonly IUnitOfWorkManager _unitOfWorkManager; |
||||
|
private readonly StreamingTracker _tracker; |
||||
|
|
||||
|
public AsyncEnumerable_Interception_Tests() |
||||
|
{ |
||||
|
_appService = GetRequiredService<IStreamingPeopleAppService>(); |
||||
|
_personRepository = GetRequiredService<IRepository<Person, Guid>>(); |
||||
|
_unitOfWorkManager = GetRequiredService<IUnitOfWorkManager>(); |
||||
|
_tracker = GetRequiredService<StreamingTracker>(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Have_Unit_Of_Work_While_Enumerating() |
||||
|
{ |
||||
|
_unitOfWorkManager.Current.ShouldBeNull(); |
||||
|
|
||||
|
var ids = await _appService.GetUnitOfWorkIdsAsync().ToStreamListAsync(); |
||||
|
|
||||
|
ids.Single().ShouldNotBeNull(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Decide_Transaction_Like_Task_Returning_Methods() |
||||
|
{ |
||||
|
(await _appService.GetIsTransactionalAsync().ToStreamListAsync()).ShouldBe(new[] { false }); |
||||
|
(await _appService.StreamIsTransactionalAsync().ToStreamListAsync()).ShouldBe(new[] { true }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Query_Database_While_Enumerating() |
||||
|
{ |
||||
|
var names = await _appService.GetNamesAsync().ToStreamListAsync(); |
||||
|
|
||||
|
names.ShouldContain("Douglas"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Save_Changes_After_Enumeration_Completed() |
||||
|
{ |
||||
|
await InsertPersonAsync("Aaron"); |
||||
|
var originalAges = await GetAgesAsync(); |
||||
|
|
||||
|
var names = await _appService.IncreaseAgesAsync().ToStreamListAsync(); |
||||
|
|
||||
|
names.Count.ShouldBe(originalAges.Count); |
||||
|
_tracker.UnitOfWorkCompleted.ShouldBeTrue(); |
||||
|
var newAges = await GetAgesAsync(); |
||||
|
foreach (var (id, age) in originalAges) |
||||
|
{ |
||||
|
newAges[id].ShouldBe(age + 100); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Rollback_When_Enumeration_Throws_After_Items_Were_Delivered() |
||||
|
{ |
||||
|
await InsertPersonAsync("Aaron"); |
||||
|
var originalAges = await GetAgesAsync(); |
||||
|
var names = new List<string>(); |
||||
|
|
||||
|
var exception = await Should.ThrowAsync<InvalidOperationException>(async () => |
||||
|
{ |
||||
|
await foreach (var name in _appService.IncreaseAgesAsync(failAfter: 2)) |
||||
|
{ |
||||
|
names.Add(name); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
exception.Message.ShouldBe("Failed while streaming"); |
||||
|
names.ShouldBe(new[] { "Aaron" }); |
||||
|
_tracker.SourceDisposed.ShouldBeTrue(); |
||||
|
_tracker.UnitOfWorkCompleted.ShouldBeFalse(); |
||||
|
(await GetAgesAsync()).ShouldBe(originalAges); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Complete_Unit_Of_Work_When_Consumer_Stops_Early() |
||||
|
{ |
||||
|
var aaronId = await InsertPersonAsync("Aaron"); |
||||
|
var originalAges = await GetAgesAsync(); |
||||
|
|
||||
|
await foreach (var name in _appService.IncreaseAgesAsync()) |
||||
|
{ |
||||
|
name.ShouldBe("Aaron"); |
||||
|
break; |
||||
|
} |
||||
|
|
||||
|
_tracker.SourceDisposed.ShouldBeTrue(); |
||||
|
_tracker.UnitOfWorkCompleted.ShouldBeTrue(); |
||||
|
var newAges = await GetAgesAsync(); |
||||
|
foreach (var (id, age) in originalAges) |
||||
|
{ |
||||
|
newAges[id].ShouldBe(id == aaronId ? age + 100 : age); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Roll_Back_The_Unit_Of_Work_Of_A_Consumer_That_Fails() |
||||
|
{ |
||||
|
await InsertPersonAsync("Aaron"); |
||||
|
var originalAges = await GetAgesAsync(); |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(async () => |
||||
|
{ |
||||
|
using (var unitOfWork = _unitOfWorkManager.Begin(new AbpUnitOfWorkOptions(isTransactional: true), requiresNew: true)) |
||||
|
{ |
||||
|
await foreach (var _ in _appService.IncreaseAgesAsync()) |
||||
|
{ |
||||
|
throw new InvalidOperationException("Failed while consuming"); |
||||
|
} |
||||
|
|
||||
|
await unitOfWork.CompleteAsync(); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
_tracker.SourceDisposed.ShouldBeTrue(); |
||||
|
_tracker.UnitOfWorkCompleted.ShouldBeFalse(); |
||||
|
(await GetAgesAsync()).ShouldBe(originalAges); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Join_Outer_Unit_Of_Work() |
||||
|
{ |
||||
|
await WithUnitOfWorkAsync(async () => |
||||
|
{ |
||||
|
var outerId = _unitOfWorkManager.Current!.Id; |
||||
|
|
||||
|
await foreach (var id in _appService.GetUnitOfWorkIdsAsync()) |
||||
|
{ |
||||
|
id.ShouldBe(outerId); |
||||
|
} |
||||
|
|
||||
|
await foreach (var _ in _appService.GetNamesAsync()) |
||||
|
{ |
||||
|
// The consumer uses the same DbContext as the stream between two items.
|
||||
|
(await _personRepository.GetCountAsync()).ShouldBeGreaterThan(0); |
||||
|
} |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Leave_Completing_The_Reserved_Unit_Of_Work_To_Its_Owner() |
||||
|
{ |
||||
|
await InsertPersonAsync("Aaron"); |
||||
|
var originalAges = await GetAgesAsync(); |
||||
|
|
||||
|
using (var reservedUnitOfWork = _unitOfWorkManager.Reserve(UnitOfWork.UnitOfWorkReservationName)) |
||||
|
{ |
||||
|
(await _appService.IncreaseAgesAsync().ToStreamListAsync()).Count.ShouldBe(originalAges.Count); |
||||
|
|
||||
|
reservedUnitOfWork.IsCompleted.ShouldBeFalse(); |
||||
|
_tracker.UnitOfWorkCompleted.ShouldBeFalse(); |
||||
|
|
||||
|
await reservedUnitOfWork.CompleteAsync(); |
||||
|
} |
||||
|
|
||||
|
_tracker.UnitOfWorkCompleted.ShouldBeTrue(); |
||||
|
var newAges = await GetAgesAsync(); |
||||
|
foreach (var (id, age) in originalAges) |
||||
|
{ |
||||
|
newAges[id].ShouldBe(age + 100); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Apply_Change_Tracking_Attribute_While_Enumerating() |
||||
|
{ |
||||
|
(await _appService.GetChangeTrackingStatesAsync().ToStreamListAsync()).ShouldBe(new bool?[] { false, false }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Have_Unit_Of_Work_When_Creating_The_Sequence() |
||||
|
{ |
||||
|
var names = await _appService.GetNamesWithWorkBeforeReturningAsync().ToStreamListAsync(); |
||||
|
|
||||
|
names.ShouldContain("Douglas"); |
||||
|
_tracker.CallUnitOfWorkCompleted.ShouldBeTrue(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Have_Unit_Of_Work_When_Calling_Method_With_Out_Parameters() |
||||
|
{ |
||||
|
var sequence = _appService.GetItemsWithOutParameter(out var hadUnitOfWork); |
||||
|
|
||||
|
hadUnitOfWork.ShouldBeTrue(); |
||||
|
(await sequence.ToStreamListAsync()).ShouldBe(new[] { 1 }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Rollback_When_Reading_The_Current_Item_Throws() |
||||
|
{ |
||||
|
var originalAges = await GetAgesAsync(); |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(_appService.IncreaseAgeThenFailOnCurrent().ToStreamListAsync()); |
||||
|
|
||||
|
(await GetAgesAsync()).ShouldBe(originalAges); |
||||
|
} |
||||
|
|
||||
|
private async Task<Guid> InsertPersonAsync(string name) |
||||
|
{ |
||||
|
var id = Guid.NewGuid(); |
||||
|
await WithUnitOfWorkAsync(() => _personRepository.InsertAsync(new Person(id, name, 20))); |
||||
|
return id; |
||||
|
} |
||||
|
|
||||
|
private async Task<Dictionary<Guid, int>> GetAgesAsync() |
||||
|
{ |
||||
|
return await WithUnitOfWorkAsync(async () => |
||||
|
(await _personRepository.GetListAsync(includeDetails: false)).ToDictionary(p => p.Id, p => p.Age)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
internal static class AsyncEnumerableTestExtensions |
||||
|
{ |
||||
|
public static async Task<List<T>> ToStreamListAsync<T>(this IAsyncEnumerable<T> source) |
||||
|
{ |
||||
|
var list = new List<T>(); |
||||
|
await foreach (var item in source) |
||||
|
{ |
||||
|
list.Add(item); |
||||
|
} |
||||
|
|
||||
|
return list; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,91 @@ |
|||||
|
using System; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.DependencyInjection; |
||||
|
using Volo.Abp.Domain.Repositories; |
||||
|
using Volo.Abp.TestApp.Domain; |
||||
|
using Volo.Abp.Uow; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.EntityFrameworkCore.AsyncEnumerable; |
||||
|
|
||||
|
public class UnitOfWorkInterceptor_BeginScope_Tests : EntityFrameworkCoreTestBase |
||||
|
{ |
||||
|
protected override void AfterAddApplication(IServiceCollection services) |
||||
|
{ |
||||
|
services.AddSingleton<FailingTransactionBehaviourState>(); |
||||
|
services.Replace(ServiceDescriptor.Scoped<IUnitOfWorkTransactionBehaviourProvider, FailingTransactionBehaviourProvider>()); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Dispose_The_Service_Scope_If_Beginning_The_Unit_Of_Work_Fails() |
||||
|
{ |
||||
|
var state = GetRequiredService<FailingTransactionBehaviourState>(); |
||||
|
var repository = GetRequiredService<IRepository<Person, Guid>>(); |
||||
|
state.Fail = true; |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(() => repository.GetListAsync()); |
||||
|
|
||||
|
state.IsFailedProviderDisposed.ShouldBeTrue(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Dispose_The_Service_Scope_If_Beginning_The_Unit_Of_Work_Of_An_Enumeration_Fails() |
||||
|
{ |
||||
|
var state = GetRequiredService<FailingTransactionBehaviourState>(); |
||||
|
var sequence = GetRequiredService<IStreamingPeopleAppService>().GetNamesAsync(); |
||||
|
state.Fail = true; |
||||
|
|
||||
|
await Should.ThrowAsync<InvalidOperationException>(async () => |
||||
|
{ |
||||
|
await foreach (var _ in sequence) |
||||
|
{ |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
state.IsFailedProviderDisposed.ShouldBeTrue(); |
||||
|
} |
||||
|
|
||||
|
public class FailingTransactionBehaviourState |
||||
|
{ |
||||
|
public bool Fail { get; set; } |
||||
|
|
||||
|
public bool IsFailedProviderDisposed { get; set; } |
||||
|
} |
||||
|
|
||||
|
[DisableConventionalRegistration] |
||||
|
public class FailingTransactionBehaviourProvider : IUnitOfWorkTransactionBehaviourProvider, IDisposable |
||||
|
{ |
||||
|
private readonly FailingTransactionBehaviourState _state; |
||||
|
private bool _hasFailed; |
||||
|
|
||||
|
public FailingTransactionBehaviourProvider(FailingTransactionBehaviourState state) |
||||
|
{ |
||||
|
_state = state; |
||||
|
} |
||||
|
|
||||
|
public bool? IsTransactional |
||||
|
{ |
||||
|
get |
||||
|
{ |
||||
|
if (_state.Fail) |
||||
|
{ |
||||
|
_hasFailed = true; |
||||
|
throw new InvalidOperationException("Failed to get the transaction behaviour"); |
||||
|
} |
||||
|
|
||||
|
return null; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public void Dispose() |
||||
|
{ |
||||
|
if (_hasFailed) |
||||
|
{ |
||||
|
_state.IsFailedProviderDisposed = true; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,121 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Concurrent; |
||||
|
using System.Collections.Generic; |
||||
|
using System.IO; |
||||
|
using System.Linq; |
||||
|
using System.Net.Http; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Shouldly; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Http.Client.ClientProxying; |
||||
|
|
||||
|
public class RegularTestControllerStaticClientProxy_AsyncEnumerable_Tests : AbpHttpClientTestBase |
||||
|
{ |
||||
|
[Fact] |
||||
|
public async Task Should_Stream_Items() |
||||
|
{ |
||||
|
var proxy = ServiceProvider.GetRequiredService<RegularTestControllerStaticClientProxy>(); |
||||
|
|
||||
|
(await ToListAsync(proxy.GetStreamAsync(3))).ShouldBe(new[] { 1, 2, 3 }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Send_The_Arguments_After_A_Leading_CancellationToken() |
||||
|
{ |
||||
|
var proxy = ServiceProvider.GetRequiredService<RegularTestControllerStaticClientProxy>(); |
||||
|
|
||||
|
(await ToListAsync(proxy.GetStreamWithLeadingCancellationTokenAsync(CancellationToken.None, 3))).ShouldBe(new[] { 1, 2, 3 }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Send_The_Request_With_The_CancellationToken_Argument() |
||||
|
{ |
||||
|
var proxy = ServiceProvider.GetRequiredService<RecordingStaticClientProxy>(); |
||||
|
using (var cancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
(await ToListAsync(proxy.GetStreamWithLeadingCancellationTokenAsync(cancellationTokenSource.Token, 3))).ShouldBe(new[] { 1, 2, 3 }); |
||||
|
|
||||
|
proxy.RequestContexts.ShouldHaveSingleItem().CancellationToken.ShouldBe(cancellationTokenSource.Token); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Not_Stream_Items_When_The_CancellationToken_Argument_Is_Canceled() |
||||
|
{ |
||||
|
var proxy = ServiceProvider.GetRequiredService<RegularTestControllerStaticClientProxy>(); |
||||
|
|
||||
|
var items = new List<int>(); |
||||
|
|
||||
|
var exception = await Should.ThrowAsync<Exception>(async () => |
||||
|
{ |
||||
|
await foreach (var item in proxy.GetStreamWithLeadingCancellationTokenAsync(new CancellationToken(canceled: true), 3)) |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
IsCanceled(exception).ShouldBeTrue(exception.ToString()); |
||||
|
items.ShouldBeEmpty(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Send_The_Arguments_In_The_Order_Of_The_Request_Parameters() |
||||
|
{ |
||||
|
var proxy = ServiceProvider.GetRequiredService<RegularTestControllerStaticClientProxy>(); |
||||
|
|
||||
|
(await proxy.GetWithSwappedQueryNamesAsync(10, 20)).ShouldBe("10-20"); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Build_A_Request_Context_For_Each_Enumeration() |
||||
|
{ |
||||
|
var proxy = ServiceProvider.GetRequiredService<RecordingStaticClientProxy>(); |
||||
|
var sequence = proxy.GetStreamAsync(3); |
||||
|
|
||||
|
var results = await Task.WhenAll(ToListAsync(sequence), ToListAsync(sequence)); |
||||
|
|
||||
|
results[0].ShouldBe(new[] { 1, 2, 3 }); |
||||
|
results[1].ShouldBe(new[] { 1, 2, 3 }); |
||||
|
proxy.RequestContexts.Distinct().Count().ShouldBe(2); |
||||
|
proxy.RequestContexts.ShouldAllBe(context => context.CancellationToken == null); |
||||
|
} |
||||
|
|
||||
|
// The test server reports a request canceled after it is sent as an aborted response.
|
||||
|
private static bool IsCanceled(Exception? exception) |
||||
|
{ |
||||
|
for (; exception != null; exception = exception.InnerException) |
||||
|
{ |
||||
|
if (exception is OperationCanceledException || exception is IOException && exception.Message.Contains("aborted")) |
||||
|
{ |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
private static async Task<List<int>> ToListAsync(IAsyncEnumerable<int> source) |
||||
|
{ |
||||
|
var list = new List<int>(); |
||||
|
await foreach (var item in source) |
||||
|
{ |
||||
|
list.Add(item); |
||||
|
} |
||||
|
|
||||
|
return list; |
||||
|
} |
||||
|
|
||||
|
public class RecordingStaticClientProxy : RegularTestControllerStaticClientProxy |
||||
|
{ |
||||
|
public ConcurrentQueue<ClientProxyRequestContext> RequestContexts { get; } = new(); |
||||
|
|
||||
|
protected override Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
||||
|
{ |
||||
|
RequestContexts.Enqueue(requestContext); |
||||
|
return base.RequestAsync(requestContext); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,286 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Concurrent; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Linq; |
||||
|
using System.Net.Http; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.AspNetCore.TestBase; |
||||
|
using Volo.Abp.Http.Client.ClientProxying; |
||||
|
using Volo.Abp.Http.Client.DynamicProxying; |
||||
|
using Volo.Abp.Http.Client.Proxying; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Http.DynamicProxying; |
||||
|
|
||||
|
public abstract class AsyncEnumerableClientProxyCancellation_Tests : AbpHttpClientTestBase |
||||
|
{ |
||||
|
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); |
||||
|
|
||||
|
protected IRegularTestController Controller => ServiceProvider.GetRequiredService<IRegularTestController>(); |
||||
|
|
||||
|
protected abstract bool BlockApiDefinitionRequest { get; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// Released when a request reaches the blocking handler, so a test can cancel exactly at that stage.
|
||||
|
/// </summary>
|
||||
|
protected SemaphoreSlim BlockedRequests { get; } = new(0); |
||||
|
|
||||
|
protected override void ConfigureServices(IServiceCollection services) |
||||
|
{ |
||||
|
services.Replace(ServiceDescriptor.Singleton<IProxyHttpClientFactory>(serviceProvider => |
||||
|
new BlockingProxyHttpClientFactory(serviceProvider.GetRequiredService<ITestServerAccessor>(), BlockApiDefinitionRequest, BlockedRequests))); |
||||
|
} |
||||
|
|
||||
|
protected async Task WaitForBlockedRequestsAsync(int count) |
||||
|
{ |
||||
|
for (var i = 0; i < count; i++) |
||||
|
{ |
||||
|
(await BlockedRequests.WaitAsync(Timeout)).ShouldBeTrue("The request did not reach the blocking handler."); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
protected async Task ShouldBeCancelledWhenBlockedAsync(Func<Task> enumerate, CancellationTokenSource cancellationTokenSource) |
||||
|
{ |
||||
|
var enumeration = enumerate(); |
||||
|
await WaitForBlockedRequestsAsync(1); |
||||
|
cancellationTokenSource.Cancel(); |
||||
|
await ShouldBeCancelledAsync(() => enumeration); |
||||
|
} |
||||
|
|
||||
|
protected static async Task ShouldBeCancelledAsync(Func<Task> enumerate) |
||||
|
{ |
||||
|
var exception = await Should.ThrowAsync<Exception>(() => enumerate().WaitAsync(Timeout)); |
||||
|
|
||||
|
exception.ShouldNotBeOfType<TimeoutException>(); |
||||
|
(exception is OperationCanceledException || exception.InnerException is OperationCanceledException).ShouldBeTrue(exception.ToString()); |
||||
|
} |
||||
|
|
||||
|
private class BlockingProxyHttpClientFactory : IProxyHttpClientFactory |
||||
|
{ |
||||
|
private readonly ITestServerAccessor _testServerAccessor; |
||||
|
private readonly bool _blockApiDefinitionRequest; |
||||
|
private readonly SemaphoreSlim _blockedRequests; |
||||
|
private int _count; |
||||
|
|
||||
|
public BlockingProxyHttpClientFactory(ITestServerAccessor testServerAccessor, bool blockApiDefinitionRequest, SemaphoreSlim blockedRequests) |
||||
|
{ |
||||
|
_testServerAccessor = testServerAccessor; |
||||
|
_blockApiDefinitionRequest = blockApiDefinitionRequest; |
||||
|
_blockedRequests = blockedRequests; |
||||
|
} |
||||
|
|
||||
|
public HttpClient Create(string name) => Create(); |
||||
|
|
||||
|
public HttpClient Create() |
||||
|
{ |
||||
|
if (Interlocked.Increment(ref _count) == 1 && !_blockApiDefinitionRequest) |
||||
|
{ |
||||
|
return _testServerAccessor.Server.CreateClient(); |
||||
|
} |
||||
|
|
||||
|
return new HttpClient(new BlockingHttpMessageHandler(_blockedRequests)) |
||||
|
{ |
||||
|
BaseAddress = new Uri("http://localhost/") |
||||
|
}; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private class BlockingHttpMessageHandler : HttpMessageHandler |
||||
|
{ |
||||
|
private readonly SemaphoreSlim _blockedRequests; |
||||
|
|
||||
|
public BlockingHttpMessageHandler(SemaphoreSlim blockedRequests) |
||||
|
{ |
||||
|
_blockedRequests = blockedRequests; |
||||
|
} |
||||
|
|
||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
||||
|
{ |
||||
|
_blockedRequests.Release(); |
||||
|
await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken); |
||||
|
throw new InvalidOperationException("Unreachable"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class AsyncEnumerableClientProxy_Request_Cancellation_Tests : AsyncEnumerableClientProxyCancellation_Tests |
||||
|
{ |
||||
|
protected override bool BlockApiDefinitionRequest => false; |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Cancel_Request_Before_Response_Headers_When_Method_Has_Its_Own_Token() |
||||
|
{ |
||||
|
using (var methodCancellationTokenSource = new CancellationTokenSource()) |
||||
|
using (var enumerationCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token) |
||||
|
.WithCancellation(enumerationCancellationTokenSource.Token)) |
||||
|
{ |
||||
|
} |
||||
|
}, enumerationCancellationTokenSource); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class AsyncEnumerableClientProxy_RequestContext_Cancellation_Tests : AsyncEnumerableClientProxyCancellation_Tests |
||||
|
{ |
||||
|
protected override bool BlockApiDefinitionRequest => false; |
||||
|
|
||||
|
protected override void ConfigureServices(IServiceCollection services) |
||||
|
{ |
||||
|
base.ConfigureServices(services); |
||||
|
services.AddSingleton<RequestContextRecorder>(); |
||||
|
services.Replace(ServiceDescriptor.Transient<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>, RecordingClientProxy>()); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Cancel_Request_With_The_Token_Of_The_Request_Context() |
||||
|
{ |
||||
|
var action = await GetActionAsync(); |
||||
|
using (var contextCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
var requestContext = new ClientProxyRequestContext(action.Action, action.Arguments, action.ServiceType) |
||||
|
{ |
||||
|
CancellationToken = contextCancellationTokenSource.Token |
||||
|
}; |
||||
|
|
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in ClientProxy.CallRequestAsyncEnumerable<int>(requestContext)) |
||||
|
{ |
||||
|
} |
||||
|
}, contextCancellationTokenSource); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Isolate_Cancellation_Of_Concurrent_Enumerations_Of_The_Same_Request_Context() |
||||
|
{ |
||||
|
var action = await GetActionAsync(); |
||||
|
var requestContext = new ClientProxyRequestContext(action.Action, action.Arguments, action.ServiceType); |
||||
|
var sequence = ClientProxy.CallRequestAsyncEnumerable<int>(requestContext); |
||||
|
using (var firstCancellationTokenSource = new CancellationTokenSource()) |
||||
|
using (var secondCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
var first = EnumerateAsync(sequence, firstCancellationTokenSource.Token); |
||||
|
var second = EnumerateAsync(sequence, secondCancellationTokenSource.Token); |
||||
|
await WaitForBlockedRequestsAsync(2); |
||||
|
|
||||
|
firstCancellationTokenSource.Cancel(); |
||||
|
await ShouldBeCancelledAsync(() => first); |
||||
|
await Task.Delay(200); |
||||
|
second.IsCompleted.ShouldBeFalse(); |
||||
|
|
||||
|
secondCancellationTokenSource.Cancel(); |
||||
|
await ShouldBeCancelledAsync(() => second); |
||||
|
requestContext.CancellationToken.ShouldBeNull(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Cancel_Request_With_Method_Token_That_Is_Not_The_Last_Argument() |
||||
|
{ |
||||
|
using (var methodCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) |
||||
|
{ |
||||
|
} |
||||
|
}, methodCancellationTokenSource); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private DynamicHttpProxyInterceptorClientProxy<IRegularTestController> ClientProxy => |
||||
|
ServiceProvider.GetRequiredService<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>>(); |
||||
|
|
||||
|
private async Task<ClientProxyRequestContext> GetActionAsync() |
||||
|
{ |
||||
|
// The business request is blocked, but RequestAsync records its context before sending it.
|
||||
|
using (var cancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in Controller.GetStreamAsync(1).WithCancellation(cancellationTokenSource.Token)) |
||||
|
{ |
||||
|
} |
||||
|
}, cancellationTokenSource); |
||||
|
|
||||
|
return ServiceProvider.GetRequiredService<RequestContextRecorder>().Contexts.Last(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static async Task EnumerateAsync(IAsyncEnumerable<int> sequence, CancellationToken cancellationToken) |
||||
|
{ |
||||
|
await foreach (var _ in sequence.WithCancellation(cancellationToken)) |
||||
|
{ |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class RequestContextRecorder |
||||
|
{ |
||||
|
public ConcurrentQueue<ClientProxyRequestContext> Contexts { get; } = new(); |
||||
|
} |
||||
|
|
||||
|
public class RecordingClientProxy : DynamicHttpProxyInterceptorClientProxy<IRegularTestController> |
||||
|
{ |
||||
|
protected override Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
||||
|
{ |
||||
|
LazyServiceProvider.LazyGetRequiredService<RequestContextRecorder>().Contexts.Enqueue(requestContext); |
||||
|
return base.RequestAsync(requestContext); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class AsyncEnumerableClientProxy_ApiDefinition_Cancellation_Tests : AsyncEnumerableClientProxyCancellation_Tests |
||||
|
{ |
||||
|
protected override bool BlockApiDefinitionRequest => true; |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Cancel_Api_Definition_Request_With_Method_Token() |
||||
|
{ |
||||
|
using (var methodCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in Controller.GetStreamWithCancellationTokenAsync(methodCancellationTokenSource.Token)) |
||||
|
{ |
||||
|
} |
||||
|
}, methodCancellationTokenSource); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Cancel_Api_Definition_Request_With_Method_Token_That_Is_Not_The_Last_Argument() |
||||
|
{ |
||||
|
using (var methodCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in Controller.GetStreamWithLeadingCancellationTokenAsync(methodCancellationTokenSource.Token, 3)) |
||||
|
{ |
||||
|
} |
||||
|
}, methodCancellationTokenSource); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Cancel_Api_Definition_Request() |
||||
|
{ |
||||
|
using (var enumerationCancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
await ShouldBeCancelledWhenBlockedAsync(async () => |
||||
|
{ |
||||
|
await foreach (var _ in Controller.GetStreamAsync(3).WithCancellation(enumerationCancellationTokenSource.Token)) |
||||
|
{ |
||||
|
} |
||||
|
}, enumerationCancellationTokenSource); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,110 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Net.Http; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.AspNetCore.TestBase; |
||||
|
using Volo.Abp.Http.Client.ClientProxying; |
||||
|
using Volo.Abp.Http.Client.DynamicProxying; |
||||
|
using Volo.Abp.Http.Client.Proxying; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Http.DynamicProxying; |
||||
|
|
||||
|
public class AsyncEnumerableClientProxy_NestedRequest_Tests : AbpHttpClientTestBase |
||||
|
{ |
||||
|
protected override void ConfigureServices(IServiceCollection services) |
||||
|
{ |
||||
|
services.Replace(ServiceDescriptor.Transient<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>, NestedRequestClientProxy>()); |
||||
|
services.Replace(ServiceDescriptor.Singleton<IProxyHttpClientFactory>(serviceProvider => |
||||
|
new TokenCheckingProxyHttpClientFactory(serviceProvider.GetRequiredService<ITestServerAccessor>()))); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Keep_The_Token_Of_Another_Request_Sent_While_Sending_A_Stream() |
||||
|
{ |
||||
|
NestedRequestClientProxy.NestedRequestExceptions.Clear(); |
||||
|
var controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
||||
|
|
||||
|
var items = new List<int>(); |
||||
|
await foreach (var item in controller.GetStreamAsync(2)) |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { 1, 2 }); |
||||
|
var exception = NestedRequestClientProxy.NestedRequestExceptions.ShouldHaveSingleItem(); |
||||
|
exception.ShouldNotBeNull(); |
||||
|
(exception is OperationCanceledException || exception.InnerException is OperationCanceledException).ShouldBeTrue(exception.ToString()); |
||||
|
} |
||||
|
|
||||
|
public class NestedRequestClientProxy : DynamicHttpProxyInterceptorClientProxy<IRegularTestController> |
||||
|
{ |
||||
|
public static List<Exception?> NestedRequestExceptions { get; } = new(); |
||||
|
|
||||
|
protected override async Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
||||
|
{ |
||||
|
if (requestContext.Action.Name == nameof(IRegularTestController.GetStreamAsync)) |
||||
|
{ |
||||
|
// Another request with its own (cancelled) token, sent before the stream request.
|
||||
|
var nestedRequestContext = new ClientProxyRequestContext(requestContext.Action, requestContext.Arguments, requestContext.ServiceType) |
||||
|
{ |
||||
|
CancellationToken = new CancellationToken(canceled: true) |
||||
|
}; |
||||
|
|
||||
|
try |
||||
|
{ |
||||
|
using (await base.RequestAsync(nestedRequestContext)) |
||||
|
{ |
||||
|
} |
||||
|
|
||||
|
NestedRequestExceptions.Add(null); |
||||
|
} |
||||
|
catch (Exception exception) |
||||
|
{ |
||||
|
NestedRequestExceptions.Add(exception); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return await base.RequestAsync(requestContext); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private class TokenCheckingProxyHttpClientFactory : IProxyHttpClientFactory |
||||
|
{ |
||||
|
private readonly ITestServerAccessor _testServerAccessor; |
||||
|
|
||||
|
public TokenCheckingProxyHttpClientFactory(ITestServerAccessor testServerAccessor) |
||||
|
{ |
||||
|
_testServerAccessor = testServerAccessor; |
||||
|
} |
||||
|
|
||||
|
public HttpClient Create(string name) => Create(); |
||||
|
|
||||
|
public HttpClient Create() |
||||
|
{ |
||||
|
return new HttpClient(new TokenCheckingHandler(_testServerAccessor.Server.CreateHandler())) |
||||
|
{ |
||||
|
BaseAddress = _testServerAccessor.Server.BaseAddress |
||||
|
}; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// The test server does not observe a token that is already cancelled when the request is sent.
|
||||
|
private class TokenCheckingHandler : DelegatingHandler |
||||
|
{ |
||||
|
public TokenCheckingHandler(HttpMessageHandler innerHandler) |
||||
|
: base(innerHandler) |
||||
|
{ |
||||
|
} |
||||
|
|
||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
||||
|
{ |
||||
|
cancellationToken.ThrowIfCancellationRequested(); |
||||
|
return base.SendAsync(request, cancellationToken); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,83 @@ |
|||||
|
using System.Collections.Generic; |
||||
|
using System.Linq; |
||||
|
using System.Net.Http; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Http.Client.ClientProxying; |
||||
|
using Volo.Abp.Http.Client.DynamicProxying; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Http.DynamicProxying; |
||||
|
|
||||
|
public class AsyncEnumerableClientProxy_RequestOverride_Tests : AbpHttpClientTestBase |
||||
|
{ |
||||
|
protected override void ConfigureServices(IServiceCollection services) |
||||
|
{ |
||||
|
services.Replace(ServiceDescriptor.Transient<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>, TrackingClientProxy>()); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Use_Overridden_RequestAsync_For_Streams() |
||||
|
{ |
||||
|
TrackingClientProxy.RequestedActions.Clear(); |
||||
|
var controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
||||
|
|
||||
|
var items = new List<int>(); |
||||
|
await foreach (var item in controller.GetStreamAsync(2)) |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { 1, 2 }); |
||||
|
TrackingClientProxy.RequestedActions.ShouldContain(nameof(IRegularTestController.GetStreamAsync)); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Pass_The_Same_Request_Context_To_RequestAsync() |
||||
|
{ |
||||
|
TrackingClientProxy.RequestContexts.Clear(); |
||||
|
var controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
||||
|
await foreach (var _ in controller.GetStreamAsync(1)) |
||||
|
{ |
||||
|
} |
||||
|
|
||||
|
var capturedContext = TrackingClientProxy.RequestContexts.Last(); |
||||
|
var requestContext = new CustomRequestContext(capturedContext.Action, capturedContext.Arguments, capturedContext.ServiceType); |
||||
|
|
||||
|
var clientProxy = ServiceProvider.GetRequiredService<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>>(); |
||||
|
var items = new List<int>(); |
||||
|
await foreach (var item in clientProxy.CallRequestAsyncEnumerable<int>(requestContext)) |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { 1 }); |
||||
|
TrackingClientProxy.RequestContexts.Last().ShouldBeSameAs(requestContext); |
||||
|
requestContext.CancellationToken.ShouldBeNull(); |
||||
|
} |
||||
|
|
||||
|
public class CustomRequestContext : ClientProxyRequestContext |
||||
|
{ |
||||
|
public CustomRequestContext(Volo.Abp.Http.Modeling.ActionApiDescriptionModel action, IReadOnlyDictionary<string, object?> arguments, System.Type serviceType) |
||||
|
: base(action, arguments, serviceType) |
||||
|
{ |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public class TrackingClientProxy : DynamicHttpProxyInterceptorClientProxy<IRegularTestController> |
||||
|
{ |
||||
|
public static List<string> RequestedActions { get; } = new(); |
||||
|
|
||||
|
public static List<ClientProxyRequestContext> RequestContexts { get; } = new(); |
||||
|
|
||||
|
protected override Task<HttpContent> RequestAsync(ClientProxyRequestContext requestContext) |
||||
|
{ |
||||
|
RequestedActions.Add(requestContext.Action.Name); |
||||
|
RequestContexts.Add(requestContext); |
||||
|
return base.RequestAsync(requestContext); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,155 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Runtime.CompilerServices; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Shouldly; |
||||
|
using Volo.Abp.Http.Client; |
||||
|
using Volo.Abp.Http.Client.DynamicProxying; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace Volo.Abp.Http.DynamicProxying; |
||||
|
|
||||
|
public class AsyncEnumerableClientProxy_Tests : AbpHttpClientTestBase |
||||
|
{ |
||||
|
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); |
||||
|
|
||||
|
private readonly IRegularTestController _controller; |
||||
|
|
||||
|
public AsyncEnumerableClientProxy_Tests() |
||||
|
{ |
||||
|
_controller = ServiceProvider.GetRequiredService<IRegularTestController>(); |
||||
|
AsyncEnumerableTestGate.Reset(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public void Should_Not_Use_A_Token_That_Can_Not_Be_Cancelled() |
||||
|
{ |
||||
|
var clientProxy = ServiceProvider.GetRequiredService<DynamicHttpProxyInterceptorClientProxy<IRegularTestController>>(); |
||||
|
|
||||
|
clientProxy.UseCancellationToken(CancellationToken.None).ShouldBeSameAs(NullDisposable.Instance); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Send_The_Arguments_After_A_Leading_CancellationToken() |
||||
|
{ |
||||
|
var items = new List<int>(); |
||||
|
await foreach (var item in _controller.GetStreamWithLeadingCancellationTokenAsync(CancellationToken.None, 3)) |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { 1, 2, 3 }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Stream_Items() |
||||
|
{ |
||||
|
var items = new List<int>(); |
||||
|
await foreach (var item in _controller.GetStreamAsync(3)) |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { 1, 2, 3 }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Receive_Items_Before_Server_Finishes() |
||||
|
{ |
||||
|
var items = new List<string>(); |
||||
|
|
||||
|
try |
||||
|
{ |
||||
|
// The server waits for the gate after the first item, so this only completes if the first item is streamed.
|
||||
|
await ConsumeAsync(_controller.GetGatedStreamAsync(false), item => |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
AsyncEnumerableTestGate.Open(); |
||||
|
}).WaitAsync(Timeout); |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
AsyncEnumerableTestGate.Open(); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { "first", "second" }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Throw_Remote_Exception_When_Server_Fails_Before_Response_Started() |
||||
|
{ |
||||
|
var items = new List<int>(); |
||||
|
|
||||
|
var exception = await Should.ThrowAsync<AbpRemoteCallException>( |
||||
|
ConsumeAsync(_controller.GetStreamWithErrorAsync(), items.Add)); |
||||
|
|
||||
|
exception.Error.Message.ShouldBe("Stream failed"); |
||||
|
items.ShouldBeEmpty(); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Throw_When_Server_Fails_After_Response_Started() |
||||
|
{ |
||||
|
var items = new List<string>(); |
||||
|
|
||||
|
Exception exception; |
||||
|
try |
||||
|
{ |
||||
|
exception = await Should.ThrowAsync<Exception>( |
||||
|
ConsumeAsync(_controller.GetGatedStreamAsync(true), item => |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
AsyncEnumerableTestGate.Open(); |
||||
|
}).WaitAsync(Timeout)); |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
AsyncEnumerableTestGate.Open(); |
||||
|
} |
||||
|
|
||||
|
exception.ShouldNotBeOfType<TimeoutException>(); |
||||
|
items.ShouldBe(new[] { "first" }); |
||||
|
} |
||||
|
|
||||
|
[Fact] |
||||
|
public async Task Should_Stop_When_Cancelled_While_Waiting_For_Next_Item() |
||||
|
{ |
||||
|
var items = new List<string>(); |
||||
|
using (var cancellationTokenSource = new CancellationTokenSource()) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
await Should.ThrowAsync<OperationCanceledException>( |
||||
|
ConsumeAsync(_controller.GetGatedStreamAsync(false).WithCancellation(cancellationTokenSource.Token), item => |
||||
|
{ |
||||
|
items.Add(item); |
||||
|
cancellationTokenSource.Cancel(); |
||||
|
}).WaitAsync(Timeout)); |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
AsyncEnumerableTestGate.Open(); |
||||
|
} |
||||
|
|
||||
|
items.ShouldBe(new[] { "first" }); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static async Task ConsumeAsync<T>(IAsyncEnumerable<T> source, Action<T> onItem) |
||||
|
{ |
||||
|
await foreach (var item in source) |
||||
|
{ |
||||
|
onItem(item); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private static async Task ConsumeAsync<T>(ConfiguredCancelableAsyncEnumerable<T> source, Action<T> onItem) |
||||
|
{ |
||||
|
await foreach (var item in source) |
||||
|
{ |
||||
|
onItem(item); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,29 @@ |
|||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
|
||||
|
namespace Volo.Abp.Http.DynamicProxying; |
||||
|
|
||||
|
public static class AsyncEnumerableTestGate |
||||
|
{ |
||||
|
private static TaskCompletionSource<bool> _gate = Create(); |
||||
|
|
||||
|
public static void Reset() |
||||
|
{ |
||||
|
_gate = Create(); |
||||
|
} |
||||
|
|
||||
|
public static void Open() |
||||
|
{ |
||||
|
_gate.TrySetResult(true); |
||||
|
} |
||||
|
|
||||
|
public static Task WaitAsync(CancellationToken cancellationToken) |
||||
|
{ |
||||
|
return _gate.Task.WaitAsync(cancellationToken); |
||||
|
} |
||||
|
|
||||
|
private static TaskCompletionSource<bool> Create() |
||||
|
{ |
||||
|
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,26 @@ |
|||||
|
using System.Collections.Generic; |
||||
|
using System.Threading.Tasks; |
||||
|
using Volo.Abp.Application.Services; |
||||
|
|
||||
|
namespace Volo.Abp.TestApp.Application; |
||||
|
|
||||
|
public class StreamingAppService : ApplicationService |
||||
|
{ |
||||
|
public virtual async IAsyncEnumerable<int> GetItemsAsync() |
||||
|
{ |
||||
|
await Task.Yield(); |
||||
|
yield return 1; |
||||
|
yield return 2; |
||||
|
} |
||||
|
|
||||
|
public virtual async IAsyncEnumerable<int> GetSlowItemsAsync() |
||||
|
{ |
||||
|
await Task.Delay(50); |
||||
|
yield return 1; |
||||
|
} |
||||
|
|
||||
|
public virtual IAsyncEnumerable<int> GetItemsWithCreationErrorAsync() |
||||
|
{ |
||||
|
throw new UserFriendlyException("Failed to create the sequence"); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue