Lidarr/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs

163 lines
5.9 KiB
C#
Raw Normal View History

2013-09-11 06:33:47 +00:00
using System;
2013-05-13 02:52:55 +00:00
using System.Linq;
using System.Threading.Tasks;
2013-02-23 20:09:44 +00:00
using NLog;
2013-09-11 06:33:47 +00:00
using NzbDrone.Common;
2013-05-13 02:52:55 +00:00
using NzbDrone.Common.EnsureThat;
using NzbDrone.Common.Serializer;
2013-07-12 06:10:34 +00:00
using NzbDrone.Common.TPL;
using NzbDrone.Core.Messaging.Commands.Tracking;
2013-09-11 06:33:47 +00:00
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.ProgressMessaging;
namespace NzbDrone.Core.Messaging.Commands
{
public class CommandExecutor : ICommandExecutor
{
2013-02-23 20:09:44 +00:00
private readonly Logger _logger;
private readonly IServiceFactory _serviceFactory;
private readonly ITrackCommands _trackCommands;
private readonly IEventAggregator _eventAggregator;
private readonly TaskFactory _taskFactory;
public CommandExecutor(Logger logger, IServiceFactory serviceFactory, ITrackCommands trackCommands, IEventAggregator eventAggregator)
{
2013-09-11 06:33:47 +00:00
var scheduler = new LimitedConcurrencyLevelTaskScheduler(3);
2013-02-23 20:09:44 +00:00
_logger = logger;
_serviceFactory = serviceFactory;
_trackCommands = trackCommands;
_eventAggregator = eventAggregator;
_taskFactory = new TaskFactory(scheduler);
}
2013-09-11 06:33:47 +00:00
public void PublishCommand<TCommand>(TCommand command) where TCommand : Command
{
2013-11-30 23:53:07 +00:00
Ensure.That(command, () => command).IsNotNull();
2013-05-13 02:52:55 +00:00
_logger.Trace("Publishing {0}", command.GetType().Name);
2013-09-11 06:33:47 +00:00
if (_trackCommands.FindExisting(command) != null)
{
2014-03-13 20:12:42 +00:00
_logger.Trace("Command is already in progress: {0}", command.GetType().Name);
return;
}
2013-09-11 06:33:47 +00:00
_trackCommands.Store(command);
ExecuteCommand<TCommand>(command);
}
public void PublishCommand(string commandTypeName)
{
PublishCommand(commandTypeName, null);
}
public void PublishCommand(string commandTypeName, DateTime? lastExecutionTime)
{
dynamic command = GetCommand(commandTypeName);
command.LastExecutionTime = lastExecutionTime;
PublishCommand(command);
}
2013-09-11 06:33:47 +00:00
public Command PublishCommandAsync<TCommand>(TCommand command) where TCommand : Command
{
2013-11-30 23:53:07 +00:00
Ensure.That(command, () => command).IsNotNull();
_logger.Trace("Publishing {0}", command.GetType().Name);
2013-09-11 06:33:47 +00:00
var existingCommand = _trackCommands.FindExisting(command);
2013-09-11 06:33:47 +00:00
if (existingCommand != null)
{
2014-03-13 20:12:42 +00:00
_logger.Trace("Command is already in progress: {0}", command.GetType().Name);
2013-09-11 06:33:47 +00:00
return existingCommand;
}
2013-09-11 06:33:47 +00:00
_trackCommands.Store(command);
// TODO: We should use async await (once we get 4.5) or normal Task Continuations on Command processing to prevent blocking the TaskScheduler.
// For now we use TaskCreationOptions 0x10, which is actually .net 4.5 HideScheduler.
// This will detach the scheduler from the thread, causing new Task creating in the command to be executed on the ThreadPool, avoiding a deadlock.
// Please note that the issue only shows itself on mono because since Microsoft .net implementation supports Task inlining on WaitAll.
if (Enum.IsDefined(typeof(TaskCreationOptions), (TaskCreationOptions)0x10))
{
_taskFactory.StartNew(() => ExecuteCommand<TCommand>(command)
, TaskCreationOptions.PreferFairness | (TaskCreationOptions)0x10)
.LogExceptions();
}
else
{
_taskFactory.StartNew(() => ExecuteCommand<TCommand>(command)
, TaskCreationOptions.PreferFairness)
.LogExceptions();
}
2013-09-11 06:33:47 +00:00
return command;
}
2013-09-11 06:33:47 +00:00
public Command PublishCommandAsync(string commandTypeName)
{
dynamic command = GetCommand(commandTypeName);
return PublishCommandAsync(command);
}
private dynamic GetCommand(string commandTypeName)
{
2013-09-11 06:33:47 +00:00
var commandType = _serviceFactory.GetImplementations(typeof(Command))
.Single(c => c.FullName.Equals(commandTypeName, StringComparison.InvariantCultureIgnoreCase));
return Json.Deserialize("{}", commandType);
}
2013-09-11 06:33:47 +00:00
private void ExecuteCommand<TCommand>(Command command) where TCommand : Command
{
var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType());
2013-05-21 02:49:08 +00:00
var handler = (IExecute<TCommand>)_serviceFactory.Build(handlerContract);
2013-09-11 06:33:47 +00:00
_logger.Trace("{0} -> {1}", command.GetType().Name, handler.GetType().Name);
try
{
2013-09-11 06:33:47 +00:00
_trackCommands.Start(command);
2013-09-14 23:43:03 +00:00
BroadcastCommandUpdate(command);
2013-09-11 06:33:47 +00:00
if (!MappedDiagnosticsContext.Contains("CommandId") && command.SendUpdatesToClient)
{
2013-09-11 06:33:47 +00:00
MappedDiagnosticsContext.Set("CommandId", command.Id.ToString());
}
2013-08-30 16:18:12 +00:00
2013-09-11 06:33:47 +00:00
handler.Execute((TCommand)command);
_trackCommands.Completed(command);
}
2013-05-21 02:49:08 +00:00
catch (Exception e)
{
2013-09-11 06:33:47 +00:00
_trackCommands.Failed(command, e);
throw;
}
finally
{
2013-09-14 23:43:03 +00:00
BroadcastCommandUpdate(command);
2013-09-14 23:34:21 +00:00
_eventAggregator.PublishEvent(new CommandExecutedEvent(command));
if (MappedDiagnosticsContext.Get("CommandId") == command.Id.ToString())
{
MappedDiagnosticsContext.Remove("CommandId");
}
}
2013-09-11 06:33:47 +00:00
_logger.Trace("{0} <- {1} [{2}]", command.GetType().Name, handler.GetType().Name, command.Runtime.ToString(""));
}
2013-09-14 23:43:03 +00:00
private void BroadcastCommandUpdate(Command command)
{
if (command.SendUpdatesToClient)
{
_eventAggregator.PublishEvent(new CommandUpdatedEvent(command));
}
}
}
}