From 65885018acceec9094f4bb6cbcf3998b13764897 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:01:41 +0000 Subject: [PATCH 01/53] Bump packages with known vulnerabilities - EF Core 10.0.1 -> 10.0.15 (pulls a patched System.Security.Cryptography.Pkcs via SqlClient) - Npgsql EF provider 10.0.0 -> 10.0.3 - Testcontainers 4.9.0 -> 4.17.0 (patched SSH.NET) - Pin MySqlConnector 2.6.2 in the MySql and MariaDb providers (Pomelo 9.0.0 pulls vulnerable 2.4.0) - Example API aligned to the same EF Core and Npgsql versions Restore now succeeds with NuGet audit enabled. --- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 2 +- .../AsyncMonolith.MariaDb.csproj | 1 + AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj | 2 +- AsyncMonolith.MySql/AsyncMonolith.MySql.csproj | 1 + .../AsyncMonolith.PostgreSql.csproj | 2 +- .../AsyncMonolith.TestHelpers.csproj | 2 +- AsyncMonolith.Tests/AsyncMonolith.Tests.csproj | 18 +++++++++--------- AsyncMonolith/AsyncMonolith.csproj | 4 ++-- Example/Example.Api/Example.Api.csproj | 6 +++--- 9 files changed, 20 insertions(+), 18 deletions(-) diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index 89f2a1c..34cdbc1 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -31,7 +31,7 @@ - + diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index dfbde4e..af168ef 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -33,5 +33,6 @@ + diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index 3faaf9e..83aa9b3 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -31,6 +31,6 @@ - + \ No newline at end of file diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 5f234e8..034fed4 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -33,5 +33,6 @@ + diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index 270cf7e..f5e5a0a 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -31,7 +31,7 @@ - + diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index 1ce5a99..f7dae64 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -24,7 +24,7 @@ - + diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index 6805ee3..277eb0a 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -14,23 +14,23 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index 8523f9c..d73fcde 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -24,8 +24,8 @@ - - + + diff --git a/Example/Example.Api/Example.Api.csproj b/Example/Example.Api/Example.Api.csproj index 5a78f34..9b2e863 100644 --- a/Example/Example.Api/Example.Api.csproj +++ b/Example/Example.Api/Example.Api.csproj @@ -11,15 +11,15 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + From 71c09f944b91fc6be7788586a892ec8879b206e6 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:02:22 +0000 Subject: [PATCH 02/53] Tag container-backed tests as integration tests Tests that start databases through Testcontainers are tagged Category=Integration so the fast in-process tests can run on every change. The test workflow now runs fast tests on push and pull requests, and the integration tests only on manual dispatch. It also targets .NET 10 instead of .NET 8. --- .github/workflows/test.yml | 38 +++++++++++++++---- .../ConsumerMessageFetcherTests.cs | 1 + .../ConsumerMessageProcessorTests.cs | 1 + AsyncMonolith.Tests/ProducerServiceDbTests.cs | 1 + .../ScheduledMessageFetcherTests.cs | 1 + .../ScheduledMessageProcessorTests.cs | 1 + .../ScheduledMessageServiceTests.cs | 1 + docs/tests.md | 14 ++++++- 8 files changed, 50 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d83af9a..6698b4e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,19 +1,43 @@ name: Test on: + push: + branches: + - main + pull_request: workflow_dispatch: + inputs: + integration: + description: Also run the integration tests (Testcontainers, slow) + type: boolean + default: false jobs: - build: + fast: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3 - + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + + - name: Fast tests + run: dotnet test AsyncMonolith.Tests --filter "Category!=Integration" + + integration: + if: github.event_name == 'workflow_dispatch' && inputs.integration + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup .NET - uses: actions/setup-dotnet@v3 + uses: actions/setup-dotnet@v4 with: - dotnet-version: 8.0.x + dotnet-version: 10.0.x - - name: Test - run: dotnet test AsyncMonolith.Tests --verbosity normal \ No newline at end of file + - name: Integration tests + run: dotnet test AsyncMonolith.Tests --filter "Category=Integration" diff --git a/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs index 6668e5e..fe7d20f 100644 --- a/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs @@ -7,6 +7,7 @@ namespace AsyncMonolith.Tests; +[Trait("Category", "Integration")] public class ConsumerMessageFetcherTests : DbTestsBase { [Theory] diff --git a/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs b/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs index bb2f6fa..d6fe5cc 100644 --- a/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs +++ b/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs @@ -8,6 +8,7 @@ namespace AsyncMonolith.Tests; +[Trait("Category", "Integration")] public class ConsumerMessageProcessorTests : DbTestsBase { [Theory] diff --git a/AsyncMonolith.Tests/ProducerServiceDbTests.cs b/AsyncMonolith.Tests/ProducerServiceDbTests.cs index 1f89e9f..3965bc1 100644 --- a/AsyncMonolith.Tests/ProducerServiceDbTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceDbTests.cs @@ -9,6 +9,7 @@ namespace AsyncMonolith.Tests; +[Trait("Category", "Integration")] public class ProducerServiceDbTests : DbTestsBase { [Theory] diff --git a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs index f616047..82f5722 100644 --- a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs @@ -6,6 +6,7 @@ namespace AsyncMonolith.Tests; +[Trait("Category", "Integration")] public class ScheduledMessageFetcherTests : DbTestsBase { [Theory] diff --git a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs index 656aff7..aeebbcc 100644 --- a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs @@ -8,6 +8,7 @@ namespace AsyncMonolith.Tests; +[Trait("Category", "Integration")] public class ScheduledMessageProcessorTests : DbTestsBase { [Theory] diff --git a/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs b/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs index 2e0df6f..2f30063 100644 --- a/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs @@ -8,6 +8,7 @@ namespace AsyncMonolith.Tests; +[Trait("Category", "Integration")] public class ScheduledMessageServiceTests : DbTestsBase { [Theory] diff --git a/docs/tests.md b/docs/tests.md index 79ff149..50df2f7 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -1,6 +1,18 @@ ## AsyncMonolith.Tests -- Some of the test rely on TestContainers to run against real databases, make sure you've got docker installed +Tests are split into two groups: + +- **Fast tests** run in-process with no external services. Run them on every change: + + ```bash + dotnet test AsyncMonolith.Tests --filter "Category!=Integration" + ``` + +- **Integration tests** (`[Trait("Category", "Integration")]`) use Testcontainers to run against real databases, so they need Docker and are much slower. Run them before a release: + + ```bash + dotnet test AsyncMonolith.Tests --filter "Category=Integration" + ``` ## AsyncMonolith.TestHelpers From 17e45957e93eba1dfbb8677f71a7e254195be476 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:02:55 +0000 Subject: [PATCH 03/53] Manage package versions centrally Package versions move from each project into Directory.Packages.props. No versions change. --- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 4 +- .../AsyncMonolith.MariaDb.csproj | 6 +-- .../AsyncMonolith.MsSql.csproj | 4 +- .../AsyncMonolith.MySql.csproj | 6 +-- .../AsyncMonolith.PostgreSql.csproj | 4 +- .../AsyncMonolith.TestHelpers.csproj | 12 ++--- .../AsyncMonolith.Tests.csproj | 32 ++++++------- AsyncMonolith/AsyncMonolith.csproj | 6 +-- Directory.Packages.props | 47 +++++++++++++++++++ .../AsyncMonolith.Web.csproj | 2 +- Example/Example.Api/Example.Api.csproj | 16 +++---- .../Example.AppHost/Example.AppHost.csproj | 2 +- 12 files changed, 94 insertions(+), 47 deletions(-) create mode 100644 Directory.Packages.props diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index 34cdbc1..4e31b95 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -30,8 +30,8 @@ - - + + diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index af168ef..5af59ee 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -31,8 +31,8 @@ - - - + + + diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index 83aa9b3..a0eee8e 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -30,7 +30,7 @@ - - + + \ No newline at end of file diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 034fed4..9b5906e 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -31,8 +31,8 @@ - - - + + + diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index f5e5a0a..64ffcbf 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -30,8 +30,8 @@ - - + + diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index f7dae64..1d46c33 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -24,12 +24,12 @@ - - - - - - + + + + + + diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index 277eb0a..07ef0bc 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -10,28 +10,28 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - + + + + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index d73fcde..2a6836c 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -23,9 +23,9 @@ - - - + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..835563e --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,47 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj b/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj index 2f2a3c0..34b9be9 100644 --- a/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj +++ b/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj @@ -11,7 +11,7 @@ - + diff --git a/Example/Example.Api/Example.Api.csproj b/Example/Example.Api/Example.Api.csproj index 9b2e863..d9a6b32 100644 --- a/Example/Example.Api/Example.Api.csproj +++ b/Example/Example.Api/Example.Api.csproj @@ -10,17 +10,17 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - + + + + + + diff --git a/Example/Example.AppHost/Example.AppHost.csproj b/Example/Example.AppHost/Example.AppHost.csproj index 83f563f..73dd732 100644 --- a/Example/Example.AppHost/Example.AppHost.csproj +++ b/Example/Example.AppHost/Example.AppHost.csproj @@ -13,7 +13,7 @@ - + From 947419f9cabe6bc3b5fec8241ee692b20bd7008f Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:03:27 +0000 Subject: [PATCH 04/53] Reference the core project from providers and test helpers The providers referenced the published AsyncMonolith 10.0.0 package, so changes to the core in this repo were not built into them or exercised by their tests. A plain ProjectReference still packs as a NuGet dependency on AsyncMonolith (checked with dotnet pack), so consumers keep a single copy of the core assembly. TestHelpers also stops bundling AsyncMonolith.dll inside its package and depends on the AsyncMonolith package instead, matching the providers. --- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 2 +- AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj | 2 +- AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj | 2 +- AsyncMonolith.MySql/AsyncMonolith.MySql.csproj | 2 +- .../AsyncMonolith.PostgreSql.csproj | 2 +- .../AsyncMonolith.TestHelpers.csproj | 11 +---------- Directory.Packages.props | 1 - 7 files changed, 6 insertions(+), 16 deletions(-) diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index 4e31b95..a98bbc7 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -30,7 +30,7 @@ - + diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index 5af59ee..903f7a8 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -31,7 +31,7 @@ - + diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index a0eee8e..30a9d5a 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -30,7 +30,7 @@ - + \ No newline at end of file diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 9b5906e..13082d3 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -31,7 +31,7 @@ - + diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index 64ffcbf..b5eee41 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -30,7 +30,7 @@ - + diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index 1d46c33..32c76e2 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -20,7 +20,6 @@ logo.png True true - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage @@ -39,16 +38,8 @@ - - true - AsyncMonolith.dll - + - - - - - diff --git a/Directory.Packages.props b/Directory.Packages.props index 835563e..4fe9537 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,7 +5,6 @@ - From eef0149151b78f8d8da845d058c6833df36a4400 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:04:39 +0000 Subject: [PATCH 05/53] Update all dependencies and move tests to xunit v3 Every package moves to its latest release that supports net10.0: Cronos 0.13.0, TimeProvider.Testing 10.11.0, Aspire 13.6.5, OpenTelemetry 1.21.0, ASP.NET Core components 10.0.15 and the container tools 1.23.0. Tests move from xunit v2 to xunit.v3 4.0.3 and run on Microsoft.Testing.Platform, selected in a new global.json that also pins the .NET 10 SDK. The VSTest-only packages (Microsoft.NET.Test.Sdk, xunit.runner.visualstudio, coverlet.collector) are removed. Test commands use --filter-trait / --filter-not-trait. Breaking for AsyncMonolith.TestHelpers users: it now depends on xunit v3, and ConsumerTestBase.InitializeAsync/DisposeAsync return ValueTask. Held back: Pomelo has no EF Core 10 release (still 9.0.0), and MySqlConnector stays on 2.x because Pomelo 9 does not support 3.0. --- .github/workflows/test.yml | 4 +-- .../AsyncMonolith.TestHelpers.csproj | 6 ++--- AsyncMonolith.TestHelpers/ConsumerTestBase.cs | 8 +++--- .../AsyncMonolith.Tests.csproj | 12 ++------- .../Infra/TestDbContainerBase.cs | 7 +++--- Directory.Packages.props | 25 ++++++++----------- .../Example.AppHost/Example.AppHost.csproj | 2 +- docs/tests.md | 6 ++--- global.json | 10 ++++++++ 9 files changed, 40 insertions(+), 40 deletions(-) create mode 100644 global.json diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6698b4e..36a86af 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,7 +25,7 @@ jobs: dotnet-version: 10.0.x - name: Fast tests - run: dotnet test AsyncMonolith.Tests --filter "Category!=Integration" + run: dotnet test --project AsyncMonolith.Tests --filter-not-trait "Category=Integration" integration: if: github.event_name == 'workflow_dispatch' && inputs.integration @@ -40,4 +40,4 @@ jobs: dotnet-version: 10.0.x - name: Integration tests - run: dotnet test AsyncMonolith.Tests --filter "Category=Integration" + run: dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index 32c76e2..c54fc91 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -25,9 +25,9 @@ - - - + + + diff --git a/AsyncMonolith.TestHelpers/ConsumerTestBase.cs b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs index 943ec68..b2aa17a 100644 --- a/AsyncMonolith.TestHelpers/ConsumerTestBase.cs +++ b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs @@ -3,7 +3,6 @@ using System.Globalization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; -using Xunit.Abstractions; using Xunit; namespace AsyncMonolith.TestHelpers @@ -69,7 +68,7 @@ protected ConsumerTestBase(ITestOutputHelper testOutput, LogLevel logLevel = Log /// Initializes the test asynchronously. /// /// A task representing the asynchronous operation. - public virtual async Task InitializeAsync() + public virtual async ValueTask InitializeAsync() { _startTime = DateTime.Now; TestOutput.WriteLine($"[Lifecycle] Initialise {_startTime.ToString(CultureInfo.InvariantCulture)}"); @@ -80,10 +79,11 @@ public virtual async Task InitializeAsync() /// Disposes the test asynchronously. /// /// A task representing the asynchronous operation. - public virtual Task DisposeAsync() + public virtual ValueTask DisposeAsync() { TestOutput.WriteLine($"[Lifecycle] Dispose ({(DateTime.Now - _startTime).TotalSeconds}s)"); - return Task.CompletedTask; + GC.SuppressFinalize(this); + return ValueTask.CompletedTask; } /// diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index 07ef0bc..afbcafa 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -6,28 +6,20 @@ enable false true + Exe preview - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs index cbc09ed..0ed374d 100644 --- a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs +++ b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs @@ -9,14 +9,15 @@ public abstract class TestDbContainerBase : IAsyncLifetime protected string ConnectionString { get; set; } = default!; public DbType DbType => GetDbType(); - public async Task InitializeAsync() + public async ValueTask InitializeAsync() { await InitializeContainerAsync(); } - public async Task DisposeAsync() + public async ValueTask DisposeAsync() { - await DbContainer.DisposeAsync().AsTask(); + await DbContainer.DisposeAsync(); + GC.SuppressFinalize(this); } public abstract Task InitializeContainerAsync(); diff --git a/Directory.Packages.props b/Directory.Packages.props index 4fe9537..eb3870c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,7 +5,7 @@ - + @@ -16,14 +16,11 @@ - - - - - - - - + + + + + @@ -35,12 +32,12 @@ - + - + - - - + + + diff --git a/Example/Example.AppHost/Example.AppHost.csproj b/Example/Example.AppHost/Example.AppHost.csproj index 73dd732..bd384ba 100644 --- a/Example/Example.AppHost/Example.AppHost.csproj +++ b/Example/Example.AppHost/Example.AppHost.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/docs/tests.md b/docs/tests.md index 50df2f7..983c808 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -5,13 +5,13 @@ Tests are split into two groups: - **Fast tests** run in-process with no external services. Run them on every change: ```bash - dotnet test AsyncMonolith.Tests --filter "Category!=Integration" + dotnet test --project AsyncMonolith.Tests --filter-not-trait "Category=Integration" ``` - **Integration tests** (`[Trait("Category", "Integration")]`) use Testcontainers to run against real databases, so they need Docker and are much slower. Run them before a release: ```bash - dotnet test AsyncMonolith.Tests --filter "Category=Integration" + dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" ``` @@ -19,7 +19,7 @@ Tests are split into two groups: [![NuGet](https://img.shields.io/nuget/v/AsyncMonolith.TestHelpers)](https://www.nuget.org/packages/AsyncMonolith.TestHelpers) -Install the TestHelpers package to help with unit / integration tests. +Install the TestHelpers package to help with unit / integration tests. It targets xunit v3 (`xunit.v3`). ### FakeIdGenerator diff --git a/global.json b/global.json new file mode 100644 index 0000000..df32a2e --- /dev/null +++ b/global.json @@ -0,0 +1,10 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} From 73b391b601a2a9870a9752d613f71074e75cc282 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:08:09 +0000 Subject: [PATCH 06/53] Fix analyzer findings in the core library and providers - Throw InvalidOperationException instead of System.Exception (CA2201) - Use source-generated LoggerMessage methods for processor logging (CA1848, CA1727) - Expose ConsumerRegistry lookups as get-only properties instead of public fields (CA1051) - Rename IScheduledMessageFetcher.Fetch's 'set' parameter (CA1716) - Build provider SQL with the invariant culture (CA1305) - Minor: static StartActivity, no explicit default initialiser --- AsyncMonolith.Ef/EfScheduledMessageFetcher.cs | 6 ++--- .../MariaDbProducerService.cs | 5 ++-- .../MariaDbScheduledMessageFetcher.cs | 6 ++--- AsyncMonolith.MsSql/MsSqlProducerService.cs | 5 ++-- .../MsSqlScheduledMessageFetcher.cs | 6 ++--- AsyncMonolith.MySql/MySqlProducerService.cs | 5 ++-- .../MySqlScheduledMessageFetcher.cs | 6 ++--- .../PostgreSqlProducerService.cs | 5 ++-- .../PostgreSqlScheduledMessageFetcher.cs | 6 ++--- AsyncMonolith/Consumers/BaseConsumer.cs | 2 +- .../Consumers/ConsumerMessageProcessor.cs | 12 ++++----- AsyncMonolith/Consumers/ConsumerRegistry.cs | 16 ++++++------ .../Scheduling/IScheduledMessageFetcher.cs | 4 +-- .../Scheduling/ScheduledMessageProcessor.cs | 4 +-- AsyncMonolith/Utilities/AsyncMonolithLog.cs | 25 +++++++++++++++++++ AsyncMonolith/Utilities/StartupExtensions.cs | 4 +-- 16 files changed, 73 insertions(+), 44 deletions(-) create mode 100644 AsyncMonolith/Utilities/AsyncMonolithLog.cs diff --git a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs index 43b46c5..494c8c9 100644 --- a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs @@ -24,14 +24,14 @@ public EfScheduledMessageFetcher(IOptions options) /// /// Fetches scheduled messages from the database. /// - /// The DbSet of scheduled messages. + /// The DbSet of scheduled messages. /// The current time. /// The cancellation token. /// A task representing the asynchronous operation, containing the list of fetched scheduled messages. - public Task> Fetch(DbSet set, long currentTime, + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return set.Where(m => m.AvailableAfter <= currentTime) + return scheduledMessageSet.Where(m => m.AvailableAfter <= currentTime) .OrderBy(m => m.AvailableAfter) .Take(_options.Value.ProcessorBatchSize) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.MariaDb/MariaDbProducerService.cs b/AsyncMonolith.MariaDb/MariaDbProducerService.cs index a241a21..4f98c1c 100644 --- a/AsyncMonolith.MariaDb/MariaDbProducerService.cs +++ b/AsyncMonolith.MariaDb/MariaDbProducerService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Text; using System.Text.Json; using AsyncMonolith.Consumers; @@ -79,7 +80,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); parameters.Add(new MySqlParameter($"@id_{index}", _idGenerator.GenerateId())); @@ -140,7 +141,7 @@ public async Task ProduceList(List messages, long? availableAfter = null sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); parameters.Add(new MySqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); diff --git a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs index df8de3d..769191c 100644 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs @@ -32,14 +32,14 @@ public MariaDbScheduledMessageFetcher(IOptions options) /// /// Fetches scheduled messages from the database. /// - /// The of scheduled messages. + /// The of scheduled messages. /// The current time. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains a list of fetched scheduled messages. - public Task> Fetch(DbSet set, long currentTime, + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return set + return scheduledMessageSet .FromSqlRaw(MariaDb, new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.MsSql/MsSqlProducerService.cs b/AsyncMonolith.MsSql/MsSqlProducerService.cs index 76c7b2b..507ec33 100644 --- a/AsyncMonolith.MsSql/MsSqlProducerService.cs +++ b/AsyncMonolith.MsSql/MsSqlProducerService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Text; using System.Text.Json; using AsyncMonolith.Consumers; @@ -80,7 +81,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); parameters.Add(new SqlParameter($"@id_{index}", _idGenerator.GenerateId())); @@ -144,7 +145,7 @@ public async Task ProduceList(List messages, long? availableAfter = null sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); parameters.Add(new SqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); diff --git a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs index da06794..24be158 100644 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs @@ -30,14 +30,14 @@ public MsSqlScheduledMessageFetcher(IOptions options) /// /// Fetches scheduled messages from the database. /// - /// The DbSet of scheduled messages. + /// The DbSet of scheduled messages. /// The current time. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains a list of scheduled messages. - public Task> Fetch(DbSet set, long currentTime, + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return set + return scheduledMessageSet .FromSqlRaw(MsSql, new SqlParameter("@currentTime", currentTime), new SqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.MySql/MySqlProducerService.cs b/AsyncMonolith.MySql/MySqlProducerService.cs index aa92fa3..3c3d549 100644 --- a/AsyncMonolith.MySql/MySqlProducerService.cs +++ b/AsyncMonolith.MySql/MySqlProducerService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Text; using System.Text.Json; using AsyncMonolith.Consumers; @@ -80,7 +81,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); parameters.Add(new MySqlParameter($"@id_{index}", _idGenerator.GenerateId())); @@ -141,7 +142,7 @@ public async Task ProduceList(List messages, long? availableAfter = null sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); parameters.Add(new MySqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); diff --git a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs index 7b1969f..8e88283 100644 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs @@ -32,14 +32,14 @@ public MySqlScheduledMessageFetcher(IOptions options) /// /// Fetches scheduled messages from the database. /// - /// The of scheduled messages. + /// The of scheduled messages. /// The current time. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains a list of fetched scheduled messages. - public Task> Fetch(DbSet set, long currentTime, + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return set + return scheduledMessageSet .FromSqlRaw(MySql, new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs b/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs index fdf5dd1..489799d 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Text; using System.Text.Json; using AsyncMonolith.Consumers; @@ -81,7 +82,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); parameters.Add(new NpgsqlParameter($"@id_{index}", _idGenerator.GenerateId())); @@ -143,7 +144,7 @@ public async Task ProduceList(List messages, long? availableAfter = null sqlBuilder.Append(", "); } - sqlBuilder.Append( + sqlBuilder.Append(CultureInfo.InvariantCulture, $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); parameters.Add(new NpgsqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); diff --git a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs index db4b077..945a248 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs @@ -32,14 +32,14 @@ public PostgreSqlScheduledMessageFetcher(IOptions options /// /// Fetches scheduled messages from the database. /// - /// The of scheduled messages. + /// The of scheduled messages. /// The current time. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains a list of fetched scheduled messages. - public Task> Fetch(DbSet set, long currentTime, + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return set + return scheduledMessageSet .FromSqlRaw(PgSql, new NpgsqlParameter("@currentTime", currentTime), new NpgsqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith/Consumers/BaseConsumer.cs b/AsyncMonolith/Consumers/BaseConsumer.cs index e7eea4f..46409a5 100644 --- a/AsyncMonolith/Consumers/BaseConsumer.cs +++ b/AsyncMonolith/Consumers/BaseConsumer.cs @@ -16,7 +16,7 @@ public abstract class BaseConsumer : IConsumer where T : IConsumerPayload /// A task representing the asynchronous operation. public async Task Consume(ConsumerMessage message, CancellationToken cancellationToken = default) { - var payload = JsonSerializer.Deserialize(message.Payload) ?? throw new Exception( + var payload = JsonSerializer.Deserialize(message.Payload) ?? throw new InvalidOperationException( $"Consumer: '{message.ConsumerType}' failed to deserialize payload: '{message.PayloadType}'"); await Consume(payload!, cancellationToken); diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 04c6ea4..4fafcb1 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -21,7 +21,7 @@ public sealed class ConsumerMessageProcessor : BackgroundService where T : Db private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; - private int _railId = 0; + private int _railId; /// /// Initializes a new instance of the class. /// @@ -75,7 +75,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } catch (Exception ex) { - _logger.LogError(ex, "Error processing consumer message batch."); + _logger.ConsumerBatchFailed(ex); } if (delay >= 10) @@ -187,7 +187,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) return processedMessageCount; } - private Activity? StartActivity(ConsumerMessage message) + private static Activity? StartActivity(ConsumerMessage message) { if (string.IsNullOrEmpty(message.TraceId) || string.IsNullOrEmpty(message.SpanId)) { @@ -237,14 +237,14 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) if (scope.ServiceProvider.GetRequiredService(consumerType) is not IConsumer consumer) { - throw new Exception($"Couldn't resolve consumer service of type: '{message.ConsumerType}'"); + throw new InvalidOperationException($"Couldn't resolve consumer service of type: '{message.ConsumerType}'"); } // Execute the consumer await consumer.Consume(message, timeoutCancellationToken.Token); activity?.SetStatus(ActivityStatusCode.Ok); - _logger.LogInformation("Successfully processed message for consumer: '{id}'", message.ConsumerType); + _logger.ConsumerMessageProcessed(message.ConsumerType); return (message, true); } catch (Exception ex) @@ -252,7 +252,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) activity?.SetStatus(ActivityStatusCode.Error, ex.Message); activity?.AddTag("exception.type", nameof(ex)); activity?.AddTag("exception.message", ex.Message); - _logger.LogError(ex, "Failed to consume message on attempt {attempt}.", message.Attempts); + _logger.ConsumerMessageFailed(ex, message.Attempts); } return (message, false); diff --git a/AsyncMonolith/Consumers/ConsumerRegistry.cs b/AsyncMonolith/Consumers/ConsumerRegistry.cs index 3c03840..5820514 100644 --- a/AsyncMonolith/Consumers/ConsumerRegistry.cs +++ b/AsyncMonolith/Consumers/ConsumerRegistry.cs @@ -15,32 +15,32 @@ public sealed class ConsumerRegistry /// /// Gets the dictionary that maps consumer names to their associated time out. /// - public readonly IReadOnlyDictionary ConsumerTimeoutDictionary; + public IReadOnlyDictionary ConsumerTimeoutDictionary { get; } /// /// Gets the dictionary that maps consumer names to their associated number of attempts. /// - public readonly IReadOnlyDictionary ConsumerAttemptsDictionary; + public IReadOnlyDictionary ConsumerAttemptsDictionary { get; } /// /// Gets the dictionary that maps consumer types to their associated rail id. /// - public readonly IReadOnlyDictionary ConsumerRailIdDictionary; + public IReadOnlyDictionary ConsumerRailIdDictionary { get; } /// /// Gets the dictionary that maps consumer names to their associated app instance execution mode. /// - public readonly IReadOnlyDictionary ConsumerExecutionModeDictionary; + public IReadOnlyDictionary ConsumerExecutionModeDictionary { get; } /// /// Gets the dictionary that maps consumer names to their associated types. /// - public readonly IReadOnlyDictionary ConsumerTypeDictionary; + public IReadOnlyDictionary ConsumerTypeDictionary { get; } /// /// Gets the dictionary that maps payload types to the list of consumer names that can handle them. /// - public readonly IReadOnlyDictionary> PayloadConsumerDictionary; + public IReadOnlyDictionary> PayloadConsumerDictionary { get; } /// /// Initializes a new instance of the class. @@ -82,7 +82,7 @@ public IReadOnlyList ResolvePayloadConsumerTypes(string payloadType) { if (!PayloadConsumerDictionary.TryGetValue(payloadType, out var names)) { - throw new Exception($"Failed to resolve consumers for payload: {payloadType}"); + throw new InvalidOperationException($"Failed to resolve consumers for payload: {payloadType}"); } return names; @@ -98,7 +98,7 @@ public Type ResolveConsumerType(ConsumerMessage consumer) { if (!ConsumerTypeDictionary.TryGetValue(consumer.ConsumerType, out var type)) { - throw new Exception($"Couldn't resolve consumer type: '{consumer.ConsumerType}'"); + throw new InvalidOperationException($"Couldn't resolve consumer type: '{consumer.ConsumerType}'"); } return type; diff --git a/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs b/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs index 3528b50..4bf3f07 100644 --- a/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs +++ b/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs @@ -10,10 +10,10 @@ public interface IScheduledMessageFetcher /// /// Fetches scheduled messages. /// - /// The DbSet of scheduled messages. + /// The DbSet of scheduled messages. /// The current time. /// The cancellation token. /// A list of fetched scheduled messages. - public Task> Fetch(DbSet set, long currentTime, + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index f264c07..0d12a0b 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -60,7 +60,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } catch (Exception ex) { - _logger.LogError(ex, "Error scheduling next message"); + _logger.ScheduleBatchFailed(ex); } if (delay >= 10) @@ -110,7 +110,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa await dbContext.SaveChangesAsync(cancellationToken); await dbContextTransaction.CommitAsync(cancellationToken); activity?.SetStatus(ActivityStatusCode.Ok); - _logger.LogInformation("Successfully scheduled message"); + _logger.ScheduledMessagesProduced(); } catch (Exception) { diff --git a/AsyncMonolith/Utilities/AsyncMonolithLog.cs b/AsyncMonolith/Utilities/AsyncMonolithLog.cs new file mode 100644 index 0000000..6e65ae4 --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithLog.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Logging; + +namespace AsyncMonolith.Utilities; + +/// +/// Source-generated log messages for the background processors. +/// +internal static partial class AsyncMonolithLog +{ + [LoggerMessage(EventId = 1, Level = LogLevel.Error, Message = "Error processing consumer message batch.")] + public static partial void ConsumerBatchFailed(this ILogger logger, Exception exception); + + [LoggerMessage(EventId = 2, Level = LogLevel.Information, + Message = "Successfully processed message for consumer: '{ConsumerType}'")] + public static partial void ConsumerMessageProcessed(this ILogger logger, string consumerType); + + [LoggerMessage(EventId = 3, Level = LogLevel.Error, Message = "Failed to consume message on attempt {Attempt}.")] + public static partial void ConsumerMessageFailed(this ILogger logger, Exception exception, int attempt); + + [LoggerMessage(EventId = 4, Level = LogLevel.Error, Message = "Error scheduling next message")] + public static partial void ScheduleBatchFailed(this ILogger logger, Exception exception); + + [LoggerMessage(EventId = 5, Level = LogLevel.Information, Message = "Successfully scheduled message")] + public static partial void ScheduledMessagesProduced(this ILogger logger); +} diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 0f4c1de..bb3b45d 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -185,7 +185,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( if (!consumerServiceDictionary.TryAdd(consumerType.Name, consumerType)) { - throw new Exception($"Consumer: '{consumerType.Name}' already defined."); + throw new InvalidOperationException($"Consumer: '{consumerType.Name}' already defined."); } if (!payloadConsumerDictionary.TryGetValue(payloadType.Name, out var payloadConsumers)) @@ -202,7 +202,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( { if (!payloadConsumerDictionary.ContainsKey(consumerPayload)) { - throw new Exception($"No consumers exist for payload: '{consumerPayload}'"); + throw new InvalidOperationException($"No consumers exist for payload: '{consumerPayload}'"); } } From 2c43c989b3a51de4818cda83908802e8a515e010 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:08:09 +0000 Subject: [PATCH 07/53] Fix analyzer findings in the test helpers Generic payload parameters are renamed from V to TPayload (CA1715), and the fake clock parses its start time with the invariant culture. --- .../ConsumerMessageTestHelpers.cs | 32 +++++++++---------- AsyncMonolith.TestHelpers/ConsumerTestBase.cs | 8 ++--- .../TestConsumerMessageProcessor.cs | 18 +++++------ 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs index b47f983..7487c96 100644 --- a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs @@ -31,14 +31,14 @@ public static async Task> GetConsumerMessages(this DbCo /// Retrieves a list of consumer messages based on the specified consumer type and payload type. /// /// The type of the consumer. - /// The type of the payload. + /// The type of the payload. /// The database context. /// A list of consumer messages. - public static async Task> GetConsumerMessages(this DbContext dbContext) - where T : BaseConsumer where V : IConsumerPayload + public static async Task> GetConsumerMessages(this DbContext dbContext) + where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + var payloadType = typeof(TPayload); return await dbContext.Set() .Where(m => m.ConsumerType == consumerType.Name && @@ -50,15 +50,15 @@ public static async Task> GetConsumerMessages(this D /// Retrieves a list of consumer messages based on the specified consumer type, payload type, and payload. /// /// The type of the consumer. - /// The type of the payload. + /// The type of the payload. /// The database context. /// The payload. /// A list of consumer messages. - public static async Task> GetConsumerMessages(this DbContext dbContext, V payload) - where T : BaseConsumer where V : IConsumerPayload + public static async Task> GetConsumerMessages(this DbContext dbContext, TPayload payload) + where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + var payloadType = typeof(TPayload); var serializedPayload = JsonSerializer.Serialize(payload); return await dbContext.Set() .Where(m => @@ -72,15 +72,15 @@ public static async Task> GetConsumerMessages(this D /// Asserts that there is a single consumer message based on the specified consumer type, payload type, and payload. /// /// The type of the consumer. - /// The type of the payload. + /// The type of the payload. /// The database context. /// The payload. /// The single consumer message. - public static async Task AssertSingleConsumerMessage(this DbContext dbContext, V payload) - where T : BaseConsumer where V : IConsumerPayload + public static async Task AssertSingleConsumerMessage(this DbContext dbContext, TPayload payload) + where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + var payloadType = typeof(TPayload); var serializedPayload = JsonSerializer.Serialize(payload); var messages = await dbContext.Set() .Where(m => @@ -117,16 +117,16 @@ public static async Task AssertSingleScheduledMessage(this /// Asserts that there is a single consumer message based on the specified consumer type, payload type, payload, and ID. /// /// The type of the consumer. - /// The type of the payload. + /// The type of the payload. /// The database context. /// The payload. /// The ID. /// The single consumer message. - public static async Task AssertSingleConsumerMessageById(this DbContext dbContext, V payload, - string id) where T : BaseConsumer where V : IConsumerPayload + public static async Task AssertSingleConsumerMessageById(this DbContext dbContext, TPayload payload, + string id) where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + var payloadType = typeof(TPayload); var serializedPayload = JsonSerializer.Serialize(payload); var messages = await dbContext.Set() .Where(m => diff --git a/AsyncMonolith.TestHelpers/ConsumerTestBase.cs b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs index b2aa17a..e07bb73 100644 --- a/AsyncMonolith.TestHelpers/ConsumerTestBase.cs +++ b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs @@ -36,7 +36,7 @@ private async Task Setup() b.AddXUnit(TestOutput); }); - FakeTime = new FakeTimeProvider(DateTimeOffset.Parse("2020-08-31T10:00:00.0000000Z")); + FakeTime = new FakeTimeProvider(DateTimeOffset.Parse("2020-08-31T10:00:00.0000000Z", CultureInfo.InvariantCulture)); services.AddSingleton(FakeTime); await Setup(services); @@ -90,14 +90,14 @@ public virtual ValueTask DisposeAsync() /// Processes the consumer message. /// /// The type of the consumer. - /// The type of the payload. + /// The type of the payload. /// The payload. /// The cancellation token. /// A task representing the asynchronous operation. - protected async Task Process(V payload, CancellationToken cancellationToken = default) where T : BaseConsumer where V : IConsumerPayload + protected async Task Process(TPayload payload, CancellationToken cancellationToken = default) where T : BaseConsumer where TPayload : IConsumerPayload { using var scope = Services.CreateScope(); - await TestConsumerMessageProcessor.Process(scope, payload, cancellationToken); + await TestConsumerMessageProcessor.Process(scope, payload, cancellationToken); } } } diff --git a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs index 7aa84b6..9d50c96 100644 --- a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs +++ b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs @@ -56,15 +56,15 @@ public static class TestConsumerMessageProcessor } /// - /// Processes the next consumer message of type T and V. + /// Processes the next consumer message of type T and TPayload. /// /// The type of DbContext. - /// The type of IConsumer. + /// The type of IConsumer. /// The service scope. /// The cancellation token. /// The processed consumer message, or null if no message is available. - public static async Task ProcessNext(IServiceScope scope, - CancellationToken cancellationToken = default) where T : DbContext where V : IConsumer + public static async Task ProcessNext(IServiceScope scope, + CancellationToken cancellationToken = default) where T : DbContext where TPayload : IConsumer { var dbContext = scope.ServiceProvider.GetRequiredService(); var consumerMessageSet = dbContext.Set(); @@ -100,15 +100,15 @@ public static class TestConsumerMessageProcessor } /// - /// Processes the consumer message of type T and V with the given payload. + /// Processes the consumer message of type T and TPayload with the given payload. /// /// The type of BaseConsumer. - /// The type of IConsumerPayload. + /// The type of IConsumerPayload. /// The service scope. /// The payload for the consumer message. /// The cancellation token. - public static async Task Process(IServiceScope scope, V payload, - CancellationToken cancellationToken = default) where T : BaseConsumer where V : IConsumerPayload + public static async Task Process(IServiceScope scope, TPayload payload, + CancellationToken cancellationToken = default) where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); @@ -130,7 +130,7 @@ await consumer.Consume(new ConsumerMessage Id = string.Empty, InsertId = string.Empty, Payload = JsonSerializer.Serialize(payload), - PayloadType = typeof(V).Name, + PayloadType = typeof(TPayload).Name, TraceId = null, SpanId = null, RailId = 0 From c2ebeae11726ba6514062204326601f296afb56b Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:08:09 +0000 Subject: [PATCH 08/53] Fix analyzer findings in the tests - Pass TestContext.Current.CancellationToken to cancellable calls (xUnit1051) - Use Assert.Single with a predicate (xUnit2031) - Pin Testcontainers images instead of the obsolete default constructors - Properties instead of visible fields, static helpers, specific exceptions --- .../ConsumerMessageFetcherTests.cs | 8 +-- .../ConsumerMessageProcessorTests.cs | 50 +++++++++---------- AsyncMonolith.Tests/ConsumerRegistryTests.cs | 6 +-- AsyncMonolith.Tests/Infra/DbTestsBase.cs | 6 +-- .../Infra/EfTestDbContainer.cs | 2 +- .../Infra/ExceptionConsumer.cs | 2 +- .../Infra/ExceptionConsumer2Attempts.cs | 2 +- .../Infra/MariaDbTestDbContainer.cs | 2 +- .../Infra/MsSqlTestDbContainer.cs | 2 +- .../Infra/MySqlTestDbContainer.cs | 2 +- .../Infra/PostgreSqlTestDbContainer.cs | 2 +- .../Infra/TestServiceHelpers.cs | 2 +- AsyncMonolith.Tests/ProducerServiceDbTests.cs | 22 ++++---- AsyncMonolith.Tests/ProducerServiceTests.cs | 22 ++++---- .../ScheduledMessageFetcherTests.cs | 2 +- .../ScheduledMessageProcessorTests.cs | 6 +-- .../ScheduledMessageServiceTests.cs | 14 +++--- 17 files changed, 76 insertions(+), 76 deletions(-) diff --git a/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs index fe7d20f..f928fbe 100644 --- a/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs @@ -34,8 +34,8 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) }); } - await producer.ProduceList(messages); - await dbContext.SaveChangesAsync(); + await producer.ProduceList(messages, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // When var dbMessages = await fetcher.Fetch(dbContext.ConsumerMessages, FakeTime.GetUtcNow().ToUnixTimeSeconds(), 0, @@ -65,8 +65,8 @@ public async Task Fetch_Returns_Messages_Partitioned_By_Rail(DbType dbType) var producer = serviceProvider.GetRequiredService(); var fetcher = serviceProvider.GetRequiredService(); - await producer.Produce(new RailConsumerMessage() { }); - await dbContext.SaveChangesAsync(); + await producer.Produce(new RailConsumerMessage() { }, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // When var rail0Messages = await fetcher.Fetch(dbContext.ConsumerMessages, FakeTime.GetUtcNow().ToUnixTimeSeconds(), 0, diff --git a/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs b/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs index d6fe5cc..0bf8bab 100644 --- a/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs +++ b/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs @@ -28,9 +28,9 @@ public async Task ConsumerMessageProcessor_Invokes_Consumer(TestDbContainerBase await producer.Produce(new SingleConsumerMessage { Name = "test-name" - }); + }, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -65,9 +65,9 @@ public async Task ConsumerMessageProcessor_Returns_0_If_No_Available_Messages(Te await producer.Produce(new SingleConsumerMessage { Name = "test-name" - }, FakeTime.GetUtcNow().ToUnixTimeSeconds() + 100); + }, FakeTime.GetUtcNow().ToUnixTimeSeconds() + 100, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } var processor = serviceProvider.GetRequiredService>(); @@ -104,9 +104,9 @@ public async Task ConsumerMessageProcessor_Increments_Message_Attempts(TestDbCon var dbContext = scope.ServiceProvider.GetRequiredService(); var producer = scope.ServiceProvider.GetRequiredService(); - await producer.Produce(consumerMessage); + await producer.Produce(consumerMessage, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -148,9 +148,9 @@ public async Task ConsumerMessageProcessor_Increments_Message_Attempts_OnTimeout var dbContext = scope.ServiceProvider.GetRequiredService(); var producer = scope.ServiceProvider.GetRequiredService(); - await producer.Produce(consumerMessage); + await producer.Produce(consumerMessage, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -192,9 +192,9 @@ public async Task ConsumerMessageProcessor_Increments_Message_AvailableAfter(Tes var dbContext = scope.ServiceProvider.GetRequiredService(); var producer = scope.ServiceProvider.GetRequiredService(); - await producer.Produce(consumerMessage); + await producer.Produce(consumerMessage, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -236,12 +236,12 @@ public async Task ConsumerMessageProcessor_Moves_Message_To_PoisonedMessages(Tes await producer.Produce(new ExceptionConsumerMessage { Name = "test-name" - }); + }, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); - message = await dbContext.ConsumerMessages.SingleAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); + message = await dbContext.ConsumerMessages.SingleAsync(TestContext.Current.CancellationToken); message.Attempts = 10; - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -253,9 +253,9 @@ await producer.Produce(new ExceptionConsumerMessage using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); - var consumerMessageExists = await dbContext.ConsumerMessages.AnyAsync(); + var consumerMessageExists = await dbContext.ConsumerMessages.AnyAsync(TestContext.Current.CancellationToken); consumerMessageExists.ShouldBeFalse(); - var poisonedMessage = await dbContext.PoisonedMessages.SingleAsync(); + var poisonedMessage = await dbContext.PoisonedMessages.SingleAsync(TestContext.Current.CancellationToken); poisonedMessage.Id.ShouldBe(message.Id); poisonedMessage.AvailableAfter.ShouldBe(message.AvailableAfter); poisonedMessage.ConsumerType.ShouldBe(message.ConsumerType); @@ -289,12 +289,12 @@ public async Task ConsumerMessageProcessor_Moves_Message_To_PoisonedMessages_OnC await producer.Produce(new ExceptionConsumer2AttemptsMessage { Name = "test-name" - }); + }, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); - message = await dbContext.ConsumerMessages.SingleAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); + message = await dbContext.ConsumerMessages.SingleAsync(TestContext.Current.CancellationToken); message.Attempts = 1; - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -306,9 +306,9 @@ await producer.Produce(new ExceptionConsumer2AttemptsMessage using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); - var consumerMessageExists = await dbContext.ConsumerMessages.AnyAsync(); + var consumerMessageExists = await dbContext.ConsumerMessages.AnyAsync(TestContext.Current.CancellationToken); consumerMessageExists.ShouldBeFalse(); - var poisonedMessage = await dbContext.PoisonedMessages.SingleAsync(); + var poisonedMessage = await dbContext.PoisonedMessages.SingleAsync(TestContext.Current.CancellationToken); poisonedMessage.Id.ShouldBe(message.Id); poisonedMessage.AvailableAfter.ShouldBe(message.AvailableAfter); poisonedMessage.ConsumerType.ShouldBe(message.ConsumerType); @@ -341,9 +341,9 @@ public async Task ConsumerMessageProcessor_Removes_Consumed_Messages(TestDbConta await producer.Produce(new SingleConsumerMessage { Name = "test-name" - }); + }, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -357,7 +357,7 @@ await producer.Produce(new SingleConsumerMessage using (var scope = serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); - var remaining = await dbContext.ConsumerMessages.CountAsync(); + var remaining = await dbContext.ConsumerMessages.CountAsync(TestContext.Current.CancellationToken); remaining.ShouldBe(0); } } diff --git a/AsyncMonolith.Tests/ConsumerRegistryTests.cs b/AsyncMonolith.Tests/ConsumerRegistryTests.cs index 3f0f9a9..32f6b74 100644 --- a/AsyncMonolith.Tests/ConsumerRegistryTests.cs +++ b/AsyncMonolith.Tests/ConsumerRegistryTests.cs @@ -8,7 +8,7 @@ namespace AsyncMonolith.Tests; public class ConsumerRegistryTests { - private ServiceProvider Setup() + private static ServiceProvider Setup() { var services = new ServiceCollection(); services.AddTestServices(DbType.Ef, AsyncMonolithSettings.Default); @@ -126,8 +126,8 @@ public void ConsumerRegistry_Resolves_PayloadConsumerNames() // Then consumerIds.Count.ShouldBe(2); - Assert.Single(consumerIds.Where(c => c == nameof(MultiConsumer1))); - Assert.Single(consumerIds.Where(c => c == nameof(MultiConsumer2))); + Assert.Single(consumerIds, c => c == nameof(MultiConsumer1)); + Assert.Single(consumerIds, c => c == nameof(MultiConsumer2)); } diff --git a/AsyncMonolith.Tests/Infra/DbTestsBase.cs b/AsyncMonolith.Tests/Infra/DbTestsBase.cs index 56b3c14..6c451a8 100644 --- a/AsyncMonolith.Tests/Infra/DbTestsBase.cs +++ b/AsyncMonolith.Tests/Infra/DbTestsBase.cs @@ -9,8 +9,8 @@ namespace AsyncMonolith.Tests.Infra; public abstract class DbTestsBase { - protected FakeTimeProvider FakeTime = default!; - protected TestConsumerInvocations TestConsumerInvocations = default!; + protected FakeTimeProvider FakeTime { get; private set; } = default!; + protected TestConsumerInvocations TestConsumerInvocations { get; private set; } = default!; protected async Task Setup(TestDbContainerBase dbContainer, AsyncMonolithSettings? settings = null) { @@ -39,7 +39,7 @@ protected async Task Setup(TestDbContainerBase dbContainer, Asy return serviceProvider; } - public Activity? GetActivity() + public static Activity? GetActivity() { var activitySource = new ActivitySource("AsyncMonolith.Tests"); var listener = new ActivityListener diff --git a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs index 9383d47..7ce50c2 100644 --- a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs @@ -8,7 +8,7 @@ public class EfTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new PostgreSqlBuilder().Build(); + var container = new PostgreSqlBuilder("postgres:18-alpine").Build(); await container.StartAsync(); ConnectionString = container.GetConnectionString(); DbContainer = container; diff --git a/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs b/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs index ff494ee..c720177 100644 --- a/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs +++ b/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs @@ -14,6 +14,6 @@ public ExceptionConsumer(TestConsumerInvocations consumerInvocations) public override Task Consume(ExceptionConsumerMessage message, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(ExceptionConsumer)); - throw new Exception(); + throw new InvalidOperationException(); } } \ No newline at end of file diff --git a/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs b/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs index 304b2fc..65667c7 100644 --- a/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs +++ b/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs @@ -15,6 +15,6 @@ public ExceptionConsumer2Attempts(TestConsumerInvocations consumerInvocations) public override Task Consume(ExceptionConsumer2AttemptsMessage message, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(ExceptionConsumer2AttemptsMessage)); - throw new Exception(); + throw new InvalidOperationException(); } } \ No newline at end of file diff --git a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs index 76e8462..5985803 100644 --- a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs @@ -9,7 +9,7 @@ public class MariaDbTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new MariaDbBuilder().Build(); + var container = new MariaDbBuilder("mariadb:11.8").Build(); await container.StartAsync(); ConnectionString = container.GetConnectionString(); DbContainer = container; diff --git a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs index 87c745b..a280eea 100644 --- a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs @@ -8,7 +8,7 @@ public class MsSqlTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new MsSqlBuilder().Build(); + var container = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest").Build(); await container.StartAsync(); ConnectionString = container.GetConnectionString(); DbContainer = container; diff --git a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs index dc57958..dfbe54c 100644 --- a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs @@ -8,7 +8,7 @@ public class MySqlTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new MySqlBuilder().Build(); + var container = new MySqlBuilder("mysql:8.4").Build(); await container.StartAsync(); ConnectionString = container.GetConnectionString(); DbContainer = container; diff --git a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs index fdc47f8..9af567c 100644 --- a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs @@ -8,7 +8,7 @@ public class PostgreSqlTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new PostgreSqlBuilder().Build(); + var container = new PostgreSqlBuilder("postgres:18-alpine").Build(); await container.StartAsync(); ConnectionString = container.GetConnectionString(); DbContainer = container; diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 17f3494..874310d 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -27,7 +27,7 @@ public static void AddInMemoryDb(this ServiceCollection services) public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) AddTestServices( this ServiceCollection services, DbType dbType, AsyncMonolithSettings settings) { - var fakeTime = new FakeTimeProvider(DateTimeOffset.Parse("2020-08-31T10:00:00.0000000Z")); + var fakeTime = new FakeTimeProvider(DateTimeOffset.Parse("2020-08-31T10:00:00.0000000Z", System.Globalization.CultureInfo.InvariantCulture)); services.AddSingleton(fakeTime); services.AddLogging(); diff --git a/AsyncMonolith.Tests/ProducerServiceDbTests.cs b/AsyncMonolith.Tests/ProducerServiceDbTests.cs index 3965bc1..cda69d2 100644 --- a/AsyncMonolith.Tests/ProducerServiceDbTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceDbTests.cs @@ -33,7 +33,7 @@ public async Task Producer_Inserts_ConsumerMessage(DbType dbType) Activity.Current = activity; // When - await producer.Produce(consumerMessage, delay); + await producer.Produce(consumerMessage, delay, cancellationToken: TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -89,13 +89,13 @@ public async Task Producer_Inserts_List_Of_ConsumerMessages(DbType dbType) Activity.Current = activity; // When - await producer.ProduceList(insertMessages, delay); + await producer.ProduceList(insertMessages, delay, cancellationToken: TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); { var postDbContext = serviceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(); + var messages = await postDbContext.ConsumerMessages.ToListAsync(TestContext.Current.CancellationToken); messages.Count.ShouldBe(2); var message1 = @@ -162,14 +162,14 @@ public async Task Ef_Producer_Inserts_List_Of_ConsumerMessages() Activity.Current = activity; // When - await producer.ProduceList(insertMessages, delay); - await dbContext.SaveChangesAsync(); + await producer.ProduceList(insertMessages, delay, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var postScope = serviceProvider.CreateScope(); { var postDbContext = postScope.ServiceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(); + var messages = await postDbContext.ConsumerMessages.ToListAsync(TestContext.Current.CancellationToken); messages.Count.ShouldBe(2); var message1 = @@ -225,13 +225,13 @@ public async Task Producer_Does_Not_Insert_Duplicate_ConsumerMessage(DbType dbTy using var activity = GetActivity(); Activity.Current = activity; - await producer.Produce(consumerMessage, delay, insertId); + await producer.Produce(consumerMessage, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); // When await producer.Produce(new SingleConsumerMessage { Name = "test-name-2" - }, delay, insertId); + }, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -277,15 +277,15 @@ public async Task EF_Producer_Throws_Exception_On_Duplicate_ConsumerMessage(DbTy { Name = "test-name" }; - await producer.Produce(consumerMessage, 10, insertId); + await producer.Produce(consumerMessage, 10, insertId, cancellationToken: TestContext.Current.CancellationToken); // When await producer.Produce(new SingleConsumerMessage { Name = "test-name-2" - }, delay, insertId); + }, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); - await Assert.ThrowsAsync(async () => { await dbContext.SaveChangesAsync(); }); + await Assert.ThrowsAsync(async () => { await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); }); } finally { diff --git a/AsyncMonolith.Tests/ProducerServiceTests.cs b/AsyncMonolith.Tests/ProducerServiceTests.cs index 36f525e..13a5926 100644 --- a/AsyncMonolith.Tests/ProducerServiceTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceTests.cs @@ -14,7 +14,7 @@ namespace AsyncMonolith.Tests; public class ProducerServiceTests { - public FakeTimeProvider FakeTime = default!; + private FakeTimeProvider FakeTime { get; set; } = default!; private ServiceProvider Setup() { @@ -25,7 +25,7 @@ private ServiceProvider Setup() return services.BuildServiceProvider(); } - public Activity? GetActivity() + public static Activity? GetActivity() { var activitySource = new ActivitySource("AsyncMonolith.Tests"); var listener = new ActivityListener @@ -60,8 +60,8 @@ public async Task Producer_Writes_Single_Consumer_Message() Activity.Current = activity; // When - await producer.Produce(consumerMessage, delay, insertId); - await dbContext.SaveChangesAsync(); + await producer.Produce(consumerMessage, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -99,8 +99,8 @@ public async Task Producer_Writes_Multiple_Consumer_Message() Activity.Current = activity; // When - await producer.Produce(consumerMessage, delay, insertId); - await dbContext.SaveChangesAsync(); + await producer.Produce(consumerMessage, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -148,8 +148,8 @@ public async Task Producer_AvailableAfter_Defaults_To_CurrentTime() Activity.Current = activity; // When - await producer.Produce(consumerMessage); - await dbContext.SaveChangesAsync(); + await producer.Produce(consumerMessage, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -198,7 +198,7 @@ public async Task Producer_Produces_Single_Scheduled_Message() // When producer.Produce(scheduledMessage); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -245,13 +245,13 @@ public async Task Producer_Produces_Multiple_Scheduled_Message() // When producer.Produce(scheduledMessage); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); { var postDbContext = serviceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(); + var messages = await postDbContext.ConsumerMessages.ToListAsync(TestContext.Current.CancellationToken); messages.Count.ShouldBe(2); var message1 = diff --git a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs index 82f5722..964846a 100644 --- a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs @@ -38,7 +38,7 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) }); } - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // When var dbMessages = await fetcher.Fetch(dbContext.ScheduledMessages, FakeTime.GetUtcNow().ToUnixTimeSeconds(), diff --git a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs index aeebbcc..6fbc54f 100644 --- a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs @@ -34,7 +34,7 @@ public async Task ScheduledMessageProcessor_Produces_ConsumerMessages(TestDbCont scheduledMessageService.Schedule(consumerMessage, "* * * * * *", "UTC", "test-tag"); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } // When @@ -48,7 +48,7 @@ public async Task ScheduledMessageProcessor_Produces_ConsumerMessages(TestDbCont using (var scope = serviceProvider.CreateScope()) { var postDbContext = scope.ServiceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(); + var messages = await postDbContext.ConsumerMessages.ToListAsync(TestContext.Current.CancellationToken); messages.Count.ShouldBe(2); var message1 = @@ -102,7 +102,7 @@ public async Task ScheduledMessageProcessor_Increments_Available_After(TestDbCon scheduledMessageService.Schedule(consumerMessage, "* * * * * *", "UTC", "test-tag"); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } FakeTime.SetUtcNow(FakeTime.GetUtcNow().AddSeconds(100)); diff --git a/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs b/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs index 2f30063..042fa3f 100644 --- a/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageServiceTests.cs @@ -30,7 +30,7 @@ public async Task Schedule_Writes_Scheduled_Message(TestDbContainerBase dbContai // When scheduledMessageService.Schedule(consumerMessage, "* * * * * *", "UTC", tag); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -72,17 +72,17 @@ public async Task DeleteByTag_Deletes_Scheduled_Messages(TestDbContainerBase dbC var tag = "test-tag"; scheduledMessageService.Schedule(consumerMessage1, "* * * * * *", "UTC", tag); scheduledMessageService.Schedule(consumerMessage2, "* * * * * *", "UTC", tag); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // When await scheduledMessageService.DeleteByTag("test-tag", CancellationToken.None); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); { var postDbContext = serviceProvider.GetRequiredService(); - var count = await postDbContext.ScheduledMessages.CountAsync(); + var count = await postDbContext.ScheduledMessages.CountAsync(TestContext.Current.CancellationToken); count.ShouldBe(0); } } @@ -109,17 +109,17 @@ public async Task DeleteById_Deletes_Scheduled_Messages(TestDbContainerBase dbCo var scheduledMessageService = serviceProvider.GetRequiredService(); var dbContext = serviceProvider.GetRequiredService(); var id = scheduledMessageService.Schedule(consumerMessage, "* * * * * *", "UTC"); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // When await scheduledMessageService.DeleteById(id, CancellationToken.None); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); { var postDbContext = serviceProvider.GetRequiredService(); - var count = await postDbContext.ScheduledMessages.CountAsync(); + var count = await postDbContext.ScheduledMessages.CountAsync(TestContext.Current.CancellationToken); count.ShouldBe(0); } } From cfac2d5253cfec45e22c731c86db7344a0b0f5ec Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:08:09 +0000 Subject: [PATCH 09/53] Fix analyzer findings in the example API Forward request cancellation tokens to the producer, fail fast when the connection string is missing, and treat EF migrations as generated code. --- .editorconfig | 5 +++++ Example/Example.Api/Counter/ValueController.cs | 2 +- Example/Example.Api/Program.cs | 5 +++-- Example/Example.Api/Spam/SpamController.cs | 4 ++-- 4 files changed, 11 insertions(+), 5 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a8819b7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,5 @@ +root = true + +# EF Core migrations are generated code. +[**/Migrations/*.cs] +generated_code = true diff --git a/Example/Example.Api/Counter/ValueController.cs b/Example/Example.Api/Counter/ValueController.cs index 9e1f89b..c68f75a 100644 --- a/Example/Example.Api/Counter/ValueController.cs +++ b/Example/Example.Api/Counter/ValueController.cs @@ -28,7 +28,7 @@ public async Task Get(CancellationToken cancellationToken) await _producerService.Produce(new ValueSubmitted { Value = newValue - }); + }, cancellationToken: cancellationToken); await _dbContext.SaveChangesAsync(cancellationToken); return Ok(sum + newValue); diff --git a/Example/Example.Api/Program.cs b/Example/Example.Api/Program.cs index 2292a9e..65c1aa5 100644 --- a/Example/Example.Api/Program.cs +++ b/Example/Example.Api/Program.cs @@ -16,7 +16,8 @@ public static void Main(string[] args) var builder = WebApplication.CreateBuilder(args); var connectionString = - builder.Configuration.GetConnectionString("postgresdb"); + builder.Configuration.GetConnectionString("postgresdb") + ?? throw new InvalidOperationException("Connection string 'postgresdb' is missing."); builder.Services.AddDbContext(options => options.UseNpgsql(connectionString)); @@ -24,7 +25,7 @@ public static void Main(string[] args) builder.Services.AddHealthChecks() .AddNpgSql(connectionString, name: "postgres", - tags: new[] { "ready" }); + tags: ["ready"]); builder.Services.AddSingleton(TimeProvider.System); diff --git a/Example/Example.Api/Spam/SpamController.cs b/Example/Example.Api/Spam/SpamController.cs index da9815b..ad5e0e0 100644 --- a/Example/Example.Api/Spam/SpamController.cs +++ b/Example/Example.Api/Spam/SpamController.cs @@ -51,13 +51,13 @@ public async Task Spam([FromQuery(Name = "count")] int count, Can }); } - await _producerService.ProduceList(messages); + await _producerService.ProduceList(messages, cancellationToken: cancellationToken); SpamResultService.Start = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); await _producerService.Produce(new SpamMessage { Last = true - }, 10); + }, 10, cancellationToken: cancellationToken); return Ok("Started."); } From 19b13a000ca0cd4fe6a3d57c78ca259d9d9f3291 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:08:14 +0000 Subject: [PATCH 10/53] Apply strict shared build settings A Directory.Build.props sets the target framework, nullable, implicit usings and latest language version for every project, and turns on TreatWarningsAsErrors, the .NET analyzers in Recommended mode and code-style enforcement. The duplicated properties are removed from each project, and LangVersion moves from preview to latest. Also: - Remove the Microsoft.AspNetCore.Components.Web references, which the shared framework already provides (NU1510) - Suppress NU1608 for the MySQL/MariaDB projects: Pomelo has no EF Core 10 release yet, so that combination is untested - Suppress CA1707 in tests, whose names use underscores - Treat ASPIRE010 as a message in the example AppHost --- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 5 --- .../AsyncMonolith.MariaDb.csproj | 7 +--- .../AsyncMonolith.MsSql.csproj | 5 --- .../AsyncMonolith.MySql.csproj | 7 +--- .../AsyncMonolith.PostgreSql.csproj | 5 --- .../AsyncMonolith.TestHelpers.csproj | 5 --- .../AsyncMonolith.Tests.csproj | 6 +-- AsyncMonolith/AsyncMonolith.csproj | 5 --- Directory.Build.props | 14 +++++++ Directory.Packages.props | 1 - .../AsyncMonolith.Web.csproj | 4 -- Example/Example.Api/Example.Api.csproj | 4 -- .../Example.AppHost/Example.AppHost.csproj | 37 +++++++++---------- 13 files changed, 38 insertions(+), 67 deletions(-) create mode 100644 Directory.Build.props diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index a98bbc7..8898132 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -1,11 +1,6 @@  - net10.0 - enable - enable - true - preview true AsyncMonolith.Ef 10.0.1 diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index 903f7a8..eea8df1 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -1,12 +1,9 @@  - net10.0 - enable - enable + + $(NoWarn);NU1608 NU5104 - true - preview true AsyncMonolith.MariaDb 10.0.1 diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index 30a9d5a..f0a4af7 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -1,11 +1,6 @@  - net10.0 - enable - enable - true - preview true AsyncMonolith.MsSql 10.0.1 diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 13082d3..b3a7bad 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -1,12 +1,9 @@  - net10.0 - enable - enable + + $(NoWarn);NU1608 NU5104 - true - preview true AsyncMonolith.MySql 10.0.1 diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index b5eee41..a0634e7 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -1,11 +1,6 @@  - net10.0 - enable - enable - true - preview true AsyncMonolith.PostgreSql 10.0.1 diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index c54fc91..932ed74 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -1,11 +1,6 @@  - net10.0 - enable - enable - true - preview true AsyncMonolith.TestHelpers 10.0.0 diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index afbcafa..b42d7ce 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -1,13 +1,11 @@  - net10.0 - enable - enable + + $(NoWarn);NU1608;CA1707 false true Exe - preview diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index 2a6836c..043f871 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -1,11 +1,6 @@  - net10.0 - enable - enable - true - preview true AsyncMonolith 10.0.0 diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..fd071d1 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,14 @@ + + + net10.0 + enable + enable + latest + + true + true + latest + Recommended + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props index eb3870c..c89ad3e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -34,7 +34,6 @@ - diff --git a/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj b/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj index 34b9be9..9d03a6c 100644 --- a/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj +++ b/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj @@ -1,9 +1,6 @@ - net10.0 - enable - enable @@ -11,7 +8,6 @@ - diff --git a/Example/Example.Api/Example.Api.csproj b/Example/Example.Api/Example.Api.csproj index d9a6b32..e99c515 100644 --- a/Example/Example.Api/Example.Api.csproj +++ b/Example/Example.Api/Example.Api.csproj @@ -1,9 +1,6 @@  - net10.0 - enable - enable c991b6df-a810-4f5d-aa76-760a5c9281e9 Example.Api true @@ -20,7 +17,6 @@ - diff --git a/Example/Example.AppHost/Example.AppHost.csproj b/Example/Example.AppHost/Example.AppHost.csproj index bd384ba..20ae086 100644 --- a/Example/Example.AppHost/Example.AppHost.csproj +++ b/Example/Example.AppHost/Example.AppHost.csproj @@ -1,19 +1,18 @@ - - - - Exe - net10.0 - enable - enable - 0ad4215a-f9fc-4c99-82ac-69d5df8fce04 - - - - - - - - - - - + + + + + $(MSBuildWarningsAsMessages);ASPIRE010 + Exe + 0ad4215a-f9fc-4c99-82ac-69d5df8fce04 + + + + + + + + + + + From 17c0cf503c91460dd54a83d3c95e2b657dfcd8d6 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:11:00 +0000 Subject: [PATCH 11/53] Add fast consumer processing tests on in-memory SQLite SqliteTestHost runs the real producer, schedule service, fetchers and processors over an in-memory SQLite database with a fake clock, so batch behaviour can be tested in milliseconds without Docker. ConsumerProcessingTests covers one batch: success removes the message, availability, retry delay, poisoning (fields copied, never retried), attempt overrides, timeouts, batch size, oldest-first ordering, independent consumers of one payload, rails, unknown consumer types, null payloads, and parallel versus sequential execution. TestConsumerInvocations becomes thread-safe, since parallel consumers in a batch increment it concurrently, and records invocation order. --- .../AsyncMonolith.Tests.csproj | 1 + .../ConsumerProcessingTests.cs | 271 ++++++++++++++++++ .../Infra/BehaviourConsumers.cs | 106 +++++++ AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 120 ++++++++ .../Infra/TestConsumerInvocations.cs | 24 +- Directory.Packages.props | 1 + 6 files changed, 512 insertions(+), 11 deletions(-) create mode 100644 AsyncMonolith.Tests/ConsumerProcessingTests.cs create mode 100644 AsyncMonolith.Tests/Infra/BehaviourConsumers.cs create mode 100644 AsyncMonolith.Tests/Infra/SqliteTestHost.cs diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index b42d7ce..46b185c 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -11,6 +11,7 @@ + diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs new file mode 100644 index 0000000..3d05da2 --- /dev/null +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -0,0 +1,271 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Tests.Infra; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Behaviour of for one batch, against in-memory SQLite. +/// +public class ConsumerProcessingTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Successful_message_is_consumed_and_removed() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "a" }); + + var processed = await host.ConsumerProcessor.ProcessBatch(Ct); + + processed.ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + (await host.ConsumerMessages()).ShouldBeEmpty(); + (await host.PoisonedMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task Empty_queue_processes_nothing() + { + await using var host = await SqliteTestHost.Create(); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + } + + [Fact] + public async Task Message_is_not_consumed_before_it_is_available() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "later" }, host.Now + 60); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(0); + + host.Time.Advance(TimeSpan.FromSeconds(60)); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + } + + [Fact] + public async Task Failed_message_is_retried_after_the_attempt_delay() + { + await using var host = await SqliteTestHost.Create(s => s.AttemptDelay = 30); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); + var start = host.Now; + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + + var message = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + message.Attempts.ShouldBe(1); + message.AvailableAfter.ShouldBe(start + 30); + + // Not retried before the delay has passed + host.Time.Advance(TimeSpan.FromSeconds(29)); + await host.ConsumerProcessor.ProcessBatch(Ct); + host.Invocations.GetInvocationCount(nameof(ExceptionConsumer)).ShouldBe(1); + + host.Time.Advance(TimeSpan.FromSeconds(1)); + await host.ConsumerProcessor.ProcessBatch(Ct); + host.Invocations.GetInvocationCount(nameof(ExceptionConsumer)).ShouldBe(2); + (await host.ConsumerMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(2); + } + + [Fact] + public async Task Message_is_poisoned_after_the_configured_max_attempts() + { + await using var host = await SqliteTestHost.Create(s => + { + s.MaxAttempts = 3; + s.AttemptDelay = 0; + }); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }, insertId: "insert-1"); + var original = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + + for (var i = 0; i < 3; i++) + { + await host.ConsumerProcessor.ProcessBatch(Ct); + } + + host.Invocations.GetInvocationCount(nameof(ExceptionConsumer)).ShouldBe(3); + (await host.ConsumerMessages()).ShouldBeEmpty(); + + var poisoned = (await host.PoisonedMessages()).ShouldHaveSingleItem(); + poisoned.Id.ShouldBe(original.Id); + poisoned.Attempts.ShouldBe(3); + poisoned.ConsumerType.ShouldBe(nameof(ExceptionConsumer)); + poisoned.PayloadType.ShouldBe(nameof(ExceptionConsumerMessage)); + poisoned.Payload.ShouldBe(original.Payload); + poisoned.InsertId.ShouldBe("insert-1"); + poisoned.CreatedAt.ShouldBe(original.CreatedAt); + poisoned.RailId.ShouldBe(original.RailId); + + // Poisoned messages are never picked up again + await host.ConsumerProcessor.ProcessBatch(Ct); + host.Invocations.GetInvocationCount(nameof(ExceptionConsumer)).ShouldBe(3); + } + + [Fact] + public async Task Consumer_attempts_attribute_overrides_the_default_max_attempts() + { + await using var host = await SqliteTestHost.Create(s => + { + s.MaxAttempts = 10; + s.AttemptDelay = 0; + }); + await host.Produce(new ExceptionConsumer2AttemptsMessage { Name = "boom" }); + + await host.ConsumerProcessor.ProcessBatch(Ct); + (await host.PoisonedMessages()).ShouldBeEmpty(); + + await host.ConsumerProcessor.ProcessBatch(Ct); + (await host.PoisonedMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(2); + } + + [Fact] + public async Task Max_attempts_of_one_poisons_on_the_first_failure() + { + await using var host = await SqliteTestHost.Create(s => s.MaxAttempts = 1); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + (await host.ConsumerMessages()).ShouldBeEmpty(); + (await host.PoisonedMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(1); + } + + [Fact] + public async Task Consumer_that_exceeds_its_timeout_counts_as_a_failed_attempt() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new TimeoutConsumerMessage { Delay = 5 }); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + + host.Invocations.GetInvocationCount(nameof(TimeoutConsumer)).ShouldBe(1); + (await host.ConsumerMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(1); + } + + [Fact] + public async Task Batch_size_limits_how_many_messages_are_processed_at_once() + { + await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 2); + for (var i = 0; i < 5; i++) + { + await host.Produce(new SingleConsumerMessage { Name = $"m{i}" }); + } + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(2); + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(2); + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(5); + } + + [Fact] + public async Task Oldest_messages_are_processed_first() + { + await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 1); + await host.Produce(new OrderedMessage { Name = "newer" }); + await host.Produce(new OrderedMessage { Name = "older" }); + + // Make the second message the oldest, so order can't come from insertion or id order. + await host.Change(db => + { + var messages = db.ConsumerMessages.ToList(); + messages.Single(m => m.Payload.Contains("newer", StringComparison.Ordinal)).CreatedAt = host.Now + 10; + }); + + await host.ConsumerProcessor.ProcessBatch(Ct); + await host.ConsumerProcessor.ProcessBatch(Ct); + + host.Invocations.Order.ShouldBe(["OrderedConsumer:older", "OrderedConsumer:newer"]); + } + + [Fact] + public async Task Each_consumer_of_a_payload_succeeds_or_fails_independently() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MixedOutcomeMessage()); + + var processed = await host.ConsumerProcessor.ProcessBatch(Ct); + + processed.ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(MixedSuccessConsumer)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(MixedFailureConsumer)).ShouldBe(1); + var remaining = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + remaining.ConsumerType.ShouldBe(nameof(MixedFailureConsumer)); + remaining.Attempts.ShouldBe(1); + } + + [Fact] + public async Task Processor_only_takes_messages_for_its_own_rail() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new RailConsumerMessage()); + + // The default processor runs rail 0 + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(RailConsumer0)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(RailConsumer1)).ShouldBe(0); + host.Invocations.GetInvocationCount(nameof(RailConsumer2)).ShouldBe(0); + + var rail1 = ActivatorUtilities.CreateInstance>(host.Services); + rail1.SetRailId(1); + (await rail1.ProcessBatch(Ct)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(RailConsumer1)).ShouldBe(1); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().ConsumerType.ShouldBe(nameof(RailConsumer2)); + } + + [Fact] + public async Task Unknown_consumer_type_counts_as_a_failed_attempt() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "a" }); + await host.Change(db => db.ConsumerMessages.Single().ConsumerType = "RemovedConsumer"); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(1); + } + + [Fact] + public async Task Payload_that_deserializes_to_null_counts_as_a_failed_attempt() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "a" }); + await host.Change(db => db.ConsumerMessages.Single().Payload = "null"); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(0); + (await host.ConsumerMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(1); + } + + [Fact] + public async Task Parallel_consumers_in_a_batch_run_concurrently() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new ParallelProbeMessage()); + await host.Produce(new ParallelProbeMessage()); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(2); + + host.Services.GetRequiredService().Max.ShouldBe(2); + } + + [Fact] + public async Task Sequential_consumers_in_a_batch_run_one_at_a_time() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SequentialProbeMessage()); + await host.Produce(new SequentialProbeMessage()); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(2); + + host.Services.GetRequiredService().Max.ShouldBe(1); + } +} diff --git a/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs new file mode 100644 index 0000000..f42b827 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs @@ -0,0 +1,106 @@ +using System.Text.Json.Serialization; +using AsyncMonolith.Consumers; + +namespace AsyncMonolith.Tests.Infra; + +/// Records the payload name, so tests can check which messages ran and in what order. +public class OrderedMessage : IConsumerPayload +{ + [JsonPropertyName("name")] public required string Name { get; set; } +} + +public class OrderedConsumer(TestConsumerInvocations invocations) : BaseConsumer +{ + public override Task Consume(OrderedMessage payload, CancellationToken cancellationToken) + { + invocations.Increment($"{nameof(OrderedConsumer)}:{payload.Name}"); + return Task.CompletedTask; + } +} + +/// One payload, two consumers: one always succeeds, one always fails. +public class MixedOutcomeMessage : IConsumerPayload +{ +} + +public class MixedSuccessConsumer(TestConsumerInvocations invocations) : BaseConsumer +{ + public override Task Consume(MixedOutcomeMessage payload, CancellationToken cancellationToken) + { + invocations.Increment(nameof(MixedSuccessConsumer)); + return Task.CompletedTask; + } +} + +public class MixedFailureConsumer(TestConsumerInvocations invocations) : BaseConsumer +{ + public override Task Consume(MixedOutcomeMessage payload, CancellationToken cancellationToken) + { + invocations.Increment(nameof(MixedFailureConsumer)); + throw new InvalidOperationException("Always fails"); + } +} + +/// Non-positive attribute values fall back to the configured defaults. +public class InvalidAttributesMessage : IConsumerPayload +{ +} + +[ConsumerTimeout(0)] +[ConsumerAttempts(-1)] +public class InvalidAttributesConsumer : BaseConsumer +{ + public override Task Consume(InvalidAttributesMessage payload, CancellationToken cancellationToken) => + Task.CompletedTask; +} + +/// Tracks how many consumers are running at once. +public sealed class ConcurrencyProbe +{ + private int _current; + private int _max; + private readonly TaskCompletionSource _bothStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public int Max => Volatile.Read(ref _max); + + public async Task Enter(int expectedConcurrency, CancellationToken cancellationToken) + { + var current = Interlocked.Increment(ref _current); + int max; + do + { + max = Volatile.Read(ref _max); + } while (current > max && Interlocked.CompareExchange(ref _max, current, max) != max); + + if (current >= expectedConcurrency) + { + _bothStarted.TrySetResult(); + } + + // Wait briefly for the other consumer; sequential execution never gets here twice at once. + await Task.WhenAny(_bothStarted.Task, Task.Delay(TimeSpan.FromMilliseconds(300), cancellationToken)); + Interlocked.Decrement(ref _current); + } +} + +public class ParallelProbeMessage : IConsumerPayload +{ +} + +[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Parallel)] +public class ParallelProbeConsumer(ConcurrencyProbe probe) : BaseConsumer +{ + public override Task Consume(ParallelProbeMessage payload, CancellationToken cancellationToken) => + probe.Enter(2, cancellationToken); +} + +public class SequentialProbeMessage : IConsumerPayload +{ +} + +[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Sequential)] +public class SequentialProbeConsumer(ConcurrencyProbe probe) : BaseConsumer +{ + public override Task Consume(SequentialProbeMessage payload, CancellationToken cancellationToken) => + probe.Enter(2, cancellationToken); +} diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs new file mode 100644 index 0000000..38d1da7 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -0,0 +1,120 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Producers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Utilities; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Time.Testing; + +namespace AsyncMonolith.Tests.Infra; + +/// +/// A fast, in-process host for low-level tests: the real AsyncMonolith services and EF providers +/// over an in-memory SQLite database (relational, with transactions and unique indexes), a fake clock, +/// and no Docker. +/// +/// +/// All DbContexts share one open connection, so consumers used with this host must not write to the +/// database while a batch is being processed. +/// +public sealed class SqliteTestHost : IAsyncDisposable +{ + private readonly SqliteConnection _connection; + + private SqliteTestHost(SqliteConnection connection, ServiceProvider services, FakeTimeProvider time, + TestConsumerInvocations invocations) + { + _connection = connection; + Services = services; + Time = time; + Invocations = invocations; + } + + public ServiceProvider Services { get; } + public FakeTimeProvider Time { get; } + public TestConsumerInvocations Invocations { get; } + + public long Now => Time.GetUtcNow().ToUnixTimeSeconds(); + + public ConsumerMessageProcessor ConsumerProcessor => + Services.GetRequiredService>(); + + public ScheduledMessageProcessor ScheduledProcessor => + Services.GetRequiredService>(); + + public static async Task Create(Action? configure = null) + { + var connection = new SqliteConnection("DataSource=:memory:"); + await connection.OpenAsync(); + + var settings = AsyncMonolithSettings.Default; + configure?.Invoke(settings); + + var services = new ServiceCollection(); + services.AddDbContext(options => options.UseSqlite(connection)); + var (time, invocations) = services.AddTestServices(DbType.Ef, settings); + services.AddSingleton>(); + services.AddSingleton>(); + services.AddSingleton(); + + var provider = services.BuildServiceProvider(); + using (var scope = provider.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + } + + return new SqliteTestHost(connection, provider, time, invocations); + } + + /// Produces a message in its own scope and saves it. + public async Task Produce(T payload, long? availableAfter = null, string? insertId = null) + where T : IConsumerPayload + { + using var scope = Services.CreateScope(); + await scope.ServiceProvider.GetRequiredService() + .Produce(payload, availableAfter, insertId); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(); + } + + /// Schedules a message in its own scope and saves it. + public async Task Schedule(T payload, string cron, string timezone = "UTC", string? tag = null) + where T : IConsumerPayload + { + using var scope = Services.CreateScope(); + var id = scope.ServiceProvider.GetRequiredService().Schedule(payload, cron, timezone, tag); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(); + return id; + } + + /// Runs a query against a fresh DbContext. + public async Task Query(Func> query) + { + using var scope = Services.CreateScope(); + return await query(scope.ServiceProvider.GetRequiredService()); + } + + /// Changes data with a fresh DbContext and saves it. + public async Task Change(Action change) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + change(db); + await db.SaveChangesAsync(); + } + + public Task> ConsumerMessages() => + Query(db => db.ConsumerMessages.OrderBy(m => m.Id).ToListAsync()); + + public Task> PoisonedMessages() => + Query(db => db.PoisonedMessages.OrderBy(m => m.Id).ToListAsync()); + + public Task> ScheduledMessages() => + Query(db => db.ScheduledMessages.OrderBy(m => m.Id).ToListAsync()); + + public async ValueTask DisposeAsync() + { + await Services.DisposeAsync(); + await _connection.DisposeAsync(); + } +} diff --git a/AsyncMonolith.Tests/Infra/TestConsumerInvocations.cs b/AsyncMonolith.Tests/Infra/TestConsumerInvocations.cs index 302ef11..88d6c9b 100644 --- a/AsyncMonolith.Tests/Infra/TestConsumerInvocations.cs +++ b/AsyncMonolith.Tests/Infra/TestConsumerInvocations.cs @@ -1,23 +1,25 @@ +using System.Collections.Concurrent; + namespace AsyncMonolith.Tests.Infra; +/// +/// Counts consumer invocations. Thread-safe because parallel consumers in a batch run concurrently. +/// public class TestConsumerInvocations { - public Dictionary InvocationCounts { get; } = new(); + private readonly ConcurrentDictionary _invocationCounts = new(); + private readonly ConcurrentQueue _order = new(); + + public IReadOnlyList Order => _order.ToList(); public void Increment(string consumerName) { - if (InvocationCounts.TryGetValue(consumerName, out var count)) - { - InvocationCounts[consumerName] = count + 1; - } - else - { - InvocationCounts[consumerName] = 1; - } + _invocationCounts.AddOrUpdate(consumerName, 1, (_, count) => count + 1); + _order.Enqueue(consumerName); } public int GetInvocationCount(string consumerName) { - return InvocationCounts.TryGetValue(consumerName, out var count) ? count : 0; + return _invocationCounts.GetValueOrDefault(consumerName); } -} \ No newline at end of file +} diff --git a/Directory.Packages.props b/Directory.Packages.props index c89ad3e..946ea42 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -23,6 +23,7 @@ + From 6ffff4d48b1a31be04d7bbab2e6fed519520eb16 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:11:45 +0000 Subject: [PATCH 12/53] Add fast scheduling tests Covers next-occurrence calculation across time zones (and that it is strictly after now), the required seconds field, unknown time zones, UpdateSchedule/UpdatePayload, the schedule service (stored fields, validation before save, DeleteByTag, DeleteById) and the scheduled message processor (producing for every consumer, advancing to the next occurrence, batch size). Two tests document current behaviour that callers should know about: scheduling the same tag twice creates two schedules, and missed occurrences are not caught up. --- AsyncMonolith.Tests/SchedulingTests.cs | 236 +++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 AsyncMonolith.Tests/SchedulingTests.cs diff --git a/AsyncMonolith.Tests/SchedulingTests.cs b/AsyncMonolith.Tests/SchedulingTests.cs new file mode 100644 index 0000000..1387c94 --- /dev/null +++ b/AsyncMonolith.Tests/SchedulingTests.cs @@ -0,0 +1,236 @@ +using System.Globalization; +using System.Text.Json; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Tests.Infra; +using Cronos; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Time.Testing; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Cron schedules, the schedule service and the scheduled message processor, against in-memory SQLite. +/// The fake clock starts at 2020-08-31T10:00:00Z (11:00 in London, which is on BST). +/// +public class SchedulingTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static long Utc(string iso) => + DateTimeOffset.Parse(iso, CultureInfo.InvariantCulture).ToUnixTimeSeconds(); + + private static ScheduledMessage Message(string cron, string timezone) => new() + { + Id = "id", + Tag = null, + AvailableAfter = 0, + ChronExpression = cron, + ChronTimezone = timezone, + PayloadType = nameof(SingleConsumerMessage), + Payload = "{}" + }; + + private static FakeTimeProvider Clock() => + new(DateTimeOffset.Parse("2020-08-31T10:00:00Z", CultureInfo.InvariantCulture)); + + [Theory] + [InlineData("UTC", "2020-09-01T09:00:00Z")] + [InlineData("Europe/London", "2020-09-01T08:00:00Z")] + [InlineData("America/New_York", "2020-08-31T13:00:00Z")] + public void Next_occurrence_is_calculated_in_the_schedule_timezone(string timezone, string expected) + { + var message = Message("0 0 9 * * *", timezone); + + message.GetNextOccurrence(Clock()).ShouldBe(Utc(expected)); + } + + [Fact] + public void Next_occurrence_is_strictly_after_now() + { + // 10:00:00 matches the expression, but the next occurrence is the following minute. + Message("0 * * * * *", "UTC").GetNextOccurrence(Clock()).ShouldBe(Utc("2020-08-31T10:01:00Z")); + } + + [Fact] + public void Cron_expressions_require_a_seconds_field() + { + Should.Throw(() => Message("0 9 * * *", "UTC").GetNextOccurrence(Clock())); + } + + [Fact] + public void Unknown_timezone_throws() + { + Should.Throw(() => Message("0 0 9 * * *", "Not/AZone").GetNextOccurrence(Clock())); + } + + [Fact] + public void UpdateSchedule_changes_the_expression_and_recalculates_availability() + { + var message = Message("0 0 9 * * *", "UTC"); + + message.UpdateSchedule("0 30 10 * * *", "UTC", Clock()); + + message.ChronExpression.ShouldBe("0 30 10 * * *"); + message.ChronTimezone.ShouldBe("UTC"); + message.AvailableAfter.ShouldBe(Utc("2020-08-31T10:30:00Z")); + } + + [Fact] + public void UpdatePayload_replaces_the_payload_and_its_type() + { + var message = Message("0 0 9 * * *", "UTC"); + + message.UpdatePayload(new OrderedMessage { Name = "updated" }); + + message.PayloadType.ShouldBe(nameof(OrderedMessage)); + JsonSerializer.Deserialize(message.Payload)!.Name.ShouldBe("updated"); + } + + [Fact] + public async Task Schedule_stores_the_message_with_its_first_occurrence() + { + await using var host = await SqliteTestHost.Create(); + + var id = await host.Schedule(new SingleConsumerMessage { Name = "daily" }, "0 0 9 * * *", "UTC", "reports"); + + var stored = (await host.ScheduledMessages()).ShouldHaveSingleItem(); + stored.Id.ShouldBe(id); + stored.Tag.ShouldBe("reports"); + stored.ChronExpression.ShouldBe("0 0 9 * * *"); + stored.ChronTimezone.ShouldBe("UTC"); + stored.PayloadType.ShouldBe(nameof(SingleConsumerMessage)); + JsonSerializer.Deserialize(stored.Payload)!.Name.ShouldBe("daily"); + stored.AvailableAfter.ShouldBe(Utc("2020-09-01T09:00:00Z")); + } + + [Fact] + public async Task Schedule_rejects_an_invalid_expression_before_saving() + { + await using var host = await SqliteTestHost.Create(); + + await Should.ThrowAsync(() => + host.Schedule(new SingleConsumerMessage { Name = "x" }, "not a cron")); + + (await host.ScheduledMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task Scheduling_the_same_tag_twice_creates_two_schedules() + { + // Documents current behaviour: Schedule always inserts, so registering a schedule + // at every startup duplicates it unless the caller deletes by tag first. + await using var host = await SqliteTestHost.Create(); + + await host.Schedule(new SingleConsumerMessage { Name = "x" }, "0 0 9 * * *", tag: "nightly"); + await host.Schedule(new SingleConsumerMessage { Name = "x" }, "0 0 9 * * *", tag: "nightly"); + + (await host.ScheduledMessages()).Count.ShouldBe(2); + } + + [Fact] + public async Task DeleteByTag_removes_only_schedules_with_that_tag() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "a" }, "0 0 9 * * *", tag: "remove"); + await host.Schedule(new SingleConsumerMessage { Name = "b" }, "0 0 9 * * *", tag: "remove"); + var keep = await host.Schedule(new SingleConsumerMessage { Name = "c" }, "0 0 9 * * *", tag: "keep"); + + using (var scope = host.Services.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().DeleteByTag("remove", Ct); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + } + + (await host.ScheduledMessages()).ShouldHaveSingleItem().Id.ShouldBe(keep); + } + + [Fact] + public async Task DeleteById_removes_one_schedule_and_ignores_unknown_ids() + { + await using var host = await SqliteTestHost.Create(); + var remove = await host.Schedule(new SingleConsumerMessage { Name = "a" }, "0 0 9 * * *"); + var keep = await host.Schedule(new SingleConsumerMessage { Name = "b" }, "0 0 9 * * *"); + + using (var scope = host.Services.CreateScope()) + { + var service = scope.ServiceProvider.GetRequiredService(); + await service.DeleteById(remove, Ct); + await service.DeleteById("does-not-exist", Ct); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + } + + (await host.ScheduledMessages()).ShouldHaveSingleItem().Id.ShouldBe(keep); + } + + [Fact] + public async Task Due_schedule_produces_a_message_and_moves_to_its_next_occurrence() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "tick" }, "0 * * * * *"); + + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(0); + (await host.ConsumerMessages()).ShouldBeEmpty(); + + host.Time.Advance(TimeSpan.FromMinutes(1)); + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(1); + + var produced = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + produced.ConsumerType.ShouldBe(nameof(SingleConsumer)); + produced.AvailableAfter.ShouldBe(host.Now); + JsonSerializer.Deserialize(produced.Payload)!.Name.ShouldBe("tick"); + (await host.ScheduledMessages()).ShouldHaveSingleItem().AvailableAfter + .ShouldBe(Utc("2020-08-31T10:02:00Z")); + + // Produced messages are consumed by the consumer processor as normal + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + } + + [Fact] + public async Task Due_schedule_produces_a_message_for_every_consumer_of_the_payload() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new MultiConsumerMessage { Name = "x" }, "0 * * * * *"); + host.Time.Advance(TimeSpan.FromMinutes(1)); + + await host.ScheduledProcessor.ProcessBatch(Ct); + + var produced = await host.ConsumerMessages(); + produced.Select(m => m.ConsumerType).Order() + .ShouldBe([nameof(MultiConsumer1), nameof(MultiConsumer2)]); + produced.Select(m => m.InsertId).Distinct().ShouldHaveSingleItem(); + } + + [Fact] + public async Task Missed_occurrences_are_not_caught_up() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "tick" }, "0 * * * * *"); + + // Five occurrences pass while the processor is not running + host.Time.Advance(TimeSpan.FromMinutes(5)); + await host.ScheduledProcessor.ProcessBatch(Ct); + await host.ScheduledProcessor.ProcessBatch(Ct); + + (await host.ConsumerMessages()).ShouldHaveSingleItem(); + (await host.ScheduledMessages()).ShouldHaveSingleItem().AvailableAfter + .ShouldBe(Utc("2020-08-31T10:06:00Z")); + } + + [Fact] + public async Task Scheduled_processor_respects_the_batch_size() + { + await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 2); + for (var i = 0; i < 3; i++) + { + await host.Schedule(new SingleConsumerMessage { Name = $"s{i}" }, "0 * * * * *"); + } + + host.Time.Advance(TimeSpan.FromMinutes(1)); + + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(2); + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(1); + (await host.ConsumerMessages()).Count.ShouldBe(3); + } +} From af26826e0429c99927d3a6c68ff43989759ae167 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:12:47 +0000 Subject: [PATCH 13/53] Add fast producer tests, including outbox guarantees Covers the rows Produce writes (one per consumer, shared insert id, timestamps, rails), explicit availability and insert ids, duplicate insert ids rejected by the unique index, ProduceList insert ids, and that a produced message is only written when the caller saves, and is discarded or kept with the caller's transaction. --- AsyncMonolith.Tests/ProducerBehaviourTests.cs | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 AsyncMonolith.Tests/ProducerBehaviourTests.cs diff --git a/AsyncMonolith.Tests/ProducerBehaviourTests.cs b/AsyncMonolith.Tests/ProducerBehaviourTests.cs new file mode 100644 index 0000000..11ead80 --- /dev/null +++ b/AsyncMonolith.Tests/ProducerBehaviourTests.cs @@ -0,0 +1,141 @@ +using System.Text.Json; +using AsyncMonolith.Producers; +using AsyncMonolith.Tests.Infra; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The EF producer against in-memory SQLite: what it writes, and its transactional outbox guarantees. +/// +public class ProducerBehaviourTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Produce_writes_one_pending_message_per_consumer() + { + await using var host = await SqliteTestHost.Create(); + + await host.Produce(new MultiConsumerMessage { Name = "hello" }); + + var messages = await host.ConsumerMessages(); + messages.Select(m => m.ConsumerType).Order().ShouldBe([nameof(MultiConsumer1), nameof(MultiConsumer2)]); + messages.ShouldAllBe(m => m.PayloadType == nameof(MultiConsumerMessage)); + messages.ShouldAllBe(m => m.Attempts == 0); + messages.ShouldAllBe(m => m.CreatedAt == host.Now && m.AvailableAfter == host.Now); + messages.Select(m => m.InsertId).Distinct().ShouldHaveSingleItem(); + messages.Select(m => m.Id).Distinct().Count().ShouldBe(2); + JsonSerializer.Deserialize(messages[0].Payload)!.Name.ShouldBe("hello"); + } + + [Fact] + public async Task Produce_uses_the_given_availability_and_insert_id() + { + await using var host = await SqliteTestHost.Create(); + + await host.Produce(new SingleConsumerMessage { Name = "x" }, host.Now + 300, "my-insert-id"); + + var message = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + message.AvailableAfter.ShouldBe(host.Now + 300); + message.InsertId.ShouldBe("my-insert-id"); + } + + [Fact] + public async Task Produce_assigns_each_consumer_its_rail() + { + await using var host = await SqliteTestHost.Create(); + + await host.Produce(new RailConsumerMessage()); + + (await host.ConsumerMessages()).Select(m => (m.ConsumerType, m.RailId)).OrderBy(x => x.RailId).ShouldBe([ + (nameof(RailConsumer0), 0), + (nameof(RailConsumer1), 1), + (nameof(RailConsumer2), 2) + ]); + } + + [Fact] + public async Task Producing_the_same_insert_id_twice_is_rejected_by_the_database() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key"); + + await Should.ThrowAsync(() => + host.Produce(new SingleConsumerMessage { Name = "second" }, insertId: "dedupe-key")); + + JsonSerializer.Deserialize((await host.ConsumerMessages()).ShouldHaveSingleItem().Payload)! + .Name.ShouldBe("first"); + } + + [Fact] + public async Task ProduceList_gives_each_message_its_own_insert_id() + { + await using var host = await SqliteTestHost.Create(); + + using (var scope = host.Services.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().ProduceList( + [new MultiConsumerMessage { Name = "a" }, new MultiConsumerMessage { Name = "b" }], + cancellationToken: Ct); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + } + + var messages = await host.ConsumerMessages(); + messages.Count.ShouldBe(4); + messages.GroupBy(m => m.InsertId).ShouldAllBe(g => g.Count() == 2); + messages.Select(m => m.InsertId).Distinct().Count().ShouldBe(2); + } + + [Fact] + public async Task Produced_message_is_not_written_until_the_caller_saves() + { + await using var host = await SqliteTestHost.Create(); + + using (var scope = host.Services.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "x" }, cancellationToken: Ct); + } + + (await host.ConsumerMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task Produced_message_is_discarded_when_the_callers_transaction_rolls_back() + { + await using var host = await SqliteTestHost.Create(); + + using (var scope = host.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(Ct); + await scope.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "x" }, cancellationToken: Ct); + await db.SaveChangesAsync(Ct); + await transaction.RollbackAsync(Ct); + } + + (await host.ConsumerMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task Produced_message_is_kept_when_the_callers_transaction_commits() + { + await using var host = await SqliteTestHost.Create(); + + using (var scope = host.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(Ct); + await scope.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "x" }, cancellationToken: Ct); + await db.SaveChangesAsync(Ct); + await transaction.CommitAsync(Ct); + } + + (await host.ConsumerMessages()).ShouldHaveSingleItem(); + } +} From aeb6aebea40dc5ae6856fa8bf61de8dd57b0284c Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:12:47 +0000 Subject: [PATCH 14/53] Add fast configuration and registration tests Covers settings validation and its boundaries, consumer attributes read at registration and their fallbacks, unknown consumer and payload names, rail lookup, id generation, BaseConsumer payload handling, and the services and background processors AddEfAsyncMonolith registers. --- AsyncMonolith.Tests/ConfigurationTests.cs | 235 ++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 AsyncMonolith.Tests/ConfigurationTests.cs diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs new file mode 100644 index 0000000..a580954 --- /dev/null +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -0,0 +1,235 @@ +using System.Text.Json; +using AsyncMonolith.Consumers; +using AsyncMonolith.Ef; +using AsyncMonolith.Producers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Settings validation, consumer registration, id generation and service wiring. No database. +/// +public class ConfigurationTests +{ + private static ConsumerRegistry Registry(Action? configure = null) + { + var settings = AsyncMonolithSettings.Default; + configure?.Invoke(settings); + var services = new ServiceCollection(); + services.AddTestServices(DbType.Ef, settings); + return services.BuildServiceProvider().GetRequiredService(); + } + + private static ConsumerMessage MessageFor(string consumerType) => new() + { + Id = "id", + CreatedAt = 0, + AvailableAfter = 0, + Attempts = 0, + ConsumerType = consumerType, + RailId = 0, + PayloadType = "payload", + Payload = "{}", + InsertId = "insert", + TraceId = null, + SpanId = null + }; + + public static TheoryData> InvalidSettings => new() + { + { "negative attempt delay", s => s.AttemptDelay = -1 }, + { "zero max attempts", s => s.MaxAttempts = 0 }, + { "zero max delay", s => s.ProcessorMaxDelay = 0 }, + { "negative min delay", s => s.ProcessorMinDelay = -1 }, + { "min delay above max delay", s => { s.ProcessorMinDelay = 500; s.ProcessorMaxDelay = 100; } }, + { "zero batch size", s => s.ProcessorBatchSize = 0 }, + { "zero default timeout", s => s.DefaultConsumerTimeout = 0 }, + { "default timeout over an hour", s => s.DefaultConsumerTimeout = 3601 } + }; + + [Theory] + [MemberData(nameof(InvalidSettings))] + public void Invalid_settings_are_rejected_at_startup(string because, Action configure) + { + var settings = AsyncMonolithSettings.Default; + configure(settings); + + Should.Throw(() => new ServiceCollection().InternalConfigureAsyncMonolithSettings(settings), + because); + } + + [Fact] + public void Boundary_settings_are_accepted() + { + var settings = new AsyncMonolithSettings + { + AttemptDelay = 0, + MaxAttempts = 1, + ProcessorMaxDelay = 1, + ProcessorMinDelay = 0, + ProcessorBatchSize = 1, + DefaultConsumerTimeout = 3600 + }; + var services = new ServiceCollection(); + + services.InternalConfigureAsyncMonolithSettings(settings); + + var configured = services.BuildServiceProvider().GetRequiredService>().Value; + configured.AttemptDelay.ShouldBe(0); + configured.MaxAttempts.ShouldBe(1); + configured.ProcessorMaxDelay.ShouldBe(1); + configured.ProcessorMinDelay.ShouldBe(0); + configured.ProcessorBatchSize.ShouldBe(1); + configured.DefaultConsumerTimeout.ShouldBe(3600); + } + + [Fact] + public void Default_settings_are_valid() + { + Should.NotThrow(() => + new ServiceCollection().InternalConfigureAsyncMonolithSettings(AsyncMonolithSettings.Default)); + } + + [Fact] + public void Consumer_attributes_are_read_at_registration() + { + var registry = Registry(); + + registry.ResolveConsumerTimeout(nameof(TimeoutConsumer)).ShouldBe(1); + registry.ResolveConsumerMaxAttempts(MessageFor(nameof(ExceptionConsumer2Attempts))).ShouldBe(2); + registry.ResolveConsumerExecutionMode(nameof(SequentialProbeConsumer)) + .ShouldBe(ConsumerInstanceExecutionMode.Sequential); + registry.ResolveConsumerRailId(nameof(RailConsumer2)).ShouldBe(2); + } + + [Fact] + public void Consumers_without_attributes_use_the_defaults() + { + var registry = Registry(s => + { + s.DefaultConsumerTimeout = 42; + s.MaxAttempts = 7; + }); + + registry.ResolveConsumerTimeout(nameof(ExceptionConsumer)).ShouldBe(42); + registry.ResolveConsumerMaxAttempts(MessageFor(nameof(ExceptionConsumer))).ShouldBe(7); + registry.ResolveConsumerExecutionMode(nameof(ExceptionConsumer)) + .ShouldBe(ConsumerInstanceExecutionMode.Parallel); + registry.ResolveConsumerRailId(nameof(ExceptionConsumer)).ShouldBe(0); + } + + [Fact] + public void Non_positive_attribute_values_fall_back_to_the_defaults() + { + var registry = Registry(s => + { + s.DefaultConsumerTimeout = 42; + s.MaxAttempts = 7; + }); + + registry.ResolveConsumerTimeout(nameof(InvalidAttributesConsumer)).ShouldBe(42); + registry.ResolveConsumerMaxAttempts(MessageFor(nameof(InvalidAttributesConsumer))).ShouldBe(7); + } + + [Fact] + public void Unknown_names_fall_back_or_throw() + { + var registry = Registry(s => + { + s.DefaultConsumerTimeout = 42; + s.MaxAttempts = 7; + }); + + Should.Throw(() => registry.ResolvePayloadConsumerTypes("UnknownPayload")); + Should.Throw(() => registry.ResolveConsumerType(MessageFor("UnknownConsumer"))); + registry.ResolveConsumerTimeout("UnknownConsumer").ShouldBe(42); + registry.ResolveConsumerMaxAttempts(MessageFor("UnknownConsumer")).ShouldBe(7); + registry.ResolveConsumerRailId("UnknownConsumer").ShouldBe(0); + registry.ResolveConsumerExecutionMode("UnknownConsumer").ShouldBe(ConsumerInstanceExecutionMode.Parallel); + } + + [Fact] + public void ResolveConsumerRailIds_returns_a_rail_per_consumer_in_order() + { + Registry().ResolveConsumerRailIds([nameof(RailConsumer2), nameof(RailConsumer0), nameof(RailConsumer1)]) + .ShouldBe([2, 0, 1]); + } + + [Fact] + public void Generated_ids_are_twelve_alphanumeric_characters() + { + var id = new AsyncMonolithIdGenerator().GenerateId(); + + id.Length.ShouldBe(12); + id.ShouldAllBe(c => char.IsAsciiLetterOrDigit(c)); + } + + [Fact] + public void Generated_ids_do_not_repeat() + { + var generator = new AsyncMonolithIdGenerator(); + + var ids = Enumerable.Range(0, 100_000).Select(_ => generator.GenerateId()).ToList(); + + ids.Distinct().Count().ShouldBe(ids.Count); + } + + [Fact] + public async Task BaseConsumer_deserializes_the_payload_for_the_typed_consumer() + { + var invocations = new TestConsumerInvocations(); + var consumer = new OrderedConsumer(invocations); + var message = MessageFor(nameof(OrderedConsumer)); + message.Payload = JsonSerializer.Serialize(new OrderedMessage { Name = "typed" }); + + await consumer.Consume(message, TestContext.Current.CancellationToken); + + invocations.Order.ShouldBe(["OrderedConsumer:typed"]); + } + + [Fact] + public async Task BaseConsumer_rejects_a_null_payload() + { + var consumer = new OrderedConsumer(new TestConsumerInvocations()); + var message = MessageFor(nameof(OrderedConsumer)); + message.Payload = "null"; + + var exception = await Should.ThrowAsync(() => + consumer.Consume(message, TestContext.Current.CancellationToken)); + exception.Message.ShouldContain(nameof(OrderedConsumer)); + } + + [Fact] + public void AddEfAsyncMonolith_registers_the_services_and_background_processors() + { + var services = new ServiceCollection(); + services.AddDbContext(_ => { }); + + services.AddEfAsyncMonolith(s => + { + s.RegisterTypesFromAssemblyContaining(); + s.MaxAttempts = 9; + }); + + services.ShouldContain(d => d.ServiceType == typeof(IProducerService) && + d.ImplementationType == typeof(EfProducerService)); + services.ShouldContain(d => d.ServiceType == typeof(IScheduleService) && + d.ImplementationType == typeof(ScheduleService)); + services.ShouldContain(d => d.ServiceType == typeof(IHostedService) && + d.ImplementationType == typeof(ScheduledMessageProcessor)); + services.Count(d => d.ServiceType == typeof(SingleConsumer)).ShouldBe(1); + + // The test assembly declares consumers on rails 0, 1 and 2, so a processor factory runs one per rail. + services.ShouldContain(d => d.ServiceType == typeof(IHostedService) && d.ImplementationFactory != null); + services.ShouldNotContain(d => d.ImplementationType == typeof(ConsumerMessageProcessor)); + + services.BuildServiceProvider().GetRequiredService>().Value.MaxAttempts + .ShouldBe(9); + } +} From 1a33dd76f91a9343dcfab76ab61b90827278459b Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:13:47 +0000 Subject: [PATCH 15/53] Fix TestConsumerMessageProcessor.ProcessNext for a single consumer ProcessNext filtered messages by the DbContext's type name instead of the consumer's, so it never found a message and always returned null. It now filters by and resolves TConsumer. The generic parameter is renamed from TPayload to TConsumer to match what it is. Adds tests for the TestHelpers package: the fake producer and schedule services, AssertSingleConsumerMessage/GetConsumerMessages, ProcessNext (both overloads) and Process. --- .../TestConsumerMessageProcessor.cs | 10 +- AsyncMonolith.Tests/TestHelpersTests.cs | 122 ++++++++++++++++++ 2 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 AsyncMonolith.Tests/TestHelpersTests.cs diff --git a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs index 9d50c96..d1d2d7c 100644 --- a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs +++ b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs @@ -56,19 +56,19 @@ public static class TestConsumerMessageProcessor } /// - /// Processes the next consumer message of type T and TPayload. + /// Processes the next message for the consumer . /// /// The type of DbContext. - /// The type of IConsumer. + /// The type of IConsumer. /// The service scope. /// The cancellation token. /// The processed consumer message, or null if no message is available. - public static async Task ProcessNext(IServiceScope scope, - CancellationToken cancellationToken = default) where T : DbContext where TPayload : IConsumer + public static async Task ProcessNext(IServiceScope scope, + CancellationToken cancellationToken = default) where T : DbContext where TConsumer : IConsumer { var dbContext = scope.ServiceProvider.GetRequiredService(); var consumerMessageSet = dbContext.Set(); - var consumerType = typeof(T); + var consumerType = typeof(TConsumer); var message = await consumerMessageSet .Where(m => m.ConsumerType == consumerType.Name) .OrderBy(m => m.AvailableAfter) diff --git a/AsyncMonolith.Tests/TestHelpersTests.cs b/AsyncMonolith.Tests/TestHelpersTests.cs new file mode 100644 index 0000000..acfd8b5 --- /dev/null +++ b/AsyncMonolith.Tests/TestHelpersTests.cs @@ -0,0 +1,122 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Producers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.TestHelpers; +using AsyncMonolith.Tests.Infra; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The shipped AsyncMonolith.TestHelpers package. +/// +public class TestHelpersTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ServiceProvider FakeServices() + { + var services = new ServiceCollection(); + services.AddSingleton(TimeProvider.System); + services.AddFakeAsyncMonolithBaseServices(s => s.RegisterTypesFromAssemblyContaining()); + return services.BuildServiceProvider(); + } + + [Fact] + public async Task FakeProducerService_records_a_message_per_consumer() + { + using var scope = FakeServices().CreateScope(); + var producer = (FakeProducerService)scope.ServiceProvider.GetRequiredService(); + + await producer.Produce(new MultiConsumerMessage { Name = "x" }, insertId: "insert", cancellationToken: Ct); + await producer.ProduceList([new RailConsumerMessage()], cancellationToken: Ct); + + producer.CreatedConsumerMessages.Select(m => m.ConsumerType).Order().ShouldBe([ + nameof(MultiConsumer1), nameof(MultiConsumer2), + nameof(RailConsumer0), nameof(RailConsumer1), nameof(RailConsumer2) + ]); + producer.CreatedConsumerMessages.Where(m => m.PayloadType == nameof(MultiConsumerMessage)) + .ShouldAllBe(m => m.InsertId == "insert"); + producer.CreatedConsumerMessages.Single(m => m.ConsumerType == nameof(RailConsumer2)).RailId.ShouldBe(2); + } + + [Fact] + public async Task FakeScheduleService_records_schedules_and_deletions() + { + using var scope = FakeServices().CreateScope(); + var schedules = (FakeScheduleService)scope.ServiceProvider.GetRequiredService(); + + var id = schedules.Schedule(new SingleConsumerMessage { Name = "x" }, "0 0 9 * * *", "UTC", "tag"); + await schedules.DeleteByTag("tag", Ct); + await schedules.DeleteById(id, Ct); + + var scheduled = schedules.CreatedScheduledMessages.ShouldHaveSingleItem(); + scheduled.Id.ShouldBe(id); + scheduled.Tag.ShouldBe("tag"); + schedules.DeletedScheduledMessageTags.ShouldBe(["tag"]); + schedules.DeletedScheduledMessageIds.ShouldBe([id]); + } + + [Fact] + public async Task AssertSingleConsumerMessage_finds_the_message_for_a_consumer() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MultiConsumerMessage { Name = "x" }); + + using var scope = host.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var message = await db.AssertSingleConsumerMessage( + new MultiConsumerMessage { Name = "x" }); + + message.ConsumerType.ShouldBe(nameof(MultiConsumer2)); + (await db.GetConsumerMessages()).Count.ShouldBe(2); + } + + [Fact] + public async Task ProcessNext_consumes_and_removes_the_next_message() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "x" }); + + using (var scope = host.Services.CreateScope()) + { + var processed = await TestConsumerMessageProcessor.ProcessNext(scope, Ct); + processed.ShouldNotBeNull().ConsumerType.ShouldBe(nameof(SingleConsumer)); + } + + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + (await host.ConsumerMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task ProcessNext_for_a_consumer_processes_only_that_consumers_message() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MultiConsumerMessage { Name = "x" }); + + using (var scope = host.Services.CreateScope()) + { + var processed = await TestConsumerMessageProcessor.ProcessNext(scope, Ct); + processed.ShouldNotBeNull().ConsumerType.ShouldBe(nameof(MultiConsumer2)); + } + + host.Invocations.GetInvocationCount(nameof(MultiConsumer1)).ShouldBe(0); + host.Invocations.GetInvocationCount(nameof(MultiConsumer2)).ShouldBe(1); + (await host.ConsumerMessages()).ShouldHaveSingleItem().ConsumerType.ShouldBe(nameof(MultiConsumer1)); + } + + [Fact] + public async Task Process_invokes_a_consumer_directly_with_a_payload() + { + await using var host = await SqliteTestHost.Create(); + using var scope = host.Services.CreateScope(); + + await TestConsumerMessageProcessor.Process( + scope, new OrderedMessage { Name = "direct" }, Ct); + + host.Invocations.Order.ShouldBe(["OrderedConsumer:direct"]); + (await host.ConsumerMessages()).ShouldBeEmpty(); + } +} From e7dc38b9e59ce49c60f11d97618ac60d44e57f1a Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:14:51 +0000 Subject: [PATCH 16/53] Add hosted end-to-end tests without Docker HostedProcessingTests starts a real generic host with AddEfAsyncMonolith, the background processors (one per rail plus the scheduler) and the real clock over a SQLite database file. It checks that a produced message is consumed, that every rail is consumed, that a failing message is poisoned, and that a schedule fires repeatedly. They take about 4 seconds in total, so they run with the fast tests. --- .../AsyncMonolith.Tests.csproj | 1 + AsyncMonolith.Tests/HostedProcessingTests.cs | 157 ++++++++++++++++++ Directory.Packages.props | 1 + 3 files changed, 159 insertions(+) create mode 100644 AsyncMonolith.Tests/HostedProcessingTests.cs diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index 46b185c..e631d31 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -12,6 +12,7 @@ + diff --git a/AsyncMonolith.Tests/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs new file mode 100644 index 0000000..605d116 --- /dev/null +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -0,0 +1,157 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Ef; +using AsyncMonolith.Producers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// End to end through a real generic host: AddEfAsyncMonolith, the background processors (one per rail plus +/// the scheduler), the real clock and a SQLite database file. No Docker, so these run with the fast tests. +/// +public sealed class HostedProcessingTests : IAsyncLifetime +{ + private static readonly TimeSpan WaitLimit = TimeSpan.FromSeconds(10); + private readonly string _path = Path.Combine(Path.GetTempPath(), $"asyncmonolith-host-{Guid.NewGuid():N}.db"); + private IHost _host = default!; + + private TestConsumerInvocations Invocations => _host.Services.GetRequiredService(); + + public ValueTask InitializeAsync() => ValueTask.CompletedTask; + + private async Task StartHost(Action? configure = null) + { + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={_path}")); + builder.Services.AddSingleton(TimeProvider.System); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddEfAsyncMonolith(s => + { + s.RegisterTypesFromAssemblyContaining(); + s.ProcessorMaxDelay = 50; + s.ProcessorMinDelay = 10; + configure?.Invoke(s); + }); + _host = builder.Build(); + + using (var scope = _host.Services.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + } + + await _host.StartAsync(TestContext.Current.CancellationToken); + } + + private async Task Produce(T payload) where T : IConsumerPayload + { + using var scope = _host.Services.CreateScope(); + await scope.ServiceProvider.GetRequiredService() + .Produce(payload, cancellationToken: TestContext.Current.CancellationToken); + await scope.ServiceProvider.GetRequiredService() + .SaveChangesAsync(TestContext.Current.CancellationToken); + } + + private async Task Query(Func> query) + { + using var scope = _host.Services.CreateScope(); + return await query(scope.ServiceProvider.GetRequiredService()); + } + + private static async Task WaitUntil(Func> condition, string what) + { + var deadline = DateTime.UtcNow + WaitLimit; + while (!await condition()) + { + if (DateTime.UtcNow > deadline) + { + throw new TimeoutException($"Timed out waiting until {what}"); + } + + await Task.Delay(20, TestContext.Current.CancellationToken); + } + } + + [Fact] + public async Task Produced_message_is_consumed_by_the_running_host() + { + await StartHost(); + + await Produce(new SingleConsumerMessage { Name = "hello" }); + + await WaitUntil(() => Query(db => db.ConsumerMessages.AnyAsync()).ContinueWith(t => !t.Result), + "the message is consumed"); + Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + } + + [Fact] + public async Task Messages_on_every_rail_are_consumed() + { + await StartHost(); + + await Produce(new RailConsumerMessage()); + + await WaitUntil(() => Task.FromResult( + Invocations.GetInvocationCount(nameof(RailConsumer0)) == 1 && + Invocations.GetInvocationCount(nameof(RailConsumer1)) == 1 && + Invocations.GetInvocationCount(nameof(RailConsumer2)) == 1), + "a consumer on each rail has run"); + } + + [Fact] + public async Task Failing_message_is_poisoned_by_the_running_host() + { + await StartHost(s => + { + s.MaxAttempts = 2; + s.AttemptDelay = 0; + }); + + await Produce(new ExceptionConsumerMessage { Name = "boom" }); + + await WaitUntil(() => Query(db => db.PoisonedMessages.AnyAsync()), "the message is poisoned"); + Invocations.GetInvocationCount(nameof(ExceptionConsumer)).ShouldBe(2); + (await Query(db => db.ConsumerMessages.CountAsync())).ShouldBe(0); + } + + [Fact] + public async Task Scheduled_message_fires_repeatedly_on_the_running_host() + { + await StartHost(); + + using (var scope = _host.Services.CreateScope()) + { + scope.ServiceProvider.GetRequiredService() + .Schedule(new SingleConsumerMessage { Name = "tick" }, "* * * * * *", "UTC"); + await scope.ServiceProvider.GetRequiredService() + .SaveChangesAsync(TestContext.Current.CancellationToken); + } + + await WaitUntil(() => Task.FromResult(Invocations.GetInvocationCount(nameof(SingleConsumer)) >= 2), + "the schedule has fired twice"); + } + + public async ValueTask DisposeAsync() + { + if (_host is not null) + { + await _host.StopAsync(CancellationToken.None); + _host.Dispose(); + } + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + foreach (var file in new[] { _path, _path + "-journal", _path + "-wal", _path + "-shm" }) + { + if (File.Exists(file)) + { + File.Delete(file); + } + } + } +} diff --git a/Directory.Packages.props b/Directory.Packages.props index 946ea42..8822bad 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -24,6 +24,7 @@ + From 0a09d123629fc3201316f0e13535887dfb2238c1 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:20:05 +0000 Subject: [PATCH 17/53] Let consumers write to the database on SQLite The consumer processor held one transaction open while every consumer in the batch ran. On SQLite that transaction holds the database's only write lock, so a consumer that wrote to the database waited for the lock, timed out and was eventually poisoned. Most real consumers write. Batches are now processed in three steps: 1. Claim: one short transaction fetches the batch, counts the attempt and leases each message by moving AvailableAfter past the consumer timeout plus a 30 second grace period. The provider fetchers still lock rows while claiming. 2. Consume: consumers run outside any transaction. 3. Complete: each message is deleted, rescheduled or poisoned in its own short write, guarded by its lease so a message another processor has since re-claimed is left alone. If a processor stops mid-batch, its messages become available again when the lease expires, and the interrupted attempt counts towards max attempts. Also disposes the per-message timeout CancellationTokenSource and records the exception's type name in the trace instead of the literal "ex". Tests cover a writing consumer (in a batch and on a running host), lease expiry after a crash, and a completed message whose lease was taken over. --- .../ConsumerProcessingTests.cs | 49 +++++ AsyncMonolith.Tests/HostedProcessingTests.cs | 14 ++ AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 58 ++++-- AsyncMonolith.Tests/Infra/WritingConsumer.cs | 35 ++++ .../Consumers/ConsumerMessageProcessor.cs | 175 +++++++++++------- 5 files changed, 254 insertions(+), 77 deletions(-) create mode 100644 AsyncMonolith.Tests/Infra/WritingConsumer.cs diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs index 3d05da2..b549961 100644 --- a/AsyncMonolith.Tests/ConsumerProcessingTests.cs +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -268,4 +268,53 @@ public async Task Sequential_consumers_in_a_batch_run_one_at_a_time() host.Services.GetRequiredService().Max.ShouldBe(1); } + + [Fact] + public async Task Consumer_that_writes_to_the_database_succeeds_on_sqlite() + { + // Each DbContext has its own connection, as in a real host. The batch must not hold the + // database's write lock while consumers run. + await using var host = await SqliteTestHost.Create(fileDatabase: true); + await host.Produce(new WritingConsumerMessage { Name = "follow-up" }); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + + (await host.PoisonedMessages()).ShouldBeEmpty(); + (await host.ConsumerMessages()).ShouldHaveSingleItem().ConsumerType.ShouldBe(nameof(SingleConsumer)); + } + + [Fact] + public async Task Claimed_message_is_leased_so_other_processors_skip_it() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new TimeoutConsumerMessage { Delay = 0 }); + + // Simulate a processor that claimed the message and then crashed before finishing it. + var claimed = await host.ConsumerProcessor.ClaimBatch(Ct); + claimed.ShouldHaveSingleItem().Attempts.ShouldBe(1); + + // While the lease (consumer timeout + grace period) is held, nobody else picks it up. + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); + host.Invocations.GetInvocationCount(nameof(TimeoutConsumer)).ShouldBe(0); + + // Once the lease expires, the message is processed again and the crashed attempt counts. + host.Time.Advance(TimeSpan.FromSeconds(1 + ConsumerMessageProcessor.LeaseGracePeriodSeconds)); + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(TimeoutConsumer)).ShouldBe(1); + } + + [Fact] + public async Task Completing_a_message_whose_lease_was_taken_over_leaves_it_alone() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "a" }); + var claimed = (await host.ConsumerProcessor.ClaimBatch(Ct)).ShouldHaveSingleItem(); + + // Another processor re-claimed the message after our lease expired. + await host.Change(db => db.ConsumerMessages.Single().AvailableAfter = claimed.AvailableAfter + 100); + + await host.ConsumerProcessor.Complete(claimed, success: true, Ct); + + (await host.ConsumerMessages()).ShouldHaveSingleItem(); + } } diff --git a/AsyncMonolith.Tests/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs index 605d116..deddc82 100644 --- a/AsyncMonolith.Tests/HostedProcessingTests.cs +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -90,6 +90,20 @@ await WaitUntil(() => Query(db => db.ConsumerMessages.AnyAsync()).ContinueWith(t Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); } + [Fact] + public async Task Consumer_can_write_to_the_database_and_chain_another_message() + { + await StartHost(); + + await Produce(new WritingConsumerMessage { Name = "chained" }); + + await WaitUntil(() => Task.FromResult(Invocations.GetInvocationCount(nameof(SingleConsumer)) == 1), + "the chained message is consumed"); + (await Query(db => db.PoisonedMessages.CountAsync())).ShouldBe(0); + await WaitUntil(() => Query(db => db.ConsumerMessages.AnyAsync()).ContinueWith(t => !t.Result), + "the queue is empty"); + } + [Fact] public async Task Messages_on_every_rail_are_consumed() { diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs index 38d1da7..7274b80 100644 --- a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -15,17 +15,20 @@ namespace AsyncMonolith.Tests.Infra; /// and no Docker. /// /// -/// All DbContexts share one open connection, so consumers used with this host must not write to the -/// database while a batch is being processed. +/// By default all DbContexts share one open in-memory connection, so consumers must not write to the +/// database while a batch is being processed. Pass fileDatabase: true to give every DbContext its +/// own connection to a temporary database file, as in a real host. /// public sealed class SqliteTestHost : IAsyncDisposable { - private readonly SqliteConnection _connection; + private readonly SqliteConnection? _connection; + private readonly string? _path; - private SqliteTestHost(SqliteConnection connection, ServiceProvider services, FakeTimeProvider time, - TestConsumerInvocations invocations) + private SqliteTestHost(SqliteConnection? connection, string? path, ServiceProvider services, + FakeTimeProvider time, TestConsumerInvocations invocations) { _connection = connection; + _path = path; Services = services; Time = time; Invocations = invocations; @@ -43,16 +46,37 @@ private SqliteTestHost(SqliteConnection connection, ServiceProvider services, Fa public ScheduledMessageProcessor ScheduledProcessor => Services.GetRequiredService>(); - public static async Task Create(Action? configure = null) + public static async Task Create(Action? configure = null, + bool fileDatabase = false) { - var connection = new SqliteConnection("DataSource=:memory:"); - await connection.OpenAsync(); + SqliteConnection? connection = null; + string? path = null; + if (fileDatabase) + { + path = Path.Combine(Path.GetTempPath(), $"asyncmonolith-{Guid.NewGuid():N}.db"); + } + else + { + connection = new SqliteConnection("DataSource=:memory:"); + await connection.OpenAsync(); + } var settings = AsyncMonolithSettings.Default; configure?.Invoke(settings); var services = new ServiceCollection(); - services.AddDbContext(options => options.UseSqlite(connection)); + services.AddDbContext(options => + { + if (connection is not null) + { + options.UseSqlite(connection); + } + else + { + // A short busy timeout makes lock contention fail fast instead of waiting 30 seconds. + options.UseSqlite($"Data Source={path};Default Timeout=3"); + } + }); var (time, invocations) = services.AddTestServices(DbType.Ef, settings); services.AddSingleton>(); services.AddSingleton>(); @@ -64,7 +88,7 @@ public static async Task Create(Action? c await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(); } - return new SqliteTestHost(connection, provider, time, invocations); + return new SqliteTestHost(connection, path, provider, time, invocations); } /// Produces a message in its own scope and saves it. @@ -115,6 +139,18 @@ public Task> ScheduledMessages() => public async ValueTask DisposeAsync() { await Services.DisposeAsync(); - await _connection.DisposeAsync(); + if (_connection is not null) + { + await _connection.DisposeAsync(); + } + + if (_path is not null) + { + SqliteConnection.ClearAllPools(); + foreach (var file in new[] { _path, _path + "-journal", _path + "-wal", _path + "-shm" }) + { + File.Delete(file); + } + } } } diff --git a/AsyncMonolith.Tests/Infra/WritingConsumer.cs b/AsyncMonolith.Tests/Infra/WritingConsumer.cs new file mode 100644 index 0000000..64b4340 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/WritingConsumer.cs @@ -0,0 +1,35 @@ +using System.Text.Json.Serialization; +using AsyncMonolith.Consumers; +using AsyncMonolith.Producers; + +namespace AsyncMonolith.Tests.Infra; + +public class WritingConsumerMessage : IConsumerPayload +{ + [JsonPropertyName("name")] public required string Name { get; set; } +} + +/// +/// A consumer that writes to the database, as most real consumers do +/// (here by producing a follow-up message and saving it). +/// +[ConsumerTimeout(10)] +[ConsumerAttempts(1)] +public class WritingConsumer : BaseConsumer +{ + private readonly TestDbContext _dbContext; + private readonly IProducerService _producer; + + public WritingConsumer(TestDbContext dbContext, IProducerService producer) + { + _dbContext = dbContext; + _producer = producer; + } + + public override async Task Consume(WritingConsumerMessage message, CancellationToken cancellationToken) + { + await _producer.Produce(new SingleConsumerMessage { Name = message.Name }, + cancellationToken: cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 4fafcb1..ed5c8f6 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -86,105 +86,148 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } /// - /// Fetch and Processes the next batch of consumer messages. + /// Seconds a claimed message stays leased beyond its consumer timeout. If a processor stops before + /// finishing a message, the message becomes available again once the lease runs out. /// + internal const int LeaseGracePeriodSeconds = 30; + + /// + /// Claims and processes the next batch of consumer messages. + /// + /// + /// Messages are claimed in one short transaction: each is leased by moving its AvailableAfter past + /// the consumer timeout, and the attempt is counted. Consumers then run outside any transaction, so + /// they can write to the database freely (SQLite allows only one writer at a time). Each message is + /// then completed in its own short write, guarded by its lease. + /// /// The cancellation token to stop the execution. - /// The number of processed messages. + /// The number of messages processed successfully. internal async Task ProcessBatch(CancellationToken cancellationToken) { - using var scope = _scopeFactory.CreateScope(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - await using var dbContextTransaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); - var consumerSet = dbContext.Set(); - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var messages = await _consumerMessageFetcher.Fetch(consumerSet, currentTime, _railId, cancellationToken); - + var messages = await ClaimBatch(cancellationToken); if (messages.Count == 0) { return 0; } - - var tasks = new List>>(); + var tasks = new List>>(); foreach (var consumerMessageGroup in messages.GroupBy(m => m.ConsumerType)) { - var group = consumerMessageGroup.ToList(); // materialize to avoid deferred execution + var group = consumerMessageGroup.ToList(); var executionMode = _consumerRegistry.ResolveConsumerExecutionMode(consumerMessageGroup.Key); if (executionMode == ConsumerInstanceExecutionMode.Parallel) { // Parallel: all messages in the group are processed concurrently - tasks.Add(Task.WhenAll(group.Select(m => Process(m, cancellationToken))) - .ContinueWith(t => t.Result.ToList(), cancellationToken)); + tasks.Add(Task.WhenAll(group.Select(m => ProcessAndComplete(m, cancellationToken))) + .ContinueWith(t => t.Result.ToList(), cancellationToken, TaskContinuationOptions.None, + TaskScheduler.Default)); } else { // Sequential: one message at a time in order tasks.Add(Task.Run(async () => { - var results = new List<(ConsumerMessage message, bool success)>(); + var results = new List(); foreach (var message in group) { - var result = await Process(message, cancellationToken); - results.Add(result); + results.Add(await ProcessAndComplete(message, cancellationToken)); } + return results; }, cancellationToken)); } } - // Wait for all group tasks (whether parallel or sequential within) - var allResults = (await Task.WhenAll(tasks)).SelectMany(r => r).ToList(); - - var processedMessageCount = 0; - foreach (var (message, success) in allResults) + return (await Task.WhenAll(tasks)).SelectMany(r => r).Count(success => success); + } + + /// + /// Fetches the next batch for this rail and leases it in one short transaction. + /// + /// The claimed messages, with their attempt counted and their lease in AvailableAfter. + internal async Task> ClaimBatch(CancellationToken cancellationToken) + { + using var scope = _scopeFactory.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); + + var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); + var messages = await _consumerMessageFetcher.Fetch(dbContext.Set(), currentTime, _railId, + cancellationToken); + if (messages.Count == 0) { - if (success) - { - processedMessageCount++; - // Remove the message - consumerSet.Remove(message); - } - else - { - // Increment the number of attempts - message.Attempts++; - if (message.Attempts < _consumerRegistry.ResolveConsumerMaxAttempts(message)) - { - // Retry the message after a delay - message.AvailableAfter = - _timeProvider.GetUtcNow().ToUnixTimeSeconds() + _options.Value.AttemptDelay; - } - else - { - // Move the message into the poisoned message table - consumerSet.Remove(message); - var poisonedSet = dbContext.Set(); - poisonedSet.Add(new PoisonedMessage - { - Id = message.Id, - Attempts = message.Attempts, - AvailableAfter = message.AvailableAfter, - ConsumerType = message.ConsumerType, - CreatedAt = message.CreatedAt, - Payload = message.Payload, - PayloadType = message.PayloadType, - InsertId = message.InsertId, - TraceId = message.TraceId, - SpanId = message.SpanId, - RailId = message.RailId, - }); - } - } + return messages; + } + + foreach (var message in messages) + { + message.Attempts++; + message.AvailableAfter = currentTime + _consumerRegistry.ResolveConsumerTimeout(message) + + LeaseGracePeriodSeconds; } - // Save changes to the message tables await dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + return messages; + } + + private async Task ProcessAndComplete(ConsumerMessage message, CancellationToken cancellationToken) + { + var (_, success) = await Process(message, cancellationToken); + + // Record the outcome even when stopping, so the attempt isn't left waiting for its lease to expire. + await Complete(message, success, CancellationToken.None); + return success; + } + + /// + /// Records the outcome of a claimed message: removes it on success, otherwise schedules a retry or + /// moves it to the poisoned messages. Does nothing if the lease has since been taken over. + /// + internal async Task Complete(ConsumerMessage message, bool success, CancellationToken cancellationToken) + { + using var scope = _scopeFactory.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var leased = dbContext.Set() + .Where(m => m.Id == message.Id && m.AvailableAfter == message.AvailableAfter); - // Commit transaction - await dbContextTransaction.CommitAsync(cancellationToken); + if (success) + { + await leased.ExecuteDeleteAsync(cancellationToken); + return; + } - return processedMessageCount; + if (message.Attempts < _consumerRegistry.ResolveConsumerMaxAttempts(message)) + { + var retryAt = _timeProvider.GetUtcNow().ToUnixTimeSeconds() + _options.Value.AttemptDelay; + await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryAt), + cancellationToken); + return; + } + + await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); + if (await leased.ExecuteDeleteAsync(cancellationToken) == 0) + { + return; + } + + dbContext.Set().Add(new PoisonedMessage + { + Id = message.Id, + Attempts = message.Attempts, + AvailableAfter = message.AvailableAfter, + ConsumerType = message.ConsumerType, + CreatedAt = message.CreatedAt, + Payload = message.Payload, + PayloadType = message.PayloadType, + InsertId = message.InsertId, + TraceId = message.TraceId, + SpanId = message.SpanId, + RailId = message.RailId + }); + await dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); } private static Activity? StartActivity(ConsumerMessage message) @@ -219,7 +262,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) using var activity = StartActivity(message); activity?.AddTag("consumer_message.id", message.Id); - activity?.AddTag("consumer_message.attempt", message.Attempts + 1); + activity?.AddTag("consumer_message.attempt", message.Attempts); activity?.AddTag("consumer_message.payload.type", message.PayloadType); activity?.AddTag("consumer_message.type", message.ConsumerType); @@ -228,7 +271,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) var consumerType = _consumerRegistry.ResolveConsumerType(message); var consumerTimeout = _consumerRegistry.ResolveConsumerTimeout(message); - var timeoutCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using var timeoutCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeoutCancellationToken.CancelAfter(TimeSpan.FromSeconds(consumerTimeout)); using var scope = _scopeFactory.CreateScope(); @@ -250,7 +293,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) catch (Exception ex) { activity?.SetStatus(ActivityStatusCode.Error, ex.Message); - activity?.AddTag("exception.type", nameof(ex)); + activity?.AddTag("exception.type", ex.GetType().FullName); activity?.AddTag("exception.message", ex.Message); _logger.ConsumerMessageFailed(ex, message.Attempts); } From 7a5ebf27d22dd6be08a92f660d98f0a9545ef6c5 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:23:00 +0000 Subject: [PATCH 18/53] Add stable payload and consumer names, and fail on name clashes Messages were keyed by the short class name. Two payloads with the same class name in different namespaces were silently merged, so each was delivered to the other's consumers and deserialized into the wrong type. - [ConsumerPayloadName("...")] and [ConsumerName("...")] set the name stored in payload_type and consumer_type. Without them the class name is still used, so stored messages and schedules keep working. - AsyncMonolithNames.ForPayload/ForConsumer resolve names for the core, every provider and TestHelpers. - Registration fails at startup when two payloads or two consumers share a stored name, naming both types and the attribute that fixes it. Tests cover default and attribute names, blank names, producing, consuming and scheduling named messages, and clashes using types emitted at runtime. --- AsyncMonolith.Ef/EfProducerService.cs | 4 +- .../MariaDbProducerService.cs | 4 +- AsyncMonolith.MsSql/MsSqlProducerService.cs | 4 +- AsyncMonolith.MySql/MySqlProducerService.cs | 4 +- .../PostgreSqlProducerService.cs | 4 +- .../ConsumerMessageTestHelpers.cs | 30 +++-- .../FakeProducerService.cs | 4 +- .../FakeScheduleService.cs | 2 +- .../TestConsumerMessageProcessor.cs | 6 +- AsyncMonolith.Tests/Infra/NamedConsumers.cs | 70 ++++++++++++ AsyncMonolith.Tests/NamingTests.cs | 108 ++++++++++++++++++ AsyncMonolith/Consumers/AsyncMonolithNames.cs | 79 +++++++++++++ AsyncMonolith/Scheduling/ScheduleService.cs | 2 +- AsyncMonolith/Scheduling/ScheduledMessage.cs | 2 +- AsyncMonolith/Utilities/StartupExtensions.cs | 38 ++++-- docs/guides/changing-messages.md | 18 +++ 16 files changed, 341 insertions(+), 38 deletions(-) create mode 100644 AsyncMonolith.Tests/Infra/NamedConsumers.cs create mode 100644 AsyncMonolith.Tests/NamingTests.cs create mode 100644 AsyncMonolith/Consumers/AsyncMonolithNames.cs diff --git a/AsyncMonolith.Ef/EfProducerService.cs b/AsyncMonolith.Ef/EfProducerService.cs index 4cb5da6..222b9de 100644 --- a/AsyncMonolith.Ef/EfProducerService.cs +++ b/AsyncMonolith.Ef/EfProducerService.cs @@ -52,7 +52,7 @@ public Task Produce(TK message, long? availableAfter = null, string? insertI availableAfter ??= currentTime; var payload = JsonSerializer.Serialize(message); insertId ??= _idGenerator.GenerateId(); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var set = _dbContext.Set(); var traceId = Activity.Current?.TraceId.ToString(); var spanId = Activity.Current?.SpanId.ToString(); @@ -93,7 +93,7 @@ public Task ProduceList(List messages, long? availableAfter = null, availableAfter ??= currentTime; var set = _dbContext.Set(); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); var traceId = Activity.Current?.TraceId.ToString(); var spanId = Activity.Current?.SpanId.ToString(); diff --git a/AsyncMonolith.MariaDb/MariaDbProducerService.cs b/AsyncMonolith.MariaDb/MariaDbProducerService.cs index 4f98c1c..6799940 100644 --- a/AsyncMonolith.MariaDb/MariaDbProducerService.cs +++ b/AsyncMonolith.MariaDb/MariaDbProducerService.cs @@ -54,7 +54,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); availableAfter ??= currentTime; var payload = JsonSerializer.Serialize(message); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); insertId ??= _idGenerator.GenerateId(); var traceId = Activity.Current?.TraceId.ToString(); var spanId = Activity.Current?.SpanId.ToString(); @@ -122,7 +122,7 @@ public async Task ProduceList(List messages, long? availableAfter = null new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) }; - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); for (var i = 0; i < messages.Count; i++) diff --git a/AsyncMonolith.MsSql/MsSqlProducerService.cs b/AsyncMonolith.MsSql/MsSqlProducerService.cs index 507ec33..2d4db64 100644 --- a/AsyncMonolith.MsSql/MsSqlProducerService.cs +++ b/AsyncMonolith.MsSql/MsSqlProducerService.cs @@ -54,7 +54,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); availableAfter ??= currentTime; var payload = JsonSerializer.Serialize(message); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); insertId ??= _idGenerator.GenerateId(); var traceId = Activity.Current?.TraceId.ToString(); var spanId = Activity.Current?.SpanId.ToString(); @@ -125,7 +125,7 @@ public async Task ProduceList(List messages, long? availableAfter = null new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) }; - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); diff --git a/AsyncMonolith.MySql/MySqlProducerService.cs b/AsyncMonolith.MySql/MySqlProducerService.cs index 3c3d549..fb5c347 100644 --- a/AsyncMonolith.MySql/MySqlProducerService.cs +++ b/AsyncMonolith.MySql/MySqlProducerService.cs @@ -54,7 +54,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); availableAfter ??= currentTime; var payload = JsonSerializer.Serialize(message); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); insertId ??= _idGenerator.GenerateId(); var traceId = Activity.Current?.TraceId.ToString(); var spanId = Activity.Current?.SpanId.ToString(); @@ -122,7 +122,7 @@ public async Task ProduceList(List messages, long? availableAfter = null new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) }; - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); diff --git a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs b/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs index 489799d..02d8dd9 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs @@ -57,7 +57,7 @@ public async Task Produce(TK message, long? availableAfter = null, string? i var traceId = Activity.Current?.TraceId.ToString(); var spanId = Activity.Current?.SpanId.ToString(); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); insertId ??= _idGenerator.GenerateId(); var sqlBuilder = new StringBuilder(); @@ -124,7 +124,7 @@ public async Task ProduceList(List messages, long? availableAfter = null new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) }; - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); diff --git a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs index 7487c96..e85e1e8 100644 --- a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs @@ -21,9 +21,10 @@ public static async Task> GetConsumerMessages(this DbCo where T : IConsumerPayload { var payloadType = typeof(T); + var payloadName = AsyncMonolithNames.ForPayload(payloadType); return await dbContext.Set() .Where(m => - m.PayloadType == payloadType.Name) + m.PayloadType == payloadName) .ToListAsync(); } @@ -38,11 +39,13 @@ public static async Task> GetConsumerMessages where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); + var consumerName = AsyncMonolithNames.ForConsumer(consumerType); var payloadType = typeof(TPayload); + var payloadName = AsyncMonolithNames.ForPayload(payloadType); return await dbContext.Set() .Where(m => - m.ConsumerType == consumerType.Name && - m.PayloadType == payloadType.Name) + m.ConsumerType == consumerName && + m.PayloadType == payloadName) .ToListAsync(); } @@ -58,12 +61,14 @@ public static async Task> GetConsumerMessages where T : BaseConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); + var consumerName = AsyncMonolithNames.ForConsumer(consumerType); var payloadType = typeof(TPayload); + var payloadName = AsyncMonolithNames.ForPayload(payloadType); var serializedPayload = JsonSerializer.Serialize(payload); return await dbContext.Set() .Where(m => - m.ConsumerType == consumerType.Name && - m.PayloadType == payloadType.Name && + m.ConsumerType == consumerName && + m.PayloadType == payloadName && m.Payload == serializedPayload) .ToListAsync(); } @@ -80,12 +85,14 @@ public static async Task AssertSingleConsumerMessage where TPayload : IConsumerPayload { var consumerType = typeof(T); + var consumerName = AsyncMonolithNames.ForConsumer(consumerType); var payloadType = typeof(TPayload); + var payloadName = AsyncMonolithNames.ForPayload(payloadType); var serializedPayload = JsonSerializer.Serialize(payload); var messages = await dbContext.Set() .Where(m => - m.ConsumerType == consumerType.Name && - m.PayloadType == payloadType.Name && + m.ConsumerType == consumerName && + m.PayloadType == payloadName && m.Payload == serializedPayload) .ToListAsync(); @@ -103,10 +110,11 @@ public static async Task AssertSingleScheduledMessage(this where T : IConsumerPayload { var payloadType = typeof(T); + var payloadName = AsyncMonolithNames.ForPayload(payloadType); var serializedPayload = JsonSerializer.Serialize(payload); var messages = await dbContext.Set() .Where(m => - m.PayloadType == payloadType.Name && + m.PayloadType == payloadName && m.Payload == serializedPayload) .ToListAsync(); @@ -126,12 +134,14 @@ public static async Task AssertSingleConsumerMessageById where TPayload : IConsumerPayload { var consumerType = typeof(T); + var consumerName = AsyncMonolithNames.ForConsumer(consumerType); var payloadType = typeof(TPayload); + var payloadName = AsyncMonolithNames.ForPayload(payloadType); var serializedPayload = JsonSerializer.Serialize(payload); var messages = await dbContext.Set() .Where(m => - m.ConsumerType == consumerType.Name && - m.PayloadType == payloadType.Name && + m.ConsumerType == consumerName && + m.PayloadType == payloadName && m.Payload == serializedPayload && m.Id == id) .ToListAsync(); diff --git a/AsyncMonolith.TestHelpers/FakeProducerService.cs b/AsyncMonolith.TestHelpers/FakeProducerService.cs index e90c8ba..9470b19 100644 --- a/AsyncMonolith.TestHelpers/FakeProducerService.cs +++ b/AsyncMonolith.TestHelpers/FakeProducerService.cs @@ -51,7 +51,7 @@ public Task Produce(TK message, long? availableAfter = null, string? insertI availableAfter ??= currentTime; var payload = JsonSerializer.Serialize(message); insertId ??= _idGenerator.GenerateId(); - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(payloadType)) { @@ -88,7 +88,7 @@ public Task ProduceList(List messages, long? availableAfter = null, var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); availableAfter ??= currentTime; - var payloadType = typeof(TK).Name; + var payloadType = AsyncMonolithNames.ForPayload(); var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); foreach (var message in messages) { diff --git a/AsyncMonolith.TestHelpers/FakeScheduleService.cs b/AsyncMonolith.TestHelpers/FakeScheduleService.cs index f0f40f5..6914716 100644 --- a/AsyncMonolith.TestHelpers/FakeScheduleService.cs +++ b/AsyncMonolith.TestHelpers/FakeScheduleService.cs @@ -75,7 +75,7 @@ public string Schedule(TK message, string chronExpression, string chronTimez CreatedScheduledMessages.Add(new ScheduledMessage { Id = id, - PayloadType = typeof(TK).Name, + PayloadType = AsyncMonolithNames.ForPayload(), AvailableAfter = next.Value.ToUnixTimeSeconds(), Tag = tag, ChronExpression = chronExpression, diff --git a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs index d1d2d7c..9753b9e 100644 --- a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs +++ b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs @@ -70,7 +70,7 @@ public static class TestConsumerMessageProcessor var consumerMessageSet = dbContext.Set(); var consumerType = typeof(TConsumer); var message = await consumerMessageSet - .Where(m => m.ConsumerType == consumerType.Name) + .Where(m => m.ConsumerType == AsyncMonolithNames.ForConsumer(consumerType)) .OrderBy(m => m.AvailableAfter) .ThenBy(m => m.CreatedAt) .FirstOrDefaultAsync(cancellationToken); @@ -125,12 +125,12 @@ await consumer.Consume(new ConsumerMessage { Attempts = 0, AvailableAfter = 0, - ConsumerType = consumerType.Name, + ConsumerType = AsyncMonolithNames.ForConsumer(consumerType), CreatedAt = 0, Id = string.Empty, InsertId = string.Empty, Payload = JsonSerializer.Serialize(payload), - PayloadType = typeof(TPayload).Name, + PayloadType = AsyncMonolithNames.ForPayload(), TraceId = null, SpanId = null, RailId = 0 diff --git a/AsyncMonolith.Tests/Infra/NamedConsumers.cs b/AsyncMonolith.Tests/Infra/NamedConsumers.cs new file mode 100644 index 0000000..ffd9a7d --- /dev/null +++ b/AsyncMonolith.Tests/Infra/NamedConsumers.cs @@ -0,0 +1,70 @@ +using System.Reflection; +using System.Reflection.Emit; +using System.Text.Json.Serialization; +using AsyncMonolith.Consumers; + +namespace AsyncMonolith.Tests.Infra; + +[ConsumerPayloadName("tests.named.payload")] +public class NamedMessage : IConsumerPayload +{ + [JsonPropertyName("name")] public required string Name { get; set; } +} + +[ConsumerName("tests.named.consumer")] +public class NamedConsumer(TestConsumerInvocations invocations) : BaseConsumer +{ + public override Task Consume(NamedMessage payload, CancellationToken cancellationToken) + { + invocations.Increment(nameof(NamedConsumer)); + return Task.CompletedTask; + } +} + +/// +/// Builds assemblies at runtime whose payload or consumer names clash, as two modules might. +/// They can't live in the test assembly, because every test registers all of its types. +/// +public static class ClashingTypes +{ + /// One payload and one consumer are emitted per namespace. + /// Class name for every consumer, or null to make them unique. + /// Optional [ConsumerPayloadName] value per namespace. + public static Assembly Build(string[] namespaces, string? consumerName = null, + string?[]? payloadNameAttributes = null) + { + var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"Clashing{Guid.NewGuid():N}"), + AssemblyBuilderAccess.Run); + var module = assembly.DefineDynamicModule("Clashing"); + + for (var i = 0; i < namespaces.Length; i++) + { + var payloadBuilder = module.DefineType($"{namespaces[i]}.SendEmail", + TypeAttributes.Public | TypeAttributes.Class, typeof(object), [typeof(IConsumerPayload)]); + payloadBuilder.DefineDefaultConstructor(MethodAttributes.Public); + if (payloadNameAttributes?[i] is { } payloadName) + { + payloadBuilder.SetCustomAttribute(new CustomAttributeBuilder( + typeof(ConsumerPayloadNameAttribute).GetConstructor([typeof(string)])!, [payloadName])); + } + + var payload = payloadBuilder.CreateType(); + + var baseType = typeof(BaseConsumer<>).MakeGenericType(payload); + var consumerBuilder = module.DefineType($"{namespaces[i]}.{consumerName ?? $"SendEmailConsumer{i}"}", + TypeAttributes.Public | TypeAttributes.Class, baseType); + consumerBuilder.DefineDefaultConstructor(MethodAttributes.Public); + var consume = consumerBuilder.DefineMethod("Consume", + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + typeof(Task), [payload, typeof(CancellationToken)]); + var il = consume.GetILGenerator(); + il.Emit(OpCodes.Call, typeof(Task).GetProperty(nameof(Task.CompletedTask))!.GetMethod!); + il.Emit(OpCodes.Ret); + consumerBuilder.DefineMethodOverride(consume, + baseType.GetMethod("Consume", [payload, typeof(CancellationToken)])!); + consumerBuilder.CreateType(); + } + + return assembly; + } +} diff --git a/AsyncMonolith.Tests/NamingTests.cs b/AsyncMonolith.Tests/NamingTests.cs new file mode 100644 index 0000000..5cadd16 --- /dev/null +++ b/AsyncMonolith.Tests/NamingTests.cs @@ -0,0 +1,108 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Stored payload and consumer names, and name clashes caught at startup. +/// +public class NamingTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static void Register(params System.Reflection.Assembly[] assemblies) + { + var settings = AsyncMonolithSettings.Default; + settings.RegisterTypesFromAssemblies(assemblies); + new ServiceCollection().InternalRegisterAsyncMonolithConsumers(settings); + } + + [Fact] + public void Names_default_to_the_class_name() + { + AsyncMonolithNames.ForPayload().ShouldBe(nameof(SingleConsumerMessage)); + AsyncMonolithNames.ForConsumer().ShouldBe(nameof(SingleConsumer)); + } + + [Fact] + public void Attributes_override_the_stored_names() + { + AsyncMonolithNames.ForPayload().ShouldBe("tests.named.payload"); + AsyncMonolithNames.ForConsumer().ShouldBe("tests.named.consumer"); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Blank_names_are_rejected(string name) + { + Should.Throw(() => new ConsumerPayloadNameAttribute(name)); + Should.Throw(() => new ConsumerNameAttribute(name)); + } + + [Fact] + public async Task Named_messages_are_stored_and_consumed_by_their_stored_names() + { + await using var host = await SqliteTestHost.Create(); + + await host.Produce(new NamedMessage { Name = "x" }); + + var message = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + message.PayloadType.ShouldBe("tests.named.payload"); + message.ConsumerType.ShouldBe("tests.named.consumer"); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + host.Invocations.GetInvocationCount(nameof(NamedConsumer)).ShouldBe(1); + } + + [Fact] + public async Task Named_schedules_are_stored_and_produced_by_their_stored_names() + { + await using var host = await SqliteTestHost.Create(); + + await host.Schedule(new NamedMessage { Name = "x" }, "0 * * * * *"); + (await host.ScheduledMessages()).ShouldHaveSingleItem().PayloadType.ShouldBe("tests.named.payload"); + + host.Time.Advance(TimeSpan.FromMinutes(1)); + await host.ScheduledProcessor.ProcessBatch(Ct); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().ConsumerType.ShouldBe("tests.named.consumer"); + } + + [Fact] + public void Payloads_with_the_same_class_name_in_different_namespaces_fail_at_startup() + { + var assembly = ClashingTypes.Build(["ModuleA", "ModuleB"]); + + var exception = Should.Throw(() => Register(assembly)); + + exception.Message.ShouldContain("ModuleA.SendEmail"); + exception.Message.ShouldContain("ModuleB.SendEmail"); + exception.Message.ShouldContain("[ConsumerPayloadName]"); + } + + [Fact] + public void Payload_name_attributes_resolve_a_class_name_clash() + { + var assembly = ClashingTypes.Build(["ModuleA", "ModuleB"], + payloadNameAttributes: ["module-a.send-email", "module-b.send-email"]); + + Should.NotThrow(() => Register(assembly)); + } + + [Fact] + public void Consumers_with_the_same_class_name_in_different_namespaces_fail_at_startup() + { + var assembly = ClashingTypes.Build(["ModuleA", "ModuleB"], consumerName: "SendEmailConsumer", + payloadNameAttributes: ["module-a.send-email", "module-b.send-email"]); + + var exception = Should.Throw(() => Register(assembly)); + + exception.Message.ShouldContain("ModuleA.SendEmailConsumer"); + exception.Message.ShouldContain("ModuleB.SendEmailConsumer"); + exception.Message.ShouldContain("[ConsumerName]"); + } +} diff --git a/AsyncMonolith/Consumers/AsyncMonolithNames.cs b/AsyncMonolith/Consumers/AsyncMonolithNames.cs new file mode 100644 index 0000000..987f7c8 --- /dev/null +++ b/AsyncMonolith/Consumers/AsyncMonolithNames.cs @@ -0,0 +1,79 @@ +using System.Collections.Concurrent; +using System.Reflection; + +namespace AsyncMonolith.Consumers; + +/// +/// Gives a payload type a stable name to store in payload_type, instead of its class name. +/// +/// +/// Use it when payloads in different modules share a class name, or to rename a class without +/// breaking stored and scheduled messages. For example [ConsumerPayloadName("minicms.email.send")]. +/// +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public sealed class ConsumerPayloadNameAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The stored name. Must not be empty or whitespace. + public ConsumerPayloadNameAttribute(string name) + { + Name = AsyncMonolithNames.Validate(name); + } + + /// Gets the stored name. + public string Name { get; } +} + +/// +/// Gives a consumer type a stable name to store in consumer_type, instead of its class name. +/// +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public sealed class ConsumerNameAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The stored name. Must not be empty or whitespace. + public ConsumerNameAttribute(string name) + { + Name = AsyncMonolithNames.Validate(name); + } + + /// Gets the stored name. + public string Name { get; } +} + +/// +/// Resolves the names stored for payload and consumer types: the name from +/// or when present, +/// otherwise the class name. +/// +public static class AsyncMonolithNames +{ + private static readonly ConcurrentDictionary PayloadNames = new(); + private static readonly ConcurrentDictionary ConsumerNames = new(); + + /// Gets the stored name for a payload type. + public static string ForPayload(Type payloadType) => + PayloadNames.GetOrAdd(payloadType, + t => t.GetCustomAttribute()?.Name ?? t.Name); + + /// Gets the stored name for a payload type. + public static string ForPayload() where TPayload : IConsumerPayload => ForPayload(typeof(TPayload)); + + /// Gets the stored name for a consumer type. + public static string ForConsumer(Type consumerType) => + ConsumerNames.GetOrAdd(consumerType, + t => t.GetCustomAttribute()?.Name ?? t.Name); + + /// Gets the stored name for a consumer type. + public static string ForConsumer() where TConsumer : IConsumer => ForConsumer(typeof(TConsumer)); + + internal static string Validate(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException("A stored name must not be empty or whitespace.", nameof(name)); + } + + return name; + } +} diff --git a/AsyncMonolith/Scheduling/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index 0896707..6b59dfc 100644 --- a/AsyncMonolith/Scheduling/ScheduleService.cs +++ b/AsyncMonolith/Scheduling/ScheduleService.cs @@ -62,7 +62,7 @@ public string Schedule(TK message, string chronExpression, string chronTimez _dbContext.Set().Add(new ScheduledMessage { Id = id, - PayloadType = typeof(TK).Name, + PayloadType = AsyncMonolithNames.ForPayload(), AvailableAfter = next.Value.ToUnixTimeSeconds(), Tag = tag, ChronExpression = chronExpression, diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index 3bea36c..266a338 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessage.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessage.cs @@ -109,6 +109,6 @@ public void UpdatePayload(TK message) where TK : IConsumerPayload { var payload = JsonSerializer.Serialize(message); Payload = payload; - PayloadType = typeof(TK).Name; + PayloadType = AsyncMonolithNames.ForPayload(); } } \ No newline at end of file diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index bb3b45d..6fddd66 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -116,6 +116,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( var consumerTimeoutDictionary = new Dictionary(); var consumerAttemptsDictionary = new Dictionary(); var consumerExecutionModeDictionary = new Dictionary(); + var payloadTypeDictionary = new Dictionary(); consumerRailIdDictionary ??= new Dictionary(); @@ -131,6 +132,8 @@ internal static void InternalRegisterAsyncMonolithConsumers( continue; } + var consumerName = AsyncMonolithNames.ForConsumer(consumerType); + // Register each consumer service services.AddScoped(consumerType); @@ -146,7 +149,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( timeoutDuration = settings.DefaultConsumerTimeout; } - consumerTimeoutDictionary[consumerType.Name] = timeoutDuration; + consumerTimeoutDictionary[consumerName] = timeoutDuration; var maxAttempts = settings.MaxAttempts; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerAttemptsAttribute)); @@ -160,7 +163,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( maxAttempts = settings.MaxAttempts; } - consumerAttemptsDictionary[consumerType.Name] = maxAttempts; + consumerAttemptsDictionary[consumerName] = maxAttempts; var consumerExecutionMode = ConsumerInstanceExecutionMode.Parallel; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerExecutionModeAttribute)); @@ -169,7 +172,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( consumerExecutionMode = executionModeAttribute.ExecutionMode; } - consumerExecutionModeDictionary[consumerType.Name] = consumerExecutionMode; + consumerExecutionModeDictionary[consumerName] = consumerExecutionMode; var consumerRailId = 0; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerRailIdAttribute)); @@ -178,27 +181,29 @@ internal static void InternalRegisterAsyncMonolithConsumers( consumerRailId = consumerRailIdAttribute.RailId; } - consumerRailIdDictionary[consumerType.Name] = consumerRailId; + consumerRailIdDictionary[consumerName] = consumerRailId; // Get the generic argument (T) of the consumer type var payloadType = consumerType.BaseType.GetGenericArguments()[0]; - if (!consumerServiceDictionary.TryAdd(consumerType.Name, consumerType)) + if (!consumerServiceDictionary.TryAdd(consumerName, consumerType)) { - throw new InvalidOperationException($"Consumer: '{consumerType.Name}' already defined."); + throw new InvalidOperationException( + $"Consumer: '{consumerName}' already defined by '{consumerServiceDictionary[consumerName].FullName}' and '{consumerType.FullName}'. Give one a unique name with [ConsumerName]."); } - if (!payloadConsumerDictionary.TryGetValue(payloadType.Name, out var payloadConsumers)) + var payloadName = RegisterPayloadName(payloadTypeDictionary, payloadType); + if (!payloadConsumerDictionary.TryGetValue(payloadName, out var payloadConsumers)) { - payloadConsumerDictionary[payloadType.Name] = payloadConsumers = new List(); + payloadConsumerDictionary[payloadName] = payloadConsumers = new List(); } - payloadConsumers.Add(consumerType.Name); + payloadConsumers.Add(consumerName); } foreach (var consumerPayload in typesToScan .Where(t => t is { IsClass: true, IsAbstract: false } && t.IsAssignableTo(typeof(IConsumerPayload))) - .Select(t => t.Name)) + .Select(t => RegisterPayloadName(payloadTypeDictionary, t))) { if (!payloadConsumerDictionary.ContainsKey(consumerPayload)) { @@ -209,4 +214,17 @@ internal static void InternalRegisterAsyncMonolithConsumers( services.AddSingleton(new ConsumerRegistry(consumerServiceDictionary, payloadConsumerDictionary, consumerTimeoutDictionary, consumerAttemptsDictionary, consumerRailIdDictionary, consumerExecutionModeDictionary, settings)); } + + private static string RegisterPayloadName(Dictionary payloadTypes, Type payloadType) + { + var payloadName = AsyncMonolithNames.ForPayload(payloadType); + if (payloadTypes.TryGetValue(payloadName, out var existing) && existing != payloadType) + { + throw new InvalidOperationException( + $"Payload name: '{payloadName}' is used by both '{existing.FullName}' and '{payloadType.FullName}'. Give one a unique name with [ConsumerPayloadName]."); + } + + payloadTypes[payloadName] = payloadType; + return payloadName; + } } diff --git a/docs/guides/changing-messages.md b/docs/guides/changing-messages.md index 508c4bf..28147e5 100644 --- a/docs/guides/changing-messages.md +++ b/docs/guides/changing-messages.md @@ -2,3 +2,21 @@ - **Schema Migration**: - If changes are not backwards compatible, make the changes in a copy of the `ConsumerPayload` (with a different class name) and update all consumers to operate on the new payload. - Once all messages with the old payload schema have been processed, you can safely delete the old payload schema and its associated consumers. + +## Stored names + +Messages are stored with the name of their payload type (`payload_type`) and consumer type (`consumer_type`). By default that is the class name, so **renaming a payload or consumer class breaks messages and schedules that are already stored**. + +Give a type a stable name to decouple it from the class name: + +```csharp +[ConsumerPayloadName("minicms.email.send")] +public class SendEmail : IConsumerPayload { ... } + +[ConsumerName("minicms.email.sender")] +public class SendEmailConsumer : BaseConsumer { ... } +``` + +To rename a class that already has stored messages, add the attribute with the old class name first. + +Names must be unique across everything registered. Two payloads or consumers with the same stored name, such as `SendEmail` classes in two modules, fail at startup with an error naming both types. From 8668e14d82befea91f44cd57ce9593ef23bfa16e Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:24:55 +0000 Subject: [PATCH 19/53] Let modules register their own consumers A host and its modules (for example MiniCMS and an LMS module) each need consumers, but Add*AsyncMonolith registers the background processors and can only be called once. - AddAsyncMonolithConsumers(assemblies) and AddAsyncMonolithConsumersFromAssemblyContaining() register a module's consumers before or after the host's call. Registering an assembly twice is harmless. - The consumer registry is built and validated when it is first resolved (at host start), so checks for payloads without consumers and for name clashes cover every module together. - Processor rails are read from the registry at start. The host always runs the per-rail processor factory, and ConsumerRegistry.RailIds falls back to rail 0 when there are no consumers. Tests cover modules registered before and after the host, duplicate registration, a payload with no consumer, rails across modules, and a running host whose consumers come only from a module registration. --- AsyncMonolith.Tests/HostedProcessingTests.cs | 27 ++++- AsyncMonolith.Tests/Infra/NamedConsumers.cs | 12 ++ .../ModuleRegistrationTests.cs | 99 ++++++++++++++++ AsyncMonolith.Tests/NamingTests.cs | 6 +- AsyncMonolith/Consumers/ConsumerRegistry.cs | 6 + AsyncMonolith/Utilities/StartupExtensions.cs | 109 +++++++++++++----- docs/quickstart.md | 12 ++ 7 files changed, 241 insertions(+), 30 deletions(-) create mode 100644 AsyncMonolith.Tests/ModuleRegistrationTests.cs diff --git a/AsyncMonolith.Tests/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs index deddc82..f755daa 100644 --- a/AsyncMonolith.Tests/HostedProcessingTests.cs +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -25,7 +25,7 @@ public sealed class HostedProcessingTests : IAsyncLifetime public ValueTask InitializeAsync() => ValueTask.CompletedTask; - private async Task StartHost(Action? configure = null) + private async Task StartHost(Action? configure = null, bool registerAsModule = false) { var builder = Host.CreateApplicationBuilder(); builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={_path}")); @@ -34,11 +34,20 @@ private async Task StartHost(Action? configure = null) builder.Services.AddSingleton(); builder.Services.AddEfAsyncMonolith(s => { - s.RegisterTypesFromAssemblyContaining(); + if (!registerAsModule) + { + s.RegisterTypesFromAssemblyContaining(); + } + s.ProcessorMaxDelay = 50; s.ProcessorMinDelay = 10; configure?.Invoke(s); }); + if (registerAsModule) + { + builder.Services.AddAsyncMonolithConsumersFromAssemblyContaining(); + } + _host = builder.Build(); using (var scope = _host.Services.CreateScope()) @@ -104,6 +113,20 @@ await WaitUntil(() => Query(db => db.ConsumerMessages.AnyAsync()).ContinueWith(t "the queue is empty"); } + [Fact] + public async Task Consumers_registered_by_a_module_after_the_host_are_processed() + { + await StartHost(registerAsModule: true); + + await Produce(new RailConsumerMessage()); + + await WaitUntil(() => Task.FromResult( + Invocations.GetInvocationCount(nameof(RailConsumer0)) == 1 && + Invocations.GetInvocationCount(nameof(RailConsumer1)) == 1 && + Invocations.GetInvocationCount(nameof(RailConsumer2)) == 1), + "the module's consumers on every rail have run"); + } + [Fact] public async Task Messages_on_every_rail_are_consumed() { diff --git a/AsyncMonolith.Tests/Infra/NamedConsumers.cs b/AsyncMonolith.Tests/Infra/NamedConsumers.cs index ffd9a7d..d8b6aaa 100644 --- a/AsyncMonolith.Tests/Infra/NamedConsumers.cs +++ b/AsyncMonolith.Tests/Infra/NamedConsumers.cs @@ -67,4 +67,16 @@ public static Assembly Build(string[] namespaces, string? consumerName = null, return assembly; } + + /// Builds an assembly with a payload that has no consumer. + public static Assembly PayloadOnly(string ns) + { + var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"PayloadOnly{Guid.NewGuid():N}"), + AssemblyBuilderAccess.Run); + var payload = assembly.DefineDynamicModule("PayloadOnly").DefineType($"{ns}.Orphan", + TypeAttributes.Public | TypeAttributes.Class, typeof(object), [typeof(IConsumerPayload)]); + payload.DefineDefaultConstructor(MethodAttributes.Public); + payload.CreateType(); + return assembly; + } } diff --git a/AsyncMonolith.Tests/ModuleRegistrationTests.cs b/AsyncMonolith.Tests/ModuleRegistrationTests.cs new file mode 100644 index 0000000..455fd11 --- /dev/null +++ b/AsyncMonolith.Tests/ModuleRegistrationTests.cs @@ -0,0 +1,99 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Ef; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Modules registering their own consumers with AddAsyncMonolithConsumers, alongside the host's +/// single AddEfAsyncMonolith call. +/// +public class ModuleRegistrationTests +{ + private static ServiceCollection Services() + { + var services = new ServiceCollection(); + services.AddSingleton(TimeProvider.System); + services.AddSingleton(); + services.AddDbContext(_ => { }); + return services; + } + + [Fact] + public void Module_consumers_registered_before_the_host_are_included() + { + var module = ClashingTypes.Build(["Billing"]); + var services = Services(); + + services.AddAsyncMonolithConsumers(module); + services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + + var provider = services.BuildServiceProvider(); + var registry = provider.GetRequiredService(); + registry.ResolvePayloadConsumerTypes("SendEmail").ShouldBe(["SendEmailConsumer0"]); + registry.ResolvePayloadConsumerTypes(nameof(SingleConsumerMessage)).ShouldBe([nameof(SingleConsumer)]); + using var scope = provider.CreateScope(); + scope.ServiceProvider.GetRequiredService(module.GetType("Billing.SendEmailConsumer0")!).ShouldNotBeNull(); + } + + [Fact] + public void Module_consumers_registered_after_the_host_are_included() + { + var module = ClashingTypes.Build(["Billing"]); + var services = Services(); + + services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolithConsumers(module); + + var registry = services.BuildServiceProvider().GetRequiredService(); + registry.ResolvePayloadConsumerTypes("SendEmail").ShouldBe(["SendEmailConsumer0"]); + } + + [Fact] + public void Registering_the_same_assembly_twice_is_harmless() + { + var services = Services(); + + services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolithConsumersFromAssemblyContaining(); + + services.Count(d => d.ServiceType == typeof(SingleConsumer)).ShouldBe(1); + services.BuildServiceProvider().GetRequiredService() + .ResolvePayloadConsumerTypes(nameof(SingleConsumerMessage)).ShouldBe([nameof(SingleConsumer)]); + } + + [Fact] + public void Payload_without_a_consumer_in_any_module_fails_when_the_host_starts() + { + var services = Services(); + services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolithConsumers(ClashingTypes.PayloadOnly("Billing")); + + var exception = Should.Throw(() => + services.BuildServiceProvider().GetRequiredService()); + + exception.Message.ShouldContain("Orphan"); + } + + [Fact] + public void Rails_are_read_from_every_module() + { + var services = Services(); + services.AddEfAsyncMonolith(_ => { }); + services.AddAsyncMonolithConsumersFromAssemblyContaining(); + + services.BuildServiceProvider().GetRequiredService().RailIds.ShouldBe([0, 1, 2]); + } + + [Fact] + public void Rail_zero_is_used_when_there_are_no_consumers() + { + var services = Services(); + services.AddEfAsyncMonolith(_ => { }); + + services.BuildServiceProvider().GetRequiredService().RailIds.ShouldBe([0]); + } +} diff --git a/AsyncMonolith.Tests/NamingTests.cs b/AsyncMonolith.Tests/NamingTests.cs index 5cadd16..5797703 100644 --- a/AsyncMonolith.Tests/NamingTests.cs +++ b/AsyncMonolith.Tests/NamingTests.cs @@ -17,7 +17,11 @@ private static void Register(params System.Reflection.Assembly[] assemblies) { var settings = AsyncMonolithSettings.Default; settings.RegisterTypesFromAssemblies(assemblies); - new ServiceCollection().InternalRegisterAsyncMonolithConsumers(settings); + var services = new ServiceCollection(); + services.InternalRegisterAsyncMonolithConsumers(settings); + + // The registry is built and validated when it is first resolved, as at host start. + services.BuildServiceProvider().GetRequiredService(); } [Fact] diff --git a/AsyncMonolith/Consumers/ConsumerRegistry.cs b/AsyncMonolith/Consumers/ConsumerRegistry.cs index 5820514..b096c32 100644 --- a/AsyncMonolith/Consumers/ConsumerRegistry.cs +++ b/AsyncMonolith/Consumers/ConsumerRegistry.cs @@ -72,6 +72,12 @@ public ConsumerRegistry(IReadOnlyDictionary consumerTypeDictionary _settings = settings; } + /// + /// Gets the distinct rails that registered consumers run on, or rail 0 when there are none. + /// + public IReadOnlyList RailIds => + ConsumerRailIdDictionary.Count == 0 ? [0] : ConsumerRailIdDictionary.Values.Distinct().Order().ToList(); + /// /// Resolves the list of consumer names that can handle the specified payload type. /// diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 6fddd66..c398e4f 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -1,7 +1,10 @@ -using AsyncMonolith.Consumers; +using System.Reflection; +using AsyncMonolith.Consumers; using AsyncMonolith.Scheduling; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; namespace AsyncMonolith.Utilities; @@ -85,31 +88,86 @@ internal static void InternalAddAsyncMonolith( AsyncMonolithSettings settings) where T : DbContext { services.InternalConfigureAsyncMonolithSettings(settings); - var consumerRailIdDictionary = new Dictionary(); - services.InternalRegisterAsyncMonolithConsumers(settings, consumerRailIdDictionary); + services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new AsyncMonolithIdGenerator()); services.AddScoped>(); services.AddScoped(sp => sp.GetRequiredService()); - - var consumerRails = consumerRailIdDictionary.Values.ToHashSet().ToArray(); - if (consumerRails.Length > 1) + + // One processor per rail. Rails are read when the host starts, after every module has + // registered its consumers. + services.AddHostedService(serviceProvider => new ConsumerMessageProcessorFactory(serviceProvider, + serviceProvider.GetRequiredService().RailIds.ToArray())); + + services.AddHostedService>(); + } + + internal static void InternalRegisterAsyncMonolithConsumers( + this IServiceCollection services, + AsyncMonolithSettings settings) + { + services.AddAsyncMonolithConsumers(settings.AssembliesToRegister.ToArray()); + } + + /// + /// Registers the consumers and payloads in the given assemblies. Call it from each module that has + /// consumers; the host calls Add*AsyncMonolith once. Order doesn't matter, and registering the + /// same assembly twice is harmless. + /// + /// + /// The consumer registry is built, and checked for name clashes and payloads without consumers, the first + /// time it is resolved, which happens when the host starts. + /// + /// The service collection. + /// The assemblies to scan. + /// The service collection. + public static IServiceCollection AddAsyncMonolithConsumers(this IServiceCollection services, + params Assembly[] assemblies) + { + var registered = services + .Where(d => d.ServiceType == typeof(ConsumerAssemblies)) + .Select(d => d.ImplementationInstance) + .OfType() + .FirstOrDefault(); + if (registered is null) { - services.AddHostedService(serviceProvider => - new ConsumerMessageProcessorFactory(serviceProvider, consumerRails)); + registered = new ConsumerAssemblies(); + services.AddSingleton(registered); + services.AddOptions(); + services.TryAddSingleton(serviceProvider => BuildConsumerRegistry(registered, + serviceProvider.GetRequiredService>().Value)); } - else + + foreach (var assembly in assemblies) { - services.AddHostedService>(); + if (!registered.Add(assembly)) + { + continue; + } + + foreach (var consumerType in FindConsumerTypes(assembly.GetTypes())) + { + services.TryAddScoped(consumerType); + } } - services.AddHostedService>(); + return services; } - internal static void InternalRegisterAsyncMonolithConsumers( - this IServiceCollection services, - AsyncMonolithSettings settings, - Dictionary? consumerRailIdDictionary = null - ) + /// + /// Registers the consumers and payloads in the assembly containing . + /// + /// Any type in the assembly to scan. + /// The service collection. + /// The service collection. + public static IServiceCollection AddAsyncMonolithConsumersFromAssemblyContaining( + this IServiceCollection services) => services.AddAsyncMonolithConsumers(typeof(TMarker).Assembly); + + private static IEnumerable FindConsumerTypes(IEnumerable types) => + types.Where(t => t is { IsAbstract: false, BaseType.IsGenericType: true } && + t.BaseType.GetGenericTypeDefinition() == typeof(BaseConsumer<>)); + + internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable assemblies, + AsyncMonolithSettings settings) { var consumerServiceDictionary = new Dictionary(); var payloadConsumerDictionary = new Dictionary>(); @@ -118,14 +176,11 @@ internal static void InternalRegisterAsyncMonolithConsumers( var consumerExecutionModeDictionary = new Dictionary(); var payloadTypeDictionary = new Dictionary(); - consumerRailIdDictionary ??= new Dictionary(); + var consumerRailIdDictionary = new Dictionary(); - var type = typeof(BaseConsumer<>); - var typesToScan = settings.AssembliesToRegister.SelectMany(x => x.GetTypes()).ToArray(); + var typesToScan = assemblies.SelectMany(x => x.GetTypes()).ToArray(); - foreach (var consumerType in typesToScan - .Where(t => t is { IsAbstract: false, BaseType.IsGenericType: true } && - t.BaseType.GetGenericTypeDefinition() == type)) + foreach (var consumerType in FindConsumerTypes(typesToScan)) { if (consumerType.BaseType == null || string.IsNullOrEmpty(consumerType.Name)) { @@ -134,9 +189,6 @@ internal static void InternalRegisterAsyncMonolithConsumers( var consumerName = AsyncMonolithNames.ForConsumer(consumerType); - // Register each consumer service - services.AddScoped(consumerType); - var timeoutDuration = settings.DefaultConsumerTimeout; var attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerTimeoutAttribute)); if (attribute is ConsumerTimeoutAttribute timeoutAttribute) @@ -211,10 +263,13 @@ internal static void InternalRegisterAsyncMonolithConsumers( } } - services.AddSingleton(new ConsumerRegistry(consumerServiceDictionary, payloadConsumerDictionary, - consumerTimeoutDictionary, consumerAttemptsDictionary, consumerRailIdDictionary, consumerExecutionModeDictionary, settings)); + return new ConsumerRegistry(consumerServiceDictionary, payloadConsumerDictionary, + consumerTimeoutDictionary, consumerAttemptsDictionary, consumerRailIdDictionary, + consumerExecutionModeDictionary, settings); } + private sealed class ConsumerAssemblies : HashSet; + private static string RegisterPayloadName(Dictionary payloadTypes, Type payloadType) { var payloadName = AsyncMonolithNames.ForPayload(payloadType); diff --git a/docs/quickstart.md b/docs/quickstart.md index dac7412..0764f87 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -77,6 +77,18 @@ The following methods are available on the `AsyncMonolithSettings` passed into t - `RegisterTypesFromAssembly(Assembly assembly)` - `RegisterTypesFromAssemblies(params Assembly[] assemblies)` +### Modules + +Call `Add*AsyncMonolith` once, in the host. A module or library with its own consumers registers them itself, before or after the host's call: + +```csharp +services.AddAsyncMonolithConsumersFromAssemblyContaining(); +// or +services.AddAsyncMonolithConsumers(typeof(BillingModule).Assembly); +``` + +Registering an assembly more than once is harmless. Consumers from every module are checked together when the host starts: a payload with no consumer in any module, or two payloads or consumers with the same stored name, stops startup with an error (see [Stored names](guides/changing-messages.md#stored-names)). + Create messages and consumers ```csharp From 5fb1c3f5e51d76f61098a0a9bbbbc86a77dee0ac Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:27:15 +0000 Subject: [PATCH 20/53] Back off between retries, record errors, and manage poisoned messages Retries used a fixed AttemptDelay, so an outage of a few minutes (for example an SMTP server) poisoned every message in under a minute. Poisoned messages had no record of why they failed, and could only be retried by editing the database. - Backoff: the first retry waits AttemptDelay seconds and each later retry doubles, capped by the new MaxAttemptDelay setting (default 300 seconds, never below AttemptDelay). Settings.GetRetryDelay(attempts) gives the delay. - Errors: consumer_messages and poisoned_messages gain a nullable last_error column holding the exception type and message (at most 2000 characters) or "Timed out after N seconds." Hosts must add the column; the SQL schemas include it. - IPoisonedMessageService (registered by every provider and by AddRealAsyncMonolithBaseServices): Count, List (newest first, paged), Retry, RetryAll and Delete. Retrying moves a message back to the queue with its attempts reset. Changes are saved immediately. Tests cover the backoff sequence and caps, recorded errors and timeouts, errors kept on poisoned messages, and every service operation. --- AsyncMonolith.TestHelpers/SetupTestHelpers.cs | 2 + .../Infra/TestServiceHelpers.cs | 1 + .../RetryAndPoisonedMessageTests.cs | 209 ++++++++++++++++++ AsyncMonolith/Consumers/ConsumerMessage.cs | 9 +- .../Consumers/ConsumerMessageProcessor.cs | 44 ++-- AsyncMonolith/Consumers/PoisonedMessage.cs | 9 +- .../Consumers/PoisonedMessageService.cs | 119 ++++++++++ .../Utilities/AsyncMonolithSettings.cs | 24 +- AsyncMonolith/Utilities/StartupExtensions.cs | 7 + Schemas/asyncmonolith_mariadb.sql | 2 + Schemas/asyncmonolith_mssql.sql | 2 + Schemas/asyncmonolith_mysql.sql | 2 + Schemas/asyncmonolith_postgresql.sql | 2 + docs/guides/consuming-messages.md | 16 +- 14 files changed, 429 insertions(+), 19 deletions(-) create mode 100644 AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs create mode 100644 AsyncMonolith/Consumers/PoisonedMessageService.cs diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index 5bc8044..23d91e1 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -1,4 +1,5 @@ using System.Reflection; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -90,6 +91,7 @@ private static IServiceCollection AddRealAsyncMonolithBaseServices( services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new AsyncMonolithIdGenerator()); services.AddScoped>(); + services.AddScoped>(); return services; } } diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 874310d..763311c 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -38,6 +38,7 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new FakeIdGenerator()); services.AddScoped>(); + services.AddScoped>(); switch (dbType) { case DbType.Ef: diff --git a/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs new file mode 100644 index 0000000..0025816 --- /dev/null +++ b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs @@ -0,0 +1,209 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Retry backoff, recorded errors and the poisoned message service. +/// +public class RetryAndPoisonedMessageTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Theory] + [InlineData(1, 10)] + [InlineData(2, 20)] + [InlineData(3, 40)] + [InlineData(4, 80)] + [InlineData(5, 100)] + [InlineData(1000, 100)] + public void Retry_delay_doubles_each_attempt_up_to_the_maximum(int attempts, long expected) + { + new AsyncMonolithSettings { AttemptDelay = 10, MaxAttemptDelay = 100 }.GetRetryDelay(attempts) + .ShouldBe(expected); + } + + [Fact] + public void Retry_delay_never_drops_below_the_attempt_delay() + { + var settings = new AsyncMonolithSettings { AttemptDelay = 600, MaxAttemptDelay = 300 }; + + settings.GetRetryDelay(1).ShouldBe(600); + settings.GetRetryDelay(3).ShouldBe(600); + } + + [Fact] + public void Zero_attempt_delay_retries_immediately() + { + new AsyncMonolithSettings { AttemptDelay = 0 }.GetRetryDelay(5).ShouldBe(0); + } + + [Fact] + public void Negative_max_attempt_delay_is_rejected() + { + Should.Throw(() => new ServiceCollection().InternalConfigureAsyncMonolithSettings( + new AsyncMonolithSettings { MaxAttemptDelay = -1 })); + } + + [Fact] + public async Task Failed_messages_back_off_between_retries() + { + await using var host = await SqliteTestHost.Create(s => + { + s.AttemptDelay = 10; + s.MaxAttemptDelay = 25; + s.MaxAttempts = 10; + }); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); + + var delays = new List(); + for (var i = 0; i < 4; i++) + { + var before = host.Now; + await host.ConsumerProcessor.ProcessBatch(Ct); + var message = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + delays.Add(message.AvailableAfter - before); + host.Time.Advance(TimeSpan.FromSeconds(message.AvailableAfter - before)); + } + + delays.ShouldBe([10, 20, 25, 25]); + } + + [Fact] + public async Task Failed_attempt_records_the_error() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MixedOutcomeMessage()); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().LastError + .ShouldBe("System.InvalidOperationException: Always fails"); + } + + [Fact] + public async Task Timed_out_attempt_records_the_timeout() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new TimeoutConsumerMessage { Delay = 5 }); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().LastError.ShouldBe("Timed out after 1 seconds."); + } + + [Fact] + public async Task Poisoned_message_keeps_the_last_error() + { + await using var host = await SqliteTestHost.Create(s => s.MaxAttempts = 1); + await host.Produce(new MixedOutcomeMessage()); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + (await host.PoisonedMessages()).ShouldHaveSingleItem().LastError + .ShouldBe("System.InvalidOperationException: Always fails"); + } + + private static async Task HostWithPoisonedMessages(int count) + { + var host = await SqliteTestHost.Create(s => s.MaxAttempts = 1); + for (var i = 0; i < count; i++) + { + await host.Produce(new ExceptionConsumerMessage { Name = $"boom{i}" }); + host.Time.Advance(TimeSpan.FromSeconds(1)); + } + + while (await host.ConsumerProcessor.ProcessBatch(Ct) > 0 || (await host.ConsumerMessages()).Count > 0) + { + } + + return host; + } + + private static async Task UseAsync(SqliteTestHost host, Func> action) + { + using var scope = host.Services.CreateScope(); + return await action(scope.ServiceProvider.GetRequiredService()); + } + + [Fact] + public async Task Poisoned_messages_are_counted_and_listed_newest_first() + { + await using var host = await HostWithPoisonedMessages(3); + + (await UseAsync(host, s => s.Count(Ct))).ShouldBe(3); + + var page = await UseAsync(host, s => s.List(0, 2, Ct)); + page.Count.ShouldBe(2); + page[0].CreatedAt.ShouldBeGreaterThan(page[1].CreatedAt); + page.ShouldAllBe(m => m.LastError != null); + + (await UseAsync(host, s => s.List(2, 2, Ct))).ShouldHaveSingleItem(); + } + + [Fact] + public async Task Listing_rejects_invalid_paging() + { + await using var host = await SqliteTestHost.Create(); + + await Should.ThrowAsync(() => UseAsync(host, s => s.List(-1, 10, Ct))); + await Should.ThrowAsync(() => UseAsync(host, s => s.List(0, 0, Ct))); + } + + [Fact] + public async Task Retry_moves_a_poisoned_message_back_to_the_queue() + { + await using var host = await HostWithPoisonedMessages(1); + var poisoned = (await host.PoisonedMessages()).ShouldHaveSingleItem(); + + (await UseAsync(host, s => s.Retry(poisoned.Id, Ct))).ShouldBeTrue(); + + (await host.PoisonedMessages()).ShouldBeEmpty(); + var requeued = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + requeued.Id.ShouldBe(poisoned.Id); + requeued.Attempts.ShouldBe(0); + requeued.AvailableAfter.ShouldBe(host.Now); + requeued.Payload.ShouldBe(poisoned.Payload); + requeued.InsertId.ShouldBe(poisoned.InsertId); + requeued.LastError.ShouldBe(poisoned.LastError); + + // It is processed again (and, since this consumer always fails, poisoned again) + await host.ConsumerProcessor.ProcessBatch(Ct); + host.Invocations.GetInvocationCount(nameof(ExceptionConsumer)).ShouldBe(2); + } + + [Fact] + public async Task RetryAll_moves_every_poisoned_message_back() + { + await using var host = await HostWithPoisonedMessages(3); + + (await UseAsync(host, s => s.RetryAll(Ct))).ShouldBe(3); + + (await host.PoisonedMessages()).ShouldBeEmpty(); + (await host.ConsumerMessages()).Count.ShouldBe(3); + } + + [Fact] + public async Task Delete_removes_a_poisoned_message() + { + await using var host = await HostWithPoisonedMessages(2); + var poisoned = await host.PoisonedMessages(); + + (await UseAsync(host, s => s.Delete(poisoned[0].Id, Ct))).ShouldBeTrue(); + + (await host.PoisonedMessages()).ShouldHaveSingleItem().Id.ShouldBe(poisoned[1].Id); + (await host.ConsumerMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task Unknown_ids_are_reported_as_not_found() + { + await using var host = await SqliteTestHost.Create(); + + (await UseAsync(host, s => s.Retry("missing", Ct))).ShouldBeFalse(); + (await UseAsync(host, s => s.Delete("missing", Ct))).ShouldBeFalse(); + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessage.cs b/AsyncMonolith/Consumers/ConsumerMessage.cs index 22ecbb9..08bcf4e 100644 --- a/AsyncMonolith/Consumers/ConsumerMessage.cs +++ b/AsyncMonolith/Consumers/ConsumerMessage.cs @@ -88,4 +88,11 @@ public sealed class ConsumerMessage [JsonPropertyName("span_id")] [Column("span_id")] public required string? SpanId { get; set; } -} \ No newline at end of file + + /// + /// Gets or sets the error from the most recent failed attempt, if any. + /// + [JsonPropertyName("last_error")] + [Column("last_error")] + public string? LastError { get; set; } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index ed5c8f6..35a86c3 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -174,18 +174,19 @@ internal async Task> ClaimBatch(CancellationToken cancella private async Task ProcessAndComplete(ConsumerMessage message, CancellationToken cancellationToken) { - var (_, success) = await Process(message, cancellationToken); + var error = await Process(message, cancellationToken); // Record the outcome even when stopping, so the attempt isn't left waiting for its lease to expire. - await Complete(message, success, CancellationToken.None); - return success; + await Complete(message, error is null, CancellationToken.None, error); + return error is null; } /// /// Records the outcome of a claimed message: removes it on success, otherwise schedules a retry or /// moves it to the poisoned messages. Does nothing if the lease has since been taken over. /// - internal async Task Complete(ConsumerMessage message, bool success, CancellationToken cancellationToken) + internal async Task Complete(ConsumerMessage message, bool success, CancellationToken cancellationToken, + string? error = null) { using var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); @@ -200,9 +201,11 @@ internal async Task Complete(ConsumerMessage message, bool success, Cancellation if (message.Attempts < _consumerRegistry.ResolveConsumerMaxAttempts(message)) { - var retryAt = _timeProvider.GetUtcNow().ToUnixTimeSeconds() + _options.Value.AttemptDelay; - await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryAt), - cancellationToken); + var retryAt = _timeProvider.GetUtcNow().ToUnixTimeSeconds() + + _options.Value.GetRetryDelay(message.Attempts); + await leased.ExecuteUpdateAsync(s => s + .SetProperty(m => m.AvailableAfter, retryAt) + .SetProperty(m => m.LastError, error), cancellationToken); return; } @@ -224,7 +227,8 @@ await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryA InsertId = message.InsertId, TraceId = message.TraceId, SpanId = message.SpanId, - RailId = message.RailId + RailId = message.RailId, + LastError = error }); await dbContext.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); @@ -255,9 +259,8 @@ await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryA /// /// The consumer message to process. /// The cancellation token to stop the execution. - /// A tuple containing the processed consumer message and a flag indicating success. - internal async Task<(ConsumerMessage message, bool success)> Process(ConsumerMessage message, - CancellationToken cancellationToken = default) + /// Null on success, otherwise a description of the error. + internal async Task Process(ConsumerMessage message, CancellationToken cancellationToken = default) { using var activity = StartActivity(message); @@ -266,10 +269,10 @@ await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryA activity?.AddTag("consumer_message.payload.type", message.PayloadType); activity?.AddTag("consumer_message.type", message.ConsumerType); + var consumerTimeout = _consumerRegistry.ResolveConsumerTimeout(message); try { var consumerType = _consumerRegistry.ResolveConsumerType(message); - var consumerTimeout = _consumerRegistry.ResolveConsumerTimeout(message); using var timeoutCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeoutCancellationToken.CancelAfter(TimeSpan.FromSeconds(consumerTimeout)); @@ -288,7 +291,13 @@ await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryA activity?.SetStatus(ActivityStatusCode.Ok); _logger.ConsumerMessageProcessed(message.ConsumerType); - return (message, true); + return null; + } + catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested) + { + activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + _logger.ConsumerMessageFailed(ex, message.Attempts); + return $"Timed out after {consumerTimeout} seconds."; } catch (Exception ex) { @@ -296,8 +305,15 @@ await leased.ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, retryA activity?.AddTag("exception.type", ex.GetType().FullName); activity?.AddTag("exception.message", ex.Message); _logger.ConsumerMessageFailed(ex, message.Attempts); + return Describe(ex); } + } + + private const int MaxErrorLength = 2000; - return (message, false); + private static string Describe(Exception exception) + { + var description = $"{exception.GetType().FullName}: {exception.Message}"; + return description.Length <= MaxErrorLength ? description : description[..MaxErrorLength]; } } \ No newline at end of file diff --git a/AsyncMonolith/Consumers/PoisonedMessage.cs b/AsyncMonolith/Consumers/PoisonedMessage.cs index fa73f71..4b7736b 100644 --- a/AsyncMonolith/Consumers/PoisonedMessage.cs +++ b/AsyncMonolith/Consumers/PoisonedMessage.cs @@ -88,4 +88,11 @@ public sealed class PoisonedMessage [JsonPropertyName("span_id")] [Column("span_id")] public required string? SpanId { get; set; } -} \ No newline at end of file + + /// + /// Gets or sets the error from the most recent failed attempt, if any. + /// + [JsonPropertyName("last_error")] + [Column("last_error")] + public string? LastError { get; set; } +} diff --git a/AsyncMonolith/Consumers/PoisonedMessageService.cs b/AsyncMonolith/Consumers/PoisonedMessageService.cs new file mode 100644 index 0000000..0c195cb --- /dev/null +++ b/AsyncMonolith/Consumers/PoisonedMessageService.cs @@ -0,0 +1,119 @@ +using Microsoft.EntityFrameworkCore; + +namespace AsyncMonolith.Consumers; + +/// +/// Inspects, retries and deletes poisoned messages: messages that failed every attempt. +/// Changes are saved immediately. +/// +public interface IPoisonedMessageService +{ + /// Counts poisoned messages. + Task Count(CancellationToken cancellationToken = default); + + /// Lists poisoned messages, most recently created first. + Task> List(int skip = 0, int take = 50, + CancellationToken cancellationToken = default); + + /// + /// Moves a poisoned message back to the queue with its attempts reset, available immediately. + /// + /// False if no poisoned message has that id. + Task Retry(string id, CancellationToken cancellationToken = default); + + /// Moves every poisoned message back to the queue. + /// The number of messages moved. + Task RetryAll(CancellationToken cancellationToken = default); + + /// Deletes a poisoned message. + /// False if no poisoned message has that id. + Task Delete(string id, CancellationToken cancellationToken = default); +} + +/// +/// Entity Framework implementation of . +/// +/// The DbContext containing the AsyncMonolith tables. +public sealed class PoisonedMessageService : IPoisonedMessageService where T : DbContext +{ + private readonly T _dbContext; + private readonly TimeProvider _timeProvider; + + /// Initializes a new instance of the class. + public PoisonedMessageService(T dbContext, TimeProvider timeProvider) + { + _dbContext = dbContext; + _timeProvider = timeProvider; + } + + /// + public Task Count(CancellationToken cancellationToken = default) => + _dbContext.Set().CountAsync(cancellationToken); + + /// + public async Task> List(int skip = 0, int take = 50, + CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfNegative(skip); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(take); + + return await _dbContext.Set() + .AsNoTracking() + .OrderByDescending(m => m.CreatedAt) + .ThenBy(m => m.Id) + .Skip(skip) + .Take(take) + .ToListAsync(cancellationToken); + } + + /// + public async Task Retry(string id, CancellationToken cancellationToken = default) + { + var poisoned = await _dbContext.Set().FirstOrDefaultAsync(m => m.Id == id, cancellationToken); + if (poisoned is null) + { + return false; + } + + Requeue(poisoned); + await _dbContext.SaveChangesAsync(cancellationToken); + return true; + } + + /// + public async Task RetryAll(CancellationToken cancellationToken = default) + { + var poisoned = await _dbContext.Set().ToListAsync(cancellationToken); + foreach (var message in poisoned) + { + Requeue(message); + } + + await _dbContext.SaveChangesAsync(cancellationToken); + return poisoned.Count; + } + + /// + public async Task Delete(string id, CancellationToken cancellationToken = default) => + await _dbContext.Set().Where(m => m.Id == id).ExecuteDeleteAsync(cancellationToken) > 0; + + private void Requeue(PoisonedMessage poisoned) + { + _dbContext.Set().Remove(poisoned); + _dbContext.Set().Add(new ConsumerMessage + { + Id = poisoned.Id, + CreatedAt = poisoned.CreatedAt, + AvailableAfter = _timeProvider.GetUtcNow().ToUnixTimeSeconds(), + Attempts = 0, + ConsumerType = poisoned.ConsumerType, + RailId = poisoned.RailId, + PayloadType = poisoned.PayloadType, + Payload = poisoned.Payload, + InsertId = poisoned.InsertId, + TraceId = poisoned.TraceId, + SpanId = poisoned.SpanId, + LastError = poisoned.LastError + }); + } +} diff --git a/AsyncMonolith/Utilities/AsyncMonolithSettings.cs b/AsyncMonolith/Utilities/AsyncMonolithSettings.cs index 13c639a..be22723 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithSettings.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithSettings.cs @@ -16,11 +16,19 @@ public class AsyncMonolithSettings public int MaxAttempts { get; set; } = 5; /// - /// Gets or sets the delay in seconds between attempts for processing a failed message. + /// Gets or sets the delay in seconds before the first retry of a failed message. Each further retry + /// waits twice as long as the one before, up to . /// Default: 10 seconds, Min: 0 second, Max N/A /// public int AttemptDelay { get; set; } = 10; + /// + /// Gets or sets the longest delay in seconds between retries. If it is less than + /// , retries wait each time. + /// Default: 300 seconds, Min: 0 second, Max N/A + /// + public int MaxAttemptDelay { get; set; } = 300; + /// /// Gets or sets the maximum delay in milliseconds between processor cycles. /// Default: 1000ms, Min: 1ms, Max N/A @@ -45,6 +53,19 @@ public class AsyncMonolithSettings /// public int DefaultConsumerTimeout { get; set; } = 10; + /// + /// Gets the delay in seconds before retrying a message that has failed times. + /// + /// The number of failed attempts so far (1 after the first failure). + /// doubled for each attempt after the first, capped at + /// (or if that is larger). + public long GetRetryDelay(int attempts) + { + var cap = Math.Max(AttemptDelay, MaxAttemptDelay); + var doublings = Math.Clamp(attempts - 1, 0, 30); + return Math.Min((long)AttemptDelay << doublings, cap); + } + /// /// Gets the default AsyncMonolithSettings. /// @@ -52,6 +73,7 @@ public class AsyncMonolithSettings { MaxAttempts = 5, AttemptDelay = 10, + MaxAttemptDelay = 300, ProcessorMaxDelay = 1000, ProcessorMinDelay = 10, ProcessorBatchSize = 5 diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index c398e4f..2c02aed 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -36,6 +36,11 @@ internal static void InternalConfigureAsyncMonolithSettings( throw new ArgumentException("AsyncMonolithSettings.AttemptDelay must be positive."); } + if (settings.MaxAttemptDelay < 0) + { + throw new ArgumentException("AsyncMonolithSettings.MaxAttemptDelay must be positive."); + } + if (settings.MaxAttempts < 1) { throw new ArgumentException("AsyncMonolithSettings.MaxAttempts must be at least 1."); @@ -75,6 +80,7 @@ internal static void InternalConfigureAsyncMonolithSettings( services.Configure(options => { options.AttemptDelay = settings.AttemptDelay; + options.MaxAttemptDelay = settings.MaxAttemptDelay; options.MaxAttempts = settings.MaxAttempts; options.ProcessorMaxDelay = settings.ProcessorMaxDelay; options.ProcessorMinDelay = settings.ProcessorMinDelay; @@ -91,6 +97,7 @@ internal static void InternalAddAsyncMonolith( services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new AsyncMonolithIdGenerator()); services.AddScoped>(); + services.AddScoped>(); services.AddScoped(sp => sp.GetRequiredService()); // One processor per rail. Rails are read when the host starts, after every module has diff --git a/Schemas/asyncmonolith_mariadb.sql b/Schemas/asyncmonolith_mariadb.sql index b6cd93f..4917c0f 100644 --- a/Schemas/asyncmonolith_mariadb.sql +++ b/Schemas/asyncmonolith_mariadb.sql @@ -11,6 +11,7 @@ CREATE TABLE consumer_messages ( insert_id VARCHAR(255) NOT NULL, trace_id VARCHAR(255) NOT NULL, span_id VARCHAR(255) NOT NULL, + last_error TEXT NULL, PRIMARY KEY (id) ); @@ -25,6 +26,7 @@ CREATE TABLE poisoned_messages ( insert_id VARCHAR(255) NOT NULL, trace_id VARCHAR(255) NOT NULL, span_id VARCHAR(255) NOT NULL, + last_error TEXT NULL, PRIMARY KEY (id) ); diff --git a/Schemas/asyncmonolith_mssql.sql b/Schemas/asyncmonolith_mssql.sql index d5a9896..07d41c9 100644 --- a/Schemas/asyncmonolith_mssql.sql +++ b/Schemas/asyncmonolith_mssql.sql @@ -11,6 +11,7 @@ CREATE TABLE consumer_messages ( insert_id NVARCHAR(255) NOT NULL, trace_id NVARCHAR(255) NOT NULL, span_id NVARCHAR(255) NOT NULL, + last_error NVARCHAR(MAX) NULL, CONSTRAINT PK_consumer_messages PRIMARY KEY (id) ); @@ -26,6 +27,7 @@ CREATE TABLE poisoned_messages ( insert_id NVARCHAR(255) NOT NULL, trace_id NVARCHAR(255) NOT NULL, span_id NVARCHAR(255) NOT NULL, + last_error NVARCHAR(MAX) NULL, CONSTRAINT PK_poisoned_messages PRIMARY KEY (id) ); diff --git a/Schemas/asyncmonolith_mysql.sql b/Schemas/asyncmonolith_mysql.sql index b6cd93f..4917c0f 100644 --- a/Schemas/asyncmonolith_mysql.sql +++ b/Schemas/asyncmonolith_mysql.sql @@ -11,6 +11,7 @@ CREATE TABLE consumer_messages ( insert_id VARCHAR(255) NOT NULL, trace_id VARCHAR(255) NOT NULL, span_id VARCHAR(255) NOT NULL, + last_error TEXT NULL, PRIMARY KEY (id) ); @@ -25,6 +26,7 @@ CREATE TABLE poisoned_messages ( insert_id VARCHAR(255) NOT NULL, trace_id VARCHAR(255) NOT NULL, span_id VARCHAR(255) NOT NULL, + last_error TEXT NULL, PRIMARY KEY (id) ); diff --git a/Schemas/asyncmonolith_postgresql.sql b/Schemas/asyncmonolith_postgresql.sql index eb0d577..0699428 100644 --- a/Schemas/asyncmonolith_postgresql.sql +++ b/Schemas/asyncmonolith_postgresql.sql @@ -11,6 +11,7 @@ CREATE TABLE consumer_messages ( insert_id text NOT NULL, trace_id text NOT NULL, span_id text NOT NULL, + last_error text NULL, CONSTRAINT "PK_consumer_messages" PRIMARY KEY (id) ); @@ -26,6 +27,7 @@ CREATE TABLE poisoned_messages ( insert_id text NOT NULL, trace_id text NOT NULL, span_id text NOT NULL, + last_error text NULL, CONSTRAINT "PK_poisoned_messages" PRIMARY KEY (id) ); diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 997888f..c1f697c 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -30,6 +30,18 @@ public class DeleteUsersPosts : BaseConsumer ## Consumer Failures 💢 -- **Retry Logic**: Messages will be retried up to `MaxAttempts` times (with a `AttemptDelay` seconds between attempts) until they are moved to the `poisoned_messages` table. Add the `[ConsumerAttempts(1)]` attribute to override this behavior. -- **Manual Intervention**: If a message is moved to the `poisoned_messages` table, it will need to be manually removed from the database or moved back to the `consumer_messages` table to be retried. Note that the poisoned message will only be retried a single time unless you set `attempts` back to 0. +- **Retry Logic**: Messages are retried up to `MaxAttempts` times before they are moved to the `poisoned_messages` table. Add the `[ConsumerAttempts(1)]` attribute to override this per consumer. +- **Backoff**: The first retry waits `AttemptDelay` seconds (default 10), and each later retry waits twice as long as the one before, up to `MaxAttemptDelay` seconds (default 300). With the defaults a message is retried after 10, 20, 40 and 80 seconds. +- **Errors**: The error from the most recent failed attempt is stored in `last_error` on both tables, for example `System.InvalidOperationException: ...` or `Timed out after 10 seconds.` +- **Interrupted processing**: A message is leased while its consumer runs. If the app stops mid-message, the message becomes available again once its consumer timeout plus 30 seconds has passed, and the interrupted attempt counts. +- **Manual Intervention**: Use `IPoisonedMessageService` to count, list, retry or delete poisoned messages. Retrying moves a message back to `consumer_messages` with its attempts reset. Changes are saved immediately. - **Monitoring**: Periodically monitor the `poisoned_messages` table to ensure there are not too many failed messages. + +```csharp +public class FailedMessagesController(IPoisonedMessageService poisoned) : ControllerBase +{ + [HttpGet] public Task> List() => poisoned.List(skip: 0, take: 50); + [HttpPost("{id}/retry")] public Task Retry(string id) => poisoned.Retry(id); + [HttpDelete("{id}")] public Task Delete(string id) => poisoned.Delete(id); +} +``` From 03c1846839e64069d982ada8d7d777ccf6176ddf Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:29:22 +0000 Subject: [PATCH 21/53] Add EnsureSchedule and queue statistics - IScheduleService.EnsureSchedule creates or updates the schedule with a tag, so it can run at every startup. The next occurrence only moves if the expression or timezone changed, and duplicates with the same tag are removed. FakeScheduleService records it in the same way. - IQueueStatisticsService.Read returns available, waiting and poisoned message counts, the number of schedules, and how long the oldest due message has waited, for health checks. Registered by every provider and by AddRealAsyncMonolithBaseServices. Tests cover creating, re-ensuring after a restart, payload updates, recalculation on expression or timezone change, duplicate removal, required tags, the fake, and statistics for empty, mixed and leased queues. --- .../FakeScheduleService.cs | 10 + AsyncMonolith.TestHelpers/SetupTestHelpers.cs | 1 + .../EnsureScheduleAndStatisticsTests.cs | 172 ++++++++++++++++++ .../Infra/TestServiceHelpers.cs | 1 + AsyncMonolith/Consumers/QueueStatistics.cs | 66 +++++++ AsyncMonolith/Scheduling/IScheduleService.cs | 16 ++ AsyncMonolith/Scheduling/ScheduleService.cs | 25 +++ AsyncMonolith/Utilities/StartupExtensions.cs | 1 + docs/guides/consuming-messages.md | 9 + docs/guides/scheduling-messages.md | 12 +- 10 files changed, 312 insertions(+), 1 deletion(-) create mode 100644 AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs create mode 100644 AsyncMonolith/Consumers/QueueStatistics.cs diff --git a/AsyncMonolith.TestHelpers/FakeScheduleService.cs b/AsyncMonolith.TestHelpers/FakeScheduleService.cs index 6914716..1ebd1fe 100644 --- a/AsyncMonolith.TestHelpers/FakeScheduleService.cs +++ b/AsyncMonolith.TestHelpers/FakeScheduleService.cs @@ -86,6 +86,16 @@ public string Schedule(TK message, string chronExpression, string chronTimez return id; } + /// + /// Records the schedule, replacing any recorded schedule with the same tag. + /// + public Task EnsureSchedule(TK message, string chronExpression, string chronTimezone, string tag, + CancellationToken cancellationToken = default) where TK : IConsumerPayload + { + CreatedScheduledMessages.RemoveAll(m => m.Tag == tag); + return Task.FromResult(Schedule(message, chronExpression, chronTimezone, tag)); + } + /// /// Deletes scheduled messages by tag. /// diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index 23d91e1..9936f1c 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -92,6 +92,7 @@ private static IServiceCollection AddRealAsyncMonolithBaseServices( services.AddSingleton(new AsyncMonolithIdGenerator()); services.AddScoped>(); services.AddScoped>(); + services.AddScoped>(); return services; } } diff --git a/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs b/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs new file mode 100644 index 0000000..eda9749 --- /dev/null +++ b/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using System.Text.Json; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.TestHelpers; +using AsyncMonolith.Tests.Infra; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// EnsureSchedule (idempotent schedules) and queue statistics. +/// +public class EnsureScheduleAndStatisticsTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static long Utc(string iso) => + DateTimeOffset.Parse(iso, CultureInfo.InvariantCulture).ToUnixTimeSeconds(); + + private static async Task Ensure(SqliteTestHost host, string name, string cron, string tag = "nightly", + string timezone = "UTC") + { + using var scope = host.Services.CreateScope(); + var id = await scope.ServiceProvider.GetRequiredService() + .EnsureSchedule(new SingleConsumerMessage { Name = name }, cron, timezone, tag, Ct); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + return id; + } + + private static async Task Statistics(SqliteTestHost host) + { + using var scope = host.Services.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().Read(Ct); + } + + [Fact] + public async Task EnsureSchedule_creates_the_schedule_when_missing() + { + await using var host = await SqliteTestHost.Create(); + + var id = await Ensure(host, "a", "0 0 9 * * *"); + + var schedule = (await host.ScheduledMessages()).ShouldHaveSingleItem(); + schedule.Id.ShouldBe(id); + schedule.Tag.ShouldBe("nightly"); + schedule.AvailableAfter.ShouldBe(Utc("2020-09-01T09:00:00Z")); + } + + [Fact] + public async Task EnsureSchedule_at_every_startup_keeps_one_schedule_and_its_next_occurrence() + { + await using var host = await SqliteTestHost.Create(); + var id = await Ensure(host, "a", "0 0 9 * * *"); + + // A restart a few hours later: the next occurrence must not move. + host.Time.Advance(TimeSpan.FromHours(3)); + (await Ensure(host, "a", "0 0 9 * * *")).ShouldBe(id); + + var schedule = (await host.ScheduledMessages()).ShouldHaveSingleItem(); + schedule.AvailableAfter.ShouldBe(Utc("2020-09-01T09:00:00Z")); + } + + [Fact] + public async Task EnsureSchedule_updates_the_payload() + { + await using var host = await SqliteTestHost.Create(); + await Ensure(host, "old", "0 0 9 * * *"); + + await Ensure(host, "new", "0 0 9 * * *"); + + JsonSerializer.Deserialize((await host.ScheduledMessages()).ShouldHaveSingleItem() + .Payload)!.Name.ShouldBe("new"); + } + + [Fact] + public async Task EnsureSchedule_recalculates_when_the_expression_or_timezone_changes() + { + await using var host = await SqliteTestHost.Create(); + await Ensure(host, "a", "0 0 9 * * *"); + + await Ensure(host, "a", "0 30 10 * * *"); + (await host.ScheduledMessages()).ShouldHaveSingleItem().AvailableAfter.ShouldBe(Utc("2020-08-31T10:30:00Z")); + + await Ensure(host, "a", "0 30 10 * * *", timezone: "Europe/London"); + var schedule = (await host.ScheduledMessages()).ShouldHaveSingleItem(); + schedule.ChronTimezone.ShouldBe("Europe/London"); + schedule.AvailableAfter.ShouldBe(Utc("2020-09-01T09:30:00Z")); + } + + [Fact] + public async Task EnsureSchedule_removes_duplicates_left_by_Schedule() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "a" }, "0 0 9 * * *", tag: "nightly"); + await host.Schedule(new SingleConsumerMessage { Name = "a" }, "0 0 9 * * *", tag: "nightly"); + await host.Schedule(new SingleConsumerMessage { Name = "other" }, "0 0 9 * * *", tag: "other"); + + await Ensure(host, "a", "0 0 9 * * *"); + + (await host.ScheduledMessages()).Select(m => m.Tag).Order().ShouldBe(["nightly", "other"]); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task EnsureSchedule_requires_a_tag(string tag) + { + await using var host = await SqliteTestHost.Create(); + + await Should.ThrowAsync(() => Ensure(host, "a", "0 0 9 * * *", tag)); + } + + [Fact] + public async Task FakeScheduleService_EnsureSchedule_replaces_the_recorded_schedule() + { + var fake = new FakeScheduleService(TimeProvider.System, new FakeIdGenerator()); + + await fake.EnsureSchedule(new SingleConsumerMessage { Name = "a" }, "0 0 9 * * *", "UTC", "nightly", Ct); + await fake.EnsureSchedule(new SingleConsumerMessage { Name = "b" }, "0 0 9 * * *", "UTC", "nightly", Ct); + + JsonSerializer.Deserialize(fake.CreatedScheduledMessages.ShouldHaveSingleItem().Payload)! + .Name.ShouldBe("b"); + } + + [Fact] + public async Task Statistics_are_zero_for_an_empty_queue() + { + await using var host = await SqliteTestHost.Create(); + + (await Statistics(host)).ShouldBe(new QueueStatistics(0, 0, 0, 0, 0)); + } + + [Fact] + public async Task Statistics_count_due_waiting_poisoned_and_scheduled_messages() + { + await using var host = await SqliteTestHost.Create(s => s.MaxAttempts = 1); + await host.Produce(new SingleConsumerMessage { Name = "due-first" }); + host.Time.Advance(TimeSpan.FromSeconds(30)); + await host.Produce(new SingleConsumerMessage { Name = "due-second" }); + await host.Produce(new SingleConsumerMessage { Name = "later" }, host.Now + 600); + await host.Schedule(new SingleConsumerMessage { Name = "s" }, "0 0 9 * * *"); + await host.Change(db => db.PoisonedMessages.Add(new PoisonedMessage + { + Id = "p", CreatedAt = 0, AvailableAfter = 0, Attempts = 1, ConsumerType = "c", RailId = 0, + PayloadType = "p", Payload = "{}", InsertId = "i", TraceId = null, SpanId = null + })); + host.Time.Advance(TimeSpan.FromSeconds(15)); + + var statistics = await Statistics(host); + + statistics.Available.ShouldBe(2); + statistics.Waiting.ShouldBe(1); + statistics.OldestAvailableAgeSeconds.ShouldBe(45); + statistics.Poisoned.ShouldBe(1); + statistics.Schedules.ShouldBe(1); + } + + [Fact] + public async Task Leased_messages_count_as_waiting() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "a" }); + + await host.ConsumerProcessor.ClaimBatch(Ct); + + var statistics = await Statistics(host); + statistics.Available.ShouldBe(0); + statistics.Waiting.ShouldBe(1); + } +} diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 763311c..38a349f 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -39,6 +39,7 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A services.AddSingleton(new FakeIdGenerator()); services.AddScoped>(); services.AddScoped>(); + services.AddScoped>(); switch (dbType) { case DbType.Ef: diff --git a/AsyncMonolith/Consumers/QueueStatistics.cs b/AsyncMonolith/Consumers/QueueStatistics.cs new file mode 100644 index 0000000..484c41d --- /dev/null +++ b/AsyncMonolith/Consumers/QueueStatistics.cs @@ -0,0 +1,66 @@ +using AsyncMonolith.Scheduling; +using Microsoft.EntityFrameworkCore; + +namespace AsyncMonolith.Consumers; + +/// +/// A snapshot of the message tables, for health checks and dashboards. +/// +/// Messages that are due now and waiting for a processor. +/// Messages that are not yet due: delayed, waiting to retry, or leased by a processor. +/// +/// How long the longest-waiting due message has been due, in seconds, or 0 when none are due. A value that +/// keeps growing means processors are stuck or falling behind. +/// +/// Messages that failed every attempt. +/// Recurring schedules. +public sealed record QueueStatistics( + int Available, + int Waiting, + long OldestAvailableAgeSeconds, + int Poisoned, + int Schedules); + +/// +/// Reads . +/// +public interface IQueueStatisticsService +{ + /// Reads the current queue statistics. + Task Read(CancellationToken cancellationToken = default); +} + +/// +/// Entity Framework implementation of . +/// +/// The DbContext containing the AsyncMonolith tables. +public sealed class QueueStatisticsService : IQueueStatisticsService where T : DbContext +{ + private readonly T _dbContext; + private readonly TimeProvider _timeProvider; + + /// Initializes a new instance of the class. + public QueueStatisticsService(T dbContext, TimeProvider timeProvider) + { + _dbContext = dbContext; + _timeProvider = timeProvider; + } + + /// + public async Task Read(CancellationToken cancellationToken = default) + { + var now = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); + var messages = _dbContext.Set().AsNoTracking(); + + var available = await messages.CountAsync(m => m.AvailableAfter <= now, cancellationToken); + var waiting = await messages.CountAsync(m => m.AvailableAfter > now, cancellationToken); + var oldest = available == 0 + ? (long?)null + : await messages.Where(m => m.AvailableAfter <= now) + .MinAsync(m => (long?)m.AvailableAfter, cancellationToken); + var poisoned = await _dbContext.Set().CountAsync(cancellationToken); + var schedules = await _dbContext.Set().CountAsync(cancellationToken); + + return new QueueStatistics(available, waiting, oldest is null ? 0 : now - oldest.Value, poisoned, schedules); + } +} diff --git a/AsyncMonolith/Scheduling/IScheduleService.cs b/AsyncMonolith/Scheduling/IScheduleService.cs index 7010e08..f54cd3c 100644 --- a/AsyncMonolith/Scheduling/IScheduleService.cs +++ b/AsyncMonolith/Scheduling/IScheduleService.cs @@ -19,6 +19,22 @@ public interface IScheduleService public string Schedule(TK message, string chronExpression, string chronTimezone, string? tag = null) where TK : IConsumerPayload; + /// + /// Creates the schedule with this tag, or updates it if it already exists, so it can be called at every + /// startup. If the expression and timezone are unchanged, the next occurrence is kept; otherwise it is + /// recalculated. Extra schedules with the same tag are deleted. Changes are tracked, not saved: call + /// SaveChanges on your DbContext. + /// + /// The type of the message payload. + /// The message payload. + /// The cron expression, including seconds. + /// The timezone the expression is evaluated in. + /// The tag that identifies this schedule. + /// The cancellation token. + /// The id of the schedule. + public Task EnsureSchedule(TK message, string chronExpression, string chronTimezone, string tag, + CancellationToken cancellationToken = default) where TK : IConsumerPayload; + /// /// Deletes scheduled messages by tag. /// diff --git a/AsyncMonolith/Scheduling/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index 6b59dfc..456978d 100644 --- a/AsyncMonolith/Scheduling/ScheduleService.cs +++ b/AsyncMonolith/Scheduling/ScheduleService.cs @@ -73,6 +73,31 @@ public string Schedule(TK message, string chronExpression, string chronTimez return id; } + /// + public async Task EnsureSchedule(TK message, string chronExpression, string chronTimezone, + string tag, CancellationToken cancellationToken = default) where TK : IConsumerPayload + { + ArgumentException.ThrowIfNullOrWhiteSpace(tag); + + var set = _dbContext.Set(); + var existing = await set.Where(m => m.Tag == tag).OrderBy(m => m.Id).ToListAsync(cancellationToken); + if (existing.Count == 0) + { + return Schedule(message, chronExpression, chronTimezone, tag); + } + + var schedule = existing[0]; + set.RemoveRange(existing.Skip(1)); + + schedule.UpdatePayload(message); + if (schedule.ChronExpression != chronExpression || schedule.ChronTimezone != chronTimezone) + { + schedule.UpdateSchedule(chronExpression, chronTimezone, _timeProvider); + } + + return schedule.Id; + } + /// /// Deletes scheduled messages by tag. /// diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 2c02aed..ef7c1ea 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -98,6 +98,7 @@ internal static void InternalAddAsyncMonolith( services.AddSingleton(new AsyncMonolithIdGenerator()); services.AddScoped>(); services.AddScoped>(); + services.AddScoped>(); services.AddScoped(sp => sp.GetRequiredService()); // One processor per rail. Rails are read when the host starts, after every module has diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index c1f697c..c1f8b13 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -45,3 +45,12 @@ public class FailedMessagesController(IPoisonedMessageService poisoned) : Contro [HttpDelete("{id}")] public Task Delete(string id) => poisoned.Delete(id); } ``` + +## Queue statistics 📊 + +`IQueueStatisticsService.Read()` returns a snapshot for health checks and dashboards: + +- `Available`: messages due now and waiting for a processor +- `Waiting`: messages not yet due (delayed, waiting to retry, or being processed) +- `OldestAvailableAgeSeconds`: how long the longest-waiting due message has been due. If this keeps growing, processors are stuck or falling behind. +- `Poisoned` and `Schedules`: row counts diff --git a/docs/guides/scheduling-messages.md b/docs/guides/scheduling-messages.md index 1f00e3a..d47f247 100644 --- a/docs/guides/scheduling-messages.md +++ b/docs/guides/scheduling-messages.md @@ -11,4 +11,14 @@ To produce your message you'll need to inject a `IScheduleService` Id = id }, "0 0 12 * * MON", "UTC", "id:{id}"); await _dbContext.SaveChangesAsync(cancellationToken); -``` \ No newline at end of file +``` +## Registering schedules at startup + +`Schedule` always inserts a new schedule, so calling it at every startup creates duplicates. Use `EnsureSchedule` with a tag instead. It creates the schedule the first time, and afterwards updates the payload. It only recalculates the next occurrence if the expression or timezone changed, and removes any duplicates with the same tag. + +```csharp +await scheduleService.EnsureSchedule(new CleanupExpiredSessions(), "0 0 3 * * *", "Europe/London", tag: "cleanup-sessions"); +await dbContext.SaveChangesAsync(); +``` + +Occurrences missed while the app was not running are not caught up: the schedule fires once and moves to its next occurrence. From baaa1a8662ed377b0314981e9be4d846738d1fc5 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:31:27 +0000 Subject: [PATCH 22/53] Bring the SQL schemas and example migrations in line with the model The hand-written schemas for hosts that don't use EF migrations had drifted from the model: - rail_id was missing from consumer_messages and poisoned_messages, so rail filtering failed against those databases - trace_id and span_id were NOT NULL, but the producer writes null when no trace is active, so those inserts failed Both are fixed in all four schemas, alongside the new last_error column. The example API gets a migration for rail_id and last_error. SchemaFileTests now parses each schema and checks every model column exists with matching nullability, so the files can't drift again. --- AsyncMonolith.Tests/SchemaFileTests.cs | 74 ++++++ ...61119233024_RailIdAndLastError.Designer.cs | 237 ++++++++++++++++++ .../20261119233024_RailIdAndLastError.cs | 60 +++++ .../ApplicationDbContextModelSnapshot.cs | 77 +++--- Schemas/asyncmonolith_mariadb.sql | 10 +- Schemas/asyncmonolith_mssql.sql | 10 +- Schemas/asyncmonolith_mysql.sql | 10 +- Schemas/asyncmonolith_postgresql.sql | 10 +- 8 files changed, 443 insertions(+), 45 deletions(-) create mode 100644 AsyncMonolith.Tests/SchemaFileTests.cs create mode 100644 Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.Designer.cs create mode 100644 Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.cs diff --git a/AsyncMonolith.Tests/SchemaFileTests.cs b/AsyncMonolith.Tests/SchemaFileTests.cs new file mode 100644 index 0000000..75e1641 --- /dev/null +++ b/AsyncMonolith.Tests/SchemaFileTests.cs @@ -0,0 +1,74 @@ +using System.Text.RegularExpressions; +using AsyncMonolith.Tests.Infra; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The hand-written SQL schemas in /Schemas must match the EF model, for hosts that don't use migrations. +/// +public partial class SchemaFileTests +{ + public static TheoryData SchemaFiles => new() + { + "asyncmonolith_postgresql.sql", + "asyncmonolith_mssql.sql", + "asyncmonolith_mysql.sql", + "asyncmonolith_mariadb.sql" + }; + + private static string SchemaPath(string file) + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !Directory.Exists(Path.Combine(directory.FullName, "Schemas"))) + { + directory = directory.Parent; + } + + directory.ShouldNotBeNull("the repository's Schemas folder should be above the test output"); + return Path.Combine(directory.FullName, "Schemas", file); + } + + [GeneratedRegex(@"CREATE TABLE\s+(\w+)\s*\((.*?)\n\);", RegexOptions.Singleline | RegexOptions.IgnoreCase)] + private static partial Regex CreateTable(); + + // A column definition: a name followed by a type. Constraint lines are skipped. + [GeneratedRegex(@"^\s*(?!CONSTRAINT\b|PRIMARY\b|UNIQUE\b|KEY\b)""?(\w+)""?\s+\w", RegexOptions.IgnoreCase)] + private static partial Regex Column(); + + /// Table name to (column name to nullable). Columns are nullable unless declared NOT NULL. + private static Dictionary> ParseTables(string sql) => + CreateTable().Matches(sql).ToDictionary( + table => table.Groups[1].Value, + table => table.Groups[2].Value.Split('\n') + .Select(line => (Line: line, Match: Column().Match(line))) + .Where(c => c.Match.Success) + .ToDictionary( + c => c.Match.Groups[1].Value, + c => !c.Line.Contains("NOT NULL", StringComparison.OrdinalIgnoreCase))); + + [Theory] + [MemberData(nameof(SchemaFiles))] + public async Task Schema_file_has_every_model_column_with_matching_nullability(string file) + { + await using var connection = new SqliteConnection("DataSource=:memory:"); + await using var db = new TestDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options); + var tables = ParseTables(await File.ReadAllTextAsync(SchemaPath(file), TestContext.Current.CancellationToken)); + + foreach (var entity in db.Model.GetEntityTypes()) + { + var table = entity.GetTableName()!; + tables.ShouldContainKey(table, $"{file} should create {table}"); + + foreach (var property in entity.GetProperties()) + { + var column = property.GetColumnName(); + tables[table].ShouldContainKey(column, $"{file} should have {table}.{column}"); + tables[table][column].ShouldBe(property.IsNullable, + $"{file}: {table}.{column} nullability should match the model"); + } + } + } +} diff --git a/Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.Designer.cs b/Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.Designer.cs new file mode 100644 index 0000000..34841c1 --- /dev/null +++ b/Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.Designer.cs @@ -0,0 +1,237 @@ +// +using Example.Api; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Demo.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261119233024_RailIdAndLastError")] + partial class RailIdAndLastError + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.15") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("AsyncMonolith.Consumers.ConsumerMessage", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id") + .HasJsonPropertyName("id"); + + b.Property("Attempts") + .HasColumnType("integer") + .HasColumnName("attempts") + .HasJsonPropertyName("attempts"); + + b.Property("AvailableAfter") + .HasColumnType("bigint") + .HasColumnName("available_after") + .HasJsonPropertyName("available_after"); + + b.Property("ConsumerType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("consumer_type") + .HasJsonPropertyName("consumer_type"); + + b.Property("CreatedAt") + .HasColumnType("bigint") + .HasColumnName("created_at") + .HasJsonPropertyName("created_at"); + + b.Property("InsertId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("insert_id") + .HasJsonPropertyName("insert_id"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error") + .HasJsonPropertyName("last_error"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload") + .HasJsonPropertyName("payload"); + + b.Property("PayloadType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload_type") + .HasJsonPropertyName("payload_type"); + + b.Property("RailId") + .HasColumnType("integer") + .HasColumnName("rail_id") + .HasJsonPropertyName("rail_id"); + + b.Property("SpanId") + .HasColumnType("text") + .HasColumnName("span_id") + .HasJsonPropertyName("span_id"); + + b.Property("TraceId") + .HasColumnType("text") + .HasColumnName("trace_id") + .HasJsonPropertyName("trace_id"); + + b.HasKey("Id"); + + b.HasIndex("InsertId", "ConsumerType") + .IsUnique(); + + b.ToTable("consumer_messages"); + }); + + modelBuilder.Entity("AsyncMonolith.Consumers.PoisonedMessage", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id") + .HasJsonPropertyName("id"); + + b.Property("Attempts") + .HasColumnType("integer") + .HasColumnName("attempts") + .HasJsonPropertyName("attempts"); + + b.Property("AvailableAfter") + .HasColumnType("bigint") + .HasColumnName("available_after") + .HasJsonPropertyName("available_after"); + + b.Property("ConsumerType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("consumer_type") + .HasJsonPropertyName("consumer_type"); + + b.Property("CreatedAt") + .HasColumnType("bigint") + .HasColumnName("created_at") + .HasJsonPropertyName("created_at"); + + b.Property("InsertId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("insert_id") + .HasJsonPropertyName("insert_id"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error") + .HasJsonPropertyName("last_error"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload") + .HasJsonPropertyName("payload"); + + b.Property("PayloadType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload_type") + .HasJsonPropertyName("payload_type"); + + b.Property("RailId") + .HasColumnType("integer") + .HasColumnName("rail_id") + .HasJsonPropertyName("rail_id"); + + b.Property("SpanId") + .HasColumnType("text") + .HasColumnName("span_id") + .HasJsonPropertyName("span_id"); + + b.Property("TraceId") + .HasColumnType("text") + .HasColumnName("trace_id") + .HasJsonPropertyName("trace_id"); + + b.HasKey("Id"); + + b.ToTable("poisoned_messages"); + }); + + modelBuilder.Entity("AsyncMonolith.Scheduling.ScheduledMessage", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id") + .HasJsonPropertyName("id"); + + b.Property("AvailableAfter") + .HasColumnType("bigint") + .HasColumnName("available_after") + .HasJsonPropertyName("available_after"); + + b.Property("ChronExpression") + .IsRequired() + .HasColumnType("text") + .HasColumnName("chron_expression") + .HasJsonPropertyName("chron_expression"); + + b.Property("ChronTimezone") + .IsRequired() + .HasColumnType("text") + .HasColumnName("chron_timezone") + .HasJsonPropertyName("chron_timezone"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload") + .HasJsonPropertyName("payload"); + + b.Property("PayloadType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload_type") + .HasJsonPropertyName("payload_type"); + + b.Property("Tag") + .HasColumnType("text") + .HasColumnName("tag") + .HasJsonPropertyName("tag"); + + b.HasKey("Id"); + + b.ToTable("scheduled_messages"); + }); + + modelBuilder.Entity("Example.Api.Spam.SubmittedValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Value") + .HasColumnType("double precision") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.ToTable("submitted_values"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.cs b/Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.cs new file mode 100644 index 0000000..a43f028 --- /dev/null +++ b/Example/Example.Api/Migrations/20261119233024_RailIdAndLastError.cs @@ -0,0 +1,60 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Demo.Migrations +{ + /// + public partial class RailIdAndLastError : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "last_error", + table: "poisoned_messages", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "rail_id", + table: "poisoned_messages", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "last_error", + table: "consumer_messages", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "rail_id", + table: "consumer_messages", + type: "integer", + nullable: false, + defaultValue: 0); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "last_error", + table: "poisoned_messages"); + + migrationBuilder.DropColumn( + name: "rail_id", + table: "poisoned_messages"); + + migrationBuilder.DropColumn( + name: "last_error", + table: "consumer_messages"); + + migrationBuilder.DropColumn( + name: "rail_id", + table: "consumer_messages"); + } + } +} diff --git a/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs b/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs index 5a9b593..cd650c7 100644 --- a/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs @@ -1,5 +1,4 @@ // -using Demo; using Example.Api; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -17,7 +16,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.6") + .HasAnnotation("ProductVersion", "10.0.15") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -27,56 +26,66 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Id") .HasColumnType("text") .HasColumnName("id") - .HasAnnotation("Relational:JsonPropertyName", "id"); + .HasJsonPropertyName("id"); b.Property("Attempts") .HasColumnType("integer") .HasColumnName("attempts") - .HasAnnotation("Relational:JsonPropertyName", "attempts"); + .HasJsonPropertyName("attempts"); b.Property("AvailableAfter") .HasColumnType("bigint") .HasColumnName("available_after") - .HasAnnotation("Relational:JsonPropertyName", "available_after"); + .HasJsonPropertyName("available_after"); b.Property("ConsumerType") .IsRequired() .HasColumnType("text") .HasColumnName("consumer_type") - .HasAnnotation("Relational:JsonPropertyName", "consumer_type"); + .HasJsonPropertyName("consumer_type"); b.Property("CreatedAt") .HasColumnType("bigint") .HasColumnName("created_at") - .HasAnnotation("Relational:JsonPropertyName", "created_at"); + .HasJsonPropertyName("created_at"); b.Property("InsertId") .IsRequired() .HasColumnType("text") .HasColumnName("insert_id") - .HasAnnotation("Relational:JsonPropertyName", "insert_id"); + .HasJsonPropertyName("insert_id"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error") + .HasJsonPropertyName("last_error"); b.Property("Payload") .IsRequired() .HasColumnType("text") .HasColumnName("payload") - .HasAnnotation("Relational:JsonPropertyName", "payload"); + .HasJsonPropertyName("payload"); b.Property("PayloadType") .IsRequired() .HasColumnType("text") .HasColumnName("payload_type") - .HasAnnotation("Relational:JsonPropertyName", "payload_type"); + .HasJsonPropertyName("payload_type"); + + b.Property("RailId") + .HasColumnType("integer") + .HasColumnName("rail_id") + .HasJsonPropertyName("rail_id"); b.Property("SpanId") .HasColumnType("text") .HasColumnName("span_id") - .HasAnnotation("Relational:JsonPropertyName", "span_id"); + .HasJsonPropertyName("span_id"); b.Property("TraceId") .HasColumnType("text") .HasColumnName("trace_id") - .HasAnnotation("Relational:JsonPropertyName", "trace_id"); + .HasJsonPropertyName("trace_id"); b.HasKey("Id"); @@ -91,56 +100,66 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Id") .HasColumnType("text") .HasColumnName("id") - .HasAnnotation("Relational:JsonPropertyName", "id"); + .HasJsonPropertyName("id"); b.Property("Attempts") .HasColumnType("integer") .HasColumnName("attempts") - .HasAnnotation("Relational:JsonPropertyName", "attempts"); + .HasJsonPropertyName("attempts"); b.Property("AvailableAfter") .HasColumnType("bigint") .HasColumnName("available_after") - .HasAnnotation("Relational:JsonPropertyName", "available_after"); + .HasJsonPropertyName("available_after"); b.Property("ConsumerType") .IsRequired() .HasColumnType("text") .HasColumnName("consumer_type") - .HasAnnotation("Relational:JsonPropertyName", "consumer_type"); + .HasJsonPropertyName("consumer_type"); b.Property("CreatedAt") .HasColumnType("bigint") .HasColumnName("created_at") - .HasAnnotation("Relational:JsonPropertyName", "created_at"); + .HasJsonPropertyName("created_at"); b.Property("InsertId") .IsRequired() .HasColumnType("text") .HasColumnName("insert_id") - .HasAnnotation("Relational:JsonPropertyName", "insert_id"); + .HasJsonPropertyName("insert_id"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error") + .HasJsonPropertyName("last_error"); b.Property("Payload") .IsRequired() .HasColumnType("text") .HasColumnName("payload") - .HasAnnotation("Relational:JsonPropertyName", "payload"); + .HasJsonPropertyName("payload"); b.Property("PayloadType") .IsRequired() .HasColumnType("text") .HasColumnName("payload_type") - .HasAnnotation("Relational:JsonPropertyName", "payload_type"); + .HasJsonPropertyName("payload_type"); + + b.Property("RailId") + .HasColumnType("integer") + .HasColumnName("rail_id") + .HasJsonPropertyName("rail_id"); b.Property("SpanId") .HasColumnType("text") .HasColumnName("span_id") - .HasAnnotation("Relational:JsonPropertyName", "span_id"); + .HasJsonPropertyName("span_id"); b.Property("TraceId") .HasColumnType("text") .HasColumnName("trace_id") - .HasAnnotation("Relational:JsonPropertyName", "trace_id"); + .HasJsonPropertyName("trace_id"); b.HasKey("Id"); @@ -152,41 +171,41 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Id") .HasColumnType("text") .HasColumnName("id") - .HasAnnotation("Relational:JsonPropertyName", "id"); + .HasJsonPropertyName("id"); b.Property("AvailableAfter") .HasColumnType("bigint") .HasColumnName("available_after") - .HasAnnotation("Relational:JsonPropertyName", "available_after"); + .HasJsonPropertyName("available_after"); b.Property("ChronExpression") .IsRequired() .HasColumnType("text") .HasColumnName("chron_expression") - .HasAnnotation("Relational:JsonPropertyName", "chron_expression"); + .HasJsonPropertyName("chron_expression"); b.Property("ChronTimezone") .IsRequired() .HasColumnType("text") .HasColumnName("chron_timezone") - .HasAnnotation("Relational:JsonPropertyName", "chron_timezone"); + .HasJsonPropertyName("chron_timezone"); b.Property("Payload") .IsRequired() .HasColumnType("text") .HasColumnName("payload") - .HasAnnotation("Relational:JsonPropertyName", "payload"); + .HasJsonPropertyName("payload"); b.Property("PayloadType") .IsRequired() .HasColumnType("text") .HasColumnName("payload_type") - .HasAnnotation("Relational:JsonPropertyName", "payload_type"); + .HasJsonPropertyName("payload_type"); b.Property("Tag") .HasColumnType("text") .HasColumnName("tag") - .HasAnnotation("Relational:JsonPropertyName", "tag"); + .HasJsonPropertyName("tag"); b.HasKey("Id"); diff --git a/Schemas/asyncmonolith_mariadb.sql b/Schemas/asyncmonolith_mariadb.sql index 4917c0f..a73fa4f 100644 --- a/Schemas/asyncmonolith_mariadb.sql +++ b/Schemas/asyncmonolith_mariadb.sql @@ -9,8 +9,9 @@ CREATE TABLE consumer_messages ( payload_type VARCHAR(255) NOT NULL, payload TEXT NOT NULL, insert_id VARCHAR(255) NOT NULL, - trace_id VARCHAR(255) NOT NULL, - span_id VARCHAR(255) NOT NULL, + trace_id VARCHAR(255) NULL, + span_id VARCHAR(255) NULL, + rail_id INT NOT NULL DEFAULT 0, last_error TEXT NULL, PRIMARY KEY (id) ); @@ -24,8 +25,9 @@ CREATE TABLE poisoned_messages ( payload_type VARCHAR(255) NOT NULL, payload TEXT NOT NULL, insert_id VARCHAR(255) NOT NULL, - trace_id VARCHAR(255) NOT NULL, - span_id VARCHAR(255) NOT NULL, + trace_id VARCHAR(255) NULL, + span_id VARCHAR(255) NULL, + rail_id INT NOT NULL DEFAULT 0, last_error TEXT NULL, PRIMARY KEY (id) ); diff --git a/Schemas/asyncmonolith_mssql.sql b/Schemas/asyncmonolith_mssql.sql index 07d41c9..d753274 100644 --- a/Schemas/asyncmonolith_mssql.sql +++ b/Schemas/asyncmonolith_mssql.sql @@ -9,8 +9,9 @@ CREATE TABLE consumer_messages ( payload_type NVARCHAR(255) NOT NULL, payload NVARCHAR(MAX) NOT NULL, insert_id NVARCHAR(255) NOT NULL, - trace_id NVARCHAR(255) NOT NULL, - span_id NVARCHAR(255) NOT NULL, + trace_id NVARCHAR(255) NULL, + span_id NVARCHAR(255) NULL, + rail_id INT NOT NULL DEFAULT 0, last_error NVARCHAR(MAX) NULL, CONSTRAINT PK_consumer_messages PRIMARY KEY (id) @@ -25,8 +26,9 @@ CREATE TABLE poisoned_messages ( payload_type NVARCHAR(255) NOT NULL, payload NVARCHAR(MAX) NOT NULL, insert_id NVARCHAR(255) NOT NULL, - trace_id NVARCHAR(255) NOT NULL, - span_id NVARCHAR(255) NOT NULL, + trace_id NVARCHAR(255) NULL, + span_id NVARCHAR(255) NULL, + rail_id INT NOT NULL DEFAULT 0, last_error NVARCHAR(MAX) NULL, CONSTRAINT PK_poisoned_messages PRIMARY KEY (id) diff --git a/Schemas/asyncmonolith_mysql.sql b/Schemas/asyncmonolith_mysql.sql index 4917c0f..a73fa4f 100644 --- a/Schemas/asyncmonolith_mysql.sql +++ b/Schemas/asyncmonolith_mysql.sql @@ -9,8 +9,9 @@ CREATE TABLE consumer_messages ( payload_type VARCHAR(255) NOT NULL, payload TEXT NOT NULL, insert_id VARCHAR(255) NOT NULL, - trace_id VARCHAR(255) NOT NULL, - span_id VARCHAR(255) NOT NULL, + trace_id VARCHAR(255) NULL, + span_id VARCHAR(255) NULL, + rail_id INT NOT NULL DEFAULT 0, last_error TEXT NULL, PRIMARY KEY (id) ); @@ -24,8 +25,9 @@ CREATE TABLE poisoned_messages ( payload_type VARCHAR(255) NOT NULL, payload TEXT NOT NULL, insert_id VARCHAR(255) NOT NULL, - trace_id VARCHAR(255) NOT NULL, - span_id VARCHAR(255) NOT NULL, + trace_id VARCHAR(255) NULL, + span_id VARCHAR(255) NULL, + rail_id INT NOT NULL DEFAULT 0, last_error TEXT NULL, PRIMARY KEY (id) ); diff --git a/Schemas/asyncmonolith_postgresql.sql b/Schemas/asyncmonolith_postgresql.sql index 0699428..527c7c4 100644 --- a/Schemas/asyncmonolith_postgresql.sql +++ b/Schemas/asyncmonolith_postgresql.sql @@ -9,8 +9,9 @@ CREATE TABLE consumer_messages ( payload_type text NOT NULL, payload text NOT NULL, insert_id text NOT NULL, - trace_id text NOT NULL, - span_id text NOT NULL, + trace_id text NULL, + span_id text NULL, + rail_id integer NOT NULL DEFAULT 0, last_error text NULL, CONSTRAINT "PK_consumer_messages" PRIMARY KEY (id) @@ -25,8 +26,9 @@ CREATE TABLE poisoned_messages ( payload_type text NOT NULL, payload text NOT NULL, insert_id text NOT NULL, - trace_id text NOT NULL, - span_id text NOT NULL, + trace_id text NULL, + span_id text NULL, + rail_id integer NOT NULL DEFAULT 0, last_error text NULL, CONSTRAINT "PK_poisoned_messages" PRIMARY KEY (id) From 4e30fe6cf093d98bc1957fee4b5e401c4ec0c2b9 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:32:23 +0000 Subject: [PATCH 23/53] Keep when a poisoned message became due Since messages are leased while processing, a poisoned message's AvailableAfter held the lease expiry, which means nothing once it is poisoned. The claim now remembers when each message became due, and the poisoned message keeps that, as it did before leasing. Found by the integration tests on CI; the fast poisoning test now checks it too. --- .../ConsumerProcessingTests.cs | 5 ++-- .../Consumers/ConsumerMessageProcessor.cs | 28 ++++++++++++------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs index b549961..339d082 100644 --- a/AsyncMonolith.Tests/ConsumerProcessingTests.cs +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -100,6 +100,7 @@ public async Task Message_is_poisoned_after_the_configured_max_attempts() poisoned.Payload.ShouldBe(original.Payload); poisoned.InsertId.ShouldBe("insert-1"); poisoned.CreatedAt.ShouldBe(original.CreatedAt); + poisoned.AvailableAfter.ShouldBe(original.AvailableAfter, "it records when the message last became due"); poisoned.RailId.ShouldBe(original.RailId); // Poisoned messages are never picked up again @@ -291,7 +292,7 @@ public async Task Claimed_message_is_leased_so_other_processors_skip_it() // Simulate a processor that claimed the message and then crashed before finishing it. var claimed = await host.ConsumerProcessor.ClaimBatch(Ct); - claimed.ShouldHaveSingleItem().Attempts.ShouldBe(1); + claimed.ShouldHaveSingleItem().Message.Attempts.ShouldBe(1); // While the lease (consumer timeout + grace period) is held, nobody else picks it up. (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); @@ -311,7 +312,7 @@ public async Task Completing_a_message_whose_lease_was_taken_over_leaves_it_alon var claimed = (await host.ConsumerProcessor.ClaimBatch(Ct)).ShouldHaveSingleItem(); // Another processor re-claimed the message after our lease expired. - await host.Change(db => db.ConsumerMessages.Single().AvailableAfter = claimed.AvailableAfter + 100); + await host.Change(db => db.ConsumerMessages.Single().AvailableAfter = claimed.Message.AvailableAfter + 100); await host.ConsumerProcessor.Complete(claimed, success: true, Ct); diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 35a86c3..1f2a988 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -111,7 +111,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) } var tasks = new List>>(); - foreach (var consumerMessageGroup in messages.GroupBy(m => m.ConsumerType)) + foreach (var consumerMessageGroup in messages.GroupBy(m => m.Message.ConsumerType)) { var group = consumerMessageGroup.ToList(); var executionMode = _consumerRegistry.ResolveConsumerExecutionMode(consumerMessageGroup.Key); @@ -146,7 +146,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) /// Fetches the next batch for this rail and leases it in one short transaction. /// /// The claimed messages, with their attempt counted and their lease in AvailableAfter. - internal async Task> ClaimBatch(CancellationToken cancellationToken) + internal async Task> ClaimBatch(CancellationToken cancellationToken) { using var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); @@ -157,9 +157,10 @@ internal async Task> ClaimBatch(CancellationToken cancella cancellationToken); if (messages.Count == 0) { - return messages; + return []; } + var claimed = messages.Select(m => new ClaimedMessage(m, m.AvailableAfter)).ToList(); foreach (var message in messages) { message.Attempts++; @@ -169,15 +170,15 @@ internal async Task> ClaimBatch(CancellationToken cancella await dbContext.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); - return messages; + return claimed; } - private async Task ProcessAndComplete(ConsumerMessage message, CancellationToken cancellationToken) + private async Task ProcessAndComplete(ClaimedMessage claimed, CancellationToken cancellationToken) { - var error = await Process(message, cancellationToken); + var error = await Process(claimed.Message, cancellationToken); // Record the outcome even when stopping, so the attempt isn't left waiting for its lease to expire. - await Complete(message, error is null, CancellationToken.None, error); + await Complete(claimed, error is null, CancellationToken.None, error); return error is null; } @@ -185,9 +186,10 @@ private async Task ProcessAndComplete(ConsumerMessage message, Cancellatio /// Records the outcome of a claimed message: removes it on success, otherwise schedules a retry or /// moves it to the poisoned messages. Does nothing if the lease has since been taken over. /// - internal async Task Complete(ConsumerMessage message, bool success, CancellationToken cancellationToken, + internal async Task Complete(ClaimedMessage claimed, bool success, CancellationToken cancellationToken, string? error = null) { + var message = claimed.Message; using var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); var leased = dbContext.Set() @@ -219,7 +221,7 @@ await leased.ExecuteUpdateAsync(s => s { Id = message.Id, Attempts = message.Attempts, - AvailableAfter = message.AvailableAfter, + AvailableAfter = claimed.DueAt, ConsumerType = message.ConsumerType, CreatedAt = message.CreatedAt, Payload = message.Payload, @@ -316,4 +318,10 @@ private static string Describe(Exception exception) var description = $"{exception.GetType().FullName}: {exception.Message}"; return description.Length <= MaxErrorLength ? description : description[..MaxErrorLength]; } -} \ No newline at end of file +} + +/// +/// A message claimed by a processor: the message (attempt counted, lease in AvailableAfter) and the time it +/// became due before it was leased. +/// +internal sealed record ClaimedMessage(ConsumerMessage Message, long DueAt); From 156813b959b11ca8a018b1b843ff95f246ec52f5 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Thu, 19 Nov 2026 23:33:13 +0000 Subject: [PATCH 24/53] Release every package together at 10.1.0 - One Version in Directory.Build.props replaces the per-project PackageVersion values (core and TestHelpers were 10.0.0, providers 10.0.1). Providers and TestHelpers now depend on the core package at that same version. - A single publish workflow replaces the five per-package ones. Those pinned the .NET 8 SDK, which cannot build net10.0, and there was none for the core package or MariaDb. The new one builds, runs the fast tests, packs all seven packages and pushes them (skipping existing versions), on a v* tag or manual dispatch. Packing was checked locally. - Test and publish workflows read the SDK from global.json; SonarCloud uses current action versions. - docs/releases.md describes 10.1.0, its migration and breaking changes. - .DS_Store files are no longer tracked and are ignored. --- .DS_Store | Bin 10244 -> 0 bytes .github/workflows/SonarCloud.yml | 8 ++-- ...ublish-AsyncMonolith.Ef-nuget-package.yaml | 29 -------------- ...ish-AsyncMonolith.MsSql-nuget-package.yaml | 29 -------------- ...ish-AsyncMonolith.MySql-nuget-package.yaml | 29 -------------- ...syncMonolith.PostgreSql-nuget-package.yaml | 29 -------------- ...yncMonolith.TestHelpers-nuget-package.yaml | 29 -------------- .github/workflows/publish.yml | 36 ++++++++++++++++++ .github/workflows/test.yml | 4 +- .gitignore | 3 ++ AsyncMonolith.Ef/.DS_Store | Bin 6148 -> 0 bytes AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 1 - AsyncMonolith.MariaDb/.DS_Store | Bin 6148 -> 0 bytes .../AsyncMonolith.MariaDb.csproj | 1 - AsyncMonolith.MsSql/.DS_Store | Bin 6148 -> 0 bytes .../AsyncMonolith.MsSql.csproj | 1 - AsyncMonolith.MySql/.DS_Store | Bin 6148 -> 0 bytes .../AsyncMonolith.MySql.csproj | 1 - AsyncMonolith.PostgreSql/.DS_Store | Bin 8196 -> 0 bytes .../AsyncMonolith.PostgreSql.csproj | 1 - .../AsyncMonolith.TestHelpers.csproj | 1 - AsyncMonolith/.DS_Store | Bin 6148 -> 0 bytes AsyncMonolith/AsyncMonolith.csproj | 1 - Directory.Build.props | 3 ++ docs/releases.md | 25 ++++++++++++ 25 files changed, 73 insertions(+), 158 deletions(-) delete mode 100644 .DS_Store delete mode 100644 .github/workflows/publish-AsyncMonolith.Ef-nuget-package.yaml delete mode 100644 .github/workflows/publish-AsyncMonolith.MsSql-nuget-package.yaml delete mode 100644 .github/workflows/publish-AsyncMonolith.MySql-nuget-package.yaml delete mode 100644 .github/workflows/publish-AsyncMonolith.PostgreSql-nuget-package.yaml delete mode 100644 .github/workflows/publish-AsyncMonolith.TestHelpers-nuget-package.yaml create mode 100644 .github/workflows/publish.yml delete mode 100644 AsyncMonolith.Ef/.DS_Store delete mode 100644 AsyncMonolith.MariaDb/.DS_Store delete mode 100644 AsyncMonolith.MsSql/.DS_Store delete mode 100644 AsyncMonolith.MySql/.DS_Store delete mode 100644 AsyncMonolith.PostgreSql/.DS_Store delete mode 100644 AsyncMonolith/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 9309a8d833613e8de4fbd9c9fab2a4ef2d01455a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10244 zcmeI1TTc@~6vxj%wJk`3B2i;ZHkue?uwuO+@ueUnnusyf=z|*Er3)-9yOnJrgpl-A z{USb?_~ZTTnzz3zz{ef zz~h63%(9foMl9vffs5P%KxXh*Cfs8mAZ@HfmJ->Br8I@lc=sR@Q;}>jL~M@#Emnst zC9)CA*qlUcP9iB;Bs&x#ONX5$)k&0MX|9HVA<#;I_wFN9pbCYwtnA-I?Bw0Yez@%T zp#v>`v1X79KV-rkzxD;}^*yR-dS5iXY*UZcs7{WmEiP%=LkHUNNkW^Nh>x1h3D|gO zg-f>P{kx_)f>uPdixY}vT0pA9=-G#1P_wG~%IsPM`&*hg!&+Y9^6(_9X{k!`U*4}h+a>BYZUEJT#=f1J4F1(r2+Th>3E>-qrn>Vu`bXfD$_gi)gCPetu*i+y&MnN zJvO#a(7SCx^GM$h=)}wa0Xk`{2Ks!*9{mgxUWDmxl_&VN$a%_4Bk$YaQN#Z;(_!Du z*1~YQV;CZ=Is$c2kt>cg_)FbAV7i?{Kx+u3i)#%lnE;`URL}53;(BTVzWnQ+QDPk( z2w!@%GB5`zWnAc3#&dY!Zukh&rz-o?Yt4hK;<59%)AXpdo!5$rmqBuvl3II#POoT< z$<^cv=G;2!SL=;4M^N#SL3CW&q);tQ#^X~e9y#cFD2rc88~R!sczzdY{c&Z*egkXS z5LQ+BYP+aw1y8E*71Fv|vSga}bg_%4khW!P_`4pjuM1c^Z?;T_%sB1!Oc$^1d~gKP zJ~D|9jfG^K)*C~7I7+;tU(??M)OQ{I4C{QA14m%sYAOO*dP0xsAr`Ms;bUIY27g6+ z2n;rw^*e+Kdaq(Lh*~%;@c=nRD^H84!wmYv0%QT@RMfg~PgN|ks4usi`aQED?`8#IK~7-X0ALpiv~8&hV-`bS-XY&7MT<4HDW1E zaFNIHkn%VlKlnKQ8ZzrnvgCyOQX(6%#1o{y{xLu~%j&$ST)^VN?Eht$;tL-X_J~Z| T4|TIL`~MVXqFzA%`u_hX@jFaJ diff --git a/.github/workflows/SonarCloud.yml b/.github/workflows/SonarCloud.yml index b12f52a..b069ddf 100644 --- a/.github/workflows/SonarCloud.yml +++ b/.github/workflows/SonarCloud.yml @@ -15,22 +15,22 @@ jobs: runs-on: windows-latest steps: - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: 'zulu' # Alternative distribution options are available. - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Cache SonarCloud packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~\sonar\cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Cache SonarCloud scanner id: cache-sonar-scanner - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: .\.sonar\scanner key: ${{ runner.os }}-sonar-scanner diff --git a/.github/workflows/publish-AsyncMonolith.Ef-nuget-package.yaml b/.github/workflows/publish-AsyncMonolith.Ef-nuget-package.yaml deleted file mode 100644 index 9e0ac39..0000000 --- a/.github/workflows/publish-AsyncMonolith.Ef-nuget-package.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Publish AsyncMonolith.Ef nuget package - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - defaults: - run: - working-directory: AsyncMonolith.Ef - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 8.0.x - - - name: Build and Package - run: | - dotnet restore - dotnet build -c Release - dotnet pack --configuration Release --output nupkg - - - name: Publish to NuGet - run: | - dotnet nuget push ./nupkg/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} diff --git a/.github/workflows/publish-AsyncMonolith.MsSql-nuget-package.yaml b/.github/workflows/publish-AsyncMonolith.MsSql-nuget-package.yaml deleted file mode 100644 index 8fee01f..0000000 --- a/.github/workflows/publish-AsyncMonolith.MsSql-nuget-package.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Publish AsyncMonolith.MsSql nuget package - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - defaults: - run: - working-directory: AsyncMonolith.MsSql - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 8.0.x - - - name: Build and Package - run: | - dotnet restore - dotnet build -c Release - dotnet pack --configuration Release --output nupkg - - - name: Publish to NuGet - run: | - dotnet nuget push ./nupkg/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} diff --git a/.github/workflows/publish-AsyncMonolith.MySql-nuget-package.yaml b/.github/workflows/publish-AsyncMonolith.MySql-nuget-package.yaml deleted file mode 100644 index 2140f55..0000000 --- a/.github/workflows/publish-AsyncMonolith.MySql-nuget-package.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Publish AsyncMonolith.MySql nuget package - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - defaults: - run: - working-directory: AsyncMonolith.MySql - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 8.0.x - - - name: Build and Package - run: | - dotnet restore - dotnet build -c Release - dotnet pack --configuration Release --output nupkg - - - name: Publish to NuGet - run: | - dotnet nuget push ./nupkg/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} diff --git a/.github/workflows/publish-AsyncMonolith.PostgreSql-nuget-package.yaml b/.github/workflows/publish-AsyncMonolith.PostgreSql-nuget-package.yaml deleted file mode 100644 index 3d973ee..0000000 --- a/.github/workflows/publish-AsyncMonolith.PostgreSql-nuget-package.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Publish AsyncMonolith.PostgreSql nuget package - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - defaults: - run: - working-directory: AsyncMonolith.PostgreSql - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 8.0.x - - - name: Build and Package - run: | - dotnet restore - dotnet build -c Release - dotnet pack --configuration Release --output nupkg - - - name: Publish to NuGet - run: | - dotnet nuget push ./nupkg/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} diff --git a/.github/workflows/publish-AsyncMonolith.TestHelpers-nuget-package.yaml b/.github/workflows/publish-AsyncMonolith.TestHelpers-nuget-package.yaml deleted file mode 100644 index ecf210b..0000000 --- a/.github/workflows/publish-AsyncMonolith.TestHelpers-nuget-package.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Publish AsyncMonolith.TestHelpers nuget package - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - defaults: - run: - working-directory: AsyncMonolith.TestHelpers - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 8.0.x - - - name: Build and Package - run: | - dotnet restore - dotnet build -c Release - dotnet pack --configuration Release --output nupkg - - - name: Publish to NuGet - run: | - dotnet nuget push ./nupkg/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..b99c1de --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,36 @@ +name: Publish NuGet packages + +# Publishes every package at the version in Directory.Build.props. The providers and test helpers +# depend on the core package at that same version, so they are always released together. +on: + workflow_dispatch: + push: + tags: + - 'v*' + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: Build + run: dotnet build AsyncMonolith.sln -c Release + + - name: Fast tests + run: dotnet test --project AsyncMonolith.Tests -c Release --no-build --filter-not-trait "Category=Integration" + + - name: Pack + run: | + for project in AsyncMonolith AsyncMonolith.Ef AsyncMonolith.PostgreSql AsyncMonolith.MsSql AsyncMonolith.MySql AsyncMonolith.MariaDb AsyncMonolith.TestHelpers; do + dotnet pack "$project/$project.csproj" -c Release --no-build --output nupkg + done + + - name: Publish to NuGet + run: dotnet nuget push "nupkg/*.nupkg" --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} --skip-duplicate diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 36a86af..e38d414 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,7 +22,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + global-json-file: global.json - name: Fast tests run: dotnet test --project AsyncMonolith.Tests --filter-not-trait "Category=Integration" @@ -37,7 +37,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + global-json-file: global.json - name: Integration tests run: dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" diff --git a/.gitignore b/.gitignore index 8a30d25..22a144f 100644 --- a/.gitignore +++ b/.gitignore @@ -396,3 +396,6 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml + +# macOS +.DS_Store diff --git a/AsyncMonolith.Ef/.DS_Store b/AsyncMonolith.Ef/.DS_Store deleted file mode 100644 index d3d9d73187f9ce7f847d35b93ba78c4b1e05e0b5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKO^Xvj5UozKCUFsRh^(N(fY)V>QIy3?HoFl#EQlj|P>C~{n2b9+6Ec&{E+LSs z`d0*x{uBR;Cw*1j3z;Myyog9w=zi7RRn@7N{zwy%YEOcDL^UF+pfHxMqS_!l&Sgys zricBM#OTp6B^0AXYu2{IGGH0_*BIcvyF&+*(gpVI^8O7eqap24hu)*^!D2*X?CcLu zqon6Yi4RXcHV#nseu_XNDw0nj#Vb}{H(UABbYxqU}8{-y5uFT?({TdN-?apr|_e=H7R(1*#JS796^({?h6gH(K7 zJy5Mys@>YoY<9n~>ogxen(sQZ{U-DW`_1{hTDgAb?&Ig(ljt-~K1x!gaKMRNGk6J~ zpqP};+;JQw@c=z+eN(7AlmjuP37t|O1RkSK@$qN??FmW-a)&Y|H0Oy^w-ITX-nvA6 zCO<`hs6Fv?r9K1k+};%D^Gcjs62~=jbEF8K!5@FWA1iUUu#6^HDkn6^XHsBZmNO}W z8Gqw)`m(f~>g0kU5BX*iw?pU9`j{m}wtU&7oAM=IaLaMfw327QEa}R2zT37e1C{~H zfLvk@c;IuQWpJTUjt*4v1OS%MEdrhY6tItDuw`(e5hD<#U4hzFnJ0$Q?&x=nUCZD? zqjo1{9v{lgtjr5V$?S;lh&id2Mq673ECYE4in>|j`@i%1_kZ5Wwk!jdf&YpDRXTEy z+DOUVt!v5gUF)E{Lt$aNg+_5fWv*jU_$t1EB7!l86=2KYLL+)0_K$$jU@ObOUuEDI D*e1%S diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index 8898132..f465ff6 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -3,7 +3,6 @@ true AsyncMonolith.Ef - 10.0.1 Tim Jones Aptacode Entity Framework interface for AsyncMonolith diff --git a/AsyncMonolith.MariaDb/.DS_Store b/AsyncMonolith.MariaDb/.DS_Store deleted file mode 100644 index 5560b457a82c21fc3b1405b67570788959e3662d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKUuzRV5T8v_lURg2R8&wn@wL<#MJc|dX)5?o5Kr_$CEn#ia`t)~a+gLafxN0; zMexyY;&<^$e>1y<{1fy=#O{Qhncbb4%lvM4=az_6YaHDnsu58Ijb-T~*c#$_ZYxx< zBkZRnMwbprQ;L?XSi1p-fJ5M4LxA`0b=sqh-ecd+@86hm8qf}QbU-7D!P^v~--YcE zBbwemPINa+bch&yfb5~|{1AdhRD^v@>5|o#^;Y2|8`@Z3!(kF9%*e+kk#=w=tboE0=HGe)zO=lpLq}gCs=?N1f0m zE6>D7C^qF2f0QOV?PG+ky(JL$<&ey1Ovls%l!xFMegXBNJwnR?^FZbV@I?sK4aA%W z`r1ij1(6zTaHEHQhXIn2y-4QkWDLRMq&iyJ_G~? K#~cEG6@j0Ln$k}I diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index eea8df1..35d0d43 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -6,7 +6,6 @@ NU5104 true AsyncMonolith.MariaDb - 10.0.1 Tim Jones Aptacode MariaDb interface for AsyncMonolith diff --git a/AsyncMonolith.MsSql/.DS_Store b/AsyncMonolith.MsSql/.DS_Store deleted file mode 100644 index 761582a7975e97762233642e4960fa9ab1e37dcf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKON$dh5Ux(LCUFsRSXmL&0k2DpQIy3?HoGf$SP)0_pb|5gkc>M!9n+JI5(0Bo z|BB$zf8u}fq+fOS!sM|BFCuPNsQ#)SRg?OrAJar6+LQ1uQH_WyP{z__6l;Y0Sy!ZB zTi8$N7(F^7NeMJw8SNSz1CD`zjR9V}*J+OweZ;!WuiuDL8d4oAT9Hrhv7+nfS2UtA z*7v(7vFru04B*e3#~!r)OA9QbA_WvtvNY=3`cc7Djcly%!6=SY+GzX`g<@&rQn_3$ zZoGJ1#Y5ev$zG&S+(5iM z$=kWuPxWgF5xb}TeO;d7C2)ORv@c81Zsnr+_J44^82;fO|JR>O(Kj%?CYU_OG+4~4 zz)a<{DuSh8?F9Rpn_yd*lqr}SqvW`U^Z`~MPf^I34o#eygztQ#+Jp*px!!A=qmuQgk~+U`E!7MJc})hnL+eGgmDELS7EOh!nmW| zv*TJ8GlRyRguQ$S`($BnC_+CS@jX49M9ZKn9RrSmMFxtdTI2Ko@cjG#qLZsR1{?$b z6$7Gl;2*S+l092jlH;@1gT95b@VLyNc0pl}V{PzJd=07veI6UYmc`5 true AsyncMonolith.MsSql - 10.0.1 Tim Jones Aptacode MsSql interface for AsyncMonolith diff --git a/AsyncMonolith.MySql/.DS_Store b/AsyncMonolith.MySql/.DS_Store deleted file mode 100644 index 6bd910628f59b468b34f08b964f9cbc263921b92..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK&ubGw6n@jBCb0-PR4RhH;I+gUMJZm=v=uxQ#1%cL#B36hZMQoyyJ;*TkgNKy z2p;`U{9ioj_ufol^P>kZB6ePQ^Szy!_crg#o0$v|sm7>tpQubkMJQwbDw-9-DfOv>6@5lNeZY#YU_7A# z4Y9tDo<+JHL^^;!ZyvkQ$}bUEL^%p5qq|q9_;is2cN5Q$>3SNcXakIR+r{lC0#@(Sfgq<#?ynP+U9X)R7 zQQS$y*Ea*DQnA!5Z%rl-s@q=e(c|g1H`%Gdez;ScPD{n>ckexU(L9b$V*N>yB86>E z5j zmnC^C6Z^UREFHvdi@z`JDSiZgUKQ=jLbN-XXuka(94~@@=a0YZ&xPpgD6bKU=a_o) zSrHe-*SXTsD4vA^TVp=6xo@HtS*_VS_Zo0YwxD0w^LdorC=-Jok71CD`t26E=H%;*2X#rOYtC->wS za18uc45<9Rzu!Pg_H12Bj?Y>T`X0){^JWIc1&uw9#o(j(22=!N9vi^A#hF3$K-?bz Mp}{qdfxpVYZ$`||-v9sr diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index b3a7bad..93611be 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -6,7 +6,6 @@ NU5104 true AsyncMonolith.MySql - 10.0.1 Tim Jones Aptacode MySql interface for AsyncMonolith diff --git a/AsyncMonolith.PostgreSql/.DS_Store b/AsyncMonolith.PostgreSql/.DS_Store deleted file mode 100644 index fe5b3dc2ff89f59ff3d5a1078ffad54b73037076..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMOK;Oa5S~p^lBgi%P(%+PER|yvLU@#li<`Dc9FQuE-~cGZiIteTc8Hw@6h+Dv z_$x>p`6v7rPVmj{Qn`+MsE~k)U1|2)$IL!H&w4Ws5sCJse~W0Hh$;}q+A6Y~#QiKw zsi0df0tM`edi0ng3L(LgwrMa77zPXjh5^HXVc=h20CzU0$|?80>NUAxz%cM%GQjT# z3&Ln?Tqu;U4rDR}0G7}!6UvAKq>ZJ~*0@k8O);j59)va(I>Zpl9Q_un18t29h02_S zGAE&D7CJ%^a(38RQk{gY(By^z!@x2F9J^nqZHnnV;`Vg>?o&cTYS2ES`55H^jmaa2 z-XgYdKr^NhS|WP$D2RG)5V;tM58pPV@k1t*h>GNrPhm#uOTLynjYoQ{ukI-DdT3#)`a)!~=NxI1-Zgpt_nX{WZf6NO3F552K8@cSNA zUOxB3el%@IldvC4TSs+NtCeb}c4ao(Y}KvS{k!wJHQQ=6>(-sE)_h*AT;90(;7R8o zI1Hl?a#JMqdx$Qn`f>gdCB5Y%XB-AmI6w<)uYlkQNIRgxNixJW^rk6GY5r|OZi9r@ zz0KbwB(z z=}fTuF>-daJ$i?dCpq#pS2^n?K8xvbP?d?D)`BqF8W#$=iQDBZ3^eyY6JnBK;2bef zRBK)5_dUPCys-a?@?L3ZMY0P4qo c7@}-Jm2GT|3x#MwG9LmY4JI=T{80ve0-Pimy8r+H diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index a0634e7..010a8a9 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -3,7 +3,6 @@ true AsyncMonolith.PostgreSql - 10.0.1 Tim Jones Aptacode PostgreSql interface for AsyncMonolith diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index 932ed74..122cb1d 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -3,7 +3,6 @@ true AsyncMonolith.TestHelpers - 10.0.0 Tim Jones Aptacode Test helpers for AsyncMonolith diff --git a/AsyncMonolith/.DS_Store b/AsyncMonolith/.DS_Store deleted file mode 100644 index 11f4aa1df65a1ee4087aec250890dbcacb1e5cb2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKO^ee&7=EX%HrYk!Va2@&0k2D~Rg`5f+3tGqAc*nfpi-Nrw9#y)G^s^OA=lNv zB6#$l_+LEf^Ulmdn%1kk$h`2*Gat{J%si8s$q_rA zI8LZ%4CyIJO5w={+g4ZwtO8d}0baX%bW9n2#=0%9-hhZW^ z#PEi33~&Edh8$6yLW(J^u)c3+g^O%zp7kS~CUKT`IzL6N-ne$X*>sz`&3C~>E`ofJ z&$HfO_J&I@q)ft#{2+W4j~4yb-ib`}L7a|eDj<$VpuBw@r;%Lr(+94zjNSqA3jV$}26_!iS z)Wk*T$8cLeYTV;;KXxbpa{?~MBs`tfzNl&cR+@H~UgA@U6`OHX9WC)EP>w*++T|-? zK5S?A^1EVtU=^?mTrmZBfAHXpzQIDH+B%S^D*&*8YGugtuK~w+27QBtMzp|$4h8B^ zVXhcLhojyzJl|lUQHPT-mk(jyEX)l>sJG+!o}!cRHQLlFU=>(bpstH8KK~#8{r true AsyncMonolith - 10.0.0 Tim Jones Aptacode Messaging library for monolithic dotnet apps diff --git a/Directory.Build.props b/Directory.Build.props index fd071d1..19f1778 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,6 +5,9 @@ enable latest + + 10.1.0 + true true latest diff --git a/docs/releases.md b/docs/releases.md index 03ab1d1..23a7aa5 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -2,6 +2,7 @@ Make sure to check this table before updating the nuget package in your solution | Version | Description | Migration Required | |---------|--------------------------------------------|--------------------| +| 10.1.0 | SQLite-safe processing, stored names, modules, backoff, poisoned message service (see below) | Yes | | 8.0.6 | Added ConsumerAttempts override attribute | No | | 8.0.5 | Bundle debug symbols with nuget package | No | | 8.0.4 | Bundle XML docs with nuget package | No | @@ -12,3 +13,27 @@ Make sure to check this table before updating the nuget package in your solution | 1.0.9 | Initial | Yes | ***If you're not using ef migrations check out the sql to configure your database [here](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas)*** + + +## 10.1.0 + +All packages now share one version and must be upgraded together. + +**Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_10_1_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. + +**Changes** +- Consumers can write to the database on SQLite. Messages are claimed and leased in a short transaction, consumers run outside it, and each message is completed in its own short write. If the app stops mid-message, the message is retried once its consumer timeout plus 30 seconds has passed. +- Retries back off exponentially from `AttemptDelay` up to the new `MaxAttemptDelay` setting (default 300 seconds). +- The last error is stored on retried and poisoned messages. +- `IPoisonedMessageService` counts, lists, retries and deletes poisoned messages. +- `IScheduleService.EnsureSchedule` creates or updates a schedule by tag, so it can run at every startup. +- `IQueueStatisticsService` reports queue depth and the age of the oldest due message, for health checks. +- `[ConsumerPayloadName]` and `[ConsumerName]` give payloads and consumers stable stored names. Name clashes now fail at startup instead of silently mixing messages. +- `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. + +**Breaking changes** +- `AsyncMonolith.TestHelpers` uses xunit v3, and `ConsumerTestBase.InitializeAsync`/`DisposeAsync` return `ValueTask`. +- `IScheduleService` has a new member (`EnsureSchedule`), so custom implementations must add it. +- Errors that were thrown as `System.Exception` are now `InvalidOperationException`. +- `ConsumerRegistry` exposes properties instead of public fields. +- `TestConsumerMessageProcessor.ProcessNext` now finds the consumer's message. It previously always returned null. From 583bcdbcd8a8e5567a5f44ec1f8fbaabf6cdfa37 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:36:48 +0000 Subject: [PATCH 25/53] Remove the unused ScheduledMessageProcessorFactory Nothing registered or referenced it, but it was public, so it would have been a compatibility promise for code that never ran. --- .../ScheduledMessageProcessorFactory.cs | 55 ------------------- 1 file changed, 55 deletions(-) delete mode 100644 AsyncMonolith/Scheduling/ScheduledMessageProcessorFactory.cs diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessorFactory.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessorFactory.cs deleted file mode 100644 index eb26c39..0000000 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessorFactory.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace AsyncMonolith.Scheduling; - -/// -/// Represents a factory for creating and managing multiple instances of as -/// hosted services. -/// -/// The type of the used by the . -public class ScheduledMessageProcessorFactory : IHostedService where T : DbContext -{ - private readonly List _hostedServices; - private readonly int _instances; - private readonly IServiceProvider _serviceProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The used to resolve dependencies. - /// The number of instances of to create and manage. - public ScheduledMessageProcessorFactory(IServiceProvider serviceProvider, int instances) - { - _serviceProvider = serviceProvider; - _instances = instances; - _hostedServices = new List(); - } - - /// - /// Starts all the instances of as hosted services. - /// - /// The cancellation token to stop the operation. - public async Task StartAsync(CancellationToken cancellationToken) - { - for (var i = 0; i < _instances; i++) - { - var hostedService = ActivatorUtilities.CreateInstance>(_serviceProvider); - _hostedServices.Add(hostedService); - await hostedService.StartAsync(cancellationToken); - } - } - - /// - /// Stops all the instances of as hosted services. - /// - /// The cancellation token to stop the operation. - public async Task StopAsync(CancellationToken cancellationToken) - { - foreach (var hostedService in _hostedServices) - { - await hostedService.StopAsync(cancellationToken); - } - } -} \ No newline at end of file From e46fab59decf2430123829137834afcb568888b2 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:37:32 +0000 Subject: [PATCH 26/53] Stop AsyncMonolith registration from taking over host services - No longer registers DbContext as an alias for the host's context. Nothing used it, and it changed what DbContext resolved to across the whole container. - Services, the producer and the fetchers use TryAdd, so a host can register its own implementation first. - TimeProvider defaults to TimeProvider.System; hosts no longer fail at runtime for not registering one. - Calling Add*AsyncMonolith twice throws, pointing to AddAsyncMonolithConsumers, instead of starting duplicate processors. --- AsyncMonolith.Ef/StartupExtensions.cs | 7 +- AsyncMonolith.MariaDb/StartupExtensions.cs | 7 +- AsyncMonolith.MsSql/StartupExtensions.cs | 7 +- AsyncMonolith.MySql/StartupExtensions.cs | 7 +- AsyncMonolith.PostgreSql/StartupExtensions.cs | 7 +- AsyncMonolith.Tests/RegistrationTests.cs | 81 +++++++++++++++++++ AsyncMonolith/Utilities/StartupExtensions.cs | 23 ++++-- 7 files changed, 119 insertions(+), 20 deletions(-) create mode 100644 AsyncMonolith.Tests/RegistrationTests.cs diff --git a/AsyncMonolith.Ef/StartupExtensions.cs b/AsyncMonolith.Ef/StartupExtensions.cs index 2a3d7b8..a04bee6 100644 --- a/AsyncMonolith.Ef/StartupExtensions.cs +++ b/AsyncMonolith.Ef/StartupExtensions.cs @@ -5,6 +5,7 @@ using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace AsyncMonolith.Ef; @@ -53,9 +54,9 @@ private static IServiceCollection AddEfAsyncMonolith( configuration(settings); services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); + services.TryAddScoped>(); + services.TryAddSingleton(); + services.TryAddSingleton(); return services; } } diff --git a/AsyncMonolith.MariaDb/StartupExtensions.cs b/AsyncMonolith.MariaDb/StartupExtensions.cs index 583720b..e221479 100644 --- a/AsyncMonolith.MariaDb/StartupExtensions.cs +++ b/AsyncMonolith.MariaDb/StartupExtensions.cs @@ -5,6 +5,7 @@ using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace AsyncMonolith.MariaDb; /// @@ -50,9 +51,9 @@ private static IServiceCollection AddMariaDbAsyncMonolith( configuration(settings); services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); + services.TryAddScoped>(); + services.TryAddSingleton(); + services.TryAddSingleton(); return services; } } diff --git a/AsyncMonolith.MsSql/StartupExtensions.cs b/AsyncMonolith.MsSql/StartupExtensions.cs index 9222fbc..2c57c81 100644 --- a/AsyncMonolith.MsSql/StartupExtensions.cs +++ b/AsyncMonolith.MsSql/StartupExtensions.cs @@ -5,6 +5,7 @@ using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace AsyncMonolith.MsSql; @@ -48,9 +49,9 @@ private static IServiceCollection AddMsSqlAsyncMonolith( { configuration(settings); services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); + services.TryAddScoped>(); + services.TryAddSingleton(); + services.TryAddSingleton(); return services; } } diff --git a/AsyncMonolith.MySql/StartupExtensions.cs b/AsyncMonolith.MySql/StartupExtensions.cs index 1c66986..24e3050 100644 --- a/AsyncMonolith.MySql/StartupExtensions.cs +++ b/AsyncMonolith.MySql/StartupExtensions.cs @@ -5,6 +5,7 @@ using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace AsyncMonolith.MySql; /// @@ -47,9 +48,9 @@ private static IServiceCollection AddMySqlAsyncMonolith( { configuration(settings); services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); + services.TryAddScoped>(); + services.TryAddSingleton(); + services.TryAddSingleton(); return services; } } diff --git a/AsyncMonolith.PostgreSql/StartupExtensions.cs b/AsyncMonolith.PostgreSql/StartupExtensions.cs index 48dd2b8..3e9e350 100644 --- a/AsyncMonolith.PostgreSql/StartupExtensions.cs +++ b/AsyncMonolith.PostgreSql/StartupExtensions.cs @@ -5,6 +5,7 @@ using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace AsyncMonolith.PostgreSql; @@ -50,9 +51,9 @@ private static IServiceCollection AddPostgreSqlAsyncMonolith( { configuration(settings); services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); + services.TryAddScoped>(); + services.TryAddSingleton(); + services.TryAddSingleton(); return services; } } diff --git a/AsyncMonolith.Tests/RegistrationTests.cs b/AsyncMonolith.Tests/RegistrationTests.cs new file mode 100644 index 0000000..5793d1b --- /dev/null +++ b/AsyncMonolith.Tests/RegistrationTests.cs @@ -0,0 +1,81 @@ +using AsyncMonolith.Ef; +using AsyncMonolith.Scheduling; +using AsyncMonolith.TestHelpers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// What Add*AsyncMonolith registers, and what it leaves to the host. +/// +public class RegistrationTests +{ + private static ServiceCollection Services() + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddDbContext(_ => { }); + return services; + } + + private static void AddAsyncMonolith(IServiceCollection services) => + services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + + [Fact] + public void Does_not_register_the_DbContext_base_type() + { + var services = Services(); + + AddAsyncMonolith(services); + + services.ShouldNotContain(d => d.ServiceType == typeof(DbContext)); + } + + [Fact] + public void Uses_the_system_clock_unless_the_host_registers_one() + { + var services = Services(); + AddAsyncMonolith(services); + services.BuildServiceProvider().GetRequiredService().ShouldBe(TimeProvider.System); + + var custom = new Microsoft.Extensions.Time.Testing.FakeTimeProvider(); + var withClock = Services(); + withClock.AddSingleton(custom); + AddAsyncMonolith(withClock); + withClock.BuildServiceProvider().GetRequiredService().ShouldBe(custom); + } + + [Fact] + public void Services_registered_by_the_host_first_are_kept() + { + var services = Services(); + var ids = new FakeIdGenerator(); + services.AddSingleton(ids); + services.AddScoped(); + + AddAsyncMonolith(services); + + var provider = services.BuildServiceProvider(); + provider.GetRequiredService().ShouldBeSameAs(ids); + using var scope = provider.CreateScope(); + scope.ServiceProvider.GetRequiredService().ShouldBeOfType(); + services.Count(d => d.ServiceType == typeof(IScheduleService)).ShouldBe(1); + } + + [Fact] + public void Calling_AddAsyncMonolith_twice_fails_with_guidance() + { + var services = Services(); + AddAsyncMonolith(services); + + var exception = Should.Throw(() => AddAsyncMonolith(services)); + + exception.Message.ShouldContain("AddAsyncMonolithConsumers"); + services.Count(d => d.ServiceType == typeof(IHostedService)).ShouldBe(2); + } +} diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index ef7c1ea..c86e42b 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -93,13 +93,23 @@ internal static void InternalAddAsyncMonolith( this IServiceCollection services, AsyncMonolithSettings settings) where T : DbContext { + if (services.Any(d => d.ServiceType == typeof(AsyncMonolithRegistration))) + { + throw new InvalidOperationException( + "AsyncMonolith is already registered. Call Add*AsyncMonolith once, in the host; modules register " + + "their consumers with AddAsyncMonolithConsumers."); + } + + services.AddSingleton(); services.InternalConfigureAsyncMonolithSettings(settings); services.InternalRegisterAsyncMonolithConsumers(settings); - services.AddSingleton(new AsyncMonolithIdGenerator()); - services.AddScoped>(); - services.AddScoped>(); - services.AddScoped>(); - services.AddScoped(sp => sp.GetRequiredService()); + + // TryAdd, so a host can register its own implementation before or instead of these. + services.TryAddSingleton(TimeProvider.System); + services.TryAddSingleton(); + services.TryAddScoped>(); + services.TryAddScoped>(); + services.TryAddScoped>(); // One processor per rail. Rails are read when the host starts, after every module has // registered its consumers. @@ -278,6 +288,9 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass private sealed class ConsumerAssemblies : HashSet; + /// Marks that Add*AsyncMonolith has been called. + private sealed class AsyncMonolithRegistration; + private static string RegisterPayloadName(Dictionary payloadTypes, Type payloadType) { var payloadName = AsyncMonolithNames.ForPayload(payloadType); From ef7b23c85ed5dcc6e848eff323bcf94b84eb1f4d Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:39:24 +0000 Subject: [PATCH 27/53] Use one producer for every database The EF provider added messages to the caller's DbContext, so they were written on SaveChanges and a duplicate insert id threw. The Postgres, SQL Server, MySQL and MariaDB providers ran their INSERT immediately and silently skipped duplicates. With those four, a message was written even when the caller's own save failed, unless they opened a transaction themselves, so the outbox guarantee depended on the provider. All providers now share one internal producer: - Messages are added to the caller's DbContext and written on SaveChanges, in the same transaction, on every database. - With an insert id, consumers that already have a pending message with it (saved, or added to this DbContext) are skipped. Producers racing in separate transactions are stopped by the unique index, and the second SaveChanges throws. - The five provider producer classes are removed. Providers now only supply their fetchers. The producing guide drops the "wrap it in a transaction" workaround and explains deduplication. Tests cover the outbox on SQLite and, as integration tests, on every database: skipping, duplicates before saving, partial duplicates, re-producing after consumption, and racing producers. --- AsyncMonolith.Ef/EfProducerService.cs | 155 -------- AsyncMonolith.Ef/StartupExtensions.cs | 1 - .../MariaDbProducerService.cs | 188 ---------- AsyncMonolith.MariaDb/StartupExtensions.cs | 1 - AsyncMonolith.MsSql/MsSqlProducerService.cs | 197 ----------- AsyncMonolith.MsSql/StartupExtensions.cs | 1 - AsyncMonolith.MySql/MySqlProducerService.cs | 189 ---------- AsyncMonolith.MySql/StartupExtensions.cs | 1 - .../PostgreSqlProducerService.cs | 192 ---------- AsyncMonolith.PostgreSql/StartupExtensions.cs | 1 - AsyncMonolith.Tests/ConfigurationTests.cs | 2 +- .../Infra/TestServiceHelpers.cs | 6 +- AsyncMonolith.Tests/ProducerBehaviourTests.cs | 68 +++- AsyncMonolith.Tests/ProducerServiceDbTests.cs | 332 +++++------------- AsyncMonolith/Producers/ProducerService.cs | 113 ++++++ AsyncMonolith/Utilities/StartupExtensions.cs | 2 + docs/guides/producing-messages.md | 32 +- 17 files changed, 268 insertions(+), 1213 deletions(-) delete mode 100644 AsyncMonolith.Ef/EfProducerService.cs delete mode 100644 AsyncMonolith.MariaDb/MariaDbProducerService.cs delete mode 100644 AsyncMonolith.MsSql/MsSqlProducerService.cs delete mode 100644 AsyncMonolith.MySql/MySqlProducerService.cs delete mode 100644 AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs create mode 100644 AsyncMonolith/Producers/ProducerService.cs diff --git a/AsyncMonolith.Ef/EfProducerService.cs b/AsyncMonolith.Ef/EfProducerService.cs deleted file mode 100644 index 222b9de..0000000 --- a/AsyncMonolith.Ef/EfProducerService.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System.Diagnostics; -using System.Text.Json; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; - -namespace AsyncMonolith.Ef; - -/// -/// Represents a service for producing messages using Entity Framework. -/// -/// The type of the DbContext. -public sealed class EfProducerService : IProducerService where T : DbContext -{ - private readonly ConsumerRegistry _consumerRegistry; - private readonly T _dbContext; - private readonly IAsyncMonolithIdGenerator _idGenerator; - private readonly TimeProvider _timeProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The time provider. - /// The consumer registry. - /// The DbContext. - /// The ID generator. - public EfProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator) - { - _timeProvider = timeProvider; - _consumerRegistry = consumerRegistry; - _dbContext = dbContext; - _idGenerator = idGenerator; - } - - /// - /// Produces a single message. - /// - /// The type of the message. - /// The message to produce. - /// The time when the message should be available for consumption. - /// The ID to insert for the message. - /// The cancellation token. - /// A task representing the asynchronous operation. - public Task Produce(TK message, long? availableAfter = null, string? insertId = null, - CancellationToken cancellationToken = default) - where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var payload = JsonSerializer.Serialize(message); - insertId ??= _idGenerator.GenerateId(); - var payloadType = AsyncMonolithNames.ForPayload(); - var set = _dbContext.Set(); - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - foreach (var consumerType in _consumerRegistry.ResolvePayloadConsumerTypes(payloadType)) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = availableAfter.Value, - ConsumerType = consumerType, - PayloadType = payloadType, - Payload = payload, - Attempts = 0, - InsertId = insertId, - TraceId = traceId, - SpanId = spanId, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerType) - }); - } - - return Task.CompletedTask; - } - - /// - /// Produces a list of messages. - /// - /// The type of the messages. - /// The messages to produce. - /// The time when the messages should be available for consumption. - /// The cancellation token. - /// A task representing the asynchronous operation. - public Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - - var set = _dbContext.Set(); - var payloadType = AsyncMonolithNames.ForPayload(); - var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - foreach (var message in messages) - { - var insertId = _idGenerator.GenerateId(); - var payload = JsonSerializer.Serialize(message); - - foreach (var consumerId in consumers) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = availableAfter.Value, - ConsumerType = consumerId, - PayloadType = payloadType, - Payload = payload, - Attempts = 0, - InsertId = insertId, - TraceId = traceId, - SpanId = spanId, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } - } - - return Task.CompletedTask; - } - - /// - /// Produces a scheduled message. - /// - /// The scheduled message to produce. - public void Produce(ScheduledMessage message) - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var set = _dbContext.Set(); - var insertId = _idGenerator.GenerateId(); - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType)) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = currentTime, - ConsumerType = consumerId, - PayloadType = message.PayloadType, - Payload = message.Payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } - } -} diff --git a/AsyncMonolith.Ef/StartupExtensions.cs b/AsyncMonolith.Ef/StartupExtensions.cs index a04bee6..aed7d09 100644 --- a/AsyncMonolith.Ef/StartupExtensions.cs +++ b/AsyncMonolith.Ef/StartupExtensions.cs @@ -54,7 +54,6 @@ private static IServiceCollection AddEfAsyncMonolith( configuration(settings); services.InternalAddAsyncMonolith(settings); - services.TryAddScoped>(); services.TryAddSingleton(); services.TryAddSingleton(); return services; diff --git a/AsyncMonolith.MariaDb/MariaDbProducerService.cs b/AsyncMonolith.MariaDb/MariaDbProducerService.cs deleted file mode 100644 index 6799940..0000000 --- a/AsyncMonolith.MariaDb/MariaDbProducerService.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System.Diagnostics; -using System.Globalization; -using System.Text; -using System.Text.Json; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using MySqlConnector; - -namespace AsyncMonolith.MariaDb; - -/// -/// Represents a service for producing messages to a MariaDb database. -/// -/// The type of the DbContext. -public sealed class MariaDbProducerService : IProducerService where T : DbContext -{ - private readonly ConsumerRegistry _consumerRegistry; - private readonly T _dbContext; - private readonly IAsyncMonolithIdGenerator _idGenerator; - private readonly TimeProvider _timeProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The time provider. - /// The consumer registry. - /// The DbContext. - /// The ID generator. - public MariaDbProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator) - { - _timeProvider = timeProvider; - _consumerRegistry = consumerRegistry; - _dbContext = dbContext; - _idGenerator = idGenerator; - } - - /// - /// Produces a single message to the database. - /// - /// The type of the message. - /// The message to produce. - /// The time when the message should be available for consumption. - /// The ID to insert into the database. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task Produce(TK message, long? availableAfter = null, string? insertId = null, - CancellationToken cancellationToken = default) - where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var payload = JsonSerializer.Serialize(message); - var payloadType = AsyncMonolithNames.ForPayload(); - insertId ??= _idGenerator.GenerateId(); - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@payload_type", payloadType), - new("@payload", payload), - new("@insert_id", insertId), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); - - parameters.Add(new MySqlParameter($"@id_{index}", _idGenerator.GenerateId())); - parameters.Add(new MySqlParameter($"@consumer_type_{index}", consumerTypes[index])); - parameters.Add(new MySqlParameter($"@rail_{index}", consumerRailIds[index])); - - } - - var sql = $@" - INSERT INTO consumer_messages (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES {sqlBuilder} - ON DUPLICATE KEY UPDATE id = id;"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a list of messages to the database. - /// - /// The type of the messages. - /// The messages to produce. - /// The time when the messages should be available for consumption. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var payloadType = AsyncMonolithNames.ForPayload(); - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - for (var i = 0; i < messages.Count; i++) - { - var message = messages[i]; - var insertId = _idGenerator.GenerateId(); - var payload = JsonSerializer.Serialize(message); - parameters.Add(new MySqlParameter($"@insert_id_{i}", insertId)); - parameters.Add(new MySqlParameter($"@payload_type_{i}", payloadType)); - parameters.Add(new MySqlParameter($"@payload_{i}", payload)); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); - - parameters.Add(new MySqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); - parameters.Add(new MySqlParameter($"@consumer_type_{i}_{index}", consumerTypes[index])); - parameters.Add(new MySqlParameter($"@rail_{i}_{index}", consumerRailIds[index])); - } - } - - var sql = $@" - INSERT INTO consumer_messages (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES {sqlBuilder} - ON DUPLICATE KEY UPDATE id = id;"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a scheduled message to the database. - /// - /// The scheduled message to produce. - public void Produce(ScheduledMessage message) - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var set = _dbContext.Set(); - var insertId = _idGenerator.GenerateId(); - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType)) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = currentTime, - ConsumerType = consumerId, - PayloadType = message.PayloadType, - Payload = message.Payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } - } -} diff --git a/AsyncMonolith.MariaDb/StartupExtensions.cs b/AsyncMonolith.MariaDb/StartupExtensions.cs index e221479..4154cb9 100644 --- a/AsyncMonolith.MariaDb/StartupExtensions.cs +++ b/AsyncMonolith.MariaDb/StartupExtensions.cs @@ -51,7 +51,6 @@ private static IServiceCollection AddMariaDbAsyncMonolith( configuration(settings); services.InternalAddAsyncMonolith(settings); - services.TryAddScoped>(); services.TryAddSingleton(); services.TryAddSingleton(); return services; diff --git a/AsyncMonolith.MsSql/MsSqlProducerService.cs b/AsyncMonolith.MsSql/MsSqlProducerService.cs deleted file mode 100644 index 2d4db64..0000000 --- a/AsyncMonolith.MsSql/MsSqlProducerService.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System.Diagnostics; -using System.Globalization; -using System.Text; -using System.Text.Json; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.Data.SqlClient; -using Microsoft.EntityFrameworkCore; - -namespace AsyncMonolith.MsSql; - -/// -/// Represents a service for producing messages to the MS SQL database. -/// -/// The type of the DbContext. -public sealed class MsSqlProducerService : IProducerService where T : DbContext -{ - private readonly ConsumerRegistry _consumerRegistry; - private readonly T _dbContext; - private readonly IAsyncMonolithIdGenerator _idGenerator; - private readonly TimeProvider _timeProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The time provider. - /// The consumer registry. - /// The DbContext. - /// The ID generator. - public MsSqlProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator) - { - _timeProvider = timeProvider; - _consumerRegistry = consumerRegistry; - _dbContext = dbContext; - _idGenerator = idGenerator; - } - - /// - /// Produces a single message to the database. - /// - /// The type of the message. - /// The message to produce. - /// The time when the message should be available for consumption. - /// The ID to use for inserting the message. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task Produce(TK message, long? availableAfter = null, string? insertId = null, - CancellationToken cancellationToken = default) - where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var payload = JsonSerializer.Serialize(message); - var payloadType = AsyncMonolithNames.ForPayload(); - insertId ??= _idGenerator.GenerateId(); - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@payload_type", payloadType), - new("@payload", payload), - new("@insert_id", insertId), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); - - parameters.Add(new SqlParameter($"@id_{index}", _idGenerator.GenerateId())); - parameters.Add(new SqlParameter($"@consumer_type_{index}", consumerTypes[index])); - parameters.Add(new SqlParameter($"@rail_{index}", consumerRailIds[index])); - } - - var sql = $@" - MERGE INTO consumer_messages AS target - USING (VALUES {sqlBuilder}) AS source (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - ON target.insert_id = source.insert_id - WHEN NOT MATCHED BY TARGET THEN - INSERT (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES (source.id, source.created_at, source.available_after, source.attempts, source.consumer_type, source.payload_type, source.payload, source.insert_id, source.trace_id, source.span_id, source.rail_id);"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a list of messages to the database. - /// - /// The type of the messages. - /// The messages to produce. - /// The time when the messages should be available for consumption. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var payloadType = AsyncMonolithNames.ForPayload(); - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - - for (var i = 0; i < messages.Count; i++) - { - var message = messages[i]; - var insertId = _idGenerator.GenerateId(); - var payload = JsonSerializer.Serialize(message); - parameters.Add(new SqlParameter($"@insert_id_{i}", insertId)); - parameters.Add(new SqlParameter($"@payload_type_{i}", payloadType)); - parameters.Add(new SqlParameter($"@payload_{i}", payload)); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); - - parameters.Add(new SqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); - parameters.Add(new SqlParameter($"@consumer_type_{i}_{index}", consumerTypes[index])); - parameters.Add(new SqlParameter($"@rail_{i}_{index}", consumerRailIds[index])); - - } - } - - var sql = $@" - MERGE INTO consumer_messages AS target - USING (VALUES {sqlBuilder}) AS source (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - ON target.insert_id = source.insert_id - WHEN NOT MATCHED BY TARGET THEN - INSERT (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES (source.id, source.created_at, source.available_after, source.attempts, source.consumer_type, source.payload_type, source.payload, source.insert_id, source.trace_id, source.span_id, source.rail_id);"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a scheduled message to the database. - /// - /// The scheduled message to produce. - public void Produce(ScheduledMessage message) - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var set = _dbContext.Set(); - var insertId = _idGenerator.GenerateId(); - - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType)) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = currentTime, - ConsumerType = consumerId, - PayloadType = message.PayloadType, - Payload = message.Payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } - } -} diff --git a/AsyncMonolith.MsSql/StartupExtensions.cs b/AsyncMonolith.MsSql/StartupExtensions.cs index 2c57c81..e60cb57 100644 --- a/AsyncMonolith.MsSql/StartupExtensions.cs +++ b/AsyncMonolith.MsSql/StartupExtensions.cs @@ -49,7 +49,6 @@ private static IServiceCollection AddMsSqlAsyncMonolith( { configuration(settings); services.InternalAddAsyncMonolith(settings); - services.TryAddScoped>(); services.TryAddSingleton(); services.TryAddSingleton(); return services; diff --git a/AsyncMonolith.MySql/MySqlProducerService.cs b/AsyncMonolith.MySql/MySqlProducerService.cs deleted file mode 100644 index fb5c347..0000000 --- a/AsyncMonolith.MySql/MySqlProducerService.cs +++ /dev/null @@ -1,189 +0,0 @@ -using System.Diagnostics; -using System.Globalization; -using System.Text; -using System.Text.Json; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using MySqlConnector; - -namespace AsyncMonolith.MySql; - -/// -/// Represents a service for producing messages to a MySQL database. -/// -/// The type of the DbContext. -public sealed class MySqlProducerService : IProducerService where T : DbContext -{ - private readonly ConsumerRegistry _consumerRegistry; - private readonly T _dbContext; - private readonly IAsyncMonolithIdGenerator _idGenerator; - private readonly TimeProvider _timeProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The time provider. - /// The consumer registry. - /// The DbContext. - /// The ID generator. - public MySqlProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator) - { - _timeProvider = timeProvider; - _consumerRegistry = consumerRegistry; - _dbContext = dbContext; - _idGenerator = idGenerator; - } - - /// - /// Produces a single message to the database. - /// - /// The type of the message. - /// The message to produce. - /// The time when the message should be available for consumption. - /// The ID to insert into the database. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task Produce(TK message, long? availableAfter = null, string? insertId = null, - CancellationToken cancellationToken = default) - where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var payload = JsonSerializer.Serialize(message); - var payloadType = AsyncMonolithNames.ForPayload(); - insertId ??= _idGenerator.GenerateId(); - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@payload_type", payloadType), - new("@payload", payload), - new("@insert_id", insertId), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); - - parameters.Add(new MySqlParameter($"@id_{index}", _idGenerator.GenerateId())); - parameters.Add(new MySqlParameter($"@consumer_type_{index}", consumerTypes[index])); - parameters.Add(new MySqlParameter($"@rail_{index}", consumerRailIds[index])); - } - - var sql = $@" - INSERT INTO consumer_messages (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES {sqlBuilder} - ON DUPLICATE KEY UPDATE id = id;"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a list of messages to the database. - /// - /// The type of the messages. - /// The messages to produce. - /// The time when the messages should be available for consumption. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var payloadType = AsyncMonolithNames.ForPayload(); - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - - for (var i = 0; i < messages.Count; i++) - { - var message = messages[i]; - var insertId = _idGenerator.GenerateId(); - var payload = JsonSerializer.Serialize(message); - parameters.Add(new MySqlParameter($"@insert_id_{i}", insertId)); - parameters.Add(new MySqlParameter($"@payload_type_{i}", payloadType)); - parameters.Add(new MySqlParameter($"@payload_{i}", payload)); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); - - parameters.Add(new MySqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); - parameters.Add(new MySqlParameter($"@consumer_type_{i}_{index}", consumerTypes[index])); - parameters.Add(new MySqlParameter($"@rail_{i}_{index}", consumerRailIds[index])); - } - } - - var sql = $@" - INSERT INTO consumer_messages (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES {sqlBuilder} - ON DUPLICATE KEY UPDATE id = id;"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a scheduled message to the database. - /// - /// The scheduled message to produce. - public void Produce(ScheduledMessage message) - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var set = _dbContext.Set(); - var insertId = _idGenerator.GenerateId(); - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType)) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = currentTime, - ConsumerType = consumerId, - PayloadType = message.PayloadType, - Payload = message.Payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } - } -} diff --git a/AsyncMonolith.MySql/StartupExtensions.cs b/AsyncMonolith.MySql/StartupExtensions.cs index 24e3050..a906517 100644 --- a/AsyncMonolith.MySql/StartupExtensions.cs +++ b/AsyncMonolith.MySql/StartupExtensions.cs @@ -48,7 +48,6 @@ private static IServiceCollection AddMySqlAsyncMonolith( { configuration(settings); services.InternalAddAsyncMonolith(settings); - services.TryAddScoped>(); services.TryAddSingleton(); services.TryAddSingleton(); return services; diff --git a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs b/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs deleted file mode 100644 index 02d8dd9..0000000 --- a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System.Diagnostics; -using System.Globalization; -using System.Text; -using System.Text.Json; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Npgsql; - -namespace AsyncMonolith.PostgreSql; - -/// -/// Represents a service for producing messages to a PostgreSQL database. -/// -/// The type of the DbContext. -public sealed class PostgreSqlProducerService : IProducerService where T : DbContext -{ - private readonly ConsumerRegistry _consumerRegistry; - private readonly T _dbContext; - private readonly IAsyncMonolithIdGenerator _idGenerator; - private readonly TimeProvider _timeProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The time provider. - /// The consumer registry. - /// The DbContext. - /// The ID generator. - public PostgreSqlProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator) - { - _timeProvider = timeProvider; - _consumerRegistry = consumerRegistry; - _dbContext = dbContext; - _idGenerator = idGenerator; - } - - /// - /// Produces a single message to the database. - /// - /// The type of the message. - /// The message to produce. - /// The time when the message should be available for consumption. - /// The insert ID for the message. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task Produce(TK message, long? availableAfter = null, string? insertId = null, - CancellationToken cancellationToken = default) - where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var payload = JsonSerializer.Serialize(message); - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var payloadType = AsyncMonolithNames.ForPayload(); - insertId ??= _idGenerator.GenerateId(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@payload_type", payloadType), - new("@payload", payload), - new("@insert_id", insertId), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{index}, @created_at, @available_after, 0, @consumer_type_{index}, @payload_type, @payload, @insert_id, @trace_id, @span_id, @rail_{index})"); - - parameters.Add(new NpgsqlParameter($"@id_{index}", _idGenerator.GenerateId())); - parameters.Add(new NpgsqlParameter($"@consumer_type_{index}", consumerTypes[index])); - parameters.Add(new NpgsqlParameter($"@rail_{index}", consumerRailIds[index])); - - } - - var sql = $@" - INSERT INTO consumer_messages (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES {sqlBuilder} - ON CONFLICT (insert_id, consumer_type) DO NOTHING;"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a list of messages to the database. - /// - /// The type of the messages. - /// The messages to produce. - /// The time when the messages should be available for consumption. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var traceId = Activity.Current?.TraceId.ToString(); - var spanId = Activity.Current?.SpanId.ToString(); - - var sqlBuilder = new StringBuilder(); - var parameters = new List - { - new("@created_at", currentTime), - new("@available_after", availableAfter), - new("@trace_id", string.IsNullOrEmpty(traceId) ? DBNull.Value : traceId), - new("@span_id", string.IsNullOrEmpty(spanId) ? DBNull.Value : spanId) - }; - - var payloadType = AsyncMonolithNames.ForPayload(); - var consumerTypes = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - var consumerRailIds = _consumerRegistry.ResolveConsumerRailIds(consumerTypes); - - for (var i = 0; i < messages.Count; i++) - { - var message = messages[i]; - var insertId = _idGenerator.GenerateId(); - var payload = JsonSerializer.Serialize(message); - parameters.Add(new NpgsqlParameter($"@insert_id_{i}", insertId)); - parameters.Add(new NpgsqlParameter($"@payload_type_{i}", payloadType)); - parameters.Add(new NpgsqlParameter($"@payload_{i}", payload)); - - for (var index = 0; index < consumerTypes.Count; index++) - { - if (sqlBuilder.Length > 0) - { - sqlBuilder.Append(", "); - } - - sqlBuilder.Append(CultureInfo.InvariantCulture, - $@"(@id_{i}_{index}, @created_at, @available_after, 0, @consumer_type_{i}_{index}, @payload_type_{i}, @payload_{i}, @insert_id_{i}, @trace_id, @span_id, @rail_{i}_{index})"); - - parameters.Add(new NpgsqlParameter($"@id_{i}_{index}", _idGenerator.GenerateId())); - parameters.Add(new NpgsqlParameter($"@consumer_type_{i}_{index}", consumerTypes[index])); - parameters.Add(new NpgsqlParameter($"@rail_{i}_{index}", consumerRailIds[index])); - - } - } - - var sql = $@" - INSERT INTO consumer_messages (id, created_at, available_after, attempts, consumer_type, payload_type, payload, insert_id, trace_id, span_id, rail_id) - VALUES {sqlBuilder} - ON CONFLICT (insert_id, consumer_type) DO NOTHING;"; - - await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); - } - - /// - /// Produces a scheduled message to the database. - /// - /// The scheduled message to produce. - public void Produce(ScheduledMessage message) - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var set = _dbContext.Set(); - var insertId = _idGenerator.GenerateId(); - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType)) - { - set.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = currentTime, - ConsumerType = consumerId, - PayloadType = message.PayloadType, - Payload = message.Payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } - } -} diff --git a/AsyncMonolith.PostgreSql/StartupExtensions.cs b/AsyncMonolith.PostgreSql/StartupExtensions.cs index 3e9e350..9ac4bff 100644 --- a/AsyncMonolith.PostgreSql/StartupExtensions.cs +++ b/AsyncMonolith.PostgreSql/StartupExtensions.cs @@ -51,7 +51,6 @@ private static IServiceCollection AddPostgreSqlAsyncMonolith( { configuration(settings); services.InternalAddAsyncMonolith(settings); - services.TryAddScoped>(); services.TryAddSingleton(); services.TryAddSingleton(); return services; diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs index a580954..63dbb48 100644 --- a/AsyncMonolith.Tests/ConfigurationTests.cs +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -218,7 +218,7 @@ public void AddEfAsyncMonolith_registers_the_services_and_background_processors( }); services.ShouldContain(d => d.ServiceType == typeof(IProducerService) && - d.ImplementationType == typeof(EfProducerService)); + d.ImplementationType == typeof(ProducerService)); services.ShouldContain(d => d.ServiceType == typeof(IScheduleService) && d.ImplementationType == typeof(ScheduleService)); services.ShouldContain(d => d.ServiceType == typeof(IHostedService) && diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 38a349f..be99764 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -37,33 +37,29 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new FakeIdGenerator()); + services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); switch (dbType) { case DbType.Ef: - services.AddScoped>(); services.AddSingleton(); services.AddSingleton(); break; case DbType.MySql: - services.AddScoped>(); services.AddSingleton(); services.AddSingleton(); break; case DbType.MsSql: - services.AddScoped>(); services.AddSingleton(); services.AddSingleton(); break; case DbType.PostgreSql: - services.AddScoped>(); services.AddSingleton(); services.AddSingleton(); break; case DbType.MariaDb: - services.AddScoped>(); services.AddSingleton(); services.AddSingleton(); break; diff --git a/AsyncMonolith.Tests/ProducerBehaviourTests.cs b/AsyncMonolith.Tests/ProducerBehaviourTests.cs index 11ead80..47b28a5 100644 --- a/AsyncMonolith.Tests/ProducerBehaviourTests.cs +++ b/AsyncMonolith.Tests/ProducerBehaviourTests.cs @@ -58,18 +58,80 @@ public async Task Produce_assigns_each_consumer_its_rail() } [Fact] - public async Task Producing_the_same_insert_id_twice_is_rejected_by_the_database() + public async Task Producing_an_insert_id_that_is_already_pending_is_skipped() { await using var host = await SqliteTestHost.Create(); await host.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key"); - await Should.ThrowAsync(() => - host.Produce(new SingleConsumerMessage { Name = "second" }, insertId: "dedupe-key")); + await host.Produce(new SingleConsumerMessage { Name = "second" }, insertId: "dedupe-key"); JsonSerializer.Deserialize((await host.ConsumerMessages()).ShouldHaveSingleItem().Payload)! .Name.ShouldBe("first"); } + [Fact] + public async Task Producing_an_insert_id_twice_before_saving_adds_it_once() + { + await using var host = await SqliteTestHost.Create(); + + using (var scope = host.Services.CreateScope()) + { + var producer = scope.ServiceProvider.GetRequiredService(); + await producer.Produce(new MultiConsumerMessage { Name = "first" }, insertId: "dedupe-key", cancellationToken: Ct); + await producer.Produce(new MultiConsumerMessage { Name = "second" }, insertId: "dedupe-key", cancellationToken: Ct); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + } + + (await host.ConsumerMessages()).Count.ShouldBe(2); + (await host.ConsumerMessages()).ShouldAllBe(m => m.Payload.Contains("first", StringComparison.Ordinal)); + } + + [Fact] + public async Task Only_consumers_that_already_have_the_insert_id_pending_are_skipped() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MultiConsumerMessage { Name = "first" }, insertId: "dedupe-key"); + // MultiConsumer1 has processed its message; MultiConsumer2's is still pending. + await host.Change(db => db.ConsumerMessages.Remove( + db.ConsumerMessages.Single(m => m.ConsumerType == nameof(MultiConsumer1)))); + + await host.Produce(new MultiConsumerMessage { Name = "second" }, insertId: "dedupe-key"); + + var messages = await host.ConsumerMessages(); + messages.Single(m => m.ConsumerType == nameof(MultiConsumer1)).Payload.ShouldContain("second"); + messages.Single(m => m.ConsumerType == nameof(MultiConsumer2)).Payload.ShouldContain("first"); + } + + [Fact] + public async Task An_insert_id_can_be_produced_again_once_its_messages_are_consumed() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key"); + await host.ConsumerProcessor.ProcessBatch(Ct); + + await host.Produce(new SingleConsumerMessage { Name = "again" }, insertId: "dedupe-key"); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().Payload.ShouldContain("again"); + } + + [Fact] + public async Task Two_producers_racing_on_one_insert_id_are_stopped_by_the_unique_index() + { + await using var host = await SqliteTestHost.Create(); + using var first = host.Services.CreateScope(); + using var second = host.Services.CreateScope(); + + // Both check before either has saved + await first.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key", cancellationToken: Ct); + await second.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "second" }, insertId: "dedupe-key", cancellationToken: Ct); + + await first.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + await Should.ThrowAsync(() => + second.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct)); + } + [Fact] public async Task ProduceList_gives_each_message_its_own_insert_id() { diff --git a/AsyncMonolith.Tests/ProducerServiceDbTests.cs b/AsyncMonolith.Tests/ProducerServiceDbTests.cs index cda69d2..245b32d 100644 --- a/AsyncMonolith.Tests/ProducerServiceDbTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceDbTests.cs @@ -3,55 +3,26 @@ using AsyncMonolith.Producers; using AsyncMonolith.TestHelpers; using AsyncMonolith.Tests.Infra; -using Shouldly; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Shouldly; namespace AsyncMonolith.Tests; +/// +/// The producer against each real database: the same outbox and deduplication behaviour everywhere. +/// [Trait("Category", "Integration")] public class ProducerServiceDbTests : DbTestsBase { - [Theory] - [MemberData(nameof(GetTestDbTypesWithoutEf))] - public async Task Producer_Inserts_ConsumerMessage(DbType dbType) + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private async Task Run(DbType dbType, Func test) { var dbContainer = GetTestDbContainer(dbType); - try { - // Given - var serviceProvider = await Setup(dbContainer); - var producer = serviceProvider.GetRequiredService(); - - var delay = 10; - var consumerMessage = new SingleConsumerMessage - { - Name = "test-name" - }; - using var activity = GetActivity(); - Activity.Current = activity; - - // When - await producer.Produce(consumerMessage, delay, cancellationToken: TestContext.Current.CancellationToken); - - // Then - using var scope = serviceProvider.CreateScope(); - { - var postDbContext = serviceProvider.GetRequiredService(); - var message = - await postDbContext.AssertSingleConsumerMessage( - consumerMessage); - message.AvailableAfter.ShouldBe(delay); - message.Attempts.ShouldBe(0); - message.InsertId.ShouldBe("fake-id-0"); - message.Id.ShouldBe("fake-id-1"); - message.ConsumerType = nameof(SingleConsumer); - message.PayloadType = nameof(SingleConsumerMessage); - message.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage)); - message.TraceId.ShouldBe(activity?.TraceId.ToString()); - message.SpanId.ShouldBe(activity?.SpanId.ToString()); - } + await test(await Setup(dbContainer)); } finally { @@ -59,237 +30,92 @@ await postDbContext.AssertSingleConsumerMessage produce) { - var dbContainer = GetTestDbContainer(dbType); - - try - { - // Given - var serviceProvider = await Setup(dbContainer); - var producer = serviceProvider.GetRequiredService(); - - var delay = 10; - var consumerMessage1 = new SingleConsumerMessage - { - Name = "test-name" - }; - var consumerMessage2 = new SingleConsumerMessage - { - Name = "test-name-2" - }; - var insertMessages = new List - { - consumerMessage1, - consumerMessage2 - }; - using var activity = GetActivity(); - Activity.Current = activity; - - // When - await producer.ProduceList(insertMessages, delay, cancellationToken: TestContext.Current.CancellationToken); - - // Then - using var scope = serviceProvider.CreateScope(); - { - var postDbContext = serviceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(TestContext.Current.CancellationToken); - messages.Count.ShouldBe(2); - - var message1 = - await postDbContext.AssertSingleConsumerMessageById( - consumerMessage1, "fake-id-1"); - message1.AvailableAfter.ShouldBe(delay); - message1.Attempts.ShouldBe(0); - message1.InsertId.ShouldBe("fake-id-0"); - message1.Id.ShouldBe("fake-id-1"); - message1.ConsumerType = nameof(SingleConsumer); - message1.PayloadType = nameof(SingleConsumerMessage); - message1.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage1)); - message1.TraceId.ShouldBe(activity?.TraceId.ToString()); - message1.SpanId.ShouldBe(activity?.SpanId.ToString()); - - var message2 = - await postDbContext.AssertSingleConsumerMessageById( - consumerMessage2, "fake-id-3"); - message2.AvailableAfter.ShouldBe(delay); - message2.Attempts.ShouldBe(0); - message2.InsertId.ShouldBe("fake-id-2"); - message2.Id.ShouldBe("fake-id-3"); - message2.ConsumerType = nameof(SingleConsumer); - message2.PayloadType = nameof(SingleConsumerMessage); - message2.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage2)); - message2.TraceId.ShouldBe(activity?.TraceId.ToString()); - message2.SpanId.ShouldBe(activity?.SpanId.ToString()); - } - } - finally - { - await dbContainer.DisposeAsync(); - } + using var scope = services.CreateScope(); + await produce(scope.ServiceProvider.GetRequiredService()); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); } - [Fact] - public async Task Ef_Producer_Inserts_List_Of_ConsumerMessages() + private static async Task> Messages(ServiceProvider services) { - var dbContainer = GetTestDbContainer(DbType.Ef); - - try - { - // Given - var serviceProvider = await Setup(dbContainer); - var scope = serviceProvider.CreateScope(); - var producer = scope.ServiceProvider.GetRequiredService(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - - var delay = 10; - var consumerMessage1 = new SingleConsumerMessage - { - Name = "test-name" - }; - var consumerMessage2 = new SingleConsumerMessage - { - Name = "test-name-2" - }; - var insertMessages = new List - { - consumerMessage1, - consumerMessage2 - }; - using var activity = GetActivity(); - Activity.Current = activity; - - // When - await producer.ProduceList(insertMessages, delay, cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); - - // Then - using var postScope = serviceProvider.CreateScope(); - { - var postDbContext = postScope.ServiceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(TestContext.Current.CancellationToken); - messages.Count.ShouldBe(2); - - var message1 = - await postDbContext.AssertSingleConsumerMessageById( - consumerMessage1, "fake-id-1"); - message1.AvailableAfter.ShouldBe(delay); - message1.Attempts.ShouldBe(0); - message1.InsertId.ShouldBe("fake-id-0"); - message1.Id.ShouldBe("fake-id-1"); - message1.ConsumerType = nameof(SingleConsumer); - message1.PayloadType = nameof(SingleConsumerMessage); - message1.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage1)); - message1.TraceId.ShouldBe(activity?.TraceId.ToString()); - message1.SpanId.ShouldBe(activity?.SpanId.ToString()); - var message2 = - await postDbContext.AssertSingleConsumerMessageById( - consumerMessage2, "fake-id-3"); - message2.AvailableAfter.ShouldBe(delay); - message2.Attempts.ShouldBe(0); - message2.InsertId.ShouldBe("fake-id-2"); - message2.Id.ShouldBe("fake-id-3"); - message2.ConsumerType = nameof(SingleConsumer); - message2.PayloadType = nameof(SingleConsumerMessage); - message2.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage2)); - message2.TraceId.ShouldBe(activity?.TraceId.ToString()); - message2.SpanId.ShouldBe(activity?.SpanId.ToString()); - } - } - finally - { - await dbContainer.DisposeAsync(); - } + using var scope = services.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().ConsumerMessages + .OrderBy(m => m.Id).ToListAsync(Ct); } [Theory] - [MemberData(nameof(GetTestDbTypesWithoutEf))] - public async Task Producer_Does_Not_Insert_Duplicate_ConsumerMessage(DbType dbType) + [MemberData(nameof(GetTestDbTypes))] + public Task Produce_writes_the_message_when_the_caller_saves(DbType dbType) => Run(dbType, async services => { - var dbContainer = GetTestDbContainer(dbType); - - try - { - // Given - var serviceProvider = await Setup(dbContainer); - var producer = serviceProvider.GetRequiredService(); + var payload = new SingleConsumerMessage { Name = "test-name" }; + using var activity = GetActivity(); + Activity.Current = activity; + + await Produce(services, p => p.Produce(payload, 10, cancellationToken: Ct)); + + using var scope = services.CreateScope(); + var message = await scope.ServiceProvider.GetRequiredService() + .AssertSingleConsumerMessage(payload); + message.AvailableAfter.ShouldBe(10); + message.Attempts.ShouldBe(0); + message.Payload.ShouldBe(JsonSerializer.Serialize(payload)); + message.TraceId.ShouldBe(activity?.TraceId.ToString()); + message.SpanId.ShouldBe(activity?.SpanId.ToString()); + }); - var delay = 10; - var insertId = "test-insert_id"; - var consumerMessage = new SingleConsumerMessage - { - Name = "test-name" - }; - using var activity = GetActivity(); - Activity.Current = activity; - - await producer.Produce(consumerMessage, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); - - // When - await producer.Produce(new SingleConsumerMessage - { - Name = "test-name-2" - }, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); - - // Then - using var scope = serviceProvider.CreateScope(); - { - var postDbContext = serviceProvider.GetRequiredService(); - var message = - await postDbContext.AssertSingleConsumerMessage( - consumerMessage); - message.AvailableAfter.ShouldBe(delay); - message.Attempts.ShouldBe(0); - message.Id.ShouldBe("fake-id-0"); - message.ConsumerType = nameof(SingleConsumer); - message.PayloadType = nameof(SingleConsumerMessage); - message.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage)); - message.InsertId.ShouldBe(insertId); - message.TraceId.ShouldBe(activity?.TraceId.ToString()); - message.SpanId.ShouldBe(activity?.SpanId.ToString()); - } - } - finally + [Theory] + [MemberData(nameof(GetTestDbTypes))] + public Task Produce_writes_nothing_until_the_caller_saves(DbType dbType) => Run(dbType, async services => + { + using (var scope = services.CreateScope()) { - await dbContainer.DisposeAsync(); + await scope.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "unsaved" }, cancellationToken: Ct); } - } + + (await Messages(services)).ShouldBeEmpty(); + }); [Theory] - [InlineData(DbType.Ef)] - public async Task EF_Producer_Throws_Exception_On_Duplicate_ConsumerMessage(DbType dbType) + [MemberData(nameof(GetTestDbTypes))] + public Task ProduceList_writes_one_message_per_payload(DbType dbType) => Run(dbType, async services => { - var dbContainer = GetTestDbContainer(dbType); + await Produce(services, p => p.ProduceList( + [new SingleConsumerMessage { Name = "a" }, new SingleConsumerMessage { Name = "b" }], 10, + cancellationToken: Ct)); - try - { - // Given - var serviceProvider = await Setup(dbContainer); - var scope = serviceProvider.CreateScope(); - var producer = scope.ServiceProvider.GetRequiredService(); - var dbContext = scope.ServiceProvider.GetRequiredService(); + var messages = await Messages(services); + messages.Count.ShouldBe(2); + messages.Select(m => m.InsertId).Distinct().Count().ShouldBe(2); + messages.ShouldAllBe(m => m.AvailableAfter == 10); + }); - var delay = 10; - var insertId = "test-insert_id"; - var consumerMessage = new SingleConsumerMessage - { - Name = "test-name" - }; - await producer.Produce(consumerMessage, 10, insertId, cancellationToken: TestContext.Current.CancellationToken); + [Theory] + [MemberData(nameof(GetTestDbTypes))] + public Task Produce_skips_an_insert_id_that_is_already_pending(DbType dbType) => Run(dbType, async services => + { + await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "key", + cancellationToken: Ct)); + await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "second" }, insertId: "key", + cancellationToken: Ct)); - // When - await producer.Produce(new SingleConsumerMessage - { - Name = "test-name-2" - }, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); + (await Messages(services)).ShouldHaveSingleItem().Payload.ShouldContain("first"); + }); - await Assert.ThrowsAsync(async () => { await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); }); - } - finally - { - await dbContainer.DisposeAsync(); - } - } -} \ No newline at end of file + [Theory] + [MemberData(nameof(GetTestDbTypes))] + public Task Racing_producers_are_stopped_by_the_unique_index(DbType dbType) => Run(dbType, async services => + { + using var first = services.CreateScope(); + using var second = services.CreateScope(); + await first.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "first" }, insertId: "key", cancellationToken: Ct); + await second.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "second" }, insertId: "key", cancellationToken: Ct); + + await first.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + await Should.ThrowAsync(() => + second.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct)); + }); +} diff --git a/AsyncMonolith/Producers/ProducerService.cs b/AsyncMonolith/Producers/ProducerService.cs new file mode 100644 index 0000000..906bd69 --- /dev/null +++ b/AsyncMonolith/Producers/ProducerService.cs @@ -0,0 +1,113 @@ +using System.Diagnostics; +using System.Text.Json; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Utilities; +using Microsoft.EntityFrameworkCore; + +namespace AsyncMonolith.Producers; + +/// +/// The producer for every provider. Messages are added to the caller's DbContext and written when the caller +/// calls SaveChanges, in the same transaction as their other changes (a transactional outbox). +/// +/// +/// When an insert id is given, consumers that already have a pending message with that insert id are skipped, +/// whether it is saved or only added to this DbContext. Two producers racing on the same insert id in separate +/// transactions are still stopped by the unique index, and the second SaveChanges throws. +/// +/// The DbContext containing the AsyncMonolith tables. +internal sealed class ProducerService : IProducerService where T : DbContext +{ + private readonly ConsumerRegistry _consumerRegistry; + private readonly T _dbContext; + private readonly IAsyncMonolithIdGenerator _idGenerator; + private readonly TimeProvider _timeProvider; + + public ProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, + IAsyncMonolithIdGenerator idGenerator) + { + _timeProvider = timeProvider; + _consumerRegistry = consumerRegistry; + _dbContext = dbContext; + _idGenerator = idGenerator; + } + + public async Task Produce(TK message, long? availableAfter = null, string? insertId = null, + CancellationToken cancellationToken = default) + where TK : IConsumerPayload + { + var payloadType = AsyncMonolithNames.ForPayload(); + var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); + + if (insertId is not null) + { + var pending = await PendingConsumers(insertId, consumers, cancellationToken); + consumers = consumers.Where(c => !pending.Contains(c)).ToList(); + } + + Add(payloadType, JsonSerializer.Serialize(message), consumers, availableAfter, + insertId ?? _idGenerator.GenerateId(), Activity.Current); + } + + public Task ProduceList(List messages, long? availableAfter = null, + CancellationToken cancellationToken = default) where TK : IConsumerPayload + { + var payloadType = AsyncMonolithNames.ForPayload(); + var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); + foreach (var message in messages) + { + Add(payloadType, JsonSerializer.Serialize(message), consumers, availableAfter, _idGenerator.GenerateId(), + Activity.Current); + } + + return Task.CompletedTask; + } + + public void Produce(ScheduledMessage message) + { + Add(message.PayloadType, message.Payload, _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType), + null, _idGenerator.GenerateId(), null); + } + + private async Task> PendingConsumers(string insertId, IReadOnlyList consumers, + CancellationToken cancellationToken) + { + var set = _dbContext.Set(); + var pending = set.Local + .Where(m => m.InsertId == insertId && consumers.Contains(m.ConsumerType)) + .Select(m => m.ConsumerType) + .ToHashSet(); + + var saved = await set.AsNoTracking() + .Where(m => m.InsertId == insertId && consumers.Contains(m.ConsumerType)) + .Select(m => m.ConsumerType) + .ToListAsync(cancellationToken); + pending.UnionWith(saved); + return pending; + } + + private void Add(string payloadType, string payload, IEnumerable consumers, long? availableAfter, + string insertId, Activity? activity) + { + var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); + var set = _dbContext.Set(); + foreach (var consumer in consumers) + { + set.Add(new ConsumerMessage + { + Id = _idGenerator.GenerateId(), + CreatedAt = currentTime, + AvailableAfter = availableAfter ?? currentTime, + Attempts = 0, + ConsumerType = consumer, + RailId = _consumerRegistry.ResolveConsumerRailId(consumer), + PayloadType = payloadType, + Payload = payload, + InsertId = insertId, + TraceId = activity?.TraceId.ToString(), + SpanId = activity?.SpanId.ToString() + }); + } + } +} diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index c86e42b..4cd9f8a 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -1,5 +1,6 @@ using System.Reflection; using AsyncMonolith.Consumers; +using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -107,6 +108,7 @@ internal static void InternalAddAsyncMonolith( // TryAdd, so a host can register its own implementation before or instead of these. services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(); + services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); diff --git a/docs/guides/producing-messages.md b/docs/guides/producing-messages.md index 3e14afd..8065e4e 100644 --- a/docs/guides/producing-messages.md +++ b/docs/guides/producing-messages.md @@ -35,9 +35,7 @@ You can produce messages to be consumed immediately like this: await _dbContext.SaveChangesAsync(cancellationToken); ``` -The message will be produced transactionally along with the change to your domain objects when you call `SaveChangesAsync`. Lean more about the [Transactional Outbox](../transactional-outbox) pattern. - -***If using the MySql, MsSql, MariaDb or PostgreSQL packages you will need to wrap your changes in a transaction see below*** +The message is added to your `DbContext` and written when you call `SaveChangesAsync`, in the same transaction as your other changes. If you never save, or the save fails, no message is written. This works the same with every database package. Learn more about the [Transactional Outbox](../transactional-outbox) pattern. ## Delayed messages You can produce messages to be consumed after a delay by specifying the number of seconds to wait before a consumer should process the message. @@ -71,30 +69,14 @@ Deduplicated messages are useful when you may emit the same message multiple tim await _dbContext.SaveChangesAsync(cancellationToken); ``` -Deduplicated events will ensure only a single message for a given consumer type and insertId are ever pending processing at any given time. - -### MySql / MsSql / MariaDb / PostgreSql Transactionality - -The produce method makes use of `ExecuteSqlRawAsync` when using the MySql, MsSql or PostgreSQL package, if you want the messages to be inserted transactionally with your domain changes you must wrap all the changes in an explicit transaction. - -```csharp - await using var dbContextTransaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken); - - order.Cancel(); - _dbContext.Orders.Update(order); - await _producerService.Produce(new OrderCancelled() - { - OrderId = order.Id, - CancelledAt = _timeProvider.UtcNow() - }); +How deduplication works: - await _dbContext.SaveChangesAsync(cancellationToken); - await dbContextTransaction.CommitAsync(cancellationToken); - -``` +- **While pending only.** If a consumer already has a pending message with this insert id (saved, or produced on the same `DbContext` and not yet saved), that consumer is skipped. Once its message has been consumed or poisoned, the same insert id is accepted again. It is not a permanent idempotency key. +- **Per consumer.** For a payload with several consumers, only the consumers that already have the insert id pending are skipped. +- **Concurrent producers.** Two requests producing the same insert id at the same moment, in separate transactions, can both pass the check. The unique index on `(insert_id, consumer_type)` then stops the second, and its `SaveChangesAsync` throws `DbUpdateException`. Summary -- **Transactional Persistence**: Produce messages along with changes to your `DbContext` before calling `SaveChangesAsync`, ensuring your domain changes and the messages they produce are persisted transactionally. +- **Transactional Persistence**: Produce messages along with changes to your `DbContext` before calling `SaveChangesAsync`, ensuring your domain changes and the messages they produce are persisted transactionally. Nothing is written until you save. - **Delay**: Specify the number of seconds a message should remain in the queue before it is processed by a consumer. -- **Deduplication**: By specifying a `insert_id` when producing messages the system ensures only one message with the same `insert_id` and `consumer_type` will be in the table at a given time. This is useful when you need a process to take place an amount of time after the first action in a sequence occured. +- **Deduplication**: By specifying an `insert_id`, a consumer that already has a pending message with that `insert_id` is skipped. This is useful when you need a process to take place an amount of time after the first action in a sequence occurred. From 21ee6870ddc512e12227f3e5005162259010f2ed Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:41:01 +0000 Subject: [PATCH 28/53] Make claiming safe for several app instances The EF fetcher reads candidate rows without locking them, so two app instances could claim and process the same message, and a schedule could fire twice for one occurrence. The provider fetchers lock rows, but nothing in the claim itself guarded against it. - A message is claimed with an update that only matches if its attempts and due time are unchanged since it was read. A processor that loses the race skips the message. - A schedule moves to its next occurrence with an update that only matches its current due time, and its message is produced only if that update won. Tests give a second processor a stale read (as another instance would have) and check it neither re-processes a message, nor claims a leased one, nor fires a schedule twice. These fail against the previous code. Two real hosts sharing a database also consume 60 messages exactly once. --- AsyncMonolith.Tests/MultipleInstanceTests.cs | 149 ++++++++++++++++++ .../Consumers/ConsumerMessageProcessor.cs | 25 ++- .../Scheduling/ScheduledMessageProcessor.cs | 12 +- docs/guides/consuming-messages.md | 3 +- 4 files changed, 182 insertions(+), 7 deletions(-) create mode 100644 AsyncMonolith.Tests/MultipleInstanceTests.cs diff --git a/AsyncMonolith.Tests/MultipleInstanceTests.cs b/AsyncMonolith.Tests/MultipleInstanceTests.cs new file mode 100644 index 0000000..8beb1c5 --- /dev/null +++ b/AsyncMonolith.Tests/MultipleInstanceTests.cs @@ -0,0 +1,149 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Ef; +using AsyncMonolith.Producers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Tests.Infra; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Several processors (in one app or several instances) working on the same tables. +/// +public class MultipleInstanceTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// Returns rows read earlier, as a second instance that read just before the first claimed would. + private sealed class StaleConsumerFetcher(List snapshot) : IConsumerMessageFetcher + { + public Task> Fetch(DbSet consumerSet, long currentTime, int railId, + CancellationToken cancellationToken = default) => Task.FromResult(snapshot); + } + + private sealed class StaleScheduleFetcher(List snapshot) : IScheduledMessageFetcher + { + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, + CancellationToken cancellationToken = default) => Task.FromResult(snapshot); + } + + [Fact] + public async Task A_message_claimed_by_one_processor_is_not_claimed_by_another_that_read_it_earlier() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "once" }); + var staleRead = await host.ConsumerMessages(); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + + var otherInstance = ActivatorUtilities.CreateInstance>( + host.Services, new StaleConsumerFetcher(staleRead)); + (await otherInstance.ProcessBatch(Ct)).ShouldBe(0); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + } + + [Fact] + public async Task A_message_leased_by_one_processor_is_not_claimed_by_another_that_read_it_earlier() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "once" }); + var staleRead = await host.ConsumerMessages(); + + // The first processor has claimed it and is still running the consumer. + (await host.ConsumerProcessor.ClaimBatch(Ct)).ShouldHaveSingleItem(); + + var otherInstance = ActivatorUtilities.CreateInstance>( + host.Services, new StaleConsumerFetcher(staleRead)); + (await otherInstance.ClaimBatch(Ct)).ShouldBeEmpty(); + (await host.ConsumerMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(1); + } + + [Fact] + public async Task A_schedule_fires_once_per_occurrence_when_two_processors_see_it() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "tick" }, "0 * * * * *"); + host.Time.Advance(TimeSpan.FromMinutes(1)); + var staleRead = await host.ScheduledMessages(); + + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(1); + + var otherInstance = ActivatorUtilities.CreateInstance>( + host.Services, new StaleScheduleFetcher(staleRead)); + (await otherInstance.ProcessBatch(Ct)).ShouldBe(0); + (await host.ConsumerMessages()).ShouldHaveSingleItem(); + } + + [Fact] + public async Task Two_running_instances_sharing_a_database_consume_each_message_exactly_once() + { + var path = Path.Combine(Path.GetTempPath(), $"asyncmonolith-instances-{Guid.NewGuid():N}.db"); + var instances = new List(); + try + { + for (var i = 0; i < 2; i++) + { + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={path}")); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddEfAsyncMonolith(s => + { + s.RegisterTypesFromAssemblyContaining(); + s.ProcessorMaxDelay = 20; + s.ProcessorMinDelay = 0; + s.ProcessorBatchSize = 5; + }); + instances.Add(builder.Build()); + } + + using (var scope = instances[0].Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.EnsureCreatedAsync(Ct); + var producer = scope.ServiceProvider.GetRequiredService(); + for (var i = 0; i < 60; i++) + { + await producer.Produce(new OrderedMessage { Name = $"m{i}" }, cancellationToken: Ct); + } + + await db.SaveChangesAsync(Ct); + } + + foreach (var instance in instances) + { + await instance.StartAsync(Ct); + } + + var counters = instances.Select(h => h.Services.GetRequiredService()).ToList(); + var deadline = DateTime.UtcNow.AddSeconds(20); + while (counters.Sum(c => c.Order.Count) < 60 && DateTime.UtcNow < deadline) + { + await Task.Delay(50, Ct); + } + + // Give a duplicate a chance to show up before checking. + await Task.Delay(300, Ct); + var all = counters.SelectMany(c => c.Order).ToList(); + all.Count.ShouldBe(60); + all.Distinct().Count().ShouldBe(60); + } + finally + { + foreach (var instance in instances) + { + await instance.StopAsync(CancellationToken.None); + instance.Dispose(); + } + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + foreach (var file in new[] { path, path + "-journal", path + "-wal", path + "-shm" }) + { + File.Delete(file); + } + } + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 1f2a988..5ee3172 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -160,15 +160,30 @@ internal async Task> ClaimBatch(CancellationToken cancellat return []; } - var claimed = messages.Select(m => new ClaimedMessage(m, m.AvailableAfter)).ToList(); + // Claim each message only if it is unchanged since it was read. Another processor (in this app or another + // instance) that claimed it first has changed its attempts and due time, so the update matches nothing. + var claimed = new List(messages.Count); foreach (var message in messages) { - message.Attempts++; - message.AvailableAfter = currentTime + _consumerRegistry.ResolveConsumerTimeout(message) + - LeaseGracePeriodSeconds; + var dueAt = message.AvailableAfter; + var attempts = message.Attempts; + var leaseUntil = currentTime + _consumerRegistry.ResolveConsumerTimeout(message) + LeaseGracePeriodSeconds; + + var updated = await dbContext.Set() + .Where(m => m.Id == message.Id && m.AvailableAfter == dueAt && m.Attempts == attempts) + .ExecuteUpdateAsync(s => s + .SetProperty(m => m.Attempts, attempts + 1) + .SetProperty(m => m.AvailableAfter, leaseUntil), cancellationToken); + if (updated == 0) + { + continue; + } + + message.Attempts = attempts + 1; + message.AvailableAfter = leaseUntil; + claimed.Add(new ClaimedMessage(message, dueAt)); } - await dbContext.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); return claimed; } diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index 0d12a0b..7ac7a13 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -102,8 +102,18 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa foreach (var message in messages) { + // Move the schedule on only if no other processor has already done so for this occurrence. + var dueAt = message.AvailableAfter; + var next = message.GetNextOccurrence(_timeProvider); + var updated = await set + .Where(m => m.Id == message.Id && m.AvailableAfter == dueAt) + .ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, next), cancellationToken); + if (updated == 0) + { + continue; + } + producer.Produce(message); - message.AvailableAfter = message.GetNextOccurrence(_timeProvider); processedScheduledMessageCount++; } diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index c1f8b13..afe4153 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -1,7 +1,8 @@ - **Independent Consumption**: Each message will be consumed independently by each consumer set up to handle it. - **Periodic Querying**: Each instance of your app will periodically query the `consumer_messages` table for a batch of available messages to process. - The query takes place at the frequency defined by `ProcessorMaxDelay`, if a full batch is returned it will delay by `ProcessorMinDelay`. -- **Concurrency**: Each app instance can run multiple parallel consumer processors defined by `ConsumerMessageProcessorCount`, unless using `AsyncMonolith.Ef`. +- **Multiple instances**: Any number of app instances can process the same tables, with every database package. A processor claims each message with a conditional update, so a message is only ever claimed by one processor at a time, and each schedule occurrence fires once. The PostgreSQL, SQL Server, MySQL and MariaDB packages also lock rows while claiming, so processors skip each other's batches instead of competing for them. +- **Rails**: Each rail (`[ConsumerRailId]`) gets its own processor, so a slow consumer on one rail doesn't hold up consumers on another. - **Batching**: Consumer messages will be read from the `consumer_messages` table in batches defined by `ConsumerMessageBatchSize`. - **Idempotency**: Ensure your Consumers are idempotent, since they will be retried on failure. - **Timeout**: Consumers timeout after the number of seconds defined by the `ConsumerTimeout` attribute or the `DefaultConsumerTimeout` if not set. From 160495de7cddaaf0026cea6ee982ccf7bee733cc Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:41:46 +0000 Subject: [PATCH 29/53] Make fetch order deterministic and document ordering honestly Fetchers ordered only by created_at, which is stored in whole seconds, so messages created in the same second came back in whatever order the database chose. Every fetcher now breaks ties by id (and the EF schedule fetcher by id after due time), so the order is stable. The consuming guide now says plainly what is and isn't guaranteed: only roughly oldest first; retries run after newer messages; and Sequential execution only means one at a time within a batch on one processor, not ordered delivery. --- AsyncMonolith.Ef/EfConsumerMessageFetcher.cs | 2 +- AsyncMonolith.Ef/EfScheduledMessageFetcher.cs | 2 +- .../MariaDbConsumerMessageFetcher.cs | 2 +- .../MsSqlConsumerMessageFetcher.cs | 2 +- .../MySqlConsumerMessageFetcher.cs | 2 +- .../PostgreSqlConsumerMessageFetcher.cs | 2 +- .../ConsumerProcessingTests.cs | 39 +++++++++++++++++++ docs/guides/consuming-messages.md | 10 +++++ 8 files changed, 55 insertions(+), 6 deletions(-) diff --git a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs index 0f29fd3..12d462b 100644 --- a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs @@ -34,7 +34,7 @@ public Task> Fetch(DbSet consumerSet, lon { return consumerSet .Where(m => m.AvailableAfter <= currentTime && m.RailId == railId) - .OrderBy(m => m.CreatedAt) + .OrderBy(m => m.CreatedAt).ThenBy(m => m.Id) .Take(_options.Value.ProcessorBatchSize) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs index 494c8c9..2a1d0cb 100644 --- a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs @@ -32,7 +32,7 @@ public Task> Fetch(DbSet scheduledMessa CancellationToken cancellationToken = default) { return scheduledMessageSet.Where(m => m.AvailableAfter <= currentTime) - .OrderBy(m => m.AvailableAfter) + .OrderBy(m => m.AvailableAfter).ThenBy(m => m.Id) .Take(_options.Value.ProcessorBatchSize) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs index d89dc95..12d7096 100644 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs @@ -15,7 +15,7 @@ public sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher SELECT * FROM consumer_messages WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at + ORDER BY created_at, id LIMIT @batchSize FOR UPDATE SKIP LOCKED"; diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs index ae4cec9..333c3d0 100644 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs @@ -15,7 +15,7 @@ public sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher SELECT TOP (@batchSize) * FROM consumer_messages WITH (ROWLOCK, READPAST) WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at"; + ORDER BY created_at, id"; private readonly IOptions _options; diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs index fbff493..25f0a44 100644 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs @@ -15,7 +15,7 @@ public sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher SELECT * FROM consumer_messages WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at + ORDER BY created_at, id LIMIT @batchSize FOR UPDATE SKIP LOCKED"; diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs index 9ae42e7..d034b30 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs @@ -15,7 +15,7 @@ public sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher SELECT * FROM consumer_messages WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at + ORDER BY created_at, id FOR UPDATE SKIP LOCKED LIMIT @batchSize"; diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs index 339d082..6f279fb 100644 --- a/AsyncMonolith.Tests/ConsumerProcessingTests.cs +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -185,6 +185,45 @@ await host.Change(db => host.Invocations.Order.ShouldBe(["OrderedConsumer:older", "OrderedConsumer:newer"]); } + [Fact] + public async Task Messages_created_in_the_same_second_are_taken_in_id_order() + { + await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 1); + await host.Produce(new OrderedMessage { Name = "first" }); + await host.Produce(new OrderedMessage { Name = "second" }); + // Swap the ids so that id order differs from insertion order. + var ids = (await host.ConsumerMessages()).Select(m => m.Id).ToList(); + await host.Change(db => + { + db.ConsumerMessages.RemoveRange(db.ConsumerMessages); + }); + await host.Change(db => + { + db.ConsumerMessages.Add(Message(ids[1], "first", host.Now)); + db.ConsumerMessages.Add(Message(ids[0], "second", host.Now)); + }); + + await host.ConsumerProcessor.ProcessBatch(Ct); + await host.ConsumerProcessor.ProcessBatch(Ct); + + host.Invocations.Order.ShouldBe(["OrderedConsumer:second", "OrderedConsumer:first"]); + } + + private static ConsumerMessage Message(string id, string name, long now) => new() + { + Id = id, + CreatedAt = now, + AvailableAfter = now, + Attempts = 0, + ConsumerType = nameof(OrderedConsumer), + RailId = 0, + PayloadType = nameof(OrderedMessage), + Payload = System.Text.Json.JsonSerializer.Serialize(new OrderedMessage { Name = name }), + InsertId = id, + TraceId = null, + SpanId = null + }; + [Fact] public async Task Each_consumer_of_a_payload_succeeds_or_fails_independently() { diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index afe4153..d688d43 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -29,6 +29,16 @@ public class DeleteUsersPosts : BaseConsumer } ``` +## Ordering + +Messages are taken roughly oldest first, but **delivery order is not guaranteed**: + +- `created_at` is stored in whole seconds. Messages created in the same second are taken in `id` order, and ids are random, so their order is effectively arbitrary. +- A failed message is retried later, after messages that were created after it. +- Messages in a batch run in parallel by default. `[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Sequential)]` only runs one consumer's messages one at a time **within a batch on one processor**. It doesn't order them across batches, retries, rails or app instances. + +Design consumers so the order of messages doesn't matter, for example by checking the current state of the data rather than relying on earlier messages having run. + ## Consumer Failures 💢 - **Retry Logic**: Messages are retried up to `MaxAttempts` times before they are moved to the `poisoned_messages` table. Add the `[ConsumerAttempts(1)]` attribute to override this per consumer. From ca388b02189bddee3826adaaca00971766d17e59 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:41:58 +0000 Subject: [PATCH 30/53] Describe the producer, multi-instance and registration changes in the 10.1.0 notes --- docs/releases.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/releases.md b/docs/releases.md index 23a7aa5..4dffdb6 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -22,6 +22,9 @@ All packages now share one version and must be upgraded together. **Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_10_1_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** +- Every database package now produces messages the same way: they are added to your `DbContext` and written on `SaveChanges`, in your transaction. The PostgreSQL, SQL Server, MySQL and MariaDB packages used to write immediately. A repeated insert id skips consumers that already have a pending message with it, on every database. +- Several app instances can safely share the tables with any database package. Claims and schedule occurrences use conditional updates, so a message is processed by one processor at a time and a schedule fires once per occurrence. +- Fetch order is deterministic (oldest first, then by id). See [Ordering](guides/consuming-messages.md#ordering) for what is and isn't guaranteed. - Consumers can write to the database on SQLite. Messages are claimed and leased in a short transaction, consumers run outside it, and each message is completed in its own short write. If the app stops mid-message, the message is retried once its consumer timeout plus 30 seconds has passed. - Retries back off exponentially from `AttemptDelay` up to the new `MaxAttemptDelay` setting (default 300 seconds). - The last error is stored on retried and poisoned messages. @@ -32,6 +35,9 @@ All packages now share one version and must be upgraded together. - `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. **Breaking changes** +- PostgreSQL, SQL Server, MySQL and MariaDB users: messages are no longer written until you call `SaveChanges`. If you produced messages without saving, call `SaveChangesAsync`. +- `Add*AsyncMonolith` no longer registers `DbContext` as an alias for your context, and throws if called twice (modules use `AddAsyncMonolithConsumers`). Its services use `TryAdd`, so services you register first win. +- Removed public types: `EfProducerService`, `PostgreSqlProducerService`, `MsSqlProducerService`, `MySqlProducerService`, `MariaDbProducerService` and the unused `ScheduledMessageProcessorFactory`. Resolve `IProducerService` instead. - `AsyncMonolith.TestHelpers` uses xunit v3, and `ConsumerTestBase.InitializeAsync`/`DisposeAsync` return `ValueTask`. - `IScheduleService` has a new member (`EnsureSchedule`), so custom implementations must add it. - Errors that were thrown as `System.Exception` are now `InvalidOperationException`. From fd8af04935e8021fff8e5e305c435a69ea18ad2f Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:48:56 +0000 Subject: [PATCH 31/53] Version 11.0.0, with MySQL and MariaDB as previews The release breaks existing users, so the major version moves to 11 and follows Semantic Versioning from here instead of tracking .NET. AsyncMonolith.MySql and AsyncMonolith.MariaDb pack as 11.0.0-preview.1 until Pomelo supports EF Core 10 and they run in the integration tests. --- AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj | 2 ++ AsyncMonolith.MySql/AsyncMonolith.MySql.csproj | 2 ++ Directory.Build.props | 2 +- docs/releases.md | 8 ++++---- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index 35d0d43..3e77a4d 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -3,6 +3,8 @@ $(NoWarn);NU1608 + + preview.1 NU5104 true AsyncMonolith.MariaDb diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 93611be..4eb42e3 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -3,6 +3,8 @@ $(NoWarn);NU1608 + + preview.1 NU5104 true AsyncMonolith.MySql diff --git a/Directory.Build.props b/Directory.Build.props index 19f1778..7a366c5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ latest - 10.1.0 + 11.0.0 true true diff --git a/docs/releases.md b/docs/releases.md index 4dffdb6..31dc6d2 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -2,7 +2,7 @@ Make sure to check this table before updating the nuget package in your solution | Version | Description | Migration Required | |---------|--------------------------------------------|--------------------| -| 10.1.0 | SQLite-safe processing, stored names, modules, backoff, poisoned message service (see below) | Yes | +| 11.0.0 | SQLite-safe processing, stored names, modules, backoff, poisoned message service (see below) | Yes | | 8.0.6 | Added ConsumerAttempts override attribute | No | | 8.0.5 | Bundle debug symbols with nuget package | No | | 8.0.4 | Bundle XML docs with nuget package | No | @@ -15,11 +15,11 @@ Make sure to check this table before updating the nuget package in your solution ***If you're not using ef migrations check out the sql to configure your database [here](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas)*** -## 10.1.0 +## 11.0.0 -All packages now share one version and must be upgraded together. +All packages now share one version and must be upgraded together. From 11.0.0 the major version follows [Semantic Versioning](https://semver.org) (it changes for breaking changes) rather than the .NET version. `AsyncMonolith.MySql` and `AsyncMonolith.MariaDb` are published as previews (`11.0.0-preview.1`) until Pomelo supports EF Core 10 and they run in the integration tests. -**Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_10_1_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. +**Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** - Every database package now produces messages the same way: they are added to your `DbContext` and written on `SaveChanges`, in your transaction. The PostgreSQL, SQL Server, MySQL and MariaDB packages used to write immediately. A repeated insert id skips consumers that already have a pending message with it, on every database. From 256eef4f83b301d3fc0d5bf0faeb475b53a14f75 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:51:40 +0000 Subject: [PATCH 32/53] Replace BaseConsumer with IConsumer and a ConsumeContext Consumers had to inherit BaseConsumer and could not see which message they were handling, so idempotency checks and useful logging were not possible. Adding that later would break every consumer, so it changes now: - Consumers implement IConsumer with Consume(payload, ConsumeContext context, CancellationToken). - ConsumeContext carries MessageId, DeduplicationKey, Attempt (from 1), MaxAttempts, IsLastAttempt, CreatedAt, ConsumerName, PayloadName and TraceId. - BaseConsumer and the non-generic IConsumer.Consume(ConsumerMessage) are removed. IConsumer remains as an empty marker for constraints. - Registration finds classes implementing IConsumer; a class that implements it for two payloads fails at startup. - TestHelpers constraints and helpers use IConsumer. Every test consumer, the example API and the docs are converted. Tests cover the context's fields, attempt numbering across retries, the shared deduplication key and the two-payload error. --- .../ConsumerMessageTestHelpers.cs | 8 +- AsyncMonolith.TestHelpers/ConsumerTestBase.cs | 2 +- .../TestConsumerMessageProcessor.cs | 67 +++++--------- AsyncMonolith.Tests/ConfigurationTests.cs | 25 ------ AsyncMonolith.Tests/ConsumeContextTests.cs | 87 +++++++++++++++++++ AsyncMonolith.Tests/HostedProcessingTests.cs | 1 + .../Infra/BehaviourConsumers.cs | 24 ++--- AsyncMonolith.Tests/Infra/ContextConsumer.cs | 30 +++++++ .../Infra/ExceptionConsumer.cs | 4 +- .../Infra/ExceptionConsumer2Attempts.cs | 4 +- AsyncMonolith.Tests/Infra/MultiConsumer1.cs | 4 +- AsyncMonolith.Tests/Infra/MultiConsumer2.cs | 4 +- AsyncMonolith.Tests/Infra/NamedConsumers.cs | 55 +++++++++--- .../Infra/RailConsumerMessages.cs | 12 +-- AsyncMonolith.Tests/Infra/SingleConsumer.cs | 4 +- AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 1 + AsyncMonolith.Tests/Infra/TimeoutConsumer.cs | 4 +- AsyncMonolith.Tests/Infra/WritingConsumer.cs | 4 +- AsyncMonolith.Tests/MultipleInstanceTests.cs | 1 + AsyncMonolith/Consumers/BaseConsumer.cs | 32 ------- AsyncMonolith/Consumers/ConsumeContext.cs | 49 +++++++++++ AsyncMonolith/Consumers/ConsumerInvoker.cs | 63 ++++++++++++++ .../Consumers/ConsumerMessageProcessor.cs | 12 +-- AsyncMonolith/Consumers/IConsumer.cs | 28 ++++-- AsyncMonolith/Utilities/StartupExtensions.cs | 11 +-- .../Example.Api/Counter/TotalValueConsumer.cs | 4 +- .../Counter/ValueSubmittedConsumer.cs | 4 +- .../Example.Api/Spam/SpamMessageConsumer.cs | 4 +- README.md | 4 +- docs/guides/changing-messages.md | 2 +- docs/guides/consuming-messages.md | 6 +- docs/posts/idempotency.md | 4 +- docs/posts/mediator.md | 8 +- docs/posts/transactional-outbox.md | 4 +- docs/quickstart.md | 4 +- 35 files changed, 382 insertions(+), 198 deletions(-) create mode 100644 AsyncMonolith.Tests/ConsumeContextTests.cs create mode 100644 AsyncMonolith.Tests/Infra/ContextConsumer.cs delete mode 100644 AsyncMonolith/Consumers/BaseConsumer.cs create mode 100644 AsyncMonolith/Consumers/ConsumeContext.cs create mode 100644 AsyncMonolith/Consumers/ConsumerInvoker.cs diff --git a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs index e85e1e8..f5ae8a3 100644 --- a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs @@ -36,7 +36,7 @@ public static async Task> GetConsumerMessages(this DbCo /// The database context. /// A list of consumer messages. public static async Task> GetConsumerMessages(this DbContext dbContext) - where T : BaseConsumer where TPayload : IConsumerPayload + where T : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); var consumerName = AsyncMonolithNames.ForConsumer(consumerType); @@ -58,7 +58,7 @@ public static async Task> GetConsumerMessages /// The payload. /// A list of consumer messages. public static async Task> GetConsumerMessages(this DbContext dbContext, TPayload payload) - where T : BaseConsumer where TPayload : IConsumerPayload + where T : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); var consumerName = AsyncMonolithNames.ForConsumer(consumerType); @@ -82,7 +82,7 @@ public static async Task> GetConsumerMessages /// The payload. /// The single consumer message. public static async Task AssertSingleConsumerMessage(this DbContext dbContext, TPayload payload) - where T : BaseConsumer where TPayload : IConsumerPayload + where T : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); var consumerName = AsyncMonolithNames.ForConsumer(consumerType); @@ -131,7 +131,7 @@ public static async Task AssertSingleScheduledMessage(this /// The ID. /// The single consumer message. public static async Task AssertSingleConsumerMessageById(this DbContext dbContext, TPayload payload, - string id) where T : BaseConsumer where TPayload : IConsumerPayload + string id) where T : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); var consumerName = AsyncMonolithNames.ForConsumer(consumerType); diff --git a/AsyncMonolith.TestHelpers/ConsumerTestBase.cs b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs index e07bb73..5a724e4 100644 --- a/AsyncMonolith.TestHelpers/ConsumerTestBase.cs +++ b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs @@ -94,7 +94,7 @@ public virtual ValueTask DisposeAsync() /// The payload. /// The cancellation token. /// A task representing the asynchronous operation. - protected async Task Process(TPayload payload, CancellationToken cancellationToken = default) where T : BaseConsumer where TPayload : IConsumerPayload + protected async Task Process(TPayload payload, CancellationToken cancellationToken = default) where T : IConsumer where TPayload : IConsumerPayload { using var scope = Services.CreateScope(); await TestConsumerMessageProcessor.Process(scope, payload, cancellationToken); diff --git a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs index 9753b9e..61e955e 100644 --- a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs +++ b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs @@ -36,16 +36,10 @@ public static class TestConsumerMessageProcessor var consumerType = consumerRegistry.ResolveConsumerType(message); - // Resolve the consumer - if (scope.ServiceProvider.GetRequiredService(consumerType) - is not IConsumer consumer) - { - Assert.Fail($"Couldn't resolve consumer service of type: '{message.ConsumerType}'"); - return null; - } - - // Execute the consumer - await consumer.Consume(message, cancellationToken); + var consumer = scope.ServiceProvider.GetRequiredService(consumerType); + var maxAttempts = scope.ServiceProvider.GetRequiredService().ResolveConsumerMaxAttempts(message); + await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), null, + cancellationToken); consumerMessageSet.Remove(message); @@ -80,16 +74,10 @@ public static class TestConsumerMessageProcessor return null; } - // Resolve the consumer - if (scope.ServiceProvider.GetRequiredService(consumerType) - is not IConsumer consumer) - { - Assert.Fail($"Couldn't resolve consumer service of type: '{message.ConsumerType}'"); - return null; - } - - // Execute the consumer - await consumer.Consume(message, cancellationToken); + var consumer = scope.ServiceProvider.GetRequiredService(consumerType); + var maxAttempts = scope.ServiceProvider.GetRequiredService().ResolveConsumerMaxAttempts(message); + await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), null, + cancellationToken); consumerMessageSet.Remove(message); @@ -102,38 +90,25 @@ public static class TestConsumerMessageProcessor /// /// Processes the consumer message of type T and TPayload with the given payload. /// - /// The type of BaseConsumer. + /// The consumer type. /// The type of IConsumerPayload. /// The service scope. /// The payload for the consumer message. /// The cancellation token. public static async Task Process(IServiceScope scope, TPayload payload, - CancellationToken cancellationToken = default) where T : BaseConsumer where TPayload : IConsumerPayload + CancellationToken cancellationToken = default) where T : IConsumer where TPayload : IConsumerPayload { - var consumerType = typeof(T); - - // Resolve the consumer - if (scope.ServiceProvider.GetRequiredService(consumerType) - is not IConsumer consumer) - { - Assert.Fail($"Couldn't resolve consumer service of type: '{consumerType.Name}'"); - return; - } - - // Execute the consumer - await consumer.Consume(new ConsumerMessage + var consumer = scope.ServiceProvider.GetRequiredService(); + var context = new ConsumeContext { - Attempts = 0, - AvailableAfter = 0, - ConsumerType = AsyncMonolithNames.ForConsumer(consumerType), - CreatedAt = 0, - Id = string.Empty, - InsertId = string.Empty, - Payload = JsonSerializer.Serialize(payload), - PayloadType = AsyncMonolithNames.ForPayload(), - TraceId = null, - SpanId = null, - RailId = 0 - }, cancellationToken); + MessageId = "test-message", + DeduplicationKey = "test-message", + Attempt = 1, + MaxAttempts = 1, + CreatedAt = DateTimeOffset.UnixEpoch, + ConsumerName = AsyncMonolithNames.ForConsumer(), + PayloadName = AsyncMonolithNames.ForPayload() + }; + await consumer.Consume(payload, context, cancellationToken); } } diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs index 63dbb48..3a3a295 100644 --- a/AsyncMonolith.Tests/ConfigurationTests.cs +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -180,31 +180,6 @@ public void Generated_ids_do_not_repeat() ids.Distinct().Count().ShouldBe(ids.Count); } - [Fact] - public async Task BaseConsumer_deserializes_the_payload_for_the_typed_consumer() - { - var invocations = new TestConsumerInvocations(); - var consumer = new OrderedConsumer(invocations); - var message = MessageFor(nameof(OrderedConsumer)); - message.Payload = JsonSerializer.Serialize(new OrderedMessage { Name = "typed" }); - - await consumer.Consume(message, TestContext.Current.CancellationToken); - - invocations.Order.ShouldBe(["OrderedConsumer:typed"]); - } - - [Fact] - public async Task BaseConsumer_rejects_a_null_payload() - { - var consumer = new OrderedConsumer(new TestConsumerInvocations()); - var message = MessageFor(nameof(OrderedConsumer)); - message.Payload = "null"; - - var exception = await Should.ThrowAsync(() => - consumer.Consume(message, TestContext.Current.CancellationToken)); - exception.Message.ShouldContain(nameof(OrderedConsumer)); - } - [Fact] public void AddEfAsyncMonolith_registers_the_services_and_background_processors() { diff --git a/AsyncMonolith.Tests/ConsumeContextTests.cs b/AsyncMonolith.Tests/ConsumeContextTests.cs new file mode 100644 index 0000000..ae7a5d1 --- /dev/null +++ b/AsyncMonolith.Tests/ConsumeContextTests.cs @@ -0,0 +1,87 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The IConsumer<T> contract and the ConsumeContext passed to consumers. +/// +public class ConsumeContextTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static async Task<(SqliteTestHost Host, ContextRecorder Recorder)> Host() + { + var host = await SqliteTestHost.Create(s => s.AttemptDelay = 0); + return (host, host.Services.GetRequiredService()); + } + + [Fact] + public async Task Context_describes_the_message_and_attempt() + { + var (host, recorder) = await Host(); + await using var _ = host; + await host.Produce(new ContextMessage(), insertId: "order-42"); + var stored = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + var context = recorder.Contexts.ShouldHaveSingleItem(); + context.MessageId.ShouldBe(stored.Id); + context.DeduplicationKey.ShouldBe("order-42"); + context.Attempt.ShouldBe(1); + context.MaxAttempts.ShouldBe(3); + context.IsLastAttempt.ShouldBeFalse(); + context.CreatedAt.ShouldBe(DateTimeOffset.FromUnixTimeSeconds(stored.CreatedAt)); + context.ConsumerName.ShouldBe(nameof(ContextConsumer)); + context.PayloadName.ShouldBe(nameof(ContextMessage)); + } + + [Fact] + public async Task Attempt_counts_up_across_retries_until_the_last() + { + var (host, recorder) = await Host(); + await using var _ = host; + recorder.FailuresLeft = 2; + await host.Produce(new ContextMessage()); + + for (var i = 0; i < 3; i++) + { + await host.ConsumerProcessor.ProcessBatch(Ct); + } + + recorder.Contexts.Select(c => c.Attempt).ShouldBe([1, 2, 3]); + recorder.Contexts.Select(c => c.IsLastAttempt).ShouldBe([false, false, true]); + recorder.Contexts.Select(c => c.MessageId).Distinct().ShouldHaveSingleItem(); + (await host.ConsumerMessages()).ShouldBeEmpty(); + } + + [Fact] + public async Task Consumers_of_one_payload_share_its_deduplication_key() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MultiConsumerMessage { Name = "x" }); + + (await host.ConsumerMessages()).Select(m => m.InsertId).Distinct().ShouldHaveSingleItem(); + } + + [Fact] + public void A_consumer_class_handling_two_payloads_is_rejected_at_startup() + { + var settings = AsyncMonolithSettings.Default; + settings.RegisterTypesFromAssemblies(ClashingTypes.ConsumerOfTwoPayloads()); + var services = new ServiceCollection(); + + var exception = Should.Throw(() => + { + services.InternalRegisterAsyncMonolithConsumers(settings); + services.BuildServiceProvider().GetRequiredService(); + }); + + exception.Message.ShouldContain("TwoPayloads.BothConsumer"); + exception.Message.ShouldContain("one consumer class per payload"); + } +} diff --git a/AsyncMonolith.Tests/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs index f755daa..fa8ef18 100644 --- a/AsyncMonolith.Tests/HostedProcessingTests.cs +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -32,6 +32,7 @@ private async Task StartHost(Action? configure = null, bo builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddEfAsyncMonolith(s => { if (!registerAsModule) diff --git a/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs index f42b827..06c149c 100644 --- a/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs +++ b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs @@ -9,9 +9,9 @@ public class OrderedMessage : IConsumerPayload [JsonPropertyName("name")] public required string Name { get; set; } } -public class OrderedConsumer(TestConsumerInvocations invocations) : BaseConsumer +public class OrderedConsumer(TestConsumerInvocations invocations) : IConsumer { - public override Task Consume(OrderedMessage payload, CancellationToken cancellationToken) + public Task Consume(OrderedMessage payload, ConsumeContext context, CancellationToken cancellationToken) { invocations.Increment($"{nameof(OrderedConsumer)}:{payload.Name}"); return Task.CompletedTask; @@ -23,18 +23,18 @@ public class MixedOutcomeMessage : IConsumerPayload { } -public class MixedSuccessConsumer(TestConsumerInvocations invocations) : BaseConsumer +public class MixedSuccessConsumer(TestConsumerInvocations invocations) : IConsumer { - public override Task Consume(MixedOutcomeMessage payload, CancellationToken cancellationToken) + public Task Consume(MixedOutcomeMessage payload, ConsumeContext context, CancellationToken cancellationToken) { invocations.Increment(nameof(MixedSuccessConsumer)); return Task.CompletedTask; } } -public class MixedFailureConsumer(TestConsumerInvocations invocations) : BaseConsumer +public class MixedFailureConsumer(TestConsumerInvocations invocations) : IConsumer { - public override Task Consume(MixedOutcomeMessage payload, CancellationToken cancellationToken) + public Task Consume(MixedOutcomeMessage payload, ConsumeContext context, CancellationToken cancellationToken) { invocations.Increment(nameof(MixedFailureConsumer)); throw new InvalidOperationException("Always fails"); @@ -48,9 +48,9 @@ public class InvalidAttributesMessage : IConsumerPayload [ConsumerTimeout(0)] [ConsumerAttempts(-1)] -public class InvalidAttributesConsumer : BaseConsumer +public class InvalidAttributesConsumer : IConsumer { - public override Task Consume(InvalidAttributesMessage payload, CancellationToken cancellationToken) => + public Task Consume(InvalidAttributesMessage payload, ConsumeContext context, CancellationToken cancellationToken) => Task.CompletedTask; } @@ -88,9 +88,9 @@ public class ParallelProbeMessage : IConsumerPayload } [ConsumerExecutionMode(ConsumerInstanceExecutionMode.Parallel)] -public class ParallelProbeConsumer(ConcurrencyProbe probe) : BaseConsumer +public class ParallelProbeConsumer(ConcurrencyProbe probe) : IConsumer { - public override Task Consume(ParallelProbeMessage payload, CancellationToken cancellationToken) => + public Task Consume(ParallelProbeMessage payload, ConsumeContext context, CancellationToken cancellationToken) => probe.Enter(2, cancellationToken); } @@ -99,8 +99,8 @@ public class SequentialProbeMessage : IConsumerPayload } [ConsumerExecutionMode(ConsumerInstanceExecutionMode.Sequential)] -public class SequentialProbeConsumer(ConcurrencyProbe probe) : BaseConsumer +public class SequentialProbeConsumer(ConcurrencyProbe probe) : IConsumer { - public override Task Consume(SequentialProbeMessage payload, CancellationToken cancellationToken) => + public Task Consume(SequentialProbeMessage payload, ConsumeContext context, CancellationToken cancellationToken) => probe.Enter(2, cancellationToken); } diff --git a/AsyncMonolith.Tests/Infra/ContextConsumer.cs b/AsyncMonolith.Tests/Infra/ContextConsumer.cs new file mode 100644 index 0000000..0cfd031 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/ContextConsumer.cs @@ -0,0 +1,30 @@ +using AsyncMonolith.Consumers; + +namespace AsyncMonolith.Tests.Infra; + +/// Records every context it receives, and fails while > 0. +public sealed class ContextRecorder +{ + public List Contexts { get; } = []; + public int FailuresLeft { get; set; } +} + +public class ContextMessage : IConsumerPayload +{ +} + +[ConsumerAttempts(3)] +public class ContextConsumer(ContextRecorder recorder) : IConsumer +{ + public Task Consume(ContextMessage payload, ConsumeContext context, CancellationToken cancellationToken) + { + recorder.Contexts.Add(context); + if (recorder.FailuresLeft > 0) + { + recorder.FailuresLeft--; + throw new InvalidOperationException("Failing as asked"); + } + + return Task.CompletedTask; + } +} diff --git a/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs b/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs index c720177..a967e09 100644 --- a/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs +++ b/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs @@ -2,7 +2,7 @@ namespace AsyncMonolith.Tests.Infra; -public class ExceptionConsumer : BaseConsumer +public class ExceptionConsumer : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -11,7 +11,7 @@ public ExceptionConsumer(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(ExceptionConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(ExceptionConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(ExceptionConsumer)); throw new InvalidOperationException(); diff --git a/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs b/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs index 65667c7..bc3cd8d 100644 --- a/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs +++ b/AsyncMonolith.Tests/Infra/ExceptionConsumer2Attempts.cs @@ -3,7 +3,7 @@ namespace AsyncMonolith.Tests.Infra; [ConsumerAttempts(2)] -public class ExceptionConsumer2Attempts : BaseConsumer +public class ExceptionConsumer2Attempts : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -12,7 +12,7 @@ public ExceptionConsumer2Attempts(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(ExceptionConsumer2AttemptsMessage message, CancellationToken cancellationToken) + public Task Consume(ExceptionConsumer2AttemptsMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(ExceptionConsumer2AttemptsMessage)); throw new InvalidOperationException(); diff --git a/AsyncMonolith.Tests/Infra/MultiConsumer1.cs b/AsyncMonolith.Tests/Infra/MultiConsumer1.cs index 45f70f7..479c413 100644 --- a/AsyncMonolith.Tests/Infra/MultiConsumer1.cs +++ b/AsyncMonolith.Tests/Infra/MultiConsumer1.cs @@ -2,7 +2,7 @@ namespace AsyncMonolith.Tests.Infra; -public class MultiConsumer1 : BaseConsumer +public class MultiConsumer1 : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -11,7 +11,7 @@ public MultiConsumer1(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(MultiConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(MultiConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(MultiConsumer1)); return Task.CompletedTask; diff --git a/AsyncMonolith.Tests/Infra/MultiConsumer2.cs b/AsyncMonolith.Tests/Infra/MultiConsumer2.cs index 20dcba7..6677348 100644 --- a/AsyncMonolith.Tests/Infra/MultiConsumer2.cs +++ b/AsyncMonolith.Tests/Infra/MultiConsumer2.cs @@ -2,7 +2,7 @@ namespace AsyncMonolith.Tests.Infra; -public class MultiConsumer2 : BaseConsumer +public class MultiConsumer2 : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -11,7 +11,7 @@ public MultiConsumer2(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(MultiConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(MultiConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(MultiConsumer2)); diff --git a/AsyncMonolith.Tests/Infra/NamedConsumers.cs b/AsyncMonolith.Tests/Infra/NamedConsumers.cs index d8b6aaa..b384ba8 100644 --- a/AsyncMonolith.Tests/Infra/NamedConsumers.cs +++ b/AsyncMonolith.Tests/Infra/NamedConsumers.cs @@ -12,9 +12,9 @@ public class NamedMessage : IConsumerPayload } [ConsumerName("tests.named.consumer")] -public class NamedConsumer(TestConsumerInvocations invocations) : BaseConsumer +public class NamedConsumer(TestConsumerInvocations invocations) : IConsumer { - public override Task Consume(NamedMessage payload, CancellationToken cancellationToken) + public Task Consume(NamedMessage payload, ConsumeContext context, CancellationToken cancellationToken) { invocations.Increment(nameof(NamedConsumer)); return Task.CompletedTask; @@ -50,24 +50,55 @@ public static Assembly Build(string[] namespaces, string? consumerName = null, var payload = payloadBuilder.CreateType(); - var baseType = typeof(BaseConsumer<>).MakeGenericType(payload); var consumerBuilder = module.DefineType($"{namespaces[i]}.{consumerName ?? $"SendEmailConsumer{i}"}", - TypeAttributes.Public | TypeAttributes.Class, baseType); + TypeAttributes.Public | TypeAttributes.Class, typeof(object)); consumerBuilder.DefineDefaultConstructor(MethodAttributes.Public); - var consume = consumerBuilder.DefineMethod("Consume", - MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, - typeof(Task), [payload, typeof(CancellationToken)]); - var il = consume.GetILGenerator(); - il.Emit(OpCodes.Call, typeof(Task).GetProperty(nameof(Task.CompletedTask))!.GetMethod!); - il.Emit(OpCodes.Ret); - consumerBuilder.DefineMethodOverride(consume, - baseType.GetMethod("Consume", [payload, typeof(CancellationToken)])!); + ImplementConsumer(consumerBuilder, payload, "Consume"); consumerBuilder.CreateType(); } return assembly; } + /// Builds an assembly with one consumer class that implements IConsumer<T> for two payloads. + public static Assembly ConsumerOfTwoPayloads() + { + var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"TwoPayloads{Guid.NewGuid():N}"), + AssemblyBuilderAccess.Run); + var module = assembly.DefineDynamicModule("TwoPayloads"); + string[] names = ["First", "Second"]; + var payloads = names.Select(name => + { + var builder = module.DefineType($"TwoPayloads.{name}", TypeAttributes.Public | TypeAttributes.Class, + typeof(object), [typeof(IConsumerPayload)]); + builder.DefineDefaultConstructor(MethodAttributes.Public); + return builder.CreateType(); + }).ToList(); + + var consumer = module.DefineType("TwoPayloads.BothConsumer", TypeAttributes.Public | TypeAttributes.Class, + typeof(object)); + consumer.DefineDefaultConstructor(MethodAttributes.Public); + ImplementConsumer(consumer, payloads[0], "ConsumeFirst"); + ImplementConsumer(consumer, payloads[1], "ConsumeSecond"); + consumer.CreateType(); + return assembly; + } + + /// Implements IConsumer<payload> with a method that does nothing. + private static void ImplementConsumer(TypeBuilder consumer, Type payload, string methodName) + { + var consumerInterface = typeof(IConsumer<>).MakeGenericType(payload); + consumer.AddInterfaceImplementation(consumerInterface); + var consume = consumer.DefineMethod(methodName, + MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.HideBySig | + MethodAttributes.NewSlot | MethodAttributes.Final, + typeof(Task), [payload, typeof(ConsumeContext), typeof(CancellationToken)]); + var il = consume.GetILGenerator(); + il.Emit(OpCodes.Call, typeof(Task).GetProperty(nameof(Task.CompletedTask))!.GetMethod!); + il.Emit(OpCodes.Ret); + consumer.DefineMethodOverride(consume, consumerInterface.GetMethod(nameof(IConsumer.Consume))!); + } + /// Builds an assembly with a payload that has no consumer. public static Assembly PayloadOnly(string ns) { diff --git a/AsyncMonolith.Tests/Infra/RailConsumerMessages.cs b/AsyncMonolith.Tests/Infra/RailConsumerMessages.cs index e33ee5f..7ed90e1 100644 --- a/AsyncMonolith.Tests/Infra/RailConsumerMessages.cs +++ b/AsyncMonolith.Tests/Infra/RailConsumerMessages.cs @@ -8,7 +8,7 @@ public class RailConsumerMessage : IConsumerPayload } -public class RailConsumer0 : BaseConsumer +public class RailConsumer0 : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -17,7 +17,7 @@ public RailConsumer0(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(RailConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(RailConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(RailConsumer0)); @@ -26,7 +26,7 @@ public override Task Consume(RailConsumerMessage message, CancellationToken canc } [ConsumerRailIdAttribute(1)] -public class RailConsumer1 : BaseConsumer +public class RailConsumer1 : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -35,7 +35,7 @@ public RailConsumer1(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(RailConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(RailConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(RailConsumer1)); @@ -44,7 +44,7 @@ public override Task Consume(RailConsumerMessage message, CancellationToken canc } [ConsumerRailId(2)] -public class RailConsumer2 : BaseConsumer +public class RailConsumer2 : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -53,7 +53,7 @@ public RailConsumer2(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(RailConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(RailConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(RailConsumer2)); diff --git a/AsyncMonolith.Tests/Infra/SingleConsumer.cs b/AsyncMonolith.Tests/Infra/SingleConsumer.cs index 4eb5794..7825f4b 100644 --- a/AsyncMonolith.Tests/Infra/SingleConsumer.cs +++ b/AsyncMonolith.Tests/Infra/SingleConsumer.cs @@ -4,7 +4,7 @@ namespace AsyncMonolith.Tests.Infra; [ConsumerTimeout(1)] [ConsumerAttempts(2)] -public class SingleConsumer : BaseConsumer +public class SingleConsumer : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -13,7 +13,7 @@ public SingleConsumer(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override Task Consume(SingleConsumerMessage message, CancellationToken cancellationToken) + public Task Consume(SingleConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(SingleConsumer)); return Task.CompletedTask; diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs index 7274b80..26cb751 100644 --- a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -81,6 +81,7 @@ public static async Task Create(Action? c services.AddSingleton>(); services.AddSingleton>(); services.AddSingleton(); + services.AddSingleton(); var provider = services.BuildServiceProvider(); using (var scope = provider.CreateScope()) diff --git a/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs b/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs index fa0045f..56c9f94 100644 --- a/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs +++ b/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs @@ -3,7 +3,7 @@ namespace AsyncMonolith.Tests.Infra; [ConsumerTimeout(1)] -public class TimeoutConsumer : BaseConsumer +public class TimeoutConsumer : IConsumer { private readonly TestConsumerInvocations _consumerInvocations; @@ -12,7 +12,7 @@ public TimeoutConsumer(TestConsumerInvocations consumerInvocations) _consumerInvocations = consumerInvocations; } - public override async Task Consume(TimeoutConsumerMessage message, CancellationToken cancellationToken) + public async Task Consume(TimeoutConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { _consumerInvocations.Increment(nameof(TimeoutConsumer)); await Task.Delay(TimeSpan.FromSeconds(message.Delay), cancellationToken); diff --git a/AsyncMonolith.Tests/Infra/WritingConsumer.cs b/AsyncMonolith.Tests/Infra/WritingConsumer.cs index 64b4340..1b38bf0 100644 --- a/AsyncMonolith.Tests/Infra/WritingConsumer.cs +++ b/AsyncMonolith.Tests/Infra/WritingConsumer.cs @@ -15,7 +15,7 @@ public class WritingConsumerMessage : IConsumerPayload /// [ConsumerTimeout(10)] [ConsumerAttempts(1)] -public class WritingConsumer : BaseConsumer +public class WritingConsumer : IConsumer { private readonly TestDbContext _dbContext; private readonly IProducerService _producer; @@ -26,7 +26,7 @@ public WritingConsumer(TestDbContext dbContext, IProducerService producer) _producer = producer; } - public override async Task Consume(WritingConsumerMessage message, CancellationToken cancellationToken) + public async Task Consume(WritingConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) { await _producer.Produce(new SingleConsumerMessage { Name = message.Name }, cancellationToken: cancellationToken); diff --git a/AsyncMonolith.Tests/MultipleInstanceTests.cs b/AsyncMonolith.Tests/MultipleInstanceTests.cs index 8beb1c5..f89c26c 100644 --- a/AsyncMonolith.Tests/MultipleInstanceTests.cs +++ b/AsyncMonolith.Tests/MultipleInstanceTests.cs @@ -90,6 +90,7 @@ public async Task Two_running_instances_sharing_a_database_consume_each_message_ builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={path}")); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddEfAsyncMonolith(s => { s.RegisterTypesFromAssemblyContaining(); diff --git a/AsyncMonolith/Consumers/BaseConsumer.cs b/AsyncMonolith/Consumers/BaseConsumer.cs deleted file mode 100644 index 46409a5..0000000 --- a/AsyncMonolith/Consumers/BaseConsumer.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Text.Json; - -namespace AsyncMonolith.Consumers; - -/// -/// Base class for consumers. -/// -/// The type of the consumer payload. -public abstract class BaseConsumer : IConsumer where T : IConsumerPayload -{ - /// - /// Internal method called by the processor to deserialize and process consumer payloads. - /// - /// The consumer message. - /// The cancellation token. - /// A task representing the asynchronous operation. - public async Task Consume(ConsumerMessage message, CancellationToken cancellationToken = default) - { - var payload = JsonSerializer.Deserialize(message.Payload) ?? throw new InvalidOperationException( - $"Consumer: '{message.ConsumerType}' failed to deserialize payload: '{message.PayloadType}'"); - - await Consume(payload!, cancellationToken); - } - - /// - /// Consumes the payload. - /// - /// The consumer payload. - /// The cancellation token. - /// A task representing the asynchronous operation. - public abstract Task Consume(T payload, CancellationToken cancellationToken = default); -} \ No newline at end of file diff --git a/AsyncMonolith/Consumers/ConsumeContext.cs b/AsyncMonolith/Consumers/ConsumeContext.cs new file mode 100644 index 0000000..583cb7f --- /dev/null +++ b/AsyncMonolith/Consumers/ConsumeContext.cs @@ -0,0 +1,49 @@ +namespace AsyncMonolith.Consumers; + +/// +/// Details of the message being consumed and of this attempt. +/// +public sealed record ConsumeContext +{ + /// The message id. Each consumer of a payload gets its own message, with its own id. + public required string MessageId { get; init; } + + /// + /// The deduplication key the message was produced with, or the generated key when none was given. All + /// consumers of one produced payload share it. + /// + public required string DeduplicationKey { get; init; } + + /// This attempt's number, starting at 1. + public required int Attempt { get; init; } + + /// The number of attempts allowed before the message is poisoned. + public required int MaxAttempts { get; init; } + + /// True when the message will be poisoned if this attempt fails. + public bool IsLastAttempt => Attempt >= MaxAttempts; + + /// When the message was produced. + public required DateTimeOffset CreatedAt { get; init; } + + /// The stored name of the consumer, see . + public required string ConsumerName { get; init; } + + /// The stored name of the payload, see . + public required string PayloadName { get; init; } + + /// The trace id of the activity that produced the message, if any. + public string? TraceId { get; init; } + + internal static ConsumeContext For(ConsumerMessage message, int maxAttempts) => new() + { + MessageId = message.Id, + DeduplicationKey = message.InsertId, + Attempt = Math.Max(message.Attempts, 1), + MaxAttempts = maxAttempts, + CreatedAt = DateTimeOffset.FromUnixTimeSeconds(message.CreatedAt), + ConsumerName = message.ConsumerType, + PayloadName = message.PayloadType, + TraceId = message.TraceId + }; +} diff --git a/AsyncMonolith/Consumers/ConsumerInvoker.cs b/AsyncMonolith/Consumers/ConsumerInvoker.cs new file mode 100644 index 0000000..3e83a1b --- /dev/null +++ b/AsyncMonolith/Consumers/ConsumerInvoker.cs @@ -0,0 +1,63 @@ +using System.Collections.Concurrent; +using System.Reflection; +using System.Text.Json; + +namespace AsyncMonolith.Consumers; + +/// +/// Finds the payload type of a consumer and calls it with a deserialized payload. +/// +internal static class ConsumerInvoker +{ + private sealed record Invoker( + Type PayloadType, + Func Invoke); + + private static readonly ConcurrentDictionary Invokers = new(); + + private static readonly MethodInfo InvokeTypedMethod = + typeof(ConsumerInvoker).GetMethod(nameof(InvokeTyped), BindingFlags.NonPublic | BindingFlags.Static)!; + + /// Gets the payload type a consumer handles. + /// The type implements IConsumer<T> more than once. + public static Type? PayloadTypeOf(Type consumerType) + { + var payloadTypes = consumerType.GetInterfaces() + .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IConsumer<>)) + .Select(i => i.GetGenericArguments()[0]) + .ToList(); + + return payloadTypes.Count switch + { + 0 => null, + 1 => payloadTypes[0], + _ => throw new InvalidOperationException( + $"Consumer: '{consumerType.FullName}' implements IConsumer for more than one payload. " + + "Use one consumer class per payload.") + }; + } + + /// Deserializes the message payload and passes it to the consumer. + public static Task Invoke(object consumer, ConsumerMessage message, ConsumeContext context, + JsonSerializerOptions? serializerOptions, CancellationToken cancellationToken) + { + var invoker = Invokers.GetOrAdd(consumer.GetType(), Create); + var payload = JsonSerializer.Deserialize(message.Payload, invoker.PayloadType, serializerOptions) ?? + throw new InvalidOperationException( + $"Consumer: '{message.ConsumerType}' failed to deserialize payload: '{message.PayloadType}'"); + return invoker.Invoke(consumer, payload, context, cancellationToken); + } + + private static Invoker Create(Type consumerType) + { + var payloadType = PayloadTypeOf(consumerType) ?? throw new InvalidOperationException( + $"Type: '{consumerType.FullName}' does not implement IConsumer."); + var invoke = InvokeTypedMethod.MakeGenericMethod(payloadType) + .CreateDelegate>(); + return new Invoker(payloadType, invoke); + } + + private static Task InvokeTyped(object consumer, object payload, ConsumeContext context, + CancellationToken cancellationToken) where TPayload : IConsumerPayload => + ((IConsumer)consumer).Consume((TPayload)payload, context, cancellationToken); +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 5ee3172..88857ae 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -296,15 +296,9 @@ await leased.ExecuteUpdateAsync(s => s using var scope = _scopeFactory.CreateScope(); - // Resolve the consumer - if (scope.ServiceProvider.GetRequiredService(consumerType) - is not IConsumer consumer) - { - throw new InvalidOperationException($"Couldn't resolve consumer service of type: '{message.ConsumerType}'"); - } - - // Execute the consumer - await consumer.Consume(message, timeoutCancellationToken.Token); + var consumer = scope.ServiceProvider.GetRequiredService(consumerType); + var context = ConsumeContext.For(message, _consumerRegistry.ResolveConsumerMaxAttempts(message)); + await ConsumerInvoker.Invoke(consumer, message, context, null, timeoutCancellationToken.Token); activity?.SetStatus(ActivityStatusCode.Ok); _logger.ConsumerMessageProcessed(message.ConsumerType); diff --git a/AsyncMonolith/Consumers/IConsumer.cs b/AsyncMonolith/Consumers/IConsumer.cs index 317bb12..27eca27 100644 --- a/AsyncMonolith/Consumers/IConsumer.cs +++ b/AsyncMonolith/Consumers/IConsumer.cs @@ -1,15 +1,27 @@ -namespace AsyncMonolith.Consumers; +namespace AsyncMonolith.Consumers; /// -/// Interface for Consumers +/// Marks a type as a consumer. Implement rather than this interface. /// -public interface IConsumer +public interface IConsumer; + +/// +/// Consumes messages with a payload. Implementations are found by +/// assembly scanning, registered as scoped services, and run once for each message. +/// +/// +/// A message may be delivered more than once (for example if the app stops mid-message), so make consumers +/// idempotent. and help. +/// +/// The payload type this consumer handles. +public interface IConsumer : IConsumer where TPayload : IConsumerPayload { /// - /// Consumes the given message. + /// Consumes one message. Throwing, or not finishing within the consumer's timeout, counts as a failed + /// attempt; the message is retried until its attempts run out, then poisoned. /// - /// The consumer message to be consumed. - /// The cancellation token. - /// A task representing the asynchronous operation. - public Task Consume(ConsumerMessage message, CancellationToken cancellationToken); + /// The message payload. + /// Details of the message and this attempt. + /// Cancelled when the consumer times out or the app is stopping. + Task Consume(TPayload payload, ConsumeContext context, CancellationToken cancellationToken); } diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 4cd9f8a..db5f035 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -183,8 +183,8 @@ public static IServiceCollection AddAsyncMonolithConsumersFromAssemblyContaining this IServiceCollection services) => services.AddAsyncMonolithConsumers(typeof(TMarker).Assembly); private static IEnumerable FindConsumerTypes(IEnumerable types) => - types.Where(t => t is { IsAbstract: false, BaseType.IsGenericType: true } && - t.BaseType.GetGenericTypeDefinition() == typeof(BaseConsumer<>)); + types.Where(t => t is { IsClass: true, IsAbstract: false, IsGenericTypeDefinition: false } && + ConsumerInvoker.PayloadTypeOf(t) is not null); internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable assemblies, AsyncMonolithSettings settings) @@ -202,11 +202,6 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass foreach (var consumerType in FindConsumerTypes(typesToScan)) { - if (consumerType.BaseType == null || string.IsNullOrEmpty(consumerType.Name)) - { - continue; - } - var consumerName = AsyncMonolithNames.ForConsumer(consumerType); var timeoutDuration = settings.DefaultConsumerTimeout; @@ -256,7 +251,7 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass consumerRailIdDictionary[consumerName] = consumerRailId; // Get the generic argument (T) of the consumer type - var payloadType = consumerType.BaseType.GetGenericArguments()[0]; + var payloadType = ConsumerInvoker.PayloadTypeOf(consumerType)!; if (!consumerServiceDictionary.TryAdd(consumerName, consumerType)) { diff --git a/Example/Example.Api/Counter/TotalValueConsumer.cs b/Example/Example.Api/Counter/TotalValueConsumer.cs index 8e388db..1a122c9 100644 --- a/Example/Example.Api/Counter/TotalValueConsumer.cs +++ b/Example/Example.Api/Counter/TotalValueConsumer.cs @@ -4,7 +4,7 @@ namespace Example.Api.Counter; [ConsumerExecutionMode(ConsumerInstanceExecutionMode.Parallel)] -public class TotalValueConsumer : BaseConsumer +public class TotalValueConsumer : IConsumer { private readonly ApplicationDbContext _dbContext; private readonly TotalValueService _totalValueService; @@ -15,7 +15,7 @@ public TotalValueConsumer(TotalValueService totalValueService, ApplicationDbCont _dbContext = dbContext; } - public override async Task Consume(ValuePersisted message, CancellationToken cancellationToken) + public async Task Consume(ValuePersisted message, ConsumeContext context, CancellationToken cancellationToken) { var totalValue = await _dbContext.SubmittedValues.SumAsync(v => v.Value, cancellationToken); _totalValueService.Set(totalValue); diff --git a/Example/Example.Api/Counter/ValueSubmittedConsumer.cs b/Example/Example.Api/Counter/ValueSubmittedConsumer.cs index 4b0de35..174b074 100644 --- a/Example/Example.Api/Counter/ValueSubmittedConsumer.cs +++ b/Example/Example.Api/Counter/ValueSubmittedConsumer.cs @@ -4,7 +4,7 @@ namespace Example.Api.Counter; -public class ValueSubmittedConsumer : BaseConsumer +public class ValueSubmittedConsumer : IConsumer { private readonly ApplicationDbContext _dbContext; private readonly IProducerService _producerService; @@ -15,7 +15,7 @@ public ValueSubmittedConsumer(ApplicationDbContext dbContext, IProducerService p _producerService = producerService; } - public override async Task Consume(ValueSubmitted message, CancellationToken cancellationToken = default) + public async Task Consume(ValueSubmitted message, ConsumeContext context, CancellationToken cancellationToken) { var newValue = new SubmittedValue { diff --git a/Example/Example.Api/Spam/SpamMessageConsumer.cs b/Example/Example.Api/Spam/SpamMessageConsumer.cs index 39dfffe..e1fc25c 100644 --- a/Example/Example.Api/Spam/SpamMessageConsumer.cs +++ b/Example/Example.Api/Spam/SpamMessageConsumer.cs @@ -2,7 +2,7 @@ namespace Example.Api.Spam; -public class SpamMessageConsumer : BaseConsumer +public class SpamMessageConsumer : IConsumer { private readonly TimeProvider _timeProvider; @@ -11,7 +11,7 @@ public SpamMessageConsumer(TimeProvider timeProvider) _timeProvider = timeProvider; } - public override Task Consume(SpamMessage message, CancellationToken cancellationToken) + public Task Consume(SpamMessage message, ConsumeContext context, CancellationToken cancellationToken) { if (message.Last) { diff --git a/README.md b/README.md index cce8d45..863b8b5 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Consuming messages ```csharp [ConsumerTimeout(5)] // Consumer timeouts after 5 seconds [ConsumerAttempts(1)] // Consumer messages moved to poisoned table after 1 failed attempt -public class DeleteUsersPosts : BaseConsumer +public class DeleteUsersPosts : IConsumer { private readonly ApplicationDbContext _dbContext; @@ -78,7 +78,7 @@ public class DeleteUsersPosts : BaseConsumer _dbContext = dbContext; } - public override Task Consume(UserDeleted message, CancellationToken cancellationToken) + public Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); diff --git a/docs/guides/changing-messages.md b/docs/guides/changing-messages.md index 28147e5..b3446bf 100644 --- a/docs/guides/changing-messages.md +++ b/docs/guides/changing-messages.md @@ -14,7 +14,7 @@ Give a type a stable name to decouple it from the class name: public class SendEmail : IConsumerPayload { ... } [ConsumerName("minicms.email.sender")] -public class SendEmailConsumer : BaseConsumer { ... } +public class SendEmailConsumer : IConsumer { ... } ``` To rename a class that already has stored messages, add the attribute with the old class name first. diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index d688d43..6f8b351 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -7,12 +7,14 @@ - **Idempotency**: Ensure your Consumers are idempotent, since they will be retried on failure. - **Timeout**: Consumers timeout after the number of seconds defined by the `ConsumerTimeout` attribute or the `DefaultConsumerTimeout` if not set. +Consumers implement `IConsumer`. The `ConsumeContext` describes the message and this attempt: `MessageId`, `DeduplicationKey`, `Attempt` (starting at 1), `MaxAttempts`, `IsLastAttempt`, `CreatedAt`, `ConsumerName`, `PayloadName` and `TraceId`. Use them for idempotency checks and logging. + Example ```csharp [ConsumerTimeout(5)] // Consumer timeouts after 5 seconds [ConsumerAttempts(1)] // Consumer messages moved to poisoned table after 1 failed attempt -public class DeleteUsersPosts : BaseConsumer +public class DeleteUsersPosts : IConsumer { private readonly ApplicationDbContext _dbContext; @@ -21,7 +23,7 @@ public class DeleteUsersPosts : BaseConsumer _dbContext = dbContext; } - public override Task Consume(UserDeleted message, CancellationToken cancellationToken) + public Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); diff --git a/docs/posts/idempotency.md b/docs/posts/idempotency.md index 50008d9..df9ed7d 100644 --- a/docs/posts/idempotency.md +++ b/docs/posts/idempotency.md @@ -38,9 +38,9 @@ await _dbContext.SaveChangesAsync(); ``` ```csharp -public class SendOrderCancelledEmail : BaseConsumer +public class SendOrderCancelledEmail : IConsumer { - public override Task Consume(OrderCancelled message, CancellationToken cancellationToken) + public Task Consume(OrderCancelled message, ConsumeContext context, CancellationToken cancellationToken) { ... // Send order cancelled email diff --git a/docs/posts/mediator.md b/docs/posts/mediator.md index 2680ac9..5af06e3 100644 --- a/docs/posts/mediator.md +++ b/docs/posts/mediator.md @@ -82,9 +82,9 @@ await _dbContext.SaveChangesAsync(); ``` ```csharp -public class CancelShipment : BaseConsumer +public class CancelShipment : IConsumer { - public override Task Consume(OrderCancelled message, CancellationToken cancellationToken) + public Task Consume(OrderCancelled message, ConsumeContext context, CancellationToken cancellationToken) { ... shipment.Cancel(); @@ -93,9 +93,9 @@ public class CancelShipment : BaseConsumer } } -public class SendOrderCancelledEmail : BaseConsumer +public class SendOrderCancelledEmail : IConsumer { - public override Task Consume(OrderCancelled message, CancellationToken cancellationToken) + public Task Consume(OrderCancelled message, ConsumeContext context, CancellationToken cancellationToken) { ... // Send order cancelled email diff --git a/docs/posts/transactional-outbox.md b/docs/posts/transactional-outbox.md index 60ff0a0..f051ad5 100644 --- a/docs/posts/transactional-outbox.md +++ b/docs/posts/transactional-outbox.md @@ -60,9 +60,9 @@ await _dbContext.SaveChangesAsync(); ``` ```csharp -public class CreateShipment : BaseConsumer +public class CreateShipment : IConsumer { - public override Task Consume(OrderCreated message, CancellationToken cancellationToken) + public Task Consume(OrderCreated message, ConsumeContext context, CancellationToken cancellationToken) { ... // Create Order diff --git a/docs/quickstart.md b/docs/quickstart.md index 0764f87..e41d3ee 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -103,7 +103,7 @@ Create messages and consumers // Define Consumer [ConsumerTimeout(5)] // Consumer timeouts after 5 seconds [ConsumerAttempts(1)] // Consumer messages moved to poisoned table after 1 failed attempt - public class ValueSubmittedConsumer : BaseConsumer + public class ValueSubmittedConsumer : IConsumer { private readonly ApplicationDbContext _dbContext; private readonly IProducerService _producerService; @@ -114,7 +114,7 @@ Create messages and consumers _producerService = producerService; } - public override Task Consume(ValueSubmitted message, CancellationToken cancellationToken) + public Task Consume(ValueSubmitted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); From e1ef8576845325f768f104cacfb48d83622b14da Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:55:39 +0000 Subject: [PATCH 33/53] Move settings to AsyncMonolithOptions with TimeSpans and validation - AsyncMonolithSettings becomes AsyncMonolithOptions, configured through the standard options pattern. Its values are copied by the framework instead of field by field, so new options can't be forgotten. - Times are TimeSpans, ending the mix of seconds and milliseconds: AttemptDelay, MaxAttemptDelay, DefaultConsumerTimeout, IdlePollInterval (was ProcessorMaxDelay, ms) and BusyPollInterval (was ProcessorMinDelay, ms). ProcessorBatchSize is BatchSize. The duplicate Default instance is removed. - Validation runs when the host starts (ValidateOnStart) and reports every invalid option, prefixed "AsyncMonolith:". - Add*AsyncMonolith returns an AsyncMonolithBuilder with BindConfiguration(section) and AddConsumers(...). The obsolete overloads taking an Assembly are removed, and the providers' entry points are documented. - [ConsumerTimeout] exposes Seconds instead of Duration. Tests cover each invalid option, boundaries, defaults, a host that refuses to start with invalid options, and binding from configuration over values set in code. --- AsyncMonolith.Ef/EfConsumerMessageFetcher.cs | 8 +- AsyncMonolith.Ef/EfScheduledMessageFetcher.cs | 6 +- AsyncMonolith.Ef/StartupExtensions.cs | 53 ++--- .../MariaDbConsumerMessageFetcher.cs | 6 +- .../MariaDbScheduledMessageFetcher.cs | 6 +- AsyncMonolith.MariaDb/StartupExtensions.cs | 51 ++--- .../MsSqlConsumerMessageFetcher.cs | 6 +- .../MsSqlScheduledMessageFetcher.cs | 6 +- AsyncMonolith.MsSql/StartupExtensions.cs | 48 ++--- .../MySqlConsumerMessageFetcher.cs | 6 +- .../MySqlScheduledMessageFetcher.cs | 6 +- AsyncMonolith.MySql/StartupExtensions.cs | 48 ++--- .../PostgreSqlConsumerMessageFetcher.cs | 6 +- .../PostgreSqlScheduledMessageFetcher.cs | 6 +- AsyncMonolith.PostgreSql/StartupExtensions.cs | 48 ++--- AsyncMonolith.TestHelpers/SetupTestHelpers.cs | 91 +++------ AsyncMonolith.Tests/ConfigurationTests.cs | 116 +++++++---- AsyncMonolith.Tests/ConsumeContextTests.cs | 4 +- .../ConsumerMessageFetcherTests.cs | 8 +- .../ConsumerProcessingTests.cs | 12 +- AsyncMonolith.Tests/ConsumerRegistryTests.cs | 2 +- AsyncMonolith.Tests/HostedProcessingTests.cs | 8 +- AsyncMonolith.Tests/Infra/DbTestsBase.cs | 4 +- AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 4 +- .../Infra/TestServiceHelpers.cs | 13 +- AsyncMonolith.Tests/MultipleInstanceTests.cs | 6 +- AsyncMonolith.Tests/NamingTests.cs | 2 +- AsyncMonolith.Tests/ProducerServiceTests.cs | 2 +- .../RetryAndPoisonedMessageTests.cs | 26 +-- .../ScheduledMessageFetcherTests.cs | 6 +- AsyncMonolith.Tests/SchedulingTests.cs | 2 +- AsyncMonolith/AsyncMonolith.csproj | 1 + .../Consumers/ConsumerMessageProcessor.cs | 14 +- AsyncMonolith/Consumers/ConsumerRegistry.cs | 8 +- .../Consumers/ConsumerTimeoutAttribute.cs | 8 +- .../Scheduling/ScheduledMessageProcessor.cs | 12 +- .../Utilities/AsyncMonolithOptions.cs | 183 ++++++++++++++++++ .../Utilities/AsyncMonolithSettings.cs | 120 ------------ AsyncMonolith/Utilities/StartupExtensions.cs | 89 ++------- Directory.Packages.props | 1 + Example/Example.Api/Program.cs | 8 +- docs/guides/consuming-messages.md | 6 +- docs/internals.md | 4 +- docs/quickstart.md | 27 +-- docs/releases.md | 6 +- 45 files changed, 513 insertions(+), 590 deletions(-) create mode 100644 AsyncMonolith/Utilities/AsyncMonolithOptions.cs delete mode 100644 AsyncMonolith/Utilities/AsyncMonolithSettings.cs diff --git a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs index 12d462b..966a0e7 100644 --- a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs @@ -10,13 +10,13 @@ namespace AsyncMonolith.Ef; /// public sealed class EfConsumerMessageFetcher : IConsumerMessageFetcher { - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// - /// The options for AsyncMonolithSettings. - public EfConsumerMessageFetcher(IOptions options) + /// The options for AsyncMonolithOptions. + public EfConsumerMessageFetcher(IOptions options) { _options = options; } @@ -35,7 +35,7 @@ public Task> Fetch(DbSet consumerSet, lon return consumerSet .Where(m => m.AvailableAfter <= currentTime && m.RailId == railId) .OrderBy(m => m.CreatedAt).ThenBy(m => m.Id) - .Take(_options.Value.ProcessorBatchSize) + .Take(_options.Value.BatchSize) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs index 2a1d0cb..d4c8f89 100644 --- a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs @@ -10,13 +10,13 @@ namespace AsyncMonolith.Ef; /// public sealed class EfScheduledMessageFetcher : IScheduledMessageFetcher { - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for AsyncMonolith. - public EfScheduledMessageFetcher(IOptions options) + public EfScheduledMessageFetcher(IOptions options) { _options = options; } @@ -33,7 +33,7 @@ public Task> Fetch(DbSet scheduledMessa { return scheduledMessageSet.Where(m => m.AvailableAfter <= currentTime) .OrderBy(m => m.AvailableAfter).ThenBy(m => m.Id) - .Take(_options.Value.ProcessorBatchSize) + .Take(_options.Value.BatchSize) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.Ef/StartupExtensions.cs b/AsyncMonolith.Ef/StartupExtensions.cs index aed7d09..5ed178b 100644 --- a/AsyncMonolith.Ef/StartupExtensions.cs +++ b/AsyncMonolith.Ef/StartupExtensions.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -12,50 +11,26 @@ namespace AsyncMonolith.Ef; /// /// Extension methods for configuring EF AsyncMonolith in the IServiceCollection. /// +/// +/// Registers AsyncMonolith for any database supported by Entity Framework Core (fetches without row locks). +/// public static class StartupExtensions { /// - /// Adds EF AsyncMonolith to the IServiceCollection. + /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the + /// background processors. Call it once, in the host. /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The action used to configure the settings. - /// A reference to this instance after the operation has completed. - /// Thrown when the ConsumerMessageProcessorCount or ScheduledMessageProcessorCount is greater than 1. - public static IServiceCollection AddEfAsyncMonolith( + /// The DbContext containing the AsyncMonolith tables. + /// The service collection. + /// Sets options and the assemblies to scan for consumers. + /// A builder to bind configuration or add more consumer assemblies. + public static AsyncMonolithBuilder AddEfAsyncMonolith( this IServiceCollection services, - Action settings) where T : DbContext => - AddEfAsyncMonolith(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds EF AsyncMonolith to the IServiceCollection. - /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The assembly containing the DbContext. - /// The optional AsyncMonolithSettings. - /// A reference to this instance after the operation has completed. - /// Thrown when the ConsumerMessageProcessorCount or ScheduledMessageProcessorCount is greater than 1. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddEfAsyncMonolith( - this IServiceCollection services, - Assembly assembly, - AsyncMonolithSettings? settings = null) where T : DbContext => - AddEfAsyncMonolith( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - private static IServiceCollection AddEfAsyncMonolith( - this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext + Action? configure = null) where T : DbContext { - configuration(settings); - - services.InternalAddAsyncMonolith(settings); + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); services.TryAddSingleton(); services.TryAddSingleton(); - return services; + return builder; } } diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs index 12d7096..e1d8bfc 100644 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs @@ -19,13 +19,13 @@ FROM consumer_messages LIMIT @batchSize FOR UPDATE SKIP LOCKED"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for AsyncMonolith settings. - public MariaDbConsumerMessageFetcher(IOptions options) + public MariaDbConsumerMessageFetcher(IOptions options) { _options = options; } @@ -44,7 +44,7 @@ public Task> Fetch(DbSet consumerSet, lon return consumerSet .FromSqlRaw(MariaDb, new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@railId", railId), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs index 769191c..1ce0840 100644 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs @@ -18,13 +18,13 @@ FROM scheduled_messages LIMIT @batchSize FOR UPDATE SKIP LOCKED"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for AsyncMonolith. - public MariaDbScheduledMessageFetcher(IOptions options) + public MariaDbScheduledMessageFetcher(IOptions options) { _options = options; } @@ -41,7 +41,7 @@ public Task> Fetch(DbSet scheduledMessa { return scheduledMessageSet .FromSqlRaw(MariaDb, new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MariaDb/StartupExtensions.cs b/AsyncMonolith.MariaDb/StartupExtensions.cs index 4154cb9..e1943f4 100644 --- a/AsyncMonolith.MariaDb/StartupExtensions.cs +++ b/AsyncMonolith.MariaDb/StartupExtensions.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -11,48 +10,26 @@ namespace AsyncMonolith.MariaDb; /// /// AsyncMonolith MariaDb startup extensions /// +/// +/// Registers AsyncMonolith for MariaDB. +/// public static class StartupExtensions { /// - /// Adds MariaDb implementation of AsyncMonolith to the IServiceCollection. + /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the + /// background processors. Call it once, in the host. /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The action used to configure the settings. - /// A reference to this instance after the operation has completed. - public static IServiceCollection AddMariaDbAsyncMonolith( + /// The DbContext containing the AsyncMonolith tables. + /// The service collection. + /// Sets options and the assemblies to scan for consumers. + /// A builder to bind configuration or add more consumer assemblies. + public static AsyncMonolithBuilder AddMariaDbAsyncMonolith( this IServiceCollection services, - Action settings) where T : DbContext => - AddMariaDbAsyncMonolith(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds MariaDb implementation of AsyncMonolith to the IServiceCollection. - /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The assembly containing the DbContext. - /// Optional AsyncMonolith settings. - /// A reference to this instance after the operation has completed. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddMariaDbAsyncMonolith( - this IServiceCollection services, - Assembly assembly, - AsyncMonolithSettings? settings = null) where T : DbContext => - AddMariaDbAsyncMonolith( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - private static IServiceCollection AddMariaDbAsyncMonolith( - this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext + Action? configure = null) where T : DbContext { - configuration(settings); - - services.InternalAddAsyncMonolith(settings); + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); services.TryAddSingleton(); services.TryAddSingleton(); - return services; + return builder; } } diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs index 333c3d0..55fba81 100644 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs @@ -17,13 +17,13 @@ FROM consumer_messages WITH (ROWLOCK, READPAST) WHERE available_after <= @currentTime AND rail_id = @railId ORDER BY created_at, id"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for the AsyncMonolith settings. - public MsSqlConsumerMessageFetcher(IOptions options) + public MsSqlConsumerMessageFetcher(IOptions options) { _options = options; } @@ -42,7 +42,7 @@ public Task> Fetch(DbSet consumerSet, lon return consumerSet .FromSqlRaw(MsSql, new SqlParameter("@currentTime", currentTime), new SqlParameter("@railId", railId), - new SqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new SqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs index 24be158..ee3edd0 100644 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs @@ -16,13 +16,13 @@ SELECT TOP (@batchSize) * FROM scheduled_messages WITH (ROWLOCK, READPAST) WHERE available_after <= @currentTime"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for the AsyncMonolith settings. - public MsSqlScheduledMessageFetcher(IOptions options) + public MsSqlScheduledMessageFetcher(IOptions options) { _options = options; } @@ -39,7 +39,7 @@ public Task> Fetch(DbSet scheduledMessa { return scheduledMessageSet .FromSqlRaw(MsSql, new SqlParameter("@currentTime", currentTime), - new SqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new SqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MsSql/StartupExtensions.cs b/AsyncMonolith.MsSql/StartupExtensions.cs index e60cb57..0dd8e99 100644 --- a/AsyncMonolith.MsSql/StartupExtensions.cs +++ b/AsyncMonolith.MsSql/StartupExtensions.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -12,45 +11,26 @@ namespace AsyncMonolith.MsSql; /// /// AsyncMonolith MsSql startup extensions /// +/// +/// Registers AsyncMonolith for SQL Server. +/// public static class StartupExtensions { /// - /// Adds the MsSqlAsyncMonolith services to the IServiceCollection. - /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The action used to configure the settings. - /// A reference to this instance after the operation has completed. - public static IServiceCollection AddMsSqlAsyncMonolith( - this IServiceCollection services, - Action settings) where T : DbContext => - AddMsSqlAsyncMonolith(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds the MsSqlAsyncMonolith services to the IServiceCollection. + /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the + /// background processors. Call it once, in the host. /// - /// The type of the DbContext. - /// The IServiceCollection to add the services to. - /// The assembly containing the DbContext and message handlers. - /// The optional AsyncMonolithSettings. - /// A reference to this instance after the operation has completed. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddMsSqlAsyncMonolith(this IServiceCollection services, Assembly assembly, - AsyncMonolithSettings? settings = null) where T : DbContext => - AddMsSqlAsyncMonolith( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - private static IServiceCollection AddMsSqlAsyncMonolith( + /// The DbContext containing the AsyncMonolith tables. + /// The service collection. + /// Sets options and the assemblies to scan for consumers. + /// A builder to bind configuration or add more consumer assemblies. + public static AsyncMonolithBuilder AddMsSqlAsyncMonolith( this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext + Action? configure = null) where T : DbContext { - configuration(settings); - services.InternalAddAsyncMonolith(settings); + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); services.TryAddSingleton(); services.TryAddSingleton(); - return services; + return builder; } } diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs index 25f0a44..875f5a7 100644 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs @@ -19,13 +19,13 @@ FROM consumer_messages LIMIT @batchSize FOR UPDATE SKIP LOCKED"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for AsyncMonolith settings. - public MySqlConsumerMessageFetcher(IOptions options) + public MySqlConsumerMessageFetcher(IOptions options) { _options = options; } @@ -44,7 +44,7 @@ public Task> Fetch(DbSet consumerSet, lon return consumerSet .FromSqlRaw(MySql, new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@railId", railId), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs index 8e88283..6b7095a 100644 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs @@ -18,13 +18,13 @@ FROM scheduled_messages LIMIT @batchSize FOR UPDATE SKIP LOCKED"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for AsyncMonolith. - public MySqlScheduledMessageFetcher(IOptions options) + public MySqlScheduledMessageFetcher(IOptions options) { _options = options; } @@ -41,7 +41,7 @@ public Task> Fetch(DbSet scheduledMessa { return scheduledMessageSet .FromSqlRaw(MySql, new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MySql/StartupExtensions.cs b/AsyncMonolith.MySql/StartupExtensions.cs index a906517..66b356e 100644 --- a/AsyncMonolith.MySql/StartupExtensions.cs +++ b/AsyncMonolith.MySql/StartupExtensions.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -11,45 +10,26 @@ namespace AsyncMonolith.MySql; /// /// AsyncMonolith MySql startup extensions /// +/// +/// Registers AsyncMonolith for MySQL. +/// public static class StartupExtensions { /// - /// Adds MySql implementation of AsyncMonolith to the IServiceCollection. + /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the + /// background processors. Call it once, in the host. /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The action used to configure the settings. - /// A reference to this instance after the operation has completed. - public static IServiceCollection AddMySqlAsyncMonolith( - this IServiceCollection services, - Action settings) where T : DbContext => - AddMySqlAsyncMonolith(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds MySql implementation of AsyncMonolith to the IServiceCollection. - /// - /// The DbContext type. - /// The IServiceCollection to add the services to. - /// The assembly containing the DbContext. - /// Optional AsyncMonolith settings. - /// A reference to this instance after the operation has completed. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddMySqlAsyncMonolith(this IServiceCollection services, Assembly assembly, - AsyncMonolithSettings? settings = null) where T : DbContext => - AddMySqlAsyncMonolith( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - private static IServiceCollection AddMySqlAsyncMonolith( + /// The DbContext containing the AsyncMonolith tables. + /// The service collection. + /// Sets options and the assemblies to scan for consumers. + /// A builder to bind configuration or add more consumer assemblies. + public static AsyncMonolithBuilder AddMySqlAsyncMonolith( this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext + Action? configure = null) where T : DbContext { - configuration(settings); - services.InternalAddAsyncMonolith(settings); + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); services.TryAddSingleton(); services.TryAddSingleton(); - return services; + return builder; } } diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs index d034b30..b6aa06d 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs @@ -19,13 +19,13 @@ FROM consumer_messages FOR UPDATE SKIP LOCKED LIMIT @batchSize"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for the AsyncMonolith settings. - public PostgreSqlConsumerMessageFetcher(IOptions options) + public PostgreSqlConsumerMessageFetcher(IOptions options) { _options = options; } @@ -44,7 +44,7 @@ public Task> Fetch(DbSet consumerSet, lon return consumerSet .FromSqlRaw(PgSql, new NpgsqlParameter("@currentTime", currentTime), new NpgsqlParameter("@railId", railId), - new NpgsqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new NpgsqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs index 945a248..ee0d21c 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs @@ -18,13 +18,13 @@ FROM scheduled_messages FOR UPDATE SKIP LOCKED LIMIT @batchSize"; - private readonly IOptions _options; + private readonly IOptions _options; /// /// Initializes a new instance of the class. /// /// The options for the AsyncMonolith. - public PostgreSqlScheduledMessageFetcher(IOptions options) + public PostgreSqlScheduledMessageFetcher(IOptions options) { _options = options; } @@ -41,7 +41,7 @@ public Task> Fetch(DbSet scheduledMessa { return scheduledMessageSet .FromSqlRaw(PgSql, new NpgsqlParameter("@currentTime", currentTime), - new NpgsqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) + new NpgsqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.PostgreSql/StartupExtensions.cs b/AsyncMonolith.PostgreSql/StartupExtensions.cs index 9ac4bff..0425904 100644 --- a/AsyncMonolith.PostgreSql/StartupExtensions.cs +++ b/AsyncMonolith.PostgreSql/StartupExtensions.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -12,47 +11,26 @@ namespace AsyncMonolith.PostgreSql; /// /// AsyncMonolith PostgreSql startup extensions /// +/// +/// Registers AsyncMonolith for PostgreSQL. +/// public static class StartupExtensions { /// - /// Adds the PostgreSql implementation of the AsyncMonolith to the service collection. + /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the + /// background processors. Call it once, in the host. /// - /// The type of the DbContext. + /// The DbContext containing the AsyncMonolith tables. /// The service collection. - /// The action used to configure the settings. - /// A reference to this instance after the operation has completed. - public static IServiceCollection AddPostgreSqlAsyncMonolith( - this IServiceCollection services, - Action settings) where T : DbContext => - AddPostgreSqlAsyncMonolith(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds the PostgreSql implementation of the AsyncMonolith to the service collection. - /// - /// The type of the DbContext. - /// The service collection. - /// The assembly containing the DbContext. - /// The optional AsyncMonolith settings. - /// A reference to this instance after the operation has completed. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddPostgreSqlAsyncMonolith( - this IServiceCollection services, - Assembly assembly, - AsyncMonolithSettings? settings = null) where T : DbContext => - AddPostgreSqlAsyncMonolith( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - private static IServiceCollection AddPostgreSqlAsyncMonolith( + /// Sets options and the assemblies to scan for consumers. + /// A builder to bind configuration or add more consumer assemblies. + public static AsyncMonolithBuilder AddPostgreSqlAsyncMonolith( this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext + Action? configure = null) where T : DbContext { - configuration(settings); - services.InternalAddAsyncMonolith(settings); + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); services.TryAddSingleton(); services.TryAddSingleton(); - return services; + return builder; } } diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index 9936f1c..d6348a3 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -14,85 +13,49 @@ namespace AsyncMonolith.TestHelpers; public static class SetupTestHelpers { /// - /// Adds fake implementations of AsyncMonolith base services for testing purposes. + /// Registers fake producer and schedule services, which record what is produced and scheduled without a + /// database, plus the consumers. No background processors are registered. /// /// The service collection. - /// The action used to configure the settings. + /// Sets options and the assemblies to scan for consumers. + /// The service collection. public static IServiceCollection AddFakeAsyncMonolithBaseServices( this IServiceCollection services, - Action settings) => - AddFakeAsyncMonolithBaseServices(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds fake implementations of AsyncMonolith base services for testing purposes. - /// - /// The service collection. - /// The assembly containing the consumers. - /// Optional AsyncMonolith settings. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddFakeAsyncMonolithBaseServices( - this IServiceCollection services, - Assembly assembly, - AsyncMonolithSettings? settings = null) => - AddFakeAsyncMonolithBaseServices( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - /// - /// Adds real implementations of AsyncMonolith base services for production use. - /// - /// The DbContext type. - /// The service collection. - /// The action used to configure the settings. - public static IServiceCollection AddRealAsyncMonolithBaseServices( - this IServiceCollection services, - Action settings) where T : DbContext => - AddRealAsyncMonolithBaseServices(services, settings, AsyncMonolithSettings.Default); - - /// - /// Adds real implementations of AsyncMonolith base services for production use. - /// - /// The DbContext type. - /// The service collection. - /// The assembly containing the consumers. - /// Optional AsyncMonolith settings. - [Obsolete("This method is obsolete. Use the method that accepts an Action instead.")] - public static IServiceCollection AddRealAsyncMonolithBaseServices( - this IServiceCollection services, - Assembly assembly, - AsyncMonolithSettings? settings = null) where T : DbContext => - AddRealAsyncMonolithBaseServices( - services, - configuration => configuration.RegisterTypesFromAssembly(assembly), - settings ?? AsyncMonolithSettings.Default); - - private static IServiceCollection AddFakeAsyncMonolithBaseServices( - this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) + Action configure) { - configuration(settings); - services.InternalConfigureAsyncMonolithSettings(settings); - services.InternalRegisterAsyncMonolithConsumers(settings); + AddBaseServices(services, configure); services.AddSingleton(new FakeIdGenerator()); services.AddScoped(); services.AddScoped(); return services; } - private static IServiceCollection AddRealAsyncMonolithBaseServices( + /// + /// Registers the real database-backed services and the consumers, but no background processors, so tests can + /// process messages themselves with . + /// + /// The DbContext containing the AsyncMonolith tables. + /// The service collection. + /// Sets options and the assemblies to scan for consumers. + /// The service collection. + public static IServiceCollection AddRealAsyncMonolithBaseServices( this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext + Action configure) where T : DbContext { - configuration(settings); - services.InternalConfigureAsyncMonolithSettings(settings); - services.InternalRegisterAsyncMonolithConsumers(settings); + AddBaseServices(services, configure); services.AddSingleton(new AsyncMonolithIdGenerator()); + services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); return services; } + + private static void AddBaseServices(IServiceCollection services, Action configure) + { + services.InternalConfigureAsyncMonolithOptions(configure); + var registration = new AsyncMonolithOptions(); + configure(registration); + services.InternalRegisterAsyncMonolithConsumers(registration); + } } diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs index 3a3a295..03b27ba 100644 --- a/AsyncMonolith.Tests/ConfigurationTests.cs +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -5,6 +5,7 @@ using AsyncMonolith.Scheduling; using AsyncMonolith.Tests.Infra; using AsyncMonolith.Utilities; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; @@ -17,9 +18,9 @@ namespace AsyncMonolith.Tests; /// public class ConfigurationTests { - private static ConsumerRegistry Registry(Action? configure = null) + private static ConsumerRegistry Registry(Action? configure = null) { - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); configure?.Invoke(settings); var services = new ServiceCollection(); services.AddTestServices(DbType.Ef, settings); @@ -41,59 +42,100 @@ private static ConsumerRegistry Registry(Action? configur SpanId = null }; - public static TheoryData> InvalidSettings => new() + public static TheoryData> InvalidSettings => new() { - { "negative attempt delay", s => s.AttemptDelay = -1 }, + { "negative attempt delay", s => s.AttemptDelay = TimeSpan.FromSeconds(-1) }, { "zero max attempts", s => s.MaxAttempts = 0 }, - { "zero max delay", s => s.ProcessorMaxDelay = 0 }, - { "negative min delay", s => s.ProcessorMinDelay = -1 }, - { "min delay above max delay", s => { s.ProcessorMinDelay = 500; s.ProcessorMaxDelay = 100; } }, - { "zero batch size", s => s.ProcessorBatchSize = 0 }, - { "zero default timeout", s => s.DefaultConsumerTimeout = 0 }, - { "default timeout over an hour", s => s.DefaultConsumerTimeout = 3601 } + { "negative max attempt delay", s => s.MaxAttemptDelay = TimeSpan.FromSeconds(-1) }, + { "zero idle poll interval", s => s.IdlePollInterval = TimeSpan.Zero }, + { "negative busy poll interval", s => s.BusyPollInterval = TimeSpan.FromMilliseconds(-1) }, + { "busy poll interval above idle", s => { s.BusyPollInterval = TimeSpan.FromMilliseconds(500); s.IdlePollInterval = TimeSpan.FromMilliseconds(100); } }, + { "fractional default timeout", s => s.DefaultConsumerTimeout = TimeSpan.FromMilliseconds(1500) }, + { "zero batch size", s => s.BatchSize = 0 }, + { "zero default timeout", s => s.DefaultConsumerTimeout = TimeSpan.FromSeconds(0) }, + { "default timeout over an hour", s => s.DefaultConsumerTimeout = TimeSpan.FromSeconds(3601) } }; [Theory] [MemberData(nameof(InvalidSettings))] - public void Invalid_settings_are_rejected_at_startup(string because, Action configure) + public void Invalid_settings_are_rejected_at_startup(string because, Action configure) { - var settings = AsyncMonolithSettings.Default; - configure(settings); + var services = new ServiceCollection(); + services.InternalConfigureAsyncMonolithOptions(configure); + + var exception = Should.Throw(() => + services.BuildServiceProvider().GetRequiredService>().Value, because); + exception.Message.ShouldStartWith("AsyncMonolith:"); + } + + [Fact] + public async Task Invalid_options_stop_the_host_from_starting() + { + var builder = Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder(); + builder.Services.AddDbContext(_ => { }); + builder.Services.AddEfAsyncMonolith(s => s.BatchSize = 0); + using var host = builder.Build(); - Should.Throw(() => new ServiceCollection().InternalConfigureAsyncMonolithSettings(settings), - because); + await Should.ThrowAsync(() => + host.StartAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public void Options_bind_from_configuration_over_code() + { + var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["AsyncMonolith:MaxAttempts"] = "9", + ["AsyncMonolith:AttemptDelay"] = "00:00:30", + ["AsyncMonolith:IdlePollInterval"] = "00:00:00.250" + }) + .Build(); + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddDbContext(_ => { }); + + services.AddEfAsyncMonolith(s => s.MaxAttempts = 3).BindConfiguration("AsyncMonolith"); + + var options = services.BuildServiceProvider().GetRequiredService>().Value; + options.MaxAttempts.ShouldBe(9); + options.AttemptDelay.ShouldBe(TimeSpan.FromSeconds(30)); + options.IdlePollInterval.ShouldBe(TimeSpan.FromMilliseconds(250)); + options.BatchSize.ShouldBe(5); } [Fact] public void Boundary_settings_are_accepted() { - var settings = new AsyncMonolithSettings - { - AttemptDelay = 0, - MaxAttempts = 1, - ProcessorMaxDelay = 1, - ProcessorMinDelay = 0, - ProcessorBatchSize = 1, - DefaultConsumerTimeout = 3600 - }; var services = new ServiceCollection(); - services.InternalConfigureAsyncMonolithSettings(settings); + services.InternalConfigureAsyncMonolithOptions(s => + { + s.AttemptDelay = TimeSpan.Zero; + s.MaxAttemptDelay = TimeSpan.Zero; + s.MaxAttempts = 1; + s.IdlePollInterval = TimeSpan.FromMilliseconds(1); + s.BusyPollInterval = TimeSpan.Zero; + s.BatchSize = 1; + s.DefaultConsumerTimeout = TimeSpan.FromHours(1); + }); - var configured = services.BuildServiceProvider().GetRequiredService>().Value; - configured.AttemptDelay.ShouldBe(0); + var configured = services.BuildServiceProvider().GetRequiredService>().Value; + configured.AttemptDelay.ShouldBe(TimeSpan.Zero); configured.MaxAttempts.ShouldBe(1); - configured.ProcessorMaxDelay.ShouldBe(1); - configured.ProcessorMinDelay.ShouldBe(0); - configured.ProcessorBatchSize.ShouldBe(1); - configured.DefaultConsumerTimeout.ShouldBe(3600); + configured.IdlePollInterval.ShouldBe(TimeSpan.FromMilliseconds(1)); + configured.BusyPollInterval.ShouldBe(TimeSpan.Zero); + configured.BatchSize.ShouldBe(1); + configured.DefaultConsumerTimeout.ShouldBe(TimeSpan.FromHours(1)); } [Fact] public void Default_settings_are_valid() { - Should.NotThrow(() => - new ServiceCollection().InternalConfigureAsyncMonolithSettings(AsyncMonolithSettings.Default)); + var services = new ServiceCollection(); + services.InternalConfigureAsyncMonolithOptions(_ => { }); + + Should.NotThrow(() => services.BuildServiceProvider().GetRequiredService>().Value); } [Fact] @@ -113,7 +155,7 @@ public void Consumers_without_attributes_use_the_defaults() { var registry = Registry(s => { - s.DefaultConsumerTimeout = 42; + s.DefaultConsumerTimeout = TimeSpan.FromSeconds(42); s.MaxAttempts = 7; }); @@ -129,7 +171,7 @@ public void Non_positive_attribute_values_fall_back_to_the_defaults() { var registry = Registry(s => { - s.DefaultConsumerTimeout = 42; + s.DefaultConsumerTimeout = TimeSpan.FromSeconds(42); s.MaxAttempts = 7; }); @@ -142,7 +184,7 @@ public void Unknown_names_fall_back_or_throw() { var registry = Registry(s => { - s.DefaultConsumerTimeout = 42; + s.DefaultConsumerTimeout = TimeSpan.FromSeconds(42); s.MaxAttempts = 7; }); @@ -204,7 +246,7 @@ public void AddEfAsyncMonolith_registers_the_services_and_background_processors( services.ShouldContain(d => d.ServiceType == typeof(IHostedService) && d.ImplementationFactory != null); services.ShouldNotContain(d => d.ImplementationType == typeof(ConsumerMessageProcessor)); - services.BuildServiceProvider().GetRequiredService>().Value.MaxAttempts + services.BuildServiceProvider().GetRequiredService>().Value.MaxAttempts .ShouldBe(9); } } diff --git a/AsyncMonolith.Tests/ConsumeContextTests.cs b/AsyncMonolith.Tests/ConsumeContextTests.cs index ae7a5d1..5046ea5 100644 --- a/AsyncMonolith.Tests/ConsumeContextTests.cs +++ b/AsyncMonolith.Tests/ConsumeContextTests.cs @@ -15,7 +15,7 @@ public class ConsumeContextTests private static async Task<(SqliteTestHost Host, ContextRecorder Recorder)> Host() { - var host = await SqliteTestHost.Create(s => s.AttemptDelay = 0); + var host = await SqliteTestHost.Create(s => s.AttemptDelay = TimeSpan.FromSeconds(0)); return (host, host.Services.GetRequiredService()); } @@ -71,7 +71,7 @@ public async Task Consumers_of_one_payload_share_its_deduplication_key() [Fact] public void A_consumer_class_handling_two_payloads_is_rejected_at_startup() { - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); settings.RegisterTypesFromAssemblies(ClashingTypes.ConsumerOfTwoPayloads()); var services = new ServiceCollection(); diff --git a/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs index f928fbe..c5a29e3 100644 --- a/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs @@ -19,14 +19,14 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) try { // Given - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); var serviceProvider = await Setup(dbContainer, settings); var dbContext = serviceProvider.GetRequiredService(); var producer = serviceProvider.GetRequiredService(); var fetcher = serviceProvider.GetRequiredService(); var messages = new List(); - for (var i = 0; i < 2 * settings.ProcessorBatchSize; i++) + for (var i = 0; i < 2 * settings.BatchSize; i++) { messages.Add(new SingleConsumerMessage { @@ -42,7 +42,7 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) CancellationToken.None); // Then - dbMessages.Count.ShouldBe(settings.ProcessorBatchSize); + dbMessages.Count.ShouldBe(settings.BatchSize); } finally { @@ -59,7 +59,7 @@ public async Task Fetch_Returns_Messages_Partitioned_By_Rail(DbType dbType) try { // Given - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); var serviceProvider = await Setup(dbContainer, settings); var dbContext = serviceProvider.GetRequiredService(); var producer = serviceProvider.GetRequiredService(); diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs index 6f279fb..3d4083d 100644 --- a/AsyncMonolith.Tests/ConsumerProcessingTests.cs +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -52,7 +52,7 @@ public async Task Message_is_not_consumed_before_it_is_available() [Fact] public async Task Failed_message_is_retried_after_the_attempt_delay() { - await using var host = await SqliteTestHost.Create(s => s.AttemptDelay = 30); + await using var host = await SqliteTestHost.Create(s => s.AttemptDelay = TimeSpan.FromSeconds(30)); await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); var start = host.Now; @@ -79,7 +79,7 @@ public async Task Message_is_poisoned_after_the_configured_max_attempts() await using var host = await SqliteTestHost.Create(s => { s.MaxAttempts = 3; - s.AttemptDelay = 0; + s.AttemptDelay = TimeSpan.FromSeconds(0); }); await host.Produce(new ExceptionConsumerMessage { Name = "boom" }, insertId: "insert-1"); var original = (await host.ConsumerMessages()).ShouldHaveSingleItem(); @@ -114,7 +114,7 @@ public async Task Consumer_attempts_attribute_overrides_the_default_max_attempts await using var host = await SqliteTestHost.Create(s => { s.MaxAttempts = 10; - s.AttemptDelay = 0; + s.AttemptDelay = TimeSpan.FromSeconds(0); }); await host.Produce(new ExceptionConsumer2AttemptsMessage { Name = "boom" }); @@ -152,7 +152,7 @@ public async Task Consumer_that_exceeds_its_timeout_counts_as_a_failed_attempt() [Fact] public async Task Batch_size_limits_how_many_messages_are_processed_at_once() { - await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 2); + await using var host = await SqliteTestHost.Create(s => s.BatchSize = 2); for (var i = 0; i < 5; i++) { await host.Produce(new SingleConsumerMessage { Name = $"m{i}" }); @@ -168,7 +168,7 @@ public async Task Batch_size_limits_how_many_messages_are_processed_at_once() [Fact] public async Task Oldest_messages_are_processed_first() { - await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 1); + await using var host = await SqliteTestHost.Create(s => s.BatchSize = 1); await host.Produce(new OrderedMessage { Name = "newer" }); await host.Produce(new OrderedMessage { Name = "older" }); @@ -188,7 +188,7 @@ await host.Change(db => [Fact] public async Task Messages_created_in_the_same_second_are_taken_in_id_order() { - await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 1); + await using var host = await SqliteTestHost.Create(s => s.BatchSize = 1); await host.Produce(new OrderedMessage { Name = "first" }); await host.Produce(new OrderedMessage { Name = "second" }); // Swap the ids so that id order differs from insertion order. diff --git a/AsyncMonolith.Tests/ConsumerRegistryTests.cs b/AsyncMonolith.Tests/ConsumerRegistryTests.cs index 32f6b74..7ded874 100644 --- a/AsyncMonolith.Tests/ConsumerRegistryTests.cs +++ b/AsyncMonolith.Tests/ConsumerRegistryTests.cs @@ -11,7 +11,7 @@ public class ConsumerRegistryTests private static ServiceProvider Setup() { var services = new ServiceCollection(); - services.AddTestServices(DbType.Ef, AsyncMonolithSettings.Default); + services.AddTestServices(DbType.Ef, new AsyncMonolithOptions()); services.AddInMemoryDb(); return services.BuildServiceProvider(); diff --git a/AsyncMonolith.Tests/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs index fa8ef18..52e30b2 100644 --- a/AsyncMonolith.Tests/HostedProcessingTests.cs +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -25,7 +25,7 @@ public sealed class HostedProcessingTests : IAsyncLifetime public ValueTask InitializeAsync() => ValueTask.CompletedTask; - private async Task StartHost(Action? configure = null, bool registerAsModule = false) + private async Task StartHost(Action? configure = null, bool registerAsModule = false) { var builder = Host.CreateApplicationBuilder(); builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={_path}")); @@ -40,8 +40,8 @@ private async Task StartHost(Action? configure = null, bo s.RegisterTypesFromAssemblyContaining(); } - s.ProcessorMaxDelay = 50; - s.ProcessorMinDelay = 10; + s.IdlePollInterval = TimeSpan.FromMilliseconds(50); + s.BusyPollInterval = TimeSpan.FromMilliseconds(10); configure?.Invoke(s); }); if (registerAsModule) @@ -148,7 +148,7 @@ public async Task Failing_message_is_poisoned_by_the_running_host() await StartHost(s => { s.MaxAttempts = 2; - s.AttemptDelay = 0; + s.AttemptDelay = TimeSpan.FromSeconds(0); }); await Produce(new ExceptionConsumerMessage { Name = "boom" }); diff --git a/AsyncMonolith.Tests/Infra/DbTestsBase.cs b/AsyncMonolith.Tests/Infra/DbTestsBase.cs index 6c451a8..fbaac7a 100644 --- a/AsyncMonolith.Tests/Infra/DbTestsBase.cs +++ b/AsyncMonolith.Tests/Infra/DbTestsBase.cs @@ -12,7 +12,7 @@ public abstract class DbTestsBase protected FakeTimeProvider FakeTime { get; private set; } = default!; protected TestConsumerInvocations TestConsumerInvocations { get; private set; } = default!; - protected async Task Setup(TestDbContainerBase dbContainer, AsyncMonolithSettings? settings = null) + protected async Task Setup(TestDbContainerBase dbContainer, AsyncMonolithOptions? settings = null) { await dbContainer.InitializeAsync(); @@ -21,7 +21,7 @@ protected async Task Setup(TestDbContainerBase dbContainer, Asy dbContainer.AddDb(services); var (fakeTime, invocations) = - services.AddTestServices(dbContainer.DbType, settings ?? AsyncMonolithSettings.Default); + services.AddTestServices(dbContainer.DbType, settings ?? new AsyncMonolithOptions()); TestConsumerInvocations = invocations; FakeTime = fakeTime; diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs index 26cb751..0928184 100644 --- a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -46,7 +46,7 @@ private SqliteTestHost(SqliteConnection? connection, string? path, ServiceProvid public ScheduledMessageProcessor ScheduledProcessor => Services.GetRequiredService>(); - public static async Task Create(Action? configure = null, + public static async Task Create(Action? configure = null, bool fileDatabase = false) { SqliteConnection? connection = null; @@ -61,7 +61,7 @@ public static async Task Create(Action? c await connection.OpenAsync(); } - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); configure?.Invoke(settings); var services = new ServiceCollection(); diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index be99764..335b069 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -25,13 +25,22 @@ public static void AddInMemoryDb(this ServiceCollection services) } public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) AddTestServices( - this ServiceCollection services, DbType dbType, AsyncMonolithSettings settings) + this ServiceCollection services, DbType dbType, AsyncMonolithOptions settings) { var fakeTime = new FakeTimeProvider(DateTimeOffset.Parse("2020-08-31T10:00:00.0000000Z", System.Globalization.CultureInfo.InvariantCulture)); services.AddSingleton(fakeTime); services.AddLogging(); - services.InternalConfigureAsyncMonolithSettings(settings); + services.InternalConfigureAsyncMonolithOptions(o => + { + o.MaxAttempts = settings.MaxAttempts; + o.AttemptDelay = settings.AttemptDelay; + o.MaxAttemptDelay = settings.MaxAttemptDelay; + o.DefaultConsumerTimeout = settings.DefaultConsumerTimeout; + o.BatchSize = settings.BatchSize; + o.IdlePollInterval = settings.IdlePollInterval; + o.BusyPollInterval = settings.BusyPollInterval; + }); settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); diff --git a/AsyncMonolith.Tests/MultipleInstanceTests.cs b/AsyncMonolith.Tests/MultipleInstanceTests.cs index f89c26c..430fa33 100644 --- a/AsyncMonolith.Tests/MultipleInstanceTests.cs +++ b/AsyncMonolith.Tests/MultipleInstanceTests.cs @@ -94,9 +94,9 @@ public async Task Two_running_instances_sharing_a_database_consume_each_message_ builder.Services.AddEfAsyncMonolith(s => { s.RegisterTypesFromAssemblyContaining(); - s.ProcessorMaxDelay = 20; - s.ProcessorMinDelay = 0; - s.ProcessorBatchSize = 5; + s.IdlePollInterval = TimeSpan.FromMilliseconds(20); + s.BusyPollInterval = TimeSpan.FromMilliseconds(0); + s.BatchSize = 5; }); instances.Add(builder.Build()); } diff --git a/AsyncMonolith.Tests/NamingTests.cs b/AsyncMonolith.Tests/NamingTests.cs index 5797703..472b377 100644 --- a/AsyncMonolith.Tests/NamingTests.cs +++ b/AsyncMonolith.Tests/NamingTests.cs @@ -15,7 +15,7 @@ public class NamingTests private static void Register(params System.Reflection.Assembly[] assemblies) { - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); settings.RegisterTypesFromAssemblies(assemblies); var services = new ServiceCollection(); services.InternalRegisterAsyncMonolithConsumers(settings); diff --git a/AsyncMonolith.Tests/ProducerServiceTests.cs b/AsyncMonolith.Tests/ProducerServiceTests.cs index 13a5926..4ca8350 100644 --- a/AsyncMonolith.Tests/ProducerServiceTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceTests.cs @@ -19,7 +19,7 @@ public class ProducerServiceTests private ServiceProvider Setup() { var services = new ServiceCollection(); - var (fakeTime, _) = services.AddTestServices(DbType.Ef, AsyncMonolithSettings.Default); + var (fakeTime, _) = services.AddTestServices(DbType.Ef, new AsyncMonolithOptions()); FakeTime = fakeTime; services.AddInMemoryDb(); return services.BuildServiceProvider(); diff --git a/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs index 0025816..985d1f5 100644 --- a/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs +++ b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs @@ -20,32 +20,26 @@ public class RetryAndPoisonedMessageTests [InlineData(4, 80)] [InlineData(5, 100)] [InlineData(1000, 100)] - public void Retry_delay_doubles_each_attempt_up_to_the_maximum(int attempts, long expected) + public void Retry_delay_doubles_each_attempt_up_to_the_maximum(int attempts, int expectedSeconds) { - new AsyncMonolithSettings { AttemptDelay = 10, MaxAttemptDelay = 100 }.GetRetryDelay(attempts) - .ShouldBe(expected); + new AsyncMonolithOptions { AttemptDelay = TimeSpan.FromSeconds(10), MaxAttemptDelay = TimeSpan.FromSeconds(100) } + .GetRetryDelay(attempts).ShouldBe(TimeSpan.FromSeconds(expectedSeconds)); } [Fact] public void Retry_delay_never_drops_below_the_attempt_delay() { - var settings = new AsyncMonolithSettings { AttemptDelay = 600, MaxAttemptDelay = 300 }; + var options = new AsyncMonolithOptions + { AttemptDelay = TimeSpan.FromMinutes(10), MaxAttemptDelay = TimeSpan.FromMinutes(5) }; - settings.GetRetryDelay(1).ShouldBe(600); - settings.GetRetryDelay(3).ShouldBe(600); + options.GetRetryDelay(1).ShouldBe(TimeSpan.FromMinutes(10)); + options.GetRetryDelay(3).ShouldBe(TimeSpan.FromMinutes(10)); } [Fact] public void Zero_attempt_delay_retries_immediately() { - new AsyncMonolithSettings { AttemptDelay = 0 }.GetRetryDelay(5).ShouldBe(0); - } - - [Fact] - public void Negative_max_attempt_delay_is_rejected() - { - Should.Throw(() => new ServiceCollection().InternalConfigureAsyncMonolithSettings( - new AsyncMonolithSettings { MaxAttemptDelay = -1 })); + new AsyncMonolithOptions { AttemptDelay = TimeSpan.Zero }.GetRetryDelay(5).ShouldBe(TimeSpan.Zero); } [Fact] @@ -53,8 +47,8 @@ public async Task Failed_messages_back_off_between_retries() { await using var host = await SqliteTestHost.Create(s => { - s.AttemptDelay = 10; - s.MaxAttemptDelay = 25; + s.AttemptDelay = TimeSpan.FromSeconds(10); + s.MaxAttemptDelay = TimeSpan.FromSeconds(25); s.MaxAttempts = 10; }); await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); diff --git a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs index 964846a..3a4f460 100644 --- a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs @@ -18,13 +18,13 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) try { // Given - var settings = AsyncMonolithSettings.Default; + var settings = new AsyncMonolithOptions(); var serviceProvider = await Setup(dbContainer, settings); var dbContext = serviceProvider.GetRequiredService(); var fetcher = serviceProvider.GetRequiredService(); var idGenerator = serviceProvider.GetRequiredService(); - for (var i = 0; i < 2 * settings.ProcessorBatchSize; i++) + for (var i = 0; i < 2 * settings.BatchSize; i++) { dbContext.ScheduledMessages.Add(new ScheduledMessage { @@ -45,7 +45,7 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) CancellationToken.None); // Then - dbMessages.Count.ShouldBe(settings.ProcessorBatchSize); + dbMessages.Count.ShouldBe(settings.BatchSize); } finally { diff --git a/AsyncMonolith.Tests/SchedulingTests.cs b/AsyncMonolith.Tests/SchedulingTests.cs index 1387c94..77adfed 100644 --- a/AsyncMonolith.Tests/SchedulingTests.cs +++ b/AsyncMonolith.Tests/SchedulingTests.cs @@ -221,7 +221,7 @@ public async Task Missed_occurrences_are_not_caught_up() [Fact] public async Task Scheduled_processor_respects_the_batch_size() { - await using var host = await SqliteTestHost.Create(s => s.ProcessorBatchSize = 2); + await using var host = await SqliteTestHost.Create(s => s.BatchSize = 2); for (var i = 0; i < 3; i++) { await host.Schedule(new SingleConsumerMessage { Name = $"s{i}" }, "0 * * * * *"); diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index b74731d..633dcf0 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -20,6 +20,7 @@ + diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 88857ae..859390f 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -17,7 +17,7 @@ public sealed class ConsumerMessageProcessor : BackgroundService where T : Db private readonly IConsumerMessageFetcher _consumerMessageFetcher; private readonly ConsumerRegistry _consumerRegistry; private readonly ILogger> _logger; - private readonly IOptions _options; + private readonly IOptions _options; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; @@ -34,7 +34,7 @@ public sealed class ConsumerMessageProcessor : BackgroundService where T : Db public ConsumerMessageProcessor(ILogger> logger, TimeProvider timeProvider, ConsumerRegistry consumerRegistry, - IOptions options, + IOptions options, IServiceScopeFactory scopeFactory, IConsumerMessageFetcher consumerMessageFetcher) { @@ -64,13 +64,13 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { - var delay = _options.Value.ProcessorMaxDelay; + var delay = _options.Value.IdlePollInterval; try { var processedMessageCount = await ProcessBatch(stoppingToken); - if (processedMessageCount == _options.Value.ProcessorBatchSize) + if (processedMessageCount == _options.Value.BatchSize) { - delay = _options.Value.ProcessorMinDelay; + delay = _options.Value.BusyPollInterval; } } catch (Exception ex) @@ -78,7 +78,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) _logger.ConsumerBatchFailed(ex); } - if (delay >= 10) + if (delay > TimeSpan.Zero) { await Task.Delay(delay, stoppingToken); } @@ -219,7 +219,7 @@ internal async Task Complete(ClaimedMessage claimed, bool success, CancellationT if (message.Attempts < _consumerRegistry.ResolveConsumerMaxAttempts(message)) { var retryAt = _timeProvider.GetUtcNow().ToUnixTimeSeconds() + - _options.Value.GetRetryDelay(message.Attempts); + (long)_options.Value.GetRetryDelay(message.Attempts).TotalSeconds; await leased.ExecuteUpdateAsync(s => s .SetProperty(m => m.AvailableAfter, retryAt) .SetProperty(m => m.LastError, error), cancellationToken); diff --git a/AsyncMonolith/Consumers/ConsumerRegistry.cs b/AsyncMonolith/Consumers/ConsumerRegistry.cs index b096c32..5ef095d 100644 --- a/AsyncMonolith/Consumers/ConsumerRegistry.cs +++ b/AsyncMonolith/Consumers/ConsumerRegistry.cs @@ -10,7 +10,7 @@ public sealed class ConsumerRegistry /// /// Gets the async monolith settings. /// - private readonly AsyncMonolithSettings _settings; + private readonly AsyncMonolithOptions _settings; /// /// Gets the dictionary that maps consumer names to their associated time out. @@ -61,7 +61,7 @@ public ConsumerRegistry(IReadOnlyDictionary consumerTypeDictionary IReadOnlyDictionary consumerAttemptsDictionary, IReadOnlyDictionary consumerRailIdDictionary, IReadOnlyDictionary consumerExecutionModeDictionary, - AsyncMonolithSettings settings) + AsyncMonolithOptions settings) { ConsumerTypeDictionary = consumerTypeDictionary; PayloadConsumerDictionary = payloadConsumerDictionary; @@ -123,7 +123,7 @@ public int ResolveConsumerTimeout(ConsumerMessage consumer) return timeout; } - return _settings.DefaultConsumerTimeout; + return (int)_settings.DefaultConsumerTimeout.TotalSeconds; } /// @@ -193,6 +193,6 @@ public int ResolveConsumerTimeout(string consumerType) return timeout; } - return _settings.DefaultConsumerTimeout; + return (int)_settings.DefaultConsumerTimeout.TotalSeconds; } } \ No newline at end of file diff --git a/AsyncMonolith/Consumers/ConsumerTimeoutAttribute.cs b/AsyncMonolith/Consumers/ConsumerTimeoutAttribute.cs index ec3aa3f..b0940e8 100644 --- a/AsyncMonolith/Consumers/ConsumerTimeoutAttribute.cs +++ b/AsyncMonolith/Consumers/ConsumerTimeoutAttribute.cs @@ -9,14 +9,14 @@ public sealed class ConsumerTimeoutAttribute : Attribute /// /// Initializes a new instance of the class with the specified duration. /// - /// The duration of the consumer timeout. - public ConsumerTimeoutAttribute(int duration) + /// The timeout in seconds, between 1 and 3600. + public ConsumerTimeoutAttribute(int seconds) { - Duration = duration; + Seconds = seconds; } /// /// Gets the duration of the consumer timeout. /// - public int Duration { get; } + public int Seconds { get; } } diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index 7ac7a13..c021501 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -17,7 +17,7 @@ public sealed class ScheduledMessageProcessor : BackgroundService where T : D { private readonly ILogger> _logger; private readonly IScheduledMessageFetcher _messageFetcher; - private readonly IOptions _options; + private readonly IOptions _options; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; @@ -30,7 +30,7 @@ public sealed class ScheduledMessageProcessor : BackgroundService where T : D /// The service scope factory. /// The scheduled message fetcher. public ScheduledMessageProcessor(ILogger> logger, - TimeProvider timeProvider, IOptions options, IServiceScopeFactory scopeFactory, + TimeProvider timeProvider, IOptions options, IServiceScopeFactory scopeFactory, IScheduledMessageFetcher messageFetcher) { _logger = logger; @@ -48,14 +48,14 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { - var delay = _options.Value.ProcessorMaxDelay; + var delay = _options.Value.IdlePollInterval; try { var processedScheduledMessages = await ProcessBatch(stoppingToken); - if (processedScheduledMessages >= _options.Value.ProcessorBatchSize) + if (processedScheduledMessages >= _options.Value.BatchSize) { - delay = _options.Value.ProcessorMinDelay; + delay = _options.Value.BusyPollInterval; } } catch (Exception ex) @@ -63,7 +63,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) _logger.ScheduleBatchFailed(ex); } - if (delay >= 10) + if (delay > TimeSpan.Zero) { await Task.Delay(delay, stoppingToken); } diff --git a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs new file mode 100644 index 0000000..a033f79 --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs @@ -0,0 +1,183 @@ +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace AsyncMonolith.Utilities; + +/// +/// Options for AsyncMonolith. Set them in the Add*AsyncMonolith call, or bind them from configuration +/// with . They are validated when the host starts. +/// +public sealed class AsyncMonolithOptions +{ + internal HashSet AssembliesToRegister { get; } = []; + + /// + /// How many times a message is attempted before it is poisoned. Default 5, at least 1. + /// Override per consumer with [ConsumerAttempts]. + /// + public int MaxAttempts { get; set; } = 5; + + /// + /// The delay before the first retry of a failed message. Each further retry waits twice as long as the one + /// before, up to . Default 10 seconds, not negative. + /// + public TimeSpan AttemptDelay { get; set; } = TimeSpan.FromSeconds(10); + + /// + /// The longest delay between retries. If it is less than , retries wait + /// each time. Default 5 minutes, not negative. + /// + public TimeSpan MaxAttemptDelay { get; set; } = TimeSpan.FromMinutes(5); + + /// + /// How long a consumer may run before it is cancelled and the attempt counts as failed. Default 10 seconds, + /// a whole number of seconds between 1 second and 1 hour. Override per consumer with [ConsumerTimeout]. + /// + public TimeSpan DefaultConsumerTimeout { get; set; } = TimeSpan.FromSeconds(10); + + /// The most messages (or schedules) a processor takes at once. Default 5, at least 1. + public int BatchSize { get; set; } = 5; + + /// + /// How long a processor waits before looking again when its last batch wasn't full. Default 1 second, at + /// least 1 millisecond. + /// + public TimeSpan IdlePollInterval { get; set; } = TimeSpan.FromSeconds(1); + + /// + /// How long a processor waits before looking again when its last batch was full. Default 10 milliseconds, + /// not negative and not more than . + /// + public TimeSpan BusyPollInterval { get; set; } = TimeSpan.FromMilliseconds(10); + + /// + /// Gets the delay before retrying a message that has failed times. + /// + /// The number of failed attempts so far (1 after the first failure). + /// doubled for each attempt after the first, capped at + /// (or if that is larger). + public TimeSpan GetRetryDelay(int attempts) + { + var cap = AttemptDelay > MaxAttemptDelay ? AttemptDelay : MaxAttemptDelay; + var ticks = AttemptDelay.Ticks; + for (var i = 1; i < attempts && ticks < cap.Ticks; i++) + { + ticks *= 2; + } + + return TimeSpan.FromTicks(Math.Min(ticks, cap.Ticks)); + } + + /// Registers the consumers and payloads in the assembly containing . + public AsyncMonolithOptions RegisterTypesFromAssemblyContaining() + => RegisterTypesFromAssemblyContaining(typeof(T)); + + /// Registers the consumers and payloads in the assembly containing . + public AsyncMonolithOptions RegisterTypesFromAssemblyContaining(Type type) + => RegisterTypesFromAssembly(type.Assembly); + + /// Registers the consumers and payloads in an assembly. + public AsyncMonolithOptions RegisterTypesFromAssembly(Assembly assembly) + => RegisterTypesFromAssemblies(assembly); + + /// Registers the consumers and payloads in the given assemblies. + public AsyncMonolithOptions RegisterTypesFromAssemblies(params Assembly[] assemblies) + { + foreach (var assembly in assemblies) + { + AssembliesToRegister.Add(assembly); + } + + return this; + } +} + +/// Validates when the host starts. +internal sealed class AsyncMonolithOptionsValidator : IValidateOptions +{ + public ValidateOptionsResult Validate(string? name, AsyncMonolithOptions options) + { + var errors = new List(); + if (options.MaxAttempts < 1) + { + errors.Add("MaxAttempts must be at least 1."); + } + + if (options.AttemptDelay < TimeSpan.Zero) + { + errors.Add("AttemptDelay must not be negative."); + } + + if (options.MaxAttemptDelay < TimeSpan.Zero) + { + errors.Add("MaxAttemptDelay must not be negative."); + } + + if (options.DefaultConsumerTimeout < TimeSpan.FromSeconds(1) || + options.DefaultConsumerTimeout > TimeSpan.FromHours(1) || + options.DefaultConsumerTimeout.Ticks % TimeSpan.TicksPerSecond != 0) + { + errors.Add("DefaultConsumerTimeout must be a whole number of seconds between 1 second and 1 hour."); + } + + if (options.BatchSize < 1) + { + errors.Add("BatchSize must be at least 1."); + } + + if (options.IdlePollInterval < TimeSpan.FromMilliseconds(1)) + { + errors.Add("IdlePollInterval must be at least 1 millisecond."); + } + + if (options.BusyPollInterval < TimeSpan.Zero) + { + errors.Add("BusyPollInterval must not be negative."); + } + + if (options.BusyPollInterval > options.IdlePollInterval) + { + errors.Add("BusyPollInterval must not be more than IdlePollInterval."); + } + + return errors.Count == 0 + ? ValidateOptionsResult.Success + : ValidateOptionsResult.Fail(errors.Select(e => $"AsyncMonolith: {e}")); + } +} + +/// +/// Returned by Add*AsyncMonolith to continue configuring AsyncMonolith. +/// +public sealed class AsyncMonolithBuilder +{ + internal AsyncMonolithBuilder(IServiceCollection services) + { + Services = services; + } + + /// The service collection. + public IServiceCollection Services { get; } + + /// + /// Binds from a configuration section, for example + /// "AsyncMonolith". Values from configuration are applied after those set in code. + /// + public AsyncMonolithBuilder BindConfiguration(string sectionPath) + { + Services.AddOptions().BindConfiguration(sectionPath); + return this; + } + + /// Registers the consumers and payloads in more assemblies. + public AsyncMonolithBuilder AddConsumers(params Assembly[] assemblies) + { + Services.AddAsyncMonolithConsumers(assemblies); + return this; + } + + /// Registers the consumers and payloads in the assembly containing . + public AsyncMonolithBuilder AddConsumersFromAssemblyContaining() => + AddConsumers(typeof(TMarker).Assembly); +} diff --git a/AsyncMonolith/Utilities/AsyncMonolithSettings.cs b/AsyncMonolith/Utilities/AsyncMonolithSettings.cs deleted file mode 100644 index be22723..0000000 --- a/AsyncMonolith/Utilities/AsyncMonolithSettings.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System.Reflection; - -namespace AsyncMonolith.Utilities; - -/// -/// Represents the settings for the AsyncMonolith application. -/// -public class AsyncMonolithSettings -{ - internal readonly HashSet AssembliesToRegister = []; - - /// - /// Gets or sets the maximum number of attempts for processing a message. - /// Default: 5, Min: 1, Max N/A - /// - public int MaxAttempts { get; set; } = 5; - - /// - /// Gets or sets the delay in seconds before the first retry of a failed message. Each further retry - /// waits twice as long as the one before, up to . - /// Default: 10 seconds, Min: 0 second, Max N/A - /// - public int AttemptDelay { get; set; } = 10; - - /// - /// Gets or sets the longest delay in seconds between retries. If it is less than - /// , retries wait each time. - /// Default: 300 seconds, Min: 0 second, Max N/A - /// - public int MaxAttemptDelay { get; set; } = 300; - - /// - /// Gets or sets the maximum delay in milliseconds between processor cycles. - /// Default: 1000ms, Min: 1ms, Max N/A - /// - public int ProcessorMaxDelay { get; set; } = 1000; - - /// - /// Gets or sets the minimum delay in milliseconds between processor cycles. - /// Default: 10ms, Min: 0ms, Max N/A - /// - public int ProcessorMinDelay { get; set; } = 10; - - /// - /// Gets or sets the number of messages to process in a batch.# - /// Default: 5, Min: 1, Max N/A - /// - public int ProcessorBatchSize { get; set; } = 5; - - /// - /// Gets or sets the default number of seconds a consumer waits before timing out. - /// Default: 10 seconds, Min: 1 second, Max 3600 seconds - /// - public int DefaultConsumerTimeout { get; set; } = 10; - - /// - /// Gets the delay in seconds before retrying a message that has failed times. - /// - /// The number of failed attempts so far (1 after the first failure). - /// doubled for each attempt after the first, capped at - /// (or if that is larger). - public long GetRetryDelay(int attempts) - { - var cap = Math.Max(AttemptDelay, MaxAttemptDelay); - var doublings = Math.Clamp(attempts - 1, 0, 30); - return Math.Min((long)AttemptDelay << doublings, cap); - } - - /// - /// Gets the default AsyncMonolithSettings. - /// - public static AsyncMonolithSettings Default => new() - { - MaxAttempts = 5, - AttemptDelay = 10, - MaxAttemptDelay = 300, - ProcessorMaxDelay = 1000, - ProcessorMinDelay = 10, - ProcessorBatchSize = 5 - }; - - /// - /// Register consumers and payloads from assembly containing given type. - /// - /// Type from assembly to scan. - /// The current instance to continue configuration. - public AsyncMonolithSettings RegisterTypesFromAssemblyContaining() - => RegisterTypesFromAssemblyContaining(typeof(T)); - - /// - /// Register consumers and payloads from assembly containing given type. - /// - /// Type from assembly to scan. - /// The current instance to continue configuration. - public AsyncMonolithSettings RegisterTypesFromAssemblyContaining(Type type) - => RegisterTypesFromAssembly(type.Assembly); - - /// - /// Register consumers and payloads from assembly. - /// - /// Assembly to scan - /// The current instance to continue configuration. - public AsyncMonolithSettings RegisterTypesFromAssembly(Assembly assembly) - => RegisterTypesFromAssemblies([assembly]); - - /// - /// Register consumers and payloads from assemblies. - /// - /// Assemblies to scan. - /// The current instance to continue configuration. - public AsyncMonolithSettings RegisterTypesFromAssemblies(params Assembly[] assemblies) - { - foreach (var assembly in assemblies) - { - AssembliesToRegister.Add(assembly); - } - - return this; - } -} \ No newline at end of file diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index db5f035..6275070 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -28,71 +28,18 @@ public static ModelBuilder ConfigureAsyncMonolith(this ModelBuilder modelBuilder return modelBuilder; } - internal static void InternalConfigureAsyncMonolithSettings( + internal static void InternalConfigureAsyncMonolithOptions( this IServiceCollection services, - AsyncMonolithSettings settings) + Action configure) { - if (settings.AttemptDelay < 0) - { - throw new ArgumentException("AsyncMonolithSettings.AttemptDelay must be positive."); - } - - if (settings.MaxAttemptDelay < 0) - { - throw new ArgumentException("AsyncMonolithSettings.MaxAttemptDelay must be positive."); - } - - if (settings.MaxAttempts < 1) - { - throw new ArgumentException("AsyncMonolithSettings.MaxAttempts must be at least 1."); - } - - if (settings.ProcessorMaxDelay < 1) - { - throw new ArgumentException("AsyncMonolithSettings.ProcessorMaxDelay must be at least 1."); - } - - if (settings.ProcessorMinDelay < 0) - { - throw new ArgumentException("AsyncMonolithSettings.ProcessorMinDelay must be positive."); - } - - if (settings.ProcessorMinDelay > settings.ProcessorMaxDelay) - { - throw new ArgumentException( - "AsyncMonolithSettings.ProcessorMaxDelay must be greater than AsyncMonolithSettings.ProcessorMinDelay."); - } - - if (settings.ProcessorBatchSize < 1) - { - throw new ArgumentException("AsyncMonolithSettings.ProcessorBatchSize must be at least 1."); - } - - if (settings.DefaultConsumerTimeout < 1) - { - throw new ArgumentException("AsyncMonolithSettings.DefaultConsumerTimeout must be at least 1."); - } - - if (settings.DefaultConsumerTimeout > 3600) - { - throw new ArgumentException("AsyncMonolithSettings.DefaultConsumerTimeout must be less then 3600."); - } - - services.Configure(options => - { - options.AttemptDelay = settings.AttemptDelay; - options.MaxAttemptDelay = settings.MaxAttemptDelay; - options.MaxAttempts = settings.MaxAttempts; - options.ProcessorMaxDelay = settings.ProcessorMaxDelay; - options.ProcessorMinDelay = settings.ProcessorMinDelay; - options.ProcessorBatchSize = settings.ProcessorBatchSize; - options.DefaultConsumerTimeout = settings.DefaultConsumerTimeout; - }); + services.AddOptions().Configure(configure).ValidateOnStart(); + services.TryAddEnumerable(ServiceDescriptor + .Singleton, AsyncMonolithOptionsValidator>()); } - internal static void InternalAddAsyncMonolith( + internal static AsyncMonolithBuilder InternalAddAsyncMonolith( this IServiceCollection services, - AsyncMonolithSettings settings) where T : DbContext + Action configure) where T : DbContext { if (services.Any(d => d.ServiceType == typeof(AsyncMonolithRegistration))) { @@ -102,8 +49,12 @@ internal static void InternalAddAsyncMonolith( } services.AddSingleton(); - services.InternalConfigureAsyncMonolithSettings(settings); - services.InternalRegisterAsyncMonolithConsumers(settings); + services.InternalConfigureAsyncMonolithOptions(configure); + + // The assemblies to scan are needed now, to register the consumer types. + var registration = new AsyncMonolithOptions(); + configure(registration); + services.InternalRegisterAsyncMonolithConsumers(registration); // TryAdd, so a host can register its own implementation before or instead of these. services.TryAddSingleton(TimeProvider.System); @@ -119,11 +70,12 @@ internal static void InternalAddAsyncMonolith( serviceProvider.GetRequiredService().RailIds.ToArray())); services.AddHostedService>(); + return new AsyncMonolithBuilder(services); } internal static void InternalRegisterAsyncMonolithConsumers( this IServiceCollection services, - AsyncMonolithSettings settings) + AsyncMonolithOptions settings) { services.AddAsyncMonolithConsumers(settings.AssembliesToRegister.ToArray()); } @@ -154,7 +106,7 @@ public static IServiceCollection AddAsyncMonolithConsumers(this IServiceCollecti services.AddSingleton(registered); services.AddOptions(); services.TryAddSingleton(serviceProvider => BuildConsumerRegistry(registered, - serviceProvider.GetRequiredService>().Value)); + serviceProvider.GetRequiredService>().Value)); } foreach (var assembly in assemblies) @@ -187,7 +139,7 @@ private static IEnumerable FindConsumerTypes(IEnumerable types) => ConsumerInvoker.PayloadTypeOf(t) is not null); internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable assemblies, - AsyncMonolithSettings settings) + AsyncMonolithOptions settings) { var consumerServiceDictionary = new Dictionary(); var payloadConsumerDictionary = new Dictionary>(); @@ -204,16 +156,17 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass { var consumerName = AsyncMonolithNames.ForConsumer(consumerType); - var timeoutDuration = settings.DefaultConsumerTimeout; + var defaultTimeout = (int)settings.DefaultConsumerTimeout.TotalSeconds; + var timeoutDuration = defaultTimeout; var attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerTimeoutAttribute)); if (attribute is ConsumerTimeoutAttribute timeoutAttribute) { - timeoutDuration = timeoutAttribute.Duration; + timeoutDuration = timeoutAttribute.Seconds; } if (timeoutDuration <= 0) { - timeoutDuration = settings.DefaultConsumerTimeout; + timeoutDuration = defaultTimeout; } consumerTimeoutDictionary[consumerName] = timeoutDuration; diff --git a/Directory.Packages.props b/Directory.Packages.props index 8822bad..0f0a47a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,6 +8,7 @@ + diff --git a/Example/Example.Api/Program.cs b/Example/Example.Api/Program.cs index 65c1aa5..3dfb80f 100644 --- a/Example/Example.Api/Program.cs +++ b/Example/Example.Api/Program.cs @@ -32,11 +32,11 @@ public static void Main(string[] args) builder.Services.AddPostgreSqlAsyncMonolith(settings => { settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); - settings.AttemptDelay = 10; + settings.AttemptDelay = TimeSpan.FromSeconds(10); settings.MaxAttempts = 5; - settings.ProcessorMinDelay = 10; - settings.ProcessorMaxDelay = 100; - settings.ProcessorBatchSize = 10; + settings.BusyPollInterval = TimeSpan.FromMilliseconds(10); + settings.IdlePollInterval = TimeSpan.FromMilliseconds(100); + settings.BatchSize = 10; }); builder.Services.AddOpenTelemetry() diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 6f8b351..15db69f 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -1,9 +1,9 @@ - **Independent Consumption**: Each message will be consumed independently by each consumer set up to handle it. - **Periodic Querying**: Each instance of your app will periodically query the `consumer_messages` table for a batch of available messages to process. - - The query takes place at the frequency defined by `ProcessorMaxDelay`, if a full batch is returned it will delay by `ProcessorMinDelay`. + - After a batch that wasn't full it waits `IdlePollInterval` before looking again; after a full batch it waits `BusyPollInterval`. - **Multiple instances**: Any number of app instances can process the same tables, with every database package. A processor claims each message with a conditional update, so a message is only ever claimed by one processor at a time, and each schedule occurrence fires once. The PostgreSQL, SQL Server, MySQL and MariaDB packages also lock rows while claiming, so processors skip each other's batches instead of competing for them. - **Rails**: Each rail (`[ConsumerRailId]`) gets its own processor, so a slow consumer on one rail doesn't hold up consumers on another. -- **Batching**: Consumer messages will be read from the `consumer_messages` table in batches defined by `ConsumerMessageBatchSize`. +- **Batching**: Consumer messages will be read from the `consumer_messages` table in batches defined by `BatchSize`. - **Idempotency**: Ensure your Consumers are idempotent, since they will be retried on failure. - **Timeout**: Consumers timeout after the number of seconds defined by the `ConsumerTimeout` attribute or the `DefaultConsumerTimeout` if not set. @@ -44,7 +44,7 @@ Design consumers so the order of messages doesn't matter, for example by checkin ## Consumer Failures 💢 - **Retry Logic**: Messages are retried up to `MaxAttempts` times before they are moved to the `poisoned_messages` table. Add the `[ConsumerAttempts(1)]` attribute to override this per consumer. -- **Backoff**: The first retry waits `AttemptDelay` seconds (default 10), and each later retry waits twice as long as the one before, up to `MaxAttemptDelay` seconds (default 300). With the defaults a message is retried after 10, 20, 40 and 80 seconds. +- **Backoff**: The first retry waits `AttemptDelay` (default 10 seconds), and each later retry waits twice as long as the one before, up to `MaxAttemptDelay` (default 5 minutes). With the defaults a message is retried after 10, 20, 40 and 80 seconds. - **Errors**: The error from the most recent failed attempt is stored in `last_error` on both tables, for example `System.InvalidOperationException: ...` or `Timed out after 10 seconds.` - **Interrupted processing**: A message is leased while its consumer runs. If the app stops mid-message, the message becomes available again once its consumer timeout plus 30 seconds has passed, and the interrupted attempt counts. - **Manual Intervention**: Use `IPoisonedMessageService` to count, list, retry or delete poisoned messages. Retrying moves a message back to `consumer_messages` with its attempts reset. Changes are saved immediately. diff --git a/docs/internals.md b/docs/internals.md index 39b876f..7bdec6c 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -22,7 +22,7 @@ Stores consumer messages that have reached `AsyncMonolith.MaxAttempts`, poisoned ## ConsumerMessageProcessor -A background service that periodically fetches available messages from the 'consumer_messages' table. Once a message is found, it's row-level locked to prevent other processes from fetching it. The corresponding consumer attempts to process the message. If successful, the message is removed from the `consumer_messages` table; otherwise, the processor increments the messages `attempts` by one and delays processing for a defined number of seconds (`AsyncMonolithSettings.AttemptDelay`). If the number of attempts reaches the limit defined by `AsyncMonolith.MaxAttempts`, the message is moved to the `poisoned_messages` table. +A background service that periodically fetches available messages from the 'consumer_messages' table. Once a message is found, it's row-level locked to prevent other processes from fetching it. The corresponding consumer attempts to process the message. If successful, the message is removed from the `consumer_messages` table; otherwise, the processor increments the messages `attempts` by one and delays processing for a defined number of seconds (`AsyncMonolithOptions.AttemptDelay`). If the number of attempts reaches the limit defined by `AsyncMonolith.MaxAttempts`, the message is moved to the `poisoned_messages` table. ## ScheduledMessageProcessor @@ -34,5 +34,5 @@ Used to resolve all the consumers able to process a given payload, and resolve i ## Notes 📋 -- The background services wait for `AsyncMonolithSettings.ProcessorMaxDelay` seconds before fetching another batch of messages. If a full batch is fetched, the delay is reduced to `AsyncMonolithSettings.ProcessorMinDelay` seconds between cycles. +- The background services wait for `AsyncMonolithOptions.IdlePollInterval` before fetching another batch of messages. If a full batch is fetched, the delay is reduced to `AsyncMonolithOptions.ProcessorMinDelay` seconds between cycles. - Configuring concurrent consumer / scheduled message processors will throw a startup exception when using AsyncMonolith.Ef (due to no built in support for row level locking) diff --git a/docs/quickstart.md b/docs/quickstart.md index e41d3ee..e65677a 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -57,20 +57,23 @@ Register your dependencies and configure settings // services.AddMySqlAsyncMonolith // services.AddPostgreSqlAsyncMonolith // services.AddMariaDbAsyncMonolith - builder.Services.AddPostgreSqlAsyncMonolith(settings => + builder.Services.AddPostgreSqlAsyncMonolith(options => { - settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); - settings.AttemptDelay = 10, // Seconds before a failed message is retried - settings.MaxAttempts = 5, // Number of times a failed message is retried - settings.ProcessorMinDelay = 10, // Minimum millisecond delay before the next batch is processed - settings.ProcessorMaxDelay = 1000, // Maximum millisecond delay before the next batch is processed - settings.ProcessorBatchSize = 5, // The number of messages to process in a single batch - settings.ConsumerMessageProcessorCount = 2, // The number of concurrent consumer message processors to run in each app instance - settings.ScheduledMessageProcessorCount = 1, // The number of concurrent scheduled message processors to run in each app instance - settings.DefaultConsumerTimeout = 10 // The default number of seconds before a consumer will timeout - }); + options.RegisterTypesFromAssemblyContaining(); + options.MaxAttempts = 5; // Attempts before a message is poisoned + options.AttemptDelay = TimeSpan.FromSeconds(10); // First retry delay; doubles each retry + options.MaxAttemptDelay = TimeSpan.FromMinutes(5); // Longest retry delay + options.DefaultConsumerTimeout = TimeSpan.FromSeconds(10); // Before a consumer is cancelled + options.BatchSize = 5; // Messages a processor takes at once + options.IdlePollInterval = TimeSpan.FromSeconds(1); // Wait after a batch that wasn't full + options.BusyPollInterval = TimeSpan.FromMilliseconds(10); // Wait after a full batch + }) + .BindConfiguration("AsyncMonolith"); // Optional: override any option from appsettings.json ``` -The following methods are available on the `AsyncMonolithSettings` passed into the `settings` lambda: + +Options are validated when the host starts, so an invalid value stops startup with an `OptionsValidationException` that names it. In `appsettings.json`, write times as `"00:00:30"`. + +The following methods are available on the `AsyncMonolithOptions` passed into the `options` lambda: - `RegisterTypesFromAssemblyContaining()` - `RegisterTypesFromAssemblyContaining(Type type)` diff --git a/docs/releases.md b/docs/releases.md index 31dc6d2..a2930ed 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -26,7 +26,7 @@ All packages now share one version and must be upgraded together. From 11.0.0 th - Several app instances can safely share the tables with any database package. Claims and schedule occurrences use conditional updates, so a message is processed by one processor at a time and a schedule fires once per occurrence. - Fetch order is deterministic (oldest first, then by id). See [Ordering](guides/consuming-messages.md#ordering) for what is and isn't guaranteed. - Consumers can write to the database on SQLite. Messages are claimed and leased in a short transaction, consumers run outside it, and each message is completed in its own short write. If the app stops mid-message, the message is retried once its consumer timeout plus 30 seconds has passed. -- Retries back off exponentially from `AttemptDelay` up to the new `MaxAttemptDelay` setting (default 300 seconds). +- Retries back off exponentially from `AttemptDelay` up to the new `MaxAttemptDelay` option (default 5 minutes). - The last error is stored on retried and poisoned messages. - `IPoisonedMessageService` counts, lists, retries and deletes poisoned messages. - `IScheduleService.EnsureSchedule` creates or updates a schedule by tag, so it can run at every startup. @@ -35,6 +35,10 @@ All packages now share one version and must be upgraded together. From 11.0.0 th - `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. **Breaking changes** +- `AsyncMonolithSettings` is now `AsyncMonolithOptions`, configured through the standard options pattern and validated when the host starts (an `OptionsValidationException` instead of an `ArgumentException` at registration). Times are `TimeSpan`s, and some names changed: `ProcessorBatchSize` → `BatchSize`, `ProcessorMaxDelay` (ms) → `IdlePollInterval`, `ProcessorMinDelay` (ms) → `BusyPollInterval`. `AsyncMonolithSettings.Default` is gone; use `new AsyncMonolithOptions()`. +- `Add*AsyncMonolith` returns an `AsyncMonolithBuilder` (for `.BindConfiguration(...)` and `.AddConsumers(...)`) instead of `IServiceCollection`, and the obsolete overloads taking an `Assembly` are removed. The TestHelpers setup methods take `Action`. +- `[ConsumerTimeout]`'s `Duration` property is now `Seconds`. +- Consumers implement `IConsumer` and receive a `ConsumeContext`; `BaseConsumer` is removed. - PostgreSQL, SQL Server, MySQL and MariaDB users: messages are no longer written until you call `SaveChanges`. If you produced messages without saving, call `SaveChangesAsync`. - `Add*AsyncMonolith` no longer registers `DbContext` as an alias for your context, and throws if called twice (modules use `AddAsyncMonolithConsumers`). Its services use `TryAdd`, so services you register first win. - Removed public types: `EfProducerService`, `PostgreSqlProducerService`, `MsSqlProducerService`, `MySqlProducerService`, `MariaDbProducerService` and the unused `ScheduledMessageProcessorFactory`. Resolve `IProducerService` instead. From 2ecb10b3df3df5f4b5839b5889fb2c44da4c5609 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:58:29 +0000 Subject: [PATCH 34/53] Use time types and clear names in the producer and schedule APIs - Produce takes a TimeSpan? delay, or a DateTimeOffset availableAt, instead of an absolute Unix-seconds long. Future times are rounded up to whole seconds so a message is never consumed early; past times mean now. Negative delays are rejected. ProduceList takes an IEnumerable. - insertId is now deduplicationKey (and InsertId is DeduplicationKey), still stored in insert_id. - Chron is spelled Cron: CronExpression, CronTimeZone and the cronExpression and timeZone parameters. Columns are unchanged. - TK generic parameters are TPayload, and ConsumerInstanceExecutionMode is ConsumerExecutionMode. - Produce(ScheduledMessage) leaves IProducerService. The scheduler uses the internal producer directly, so a host's own IProducerService can't stop schedules from firing. - FakeProducerService implements the new interface and mirrors the deduplication behaviour. Tests cover delay rounding, immediate messages produced mid-second, future and past times, and negative delays. No migration is needed. --- .../FakeProducerService.cs | 135 +++++------------- .../FakeScheduleService.cs | 30 ++-- AsyncMonolith.TestHelpers/SetupTestHelpers.cs | 1 + AsyncMonolith.Tests/ConfigurationTests.cs | 8 +- AsyncMonolith.Tests/ConsumeContextTests.cs | 4 +- .../ConsumerMessageProcessorTests.cs | 2 +- .../ConsumerProcessingTests.cs | 8 +- AsyncMonolith.Tests/ConsumerRegistryTests.cs | 8 +- .../EnsureScheduleAndStatisticsTests.cs | 6 +- .../Infra/BehaviourConsumers.cs | 4 +- AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 4 +- .../Infra/TestServiceHelpers.cs | 1 + AsyncMonolith.Tests/ProducerBehaviourTests.cs | 84 +++++++++-- AsyncMonolith.Tests/ProducerServiceDbTests.cs | 18 +-- AsyncMonolith.Tests/ProducerServiceTests.cs | 44 +++--- .../RetryAndPoisonedMessageTests.cs | 2 +- .../ScheduledMessageFetcherTests.cs | 4 +- .../ScheduledMessageProcessorTests.cs | 4 +- AsyncMonolith.Tests/SchedulingTests.cs | 14 +- AsyncMonolith.Tests/TestHelpersTests.cs | 4 +- AsyncMonolith/Consumers/ConsumeContext.cs | 2 +- ...cutionMode.cs => ConsumerExecutionMode.cs} | 2 +- .../ConsumerExecutionModeAttribute.cs | 4 +- AsyncMonolith/Consumers/ConsumerMessage.cs | 2 +- .../Consumers/ConsumerMessageProcessor.cs | 4 +- AsyncMonolith/Consumers/ConsumerRegistry.cs | 8 +- AsyncMonolith/Consumers/PoisonedMessage.cs | 2 +- .../Consumers/PoisonedMessageService.cs | 2 +- AsyncMonolith/Producers/IProducerService.cs | 55 +++---- AsyncMonolith/Producers/ProducerService.cs | 76 +++++++--- AsyncMonolith/Scheduling/IScheduleService.cs | 20 +-- AsyncMonolith/Scheduling/ScheduleService.cs | 34 ++--- AsyncMonolith/Scheduling/ScheduledMessage.cs | 26 ++-- .../Scheduling/ScheduledMessageProcessor.cs | 4 +- AsyncMonolith/Utilities/StartupExtensions.cs | 7 +- .../Components/Pages/PoisonedMessages.razor | 2 +- .../Components/Pages/ScheduledMessages.razor | 2 +- Example/Example.Api/Spam/SpamController.cs | 2 +- README.md | 2 +- docs/guides/consuming-messages.md | 2 +- docs/guides/producing-messages.md | 18 +-- docs/quickstart.md | 2 +- docs/releases.md | 2 + 43 files changed, 350 insertions(+), 315 deletions(-) rename AsyncMonolith/Consumers/{ExecutionMode.cs => ConsumerExecutionMode.cs} (92%) diff --git a/AsyncMonolith.TestHelpers/FakeProducerService.cs b/AsyncMonolith.TestHelpers/FakeProducerService.cs index 9470b19..4efe776 100644 --- a/AsyncMonolith.TestHelpers/FakeProducerService.cs +++ b/AsyncMonolith.TestHelpers/FakeProducerService.cs @@ -1,13 +1,13 @@ using System.Text.Json; using AsyncMonolith.Consumers; using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; namespace AsyncMonolith.TestHelpers; /// -/// Represents a fake implementation of the interface for testing purposes. +/// An that records produced messages in +/// instead of writing them to a database. /// public class FakeProducerService : IProducerService { @@ -15,12 +15,7 @@ public class FakeProducerService : IProducerService private readonly IAsyncMonolithIdGenerator _idGenerator; private readonly TimeProvider _timeProvider; - /// - /// Initializes a new instance of the class. - /// - /// The time provider. - /// The consumer registry. - /// The ID generator. + /// Initializes a new instance of the class. public FakeProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, IAsyncMonolithIdGenerator idGenerator) { @@ -29,117 +24,61 @@ public FakeProducerService(TimeProvider timeProvider, ConsumerRegistry consumerR _idGenerator = idGenerator ?? throw new ArgumentNullException(nameof(idGenerator)); } - /// - /// Gets or sets the list of consumer messages created by the producer service. - /// - public List CreatedConsumerMessages { get; set; } = new List(); + /// The messages produced so far, one per consumer. + public List CreatedConsumerMessages { get; } = []; - /// - /// Produces a single consumer message. - /// - /// The type of the consumer payload. - /// The consumer payload message. - /// The available after timestamp (in Unix time) for the consumer message. - /// The insert ID for the consumer message. - /// The cancellation token. - /// A task representing the asynchronous operation. - public Task Produce(TK message, long? availableAfter = null, string? insertId = null, - CancellationToken cancellationToken = default) - where TK : IConsumerPayload - { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - var payload = JsonSerializer.Serialize(message); - insertId ??= _idGenerator.GenerateId(); - var payloadType = AsyncMonolithNames.ForPayload(); - - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(payloadType)) - { - CreatedConsumerMessages.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = availableAfter.Value, - ConsumerType = consumerId, - PayloadType = payloadType, - Payload = payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } + /// + public Task Produce(TPayload payload, TimeSpan? delay = null, string? deduplicationKey = null, + CancellationToken cancellationToken = default) where TPayload : IConsumerPayload => + Produce(payload, _timeProvider.GetUtcNow() + (delay ?? TimeSpan.Zero), deduplicationKey, cancellationToken); + /// + public Task Produce(TPayload payload, DateTimeOffset availableAt, string? deduplicationKey = null, + CancellationToken cancellationToken = default) where TPayload : IConsumerPayload + { + var payloadType = AsyncMonolithNames.ForPayload(); + var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType) + .Where(c => deduplicationKey is null || !CreatedConsumerMessages.Any(m => + m.DeduplicationKey == deduplicationKey && m.ConsumerType == c)); + Record(payloadType, JsonSerializer.Serialize(payload), consumers, availableAt, + deduplicationKey ?? _idGenerator.GenerateId()); return Task.CompletedTask; } - /// - /// Produces a list of consumer messages. - /// - /// The type of the consumer payload. - /// The list of consumer payload messages. - /// The available after timestamp (in Unix time) for the consumer messages. - /// The cancellation token. - /// A task representing the asynchronous operation. - public Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload + /// + public Task ProduceList(IEnumerable payloads, TimeSpan? delay = null, + CancellationToken cancellationToken = default) where TPayload : IConsumerPayload { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - availableAfter ??= currentTime; - - var payloadType = AsyncMonolithNames.ForPayload(); + var payloadType = AsyncMonolithNames.ForPayload(); var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - foreach (var message in messages) + var availableAt = _timeProvider.GetUtcNow() + (delay ?? TimeSpan.Zero); + foreach (var payload in payloads) { - var insertId = _idGenerator.GenerateId(); - var payload = JsonSerializer.Serialize(message); - - foreach (var consumerId in consumers) - { - CreatedConsumerMessages.Add(new ConsumerMessage - { - Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = availableAfter.Value, - ConsumerType = consumerId, - PayloadType = payloadType, - Payload = payload, - Attempts = 0, - InsertId = insertId, - TraceId = null, - SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) - }); - } + Record(payloadType, JsonSerializer.Serialize(payload), consumers, availableAt, _idGenerator.GenerateId()); } return Task.CompletedTask; } - /// - /// Produces a scheduled consumer message. - /// - /// The scheduled consumer message. - public void Produce(ScheduledMessage message) + private void Record(string payloadType, string payload, IEnumerable consumers, DateTimeOffset availableAt, + string deduplicationKey) { - var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); - var insertId = _idGenerator.GenerateId(); - foreach (var consumerId in _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType)) + var now = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); + foreach (var consumer in consumers) { CreatedConsumerMessages.Add(new ConsumerMessage { Id = _idGenerator.GenerateId(), - CreatedAt = currentTime, - AvailableAfter = currentTime, - ConsumerType = consumerId, - PayloadType = message.PayloadType, - Payload = message.Payload, + CreatedAt = now, + AvailableAfter = Math.Max(now, availableAt.ToUnixTimeSeconds()), + ConsumerType = consumer, + PayloadType = payloadType, + Payload = payload, Attempts = 0, - InsertId = insertId, + DeduplicationKey = deduplicationKey, TraceId = null, SpanId = null, - RailId = _consumerRegistry.ResolveConsumerRailId(consumerId) + RailId = _consumerRegistry.ResolveConsumerRailId(consumer) }); } } diff --git a/AsyncMonolith.TestHelpers/FakeScheduleService.cs b/AsyncMonolith.TestHelpers/FakeScheduleService.cs index 1ebd1fe..8b02218 100644 --- a/AsyncMonolith.TestHelpers/FakeScheduleService.cs +++ b/AsyncMonolith.TestHelpers/FakeScheduleService.cs @@ -43,43 +43,43 @@ public FakeScheduleService(TimeProvider timeProvider, IAsyncMonolithIdGenerator /// /// Schedules a message for future execution. /// - /// The type of the message payload. + /// The type of the message payload. /// The message to schedule. - /// The cron expression for scheduling the message. - /// The timezone for scheduling the message. + /// The cron expression for scheduling the message. + /// The timezone for scheduling the message. /// The optional tag for the scheduled message. /// The ID of the scheduled message. /// Thrown when the cron expression or timezone is invalid. - public string Schedule(TK message, string chronExpression, string chronTimezone, string? tag = null) - where TK : IConsumerPayload + public string Schedule(TPayload message, string cronExpression, string timeZone, string? tag = null) + where TPayload : IConsumerPayload { var payload = JsonSerializer.Serialize(message); var id = _fakeIdGenerator.GenerateId(); - var expression = CronExpression.Parse(chronExpression, CronFormat.IncludeSeconds); + var expression = Cronos.CronExpression.Parse(cronExpression, Cronos.CronFormat.IncludeSeconds); - var timezone = TimeZoneInfo.FindSystemTimeZoneById(chronTimezone); + var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZone); if (timezone == null) { throw new InvalidOperationException( - $"Couldn't determine scheduled message timezone: '{chronTimezone}'"); + $"Couldn't determine scheduled message timezone: '{timeZone}'"); } var next = expression.GetNextOccurrence(_timeProvider.GetUtcNow(), timezone); if (next == null) { throw new InvalidOperationException( - $"Couldn't determine next scheduled message occurrence for cron expression: '{chronExpression}', timezone: '{chronTimezone}'"); + $"Couldn't determine next scheduled message occurrence for cron expression: '{cronExpression}', timezone: '{timeZone}'"); } CreatedScheduledMessages.Add(new ScheduledMessage { Id = id, - PayloadType = AsyncMonolithNames.ForPayload(), + PayloadType = AsyncMonolithNames.ForPayload(), AvailableAfter = next.Value.ToUnixTimeSeconds(), Tag = tag, - ChronExpression = chronExpression, - ChronTimezone = chronTimezone, + CronExpression = cronExpression, + CronTimeZone = timeZone, Payload = payload }); @@ -89,11 +89,11 @@ public string Schedule(TK message, string chronExpression, string chronTimez /// /// Records the schedule, replacing any recorded schedule with the same tag. /// - public Task EnsureSchedule(TK message, string chronExpression, string chronTimezone, string tag, - CancellationToken cancellationToken = default) where TK : IConsumerPayload + public Task EnsureSchedule(TPayload message, string cronExpression, string timeZone, string tag, + CancellationToken cancellationToken = default) where TPayload : IConsumerPayload { CreatedScheduledMessages.RemoveAll(m => m.Tag == tag); - return Task.FromResult(Schedule(message, chronExpression, chronTimezone, tag)); + return Task.FromResult(Schedule(message, cronExpression, timeZone, tag)); } /// diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index d6348a3..5e44fa8 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -44,6 +44,7 @@ public static IServiceCollection AddRealAsyncMonolithBaseServices( { AddBaseServices(services, configure); services.AddSingleton(new AsyncMonolithIdGenerator()); + services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs index 03b27ba..d7efe62 100644 --- a/AsyncMonolith.Tests/ConfigurationTests.cs +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -37,7 +37,7 @@ private static ConsumerRegistry Registry(Action? configure RailId = 0, PayloadType = "payload", Payload = "{}", - InsertId = "insert", + DeduplicationKey = "insert", TraceId = null, SpanId = null }; @@ -146,7 +146,7 @@ public void Consumer_attributes_are_read_at_registration() registry.ResolveConsumerTimeout(nameof(TimeoutConsumer)).ShouldBe(1); registry.ResolveConsumerMaxAttempts(MessageFor(nameof(ExceptionConsumer2Attempts))).ShouldBe(2); registry.ResolveConsumerExecutionMode(nameof(SequentialProbeConsumer)) - .ShouldBe(ConsumerInstanceExecutionMode.Sequential); + .ShouldBe(ConsumerExecutionMode.Sequential); registry.ResolveConsumerRailId(nameof(RailConsumer2)).ShouldBe(2); } @@ -162,7 +162,7 @@ public void Consumers_without_attributes_use_the_defaults() registry.ResolveConsumerTimeout(nameof(ExceptionConsumer)).ShouldBe(42); registry.ResolveConsumerMaxAttempts(MessageFor(nameof(ExceptionConsumer))).ShouldBe(7); registry.ResolveConsumerExecutionMode(nameof(ExceptionConsumer)) - .ShouldBe(ConsumerInstanceExecutionMode.Parallel); + .ShouldBe(ConsumerExecutionMode.Parallel); registry.ResolveConsumerRailId(nameof(ExceptionConsumer)).ShouldBe(0); } @@ -193,7 +193,7 @@ public void Unknown_names_fall_back_or_throw() registry.ResolveConsumerTimeout("UnknownConsumer").ShouldBe(42); registry.ResolveConsumerMaxAttempts(MessageFor("UnknownConsumer")).ShouldBe(7); registry.ResolveConsumerRailId("UnknownConsumer").ShouldBe(0); - registry.ResolveConsumerExecutionMode("UnknownConsumer").ShouldBe(ConsumerInstanceExecutionMode.Parallel); + registry.ResolveConsumerExecutionMode("UnknownConsumer").ShouldBe(ConsumerExecutionMode.Parallel); } [Fact] diff --git a/AsyncMonolith.Tests/ConsumeContextTests.cs b/AsyncMonolith.Tests/ConsumeContextTests.cs index 5046ea5..03c412a 100644 --- a/AsyncMonolith.Tests/ConsumeContextTests.cs +++ b/AsyncMonolith.Tests/ConsumeContextTests.cs @@ -24,7 +24,7 @@ public async Task Context_describes_the_message_and_attempt() { var (host, recorder) = await Host(); await using var _ = host; - await host.Produce(new ContextMessage(), insertId: "order-42"); + await host.Produce(new ContextMessage(), deduplicationKey: "order-42"); var stored = (await host.ConsumerMessages()).ShouldHaveSingleItem(); await host.ConsumerProcessor.ProcessBatch(Ct); @@ -65,7 +65,7 @@ public async Task Consumers_of_one_payload_share_its_deduplication_key() await using var host = await SqliteTestHost.Create(); await host.Produce(new MultiConsumerMessage { Name = "x" }); - (await host.ConsumerMessages()).Select(m => m.InsertId).Distinct().ShouldHaveSingleItem(); + (await host.ConsumerMessages()).Select(m => m.DeduplicationKey).Distinct().ShouldHaveSingleItem(); } [Fact] diff --git a/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs b/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs index 0bf8bab..2aca04d 100644 --- a/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs +++ b/AsyncMonolith.Tests/ConsumerMessageProcessorTests.cs @@ -65,7 +65,7 @@ public async Task ConsumerMessageProcessor_Returns_0_If_No_Available_Messages(Te await producer.Produce(new SingleConsumerMessage { Name = "test-name" - }, FakeTime.GetUtcNow().ToUnixTimeSeconds() + 100, cancellationToken: TestContext.Current.CancellationToken); + }, TimeSpan.FromSeconds(100), cancellationToken: TestContext.Current.CancellationToken); await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs index 3d4083d..e582ff7 100644 --- a/AsyncMonolith.Tests/ConsumerProcessingTests.cs +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -38,7 +38,7 @@ public async Task Empty_queue_processes_nothing() public async Task Message_is_not_consumed_before_it_is_available() { await using var host = await SqliteTestHost.Create(); - await host.Produce(new SingleConsumerMessage { Name = "later" }, host.Now + 60); + await host.Produce(new SingleConsumerMessage { Name = "later" }, TimeSpan.FromSeconds(60)); (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(0); host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(0); @@ -81,7 +81,7 @@ public async Task Message_is_poisoned_after_the_configured_max_attempts() s.MaxAttempts = 3; s.AttemptDelay = TimeSpan.FromSeconds(0); }); - await host.Produce(new ExceptionConsumerMessage { Name = "boom" }, insertId: "insert-1"); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }, deduplicationKey: "insert-1"); var original = (await host.ConsumerMessages()).ShouldHaveSingleItem(); for (var i = 0; i < 3; i++) @@ -98,7 +98,7 @@ public async Task Message_is_poisoned_after_the_configured_max_attempts() poisoned.ConsumerType.ShouldBe(nameof(ExceptionConsumer)); poisoned.PayloadType.ShouldBe(nameof(ExceptionConsumerMessage)); poisoned.Payload.ShouldBe(original.Payload); - poisoned.InsertId.ShouldBe("insert-1"); + poisoned.DeduplicationKey.ShouldBe("insert-1"); poisoned.CreatedAt.ShouldBe(original.CreatedAt); poisoned.AvailableAfter.ShouldBe(original.AvailableAfter, "it records when the message last became due"); poisoned.RailId.ShouldBe(original.RailId); @@ -219,7 +219,7 @@ await host.Change(db => RailId = 0, PayloadType = nameof(OrderedMessage), Payload = System.Text.Json.JsonSerializer.Serialize(new OrderedMessage { Name = name }), - InsertId = id, + DeduplicationKey = id, TraceId = null, SpanId = null }; diff --git a/AsyncMonolith.Tests/ConsumerRegistryTests.cs b/AsyncMonolith.Tests/ConsumerRegistryTests.cs index 7ded874..c2f74a7 100644 --- a/AsyncMonolith.Tests/ConsumerRegistryTests.cs +++ b/AsyncMonolith.Tests/ConsumerRegistryTests.cs @@ -77,7 +77,7 @@ public void ConsumerRegistry_Resolves_ConsumerTimeout_By_ConsumerMessage() PayloadType = default!, Payload = default!, Attempts = default, - InsertId = string.Empty, + DeduplicationKey = string.Empty, TraceId = null, SpanId = null, RailId = 0 @@ -104,7 +104,7 @@ public void ConsumerRegistry_Resolves_ConsumerType() PayloadType = default!, Payload = default!, Attempts = default, - InsertId = string.Empty, + DeduplicationKey = string.Empty, TraceId = null, SpanId = null, RailId = 0 @@ -148,7 +148,7 @@ public void ConsumerRegistry_Resolves_Default_ConsumerAttempts_When_Not_Set() PayloadType = default!, Payload = default!, Attempts = default, - InsertId = string.Empty, + DeduplicationKey = string.Empty, TraceId = null, SpanId = null, RailId = 0 @@ -175,7 +175,7 @@ public void ConsumerRegistry_Resolves_ConsumerAttempts_By_ConsumerMessage() PayloadType = default!, Payload = default!, Attempts = default, - InsertId = string.Empty, + DeduplicationKey = string.Empty, TraceId = null, SpanId = null, RailId = 0 diff --git a/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs b/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs index eda9749..8639db0 100644 --- a/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs +++ b/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs @@ -85,7 +85,7 @@ public async Task EnsureSchedule_recalculates_when_the_expression_or_timezone_ch await Ensure(host, "a", "0 30 10 * * *", timezone: "Europe/London"); var schedule = (await host.ScheduledMessages()).ShouldHaveSingleItem(); - schedule.ChronTimezone.ShouldBe("Europe/London"); + schedule.CronTimeZone.ShouldBe("Europe/London"); schedule.AvailableAfter.ShouldBe(Utc("2020-09-01T09:30:00Z")); } @@ -139,12 +139,12 @@ public async Task Statistics_count_due_waiting_poisoned_and_scheduled_messages() await host.Produce(new SingleConsumerMessage { Name = "due-first" }); host.Time.Advance(TimeSpan.FromSeconds(30)); await host.Produce(new SingleConsumerMessage { Name = "due-second" }); - await host.Produce(new SingleConsumerMessage { Name = "later" }, host.Now + 600); + await host.Produce(new SingleConsumerMessage { Name = "later" }, TimeSpan.FromSeconds(600)); await host.Schedule(new SingleConsumerMessage { Name = "s" }, "0 0 9 * * *"); await host.Change(db => db.PoisonedMessages.Add(new PoisonedMessage { Id = "p", CreatedAt = 0, AvailableAfter = 0, Attempts = 1, ConsumerType = "c", RailId = 0, - PayloadType = "p", Payload = "{}", InsertId = "i", TraceId = null, SpanId = null + PayloadType = "p", Payload = "{}", DeduplicationKey = "i", TraceId = null, SpanId = null })); host.Time.Advance(TimeSpan.FromSeconds(15)); diff --git a/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs index 06c149c..f3cb35c 100644 --- a/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs +++ b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs @@ -87,7 +87,7 @@ public class ParallelProbeMessage : IConsumerPayload { } -[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Parallel)] +[ConsumerExecutionMode(ConsumerExecutionMode.Parallel)] public class ParallelProbeConsumer(ConcurrencyProbe probe) : IConsumer { public Task Consume(ParallelProbeMessage payload, ConsumeContext context, CancellationToken cancellationToken) => @@ -98,7 +98,7 @@ public class SequentialProbeMessage : IConsumerPayload { } -[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Sequential)] +[ConsumerExecutionMode(ConsumerExecutionMode.Sequential)] public class SequentialProbeConsumer(ConcurrencyProbe probe) : IConsumer { public Task Consume(SequentialProbeMessage payload, ConsumeContext context, CancellationToken cancellationToken) => diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs index 0928184..7ba1f5a 100644 --- a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -93,12 +93,12 @@ public static async Task Create(Action? co } /// Produces a message in its own scope and saves it. - public async Task Produce(T payload, long? availableAfter = null, string? insertId = null) + public async Task Produce(T payload, TimeSpan? delay = null, string? deduplicationKey = null) where T : IConsumerPayload { using var scope = Services.CreateScope(); await scope.ServiceProvider.GetRequiredService() - .Produce(payload, availableAfter, insertId); + .Produce(payload, delay, deduplicationKey); await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(); } diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 335b069..06be428 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -46,6 +46,7 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new FakeIdGenerator()); + services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); diff --git a/AsyncMonolith.Tests/ProducerBehaviourTests.cs b/AsyncMonolith.Tests/ProducerBehaviourTests.cs index 47b28a5..8d53a5b 100644 --- a/AsyncMonolith.Tests/ProducerBehaviourTests.cs +++ b/AsyncMonolith.Tests/ProducerBehaviourTests.cs @@ -26,7 +26,7 @@ public async Task Produce_writes_one_pending_message_per_consumer() messages.ShouldAllBe(m => m.PayloadType == nameof(MultiConsumerMessage)); messages.ShouldAllBe(m => m.Attempts == 0); messages.ShouldAllBe(m => m.CreatedAt == host.Now && m.AvailableAfter == host.Now); - messages.Select(m => m.InsertId).Distinct().ShouldHaveSingleItem(); + messages.Select(m => m.DeduplicationKey).Distinct().ShouldHaveSingleItem(); messages.Select(m => m.Id).Distinct().Count().ShouldBe(2); JsonSerializer.Deserialize(messages[0].Payload)!.Name.ShouldBe("hello"); } @@ -36,11 +36,65 @@ public async Task Produce_uses_the_given_availability_and_insert_id() { await using var host = await SqliteTestHost.Create(); - await host.Produce(new SingleConsumerMessage { Name = "x" }, host.Now + 300, "my-insert-id"); + await host.Produce(new SingleConsumerMessage { Name = "x" }, TimeSpan.FromSeconds(300), "my-insert-id"); var message = (await host.ConsumerMessages()).ShouldHaveSingleItem(); message.AvailableAfter.ShouldBe(host.Now + 300); - message.InsertId.ShouldBe("my-insert-id"); + message.DeduplicationKey.ShouldBe("my-insert-id"); + } + + [Fact] + public async Task A_delay_is_rounded_up_to_whole_seconds() + { + await using var host = await SqliteTestHost.Create(); + host.Time.Advance(TimeSpan.FromMilliseconds(400)); + + await host.Produce(new SingleConsumerMessage { Name = "x" }, TimeSpan.FromSeconds(1)); + + // 10:00:00.400 + 1s = 10:00:01.400, never consumed before then, so stored as 10:00:02 + (await host.ConsumerMessages()).ShouldHaveSingleItem().AvailableAfter.ShouldBe(host.Now + 2); + } + + [Fact] + public async Task No_delay_is_available_straight_away_even_mid_second() + { + await using var host = await SqliteTestHost.Create(); + host.Time.Advance(TimeSpan.FromMilliseconds(400)); + + await host.Produce(new SingleConsumerMessage { Name = "x" }); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().AvailableAfter.ShouldBe(host.Now); + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + } + + [Fact] + public async Task Produce_at_a_time_waits_until_then_and_a_past_time_means_now() + { + await using var host = await SqliteTestHost.Create(); + + using (var scope = host.Services.CreateScope()) + { + var producer = scope.ServiceProvider.GetRequiredService(); + await producer.Produce(new OrderedMessage { Name = "future" }, host.Time.GetUtcNow().AddMinutes(5), + cancellationToken: Ct); + await producer.Produce(new OrderedMessage { Name = "past" }, host.Time.GetUtcNow().AddDays(-1), + cancellationToken: Ct); + await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + } + + var messages = await host.ConsumerMessages(); + messages.Single(m => m.Payload.Contains("future", StringComparison.Ordinal)).AvailableAfter + .ShouldBe(host.Now + 300); + messages.Single(m => m.Payload.Contains("past", StringComparison.Ordinal)).AvailableAfter.ShouldBe(host.Now); + } + + [Fact] + public async Task A_negative_delay_is_rejected() + { + await using var host = await SqliteTestHost.Create(); + + await Should.ThrowAsync(() => + host.Produce(new SingleConsumerMessage { Name = "x" }, TimeSpan.FromSeconds(-1))); } [Fact] @@ -61,9 +115,9 @@ public async Task Produce_assigns_each_consumer_its_rail() public async Task Producing_an_insert_id_that_is_already_pending_is_skipped() { await using var host = await SqliteTestHost.Create(); - await host.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key"); + await host.Produce(new SingleConsumerMessage { Name = "first" }, deduplicationKey: "dedupe-key"); - await host.Produce(new SingleConsumerMessage { Name = "second" }, insertId: "dedupe-key"); + await host.Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "dedupe-key"); JsonSerializer.Deserialize((await host.ConsumerMessages()).ShouldHaveSingleItem().Payload)! .Name.ShouldBe("first"); @@ -77,8 +131,8 @@ public async Task Producing_an_insert_id_twice_before_saving_adds_it_once() using (var scope = host.Services.CreateScope()) { var producer = scope.ServiceProvider.GetRequiredService(); - await producer.Produce(new MultiConsumerMessage { Name = "first" }, insertId: "dedupe-key", cancellationToken: Ct); - await producer.Produce(new MultiConsumerMessage { Name = "second" }, insertId: "dedupe-key", cancellationToken: Ct); + await producer.Produce(new MultiConsumerMessage { Name = "first" }, deduplicationKey: "dedupe-key", cancellationToken: Ct); + await producer.Produce(new MultiConsumerMessage { Name = "second" }, deduplicationKey: "dedupe-key", cancellationToken: Ct); await scope.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); } @@ -90,12 +144,12 @@ public async Task Producing_an_insert_id_twice_before_saving_adds_it_once() public async Task Only_consumers_that_already_have_the_insert_id_pending_are_skipped() { await using var host = await SqliteTestHost.Create(); - await host.Produce(new MultiConsumerMessage { Name = "first" }, insertId: "dedupe-key"); + await host.Produce(new MultiConsumerMessage { Name = "first" }, deduplicationKey: "dedupe-key"); // MultiConsumer1 has processed its message; MultiConsumer2's is still pending. await host.Change(db => db.ConsumerMessages.Remove( db.ConsumerMessages.Single(m => m.ConsumerType == nameof(MultiConsumer1)))); - await host.Produce(new MultiConsumerMessage { Name = "second" }, insertId: "dedupe-key"); + await host.Produce(new MultiConsumerMessage { Name = "second" }, deduplicationKey: "dedupe-key"); var messages = await host.ConsumerMessages(); messages.Single(m => m.ConsumerType == nameof(MultiConsumer1)).Payload.ShouldContain("second"); @@ -106,10 +160,10 @@ await host.Change(db => db.ConsumerMessages.Remove( public async Task An_insert_id_can_be_produced_again_once_its_messages_are_consumed() { await using var host = await SqliteTestHost.Create(); - await host.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key"); + await host.Produce(new SingleConsumerMessage { Name = "first" }, deduplicationKey: "dedupe-key"); await host.ConsumerProcessor.ProcessBatch(Ct); - await host.Produce(new SingleConsumerMessage { Name = "again" }, insertId: "dedupe-key"); + await host.Produce(new SingleConsumerMessage { Name = "again" }, deduplicationKey: "dedupe-key"); (await host.ConsumerMessages()).ShouldHaveSingleItem().Payload.ShouldContain("again"); } @@ -123,9 +177,9 @@ public async Task Two_producers_racing_on_one_insert_id_are_stopped_by_the_uniqu // Both check before either has saved await first.ServiceProvider.GetRequiredService() - .Produce(new SingleConsumerMessage { Name = "first" }, insertId: "dedupe-key", cancellationToken: Ct); + .Produce(new SingleConsumerMessage { Name = "first" }, deduplicationKey: "dedupe-key", cancellationToken: Ct); await second.ServiceProvider.GetRequiredService() - .Produce(new SingleConsumerMessage { Name = "second" }, insertId: "dedupe-key", cancellationToken: Ct); + .Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "dedupe-key", cancellationToken: Ct); await first.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); await Should.ThrowAsync(() => @@ -147,8 +201,8 @@ await scope.ServiceProvider.GetRequiredService().ProduceList( var messages = await host.ConsumerMessages(); messages.Count.ShouldBe(4); - messages.GroupBy(m => m.InsertId).ShouldAllBe(g => g.Count() == 2); - messages.Select(m => m.InsertId).Distinct().Count().ShouldBe(2); + messages.GroupBy(m => m.DeduplicationKey).ShouldAllBe(g => g.Count() == 2); + messages.Select(m => m.DeduplicationKey).Distinct().Count().ShouldBe(2); } [Fact] diff --git a/AsyncMonolith.Tests/ProducerServiceDbTests.cs b/AsyncMonolith.Tests/ProducerServiceDbTests.cs index 245b32d..a491a7a 100644 --- a/AsyncMonolith.Tests/ProducerServiceDbTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceDbTests.cs @@ -52,12 +52,12 @@ public Task Produce_writes_the_message_when_the_caller_saves(DbType dbType) => R using var activity = GetActivity(); Activity.Current = activity; - await Produce(services, p => p.Produce(payload, 10, cancellationToken: Ct)); + await Produce(services, p => p.Produce(payload, TimeSpan.FromSeconds(10), cancellationToken: Ct)); using var scope = services.CreateScope(); var message = await scope.ServiceProvider.GetRequiredService() .AssertSingleConsumerMessage(payload); - message.AvailableAfter.ShouldBe(10); + message.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds() + 10); message.Attempts.ShouldBe(0); message.Payload.ShouldBe(JsonSerializer.Serialize(payload)); message.TraceId.ShouldBe(activity?.TraceId.ToString()); @@ -82,22 +82,22 @@ await scope.ServiceProvider.GetRequiredService() public Task ProduceList_writes_one_message_per_payload(DbType dbType) => Run(dbType, async services => { await Produce(services, p => p.ProduceList( - [new SingleConsumerMessage { Name = "a" }, new SingleConsumerMessage { Name = "b" }], 10, + [new SingleConsumerMessage { Name = "a" }, new SingleConsumerMessage { Name = "b" }], TimeSpan.FromSeconds(10), cancellationToken: Ct)); var messages = await Messages(services); messages.Count.ShouldBe(2); - messages.Select(m => m.InsertId).Distinct().Count().ShouldBe(2); - messages.ShouldAllBe(m => m.AvailableAfter == 10); + messages.Select(m => m.DeduplicationKey).Distinct().Count().ShouldBe(2); + messages.ShouldAllBe(m => m.AvailableAfter == FakeTime.GetUtcNow().ToUnixTimeSeconds() + 10); }); [Theory] [MemberData(nameof(GetTestDbTypes))] public Task Produce_skips_an_insert_id_that_is_already_pending(DbType dbType) => Run(dbType, async services => { - await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "first" }, insertId: "key", + await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "first" }, deduplicationKey: "key", cancellationToken: Ct)); - await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "second" }, insertId: "key", + await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "key", cancellationToken: Ct)); (await Messages(services)).ShouldHaveSingleItem().Payload.ShouldContain("first"); @@ -110,9 +110,9 @@ public Task Racing_producers_are_stopped_by_the_unique_index(DbType dbType) => R using var first = services.CreateScope(); using var second = services.CreateScope(); await first.ServiceProvider.GetRequiredService() - .Produce(new SingleConsumerMessage { Name = "first" }, insertId: "key", cancellationToken: Ct); + .Produce(new SingleConsumerMessage { Name = "first" }, deduplicationKey: "key", cancellationToken: Ct); await second.ServiceProvider.GetRequiredService() - .Produce(new SingleConsumerMessage { Name = "second" }, insertId: "key", cancellationToken: Ct); + .Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "key", cancellationToken: Ct); await first.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); await Should.ThrowAsync(() => diff --git a/AsyncMonolith.Tests/ProducerServiceTests.cs b/AsyncMonolith.Tests/ProducerServiceTests.cs index 4ca8350..3841dfa 100644 --- a/AsyncMonolith.Tests/ProducerServiceTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceTests.cs @@ -52,15 +52,15 @@ public async Task Producer_Writes_Single_Consumer_Message() Name = "test-name" }; - var delay = 100; - var insertId = "test-insert_id"; + var delay = TimeSpan.FromSeconds(100); + var deduplicationKey = "test-insert_id"; var producer = serviceProvider.GetRequiredService(); var dbContext = serviceProvider.GetRequiredService(); using var activity = GetActivity(); Activity.Current = activity; // When - await producer.Produce(consumerMessage, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); + await producer.Produce(consumerMessage, delay, deduplicationKey, cancellationToken: TestContext.Current.CancellationToken); await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then @@ -69,13 +69,13 @@ public async Task Producer_Writes_Single_Consumer_Message() var postDbContext = serviceProvider.GetRequiredService(); var message = await postDbContext.AssertSingleConsumerMessage(consumerMessage); - message.AvailableAfter.ShouldBe(delay); + message.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds() + 100); message.Attempts.ShouldBe(0); message.Id.ShouldBe("fake-id-0"); message.ConsumerType = nameof(SingleConsumer); message.PayloadType = nameof(SingleConsumerMessage); message.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage)); - message.InsertId.ShouldBe(insertId); + message.DeduplicationKey.ShouldBe(deduplicationKey); message.TraceId.ShouldBe(activity?.TraceId.ToString()); message.SpanId.ShouldBe(activity?.SpanId.ToString()); } @@ -91,15 +91,15 @@ public async Task Producer_Writes_Multiple_Consumer_Message() Name = "test-name" }; - var delay = 100; - var insertId = "test-insert_id"; + var delay = TimeSpan.FromSeconds(100); + var deduplicationKey = "test-insert_id"; var producer = serviceProvider.GetRequiredService(); var dbContext = serviceProvider.GetRequiredService(); using var activity = GetActivity(); Activity.Current = activity; // When - await producer.Produce(consumerMessage, delay, insertId, cancellationToken: TestContext.Current.CancellationToken); + await producer.Produce(consumerMessage, delay, deduplicationKey, cancellationToken: TestContext.Current.CancellationToken); await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then @@ -108,25 +108,25 @@ public async Task Producer_Writes_Multiple_Consumer_Message() var postDbContext = serviceProvider.GetRequiredService(); var message1 = await postDbContext.AssertSingleConsumerMessage(consumerMessage); - message1.AvailableAfter.ShouldBe(delay); + message1.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds() + 100); message1.Attempts.ShouldBe(0); message1.Id.ShouldBe("fake-id-0"); message1.ConsumerType = nameof(MultiConsumer1); message1.PayloadType = nameof(MultiConsumerMessage); message1.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage)); - message1.InsertId.ShouldBe(insertId); + message1.DeduplicationKey.ShouldBe(deduplicationKey); message1.TraceId.ShouldBe(activity?.TraceId.ToString()); message1.SpanId.ShouldBe(activity?.SpanId.ToString()); var message2 = await postDbContext.AssertSingleConsumerMessage(consumerMessage); - message2.AvailableAfter.ShouldBe(delay); + message2.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds() + 100); message2.Attempts.ShouldBe(0); message2.Id.ShouldBe("fake-id-1"); message2.ConsumerType = nameof(MultiConsumer2); message2.PayloadType = nameof(MultiConsumerMessage); message2.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage)); - message2.InsertId.ShouldBe(insertId); + message2.DeduplicationKey.ShouldBe(deduplicationKey); message2.TraceId.ShouldBe(activity?.TraceId.ToString()); message2.SpanId.ShouldBe(activity?.SpanId.ToString()); } @@ -163,7 +163,7 @@ public async Task Producer_AvailableAfter_Defaults_To_CurrentTime() message.ConsumerType = nameof(SingleConsumer); message.PayloadType = nameof(SingleConsumerMessage); message.Payload.ShouldBe(JsonSerializer.Serialize(consumerMessage)); - message.InsertId.ShouldBe("fake-id-0"); + message.DeduplicationKey.ShouldBe("fake-id-0"); message.TraceId.ShouldBe(activity?.TraceId.ToString()); message.SpanId.ShouldBe(activity?.SpanId.ToString()); } @@ -185,8 +185,8 @@ public async Task Producer_Produces_Single_Scheduled_Message() Id = "test-id", Tag = "test-tag", AvailableAfter = FakeTime.GetUtcNow().ToUnixTimeSeconds(), - ChronExpression = "* * * * *", - ChronTimezone = "", + CronExpression = "* * * * *", + CronTimeZone = "", PayloadType = nameof(SingleConsumerMessage), Payload = expectedPayload }; @@ -197,7 +197,7 @@ public async Task Producer_Produces_Single_Scheduled_Message() Activity.Current = activity; // When - producer.Produce(scheduledMessage); + serviceProvider.GetRequiredService>().ProduceScheduled(scheduledMessage); await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then @@ -208,7 +208,7 @@ public async Task Producer_Produces_Single_Scheduled_Message() await postDbContext.AssertSingleConsumerMessage(consumerMessage); message.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds()); message.Attempts.ShouldBe(0); - message.InsertId.ShouldBe("fake-id-0"); + message.DeduplicationKey.ShouldBe("fake-id-0"); message.Id.ShouldBe("fake-id-1"); message.ConsumerType = nameof(SingleConsumer); message.PayloadType = nameof(SingleConsumerMessage); @@ -234,8 +234,8 @@ public async Task Producer_Produces_Multiple_Scheduled_Message() Id = "test-id", Tag = "test-tag", AvailableAfter = FakeTime.GetUtcNow().ToUnixTimeSeconds(), - ChronExpression = "* * * * *", - ChronTimezone = "UTC", + CronExpression = "* * * * *", + CronTimeZone = "UTC", PayloadType = nameof(MultiConsumerMessage), Payload = payload }; @@ -244,7 +244,7 @@ public async Task Producer_Produces_Multiple_Scheduled_Message() var dbContext = serviceProvider.GetRequiredService(); // When - producer.Produce(scheduledMessage); + serviceProvider.GetRequiredService>().ProduceScheduled(scheduledMessage); await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then @@ -258,7 +258,7 @@ public async Task Producer_Produces_Multiple_Scheduled_Message() await postDbContext.AssertSingleConsumerMessage(consumerMessage); message1.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds()); message1.Attempts.ShouldBe(0); - message1.InsertId.ShouldBe("fake-id-0"); + message1.DeduplicationKey.ShouldBe("fake-id-0"); message1.Id.ShouldBe("fake-id-1"); message1.ConsumerType = nameof(MultiConsumer1); message1.PayloadType = nameof(MultiConsumerMessage); @@ -269,7 +269,7 @@ public async Task Producer_Produces_Multiple_Scheduled_Message() await postDbContext.AssertSingleConsumerMessage(consumerMessage); message2.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds()); message2.Attempts.ShouldBe(0); - message2.InsertId.ShouldBe("fake-id-0"); + message2.DeduplicationKey.ShouldBe("fake-id-0"); message2.Id.ShouldBe("fake-id-2"); message2.ConsumerType = nameof(MultiConsumer2); message2.PayloadType = nameof(MultiConsumerMessage); diff --git a/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs index 985d1f5..02525cb 100644 --- a/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs +++ b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs @@ -161,7 +161,7 @@ public async Task Retry_moves_a_poisoned_message_back_to_the_queue() requeued.Attempts.ShouldBe(0); requeued.AvailableAfter.ShouldBe(host.Now); requeued.Payload.ShouldBe(poisoned.Payload); - requeued.InsertId.ShouldBe(poisoned.InsertId); + requeued.DeduplicationKey.ShouldBe(poisoned.DeduplicationKey); requeued.LastError.ShouldBe(poisoned.LastError); // It is processed again (and, since this consumer always fails, poisoned again) diff --git a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs index 3a4f460..3db8644 100644 --- a/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs @@ -29,8 +29,8 @@ public async Task Fetch_Returns_Batch_Of_Messages(DbType dbType) dbContext.ScheduledMessages.Add(new ScheduledMessage { AvailableAfter = FakeTime.GetUtcNow().ToUnixTimeSeconds(), - ChronExpression = "", - ChronTimezone = "", + CronExpression = "", + CronTimeZone = "", Id = idGenerator.GenerateId(), Payload = "", PayloadType = "", diff --git a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs index 6fbc54f..1e66415 100644 --- a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs +++ b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs @@ -56,7 +56,7 @@ await postDbContext.AssertSingleConsumerMessageById Id = "id", Tag = null, AvailableAfter = 0, - ChronExpression = cron, - ChronTimezone = timezone, + CronExpression = cron, + CronTimeZone = timezone, PayloadType = nameof(SingleConsumerMessage), Payload = "{}" }; @@ -71,8 +71,8 @@ public void UpdateSchedule_changes_the_expression_and_recalculates_availability( message.UpdateSchedule("0 30 10 * * *", "UTC", Clock()); - message.ChronExpression.ShouldBe("0 30 10 * * *"); - message.ChronTimezone.ShouldBe("UTC"); + message.CronExpression.ShouldBe("0 30 10 * * *"); + message.CronTimeZone.ShouldBe("UTC"); message.AvailableAfter.ShouldBe(Utc("2020-08-31T10:30:00Z")); } @@ -97,8 +97,8 @@ public async Task Schedule_stores_the_message_with_its_first_occurrence() var stored = (await host.ScheduledMessages()).ShouldHaveSingleItem(); stored.Id.ShouldBe(id); stored.Tag.ShouldBe("reports"); - stored.ChronExpression.ShouldBe("0 0 9 * * *"); - stored.ChronTimezone.ShouldBe("UTC"); + stored.CronExpression.ShouldBe("0 0 9 * * *"); + stored.CronTimeZone.ShouldBe("UTC"); stored.PayloadType.ShouldBe(nameof(SingleConsumerMessage)); JsonSerializer.Deserialize(stored.Payload)!.Name.ShouldBe("daily"); stored.AvailableAfter.ShouldBe(Utc("2020-09-01T09:00:00Z")); @@ -199,7 +199,7 @@ public async Task Due_schedule_produces_a_message_for_every_consumer_of_the_payl var produced = await host.ConsumerMessages(); produced.Select(m => m.ConsumerType).Order() .ShouldBe([nameof(MultiConsumer1), nameof(MultiConsumer2)]); - produced.Select(m => m.InsertId).Distinct().ShouldHaveSingleItem(); + produced.Select(m => m.DeduplicationKey).Distinct().ShouldHaveSingleItem(); } [Fact] diff --git a/AsyncMonolith.Tests/TestHelpersTests.cs b/AsyncMonolith.Tests/TestHelpersTests.cs index acfd8b5..3daef03 100644 --- a/AsyncMonolith.Tests/TestHelpersTests.cs +++ b/AsyncMonolith.Tests/TestHelpersTests.cs @@ -29,7 +29,7 @@ public async Task FakeProducerService_records_a_message_per_consumer() using var scope = FakeServices().CreateScope(); var producer = (FakeProducerService)scope.ServiceProvider.GetRequiredService(); - await producer.Produce(new MultiConsumerMessage { Name = "x" }, insertId: "insert", cancellationToken: Ct); + await producer.Produce(new MultiConsumerMessage { Name = "x" }, deduplicationKey: "insert", cancellationToken: Ct); await producer.ProduceList([new RailConsumerMessage()], cancellationToken: Ct); producer.CreatedConsumerMessages.Select(m => m.ConsumerType).Order().ShouldBe([ @@ -37,7 +37,7 @@ public async Task FakeProducerService_records_a_message_per_consumer() nameof(RailConsumer0), nameof(RailConsumer1), nameof(RailConsumer2) ]); producer.CreatedConsumerMessages.Where(m => m.PayloadType == nameof(MultiConsumerMessage)) - .ShouldAllBe(m => m.InsertId == "insert"); + .ShouldAllBe(m => m.DeduplicationKey == "insert"); producer.CreatedConsumerMessages.Single(m => m.ConsumerType == nameof(RailConsumer2)).RailId.ShouldBe(2); } diff --git a/AsyncMonolith/Consumers/ConsumeContext.cs b/AsyncMonolith/Consumers/ConsumeContext.cs index 583cb7f..c67288e 100644 --- a/AsyncMonolith/Consumers/ConsumeContext.cs +++ b/AsyncMonolith/Consumers/ConsumeContext.cs @@ -38,7 +38,7 @@ public sealed record ConsumeContext internal static ConsumeContext For(ConsumerMessage message, int maxAttempts) => new() { MessageId = message.Id, - DeduplicationKey = message.InsertId, + DeduplicationKey = message.DeduplicationKey, Attempt = Math.Max(message.Attempts, 1), MaxAttempts = maxAttempts, CreatedAt = DateTimeOffset.FromUnixTimeSeconds(message.CreatedAt), diff --git a/AsyncMonolith/Consumers/ExecutionMode.cs b/AsyncMonolith/Consumers/ConsumerExecutionMode.cs similarity index 92% rename from AsyncMonolith/Consumers/ExecutionMode.cs rename to AsyncMonolith/Consumers/ConsumerExecutionMode.cs index 7edf5ba..9c720ff 100644 --- a/AsyncMonolith/Consumers/ExecutionMode.cs +++ b/AsyncMonolith/Consumers/ConsumerExecutionMode.cs @@ -3,7 +3,7 @@ namespace AsyncMonolith.Consumers; /// /// Determines if multiple consumers of the same type can be executed concurrently on the same processor instance /// -public enum ConsumerInstanceExecutionMode +public enum ConsumerExecutionMode { /// /// Will ensure no more than one instance of each consumer will be running concurrently on each processor instance diff --git a/AsyncMonolith/Consumers/ConsumerExecutionModeAttribute.cs b/AsyncMonolith/Consumers/ConsumerExecutionModeAttribute.cs index e4c8c00..1db7cf1 100644 --- a/AsyncMonolith/Consumers/ConsumerExecutionModeAttribute.cs +++ b/AsyncMonolith/Consumers/ConsumerExecutionModeAttribute.cs @@ -10,7 +10,7 @@ public sealed class ConsumerExecutionModeAttribute : Attribute /// Initializes a new instance of the class with the specified execution mode. /// /// Determines if multiple consumers of the same type can be executed concurrently on the same processor instance. - public ConsumerExecutionModeAttribute(ConsumerInstanceExecutionMode executionMode) + public ConsumerExecutionModeAttribute(ConsumerExecutionMode executionMode) { ExecutionMode = executionMode; } @@ -18,5 +18,5 @@ public ConsumerExecutionModeAttribute(ConsumerInstanceExecutionMode executionMod /// /// Determines if multiple consumers of the same type can be executed concurrently on the same processor instance. /// - public ConsumerInstanceExecutionMode ExecutionMode { get; } + public ConsumerExecutionMode ExecutionMode { get; } } \ No newline at end of file diff --git a/AsyncMonolith/Consumers/ConsumerMessage.cs b/AsyncMonolith/Consumers/ConsumerMessage.cs index 08bcf4e..e8d8a2d 100644 --- a/AsyncMonolith/Consumers/ConsumerMessage.cs +++ b/AsyncMonolith/Consumers/ConsumerMessage.cs @@ -73,7 +73,7 @@ public sealed class ConsumerMessage /// [JsonPropertyName("insert_id")] [Column("insert_id")] - public required string InsertId { get; set; } + public required string DeduplicationKey { get; set; } /// /// Gets or sets the trace Id of the activity that produced the consumer message. diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 859390f..e94b94f 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -116,7 +116,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) var group = consumerMessageGroup.ToList(); var executionMode = _consumerRegistry.ResolveConsumerExecutionMode(consumerMessageGroup.Key); - if (executionMode == ConsumerInstanceExecutionMode.Parallel) + if (executionMode == ConsumerExecutionMode.Parallel) { // Parallel: all messages in the group are processed concurrently tasks.Add(Task.WhenAll(group.Select(m => ProcessAndComplete(m, cancellationToken))) @@ -241,7 +241,7 @@ await leased.ExecuteUpdateAsync(s => s CreatedAt = message.CreatedAt, Payload = message.Payload, PayloadType = message.PayloadType, - InsertId = message.InsertId, + DeduplicationKey = message.DeduplicationKey, TraceId = message.TraceId, SpanId = message.SpanId, RailId = message.RailId, diff --git a/AsyncMonolith/Consumers/ConsumerRegistry.cs b/AsyncMonolith/Consumers/ConsumerRegistry.cs index 5ef095d..6318f98 100644 --- a/AsyncMonolith/Consumers/ConsumerRegistry.cs +++ b/AsyncMonolith/Consumers/ConsumerRegistry.cs @@ -30,7 +30,7 @@ public sealed class ConsumerRegistry /// /// Gets the dictionary that maps consumer names to their associated app instance execution mode. /// - public IReadOnlyDictionary ConsumerExecutionModeDictionary { get; } + public IReadOnlyDictionary ConsumerExecutionModeDictionary { get; } /// /// Gets the dictionary that maps consumer names to their associated types. @@ -60,7 +60,7 @@ public ConsumerRegistry(IReadOnlyDictionary consumerTypeDictionary IReadOnlyDictionary consumerTimeoutDictionary, IReadOnlyDictionary consumerAttemptsDictionary, IReadOnlyDictionary consumerRailIdDictionary, - IReadOnlyDictionary consumerExecutionModeDictionary, + IReadOnlyDictionary consumerExecutionModeDictionary, AsyncMonolithOptions settings) { ConsumerTypeDictionary = consumerTypeDictionary; @@ -175,9 +175,9 @@ public List ResolveConsumerRailIds(IEnumerable consumerTypes) /// /// /// - public ConsumerInstanceExecutionMode ResolveConsumerExecutionMode(string consumerType) + public ConsumerExecutionMode ResolveConsumerExecutionMode(string consumerType) { - return ConsumerExecutionModeDictionary.GetValueOrDefault(consumerType, ConsumerInstanceExecutionMode.Parallel); + return ConsumerExecutionModeDictionary.GetValueOrDefault(consumerType, ConsumerExecutionMode.Parallel); } /// diff --git a/AsyncMonolith/Consumers/PoisonedMessage.cs b/AsyncMonolith/Consumers/PoisonedMessage.cs index 4b7736b..a6331f2 100644 --- a/AsyncMonolith/Consumers/PoisonedMessage.cs +++ b/AsyncMonolith/Consumers/PoisonedMessage.cs @@ -73,7 +73,7 @@ public sealed class PoisonedMessage /// [JsonPropertyName("insert_id")] [Column("insert_id")] - public required string InsertId { get; set; } + public required string DeduplicationKey { get; set; } /// /// Gets or sets the trace Id of the activity that produced the consumer message. diff --git a/AsyncMonolith/Consumers/PoisonedMessageService.cs b/AsyncMonolith/Consumers/PoisonedMessageService.cs index 0c195cb..2aff881 100644 --- a/AsyncMonolith/Consumers/PoisonedMessageService.cs +++ b/AsyncMonolith/Consumers/PoisonedMessageService.cs @@ -110,7 +110,7 @@ private void Requeue(PoisonedMessage poisoned) RailId = poisoned.RailId, PayloadType = poisoned.PayloadType, Payload = poisoned.Payload, - InsertId = poisoned.InsertId, + DeduplicationKey = poisoned.DeduplicationKey, TraceId = poisoned.TraceId, SpanId = poisoned.SpanId, LastError = poisoned.LastError diff --git a/AsyncMonolith/Producers/IProducerService.cs b/AsyncMonolith/Producers/IProducerService.cs index 1dd7b2c..f85639c 100644 --- a/AsyncMonolith/Producers/IProducerService.cs +++ b/AsyncMonolith/Producers/IProducerService.cs @@ -1,40 +1,47 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; +using AsyncMonolith.Consumers; namespace AsyncMonolith.Producers; /// -/// Interface for producing messages. +/// Produces messages for consumers. Messages are added to your DbContext and written when you call +/// SaveChanges, in the same transaction as your other changes. /// public interface IProducerService { /// - /// Produces a single message + /// Produces a message for every consumer of . /// - /// The type of the message. - /// The message to produce. - /// The time in seconds after which the message should be available for consumption. - /// The insert ID for the message. - /// Cancellation Token - /// A task representing the asynchronous operation. - public Task Produce(TK message, long? availableAfter = null, string? insertId = null, + /// The payload. + /// How long to wait before the message is consumed. Null means straight away. + /// + /// Skips consumers that already have a pending message with this key. Leave null to always produce. + /// + /// The cancellation token. + Task Produce(TPayload payload, TimeSpan? delay = null, string? deduplicationKey = null, CancellationToken cancellationToken = default) - where TK : IConsumerPayload; + where TPayload : IConsumerPayload; /// - /// Produces a list of messages of type TK. + /// Produces a message for every consumer of , to be consumed at or after + /// . /// - /// The type of the messages. - /// The list of messages to produce. - /// The time in seconds after which the messages should be available for consumption. - /// Cancellation Token - /// A task representing the asynchronous operation. - public Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload; + /// The payload. + /// The earliest time the message is consumed. + /// + /// Skips consumers that already have a pending message with this key. Leave null to always produce. + /// + /// The cancellation token. + Task Produce(TPayload payload, DateTimeOffset availableAt, string? deduplicationKey = null, + CancellationToken cancellationToken = default) + where TPayload : IConsumerPayload; /// - /// Produces a scheduled message. + /// Produces a message per payload for every consumer of . /// - /// The scheduled message to produce. - public void Produce(ScheduledMessage message); -} \ No newline at end of file + /// The payloads. + /// How long to wait before the messages are consumed. Null means straight away. + /// The cancellation token. + Task ProduceList(IEnumerable payloads, TimeSpan? delay = null, + CancellationToken cancellationToken = default) + where TPayload : IConsumerPayload; +} diff --git a/AsyncMonolith/Producers/ProducerService.cs b/AsyncMonolith/Producers/ProducerService.cs index 906bd69..f85655e 100644 --- a/AsyncMonolith/Producers/ProducerService.cs +++ b/AsyncMonolith/Producers/ProducerService.cs @@ -33,54 +33,84 @@ public ProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegis _idGenerator = idGenerator; } - public async Task Produce(TK message, long? availableAfter = null, string? insertId = null, + public Task Produce(TPayload payload, TimeSpan? delay = null, string? deduplicationKey = null, CancellationToken cancellationToken = default) - where TK : IConsumerPayload + where TPayload : IConsumerPayload => + Produce(payload, AvailableAfter(delay), deduplicationKey, cancellationToken); + + public Task Produce(TPayload payload, DateTimeOffset availableAt, string? deduplicationKey = null, + CancellationToken cancellationToken = default) + where TPayload : IConsumerPayload => + Produce(payload, ToStoredTime(availableAt), deduplicationKey, cancellationToken); + + public Task ProduceList(IEnumerable payloads, TimeSpan? delay = null, + CancellationToken cancellationToken = default) where TPayload : IConsumerPayload + { + ArgumentNullException.ThrowIfNull(payloads); + var payloadType = AsyncMonolithNames.ForPayload(); + var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); + var availableAfter = AvailableAfter(delay); + foreach (var payload in payloads) + { + Add(payloadType, JsonSerializer.Serialize(payload), consumers, availableAfter, _idGenerator.GenerateId(), + Activity.Current); + } + + return Task.CompletedTask; + } + + /// Produces the message for a due schedule. Used by the scheduled message processor. + internal void ProduceScheduled(ScheduledMessage message) + { + Add(message.PayloadType, message.Payload, _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType), + null, _idGenerator.GenerateId(), null); + } + + private async Task Produce(TPayload payload, long availableAfter, string? deduplicationKey, + CancellationToken cancellationToken) where TPayload : IConsumerPayload { - var payloadType = AsyncMonolithNames.ForPayload(); + var payloadType = AsyncMonolithNames.ForPayload(); var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - if (insertId is not null) + if (deduplicationKey is not null) { - var pending = await PendingConsumers(insertId, consumers, cancellationToken); + var pending = await PendingConsumers(deduplicationKey, consumers, cancellationToken); consumers = consumers.Where(c => !pending.Contains(c)).ToList(); } - Add(payloadType, JsonSerializer.Serialize(message), consumers, availableAfter, - insertId ?? _idGenerator.GenerateId(), Activity.Current); + Add(payloadType, JsonSerializer.Serialize(payload), consumers, availableAfter, + deduplicationKey ?? _idGenerator.GenerateId(), Activity.Current); } - public Task ProduceList(List messages, long? availableAfter = null, - CancellationToken cancellationToken = default) where TK : IConsumerPayload + private long AvailableAfter(TimeSpan? delay) { - var payloadType = AsyncMonolithNames.ForPayload(); - var consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); - foreach (var message in messages) + if (delay < TimeSpan.Zero) { - Add(payloadType, JsonSerializer.Serialize(message), consumers, availableAfter, _idGenerator.GenerateId(), - Activity.Current); + throw new ArgumentOutOfRangeException(nameof(delay), delay, "The delay must not be negative."); } - return Task.CompletedTask; + return ToStoredTime(_timeProvider.GetUtcNow() + (delay ?? TimeSpan.Zero)); } - public void Produce(ScheduledMessage message) + // Stored times are whole seconds. A future time is rounded up, so a message is never consumed before it was + // asked to be; a time that has already passed is stored as now, so the message is available straight away. + private long ToStoredTime(DateTimeOffset time) { - Add(message.PayloadType, message.Payload, _consumerRegistry.ResolvePayloadConsumerTypes(message.PayloadType), - null, _idGenerator.GenerateId(), null); + var now = _timeProvider.GetUtcNow(); + return time <= now ? now.ToUnixTimeSeconds() : (time.ToUnixTimeMilliseconds() + 999) / 1000; } - private async Task> PendingConsumers(string insertId, IReadOnlyList consumers, + private async Task> PendingConsumers(string deduplicationKey, IReadOnlyList consumers, CancellationToken cancellationToken) { var set = _dbContext.Set(); var pending = set.Local - .Where(m => m.InsertId == insertId && consumers.Contains(m.ConsumerType)) + .Where(m => m.DeduplicationKey == deduplicationKey && consumers.Contains(m.ConsumerType)) .Select(m => m.ConsumerType) .ToHashSet(); var saved = await set.AsNoTracking() - .Where(m => m.InsertId == insertId && consumers.Contains(m.ConsumerType)) + .Where(m => m.DeduplicationKey == deduplicationKey && consumers.Contains(m.ConsumerType)) .Select(m => m.ConsumerType) .ToListAsync(cancellationToken); pending.UnionWith(saved); @@ -88,7 +118,7 @@ private async Task> PendingConsumers(string insertId, IReadOnlyL } private void Add(string payloadType, string payload, IEnumerable consumers, long? availableAfter, - string insertId, Activity? activity) + string deduplicationKey, Activity? activity) { var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); var set = _dbContext.Set(); @@ -104,7 +134,7 @@ private void Add(string payloadType, string payload, IEnumerable consume RailId = _consumerRegistry.ResolveConsumerRailId(consumer), PayloadType = payloadType, Payload = payload, - InsertId = insertId, + DeduplicationKey = deduplicationKey, TraceId = activity?.TraceId.ToString(), SpanId = activity?.SpanId.ToString() }); diff --git a/AsyncMonolith/Scheduling/IScheduleService.cs b/AsyncMonolith/Scheduling/IScheduleService.cs index f54cd3c..d42709e 100644 --- a/AsyncMonolith/Scheduling/IScheduleService.cs +++ b/AsyncMonolith/Scheduling/IScheduleService.cs @@ -10,14 +10,14 @@ public interface IScheduleService /// /// Schedules a message. /// - /// The type of the message. + /// The type of the message. /// The message to schedule. - /// The cron expression. - /// The timezone for the cron expression. + /// The cron expression. + /// The timezone for the cron expression. /// The optional tag for the scheduled message. /// The ID of the scheduled message. - public string Schedule(TK message, string chronExpression, string chronTimezone, string? tag = null) - where TK : IConsumerPayload; + public string Schedule(TPayload message, string cronExpression, string timeZone, string? tag = null) + where TPayload : IConsumerPayload; /// /// Creates the schedule with this tag, or updates it if it already exists, so it can be called at every @@ -25,15 +25,15 @@ public string Schedule(TK message, string chronExpression, string chronTimez /// recalculated. Extra schedules with the same tag are deleted. Changes are tracked, not saved: call /// SaveChanges on your DbContext. /// - /// The type of the message payload. + /// The type of the message payload. /// The message payload. - /// The cron expression, including seconds. - /// The timezone the expression is evaluated in. + /// The cron expression, including seconds. + /// The timezone the expression is evaluated in. /// The tag that identifies this schedule. /// The cancellation token. /// The id of the schedule. - public Task EnsureSchedule(TK message, string chronExpression, string chronTimezone, string tag, - CancellationToken cancellationToken = default) where TK : IConsumerPayload; + public Task EnsureSchedule(TPayload message, string cronExpression, string timeZone, string tag, + CancellationToken cancellationToken = default) where TPayload : IConsumerPayload; /// /// Deletes scheduled messages by tag. diff --git a/AsyncMonolith/Scheduling/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index 456978d..c93d188 100644 --- a/AsyncMonolith/Scheduling/ScheduleService.cs +++ b/AsyncMonolith/Scheduling/ScheduleService.cs @@ -32,41 +32,41 @@ public ScheduleService(TimeProvider timeProvider, T dbContext, IAsyncMonolithIdG /// /// Schedules a message. /// - /// The type of the message. + /// The type of the message. /// The message to schedule. - /// The cron expression for scheduling. - /// The timezone for scheduling. + /// The cron expression for scheduling. + /// The timezone for scheduling. /// The optional tag for the scheduled message. /// The ID of the scheduled message. - public string Schedule(TK message, string chronExpression, string chronTimezone, string? tag = null) - where TK : IConsumerPayload + public string Schedule(TPayload message, string cronExpression, string timeZone, string? tag = null) + where TPayload : IConsumerPayload { var payload = JsonSerializer.Serialize(message); var id = _idGenerator.GenerateId(); - var expression = CronExpression.Parse(chronExpression, CronFormat.IncludeSeconds); + var expression = Cronos.CronExpression.Parse(cronExpression, Cronos.CronFormat.IncludeSeconds); - var timezone = TimeZoneInfo.FindSystemTimeZoneById(chronTimezone); + var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZone); if (timezone == null) { - throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{chronTimezone}'"); + throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{timeZone}'"); } var next = expression.GetNextOccurrence(_timeProvider.GetUtcNow(), timezone); if (next == null) { throw new InvalidOperationException( - $"Couldn't determine next scheduled message occurrence for chron expression: '{chronExpression}', timezone: '{chronTimezone}'"); + $"Couldn't determine next scheduled message occurrence for chron expression: '{cronExpression}', timezone: '{timeZone}'"); } _dbContext.Set().Add(new ScheduledMessage { Id = id, - PayloadType = AsyncMonolithNames.ForPayload(), + PayloadType = AsyncMonolithNames.ForPayload(), AvailableAfter = next.Value.ToUnixTimeSeconds(), Tag = tag, - ChronExpression = chronExpression, - ChronTimezone = chronTimezone, + CronExpression = cronExpression, + CronTimeZone = timeZone, Payload = payload }); @@ -74,8 +74,8 @@ public string Schedule(TK message, string chronExpression, string chronTimez } /// - public async Task EnsureSchedule(TK message, string chronExpression, string chronTimezone, - string tag, CancellationToken cancellationToken = default) where TK : IConsumerPayload + public async Task EnsureSchedule(TPayload message, string cronExpression, string timeZone, + string tag, CancellationToken cancellationToken = default) where TPayload : IConsumerPayload { ArgumentException.ThrowIfNullOrWhiteSpace(tag); @@ -83,16 +83,16 @@ public async Task EnsureSchedule(TK message, string chronExpression, var existing = await set.Where(m => m.Tag == tag).OrderBy(m => m.Id).ToListAsync(cancellationToken); if (existing.Count == 0) { - return Schedule(message, chronExpression, chronTimezone, tag); + return Schedule(message, cronExpression, timeZone, tag); } var schedule = existing[0]; set.RemoveRange(existing.Skip(1)); schedule.UpdatePayload(message); - if (schedule.ChronExpression != chronExpression || schedule.ChronTimezone != chronTimezone) + if (schedule.CronExpression != cronExpression || schedule.CronTimeZone != timeZone) { - schedule.UpdateSchedule(chronExpression, chronTimezone, _timeProvider); + schedule.UpdateSchedule(cronExpression, timeZone, _timeProvider); } return schedule.Id; diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index 266a338..f818932 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessage.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessage.cs @@ -40,14 +40,14 @@ public class ScheduledMessage /// [JsonPropertyName("chron_expression")] [Column("chron_expression")] - public required string ChronExpression { get; set; } + public required string CronExpression { get; set; } /// /// Gets or sets the cron timezone of the scheduled message. /// [JsonPropertyName("chron_timezone")] [Column("chron_timezone")] - public required string ChronTimezone { get; set; } + public required string CronTimeZone { get; set; } /// /// Gets or sets the payload type of the scheduled message. @@ -70,12 +70,12 @@ public class ScheduledMessage /// The next occurrence of the scheduled message in Unix timestamp format. public long GetNextOccurrence(TimeProvider timeProvider) { - var expression = CronExpression.Parse(ChronExpression, CronFormat.IncludeSeconds); + var expression = Cronos.CronExpression.Parse(CronExpression, Cronos.CronFormat.IncludeSeconds); - var timezone = TimeZoneInfo.FindSystemTimeZoneById(ChronTimezone); + var timezone = TimeZoneInfo.FindSystemTimeZoneById(CronTimeZone); if (timezone == null) { - throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{ChronTimezone}'"); + throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{CronTimeZone}'"); } var next = expression.GetNextOccurrence(timeProvider.GetUtcNow(), timezone); @@ -90,25 +90,25 @@ public long GetNextOccurrence(TimeProvider timeProvider) /// /// Updates the schedule of the scheduled message. /// - /// The new cron expression. - /// The new cron timezone. + /// The new cron expression. + /// The new cron timezone. /// The time provider. - public void UpdateSchedule(string chronExpression, string chronTimezone, TimeProvider timeProvider) + public void UpdateSchedule(string cronExpression, string timeZone, TimeProvider timeProvider) { - ChronExpression = chronExpression; - ChronTimezone = chronTimezone; + CronExpression = cronExpression; + CronTimeZone = timeZone; AvailableAfter = GetNextOccurrence(timeProvider); } /// /// Updates the payload of the scheduled message. /// - /// The type of the payload. + /// The type of the payload. /// The payload message. - public void UpdatePayload(TK message) where TK : IConsumerPayload + public void UpdatePayload(TPayload message) where TPayload : IConsumerPayload { var payload = JsonSerializer.Serialize(message); Payload = payload; - PayloadType = AsyncMonolithNames.ForPayload(); + PayloadType = AsyncMonolithNames.ForPayload(); } } \ No newline at end of file diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index c021501..7f84f5c 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -79,7 +79,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa { using var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); - var producer = scope.ServiceProvider.GetRequiredService(); + var producer = scope.ServiceProvider.GetRequiredService>(); var currentTime = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); var processedScheduledMessageCount = 0; await using var dbContextTransaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); @@ -113,7 +113,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa continue; } - producer.Produce(message); + producer.ProduceScheduled(message); processedScheduledMessageCount++; } diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 6275070..adf9c39 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -22,7 +22,7 @@ public static class StartupExtensions public static ModelBuilder ConfigureAsyncMonolith(this ModelBuilder modelBuilder) { modelBuilder.Entity() - .HasIndex(e => new { e.InsertId, e.ConsumerType }) + .HasIndex(e => new { e.DeduplicationKey, e.ConsumerType }) .IsUnique(); return modelBuilder; @@ -59,6 +59,7 @@ internal static AsyncMonolithBuilder InternalAddAsyncMonolith( // TryAdd, so a host can register its own implementation before or instead of these. services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(); + services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); @@ -145,7 +146,7 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass var payloadConsumerDictionary = new Dictionary>(); var consumerTimeoutDictionary = new Dictionary(); var consumerAttemptsDictionary = new Dictionary(); - var consumerExecutionModeDictionary = new Dictionary(); + var consumerExecutionModeDictionary = new Dictionary(); var payloadTypeDictionary = new Dictionary(); var consumerRailIdDictionary = new Dictionary(); @@ -185,7 +186,7 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass consumerAttemptsDictionary[consumerName] = maxAttempts; - var consumerExecutionMode = ConsumerInstanceExecutionMode.Parallel; + var consumerExecutionMode = ConsumerExecutionMode.Parallel; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerExecutionModeAttribute)); if (attribute is ConsumerExecutionModeAttribute executionModeAttribute) { diff --git a/Example/AsyncMonolith.Web/Components/Pages/PoisonedMessages.razor b/Example/AsyncMonolith.Web/Components/Pages/PoisonedMessages.razor index 7ca99e6..1579019 100644 --- a/Example/AsyncMonolith.Web/Components/Pages/PoisonedMessages.razor +++ b/Example/AsyncMonolith.Web/Components/Pages/PoisonedMessages.razor @@ -38,7 +38,7 @@ @msg.Attempts @DateTimeOffset.FromUnixTimeSeconds(msg.AvailableAfter).ToString("HH:mm:ss") @msg.RailId - @msg.InsertId + @msg.DeduplicationKey @(expandedIds.Contains(msg.Id) ? "−" : "+") diff --git a/Example/AsyncMonolith.Web/Components/Pages/ScheduledMessages.razor b/Example/AsyncMonolith.Web/Components/Pages/ScheduledMessages.razor index 5eca844..1eb5baa 100644 --- a/Example/AsyncMonolith.Web/Components/Pages/ScheduledMessages.razor +++ b/Example/AsyncMonolith.Web/Components/Pages/ScheduledMessages.razor @@ -38,7 +38,7 @@ @msg.PayloadType @DateTimeOffset.FromUnixTimeSeconds(msg.AvailableAfter).ToString("HH:mm:ss") - @msg.ChronExpression (@msg.ChronTimezone) + @msg.CronExpression (@msg.CronTimeZone) @(expandedIds.Contains(msg.Id) ? "−" : "+") diff --git a/Example/Example.Api/Spam/SpamController.cs b/Example/Example.Api/Spam/SpamController.cs index ad5e0e0..40ef69c 100644 --- a/Example/Example.Api/Spam/SpamController.cs +++ b/Example/Example.Api/Spam/SpamController.cs @@ -57,7 +57,7 @@ public async Task Spam([FromQuery(Name = "count")] int count, Can await _producerService.Produce(new SpamMessage { Last = true - }, 10, cancellationToken: cancellationToken); + }, cancellationToken: cancellationToken); return Ok("Started."); } diff --git a/README.md b/README.md index 863b8b5..867053d 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Producing and scheduling messages await _producerService.Produce(new UserDeleted() { Id = id - }, 60); + }, TimeSpan.FromSeconds(60)); // Publish 'CacheRefreshScheduled' every Monday at 12pm (UTC) with a tag that can be used to modify / delete related scheduled messages. _scheduleService.Schedule(new CacheRefreshScheduled diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 15db69f..ad3454d 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -37,7 +37,7 @@ Messages are taken roughly oldest first, but **delivery order is not guaranteed* - `created_at` is stored in whole seconds. Messages created in the same second are taken in `id` order, and ids are random, so their order is effectively arbitrary. - A failed message is retried later, after messages that were created after it. -- Messages in a batch run in parallel by default. `[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Sequential)]` only runs one consumer's messages one at a time **within a batch on one processor**. It doesn't order them across batches, retries, rails or app instances. +- Messages in a batch run in parallel by default. `[ConsumerExecutionMode(ConsumerExecutionMode.Sequential)]` only runs one consumer's messages one at a time **within a batch on one processor**. It doesn't order them across batches, retries, rails or app instances. Design consumers so the order of messages doesn't matter, for example by checking the current state of the data rather than relying on earlier messages having run. diff --git a/docs/guides/producing-messages.md b/docs/guides/producing-messages.md index 8065e4e..deb1e24 100644 --- a/docs/guides/producing-messages.md +++ b/docs/guides/producing-messages.md @@ -38,7 +38,7 @@ You can produce messages to be consumed immediately like this: The message is added to your `DbContext` and written when you call `SaveChangesAsync`, in the same transaction as your other changes. If you never save, or the save fails, no message is written. This works the same with every database package. Learn more about the [Transactional Outbox](../transactional-outbox) pattern. ## Delayed messages -You can produce messages to be consumed after a delay by specifying the number of seconds to wait before a consumer should process the message. +You can produce messages to be consumed after a delay by passing a `TimeSpan`, or at a set time by passing a `DateTimeOffset`. Times are stored in whole seconds and rounded up, so a message is never consumed early. ```csharp order.Cancel(); @@ -47,7 +47,7 @@ You can produce messages to be consumed after a delay by specifying the number o { OrderId = order.Id, CancelledAt = _timeProvider.UtcNow() - }, 60); + }, TimeSpan.FromSeconds(60)); // Save changes await _dbContext.SaveChangesAsync(cancellationToken); @@ -63,20 +63,20 @@ Deduplicated messages are useful when you may emit the same message multiple tim await _producerService.Produce(new PageViewed() { PageId = pageView.Id, - }, 10, $"page_id:{pageView.Id}"); + }, TimeSpan.FromSeconds(10), $"page_id:{pageView.Id}"); // Save changes await _dbContext.SaveChangesAsync(cancellationToken); ``` -How deduplication works: +How deduplication works (the key is stored in the `insert_id` column): -- **While pending only.** If a consumer already has a pending message with this insert id (saved, or produced on the same `DbContext` and not yet saved), that consumer is skipped. Once its message has been consumed or poisoned, the same insert id is accepted again. It is not a permanent idempotency key. -- **Per consumer.** For a payload with several consumers, only the consumers that already have the insert id pending are skipped. -- **Concurrent producers.** Two requests producing the same insert id at the same moment, in separate transactions, can both pass the check. The unique index on `(insert_id, consumer_type)` then stops the second, and its `SaveChangesAsync` throws `DbUpdateException`. +- **While pending only.** If a consumer already has a pending message with this deduplication key (saved, or produced on the same `DbContext` and not yet saved), that consumer is skipped. Once its message has been consumed or poisoned, the same key is accepted again. It is not a permanent idempotency key. +- **Per consumer.** For a payload with several consumers, only the consumers that already have the key pending are skipped. +- **Concurrent producers.** Two requests producing the same deduplication key at the same moment, in separate transactions, can both pass the check. The unique index on `(insert_id, consumer_type)` then stops the second, and its `SaveChangesAsync` throws `DbUpdateException`. Summary - **Transactional Persistence**: Produce messages along with changes to your `DbContext` before calling `SaveChangesAsync`, ensuring your domain changes and the messages they produce are persisted transactionally. Nothing is written until you save. -- **Delay**: Specify the number of seconds a message should remain in the queue before it is processed by a consumer. -- **Deduplication**: By specifying an `insert_id`, a consumer that already has a pending message with that `insert_id` is skipped. This is useful when you need a process to take place an amount of time after the first action in a sequence occurred. +- **Delay**: Pass a `TimeSpan` delay or a `DateTimeOffset` to control when a message is consumed. +- **Deduplication**: By passing a `deduplicationKey`, a consumer that already has a pending message with that key is skipped. It is stored in the `insert_id` column. This is useful when you need a process to take place an amount of time after the first action in a sequence occurred. diff --git a/docs/quickstart.md b/docs/quickstart.md index e65677a..173d821 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -149,7 +149,7 @@ Produce / schedule messages await _producerService.Produce(new ValueSubmitted() { Value = newValue - }, 10, $"user:{userId}"); + }, TimeSpan.FromSeconds(10), $"user:{userId}"); // Publish a message every Monday at 12pm (UTC) with a tag that can be used to modify / delete related scheduled messages. _scheduleService.Schedule(new ValueSubmitted diff --git a/docs/releases.md b/docs/releases.md index a2930ed..0783776 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -35,6 +35,8 @@ All packages now share one version and must be upgraded together. From 11.0.0 th - `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. **Breaking changes** +- `IProducerService.Produce` takes a `TimeSpan? delay` or a `DateTimeOffset availableAt` instead of a Unix-seconds `long availableAfter`, and `insertId` is renamed `deduplicationKey` (still stored in `insert_id`). `ProduceList` takes an `IEnumerable`. `Produce(ScheduledMessage)` is no longer on the interface. +- Renamed: `ChronExpression`/`ChronTimezone` → `CronExpression`/`CronTimeZone` (columns unchanged), `InsertId` → `DeduplicationKey` (column unchanged), `ConsumerInstanceExecutionMode` → `ConsumerExecutionMode`, and `IScheduleService` parameters to `cronExpression`/`timeZone`. No migration is needed for these. - `AsyncMonolithSettings` is now `AsyncMonolithOptions`, configured through the standard options pattern and validated when the host starts (an `OptionsValidationException` instead of an `ArgumentException` at registration). Times are `TimeSpan`s, and some names changed: `ProcessorBatchSize` → `BatchSize`, `ProcessorMaxDelay` (ms) → `IdlePollInterval`, `ProcessorMinDelay` (ms) → `BusyPollInterval`. `AsyncMonolithSettings.Default` is gone; use `new AsyncMonolithOptions()`. - `Add*AsyncMonolith` returns an `AsyncMonolithBuilder` (for `.BindConfiguration(...)` and `.AddConsumers(...)`) instead of `IServiceCollection`, and the obsolete overloads taking an `Assembly` are removed. The TestHelpers setup methods take `Action`. - `[ConsumerTimeout]`'s `Duration` property is now `Seconds`. From d003f5af83efb83d6d45c2140a40afad89c6a153 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 04:58:39 +0000 Subject: [PATCH 35/53] Rename the execution mode enum in the example's TotalValueConsumer Missed by the previous commit because the file also has unrelated local edits. --- Example/Example.Api/Counter/TotalValueConsumer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Example/Example.Api/Counter/TotalValueConsumer.cs b/Example/Example.Api/Counter/TotalValueConsumer.cs index 1a122c9..ff0398f 100644 --- a/Example/Example.Api/Counter/TotalValueConsumer.cs +++ b/Example/Example.Api/Counter/TotalValueConsumer.cs @@ -3,7 +3,7 @@ namespace Example.Api.Counter; -[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Parallel)] +[ConsumerExecutionMode(ConsumerExecutionMode.Parallel)] public class TotalValueConsumer : IConsumer { private readonly ApplicationDbContext _dbContext; From 86543ecafe4f8642f8bea5bce3c90dcf85d47ef3 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:00:40 +0000 Subject: [PATCH 36/53] Make implementation types internal and pin the public API Every public type is a compatibility promise, and many existed only to wire the library together. Now internal: - ConsumerRegistry, the consumer and scheduled message processors, and the processor factory - IConsumerMessageFetcher, IScheduledMessageFetcher and every provider's fetchers - ScheduleService, PoisonedMessageService, QueueStatisticsService and AsyncMonolithIdGenerator (use the interfaces) - AsyncMonolithInstrumentation.ActivitySource (the name constants stay public for OpenTelemetry) and ScheduledMessage's scheduling methods FakeProducerService's constructor is internal; AddFakeAsyncMonolithBase Services creates it. Providers grant the test project access to their internals, as the core already did. PublicApiTests lists the types each package exports, so any change to the public surface has to be made on purpose. Each provider now exports only its StartupExtensions. --- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 3 + AsyncMonolith.Ef/EfConsumerMessageFetcher.cs | 2 +- AsyncMonolith.Ef/EfScheduledMessageFetcher.cs | 2 +- .../AsyncMonolith.MariaDb.csproj | 3 + .../MariaDbConsumerMessageFetcher.cs | 2 +- .../MariaDbScheduledMessageFetcher.cs | 2 +- .../AsyncMonolith.MsSql.csproj | 3 + .../MsSqlConsumerMessageFetcher.cs | 2 +- .../MsSqlScheduledMessageFetcher.cs | 2 +- .../AsyncMonolith.MySql.csproj | 3 + .../MySqlConsumerMessageFetcher.cs | 2 +- .../MySqlScheduledMessageFetcher.cs | 2 +- .../AsyncMonolith.PostgreSql.csproj | 3 + .../PostgreSqlConsumerMessageFetcher.cs | 2 +- .../PostgreSqlScheduledMessageFetcher.cs | 2 +- .../FakeProducerService.cs | 2 +- AsyncMonolith.TestHelpers/SetupTestHelpers.cs | 4 +- AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 4 +- AsyncMonolith.Tests/PublicApiTests.cs | 73 +++++++++++++++++++ .../Consumers/ConsumerMessageProcessor.cs | 2 +- .../ConsumerMessageProcessorFactory.cs | 2 +- AsyncMonolith/Consumers/ConsumerRegistry.cs | 2 +- .../Consumers/IConsumerMessageFetcher.cs | 2 +- .../Consumers/PoisonedMessageService.cs | 2 +- AsyncMonolith/Consumers/QueueStatistics.cs | 2 +- .../Scheduling/IScheduledMessageFetcher.cs | 2 +- AsyncMonolith/Scheduling/ScheduleService.cs | 2 +- AsyncMonolith/Scheduling/ScheduledMessage.cs | 6 +- .../Scheduling/ScheduledMessageProcessor.cs | 2 +- .../Utilities/AsyncMonolithIdGenerator.cs | 2 +- .../Utilities/AsyncMonolithInstrumentation.cs | 2 +- docs/releases.md | 1 + 32 files changed, 119 insertions(+), 28 deletions(-) create mode 100644 AsyncMonolith.Tests/PublicApiTests.cs diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index f465ff6..8d89d48 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -28,4 +28,7 @@ + + + diff --git a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs index 966a0e7..ab3f1ca 100644 --- a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs @@ -8,7 +8,7 @@ namespace AsyncMonolith.Ef; /// /// Fetches consumer messages using Entity Framework. /// -public sealed class EfConsumerMessageFetcher : IConsumerMessageFetcher +internal sealed class EfConsumerMessageFetcher : IConsumerMessageFetcher { private readonly IOptions _options; diff --git a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs index d4c8f89..0cb3063 100644 --- a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs +++ b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs @@ -8,7 +8,7 @@ namespace AsyncMonolith.Ef; /// /// Fetches scheduled messages from the database using Entity Framework. /// -public sealed class EfScheduledMessageFetcher : IScheduledMessageFetcher +internal sealed class EfScheduledMessageFetcher : IScheduledMessageFetcher { private readonly IOptions _options; diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index 3e77a4d..1c26213 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -33,4 +33,7 @@ + + + diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs index e1d8bfc..073d22e 100644 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.MariaDb; /// /// Represents a message fetcher for consumer messages in MariaDb. /// -public sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher +internal sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher { private const string MariaDb = @" SELECT * diff --git a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs index 1ce0840..86d48bd 100644 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.MariaDb; /// /// Fetches scheduled messages from MariaDb. /// -public sealed class MariaDbScheduledMessageFetcher : IScheduledMessageFetcher +internal sealed class MariaDbScheduledMessageFetcher : IScheduledMessageFetcher { private const string MariaDb = @" SELECT * diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index aca6b64..176e643 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -27,4 +27,7 @@ + + + \ No newline at end of file diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs index 55fba81..0c7425a 100644 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.MsSql; /// /// Represents a message fetcher for consuming messages from a SQL Server database. /// -public sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher +internal sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher { private const string MsSql = @" SELECT TOP (@batchSize) * diff --git a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs index ee3edd0..89290d0 100644 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.MsSql; /// /// Fetches scheduled messages from the MsSql database. /// -public sealed class MsSqlScheduledMessageFetcher : IScheduledMessageFetcher +internal sealed class MsSqlScheduledMessageFetcher : IScheduledMessageFetcher { private const string MsSql = @" SELECT TOP (@batchSize) * diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 4eb42e3..c986634 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -33,4 +33,7 @@ + + + diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs index 875f5a7..5d256ef 100644 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.MySql; /// /// Represents a message fetcher for consumer messages in MySQL. /// -public sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher +internal sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher { private const string MySql = @" SELECT * diff --git a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs index 6b7095a..c07440e 100644 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.MySql; /// /// Fetches scheduled messages from MySQL database. /// -public sealed class MySqlScheduledMessageFetcher : IScheduledMessageFetcher +internal sealed class MySqlScheduledMessageFetcher : IScheduledMessageFetcher { private const string MySql = @" SELECT * diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index 010a8a9..5bd8064 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -28,4 +28,7 @@ + + + diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs index b6aa06d..9766444 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.PostgreSql; /// /// Represents a consumer message fetcher implementation for PostgreSQL. /// -public sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher +internal sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher { private const string PgSql = @" SELECT * diff --git a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs index ee0d21c..e4910f8 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs @@ -9,7 +9,7 @@ namespace AsyncMonolith.PostgreSql; /// /// Fetches scheduled messages from a PostgreSQL database. /// -public sealed class PostgreSqlScheduledMessageFetcher : IScheduledMessageFetcher +internal sealed class PostgreSqlScheduledMessageFetcher : IScheduledMessageFetcher { private const string PgSql = @" SELECT * diff --git a/AsyncMonolith.TestHelpers/FakeProducerService.cs b/AsyncMonolith.TestHelpers/FakeProducerService.cs index 4efe776..20f621d 100644 --- a/AsyncMonolith.TestHelpers/FakeProducerService.cs +++ b/AsyncMonolith.TestHelpers/FakeProducerService.cs @@ -16,7 +16,7 @@ public class FakeProducerService : IProducerService private readonly TimeProvider _timeProvider; /// Initializes a new instance of the class. - public FakeProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, + internal FakeProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, IAsyncMonolithIdGenerator idGenerator) { _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider)); diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index 5e44fa8..8a1f470 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -26,7 +26,9 @@ public static IServiceCollection AddFakeAsyncMonolithBaseServices( AddBaseServices(services, configure); services.AddSingleton(new FakeIdGenerator()); services.AddScoped(); - services.AddScoped(); + services.AddScoped(sp => new FakeProducerService(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService())); + services.AddScoped(sp => sp.GetRequiredService()); return services; } diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs index 7ba1f5a..7ad8b7a 100644 --- a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -40,10 +40,10 @@ private SqliteTestHost(SqliteConnection? connection, string? path, ServiceProvid public long Now => Time.GetUtcNow().ToUnixTimeSeconds(); - public ConsumerMessageProcessor ConsumerProcessor => + internal ConsumerMessageProcessor ConsumerProcessor => Services.GetRequiredService>(); - public ScheduledMessageProcessor ScheduledProcessor => + internal ScheduledMessageProcessor ScheduledProcessor => Services.GetRequiredService>(); public static async Task Create(Action? configure = null, diff --git a/AsyncMonolith.Tests/PublicApiTests.cs b/AsyncMonolith.Tests/PublicApiTests.cs new file mode 100644 index 0000000..802ffe9 --- /dev/null +++ b/AsyncMonolith.Tests/PublicApiTests.cs @@ -0,0 +1,73 @@ +using System.Reflection; +using AsyncMonolith.Consumers; +using AsyncMonolith.TestHelpers; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Pins the types each package exports. Every public type is a compatibility promise, so adding or removing +/// one should be a deliberate change to this list. +/// +public class PublicApiTests +{ + private static string[] ExportedTypes(Assembly assembly) => + assembly.GetExportedTypes().Select(t => t.FullName!).Order(StringComparer.Ordinal).ToArray(); + + [Fact] + public void Core_package_exports_only_the_intended_types() + { + ExportedTypes(typeof(IConsumer).Assembly).ShouldBe([ + "AsyncMonolith.Consumers.AsyncMonolithNames", + "AsyncMonolith.Consumers.ConsumeContext", + "AsyncMonolith.Consumers.ConsumerAttemptsAttribute", + "AsyncMonolith.Consumers.ConsumerExecutionMode", + "AsyncMonolith.Consumers.ConsumerExecutionModeAttribute", + "AsyncMonolith.Consumers.ConsumerMessage", + "AsyncMonolith.Consumers.ConsumerNameAttribute", + "AsyncMonolith.Consumers.ConsumerPayloadNameAttribute", + "AsyncMonolith.Consumers.ConsumerRailIdAttribute", + "AsyncMonolith.Consumers.ConsumerTimeoutAttribute", + "AsyncMonolith.Consumers.IConsumer", + "AsyncMonolith.Consumers.IConsumerPayload", + "AsyncMonolith.Consumers.IConsumer`1", + "AsyncMonolith.Consumers.IPoisonedMessageService", + "AsyncMonolith.Consumers.IQueueStatisticsService", + "AsyncMonolith.Consumers.PoisonedMessage", + "AsyncMonolith.Consumers.QueueStatistics", + "AsyncMonolith.Producers.IProducerService", + "AsyncMonolith.Scheduling.IScheduleService", + "AsyncMonolith.Scheduling.ScheduledMessage", + "AsyncMonolith.Utilities.AsyncMonolithBuilder", + "AsyncMonolith.Utilities.AsyncMonolithInstrumentation", + "AsyncMonolith.Utilities.AsyncMonolithOptions", + "AsyncMonolith.Utilities.IAsyncMonolithIdGenerator", + "AsyncMonolith.Utilities.StartupExtensions" + ]); + } + + [Theory] + [InlineData("AsyncMonolith.Ef")] + [InlineData("AsyncMonolith.PostgreSql")] + [InlineData("AsyncMonolith.MsSql")] + [InlineData("AsyncMonolith.MySql")] + [InlineData("AsyncMonolith.MariaDb")] + public void Provider_packages_export_only_their_registration_extensions(string assemblyName) + { + ExportedTypes(Assembly.Load(assemblyName)).ShouldBe([$"{assemblyName}.StartupExtensions"]); + } + + [Fact] + public void TestHelpers_package_exports_only_the_intended_types() + { + ExportedTypes(typeof(FakeProducerService).Assembly).ShouldBe([ + "AsyncMonolith.TestHelpers.ConsumerMessageTestHelpers", + "AsyncMonolith.TestHelpers.ConsumerTestBase", + "AsyncMonolith.TestHelpers.FakeIdGenerator", + "AsyncMonolith.TestHelpers.FakeProducerService", + "AsyncMonolith.TestHelpers.FakeScheduleService", + "AsyncMonolith.TestHelpers.SetupTestHelpers", + "AsyncMonolith.TestHelpers.TestConsumerMessageProcessor" + ]); + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index e94b94f..f70439f 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -12,7 +12,7 @@ namespace AsyncMonolith.Consumers; /// Background service which fetches and processes batches of consumer messages. /// /// The type of the DbContext. -public sealed class ConsumerMessageProcessor : BackgroundService where T : DbContext +internal sealed class ConsumerMessageProcessor : BackgroundService where T : DbContext { private readonly IConsumerMessageFetcher _consumerMessageFetcher; private readonly ConsumerRegistry _consumerRegistry; diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessorFactory.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessorFactory.cs index faabf5e..c0a81f8 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessorFactory.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessorFactory.cs @@ -8,7 +8,7 @@ namespace AsyncMonolith.Consumers; /// Represents a factory for creating and managing consumer message processors. /// /// The type of the DbContext used by the consumer message processors. -public class ConsumerMessageProcessorFactory : IHostedService where T : DbContext +internal sealed class ConsumerMessageProcessorFactory : IHostedService where T : DbContext { private readonly List _hostedServices; private readonly int[] _instances; diff --git a/AsyncMonolith/Consumers/ConsumerRegistry.cs b/AsyncMonolith/Consumers/ConsumerRegistry.cs index 6318f98..5e1afc9 100644 --- a/AsyncMonolith/Consumers/ConsumerRegistry.cs +++ b/AsyncMonolith/Consumers/ConsumerRegistry.cs @@ -5,7 +5,7 @@ namespace AsyncMonolith.Consumers; /// /// Represents a registry for consumers and their associated types and payloads. /// -public sealed class ConsumerRegistry +internal sealed class ConsumerRegistry { /// /// Gets the async monolith settings. diff --git a/AsyncMonolith/Consumers/IConsumerMessageFetcher.cs b/AsyncMonolith/Consumers/IConsumerMessageFetcher.cs index 4027c5e..328fd4a 100644 --- a/AsyncMonolith/Consumers/IConsumerMessageFetcher.cs +++ b/AsyncMonolith/Consumers/IConsumerMessageFetcher.cs @@ -5,7 +5,7 @@ namespace AsyncMonolith.Consumers; /// /// Represents an interface for fetching consumer messages. /// -public interface IConsumerMessageFetcher +internal interface IConsumerMessageFetcher { /// /// Fetches consumer messages. diff --git a/AsyncMonolith/Consumers/PoisonedMessageService.cs b/AsyncMonolith/Consumers/PoisonedMessageService.cs index 2aff881..018e4fc 100644 --- a/AsyncMonolith/Consumers/PoisonedMessageService.cs +++ b/AsyncMonolith/Consumers/PoisonedMessageService.cs @@ -34,7 +34,7 @@ Task> List(int skip = 0, int take = 50, /// Entity Framework implementation of . /// /// The DbContext containing the AsyncMonolith tables. -public sealed class PoisonedMessageService : IPoisonedMessageService where T : DbContext +internal sealed class PoisonedMessageService : IPoisonedMessageService where T : DbContext { private readonly T _dbContext; private readonly TimeProvider _timeProvider; diff --git a/AsyncMonolith/Consumers/QueueStatistics.cs b/AsyncMonolith/Consumers/QueueStatistics.cs index 484c41d..36389bd 100644 --- a/AsyncMonolith/Consumers/QueueStatistics.cs +++ b/AsyncMonolith/Consumers/QueueStatistics.cs @@ -34,7 +34,7 @@ public interface IQueueStatisticsService /// Entity Framework implementation of . /// /// The DbContext containing the AsyncMonolith tables. -public sealed class QueueStatisticsService : IQueueStatisticsService where T : DbContext +internal sealed class QueueStatisticsService : IQueueStatisticsService where T : DbContext { private readonly T _dbContext; private readonly TimeProvider _timeProvider; diff --git a/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs b/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs index 4bf3f07..7dc5f3c 100644 --- a/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs +++ b/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs @@ -5,7 +5,7 @@ namespace AsyncMonolith.Scheduling; /// /// Interface for fetching scheduled messages. /// -public interface IScheduledMessageFetcher +internal interface IScheduledMessageFetcher { /// /// Fetches scheduled messages. diff --git a/AsyncMonolith/Scheduling/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index c93d188..e15391d 100644 --- a/AsyncMonolith/Scheduling/ScheduleService.cs +++ b/AsyncMonolith/Scheduling/ScheduleService.cs @@ -10,7 +10,7 @@ namespace AsyncMonolith.Scheduling; /// Service for scheduling messages. /// /// The type of DbContext. -public sealed class ScheduleService : IScheduleService where T : DbContext +internal sealed class ScheduleService : IScheduleService where T : DbContext { private readonly T _dbContext; private readonly IAsyncMonolithIdGenerator _idGenerator; diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index f818932..d030bc3 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessage.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessage.cs @@ -68,7 +68,7 @@ public class ScheduledMessage /// /// The time provider. /// The next occurrence of the scheduled message in Unix timestamp format. - public long GetNextOccurrence(TimeProvider timeProvider) + internal long GetNextOccurrence(TimeProvider timeProvider) { var expression = Cronos.CronExpression.Parse(CronExpression, Cronos.CronFormat.IncludeSeconds); @@ -93,7 +93,7 @@ public long GetNextOccurrence(TimeProvider timeProvider) /// The new cron expression. /// The new cron timezone. /// The time provider. - public void UpdateSchedule(string cronExpression, string timeZone, TimeProvider timeProvider) + internal void UpdateSchedule(string cronExpression, string timeZone, TimeProvider timeProvider) { CronExpression = cronExpression; CronTimeZone = timeZone; @@ -105,7 +105,7 @@ public void UpdateSchedule(string cronExpression, string timeZone, TimeProvider /// /// The type of the payload. /// The payload message. - public void UpdatePayload(TPayload message) where TPayload : IConsumerPayload + internal void UpdatePayload(TPayload message) where TPayload : IConsumerPayload { var payload = JsonSerializer.Serialize(message); Payload = payload; diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index 7f84f5c..f1f43e8 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -13,7 +13,7 @@ namespace AsyncMonolith.Scheduling; /// Represents a background service for processing scheduled messages. /// /// The type of the database context. -public sealed class ScheduledMessageProcessor : BackgroundService where T : DbContext +internal sealed class ScheduledMessageProcessor : BackgroundService where T : DbContext { private readonly ILogger> _logger; private readonly IScheduledMessageFetcher _messageFetcher; diff --git a/AsyncMonolith/Utilities/AsyncMonolithIdGenerator.cs b/AsyncMonolith/Utilities/AsyncMonolithIdGenerator.cs index 8b62302..14d161f 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithIdGenerator.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithIdGenerator.cs @@ -17,7 +17,7 @@ public interface IAsyncMonolithIdGenerator /// /// Represents an implementation of the interface. /// -public sealed class AsyncMonolithIdGenerator : IAsyncMonolithIdGenerator +internal sealed class AsyncMonolithIdGenerator : IAsyncMonolithIdGenerator { private const string ValidIdCharacters = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private const int Length = 12; diff --git a/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs b/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs index ca92a8d..c6b773a 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs @@ -26,5 +26,5 @@ public static class AsyncMonolithInstrumentation /// /// The activity source instance. /// - public static readonly ActivitySource ActivitySource = new(ActivitySourceName); + internal static readonly ActivitySource ActivitySource = new(ActivitySourceName); } diff --git a/docs/releases.md b/docs/releases.md index 0783776..056cd9a 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -35,6 +35,7 @@ All packages now share one version and must be upgraded together. From 11.0.0 th - `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. **Breaking changes** +- Implementation types are now internal: `ConsumerRegistry`, the processors and processor factory, the fetchers and their interfaces, `ScheduleService`, `PoisonedMessageService`, `QueueStatisticsService`, `AsyncMonolithIdGenerator`, `AsyncMonolithInstrumentation.ActivitySource` (the source name constants stay public), and `ScheduledMessage.GetNextOccurrence`/`UpdateSchedule`/`UpdatePayload`. Use the service interfaces instead. `FakeProducerService` is created by `AddFakeAsyncMonolithBaseServices`. - `IProducerService.Produce` takes a `TimeSpan? delay` or a `DateTimeOffset availableAt` instead of a Unix-seconds `long availableAfter`, and `insertId` is renamed `deduplicationKey` (still stored in `insert_id`). `ProduceList` takes an `IEnumerable`. `Produce(ScheduledMessage)` is no longer on the interface. - Renamed: `ChronExpression`/`ChronTimezone` → `CronExpression`/`CronTimeZone` (columns unchanged), `InsertId` → `DeduplicationKey` (column unchanged), `ConsumerInstanceExecutionMode` → `ConsumerExecutionMode`, and `IScheduleService` parameters to `cronExpression`/`timeZone`. No migration is needed for these. - `AsyncMonolithSettings` is now `AsyncMonolithOptions`, configured through the standard options pattern and validated when the host starts (an `OptionsValidationException` instead of an `ArgumentException` at registration). Times are `TimeSpan`s, and some names changed: `ProcessorBatchSize` → `BatchSize`, `ProcessorMaxDelay` (ms) → `IdlePollInterval`, `ProcessorMinDelay` (ms) → `BusyPollInterval`. `AsyncMonolithSettings.Default` is gone; use `new AsyncMonolithOptions()`. From 8762c727898395114d3c54bc41c2369d5364b695 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:04:01 +0000 Subject: [PATCH 37/53] Map AsyncMonolith's tables in ConfigureAsyncMonolith, with schema and prefix Hosts had to declare DbSets for AsyncMonolith's three tables and could not move them out of the way of their own, which matters when the library shares a database with an app like MiniCMS. - ConfigureAsyncMonolith maps consumer_messages, poisoned_messages and scheduled_messages itself (tables, keys and the unique index), so DbSets are optional. It takes an optional Schema and TablePrefix. - The [Table] attributes on the entities are removed; the fluent mapping is the only source of table names. - The PostgreSQL, SQL Server, MySQL and MariaDB fetchers read the quoted, schema-qualified table name from the model instead of hard-coding it. The core now references EF Core Relational for this, and the MySQL and MariaDB projects reference it directly (Pomelo still caps it at 9). - IPoisonedMessageService.List returns PoisonedMessageInfo records with DateTimeOffset times instead of storage entities. - MySQL and MariaDB's NoWarn no longer drops the inherited list. Tests cover the default table names, a DbSet-free host context with prefixed tables running end to end on SQLite, and (as integration tests) a custom schema on PostgreSQL and SQL Server. --- .../AsyncMonolith.MariaDb.csproj | 3 +- .../MariaDbConsumerMessageFetcher.cs | 7 +- .../MariaDbScheduledMessageFetcher.cs | 7 +- .../MsSqlConsumerMessageFetcher.cs | 7 +- .../MsSqlScheduledMessageFetcher.cs | 7 +- .../AsyncMonolith.MySql.csproj | 3 +- .../MySqlConsumerMessageFetcher.cs | 7 +- .../MySqlScheduledMessageFetcher.cs | 7 +- .../PostgreSqlConsumerMessageFetcher.cs | 7 +- .../PostgreSqlScheduledMessageFetcher.cs | 7 +- .../Infra/CustomTableContexts.cs | 22 +++ .../Infra/TestDbContainerBase.cs | 2 +- AsyncMonolith.Tests/ModelMappingTests.cs | 155 ++++++++++++++++++ AsyncMonolith.Tests/PublicApiTests.cs | 2 + AsyncMonolith/AsyncMonolith.csproj | 1 + AsyncMonolith/Consumers/ConsumerMessage.cs | 1 - AsyncMonolith/Consumers/PoisonedMessage.cs | 1 - .../Consumers/PoisonedMessageService.cs | 53 +++++- AsyncMonolith/Scheduling/ScheduledMessage.cs | 1 - AsyncMonolith/Utilities/AsyncMonolithModel.cs | 59 +++++++ AsyncMonolith/Utilities/StartupExtensions.cs | 16 +- Directory.Packages.props | 1 + docs/guides/consuming-messages.md | 2 +- docs/quickstart.md | 25 +-- docs/releases.md | 3 + 25 files changed, 355 insertions(+), 51 deletions(-) create mode 100644 AsyncMonolith.Tests/Infra/CustomTableContexts.cs create mode 100644 AsyncMonolith.Tests/ModelMappingTests.cs create mode 100644 AsyncMonolith/Utilities/AsyncMonolithModel.cs diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index 1c26213..c79b25b 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -5,7 +5,7 @@ $(NoWarn);NU1608 preview.1 - NU5104 + $(NoWarn);NU5104 true AsyncMonolith.MariaDb Tim Jones @@ -31,6 +31,7 @@ + diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs index 073d22e..fa8af15 100644 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Consumers; +using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -13,7 +14,7 @@ internal sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher { private const string MariaDb = @" SELECT * - FROM consumer_messages + FROM {table} WHERE available_after <= @currentTime AND rail_id = @railId ORDER BY created_at, id LIMIT @batchSize @@ -42,7 +43,7 @@ public Task> Fetch(DbSet consumerSet, lon CancellationToken cancellationToken = default) { return consumerSet - .FromSqlRaw(MariaDb, new MySqlParameter("@currentTime", currentTime), + .FromSqlRaw(MariaDb.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@railId", railId), new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs index 86d48bd..f43445f 100644 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Scheduling; +using System.Globalization; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -13,7 +14,7 @@ internal sealed class MariaDbScheduledMessageFetcher : IScheduledMessageFetcher { private const string MariaDb = @" SELECT * - FROM scheduled_messages + FROM {table} WHERE available_after <= @currentTime LIMIT @batchSize FOR UPDATE SKIP LOCKED"; @@ -40,7 +41,7 @@ public Task> Fetch(DbSet scheduledMessa CancellationToken cancellationToken = default) { return scheduledMessageSet - .FromSqlRaw(MariaDb, new MySqlParameter("@currentTime", currentTime), + .FromSqlRaw(MariaDb.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs index 0c7425a..a0dd897 100644 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Consumers; +using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Utilities; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; @@ -13,7 +14,7 @@ internal sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher { private const string MsSql = @" SELECT TOP (@batchSize) * - FROM consumer_messages WITH (ROWLOCK, READPAST) + FROM {table} WITH (ROWLOCK, READPAST) WHERE available_after <= @currentTime AND rail_id = @railId ORDER BY created_at, id"; @@ -40,7 +41,7 @@ public Task> Fetch(DbSet consumerSet, lon CancellationToken cancellationToken = default) { return consumerSet - .FromSqlRaw(MsSql, new SqlParameter("@currentTime", currentTime), + .FromSqlRaw(MsSql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new SqlParameter("@currentTime", currentTime), new SqlParameter("@railId", railId), new SqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs index 89290d0..a602bb7 100644 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Scheduling; +using System.Globalization; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; @@ -13,7 +14,7 @@ internal sealed class MsSqlScheduledMessageFetcher : IScheduledMessageFetcher { private const string MsSql = @" SELECT TOP (@batchSize) * - FROM scheduled_messages WITH (ROWLOCK, READPAST) + FROM {table} WITH (ROWLOCK, READPAST) WHERE available_after <= @currentTime"; private readonly IOptions _options; @@ -38,7 +39,7 @@ public Task> Fetch(DbSet scheduledMessa CancellationToken cancellationToken = default) { return scheduledMessageSet - .FromSqlRaw(MsSql, new SqlParameter("@currentTime", currentTime), + .FromSqlRaw(MsSql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new SqlParameter("@currentTime", currentTime), new SqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index c986634..3397cf9 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -5,7 +5,7 @@ $(NoWarn);NU1608 preview.1 - NU5104 + $(NoWarn);NU5104 true AsyncMonolith.MySql Tim Jones @@ -31,6 +31,7 @@ + diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs index 5d256ef..b3c653b 100644 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Consumers; +using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -13,7 +14,7 @@ internal sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher { private const string MySql = @" SELECT * - FROM consumer_messages + FROM {table} WHERE available_after <= @currentTime AND rail_id = @railId ORDER BY created_at, id LIMIT @batchSize @@ -42,7 +43,7 @@ public Task> Fetch(DbSet consumerSet, lon CancellationToken cancellationToken = default) { return consumerSet - .FromSqlRaw(MySql, new MySqlParameter("@currentTime", currentTime), + .FromSqlRaw(MySql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@railId", railId), new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs index c07440e..09af4a5 100644 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Scheduling; +using System.Globalization; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -13,7 +14,7 @@ internal sealed class MySqlScheduledMessageFetcher : IScheduledMessageFetcher { private const string MySql = @" SELECT * - FROM scheduled_messages + FROM {table} WHERE available_after <= @currentTime LIMIT @batchSize FOR UPDATE SKIP LOCKED"; @@ -40,7 +41,7 @@ public Task> Fetch(DbSet scheduledMessa CancellationToken cancellationToken = default) { return scheduledMessageSet - .FromSqlRaw(MySql, new MySqlParameter("@currentTime", currentTime), + .FromSqlRaw(MySql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), new MySqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs index 9766444..2085533 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Consumers; +using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -13,7 +14,7 @@ internal sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher { private const string PgSql = @" SELECT * - FROM consumer_messages + FROM {table} WHERE available_after <= @currentTime AND rail_id = @railId ORDER BY created_at, id FOR UPDATE SKIP LOCKED @@ -42,7 +43,7 @@ public Task> Fetch(DbSet consumerSet, lon CancellationToken cancellationToken = default) { return consumerSet - .FromSqlRaw(PgSql, new NpgsqlParameter("@currentTime", currentTime), + .FromSqlRaw(PgSql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new NpgsqlParameter("@currentTime", currentTime), new NpgsqlParameter("@railId", railId), new NpgsqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); diff --git a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs index e4910f8..376afee 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs @@ -1,4 +1,5 @@ -using AsyncMonolith.Scheduling; +using System.Globalization; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -13,7 +14,7 @@ internal sealed class PostgreSqlScheduledMessageFetcher : IScheduledMessageFetch { private const string PgSql = @" SELECT * - FROM scheduled_messages + FROM {table} WHERE available_after <= @currentTime FOR UPDATE SKIP LOCKED LIMIT @batchSize"; @@ -40,7 +41,7 @@ public Task> Fetch(DbSet scheduledMessa CancellationToken cancellationToken = default) { return scheduledMessageSet - .FromSqlRaw(PgSql, new NpgsqlParameter("@currentTime", currentTime), + .FromSqlRaw(PgSql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new NpgsqlParameter("@currentTime", currentTime), new NpgsqlParameter("@batchSize", _options.Value.BatchSize)) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith.Tests/Infra/CustomTableContexts.cs b/AsyncMonolith.Tests/Infra/CustomTableContexts.cs new file mode 100644 index 0000000..fda5d11 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/CustomTableContexts.cs @@ -0,0 +1,22 @@ +using AsyncMonolith.Utilities; +using Microsoft.EntityFrameworkCore; + +namespace AsyncMonolith.Tests.Infra; + +/// A host DbContext with no AsyncMonolith DbSets and prefixed table names. +public class PrefixedDbContext(DbContextOptions options) : DbContext(options) +{ + protected override void OnModelCreating(ModelBuilder modelBuilder) => + modelBuilder.ConfigureAsyncMonolith(o => o.TablePrefix = "jobs_"); +} + +/// A host DbContext with AsyncMonolith's tables in their own schema, for databases that support schemas. +public class SchemaDbContext(DbContextOptions options) : DbContext(options) +{ + protected override void OnModelCreating(ModelBuilder modelBuilder) => + modelBuilder.ConfigureAsyncMonolith(o => + { + o.Schema = "async_monolith"; + o.TablePrefix = "app_"; + }); +} diff --git a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs index 0ed374d..3d6858c 100644 --- a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs +++ b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs @@ -6,7 +6,7 @@ namespace AsyncMonolith.Tests.Infra; public abstract class TestDbContainerBase : IAsyncLifetime { protected IContainer DbContainer { get; set; } = default!; - protected string ConnectionString { get; set; } = default!; + public string ConnectionString { get; protected set; } = default!; public DbType DbType => GetDbType(); public async ValueTask InitializeAsync() diff --git a/AsyncMonolith.Tests/ModelMappingTests.cs b/AsyncMonolith.Tests/ModelMappingTests.cs new file mode 100644 index 0000000..80de05e --- /dev/null +++ b/AsyncMonolith.Tests/ModelMappingTests.cs @@ -0,0 +1,155 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Ef; +using AsyncMonolith.MsSql; +using AsyncMonolith.PostgreSql; +using AsyncMonolith.Producers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Tests.Infra; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// ConfigureAsyncMonolith maps the tables itself, with an optional schema and prefix. +/// +public class ModelMappingTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Default_table_names_are_unchanged() + { + await using var connection = new SqliteConnection("DataSource=:memory:"); + await using var db = new TestDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options); + + db.Model.FindEntityType(typeof(ConsumerMessage))!.GetTableName().ShouldBe("consumer_messages"); + db.Model.FindEntityType(typeof(PoisonedMessage))!.GetTableName().ShouldBe("poisoned_messages"); + db.Model.FindEntityType(typeof(ScheduledMessage))!.GetTableName().ShouldBe("scheduled_messages"); + } + + /// Runs produce, consume, poison and schedule against a host DbContext type. + internal static async Task RunEndToEnd(IServiceProvider services) where TDb : DbContext + { + using (var scope = services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var producer = scope.ServiceProvider.GetRequiredService(); + await producer.Produce(new SingleConsumerMessage { Name = "ok" }, cancellationToken: Ct); + await producer.Produce(new MixedOutcomeMessage(), cancellationToken: Ct); + await scope.ServiceProvider.GetRequiredService() + .EnsureSchedule(new SingleConsumerMessage { Name = "tick" }, "* * * * * *", "UTC", "tick", Ct); + await db.SaveChangesAsync(Ct); + } + + var processor = ActivatorUtilities.CreateInstance>(services); + (await processor.ProcessBatch(Ct)).ShouldBe(2); + + using (var scope = services.CreateScope()) + { + var poisoned = scope.ServiceProvider.GetRequiredService(); + var statistics = await scope.ServiceProvider.GetRequiredService().Read(Ct); + statistics.Schedules.ShouldBe(1); + statistics.Waiting.ShouldBe(1); // MixedFailureConsumer, waiting to retry + (await poisoned.Count(Ct)).ShouldBe(0); + } + } + + private static ServiceProvider Services(Action configureDb, + Action addAsyncMonolith) where TDb : DbContext + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddDbContext(configureDb); + addAsyncMonolith(services); + return services.BuildServiceProvider(); + } + + [Fact] + public async Task A_host_context_without_DbSets_can_use_prefixed_tables() + { + var path = Path.Combine(Path.GetTempPath(), $"asyncmonolith-prefix-{Guid.NewGuid():N}.db"); + try + { + await using var services = Services(o => o.UseSqlite($"Data Source={path}"), + s => s.AddEfAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining())); + using (var scope = services.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(Ct); + } + + await RunEndToEnd(services); + + await using var connection = new SqliteConnection($"Data Source={path}"); + await connection.OpenAsync(Ct); + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name"; + var tables = new List(); + await using (var reader = await command.ExecuteReaderAsync(Ct)) + { + while (await reader.ReadAsync(Ct)) + { + tables.Add(reader.GetString(0)); + } + } + + tables.ShouldBe(["jobs_consumer_messages", "jobs_poisoned_messages", "jobs_scheduled_messages"]); + } + finally + { + SqliteConnection.ClearAllPools(); + File.Delete(path); + } + } + + [Theory] + [Trait("Category", "Integration")] + [InlineData(DbType.PostgreSql)] + [InlineData(DbType.MsSql)] + public async Task Provider_sql_finds_tables_in_a_custom_schema(DbType dbType) + { + var container = DbTestsBase.GetTestDbContainer(dbType); + await container.InitializeAsync(); + try + { + await using var services = Services( + o => + { + if (dbType == DbType.PostgreSql) + { + o.UseNpgsql(container.ConnectionString); + } + else + { + o.UseSqlServer(container.ConnectionString); + } + }, + s => + { + if (dbType == DbType.PostgreSql) + { + s.AddPostgreSqlAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); + } + else + { + s.AddMsSqlAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); + } + }); + using (var scope = services.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(Ct); + } + + await RunEndToEnd(services); + } + finally + { + await container.DisposeAsync(); + } + } +} diff --git a/AsyncMonolith.Tests/PublicApiTests.cs b/AsyncMonolith.Tests/PublicApiTests.cs index 802ffe9..f43541e 100644 --- a/AsyncMonolith.Tests/PublicApiTests.cs +++ b/AsyncMonolith.Tests/PublicApiTests.cs @@ -34,12 +34,14 @@ public void Core_package_exports_only_the_intended_types() "AsyncMonolith.Consumers.IPoisonedMessageService", "AsyncMonolith.Consumers.IQueueStatisticsService", "AsyncMonolith.Consumers.PoisonedMessage", + "AsyncMonolith.Consumers.PoisonedMessageInfo", "AsyncMonolith.Consumers.QueueStatistics", "AsyncMonolith.Producers.IProducerService", "AsyncMonolith.Scheduling.IScheduleService", "AsyncMonolith.Scheduling.ScheduledMessage", "AsyncMonolith.Utilities.AsyncMonolithBuilder", "AsyncMonolith.Utilities.AsyncMonolithInstrumentation", + "AsyncMonolith.Utilities.AsyncMonolithModelOptions", "AsyncMonolith.Utilities.AsyncMonolithOptions", "AsyncMonolith.Utilities.IAsyncMonolithIdGenerator", "AsyncMonolith.Utilities.StartupExtensions" diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index 633dcf0..1a3df66 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -19,6 +19,7 @@ + diff --git a/AsyncMonolith/Consumers/ConsumerMessage.cs b/AsyncMonolith/Consumers/ConsumerMessage.cs index e8d8a2d..3775e38 100644 --- a/AsyncMonolith/Consumers/ConsumerMessage.cs +++ b/AsyncMonolith/Consumers/ConsumerMessage.cs @@ -7,7 +7,6 @@ namespace AsyncMonolith.Consumers; /// /// Consumer Message model /// -[Table("consumer_messages")] public sealed class ConsumerMessage { /// diff --git a/AsyncMonolith/Consumers/PoisonedMessage.cs b/AsyncMonolith/Consumers/PoisonedMessage.cs index a6331f2..b77bd9c 100644 --- a/AsyncMonolith/Consumers/PoisonedMessage.cs +++ b/AsyncMonolith/Consumers/PoisonedMessage.cs @@ -7,7 +7,6 @@ namespace AsyncMonolith.Consumers; /// /// Poisoned message model /// -[Table("poisoned_messages")] public sealed class PoisonedMessage { /// diff --git a/AsyncMonolith/Consumers/PoisonedMessageService.cs b/AsyncMonolith/Consumers/PoisonedMessageService.cs index 018e4fc..6c2df44 100644 --- a/AsyncMonolith/Consumers/PoisonedMessageService.cs +++ b/AsyncMonolith/Consumers/PoisonedMessageService.cs @@ -12,7 +12,7 @@ public interface IPoisonedMessageService Task Count(CancellationToken cancellationToken = default); /// Lists poisoned messages, most recently created first. - Task> List(int skip = 0, int take = 50, + Task> List(int skip = 0, int take = 50, CancellationToken cancellationToken = default); /// @@ -30,6 +30,42 @@ Task> List(int skip = 0, int take = 50, Task Delete(string id, CancellationToken cancellationToken = default); } +/// +/// A poisoned message, as returned by . +/// +public sealed record PoisonedMessageInfo +{ + /// The message id. + public required string Id { get; init; } + + /// The stored name of the consumer that failed. + public required string ConsumerName { get; init; } + + /// The stored name of the payload. + public required string PayloadName { get; init; } + + /// The payload as JSON. + public required string Payload { get; init; } + + /// The deduplication key the message was produced with (or the generated one). + public required string DeduplicationKey { get; init; } + + /// How many attempts were made. + public required int Attempts { get; init; } + + /// When the message was produced. + public required DateTimeOffset CreatedAt { get; init; } + + /// When the message last became due before its final attempt. + public required DateTimeOffset LastDueAt { get; init; } + + /// The error from the final attempt, if one was recorded. + public string? LastError { get; init; } + + /// The trace id of the activity that produced the message, if any. + public string? TraceId { get; init; } +} + /// /// Entity Framework implementation of . /// @@ -51,7 +87,7 @@ public Task Count(CancellationToken cancellationToken = default) => _dbContext.Set().CountAsync(cancellationToken); /// - public async Task> List(int skip = 0, int take = 50, + public async Task> List(int skip = 0, int take = 50, CancellationToken cancellationToken = default) { ArgumentOutOfRangeException.ThrowIfNegative(skip); @@ -63,6 +99,19 @@ public async Task> List(int skip = 0, int take = .ThenBy(m => m.Id) .Skip(skip) .Take(take) + .Select(m => new PoisonedMessageInfo + { + Id = m.Id, + ConsumerName = m.ConsumerType, + PayloadName = m.PayloadType, + Payload = m.Payload, + DeduplicationKey = m.DeduplicationKey, + Attempts = m.Attempts, + CreatedAt = DateTimeOffset.FromUnixTimeSeconds(m.CreatedAt), + LastDueAt = DateTimeOffset.FromUnixTimeSeconds(m.AvailableAfter), + LastError = m.LastError, + TraceId = m.TraceId + }) .ToListAsync(cancellationToken); } diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index d030bc3..69721e1 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessage.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessage.cs @@ -10,7 +10,6 @@ namespace AsyncMonolith.Scheduling; /// /// Represents a scheduled message. /// -[Table("scheduled_messages")] public class ScheduledMessage { /// diff --git a/AsyncMonolith/Utilities/AsyncMonolithModel.cs b/AsyncMonolith/Utilities/AsyncMonolithModel.cs new file mode 100644 index 0000000..fbac318 --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithModel.cs @@ -0,0 +1,59 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage; + +namespace AsyncMonolith.Utilities; + +/// +/// Where AsyncMonolith's tables live, set in modelBuilder.ConfigureAsyncMonolith(...). +/// +public sealed class AsyncMonolithModelOptions +{ + /// The database schema for the tables, or null for the default schema. + public string? Schema { get; set; } + + /// + /// Prepended to every table name, for example "jobs_" gives jobs_consumer_messages. Default none. + /// + public string TablePrefix { get; set; } = ""; +} + +/// Finds the quoted, schema-qualified table names the model maps the entities to. +internal static class AsyncMonolithTables +{ + public static string Name(DbSet set) where TEntity : class + { + var context = set.GetService().Context; + var entityType = context.Model.FindEntityType(typeof(TEntity)) ?? throw new InvalidOperationException( + $"{typeof(TEntity).Name} is not in the model. Call modelBuilder.ConfigureAsyncMonolith() in OnModelCreating."); + return context.GetService() + .DelimitIdentifier(entityType.GetTableName()!, entityType.GetSchema()); + } +} + +internal static class AsyncMonolithModel +{ + public static void Configure(ModelBuilder modelBuilder, AsyncMonolithModelOptions options) + { + modelBuilder.Entity(entity => + { + entity.ToTable(options.TablePrefix + "consumer_messages", options.Schema); + entity.HasKey(m => m.Id); + entity.HasIndex(m => new { m.DeduplicationKey, m.ConsumerType }).IsUnique(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable(options.TablePrefix + "poisoned_messages", options.Schema); + entity.HasKey(m => m.Id); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable(options.TablePrefix + "scheduled_messages", options.Schema); + entity.HasKey(m => m.Id); + }); + } +} diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index adf9c39..3042dcf 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -15,16 +15,18 @@ namespace AsyncMonolith.Utilities; public static class StartupExtensions { /// - /// Configures the AsyncMonolith model. + /// Maps AsyncMonolith's tables (consumer_messages, poisoned_messages and scheduled_messages). Call it in + /// your DbContext's OnModelCreating. You don't need DbSet properties for them. /// /// The model builder. - /// A reference to this instance after the operation has completed. - public static ModelBuilder ConfigureAsyncMonolith(this ModelBuilder modelBuilder) + /// Optionally sets the schema and a table name prefix. + /// The model builder. + public static ModelBuilder ConfigureAsyncMonolith(this ModelBuilder modelBuilder, + Action? configure = null) { - modelBuilder.Entity() - .HasIndex(e => new { e.DeduplicationKey, e.ConsumerType }) - .IsUnique(); - + var options = new AsyncMonolithModelOptions(); + configure?.Invoke(options); + AsyncMonolithModel.Configure(modelBuilder, options); return modelBuilder; } diff --git a/Directory.Packages.props b/Directory.Packages.props index 0f0a47a..ca3435f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,6 +7,7 @@ + diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index ad3454d..fa6e18b 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -53,7 +53,7 @@ Design consumers so the order of messages doesn't matter, for example by checkin ```csharp public class FailedMessagesController(IPoisonedMessageService poisoned) : ControllerBase { - [HttpGet] public Task> List() => poisoned.List(skip: 0, take: 50); + [HttpGet] public Task> List() => poisoned.List(skip: 0, take: 50); [HttpPost("{id}/retry")] public Task Retry(string id) => poisoned.Retry(id); [HttpDelete("{id}")] public Task Delete(string id) => poisoned.Delete(id); } diff --git a/docs/quickstart.md b/docs/quickstart.md index 173d821..aed7787 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -27,17 +27,20 @@ Setup your DbContext { } - // Add Db Sets - public DbSet ConsumerMessages { get; set; } = default!; - public DbSet PoisonedMessages { get; set; } = default!; - public DbSet ScheduledMessages { get; set; } = default!; - - // Configure the ModelBuilder - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.ConfigureAsyncMonolith(); - base.OnModelCreating(modelBuilder); - } + // Map AsyncMonolith's tables. DbSet properties for them are optional. + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.ConfigureAsyncMonolith(); + + // Or keep them apart from your own tables: + // modelBuilder.ConfigureAsyncMonolith(o => + // { + // o.Schema = "jobs"; // databases that support schemas + // o.TablePrefix = "jobs_"; // jobs_consumer_messages, ... + // }); + + base.OnModelCreating(modelBuilder); + } } ``` diff --git a/docs/releases.md b/docs/releases.md index 056cd9a..702122a 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -22,6 +22,7 @@ All packages now share one version and must be upgraded together. From 11.0.0 th **Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** +- Tables can live in their own schema or have a prefix: `modelBuilder.ConfigureAsyncMonolith(o => { o.Schema = "jobs"; o.TablePrefix = "jobs_"; })`. The database packages' SQL follows the mapping. - Every database package now produces messages the same way: they are added to your `DbContext` and written on `SaveChanges`, in your transaction. The PostgreSQL, SQL Server, MySQL and MariaDB packages used to write immediately. A repeated insert id skips consumers that already have a pending message with it, on every database. - Several app instances can safely share the tables with any database package. Claims and schedule occurrences use conditional updates, so a message is processed by one processor at a time and a schedule fires once per occurrence. - Fetch order is deterministic (oldest first, then by id). See [Ordering](guides/consuming-messages.md#ordering) for what is and isn't guaranteed. @@ -35,6 +36,8 @@ All packages now share one version and must be upgraded together. From 11.0.0 th - `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. **Breaking changes** +- `ConfigureAsyncMonolith()` now maps all three tables (previously only an index), so DbSet properties for them are optional. It takes an optional schema and table prefix. The `[Table]` attributes on the entities are removed; call `ConfigureAsyncMonolith()` in `OnModelCreating` if you weren't already. +- `IPoisonedMessageService.List` returns `PoisonedMessageInfo` records with `DateTimeOffset` times instead of `PoisonedMessage` entities. - Implementation types are now internal: `ConsumerRegistry`, the processors and processor factory, the fetchers and their interfaces, `ScheduleService`, `PoisonedMessageService`, `QueueStatisticsService`, `AsyncMonolithIdGenerator`, `AsyncMonolithInstrumentation.ActivitySource` (the source name constants stay public), and `ScheduledMessage.GetNextOccurrence`/`UpdateSchedule`/`UpdatePayload`. Use the service interfaces instead. `FakeProducerService` is created by `AddFakeAsyncMonolithBaseServices`. - `IProducerService.Produce` takes a `TimeSpan? delay` or a `DateTimeOffset availableAt` instead of a Unix-seconds `long availableAfter`, and `insertId` is renamed `deduplicationKey` (still stored in `insert_id`). `ProduceList` takes an `IEnumerable`. `Produce(ScheduledMessage)` is no longer on the interface. - Renamed: `ChronExpression`/`ChronTimezone` → `CronExpression`/`CronTimeZone` (columns unchanged), `InsertId` → `DeduplicationKey` (column unchanged), `ConsumerInstanceExecutionMode` → `ConsumerExecutionMode`, and `IScheduleService` parameters to `cronExpression`/`timeZone`. No migration is needed for these. From 174aa58d1d827a9bb203145ab7208478d32ef1d7 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:05:44 +0000 Subject: [PATCH 38/53] Add serializer options and accept 5-field cron expressions - AsyncMonolithOptions.SerializerOptions sets the JsonSerializerOptions used to store and read payloads (producer, schedules, consumers and TestHelpers' processor). Null keeps System.Text.Json's defaults, so stored payloads are unaffected. - Cron expressions may have 5 fields (minute precision) or 6 (seconds first); previously only 6 were accepted, which surprised anyone using standard cron. Tests cover the default payload format, custom options for storing and consuming (camelCase names, string enums) and for schedules, 5- and 6-field expressions, and wrong field counts. --- .../FakeScheduleService.cs | 2 +- .../TestConsumerMessageProcessor.cs | 10 ++-- .../Infra/SerializationConsumer.cs | 30 +++++++++++ AsyncMonolith.Tests/Infra/SqliteTestHost.cs | 1 + .../Infra/TestServiceHelpers.cs | 1 + AsyncMonolith.Tests/SchedulingTests.cs | 19 ++++++- AsyncMonolith.Tests/SerializationTests.cs | 54 +++++++++++++++++++ .../Consumers/ConsumerMessageProcessor.cs | 3 +- AsyncMonolith/Producers/ProducerService.cs | 9 ++-- AsyncMonolith/Scheduling/Cron.cs | 13 +++++ AsyncMonolith/Scheduling/IScheduleService.cs | 4 +- AsyncMonolith/Scheduling/ScheduleService.cs | 13 +++-- AsyncMonolith/Scheduling/ScheduledMessage.cs | 7 +-- .../Utilities/AsyncMonolithOptions.cs | 8 +++ docs/guides/scheduling-messages.md | 4 ++ docs/releases.md | 2 + 16 files changed, 161 insertions(+), 19 deletions(-) create mode 100644 AsyncMonolith.Tests/Infra/SerializationConsumer.cs create mode 100644 AsyncMonolith.Tests/SerializationTests.cs create mode 100644 AsyncMonolith/Scheduling/Cron.cs diff --git a/AsyncMonolith.TestHelpers/FakeScheduleService.cs b/AsyncMonolith.TestHelpers/FakeScheduleService.cs index 8b02218..6f9ba75 100644 --- a/AsyncMonolith.TestHelpers/FakeScheduleService.cs +++ b/AsyncMonolith.TestHelpers/FakeScheduleService.cs @@ -56,7 +56,7 @@ public string Schedule(TPayload message, string cronExpression, string var payload = JsonSerializer.Serialize(message); var id = _fakeIdGenerator.GenerateId(); - var expression = Cronos.CronExpression.Parse(cronExpression, Cronos.CronFormat.IncludeSeconds); + var expression = Cron.Parse(cronExpression); var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZone); if (timezone == null) diff --git a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs index 61e955e..c4bd2c3 100644 --- a/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs +++ b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs @@ -1,4 +1,6 @@ -using System.Text.Json; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.Options; +using System.Text.Json; using AsyncMonolith.Consumers; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -38,7 +40,8 @@ public static class TestConsumerMessageProcessor var consumer = scope.ServiceProvider.GetRequiredService(consumerType); var maxAttempts = scope.ServiceProvider.GetRequiredService().ResolveConsumerMaxAttempts(message); - await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), null, + var serializerOptions = scope.ServiceProvider.GetService>()?.Value.SerializerOptions; + await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), serializerOptions, cancellationToken); consumerMessageSet.Remove(message); @@ -76,7 +79,8 @@ await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxA var consumer = scope.ServiceProvider.GetRequiredService(consumerType); var maxAttempts = scope.ServiceProvider.GetRequiredService().ResolveConsumerMaxAttempts(message); - await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), null, + var serializerOptions = scope.ServiceProvider.GetService>()?.Value.SerializerOptions; + await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), serializerOptions, cancellationToken); consumerMessageSet.Remove(message); diff --git a/AsyncMonolith.Tests/Infra/SerializationConsumer.cs b/AsyncMonolith.Tests/Infra/SerializationConsumer.cs new file mode 100644 index 0000000..0c2a9e4 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/SerializationConsumer.cs @@ -0,0 +1,30 @@ +using AsyncMonolith.Consumers; + +namespace AsyncMonolith.Tests.Infra; + +public enum Priority +{ + Normal, + Urgent +} + +/// No [JsonPropertyName] attributes, so the serializer options decide the stored names. +public class SerializationMessage : IConsumerPayload +{ + public required string FirstName { get; set; } + public Priority Priority { get; set; } +} + +public sealed class SerializationRecorder +{ + public List Received { get; } = []; +} + +public class SerializationConsumer(SerializationRecorder recorder) : IConsumer +{ + public Task Consume(SerializationMessage payload, ConsumeContext context, CancellationToken cancellationToken) + { + recorder.Received.Add(payload); + return Task.CompletedTask; + } +} diff --git a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs index 7ad8b7a..506a5a5 100644 --- a/AsyncMonolith.Tests/Infra/SqliteTestHost.cs +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -82,6 +82,7 @@ public static async Task Create(Action? co services.AddSingleton>(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); var provider = services.BuildServiceProvider(); using (var scope = provider.CreateScope()) diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 06be428..fa8daa1 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -40,6 +40,7 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A o.BatchSize = settings.BatchSize; o.IdlePollInterval = settings.IdlePollInterval; o.BusyPollInterval = settings.BusyPollInterval; + o.SerializerOptions = settings.SerializerOptions; }); settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); diff --git a/AsyncMonolith.Tests/SchedulingTests.cs b/AsyncMonolith.Tests/SchedulingTests.cs index c4bb336..97085ae 100644 --- a/AsyncMonolith.Tests/SchedulingTests.cs +++ b/AsyncMonolith.Tests/SchedulingTests.cs @@ -53,9 +53,24 @@ public void Next_occurrence_is_strictly_after_now() } [Fact] - public void Cron_expressions_require_a_seconds_field() + public void Five_field_cron_expressions_are_accepted_with_minute_precision() { - Should.Throw(() => Message("0 9 * * *", "UTC").GetNextOccurrence(Clock())); + Message("0 9 * * *", "UTC").GetNextOccurrence(Clock()).ShouldBe(Utc("2020-09-01T09:00:00Z")); + Message("*/15 * * * *", "UTC").GetNextOccurrence(Clock()).ShouldBe(Utc("2020-08-31T10:15:00Z")); + } + + [Fact] + public void Six_field_cron_expressions_start_with_seconds() + { + Message("30 0 9 * * *", "UTC").GetNextOccurrence(Clock()).ShouldBe(Utc("2020-09-01T09:00:30Z")); + } + + [Theory] + [InlineData("0 9 * *")] + [InlineData("0 0 0 9 * * *")] + public void Cron_expressions_with_the_wrong_number_of_fields_are_rejected(string expression) + { + Should.Throw(() => Message(expression, "UTC").GetNextOccurrence(Clock())); } [Fact] diff --git a/AsyncMonolith.Tests/SerializationTests.cs b/AsyncMonolith.Tests/SerializationTests.cs new file mode 100644 index 0000000..09f4511 --- /dev/null +++ b/AsyncMonolith.Tests/SerializationTests.cs @@ -0,0 +1,54 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using AsyncMonolith.Tests.Infra; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Payload serialization, with the default and with custom JsonSerializerOptions. +/// +public class SerializationTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Payloads_use_System_Text_Json_defaults_unless_configured() + { + await using var host = await SqliteTestHost.Create(); + + await host.Produce(new SerializationMessage { FirstName = "Ada", Priority = Priority.Urgent }); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().Payload + .ShouldBe("""{"FirstName":"Ada","Priority":1}"""); + } + + [Fact] + public async Task Custom_serializer_options_are_used_to_store_and_to_consume() + { + await using var host = await SqliteTestHost.Create(s => s.SerializerOptions = + new JsonSerializerOptions(JsonSerializerDefaults.Web) { Converters = { new JsonStringEnumConverter() } }); + + await host.Produce(new SerializationMessage { FirstName = "Ada", Priority = Priority.Urgent }); + (await host.ConsumerMessages()).ShouldHaveSingleItem().Payload + .ShouldBe("""{"firstName":"Ada","priority":"Urgent"}"""); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + + var received = host.Services.GetRequiredService().Received.ShouldHaveSingleItem(); + received.FirstName.ShouldBe("Ada"); + received.Priority.ShouldBe(Priority.Urgent); + } + + [Fact] + public async Task Custom_serializer_options_are_used_for_schedules() + { + await using var host = await SqliteTestHost.Create(s => s.SerializerOptions = + new JsonSerializerOptions(JsonSerializerDefaults.Web)); + + await host.Schedule(new SerializationMessage { FirstName = "Ada" }, "0 * * * * *"); + + (await host.ScheduledMessages()).ShouldHaveSingleItem().Payload.ShouldContain("\"firstName\""); + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index f70439f..7d7d3e5 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -298,7 +298,8 @@ await leased.ExecuteUpdateAsync(s => s var consumer = scope.ServiceProvider.GetRequiredService(consumerType); var context = ConsumeContext.For(message, _consumerRegistry.ResolveConsumerMaxAttempts(message)); - await ConsumerInvoker.Invoke(consumer, message, context, null, timeoutCancellationToken.Token); + await ConsumerInvoker.Invoke(consumer, message, context, _options.Value.SerializerOptions, + timeoutCancellationToken.Token); activity?.SetStatus(ActivityStatusCode.Ok); _logger.ConsumerMessageProcessed(message.ConsumerType); diff --git a/AsyncMonolith/Producers/ProducerService.cs b/AsyncMonolith/Producers/ProducerService.cs index f85655e..74b68df 100644 --- a/AsyncMonolith/Producers/ProducerService.cs +++ b/AsyncMonolith/Producers/ProducerService.cs @@ -4,6 +4,7 @@ using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; namespace AsyncMonolith.Producers; @@ -23,10 +24,12 @@ internal sealed class ProducerService : IProducerService where T : DbContext private readonly T _dbContext; private readonly IAsyncMonolithIdGenerator _idGenerator; private readonly TimeProvider _timeProvider; + private readonly JsonSerializerOptions? _serializerOptions; public ProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator) + IAsyncMonolithIdGenerator idGenerator, IOptions options) { + _serializerOptions = options.Value.SerializerOptions; _timeProvider = timeProvider; _consumerRegistry = consumerRegistry; _dbContext = dbContext; @@ -52,7 +55,7 @@ public Task ProduceList(IEnumerable payloads, TimeSpan? dela var availableAfter = AvailableAfter(delay); foreach (var payload in payloads) { - Add(payloadType, JsonSerializer.Serialize(payload), consumers, availableAfter, _idGenerator.GenerateId(), + Add(payloadType, JsonSerializer.Serialize(payload, _serializerOptions), consumers, availableAfter, _idGenerator.GenerateId(), Activity.Current); } @@ -78,7 +81,7 @@ private async Task Produce(TPayload payload, long availableAfter, stri consumers = consumers.Where(c => !pending.Contains(c)).ToList(); } - Add(payloadType, JsonSerializer.Serialize(payload), consumers, availableAfter, + Add(payloadType, JsonSerializer.Serialize(payload, _serializerOptions), consumers, availableAfter, deduplicationKey ?? _idGenerator.GenerateId(), Activity.Current); } diff --git a/AsyncMonolith/Scheduling/Cron.cs b/AsyncMonolith/Scheduling/Cron.cs new file mode 100644 index 0000000..8a4164c --- /dev/null +++ b/AsyncMonolith/Scheduling/Cron.cs @@ -0,0 +1,13 @@ +using Cronos; + +namespace AsyncMonolith.Scheduling; + +/// Parses cron expressions with 5 fields (minute precision) or 6 fields (with seconds first). +internal static class Cron +{ + public static CronExpression Parse(string expression) + { + var fields = expression.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Length; + return CronExpression.Parse(expression, fields == 6 ? CronFormat.IncludeSeconds : CronFormat.Standard); + } +} diff --git a/AsyncMonolith/Scheduling/IScheduleService.cs b/AsyncMonolith/Scheduling/IScheduleService.cs index d42709e..d5de22e 100644 --- a/AsyncMonolith/Scheduling/IScheduleService.cs +++ b/AsyncMonolith/Scheduling/IScheduleService.cs @@ -12,7 +12,7 @@ public interface IScheduleService /// /// The type of the message. /// The message to schedule. - /// The cron expression. + /// A cron expression with 5 fields, or 6 with seconds first. /// The timezone for the cron expression. /// The optional tag for the scheduled message. /// The ID of the scheduled message. @@ -27,7 +27,7 @@ public string Schedule(TPayload message, string cronExpression, string /// /// The type of the message payload. /// The message payload. - /// The cron expression, including seconds. + /// A cron expression with 5 fields, or 6 with seconds first. /// The timezone the expression is evaluated in. /// The tag that identifies this schedule. /// The cancellation token. diff --git a/AsyncMonolith/Scheduling/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index e15391d..26664c7 100644 --- a/AsyncMonolith/Scheduling/ScheduleService.cs +++ b/AsyncMonolith/Scheduling/ScheduleService.cs @@ -3,6 +3,7 @@ using AsyncMonolith.Utilities; using Cronos; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; namespace AsyncMonolith.Scheduling; @@ -15,6 +16,7 @@ internal sealed class ScheduleService : IScheduleService where T : DbContext private readonly T _dbContext; private readonly IAsyncMonolithIdGenerator _idGenerator; private readonly TimeProvider _timeProvider; + private readonly IOptions _options; /// /// Initializes a new instance of the class. @@ -22,9 +24,12 @@ internal sealed class ScheduleService : IScheduleService where T : DbContext /// The time provider. /// The DbContext. /// The ID generator. - public ScheduleService(TimeProvider timeProvider, T dbContext, IAsyncMonolithIdGenerator idGenerator) + /// The AsyncMonolith options. + public ScheduleService(TimeProvider timeProvider, T dbContext, IAsyncMonolithIdGenerator idGenerator, + IOptions options) { _timeProvider = timeProvider; + _options = options; _dbContext = dbContext; _idGenerator = idGenerator; } @@ -41,10 +46,10 @@ public ScheduleService(TimeProvider timeProvider, T dbContext, IAsyncMonolithIdG public string Schedule(TPayload message, string cronExpression, string timeZone, string? tag = null) where TPayload : IConsumerPayload { - var payload = JsonSerializer.Serialize(message); + var payload = JsonSerializer.Serialize(message, _options.Value.SerializerOptions); var id = _idGenerator.GenerateId(); - var expression = Cronos.CronExpression.Parse(cronExpression, Cronos.CronFormat.IncludeSeconds); + var expression = Cron.Parse(cronExpression); var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZone); if (timezone == null) @@ -89,7 +94,7 @@ public async Task EnsureSchedule(TPayload message, string cron var schedule = existing[0]; set.RemoveRange(existing.Skip(1)); - schedule.UpdatePayload(message); + schedule.UpdatePayload(message, _options.Value.SerializerOptions); if (schedule.CronExpression != cronExpression || schedule.CronTimeZone != timeZone) { schedule.UpdateSchedule(cronExpression, timeZone, _timeProvider); diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index 69721e1..2eb8b60 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessage.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessage.cs @@ -69,7 +69,7 @@ public class ScheduledMessage /// The next occurrence of the scheduled message in Unix timestamp format. internal long GetNextOccurrence(TimeProvider timeProvider) { - var expression = Cronos.CronExpression.Parse(CronExpression, Cronos.CronFormat.IncludeSeconds); + var expression = Cron.Parse(CronExpression); var timezone = TimeZoneInfo.FindSystemTimeZoneById(CronTimeZone); if (timezone == null) @@ -104,9 +104,10 @@ internal void UpdateSchedule(string cronExpression, string timeZone, TimeProvide /// /// The type of the payload. /// The payload message. - internal void UpdatePayload(TPayload message) where TPayload : IConsumerPayload + /// The JSON serializer options, or null for the defaults. + internal void UpdatePayload(TPayload message, JsonSerializerOptions? serializerOptions = null) where TPayload : IConsumerPayload { - var payload = JsonSerializer.Serialize(message); + var payload = JsonSerializer.Serialize(message, serializerOptions); Payload = payload; PayloadType = AsyncMonolithNames.ForPayload(); } diff --git a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs index a033f79..00f91ed 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs @@ -1,4 +1,5 @@ using System.Reflection; +using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -51,6 +52,13 @@ public sealed class AsyncMonolithOptions /// public TimeSpan BusyPollInterval { get; set; } = TimeSpan.FromMilliseconds(10); + /// + /// How payloads are serialized to and from JSON. Null (the default) uses System.Text.Json's defaults. + /// Changing it changes the stored format, so messages and schedules already stored with different settings + /// may no longer deserialize. Set it in code; it isn't read from configuration. + /// + public JsonSerializerOptions? SerializerOptions { get; set; } + /// /// Gets the delay before retrying a message that has failed times. /// diff --git a/docs/guides/scheduling-messages.md b/docs/guides/scheduling-messages.md index d47f247..e2e29d8 100644 --- a/docs/guides/scheduling-messages.md +++ b/docs/guides/scheduling-messages.md @@ -12,6 +12,10 @@ To produce your message you'll need to inject a `IScheduleService` }, "0 0 12 * * MON", "UTC", "id:{id}"); await _dbContext.SaveChangesAsync(cancellationToken); ``` +## Cron expressions + +Expressions can have 5 fields (`minute hour day month weekday`, for example `0 9 * * *` for 09:00 daily) or 6 fields with seconds first (`30 0 9 * * *` for 09:00:30). They are evaluated in the time zone you pass, using an IANA id such as `Europe/London` or `UTC`. + ## Registering schedules at startup `Schedule` always inserts a new schedule, so calling it at every startup creates duplicates. Use `EnsureSchedule` with a tag instead. It creates the schedule the first time, and afterwards updates the payload. It only recalculates the next occurrence if the expression or timezone changed, and removes any duplicates with the same tag. diff --git a/docs/releases.md b/docs/releases.md index 702122a..b254461 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -22,6 +22,8 @@ All packages now share one version and must be upgraded together. From 11.0.0 th **Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** +- Cron expressions can have 5 fields (minute precision) as well as 6 (seconds first). +- `AsyncMonolithOptions.SerializerOptions` sets the `JsonSerializerOptions` for payloads. The default is unchanged. - Tables can live in their own schema or have a prefix: `modelBuilder.ConfigureAsyncMonolith(o => { o.Schema = "jobs"; o.TablePrefix = "jobs_"; })`. The database packages' SQL follows the mapping. - Every database package now produces messages the same way: they are added to your `DbContext` and written on `SaveChanges`, in your transaction. The PostgreSQL, SQL Server, MySQL and MariaDB packages used to write immediately. A repeated insert id skips consumers that already have a pending message with it, on every database. - Several app instances can safely share the tables with any database package. Claims and schedule occurrences use conditional updates, so a message is processed by one processor at a time and a schedule fires once per occurrence. From 551b86d264de8306fe7248c680804b0b9e1e6747 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:23:49 +0000 Subject: [PATCH 39/53] Make the database packages provider-agnostic and drop Pomelo The PostgreSQL, SQL Server, MySQL and MariaDB packages referenced a database driver only to build SQL parameters. MySQL and MariaDB pulled in Pomelo, which has no EF Core 10 release, plus a pinned MySqlConnector. - Every fetcher passes its values as EF positional parameters, so the packages depend only on AsyncMonolith and EF Core Relational. The host chooses its EF provider (for MySQL, Oracle's MySql.EntityFrameworkCore or Pomelo once it supports EF Core 10). - Schedule fetchers on PostgreSQL, MySQL and MariaDB now order by due time, then id; they had no ORDER BY. - SQL Server fetchers add UPDLOCK. ROWLOCK, READPAST alone does not hold row locks in a plain SELECT, so batches weren't actually locked. - Tests use Oracle's MySql.EntityFrameworkCore 10.0.12, and the MySQL and MariaDB integration tests are switched back on. --- .../AsyncMonolith.MariaDb.csproj | 6 +--- .../MariaDbConsumerMessageFetcher.cs | 35 ++++--------------- .../MariaDbScheduledMessageFetcher.cs | 30 ++++------------ .../AsyncMonolith.MsSql.csproj | 2 +- .../MsSqlConsumerMessageFetcher.cs | 33 ++++------------- .../MsSqlScheduledMessageFetcher.cs | 28 ++++----------- .../AsyncMonolith.MySql.csproj | 6 +--- .../MySqlConsumerMessageFetcher.cs | 35 ++++--------------- .../MySqlScheduledMessageFetcher.cs | 30 ++++------------ .../AsyncMonolith.PostgreSql.csproj | 2 +- .../PostgreSqlConsumerMessageFetcher.cs | 35 ++++--------------- .../PostgreSqlScheduledMessageFetcher.cs | 30 ++++------------ .../AsyncMonolith.Tests.csproj | 5 ++- AsyncMonolith.Tests/Infra/DbTestsBase.cs | 16 ++++----- .../Infra/MariaDbTestDbContainer.cs | 2 +- .../Infra/MySqlTestDbContainer.cs | 2 +- Directory.Packages.props | 3 +- 17 files changed, 69 insertions(+), 231 deletions(-) diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index c79b25b..ece45dd 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -1,9 +1,7 @@  - - $(NoWarn);NU1608 - + preview.1 $(NoWarn);NU5104 true @@ -30,9 +28,7 @@ - - diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs index fa8af15..e608112 100644 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs @@ -1,51 +1,30 @@ -using System.Globalization; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; -using MySqlConnector; namespace AsyncMonolith.MariaDb; /// -/// Represents a message fetcher for consumer messages in MariaDb. +/// Fetches due consumer messages on this rail for MariaDB, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for MariaDB. /// internal sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher { - private const string MariaDb = @" - SELECT * - FROM {table} - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at, id - LIMIT @batchSize - FOR UPDATE SKIP LOCKED"; + private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolith settings. public MariaDbConsumerMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches consumer messages from the database. - /// - /// The DbSet of consumer messages. - /// The current time. - /// The message rail to fetch messages from. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of consumer messages. public Task> Fetch(DbSet consumerSet, long currentTime, int railId, CancellationToken cancellationToken = default) { - return consumerSet - .FromSqlRaw(MariaDb.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@railId", railId), - new MySqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); + return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs index f43445f..2aea68d 100644 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs @@ -1,48 +1,30 @@ -using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; -using MySqlConnector; namespace AsyncMonolith.MariaDb; /// -/// Fetches scheduled messages from MariaDb. +/// Fetches due schedules for MariaDB, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for MariaDB. /// internal sealed class MariaDbScheduledMessageFetcher : IScheduledMessageFetcher { - private const string MariaDb = @" - SELECT * - FROM {table} - WHERE available_after <= @currentTime - LIMIT @batchSize - FOR UPDATE SKIP LOCKED"; + private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolith. public MariaDbScheduledMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches scheduled messages from the database. - /// - /// The of scheduled messages. - /// The current time. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of fetched scheduled messages. public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return scheduledMessageSet - .FromSqlRaw(MariaDb.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); + return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index 176e643..211ef65 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -25,7 +25,7 @@ - + diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs index a0dd897..1ec8aa1 100644 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs @@ -1,49 +1,30 @@ -using System.Globalization; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; -using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; namespace AsyncMonolith.MsSql; /// -/// Represents a message fetcher for consuming messages from a SQL Server database. +/// Fetches due consumer messages on this rail for SQL Server, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for SQL Server. /// internal sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher { - private const string MsSql = @" - SELECT TOP (@batchSize) * - FROM {table} WITH (ROWLOCK, READPAST) - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at, id"; + private const string Sql = "SELECT TOP ({2}) * FROM {table} WITH (ROWLOCK, UPDLOCK, READPAST) WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for the AsyncMonolith settings. public MsSqlConsumerMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches a batch of consumer messages from the database. - /// - /// The of consumer messages. - /// The current time. - /// The message rail to fetch messages from. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the list of fetched consumer messages. public Task> Fetch(DbSet consumerSet, long currentTime, int railId, CancellationToken cancellationToken = default) { - return consumerSet - .FromSqlRaw(MsSql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new SqlParameter("@currentTime", currentTime), - new SqlParameter("@railId", railId), - new SqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); + return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs index a602bb7..3ba4e07 100644 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs @@ -1,46 +1,30 @@ -using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; -using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; namespace AsyncMonolith.MsSql; /// -/// Fetches scheduled messages from the MsSql database. +/// Fetches due schedules for SQL Server, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for SQL Server. /// internal sealed class MsSqlScheduledMessageFetcher : IScheduledMessageFetcher { - private const string MsSql = @" - SELECT TOP (@batchSize) * - FROM {table} WITH (ROWLOCK, READPAST) - WHERE available_after <= @currentTime"; + private const string Sql = "SELECT TOP ({1}) * FROM {table} WITH (ROWLOCK, UPDLOCK, READPAST) WHERE available_after <= {0} ORDER BY available_after, id"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for the AsyncMonolith settings. public MsSqlScheduledMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches scheduled messages from the database. - /// - /// The DbSet of scheduled messages. - /// The current time. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of scheduled messages. public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return scheduledMessageSet - .FromSqlRaw(MsSql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new SqlParameter("@currentTime", currentTime), - new SqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); + return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 3397cf9..737b9b9 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -1,9 +1,7 @@  - - $(NoWarn);NU1608 - + preview.1 $(NoWarn);NU5104 true @@ -30,9 +28,7 @@ - - diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs index b3c653b..1bcf5bf 100644 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs @@ -1,51 +1,30 @@ -using System.Globalization; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; -using MySqlConnector; namespace AsyncMonolith.MySql; /// -/// Represents a message fetcher for consumer messages in MySQL. +/// Fetches due consumer messages on this rail for MySQL, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for MySQL. /// internal sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher { - private const string MySql = @" - SELECT * - FROM {table} - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at, id - LIMIT @batchSize - FOR UPDATE SKIP LOCKED"; + private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolith settings. public MySqlConsumerMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches consumer messages from the database. - /// - /// The DbSet of consumer messages. - /// The current time. - /// The message rail to fetch messages from. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of consumer messages. public Task> Fetch(DbSet consumerSet, long currentTime, int railId, CancellationToken cancellationToken = default) { - return consumerSet - .FromSqlRaw(MySql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@railId", railId), - new MySqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); + return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs index 09af4a5..e5e947e 100644 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs @@ -1,48 +1,30 @@ -using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; -using MySqlConnector; namespace AsyncMonolith.MySql; /// -/// Fetches scheduled messages from MySQL database. +/// Fetches due schedules for MySQL, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for MySQL. /// internal sealed class MySqlScheduledMessageFetcher : IScheduledMessageFetcher { - private const string MySql = @" - SELECT * - FROM {table} - WHERE available_after <= @currentTime - LIMIT @batchSize - FOR UPDATE SKIP LOCKED"; + private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolith. public MySqlScheduledMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches scheduled messages from the database. - /// - /// The of scheduled messages. - /// The current time. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of fetched scheduled messages. public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return scheduledMessageSet - .FromSqlRaw(MySql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); + return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index 5bd8064..6eb4e69 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -25,7 +25,7 @@ - + diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs index 2085533..fbace43 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs @@ -1,51 +1,30 @@ -using System.Globalization; -using AsyncMonolith.Consumers; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; -using Npgsql; namespace AsyncMonolith.PostgreSql; /// -/// Represents a consumer message fetcher implementation for PostgreSQL. +/// Fetches due consumer messages on this rail for PostgreSQL, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for PostgreSQL. /// internal sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher { - private const string PgSql = @" - SELECT * - FROM {table} - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at, id - FOR UPDATE SKIP LOCKED - LIMIT @batchSize"; + private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for the AsyncMonolith settings. public PostgreSqlConsumerMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches a batch of consumer messages from the PostgreSQL database. - /// - /// The DbSet of consumer messages. - /// The current time. - /// The message rail to fetch messages from. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the list of fetched consumer messages. public Task> Fetch(DbSet consumerSet, long currentTime, int railId, CancellationToken cancellationToken = default) { - return consumerSet - .FromSqlRaw(PgSql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), new NpgsqlParameter("@currentTime", currentTime), - new NpgsqlParameter("@railId", railId), - new NpgsqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); + return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs index 376afee..7fda19a 100644 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs @@ -1,48 +1,30 @@ -using System.Globalization; +using AsyncMonolith.Consumers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; -using Npgsql; namespace AsyncMonolith.PostgreSql; /// -/// Fetches scheduled messages from a PostgreSQL database. +/// Fetches due schedules for PostgreSQL, locking the rows and skipping rows other processors have locked. Values are +/// passed as EF parameters, so this works with any EF Core provider for PostgreSQL. /// internal sealed class PostgreSqlScheduledMessageFetcher : IScheduledMessageFetcher { - private const string PgSql = @" - SELECT * - FROM {table} - WHERE available_after <= @currentTime - FOR UPDATE SKIP LOCKED - LIMIT @batchSize"; + private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; private readonly IOptions _options; - /// - /// Initializes a new instance of the class. - /// - /// The options for the AsyncMonolith. public PostgreSqlScheduledMessageFetcher(IOptions options) { _options = options; } - /// - /// Fetches scheduled messages from the database. - /// - /// The of scheduled messages. - /// The current time. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of fetched scheduled messages. public Task> Fetch(DbSet scheduledMessageSet, long currentTime, CancellationToken cancellationToken = default) { - return scheduledMessageSet - .FromSqlRaw(PgSql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), new NpgsqlParameter("@currentTime", currentTime), - new NpgsqlParameter("@batchSize", _options.Value.BatchSize)) - .ToListAsync(cancellationToken); + var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); + return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); } } diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index e631d31..f6746c4 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -1,8 +1,7 @@  - - $(NoWarn);NU1608;CA1707 + $(NoWarn);CA1707 false true Exe @@ -23,7 +22,7 @@ - + diff --git a/AsyncMonolith.Tests/Infra/DbTestsBase.cs b/AsyncMonolith.Tests/Infra/DbTestsBase.cs index fbaac7a..7921c00 100644 --- a/AsyncMonolith.Tests/Infra/DbTestsBase.cs +++ b/AsyncMonolith.Tests/Infra/DbTestsBase.cs @@ -57,28 +57,28 @@ protected async Task Setup(TestDbContainerBase dbContainer, Asy } public static IEnumerable GetTestDbContainers() { - // yield return new object[] { new MySqlTestDbContainer() }; + yield return new object[] { new MySqlTestDbContainer() }; yield return new object[] { new MsSqlTestDbContainer() }; yield return new object[] { new PostgreSqlTestDbContainer() }; yield return new object[] { new EfTestDbContainer() }; - // yield return new object[] { new MariaDbTestDbContainer() }; + yield return new object[] { new MariaDbTestDbContainer() }; } public static IEnumerable GetTestDbTypes() { - // yield return new object[] { DbType.MySql }; + yield return new object[] { DbType.MySql }; yield return new object[] { DbType.Ef }; yield return new object[] { DbType.MsSql }; yield return new object[] { DbType.PostgreSql }; - // yield return new object[] { DbType.MariaDb }; + yield return new object[] { DbType.MariaDb }; } public static IEnumerable GetTestDbTypesWithoutEf() { - // yield return new object[] { DbType.MySql }; + yield return new object[] { DbType.MySql }; yield return new object[] { DbType.MsSql }; yield return new object[] { DbType.PostgreSql }; - // yield return new object[] { DbType.MariaDb }; + yield return new object[] { DbType.MariaDb }; } public static TestDbContainerBase GetTestDbContainer(DbType dbType) @@ -86,10 +86,10 @@ public static TestDbContainerBase GetTestDbContainer(DbType dbType) return dbType switch { DbType.Ef => new EfTestDbContainer(), - // DbType.MySql => new MySqlTestDbContainer(), + DbType.MySql => new MySqlTestDbContainer(), DbType.MsSql => new MsSqlTestDbContainer(), DbType.PostgreSql => new PostgreSqlTestDbContainer(), - // DbType.MariaDb => new MariaDbTestDbContainer(), + DbType.MariaDb => new MariaDbTestDbContainer(), _ => throw new ArgumentOutOfRangeException(nameof(dbType), dbType, null) }; diff --git a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs index 5985803..c75572d 100644 --- a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs @@ -19,7 +19,7 @@ public override void AddDb(ServiceCollection services) { services.AddDbContext((sp, options) => { - options.UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString)); + options.UseMySQL(ConnectionString); } ); } diff --git a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs index dfbe54c..a96dad3 100644 --- a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs @@ -18,7 +18,7 @@ public override void AddDb(ServiceCollection services) { services.AddDbContext((sp, options) => { - options.UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString)); + options.UseMySQL(ConnectionString); } ); } diff --git a/Directory.Packages.props b/Directory.Packages.props index ca3435f..4601b17 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,8 +12,6 @@ - - @@ -24,6 +22,7 @@ + From e9d273f335dabb8ebbfa0f4ea8be0fbf7a97cee9 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:24:58 +0000 Subject: [PATCH 40/53] Stop one bad schedule from blocking every schedule The scheduler processed a batch in one transaction, so a single schedule that couldn't be evaluated (an invalid cron expression or time zone, or no future occurrence) or whose payload had no registered consumers (for example after a module was removed) rolled the batch back on every poll, and no schedule fired again. Each schedule is now handled on its own: - One that can't be evaluated is logged (event 6) and checked again in an hour, so it neither blocks the batch nor floods the log. - One whose payload has no consumers moves to its next occurrence and logs the skipped occurrence (event 7). The schedule is kept, so it works again once the consumer is back. Tests cover a bad expression, a bad time zone and a payload without consumers, each alongside a healthy schedule that keeps firing. --- AsyncMonolith.Tests/SchedulingTests.cs | 49 +++++++++++++++++++ .../Scheduling/ScheduledMessageProcessor.cs | 45 ++++++++++++++--- AsyncMonolith/Utilities/AsyncMonolithLog.cs | 10 ++++ 3 files changed, 98 insertions(+), 6 deletions(-) diff --git a/AsyncMonolith.Tests/SchedulingTests.cs b/AsyncMonolith.Tests/SchedulingTests.cs index 97085ae..e5ba836 100644 --- a/AsyncMonolith.Tests/SchedulingTests.cs +++ b/AsyncMonolith.Tests/SchedulingTests.cs @@ -248,4 +248,53 @@ public async Task Scheduled_processor_respects_the_batch_size() (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(1); (await host.ConsumerMessages()).Count.ShouldBe(3); } + + private static ScheduledMessage StoredSchedule(string id, string cron, string timeZone, string payloadType, + long availableAfter) => new() + { + Id = id, + Tag = id, + AvailableAfter = availableAfter, + CronExpression = cron, + CronTimeZone = timeZone, + PayloadType = payloadType, + Payload = "{\"name\":\"x\"}" + }; + + [Theory] + [InlineData("not a cron", "UTC")] + [InlineData("0 * * * * *", "Not/AZone")] + public async Task A_schedule_that_cant_be_evaluated_doesnt_stop_the_others(string cron, string timeZone) + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "good" }, "0 * * * * *"); + await host.Change(db => db.ScheduledMessages.Add( + StoredSchedule("broken", cron, timeZone, nameof(SingleConsumerMessage), host.Now))); + host.Time.Advance(TimeSpan.FromMinutes(1)); + + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(1); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().Payload.ShouldContain("good"); + var broken = (await host.ScheduledMessages()).Single(m => m.Id == "broken"); + broken.AvailableAfter.ShouldBe(host.Now + ScheduledMessageProcessor.InvalidScheduleRetrySeconds); + + // And it isn't retried every poll. + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(0); + } + + [Fact] + public async Task A_schedule_whose_payload_has_no_consumers_skips_the_occurrence_without_stopping_the_others() + { + await using var host = await SqliteTestHost.Create(); + await host.Schedule(new SingleConsumerMessage { Name = "good" }, "0 * * * * *"); + await host.Change(db => db.ScheduledMessages.Add( + StoredSchedule("orphan", "0 * * * * *", "UTC", "RemovedPayload", host.Now))); + host.Time.Advance(TimeSpan.FromMinutes(1)); + + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(1); + + (await host.ConsumerMessages()).ShouldHaveSingleItem().Payload.ShouldContain("good"); + (await host.ScheduledMessages()).Single(m => m.Id == "orphan").AvailableAfter + .ShouldBe(Utc("2020-08-31T10:02:00Z")); + } } diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index f1f43e8..ce4ccef 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -70,11 +70,15 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } } + /// How long to wait before checking a schedule that couldn't be evaluated again. + internal const int InvalidScheduleRetrySeconds = 3600; + /// - /// Processes a batch of scheduled messages. + /// Processes a batch of scheduled messages. A schedule that fails is logged and moved on; it never stops + /// the others. /// /// The cancellation token. - /// The number of processed scheduled messages. + /// The number of messages produced. internal async Task ProcessBatch(CancellationToken cancellationToken = default) { using var scope = _scopeFactory.CreateScope(); @@ -102,9 +106,23 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa foreach (var message in messages) { - // Move the schedule on only if no other processor has already done so for this occurrence. + // A schedule that can't be evaluated (bad cron expression or time zone, or no future occurrence) + // is checked again in an hour instead of blocking every other schedule in the batch. var dueAt = message.AvailableAfter; - var next = message.GetNextOccurrence(_timeProvider); + long next; + Exception? invalid = null; + try + { + next = message.GetNextOccurrence(_timeProvider); + } + catch (Exception ex) when (ex is FormatException or InvalidOperationException or ArgumentException + or TimeZoneNotFoundException or InvalidTimeZoneException) + { + invalid = ex; + next = currentTime + InvalidScheduleRetrySeconds; + } + + // Move the schedule on only if no other processor has already done so for this occurrence. var updated = await set .Where(m => m.Id == message.Id && m.AvailableAfter == dueAt) .ExecuteUpdateAsync(s => s.SetProperty(m => m.AvailableAfter, next), cancellationToken); @@ -113,8 +131,23 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa continue; } - producer.ProduceScheduled(message); - processedScheduledMessageCount++; + if (invalid is not null) + { + _logger.ScheduleInvalid(invalid, message.Id, message.Tag); + continue; + } + + try + { + producer.ProduceScheduled(message); + processedScheduledMessageCount++; + } + catch (InvalidOperationException ex) + { + // No registered consumers for the payload (for example a module was removed): skip this + // occurrence, keep the schedule. + _logger.ScheduledOccurrenceSkipped(ex, message.Id, message.PayloadType); + } } await dbContext.SaveChangesAsync(cancellationToken); diff --git a/AsyncMonolith/Utilities/AsyncMonolithLog.cs b/AsyncMonolith/Utilities/AsyncMonolithLog.cs index 6e65ae4..2bd32ff 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithLog.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithLog.cs @@ -22,4 +22,14 @@ internal static partial class AsyncMonolithLog [LoggerMessage(EventId = 5, Level = LogLevel.Information, Message = "Successfully scheduled message")] public static partial void ScheduledMessagesProduced(this ILogger logger); + + [LoggerMessage(EventId = 6, Level = LogLevel.Error, + Message = "Schedule '{ScheduleId}' (tag '{Tag}') can't be evaluated and will be checked again in an hour.")] + public static partial void ScheduleInvalid(this ILogger logger, Exception exception, string scheduleId, + string? tag); + + [LoggerMessage(EventId = 7, Level = LogLevel.Error, + Message = "Schedule '{ScheduleId}' skipped an occurrence: payload '{PayloadType}' has no registered consumers.")] + public static partial void ScheduledOccurrenceSkipped(this ILogger logger, Exception exception, string scheduleId, + string payloadType); } From 36b92cc66ac862a63e22594861a31b6211f4c9ce Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:25:54 +0000 Subject: [PATCH 41/53] Abandon consumers that ignore cancellation after their timeout Consumer timeouts relied on the consumer honouring its cancellation token. One that didn't held up its whole rail for as long as it ran, and its lease could expire meanwhile, letting the message run again elsewhere. The processor now stops waiting two seconds after the timeout, records the attempt as failed ("Timed out after N seconds and did not stop when cancelled."), logs event 8, and carries on with the batch. The abandoned task's eventual failure is observed so it isn't reported as unobserved. The docs say to pass the token to everything a consumer awaits. The test's consumer ignores its token for 20 seconds; the batch finishes in about 3 and the next message is still consumed. --- .../ConsumerProcessingTests.cs | 18 ++++++++++++++ AsyncMonolith.Tests/Infra/TimeoutConsumer.cs | 18 +++++++++++++- .../Consumers/ConsumerMessageProcessor.cs | 24 ++++++++++++++++++- AsyncMonolith/Utilities/AsyncMonolithLog.cs | 4 ++++ docs/guides/consuming-messages.md | 2 +- 5 files changed, 63 insertions(+), 3 deletions(-) diff --git a/AsyncMonolith.Tests/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs index e582ff7..7f9f4b6 100644 --- a/AsyncMonolith.Tests/ConsumerProcessingTests.cs +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -149,6 +149,24 @@ public async Task Consumer_that_exceeds_its_timeout_counts_as_a_failed_attempt() (await host.ConsumerMessages()).ShouldHaveSingleItem().Attempts.ShouldBe(1); } + [Fact] + public async Task A_consumer_that_ignores_cancellation_is_abandoned_after_its_timeout() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new StubbornMessage()); + await host.Produce(new SingleConsumerMessage { Name = "after" }); + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + + (await host.ConsumerProcessor.ProcessBatch(Ct)).ShouldBe(1); + + // 1 second timeout + 2 second grace, not the consumer's 20 seconds + stopwatch.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10)); + host.Invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + var stubborn = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + stubborn.Attempts.ShouldBe(1); + stubborn.LastError.ShouldBe("Timed out after 1 seconds and did not stop when cancelled."); + } + [Fact] public async Task Batch_size_limits_how_many_messages_are_processed_at_once() { diff --git a/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs b/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs index 56c9f94..9da4ab1 100644 --- a/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs +++ b/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs @@ -17,4 +17,20 @@ public async Task Consume(TimeoutConsumerMessage message, ConsumeContext context _consumerInvocations.Increment(nameof(TimeoutConsumer)); await Task.Delay(TimeSpan.FromSeconds(message.Delay), cancellationToken); } -} \ No newline at end of file +} +/// Ignores its cancellation token, as a badly written consumer might. +public class StubbornMessage : IConsumerPayload +{ +} + +[ConsumerTimeout(1)] +public class StubbornConsumer(TestConsumerInvocations invocations) : IConsumer +{ + public async Task Consume(StubbornMessage payload, ConsumeContext context, CancellationToken cancellationToken) + { + invocations.Increment(nameof(StubbornConsumer)); +#pragma warning disable CA2016 // Deliberately not passing the token + await Task.Delay(TimeSpan.FromSeconds(20)); +#pragma warning restore CA2016 + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 7d7d3e5..1d369ef 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -91,6 +91,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) /// internal const int LeaseGracePeriodSeconds = 30; + /// + /// How long after its timeout the processor keeps waiting for a consumer to stop before abandoning it. + /// + internal static readonly TimeSpan AbandonGracePeriod = TimeSpan.FromSeconds(2); + /// /// Claims and processes the next batch of consumer messages. /// @@ -298,8 +303,25 @@ await leased.ExecuteUpdateAsync(s => s var consumer = scope.ServiceProvider.GetRequiredService(consumerType); var context = ConsumeContext.For(message, _consumerRegistry.ResolveConsumerMaxAttempts(message)); - await ConsumerInvoker.Invoke(consumer, message, context, _options.Value.SerializerOptions, + var consuming = ConsumerInvoker.Invoke(consumer, message, context, _options.Value.SerializerOptions, timeoutCancellationToken.Token); + try + { + // Don't wait indefinitely for a consumer that ignores its cancellation token: it would hold up its + // rail, and its lease would expire while it ran. + await consuming.WaitAsync(TimeSpan.FromSeconds(consumerTimeout) + AbandonGracePeriod, + cancellationToken); + } + catch (TimeoutException ex) + { + // Observe the abandoned task's eventual failure so it isn't reported as unobserved. + _ = consuming.ContinueWith(t => _ = t.Exception, CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + _logger.ConsumerAbandoned(message.ConsumerType, consumerTimeout); + return $"Timed out after {consumerTimeout} seconds and did not stop when cancelled."; + } activity?.SetStatus(ActivityStatusCode.Ok); _logger.ConsumerMessageProcessed(message.ConsumerType); diff --git a/AsyncMonolith/Utilities/AsyncMonolithLog.cs b/AsyncMonolith/Utilities/AsyncMonolithLog.cs index 2bd32ff..92a14a8 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithLog.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithLog.cs @@ -23,6 +23,10 @@ internal static partial class AsyncMonolithLog [LoggerMessage(EventId = 5, Level = LogLevel.Information, Message = "Successfully scheduled message")] public static partial void ScheduledMessagesProduced(this ILogger logger); + [LoggerMessage(EventId = 8, Level = LogLevel.Error, + Message = "Consumer '{ConsumerType}' ignored cancellation after its {TimeoutSeconds} second timeout and was abandoned. Consumers must honour their CancellationToken.")] + public static partial void ConsumerAbandoned(this ILogger logger, string consumerType, int timeoutSeconds); + [LoggerMessage(EventId = 6, Level = LogLevel.Error, Message = "Schedule '{ScheduleId}' (tag '{Tag}') can't be evaluated and will be checked again in an hour.")] public static partial void ScheduleInvalid(this ILogger logger, Exception exception, string scheduleId, diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index fa6e18b..15a0215 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -5,7 +5,7 @@ - **Rails**: Each rail (`[ConsumerRailId]`) gets its own processor, so a slow consumer on one rail doesn't hold up consumers on another. - **Batching**: Consumer messages will be read from the `consumer_messages` table in batches defined by `BatchSize`. - **Idempotency**: Ensure your Consumers are idempotent, since they will be retried on failure. -- **Timeout**: Consumers timeout after the number of seconds defined by the `ConsumerTimeout` attribute or the `DefaultConsumerTimeout` if not set. +- **Timeout**: Consumers timeout after the number of seconds defined by the `ConsumerTimeout` attribute or the `DefaultConsumerTimeout` if not set. **Pass the `CancellationToken` to everything your consumer awaits.** A consumer that ignores it is abandoned two seconds after its timeout so its rail can carry on, but it may keep running in the background while the message is retried. Consumers implement `IConsumer`. The `ConsumeContext` describes the message and this attempt: `MessageId`, `DeduplicationKey`, `Attempt` (starting at 1), `MaxAttempts`, `IsLastAttempt`, `CreatedAt`, `ConsumerName`, `PayloadName` and `TraceId`. Use them for idempotency checks and logging. From df62d2bb8b5502d52b1ee6f683dfff324f679780 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:27:09 +0000 Subject: [PATCH 42/53] Index the columns the processors and services query The only index was the unique (insert_id, consumer_type) one, so finding due messages, due schedules and schedules by tag scanned whole tables, getting slower as they grew. The model adds indexes on consumer_messages (rail_id, available_after), scheduled_messages (available_after) and (tag), and poisoned_messages (created_at). The four SQL schemas and the example migrations include them, and SchemaFileTests now checks every model index is in every schema file. --- AsyncMonolith.Tests/SchemaFileTests.cs | 17 ++ AsyncMonolith/Utilities/AsyncMonolithModel.cs | 7 + .../20261120052636_QueueIndexes.Designer.cs | 245 ++++++++++++++++++ .../Migrations/20261120052636_QueueIndexes.cs | 54 ++++ .../ApplicationDbContextModelSnapshot.cs | 24 +- Schemas/asyncmonolith_mariadb.sql | 4 + Schemas/asyncmonolith_mssql.sql | 4 + Schemas/asyncmonolith_mysql.sql | 4 + Schemas/asyncmonolith_postgresql.sql | 4 + docs/releases.md | 2 +- 10 files changed, 356 insertions(+), 9 deletions(-) create mode 100644 Example/Example.Api/Migrations/20261120052636_QueueIndexes.Designer.cs create mode 100644 Example/Example.Api/Migrations/20261120052636_QueueIndexes.cs diff --git a/AsyncMonolith.Tests/SchemaFileTests.cs b/AsyncMonolith.Tests/SchemaFileTests.cs index 75e1641..1f924b5 100644 --- a/AsyncMonolith.Tests/SchemaFileTests.cs +++ b/AsyncMonolith.Tests/SchemaFileTests.cs @@ -71,4 +71,21 @@ public async Task Schema_file_has_every_model_column_with_matching_nullability(s } } } + + [Theory] + [MemberData(nameof(SchemaFiles))] + public async Task Schema_file_creates_every_model_index(string file) + { + await using var connection = new SqliteConnection("DataSource=:memory:"); + await using var db = new TestDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options); + var sql = await File.ReadAllTextAsync(SchemaPath(file), TestContext.Current.CancellationToken); + + foreach (var index in db.Model.GetEntityTypes().SelectMany(e => e.GetIndexes())) + { + var columns = string.Join(", ", index.Properties.Select(p => p.GetColumnName())); + var table = index.DeclaringEntityType.GetTableName(); + sql.ShouldContain($"{index.GetDatabaseName()}", customMessage: $"{file} should create {index.GetDatabaseName()}"); + sql.ShouldContain($"ON {table} ({columns})", customMessage: $"{file} should index {table} ({columns})"); + } + } } diff --git a/AsyncMonolith/Utilities/AsyncMonolithModel.cs b/AsyncMonolith/Utilities/AsyncMonolithModel.cs index fbac318..134078b 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithModel.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithModel.cs @@ -42,18 +42,25 @@ public static void Configure(ModelBuilder modelBuilder, AsyncMonolithModelOption entity.ToTable(options.TablePrefix + "consumer_messages", options.Schema); entity.HasKey(m => m.Id); entity.HasIndex(m => new { m.DeduplicationKey, m.ConsumerType }).IsUnique(); + // Processors look for due messages on their rail. + entity.HasIndex(m => new { m.RailId, m.AvailableAfter }); }); modelBuilder.Entity(entity => { entity.ToTable(options.TablePrefix + "poisoned_messages", options.Schema); entity.HasKey(m => m.Id); + // Listed newest first. + entity.HasIndex(m => m.CreatedAt); }); modelBuilder.Entity(entity => { entity.ToTable(options.TablePrefix + "scheduled_messages", options.Schema); entity.HasKey(m => m.Id); + // The scheduler looks for due schedules; EnsureSchedule and DeleteByTag look schedules up by tag. + entity.HasIndex(m => m.AvailableAfter); + entity.HasIndex(m => m.Tag); }); } } diff --git a/Example/Example.Api/Migrations/20261120052636_QueueIndexes.Designer.cs b/Example/Example.Api/Migrations/20261120052636_QueueIndexes.Designer.cs new file mode 100644 index 0000000..be822d3 --- /dev/null +++ b/Example/Example.Api/Migrations/20261120052636_QueueIndexes.Designer.cs @@ -0,0 +1,245 @@ +// +using Example.Api; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Demo.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261120052636_QueueIndexes")] + partial class QueueIndexes + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.15") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("AsyncMonolith.Consumers.ConsumerMessage", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id") + .HasJsonPropertyName("id"); + + b.Property("Attempts") + .HasColumnType("integer") + .HasColumnName("attempts") + .HasJsonPropertyName("attempts"); + + b.Property("AvailableAfter") + .HasColumnType("bigint") + .HasColumnName("available_after") + .HasJsonPropertyName("available_after"); + + b.Property("ConsumerType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("consumer_type") + .HasJsonPropertyName("consumer_type"); + + b.Property("CreatedAt") + .HasColumnType("bigint") + .HasColumnName("created_at") + .HasJsonPropertyName("created_at"); + + b.Property("DeduplicationKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("insert_id") + .HasJsonPropertyName("insert_id"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error") + .HasJsonPropertyName("last_error"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload") + .HasJsonPropertyName("payload"); + + b.Property("PayloadType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload_type") + .HasJsonPropertyName("payload_type"); + + b.Property("RailId") + .HasColumnType("integer") + .HasColumnName("rail_id") + .HasJsonPropertyName("rail_id"); + + b.Property("SpanId") + .HasColumnType("text") + .HasColumnName("span_id") + .HasJsonPropertyName("span_id"); + + b.Property("TraceId") + .HasColumnType("text") + .HasColumnName("trace_id") + .HasJsonPropertyName("trace_id"); + + b.HasKey("Id"); + + b.HasIndex("DeduplicationKey", "ConsumerType") + .IsUnique(); + + b.HasIndex("RailId", "AvailableAfter"); + + b.ToTable("consumer_messages", (string)null); + }); + + modelBuilder.Entity("AsyncMonolith.Consumers.PoisonedMessage", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id") + .HasJsonPropertyName("id"); + + b.Property("Attempts") + .HasColumnType("integer") + .HasColumnName("attempts") + .HasJsonPropertyName("attempts"); + + b.Property("AvailableAfter") + .HasColumnType("bigint") + .HasColumnName("available_after") + .HasJsonPropertyName("available_after"); + + b.Property("ConsumerType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("consumer_type") + .HasJsonPropertyName("consumer_type"); + + b.Property("CreatedAt") + .HasColumnType("bigint") + .HasColumnName("created_at") + .HasJsonPropertyName("created_at"); + + b.Property("DeduplicationKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("insert_id") + .HasJsonPropertyName("insert_id"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error") + .HasJsonPropertyName("last_error"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload") + .HasJsonPropertyName("payload"); + + b.Property("PayloadType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload_type") + .HasJsonPropertyName("payload_type"); + + b.Property("RailId") + .HasColumnType("integer") + .HasColumnName("rail_id") + .HasJsonPropertyName("rail_id"); + + b.Property("SpanId") + .HasColumnType("text") + .HasColumnName("span_id") + .HasJsonPropertyName("span_id"); + + b.Property("TraceId") + .HasColumnType("text") + .HasColumnName("trace_id") + .HasJsonPropertyName("trace_id"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.ToTable("poisoned_messages", (string)null); + }); + + modelBuilder.Entity("AsyncMonolith.Scheduling.ScheduledMessage", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id") + .HasJsonPropertyName("id"); + + b.Property("AvailableAfter") + .HasColumnType("bigint") + .HasColumnName("available_after") + .HasJsonPropertyName("available_after"); + + b.Property("CronExpression") + .IsRequired() + .HasColumnType("text") + .HasColumnName("chron_expression") + .HasJsonPropertyName("chron_expression"); + + b.Property("CronTimeZone") + .IsRequired() + .HasColumnType("text") + .HasColumnName("chron_timezone") + .HasJsonPropertyName("chron_timezone"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload") + .HasJsonPropertyName("payload"); + + b.Property("PayloadType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload_type") + .HasJsonPropertyName("payload_type"); + + b.Property("Tag") + .HasColumnType("text") + .HasColumnName("tag") + .HasJsonPropertyName("tag"); + + b.HasKey("Id"); + + b.HasIndex("AvailableAfter"); + + b.HasIndex("Tag"); + + b.ToTable("scheduled_messages", (string)null); + }); + + modelBuilder.Entity("Example.Api.Spam.SubmittedValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Value") + .HasColumnType("double precision") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.ToTable("submitted_values"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Example/Example.Api/Migrations/20261120052636_QueueIndexes.cs b/Example/Example.Api/Migrations/20261120052636_QueueIndexes.cs new file mode 100644 index 0000000..69fd100 --- /dev/null +++ b/Example/Example.Api/Migrations/20261120052636_QueueIndexes.cs @@ -0,0 +1,54 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Demo.Migrations +{ + /// + public partial class QueueIndexes : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateIndex( + name: "IX_scheduled_messages_available_after", + table: "scheduled_messages", + column: "available_after"); + + migrationBuilder.CreateIndex( + name: "IX_scheduled_messages_tag", + table: "scheduled_messages", + column: "tag"); + + migrationBuilder.CreateIndex( + name: "IX_poisoned_messages_created_at", + table: "poisoned_messages", + column: "created_at"); + + migrationBuilder.CreateIndex( + name: "IX_consumer_messages_rail_id_available_after", + table: "consumer_messages", + columns: new[] { "rail_id", "available_after" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_scheduled_messages_available_after", + table: "scheduled_messages"); + + migrationBuilder.DropIndex( + name: "IX_scheduled_messages_tag", + table: "scheduled_messages"); + + migrationBuilder.DropIndex( + name: "IX_poisoned_messages_created_at", + table: "poisoned_messages"); + + migrationBuilder.DropIndex( + name: "IX_consumer_messages_rail_id_available_after", + table: "consumer_messages"); + } + } +} diff --git a/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs b/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs index cd650c7..f208518 100644 --- a/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/Example/Example.Api/Migrations/ApplicationDbContextModelSnapshot.cs @@ -49,7 +49,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnName("created_at") .HasJsonPropertyName("created_at"); - b.Property("InsertId") + b.Property("DeduplicationKey") .IsRequired() .HasColumnType("text") .HasColumnName("insert_id") @@ -89,10 +89,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("InsertId", "ConsumerType") + b.HasIndex("DeduplicationKey", "ConsumerType") .IsUnique(); - b.ToTable("consumer_messages"); + b.HasIndex("RailId", "AvailableAfter"); + + b.ToTable("consumer_messages", (string)null); }); modelBuilder.Entity("AsyncMonolith.Consumers.PoisonedMessage", b => @@ -123,7 +125,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnName("created_at") .HasJsonPropertyName("created_at"); - b.Property("InsertId") + b.Property("DeduplicationKey") .IsRequired() .HasColumnType("text") .HasColumnName("insert_id") @@ -163,7 +165,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.ToTable("poisoned_messages"); + b.HasIndex("CreatedAt"); + + b.ToTable("poisoned_messages", (string)null); }); modelBuilder.Entity("AsyncMonolith.Scheduling.ScheduledMessage", b => @@ -178,13 +182,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnName("available_after") .HasJsonPropertyName("available_after"); - b.Property("ChronExpression") + b.Property("CronExpression") .IsRequired() .HasColumnType("text") .HasColumnName("chron_expression") .HasJsonPropertyName("chron_expression"); - b.Property("ChronTimezone") + b.Property("CronTimeZone") .IsRequired() .HasColumnType("text") .HasColumnName("chron_timezone") @@ -209,7 +213,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.ToTable("scheduled_messages"); + b.HasIndex("AvailableAfter"); + + b.HasIndex("Tag"); + + b.ToTable("scheduled_messages", (string)null); }); modelBuilder.Entity("Example.Api.Spam.SubmittedValue", b => diff --git a/Schemas/asyncmonolith_mariadb.sql b/Schemas/asyncmonolith_mariadb.sql index a73fa4f..efc469b 100644 --- a/Schemas/asyncmonolith_mariadb.sql +++ b/Schemas/asyncmonolith_mariadb.sql @@ -50,5 +50,9 @@ CREATE TABLE submitted_values ( ); CREATE UNIQUE INDEX IX_consumer_messages_insert_id_consumer_type ON consumer_messages (insert_id, consumer_type); +CREATE INDEX IX_consumer_messages_rail_id_available_after ON consumer_messages (rail_id, available_after); +CREATE INDEX IX_poisoned_messages_created_at ON poisoned_messages (created_at); +CREATE INDEX IX_scheduled_messages_available_after ON scheduled_messages (available_after); +CREATE INDEX IX_scheduled_messages_tag ON scheduled_messages (tag); COMMIT; diff --git a/Schemas/asyncmonolith_mssql.sql b/Schemas/asyncmonolith_mssql.sql index d753274..24bf3ae 100644 --- a/Schemas/asyncmonolith_mssql.sql +++ b/Schemas/asyncmonolith_mssql.sql @@ -52,5 +52,9 @@ CREATE TABLE submitted_values ( ); CREATE UNIQUE INDEX IX_consumer_messages_insert_id_consumer_type ON consumer_messages (insert_id, consumer_type); +CREATE INDEX IX_consumer_messages_rail_id_available_after ON consumer_messages (rail_id, available_after); +CREATE INDEX IX_poisoned_messages_created_at ON poisoned_messages (created_at); +CREATE INDEX IX_scheduled_messages_available_after ON scheduled_messages (available_after); +CREATE INDEX IX_scheduled_messages_tag ON scheduled_messages (tag); COMMIT; diff --git a/Schemas/asyncmonolith_mysql.sql b/Schemas/asyncmonolith_mysql.sql index a73fa4f..efc469b 100644 --- a/Schemas/asyncmonolith_mysql.sql +++ b/Schemas/asyncmonolith_mysql.sql @@ -50,5 +50,9 @@ CREATE TABLE submitted_values ( ); CREATE UNIQUE INDEX IX_consumer_messages_insert_id_consumer_type ON consumer_messages (insert_id, consumer_type); +CREATE INDEX IX_consumer_messages_rail_id_available_after ON consumer_messages (rail_id, available_after); +CREATE INDEX IX_poisoned_messages_created_at ON poisoned_messages (created_at); +CREATE INDEX IX_scheduled_messages_available_after ON scheduled_messages (available_after); +CREATE INDEX IX_scheduled_messages_tag ON scheduled_messages (tag); COMMIT; diff --git a/Schemas/asyncmonolith_postgresql.sql b/Schemas/asyncmonolith_postgresql.sql index 527c7c4..c4d6f01 100644 --- a/Schemas/asyncmonolith_postgresql.sql +++ b/Schemas/asyncmonolith_postgresql.sql @@ -52,6 +52,10 @@ CREATE TABLE submitted_values ( ); CREATE UNIQUE INDEX "IX_consumer_messages_insert_id_consumer_type" ON consumer_messages (insert_id, consumer_type); +CREATE INDEX "IX_consumer_messages_rail_id_available_after" ON consumer_messages (rail_id, available_after); +CREATE INDEX "IX_poisoned_messages_created_at" ON poisoned_messages (created_at); +CREATE INDEX "IX_scheduled_messages_available_after" ON scheduled_messages (available_after); +CREATE INDEX "IX_scheduled_messages_tag" ON scheduled_messages (tag); COMMIT; diff --git a/docs/releases.md b/docs/releases.md index b254461..1e5e00c 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -19,7 +19,7 @@ Make sure to check this table before updating the nuget package in your solution All packages now share one version and must be upgraded together. From 11.0.0 the major version follows [Semantic Versioning](https://semver.org) (it changes for breaking changes) rather than the .NET version. `AsyncMonolith.MySql` and `AsyncMonolith.MariaDb` are published as previews (`11.0.0-preview.1`) until Pomelo supports EF Core 10 and they run in the integration tests. -**Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. +**Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. It also adds indexes for finding due messages (`rail_id, available_after`), due schedules (`available_after`), schedules by tag, and poisoned messages by age, which keep processing fast as the tables grow. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** - Cron expressions can have 5 fields (minute precision) as well as 6 (seconds first). From dd4538b1ab5eb3f2adeb1e0e01b455de3daea2eb Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:27:09 +0000 Subject: [PATCH 43/53] Back off while batches keep failing, and stop quietly on shutdown Each processor logged an error every poll interval (one second by default) for as long as the database was unavailable. After repeated failures the wait now doubles from the idle interval up to 30 seconds, and resets after the next successful batch. Shutdown no longer logs a batch failure for the cancellation it causes, and the wait uses the injected TimeProvider. --- AsyncMonolith.Tests/PollingTests.cs | 38 +++++++++++++++++++ .../Consumers/ConsumerMessageProcessor.cs | 26 +++++++++---- .../Scheduling/ScheduledMessageProcessor.cs | 27 +++++++++---- AsyncMonolith/Utilities/ProcessorPolling.cs | 27 +++++++++++++ 4 files changed, 103 insertions(+), 15 deletions(-) create mode 100644 AsyncMonolith.Tests/PollingTests.cs create mode 100644 AsyncMonolith/Utilities/ProcessorPolling.cs diff --git a/AsyncMonolith.Tests/PollingTests.cs b/AsyncMonolith.Tests/PollingTests.cs new file mode 100644 index 0000000..6ee77fc --- /dev/null +++ b/AsyncMonolith.Tests/PollingTests.cs @@ -0,0 +1,38 @@ +using AsyncMonolith.Utilities; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// How long processors wait between batches. +/// +public class PollingTests +{ + private static readonly AsyncMonolithOptions Options = new() + { + BatchSize = 5, + IdlePollInterval = TimeSpan.FromSeconds(1), + BusyPollInterval = TimeSpan.FromMilliseconds(10) + }; + + [Theory] + [InlineData(0, 1000)] + [InlineData(4, 1000)] + [InlineData(5, 10)] + public void A_full_batch_polls_again_quickly(int processed, int expectedMilliseconds) + { + ProcessorPolling.NextDelay(Options, processed, 0).ShouldBe(TimeSpan.FromMilliseconds(expectedMilliseconds)); + } + + [Theory] + [InlineData(1, 2)] + [InlineData(2, 4)] + [InlineData(3, 8)] + [InlineData(4, 16)] + [InlineData(5, 30)] + [InlineData(1000, 30)] + public void Repeated_failures_back_off_up_to_thirty_seconds(int failures, int expectedSeconds) + { + ProcessorPolling.NextDelay(Options, 0, failures).ShouldBe(TimeSpan.FromSeconds(expectedSeconds)); + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 1d369ef..0531c90 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -62,25 +62,37 @@ public void SetRailId(int railId) /// A task representing the asynchronous operation. protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + var consecutiveFailures = 0; while (!stoppingToken.IsCancellationRequested) { - var delay = _options.Value.IdlePollInterval; + var processed = 0; try { - var processedMessageCount = await ProcessBatch(stoppingToken); - if (processedMessageCount == _options.Value.BatchSize) - { - delay = _options.Value.BusyPollInterval; - } + processed = await ProcessBatch(stoppingToken); + consecutiveFailures = 0; + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; } catch (Exception ex) { + // Back off while batches keep failing (for example while the database is unavailable). + consecutiveFailures++; _logger.ConsumerBatchFailed(ex); } + var delay = ProcessorPolling.NextDelay(_options.Value, processed, consecutiveFailures); if (delay > TimeSpan.Zero) { - await Task.Delay(delay, stoppingToken); + try + { + await Task.Delay(delay, _timeProvider, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } } } } diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index ce4ccef..33f9fe1 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -46,26 +46,37 @@ public ScheduledMessageProcessor(ILogger> logger, /// The cancellation token to stop the execution. protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + var consecutiveFailures = 0; while (!stoppingToken.IsCancellationRequested) { - var delay = _options.Value.IdlePollInterval; + var processed = 0; try { - var processedScheduledMessages = await ProcessBatch(stoppingToken); - - if (processedScheduledMessages >= _options.Value.BatchSize) - { - delay = _options.Value.BusyPollInterval; - } + processed = await ProcessBatch(stoppingToken); + consecutiveFailures = 0; + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; } catch (Exception ex) { + // Back off while batches keep failing (for example while the database is unavailable). + consecutiveFailures++; _logger.ScheduleBatchFailed(ex); } + var delay = ProcessorPolling.NextDelay(_options.Value, processed, consecutiveFailures); if (delay > TimeSpan.Zero) { - await Task.Delay(delay, stoppingToken); + try + { + await Task.Delay(delay, _timeProvider, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } } } } diff --git a/AsyncMonolith/Utilities/ProcessorPolling.cs b/AsyncMonolith/Utilities/ProcessorPolling.cs new file mode 100644 index 0000000..0196fc6 --- /dev/null +++ b/AsyncMonolith/Utilities/ProcessorPolling.cs @@ -0,0 +1,27 @@ +namespace AsyncMonolith.Utilities; + +/// How long a processor waits before its next batch. +internal static class ProcessorPolling +{ + /// The longest wait between attempts while batches keep failing (for example during an outage). + public static readonly TimeSpan MaxFailureDelay = TimeSpan.FromSeconds(30); + + /// The options. + /// How many items the last batch handled. + /// How many batches in a row have thrown, 0 if the last one succeeded. + public static TimeSpan NextDelay(AsyncMonolithOptions options, int processed, int consecutiveFailures) + { + if (consecutiveFailures > 0) + { + var delay = options.IdlePollInterval; + for (var i = 0; i < consecutiveFailures && delay < MaxFailureDelay; i++) + { + delay *= 2; + } + + return delay < MaxFailureDelay ? delay : MaxFailureDelay; + } + + return processed >= options.BatchSize ? options.BusyPollInterval : options.IdlePollInterval; + } +} From da40a6444840584e16d2f43222eef4201e1d88a2 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:29:03 +0000 Subject: [PATCH 44/53] Publish metrics on the async_monolith meter There was no way to see throughput, failures or backlog without querying the tables. AsyncMonolith now publishes System.Diagnostics.Metrics on the async_monolith meter (AsyncMonolithInstrumentation.MeterName), created from the host's IMeterFactory when there is one: - messages.produced (payload_type, consumer_type) - messages.consumed, messages.failed, messages.poisoned (consumer_type) - consume.duration in seconds (consumer_type, outcome) - messages.lag: seconds from due to claimed (consumer_type) - schedules.fired (payload_type) Completing a message now reports its outcome (consumed, retrying, poisoned, or lease lost) so the counters are exact. The OpenTelemetry guide lists the metrics. Tests listen to each host's own meter and check every instrument, and that the host's meter factory is used. --- AsyncMonolith.TestHelpers/SetupTestHelpers.cs | 5 +- .../Infra/TestServiceHelpers.cs | 3 + AsyncMonolith.Tests/MetricsTests.cs | 126 ++++++++++++++++++ .../Consumers/ConsumerMessageProcessor.cs | 28 ++-- AsyncMonolith/Producers/ProducerService.cs | 6 +- .../Scheduling/ScheduledMessageProcessor.cs | 6 +- .../Utilities/AsyncMonolithInstrumentation.cs | 6 + .../Utilities/AsyncMonolithMetrics.cs | 85 ++++++++++++ AsyncMonolith/Utilities/StartupExtensions.cs | 5 +- docs/guides/opentelemetry.md | 21 +++ 10 files changed, 278 insertions(+), 13 deletions(-) create mode 100644 AsyncMonolith.Tests/MetricsTests.cs create mode 100644 AsyncMonolith/Utilities/AsyncMonolithMetrics.cs diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index 8a1f470..4d47bfe 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -1,4 +1,6 @@ -using AsyncMonolith.Consumers; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Diagnostics.Metrics; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -57,6 +59,7 @@ public static IServiceCollection AddRealAsyncMonolithBaseServices( private static void AddBaseServices(IServiceCollection services, Action configure) { services.InternalConfigureAsyncMonolithOptions(configure); + services.TryAddSingleton(sp => new AsyncMonolithMetrics(sp.GetService())); var registration = new AsyncMonolithOptions(); configure(registration); services.InternalRegisterAsyncMonolithConsumers(registration); diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index fa8daa1..b22189c 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Diagnostics.Metrics; using System.Reflection; using AsyncMonolith.Consumers; using AsyncMonolith.Ef; @@ -30,6 +32,7 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A var fakeTime = new FakeTimeProvider(DateTimeOffset.Parse("2020-08-31T10:00:00.0000000Z", System.Globalization.CultureInfo.InvariantCulture)); services.AddSingleton(fakeTime); services.AddLogging(); + services.TryAddSingleton(sp => new AsyncMonolithMetrics(sp.GetService())); services.InternalConfigureAsyncMonolithOptions(o => { diff --git a/AsyncMonolith.Tests/MetricsTests.cs b/AsyncMonolith.Tests/MetricsTests.cs new file mode 100644 index 0000000..a19019f --- /dev/null +++ b/AsyncMonolith.Tests/MetricsTests.cs @@ -0,0 +1,126 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using AsyncMonolith.Ef; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The metrics published on the async_monolith meter. +/// +public sealed class MetricsTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// Records measurements from one host's meter only. + private sealed class Recorder : IDisposable + { + private readonly MeterListener _listener = new(); + + public Recorder(Meter meter) + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter == meter) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((i, value, tags, _) => Add(i, value, tags)); + _listener.SetMeasurementEventCallback((i, value, tags, _) => Add(i, value, tags)); + _listener.Start(); + } + + public ConcurrentQueue<(string Name, double Value, Dictionary Tags)> Measurements { get; } = new(); + + private void Add(Instrument instrument, double value, ReadOnlySpan> tags) => + Measurements.Enqueue((instrument.Name, value, tags.ToArray().ToDictionary(t => t.Key, t => t.Value))); + + public double Sum(string name, string? tag = null, object? tagValue = null) => Measurements + .Where(m => m.Name == name && (tag is null || Equals(m.Tags.GetValueOrDefault(tag), tagValue))) + .Sum(m => m.Value); + + public int Count(string name) => Measurements.Count(m => m.Name == name); + + public void Dispose() => _listener.Dispose(); + } + + private static Recorder Listen(SqliteTestHost host) => + new(host.Services.GetRequiredService().Meter); + + [Fact] + public async Task Producing_counts_a_message_per_consumer() + { + await using var host = await SqliteTestHost.Create(); + using var recorder = Listen(host); + + await host.Produce(new MultiConsumerMessage { Name = "x" }); + + recorder.Sum("async_monolith.messages.produced").ShouldBe(2); + recorder.Sum("async_monolith.messages.produced", "consumer_type", nameof(MultiConsumer1)).ShouldBe(1); + recorder.Sum("async_monolith.messages.produced", "payload_type", nameof(MultiConsumerMessage)).ShouldBe(2); + } + + [Fact] + public async Task Consuming_records_outcomes_durations_and_lag() + { + await using var host = await SqliteTestHost.Create(); + using var recorder = Listen(host); + await host.Produce(new SingleConsumerMessage { Name = "a" }); + await host.Produce(new MixedOutcomeMessage()); + host.Time.Advance(TimeSpan.FromSeconds(5)); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + recorder.Sum("async_monolith.messages.consumed").ShouldBe(2); + recorder.Sum("async_monolith.messages.failed", "consumer_type", nameof(MixedFailureConsumer)).ShouldBe(1); + recorder.Sum("async_monolith.messages.poisoned").ShouldBe(0); + recorder.Count("async_monolith.consume.duration").ShouldBe(3); + recorder.Measurements.Where(m => m.Name == "async_monolith.messages.lag").ShouldAllBe(m => m.Value == 5); + } + + [Fact] + public async Task Poisoning_is_counted() + { + await using var host = await SqliteTestHost.Create(s => s.MaxAttempts = 1); + using var recorder = Listen(host); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); + + await host.ConsumerProcessor.ProcessBatch(Ct); + + recorder.Sum("async_monolith.messages.poisoned", "consumer_type", nameof(ExceptionConsumer)).ShouldBe(1); + recorder.Measurements.Single(m => m.Name == "async_monolith.consume.duration").Tags["outcome"] + .ShouldBe("poisoned"); + } + + [Fact] + public async Task Fired_schedules_are_counted() + { + await using var host = await SqliteTestHost.Create(); + using var recorder = Listen(host); + await host.Schedule(new SingleConsumerMessage { Name = "tick" }, "0 * * * * *"); + host.Time.Advance(TimeSpan.FromMinutes(1)); + + await host.ScheduledProcessor.ProcessBatch(Ct); + + recorder.Sum("async_monolith.schedules.fired", "payload_type", nameof(SingleConsumerMessage)).ShouldBe(1); + } + + [Fact] + public void The_meter_comes_from_the_hosts_meter_factory_when_there_is_one() + { + var services = new ServiceCollection(); + services.AddMetrics(); + services.AddDbContext(_ => { }); + services.AddEfAsyncMonolith(); + + using var provider = services.BuildServiceProvider(); + var meter = provider.GetRequiredService().Meter; + + meter.Name.ShouldBe(AsyncMonolithInstrumentation.MeterName); + meter.Scope.ShouldBe(provider.GetRequiredService()); + } +} diff --git a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs index 0531c90..c63e872 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -20,6 +20,7 @@ internal sealed class ConsumerMessageProcessor : BackgroundService where T : private readonly IOptions _options; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; + private readonly AsyncMonolithMetrics _metrics; private int _railId; /// @@ -31,12 +32,13 @@ internal sealed class ConsumerMessageProcessor : BackgroundService where T : /// The options. /// The service scope factory. /// The consumer message fetcher. + /// The metrics. public ConsumerMessageProcessor(ILogger> logger, TimeProvider timeProvider, ConsumerRegistry consumerRegistry, IOptions options, IServiceScopeFactory scopeFactory, - IConsumerMessageFetcher consumerMessageFetcher) + IConsumerMessageFetcher consumerMessageFetcher, AsyncMonolithMetrics metrics) { _logger = logger; _timeProvider = timeProvider; @@ -44,6 +46,7 @@ public ConsumerMessageProcessor(ILogger> logger, _options = options; _scopeFactory = scopeFactory; _consumerMessageFetcher = consumerMessageFetcher; + _metrics = metrics; } /// @@ -199,6 +202,8 @@ internal async Task> ClaimBatch(CancellationToken cancellat message.Attempts = attempts + 1; message.AvailableAfter = leaseUntil; claimed.Add(new ClaimedMessage(message, dueAt)); + _metrics.Lag.Record(Math.Max(0, currentTime - dueAt), + new KeyValuePair("consumer_type", message.ConsumerType)); } await transaction.CommitAsync(cancellationToken); @@ -207,10 +212,13 @@ internal async Task> ClaimBatch(CancellationToken cancellat private async Task ProcessAndComplete(ClaimedMessage claimed, CancellationToken cancellationToken) { + var started = Stopwatch.GetTimestamp(); var error = await Process(claimed.Message, cancellationToken); + var duration = Stopwatch.GetElapsedTime(started); // Record the outcome even when stopping, so the attempt isn't left waiting for its lease to expire. - await Complete(claimed, error is null, CancellationToken.None, error); + var outcome = await Complete(claimed, error is null, CancellationToken.None, error); + _metrics.RecordOutcome(claimed.Message.ConsumerType, outcome, duration); return error is null; } @@ -218,8 +226,8 @@ private async Task ProcessAndComplete(ClaimedMessage claimed, Cancellation /// Records the outcome of a claimed message: removes it on success, otherwise schedules a retry or /// moves it to the poisoned messages. Does nothing if the lease has since been taken over. /// - internal async Task Complete(ClaimedMessage claimed, bool success, CancellationToken cancellationToken, - string? error = null) + internal async Task Complete(ClaimedMessage claimed, bool success, + CancellationToken cancellationToken, string? error = null) { var message = claimed.Message; using var scope = _scopeFactory.CreateScope(); @@ -229,24 +237,25 @@ internal async Task Complete(ClaimedMessage claimed, bool success, CancellationT if (success) { - await leased.ExecuteDeleteAsync(cancellationToken); - return; + return await leased.ExecuteDeleteAsync(cancellationToken) == 0 + ? MessageOutcome.LeaseLost + : MessageOutcome.Consumed; } if (message.Attempts < _consumerRegistry.ResolveConsumerMaxAttempts(message)) { var retryAt = _timeProvider.GetUtcNow().ToUnixTimeSeconds() + (long)_options.Value.GetRetryDelay(message.Attempts).TotalSeconds; - await leased.ExecuteUpdateAsync(s => s + var updated = await leased.ExecuteUpdateAsync(s => s .SetProperty(m => m.AvailableAfter, retryAt) .SetProperty(m => m.LastError, error), cancellationToken); - return; + return updated == 0 ? MessageOutcome.LeaseLost : MessageOutcome.Retrying; } await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); if (await leased.ExecuteDeleteAsync(cancellationToken) == 0) { - return; + return MessageOutcome.LeaseLost; } dbContext.Set().Add(new PoisonedMessage @@ -266,6 +275,7 @@ await leased.ExecuteUpdateAsync(s => s }); await dbContext.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); + return MessageOutcome.Poisoned; } private static Activity? StartActivity(ConsumerMessage message) diff --git a/AsyncMonolith/Producers/ProducerService.cs b/AsyncMonolith/Producers/ProducerService.cs index 74b68df..3508f6b 100644 --- a/AsyncMonolith/Producers/ProducerService.cs +++ b/AsyncMonolith/Producers/ProducerService.cs @@ -25,10 +25,12 @@ internal sealed class ProducerService : IProducerService where T : DbContext private readonly IAsyncMonolithIdGenerator _idGenerator; private readonly TimeProvider _timeProvider; private readonly JsonSerializerOptions? _serializerOptions; + private readonly AsyncMonolithMetrics _metrics; public ProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, - IAsyncMonolithIdGenerator idGenerator, IOptions options) + IAsyncMonolithIdGenerator idGenerator, IOptions options, AsyncMonolithMetrics metrics) { + _metrics = metrics; _serializerOptions = options.Value.SerializerOptions; _timeProvider = timeProvider; _consumerRegistry = consumerRegistry; @@ -141,6 +143,8 @@ private void Add(string payloadType, string payload, IEnumerable consume TraceId = activity?.TraceId.ToString(), SpanId = activity?.SpanId.ToString() }); + _metrics.Produced.Add(1, new KeyValuePair("payload_type", payloadType), + new KeyValuePair("consumer_type", consumer)); } } } diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index 33f9fe1..661e42d 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -20,6 +20,7 @@ internal sealed class ScheduledMessageProcessor : BackgroundService where T : private readonly IOptions _options; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; + private readonly AsyncMonolithMetrics _metrics; /// /// Initializes a new instance of the class. @@ -29,15 +30,17 @@ internal sealed class ScheduledMessageProcessor : BackgroundService where T : /// The options. /// The service scope factory. /// The scheduled message fetcher. + /// The metrics. public ScheduledMessageProcessor(ILogger> logger, TimeProvider timeProvider, IOptions options, IServiceScopeFactory scopeFactory, - IScheduledMessageFetcher messageFetcher) + IScheduledMessageFetcher messageFetcher, AsyncMonolithMetrics metrics) { _logger = logger; _timeProvider = timeProvider; _options = options; _scopeFactory = scopeFactory; _messageFetcher = messageFetcher; + _metrics = metrics; } /// @@ -152,6 +155,7 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa { producer.ProduceScheduled(message); processedScheduledMessageCount++; + _metrics.SchedulesFired.Add(1, new KeyValuePair("payload_type", message.PayloadType)); } catch (InvalidOperationException ex) { diff --git a/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs b/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs index c6b773a..0cd55de 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithInstrumentation.cs @@ -13,6 +13,12 @@ public static class AsyncMonolithInstrumentation /// public const string ActivitySourceName = "async_monolith"; + /// + /// The name of the meter that publishes AsyncMonolith's metrics, for example with OpenTelemetry's + /// AddMeter(AsyncMonolithInstrumentation.MeterName). + /// + public const string MeterName = "async_monolith"; + /// /// The activity name for processing consumer messages. /// diff --git a/AsyncMonolith/Utilities/AsyncMonolithMetrics.cs b/AsyncMonolith/Utilities/AsyncMonolithMetrics.cs new file mode 100644 index 0000000..40d5eb8 --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithMetrics.cs @@ -0,0 +1,85 @@ +using System.Diagnostics; +using System.Diagnostics.Metrics; + +namespace AsyncMonolith.Utilities; + +/// What happened to a claimed message once its consumer finished. +internal enum MessageOutcome +{ + Consumed, + Retrying, + Poisoned, + + /// The lease had expired and another processor had claimed the message, so nothing was recorded. + LeaseLost +} + +/// +/// AsyncMonolith's metrics, on the meter. +/// +internal sealed class AsyncMonolithMetrics : IDisposable +{ + private readonly bool _ownsMeter; + + public AsyncMonolithMetrics(IMeterFactory? meterFactory) + { + _ownsMeter = meterFactory is null; + Meter = meterFactory?.Create(AsyncMonolithInstrumentation.MeterName) ?? + new Meter(AsyncMonolithInstrumentation.MeterName); + + Produced = Meter.CreateCounter("async_monolith.messages.produced", "{message}", + "Messages produced, one per consumer."); + Consumed = Meter.CreateCounter("async_monolith.messages.consumed", "{message}", + "Messages consumed successfully."); + Failed = Meter.CreateCounter("async_monolith.messages.failed", "{message}", + "Failed attempts that will be retried."); + Poisoned = Meter.CreateCounter("async_monolith.messages.poisoned", "{message}", + "Messages moved to poisoned_messages after their last attempt failed."); + ConsumeDuration = Meter.CreateHistogram("async_monolith.consume.duration", "s", + "How long consumers took, by outcome."); + Lag = Meter.CreateHistogram("async_monolith.messages.lag", "s", + "How long a message waited between becoming due and being claimed."); + SchedulesFired = Meter.CreateCounter("async_monolith.schedules.fired", "{occurrence}", + "Schedule occurrences that produced a message."); + } + + public Meter Meter { get; } + public Counter Produced { get; } + public Counter Consumed { get; } + public Counter Failed { get; } + public Counter Poisoned { get; } + public Histogram ConsumeDuration { get; } + public Histogram Lag { get; } + public Counter SchedulesFired { get; } + + public void RecordOutcome(string consumerType, MessageOutcome outcome, TimeSpan duration) + { + var consumer = new KeyValuePair("consumer_type", consumerType); + switch (outcome) + { + case MessageOutcome.Consumed: + Consumed.Add(1, consumer); + break; + case MessageOutcome.Retrying: + Failed.Add(1, consumer); + break; + case MessageOutcome.Poisoned: + Failed.Add(1, consumer); + Poisoned.Add(1, consumer); + break; + case MessageOutcome.LeaseLost: + break; + } + + ConsumeDuration.Record(duration.TotalSeconds, consumer, + new KeyValuePair("outcome", outcome.ToString().ToLowerInvariant())); + } + + public void Dispose() + { + if (_ownsMeter) + { + Meter.Dispose(); + } + } +} diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 3042dcf..6d3347d 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -1,4 +1,6 @@ -using System.Reflection; +using AsyncMonolith.Utilities; +using System.Diagnostics.Metrics; +using System.Reflection; using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; @@ -61,6 +63,7 @@ internal static AsyncMonolithBuilder InternalAddAsyncMonolith( // TryAdd, so a host can register its own implementation before or instead of these. services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(); + services.TryAddSingleton(sp => new AsyncMonolithMetrics(sp.GetService())); services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); diff --git a/docs/guides/opentelemetry.md b/docs/guides/opentelemetry.md index 8e768c9..4511fe6 100644 --- a/docs/guides/opentelemetry.md +++ b/docs/guides/opentelemetry.md @@ -20,3 +20,24 @@ Ensure you add `AsyncMonolithInstrumentation.ActivitySourceName` as a source to | consumer_message.type | Message consumer type | | exception.type | Exception type | | exception.message | Exception message | + +## Metrics + +AsyncMonolith publishes metrics on the `async_monolith` meter (`AsyncMonolithInstrumentation.MeterName`): + +| Metric | Unit | Tags | Meaning | +|---|---|---|---| +| `async_monolith.messages.produced` | messages | `payload_type`, `consumer_type` | Messages produced, one per consumer | +| `async_monolith.messages.consumed` | messages | `consumer_type` | Messages consumed successfully | +| `async_monolith.messages.failed` | messages | `consumer_type` | Failed attempts (including the last one before poisoning) | +| `async_monolith.messages.poisoned` | messages | `consumer_type` | Messages moved to `poisoned_messages` | +| `async_monolith.consume.duration` | s | `consumer_type`, `outcome` | How long consumers took (`consumed`, `retrying`, `poisoned`) | +| `async_monolith.messages.lag` | s | `consumer_type` | Time between a message becoming due and being claimed | +| `async_monolith.schedules.fired` | occurrences | `payload_type` | Schedule occurrences that produced a message | + +```csharp +builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => metrics.AddMeter(AsyncMonolithInstrumentation.MeterName)); +``` + +A growing `messages.lag`, or `IQueueStatisticsService`'s `OldestAvailableAgeSeconds`, means processors are falling behind. From fb98c10b8b6a8b522517ad1432f8b16d39cd1e7f Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:29:53 +0000 Subject: [PATCH 45/53] Add optional retention for poisoned messages Poisoned messages were kept forever unless deleted by hand. AsyncMonolithOptions.PoisonedMessageRetention (null by default, so nothing changes unless set; at least one hour) deletes poisoned messages older than the retention, measured from when they were last due. The scheduled message processor runs the cleanup at most once an hour. Tests cover deletion, retention off, the hourly limit and validation. The release notes and consuming guide describe the new behaviour. --- .../Infra/TestServiceHelpers.cs | 1 + AsyncMonolith.Tests/RetentionTests.cs | 79 +++++++++++++++++++ .../Scheduling/ScheduledMessageProcessor.cs | 30 ++++++- .../Utilities/AsyncMonolithOptions.cs | 11 +++ docs/guides/consuming-messages.md | 1 + docs/releases.md | 3 + 6 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 AsyncMonolith.Tests/RetentionTests.cs diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index b22189c..db80cb9 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -44,6 +44,7 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A o.IdlePollInterval = settings.IdlePollInterval; o.BusyPollInterval = settings.BusyPollInterval; o.SerializerOptions = settings.SerializerOptions; + o.PoisonedMessageRetention = settings.PoisonedMessageRetention; }); settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); diff --git a/AsyncMonolith.Tests/RetentionTests.cs b/AsyncMonolith.Tests/RetentionTests.cs new file mode 100644 index 0000000..cbbac43 --- /dev/null +++ b/AsyncMonolith.Tests/RetentionTests.cs @@ -0,0 +1,79 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Optional deletion of old poisoned messages. +/// +public class RetentionTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static PoisonedMessage Poisoned(string id, long lastDue) => new() + { + Id = id, CreatedAt = lastDue, AvailableAfter = lastDue, Attempts = 5, ConsumerType = "c", RailId = 0, + PayloadType = "p", Payload = "{}", DeduplicationKey = id, TraceId = null, SpanId = null + }; + + private static async Task HostWithPoisonedMessages(TimeSpan? retention) + { + var host = await SqliteTestHost.Create(s => s.PoisonedMessageRetention = retention); + await host.Change(db => + { + db.PoisonedMessages.Add(Poisoned("old", host.Now - (long)TimeSpan.FromDays(8).TotalSeconds)); + db.PoisonedMessages.Add(Poisoned("recent", host.Now - (long)TimeSpan.FromDays(6).TotalSeconds)); + }); + return host; + } + + [Fact] + public async Task Poisoned_messages_older_than_the_retention_are_deleted() + { + await using var host = await HostWithPoisonedMessages(TimeSpan.FromDays(7)); + + (await host.ScheduledProcessor.CleanUpIfDue(Ct)).ShouldBe(1); + + (await host.PoisonedMessages()).ShouldHaveSingleItem().Id.ShouldBe("recent"); + } + + [Fact] + public async Task Poisoned_messages_are_kept_when_retention_is_off() + { + await using var host = await HostWithPoisonedMessages(null); + + (await host.ScheduledProcessor.CleanUpIfDue(Ct)).ShouldBe(0); + + (await host.PoisonedMessages()).Count.ShouldBe(2); + } + + [Fact] + public async Task Cleanup_runs_at_most_once_an_hour() + { + await using var host = await HostWithPoisonedMessages(TimeSpan.FromDays(7)); + await host.ScheduledProcessor.CleanUpIfDue(Ct); + + // A message that is already expired arrives, but the next cleanup isn't due until the hour is up + host.Time.Advance(TimeSpan.FromMinutes(59)); + await host.Change(db => db.PoisonedMessages.Add(Poisoned("older", 0))); + (await host.ScheduledProcessor.CleanUpIfDue(Ct)).ShouldBe(0); + + host.Time.Advance(TimeSpan.FromMinutes(1)); + (await host.ScheduledProcessor.CleanUpIfDue(Ct)).ShouldBe(1); + (await host.PoisonedMessages()).ShouldHaveSingleItem().Id.ShouldBe("recent"); + } + + [Fact] + public void Retention_under_an_hour_is_rejected() + { + var services = new ServiceCollection(); + services.InternalConfigureAsyncMonolithOptions(o => o.PoisonedMessageRetention = TimeSpan.FromMinutes(30)); + + Should.Throw(() => + services.BuildServiceProvider().GetRequiredService>().Value); + } +} diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index 661e42d..f3b058b 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +using AsyncMonolith.Consumers; +using System.Diagnostics; using AsyncMonolith.Producers; using AsyncMonolith.Utilities; using Microsoft.EntityFrameworkCore; @@ -56,6 +57,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) try { processed = await ProcessBatch(stoppingToken); + await CleanUpIfDue(stoppingToken); consecutiveFailures = 0; } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) @@ -84,6 +86,32 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } } + /// How often expired poisoned messages are deleted, when retention is set. + internal static readonly TimeSpan CleanupInterval = TimeSpan.FromHours(1); + + private DateTimeOffset _nextCleanup = DateTimeOffset.MinValue; + + /// + /// Deletes poisoned messages older than , at most + /// once per . + /// + /// The number deleted, or 0 when retention is off or a cleanup ran recently. + internal async Task CleanUpIfDue(CancellationToken cancellationToken) + { + var now = _timeProvider.GetUtcNow(); + if (_options.Value.PoisonedMessageRetention is not { } retention || now < _nextCleanup) + { + return 0; + } + + _nextCleanup = now + CleanupInterval; + var cutoff = (now - retention).ToUnixTimeSeconds(); + using var scope = _scopeFactory.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().Set() + .Where(m => m.AvailableAfter < cutoff) + .ExecuteDeleteAsync(cancellationToken); + } + /// How long to wait before checking a schedule that couldn't be evaluated again. internal const int InvalidScheduleRetrySeconds = 3600; diff --git a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs index 00f91ed..3463a22 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs @@ -52,6 +52,12 @@ public sealed class AsyncMonolithOptions /// public TimeSpan BusyPollInterval { get; set; } = TimeSpan.FromMilliseconds(10); + /// + /// How long poisoned messages are kept, measured from when they were last due. Older ones are deleted about + /// once an hour. Null (the default) keeps them until you delete or retry them. + /// + public TimeSpan? PoisonedMessageRetention { get; set; } + /// /// How payloads are serialized to and from JSON. Null (the default) uses System.Text.Json's defaults. /// Changing it changes the stored format, so messages and schedules already stored with different settings @@ -144,6 +150,11 @@ public ValidateOptionsResult Validate(string? name, AsyncMonolithOptions options errors.Add("BusyPollInterval must not be negative."); } + if (options.PoisonedMessageRetention is { } retention && retention < TimeSpan.FromHours(1)) + { + errors.Add("PoisonedMessageRetention must be at least 1 hour, or null to keep poisoned messages."); + } + if (options.BusyPollInterval > options.IdlePollInterval) { errors.Add("BusyPollInterval must not be more than IdlePollInterval."); diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 15a0215..752ed8a 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -48,6 +48,7 @@ Design consumers so the order of messages doesn't matter, for example by checkin - **Errors**: The error from the most recent failed attempt is stored in `last_error` on both tables, for example `System.InvalidOperationException: ...` or `Timed out after 10 seconds.` - **Interrupted processing**: A message is leased while its consumer runs. If the app stops mid-message, the message becomes available again once its consumer timeout plus 30 seconds has passed, and the interrupted attempt counts. - **Manual Intervention**: Use `IPoisonedMessageService` to count, list, retry or delete poisoned messages. Retrying moves a message back to `consumer_messages` with its attempts reset. Changes are saved immediately. +- **Retention**: Set `PoisonedMessageRetention` (for example `TimeSpan.FromDays(30)`) to delete poisoned messages that old, measured from when they were last due. It runs about once an hour. By default they are kept. - **Monitoring**: Periodically monitor the `poisoned_messages` table to ensure there are not too many failed messages. ```csharp diff --git a/docs/releases.md b/docs/releases.md index 1e5e00c..f7f930a 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -22,6 +22,9 @@ All packages now share one version and must be upgraded together. From 11.0.0 th **Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. It also adds indexes for finding due messages (`rail_id, available_after`), due schedules (`available_after`), schedules by tag, and poisoned messages by age, which keep processing fast as the tables grow. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** +- Metrics on the `async_monolith` meter, and optional `PoisonedMessageRetention`. +- A schedule that can't be evaluated, or whose payload has no consumers, no longer stops the others. A consumer that ignores cancellation is abandoned two seconds after its timeout. Processors back off while the database is unavailable. +- The database packages no longer reference a database driver: bring your own EF Core provider (for MySQL, `MySql.EntityFrameworkCore`). - Cron expressions can have 5 fields (minute precision) as well as 6 (seconds first). - `AsyncMonolithOptions.SerializerOptions` sets the `JsonSerializerOptions` for payloads. The default is unchanged. - Tables can live in their own schema or have a prefix: `modelBuilder.ConfigureAsyncMonolith(o => { o.Schema = "jobs"; o.TablePrefix = "jobs_"; })`. The database packages' SQL follows the mapping. From 436323a0edb6d708d0dfee8d0e20592ac1baf988 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:30:12 +0000 Subject: [PATCH 46/53] Release MySQL and MariaDB at 11.0.0, not as previews They no longer depend on Pomelo, and their integration tests now pass on CI against MySQL 8.4 and MariaDB 11.8 using Oracle's MySql.EntityFrameworkCore (107 integration tests, none skipped). --- AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj | 2 -- AsyncMonolith.MySql/AsyncMonolith.MySql.csproj | 2 -- docs/releases.md | 2 +- 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index ece45dd..b28e831 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -1,8 +1,6 @@  - - preview.1 $(NoWarn);NU5104 true AsyncMonolith.MariaDb diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 737b9b9..942d0c5 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -1,8 +1,6 @@  - - preview.1 $(NoWarn);NU5104 true AsyncMonolith.MySql diff --git a/docs/releases.md b/docs/releases.md index f7f930a..111d696 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -17,7 +17,7 @@ Make sure to check this table before updating the nuget package in your solution ## 11.0.0 -All packages now share one version and must be upgraded together. From 11.0.0 the major version follows [Semantic Versioning](https://semver.org) (it changes for breaking changes) rather than the .NET version. `AsyncMonolith.MySql` and `AsyncMonolith.MariaDb` are published as previews (`11.0.0-preview.1`) until Pomelo supports EF Core 10 and they run in the integration tests. +All packages now share one version and must be upgraded together. From 11.0.0 the major version follows [Semantic Versioning](https://semver.org) (it changes for breaking changes) rather than the .NET version. The MySQL and MariaDB packages are tested against MySQL 8.4 and MariaDB 11.8 with Oracle's `MySql.EntityFrameworkCore`. **Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. It also adds indexes for finding due messages (`rail_id, available_after`), due schedules (`available_after`), schedules by tag, and poisoned messages by age, which keep processing fast as the tables grow. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. From 135f06e8020dab39a30a21ecfd0bd5abb3579747 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:31:02 +0000 Subject: [PATCH 47/53] Add a multi-instance load test on every real database Three app instances share one PostgreSQL, SQL Server, MySQL or MariaDB database and process 1,000 messages, with every tenth failing its first attempt. Each message must succeed exactly once, the failing ones must be attempted exactly twice, and the queue must end empty with nothing poisoned. It runs with the integration tests. TestDbContainerBase.AddDb takes IServiceCollection so a generic host can use it. --- .../Infra/EfTestDbContainer.cs | 2 +- AsyncMonolith.Tests/Infra/LoadConsumer.cs | 33 +++++ .../Infra/MariaDbTestDbContainer.cs | 2 +- .../Infra/MsSqlTestDbContainer.cs | 2 +- .../Infra/MySqlTestDbContainer.cs | 2 +- .../Infra/PostgreSqlTestDbContainer.cs | 2 +- .../Infra/TestDbContainerBase.cs | 2 +- AsyncMonolith.Tests/LoadTests.cs | 118 ++++++++++++++++++ 8 files changed, 157 insertions(+), 6 deletions(-) create mode 100644 AsyncMonolith.Tests/Infra/LoadConsumer.cs create mode 100644 AsyncMonolith.Tests/LoadTests.cs diff --git a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs index 7ce50c2..85ed003 100644 --- a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs @@ -14,7 +14,7 @@ public override async Task InitializeContainerAsync() DbContainer = container; } - public override void AddDb(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { options.UseNpgsql(ConnectionString, o => { }); } ); diff --git a/AsyncMonolith.Tests/Infra/LoadConsumer.cs b/AsyncMonolith.Tests/Infra/LoadConsumer.cs new file mode 100644 index 0000000..96707cc --- /dev/null +++ b/AsyncMonolith.Tests/Infra/LoadConsumer.cs @@ -0,0 +1,33 @@ +using System.Collections.Concurrent; +using System.Text.Json.Serialization; +using AsyncMonolith.Consumers; + +namespace AsyncMonolith.Tests.Infra; + +public class LoadMessage : IConsumerPayload +{ + [JsonPropertyName("number")] public int Number { get; set; } +} + +/// Shared by every app instance in a load test. +public sealed class LoadRecorder +{ + public ConcurrentDictionary Successes { get; } = new(); + public ConcurrentDictionary Attempts { get; } = new(); +} + +/// Fails the first attempt of every tenth message, so retries happen under load. +public class LoadConsumer(LoadRecorder recorder) : IConsumer +{ + public Task Consume(LoadMessage payload, ConsumeContext context, CancellationToken cancellationToken) + { + recorder.Attempts.AddOrUpdate(payload.Number, 1, (_, n) => n + 1); + if (payload.Number % 10 == 0 && context.Attempt == 1) + { + throw new InvalidOperationException("Failing the first attempt on purpose"); + } + + recorder.Successes.AddOrUpdate(payload.Number, 1, (_, n) => n + 1); + return Task.CompletedTask; + } +} diff --git a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs index c75572d..0a240b2 100644 --- a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs @@ -15,7 +15,7 @@ public override async Task InitializeContainerAsync() DbContainer = container; } - public override void AddDb(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { diff --git a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs index a280eea..26796a7 100644 --- a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs @@ -14,7 +14,7 @@ public override async Task InitializeContainerAsync() DbContainer = container; } - public override void AddDb(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { options.UseSqlServer(ConnectionString); } ); diff --git a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs index a96dad3..e4777d0 100644 --- a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs @@ -14,7 +14,7 @@ public override async Task InitializeContainerAsync() DbContainer = container; } - public override void AddDb(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { diff --git a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs index 9af567c..e41f3ac 100644 --- a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs @@ -14,7 +14,7 @@ public override async Task InitializeContainerAsync() DbContainer = container; } - public override void AddDb(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { options.UseNpgsql(ConnectionString, o => { }); } ); diff --git a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs index 3d6858c..be5a655 100644 --- a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs +++ b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs @@ -22,6 +22,6 @@ public async ValueTask DisposeAsync() public abstract Task InitializeContainerAsync(); - public abstract void AddDb(ServiceCollection services); + public abstract void AddDb(IServiceCollection services); public abstract DbType GetDbType(); } \ No newline at end of file diff --git a/AsyncMonolith.Tests/LoadTests.cs b/AsyncMonolith.Tests/LoadTests.cs new file mode 100644 index 0000000..0648e70 --- /dev/null +++ b/AsyncMonolith.Tests/LoadTests.cs @@ -0,0 +1,118 @@ +using AsyncMonolith.Ef; +using AsyncMonolith.MariaDb; +using AsyncMonolith.MsSql; +using AsyncMonolith.MySql; +using AsyncMonolith.PostgreSql; +using AsyncMonolith.Producers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Several app instances sharing one real database under load. +/// +[Trait("Category", "Integration")] +public class LoadTests +{ + private const int Instances = 3; + private const int Messages = 1000; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static void AddAsyncMonolith(IServiceCollection services, DbType dbType) + { + Action configure = o => + { + o.RegisterTypesFromAssemblyContaining(); + o.BatchSize = 20; + o.AttemptDelay = TimeSpan.Zero; + o.IdlePollInterval = TimeSpan.FromMilliseconds(50); + o.BusyPollInterval = TimeSpan.Zero; + }; + _ = dbType switch + { + DbType.Ef => services.AddEfAsyncMonolith(configure), + DbType.PostgreSql => services.AddPostgreSqlAsyncMonolith(configure), + DbType.MsSql => services.AddMsSqlAsyncMonolith(configure), + DbType.MySql => services.AddMySqlAsyncMonolith(configure), + DbType.MariaDb => services.AddMariaDbAsyncMonolith(configure), + _ => throw new ArgumentOutOfRangeException(nameof(dbType)) + }; + } + + [Theory] + [MemberData(nameof(DbTestsBase.GetTestDbTypesWithoutEf), MemberType = typeof(DbTestsBase))] + public async Task Several_instances_consume_every_message_exactly_once(DbType dbType) + { + var container = DbTestsBase.GetTestDbContainer(dbType); + await container.InitializeAsync(); + var recorder = new LoadRecorder(); + var hosts = new List(); + try + { + for (var i = 0; i < Instances; i++) + { + var builder = Host.CreateApplicationBuilder(); + container.AddDb(builder.Services); + builder.Services.AddSingleton(recorder); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + AddAsyncMonolith(builder.Services, dbType); + hosts.Add(builder.Build()); + } + + using (var scope = hosts[0].Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.EnsureCreatedAsync(Ct); + await scope.ServiceProvider.GetRequiredService().ProduceList( + Enumerable.Range(0, Messages).Select(n => new LoadMessage { Number = n }), + cancellationToken: Ct); + await db.SaveChangesAsync(Ct); + } + + foreach (var host in hosts) + { + await host.StartAsync(Ct); + } + + var deadline = DateTime.UtcNow.AddMinutes(2); + while (recorder.Successes.Count < Messages && DateTime.UtcNow < deadline) + { + await Task.Delay(100, Ct); + } + + // Give any duplicate a chance to appear before checking. + await Task.Delay(500, Ct); + + recorder.Successes.Count.ShouldBe(Messages); + recorder.Successes.Values.ShouldAllBe(n => n == 1, "no message succeeds twice"); + recorder.Attempts.Where(a => a.Key % 10 == 0).ShouldAllBe(a => a.Value == 2, + "every tenth message fails once and is retried once"); + recorder.Attempts.Where(a => a.Key % 10 != 0).ShouldAllBe(a => a.Value == 1); + + using (var scope = hosts[0].Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.ConsumerMessages.Count().ShouldBe(0); + db.PoisonedMessages.Count().ShouldBe(0); + } + } + finally + { + foreach (var host in hosts) + { + await host.StopAsync(CancellationToken.None); + host.Dispose(); + } + + await container.DisposeAsync(); + } + } +} From a605bfb966847b8dd26262da7431ba79126a2168 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:32:27 +0000 Subject: [PATCH 48/53] Complete the package metadata for publishing The packages had no licence expression or README and repeated their metadata in every project. Directory.Build.targets now sets, for the seven published packages: - the Apache-2.0 licence expression, copyright, repository, docs site, release notes link, icon and tags - PACKAGE.md as each package's README (install, packages, quick start) - SourceLink repository details, embedded untracked sources, snupkg symbol packages and deterministic builds on GitHub Actions - package validation (with a note to add the 11.0.0 baseline once it is published) Each project keeps only its id, title and a clearer description, and still generates its XML documentation file, which is in the package. --- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 18 +-------- .../AsyncMonolith.MariaDb.csproj | 18 +-------- .../AsyncMonolith.MsSql.csproj | 18 +-------- .../AsyncMonolith.MySql.csproj | 18 +-------- .../AsyncMonolith.PostgreSql.csproj | 18 +-------- .../AsyncMonolith.TestHelpers.csproj | 18 +-------- AsyncMonolith/AsyncMonolith.csproj | 18 +-------- Directory.Build.targets | 31 ++++++++++++++ PACKAGE.md | 40 +++++++++++++++++++ 9 files changed, 85 insertions(+), 112 deletions(-) create mode 100644 Directory.Build.targets create mode 100644 PACKAGE.md diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj index 8d89d48..f240e0a 100644 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj @@ -2,26 +2,12 @@ true + true AsyncMonolith.Ef - Tim Jones - Aptacode - Entity Framework interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + AsyncMonolith for any EF Core provider, including SQLite. Fetches without row locks. AsyncMonolith.Ef - logo.png - True - true - - - True - \ - - diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj index b28e831..c78bade 100644 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj @@ -3,26 +3,12 @@ $(NoWarn);NU5104 true + true AsyncMonolith.MariaDb - Tim Jones - Aptacode - MariaDb interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + AsyncMonolith for MariaDB, with row locking (FOR UPDATE SKIP LOCKED). AsyncMonolith.MariaDb - logo.png - True - true - - - True - \ - - diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj index 211ef65..b7e4055 100644 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj @@ -2,26 +2,12 @@ true + true AsyncMonolith.MsSql - Tim Jones - Aptacode - MsSql interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + AsyncMonolith for SQL Server, with row locking (UPDLOCK, READPAST). AsyncMonolith.MsSql - logo.png - True - true - - - True - \ - - diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj index 942d0c5..6216a7f 100644 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj @@ -3,26 +3,12 @@ $(NoWarn);NU5104 true + true AsyncMonolith.MySql - Tim Jones - Aptacode - MySql interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + AsyncMonolith for MySQL, with row locking (FOR UPDATE SKIP LOCKED). AsyncMonolith.MySql - logo.png - True - true - - - True - \ - - diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj index 6eb4e69..eba70e8 100644 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj @@ -2,26 +2,12 @@ true + true AsyncMonolith.PostgreSql - Tim Jones - Aptacode - PostgreSql interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + AsyncMonolith for PostgreSQL, with row locking (FOR UPDATE SKIP LOCKED). AsyncMonolith.PostgreSql - logo.png - True - true - - - True - \ - - diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index 122cb1d..23a2b60 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -2,18 +2,10 @@ true + true AsyncMonolith.TestHelpers - Tim Jones - Aptacode - Test helpers for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + Fakes and helpers for testing AsyncMonolith consumers with xunit v3. AsyncMonolith.TestHelpers - logo.png - True - true @@ -24,12 +16,6 @@ - - - True - \ - - diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index 1a3df66..afb99ce 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -2,18 +2,10 @@ true + true AsyncMonolith - Tim Jones - Aptacode - Messaging library for monolithic dotnet apps - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async + Transactional outbox, background consumers and scheduled messages for .NET monoliths on EF Core. Async Monolith - logo.png - True - true @@ -32,10 +24,4 @@ - - - True - \ - - \ No newline at end of file diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000..344001c --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,31 @@ + + + + Tim Jones + Aptacode + Copyright (c) Tim Jones + Apache-2.0 + https://timmoth.github.io/AsyncMonolith/ + https://github.com/Timmoth/AsyncMonolith + git + monolith;messaging;outbox;transactional-outbox;scheduling;background-jobs;efcore + logo.png + README.md + https://github.com/Timmoth/AsyncMonolith/blob/main/docs/releases.md + + + true + true + true + snupkg + true + + + true + + + + + + + diff --git a/PACKAGE.md b/PACKAGE.md new file mode 100644 index 0000000..4ef2d09 --- /dev/null +++ b/PACKAGE.md @@ -0,0 +1,40 @@ +# AsyncMonolith + +Background messaging and scheduling for .NET monoliths, using the database you already have through Entity Framework Core. + +- **Transactional outbox**: messages are written in the same `SaveChanges` as your data, so they are never lost or sent for changes that rolled back. +- **Consumers** run in the background with timeouts, retries with exponential backoff, and poisoned message handling. +- **Schedules**: recurring messages from cron expressions in any time zone. +- **Safe with several app instances**, with metrics on the `async_monolith` meter. + +## Packages + +| Package | Use with | +|---|---| +| `AsyncMonolith.PostgreSql` | PostgreSQL (Npgsql) | +| `AsyncMonolith.MsSql` | SQL Server | +| `AsyncMonolith.MySql` | MySQL (`MySql.EntityFrameworkCore`) | +| `AsyncMonolith.MariaDb` | MariaDB | +| `AsyncMonolith.Ef` | Any EF Core provider, including SQLite (without row locking) | +| `AsyncMonolith.TestHelpers` | Testing consumers with xunit v3 | + +## Quick start + +```csharp +builder.Services.AddPostgreSqlAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); + +// In AppDbContext.OnModelCreating +modelBuilder.ConfigureAsyncMonolith(); + +public record OrderPlaced(int OrderId) : IConsumerPayload; + +public class SendReceipt : IConsumer +{ + public Task Consume(OrderPlaced payload, ConsumeContext context, CancellationToken cancellationToken) => ...; +} + +await producer.Produce(new OrderPlaced(order.Id)); +await dbContext.SaveChangesAsync(); +``` + +Documentation: https://timmoth.github.io/AsyncMonolith/ From 6d51ec024b5fc232bd4a1aad0a2e81cfa5370ffd Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:35:11 +0000 Subject: [PATCH 49/53] Close the test coverage gaps and report coverage in CI Coverage of the fast tests showed untested paths. New tests cover: - the consumer's trace continuing the producer's (parent span) - a running host recovering once its database becomes available - a lost lease on the poisoning path (nothing poisoned, message kept) - a cron expression that never occurs, both when scheduling and stored - the builder's AddConsumersFromAssemblyContaining - quoted, prefixed table names and the error when ConfigureAsyncMonolith wasn't called - ConsumerTestBase and the message assertion helpers in TestHelpers The time zone null checks were dead (the lookup throws instead) and are removed; a cron expression with no future occurrence now says so. Fast tests now cover 99% of the core's lines (96% of branches) and 93% of TestHelpers' lines. The test workflow collects Cobertura coverage with Microsoft.Testing.Extensions.CodeCoverage and uploads it. --- .github/workflows/test.yml | 22 ++- .../AsyncMonolith.Tests.csproj | 1 + AsyncMonolith.Tests/ConsumerTestBaseTests.cs | 34 ++++ AsyncMonolith.Tests/RobustnessTests.cs | 180 ++++++++++++++++++ AsyncMonolith.Tests/TestHelpersTests.cs | 19 ++ AsyncMonolith/Scheduling/ScheduleService.cs | 17 +- AsyncMonolith/Scheduling/ScheduledMessage.cs | 17 +- Directory.Packages.props | 1 + docs/tests.md | 2 + 9 files changed, 267 insertions(+), 26 deletions(-) create mode 100644 AsyncMonolith.Tests/ConsumerTestBaseTests.cs create mode 100644 AsyncMonolith.Tests/RobustnessTests.cs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e38d414..1413715 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,7 +25,16 @@ jobs: global-json-file: global.json - name: Fast tests - run: dotnet test --project AsyncMonolith.Tests --filter-not-trait "Category=Integration" + run: >- + dotnet test --project AsyncMonolith.Tests --filter-not-trait "Category=Integration" + --coverage --coverage-output-format cobertura --coverage-output "$GITHUB_WORKSPACE/coverage/fast.cobertura.xml" + + - name: Upload coverage + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage-fast + path: coverage/ integration: if: github.event_name == 'workflow_dispatch' && inputs.integration @@ -40,4 +49,13 @@ jobs: global-json-file: global.json - name: Integration tests - run: dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" + run: >- + dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" + --coverage --coverage-output-format cobertura --coverage-output "$GITHUB_WORKSPACE/coverage/integration.cobertura.xml" + + - name: Upload coverage + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage-integration + path: coverage/ diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index f6746c4..34399ed 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -13,6 +13,7 @@ + diff --git a/AsyncMonolith.Tests/ConsumerTestBaseTests.cs b/AsyncMonolith.Tests/ConsumerTestBaseTests.cs new file mode 100644 index 0000000..361c0ca --- /dev/null +++ b/AsyncMonolith.Tests/ConsumerTestBaseTests.cs @@ -0,0 +1,34 @@ +using AsyncMonolith.TestHelpers; +using AsyncMonolith.Tests.Infra; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The TestHelpers ConsumerTestBase, used as a consumer test would use it. +/// +public class ConsumerTestBaseTests(ITestOutputHelper output) : ConsumerTestBase(output) +{ + protected override Task Setup(IServiceCollection services) + { + services.AddSingleton(); + services.AddScoped(); + return Task.CompletedTask; + } + + [Fact] + public async Task Process_runs_the_consumer_with_the_payload() + { + await Process(new OrderedMessage { Name = "from base" }, + TestContext.Current.CancellationToken); + + Services.GetRequiredService().Order.ShouldBe(["OrderedConsumer:from base"]); + } + + [Fact] + public void A_fake_clock_is_registered() + { + Services.GetRequiredService().ShouldBeSameAs(FakeTime); + } +} diff --git a/AsyncMonolith.Tests/RobustnessTests.cs b/AsyncMonolith.Tests/RobustnessTests.cs new file mode 100644 index 0000000..150b63c --- /dev/null +++ b/AsyncMonolith.Tests/RobustnessTests.cs @@ -0,0 +1,180 @@ +using System.Diagnostics; +using AsyncMonolith.Consumers; +using AsyncMonolith.Ef; +using AsyncMonolith.Producers; +using AsyncMonolith.Tests.Infra; +using AsyncMonolith.Utilities; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// Behaviour in the cases production finds: outages, lost leases, tracing, odd schedules and mapping mistakes. +/// +public class RobustnessTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Consuming_continues_the_producers_trace() + { + var started = new List(); + using var listener = new ActivityListener + { + ShouldListenTo = s => s.Name is "AsyncMonolith.Tests.Trace" or AsyncMonolithInstrumentation.ActivitySourceName, + Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + ActivityStarted = a => { lock (started) { started.Add(a); } } + }; + ActivitySource.AddActivityListener(listener); + using var source = new ActivitySource("AsyncMonolith.Tests.Trace"); + await using var host = await SqliteTestHost.Create(); + + ActivityTraceId traceId; + ActivitySpanId spanId; + using (var request = source.StartActivity("request")!) + { + traceId = request.TraceId; + spanId = request.SpanId; + await host.Produce(new SingleConsumerMessage { Name = "traced" }); + } + + await host.ConsumerProcessor.ProcessBatch(Ct); + + Activity consume; + lock (started) + { + consume = started.Single(a => a.OperationName == AsyncMonolithInstrumentation.ProcessConsumerMessageActivity && + a.TraceId == traceId); + } + + consume.ParentSpanId.ShouldBe(spanId); + } + + [Fact] + public async Task A_running_host_recovers_once_its_database_is_available() + { + var path = Path.Combine(Path.GetTempPath(), $"asyncmonolith-outage-{Guid.NewGuid():N}.db"); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={path}")); + builder.Services.AddSingleton(); + builder.Services.AddEfAsyncMonolith(o => + { + o.RegisterTypesFromAssemblyContaining(); + o.IdlePollInterval = TimeSpan.FromMilliseconds(50); + o.BusyPollInterval = TimeSpan.Zero; + }); + using var host = builder.Build(); + try + { + // The tables don't exist yet, so every batch fails while the host runs. + await host.StartAsync(Ct); + await Task.Delay(500, Ct); + + using (var scope = host.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.EnsureCreatedAsync(Ct); + await scope.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "after outage" }, cancellationToken: Ct); + await db.SaveChangesAsync(Ct); + } + + var invocations = host.Services.GetRequiredService(); + var deadline = DateTime.UtcNow.AddSeconds(15); + while (invocations.GetInvocationCount(nameof(SingleConsumer)) == 0 && DateTime.UtcNow < deadline) + { + await Task.Delay(50, Ct); + } + + invocations.GetInvocationCount(nameof(SingleConsumer)).ShouldBe(1); + } + finally + { + await host.StopAsync(CancellationToken.None); + SqliteConnection.ClearAllPools(); + File.Delete(path); + } + } + + [Fact] + public async Task A_message_whose_lease_was_lost_is_not_poisoned_by_the_old_processor() + { + await using var host = await SqliteTestHost.Create(s => s.MaxAttempts = 1); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }); + var claimed = (await host.ConsumerProcessor.ClaimBatch(Ct)).ShouldHaveSingleItem(); + await host.Change(db => db.ConsumerMessages.Single().AvailableAfter = claimed.Message.AvailableAfter + 100); + + var outcome = await host.ConsumerProcessor.Complete(claimed, success: false, Ct, "failed"); + + outcome.ShouldBe(MessageOutcome.LeaseLost); + (await host.PoisonedMessages()).ShouldBeEmpty(); + (await host.ConsumerMessages()).ShouldHaveSingleItem(); + } + + [Fact] + public async Task Scheduling_an_expression_that_never_occurs_is_rejected() + { + await using var host = await SqliteTestHost.Create(); + + var exception = await Should.ThrowAsync(() => + host.Schedule(new SingleConsumerMessage { Name = "x" }, "0 0 30 2 *")); + + exception.Message.ShouldContain("never occurs"); + } + + [Fact] + public async Task A_stored_schedule_that_never_occurs_is_set_aside_like_any_invalid_schedule() + { + await using var host = await SqliteTestHost.Create(); + await host.Change(db => db.ScheduledMessages.Add(new Scheduling.ScheduledMessage + { + Id = "never", Tag = null, AvailableAfter = host.Now, CronExpression = "0 0 30 2 *", CronTimeZone = "UTC", + PayloadType = nameof(SingleConsumerMessage), Payload = "{}" + })); + + (await host.ScheduledProcessor.ProcessBatch(Ct)).ShouldBe(0); + + (await host.ScheduledMessages()).ShouldHaveSingleItem().AvailableAfter + .ShouldBe(host.Now + Scheduling.ScheduledMessageProcessor.InvalidScheduleRetrySeconds); + } + + [Fact] + public void The_builder_adds_consumers_from_more_assemblies() + { + var services = new ServiceCollection(); + services.AddDbContext(_ => { }); + + services.AddEfAsyncMonolith().AddConsumersFromAssemblyContaining(); + + services.ShouldContain(d => d.ServiceType == typeof(SingleConsumer)); + services.BuildServiceProvider().GetRequiredService() + .ResolvePayloadConsumerTypes(nameof(SingleConsumerMessage)).ShouldBe([nameof(SingleConsumer)]); + } + + [Fact] + public async Task Table_names_are_quoted_and_follow_the_mapping() + { + await using var connection = new SqliteConnection("DataSource=:memory:"); + await using var plain = new TestDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options); + await using var prefixed = new PrefixedDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options); + + AsyncMonolithTables.Name(plain.Set()).ShouldBe("\"consumer_messages\""); + AsyncMonolithTables.Name(prefixed.Set()).ShouldBe("\"jobs_scheduled_messages\""); + } + + private sealed class UnmappedDbContext(DbContextOptions options) : DbContext(options); + + [Fact] + public async Task Forgetting_ConfigureAsyncMonolith_gives_a_clear_error() + { + await using var connection = new SqliteConnection("DataSource=:memory:"); + await using var db = new UnmappedDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options); + + Should.Throw(() => AsyncMonolithTables.Name(db.Set())) + .Message.ShouldContain("ConfigureAsyncMonolith"); + } +} diff --git a/AsyncMonolith.Tests/TestHelpersTests.cs b/AsyncMonolith.Tests/TestHelpersTests.cs index 3daef03..490cb92 100644 --- a/AsyncMonolith.Tests/TestHelpersTests.cs +++ b/AsyncMonolith.Tests/TestHelpersTests.cs @@ -119,4 +119,23 @@ await TestConsumerMessageProcessor.Process( host.Invocations.Order.ShouldBe(["OrderedConsumer:direct"]); (await host.ConsumerMessages()).ShouldBeEmpty(); } + + [Fact] + public async Task Message_assertion_helpers_find_messages_by_consumer_payload_and_id() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new MultiConsumerMessage { Name = "x" }); + await host.Produce(new MultiConsumerMessage { Name = "y" }); + await host.Schedule(new SingleConsumerMessage { Name = "s" }, "0 * * * * *"); + using var scope = host.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + (await db.GetConsumerMessages()).Count.ShouldBe(2); + var x = (await db.GetConsumerMessages(new MultiConsumerMessage { Name = "x" })) + .ShouldHaveSingleItem(); + (await db.AssertSingleConsumerMessageById( + new MultiConsumerMessage { Name = "x" }, x.Id)).Id.ShouldBe(x.Id); + (await db.AssertSingleScheduledMessage(new SingleConsumerMessage { Name = "s" })).CronExpression + .ShouldBe("0 * * * * *"); + } } diff --git a/AsyncMonolith/Scheduling/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index 26664c7..cbefd4f 100644 --- a/AsyncMonolith/Scheduling/ScheduleService.cs +++ b/AsyncMonolith/Scheduling/ScheduleService.cs @@ -51,24 +51,17 @@ public string Schedule(TPayload message, string cronExpression, string var expression = Cron.Parse(cronExpression); + // Throws TimeZoneNotFoundException for an unknown time zone. var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZone); - if (timezone == null) - { - throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{timeZone}'"); - } - - var next = expression.GetNextOccurrence(_timeProvider.GetUtcNow(), timezone); - if (next == null) - { - throw new InvalidOperationException( - $"Couldn't determine next scheduled message occurrence for chron expression: '{cronExpression}', timezone: '{timeZone}'"); - } + var next = expression.GetNextOccurrence(_timeProvider.GetUtcNow(), timezone) ?? + throw new InvalidOperationException( + $"The cron expression '{cronExpression}' never occurs after now in time zone '{timeZone}'."); _dbContext.Set().Add(new ScheduledMessage { Id = id, PayloadType = AsyncMonolithNames.ForPayload(), - AvailableAfter = next.Value.ToUnixTimeSeconds(), + AvailableAfter = next.ToUnixTimeSeconds(), Tag = tag, CronExpression = cronExpression, CronTimeZone = timeZone, diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index 2eb8b60..9aa20af 100644 --- a/AsyncMonolith/Scheduling/ScheduledMessage.cs +++ b/AsyncMonolith/Scheduling/ScheduledMessage.cs @@ -71,19 +71,12 @@ internal long GetNextOccurrence(TimeProvider timeProvider) { var expression = Cron.Parse(CronExpression); + // Throws TimeZoneNotFoundException for an unknown time zone. var timezone = TimeZoneInfo.FindSystemTimeZoneById(CronTimeZone); - if (timezone == null) - { - throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{CronTimeZone}'"); - } - - var next = expression.GetNextOccurrence(timeProvider.GetUtcNow(), timezone); - if (next == null) - { - throw new InvalidOperationException("Couldn't determine next scheduled message occurrence"); - } - - return next.Value.ToUnixTimeSeconds(); + var next = expression.GetNextOccurrence(timeProvider.GetUtcNow(), timezone) ?? + throw new InvalidOperationException( + $"The cron expression '{CronExpression}' never occurs after now in time zone '{CronTimeZone}'."); + return next.ToUnixTimeSeconds(); } /// diff --git a/Directory.Packages.props b/Directory.Packages.props index 4601b17..e4259de 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -22,6 +22,7 @@ + diff --git a/docs/tests.md b/docs/tests.md index 983c808..b504c8a 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -14,6 +14,8 @@ Tests are split into two groups: dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" ``` +Add `--coverage --coverage-output-format cobertura` to either command for a coverage report. CI uploads one for each run as an artifact. + ## AsyncMonolith.TestHelpers From 38238302547fe5b0d0ebe2cad7e0e15e5803ff92 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:36:04 +0000 Subject: [PATCH 50/53] Bring the docs up to date with 11.0.0 - Internals describe the claim, consume and complete cycle, leasing, conditional claims, schedule isolation and the polling backoff, and no longer mention removed APIs or the old startup exception. - Warnings explain at-least-once delivery, the cancellation token, rails for slow consumers, ordering, and when AsyncMonolith.Ef is enough. - The scheduling guide describes cron occurrences and per-schedule handling; the TestHelpers example uses the options lambda. - The README and docs consumer example had a mismatched constructor name and awaited in a non-async method; both are fixed. --- README.md | 4 ++-- docs/guides/consuming-messages.md | 2 +- docs/guides/scheduling-messages.md | 4 ++-- docs/internals.md | 30 ++++++++++++++---------------- docs/tests.md | 4 ++-- docs/warnings.md | 9 ++++++--- 6 files changed, 27 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 867053d..fb8a1f0 100644 --- a/README.md +++ b/README.md @@ -73,12 +73,12 @@ public class DeleteUsersPosts : IConsumer { private readonly ApplicationDbContext _dbContext; - public ValueSubmittedConsumer(ApplicationDbContext dbContext) + public DeleteUsersPosts(ApplicationDbContext dbContext) { _dbContext = dbContext; } - public Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) + public async Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 752ed8a..5cd0f7e 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -23,7 +23,7 @@ public class DeleteUsersPosts : IConsumer _dbContext = dbContext; } - public Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) + public async Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); diff --git a/docs/guides/scheduling-messages.md b/docs/guides/scheduling-messages.md index e2e29d8..2454538 100644 --- a/docs/guides/scheduling-messages.md +++ b/docs/guides/scheduling-messages.md @@ -1,6 +1,6 @@ -- **Frequency**: Scheduled messages will be produced periodically by the `chron_expression` in the given `chron_timezone` +- **Frequency**: Scheduled messages are produced each time their cron expression occurs, in their time zone. - **Transactional Persistence**: Schedule messages along with changes to your `DbContext` before calling `SaveChangesAsync`, ensuring your domain changes and the messages they produce are persisted transactionally. -- **Processing**: Schedule messages will be processed sequentially after they are made available by their chron job, at which point they will be turned into Consumer Messages and inserted into the `consumer_messages` table to be handled by their respective consumers. +- **Processing**: When a schedule is due, a message is produced for each consumer of its payload and the schedule moves to its next occurrence. Each due schedule is handled on its own, so one that fails doesn't affect the others. To produce your message you'll need to inject a `IScheduleService` diff --git a/docs/internals.md b/docs/internals.md index 7bdec6c..498dfac 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -8,31 +8,29 @@ Resolves consumers for a given payload and writes messages to the `consumer_mess Writes scheduled messages to the `scheduled_messages` table. -## DbSet: ConsumerMessage +## Tables -Stores all messages awaiting processing by the `ConsumerMessageProcessor`. +`ConfigureAsyncMonolith()` maps three tables (with an optional schema and table prefix): -## DbSet: ScheduledMessage - -Stores all scheduled messages awaiting processing by the `ScheduledMessageProcessor`. - -## DbSet: PoisonedMessage - -Stores consumer messages that have reached `AsyncMonolith.MaxAttempts`, poisoned messages will then need to be manually moved back to the `consumer_messages` table or deleted. +- `consumer_messages`: one row per pending message per consumer. +- `scheduled_messages`: recurring schedules and when they are next due. +- `poisoned_messages`: messages that failed every attempt, with the last error. ## ConsumerMessageProcessor -A background service that periodically fetches available messages from the 'consumer_messages' table. Once a message is found, it's row-level locked to prevent other processes from fetching it. The corresponding consumer attempts to process the message. If successful, the message is removed from the `consumer_messages` table; otherwise, the processor increments the messages `attempts` by one and delays processing for a defined number of seconds (`AsyncMonolithOptions.AttemptDelay`). If the number of attempts reaches the limit defined by `AsyncMonolith.MaxAttempts`, the message is moved to the `poisoned_messages` table. +One background processor runs per rail. Each cycle it: -## ScheduledMessageProcessor +1. **Claims** a batch in a short transaction: it reads due messages (locking rows with the PostgreSQL, SQL Server, MySQL and MariaDB packages), then for each one counts the attempt and leases it by moving `available_after` past the consumer's timeout plus 30 seconds. The update only applies if the message is unchanged since it was read, so only one processor can claim it. +2. **Consumes** each claimed message outside any transaction, in its own DI scope, so consumers can use the database freely. +3. **Completes** each message in its own short write: deleted on success, otherwise retried after a backoff delay, or moved to `poisoned_messages` after its last attempt. If its lease was taken over meanwhile, nothing is changed. -A background service that fetches available messages from the `scheduled_messages` table. Once found, each consumer set up to handle the payload is resolved, and a message is written to the `consumer_messages` table for each of them. +If the app stops mid-message, the message becomes available again when its lease expires. -## ConsumerRegistry +## ScheduledMessageProcessor -Used to resolve all the consumers able to process a given payload, and resolve instances of the consumers when processing a message. The registry is populated on startup by calling `builder.Services.AddAsyncMonolith(Assembly.GetExecutingAssembly());` which uses reflection to find all consumer & payload types. +Reads due schedules and, for each one, moves it to its next occurrence (conditionally, so each occurrence fires once across instances) and produces a message for every consumer of its payload. A schedule that can't be evaluated is checked again an hour later without affecting the others. It also deletes expired poisoned messages when `PoisonedMessageRetention` is set. ## Notes 📋 -- The background services wait for `AsyncMonolithOptions.IdlePollInterval` before fetching another batch of messages. If a full batch is fetched, the delay is reduced to `AsyncMonolithOptions.ProcessorMinDelay` seconds between cycles. -- Configuring concurrent consumer / scheduled message processors will throw a startup exception when using AsyncMonolith.Ef (due to no built in support for row level locking) +- After a batch that wasn't full a processor waits `IdlePollInterval`; after a full batch it waits `BusyPollInterval`. While batches keep failing (for example during a database outage) the wait doubles up to 30 seconds. +- Consumers and payloads are found by scanning the registered assemblies at startup, and the registry is checked for name clashes and payloads without consumers when the host starts. diff --git a/docs/tests.md b/docs/tests.md index b504c8a..51fed8e 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -69,8 +69,8 @@ public class CancelShipmentTests : ConsumerTestBase } ); - services.AddRealAsyncMonolithBaseServices(settings => - settings.RegisterTypesFromAssemblyContaining()); + services.AddRealAsyncMonolithBaseServices(options => + options.RegisterTypesFromAssemblyContaining()); return Task.CompletedTask; } diff --git a/docs/warnings.md b/docs/warnings.md index bf787ee..4c5e0de 100644 --- a/docs/warnings.md +++ b/docs/warnings.md @@ -1,3 +1,6 @@ -- Efcore does not natively support row level locking, this makes it possible for two instances of your app to compete over the next available message to be processed, potentially wasting cycles. For this reason it is reccomended that you only use `AsyncMonolith.Ef` when you are running a single instance of your app OR for development purposes. Using `AsyncMonlith.PostgreSql` / `AsyncMonolith.MySql` / `AsyncMonolith.MsSql` / `AsyncMonolith.MariaDb` will allow the system to lock rows ensuring they are only retrieved and processed once. -- Test your desired throughput -- All consumers must finish executing for a batch of messages before the next batch is started, therefore it is not currently reccomended to execute long running tasks inside your consumers. If you have a need for this please get in touch. \ No newline at end of file +- **Single-instance or development with `AsyncMonolith.Ef`.** EF Core has no portable row locking, so with `AsyncMonolith.Ef` several app instances read the same candidate messages and compete for them. Claims are conditional, so a message is still only processed by one instance, but instances waste work. In production with several instances, use `AsyncMonolith.PostgreSql`, `AsyncMonolith.MsSql`, `AsyncMonolith.MySql` or `AsyncMonolith.MariaDb`, which lock rows and skip each other's batches. +- **Consumers run at least once.** A message can run again if the app stops mid-message, or if a consumer ignores its cancellation token and is abandoned. Make consumers idempotent: `ConsumeContext.MessageId` and `ConsumeContext.DeduplicationKey` help. +- **Honour the `CancellationToken`.** It is cancelled at the consumer's timeout and when the app stops. +- **Batches finish together.** A processor waits for every consumer in its batch before taking the next, so a slow consumer delays the others on its rail. Put slow consumers on their own rail with `[ConsumerRailId]`, or raise their `[ConsumerTimeout]`. +- **No ordering guarantee.** See [Ordering](guides/consuming-messages.md#ordering). +- **Test your expected throughput** against your database before relying on it. From 04e369a3fdd71c39c73dc937b2032d1163bf0532 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:42:28 +0000 Subject: [PATCH 51/53] Remove the SonarCloud workflow It had been failing at authentication on every run, including on main, and the strict build settings and test coverage reports now cover the same ground. --- .github/workflows/SonarCloud.yml | 52 -------------------------------- 1 file changed, 52 deletions(-) delete mode 100644 .github/workflows/SonarCloud.yml diff --git a/.github/workflows/SonarCloud.yml b/.github/workflows/SonarCloud.yml deleted file mode 100644 index b069ddf..0000000 --- a/.github/workflows/SonarCloud.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: SonarCloud -on: - workflow_dispatch: - push: - branches: - - main - pull_request: - types: [opened, synchronize, reopened] -jobs: - build: - defaults: - run: - working-directory: AsyncMonolith - name: Build and analyze - runs-on: windows-latest - steps: - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: 17 - distribution: 'zulu' # Alternative distribution options are available. - - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Cache SonarCloud packages - uses: actions/cache@v4 - with: - path: ~\sonar\cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Cache SonarCloud scanner - id: cache-sonar-scanner - uses: actions/cache@v4 - with: - path: .\.sonar\scanner - key: ${{ runner.os }}-sonar-scanner - restore-keys: ${{ runner.os }}-sonar-scanner - - name: Install SonarCloud scanner - if: steps.cache-sonar-scanner.outputs.cache-hit != 'true' - shell: powershell - run: | - New-Item -Path .\.sonar\scanner -ItemType Directory - dotnet tool update dotnet-sonarscanner --tool-path .\.sonar\scanner - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - shell: powershell - run: | - .\.sonar\scanner\dotnet-sonarscanner begin /k:"timmoth_asyncmonolith" /o:"timmoth" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" - dotnet build - .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}" From 1dec53a36c23eec86aa874bdd564ddab53f2d90b Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 05:45:19 +0000 Subject: [PATCH 52/53] Merge the database packages into a single AsyncMonolith package None of the database packages referenced a driver any more; each only held a couple of SQL statements. They are merged into the core: - AddAsyncMonolith() replaces AddEfAsyncMonolith, AddPostgreSqlAsyncMonolith, AddMsSqlAsyncMonolith, AddMySqlAsyncMonolith and AddMariaDbAsyncMonolith. - The fetch SQL is chosen from the DbContext's EF Core provider: PostgreSQL (Npgsql), SQL Server, and MySQL/MariaDB (Oracle's provider or Pomelo, which share the same SQL) lock rows; anything else, such as SQLite, uses LINQ without locks. - AsyncMonolith.Ef, .PostgreSql, .MsSql, .MySql and .MariaDb are removed from the solution and the publish workflow, which now packs AsyncMonolith and AsyncMonolith.TestHelpers. - README, package README, quickstart, warnings and release notes describe one package and how the database is detected. SqlDialectTests checks the detection for Npgsql, SQL Server, Oracle's MySQL provider, SQLite, Pomelo, InMemory and unknown providers. The integration and load tests now exercise the merged fetchers on every real database. --- .github/workflows/publish.yml | 2 +- AsyncMonolith.Ef/AsyncMonolith.Ef.csproj | 20 ---- AsyncMonolith.Ef/EfConsumerMessageFetcher.cs | 41 --------- AsyncMonolith.Ef/EfScheduledMessageFetcher.cs | 39 -------- AsyncMonolith.Ef/StartupExtensions.cs | 36 -------- .../AsyncMonolith.MariaDb.csproj | 20 ---- .../MariaDbConsumerMessageFetcher.cs | 30 ------ .../MariaDbScheduledMessageFetcher.cs | 30 ------ AsyncMonolith.MariaDb/StartupExtensions.cs | 35 ------- .../AsyncMonolith.MsSql.csproj | 19 ---- .../MsSqlConsumerMessageFetcher.cs | 30 ------ .../MsSqlScheduledMessageFetcher.cs | 30 ------ AsyncMonolith.MsSql/StartupExtensions.cs | 36 -------- .../AsyncMonolith.MySql.csproj | 20 ---- .../MySqlConsumerMessageFetcher.cs | 30 ------ .../MySqlScheduledMessageFetcher.cs | 30 ------ AsyncMonolith.MySql/StartupExtensions.cs | 35 ------- .../AsyncMonolith.PostgreSql.csproj | 20 ---- .../PostgreSqlConsumerMessageFetcher.cs | 30 ------ .../PostgreSqlScheduledMessageFetcher.cs | 30 ------ AsyncMonolith.PostgreSql/StartupExtensions.cs | 36 -------- .../AsyncMonolith.Tests.csproj | 5 - AsyncMonolith.Tests/ConfigurationTests.cs | 7 +- AsyncMonolith.Tests/HostedProcessingTests.cs | 3 +- .../Infra/TestServiceHelpers.cs | 32 +------ AsyncMonolith.Tests/LoadTests.cs | 19 +--- AsyncMonolith.Tests/MetricsTests.cs | 3 +- AsyncMonolith.Tests/ModelMappingTests.cs | 18 +--- .../ModuleRegistrationTests.cs | 13 ++- AsyncMonolith.Tests/MultipleInstanceTests.cs | 4 +- AsyncMonolith.Tests/PublicApiTests.cs | 11 --- AsyncMonolith.Tests/RegistrationTests.cs | 3 +- AsyncMonolith.Tests/RobustnessTests.cs | 5 +- AsyncMonolith.Tests/SqlDialectTests.cs | 45 +++++++++ AsyncMonolith.sln | 36 +------- AsyncMonolith/AsyncMonolith.csproj | 5 - AsyncMonolith/Database/Fetchers.cs | 92 +++++++++++++++++++ AsyncMonolith/Database/SqlDialect.cs | 39 ++++++++ .../Utilities/AsyncMonolithOptions.cs | 4 +- AsyncMonolith/Utilities/StartupExtensions.cs | 29 +++++- Example/Example.Api/Example.Api.csproj | 2 +- Example/Example.Api/Program.cs | 3 +- PACKAGE.md | 20 ++-- README.md | 6 +- docs/guides/consuming-messages.md | 2 +- docs/guides/producing-messages.md | 2 +- docs/index.md | 6 +- docs/internals.md | 2 +- docs/quickstart.md | 33 ++----- docs/releases.md | 18 ++-- docs/warnings.md | 2 +- 51 files changed, 272 insertions(+), 796 deletions(-) delete mode 100644 AsyncMonolith.Ef/AsyncMonolith.Ef.csproj delete mode 100644 AsyncMonolith.Ef/EfConsumerMessageFetcher.cs delete mode 100644 AsyncMonolith.Ef/EfScheduledMessageFetcher.cs delete mode 100644 AsyncMonolith.Ef/StartupExtensions.cs delete mode 100644 AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj delete mode 100644 AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs delete mode 100644 AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs delete mode 100644 AsyncMonolith.MariaDb/StartupExtensions.cs delete mode 100644 AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj delete mode 100644 AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs delete mode 100644 AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs delete mode 100644 AsyncMonolith.MsSql/StartupExtensions.cs delete mode 100644 AsyncMonolith.MySql/AsyncMonolith.MySql.csproj delete mode 100644 AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs delete mode 100644 AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs delete mode 100644 AsyncMonolith.MySql/StartupExtensions.cs delete mode 100644 AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj delete mode 100644 AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs delete mode 100644 AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs delete mode 100644 AsyncMonolith.PostgreSql/StartupExtensions.cs create mode 100644 AsyncMonolith.Tests/SqlDialectTests.cs create mode 100644 AsyncMonolith/Database/Fetchers.cs create mode 100644 AsyncMonolith/Database/SqlDialect.cs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b99c1de..3c1d309 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -28,7 +28,7 @@ jobs: - name: Pack run: | - for project in AsyncMonolith AsyncMonolith.Ef AsyncMonolith.PostgreSql AsyncMonolith.MsSql AsyncMonolith.MySql AsyncMonolith.MariaDb AsyncMonolith.TestHelpers; do + for project in AsyncMonolith AsyncMonolith.TestHelpers; do dotnet pack "$project/$project.csproj" -c Release --no-build --output nupkg done diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj deleted file mode 100644 index f240e0a..0000000 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - true - true - AsyncMonolith.Ef - AsyncMonolith for any EF Core provider, including SQLite. Fetches without row locks. - AsyncMonolith.Ef - - - - - - - - - - - - diff --git a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs deleted file mode 100644 index ab3f1ca..0000000 --- a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs +++ /dev/null @@ -1,41 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.Ef; - -/// -/// Fetches consumer messages using Entity Framework. -/// -internal sealed class EfConsumerMessageFetcher : IConsumerMessageFetcher -{ - private readonly IOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolithOptions. - public EfConsumerMessageFetcher(IOptions options) - { - _options = options; - } - - /// - /// Fetches consumer messages from the database. - /// - /// The DbSet of consumer messages. - /// The current time. - /// The message rail to fetch messages from. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of consumer messages. - public Task> Fetch(DbSet consumerSet, long currentTime, int railId, - CancellationToken cancellationToken = default) - { - return consumerSet - .Where(m => m.AvailableAfter <= currentTime && m.RailId == railId) - .OrderBy(m => m.CreatedAt).ThenBy(m => m.Id) - .Take(_options.Value.BatchSize) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs deleted file mode 100644 index 0cb3063..0000000 --- a/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs +++ /dev/null @@ -1,39 +0,0 @@ -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.Ef; - -/// -/// Fetches scheduled messages from the database using Entity Framework. -/// -internal sealed class EfScheduledMessageFetcher : IScheduledMessageFetcher -{ - private readonly IOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolith. - public EfScheduledMessageFetcher(IOptions options) - { - _options = options; - } - - /// - /// Fetches scheduled messages from the database. - /// - /// The DbSet of scheduled messages. - /// The current time. - /// The cancellation token. - /// A task representing the asynchronous operation, containing the list of fetched scheduled messages. - public Task> Fetch(DbSet scheduledMessageSet, long currentTime, - CancellationToken cancellationToken = default) - { - return scheduledMessageSet.Where(m => m.AvailableAfter <= currentTime) - .OrderBy(m => m.AvailableAfter).ThenBy(m => m.Id) - .Take(_options.Value.BatchSize) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.Ef/StartupExtensions.cs b/AsyncMonolith.Ef/StartupExtensions.cs deleted file mode 100644 index 5ed178b..0000000 --- a/AsyncMonolith.Ef/StartupExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace AsyncMonolith.Ef; - -/// -/// Extension methods for configuring EF AsyncMonolith in the IServiceCollection. -/// -/// -/// Registers AsyncMonolith for any database supported by Entity Framework Core (fetches without row locks). -/// -public static class StartupExtensions -{ - /// - /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the - /// background processors. Call it once, in the host. - /// - /// The DbContext containing the AsyncMonolith tables. - /// The service collection. - /// Sets options and the assemblies to scan for consumers. - /// A builder to bind configuration or add more consumer assemblies. - public static AsyncMonolithBuilder AddEfAsyncMonolith( - this IServiceCollection services, - Action? configure = null) where T : DbContext - { - var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); - services.TryAddSingleton(); - services.TryAddSingleton(); - return builder; - } -} diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj deleted file mode 100644 index c78bade..0000000 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - $(NoWarn);NU5104 - true - true - AsyncMonolith.MariaDb - AsyncMonolith for MariaDB, with row locking (FOR UPDATE SKIP LOCKED). - AsyncMonolith.MariaDb - - - - - - - - - - - diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs deleted file mode 100644 index e608112..0000000 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.MariaDb; - -/// -/// Fetches due consumer messages on this rail for MariaDB, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for MariaDB. -/// -internal sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; - - private readonly IOptions _options; - - public MariaDbConsumerMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet consumerSet, long currentTime, int railId, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); - return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs deleted file mode 100644 index 2aea68d..0000000 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.MariaDb; - -/// -/// Fetches due schedules for MariaDB, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for MariaDB. -/// -internal sealed class MariaDbScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; - - private readonly IOptions _options; - - public MariaDbScheduledMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet scheduledMessageSet, long currentTime, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); - return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MariaDb/StartupExtensions.cs b/AsyncMonolith.MariaDb/StartupExtensions.cs deleted file mode 100644 index e1943f4..0000000 --- a/AsyncMonolith.MariaDb/StartupExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace AsyncMonolith.MariaDb; -/// -/// AsyncMonolith MariaDb startup extensions -/// -/// -/// Registers AsyncMonolith for MariaDB. -/// -public static class StartupExtensions -{ - /// - /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the - /// background processors. Call it once, in the host. - /// - /// The DbContext containing the AsyncMonolith tables. - /// The service collection. - /// Sets options and the assemblies to scan for consumers. - /// A builder to bind configuration or add more consumer assemblies. - public static AsyncMonolithBuilder AddMariaDbAsyncMonolith( - this IServiceCollection services, - Action? configure = null) where T : DbContext - { - var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); - services.TryAddSingleton(); - services.TryAddSingleton(); - return builder; - } -} diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj deleted file mode 100644 index b7e4055..0000000 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - true - true - AsyncMonolith.MsSql - AsyncMonolith for SQL Server, with row locking (UPDLOCK, READPAST). - AsyncMonolith.MsSql - - - - - - - - - - - \ No newline at end of file diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs deleted file mode 100644 index 1ec8aa1..0000000 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.MsSql; - -/// -/// Fetches due consumer messages on this rail for SQL Server, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for SQL Server. -/// -internal sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string Sql = "SELECT TOP ({2}) * FROM {table} WITH (ROWLOCK, UPDLOCK, READPAST) WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id"; - - private readonly IOptions _options; - - public MsSqlConsumerMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet consumerSet, long currentTime, int railId, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); - return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs deleted file mode 100644 index 3ba4e07..0000000 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.MsSql; - -/// -/// Fetches due schedules for SQL Server, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for SQL Server. -/// -internal sealed class MsSqlScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string Sql = "SELECT TOP ({1}) * FROM {table} WITH (ROWLOCK, UPDLOCK, READPAST) WHERE available_after <= {0} ORDER BY available_after, id"; - - private readonly IOptions _options; - - public MsSqlScheduledMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet scheduledMessageSet, long currentTime, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); - return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MsSql/StartupExtensions.cs b/AsyncMonolith.MsSql/StartupExtensions.cs deleted file mode 100644 index 0dd8e99..0000000 --- a/AsyncMonolith.MsSql/StartupExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace AsyncMonolith.MsSql; - -/// -/// AsyncMonolith MsSql startup extensions -/// -/// -/// Registers AsyncMonolith for SQL Server. -/// -public static class StartupExtensions -{ - /// - /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the - /// background processors. Call it once, in the host. - /// - /// The DbContext containing the AsyncMonolith tables. - /// The service collection. - /// Sets options and the assemblies to scan for consumers. - /// A builder to bind configuration or add more consumer assemblies. - public static AsyncMonolithBuilder AddMsSqlAsyncMonolith( - this IServiceCollection services, - Action? configure = null) where T : DbContext - { - var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); - services.TryAddSingleton(); - services.TryAddSingleton(); - return builder; - } -} diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj deleted file mode 100644 index 6216a7f..0000000 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - $(NoWarn);NU5104 - true - true - AsyncMonolith.MySql - AsyncMonolith for MySQL, with row locking (FOR UPDATE SKIP LOCKED). - AsyncMonolith.MySql - - - - - - - - - - - diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs deleted file mode 100644 index 1bcf5bf..0000000 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.MySql; - -/// -/// Fetches due consumer messages on this rail for MySQL, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for MySQL. -/// -internal sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; - - private readonly IOptions _options; - - public MySqlConsumerMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet consumerSet, long currentTime, int railId, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); - return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs deleted file mode 100644 index e5e947e..0000000 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.MySql; - -/// -/// Fetches due schedules for MySQL, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for MySQL. -/// -internal sealed class MySqlScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; - - private readonly IOptions _options; - - public MySqlScheduledMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet scheduledMessageSet, long currentTime, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); - return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MySql/StartupExtensions.cs b/AsyncMonolith.MySql/StartupExtensions.cs deleted file mode 100644 index 66b356e..0000000 --- a/AsyncMonolith.MySql/StartupExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace AsyncMonolith.MySql; -/// -/// AsyncMonolith MySql startup extensions -/// -/// -/// Registers AsyncMonolith for MySQL. -/// -public static class StartupExtensions -{ - /// - /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the - /// background processors. Call it once, in the host. - /// - /// The DbContext containing the AsyncMonolith tables. - /// The service collection. - /// Sets options and the assemblies to scan for consumers. - /// A builder to bind configuration or add more consumer assemblies. - public static AsyncMonolithBuilder AddMySqlAsyncMonolith( - this IServiceCollection services, - Action? configure = null) where T : DbContext - { - var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); - services.TryAddSingleton(); - services.TryAddSingleton(); - return builder; - } -} diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj deleted file mode 100644 index eba70e8..0000000 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - true - true - AsyncMonolith.PostgreSql - AsyncMonolith for PostgreSQL, with row locking (FOR UPDATE SKIP LOCKED). - AsyncMonolith.PostgreSql - - - - - - - - - - - - diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs deleted file mode 100644 index fbace43..0000000 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.PostgreSql; - -/// -/// Fetches due consumer messages on this rail for PostgreSQL, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for PostgreSQL. -/// -internal sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; - - private readonly IOptions _options; - - public PostgreSqlConsumerMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet consumerSet, long currentTime, int railId, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal); - return consumerSet.FromSqlRaw(sql, currentTime, railId, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs deleted file mode 100644 index 7fda19a..0000000 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace AsyncMonolith.PostgreSql; - -/// -/// Fetches due schedules for PostgreSQL, locking the rows and skipping rows other processors have locked. Values are -/// passed as EF parameters, so this works with any EF Core provider for PostgreSQL. -/// -internal sealed class PostgreSqlScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string Sql = "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; - - private readonly IOptions _options; - - public PostgreSqlScheduledMessageFetcher(IOptions options) - { - _options = options; - } - - public Task> Fetch(DbSet scheduledMessageSet, long currentTime, - CancellationToken cancellationToken = default) - { - var sql = Sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal); - return scheduledMessageSet.FromSqlRaw(sql, currentTime, _options.Value.BatchSize).ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.PostgreSql/StartupExtensions.cs b/AsyncMonolith.PostgreSql/StartupExtensions.cs deleted file mode 100644 index 0425904..0000000 --- a/AsyncMonolith.PostgreSql/StartupExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace AsyncMonolith.PostgreSql; - -/// -/// AsyncMonolith PostgreSql startup extensions -/// -/// -/// Registers AsyncMonolith for PostgreSQL. -/// -public static class StartupExtensions -{ - /// - /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the - /// background processors. Call it once, in the host. - /// - /// The DbContext containing the AsyncMonolith tables. - /// The service collection. - /// Sets options and the assemblies to scan for consumers. - /// A builder to bind configuration or add more consumer assemblies. - public static AsyncMonolithBuilder AddPostgreSqlAsyncMonolith( - this IServiceCollection services, - Action? configure = null) where T : DbContext - { - var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); - services.TryAddSingleton(); - services.TryAddSingleton(); - return builder; - } -} diff --git a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index 34399ed..38d16f9 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -28,11 +28,6 @@ - - - - - diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs index d7efe62..ae3bb86 100644 --- a/AsyncMonolith.Tests/ConfigurationTests.cs +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -1,6 +1,5 @@ using System.Text.Json; using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Tests.Infra; @@ -73,7 +72,7 @@ public async Task Invalid_options_stop_the_host_from_starting() { var builder = Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder(); builder.Services.AddDbContext(_ => { }); - builder.Services.AddEfAsyncMonolith(s => s.BatchSize = 0); + builder.Services.AddAsyncMonolith(s => s.BatchSize = 0); using var host = builder.Build(); await Should.ThrowAsync(() => @@ -95,7 +94,7 @@ public void Options_bind_from_configuration_over_code() services.AddSingleton(configuration); services.AddDbContext(_ => { }); - services.AddEfAsyncMonolith(s => s.MaxAttempts = 3).BindConfiguration("AsyncMonolith"); + services.AddAsyncMonolith(s => s.MaxAttempts = 3).BindConfiguration("AsyncMonolith"); var options = services.BuildServiceProvider().GetRequiredService>().Value; options.MaxAttempts.ShouldBe(9); @@ -228,7 +227,7 @@ public void AddEfAsyncMonolith_registers_the_services_and_background_processors( var services = new ServiceCollection(); services.AddDbContext(_ => { }); - services.AddEfAsyncMonolith(s => + services.AddAsyncMonolith(s => { s.RegisterTypesFromAssemblyContaining(); s.MaxAttempts = 9; diff --git a/AsyncMonolith.Tests/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs index 52e30b2..eda8a49 100644 --- a/AsyncMonolith.Tests/HostedProcessingTests.cs +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -1,5 +1,4 @@ using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Tests.Infra; @@ -33,7 +32,7 @@ private async Task StartHost(Action? configure = null, boo builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); - builder.Services.AddEfAsyncMonolith(s => + builder.Services.AddAsyncMonolith(s => { if (!registerAsModule) { diff --git a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index db80cb9..a28c3e8 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -1,12 +1,8 @@ +using AsyncMonolith.Database; using Microsoft.Extensions.DependencyInjection.Extensions; using System.Diagnostics.Metrics; using System.Reflection; using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; -using AsyncMonolith.MariaDb; -using AsyncMonolith.MsSql; -using AsyncMonolith.MySql; -using AsyncMonolith.PostgreSql; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.TestHelpers; @@ -56,29 +52,9 @@ public static (FakeTimeProvider fakeTime, TestConsumerInvocations invocations) A services.AddScoped>(); services.AddScoped>(); services.AddScoped>(); - switch (dbType) - { - case DbType.Ef: - services.AddSingleton(); - services.AddSingleton(); - break; - case DbType.MySql: - services.AddSingleton(); - services.AddSingleton(); - break; - case DbType.MsSql: - services.AddSingleton(); - services.AddSingleton(); - break; - case DbType.PostgreSql: - services.AddSingleton(); - services.AddSingleton(); - break; - case DbType.MariaDb: - services.AddSingleton(); - services.AddSingleton(); - break; - } + // One fetcher pair for every database: the SQL is chosen from the EF provider in use. + services.AddSingleton(); + services.AddSingleton(); var invocations = new TestConsumerInvocations(); services.AddSingleton(invocations); diff --git a/AsyncMonolith.Tests/LoadTests.cs b/AsyncMonolith.Tests/LoadTests.cs index 0648e70..2906013 100644 --- a/AsyncMonolith.Tests/LoadTests.cs +++ b/AsyncMonolith.Tests/LoadTests.cs @@ -1,8 +1,3 @@ -using AsyncMonolith.Ef; -using AsyncMonolith.MariaDb; -using AsyncMonolith.MsSql; -using AsyncMonolith.MySql; -using AsyncMonolith.PostgreSql; using AsyncMonolith.Producers; using AsyncMonolith.Tests.Infra; using AsyncMonolith.Utilities; @@ -23,7 +18,7 @@ public class LoadTests private static CancellationToken Ct => TestContext.Current.CancellationToken; - private static void AddAsyncMonolith(IServiceCollection services, DbType dbType) + private static void AddAsyncMonolith(IServiceCollection services) { Action configure = o => { @@ -33,15 +28,7 @@ private static void AddAsyncMonolith(IServiceCollection services, DbType dbType) o.IdlePollInterval = TimeSpan.FromMilliseconds(50); o.BusyPollInterval = TimeSpan.Zero; }; - _ = dbType switch - { - DbType.Ef => services.AddEfAsyncMonolith(configure), - DbType.PostgreSql => services.AddPostgreSqlAsyncMonolith(configure), - DbType.MsSql => services.AddMsSqlAsyncMonolith(configure), - DbType.MySql => services.AddMySqlAsyncMonolith(configure), - DbType.MariaDb => services.AddMariaDbAsyncMonolith(configure), - _ => throw new ArgumentOutOfRangeException(nameof(dbType)) - }; + services.AddAsyncMonolith(configure); } [Theory] @@ -63,7 +50,7 @@ public async Task Several_instances_consume_every_message_exactly_once(DbType db builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); - AddAsyncMonolith(builder.Services, dbType); + AddAsyncMonolith(builder.Services); hosts.Add(builder.Build()); } diff --git a/AsyncMonolith.Tests/MetricsTests.cs b/AsyncMonolith.Tests/MetricsTests.cs index a19019f..a928fac 100644 --- a/AsyncMonolith.Tests/MetricsTests.cs +++ b/AsyncMonolith.Tests/MetricsTests.cs @@ -1,6 +1,5 @@ using System.Collections.Concurrent; using System.Diagnostics.Metrics; -using AsyncMonolith.Ef; using AsyncMonolith.Tests.Infra; using AsyncMonolith.Utilities; using Microsoft.Extensions.DependencyInjection; @@ -115,7 +114,7 @@ public void The_meter_comes_from_the_hosts_meter_factory_when_there_is_one() var services = new ServiceCollection(); services.AddMetrics(); services.AddDbContext(_ => { }); - services.AddEfAsyncMonolith(); + services.AddAsyncMonolith(); using var provider = services.BuildServiceProvider(); var meter = provider.GetRequiredService().Meter; diff --git a/AsyncMonolith.Tests/ModelMappingTests.cs b/AsyncMonolith.Tests/ModelMappingTests.cs index 80de05e..c720ea9 100644 --- a/AsyncMonolith.Tests/ModelMappingTests.cs +++ b/AsyncMonolith.Tests/ModelMappingTests.cs @@ -1,7 +1,5 @@ +using AsyncMonolith.Utilities; using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; -using AsyncMonolith.MsSql; -using AsyncMonolith.PostgreSql; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Tests.Infra; @@ -77,7 +75,7 @@ public async Task A_host_context_without_DbSets_can_use_prefixed_tables() try { await using var services = Services(o => o.UseSqlite($"Data Source={path}"), - s => s.AddEfAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining())); + s => s.AddAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining())); using (var scope = services.CreateScope()) { await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(Ct); @@ -129,17 +127,7 @@ public async Task Provider_sql_finds_tables_in_a_custom_schema(DbType dbType) o.UseSqlServer(container.ConnectionString); } }, - s => - { - if (dbType == DbType.PostgreSql) - { - s.AddPostgreSqlAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); - } - else - { - s.AddMsSqlAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); - } - }); + s => s.AddAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining())); using (var scope = services.CreateScope()) { await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(Ct); diff --git a/AsyncMonolith.Tests/ModuleRegistrationTests.cs b/AsyncMonolith.Tests/ModuleRegistrationTests.cs index 455fd11..ef5db80 100644 --- a/AsyncMonolith.Tests/ModuleRegistrationTests.cs +++ b/AsyncMonolith.Tests/ModuleRegistrationTests.cs @@ -1,5 +1,4 @@ using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; using AsyncMonolith.Tests.Infra; using AsyncMonolith.Utilities; using Microsoft.Extensions.DependencyInjection; @@ -29,7 +28,7 @@ public void Module_consumers_registered_before_the_host_are_included() var services = Services(); services.AddAsyncMonolithConsumers(module); - services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); var provider = services.BuildServiceProvider(); var registry = provider.GetRequiredService(); @@ -45,7 +44,7 @@ public void Module_consumers_registered_after_the_host_are_included() var module = ClashingTypes.Build(["Billing"]); var services = Services(); - services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); services.AddAsyncMonolithConsumers(module); var registry = services.BuildServiceProvider().GetRequiredService(); @@ -57,7 +56,7 @@ public void Registering_the_same_assembly_twice_is_harmless() { var services = Services(); - services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); services.AddAsyncMonolithConsumersFromAssemblyContaining(); services.Count(d => d.ServiceType == typeof(SingleConsumer)).ShouldBe(1); @@ -69,7 +68,7 @@ public void Registering_the_same_assembly_twice_is_harmless() public void Payload_without_a_consumer_in_any_module_fails_when_the_host_starts() { var services = Services(); - services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); services.AddAsyncMonolithConsumers(ClashingTypes.PayloadOnly("Billing")); var exception = Should.Throw(() => @@ -82,7 +81,7 @@ public void Payload_without_a_consumer_in_any_module_fails_when_the_host_starts( public void Rails_are_read_from_every_module() { var services = Services(); - services.AddEfAsyncMonolith(_ => { }); + services.AddAsyncMonolith(_ => { }); services.AddAsyncMonolithConsumersFromAssemblyContaining(); services.BuildServiceProvider().GetRequiredService().RailIds.ShouldBe([0, 1, 2]); @@ -92,7 +91,7 @@ public void Rails_are_read_from_every_module() public void Rail_zero_is_used_when_there_are_no_consumers() { var services = Services(); - services.AddEfAsyncMonolith(_ => { }); + services.AddAsyncMonolith(_ => { }); services.BuildServiceProvider().GetRequiredService().RailIds.ShouldBe([0]); } diff --git a/AsyncMonolith.Tests/MultipleInstanceTests.cs b/AsyncMonolith.Tests/MultipleInstanceTests.cs index 430fa33..15be858 100644 --- a/AsyncMonolith.Tests/MultipleInstanceTests.cs +++ b/AsyncMonolith.Tests/MultipleInstanceTests.cs @@ -1,5 +1,5 @@ +using AsyncMonolith.Utilities; using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Tests.Infra; @@ -91,7 +91,7 @@ public async Task Two_running_instances_sharing_a_database_consume_each_message_ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); - builder.Services.AddEfAsyncMonolith(s => + builder.Services.AddAsyncMonolith(s => { s.RegisterTypesFromAssemblyContaining(); s.IdlePollInterval = TimeSpan.FromMilliseconds(20); diff --git a/AsyncMonolith.Tests/PublicApiTests.cs b/AsyncMonolith.Tests/PublicApiTests.cs index f43541e..0b90481 100644 --- a/AsyncMonolith.Tests/PublicApiTests.cs +++ b/AsyncMonolith.Tests/PublicApiTests.cs @@ -48,17 +48,6 @@ public void Core_package_exports_only_the_intended_types() ]); } - [Theory] - [InlineData("AsyncMonolith.Ef")] - [InlineData("AsyncMonolith.PostgreSql")] - [InlineData("AsyncMonolith.MsSql")] - [InlineData("AsyncMonolith.MySql")] - [InlineData("AsyncMonolith.MariaDb")] - public void Provider_packages_export_only_their_registration_extensions(string assemblyName) - { - ExportedTypes(Assembly.Load(assemblyName)).ShouldBe([$"{assemblyName}.StartupExtensions"]); - } - [Fact] public void TestHelpers_package_exports_only_the_intended_types() { diff --git a/AsyncMonolith.Tests/RegistrationTests.cs b/AsyncMonolith.Tests/RegistrationTests.cs index 5793d1b..ba5e2b3 100644 --- a/AsyncMonolith.Tests/RegistrationTests.cs +++ b/AsyncMonolith.Tests/RegistrationTests.cs @@ -1,4 +1,3 @@ -using AsyncMonolith.Ef; using AsyncMonolith.Scheduling; using AsyncMonolith.TestHelpers; using AsyncMonolith.Tests.Infra; @@ -24,7 +23,7 @@ private static ServiceCollection Services() } private static void AddAsyncMonolith(IServiceCollection services) => - services.AddEfAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); + services.AddAsyncMonolith(s => s.RegisterTypesFromAssemblyContaining()); [Fact] public void Does_not_register_the_DbContext_base_type() diff --git a/AsyncMonolith.Tests/RobustnessTests.cs b/AsyncMonolith.Tests/RobustnessTests.cs index 150b63c..1fceb9a 100644 --- a/AsyncMonolith.Tests/RobustnessTests.cs +++ b/AsyncMonolith.Tests/RobustnessTests.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using AsyncMonolith.Consumers; -using AsyncMonolith.Ef; using AsyncMonolith.Producers; using AsyncMonolith.Tests.Infra; using AsyncMonolith.Utilities; @@ -61,7 +60,7 @@ public async Task A_running_host_recovers_once_its_database_is_available() var builder = Host.CreateApplicationBuilder(); builder.Services.AddDbContext(o => o.UseSqlite($"Data Source={path}")); builder.Services.AddSingleton(); - builder.Services.AddEfAsyncMonolith(o => + builder.Services.AddAsyncMonolith(o => { o.RegisterTypesFromAssemblyContaining(); o.IdlePollInterval = TimeSpan.FromMilliseconds(50); @@ -148,7 +147,7 @@ public void The_builder_adds_consumers_from_more_assemblies() var services = new ServiceCollection(); services.AddDbContext(_ => { }); - services.AddEfAsyncMonolith().AddConsumersFromAssemblyContaining(); + services.AddAsyncMonolith().AddConsumersFromAssemblyContaining(); services.ShouldContain(d => d.ServiceType == typeof(SingleConsumer)); services.BuildServiceProvider().GetRequiredService() diff --git a/AsyncMonolith.Tests/SqlDialectTests.cs b/AsyncMonolith.Tests/SqlDialectTests.cs new file mode 100644 index 0000000..214b3fc --- /dev/null +++ b/AsyncMonolith.Tests/SqlDialectTests.cs @@ -0,0 +1,45 @@ +using AsyncMonolith.Database; +using Microsoft.EntityFrameworkCore; +using Shouldly; + +namespace AsyncMonolith.Tests; + +/// +/// The fetch SQL is chosen from the EF Core provider the DbContext uses. +/// +public class SqlDialectTests +{ + private sealed class AnyDbContext(DbContextOptions options) : DbContext(options); + + private static SqlDialect DialectOf(Action configure) + { + var builder = new DbContextOptionsBuilder(); + configure(builder); + using var db = new AnyDbContext(builder.Options); + return SqlDialects.For(db); + } + + [Fact] + public void Npgsql_uses_PostgreSQL_queries() => + DialectOf(o => o.UseNpgsql("Host=localhost")).ShouldBe(SqlDialect.PostgreSql); + + [Fact] + public void SqlServer_uses_SQL_Server_queries() => + DialectOf(o => o.UseSqlServer("Server=localhost")).ShouldBe(SqlDialect.SqlServer); + + [Fact] + public void Oracles_MySQL_provider_uses_MySQL_queries() => + DialectOf(o => o.UseMySQL("Server=localhost")).ShouldBe(SqlDialect.MySql); + + [Fact] + public void SQLite_uses_generic_queries() => + DialectOf(o => o.UseSqlite("Data Source=:memory:")).ShouldBe(SqlDialect.Generic); + + [Theory] + [InlineData("Pomelo.EntityFrameworkCore.MySql", "MySql")] + [InlineData("Microsoft.EntityFrameworkCore.InMemory", "Generic")] + [InlineData("Some.Future.Provider", "Generic")] + [InlineData(null, "Generic")] + public void Other_providers_are_mapped_by_name(string? provider, string expected) => + SqlDialects.ForProvider(provider).ToString().ShouldBe(expected); +} diff --git a/AsyncMonolith.sln b/AsyncMonolith.sln index d563057..1ca3434 100644 --- a/AsyncMonolith.sln +++ b/AsyncMonolith.sln @@ -9,18 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.Tests", "Asyn EndProject Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{806BECFB-C02C-4502-BB1D-2CC45AD361B7}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.PostgreSql", "AsyncMonolith.PostgreSql\AsyncMonolith.PostgreSql.csproj", "{270D9590-C9A5-4E9A-99F4-523623DDD1BE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.Ef", "AsyncMonolith.Ef\AsyncMonolith.Ef.csproj", "{4280E7D0-D9EC-4E2E-9FDF-FB248815E1C6}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.MySql", "AsyncMonolith.MySql\AsyncMonolith.MySql.csproj", "{2F06268B-3C51-43B4-BC23-F57488FB7D54}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.MsSql", "AsyncMonolith.MsSql\AsyncMonolith.MsSql.csproj", "{4D8CF8E7-4708-49C3-B705-DF0D6BED7D70}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.TestHelpers", "AsyncMonolith.TestHelpers\AsyncMonolith.TestHelpers.csproj", "{5324854E-EC36-4C19-9B2E-67E360A9720F}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncMonolith.MariaDb", "AsyncMonolith.MariaDb\AsyncMonolith.MariaDb.csproj", "{5373CB42-0343-4B55-8215-1F84D3F6B9A3}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Example", "Example", "{A65E35F2-1B92-4704-8FE4-794B804D4DC0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example.Api", "Example\Example.Api\Example.Api.csproj", "{22570D99-521B-40A5-BC86-2ED8CFB13B01}" @@ -47,30 +37,10 @@ Global {806BECFB-C02C-4502-BB1D-2CC45AD361B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {806BECFB-C02C-4502-BB1D-2CC45AD361B7}.Release|Any CPU.ActiveCfg = Release|Any CPU {806BECFB-C02C-4502-BB1D-2CC45AD361B7}.Release|Any CPU.Build.0 = Release|Any CPU - {270D9590-C9A5-4E9A-99F4-523623DDD1BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {270D9590-C9A5-4E9A-99F4-523623DDD1BE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {270D9590-C9A5-4E9A-99F4-523623DDD1BE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {270D9590-C9A5-4E9A-99F4-523623DDD1BE}.Release|Any CPU.Build.0 = Release|Any CPU - {4280E7D0-D9EC-4E2E-9FDF-FB248815E1C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4280E7D0-D9EC-4E2E-9FDF-FB248815E1C6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4280E7D0-D9EC-4E2E-9FDF-FB248815E1C6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4280E7D0-D9EC-4E2E-9FDF-FB248815E1C6}.Release|Any CPU.Build.0 = Release|Any CPU - {2F06268B-3C51-43B4-BC23-F57488FB7D54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2F06268B-3C51-43B4-BC23-F57488FB7D54}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2F06268B-3C51-43B4-BC23-F57488FB7D54}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2F06268B-3C51-43B4-BC23-F57488FB7D54}.Release|Any CPU.Build.0 = Release|Any CPU - {4D8CF8E7-4708-49C3-B705-DF0D6BED7D70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4D8CF8E7-4708-49C3-B705-DF0D6BED7D70}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4D8CF8E7-4708-49C3-B705-DF0D6BED7D70}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4D8CF8E7-4708-49C3-B705-DF0D6BED7D70}.Release|Any CPU.Build.0 = Release|Any CPU {5324854E-EC36-4C19-9B2E-67E360A9720F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5324854E-EC36-4C19-9B2E-67E360A9720F}.Debug|Any CPU.Build.0 = Debug|Any CPU {5324854E-EC36-4C19-9B2E-67E360A9720F}.Release|Any CPU.ActiveCfg = Release|Any CPU {5324854E-EC36-4C19-9B2E-67E360A9720F}.Release|Any CPU.Build.0 = Release|Any CPU - {5373CB42-0343-4B55-8215-1F84D3F6B9A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5373CB42-0343-4B55-8215-1F84D3F6B9A3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5373CB42-0343-4B55-8215-1F84D3F6B9A3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5373CB42-0343-4B55-8215-1F84D3F6B9A3}.Release|Any CPU.Build.0 = Release|Any CPU {22570D99-521B-40A5-BC86-2ED8CFB13B01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {22570D99-521B-40A5-BC86-2ED8CFB13B01}.Debug|Any CPU.Build.0 = Debug|Any CPU {22570D99-521B-40A5-BC86-2ED8CFB13B01}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -87,12 +57,12 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {3364CDD8-5643-424F-B460-C6C6C54AC23C} - EndGlobalSection GlobalSection(NestedProjects) = preSolution {22570D99-521B-40A5-BC86-2ED8CFB13B01} = {A65E35F2-1B92-4704-8FE4-794B804D4DC0} {6F1B4763-8CB7-4CD2-8191-76B662D9458A} = {A65E35F2-1B92-4704-8FE4-794B804D4DC0} {A89CE061-B485-42B0-B48E-D16E049DAFEB} = {A65E35F2-1B92-4704-8FE4-794B804D4DC0} EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3364CDD8-5643-424F-B460-C6C6C54AC23C} + EndGlobalSection EndGlobal diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index afb99ce..34d3e16 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -16,11 +16,6 @@ - - - - - diff --git a/AsyncMonolith/Database/Fetchers.cs b/AsyncMonolith/Database/Fetchers.cs new file mode 100644 index 0000000..38e45d4 --- /dev/null +++ b/AsyncMonolith/Database/Fetchers.cs @@ -0,0 +1,92 @@ +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Utilities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Options; + +namespace AsyncMonolith.Database; + +/// +/// Fetches due consumer messages on a rail. On PostgreSQL, SQL Server, MySQL and MariaDB the rows are locked +/// and rows locked by other processors are skipped; other providers use LINQ without locks. Values are passed +/// as EF parameters, so no database driver is referenced. +/// +internal sealed class ConsumerMessageFetcher(IOptions options) : IConsumerMessageFetcher +{ + private const string PostgreSql = + "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; + + private const string SqlServer = + "SELECT TOP ({2}) * FROM {table} WITH (ROWLOCK, UPDLOCK, READPAST) WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id"; + + private const string MySql = + "SELECT * FROM {table} WHERE available_after <= {0} AND rail_id = {1} ORDER BY created_at, id LIMIT {2} FOR UPDATE SKIP LOCKED"; + + public Task> Fetch(DbSet consumerSet, long currentTime, int railId, + CancellationToken cancellationToken = default) + { + var batchSize = options.Value.BatchSize; + var sql = SqlDialects.For(consumerSet.GetService().Context) switch + { + SqlDialect.PostgreSql => PostgreSql, + SqlDialect.SqlServer => SqlServer, + SqlDialect.MySql => MySql, + _ => null + }; + + if (sql is null) + { + return consumerSet + .Where(m => m.AvailableAfter <= currentTime && m.RailId == railId) + .OrderBy(m => m.CreatedAt).ThenBy(m => m.Id) + .Take(batchSize) + .ToListAsync(cancellationToken); + } + + return consumerSet + .FromSqlRaw(sql.Replace("{table}", AsyncMonolithTables.Name(consumerSet), StringComparison.Ordinal), + currentTime, railId, batchSize) + .ToListAsync(cancellationToken); + } +} + +/// Fetches due schedules, locking rows where the database supports it, like . +internal sealed class ScheduledMessageFetcher(IOptions options) : IScheduledMessageFetcher +{ + private const string PostgreSql = + "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; + + private const string SqlServer = + "SELECT TOP ({1}) * FROM {table} WITH (ROWLOCK, UPDLOCK, READPAST) WHERE available_after <= {0} ORDER BY available_after, id"; + + private const string MySql = + "SELECT * FROM {table} WHERE available_after <= {0} ORDER BY available_after, id LIMIT {1} FOR UPDATE SKIP LOCKED"; + + public Task> Fetch(DbSet scheduledMessageSet, long currentTime, + CancellationToken cancellationToken = default) + { + var batchSize = options.Value.BatchSize; + var sql = SqlDialects.For(scheduledMessageSet.GetService().Context) switch + { + SqlDialect.PostgreSql => PostgreSql, + SqlDialect.SqlServer => SqlServer, + SqlDialect.MySql => MySql, + _ => null + }; + + if (sql is null) + { + return scheduledMessageSet + .Where(m => m.AvailableAfter <= currentTime) + .OrderBy(m => m.AvailableAfter).ThenBy(m => m.Id) + .Take(batchSize) + .ToListAsync(cancellationToken); + } + + return scheduledMessageSet + .FromSqlRaw(sql.Replace("{table}", AsyncMonolithTables.Name(scheduledMessageSet), StringComparison.Ordinal), + currentTime, batchSize) + .ToListAsync(cancellationToken); + } +} diff --git a/AsyncMonolith/Database/SqlDialect.cs b/AsyncMonolith/Database/SqlDialect.cs new file mode 100644 index 0000000..571f48f --- /dev/null +++ b/AsyncMonolith/Database/SqlDialect.cs @@ -0,0 +1,39 @@ +using System.Collections.Concurrent; +using Microsoft.EntityFrameworkCore; + +namespace AsyncMonolith.Database; + +/// The SQL used to fetch due rows, chosen from the EF Core provider in use. +internal enum SqlDialect +{ + /// LINQ without row locks: works with any provider, such as SQLite. + Generic, + + /// PostgreSQL: FOR UPDATE SKIP LOCKED. + PostgreSql, + + /// SQL Server: WITH (ROWLOCK, UPDLOCK, READPAST). + SqlServer, + + /// MySQL and MariaDB: FOR UPDATE SKIP LOCKED. + MySql +} + +internal static class SqlDialects +{ + private static readonly ConcurrentDictionary ByProvider = new(); + + /// Picks the dialect for an EF Core provider name, such as Npgsql.EntityFrameworkCore.PostgreSQL. + public static SqlDialect ForProvider(string? providerName) => + providerName is null ? SqlDialect.Generic : ByProvider.GetOrAdd(providerName, Detect); + + public static SqlDialect For(DbContext context) => ForProvider(context.Database.ProviderName); + + private static SqlDialect Detect(string providerName) => providerName switch + { + "Npgsql.EntityFrameworkCore.PostgreSQL" => SqlDialect.PostgreSql, + "Microsoft.EntityFrameworkCore.SqlServer" => SqlDialect.SqlServer, + "MySql.EntityFrameworkCore" or "Pomelo.EntityFrameworkCore.MySql" => SqlDialect.MySql, + _ => SqlDialect.Generic + }; +} diff --git a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs index 3463a22..db321a6 100644 --- a/AsyncMonolith/Utilities/AsyncMonolithOptions.cs +++ b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs @@ -6,7 +6,7 @@ namespace AsyncMonolith.Utilities; /// -/// Options for AsyncMonolith. Set them in the Add*AsyncMonolith call, or bind them from configuration +/// Options for AsyncMonolith. Set them in the AddAsyncMonolith call, or bind them from configuration /// with . They are validated when the host starts. /// public sealed class AsyncMonolithOptions @@ -167,7 +167,7 @@ public ValidateOptionsResult Validate(string? name, AsyncMonolithOptions options } /// -/// Returned by Add*AsyncMonolith to continue configuring AsyncMonolith. +/// Returned by AddAsyncMonolith to continue configuring AsyncMonolith. /// public sealed class AsyncMonolithBuilder { diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 6d3347d..4e088f8 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -2,6 +2,7 @@ using System.Diagnostics.Metrics; using System.Reflection; using AsyncMonolith.Consumers; +using AsyncMonolith.Database; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using Microsoft.EntityFrameworkCore; @@ -32,6 +33,28 @@ public static ModelBuilder ConfigureAsyncMonolith(this ModelBuilder modelBuilder return modelBuilder; } + /// + /// Registers AsyncMonolith: the producer, schedule, poisoned message and statistics services, and the + /// background processors. Call it once, in the host. + /// + /// + /// The queries are chosen from the DbContext's EF Core provider. PostgreSQL (Npgsql), SQL Server, and MySQL + /// or MariaDB (MySql.EntityFrameworkCore or Pomelo) lock rows, so several app instances skip each other's + /// batches. Other providers, such as SQLite, use plain queries without row locks. + /// + /// The DbContext containing the AsyncMonolith tables. + /// The service collection. + /// Sets options and the assemblies to scan for consumers. + /// A builder to bind configuration or add more consumer assemblies. + public static AsyncMonolithBuilder AddAsyncMonolith(this IServiceCollection services, + Action? configure = null) where T : DbContext + { + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); + services.TryAddSingleton(); + services.TryAddSingleton(); + return builder; + } + internal static void InternalConfigureAsyncMonolithOptions( this IServiceCollection services, Action configure) @@ -48,7 +71,7 @@ internal static AsyncMonolithBuilder InternalAddAsyncMonolith( if (services.Any(d => d.ServiceType == typeof(AsyncMonolithRegistration))) { throw new InvalidOperationException( - "AsyncMonolith is already registered. Call Add*AsyncMonolith once, in the host; modules register " + + "AsyncMonolith is already registered. Call AddAsyncMonolith once, in the host; modules register " + "their consumers with AddAsyncMonolithConsumers."); } @@ -88,7 +111,7 @@ internal static void InternalRegisterAsyncMonolithConsumers( /// /// Registers the consumers and payloads in the given assemblies. Call it from each module that has - /// consumers; the host calls Add*AsyncMonolith once. Order doesn't matter, and registering the + /// consumers; the host calls AddAsyncMonolith once. Order doesn't matter, and registering the /// same assembly twice is harmless. /// /// @@ -244,7 +267,7 @@ internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable ass private sealed class ConsumerAssemblies : HashSet; - /// Marks that Add*AsyncMonolith has been called. + /// Marks that AddAsyncMonolith has been called. private sealed class AsyncMonolithRegistration; private static string RegisterPayloadName(Dictionary payloadTypes, Type payloadType) diff --git a/Example/Example.Api/Example.Api.csproj b/Example/Example.Api/Example.Api.csproj index e99c515..32ff087 100644 --- a/Example/Example.Api/Example.Api.csproj +++ b/Example/Example.Api/Example.Api.csproj @@ -21,7 +21,7 @@ - + diff --git a/Example/Example.Api/Program.cs b/Example/Example.Api/Program.cs index 3dfb80f..b565662 100644 --- a/Example/Example.Api/Program.cs +++ b/Example/Example.Api/Program.cs @@ -1,5 +1,4 @@ using System.Reflection; -using AsyncMonolith.PostgreSql; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; using Example.Api.Counter; @@ -29,7 +28,7 @@ public static void Main(string[] args) builder.Services.AddSingleton(TimeProvider.System); - builder.Services.AddPostgreSqlAsyncMonolith(settings => + builder.Services.AddAsyncMonolith(settings => { settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); settings.AttemptDelay = TimeSpan.FromSeconds(10); diff --git a/PACKAGE.md b/PACKAGE.md index 4ef2d09..d7d92db 100644 --- a/PACKAGE.md +++ b/PACKAGE.md @@ -7,21 +7,23 @@ Background messaging and scheduling for .NET monoliths, using the database you a - **Schedules**: recurring messages from cron expressions in any time zone. - **Safe with several app instances**, with metrics on the `async_monolith` meter. -## Packages +## Databases -| Package | Use with | +One package works with any EF Core provider and picks its queries from the one you use: + +| Provider | Row locking | |---|---| -| `AsyncMonolith.PostgreSql` | PostgreSQL (Npgsql) | -| `AsyncMonolith.MsSql` | SQL Server | -| `AsyncMonolith.MySql` | MySQL (`MySql.EntityFrameworkCore`) | -| `AsyncMonolith.MariaDb` | MariaDB | -| `AsyncMonolith.Ef` | Any EF Core provider, including SQLite (without row locking) | -| `AsyncMonolith.TestHelpers` | Testing consumers with xunit v3 | +| PostgreSQL (`Npgsql.EntityFrameworkCore.PostgreSQL`) | `FOR UPDATE SKIP LOCKED` | +| SQL Server (`Microsoft.EntityFrameworkCore.SqlServer`) | `UPDLOCK, READPAST` | +| MySQL / MariaDB (`MySql.EntityFrameworkCore` or Pomelo) | `FOR UPDATE SKIP LOCKED` | +| Anything else, such as SQLite | None: fine for a single instance | + +`AsyncMonolith.TestHelpers` adds fakes and helpers for testing consumers with xunit v3. ## Quick start ```csharp -builder.Services.AddPostgreSqlAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); +builder.Services.AddAsyncMonolith(o => o.RegisterTypesFromAssemblyContaining()); // In AppDbContext.OnModelCreating modelBuilder.ConfigureAsyncMonolith(); diff --git a/README.md b/README.md index fb8a1f0..0d12acc 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,5 @@ # AsyncMonolith ![Logo](AsyncMonolith/logo.png) -[![Ef](https://img.shields.io/nuget/v/AsyncMonolith.Ef?label=Ef)](https://www.nuget.org/packages/AsyncMonolith.Ef) -[![MySql](https://img.shields.io/nuget/v/AsyncMonolith.MySql?label=MySql)](https://www.nuget.org/packages/AsyncMonolith.MySql) -[![MsSql](https://img.shields.io/nuget/v/AsyncMonolith.MsSql?label=MsSql)](https://www.nuget.org/packages/AsyncMonolith.MsSql) -[![PostgreSql](https://img.shields.io/nuget/v/AsyncMonolith.PostgreSql?label=PostgreSql)](https://www.nuget.org/packages/AsyncMonolith.PostgreSql) -[![MariaDb](https://img.shields.io/nuget/v/AsyncMonolith.MariaDb?label=MariaDb)](https://www.nuget.org/packages/AsyncMonolith.MariaDb) +[![NuGet](https://img.shields.io/nuget/v/AsyncMonolith?label=AsyncMonolith)](https://www.nuget.org/packages/AsyncMonolith) AsyncMonolith is a lightweight library that facilitates simple, durable and asynchronous messaging in dotnet apps. diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 5cd0f7e..d6ec76e 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -1,7 +1,7 @@ - **Independent Consumption**: Each message will be consumed independently by each consumer set up to handle it. - **Periodic Querying**: Each instance of your app will periodically query the `consumer_messages` table for a batch of available messages to process. - After a batch that wasn't full it waits `IdlePollInterval` before looking again; after a full batch it waits `BusyPollInterval`. -- **Multiple instances**: Any number of app instances can process the same tables, with every database package. A processor claims each message with a conditional update, so a message is only ever claimed by one processor at a time, and each schedule occurrence fires once. The PostgreSQL, SQL Server, MySQL and MariaDB packages also lock rows while claiming, so processors skip each other's batches instead of competing for them. +- **Multiple instances**: Any number of app instances can process the same tables, with any database. A processor claims each message with a conditional update, so a message is only ever claimed by one processor at a time, and each schedule occurrence fires once. On PostgreSQL, SQL Server, MySQL and MariaDB, processors also lock rows while claiming, so processors skip each other's batches instead of competing for them. - **Rails**: Each rail (`[ConsumerRailId]`) gets its own processor, so a slow consumer on one rail doesn't hold up consumers on another. - **Batching**: Consumer messages will be read from the `consumer_messages` table in batches defined by `BatchSize`. - **Idempotency**: Ensure your Consumers are idempotent, since they will be retried on failure. diff --git a/docs/guides/producing-messages.md b/docs/guides/producing-messages.md index deb1e24..c20d7e6 100644 --- a/docs/guides/producing-messages.md +++ b/docs/guides/producing-messages.md @@ -35,7 +35,7 @@ You can produce messages to be consumed immediately like this: await _dbContext.SaveChangesAsync(cancellationToken); ``` -The message is added to your `DbContext` and written when you call `SaveChangesAsync`, in the same transaction as your other changes. If you never save, or the save fails, no message is written. This works the same with every database package. Learn more about the [Transactional Outbox](../transactional-outbox) pattern. +The message is added to your `DbContext` and written when you call `SaveChangesAsync`, in the same transaction as your other changes. If you never save, or the save fails, no message is written. This works the same with every database. Learn more about the [Transactional Outbox](../transactional-outbox) pattern. ## Delayed messages You can produce messages to be consumed after a delay by passing a `TimeSpan`, or at a set time by passing a `DateTimeOffset`. Times are stored in whole seconds and rounded up, so a message is never consumed early. diff --git a/docs/index.md b/docs/index.md index e40f33b..1866420 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,10 +1,6 @@ # [AsyncMonolith](https://github.com/Timmoth/AsyncMonolith) ![Logo](assets/logo.png) -[![Ef](https://img.shields.io/nuget/v/AsyncMonolith.Ef?label=Ef)](https://www.nuget.org/packages/AsyncMonolith.Ef) -[![MySql](https://img.shields.io/nuget/v/AsyncMonolith.MySql?label=MySql)](https://www.nuget.org/packages/AsyncMonolith.MySql) -[![MsSql](https://img.shields.io/nuget/v/AsyncMonolith.MsSql?label=MsSql)](https://www.nuget.org/packages/AsyncMonolith.MsSql) -[![PostgreSql](https://img.shields.io/nuget/v/AsyncMonolith.PostgreSql?label=PostgreSql)](https://www.nuget.org/packages/AsyncMonolith.PostgreSql) -[![MariaDb](https://img.shields.io/nuget/v/AsyncMonolith.MariaDb?label=MariaDb)](https://www.nuget.org/packages/AsyncMonolith.MariaDb) +[![NuGet](https://img.shields.io/nuget/v/AsyncMonolith?label=AsyncMonolith)](https://www.nuget.org/packages/AsyncMonolith) AsyncMonolith is a lightweight library that facilitates simple, durable and asynchronous messaging in dotnet apps. diff --git a/docs/internals.md b/docs/internals.md index 498dfac..6668f5a 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -20,7 +20,7 @@ Writes scheduled messages to the `scheduled_messages` table. One background processor runs per rail. Each cycle it: -1. **Claims** a batch in a short transaction: it reads due messages (locking rows with the PostgreSQL, SQL Server, MySQL and MariaDB packages), then for each one counts the attempt and leases it by moving `available_after` past the consumer's timeout plus 30 seconds. The update only applies if the message is unchanged since it was read, so only one processor can claim it. +1. **Claims** a batch in a short transaction: it reads due messages (locking rows on PostgreSQL, SQL Server, MySQL and MariaDB), then for each one counts the attempt and leases it by moving `available_after` past the consumer's timeout plus 30 seconds. The update only applies if the message is unchanged since it was read, so only one processor can claim it. 2. **Consumes** each claimed message outside any transaction, in its own DI scope, so consumers can use the database freely. 3. **Completes** each message in its own short write: deleted on success, otherwise retried after a backoff delay, or moved to `poisoned_messages` after its last attempt. If its lease was taken over meanwhile, nothing is changed. diff --git a/docs/quickstart.md b/docs/quickstart.md index aed7787..45350d1 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -2,19 +2,10 @@ Install the nuget package to support your database -[![Ef](https://img.shields.io/nuget/v/AsyncMonolith.Ef?label=Ef)](https://www.nuget.org/packages/AsyncMonolith.Ef) -[![MySql](https://img.shields.io/nuget/v/AsyncMonolith.MySql?label=MySql)](https://www.nuget.org/packages/AsyncMonolith.MySql) -[![MsSql](https://img.shields.io/nuget/v/AsyncMonolith.MsSql?label=MsSql)](https://www.nuget.org/packages/AsyncMonolith.MsSql) -[![PostgreSql](https://img.shields.io/nuget/v/AsyncMonolith.PostgreSql?label=PostgreSql)](https://www.nuget.org/packages/AsyncMonolith.PostgreSql) -[![MariaDb](https://img.shields.io/nuget/v/AsyncMonolith.MariaDb?label=MariaDb)](https://www.nuget.org/packages/AsyncMonolith.MariaDb) +[![NuGet](https://img.shields.io/nuget/v/AsyncMonolith?label=AsyncMonolith)](https://www.nuget.org/packages/AsyncMonolith) ```csharp - // Pick one - dotnet add package AsyncMonolith.Ef - dotnet add package AsyncMonolith.MySql - dotnet add package AsyncMonolith.MsSql - dotnet add package AsyncMonolith.PostgreSql - dotnet add package AsyncMonolith.MariaDb + dotnet add package AsyncMonolith ``` Setup your DbContext @@ -50,17 +41,13 @@ Register your dependencies and configure settings ```csharp - // Register required services - builder.Services.AddLogging(); - builder.Services.AddSingleton(TimeProvider.System); - - // Register AsyncMonolith using either: - // services.AddEfAsyncMonolith - // services.AddMsSqlAsyncMonolith - // services.AddMySqlAsyncMonolith - // services.AddPostgreSqlAsyncMonolith - // services.AddMariaDbAsyncMonolith - builder.Services.AddPostgreSqlAsyncMonolith(options => + // Your DbContext, with any EF Core provider + builder.Services.AddDbContext(o => o.UseNpgsql(connectionString)); + + // AsyncMonolith picks its queries from the provider: PostgreSQL (Npgsql), SQL Server, and MySQL or MariaDB + // (MySql.EntityFrameworkCore or Pomelo) lock rows so several app instances can share the tables. Any other + // provider, such as SQLite, works without row locks (fine for a single instance). + builder.Services.AddAsyncMonolith(options => { options.RegisterTypesFromAssemblyContaining(); options.MaxAttempts = 5; // Attempts before a message is poisoned @@ -85,7 +72,7 @@ The following methods are available on the `AsyncMonolithOptions` passed into th ### Modules -Call `Add*AsyncMonolith` once, in the host. A module or library with its own consumers registers them itself, before or after the host's call: +Call `AddAsyncMonolith` once, in the host. A module or library with its own consumers registers them itself, before or after the host's call: ```csharp services.AddAsyncMonolithConsumersFromAssemblyContaining(); diff --git a/docs/releases.md b/docs/releases.md index 111d696..142f497 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -17,19 +17,18 @@ Make sure to check this table before updating the nuget package in your solution ## 11.0.0 -All packages now share one version and must be upgraded together. From 11.0.0 the major version follows [Semantic Versioning](https://semver.org) (it changes for breaking changes) rather than the .NET version. The MySQL and MariaDB packages are tested against MySQL 8.4 and MariaDB 11.8 with Oracle's `MySql.EntityFrameworkCore`. +AsyncMonolith is now a single package. From 11.0.0 the major version follows [Semantic Versioning](https://semver.org) (it changes for breaking changes) rather than the .NET version. It is tested against PostgreSQL, SQL Server, MySQL 8.4 (with Oracle's `MySql.EntityFrameworkCore`), MariaDB 11.8 and SQLite. **Migration required.** Add a migration (`dotnet ef migrations add AsyncMonolith_11_0_0`). It adds a nullable `last_error` column to `consumer_messages` and `poisoned_messages`. It also adds indexes for finding due messages (`rail_id, available_after`), due schedules (`available_after`), schedules by tag, and poisoned messages by age, which keep processing fast as the tables grow. If you manage the schema by hand, see the [SQL schemas](https://github.com/Timmoth/AsyncMonolith/tree/main/Schemas). They also now include `rail_id`, and their `trace_id` and `span_id` columns are nullable. **Changes** - Metrics on the `async_monolith` meter, and optional `PoisonedMessageRetention`. - A schedule that can't be evaluated, or whose payload has no consumers, no longer stops the others. A consumer that ignores cancellation is abandoned two seconds after its timeout. Processors back off while the database is unavailable. -- The database packages no longer reference a database driver: bring your own EF Core provider (for MySQL, `MySql.EntityFrameworkCore`). - Cron expressions can have 5 fields (minute precision) as well as 6 (seconds first). - `AsyncMonolithOptions.SerializerOptions` sets the `JsonSerializerOptions` for payloads. The default is unchanged. -- Tables can live in their own schema or have a prefix: `modelBuilder.ConfigureAsyncMonolith(o => { o.Schema = "jobs"; o.TablePrefix = "jobs_"; })`. The database packages' SQL follows the mapping. -- Every database package now produces messages the same way: they are added to your `DbContext` and written on `SaveChanges`, in your transaction. The PostgreSQL, SQL Server, MySQL and MariaDB packages used to write immediately. A repeated insert id skips consumers that already have a pending message with it, on every database. -- Several app instances can safely share the tables with any database package. Claims and schedule occurrences use conditional updates, so a message is processed by one processor at a time and a schedule fires once per occurrence. +- Tables can live in their own schema or have a prefix: `modelBuilder.ConfigureAsyncMonolith(o => { o.Schema = "jobs"; o.TablePrefix = "jobs_"; })`. The row-locking SQL follows the mapping. +- Every database now produces messages the same way: they are added to your `DbContext` and written on `SaveChanges`, in your transaction. The PostgreSQL, SQL Server, MySQL and MariaDB packages used to write immediately. A repeated insert id skips consumers that already have a pending message with it, on every database. +- Several app instances can safely share the tables with any database. Claims and schedule occurrences use conditional updates, so a message is processed by one processor at a time and a schedule fires once per occurrence. - Fetch order is deterministic (oldest first, then by id). See [Ordering](guides/consuming-messages.md#ordering) for what is and isn't guaranteed. - Consumers can write to the database on SQLite. Messages are claimed and leased in a short transaction, consumers run outside it, and each message is completed in its own short write. If the app stops mid-message, the message is retried once its consumer timeout plus 30 seconds has passed. - Retries back off exponentially from `AttemptDelay` up to the new `MaxAttemptDelay` option (default 5 minutes). @@ -38,21 +37,22 @@ All packages now share one version and must be upgraded together. From 11.0.0 th - `IScheduleService.EnsureSchedule` creates or updates a schedule by tag, so it can run at every startup. - `IQueueStatisticsService` reports queue depth and the age of the oldest due message, for health checks. - `[ConsumerPayloadName]` and `[ConsumerName]` give payloads and consumers stable stored names. Name clashes now fail at startup instead of silently mixing messages. -- `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `Add*AsyncMonolith` call. +- `AddAsyncMonolithConsumers` lets modules register their own consumers alongside the host's `AddAsyncMonolith` call. **Breaking changes** +- **One package.** `AsyncMonolith.Ef`, `.PostgreSql`, `.MsSql`, `.MySql` and `.MariaDb` are replaced by `AsyncMonolith` alone, and `AddEfAsyncMonolith`/`AddPostgreSqlAsyncMonolith`/... by `AddAsyncMonolith()`. The queries are chosen from your DbContext's EF Core provider, and AsyncMonolith no longer references any database driver: bring your own provider (for MySQL, `MySql.EntityFrameworkCore`; Pomelo works once it supports EF Core 10). - `ConfigureAsyncMonolith()` now maps all three tables (previously only an index), so DbSet properties for them are optional. It takes an optional schema and table prefix. The `[Table]` attributes on the entities are removed; call `ConfigureAsyncMonolith()` in `OnModelCreating` if you weren't already. - `IPoisonedMessageService.List` returns `PoisonedMessageInfo` records with `DateTimeOffset` times instead of `PoisonedMessage` entities. - Implementation types are now internal: `ConsumerRegistry`, the processors and processor factory, the fetchers and their interfaces, `ScheduleService`, `PoisonedMessageService`, `QueueStatisticsService`, `AsyncMonolithIdGenerator`, `AsyncMonolithInstrumentation.ActivitySource` (the source name constants stay public), and `ScheduledMessage.GetNextOccurrence`/`UpdateSchedule`/`UpdatePayload`. Use the service interfaces instead. `FakeProducerService` is created by `AddFakeAsyncMonolithBaseServices`. - `IProducerService.Produce` takes a `TimeSpan? delay` or a `DateTimeOffset availableAt` instead of a Unix-seconds `long availableAfter`, and `insertId` is renamed `deduplicationKey` (still stored in `insert_id`). `ProduceList` takes an `IEnumerable`. `Produce(ScheduledMessage)` is no longer on the interface. - Renamed: `ChronExpression`/`ChronTimezone` → `CronExpression`/`CronTimeZone` (columns unchanged), `InsertId` → `DeduplicationKey` (column unchanged), `ConsumerInstanceExecutionMode` → `ConsumerExecutionMode`, and `IScheduleService` parameters to `cronExpression`/`timeZone`. No migration is needed for these. - `AsyncMonolithSettings` is now `AsyncMonolithOptions`, configured through the standard options pattern and validated when the host starts (an `OptionsValidationException` instead of an `ArgumentException` at registration). Times are `TimeSpan`s, and some names changed: `ProcessorBatchSize` → `BatchSize`, `ProcessorMaxDelay` (ms) → `IdlePollInterval`, `ProcessorMinDelay` (ms) → `BusyPollInterval`. `AsyncMonolithSettings.Default` is gone; use `new AsyncMonolithOptions()`. -- `Add*AsyncMonolith` returns an `AsyncMonolithBuilder` (for `.BindConfiguration(...)` and `.AddConsumers(...)`) instead of `IServiceCollection`, and the obsolete overloads taking an `Assembly` are removed. The TestHelpers setup methods take `Action`. +- `AddAsyncMonolith` returns an `AsyncMonolithBuilder` (for `.BindConfiguration(...)` and `.AddConsumers(...)`) instead of `IServiceCollection`, and the obsolete overloads taking an `Assembly` are removed. The TestHelpers setup methods take `Action`. - `[ConsumerTimeout]`'s `Duration` property is now `Seconds`. - Consumers implement `IConsumer` and receive a `ConsumeContext`; `BaseConsumer` is removed. - PostgreSQL, SQL Server, MySQL and MariaDB users: messages are no longer written until you call `SaveChanges`. If you produced messages without saving, call `SaveChangesAsync`. -- `Add*AsyncMonolith` no longer registers `DbContext` as an alias for your context, and throws if called twice (modules use `AddAsyncMonolithConsumers`). Its services use `TryAdd`, so services you register first win. -- Removed public types: `EfProducerService`, `PostgreSqlProducerService`, `MsSqlProducerService`, `MySqlProducerService`, `MariaDbProducerService` and the unused `ScheduledMessageProcessorFactory`. Resolve `IProducerService` instead. +- `AddAsyncMonolith` no longer registers `DbContext` as an alias for your context, and throws if called twice (modules use `AddAsyncMonolithConsumers`). Its services use `TryAdd`, so services you register first win. +- Removed public types: the per-database producer services and the unused `ScheduledMessageProcessorFactory`. Resolve `IProducerService` instead. - `AsyncMonolith.TestHelpers` uses xunit v3, and `ConsumerTestBase.InitializeAsync`/`DisposeAsync` return `ValueTask`. - `IScheduleService` has a new member (`EnsureSchedule`), so custom implementations must add it. - Errors that were thrown as `System.Exception` are now `InvalidOperationException`. diff --git a/docs/warnings.md b/docs/warnings.md index 4c5e0de..540b144 100644 --- a/docs/warnings.md +++ b/docs/warnings.md @@ -1,4 +1,4 @@ -- **Single-instance or development with `AsyncMonolith.Ef`.** EF Core has no portable row locking, so with `AsyncMonolith.Ef` several app instances read the same candidate messages and compete for them. Claims are conditional, so a message is still only processed by one instance, but instances waste work. In production with several instances, use `AsyncMonolith.PostgreSql`, `AsyncMonolith.MsSql`, `AsyncMonolith.MySql` or `AsyncMonolith.MariaDb`, which lock rows and skip each other's batches. +- **Row locking depends on your database.** With PostgreSQL (Npgsql), SQL Server, and MySQL or MariaDB (MySql.EntityFrameworkCore or Pomelo), processors lock rows and skip each other's batches. With any other EF Core provider, such as SQLite, several app instances read the same candidate messages and compete for them. Claims are conditional, so a message is still processed by only one instance, but instances waste work. That is fine for a single instance. - **Consumers run at least once.** A message can run again if the app stops mid-message, or if a consumer ignores its cancellation token and is abandoned. Make consumers idempotent: `ConsumeContext.MessageId` and `ConsumeContext.DeduplicationKey` help. - **Honour the `CancellationToken`.** It is cancelled at the consumer's timeout and when the app stops. - **Batches finish together.** A processor waits for every consumer in its batch before taking the next, so a slow consumer delays the others on its rail. Put slow consumers on their own rail with `[ConsumerRailId]`, or raise their `[ConsumerTimeout]`. From 8f9e60ad0d5b9f00e47020786101953d5a4b68b7 Mon Sep 17 00:00:00 2001 From: Tim Jones Date: Fri, 20 Nov 2026 06:14:05 +0000 Subject: [PATCH 53/53] Make the integration test harness reliable locally - Each test database container is tracked before it starts, so one that fails to start is still cleaned up and its real error is reported (it surfaced as a NullReferenceException before). - The harness waits until the database accepts a connection before a test uses it. MySQL can refuse connections for a moment after the container reports ready, which failed one test in a long local run. - The tests guide explains running SQL Server containers on Apple Silicon. A full local run (fast and integration tests against PostgreSQL, SQL Server, MySQL and MariaDB) passed 325 of 326 before these fixes; the one failure was that MySQL startup race, and the test passes on rerun. --- .../Infra/EfTestDbContainer.cs | 3 +- .../Infra/MariaDbTestDbContainer.cs | 3 +- .../Infra/MsSqlTestDbContainer.cs | 3 +- .../Infra/MySqlTestDbContainer.cs | 3 +- .../Infra/PostgreSqlTestDbContainer.cs | 3 +- .../Infra/TestDbContainerBase.cs | 45 ++++++++++++++++++- docs/tests.md | 2 + 7 files changed, 55 insertions(+), 7 deletions(-) diff --git a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs index 85ed003..f21d699 100644 --- a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs @@ -9,9 +9,10 @@ public class EfTestDbContainer : TestDbContainerBase public override async Task InitializeContainerAsync() { var container = new PostgreSqlBuilder("postgres:18-alpine").Build(); + // Kept before starting, so a container that fails to start is still cleaned up. + DbContainer = container; await container.StartAsync(); ConnectionString = container.GetConnectionString(); - DbContainer = container; } public override void AddDb(IServiceCollection services) diff --git a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs index 0a240b2..4ab64b5 100644 --- a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs @@ -10,9 +10,10 @@ public class MariaDbTestDbContainer : TestDbContainerBase public override async Task InitializeContainerAsync() { var container = new MariaDbBuilder("mariadb:11.8").Build(); + // Kept before starting, so a container that fails to start is still cleaned up. + DbContainer = container; await container.StartAsync(); ConnectionString = container.GetConnectionString(); - DbContainer = container; } public override void AddDb(IServiceCollection services) diff --git a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs index 26796a7..484f8a5 100644 --- a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs @@ -9,9 +9,10 @@ public class MsSqlTestDbContainer : TestDbContainerBase public override async Task InitializeContainerAsync() { var container = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest").Build(); + // Kept before starting, so a container that fails to start is still cleaned up. + DbContainer = container; await container.StartAsync(); ConnectionString = container.GetConnectionString(); - DbContainer = container; } public override void AddDb(IServiceCollection services) diff --git a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs index e4777d0..a7ba9fe 100644 --- a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs @@ -9,9 +9,10 @@ public class MySqlTestDbContainer : TestDbContainerBase public override async Task InitializeContainerAsync() { var container = new MySqlBuilder("mysql:8.4").Build(); + // Kept before starting, so a container that fails to start is still cleaned up. + DbContainer = container; await container.StartAsync(); ConnectionString = container.GetConnectionString(); - DbContainer = container; } public override void AddDb(IServiceCollection services) diff --git a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs index e41f3ac..2ce1319 100644 --- a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs @@ -9,9 +9,10 @@ public class PostgreSqlTestDbContainer : TestDbContainerBase public override async Task InitializeContainerAsync() { var container = new PostgreSqlBuilder("postgres:18-alpine").Build(); + // Kept before starting, so a container that fails to start is still cleaned up. + DbContainer = container; await container.StartAsync(); ConnectionString = container.GetConnectionString(); - DbContainer = container; } public override void AddDb(IServiceCollection services) diff --git a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs index be5a655..5440a72 100644 --- a/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs +++ b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs @@ -1,3 +1,4 @@ +using Microsoft.EntityFrameworkCore; using DotNet.Testcontainers.Containers; using Microsoft.Extensions.DependencyInjection; @@ -5,18 +6,58 @@ namespace AsyncMonolith.Tests.Infra; public abstract class TestDbContainerBase : IAsyncLifetime { - protected IContainer DbContainer { get; set; } = default!; + protected IContainer? DbContainer { get; set; } public string ConnectionString { get; protected set; } = default!; public DbType DbType => GetDbType(); public async ValueTask InitializeAsync() { await InitializeContainerAsync(); + await WaitUntilConnectable(); + } + + /// + /// A container can report ready a moment before the database accepts connections (MySQL restarts once while + /// initialising), so wait until a connection succeeds before handing it to a test. + /// + private async Task WaitUntilConnectable() + { + var services = new ServiceCollection(); + AddDb(services); + await using var provider = services.BuildServiceProvider(); + var deadline = DateTime.UtcNow.AddMinutes(2); + while (true) + { + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + try + { + if (await db.Database.CanConnectAsync()) + { + return; + } + } + catch (Exception) when (DateTime.UtcNow < deadline) + { + // Not accepting connections yet + } + + if (DateTime.UtcNow >= deadline) + { + throw new TimeoutException($"The {GetDbType()} test database never accepted a connection."); + } + + await Task.Delay(500); + } } public async ValueTask DisposeAsync() { - await DbContainer.DisposeAsync(); + if (DbContainer is not null) + { + await DbContainer.DisposeAsync(); + } + GC.SuppressFinalize(this); } diff --git a/docs/tests.md b/docs/tests.md index 51fed8e..62c6c4a 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -14,6 +14,8 @@ Tests are split into two groups: dotnet test --project AsyncMonolith.Tests --filter-trait "Category=Integration" ``` +On Apple Silicon, SQL Server runs under emulation and needs about 2 GB per container. If SQL Server containers exit with code 114, give Docker more memory or run the tests one class at a time with `--parallel none` (about 9 minutes for the whole suite). + Add `--coverage --coverage-output-format cobertura` to either command for a coverage report. CI uploads one for each run as an artifact.