Skip to content

Commit

Permalink
feat: Adds FeatureSwitchAsync attribute and handler (#2419)
Browse files Browse the repository at this point in the history
  • Loading branch information
DevJonny authored Dec 18, 2022
1 parent 8fb3b0c commit 1a7a94c
Show file tree
Hide file tree
Showing 14 changed files with 466 additions and 173 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
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. */

#endregion

using System;
using Paramore.Brighter.FeatureSwitch.Handlers;

namespace Paramore.Brighter.FeatureSwitch.Attributes
{
/// <summary>
/// Class FeatureSwitchAttribute.
/// This attribute supports adding feature switches on a handler. It is intended to allow control over which handlers can be used at
/// run-time using <see cref="FeatureSwitchStatus.Config"/> or compile time using <see cref="FeatureSwitchStatus.On"/> and <see cref="FeatureSwitchStatus.Off"/>.
/// </summary>
public class FeatureSwitchAsyncAttribute : RequestHandlerAttribute
{
private readonly Type _handler;
private readonly FeatureSwitchStatus _status;

/// <summary>
/// Initialises a new instance of the <see cref="FeatureSwitchAttribute"/> class.
/// </summary>
/// <param name="handler">The handler to feature switch</param>
/// <param name="status">The status of the feature switch</param>
/// <param name="step">The step.</param>
/// <param name="timing">The timing.</param>
public FeatureSwitchAsyncAttribute(Type handler, FeatureSwitchStatus status, int step, HandlerTiming timing = HandlerTiming.Before) : base(step, timing)
{
_handler = handler;
_status = status;
}

/// <summary>
/// Initialises the paramers
/// </summary>
/// <returns>System.Object[]</returns>
public override object[] InitializerParams()
{
return new object[] { _handler, _status };
}

/// <summary>
/// Gets the type of the handler
/// </summary>
/// <returns></returns>
public override Type GetHandlerType()
{
return typeof(FeatureSwitchHandlerAsync<>);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
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. */

#endregion

using System;
using System.Threading;
using System.Threading.Tasks;
using Paramore.Brighter.FeatureSwitch.Attributes;

namespace Paramore.Brighter.FeatureSwitch.Handlers
{
/// <summary>
/// Class FeatureSwitchHandler.
/// The handler is injected into the pipeline if the <see cref="FeatureSwitchAttribute"/> is applied
/// </summary>
/// <typeparam name="TRequest">The type of the request</typeparam>
public class FeatureSwitchHandlerAsync<TRequest> : RequestHandlerAsync<TRequest> where TRequest : class, IRequest
{
private Type _handler;
private FeatureSwitchStatus _status;

/// <summary>
/// Initializes from attribute parameters.
/// </summary>
/// <param name="initializerList">The initializer list.</param>
public override void InitializeFromAttributeParams(params object[] initializerList)
{
_handler = (Type) initializerList[0];
_status = (FeatureSwitchStatus) initializerList[1];
}

/// <summary>
/// Checks the status of the feature switch and either stops passes the command on to the next handler
/// or stops execution of the feature switched handler.
/// </summary>
/// <param name="command">The command.</param>
/// <returns>TRequest.</returns>
public override async Task<TRequest> HandleAsync(TRequest command, CancellationToken cancellationToken = default)
{
var featureEnabled = _status;

if (featureEnabled is FeatureSwitchStatus.Config)
{
featureEnabled = Context.FeatureSwitches?.StatusOf(_handler) ?? FeatureSwitchStatus.On;
}

return featureEnabled is FeatureSwitchStatus.Off
? command
: await base.HandleAsync(command, cancellationToken);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System;

namespace Paramore.Brighter.Core.Tests.FeatureSwitch.TestDoubles;

public class MyCommandAsync : Command
{
public MyCommandAsync() : base(Guid.NewGuid())
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ THE SOFTWARE. */

#endregion

using System.Threading;
using System.Threading.Tasks;
using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles;
using Paramore.Brighter.FeatureSwitch;
using Paramore.Brighter.FeatureSwitch.Attributes;
Expand All @@ -32,15 +34,33 @@ class MyFeatureSwitchedConfigHandler : RequestHandler<MyCommand>
{
public bool CommandReceived { get; set; }

[FeatureSwitch(typeof(MyFeatureSwitchedConfigHandler), FeatureSwitchStatus.Config, 1, HandlerTiming.Before)]
public override MyCommand Handle(MyCommand comand)
[FeatureSwitch(typeof(MyFeatureSwitchedConfigHandler), FeatureSwitchStatus.Config, 1)]
public override MyCommand Handle(MyCommand command)
{
CommandReceived = true;

return base.Handle(comand);
return base.Handle(command);
}

public bool DidReceive(MyCommand command)
public bool DidReceive()
{
return CommandReceived;
}
}

class MyFeatureSwitchedConfigHandlerAsync : RequestHandlerAsync<MyCommandAsync>
{
public bool CommandReceived { get; set; }

[FeatureSwitchAsync(typeof(MyFeatureSwitchedConfigHandlerAsync), FeatureSwitchStatus.Config, 1)]
public override async Task<MyCommandAsync> HandleAsync(MyCommandAsync command, CancellationToken cancellationToken = default)
{
CommandReceived = true;

return await base.HandleAsync(command, cancellationToken);
}

public bool DidReceive()
{
return CommandReceived;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ THE SOFTWARE. */

#endregion

using System.Threading;
using System.Threading.Tasks;
using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles;
using Paramore.Brighter.FeatureSwitch;
using Paramore.Brighter.FeatureSwitch.Attributes;
Expand All @@ -32,15 +34,33 @@ class MyFeatureSwitchedOffHandler : RequestHandler<MyCommand>
{
public static bool CommandReceived { get; set; }

[FeatureSwitch(typeof(MyFeatureSwitchedOffHandler), FeatureSwitchStatus.Off, 1, HandlerTiming.Before)]
public override MyCommand Handle(MyCommand comand)
[FeatureSwitch(typeof(MyFeatureSwitchedOffHandler), FeatureSwitchStatus.Off, 1)]
public override MyCommand Handle(MyCommand command)
{
CommandReceived = true;

return base.Handle(comand);
return base.Handle(command);
}

public static bool DidReceive(MyCommand command)
public static bool DidReceive()
{
return CommandReceived;
}
}

class MyFeatureSwitchedOffHandlerAsync : RequestHandlerAsync<MyCommandAsync>
{
public static bool CommandReceived { get; set; }

[FeatureSwitchAsync(typeof(MyFeatureSwitchedOffHandlerAsync), FeatureSwitchStatus.Off, 1)]
public override async Task<MyCommandAsync> HandleAsync(MyCommandAsync command, CancellationToken cancellationToken = default)
{
CommandReceived = true;

return await base.HandleAsync(command, cancellationToken);
}

public static bool DidReceive()
{
return CommandReceived;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ THE SOFTWARE. */

#endregion

using System.Threading;
using System.Threading.Tasks;
using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles;
using Paramore.Brighter.FeatureSwitch;
using Paramore.Brighter.FeatureSwitch.Attributes;
Expand All @@ -32,7 +34,7 @@ class MyFeatureSwitchedOnHandler : RequestHandler<MyCommand>
{
public static bool CommandReceived { get; set; }

[FeatureSwitch(typeof(MyFeatureSwitchedOnHandler), FeatureSwitchStatus.On, 1, HandlerTiming.Before)]
[FeatureSwitch(typeof(MyFeatureSwitchedOnHandler), FeatureSwitchStatus.On, 1)]
public override MyCommand Handle(MyCommand comand)
{
CommandReceived = true;
Expand All @@ -45,4 +47,21 @@ public static bool DidReceive(MyCommand command)
return CommandReceived;
}
}
class MyFeatureSwitchedOnHandlerAsync : RequestHandlerAsync<MyCommandAsync>
{
public static bool CommandReceived { get; set; }

[FeatureSwitchAsync(typeof(MyFeatureSwitchedOnHandlerAsync), FeatureSwitchStatus.On, 1)]
public override async Task<MyCommandAsync> HandleAsync(MyCommandAsync command, CancellationToken cancellationToken = default)
{
CommandReceived = true;

return await base.HandleAsync(command, cancellationToken);
}

public static bool DidReceive()
{
return CommandReceived;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ THE SOFTWARE. */
#endregion

using System;
using System.Threading.Tasks;
using FluentAssertions;
using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles;
using Paramore.Brighter.Core.Tests.FeatureSwitch.TestDoubles;
using Paramore.Brighter.FeatureSwitch;
using Paramore.Brighter.FeatureSwitch.Providers;
using Polly.Registry;
using Microsoft.Extensions.DependencyInjection;
using Paramore.Brighter.Extensions.DependencyInjection;
using Xunit;
Expand All @@ -39,48 +39,58 @@ namespace Paramore.Brighter.Core.Tests.FeatureSwitch
[Collection("CommandProcessor")]
public class CommandProcessorWithFeatureSwitchOffByConfigInPipelineTests : IDisposable
{
private readonly MyCommand _myCommand = new MyCommand();
private readonly SubscriberRegistry _registry;
private readonly ServiceProviderHandlerFactory _handlerFactory;
private readonly MyCommand _myCommand = new();
private readonly MyCommandAsync _myAsyncCommand = new();

private CommandProcessor _commandProcessor;
ServiceProvider _provider;
private readonly CommandProcessor _commandProcessor;
private readonly ServiceProvider _provider;

public CommandProcessorWithFeatureSwitchOffByConfigInPipelineTests()
{
_registry = new SubscriberRegistry();
_registry.Register<MyCommand, MyFeatureSwitchedConfigHandler>();
{
SubscriberRegistry registry = new();
registry.Register<MyCommand, MyFeatureSwitchedConfigHandler>();
registry.RegisterAsync<MyCommandAsync, MyFeatureSwitchedConfigHandlerAsync>();

IAmAFeatureSwitchRegistry featureSwitchRegistry = FluentConfigRegistryBuilder
.With()
.StatusOf<MyFeatureSwitchedConfigHandler>().Is(FeatureSwitchStatus.Off)
.StatusOf<MyFeatureSwitchedConfigHandlerAsync>().Is(FeatureSwitchStatus.Off)
.Build();

var container = new ServiceCollection();
container.AddSingleton<MyFeatureSwitchedConfigHandler>();
container.AddSingleton<MyFeatureSwitchedConfigHandlerAsync>();
container.AddTransient<FeatureSwitchHandler<MyCommand>>();
container.AddSingleton<IBrighterOptions>(new BrighterOptions() {HandlerLifetime = ServiceLifetime.Transient});
container.AddTransient<FeatureSwitchHandlerAsync<MyCommandAsync>>();
container.AddSingleton<IBrighterOptions>(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient});

_provider = container.BuildServiceProvider();
_handlerFactory = new ServiceProviderHandlerFactory(_provider);
}

[Fact]
public void When_Sending_A_Command_To_The_Processor_When_A_Feature_Switch_Is_Off_By_Fluent_Config()
{
var fluentConfig = FluentConfigRegistryBuilder
.With()
.StatusOf<MyFeatureSwitchedConfigHandler>().Is(FeatureSwitchStatus.Off)
.Build();

ServiceProviderHandlerFactory handlerFactory = new(_provider);

_commandProcessor = CommandProcessorBuilder
.With()
.ConfigureFeatureSwitches(fluentConfig)
.Handlers(new HandlerConfiguration(_registry, _handlerFactory))
.ConfigureFeatureSwitches(featureSwitchRegistry)
.Handlers(new HandlerConfiguration(registry, handlerFactory))
.DefaultPolicy()
.NoExternalBus()
.RequestContextFactory(new InMemoryRequestContextFactory())
.Build();
}

[Fact]
public void When_Sending_A_Command_To_The_Processor_When_A_Feature_Switch_Is_Off_By_Fluent_Config()
{
_commandProcessor.Send(_myCommand);

_provider.GetService<MyFeatureSwitchedConfigHandler>().DidReceive(_myCommand).Should().BeFalse();
_provider.GetService<MyFeatureSwitchedConfigHandler>().DidReceive().Should().BeFalse();
}

[Fact]
public async Task When_Sending_A_Async_Command_To_The_Processor_When_A_Feature_Switch_Is_Off_By_Fluent_Config()
{
await _commandProcessor.SendAsync(_myAsyncCommand);

_provider.GetService<MyFeatureSwitchedConfigHandlerAsync>().DidReceive().Should().BeFalse();
}

public void Dispose()
Expand Down
Loading

0 comments on commit 1a7a94c

Please sign in to comment.