continuity/Server/Services/PacketDistributorService.cs

144 lines
5.9 KiB
C#
Raw Normal View History

namespace Server.Services;
using System.Collections.Concurrent;
2023-08-09 14:23:41 +00:00
using System.Reflection;
2023-08-09 18:14:14 +00:00
using MassTransit.Internals;
using Microsoft.Extensions.DependencyInjection;
2023-08-09 14:23:41 +00:00
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
2023-08-09 18:14:14 +00:00
using Microsoft.VisualBasic.CompilerServices;
using Newtonsoft.Json;
using PacketHandlers;
using Packets;
using static DotNext.Metaprogramming.CodeGenerator;
using static DotNext.Linq.Expressions.ExpressionBuilder;
2023-08-09 14:23:41 +00:00
public class PacketDistributorService : IHostedService
{
private readonly ConcurrentQueue<RawPacket> concurrentQueue;
private readonly ILogger<PacketDistributorService> logger;
private readonly Dictionary<OperationCode, Type> packetHandlers;
private readonly Dictionary<OperationCode, Func<byte[], IPacket>> deserializationMap;
private readonly IServiceProvider serviceProvider;
2023-08-09 14:23:41 +00:00
2023-08-09 18:14:14 +00:00
public PacketDistributorService(ILogger<PacketDistributorService> logger, IServiceProvider serviceProvider)
2023-08-09 14:23:41 +00:00
{
this.concurrentQueue = new ConcurrentQueue<RawPacket>();
this.logger = logger;
this.serviceProvider = serviceProvider;
this.packetHandlers = new Dictionary<OperationCode, Type>();
this.deserializationMap = new Dictionary<OperationCode, Func<byte[], IPacket>>();
2023-08-09 18:14:14 +00:00
var executingAssembly = Assembly.GetExecutingAssembly();
var packetsTypes = this.GetPacketsWithId(executingAssembly);
this.packetHandlers = this.GetAllPacketHandlersWithId(executingAssembly);
foreach (var packetsType in packetsTypes)
{
var lambda = Lambda<Func<byte[], IPacket>>(fun =>
{
var arg = fun[0];
var newPacket = packetsType.Value.New();
var packetVariable = DeclareVariable(packetsType.Value, "packet");
Assign(packetVariable, newPacket);
2023-08-13 16:29:39 +00:00
Call(packetVariable, nameof(IPacket.Deserialize), arg);
Return(packetVariable);
}).Compile();
logger.LogInformation("Packet creation function created for {Opcode}", packetsType.Key);
this.deserializationMap.Add(packetsType.Key, lambda);
}
}
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
private Dictionary<OperationCode, Type> GetPacketsWithId(Assembly executingAssembly)
{
var packetsWithId = executingAssembly.GetTypes().AsParallel()
.Where(type => type.GetCustomAttribute<PacketIdAttribute>() != null && type.HasInterface(typeof(IPacket)) &&
2023-08-09 18:14:14 +00:00
!type.IsInterface)
.ToDictionary(packet => packet.GetCustomAttribute<PacketIdAttribute>()!.Code);
if (packetsWithId is not { Count: 0 })
2023-08-09 14:23:41 +00:00
{
packetsWithId.AsParallel().ForAll(packet =>
{
this.logger.LogTrace("Packet with ID: {PacketID} has been added as {PacketName}", packet.Key,
packet.Value.FullName);
});
return packetsWithId;
2023-08-09 14:23:41 +00:00
}
2023-08-09 18:14:14 +00:00
this.logger.LogCritical("No Packets have been found");
throw new IncompleteInitialization();
}
2023-08-09 18:14:14 +00:00
private Dictionary<OperationCode, Type> GetAllPacketHandlersWithId(Assembly assembly)
{
var packetHandlersWithId = assembly.GetTypes().AsParallel().Where(t =>
2023-08-09 18:14:14 +00:00
t is { IsClass: true, IsAbstract: false } && t
.GetInterfaces().Any(i =>
i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPacketHandler<>))).ToDictionary(type =>
type.GetInterfaces().First(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IPacketHandler<>))
.GetGenericArguments()[0].GetCustomAttribute<PacketIdAttribute>().Code);
2023-08-09 18:14:14 +00:00
if (packetHandlersWithId is not { Count: 0 })
2023-08-09 18:14:14 +00:00
{
packetHandlersWithId.AsParallel().ForAll(packetHandler =>
{
this.logger.LogTrace("PacketHandler with ID: {PacketID} has been added as {PacketName}",
2023-08-11 09:31:30 +00:00
packetHandler.Key,
packetHandler.Value.FullName);
});
return packetHandlersWithId;
2023-08-09 18:14:14 +00:00
}
this.logger.LogCritical("No PacketHandlers have been found");
throw new IncompleteInitialization();
2023-08-09 14:23:41 +00:00
}
2023-08-09 18:14:14 +00:00
public void AddPacket(RawPacket rawPacket)
2023-08-09 14:23:41 +00:00
{
this.concurrentQueue.Enqueue(rawPacket);
2023-08-12 21:12:59 +00:00
Task.Run(this.DequeueRawPacketAsync);
this.logger.LogInformation("Packet with ID: {MessageOperationCode} has been received",
2023-08-09 18:14:14 +00:00
rawPacket.OperationCode);
2023-08-09 14:23:41 +00:00
}
private async Task DequeueRawPacketAsync()
2023-08-09 14:23:41 +00:00
{
if (this.concurrentQueue.TryDequeue(out var item))
2023-08-09 14:23:41 +00:00
{
2023-08-13 12:22:34 +00:00
ThreadPool.QueueUserWorkItem(this.InvokePacketHandler, item, true);
2023-08-09 18:14:14 +00:00
}
else
{
await Task.Delay(100); // Delay to prevent busy-waiting, can be adjusted based on needs
2023-08-09 14:23:41 +00:00
}
}
2023-08-13 16:29:39 +00:00
private void InvokePacketHandler(RawPacket item)
{
this.logger.LogTrace("[{TempId}] Packet with ID: {MessageOperationCode} is being dequeued",
item.Session.Id, item.OperationCode);
2023-08-13 16:29:39 +00:00
if (!this.deserializationMap.ContainsKey(item.OperationCode))
{
this.logger.LogInformation("Couldn't find Packet type for Id: {Opcode}", item.OperationCode);
return;
}
var packet = this.deserializationMap[item.OperationCode](item.MessageBody);
var packetHandler =
ActivatorUtilities.GetServiceOrCreateInstance(this.serviceProvider,
this.packetHandlers[item.OperationCode]);
packetHandler.GetType().GetMethod("HandleAsync")
2023-08-11 09:31:30 +00:00
?.Invoke(packetHandler, new object[] { packet, item.Session });
this.logger.LogDebug("Packet data {PacketData}", JsonConvert.SerializeObject(packet));
this.logger.LogTrace("[{TempId}] Packet with ID: {MessageOperationCode} has finished",
item.Session.Id,
item.OperationCode);
}
2023-08-11 09:31:30 +00:00
}