diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 9309a8d..0000000 Binary files a/.DS_Store and /dev/null differ 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/.github/workflows/SonarCloud.yml b/.github/workflows/SonarCloud.yml deleted file mode 100644 index b12f52a..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@v3 - with: - java-version: 17 - distribution: 'zulu' # Alternative distribution options are available. - - uses: actions/checkout@v3 - with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Cache SonarCloud packages - uses: actions/cache@v3 - 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 - 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 }}" 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..3c1d309 --- /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.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 d83af9a..1413715 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,19 +1,61 @@ 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@v3 + uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: Fast tests + 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: - dotnet-version: 8.0.x + name: coverage-fast + path: coverage/ - - name: Test - run: dotnet test AsyncMonolith.Tests --verbosity normal \ No newline at end of file + 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@v4 + with: + global-json-file: global.json + + - name: Integration tests + 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/.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 d3d9d73..0000000 Binary files a/AsyncMonolith.Ef/.DS_Store and /dev/null differ diff --git a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj b/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj deleted file mode 100644 index 89f2a1c..0000000 --- a/AsyncMonolith.Ef/AsyncMonolith.Ef.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - net10.0 - enable - enable - true - preview - true - AsyncMonolith.Ef - 10.0.1 - Tim Jones - Aptacode - Entity Framework interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async - AsyncMonolith.Ef - logo.png - True - true - - - - - True - \ - - - - - - - - - diff --git a/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs b/AsyncMonolith.Ef/EfConsumerMessageFetcher.cs deleted file mode 100644 index 0f29fd3..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. -/// -public sealed class EfConsumerMessageFetcher : IConsumerMessageFetcher -{ - private readonly IOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// The options for AsyncMonolithSettings. - 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) - .Take(_options.Value.ProcessorBatchSize) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.Ef/EfProducerService.cs b/AsyncMonolith.Ef/EfProducerService.cs deleted file mode 100644 index 4cb5da6..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 = typeof(TK).Name; - 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 = typeof(TK).Name; - 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/EfScheduledMessageFetcher.cs b/AsyncMonolith.Ef/EfScheduledMessageFetcher.cs deleted file mode 100644 index 43b46c5..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. -/// -public 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 set, long currentTime, - CancellationToken cancellationToken = default) - { - return set.Where(m => m.AvailableAfter <= currentTime) - .OrderBy(m => m.AvailableAfter) - .Take(_options.Value.ProcessorBatchSize) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.Ef/StartupExtensions.cs b/AsyncMonolith.Ef/StartupExtensions.cs deleted file mode 100644 index 2a3d7b8..0000000 --- a/AsyncMonolith.Ef/StartupExtensions.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Reflection; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace AsyncMonolith.Ef; - -/// -/// Extension methods for configuring EF AsyncMonolith in the IServiceCollection. -/// -public static class StartupExtensions -{ - /// - /// Adds EF AsyncMonolith 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. - /// Thrown when the ConsumerMessageProcessorCount or ScheduledMessageProcessorCount is greater than 1. - public static IServiceCollection 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 - { - configuration(settings); - - services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); - return services; - } -} diff --git a/AsyncMonolith.MariaDb/.DS_Store b/AsyncMonolith.MariaDb/.DS_Store deleted file mode 100644 index 5560b45..0000000 Binary files a/AsyncMonolith.MariaDb/.DS_Store and /dev/null differ diff --git a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj b/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj deleted file mode 100644 index dfbde4e..0000000 --- a/AsyncMonolith.MariaDb/AsyncMonolith.MariaDb.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - net10.0 - enable - enable - NU5104 - true - preview - true - AsyncMonolith.MariaDb - 10.0.1 - Tim Jones - Aptacode - MariaDb interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async - AsyncMonolith.MariaDb - logo.png - True - true - - - - - True - \ - - - - - - - - diff --git a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs deleted file mode 100644 index d89dc95..0000000 --- a/AsyncMonolith.MariaDb/MariaDbConsumerMessageFetcher.cs +++ /dev/null @@ -1,50 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using MySqlConnector; - -namespace AsyncMonolith.MariaDb; - -/// -/// Represents a message fetcher for consumer messages in MariaDb. -/// -public sealed class MariaDbConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string MariaDb = @" - SELECT * - FROM consumer_messages - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at - LIMIT @batchSize - 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, new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@railId", railId), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MariaDb/MariaDbProducerService.cs b/AsyncMonolith.MariaDb/MariaDbProducerService.cs deleted file mode 100644 index a241a21..0000000 --- a/AsyncMonolith.MariaDb/MariaDbProducerService.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System.Diagnostics; -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 = typeof(TK).Name; - 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( - $@"(@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 = typeof(TK).Name; - 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( - $@"(@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/MariaDbScheduledMessageFetcher.cs b/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs deleted file mode 100644 index df8de3d..0000000 --- a/AsyncMonolith.MariaDb/MariaDbScheduledMessageFetcher.cs +++ /dev/null @@ -1,47 +0,0 @@ -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using MySqlConnector; - -namespace AsyncMonolith.MariaDb; - -/// -/// Fetches scheduled messages from MariaDb. -/// -public sealed class MariaDbScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string MariaDb = @" - SELECT * - FROM scheduled_messages - WHERE available_after <= @currentTime - LIMIT @batchSize - 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 set, long currentTime, - CancellationToken cancellationToken = default) - { - return set - .FromSqlRaw(MariaDb, new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MariaDb/StartupExtensions.cs b/AsyncMonolith.MariaDb/StartupExtensions.cs deleted file mode 100644 index 583720b..0000000 --- a/AsyncMonolith.MariaDb/StartupExtensions.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Reflection; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace AsyncMonolith.MariaDb; -/// -/// AsyncMonolith MariaDb startup extensions -/// -public static class StartupExtensions -{ - /// - /// Adds MariaDb implementation of AsyncMonolith 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 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 - { - configuration(settings); - - services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); - return services; - } -} diff --git a/AsyncMonolith.MsSql/.DS_Store b/AsyncMonolith.MsSql/.DS_Store deleted file mode 100644 index 761582a..0000000 Binary files a/AsyncMonolith.MsSql/.DS_Store and /dev/null differ diff --git a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj b/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj deleted file mode 100644 index 3faaf9e..0000000 --- a/AsyncMonolith.MsSql/AsyncMonolith.MsSql.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - net10.0 - enable - enable - true - preview - true - AsyncMonolith.MsSql - 10.0.1 - Tim Jones - Aptacode - MsSql interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async - AsyncMonolith.MsSql - logo.png - True - true - - - - - True - \ - - - - - - - - \ No newline at end of file diff --git a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs deleted file mode 100644 index ae4cec9..0000000 --- a/AsyncMonolith.MsSql/MsSqlConsumerMessageFetcher.cs +++ /dev/null @@ -1,48 +0,0 @@ -using AsyncMonolith.Consumers; -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. -/// -public sealed class MsSqlConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string MsSql = @" - SELECT TOP (@batchSize) * - FROM consumer_messages WITH (ROWLOCK, READPAST) - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at"; - - 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, new SqlParameter("@currentTime", currentTime), - new SqlParameter("@railId", railId), - new SqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MsSql/MsSqlProducerService.cs b/AsyncMonolith.MsSql/MsSqlProducerService.cs deleted file mode 100644 index 76c7b2b..0000000 --- a/AsyncMonolith.MsSql/MsSqlProducerService.cs +++ /dev/null @@ -1,196 +0,0 @@ -using System.Diagnostics; -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 = typeof(TK).Name; - 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( - $@"(@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 = typeof(TK).Name; - 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( - $@"(@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/MsSqlScheduledMessageFetcher.cs b/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs deleted file mode 100644 index da06794..0000000 --- a/AsyncMonolith.MsSql/MsSqlScheduledMessageFetcher.cs +++ /dev/null @@ -1,45 +0,0 @@ -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. -/// -public sealed class MsSqlScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string MsSql = @" - SELECT TOP (@batchSize) * - FROM scheduled_messages WITH (ROWLOCK, READPAST) - WHERE available_after <= @currentTime"; - - 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 set, long currentTime, - CancellationToken cancellationToken = default) - { - return set - .FromSqlRaw(MsSql, new SqlParameter("@currentTime", currentTime), - new SqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MsSql/StartupExtensions.cs b/AsyncMonolith.MsSql/StartupExtensions.cs deleted file mode 100644 index 9222fbc..0000000 --- a/AsyncMonolith.MsSql/StartupExtensions.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Reflection; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace AsyncMonolith.MsSql; - -/// -/// AsyncMonolith MsSql startup extensions -/// -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. - /// - /// 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( - this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext - { - configuration(settings); - services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); - return services; - } -} diff --git a/AsyncMonolith.MySql/.DS_Store b/AsyncMonolith.MySql/.DS_Store deleted file mode 100644 index 6bd9106..0000000 Binary files a/AsyncMonolith.MySql/.DS_Store and /dev/null differ diff --git a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj b/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj deleted file mode 100644 index 5f234e8..0000000 --- a/AsyncMonolith.MySql/AsyncMonolith.MySql.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - net10.0 - enable - enable - NU5104 - true - preview - true - AsyncMonolith.MySql - 10.0.1 - Tim Jones - Aptacode - MySql interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async - AsyncMonolith.MySql - logo.png - True - true - - - - - True - \ - - - - - - - - diff --git a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs b/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs deleted file mode 100644 index fbff493..0000000 --- a/AsyncMonolith.MySql/MySqlConsumerMessageFetcher.cs +++ /dev/null @@ -1,50 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using MySqlConnector; - -namespace AsyncMonolith.MySql; - -/// -/// Represents a message fetcher for consumer messages in MySQL. -/// -public sealed class MySqlConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string MySql = @" - SELECT * - FROM consumer_messages - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at - LIMIT @batchSize - 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, new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@railId", railId), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MySql/MySqlProducerService.cs b/AsyncMonolith.MySql/MySqlProducerService.cs deleted file mode 100644 index aa92fa3..0000000 --- a/AsyncMonolith.MySql/MySqlProducerService.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System.Diagnostics; -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 = typeof(TK).Name; - 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( - $@"(@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 = typeof(TK).Name; - 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( - $@"(@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/MySqlScheduledMessageFetcher.cs b/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs deleted file mode 100644 index 7b1969f..0000000 --- a/AsyncMonolith.MySql/MySqlScheduledMessageFetcher.cs +++ /dev/null @@ -1,47 +0,0 @@ -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using MySqlConnector; - -namespace AsyncMonolith.MySql; - -/// -/// Fetches scheduled messages from MySQL database. -/// -public sealed class MySqlScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string MySql = @" - SELECT * - FROM scheduled_messages - WHERE available_after <= @currentTime - LIMIT @batchSize - 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 set, long currentTime, - CancellationToken cancellationToken = default) - { - return set - .FromSqlRaw(MySql, new MySqlParameter("@currentTime", currentTime), - new MySqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.MySql/StartupExtensions.cs b/AsyncMonolith.MySql/StartupExtensions.cs deleted file mode 100644 index 1c66986..0000000 --- a/AsyncMonolith.MySql/StartupExtensions.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Reflection; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace AsyncMonolith.MySql; -/// -/// AsyncMonolith MySql startup extensions -/// -public static class StartupExtensions -{ - /// - /// Adds MySql implementation of AsyncMonolith 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 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( - this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext - { - configuration(settings); - services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); - return services; - } -} diff --git a/AsyncMonolith.PostgreSql/.DS_Store b/AsyncMonolith.PostgreSql/.DS_Store deleted file mode 100644 index fe5b3dc..0000000 Binary files a/AsyncMonolith.PostgreSql/.DS_Store and /dev/null differ diff --git a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj b/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj deleted file mode 100644 index 270cf7e..0000000 --- a/AsyncMonolith.PostgreSql/AsyncMonolith.PostgreSql.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - net10.0 - enable - enable - true - preview - true - AsyncMonolith.PostgreSql - 10.0.1 - Tim Jones - Aptacode - PostgreSql interface for AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - https://github.com/Timmoth/AsyncMonolith - git - Monolith Messaging Scheduling Async - AsyncMonolith.PostgreSql - logo.png - True - true - - - - - True - \ - - - - - - - - - diff --git a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs deleted file mode 100644 index 9ae42e7..0000000 --- a/AsyncMonolith.PostgreSql/PostgreSqlConsumerMessageFetcher.cs +++ /dev/null @@ -1,50 +0,0 @@ -using AsyncMonolith.Consumers; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using Npgsql; - -namespace AsyncMonolith.PostgreSql; - -/// -/// Represents a consumer message fetcher implementation for PostgreSQL. -/// -public sealed class PostgreSqlConsumerMessageFetcher : IConsumerMessageFetcher -{ - private const string PgSql = @" - SELECT * - FROM consumer_messages - WHERE available_after <= @currentTime AND rail_id = @railId - ORDER BY created_at - FOR UPDATE SKIP LOCKED - LIMIT @batchSize"; - - 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, new NpgsqlParameter("@currentTime", currentTime), - new NpgsqlParameter("@railId", railId), - new NpgsqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs b/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs deleted file mode 100644 index fdf5dd1..0000000 --- a/AsyncMonolith.PostgreSql/PostgreSqlProducerService.cs +++ /dev/null @@ -1,191 +0,0 @@ -using System.Diagnostics; -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 = typeof(TK).Name; - 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( - $@"(@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 = typeof(TK).Name; - 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( - $@"(@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/PostgreSqlScheduledMessageFetcher.cs b/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs deleted file mode 100644 index db4b077..0000000 --- a/AsyncMonolith.PostgreSql/PostgreSqlScheduledMessageFetcher.cs +++ /dev/null @@ -1,47 +0,0 @@ -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. -/// -public sealed class PostgreSqlScheduledMessageFetcher : IScheduledMessageFetcher -{ - private const string PgSql = @" - SELECT * - FROM scheduled_messages - WHERE available_after <= @currentTime - FOR UPDATE SKIP LOCKED - LIMIT @batchSize"; - - 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 set, long currentTime, - CancellationToken cancellationToken = default) - { - return set - .FromSqlRaw(PgSql, new NpgsqlParameter("@currentTime", currentTime), - new NpgsqlParameter("@batchSize", _options.Value.ProcessorBatchSize)) - .ToListAsync(cancellationToken); - } -} diff --git a/AsyncMonolith.PostgreSql/StartupExtensions.cs b/AsyncMonolith.PostgreSql/StartupExtensions.cs deleted file mode 100644 index 48dd2b8..0000000 --- a/AsyncMonolith.PostgreSql/StartupExtensions.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Reflection; -using AsyncMonolith.Consumers; -using AsyncMonolith.Producers; -using AsyncMonolith.Scheduling; -using AsyncMonolith.Utilities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace AsyncMonolith.PostgreSql; - -/// -/// AsyncMonolith PostgreSql startup extensions -/// -public static class StartupExtensions -{ - /// - /// Adds the PostgreSql implementation of the AsyncMonolith to the service collection. - /// - /// The type of the DbContext. - /// 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( - this IServiceCollection services, - Action configuration, - AsyncMonolithSettings settings) where T : DbContext - { - configuration(settings); - services.InternalAddAsyncMonolith(settings); - services.AddScoped>(); - services.AddSingleton(); - services.AddSingleton(); - return services; - } -} diff --git a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj index 1ce5a99..23a2b60 100644 --- a/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj +++ b/AsyncMonolith.TestHelpers/AsyncMonolith.TestHelpers.csproj @@ -1,54 +1,25 @@  - net10.0 - enable - enable - true - preview true + true AsyncMonolith.TestHelpers - 10.0.0 - 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 - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - - - - - - + + + + + + - - - True - \ - - - - true - AsyncMonolith.dll - + - - - - - diff --git a/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs b/AsyncMonolith.TestHelpers/ConsumerMessageTestHelpers.cs index b47f983..f5ae8a3 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(); } @@ -31,18 +32,20 @@ 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 : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + 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(); } @@ -50,20 +53,22 @@ 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 : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + 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(); } @@ -72,20 +77,22 @@ 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 : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + 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(); @@ -117,21 +125,23 @@ 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 : IConsumer where TPayload : IConsumerPayload { var consumerType = typeof(T); - var payloadType = typeof(V); + 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/ConsumerTestBase.cs b/AsyncMonolith.TestHelpers/ConsumerTestBase.cs index 943ec68..5a724e4 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 @@ -37,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); @@ -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,24 +79,25 @@ 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; } /// /// 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 : IConsumer 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/FakeProducerService.cs b/AsyncMonolith.TestHelpers/FakeProducerService.cs index e90c8ba..20f621d 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,13 +15,8 @@ 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. - public FakeProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, + /// Initializes a new instance of the class. + internal FakeProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, IAsyncMonolithIdGenerator idGenerator) { _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider)); @@ -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 = typeof(TK).Name; - - 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 = typeof(TK).Name; + 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 f0f40f5..6f9ba75 100644 --- a/AsyncMonolith.TestHelpers/FakeScheduleService.cs +++ b/AsyncMonolith.TestHelpers/FakeScheduleService.cs @@ -43,49 +43,59 @@ 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 = Cron.Parse(cronExpression); - 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 = typeof(TK).Name, + PayloadType = AsyncMonolithNames.ForPayload(), AvailableAfter = next.Value.ToUnixTimeSeconds(), Tag = tag, - ChronExpression = chronExpression, - ChronTimezone = chronTimezone, + CronExpression = cronExpression, + CronTimeZone = timeZone, Payload = payload }); return id; } + /// + /// Records the schedule, replacing any recorded schedule with the same tag. + /// + 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, cronExpression, timeZone, tag)); + } + /// /// Deletes scheduled messages by tag. /// diff --git a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs index 5bc8044..4d47bfe 100644 --- a/AsyncMonolith.TestHelpers/SetupTestHelpers.cs +++ b/AsyncMonolith.TestHelpers/SetupTestHelpers.cs @@ -1,4 +1,6 @@ -using System.Reflection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Diagnostics.Metrics; +using AsyncMonolith.Consumers; using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using AsyncMonolith.Utilities; @@ -13,83 +15,53 @@ 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(); + services.AddScoped(sp => new FakeProducerService(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService())); + services.AddScoped(sp => sp.GetRequiredService()); 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>(); + services.AddScoped>(); return services; } + + 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.TestHelpers/TestConsumerMessageProcessor.cs b/AsyncMonolith.TestHelpers/TestConsumerMessageProcessor.cs index 7aa84b6..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; @@ -36,16 +38,11 @@ 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); + var serializerOptions = scope.ServiceProvider.GetService>()?.Value.SerializerOptions; + await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), serializerOptions, + cancellationToken); consumerMessageSet.Remove(message); @@ -56,21 +53,21 @@ public static class TestConsumerMessageProcessor } /// - /// Processes the next consumer message of type T and V. + /// 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 V : 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) + .Where(m => m.ConsumerType == AsyncMonolithNames.ForConsumer(consumerType)) .OrderBy(m => m.AvailableAfter) .ThenBy(m => m.CreatedAt) .FirstOrDefaultAsync(cancellationToken); @@ -80,16 +77,11 @@ 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); + var serializerOptions = scope.ServiceProvider.GetService>()?.Value.SerializerOptions; + await ConsumerInvoker.Invoke(consumer, message, ConsumeContext.For(message, maxAttempts), serializerOptions, + cancellationToken); consumerMessageSet.Remove(message); @@ -100,40 +92,27 @@ 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 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, 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 : 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 = consumerType.Name, - CreatedAt = 0, - Id = string.Empty, - InsertId = string.Empty, - Payload = JsonSerializer.Serialize(payload), - PayloadType = typeof(V).Name, - 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/AsyncMonolith.Tests.csproj b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj index 6805ee3..38d16f9 100644 --- a/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj +++ b/AsyncMonolith.Tests/AsyncMonolith.Tests.csproj @@ -1,46 +1,33 @@  - net10.0 - enable - enable + $(NoWarn);CA1707 false true - preview + Exe - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + + + + + + + + + + + + + + - - - - - diff --git a/AsyncMonolith.Tests/ConfigurationTests.cs b/AsyncMonolith.Tests/ConfigurationTests.cs new file mode 100644 index 0000000..ae3bb86 --- /dev/null +++ b/AsyncMonolith.Tests/ConfigurationTests.cs @@ -0,0 +1,251 @@ +using System.Text.Json; +using AsyncMonolith.Consumers; +using AsyncMonolith.Producers; +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; +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 = new AsyncMonolithOptions(); + 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 = "{}", + DeduplicationKey = "insert", + TraceId = null, + SpanId = null + }; + + public static TheoryData> InvalidSettings => new() + { + { "negative attempt delay", s => s.AttemptDelay = TimeSpan.FromSeconds(-1) }, + { "zero max attempts", s => s.MaxAttempts = 0 }, + { "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) + { + 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.AddAsyncMonolith(s => s.BatchSize = 0); + using var host = builder.Build(); + + 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.AddAsyncMonolith(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 services = new ServiceCollection(); + + 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(TimeSpan.Zero); + configured.MaxAttempts.ShouldBe(1); + 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() + { + var services = new ServiceCollection(); + services.InternalConfigureAsyncMonolithOptions(_ => { }); + + Should.NotThrow(() => services.BuildServiceProvider().GetRequiredService>().Value); + } + + [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(ConsumerExecutionMode.Sequential); + registry.ResolveConsumerRailId(nameof(RailConsumer2)).ShouldBe(2); + } + + [Fact] + public void Consumers_without_attributes_use_the_defaults() + { + var registry = Registry(s => + { + s.DefaultConsumerTimeout = TimeSpan.FromSeconds(42); + s.MaxAttempts = 7; + }); + + registry.ResolveConsumerTimeout(nameof(ExceptionConsumer)).ShouldBe(42); + registry.ResolveConsumerMaxAttempts(MessageFor(nameof(ExceptionConsumer))).ShouldBe(7); + registry.ResolveConsumerExecutionMode(nameof(ExceptionConsumer)) + .ShouldBe(ConsumerExecutionMode.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 = TimeSpan.FromSeconds(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 = TimeSpan.FromSeconds(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(ConsumerExecutionMode.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 void AddEfAsyncMonolith_registers_the_services_and_background_processors() + { + var services = new ServiceCollection(); + services.AddDbContext(_ => { }); + + services.AddAsyncMonolith(s => + { + s.RegisterTypesFromAssemblyContaining(); + s.MaxAttempts = 9; + }); + + services.ShouldContain(d => d.ServiceType == typeof(IProducerService) && + d.ImplementationType == typeof(ProducerService)); + 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); + } +} diff --git a/AsyncMonolith.Tests/ConsumeContextTests.cs b/AsyncMonolith.Tests/ConsumeContextTests.cs new file mode 100644 index 0000000..03c412a --- /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 = TimeSpan.FromSeconds(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(), deduplicationKey: "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.DeduplicationKey).Distinct().ShouldHaveSingleItem(); + } + + [Fact] + public void A_consumer_class_handling_two_payloads_is_rejected_at_startup() + { + var settings = new AsyncMonolithOptions(); + 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/ConsumerMessageFetcherTests.cs b/AsyncMonolith.Tests/ConsumerMessageFetcherTests.cs index 6668e5e..c5a29e3 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] @@ -18,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 { @@ -33,15 +34,15 @@ 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, CancellationToken.None); // Then - dbMessages.Count.ShouldBe(settings.ProcessorBatchSize); + dbMessages.Count.ShouldBe(settings.BatchSize); } finally { @@ -58,14 +59,14 @@ 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(); 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 bb2f6fa..2aca04d 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] @@ -27,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 @@ -64,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); + }, TimeSpan.FromSeconds(100), cancellationToken: TestContext.Current.CancellationToken); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } var processor = serviceProvider.GetRequiredService>(); @@ -103,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 @@ -147,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 @@ -191,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 @@ -235,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 @@ -252,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); @@ -288,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 @@ -305,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); @@ -340,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 @@ -356,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/ConsumerProcessingTests.cs b/AsyncMonolith.Tests/ConsumerProcessingTests.cs new file mode 100644 index 0000000..7f9f4b6 --- /dev/null +++ b/AsyncMonolith.Tests/ConsumerProcessingTests.cs @@ -0,0 +1,378 @@ +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" }, TimeSpan.FromSeconds(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 = TimeSpan.FromSeconds(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 = TimeSpan.FromSeconds(0); + }); + await host.Produce(new ExceptionConsumerMessage { Name = "boom" }, deduplicationKey: "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.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); + + // 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 = TimeSpan.FromSeconds(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 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() + { + 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}" }); + } + + (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.BatchSize = 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 Messages_created_in_the_same_second_are_taken_in_id_order() + { + 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. + 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 }), + DeduplicationKey = id, + TraceId = null, + SpanId = null + }; + + [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); + } + + [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().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); + 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.Message.AvailableAfter + 100); + + await host.ConsumerProcessor.Complete(claimed, success: true, Ct); + + (await host.ConsumerMessages()).ShouldHaveSingleItem(); + } +} diff --git a/AsyncMonolith.Tests/ConsumerRegistryTests.cs b/AsyncMonolith.Tests/ConsumerRegistryTests.cs index 3f0f9a9..c2f74a7 100644 --- a/AsyncMonolith.Tests/ConsumerRegistryTests.cs +++ b/AsyncMonolith.Tests/ConsumerRegistryTests.cs @@ -8,10 +8,10 @@ namespace AsyncMonolith.Tests; public class ConsumerRegistryTests { - private ServiceProvider Setup() + 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(); @@ -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 @@ -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)); } @@ -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/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/EnsureScheduleAndStatisticsTests.cs b/AsyncMonolith.Tests/EnsureScheduleAndStatisticsTests.cs new file mode 100644 index 0000000..8639db0 --- /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.CronTimeZone.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" }, 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 = "{}", DeduplicationKey = "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/HostedProcessingTests.cs b/AsyncMonolith.Tests/HostedProcessingTests.cs new file mode 100644 index 0000000..eda8a49 --- /dev/null +++ b/AsyncMonolith.Tests/HostedProcessingTests.cs @@ -0,0 +1,194 @@ +using AsyncMonolith.Consumers; +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, bool registerAsModule = false) + { + 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.AddSingleton(); + builder.Services.AddAsyncMonolith(s => + { + if (!registerAsModule) + { + s.RegisterTypesFromAssemblyContaining(); + } + + s.IdlePollInterval = TimeSpan.FromMilliseconds(50); + s.BusyPollInterval = TimeSpan.FromMilliseconds(10); + configure?.Invoke(s); + }); + if (registerAsModule) + { + builder.Services.AddAsyncMonolithConsumersFromAssemblyContaining(); + } + + _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 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 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() + { + 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 = TimeSpan.FromSeconds(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/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs b/AsyncMonolith.Tests/Infra/BehaviourConsumers.cs new file mode 100644 index 0000000..f3cb35c --- /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) : IConsumer +{ + public Task Consume(OrderedMessage payload, ConsumeContext context, 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) : IConsumer +{ + public Task Consume(MixedOutcomeMessage payload, ConsumeContext context, CancellationToken cancellationToken) + { + invocations.Increment(nameof(MixedSuccessConsumer)); + return Task.CompletedTask; + } +} + +public class MixedFailureConsumer(TestConsumerInvocations invocations) : IConsumer +{ + public Task Consume(MixedOutcomeMessage payload, ConsumeContext context, 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 : IConsumer +{ + public Task Consume(InvalidAttributesMessage payload, ConsumeContext context, 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(ConsumerExecutionMode.Parallel)] +public class ParallelProbeConsumer(ConcurrencyProbe probe) : IConsumer +{ + public Task Consume(ParallelProbeMessage payload, ConsumeContext context, CancellationToken cancellationToken) => + probe.Enter(2, cancellationToken); +} + +public class SequentialProbeMessage : IConsumerPayload +{ +} + +[ConsumerExecutionMode(ConsumerExecutionMode.Sequential)] +public class SequentialProbeConsumer(ConcurrencyProbe probe) : IConsumer +{ + 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/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/DbTestsBase.cs b/AsyncMonolith.Tests/Infra/DbTestsBase.cs index 56b3c14..7921c00 100644 --- a/AsyncMonolith.Tests/Infra/DbTestsBase.cs +++ b/AsyncMonolith.Tests/Infra/DbTestsBase.cs @@ -9,10 +9,10 @@ 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) + 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; @@ -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 @@ -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/EfTestDbContainer.cs b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs index 9383d47..f21d699 100644 --- a/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/EfTestDbContainer.cs @@ -8,13 +8,14 @@ public class EfTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new PostgreSqlBuilder().Build(); + 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(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { options.UseNpgsql(ConnectionString, o => { }); } ); diff --git a/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs b/AsyncMonolith.Tests/Infra/ExceptionConsumer.cs index ff494ee..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,9 +11,9 @@ 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 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..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,9 +12,9 @@ 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 Exception(); + throw new InvalidOperationException(); } } \ No newline at end of file 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 76e8462..4ab64b5 100644 --- a/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MariaDbTestDbContainer.cs @@ -9,17 +9,18 @@ public class MariaDbTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new MariaDbBuilder().Build(); + 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(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { - options.UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString)); + options.UseMySQL(ConnectionString); } ); } diff --git a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs index 87c745b..484f8a5 100644 --- a/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MsSqlTestDbContainer.cs @@ -8,13 +8,14 @@ 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(); + // 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(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { options.UseSqlServer(ConnectionString); } ); 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/MySqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs index dc57958..a7ba9fe 100644 --- a/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/MySqlTestDbContainer.cs @@ -8,17 +8,18 @@ public class MySqlTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new MySqlBuilder().Build(); + 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(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { - options.UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString)); + options.UseMySQL(ConnectionString); } ); } diff --git a/AsyncMonolith.Tests/Infra/NamedConsumers.cs b/AsyncMonolith.Tests/Infra/NamedConsumers.cs new file mode 100644 index 0000000..b384ba8 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/NamedConsumers.cs @@ -0,0 +1,113 @@ +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) : IConsumer +{ + public Task Consume(NamedMessage payload, ConsumeContext context, 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 consumerBuilder = module.DefineType($"{namespaces[i]}.{consumerName ?? $"SendEmailConsumer{i}"}", + TypeAttributes.Public | TypeAttributes.Class, typeof(object)); + consumerBuilder.DefineDefaultConstructor(MethodAttributes.Public); + 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) + { + 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/Infra/PostgreSqlTestDbContainer.cs b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs index fdc47f8..2ce1319 100644 --- a/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs +++ b/AsyncMonolith.Tests/Infra/PostgreSqlTestDbContainer.cs @@ -8,13 +8,14 @@ public class PostgreSqlTestDbContainer : TestDbContainerBase { public override async Task InitializeContainerAsync() { - var container = new PostgreSqlBuilder().Build(); + 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(ServiceCollection services) + public override void AddDb(IServiceCollection services) { services.AddDbContext((sp, options) => { options.UseNpgsql(ConnectionString, o => { }); } ); 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/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/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 new file mode 100644 index 0000000..506a5a5 --- /dev/null +++ b/AsyncMonolith.Tests/Infra/SqliteTestHost.cs @@ -0,0 +1,158 @@ +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. +/// +/// +/// 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 string? _path; + + private SqliteTestHost(SqliteConnection? connection, string? path, ServiceProvider services, + FakeTimeProvider time, TestConsumerInvocations invocations) + { + _connection = connection; + _path = path; + Services = services; + Time = time; + Invocations = invocations; + } + + public ServiceProvider Services { get; } + public FakeTimeProvider Time { get; } + public TestConsumerInvocations Invocations { get; } + + public long Now => Time.GetUtcNow().ToUnixTimeSeconds(); + + internal ConsumerMessageProcessor ConsumerProcessor => + Services.GetRequiredService>(); + + internal ScheduledMessageProcessor ScheduledProcessor => + Services.GetRequiredService>(); + + public static async Task Create(Action? configure = null, + bool fileDatabase = false) + { + 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 = new AsyncMonolithOptions(); + configure?.Invoke(settings); + + var services = new ServiceCollection(); + 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>(); + 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, path, provider, time, invocations); + } + + /// Produces a message in its own scope and saves it. + 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, delay, deduplicationKey); + 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(); + 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/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/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs b/AsyncMonolith.Tests/Infra/TestDbContainerBase.cs index cbc09ed..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,22 +6,63 @@ namespace AsyncMonolith.Tests.Infra; public abstract class TestDbContainerBase : IAsyncLifetime { - protected IContainer DbContainer { get; set; } = default!; - protected string ConnectionString { get; set; } = default!; + protected IContainer? DbContainer { get; set; } + public string ConnectionString { get; protected set; } = default!; public DbType DbType => GetDbType(); - public async Task InitializeAsync() + public async ValueTask InitializeAsync() { await InitializeContainerAsync(); + await WaitUntilConnectable(); } - public async Task DisposeAsync() + /// + /// 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() { - await DbContainer.DisposeAsync().AsTask(); + 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() + { + if (DbContainer is not null) + { + await DbContainer.DisposeAsync(); + } + + GC.SuppressFinalize(this); } 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/Infra/TestServiceHelpers.cs b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs index 17f3494..a28c3e8 100644 --- a/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs +++ b/AsyncMonolith.Tests/Infra/TestServiceHelpers.cs @@ -1,10 +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; @@ -25,47 +23,38 @@ 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")); + 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.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; + o.SerializerOptions = settings.SerializerOptions; + o.PoisonedMessageRetention = settings.PoisonedMessageRetention; + }); settings.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly()); services.InternalRegisterAsyncMonolithConsumers(settings); services.AddSingleton(new FakeIdGenerator()); + 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; - } + services.AddScoped>(); + services.AddScoped>(); + // 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/Infra/TimeoutConsumer.cs b/AsyncMonolith.Tests/Infra/TimeoutConsumer.cs index fa0045f..9da4ab1 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,9 +12,25 @@ 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); } -} \ 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.Tests/Infra/WritingConsumer.cs b/AsyncMonolith.Tests/Infra/WritingConsumer.cs new file mode 100644 index 0000000..1b38bf0 --- /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 : IConsumer +{ + private readonly TestDbContext _dbContext; + private readonly IProducerService _producer; + + public WritingConsumer(TestDbContext dbContext, IProducerService producer) + { + _dbContext = dbContext; + _producer = producer; + } + + public async Task Consume(WritingConsumerMessage message, ConsumeContext context, CancellationToken cancellationToken) + { + await _producer.Produce(new SingleConsumerMessage { Name = message.Name }, + cancellationToken: cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + } +} diff --git a/AsyncMonolith.Tests/LoadTests.cs b/AsyncMonolith.Tests/LoadTests.cs new file mode 100644 index 0000000..2906013 --- /dev/null +++ b/AsyncMonolith.Tests/LoadTests.cs @@ -0,0 +1,105 @@ +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) + { + Action configure = o => + { + o.RegisterTypesFromAssemblyContaining(); + o.BatchSize = 20; + o.AttemptDelay = TimeSpan.Zero; + o.IdlePollInterval = TimeSpan.FromMilliseconds(50); + o.BusyPollInterval = TimeSpan.Zero; + }; + services.AddAsyncMonolith(configure); + } + + [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); + 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(); + } + } +} diff --git a/AsyncMonolith.Tests/MetricsTests.cs b/AsyncMonolith.Tests/MetricsTests.cs new file mode 100644 index 0000000..a928fac --- /dev/null +++ b/AsyncMonolith.Tests/MetricsTests.cs @@ -0,0 +1,125 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +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.AddAsyncMonolith(); + + using var provider = services.BuildServiceProvider(); + var meter = provider.GetRequiredService().Meter; + + meter.Name.ShouldBe(AsyncMonolithInstrumentation.MeterName); + meter.Scope.ShouldBe(provider.GetRequiredService()); + } +} diff --git a/AsyncMonolith.Tests/ModelMappingTests.cs b/AsyncMonolith.Tests/ModelMappingTests.cs new file mode 100644 index 0000000..c720ea9 --- /dev/null +++ b/AsyncMonolith.Tests/ModelMappingTests.cs @@ -0,0 +1,143 @@ +using AsyncMonolith.Utilities; +using AsyncMonolith.Consumers; +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.AddAsyncMonolith(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 => s.AddAsyncMonolith(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/ModuleRegistrationTests.cs b/AsyncMonolith.Tests/ModuleRegistrationTests.cs new file mode 100644 index 0000000..ef5db80 --- /dev/null +++ b/AsyncMonolith.Tests/ModuleRegistrationTests.cs @@ -0,0 +1,98 @@ +using AsyncMonolith.Consumers; +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.AddAsyncMonolith(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.AddAsyncMonolith(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.AddAsyncMonolith(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.AddAsyncMonolith(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.AddAsyncMonolith(_ => { }); + 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.AddAsyncMonolith(_ => { }); + + services.BuildServiceProvider().GetRequiredService().RailIds.ShouldBe([0]); + } +} diff --git a/AsyncMonolith.Tests/MultipleInstanceTests.cs b/AsyncMonolith.Tests/MultipleInstanceTests.cs new file mode 100644 index 0000000..15be858 --- /dev/null +++ b/AsyncMonolith.Tests/MultipleInstanceTests.cs @@ -0,0 +1,150 @@ +using AsyncMonolith.Utilities; +using AsyncMonolith.Consumers; +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.AddSingleton(); + builder.Services.AddAsyncMonolith(s => + { + s.RegisterTypesFromAssemblyContaining(); + s.IdlePollInterval = TimeSpan.FromMilliseconds(20); + s.BusyPollInterval = TimeSpan.FromMilliseconds(0); + s.BatchSize = 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.Tests/NamingTests.cs b/AsyncMonolith.Tests/NamingTests.cs new file mode 100644 index 0000000..472b377 --- /dev/null +++ b/AsyncMonolith.Tests/NamingTests.cs @@ -0,0 +1,112 @@ +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 = new AsyncMonolithOptions(); + settings.RegisterTypesFromAssemblies(assemblies); + 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] + 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.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.Tests/ProducerBehaviourTests.cs b/AsyncMonolith.Tests/ProducerBehaviourTests.cs new file mode 100644 index 0000000..8d53a5b --- /dev/null +++ b/AsyncMonolith.Tests/ProducerBehaviourTests.cs @@ -0,0 +1,257 @@ +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.DeduplicationKey).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" }, TimeSpan.FromSeconds(300), "my-insert-id"); + + var message = (await host.ConsumerMessages()).ShouldHaveSingleItem(); + message.AvailableAfter.ShouldBe(host.Now + 300); + 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] + 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_an_insert_id_that_is_already_pending_is_skipped() + { + await using var host = await SqliteTestHost.Create(); + await host.Produce(new SingleConsumerMessage { Name = "first" }, deduplicationKey: "dedupe-key"); + + await host.Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "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" }, deduplicationKey: "dedupe-key", cancellationToken: Ct); + await producer.Produce(new MultiConsumerMessage { Name = "second" }, deduplicationKey: "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" }, 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" }, deduplicationKey: "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" }, deduplicationKey: "dedupe-key"); + await host.ConsumerProcessor.ProcessBatch(Ct); + + await host.Produce(new SingleConsumerMessage { Name = "again" }, deduplicationKey: "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" }, deduplicationKey: "dedupe-key", cancellationToken: Ct); + await second.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "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() + { + 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.DeduplicationKey).ShouldAllBe(g => g.Count() == 2); + messages.Select(m => m.DeduplicationKey).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(); + } +} diff --git a/AsyncMonolith.Tests/ProducerServiceDbTests.cs b/AsyncMonolith.Tests/ProducerServiceDbTests.cs index 1f89e9f..a491a7a 100644 --- a/AsyncMonolith.Tests/ProducerServiceDbTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceDbTests.cs @@ -3,54 +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); - - // 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 { @@ -58,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); - - // Then - using var scope = serviceProvider.CreateScope(); - { - var postDbContext = serviceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(); - 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); - await dbContext.SaveChangesAsync(); - - // Then - using var postScope = serviceProvider.CreateScope(); - { - var postDbContext = postScope.ServiceProvider.GetRequiredService(); - var messages = await postDbContext.ConsumerMessages.ToListAsync(); - 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, TimeSpan.FromSeconds(10), cancellationToken: Ct)); + + using var scope = services.CreateScope(); + var message = await scope.ServiceProvider.GetRequiredService() + .AssertSingleConsumerMessage(payload); + message.AvailableAfter.ShouldBe(FakeTime.GetUtcNow().ToUnixTimeSeconds() + 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); - - // When - await producer.Produce(new SingleConsumerMessage - { - Name = "test-name-2" - }, delay, insertId); - - // 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" }], TimeSpan.FromSeconds(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.DeduplicationKey).Distinct().Count().ShouldBe(2); + messages.ShouldAllBe(m => m.AvailableAfter == FakeTime.GetUtcNow().ToUnixTimeSeconds() + 10); + }); - var delay = 10; - var insertId = "test-insert_id"; - var consumerMessage = new SingleConsumerMessage - { - Name = "test-name" - }; - await producer.Produce(consumerMessage, 10, insertId); + [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" }, deduplicationKey: "key", + cancellationToken: Ct)); + await Produce(services, p => p.Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "key", + cancellationToken: Ct)); - // When - await producer.Produce(new SingleConsumerMessage - { - Name = "test-name-2" - }, delay, insertId); + (await Messages(services)).ShouldHaveSingleItem().Payload.ShouldContain("first"); + }); - await Assert.ThrowsAsync(async () => { await dbContext.SaveChangesAsync(); }); - } - 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" }, deduplicationKey: "key", cancellationToken: Ct); + await second.ServiceProvider.GetRequiredService() + .Produce(new SingleConsumerMessage { Name = "second" }, deduplicationKey: "key", cancellationToken: Ct); + + await first.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct); + await Should.ThrowAsync(() => + second.ServiceProvider.GetRequiredService().SaveChangesAsync(Ct)); + }); +} diff --git a/AsyncMonolith.Tests/ProducerServiceTests.cs b/AsyncMonolith.Tests/ProducerServiceTests.cs index 36f525e..3841dfa 100644 --- a/AsyncMonolith.Tests/ProducerServiceTests.cs +++ b/AsyncMonolith.Tests/ProducerServiceTests.cs @@ -14,18 +14,18 @@ namespace AsyncMonolith.Tests; public class ProducerServiceTests { - public FakeTimeProvider FakeTime = default!; + private FakeTimeProvider FakeTime { get; set; } = default!; 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(); } - public Activity? GetActivity() + public static Activity? GetActivity() { var activitySource = new ActivitySource("AsyncMonolith.Tests"); var listener = new ActivityListener @@ -52,16 +52,16 @@ 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); - await dbContext.SaveChangesAsync(); + await producer.Produce(consumerMessage, delay, deduplicationKey, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -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,16 +91,16 @@ 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); - await dbContext.SaveChangesAsync(); + await producer.Produce(consumerMessage, delay, deduplicationKey, cancellationToken: TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -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()); } @@ -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(); @@ -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,8 +197,8 @@ public async Task Producer_Produces_Single_Scheduled_Message() Activity.Current = activity; // When - producer.Produce(scheduledMessage); - await dbContext.SaveChangesAsync(); + serviceProvider.GetRequiredService>().ProduceScheduled(scheduledMessage); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // Then using var scope = serviceProvider.CreateScope(); @@ -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,21 +244,21 @@ public async Task Producer_Produces_Multiple_Scheduled_Message() var dbContext = serviceProvider.GetRequiredService(); // When - producer.Produce(scheduledMessage); - await dbContext.SaveChangesAsync(); + serviceProvider.GetRequiredService>().ProduceScheduled(scheduledMessage); + 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 = 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/PublicApiTests.cs b/AsyncMonolith.Tests/PublicApiTests.cs new file mode 100644 index 0000000..0b90481 --- /dev/null +++ b/AsyncMonolith.Tests/PublicApiTests.cs @@ -0,0 +1,64 @@ +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.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" + ]); + } + + [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.Tests/RegistrationTests.cs b/AsyncMonolith.Tests/RegistrationTests.cs new file mode 100644 index 0000000..ba5e2b3 --- /dev/null +++ b/AsyncMonolith.Tests/RegistrationTests.cs @@ -0,0 +1,80 @@ +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.AddAsyncMonolith(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.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.Tests/RetryAndPoisonedMessageTests.cs b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs new file mode 100644 index 0000000..02525cb --- /dev/null +++ b/AsyncMonolith.Tests/RetryAndPoisonedMessageTests.cs @@ -0,0 +1,203 @@ +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, int expectedSeconds) + { + 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 options = new AsyncMonolithOptions + { AttemptDelay = TimeSpan.FromMinutes(10), MaxAttemptDelay = TimeSpan.FromMinutes(5) }; + + options.GetRetryDelay(1).ShouldBe(TimeSpan.FromMinutes(10)); + options.GetRetryDelay(3).ShouldBe(TimeSpan.FromMinutes(10)); + } + + [Fact] + public void Zero_attempt_delay_retries_immediately() + { + new AsyncMonolithOptions { AttemptDelay = TimeSpan.Zero }.GetRetryDelay(5).ShouldBe(TimeSpan.Zero); + } + + [Fact] + public async Task Failed_messages_back_off_between_retries() + { + await using var host = await SqliteTestHost.Create(s => + { + s.AttemptDelay = TimeSpan.FromSeconds(10); + s.MaxAttemptDelay = TimeSpan.FromSeconds(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.DeduplicationKey.ShouldBe(poisoned.DeduplicationKey); + 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.Tests/RobustnessTests.cs b/AsyncMonolith.Tests/RobustnessTests.cs new file mode 100644 index 0000000..1fceb9a --- /dev/null +++ b/AsyncMonolith.Tests/RobustnessTests.cs @@ -0,0 +1,179 @@ +using System.Diagnostics; +using AsyncMonolith.Consumers; +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.AddAsyncMonolith(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.AddAsyncMonolith().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/ScheduledMessageFetcherTests.cs b/AsyncMonolith.Tests/ScheduledMessageFetcherTests.cs index f616047..3db8644 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] @@ -17,19 +18,19 @@ 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 { AvailableAfter = FakeTime.GetUtcNow().ToUnixTimeSeconds(), - ChronExpression = "", - ChronTimezone = "", + CronExpression = "", + CronTimeZone = "", Id = idGenerator.GenerateId(), Payload = "", PayloadType = "", @@ -37,14 +38,14 @@ 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(), CancellationToken.None); // Then - dbMessages.Count.ShouldBe(settings.ProcessorBatchSize); + dbMessages.Count.ShouldBe(settings.BatchSize); } finally { diff --git a/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs b/AsyncMonolith.Tests/ScheduledMessageProcessorTests.cs index 656aff7..1e66415 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] @@ -33,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 @@ -47,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 = @@ -55,7 +56,7 @@ await postDbContext.AssertSingleConsumerMessageById(); - var count = await postDbContext.ScheduledMessages.CountAsync(); + var count = await postDbContext.ScheduledMessages.CountAsync(TestContext.Current.CancellationToken); count.ShouldBe(0); } } @@ -108,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); } } diff --git a/AsyncMonolith.Tests/SchedulingTests.cs b/AsyncMonolith.Tests/SchedulingTests.cs new file mode 100644 index 0000000..e5ba836 --- /dev/null +++ b/AsyncMonolith.Tests/SchedulingTests.cs @@ -0,0 +1,300 @@ +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, + CronExpression = cron, + CronTimeZone = 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 Five_field_cron_expressions_are_accepted_with_minute_precision() + { + 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] + 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.CronExpression.ShouldBe("0 30 10 * * *"); + message.CronTimeZone.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.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")); + } + + [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.DeduplicationKey).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.BatchSize = 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); + } + + 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.Tests/SchemaFileTests.cs b/AsyncMonolith.Tests/SchemaFileTests.cs new file mode 100644 index 0000000..1f924b5 --- /dev/null +++ b/AsyncMonolith.Tests/SchemaFileTests.cs @@ -0,0 +1,91 @@ +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"); + } + } + } + + [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.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.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.Tests/TestHelpersTests.cs b/AsyncMonolith.Tests/TestHelpersTests.cs new file mode 100644 index 0000000..490cb92 --- /dev/null +++ b/AsyncMonolith.Tests/TestHelpersTests.cs @@ -0,0 +1,141 @@ +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" }, deduplicationKey: "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.DeduplicationKey == "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(); + } + + [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.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/.DS_Store b/AsyncMonolith/.DS_Store deleted file mode 100644 index 11f4aa1..0000000 Binary files a/AsyncMonolith/.DS_Store and /dev/null differ diff --git a/AsyncMonolith/AsyncMonolith.csproj b/AsyncMonolith/AsyncMonolith.csproj index 8523f9c..34d3e16 100644 --- a/AsyncMonolith/AsyncMonolith.csproj +++ b/AsyncMonolith/AsyncMonolith.csproj @@ -1,45 +1,22 @@  - net10.0 - enable - enable - true - preview true + true AsyncMonolith - 10.0.0 - 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 - - - + + + + + - - - - - - - - True - \ - - \ No newline at end of file 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/Consumers/BaseConsumer.cs b/AsyncMonolith/Consumers/BaseConsumer.cs deleted file mode 100644 index e7eea4f..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 Exception( - $"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..c67288e --- /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.DeduplicationKey, + 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/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/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/ConsumerMessage.cs b/AsyncMonolith/Consumers/ConsumerMessage.cs index 22ecbb9..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 { /// @@ -73,7 +72,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. @@ -88,4 +87,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 04c6ea4..c63e872 100644 --- a/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs +++ b/AsyncMonolith/Consumers/ConsumerMessageProcessor.cs @@ -12,16 +12,17 @@ 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; private readonly ILogger> _logger; - private readonly IOptions _options; + private readonly IOptions _options; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; + private readonly AsyncMonolithMetrics _metrics; - private int _railId = 0; + private int _railId; /// /// Initializes a new instance of the class. /// @@ -31,12 +32,13 @@ public sealed class ConsumerMessageProcessor : BackgroundService where T : Db /// The options. /// The service scope factory. /// The consumer message fetcher. + /// The metrics. public ConsumerMessageProcessor(ILogger> logger, TimeProvider timeProvider, ConsumerRegistry consumerRegistry, - IOptions options, + 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; } /// @@ -62,132 +65,220 @@ 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.ProcessorMaxDelay; + var processed = 0; try { - var processedMessageCount = await ProcessBatch(stoppingToken); - if (processedMessageCount == _options.Value.ProcessorBatchSize) - { - delay = _options.Value.ProcessorMinDelay; - } + processed = await ProcessBatch(stoppingToken); + consecutiveFailures = 0; + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; } catch (Exception ex) { - _logger.LogError(ex, "Error processing consumer message batch."); + // Back off while batches keep failing (for example while the database is unavailable). + consecutiveFailures++; + _logger.ConsumerBatchFailed(ex); } - if (delay >= 10) + 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; + } } } } /// - /// 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; + + /// + /// 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. + /// + /// + /// 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>>(); - foreach (var consumerMessageGroup in messages.GroupBy(m => m.ConsumerType)) + var tasks = new List>>(); + foreach (var consumerMessageGroup in messages.GroupBy(m => m.Message.ConsumerType)) { - var group = consumerMessageGroup.ToList(); // materialize to avoid deferred execution + 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 => 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) + return []; + } + + // 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) + { + 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) { - 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, - }); - } + continue; } + + 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)); } - // Save changes to the message tables - await dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + return claimed; + } + + 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. + var outcome = await Complete(claimed, error is null, CancellationToken.None, error); + _metrics.RecordOutcome(claimed.Message.ConsumerType, outcome, duration); + 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(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() + .Where(m => m.Id == message.Id && m.AvailableAfter == message.AvailableAfter); + + if (success) + { + 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; + var updated = await leased.ExecuteUpdateAsync(s => s + .SetProperty(m => m.AvailableAfter, retryAt) + .SetProperty(m => m.LastError, error), cancellationToken); + return updated == 0 ? MessageOutcome.LeaseLost : MessageOutcome.Retrying; + } - // Commit transaction - await dbContextTransaction.CommitAsync(cancellationToken); + await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); + if (await leased.ExecuteDeleteAsync(cancellationToken) == 0) + { + return MessageOutcome.LeaseLost; + } - return processedMessageCount; + dbContext.Set().Add(new PoisonedMessage + { + Id = message.Id, + Attempts = message.Attempts, + AvailableAfter = claimed.DueAt, + ConsumerType = message.ConsumerType, + CreatedAt = message.CreatedAt, + Payload = message.Payload, + PayloadType = message.PayloadType, + DeduplicationKey = message.DeduplicationKey, + TraceId = message.TraceId, + SpanId = message.SpanId, + RailId = message.RailId, + LastError = error + }); + await dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + return MessageOutcome.Poisoned; } - private Activity? StartActivity(ConsumerMessage message) + private static Activity? StartActivity(ConsumerMessage message) { if (string.IsNullOrEmpty(message.TraceId) || string.IsNullOrEmpty(message.SpanId)) { @@ -212,49 +303,79 @@ internal async Task ProcessBatch(CancellationToken cancellationToken) /// /// 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); 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); + var consumerTimeout = _consumerRegistry.ResolveConsumerTimeout(message); try { 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(); - // Resolve the consumer - if (scope.ServiceProvider.GetRequiredService(consumerType) - is not IConsumer consumer) + var consumer = scope.ServiceProvider.GetRequiredService(consumerType); + var context = ConsumeContext.For(message, _consumerRegistry.ResolveConsumerMaxAttempts(message)); + var consuming = ConsumerInvoker.Invoke(consumer, message, context, _options.Value.SerializerOptions, + timeoutCancellationToken.Token); + try { - throw new Exception($"Couldn't resolve consumer service of type: '{message.ConsumerType}'"); + // 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."; } - - // Execute the consumer - await consumer.Consume(message, timeoutCancellationToken.Token); activity?.SetStatus(ActivityStatusCode.Ok); - _logger.LogInformation("Successfully processed message for consumer: '{id}'", message.ConsumerType); - return (message, true); + _logger.ConsumerMessageProcessed(message.ConsumerType); + 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) { 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.LogError(ex, "Failed to consume message on attempt {attempt}.", message.Attempts); + _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 +} + +/// +/// 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); 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 3c03840..5e1afc9 100644 --- a/AsyncMonolith/Consumers/ConsumerRegistry.cs +++ b/AsyncMonolith/Consumers/ConsumerRegistry.cs @@ -5,42 +5,42 @@ 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. /// - private readonly AsyncMonolithSettings _settings; + private readonly AsyncMonolithOptions _settings; /// /// 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. @@ -60,8 +60,8 @@ public ConsumerRegistry(IReadOnlyDictionary consumerTypeDictionary IReadOnlyDictionary consumerTimeoutDictionary, IReadOnlyDictionary consumerAttemptsDictionary, IReadOnlyDictionary consumerRailIdDictionary, - IReadOnlyDictionary consumerExecutionModeDictionary, - AsyncMonolithSettings settings) + IReadOnlyDictionary consumerExecutionModeDictionary, + AsyncMonolithOptions settings) { ConsumerTypeDictionary = consumerTypeDictionary; PayloadConsumerDictionary = payloadConsumerDictionary; @@ -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. /// @@ -82,7 +88,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 +104,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; @@ -117,7 +123,7 @@ public int ResolveConsumerTimeout(ConsumerMessage consumer) return timeout; } - return _settings.DefaultConsumerTimeout; + return (int)_settings.DefaultConsumerTimeout.TotalSeconds; } /// @@ -169,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); } /// @@ -187,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/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/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/PoisonedMessage.cs b/AsyncMonolith/Consumers/PoisonedMessage.cs index fa73f71..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 { /// @@ -73,7 +72,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. @@ -88,4 +87,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..6c2df44 --- /dev/null +++ b/AsyncMonolith/Consumers/PoisonedMessageService.cs @@ -0,0 +1,168 @@ +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); +} + +/// +/// 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 . +/// +/// The DbContext containing the AsyncMonolith tables. +internal 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) + .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); + } + + /// + 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, + DeduplicationKey = poisoned.DeduplicationKey, + TraceId = poisoned.TraceId, + SpanId = poisoned.SpanId, + LastError = poisoned.LastError + }); + } +} diff --git a/AsyncMonolith/Consumers/QueueStatistics.cs b/AsyncMonolith/Consumers/QueueStatistics.cs new file mode 100644 index 0000000..36389bd --- /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. +internal 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/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/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 new file mode 100644 index 0000000..3508f6b --- /dev/null +++ b/AsyncMonolith/Producers/ProducerService.cs @@ -0,0 +1,150 @@ +using System.Diagnostics; +using System.Text.Json; +using AsyncMonolith.Consumers; +using AsyncMonolith.Scheduling; +using AsyncMonolith.Utilities; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +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; + private readonly JsonSerializerOptions? _serializerOptions; + private readonly AsyncMonolithMetrics _metrics; + + public ProducerService(TimeProvider timeProvider, ConsumerRegistry consumerRegistry, T dbContext, + IAsyncMonolithIdGenerator idGenerator, IOptions options, AsyncMonolithMetrics metrics) + { + _metrics = metrics; + _serializerOptions = options.Value.SerializerOptions; + _timeProvider = timeProvider; + _consumerRegistry = consumerRegistry; + _dbContext = dbContext; + _idGenerator = idGenerator; + } + + public Task Produce(TPayload payload, TimeSpan? delay = null, string? deduplicationKey = null, + CancellationToken cancellationToken = default) + 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, _serializerOptions), 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 consumers = _consumerRegistry.ResolvePayloadConsumerTypes(payloadType); + + if (deduplicationKey is not null) + { + var pending = await PendingConsumers(deduplicationKey, consumers, cancellationToken); + consumers = consumers.Where(c => !pending.Contains(c)).ToList(); + } + + Add(payloadType, JsonSerializer.Serialize(payload, _serializerOptions), consumers, availableAfter, + deduplicationKey ?? _idGenerator.GenerateId(), Activity.Current); + } + + private long AvailableAfter(TimeSpan? delay) + { + if (delay < TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException(nameof(delay), delay, "The delay must not be negative."); + } + + return ToStoredTime(_timeProvider.GetUtcNow() + (delay ?? TimeSpan.Zero)); + } + + // 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) + { + var now = _timeProvider.GetUtcNow(); + return time <= now ? now.ToUnixTimeSeconds() : (time.ToUnixTimeMilliseconds() + 999) / 1000; + } + + private async Task> PendingConsumers(string deduplicationKey, IReadOnlyList consumers, + CancellationToken cancellationToken) + { + var set = _dbContext.Set(); + var pending = set.Local + .Where(m => m.DeduplicationKey == deduplicationKey && consumers.Contains(m.ConsumerType)) + .Select(m => m.ConsumerType) + .ToHashSet(); + + var saved = await set.AsNoTracking() + .Where(m => m.DeduplicationKey == deduplicationKey && 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 deduplicationKey, 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, + DeduplicationKey = deduplicationKey, + 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/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 7010e08..d5de22e 100644 --- a/AsyncMonolith/Scheduling/IScheduleService.cs +++ b/AsyncMonolith/Scheduling/IScheduleService.cs @@ -10,14 +10,30 @@ 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. + /// 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. - 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 + /// 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. + /// 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. + /// The id of the schedule. + 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/IScheduledMessageFetcher.cs b/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs index 3528b50..7dc5f3c 100644 --- a/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs +++ b/AsyncMonolith/Scheduling/IScheduledMessageFetcher.cs @@ -5,15 +5,15 @@ namespace AsyncMonolith.Scheduling; /// /// Interface for fetching scheduled messages. /// -public interface IScheduledMessageFetcher +internal 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/ScheduleService.cs b/AsyncMonolith/Scheduling/ScheduleService.cs index 0896707..cbefd4f 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; @@ -10,11 +11,12 @@ 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; private readonly TimeProvider _timeProvider; + private readonly IOptions _options; /// /// Initializes a new instance of the class. @@ -22,9 +24,12 @@ public 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; } @@ -32,47 +37,65 @@ 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 payload = JsonSerializer.Serialize(message, _options.Value.SerializerOptions); var id = _idGenerator.GenerateId(); - var expression = CronExpression.Parse(chronExpression, CronFormat.IncludeSeconds); + var expression = Cron.Parse(cronExpression); - var timezone = TimeZoneInfo.FindSystemTimeZoneById(chronTimezone); - if (timezone == null) - { - throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{chronTimezone}'"); - } - - 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}'"); - } + // Throws TimeZoneNotFoundException for an unknown time zone. + var timezone = TimeZoneInfo.FindSystemTimeZoneById(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 = typeof(TK).Name, - AvailableAfter = next.Value.ToUnixTimeSeconds(), + PayloadType = AsyncMonolithNames.ForPayload(), + AvailableAfter = next.ToUnixTimeSeconds(), Tag = tag, - ChronExpression = chronExpression, - ChronTimezone = chronTimezone, + CronExpression = cronExpression, + CronTimeZone = timeZone, Payload = payload }); return id; } + /// + public async Task EnsureSchedule(TPayload message, string cronExpression, string timeZone, + string tag, CancellationToken cancellationToken = default) where TPayload : 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, cronExpression, timeZone, tag); + } + + var schedule = existing[0]; + set.RemoveRange(existing.Skip(1)); + + schedule.UpdatePayload(message, _options.Value.SerializerOptions); + if (schedule.CronExpression != cronExpression || schedule.CronTimeZone != timeZone) + { + schedule.UpdateSchedule(cronExpression, timeZone, _timeProvider); + } + + return schedule.Id; + } + /// /// Deletes scheduled messages by tag. /// diff --git a/AsyncMonolith/Scheduling/ScheduledMessage.cs b/AsyncMonolith/Scheduling/ScheduledMessage.cs index 3bea36c..9aa20af 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 { /// @@ -40,14 +39,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. @@ -68,47 +67,41 @@ 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 = CronExpression.Parse(ChronExpression, CronFormat.IncludeSeconds); + var expression = Cron.Parse(CronExpression); - var timezone = TimeZoneInfo.FindSystemTimeZoneById(ChronTimezone); - if (timezone == null) - { - throw new InvalidOperationException($"Couldn't determine scheduled message timezone: '{ChronTimezone}'"); - } - - var next = expression.GetNextOccurrence(timeProvider.GetUtcNow(), timezone); - if (next == null) - { - throw new InvalidOperationException("Couldn't determine next scheduled message occurrence"); - } - - return next.Value.ToUnixTimeSeconds(); + // Throws TimeZoneNotFoundException for an unknown time zone. + var timezone = TimeZoneInfo.FindSystemTimeZoneById(CronTimeZone); + 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(); } /// /// 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) + internal 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 + /// 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 = typeof(TK).Name; + PayloadType = AsyncMonolithNames.ForPayload(); } } \ No newline at end of file diff --git a/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs b/AsyncMonolith/Scheduling/ScheduledMessageProcessor.cs index f264c07..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; @@ -13,13 +14,14 @@ 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; - private readonly IOptions _options; + 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 +31,17 @@ public sealed class ScheduledMessageProcessor : BackgroundService where T : D /// The options. /// The service scope factory. /// The scheduled message fetcher. + /// The metrics. public ScheduledMessageProcessor(ILogger> logger, - TimeProvider timeProvider, IOptions options, IServiceScopeFactory scopeFactory, - IScheduledMessageFetcher messageFetcher) + TimeProvider timeProvider, IOptions options, IServiceScopeFactory scopeFactory, + IScheduledMessageFetcher messageFetcher, AsyncMonolithMetrics metrics) { _logger = logger; _timeProvider = timeProvider; _options = options; _scopeFactory = scopeFactory; _messageFetcher = messageFetcher; + _metrics = metrics; } /// @@ -46,40 +50,82 @@ 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.ProcessorMaxDelay; + var processed = 0; try { - var processedScheduledMessages = await ProcessBatch(stoppingToken); - - if (processedScheduledMessages >= _options.Value.ProcessorBatchSize) - { - delay = _options.Value.ProcessorMinDelay; - } + processed = await ProcessBatch(stoppingToken); + await CleanUpIfDue(stoppingToken); + consecutiveFailures = 0; + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; } catch (Exception ex) { - _logger.LogError(ex, "Error scheduling next message"); + // Back off while batches keep failing (for example while the database is unavailable). + consecutiveFailures++; + _logger.ScheduleBatchFailed(ex); } - if (delay >= 10) + 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; + } } } } + /// 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; + /// - /// 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(); 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); @@ -102,15 +148,55 @@ internal async Task ProcessBatch(CancellationToken cancellationToken = defa foreach (var message in messages) { - producer.Produce(message); - message.AvailableAfter = message.GetNextOccurrence(_timeProvider); - processedScheduledMessageCount++; + // 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; + 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); + if (updated == 0) + { + continue; + } + + if (invalid is not null) + { + _logger.ScheduleInvalid(invalid, message.Id, message.Tag); + continue; + } + + try + { + producer.ProduceScheduled(message); + processedScheduledMessageCount++; + _metrics.SchedulesFired.Add(1, new KeyValuePair("payload_type", message.PayloadType)); + } + 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); await dbContextTransaction.CommitAsync(cancellationToken); activity?.SetStatus(ActivityStatusCode.Ok); - _logger.LogInformation("Successfully scheduled message"); + _logger.ScheduledMessagesProduced(); } catch (Exception) { 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 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..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. /// @@ -26,5 +32,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/AsyncMonolith/Utilities/AsyncMonolithLog.cs b/AsyncMonolith/Utilities/AsyncMonolithLog.cs new file mode 100644 index 0000000..92a14a8 --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithLog.cs @@ -0,0 +1,39 @@ +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); + + [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, + 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); +} 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/AsyncMonolithModel.cs b/AsyncMonolith/Utilities/AsyncMonolithModel.cs new file mode 100644 index 0000000..134078b --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithModel.cs @@ -0,0 +1,66 @@ +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(); + // 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/AsyncMonolith/Utilities/AsyncMonolithOptions.cs b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs new file mode 100644 index 0000000..db321a6 --- /dev/null +++ b/AsyncMonolith/Utilities/AsyncMonolithOptions.cs @@ -0,0 +1,202 @@ +using System.Reflection; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace AsyncMonolith.Utilities; + +/// +/// 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 +{ + 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); + + /// + /// 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 + /// 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. + /// + /// 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.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."); + } + + return errors.Count == 0 + ? ValidateOptionsResult.Success + : ValidateOptionsResult.Fail(errors.Select(e => $"AsyncMonolith: {e}")); + } +} + +/// +/// Returned by AddAsyncMonolith 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 13c639a..0000000 --- a/AsyncMonolith/Utilities/AsyncMonolithSettings.cs +++ /dev/null @@ -1,98 +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 between attempts for processing a failed message. - /// Default: 10 seconds, Min: 0 second, Max N/A - /// - public int AttemptDelay { get; set; } = 10; - - /// - /// 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 default AsyncMonolithSettings. - /// - public static AsyncMonolithSettings Default => new() - { - MaxAttempts = 5, - AttemptDelay = 10, - 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/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; + } +} diff --git a/AsyncMonolith/Utilities/StartupExtensions.cs b/AsyncMonolith/Utilities/StartupExtensions.cs index 0f4c1de..4e088f8 100644 --- a/AsyncMonolith/Utilities/StartupExtensions.cs +++ b/AsyncMonolith/Utilities/StartupExtensions.cs @@ -1,7 +1,14 @@ -using AsyncMonolith.Consumers; +using AsyncMonolith.Utilities; +using System.Diagnostics.Metrics; +using System.Reflection; +using AsyncMonolith.Consumers; +using AsyncMonolith.Database; +using AsyncMonolith.Producers; using AsyncMonolith.Scheduling; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; namespace AsyncMonolith.Utilities; @@ -11,142 +18,187 @@ 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.InsertId, e.ConsumerType }) - .IsUnique(); - + var options = new AsyncMonolithModelOptions(); + configure?.Invoke(options); + AsyncMonolithModel.Configure(modelBuilder, options); return modelBuilder; } - internal static void InternalConfigureAsyncMonolithSettings( - this IServiceCollection services, - AsyncMonolithSettings settings) + /// + /// 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 { - if (settings.AttemptDelay < 0) - { - throw new ArgumentException("AsyncMonolithSettings.AttemptDelay 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."); - } + var builder = services.InternalAddAsyncMonolith(configure ?? (_ => { })); + services.TryAddSingleton(); + services.TryAddSingleton(); + return builder; + } - if (settings.ProcessorBatchSize < 1) - { - throw new ArgumentException("AsyncMonolithSettings.ProcessorBatchSize must be at least 1."); - } + internal static void InternalConfigureAsyncMonolithOptions( + this IServiceCollection services, + Action configure) + { + services.AddOptions().Configure(configure).ValidateOnStart(); + services.TryAddEnumerable(ServiceDescriptor + .Singleton, AsyncMonolithOptionsValidator>()); + } - if (settings.DefaultConsumerTimeout < 1) + internal static AsyncMonolithBuilder InternalAddAsyncMonolith( + this IServiceCollection services, + Action configure) where T : DbContext + { + if (services.Any(d => d.ServiceType == typeof(AsyncMonolithRegistration))) { - throw new ArgumentException("AsyncMonolithSettings.DefaultConsumerTimeout must be at least 1."); + throw new InvalidOperationException( + "AsyncMonolith is already registered. Call AddAsyncMonolith once, in the host; modules register " + + "their consumers with AddAsyncMonolithConsumers."); } - if (settings.DefaultConsumerTimeout > 3600) - { - throw new ArgumentException("AsyncMonolithSettings.DefaultConsumerTimeout must be less then 3600."); - } + services.AddSingleton(); + 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); + services.TryAddSingleton(); + services.TryAddSingleton(sp => new AsyncMonolithMetrics(sp.GetService())); + services.TryAddScoped>(); + services.TryAddScoped>(); + services.TryAddScoped>(); + services.TryAddScoped>(); + services.TryAddScoped>(); + + // 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.Configure(options => - { - options.AttemptDelay = settings.AttemptDelay; - options.MaxAttempts = settings.MaxAttempts; - options.ProcessorMaxDelay = settings.ProcessorMaxDelay; - options.ProcessorMinDelay = settings.ProcessorMinDelay; - options.ProcessorBatchSize = settings.ProcessorBatchSize; - options.DefaultConsumerTimeout = settings.DefaultConsumerTimeout; - }); + services.AddHostedService>(); + return new AsyncMonolithBuilder(services); } - internal static void InternalAddAsyncMonolith( + internal static void InternalRegisterAsyncMonolithConsumers( this IServiceCollection services, - AsyncMonolithSettings settings) where T : DbContext + AsyncMonolithOptions settings) { - services.InternalConfigureAsyncMonolithSettings(settings); - var consumerRailIdDictionary = new Dictionary(); - services.InternalRegisterAsyncMonolithConsumers(settings, consumerRailIdDictionary); - services.AddSingleton(new AsyncMonolithIdGenerator()); - services.AddScoped>(); - services.AddScoped(sp => sp.GetRequiredService()); - - var consumerRails = consumerRailIdDictionary.Values.ToHashSet().ToArray(); - if (consumerRails.Length > 1) + 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 AddAsyncMonolith 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 { IsClass: true, IsAbstract: false, IsGenericTypeDefinition: false } && + ConsumerInvoker.PayloadTypeOf(t) is not null); + + internal static ConsumerRegistry BuildConsumerRegistry(IEnumerable assemblies, + AsyncMonolithOptions settings) { var consumerServiceDictionary = new Dictionary(); var payloadConsumerDictionary = new Dictionary>(); var consumerTimeoutDictionary = new Dictionary(); var consumerAttemptsDictionary = new Dictionary(); - var consumerExecutionModeDictionary = new Dictionary(); + 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)) - { - continue; - } + var consumerName = AsyncMonolithNames.ForConsumer(consumerType); - // Register each consumer service - services.AddScoped(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[consumerType.Name] = timeoutDuration; + consumerTimeoutDictionary[consumerName] = timeoutDuration; var maxAttempts = settings.MaxAttempts; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerAttemptsAttribute)); @@ -160,16 +212,16 @@ internal static void InternalRegisterAsyncMonolithConsumers( maxAttempts = settings.MaxAttempts; } - consumerAttemptsDictionary[consumerType.Name] = maxAttempts; + consumerAttemptsDictionary[consumerName] = maxAttempts; - var consumerExecutionMode = ConsumerInstanceExecutionMode.Parallel; + var consumerExecutionMode = ConsumerExecutionMode.Parallel; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerExecutionModeAttribute)); if (attribute is ConsumerExecutionModeAttribute executionModeAttribute) { consumerExecutionMode = executionModeAttribute.ExecutionMode; } - consumerExecutionModeDictionary[consumerType.Name] = consumerExecutionMode; + consumerExecutionModeDictionary[consumerName] = consumerExecutionMode; var consumerRailId = 0; attribute = Attribute.GetCustomAttribute(consumerType, typeof(ConsumerRailIdAttribute)); @@ -178,35 +230,56 @@ 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]; + var payloadType = ConsumerInvoker.PayloadTypeOf(consumerType)!; - if (!consumerServiceDictionary.TryAdd(consumerType.Name, consumerType)) + if (!consumerServiceDictionary.TryAdd(consumerName, consumerType)) { - throw new Exception($"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)) { - throw new Exception($"No consumers exist for payload: '{consumerPayload}'"); + throw new InvalidOperationException($"No consumers exist for payload: '{consumerPayload}'"); } } - 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; + + /// Marks that AddAsyncMonolith has been called. + private sealed class AsyncMonolithRegistration; + + 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/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..7a366c5 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,17 @@ + + + net10.0 + enable + enable + latest + + + 11.0.0 + + true + true + latest + Recommended + true + + 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/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..e4259de --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,46 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj b/Example/AsyncMonolith.Web/AsyncMonolith.Web.csproj index 2f2a3c0..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/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/Counter/TotalValueConsumer.cs b/Example/Example.Api/Counter/TotalValueConsumer.cs index 8e388db..ff0398f 100644 --- a/Example/Example.Api/Counter/TotalValueConsumer.cs +++ b/Example/Example.Api/Counter/TotalValueConsumer.cs @@ -3,8 +3,8 @@ namespace Example.Api.Counter; -[ConsumerExecutionMode(ConsumerInstanceExecutionMode.Parallel)] -public class TotalValueConsumer : BaseConsumer +[ConsumerExecutionMode(ConsumerExecutionMode.Parallel)] +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/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/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/Example.Api.csproj b/Example/Example.Api/Example.Api.csproj index 5a78f34..32ff087 100644 --- a/Example/Example.Api/Example.Api.csproj +++ b/Example/Example.Api/Example.Api.csproj @@ -1,31 +1,27 @@  - net10.0 - enable - enable c991b6df-a810-4f5d-aa76-760a5c9281e9 Example.Api true - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - + + + + + - + 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/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 5a9b593..f208518 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,63 +26,75 @@ 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") + b.Property("DeduplicationKey") .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"); - 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 => @@ -91,60 +102,72 @@ 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") + b.Property("DeduplicationKey") .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"); - b.ToTable("poisoned_messages"); + b.HasIndex("CreatedAt"); + + b.ToTable("poisoned_messages", (string)null); }); modelBuilder.Entity("AsyncMonolith.Scheduling.ScheduledMessage", b => @@ -152,45 +175,49 @@ 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") + b.Property("CronExpression") .IsRequired() .HasColumnType("text") .HasColumnName("chron_expression") - .HasAnnotation("Relational:JsonPropertyName", "chron_expression"); + .HasJsonPropertyName("chron_expression"); - b.Property("ChronTimezone") + b.Property("CronTimeZone") .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"); - 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/Example/Example.Api/Program.cs b/Example/Example.Api/Program.cs index 2292a9e..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; @@ -16,7 +15,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,18 +24,18 @@ public static void Main(string[] args) builder.Services.AddHealthChecks() .AddNpgSql(connectionString, name: "postgres", - tags: new[] { "ready" }); + tags: ["ready"]); builder.Services.AddSingleton(TimeProvider.System); - builder.Services.AddPostgreSqlAsyncMonolith(settings => + builder.Services.AddAsyncMonolith(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/Example/Example.Api/Spam/SpamController.cs b/Example/Example.Api/Spam/SpamController.cs index da9815b..40ef69c 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); + }, cancellationToken: cancellationToken); return Ok("Started."); } 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/Example/Example.AppHost/Example.AppHost.csproj b/Example/Example.AppHost/Example.AppHost.csproj index 83f563f..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 + + + + + + + + + + + diff --git a/PACKAGE.md b/PACKAGE.md new file mode 100644 index 0000000..d7d92db --- /dev/null +++ b/PACKAGE.md @@ -0,0 +1,42 @@ +# 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. + +## Databases + +One package works with any EF Core provider and picks its queries from the one you use: + +| Provider | Row locking | +|---|---| +| 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.AddAsyncMonolith(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/ diff --git a/README.md b/README.md index cce8d45..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. @@ -56,7 +52,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 @@ -69,16 +65,16 @@ 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; - public ValueSubmittedConsumer(ApplicationDbContext dbContext) + public DeleteUsersPosts(ApplicationDbContext dbContext) { _dbContext = dbContext; } - public override Task Consume(UserDeleted message, CancellationToken cancellationToken) + public async Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); diff --git a/Schemas/asyncmonolith_mariadb.sql b/Schemas/asyncmonolith_mariadb.sql index b6cd93f..efc469b 100644 --- a/Schemas/asyncmonolith_mariadb.sql +++ b/Schemas/asyncmonolith_mariadb.sql @@ -9,8 +9,10 @@ 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) ); @@ -23,8 +25,10 @@ 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) ); @@ -46,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 d5a9896..24bf3ae 100644 --- a/Schemas/asyncmonolith_mssql.sql +++ b/Schemas/asyncmonolith_mssql.sql @@ -9,8 +9,10 @@ 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) ); @@ -24,8 +26,10 @@ 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) ); @@ -48,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 b6cd93f..efc469b 100644 --- a/Schemas/asyncmonolith_mysql.sql +++ b/Schemas/asyncmonolith_mysql.sql @@ -9,8 +9,10 @@ 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) ); @@ -23,8 +25,10 @@ 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) ); @@ -46,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 eb0d577..c4d6f01 100644 --- a/Schemas/asyncmonolith_postgresql.sql +++ b/Schemas/asyncmonolith_postgresql.sql @@ -9,8 +9,10 @@ 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) ); @@ -24,8 +26,10 @@ 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) ); @@ -48,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/guides/changing-messages.md b/docs/guides/changing-messages.md index 508c4bf..b3446bf 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 : IConsumer { ... } +``` + +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. diff --git a/docs/guides/consuming-messages.md b/docs/guides/consuming-messages.md index 997888f..d6ec76e 100644 --- a/docs/guides/consuming-messages.md +++ b/docs/guides/consuming-messages.md @@ -1,17 +1,20 @@ - **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`. -- **Batching**: Consumer messages will be read from the `consumer_messages` table in batches defined by `ConsumerMessageBatchSize`. + - 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 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. -- **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. 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; @@ -20,7 +23,7 @@ public class DeleteUsersPosts : BaseConsumer _dbContext = dbContext; } - public override Task Consume(UserDeleted message, CancellationToken cancellationToken) + public async Task Consume(UserDeleted message, ConsumeContext context, CancellationToken cancellationToken) { ... await _dbContext.SaveChangesAsync(cancellationToken); @@ -28,8 +31,40 @@ 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(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. + ## 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` (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. +- **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 +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); +} +``` + +## 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/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. diff --git a/docs/guides/producing-messages.md b/docs/guides/producing-messages.md index 3e14afd..c20d7e6 100644 --- a/docs/guides/producing-messages.md +++ b/docs/guides/producing-messages.md @@ -35,12 +35,10 @@ 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. 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(); @@ -49,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); @@ -65,36 +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); ``` -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 (the key is stored in the `insert_id` column): - await _dbContext.SaveChangesAsync(cancellationToken); - await dbContextTransaction.CommitAsync(cancellationToken); - -``` +- **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. -- **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. +- **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**: 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/guides/scheduling-messages.md b/docs/guides/scheduling-messages.md index 1f00e3a..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` @@ -11,4 +11,18 @@ 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 +``` +## 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. + +```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. 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 39b876f..6668f5a 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 (`AsyncMonolithSettings.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 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. -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 `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. -- 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/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 dac7412..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 @@ -27,17 +18,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); + } } ``` @@ -47,36 +41,47 @@ 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(settings => + // 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 => { - 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)` - `RegisterTypesFromAssembly(Assembly assembly)` - `RegisterTypesFromAssemblies(params Assembly[] assemblies)` +### Modules + +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(); +// 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 @@ -91,7 +96,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; @@ -102,7 +107,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); @@ -134,7 +139,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 03ab1d1..142f497 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 | |---------|--------------------------------------------|--------------------| +| 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 | @@ -12,3 +13,48 @@ 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)*** + + +## 11.0.0 + +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. +- 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 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). +- 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 `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()`. +- `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`. +- `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`. +- `ConsumerRegistry` exposes properties instead of public fields. +- `TestConsumerMessageProcessor.ProcessNext` now finds the consumer's message. It previously always returned null. diff --git a/docs/tests.md b/docs/tests.md index 79ff149..62c6c4a 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -1,13 +1,29 @@ ## 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 --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 --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. ## AsyncMonolith.TestHelpers [![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 @@ -55,8 +71,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..540b144 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 +- **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]`. +- **No ordering guarantee.** See [Ordering](guides/consuming-messages.md#ordering). +- **Test your expected throughput** against your database before relying on it. 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" + } +}