From 8ffc1f1836286dd94c7d8c55bdd249be490f64d4 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 18 Mar 2022 12:08:54 +0800 Subject: [PATCH 1/4] fix(EventBus): Fix EventBus Cannel relationship error problem --- .../Internal/Dispatch/DispatchRelationNetwork.cs | 2 +- ...rib.Dispatcher.Events.HandlerOrder.Tests.csproj | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.csproj diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs index af5f95b28..473aa4b73 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs @@ -51,7 +51,7 @@ public void Build() { if (CancelRelationNetwork.TryGetValue(relation.Key, out List? cancelRelations)) { - var cancelHandlers = cancelRelations.TakeWhile(handler => relationOption.IsCancelHandler(relationOption.Handler)).Reverse().ToList(); + var cancelHandlers = cancelRelations.TakeWhile(cancelHandler => relationOption.IsCancelHandler(cancelHandler)).Reverse().ToList(); relationOption.AddCancelHandler(cancelHandlers); } } diff --git a/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.csproj b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.csproj new file mode 100644 index 000000000..b6c588b8d --- /dev/null +++ b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + false + + + + + + + From f5a1ddb3f51970bba6f38d69aee5dfdef492720e Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 18 Mar 2022 12:12:43 +0800 Subject: [PATCH 2/4] test(EventBus): Added unit test for EventBus Cannel relationship error --- .../EventHandlers/Handler.cs | 48 +++++++++++++++++++ .../Events/CalculateEvent.cs | 10 ++++ .../_Imports.cs | 1 + 3 files changed, 59 insertions(+) create mode 100644 test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/EventHandlers/Handler.cs create mode 100644 test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Events/CalculateEvent.cs create mode 100644 test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/_Imports.cs diff --git a/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/EventHandlers/Handler.cs b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/EventHandlers/Handler.cs new file mode 100644 index 000000000..b934ae35d --- /dev/null +++ b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/EventHandlers/Handler.cs @@ -0,0 +1,48 @@ +using Masa.Contrib.Dispatcher.Events.Enums; + +namespace Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.EventHandlers; + +public class Handler +{ + [EventHandler(Order = 1)] + public void First(CalculateEvent @event) + { + @event.Result = @event.ParameterA + @event.ParameterB; + if (@event.Result % 2 == 0) + throw new Exception("result is even"); + } + + [EventHandler(Order = 2, IsCancel = true)] + public void SecondCancal(CalculateEvent @event) + { + @event.Result = @event.Result - 2; + } + + [EventHandler(Order = 2, FailureLevels = FailureLevels.Throw)] + public void Second(CalculateEvent @event) + { + @event.Result *= 3; + + if (@event.Result / 12 > 0) + throw new Exception("result must not be greater than 11"); + } + + [EventHandler(Order = 3, FailureLevels = FailureLevels.ThrowAndCancel)] + public void Third(CalculateEvent @event) + { + if (@event.Result == 9) + throw new Exception("result is not equal to 9"); + } + + [EventHandler(Order = 3, IsCancel = true)] + public void ThirdCancel(CalculateEvent @event) + { + @event.Result -= 5; + } + + [EventHandler(Order = 1, IsCancel = true)] + public void FirstCancal(CalculateEvent @event) + { + @event.Result -= 3; + } +} diff --git a/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Events/CalculateEvent.cs b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Events/CalculateEvent.cs new file mode 100644 index 000000000..0c76d2c30 --- /dev/null +++ b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/Events/CalculateEvent.cs @@ -0,0 +1,10 @@ +namespace Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events; + +public record CalculateEvent : Event +{ + public int ParameterA { get; set; } + + public int ParameterB { get; set; } + + public int Result { get; set; } +} diff --git a/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/_Imports.cs b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/_Imports.cs new file mode 100644 index 000000000..a216cadb7 --- /dev/null +++ b/test/Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests/_Imports.cs @@ -0,0 +1 @@ +global using Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events; From 851e2d6dd2904c0cdab7413a07f4e31287f7e75f Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 18 Mar 2022 12:14:44 +0800 Subject: [PATCH 3/4] chore(EventBus): Modify the parameter name, adjust the order check, modify the error content --- Masa.Contrib.sln | 33 ++-- .../EventHandlerAttribute.cs | 44 +++-- .../Internal/Dispatch/Dispatcher.cs | 55 +++--- .../Internal/Dispatch/DispatcherBase.cs | 38 ++--- .../Internal/Dispatch/SagaDispatcher.cs | 13 +- .../OrderStockConfirmedHandler.cs | 14 -- .../Events/OrderStockConfirmedEvent.cs | 6 - ...ts.OrderLessThanZeroByFeature.Tests.csproj | 14 -- .../_Imports.cs | 2 - .../EventHandlers/EditGoodsHandler.cs | 14 -- .../Events/EditGoodsEvent.cs | 10 -- ...vents.OrderLessThanZeroBySaga.Tests.csproj | 14 -- .../_Imports.cs | 3 - .../EventHandlers/UserEventHandler.cs | 27 --- .../Events/EditUserEvent.cs | 8 - .../FeaturesTest.cs | 156 +++++++++++++++--- ...asa.Contrib.Dispatcher.Events.Tests.csproj | 3 +- .../SagaTest.cs | 33 ---- .../_Imports.cs | 2 - 19 files changed, 223 insertions(+), 266 deletions(-) delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/EventHandlers/OrderStockConfirmedHandler.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Events/OrderStockConfirmedEvent.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.csproj delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/_Imports.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/EventHandlers/EditGoodsHandler.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Events/EditGoodsEvent.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.csproj delete mode 100644 test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/_Imports.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.Tests/EventHandlers/UserEventHandler.cs delete mode 100644 test/Masa.Contrib.Dispatcher.Events.Tests/Events/EditUserEvent.cs diff --git a/Masa.Contrib.sln b/Masa.Contrib.sln index 81178ac4d..09ba21992 100644 --- a/Masa.Contrib.sln +++ b/Masa.Contrib.sln @@ -54,10 +54,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.Eve EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.Events.OrderEqualBySaga.Tests", "test\Masa.Contrib.Dispatcher.Events.OrderEqualBySaga.Tests\Masa.Contrib.Dispatcher.Events.OrderEqualBySaga.Tests.csproj", "{7D083C64-FF32-43C4-A82C-32C4A4EC1414}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests", "test\Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests\Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.csproj", "{DE2E92D3-929F-40E7-B8D0-502A57170A3E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests", "test\Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests\Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.csproj", "{0B139C21-8AFD-41CD-82FE-36E64FDEDE50}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.Events.Tests", "test\Masa.Contrib.Dispatcher.Events.Tests\Masa.Contrib.Dispatcher.Events.Tests.csproj", "{3870E8F1-B269-425D-8B03-58835FD53610}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF", "src\Dispatcher\Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF\Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.csproj", "{519A99D2-8094-48EC-A888-C0B4E017A4C1}" @@ -134,6 +130,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.SearchE EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Service.MinimalAPIs", "src\BuildingBlocks\MASA.BuildingBlocks\src\Service\Masa.BuildingBlocks.Service.MinimalAPIs\Masa.BuildingBlocks.Service.MinimalAPIs.csproj", "{E72E105D-B15F-4D69-9A13-CAA49D4889D6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests", "test\Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests\Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.csproj", "{4A052E17-4D9E-41EF-89A5-73B917053F8E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -206,22 +204,6 @@ Global {7D083C64-FF32-43C4-A82C-32C4A4EC1414}.Release|Any CPU.Build.0 = Release|Any CPU {7D083C64-FF32-43C4-A82C-32C4A4EC1414}.Release|x64.ActiveCfg = Release|Any CPU {7D083C64-FF32-43C4-A82C-32C4A4EC1414}.Release|x64.Build.0 = Release|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Debug|x64.ActiveCfg = Debug|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Debug|x64.Build.0 = Debug|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Release|Any CPU.Build.0 = Release|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Release|x64.ActiveCfg = Release|Any CPU - {DE2E92D3-929F-40E7-B8D0-502A57170A3E}.Release|x64.Build.0 = Release|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Debug|x64.ActiveCfg = Debug|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Debug|x64.Build.0 = Debug|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Release|Any CPU.Build.0 = Release|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Release|x64.ActiveCfg = Release|Any CPU - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50}.Release|x64.Build.0 = Release|Any CPU {3870E8F1-B269-425D-8B03-58835FD53610}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3870E8F1-B269-425D-8B03-58835FD53610}.Debug|Any CPU.Build.0 = Debug|Any CPU {3870E8F1-B269-425D-8B03-58835FD53610}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -494,6 +476,14 @@ Global {E72E105D-B15F-4D69-9A13-CAA49D4889D6}.Release|Any CPU.Build.0 = Release|Any CPU {E72E105D-B15F-4D69-9A13-CAA49D4889D6}.Release|x64.ActiveCfg = Release|Any CPU {E72E105D-B15F-4D69-9A13-CAA49D4889D6}.Release|x64.Build.0 = Release|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Debug|x64.ActiveCfg = Debug|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Debug|x64.Build.0 = Debug|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Release|Any CPU.Build.0 = Release|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Release|x64.ActiveCfg = Release|Any CPU + {4A052E17-4D9E-41EF-89A5-73B917053F8E}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -520,8 +510,6 @@ Global {62760E2C-D3D6-4824-997F-35033E6EB92C} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} {965C85E2-D94E-43DE-BFC2-B9D157242EBB} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} {7D083C64-FF32-43C4-A82C-32C4A4EC1414} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} - {DE2E92D3-929F-40E7-B8D0-502A57170A3E} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} - {0B139C21-8AFD-41CD-82FE-36E64FDEDE50} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} {3870E8F1-B269-425D-8B03-58835FD53610} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} {519A99D2-8094-48EC-A888-C0B4E017A4C1} = {FBD326D3-E59C-433E-A88E-14E179E3093D} {E946A129-34ED-4069-B44E-EC7B98751006} = {FBD326D3-E59C-433E-A88E-14E179E3093D} @@ -560,6 +548,7 @@ Global {316B1D0A-9CF7-4E5C-A39A-8A389B075A19} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {2F4986D6-3F56-4C05-8A1D-399594F96093} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {E72E105D-B15F-4D69-9A13-CAA49D4889D6} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} + {4A052E17-4D9E-41EF-89A5-73B917053F8E} = {2BE750A5-8AC7-457C-9BB2-6E3D5E2D23B8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {40383055-CC50-4600-AD9A-53C14F620D03} diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/EventHandlerAttribute.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/EventHandlerAttribute.cs index 4671678ab..ce78896d2 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/EventHandlerAttribute.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/EventHandlerAttribute.cs @@ -27,32 +27,31 @@ public EventHandlerAttribute(int order, bool enableRetry, int retryTimes) : this } - public EventHandlerAttribute(int order, bool enableRetry, bool isCancel) : this(order, enableRetry, isCancel, enableRetry ? DefaultRetryCount : 0) + public EventHandlerAttribute(int order, bool enableRetry, bool isCancel) : this(order, enableRetry, isCancel, + enableRetry ? DefaultRetryCount : 0) { } - public EventHandlerAttribute(int order, bool enableRetry, bool isCancel, int retryTimes) : this(order, FailureLevels.Throw, enableRetry, retryTimes, isCancel) + public EventHandlerAttribute(int order, bool enableRetry, bool isCancel, int retryTimes) : this(order, FailureLevels.Throw, enableRetry, + retryTimes, isCancel) { } - public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry) : this(order, failureLevels, enableRetry, enableRetry ? DefaultRetryCount : 0) + public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry) : this(order, failureLevels, enableRetry, + enableRetry ? DefaultRetryCount : 0) { } - public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry, bool isCancel) : this(order, failureLevels, enableRetry, enableRetry ? DefaultRetryCount : 0, isCancel) + public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry, bool isCancel) : this(order, failureLevels, + enableRetry, enableRetry ? DefaultRetryCount : 0, isCancel) { } - public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry, int retryTimes) : this(order, failureLevels, enableRetry, retryTimes, false) - { - - } - - public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry, int retryTimes, bool isCancel) + public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enableRetry, int retryTimes, bool isCancel = false) { Order = order; FailureLevels = failureLevels; @@ -68,11 +67,23 @@ public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enable private const int DefaultOrder = int.MaxValue; + private int _order; + /// /// Used to control the order in which methods are executed, in ascending order. default is 100 /// Must be greater than or equal to 0 /// - public int Order { get; set; } + public int Order + { + get => _order; + set + { + if (value < 0) + throw new ArgumentOutOfRangeException("The order must be greater than or equal to 0"); + + _order = value; + } + } public FailureLevels FailureLevels { get; set; } @@ -96,11 +107,11 @@ public EventHandlerAttribute(int order, FailureLevels failureLevels, bool enable internal int ActualRetryTimes => EnableRetry ? RetryTimes : 0; - internal TaskInvokeDelegate InvokeDelegate { get; private set; } + internal TaskInvokeDelegate? InvokeDelegate { get; private set; } private object Instance { get; set; } = default!; - private object EventHandler { get; set; } + private object? EventHandler { get; set; } internal bool IsEventHandler => FailureLevels == FailureLevels.Throw || FailureLevels == FailureLevels.ThrowAndCancel; @@ -129,7 +140,7 @@ private async Task ExcuteSagaAction(IServiceProvider serviceProvider, TE if (EventHandler == null) { var handlers = serviceProvider.GetServices>(); - var handler = handlers.Where(x => x.GetType().Equals(InstanceType)).FirstOrDefault()!; + var handler = handlers.FirstOrDefault(x => x.GetType() == InstanceType)!; EventHandler = handler; } await ((IEventHandler)EventHandler).HandleAsync(@event); @@ -139,12 +150,13 @@ private async Task ExcuteSagaAction(IServiceProvider serviceProvider, TE if (EventHandler == null) { var handlers = serviceProvider.GetServices>(); - var handler = handlers.Where(x => x.GetType().Equals(InstanceType)).FirstOrDefault()!; + var handler = handlers.FirstOrDefault(x => x.GetType() == InstanceType)!; EventHandler = handler; } await ((ISagaEventHandler)EventHandler).CancelAsync(@event); } } - internal bool IsHandlerMissing(int maxCancelOrder) => FailureLevels == FailureLevels.ThrowAndCancel && Order < maxCancelOrder || FailureLevels == FailureLevels.Throw && Order <= maxCancelOrder; + internal bool IsHandlerMissing(int maxCancelOrder) => FailureLevels == FailureLevels.ThrowAndCancel && Order < maxCancelOrder || + FailureLevels == FailureLevels.Throw && Order <= maxCancelOrder; } diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/Dispatcher.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/Dispatcher.cs index dd27cf022..269afadc9 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/Dispatcher.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/Dispatcher.cs @@ -2,17 +2,19 @@ namespace Masa.Contrib.Dispatcher.Events.Internal.Dispatch; internal class Dispatcher : DispatcherBase { - public Dispatcher(IServiceCollection services, Assembly[] assemblies, bool forceInit = false) : base(services, assemblies, forceInit) { } + public Dispatcher(IServiceCollection services, Assembly[] assemblies, bool forceInit = false) : base(services, assemblies, forceInit) + { + } public Dispatcher Build(ServiceLifetime lifetime) { - foreach (var assembly in _assemblies) + foreach (var assembly in Assemblies) { AddRelationNetwork(assembly); } foreach (var dispatchInstance in GetAddServiceTypeList()) { - _services.Add(dispatchInstance, dispatchInstance, lifetime); + Services.Add(dispatchInstance, dispatchInstance, lifetime); } Build(); return this; @@ -24,7 +26,7 @@ private void AddRelationNetwork(Assembly assembly) { if (!type.IsConcrete()) { - continue;//Handler and Cancel must be normal classes, not abstract classes or interfaces + continue; //Handler and Cancel must be normal classes, not abstract classes or interfaces } foreach (var method in type.GetMethods()) @@ -36,33 +38,32 @@ private void AddRelationNetwork(Assembly assembly) private void AddRelationNetwork(Type type, MethodInfo method) { - var attribute = method.GetCustomAttributes(typeof(EventHandlerAttribute), true).FirstOrDefault(); - var handler = attribute as EventHandlerAttribute; - if (attribute is not null && handler is not null) + try { - var parameters = method.GetParameters(); - if (parameters == null || - parameters.Length != 1 || - !parameters.Any(parameter => typeof(IEvent).IsAssignableFrom(parameter.ParameterType))) - { - throw new ArgumentOutOfRangeException(string.Format("[{0}] must have only one argument and inherit from Event", method.Name)); - } - if (IsSagaMode(type, method)) + var attribute = method.GetCustomAttributes(typeof(EventHandlerAttribute), true).FirstOrDefault(); + if (attribute is not null && attribute is EventHandlerAttribute handler) { - return; - } + var parameters = method.GetParameters(); - if (handler.Order < 0) - { - throw new ArgumentOutOfRangeException("The order must be greater than or equal to 0"); - } + if (parameters == null || parameters.Length != 1 || + !parameters.Any(parameter => typeof(IEvent).IsAssignableFrom(parameter.ParameterType))) + throw new ArgumentOutOfRangeException($"[{method.Name}] must have only one argument and inherit from Event"); + + if (IsSagaMode(type, method)) + return; - var parameter = parameters.FirstOrDefault()!; - handler.ActionMethodInfo = method; - handler.InstanceType = type; - handler.EventType = parameter.ParameterType; - handler.BuildExpression(); - AddRelationNetwork(parameter.ParameterType, handler); + var parameter = parameters.FirstOrDefault()!; + handler.ActionMethodInfo = method; + handler.InstanceType = type; + handler.EventType = parameter.ParameterType; + handler.BuildExpression(); + AddRelationNetwork(parameter.ParameterType, handler); + } + } + catch (Exception ex) + { + Logger?.LogError($"Dispatcher: Failed to get EventBus network, type name: [{type.FullName ?? type.Name}], method: [{method.Name}]", ex); + throw; } } } diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatcherBase.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatcherBase.cs index 9176c2e20..cf4611e64 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatcherBase.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatcherBase.cs @@ -2,39 +2,39 @@ namespace Masa.Contrib.Dispatcher.Events.Internal.Dispatch; internal class DispatcherBase { - protected static DispatchRelationNetwork? _sharingRelationNetwork; + protected static DispatchRelationNetwork? SharingRelationNetwork; - protected readonly IServiceCollection _services; + protected readonly IServiceCollection Services; - protected readonly Assembly[] _assemblies; + protected readonly Assembly[] Assemblies; - private readonly ILogger? _logger; + protected readonly ILogger? Logger; public DispatcherBase(IServiceCollection services, Assembly[] assemblies, bool forceInit) { - _services = services; - _assemblies = assemblies; + Services = services; + Assemblies = assemblies; var serviceProvider = services.BuildServiceProvider(); - if (_sharingRelationNetwork == null || forceInit) + if (SharingRelationNetwork == null || forceInit) { - _sharingRelationNetwork = new DispatchRelationNetwork(serviceProvider.GetService>()); + SharingRelationNetwork = new DispatchRelationNetwork(serviceProvider.GetService>()); } - _logger = serviceProvider.GetService>(); + Logger = serviceProvider.GetService>(); } public async Task PublishEventAsync(IServiceProvider serviceProvider, TEvent @event) where TEvent : IEvent { var eventType = typeof(TEvent); - if (!_sharingRelationNetwork!.RelationNetwork.TryGetValue(eventType, out List? dispatchRelations)) + if (!SharingRelationNetwork!.RelationNetwork.TryGetValue(eventType, out List? dispatchRelations)) { if (@event is IIntegrationEvent) { - _logger?.LogError($"Dispatcher: The current event is an out-of-process event. You should use IIntegrationEventBus or IDomainEventBus to send it"); + Logger?.LogError($"Dispatcher: The current event is an out-of-process event. You should use IIntegrationEventBus or IDomainEventBus to send it"); throw new ArgumentNullException($"The current event is an out-of-process event. You should use IIntegrationEventBus or IDomainEventBus to send it"); } - _logger?.LogError($"Dispatcher: The {eventType.FullName} Handler method was not found. Check to see if the EventHandler feature is added to the method and if the Assembly is specified when using EventBus"); + Logger?.LogError($"Dispatcher: The {eventType.FullName} Handler method was not found. Check to see if the EventHandler feature is added to the method and if the Assembly is specified when using EventBus"); throw new ArgumentNullException($"The {eventType.FullName} Handler method was not found. Check to see if the EventHandler feature is added to the method and if the Assembly is specified when using EventBus"); } await ExecuteEventHandlerAsync(serviceProvider, dispatchRelations, @event); @@ -58,7 +58,7 @@ private async Task ExecuteEventHandlerAsync(IServiceProvider serviceProv await executionStrategy.ExecuteAsync(strategyOptions, @event, async (@event) => { - _logger?.LogDebug("----- Publishing event {@Event}: message id: {messageId} -----", @event, @event.Id); + Logger?.LogDebug("----- Publishing event {@Event}: message id: {messageId} -----", @event, @event.Id); await dispatchHandler.ExcuteAction(serviceProvider, @event); }, async (@event, ex, failureLevels) => { @@ -67,7 +67,7 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async (@event) => isCancel = true; if (dispatchRelation.CancelHandlers.Any()) { - await ExecuteEventCanceledHandlerAsync(serviceProvider, _logger, executionStrategy, dispatchRelation.CancelHandlers, @event); + await ExecuteEventCanceledHandlerAsync(serviceProvider, Logger, executionStrategy, dispatchRelation.CancelHandlers, @event); } else { @@ -76,7 +76,7 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async (@event) => } else { - _logger?.LogWarning("----- Publishing event {@Event} error rollback is ignored: message id: {messageId} -----", @event, @event.Id); + Logger?.LogWarning("----- Publishing event {@Event} error rollback is ignored: message id: {messageId} -----", @event, @event.Id); } }); } @@ -111,16 +111,16 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async @event => protected void AddRelationNetwork(Type parameterType, EventHandlerAttribute handler) { - _sharingRelationNetwork!.Add(parameterType, handler); + SharingRelationNetwork!.Add(parameterType, handler); } - protected IEnumerable GetAddServiceTypeList() => _sharingRelationNetwork!.HandlerRelationNetwork - .Concat(_sharingRelationNetwork.CancelRelationNetwork) + protected IEnumerable GetAddServiceTypeList() => SharingRelationNetwork!.HandlerRelationNetwork + .Concat(SharingRelationNetwork.CancelRelationNetwork) .SelectMany(relative => relative.Value) .Where(dispatchHandler => dispatchHandler.InvokeDelegate != null) .Select(dispatchHandler => dispatchHandler.InstanceType).Distinct(); - protected void Build() => _sharingRelationNetwork!.Build(); + protected void Build() => SharingRelationNetwork!.Build(); protected bool IsSagaMode(Type handlerType, MethodInfo method) => typeof(IEventHandler<>).IsGenericInterfaceAssignableFrom(handlerType) && method.Name.Equals(nameof(IEventHandler.HandleAsync)) || diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs index 952003208..ec33e8b36 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs @@ -6,8 +6,8 @@ public SagaDispatcher(IServiceCollection services, Assembly[] assemblies, bool f public SagaDispatcher Build(ServiceLifetime lifetime) { - AddSagaDispatchRelation(_services, typeof(IEventHandler<>), lifetime); - AddSagaDispatchRelation(_services, typeof(ISagaEventHandler<>), lifetime); + AddSagaDispatchRelation(Services, typeof(IEventHandler<>), lifetime); + AddSagaDispatchRelation(Services, typeof(ISagaEventHandler<>), lifetime); return this; } @@ -24,12 +24,9 @@ private IServiceCollection AddSagaDispatchRelation(IServiceCollection services, private void AddSagaRelationNetwork(Type eventBusHandlerType) { var eventHandlers = GetSagaHandlers(eventBusHandlerType); - var eventHandler = eventHandlers.Where(x => x.Order != int.MaxValue).FirstOrDefault(); + var eventHandler = eventHandlers.FirstOrDefault(x => x.Order != int.MaxValue); var actualOrder = eventHandler?.Order ?? int.MaxValue; - if (actualOrder < 0) - { - throw new ArgumentOutOfRangeException("The order must be greater than or equal to 0"); - } + foreach (var handler in eventHandlers) { if (actualOrder != handler.Order) @@ -101,7 +98,7 @@ private List GetSagaHandlers(Type eventBusHandlerType) { var concretions = new List(); var interfaces = new List(); - foreach (var type in _assemblies.SelectMany(a => a.DefinedTypes).Where(t => !t.IsGeneric())) + foreach (var type in Assemblies.SelectMany(a => a.DefinedTypes).Where(t => !t.IsGeneric())) { if (type.IsConcrete()) { diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/EventHandlers/OrderStockConfirmedHandler.cs b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/EventHandlers/OrderStockConfirmedHandler.cs deleted file mode 100644 index 3872e5b0f..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/EventHandlers/OrderStockConfirmedHandler.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.EventHandlers; - -public class OrderStockConfirmedHandler -{ - private readonly ILogger? _logger; - - public OrderStockConfirmedHandler(ILogger? logger = null) => _logger = logger; - - [EventHandler(-10)] - public void AddLog(OrderStockConfirmedEvent @event) - { - _logger?.LogInformation($"add order stock confirmed log,orderId:{@event.OrderId}"); - } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Events/OrderStockConfirmedEvent.cs b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Events/OrderStockConfirmedEvent.cs deleted file mode 100644 index ceb2a222c..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Events/OrderStockConfirmedEvent.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.Events; - -public record OrderStockConfirmedEvent : Event -{ - public string OrderId { get; set; } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.csproj b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.csproj deleted file mode 100644 index b6c588b8d..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net6.0 - enable - enable - false - - - - - - - diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/_Imports.cs b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/_Imports.cs deleted file mode 100644 index 8162d5067..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests/_Imports.cs +++ /dev/null @@ -1,2 +0,0 @@ -global using Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.Events; -global using Microsoft.Extensions.Logging; diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/EventHandlers/EditGoodsHandler.cs b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/EventHandlers/EditGoodsHandler.cs deleted file mode 100644 index a0efe737e..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/EventHandlers/EditGoodsHandler.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.EventHandlers; - -public class EditGoodsHandler : IEventHandler -{ - private readonly ILogger? _logger; - public EditGoodsHandler(ILogger? logger) => _logger = logger; - - [EventHandler(-10)] - public Task HandleAsync(EditGoodsEvent @event) - { - _logger?.LogInformation($"edit goods log,GoodsId:{@event.GoodsId},Name:{@event.GoodsName},CategoryId:{@event.CategoryId}"); - return Task.CompletedTask; - } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Events/EditGoodsEvent.cs b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Events/EditGoodsEvent.cs deleted file mode 100644 index 4887ebc94..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Events/EditGoodsEvent.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.Events; - -public record EditGoodsEvent : Event -{ - public string GoodsId { get; set; } - - public string CategoryId { get; set; } - - public string GoodsName { get; set; } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.csproj b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.csproj deleted file mode 100644 index b6c588b8d..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net6.0 - enable - enable - false - - - - - - - diff --git a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/_Imports.cs b/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/_Imports.cs deleted file mode 100644 index cd6f37d5b..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests/_Imports.cs +++ /dev/null @@ -1,3 +0,0 @@ -global using Masa.BuildingBlocks.Dispatcher.Events; -global using Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.Events; -global using Microsoft.Extensions.Logging; diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/EventHandlers/UserEventHandler.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/EventHandlers/UserEventHandler.cs deleted file mode 100644 index 529b52fdd..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/EventHandlers/UserEventHandler.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.Tests.EventHandlers; - -public class UserEventHandler : IEventHandler -{ - [EventHandler(10, true, 1, FailureLevels = FailureLevels.ThrowAndCancel)] - public Task HandleAsync(EditUserEvent @event) - { - throw new NotSupportedException("users cannot be modified"); - } - - /// - /// This CancelHandler is not the same as EventHandler in Saga mode, so a different order can be used - /// - /// - /// - [EventHandler(20, true, 1, FailureLevels = FailureLevels.Ignore, IsCancel = true)] - public Task CancelAsync(EditUserEvent @event) - { - throw new NotSupportedException("edit users do not support cancellation"); - } - - [EventHandler(10, true)] - public void ForgotPassword(ForgotPasswordEvent @event) - { - throw new Exception("Password retrieval is not supported"); - } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/Events/EditUserEvent.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/Events/EditUserEvent.cs deleted file mode 100644 index ab2538c4a..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/Events/EditUserEvent.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.Tests.Events; - -public record EditUserEvent : Event -{ - public string UserId { get; set; } - - public string UserName { get; set; } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs index 8b6f01a13..ac838e1c4 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs @@ -1,9 +1,12 @@ +using Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events; + namespace Masa.Contrib.Dispatcher.Events.Tests; [TestClass] public class FeaturesTest : TestBase { private readonly IEventBus _eventBus; + public FeaturesTest() : base() { _eventBus = _serviceProvider.GetRequiredService(); @@ -127,31 +130,6 @@ await Assert.ThrowsExceptionAsync(async () => }); } - [TestMethod] - public Task TestOrderLessThenZero() - { - Assert.ThrowsException(() => - { - try - { - ResetMemoryEventBus(typeof(OrderStockConfirmedEvent).Assembly); - } - catch (ArgumentOutOfRangeException) - { - try - { - ResetMemoryEventBus(typeof(FeaturesTest).Assembly); - } - catch (Exception) - { - - } - throw; - } - }); - return Task.CompletedTask; - } - [TestMethod] public Task TestOnlyCancelHandler() { @@ -275,4 +253,132 @@ public async Task TestUseUoWCommitAsync() await eventBus.CommitAsync(default); uoW.Verify(u => u.CommitAsync(default), Times.Once); } + + [DataTestMethod] + [DataRow(1, 2, -1)] + [DataRow(5, 4, 24)] + public async Task TestEventBusCancelOrder(int parameterA, int parameterB, int result) + { + IServiceCollection services = new ServiceCollection(); + services.AddTestEventBus(new[] { typeof(CalculateEvent).Assembly }, ServiceLifetime.Scoped); + var @event = new CalculateEvent() + { + ParameterA = parameterA, + ParameterB = parameterB + }; + var eventBus = services.BuildServiceProvider().GetRequiredService(); + await eventBus.PublishAsync(@event); + Assert.IsTrue(@event.Result == result); + } + + [DataTestMethod] + public void TestEventHandler() + { + var order = 1; + bool enableRetry = true; + var failureLevels = FailureLevels.ThrowAndCancel; + bool isCancel = true; + int retryTimes = 5; + int defaultRetryTimes = 3; + + var eventAttribute = new EventHandlerAttribute(order); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry == false && + eventAttribute.RetryTimes == 0 && + eventAttribute.FailureLevels == FailureLevels.Throw && + eventAttribute.IsCancel == false + ); + + eventAttribute = new EventHandlerAttribute(order, failureLevels); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry == false && + eventAttribute.RetryTimes == 0 && + eventAttribute.FailureLevels == failureLevels && + eventAttribute.IsCancel == false + ); + + eventAttribute = new EventHandlerAttribute(order, failureLevels, enableRetry); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry == enableRetry && + eventAttribute.RetryTimes == defaultRetryTimes && + eventAttribute.FailureLevels == failureLevels && + eventAttribute.IsCancel == false + ); + + eventAttribute = new EventHandlerAttribute(order, failureLevels, enableRetry, isCancel); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry == enableRetry && + eventAttribute.RetryTimes == defaultRetryTimes && + eventAttribute.FailureLevels == failureLevels && + eventAttribute.IsCancel == isCancel + ); + + eventAttribute = new EventHandlerAttribute(order, failureLevels, enableRetry, retryTimes); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry == enableRetry && + eventAttribute.RetryTimes == retryTimes && + eventAttribute.FailureLevels == failureLevels && + eventAttribute.IsCancel == false + ); + + eventAttribute = new EventHandlerAttribute(order, failureLevels, enableRetry, retryTimes, isCancel); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry == enableRetry && + eventAttribute.RetryTimes == retryTimes && + eventAttribute.FailureLevels == failureLevels && + eventAttribute.IsCancel == isCancel + ); + + eventAttribute = new EventHandlerAttribute(order, enableRetry); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry && + eventAttribute.RetryTimes == defaultRetryTimes && + eventAttribute.FailureLevels == FailureLevels.Throw && + eventAttribute.IsCancel == false + ); + + eventAttribute = new EventHandlerAttribute(order, enableRetry, retryTimes); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry && + eventAttribute.RetryTimes == retryTimes && + eventAttribute.FailureLevels == FailureLevels.Throw && + eventAttribute.IsCancel == false + ); + + eventAttribute = new EventHandlerAttribute(order, enableRetry, isCancel); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry && + eventAttribute.RetryTimes == defaultRetryTimes && + eventAttribute.FailureLevels == FailureLevels.Throw && + eventAttribute.IsCancel == isCancel + ); + + eventAttribute = new EventHandlerAttribute(order, enableRetry, isCancel, retryTimes); + Assert.IsTrue( + eventAttribute.Order == order && + eventAttribute.EnableRetry && + eventAttribute.RetryTimes == retryTimes && + eventAttribute.FailureLevels == FailureLevels.Throw && + eventAttribute.IsCancel == isCancel + ); + + } + + [TestMethod] + public void TestOrderLessThanZero() + { + Assert.ThrowsException(() => + { + new EventHandlerAttribute(-10); + },"The order must be greater than or equal to 0"); + } } diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/Masa.Contrib.Dispatcher.Events.Tests.csproj b/test/Masa.Contrib.Dispatcher.Events.Tests/Masa.Contrib.Dispatcher.Events.Tests.csproj index 589d40718..d06f67e54 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/Masa.Contrib.Dispatcher.Events.Tests.csproj +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/Masa.Contrib.Dispatcher.Events.Tests.csproj @@ -32,10 +32,9 @@ + - - diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/SagaTest.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/SagaTest.cs index 9e8e710af..ba72835b8 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/SagaTest.cs +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/SagaTest.cs @@ -49,17 +49,6 @@ await Assert.ThrowsExceptionAsync(async () => } } - [TestMethod] - public async Task TestEqualMethodsBySaga() - { - EditUserEvent @event = new EditUserEvent() - { - UserId = new Random().Next(10, 1000000).ToString(), - UserName = "roller" - }; - await _eventBus.PublishAsync(@event); - } - [DataTestMethod] [DataRow("smith", "alice", "1000", 0)] [DataRow("roller", "alice", "1000", 1)] @@ -106,26 +95,4 @@ public async Task TestMultiOrderBySaga() } ResetMemoryEventBus(false, null!); } - - [TestMethod] - public async Task TestLessThenZeroBySaga() - { - IEventBus? eventBus = null; - Assert.ThrowsException(() => - { - ResetMemoryEventBus(false, typeof(EditGoodsEvent).Assembly); - eventBus = _serviceProvider.GetRequiredService(); - }); - EditGoodsEvent @event = new EditGoodsEvent() - { - GoodsId = new Random().Next(10, 1000).ToString(), - CategoryId = new Random().Next(100, 10000).ToString(), - GoodsName = "Name" - }; - if (eventBus != null) - { - await eventBus.PublishAsync(@event); - } - ResetMemoryEventBus(false, null!); - } } diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/_Imports.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/_Imports.cs index b47c66104..df4d04cb9 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/_Imports.cs +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/_Imports.cs @@ -8,8 +8,6 @@ global using Masa.Contrib.Dispatcher.Events.Enums; global using Masa.Contrib.Dispatcher.Events.Options; global using Masa.Contrib.Dispatcher.Events.OrderEqualBySaga.Tests.Events; -global using Masa.Contrib.Dispatcher.Events.OrderLessThanZeroByFeature.Tests.Events; -global using Masa.Contrib.Dispatcher.Events.OrderLessThanZeroBySaga.Tests.Events; global using Masa.Contrib.Dispatcher.Events.Tests.Events; global using Masa.Contrib.Dispatcher.Events.Tests.Middleware; global using Microsoft.Extensions.DependencyInjection; From 4f75c84a4f48b58e36a9923cd19198aea6c0c3a4 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 18 Mar 2022 13:20:45 +0800 Subject: [PATCH 4/4] test(EventBus): Remove invalid unit tests --- .../Internal/Dispatch/DispatchRelationNetwork.cs | 2 +- .../Internal/Dispatch/SagaDispatcher.cs | 14 ++++---------- .../Events/ForgotPasswordEvent.cs | 8 -------- .../FeaturesTest.cs | 14 -------------- 4 files changed, 5 insertions(+), 33 deletions(-) delete mode 100644 test/Masa.Contrib.Dispatcher.Events.Tests/Events/ForgotPasswordEvent.cs diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs index 473aa4b73..df6573cb1 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatchRelationNetwork.cs @@ -32,7 +32,7 @@ private void Add(Type keyEventType, dispatchRelativeNetwork.Add(keyEventType, new List()); } - if (!dispatchRelativeNetwork[keyEventType].Any(x => x.ActionMethodInfo.Equals(handlers.ActionMethodInfo) && x.InstanceType.Equals(handlers.InstanceType))) + if (!dispatchRelativeNetwork[keyEventType].Any(x => x.ActionMethodInfo.Equals(handlers.ActionMethodInfo) && x.InstanceType == handlers.InstanceType)) { dispatchRelativeNetwork[keyEventType].Add(handlers); } diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs index ec33e8b36..5eb3cb359 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/SagaDispatcher.cs @@ -45,19 +45,13 @@ private List GetSagaHandlers(Type eventBusHandlerType) foreach (var method in methods) { var parameters = method.GetParameters(); - if (parameters != null && parameters.Length == 1 && parameters.All(parameter => typeof(IEvent).IsAssignableFrom(parameter.ParameterType) && !typeof(IIntegrationEvent).IsAssignableFrom(parameter.ParameterType)) && IsSagaMode(eventBusHandlerType, method)) + if (parameters.Length == 1 && parameters.All(parameter => typeof(IEvent).IsAssignableFrom(parameter.ParameterType) && !typeof(IIntegrationEvent).IsAssignableFrom(parameter.ParameterType)) && IsSagaMode(eventBusHandlerType, method)) { var attribute = method.GetCustomAttributes(typeof(EventHandlerAttribute), true).FirstOrDefault(); - var handler = attribute != null ? attribute as EventHandlerAttribute : null; - if (eventType == null) - { - eventType = parameters.Select(x => x.ParameterType).FirstOrDefault()!; - } + var handler = attribute as EventHandlerAttribute; + eventType ??= parameters.Select(x => x.ParameterType).FirstOrDefault()!; - if (handler is null) - { - handler = new EventHandlerAttribute(); - } + handler ??= new EventHandlerAttribute(); handler.ActionMethodInfo = method; handler.InstanceType = eventBusHandlerType; handler.EventType = eventType; diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/Events/ForgotPasswordEvent.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/Events/ForgotPasswordEvent.cs deleted file mode 100644 index 78b973da4..000000000 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/Events/ForgotPasswordEvent.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Masa.Contrib.Dispatcher.Events.Tests.Events; - -public record ForgotPasswordEvent() : Event -{ - public string Account { get; set; } - - public string Email { get; set; } -} diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs index ac838e1c4..faf0da851 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs @@ -116,20 +116,6 @@ await Assert.ThrowsExceptionAsync(async () => }); } - [TestMethod] - public async Task TestThrowException() - { - ForgotPasswordEvent @event = new ForgotPasswordEvent() - { - Account = new Random().Next(1000, 9000).ToString(), - Email = new Random().Next(100000, 9000000).ToString() + "@qq.com", - }; - await Assert.ThrowsExceptionAsync(async () => - { - await _eventBus.PublishAsync(@event); - }); - } - [TestMethod] public Task TestOnlyCancelHandler() {