| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using IceRpc.Extensions.DependencyInjection; |
| | | 4 | | using IceRpc.Metrics.Internal; |
| | | 5 | | using System.Diagnostics.Metrics; |
| | | 6 | | |
| | | 7 | | namespace IceRpc.Metrics; |
| | | 8 | | |
| | | 9 | | /// <summary>A middleware that publishes dispatch metrics using a singleton meter named "IceRpc.Dispatch". |
| | | 10 | | /// </summary> |
| | | 11 | | /// <seealso cref="Meter"/> |
| | | 12 | | /// <seealso cref="MetricsRouterExtensions"/> |
| | | 13 | | /// <seealso cref="MetricsDispatcherBuilderExtensions"/> |
| | | 14 | | public class MetricsMiddleware : IDispatcher |
| | | 15 | | { |
| | | 16 | | private readonly IDispatcher _next; |
| | | 17 | | private readonly DispatchMetrics _dispatchMetrics; |
| | | 18 | | |
| | | 19 | | /// <summary>Constructs a metrics middleware.</summary> |
| | | 20 | | /// <param name="next">The next dispatcher in the dispatch pipeline.</param> |
| | | 21 | | public MetricsMiddleware(IDispatcher next) |
| | 0 | 22 | | : this(next, DispatchMetrics.Instance) |
| | 0 | 23 | | { |
| | 0 | 24 | | } |
| | | 25 | | |
| | | 26 | | /// <inheritdoc/> |
| | | 27 | | public async ValueTask<OutgoingResponse> DispatchAsync( |
| | | 28 | | IncomingRequest request, |
| | | 29 | | CancellationToken cancellationToken) |
| | 5 | 30 | | { |
| | 5 | 31 | | _dispatchMetrics.RequestStart(); |
| | | 32 | | try |
| | 5 | 33 | | { |
| | 5 | 34 | | OutgoingResponse response = await _next.DispatchAsync(request, cancellationToken).ConfigureAwait(false); |
| | | 35 | | // A non-OK status code means the dispatch produced a failure response. |
| | 2 | 36 | | if (response.StatusCode != StatusCode.Ok) |
| | 1 | 37 | | { |
| | 1 | 38 | | _dispatchMetrics.RequestFailure(); |
| | 1 | 39 | | } |
| | 2 | 40 | | return response; |
| | | 41 | | } |
| | 2 | 42 | | catch (OperationCanceledException exception) when (exception.CancellationToken == cancellationToken) |
| | 1 | 43 | | { |
| | 1 | 44 | | _dispatchMetrics.RequestCancel(); |
| | 1 | 45 | | throw; |
| | | 46 | | } |
| | 2 | 47 | | catch |
| | 2 | 48 | | { |
| | 2 | 49 | | _dispatchMetrics.RequestFailure(); |
| | 2 | 50 | | throw; |
| | | 51 | | } |
| | | 52 | | finally |
| | 5 | 53 | | { |
| | 5 | 54 | | _dispatchMetrics.RequestStop(); |
| | 5 | 55 | | } |
| | 2 | 56 | | } |
| | | 57 | | |
| | 5 | 58 | | internal MetricsMiddleware(IDispatcher next, DispatchMetrics dispatchMetrics) |
| | 5 | 59 | | { |
| | 5 | 60 | | _next = next; |
| | 5 | 61 | | _dispatchMetrics = dispatchMetrics; |
| | 5 | 62 | | } |
| | | 63 | | } |