Skip to content

Commit

Permalink
Clean up and remove commented code (#353)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev authored Jun 21, 2024
1 parent 9f9313b commit c475ab2
Show file tree
Hide file tree
Showing 119 changed files with 438 additions and 697 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using static Bookings.Application.BookingCommands;
// ReSharper disable UnusedAutoPropertyAccessor.Global

namespace Bookings.HttpApi.Bookings;

Expand Down Expand Up @@ -38,7 +39,7 @@ protected override ActionResult AsActionResult(Result<BookingState> result)
};

static BadRequestObjectResult MapValidationExceptionAsValidationProblemDetails(ErrorResult<BookingState> error) {
if (error?.Exception is not ValidationException exception) {
if (error.Exception is not ValidationException exception) {
throw new ArgumentNullException(nameof(error), "Exception in result is not of the type `ValidationException`. Unable to map validation result.");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public abstract partial class CommandService<TAggregate, TState, TId>(
StreamNameMap? streamNameMap = null,
TypeMapper? typeMap = null
)
: ICommandService<TAggregate, TState, TId>//, ICommandService<TAggregate>
: ICommandService<TAggregate, TState, TId>
where TAggregate : Aggregate<TState>, new()
where TState : State<TState>, new()
where TId : Id {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,12 @@ public void CommandHandlerRegistered<T>() {
void CommandHandlerNotFound(string commandType) => WriteEvent(CommandHandlerNotFoundId, commandType);

[Event(ErrorHandlingCommandId, Message = "Error handling command: '{0}' {1}", Level = EventLevel.Error)]
void ErrorHandlingCommand(string commandType, string exception)
=> WriteEvent(ErrorHandlingCommandId, commandType, exception);
void ErrorHandlingCommand(string commandType, string exception) => WriteEvent(ErrorHandlingCommandId, commandType, exception);

[Event(CommandHandledId, Message = "Command handled: '{0}'", Level = EventLevel.Verbose)]
void CommandHandled(string commandType) => WriteEvent(CommandHandledId, commandType);

[Event(
CommandHandlerAlreadyRegisteredId,
Message = "Command handler already registered for {0}",
Level = EventLevel.Critical
)]
[Event(CommandHandlerAlreadyRegisteredId, Message = "Command handler already registered for {0}", Level = EventLevel.Critical)]
void CommandHandlerAlreadyRegistered(string type) => WriteEvent(CommandHandlerAlreadyRegisteredId, type);

[Event(CommandHandlerRegisteredId, Message = "Command handler registered for {0}", Level = EventLevel.Verbose)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,8 @@ CancellationToken cancellationToken
using var measure = Measure.Start(diagnosticSource, new CommandServiceMetricsContext(appServiceTypeName, cmdName));

try {
var result = await handleCommand(command, cancellationToken).NoContext();

activity?.SetActivityStatus(
result is ErrorResult<T> err
? ActivityStatus.Error(err.Exception)
: ActivityStatus.Ok()
);
var result = await handleCommand(command, cancellationToken).NoContext();
activity?.SetActivityStatus(result is ErrorResult<T> err ? ActivityStatus.Error(err.Exception) : ActivityStatus.Ok());

return result;
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ public CommandServiceMetrics() {

var duration = _meter.CreateHistogram<double>(CommandService, "ms", "Command execution duration, milliseconds");
var errorCount = _meter.CreateCounter<long>($"{CommandService}.errors", "errors", "Number of failed commands");
_listener = new MetricsListener<CommandServiceMetricsContext>(ListenerName, duration, errorCount, GetTags);
_listener = new(ListenerName, duration, errorCount, GetTags);

return;

TagList GetTags(CommandServiceMetricsContext ctx)
=> new(_customTags) {
new KeyValuePair<string, object?>(AppServiceTag, ctx.ServiceName),
new KeyValuePair<string, object?>(CommandTag, ctx.CommandName)
new(AppServiceTag, ctx.ServiceName),
new(CommandTag, ctx.CommandName)
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,50 +5,18 @@

namespace Eventuous.Diagnostics;

// public class TracedCommandService<T>(ICommandService<T> appService) : ICommandService<T> where T : Aggregate {
// public static ICommandService<T> Trace(ICommandService<T> appService)
// => new TracedCommandService<T>(appService);
//
// ICommandService<T> InnerService { get; } = appService;
//
// readonly string _appServiceTypeName = appService.GetType().Name;
// readonly DiagnosticSource _metricsSource = new DiagnosticListener(CommandServiceMetrics.ListenerName);
//
// static bool GetError(Result result, out Exception? exception) {
// if (result is ErrorResult err) {
// exception = err.Exception;
//
// return true;
// }
//
// exception = null;
//
// return false;
// }
//
// public Task<Result> Handle<TCommand>(TCommand command, CancellationToken cancellationToken)
// where TCommand : class
// => CommandServiceActivity.TryExecute(
// _appServiceTypeName,
// command,
// _metricsSource,
// InnerService.Handle,
// GetError,
// cancellationToken
// );
// }
public class TracedCommandService<TState> : ICommandService<TState> where TState : State<TState>, new() {
public static ICommandService<TState> Trace(ICommandService<TState> appService) => new TracedCommandService<TState>(appService);

public class TracedCommandService<T, TState, TId>(ICommandService<T, TState, TId> appService) : ICommandService<T, TState, TId>
where TState : State<TState>, new()
where TId : Id
where T : Aggregate<TState> {
public static ICommandService<T, TState, TId> Trace(ICommandService<T, TState, TId> appService)
=> new TracedCommandService<T, TState, TId>(appService);
ICommandService<TState> InnerService { get; }

ICommandService<T, TState, TId> InnerService { get; } = appService;
readonly string _appServiceTypeName;
readonly DiagnosticSource _metricsSource = new DiagnosticListener(CommandServiceMetrics.ListenerName);

readonly DiagnosticSource _metricsSource = new DiagnosticListener(CommandServiceMetrics.ListenerName);
readonly string _appServiceTypeName = appService.GetType().Name;
TracedCommandService(ICommandService<TState> appService) {
_appServiceTypeName = appService.GetType().Name;
InnerService = appService;
}

public Task<Result<TState>> Handle<TCommand>(TCommand command, CancellationToken cancellationToken)
where TCommand : class
Expand All @@ -63,4 +31,4 @@ public Task<Result<TState>> Handle<TCommand>(TCommand command, CancellationToken

delegate Task<Result<T>> HandleCommand<T, in TCommand>(TCommand command, CancellationToken cancellationToken)
where TCommand : class
where T : State<T>, new();
where T : State<T>, new();

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@ namespace Eventuous;
static class ExceptionMessages {
static readonly ResourceManager Resources = new("Eventuous.ExceptionMessages", Assembly.GetExecutingAssembly());

internal static string MissingCommandHandler(Type type)
=> string.Format(Resources.GetString("MissingCommandHandler")!, type.Name);
internal static string MissingCommandHandler(Type type) => string.Format(Resources.GetString("MissingCommandHandler")!, type.Name);

internal static string DuplicateTypeKey<T>()
=> string.Format(Resources.GetString("DuplicateTypeKey")!, typeof(T).Name);
internal static string DuplicateTypeKey<T>() => string.Format(Resources.GetString("DuplicateTypeKey")!, typeof(T).Name);

internal static string DuplicateCommandHandler<T>()
=> string.Format(Resources.GetString("DuplicateCommandHandler")!, typeof(T).Name);
internal static string DuplicateCommandHandler<T>() => string.Format(Resources.GetString("DuplicateCommandHandler")!, typeof(T).Name);

internal static string MissingCommandMap<TIn, TOut>()
=> string.Format(Resources.GetString("MissingCommandMap")!, typeof(TIn).Name, typeof(TOut).Name);
internal static string MissingCommandMap<TIn, TOut>() => string.Format(Resources.GetString("MissingCommandMap")!, typeof(TIn).Name, typeof(TOut).Name);
}
2 changes: 0 additions & 2 deletions src/Core/src/Eventuous.Application/Exceptions/Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ namespace Eventuous;
public static class Exceptions {
public class CommandHandlerNotFound(Type type) : Exception(MissingCommandHandler(type));

public class UnableToResolveAggregateId(Type type) : Exception($"Unable to resolve aggregate id from command {type.Name}");

public class CommandHandlerNotFound<T>() : CommandHandlerNotFound(typeof(T));

public class CommandHandlerAlreadyRegistered<T>() : Exception(DuplicateCommandHandler<T>());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

namespace Eventuous;

public abstract class FuncCommandHandlerBuilder<TState> where TState : State<TState> {
internal abstract RegisteredFuncHandler<TState> Build();
public abstract class CommandHandlerBuilder<TState> where TState : State<TState> {
internal abstract RegisteredHandler<TState> Build();
}

public class FuncCommandHandlerBuilder<TCommand, TState>(IEventReader? reader, IEventWriter? writer) : FuncCommandHandlerBuilder<TState>
public class CommandHandlerBuilder<TCommand, TState>(IEventReader? reader, IEventWriter? writer) : CommandHandlerBuilder<TState>
where TState : State<TState> where TCommand : class {
ExpectedState _expectedState = ExpectedState.Any;
GetStreamNameFromUntypedCommand? _getStream;
Expand All @@ -22,7 +22,7 @@ public class FuncCommandHandlerBuilder<TCommand, TState>(IEventReader? reader, I
/// </summary>
/// <param name="expectedState">Expected stream state</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> InState(ExpectedState expectedState) {
public CommandHandlerBuilder<TCommand, TState> InState(ExpectedState expectedState) {
_expectedState = expectedState;

return this;
Expand All @@ -33,7 +33,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> InState(ExpectedState expecte
/// </summary>
/// <param name="getStream">A function to get the stream name from the command</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> GetStream(GetStreamNameFromCommand<TCommand> getStream) {
public CommandHandlerBuilder<TCommand, TState> GetStream(GetStreamNameFromCommand<TCommand> getStream) {
_getStream = getStream.AsGetStream();

return this;
Expand All @@ -44,7 +44,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> GetStream(GetStreamNameFromCo
/// </summary>
/// <param name="getStream">A function to get the stream name from the command</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> GetStreamAsync(GetStreamNameFromCommandAsync<TCommand> getStream) {
public CommandHandlerBuilder<TCommand, TState> GetStreamAsync(GetStreamNameFromCommandAsync<TCommand> getStream) {
_getStream = getStream.AsGetStream();

return this;
Expand All @@ -55,7 +55,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> GetStreamAsync(GetStreamNameF
/// </summary>
/// <param name="executeCommand">Function to be executed on the stream for the command</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> Act(ExecuteCommand<TState, TCommand> executeCommand) {
public CommandHandlerBuilder<TCommand, TState> Act(ExecuteCommand<TState, TCommand> executeCommand) {
_execute = executeCommand.AsExecute();

return this;
Expand All @@ -67,7 +67,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> Act(ExecuteCommand<TState, TC
/// </summary>
/// <param name="executeCommand">Function to be executed on the stream for the command</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> ActAsync(ExecuteCommandAsync<TState, TCommand> executeCommand) {
public CommandHandlerBuilder<TCommand, TState> ActAsync(ExecuteCommandAsync<TState, TCommand> executeCommand) {
_execute = executeCommand.AsExecute();

return this;
Expand All @@ -78,7 +78,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> ActAsync(ExecuteCommandAsync<
/// </summary>
/// <param name="executeCommand">Function to be executed on a new stream for the command</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> Act(Func<TCommand, IEnumerable<object>> executeCommand) {
public CommandHandlerBuilder<TCommand, TState> Act(Func<TCommand, IEnumerable<object>> executeCommand) {
// This is not ideal as we can return more specific interface depending on expected state, but it would do for now.
if (_expectedState != ExpectedState.New) {
throw new InvalidOperationException("Action without state is only allowed for new streams");
Expand All @@ -94,7 +94,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> Act(Func<TCommand, IEnumerabl
/// </summary>
/// <param name="executeCommand">Function to be executed on a new stream for the command</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> ActAsync(Func<TCommand, Task<IEnumerable<object>>> executeCommand) {
public CommandHandlerBuilder<TCommand, TState> ActAsync(Func<TCommand, Task<IEnumerable<object>>> executeCommand) {
// This is not ideal as we can return more specific interface depending on expected state, but it would do for now.
if (_expectedState != ExpectedState.New) {
throw new InvalidOperationException("Action without state is only allowed for new streams");
Expand All @@ -111,7 +111,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> ActAsync(Func<TCommand, Task<
/// </summary>
/// <param name="resolveReader">Function to resolve the event reader</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> ResolveReader(ResolveReaderFromCommand<TCommand>? resolveReader) {
public CommandHandlerBuilder<TCommand, TState> ResolveReader(ResolveReaderFromCommand<TCommand>? resolveReader) {
_reader = resolveReader;

return this;
Expand All @@ -123,7 +123,7 @@ public FuncCommandHandlerBuilder<TCommand, TState> ResolveReader(ResolveReaderFr
/// </summary>
/// <param name="resolveWriter">Function to resolve the event writer</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> ResolveWriter(ResolveWriterFromCommand<TCommand>? resolveWriter) {
public CommandHandlerBuilder<TCommand, TState> ResolveWriter(ResolveWriterFromCommand<TCommand>? resolveWriter) {
_writer = resolveWriter;

return this;
Expand All @@ -135,15 +135,15 @@ public FuncCommandHandlerBuilder<TCommand, TState> ResolveWriter(ResolveWriterFr
/// </summary>
/// <param name="resolveStore">Function to resolve the event writer</param>
/// <returns></returns>
public FuncCommandHandlerBuilder<TCommand, TState> ResolveStore(ResolveEventStoreFromCommand<TCommand>? resolveStore) {
public CommandHandlerBuilder<TCommand, TState> ResolveStore(ResolveEventStoreFromCommand<TCommand>? resolveStore) {
_reader ??= resolveStore?.AsResolveReader();
_writer ??= resolveStore?.AsResolveWriter();

return this;
}

internal override RegisteredFuncHandler<TState> Build() {
return new RegisteredFuncHandler<TState>(
internal override RegisteredHandler<TState> Build() {
return new(
_expectedState,
Ensure.NotNull(_getStream, $"Function to get the stream id from {typeof(TCommand).Name} is not defined"),
Ensure.NotNull(_execute, $"Function to act on the stream for command {typeof(TCommand).Name} is not defined"),
Expand Down
Loading

0 comments on commit c475ab2

Please sign in to comment.