Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CQRS.slnx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Solution>
<Folder Name="/Solution Items/">
<File Path=".adr-dir" />
<File Path=".editorconfig" />
<File Path=".gitattributes" />
<File Path=".gitignore" />
<File Path="CHANGELOG.md" />
<File Path="LICENSE" />
<File Path="README.md" />
</Folder>
<Folder Name="/Tests/">
<Project Path="tests/Logitar.CQRS.Tests/Logitar.CQRS.Tests.csproj" Id="2606ed5e-6139-4692-adc8-a4a37830dfba" />
</Folder>
<Project Path="lib/Logitar.CQRS/Logitar.CQRS.csproj" />
</Solution>
Empty file removed lib/.gitkeep
Empty file.
195 changes: 195 additions & 0 deletions lib/Logitar.CQRS/CommandBus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Logitar.CQRS;

/// <summary>
/// Represents an in-memory bus in which sent commands are executed synchronously.
/// </summary>
public class CommandBus : ICommandBus
{
/// <summary>
/// The name of the command handler method.
/// </summary>
protected const string HandlerName = nameof(ICommandHandler<,>.HandleAsync);

/// <summary>
/// Gets the logger.
/// </summary>
protected virtual ILogger<CommandBus>? Logger { get; }
/// <summary>
/// Gets the pseudo-random number generator.
/// </summary>
protected virtual Random Random { get; } = new();
/// <summary>
/// Gets the service provider.
/// </summary>
protected virtual IServiceProvider ServiceProvider { get; }
/// <summary>
/// Gets the retry settings.
/// </summary>
protected virtual RetrySettings Settings { get; }

/// <summary>
/// Initializes a new instance of the <see cref="CommandBus"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public CommandBus(IServiceProvider serviceProvider)
{
Logger = serviceProvider.GetService<ILogger<CommandBus>>();
ServiceProvider = serviceProvider;
Settings = serviceProvider.GetService<RetrySettings>() ?? new();
}

/// <summary>
/// Executes the specified command.
/// </summary>
/// <typeparam name="TResult">The type of the command result.</typeparam>
/// <param name="command">The command to execute.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The command result.</returns>
/// <exception cref="InvalidOperationException">The handler did not define the handle method, or it did not return a task.</exception>
public virtual async Task<TResult> ExecuteAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken)
{
Settings.Validate();

object handler = await GetHandlerAsync(command, cancellationToken);

Type handlerType = handler.GetType();
Type commandType = command.GetType();
Type[] parameterTypes = [commandType, typeof(CancellationToken)];
MethodInfo handle = handlerType.GetMethod(HandlerName, parameterTypes)
?? throw new InvalidOperationException($"The handler {handlerType} must define a '{HandlerName}' method.");

object[] parameters = [command, cancellationToken];
Exception? innerException;
int attempt = 0;
while (true)
{
attempt++;
try
{
object? result = handle.Invoke(handler, parameters);
if (result is not Task<TResult> task)
{
throw new InvalidOperationException($"The handler {handlerType} {HandlerName} method must return a {nameof(Task)}.");
}
return await task;
}
catch (Exception exception)
{
if (!ShouldRetry(command, exception))
{
throw;
}
innerException = exception;

int millisecondsDelay = CalculateMillisecondsDelay(command, exception, attempt);
if (millisecondsDelay < 0)
{
throw new InvalidOperationException($"The retry delay '{millisecondsDelay}' should be greater than or equal to 0ms.");
}

if (Settings.Algorithm == RetryAlgorithm.None
|| (Settings.MaximumRetries > 0 && attempt > Settings.MaximumRetries)
|| (Settings.MaximumDelay > 0 && millisecondsDelay > Settings.MaximumDelay))
{
break;
}

if (Logger is not null && Logger.IsEnabled(LogLevel.Warning))
{
Logger.LogWarning(exception, "Command '{Command}' execution failed at attempt {Attempt}, will retry in {Delay}ms.", commandType, attempt, millisecondsDelay);
}

if (millisecondsDelay > 0)
{
await Task.Delay(millisecondsDelay, cancellationToken);
}
}
}

throw new InvalidOperationException($"Command '{commandType}' execution failed after {attempt} attempts. See inner exception for more detail.", innerException);
}

/// <summary>
/// Finds the handler for the specified command.
/// </summary>
/// <typeparam name="TResult">The type of the command result.</typeparam>
/// <param name="command">The command.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The command handler.</returns>
/// <exception cref="InvalidOperationException">There is no handler or many handlers for the specified command.</exception>
protected virtual async Task<object> GetHandlerAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken)
{
Type commandType = command.GetType();
IEnumerable<object> handlers = ServiceProvider.GetServices(typeof(ICommandHandler<,>).MakeGenericType(commandType, typeof(TResult)))
.Where(handler => handler is not null)
.Select(handler => handler!);
int count = handlers.Count();
if (count != 1)
{
StringBuilder message = new StringBuilder("Exactly one handler was expected for command of type '").Append(commandType).Append("', but ");
if (count < 1)
{
message.Append("none was found.");
}
else
{
message.Append(count).Append(" were found.");
}
throw new InvalidOperationException(message.ToString());
}
return handlers.Single();
}

