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