Skip to content

Commit

Permalink
Update command bus to use source generation and switch pipeline to Va…
Browse files Browse the repository at this point in the history
…lueTask to reduce allocations
  • Loading branch information
Blackburn29 committed Jul 9, 2024
1 parent e6c3344 commit 2fac9cb
Show file tree
Hide file tree
Showing 107 changed files with 271 additions and 297 deletions.
20 changes: 20 additions & 0 deletions .run/Fragment.NetSlum.Server.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Fragment.NetSlum.Server" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/src/Fragment.NetSlum.Server/bin/Debug/net8.0/Fragment.NetSlum.Server.exe" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/src/Fragment.NetSlum.Server/bin/Debug/net8.0" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/src/Fragment.NetSlum.Server/Fragment.NetSlum.Server.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Commands;

Expand All @@ -13,5 +13,5 @@ namespace Fragment.NetSlum.Core.CommandBus.Contracts.Commands;
public abstract class CommandHandler<TCommand, TResult> : ICommandHandler<TCommand, TResult>, IRequestHandler<TCommand, TResult>
where TCommand : ICommand<TResult>
{
public abstract Task<TResult> Handle(TCommand command, CancellationToken cancellationToken);
public abstract ValueTask<TResult> Handle(TCommand command, CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Commands;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Commands;

public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand<TResult>
{
public Task<TResult> Handle(TCommand command, CancellationToken cancellationToken);
public ValueTask<TResult> Handle(TCommand command, CancellationToken cancellationToken);
}

public interface ICommandHandler<in TCommand> : ICommandHandler<TCommand, Unit> where TCommand : ICommand {}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Events;

Expand All @@ -12,5 +12,5 @@ namespace Fragment.NetSlum.Core.CommandBus.Contracts.Events;
public abstract class EventHandler<TEvent> : IEventHandler<TEvent>, INotificationHandler<TEvent>
where TEvent : IEvent
{
public abstract Task Handle(TEvent eventInfo, CancellationToken cancellationToken);
public abstract ValueTask Handle(TEvent eventInfo, CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Events;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ namespace Fragment.NetSlum.Core.CommandBus.Contracts.Events;

internal interface IEventHandler<in TEvent> where TEvent : IEvent
{
public Task Handle(TEvent eventInfo, CancellationToken cancellationToken);
public ValueTask Handle(TEvent eventInfo, CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Queries;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ namespace Fragment.NetSlum.Core.CommandBus.Contracts.Queries;

public interface IQueryHandler<in TQuery, TResult> where TQuery : IQuery<TResult>
{
public Task<TResult> Handle(TQuery command, CancellationToken cancellationToken);
public ValueTask<TResult> Handle(TQuery command, CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus.Contracts.Queries;

Expand All @@ -13,5 +13,5 @@ namespace Fragment.NetSlum.Core.CommandBus.Contracts.Queries;
public abstract class QueryHandler<TCommand, TResult> : IQueryHandler<TCommand, TResult>, IRequestHandler<TCommand, TResult>
where TCommand : IQuery<TResult>
{
public abstract Task<TResult> Handle(TCommand command, CancellationToken cancellationToken);
public abstract ValueTask<TResult> Handle(TCommand command, CancellationToken cancellationToken);
}
8 changes: 3 additions & 5 deletions src/Fragment.NetSlum.Core/CommandBus/MediatorCommandBus.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using System.Threading;
using System.Threading.Tasks;
using Fragment.NetSlum.Core.CommandBus.Contracts.Commands;
using Fragment.NetSlum.Core.CommandBus.Contracts.Events;
using Fragment.NetSlum.Core.CommandBus.Contracts.Queries;
using MediatR;
using Mediator;

namespace Fragment.NetSlum.Core.CommandBus;

Expand All @@ -24,12 +22,12 @@ public async Task Notify<TEvent>(TEvent eventInfo, CancellationToken cancellatio
await _mediator.Publish(eventInfo, cancellationToken);
}

public async Task<TResult> GetResult<TResult>(IQuery<TResult> query, CancellationToken cancellationToken = default)
public async Task<TResult> GetResult<TResult>(Contracts.Queries.IQuery<TResult> query, CancellationToken cancellationToken = default)
{
return await _mediator.Send(query, cancellationToken);
}

public async Task<TResult> Execute<TResult>(ICommand<TResult> command, CancellationToken cancellationToken = default)
public async Task<TResult> Execute<TResult>(Contracts.Commands.ICommand<TResult> command, CancellationToken cancellationToken = default)
{
return await _mediator.Send(command, cancellationToken);
}
Expand Down
8 changes: 4 additions & 4 deletions src/Fragment.NetSlum.Core/Extensions/IpAddressExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ public static class IpAddressExtensions
/// Private IP CIDR ranges defined by
/// <a href="http://www.faqs.org/rfcs/rfc1918.html">RFC1918</a>
/// </summary>
private static readonly string[] _privateIpCidrs = new string[]
{
private static readonly string[] _privateIpCidrs =
[
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
};
"192.168.0.0/16"
];

/// <summary>
/// Determines if the given <see cref="IPAddress"/> is a private (LAN) IP
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Mediator;
using System;
using System.Linq;
using Fragment.NetSlum.Core.CommandBus;
Expand All @@ -16,18 +17,6 @@ public static class ServiceCollectionExtensions
/// <returns></returns>
public static IServiceCollection AddCommandBus(this IServiceCollection services, params Type[] types)
{
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblies(types.Select(t => t.Assembly).ToArray());
cfg.TypeEvaluator = t =>
{
Log.Information(t.Name);
return true;
};
});

services.AddScoped<ICommandBus, MediatorCommandBus>();

return services;
}
}
6 changes: 3 additions & 3 deletions src/Fragment.NetSlum.Core/Fragment.NetSlum.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
<PackageReference Include="IPNetwork2" Version="3.0.667">
<Aliases>IPNetwork2</Aliases>
</PackageReference>
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.5" />
<PackageReference Include="Mediator.Abstractions" Version="2.1.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Fragment.NetSlum.Networking.Commands.News;

public class MarkNewsArticleReadCommand : ICommand, ICommand<bool>
public class MarkNewsArticleReadCommand : ICommand<bool>
{
public int PlayerId { get; }
public ushort ArticleId { get; }
Expand Down
18 changes: 9 additions & 9 deletions src/Fragment.NetSlum.Networking/Crypto/BlowfishProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class BlowfishProvider
private uint SecretKeyLength => (uint)(_secretKey?.Length ?? 0);

private uint[]? _pArray;
private List<uint[]> _sBoxes = new();
private List<uint[]> _sBoxes = [];

public bool Initialized => _pArray != null && _sBoxes.Count > 0;

Expand Down Expand Up @@ -81,7 +81,7 @@ public void Initialize()
_pArray[i] = DefaultParray[i];
}

_sBoxes = new List<uint[]>();
_sBoxes = [];
for (int i = 0; i < 4; i++)
{
uint[] sBox = new uint[256];
Expand All @@ -108,7 +108,7 @@ public void Initialize()
}

// Encrypt P-Array
uint[] tempChunks = { 0, 0 };
uint[] tempChunks = [0, 0];
for (int i = 0; i < 9; i++)
{
// Encrypt 1st Half
Expand Down Expand Up @@ -206,7 +206,7 @@ public byte[] Decrypt(byte[] payload)
chunkBuffer[0] = BitConverter.ToUInt32(result, i * 8);
chunkBuffer[1] = BitConverter.ToUInt32(result, i * 8 + 4);
// Processing Variables
uint[] tempChunks = { 0, 0 };
uint[] tempChunks = [0, 0];

// Decrypt Chunk
var runningChunk = chunkBuffer[0] ^ _pArray![17];
Expand Down Expand Up @@ -297,7 +297,7 @@ public byte[] Encrypt(byte[] payload)
chunkBuffer[0] = BitConverter.ToUInt32(result, i * 8);
chunkBuffer[1] = BitConverter.ToUInt32(result, i * 8 + 4);
// Processing Variables
uint[] tempChunks = { 0, 0 };
uint[] tempChunks = [0, 0];

// Encrypt Chunk
var runningChunk = chunkBuffer[0] ^ _pArray![0];
Expand Down Expand Up @@ -393,16 +393,16 @@ public static ushort Checksum(byte[] data)
#region defaults

private static readonly uint[] DefaultParray =
{
[
0x25406B89, 0x86A409D4, 0x141A8B2F, 0x04717445,
0xA50A3923, 0x2AA032D1, 0x092FFB99, 0xED4F6D8A,
0x462922E7, 0x39D11478, 0xBF5567D0, 0x35EA0D6D,
0xC1AD2AB8, 0xCA7D51DE, 0x4085D6B6, 0xB6480A18,
0x9317D6DA, 0x8A7AFC1C
};
];

private static readonly uint[] DefaultSboxes =
{
[
0xD2320CA7, 0x99E0B6AD, 0x30FE73DC, 0xD11BE0B8,
0xB9E2B0EE, 0x6B277F97, 0xBB7D9146, 0xF22D809A,
0x25A29A48, 0xB4926DF8, 0x0902F3E3, 0x868FFD17,
Expand Down Expand Up @@ -659,7 +659,7 @@ public static ushort Checksum(byte[] data)
0x1A49C35D, 0x03FC8B8D, 0x02C46BE5, 0xD7ECE2FA,
0x91D5F96A, 0xA75DDFA1, 0x400A262E, 0xC309E7A0,
0xB84F6233, 0xCF78E35C, 0x5890E0E4, 0x3BC473E7
};
];

#endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public static Memory<byte> Replace(this Memory<byte> sourceData, Memory<byte> re
/// <typeparam name="TSession"></typeparam>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static async Task<ICollection<FragmentMessage>> CreateResponse<TSession>(this BaseRequest ro, TSession session, FragmentMessage request)
public static async ValueTask<ICollection<FragmentMessage>> CreateResponse<TSession>(this BaseRequest ro, TSession session, FragmentMessage request)
{
return session switch
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public FragmentPacketHandler(ILogger<FragmentPacketHandler> logger, PacketCache
_packetCache = packetCache;
}

public async Task<ICollection<FragmentMessage>> CreateResponse<TSession>(TSession session, FragmentMessage o) where TSession : IScopeable
public async ValueTask<ICollection<FragmentMessage>> CreateResponse<TSession>(TSession session, FragmentMessage o) where TSession : IScopeable
{
BaseRequest? availableResponseObject = GetRequest(session.ServiceScope.ServiceProvider, o);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ namespace Fragment.NetSlum.Networking.Messaging;

public interface IPacketHandler<TRequest>
{
public Task<ICollection<TRequest>> CreateResponse<TSession>(TSession session, TRequest o) where TSession : IScopeable;
public ValueTask<ICollection<TRequest>> CreateResponse<TSession>(TSession session, TRequest o) where TSession : IScopeable;
}
4 changes: 2 additions & 2 deletions src/Fragment.NetSlum.Networking/Models/ChatLobbyModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public void NotifyAllExcept(ChatLobbyPlayer? sender, List<FragmentMessage> messa
public void NotifyAllExcept(ChatLobbyPlayer? sender, FragmentMessage message)
{
Log.ForContext<ChatLobbyModel>().Debug("Notifying lobby {LobbyName} ({LobbyId}) with data:\n{HexDump}", LobbyName, LobbyId, message.Data.ToHexDump());
NotifyAllExcept(sender, new List<FragmentMessage> { message });
NotifyAllExcept(sender, [message]);
}

/// <summary>
Expand Down Expand Up @@ -220,7 +220,7 @@ public void SendTo(ushort idx, List<FragmentMessage> messages)
/// <param name="message"></param>
public void SendTo(ushort idx, FragmentMessage message)
{
SendTo(idx, new List<FragmentMessage> {message});
SendTo(idx, [message]);
}

private ushort GetAvailablePlayerIndex()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public AreaServerIPAddressPortRequest(ILogger<AreaServerIPAddressPortRequest> lo
_logger = logger;
}

public override Task<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
public override ValueTask<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
{
var ipAddressBytes = new Span<byte>(new byte[4]);
request.Data.Span[..4].CopyTo(ipAddressBytes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public AreaServerPublishDetailsRequest(FragmentContext database, ILogger<AreaSer
_logger = logger;
}

public override Task<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
public override ValueTask<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
{
BaseResponse response;

Expand All @@ -50,17 +50,25 @@ public override Task<ICollection<FragmentMessage>> GetResponse(FragmentTcpSessio
pos += 3;
session.AreaServerInfo.Detail = request.Data[pos..];

response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails1Success, Data = new byte[] { 0x00, 0x01 } };
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails1Success, Data = [0x00, 0x01
]
};
break;
case OpCodes.Data_AreaServerPublishDetails2Request:
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails2Success, Data = new byte[] { 0xDE, 0xAD } };
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails2Success, Data = [0xDE, 0xAD
]
};
break;

case OpCodes.Data_AreaServerPublishDetails3Request:
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails3Success, Data = new byte[] { 0x00, 0x01 } };
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails3Success, Data = [0x00, 0x01
]
};
break;
case OpCodes.Data_AreaServerPublishDetails4Request:
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails4Success, Data = new byte[] { 0x00, 0x01 } };
response = new AreaServerPublishDetailsResponse { PacketType = OpCodes.Data_AreaServerPublishDetails4Success, Data = [0x00, 0x01
]
};
break;
case OpCodes.Data_AreaServerPublishDetails6Request:
//response = new AreaServerPublishDetailsResponse() { PacketType = OpCodes.Data_AreaServerPublishDetails6Success, Data = new byte[] { 0x00, 0x09 } };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public AreaServerPublshRequest(ILogger<AreaServerPublshRequest> logger)
_logger = logger;
}

public override Task<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
public override ValueTask<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
{
BaseResponse response = new AreaServerPublishResponse();
return SingleMessage(response.Build());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public AreaServerUpdateStatusRequest(ILogger<AreaServerUpdateStatusRequest> logg
_logger = logger;
}

public override Task<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
public override ValueTask<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
{
//byte[] diskId = request.Data[0..64].ToArray();
var pos = 0x43;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public AreaServerUpdateUserCountRequest(ILogger<AreaServerUpdateUserCountRequest
_logger = logger;
}

public override Task<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
public override ValueTask<ICollection<FragmentMessage>> GetResponse(FragmentTcpSession session, FragmentMessage request)
{
session.AreaServerInfo!.CurrentPlayerCount = BinaryPrimitives.ReadUInt16BigEndian(request.Data[2..4].ToArray());
return NoResponse();
Expand Down
Loading

0 comments on commit 2fac9cb

Please sign in to comment.