2024-06-24 18:28:40 -04:00
|
|
|
|
using Serilog;
|
|
|
|
|
|
|
|
|
|
namespace CommonSocketLibrary.Abstract
|
|
|
|
|
{
|
2024-08-10 15:31:08 -04:00
|
|
|
|
public interface ICodedOperation
|
|
|
|
|
{
|
|
|
|
|
int OperationCode { get; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public interface IMessageTypeManager
|
|
|
|
|
{
|
|
|
|
|
Type? GetMessageTypeByCode(int code);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public abstract class MessageTypeManager<Handler> : IMessageTypeManager where Handler : ICodedOperation
|
2024-06-24 18:28:40 -04:00
|
|
|
|
{
|
|
|
|
|
private readonly IDictionary<int, Type> _types;
|
|
|
|
|
protected readonly ILogger _logger;
|
|
|
|
|
|
|
|
|
|
|
2024-08-10 15:31:08 -04:00
|
|
|
|
public MessageTypeManager(IEnumerable<Handler> handlers, ILogger logger)
|
2024-06-24 18:28:40 -04:00
|
|
|
|
{
|
|
|
|
|
_types = new Dictionary<int, Type>();
|
|
|
|
|
_logger = logger;
|
|
|
|
|
|
2024-08-10 15:31:08 -04:00
|
|
|
|
GenerateHandlerTypes(handlers);
|
2024-06-24 18:28:40 -04:00
|
|
|
|
}
|
|
|
|
|
|
2024-08-10 15:31:08 -04:00
|
|
|
|
public Type? GetMessageTypeByCode(int code)
|
|
|
|
|
{
|
|
|
|
|
_types.TryGetValue(code, out Type? type);
|
|
|
|
|
return type;
|
|
|
|
|
}
|
2024-06-24 18:28:40 -04:00
|
|
|
|
|
2024-08-10 15:31:08 -04:00
|
|
|
|
private void GenerateHandlerTypes(IEnumerable<Handler> handlers)
|
2024-06-24 18:28:40 -04:00
|
|
|
|
{
|
2024-08-10 15:31:08 -04:00
|
|
|
|
foreach (var handler in handlers)
|
2024-06-24 18:28:40 -04:00
|
|
|
|
{
|
2024-08-10 15:31:08 -04:00
|
|
|
|
if (handler == null)
|
2024-06-24 18:28:40 -04:00
|
|
|
|
{
|
2024-08-10 15:31:08 -04:00
|
|
|
|
_logger.Error($"Failed to link websocket handler due to null value.");
|
2024-06-24 18:28:40 -04:00
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-10 15:31:08 -04:00
|
|
|
|
var type = handler.GetType();
|
2024-06-24 18:28:40 -04:00
|
|
|
|
var target = FetchMessageType(type);
|
|
|
|
|
if (target == null)
|
|
|
|
|
{
|
2024-08-10 15:31:08 -04:00
|
|
|
|
_logger.Error($"Failed to link websocket handler #{handler.OperationCode} due to no match for {target}.");
|
2024-06-24 18:28:40 -04:00
|
|
|
|
continue;
|
|
|
|
|
}
|
2024-08-10 15:31:08 -04:00
|
|
|
|
_types.Add(handler.OperationCode, target);
|
|
|
|
|
_logger.Debug($"Linked websocket handler #{handler.OperationCode} to type {target.AssemblyQualifiedName}.");
|
2024-06-24 18:28:40 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected abstract Type? FetchMessageType(Type handlerType);
|
|
|
|
|
}
|
|
|
|
|
}
|