/// <summary>
/// Determines if the command execution should be retried or not.
/// </summary>
/// <typeparam name="TResult">The type of the command result.</typeparam>
/// <param name="command">The command to execute.</param>
/// <param name="exception">The exception.</param>
/// <returns>A value indicating whether or not the command execution should be retried.</returns>
protected virtual bool ShouldRetry<TResult>(ICommand<TResult> command, Exception exception)
{
return true;
}

/// <summary>
/// Calculates the delay, in milliseconds, to wait before retrying the execution of a command after a failure.
/// The delay is computed according to the retry algorithm and configuration defined in <see cref="RetrySettings"/>.
/// </summary>
/// <typeparam name="TResult">The type of the command result.</typeparam>
/// <param name="command">The command to execute.</param>
/// <param name="exception">The exception.</param>
/// <param name="attempt">The current retry attempt number, starting at 1.</param>
/// <returns>The number of milliseconds to wait before retrying. Returns <c>0</c> when retrying should occur immediately or when the configured delay or algorithm does not produce a positive value.</returns>
protected virtual int CalculateMillisecondsDelay<TResult>(ICommand<TResult> command, Exception exception, int attempt)
{
if (Settings.Delay > 0)
{
switch (Settings.Algorithm)
{
case RetryAlgorithm.Exponential:
if (Settings.ExponentialBase > 1)
{
return (int)Math.Pow(Settings.ExponentialBase, attempt - 1) * Settings.Delay;
}
break;
case RetryAlgorithm.Fixed:
return Settings.Delay;
case RetryAlgorithm.Linear:
return attempt * Settings.Delay;
case RetryAlgorithm.Random:
if (Settings.RandomVariation > 0 && Settings.RandomVariation < Settings.Delay)
{
int minimum = Settings.Delay - Settings.RandomVariation;
int maximum = Settings.Delay + Settings.RandomVariation;
return Random.Next(minimum, maximum + 1);
}
break;
}
}
return 0;
}
}
24 changes: 24 additions & 0 deletions lib/Logitar.CQRS/DependencyInjectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Logitar.CQRS;

/// <summary>
/// Provides extension methods for registering the Logitar CQRS pattern into a dependency injection container.
/// </summary>
public static class DependencyInjectionExtensions
{
/// <summary>
/// Registers the command and query buses, along with their supporting configuration such as <see cref="RetrySettings"/>, into the service collection.
/// This enables Logitar's CQRS handling throughout the application.
/// </summary>
/// <param name="services">The service collection.</param>
/// <returns>The service collection.</returns>
public static IServiceCollection AddLogitarCQRS(this IServiceCollection services)
{
return services
.AddSingleton(serviceProvider => RetrySettings.Initialize(serviceProvider.GetRequiredService<IConfiguration>()))
.AddTransient<ICommandBus, CommandBus>()
.AddTransient<IQueryBus, QueryBus>();
}
}
12 changes: 12 additions & 0 deletions lib/Logitar.CQRS/ICommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Logitar.CQRS;

/// <summary>
/// Represents a command without result.
/// </summary>
public interface ICommand : ICommand<Unit>;

/// <summary>
/// Represents a command returning a result.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
public interface ICommand<TResult>;
16 changes: 16 additions & 0 deletions lib/Logitar.CQRS/ICommandBus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Logitar.CQRS;

/// <summary>
/// Represents a bus in which commands are sent.
/// </summary>
public interface ICommandBus
{
/// <summary>
/// Executes the specified command.
/// </summary>
/// <typeparam name="TResult">The type of the command result.</typeparam>
/// <param name="command">The command to execute.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The command result.</returns>
Task<TResult> ExecuteAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken = default);
}
17 changes: 17 additions & 0 deletions lib/Logitar.CQRS/ICommandHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Logitar.CQRS;

/// <summary>
/// Represents a handler for a specific command.
/// </summary>
/// <typeparam name="TCommand">The type of the command.</typeparam>
/// <typeparam name="TResult">The type of the command result.</typeparam>
public interface ICommandHandler<TCommand, TResult> where TCommand : ICommand<TResult>
{
/// <summary>
/// Handles the specified command and returns its result.
/// </summary>
/// <param name="command">The command to handle.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The command result.</returns>
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken = default);
}
7 changes: 7 additions & 0 deletions lib/Logitar.CQRS/IQuery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Logitar.CQRS;

/// <summary>
/// Represents a query returning a result.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
public interface IQuery<TResult>;
16 changes: 16 additions & 0 deletions lib/Logitar.CQRS/IQueryBus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Logitar.CQRS;

/// <summary>
/// Represents a bus in which queries are sent.
/// </summary>
public interface IQueryBus
{
/// <summary>
/// Executes the specified query.
/// </summary>
/// <typeparam name="TResult">The type of the query result.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The query result.</returns>
Task<TResult> ExecuteAsync<TResult>(IQuery<TResult> query, CancellationToken cancellationToken = default);
}
17 changes: 17 additions & 0 deletions lib/Logitar.CQRS/IQueryHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Logitar.CQRS;

/// <summary>
/// Represents a handler for a specific query.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <typeparam name="TResult">The type of the query result.</typeparam>
public interface IQueryHandler<TQuery, TResult> where TQuery : IQuery<TResult>
{
/// <summary>
/// Handles the specified query and returns its result.
/// </summary>
/// <param name="query">The query to handle.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The query result.</returns>
Task<TResult> HandleAsync(TQuery query, CancellationToken cancellationToken = default);
}
21 changes: 21 additions & 0 deletions lib/Logitar.CQRS/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Logitar

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading