cs-codex-dist-tests/Tools/TranscriptAnalysis/ReceiverSet.cs

104 lines
2.7 KiB
C#
Raw Normal View History

2024-08-14 12:13:00 +00:00
using CodexPlugin.OverwatchSupport;
using Logging;
2024-08-07 09:18:40 +00:00
using OverwatchTranscript;
using TranscriptAnalysis.Receivers;
namespace TranscriptAnalysis
{
public interface IEventReceiver
{
2024-08-14 12:13:00 +00:00
void Init(ILog log, OverwatchCodexHeader header);
2024-08-07 09:18:40 +00:00
void Finish();
}
public interface IEventReceiver<T> : IEventReceiver
{
void Receive(ActivateEvent<T> @event);
}
public class ReceiverSet
{
private readonly ILog log;
private readonly ITranscriptReader reader;
2024-08-14 12:13:00 +00:00
private readonly OverwatchCodexHeader header;
2024-08-07 09:18:40 +00:00
private readonly List<IEventReceiver> receivers = new List<IEventReceiver>();
2024-08-14 12:13:00 +00:00
public ReceiverSet(ILog log, ITranscriptReader reader, OverwatchCodexHeader header)
2024-08-07 09:18:40 +00:00
{
this.log = log;
this.reader = reader;
2024-08-14 12:13:00 +00:00
this.header = header;
2024-08-07 09:18:40 +00:00
}
public void InitAll()
{
Add(new LogReplaceReceiver());
Add(new DuplicateBlocksReceived());
Add(new NodesDegree());
}
public void FinishAll()
{
foreach (var r in receivers)
{
r.Finish();
}
receivers.Clear();
}
private void Add<T>(IEventReceiver<T> receiver)
{
var mux = GetMux<T>();
mux.Add(receiver);
receivers.Add(receiver);
2024-08-14 12:13:00 +00:00
receiver.Init(log, header);
2024-08-07 09:18:40 +00:00
}
// We use a mux here because, for each time we call reader.AddEventHandler,
// The reader will perform one separate round of JSON deserialization.
// TODO: Move the mux into the reader.
private readonly Dictionary<string, IEventMux> muxes = new Dictionary<string, IEventMux>();
private IEventMux GetMux<T>()
{
var typeName = typeof(T).FullName;
if (string.IsNullOrEmpty(typeName)) throw new Exception("A!");
if (!muxes.ContainsKey(typeName))
{
muxes.Add(typeName, new EventMux<T>(reader));
}
return muxes[typeName];
}
}
public interface IEventMux
{
void Add(IEventReceiver receiver);
}
public class EventMux<T> : IEventMux
{
private readonly List<IEventReceiver<T>> receivers = new List<IEventReceiver<T>>();
public EventMux(ITranscriptReader reader)
{
reader.AddEventHandler<T>(Handle);
}
public void Add(IEventReceiver receiver)
{
if (receiver is IEventReceiver<T> r)
{
receivers.Add(r);
}
}
public void Handle(ActivateEvent<T> @event)
{
foreach (var r in receivers) r.Receive(@event);
}
}
}