Skip to content

Commit

Permalink
fix: ensure commands are processed by all connected clients
Browse files Browse the repository at this point in the history
  • Loading branch information
rdavisau committed Sep 17, 2022
1 parent 8d876cb commit 27585e9
Showing 1 changed file with 15 additions and 6 deletions.
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ImTools;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Tbc.Host.Components.Abstractions;
Expand All @@ -11,7 +12,7 @@ namespace Tbc.Host.Components.CommandProcessor
{
public class CommandProcessor : ComponentBase<CommandProcessor>, ICommandProcessor
{
public List<TbcComponentCommand> Commands { get; set; }
public Dictionary<string, List<TbcComponentCommand>> Commands { get; set; } = new();

public CommandProcessor(ILogger<CommandProcessor> logger) : base(logger)
{
Expand All @@ -22,19 +23,23 @@ public void RegisterCommands(object context)

public void RegisterManyCommands(params object[] context)
{
var key = context is { Length: 1 } && context[0] is IExposeCommands {} iec
? iec.Identifier : Guid.NewGuid().ToString();

var commands = new List<TbcComponentCommand>();

foreach (var obj in context)
commands.AddRange(Descend(obj));

Commands = commands;
Commands[key] = commands;
}

public void PrintCommands()
{
Logger.LogInformation(
JsonConvert.SerializeObject(
Commands
.SelectMany(x => x.Value)
.GroupBy(x => x.ComponentIdentifier, x => x.Command)
.Select(x => new { Component = x.Key, Commands = x.ToList() })
, Formatting.Indented));
Expand All @@ -58,8 +63,9 @@ public async Task<object> HandleCommand(string command)
var handlers =

isCommandForTarget
? Commands.Where(x => x.Command.Command == "run-on-target").ToList()
? Commands.SelectMany(x => x.Value).Where(x => x.Command.Command == "run-on-target").ToList()
: Commands
.SelectMany(x => x.Value)
.Where(x => String.Equals(x.Command.Command, cmd, StringComparison.InvariantCultureIgnoreCase))
.ToList();

Expand All @@ -69,8 +75,11 @@ public async Task<object> HandleCommand(string command)
return null;
}

foreach (var handler in handlers)
await handler.Command.Execute(cmd, args);
foreach (var handler in handlers)
{
try { await handler.Command.Execute(cmd, args); }
catch (Exception ex) { Logger.LogError(ex, "When executing command via handler {@Handler}", handler); }
}

return "cool";
}
Expand All @@ -87,4 +96,4 @@ private IEnumerable<TbcComponentCommand> Descend(object o)
yield return cmd;
}
}
}
}

0 comments on commit 27585e9

Please sign in to comment.