From c32f15b00ff60f26d3c07e956d9617a2dcf55760 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:07:59 +0000 Subject: [PATCH] Target net10.0 and net11.0, fix HTTP and header bugs, run CI on every PR - Multi-target net10.0 and net11.0 (.NET 8 and 9 are out of support). Replace the deprecated Microsoft.AspNetCore.Http.Abstractions 2.2.0 package with a framework reference and update dependencies. - AddMetronome() now registers IHttpContextAccessor, so apps that don't use Identity no longer fail on the first tracked HTTP call. - HttpCallCountingHandler passes calls made outside a request through untracked instead of throwing NullReferenceException, and is registered as transient. - HttpCallCounter records calls under a lock, like DbCallCounter, so concurrent HTTP calls are all counted. - Fix the response header: drop the stray trailing text, format numbers with the invariant culture, and set rather than Add the header. - Use structured log message templates. - Move DbCallCountingInterceptor into the NimblePros.Metronome namespace and fix its nullability warnings. - Add integration tests for the middleware, HTTP handler and EF Core interceptor on a TestServer app without Identity. - CI: drop the paths filter so every PR to main is built, install the .NET 10 and 11 SDKs, test both frameworks and upload the package. - Bump to 0.5.0 and update the README. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014WE1LzSNPYAu6PDCk7wEEo --- .github/workflows/ci.yml | 30 ++- .github/workflows/release.yml | 17 +- README.md | 17 +- .../Metronome.Sample1.csproj | 14 +- .../CombinedCallLoggingMiddleware.cs | 36 ++-- .../DbCallCountingInterceptor.cs | 8 +- src/NimblePros.Metronome/HttpCallCounter.cs | 16 +- .../HttpCallCountingHandler.cs | 15 +- .../NimblePros.Metronome.csproj | 29 ++- .../ServiceRegistrationExtensions.cs | 12 +- .../MetronomeIntegrationTests.cs | 181 ++++++++++++++++++ .../NimblePros.Metronome.Tests.csproj | 21 +- 12 files changed, 331 insertions(+), 65 deletions(-) create mode 100644 tests/NimblePros.Metronome.Tests/MetronomeIntegrationTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5265fbc..b848a7d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,32 +1,42 @@ name: Build and Test -on: +on: workflow_dispatch: push: branches: - main - paths: - - 'src/**' - - 'tests/**' pull_request: branches: - main - paths: - - 'src/**' - - 'tests/**' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: build: runs-on: ubuntu-latest - + steps: - name: Checkout uses: actions/checkout@v4 - name: Setup dotnet uses: actions/setup-dotnet@v4 with: - dotnet-version: 9.x + dotnet-version: | + 10.x + 11.x - name: Build run: dotnet build ci.slnf --configuration Release - name: Test - run: dotnet test ci.slnf --configuration Release --no-build --no-restore --framework net9.0 + run: dotnet test ci.slnf --configuration Release --no-build + - name: Pack + run: dotnet pack src/NimblePros.Metronome/NimblePros.Metronome.csproj --configuration Release --no-build --output artifacts + - name: Upload package + uses: actions/upload-artifact@v4 + with: + name: nupkg + path: artifacts/*.nupkg diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5933704..8bb94e2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,25 +1,30 @@ name: Release to Nuget -on: +on: release: types: [published] +permissions: + contents: read + jobs: build: runs-on: ubuntu-latest - + steps: - name: Checkout uses: actions/checkout@v4 - name: Setup dotnet uses: actions/setup-dotnet@v4 with: - dotnet-version: 9.x + dotnet-version: | + 10.x + 11.x - name: Build run: dotnet build ci.slnf --configuration Release - name: Test - run: dotnet test ci.slnf --configuration Release --no-build --no-restore --framework net9.0 + run: dotnet test ci.slnf --configuration Release --no-build - name: Pack - run: dotnet pack ci.slnf --configuration Release --no-build --no-restore --output . + run: dotnet pack src/NimblePros.Metronome/NimblePros.Metronome.csproj --configuration Release --no-build --output artifacts - name: Push to NuGet - run: dotnet nuget push "*.nupkg" --api-key ${{secrets.NUGET_API_KEY}} --source https://api.nuget.org/v3/index.json + run: dotnet nuget push "artifacts/*.nupkg" --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate diff --git a/README.md b/README.md index 3644e02..b4e5430 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,12 @@ # Metronome by NimblePros +[![Build and Test](https://github.com/NimblePros/Metronome/actions/workflows/ci.yml/badge.svg)](https://github.com/NimblePros/Metronome/actions/workflows/ci.yml) +[![NuGet](https://img.shields.io/nuget/v/NimblePros.Metronome.svg)](https://www.nuget.org/packages/NimblePros.Metronome) + A simple tool for tracking Database and Http calls per ASP.NET Core request. +Supports .NET 10 and .NET 11. + ## Installation Install the NuGet package: @@ -14,7 +19,7 @@ dotnet add package NimblePros.Metronome ## Usage -Refer to the samples in the [samples](samples) directory. +Refer to the sample in the [sample](sample) directory. ### Wire up services @@ -42,6 +47,8 @@ builder.Services.AddDbContext((provider, options) => ); ``` +Use the `AddDbContext` overload that takes the service provider, as shown. `AddDbContextPool` and `AddDbContextFactory` aren't supported, because they build the options once and share them across requests. + ### Dapper Query Tracking Inject the scoped `DbCallCounter` and pass it as the first argument of a Dapper call. Calls are counted with any EF Core calls in the same request. @@ -60,6 +67,8 @@ Available with sync and async versions: `Query`, `QueryFirst`, `QueryFirst ### HttpClient Tracking +Only calls made during a request are tracked. Calls made elsewhere, such as from a hosted service, are sent as usual without being counted. + ```csharp // simple named client builder.Services.AddHttpClient("Foo") @@ -90,9 +99,11 @@ info: NimblePros.Metronome.CombinedCallLoggingMiddleware[0] ### HTTP Headers -In addition, the information is added to a response header (unless configured not to do so): +In addition, the information is added to a `NimblePros.Metronome` response header: -![image](https://github.com/user-attachments/assets/a2076ab9-0808-4515-976f-1e6a13951568) +``` +NimblePros.Metronome: DbCallCount=2;DbCallDuration=6.4678ms;HttpCallCount=1;HttpCallDuration=222.3137ms +``` ## Using the Information diff --git a/sample/Metronome.Sample1/Metronome.Sample1.csproj b/sample/Metronome.Sample1/Metronome.Sample1.csproj index 6e19d8c..99a4d92 100644 --- a/sample/Metronome.Sample1/Metronome.Sample1.csproj +++ b/sample/Metronome.Sample1/Metronome.Sample1.csproj @@ -1,20 +1,18 @@  - net9.0 + net10.0 enable enable - - - - - - - + + + + + diff --git a/src/NimblePros.Metronome/CombinedCallLoggingMiddleware.cs b/src/NimblePros.Metronome/CombinedCallLoggingMiddleware.cs index d5aae9f..85b0a99 100644 --- a/src/NimblePros.Metronome/CombinedCallLoggingMiddleware.cs +++ b/src/NimblePros.Metronome/CombinedCallLoggingMiddleware.cs @@ -1,9 +1,16 @@ -using Microsoft.AspNetCore.Http; +using System.Globalization; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace NimblePros.Metronome; + public class CombinedCallLoggingMiddleware { + /// + /// The name of the response header that holds the call counts and durations for the request. + /// + public const string HeaderName = "NimblePros.Metronome"; + private readonly RequestDelegate _next; public CombinedCallLoggingMiddleware(RequestDelegate next) @@ -19,22 +26,29 @@ public async Task InvokeAsync( { context.Response.OnStarting(() => { - string message = $"DbCallCount={dbCounter.CallCount};DbCallDuration={dbCounter.TotalTimeSpan.TotalMilliseconds}ms;HttpCallCount={httpCounter.CallCount};HttpCallDuration={httpCounter.TotalTimeSpan.TotalMilliseconds}ms HttpCallCount: {httpCounter.CallCount}"; - - context.Response.Headers.Add("NimblePros.Metronome", message); + context.Response.Headers[HeaderName] = FormatHeader(dbCounter, httpCounter); return Task.CompletedTask; }); + await _next(context); - bool verbose = false; // TODO: Read from configuration - bool addHeader = true; // TODO: Read from configuration - if (dbCounter.CallCount > 0 || verbose) + + if (dbCounter.CallCount > 0) { - logger.LogInformation($"Database calls: {dbCounter.CallCount}, Total time: {dbCounter.TotalTimeSpan.TotalMilliseconds} ms"); + logger.LogInformation("Database calls: {DbCallCount}, Total time: {DbCallDuration} ms", + dbCounter.CallCount, dbCounter.TotalTimeSpan.TotalMilliseconds); } - if (httpCounter.CallCount > 0 || verbose) + if (httpCounter.CallCount > 0) { - logger.LogInformation($"HTTP calls: {httpCounter.CallCount}, Total time: {httpCounter.TotalTimeSpan.TotalMilliseconds} ms"); + logger.LogInformation("HTTP calls: {HttpCallCount}, Total time: {HttpCallDuration} ms", + httpCounter.CallCount, httpCounter.TotalTimeSpan.TotalMilliseconds); } - } + + /// + /// Formats the header value, for example DbCallCount=2;DbCallDuration=6.4678ms;HttpCallCount=1;HttpCallDuration=222.3137ms. + /// Numbers always use the invariant culture so the value parses the same way everywhere. + /// + internal static string FormatHeader(DbCallCounter dbCounter, HttpCallCounter httpCounter) => + string.Create(CultureInfo.InvariantCulture, + $"DbCallCount={dbCounter.CallCount};DbCallDuration={dbCounter.TotalTimeSpan.TotalMilliseconds}ms;HttpCallCount={httpCounter.CallCount};HttpCallDuration={httpCounter.TotalTimeSpan.TotalMilliseconds}ms"); } diff --git a/src/NimblePros.Metronome/DbCallCountingInterceptor.cs b/src/NimblePros.Metronome/DbCallCountingInterceptor.cs index 96538c8..50e9766 100644 --- a/src/NimblePros.Metronome/DbCallCountingInterceptor.cs +++ b/src/NimblePros.Metronome/DbCallCountingInterceptor.cs @@ -1,7 +1,7 @@ using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics; -using NimblePros.Metronome; +namespace NimblePros.Metronome; public class DbCallCountingInterceptor : DbCommandInterceptor { @@ -50,10 +50,10 @@ public override async ValueTask NonQueryExecutedAsync( return await base.NonQueryExecutedAsync(command, eventData, result, cancellationToken); } - public override object ScalarExecuted( + public override object? ScalarExecuted( DbCommand command, CommandExecutedEventData eventData, - object result) + object? result) { _counter.RecordCall(eventData.Duration); return base.ScalarExecuted(command, eventData, result); @@ -62,7 +62,7 @@ public override object ScalarExecuted( public override async ValueTask ScalarExecutedAsync( DbCommand command, CommandExecutedEventData eventData, - object result, + object? result, CancellationToken cancellationToken = default) { _counter.RecordCall(eventData.Duration); diff --git a/src/NimblePros.Metronome/HttpCallCounter.cs b/src/NimblePros.Metronome/HttpCallCounter.cs index 505b3b2..2adb393 100644 --- a/src/NimblePros.Metronome/HttpCallCounter.cs +++ b/src/NimblePros.Metronome/HttpCallCounter.cs @@ -2,6 +2,18 @@ public class HttpCallCounter { - public int CallCount { get; internal set; } - public TimeSpan TotalTimeSpan { get; internal set; } + private readonly object _lock = new(); + + public int CallCount { get; private set; } + public TimeSpan TotalTimeSpan { get; private set; } + + // HTTP calls within a request often run concurrently (e.g. Task.WhenAll). + internal void RecordCall(TimeSpan duration) + { + lock (_lock) + { + CallCount++; + TotalTimeSpan += duration; + } + } } diff --git a/src/NimblePros.Metronome/HttpCallCountingHandler.cs b/src/NimblePros.Metronome/HttpCallCountingHandler.cs index 6be6b11..bc4d56a 100644 --- a/src/NimblePros.Metronome/HttpCallCountingHandler.cs +++ b/src/NimblePros.Metronome/HttpCallCountingHandler.cs @@ -16,15 +16,18 @@ public HttpCallCountingHandler(IHttpContextAccessor accessor) protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { - var counter = _accessor.HttpContext.RequestServices - .GetRequiredService(); + // Handlers are created by IHttpClientFactory outside the request scope, so the request's + // counter is found through the current HttpContext. Calls made outside a request (hosted + // services, startup code) have no counter and are passed through untracked. + var counter = _accessor.HttpContext?.RequestServices.GetService(); + if (counter is null) + { + return await base.SendAsync(request, cancellationToken); + } var stopwatch = Stopwatch.StartNew(); var response = await base.SendAsync(request, cancellationToken); - stopwatch.Stop(); - - counter.CallCount++; - counter.TotalTimeSpan += stopwatch.Elapsed; + counter.RecordCall(stopwatch.Elapsed); return response; } diff --git a/src/NimblePros.Metronome/NimblePros.Metronome.csproj b/src/NimblePros.Metronome/NimblePros.Metronome.csproj index 624cc7d..688ca50 100644 --- a/src/NimblePros.Metronome/NimblePros.Metronome.csproj +++ b/src/NimblePros.Metronome/NimblePros.Metronome.csproj @@ -1,7 +1,7 @@  - net8.0 + net10.0;net11.0 enable enable @@ -18,9 +18,14 @@ https://github.com/NimblePros/Metronome performance metrics timing logging diagnostics dataaccess - * Now it's on net8 + * Targets net10.0 and net11.0 + * Adds Dapper extensions that track db calls + * AddMetronome() registers IHttpContextAccessor, so apps without Identity work + * HTTP calls made outside a request are no longer an error, and concurrent calls are all counted + * Fixes the format of the NimblePros.Metronome response header + * Moves DbCallCountingInterceptor into the NimblePros.Metronome namespace - 0.4.1 + 0.5.0 NimblePros.Metronome icon.png true @@ -31,15 +36,21 @@ - - - - - + + + + + + + + + + + - + diff --git a/src/NimblePros.Metronome/ServiceRegistrationExtensions.cs b/src/NimblePros.Metronome/ServiceRegistrationExtensions.cs index dc904bc..292d497 100644 --- a/src/NimblePros.Metronome/ServiceRegistrationExtensions.cs +++ b/src/NimblePros.Metronome/ServiceRegistrationExtensions.cs @@ -7,10 +7,14 @@ public static class ServiceRegistrationExtensions { public static IServiceCollection AddMetronome(this IServiceCollection services) { + // The HTTP handler finds the request's counter through the current HttpContext. + services.AddHttpContextAccessor(); + services.AddScoped(); services.AddScoped(); - services.AddScoped(); + // IHttpClientFactory creates handlers in its own scope and caches them, so they are transient. + services.AddTransient(); services.AddScoped(); return services; @@ -21,6 +25,12 @@ public static IHttpClientBuilder AddMetronomeHandler(this IHttpClientBuilder bui return builder.AddHttpMessageHandler(); } + /// + /// Adds the interceptor that counts this request's database calls. Use it with + /// AddDbContext((provider, options) => ...), which builds the options in the request scope. + /// It isn't supported with AddDbContextPool or AddDbContextFactory, whose options are + /// built once and shared across requests. + /// public static DbContextOptionsBuilder AddMetronomeDbTracking(this DbContextOptionsBuilder builder, IServiceProvider provider) { return builder.AddInterceptors(provider.GetRequiredService()); diff --git a/tests/NimblePros.Metronome.Tests/MetronomeIntegrationTests.cs b/tests/NimblePros.Metronome.Tests/MetronomeIntegrationTests.cs new file mode 100644 index 0000000..6222fee --- /dev/null +++ b/tests/NimblePros.Metronome.Tests/MetronomeIntegrationTests.cs @@ -0,0 +1,181 @@ +using System.Globalization; +using System.Net; +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Testing; +using Xunit; + +namespace NimblePros.Metronome.Tests; + +/// +/// Runs a minimal API app (no Identity, so nothing else registers IHttpContextAccessor) on a TestServer. +/// +public sealed class MetronomeIntegrationTests : IAsyncLifetime +{ + private const string StubClient = "stub"; + + private readonly SqliteConnection _sqlite = new("Data Source=:memory:"); + private readonly FakeLogCollector _logs = new(); + private WebApplication _app = default!; + private HttpClient _client = default!; + + public async Task InitializeAsync() + { + await _sqlite.OpenAsync(); + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseTestServer(); + builder.Logging.ClearProviders(); + builder.Logging.AddProvider(new FakeLoggerProvider(_logs)); + + builder.Services.AddMetronome(); + builder.Services.AddDbContext((provider, options) => + options.UseSqlite(_sqlite).AddMetronomeDbTracking(provider)); + builder.Services.AddHttpClient(StubClient, c => c.BaseAddress = new Uri("http://stub.test/")) + .ConfigurePrimaryHttpMessageHandler(() => new StubHandler()) + .AddMetronomeHandler(); + + _app = builder.Build(); + _app.UseMetronomeLoggingMiddleware(); + + _app.MapGet("/none", () => "ok"); + _app.MapGet("/http/{count:int}", async (int count, IHttpClientFactory factory) => + { + var client = factory.CreateClient(StubClient); + await Task.WhenAll(Enumerable.Range(0, count).Select(_ => client.GetAsync("ping"))); + return "ok"; + }); + _app.MapGet("/db", async (TestDbContext db) => + { + db.Items.Add(new Item { Name = "one" }); + await db.SaveChangesAsync(); + return await db.Items.CountAsync(); + }); + + await _app.StartAsync(); + _client = _app.GetTestClient(); + + using var scope = _app.Services.CreateScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _app.DisposeAsync(); + await _sqlite.DisposeAsync(); + } + + private static Dictionary ParseHeader(HttpResponseMessage response) + { + var value = Assert.Single(response.Headers.GetValues(CombinedCallLoggingMiddleware.HeaderName)); + Assert.Matches(new Regex(@"^DbCallCount=\d+;DbCallDuration=[\d.E+-]+ms;HttpCallCount=\d+;HttpCallDuration=[\d.E+-]+ms$"), value); + return value.Split(';').Select(p => p.Split('=')).ToDictionary(p => p[0], p => p[1]); + } + + [Fact] + public async Task Request_WithNoCalls_AddsZeroCountHeaderAndLogsNothing() + { + var response = await _client.GetAsync("/none"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var header = ParseHeader(response); + Assert.Equal("0", header["DbCallCount"]); + Assert.Equal("0", header["HttpCallCount"]); + Assert.DoesNotContain(_logs.GetSnapshot(), r => r.Category == typeof(CombinedCallLoggingMiddleware).FullName); + } + + [Fact] + public async Task ConcurrentHttpCalls_AreAllCountedInHeaderAndLog() + { + var response = await _client.GetAsync("/http/50"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("50", ParseHeader(response)["HttpCallCount"]); + + var log = Assert.Single(_logs.GetSnapshot(), r => r.Message.StartsWith("HTTP calls")); + Assert.Equal(LogLevel.Information, log.Level); + Assert.Equal("50", log.GetStructuredStateValue("HttpCallCount")); + } + + [Fact] + public async Task EfCoreCalls_AreCountedInHeaderAndLog() + { + var response = await _client.GetAsync("/db"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var header = ParseHeader(response); + Assert.Equal("2", header["DbCallCount"]); // the INSERT and the COUNT + Assert.Equal("0", header["HttpCallCount"]); + + var log = Assert.Single(_logs.GetSnapshot(), r => r.Message.StartsWith("Database calls")); + Assert.Equal("2", log.GetStructuredStateValue("DbCallCount")); + } + + [Fact] + public async Task Counts_AreScopedToEachRequest() + { + await _client.GetAsync("/http/3"); + var response = await _client.GetAsync("/http/1"); + + Assert.Equal("1", ParseHeader(response)["HttpCallCount"]); + } + + [Fact] + public async Task HttpCall_OutsideARequest_IsSentWithoutTracking() + { + var factory = _app.Services.GetRequiredService(); + + var response = await factory.CreateClient(StubClient).GetAsync("ping"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public void FormatHeader_UsesInvariantCulture() + { + var original = CultureInfo.CurrentCulture; + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + try + { + var db = new DbCallCounter(); + db.RecordCall(TimeSpan.FromMilliseconds(1.5)); + var http = new HttpCallCounter(); + http.RecordCall(TimeSpan.FromMilliseconds(2.25)); + + Assert.Equal("DbCallCount=1;DbCallDuration=1.5ms;HttpCallCount=1;HttpCallDuration=2.25ms", + CombinedCallLoggingMiddleware.FormatHeader(db, http)); + } + finally + { + CultureInfo.CurrentCulture = original; + } + } + + private sealed class StubHandler : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + await Task.Yield(); + return new HttpResponseMessage(HttpStatusCode.OK); + } + } + + public sealed class Item + { + public int Id { get; set; } + public string Name { get; set; } = ""; + } + + public sealed class TestDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet Items => Set(); + } +} diff --git a/tests/NimblePros.Metronome.Tests/NimblePros.Metronome.Tests.csproj b/tests/NimblePros.Metronome.Tests/NimblePros.Metronome.Tests.csproj index e5b60e4..da33115 100644 --- a/tests/NimblePros.Metronome.Tests/NimblePros.Metronome.Tests.csproj +++ b/tests/NimblePros.Metronome.Tests/NimblePros.Metronome.Tests.csproj @@ -1,17 +1,28 @@ - net9.0 + net10.0;net11.0 enable enable false - - - - + + + + + + + + + + + + + + +