diff --git a/docs/en/framework/api-development/dynamic-csharp-clients.md b/docs/en/framework/api-development/dynamic-csharp-clients.md index bfacc26886..53ff6c833d 100644 --- a/docs/en/framework/api-development/dynamic-csharp-clients.md +++ b/docs/en/framework/api-development/dynamic-csharp-clients.md @@ -119,6 +119,19 @@ public class MyService : ITransientDependency This sample injects the `IBookAppService` service interface defined above. The dynamic client proxy implementation makes an HTTP call whenever a service method is called by the client. +### Streaming with IAsyncEnumerable + +Service methods returning `IAsyncEnumerable` are also supported. The HTTP request is sent when the returned sequence is enumerated, and the items are read from the response as they arrive. For example, if `IBookAppService` has an `IAsyncEnumerable GetStreamAsync()` method: + +````csharp +await foreach (var book in _bookService.GetStreamAsync().WithCancellation(cancellationToken)) +{ + Console.WriteLine($"[BOOK {book.Id}] Name={book.Name}"); +} +```` + +You can cancel the request with the token passed to the enumeration (like `WithCancellation` above) or with a `CancellationToken` parameter of the service method. + ### IHttpClientProxy Interface While you can inject `IBookAppService` like above to use the client proxy, you could inject `IHttpClientProxy` for a more explicit usage. In this case you will use the `Service` property of the `IHttpClientProxy` interface. diff --git a/docs/en/framework/api-development/static-csharp-clients.md b/docs/en/framework/api-development/static-csharp-clients.md index 7491f46d67..f7d9cae589 100644 --- a/docs/en/framework/api-development/static-csharp-clients.md +++ b/docs/en/framework/api-development/static-csharp-clients.md @@ -204,6 +204,19 @@ public class MyService : ITransientDependency This sample injects the `IBookAppService` service interface defined above. The static client proxy implementation makes an HTTP call whenever a service method is called by the client. +### Streaming with IAsyncEnumerable + +Service methods returning `IAsyncEnumerable` are also supported. The HTTP request is sent when the returned sequence is enumerated (a new request for each enumeration), and the items are read from the response as they arrive. For example, if `IBookAppService` has an `IAsyncEnumerable GetStreamAsync()` method: + +````csharp +await foreach (var book in _bookService.GetStreamAsync().WithCancellation(cancellationToken)) +{ + Console.WriteLine($"[BOOK {book.Id}] Name={book.Name}"); +} +```` + +You can cancel the request with the token passed to the enumeration, like `WithCancellation` above. + ## Configuration ### AbpRemoteServiceOptions diff --git a/docs/en/framework/architecture/domain-driven-design/unit-of-work.md b/docs/en/framework/architecture/domain-driven-design/unit-of-work.md index 6b6de422a1..d6f7b619e5 100644 --- a/docs/en/framework/architecture/domain-driven-design/unit-of-work.md +++ b/docs/en/framework/architecture/domain-driven-design/unit-of-work.md @@ -34,6 +34,14 @@ A UOW automatically begins for these methods **except** if there is already a ** All of these are automatically handled by the ABP. +### Methods Returning IAsyncEnumerable + +A method returning `IAsyncEnumerable` does its work when the returned sequence is enumerated, after the method has returned. So; + +* The method call and each enumeration of the returned sequence run in separate UOWs (or participate in the surrounding UOW, if there is one). +* The UOW of an enumeration is completed when the enumeration ends, even if the caller stops it early. It is not completed if the sequence throws an exception. +* Query the database inside the iterator method (the method body containing `yield return`). A `DbContext` or a query obtained while calling the method can not be used after the UOW of the call ends. + ### Database Transaction Behavior While the section above explains the UOW as it is database transaction, actually a UOW doesn't have to be transactional. By default; diff --git a/docs/en/framework/infrastructure/audit-logging.md b/docs/en/framework/infrastructure/audit-logging.md index dc8564ec0c..9c0eb68b9e 100644 --- a/docs/en/framework/infrastructure/audit-logging.md +++ b/docs/en/framework/infrastructure/audit-logging.md @@ -331,6 +331,16 @@ An **audit log object** is created for each **web request** by default. An audit In addition to the standard properties explained above, `AuditLogInfo`, `AuditLogActionInfo` and `EntityChangeInfo` objects implement the `IHasExtraProperties` interface, so you can add custom properties to these objects. +### Methods Returning IAsyncEnumerable + +A method returning `IAsyncEnumerable` does its work when the returned sequence is enumerated. So, if such a method is audited by the auditing interceptor, the method call and each enumeration of the returned sequence are recorded as separate actions: + +* The action of the method call is recorded like for other methods. +* The action of an enumeration has the `AsyncEnumeration` extra property set to `true`, and its `ExecutionDuration` is the duration of the whole enumeration, regardless of the number of items. The exceptions and the entity changes during the enumeration are also recorded. +* If there is no current audit log scope when the sequence is enumerated (for example, in a background job), the enumeration is saved as a separate audit log. + +A controller action (including an [Auto API Controller](../api-development/auto-controllers.md) action) returning `IAsyncEnumerable` is audited by the auditing action filter instead, and recorded as a single action of the audit log of the web request. + ## Audit Log Contributors You can extend the auditing system by creating a class that is derived from the `AuditLogContributor` class which defines the `PreContribute` and the `PostContribute` methods. diff --git a/docs/en/framework/infrastructure/interceptors.md b/docs/en/framework/infrastructure/interceptors.md index c6cedf7859..cfb6438c0d 100644 --- a/docs/en/framework/infrastructure/interceptors.md +++ b/docs/en/framework/infrastructure/interceptors.md @@ -152,6 +152,89 @@ public override void PreConfigureServices(ServiceConfigurationContext context) } ```` +## Advanced Topics + +### Intercepting Methods Returning IAsyncEnumerable + +A method returning `IAsyncEnumerable` is intercepted like a method returning `Task`: the interceptor runs when the method is called, and `invocation.ProceedAsync()` only creates the sequence. The sequence does its work later, when the caller enumerates it, so an interceptor does not cover the enumeration by default. If an interceptor throws (for example, an authorization or validation error), the exception is thrown when the sequence is enumerated. + +To also cover the enumeration, inherit your interceptor from `AbpScopeInterceptor` and return an `IAbpInterceptionScope` from the `BeginScope` method. The scope runs around the method call, and a new scope runs around each enumeration of the returned sequence. For example, you can change the `ExecutionTimeLogInterceptor` above as below to also measure the enumerations: + +````csharp +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DynamicProxy; + +public class ExecutionTimeLogInterceptor : AbpScopeInterceptor, ITransientDependency +{ + private readonly ILogger _logger; + + public ExecutionTimeLogInterceptor(ILogger logger) + { + _logger = logger; + } + + protected override IAbpInterceptionScope BeginScope(IAbpMethodInvocation invocation) + { + return new ExecutionTimeLogScope(_logger, invocation.Method.Name); + } +} + +public class ExecutionTimeLogScope : IAbpInterceptionScope +{ + private readonly ILogger _logger; + private readonly string _methodName; + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); + + public ExecutionTimeLogScope(ILogger logger, string methodName) + { + _logger = logger; + _methodName = methodName; + } + + public Task CompleteAsync(CancellationToken cancellationToken) + { + _logger.LogInformation($"Executed {_methodName} in {_stopwatch.ElapsedMilliseconds} ms"); + return Task.CompletedTask; + } + + public Task FailAsync(Exception exception) + { + _logger.LogWarning($"{_methodName} failed after {_stopwatch.ElapsedMilliseconds} ms"); + return Task.CompletedTask; + } + + public void Dispose() + { + } +} +```` + +* `CompleteAsync` is called when the method call or the enumeration completes, including when the caller stops enumerating early (for example, with `break`). +* `FailAsync` is called when the method or the sequence throws an exception. +* `Dispose` is always called at the end. + +`AbpInterceptionScope` is a default implementation that disposes a given object, which is useful to change an ambient value during the scope. For example, `new AbpInterceptionScope(_currentTenant.Change(tenantId))` switches the current tenant during the method call and each enumeration. + +If your interceptor can not inherit from `AbpScopeInterceptor`, call the `ProceedInScopeAsync` extension method in the `InterceptAsync` method instead of `invocation.ProceedAsync()`: + +````csharp +public override async Task InterceptAsync(IAbpMethodInvocation invocation) +{ + await invocation.ProceedInScopeAsync(() => BeginScope(invocation)); +} +```` + +ABP's [Unit of Work](../architecture/domain-driven-design/unit-of-work.md), [Auditing](./audit-logging.md) and entity change tracking interceptors work this way, while the authorization, validation and feature checks are only performed when the method is called. + +> `BeginScope` must set its async local values synchronously (for example, it should not be an `async` method). Otherwise, the values are not available to the method and to the enumeration. + +> Since the authorization and other checks are performed when the method is called, you should enumerate the returned sequence in the same context (the same user and tenant) as the method call. + ## Restrictions and Important Notes ### Always use asynchronous methods