первый пул рефакторинга

This commit is contained in:
2025-02-18 22:06:20 +03:00
parent e1a091e306
commit 4e4cdc4762
21 changed files with 111 additions and 118 deletions
-1
View File
@@ -1,5 +1,4 @@
using Example.Shared; using Example.Shared;
using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
namespace Example.Backend; namespace Example.Backend;
-1
View File
@@ -1,4 +1,3 @@
using Example.Backend;
using Example.Shared; using Example.Shared;
using mROA.Implementation; using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
+20 -19
View File
@@ -1,4 +1,6 @@
using System.Net; using System.Diagnostics;
using System.Net;
using System.Text;
using Example.Frontend; using Example.Frontend;
using Example.Shared; using Example.Shared;
using mROA.Codegen; using mROA.Codegen;
@@ -56,22 +58,21 @@ var names = factory.CollectAllNames();
Thread.Sleep(100); Thread.Sleep(100);
Console.WriteLine(string.Join(", ", names)); Console.WriteLine(string.Join(", ", names));
Console.ReadLine();
// var page = await printer.Value.Print("Test Page", new CancellationToken()); var page = printer.Value.Print("Test Page", new CancellationToken()).GetAwaiter().GetResult();
// var data = page.Value.GetData(); var data = page.Value.GetData();
// Console.WriteLine("Data : {0}", Encoding.UTF8.GetString(data)); Console.WriteLine("Data : {0}", Encoding.UTF8.GetString(data));
//
// var loadSingleton = context.GetSingleObject(typeof(ILoadTest)) as ILoadTest; var loadSingleton = context.GetSingleObject(typeof(ILoadTest)) as ILoadTest;
//
// const int iterations = 10000; const int iterations = 10000;
// var timer = Stopwatch.StartNew(); var timer = Stopwatch.StartNew();
// var x = 0; var x = 0;
// for (int i = 0; i < iterations; i++) for (int i = 0; i < iterations; i++)
// { {
// x = loadSingleton.Next(x); x = loadSingleton.Next(x);
// } }
//
// timer.Stop(); timer.Stop();
// Console.WriteLine("X is {0}", x); Console.WriteLine("X is {0}", x);
// Console.WriteLine("Time : {0}", timer.Elapsed.TotalMilliseconds); Console.WriteLine("Time : {0}", timer.Elapsed.TotalMilliseconds);
+1 -2
View File
@@ -1,5 +1,4 @@
using mROA.Implementation; using mROA.Implementation.Attributes;
using mROA.Implementation.Attributes;
namespace Example.Shared; namespace Example.Shared;
-1
View File
@@ -1,4 +1,3 @@
using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
namespace Example.Shared; namespace Example.Shared;
-2
View File
@@ -1,5 +1,3 @@
using System.Collections.Frozen;
using mROA.Abstract;
using mROA.Implementation; using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
+1 -2
View File
@@ -1,5 +1,4 @@
using System.Collections.Immutable; using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running; using BenchmarkDotNet.Running;
namespace mROA.Benchmark; namespace mROA.Benchmark;
+2 -3
View File
@@ -1,4 +1,3 @@
using System.Windows.Input;
using mROA.Implementation; using mROA.Implementation;
namespace mROA.Abstract; namespace mROA.Abstract;
@@ -24,8 +23,8 @@ public interface IRepresentationModule : IInjectableModule
T GetMessage<T>(Guid? requestId = null, MessageType? messageType = null); T GetMessage<T>(Guid? requestId = null, MessageType? messageType = null);
Task<byte[]> GetRawMessage(Guid? requestId = null, MessageType? messageType = null); Task<byte[]> GetRawMessage(Guid? requestId = null, MessageType? messageType = null);
Task PostCallMessageAsync<T>(Guid id, MessageType messageType, T payload); Task PostCallMessageAsync<T>(Guid id, MessageType messageType, T payload) where T : notnull;
Task PostCallMessageAsync(Guid id, MessageType messageType, object payload, Type payloadType); Task PostCallMessageAsync(Guid id, MessageType messageType, object payload, Type payloadType);
void PostCallMessage<T>(Guid id, MessageType messageType, T payload); void PostCallMessage<T>(Guid id, MessageType messageType, T payload) where T : notnull;
void PostCallMessage(Guid id, MessageType messageType, object payload, Type payloadType); void PostCallMessage(Guid id, MessageType messageType, object payload, Type payloadType);
} }
@@ -1,5 +1,4 @@
using System.Text.Json; using mROA.Abstract;
using mROA.Abstract;
using mROA.Implementation.Frontend; using mROA.Implementation.Frontend;
namespace mROA.Implementation; namespace mROA.Implementation;
@@ -1,6 +1,4 @@
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation.Backend;
using mROA.Implementation.Frontend;
namespace mROA.Implementation; namespace mROA.Implementation;
@@ -1,7 +1,3 @@
using System.Text;
using System.Text.Json;
using mROA.Abstract;
namespace mROA.Implementation.Frontend; namespace mROA.Implementation.Frontend;
// public class JsonFrontendSerialisationModule // public class JsonFrontendSerialisationModule
@@ -1,7 +1,5 @@
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using mROA.Abstract; using mROA.Abstract;
namespace mROA.Implementation.Frontend; namespace mROA.Implementation.Frontend;
@@ -1,5 +1,3 @@
using mROA.Abstract;
namespace mROA.Implementation.Frontend; namespace mROA.Implementation.Frontend;
// public class StreamBasedFrontendInteractionModule : IInteractionModule.IFrontendInteractionModule // public class StreamBasedFrontendInteractionModule : IInteractionModule.IFrontendInteractionModule
@@ -26,12 +26,12 @@ public class JsonSerializationToolkit : ISerializationToolkit
public T Cast<T>(object nonCasted) public T Cast<T>(object nonCasted)
{ {
if (nonCasted is JsonElement jsonElement) return nonCasted switch
return jsonElement.Deserialize<T>()!; {
if (nonCasted is T casted) JsonElement jsonElement => jsonElement.Deserialize<T>()!,
return casted; T casted => casted,
_ => throw new JsonException("Cannot cast object to type " + typeof(T).FullName)
throw new JsonException("Cannot cast object to type " + typeof(T).FullName); };
} }
public object Cast(object nonCasted, Type type) public object Cast(object nonCasted, Type type)
+6 -7
View File
@@ -1,18 +1,17 @@
using System.Text.Json; using System.Text.Json.Serialization;
using System.Text.Json.Serialization;
using mROA.Abstract;
namespace mROA.Implementation; namespace mROA.Implementation;
public class NetworkMessage public class NetworkMessage
{ {
public Guid Id { get; set; } public Guid Id { get; init; }
[JsonConverter(typeof(JsonStringEnumConverter))] [JsonConverter(typeof(JsonStringEnumConverter))]
public MessageType SchemaId { get; set; } public MessageType SchemaId { get; init; }
public byte[] Data { get; set; }
public required byte[] Data { get; init; }
} }
public enum MessageType public enum MessageType
{ {
Unknown, FinishedCommandExecution, ExceptionCommandExecution, AcyncCancelCommandExecution, CallRequest, IdAssigning Unknown, FinishedCommandExecution, ExceptionCommandExecution, AsyncCancelCommandExecution, CallRequest, IdAssigning
} }
@@ -1,5 +1,4 @@
using System.Text; using mROA.Abstract;
using mROA.Abstract;
namespace mROA.Implementation; namespace mROA.Implementation;
@@ -11,7 +10,7 @@ public class NextGenerationInteractionModule : INextGenerationInteractionModule
private Task<NetworkMessage>? _currentReceiving; private Task<NetworkMessage>? _currentReceiving;
private const int BufferSize = ushort.MaxValue; private const int BufferSize = ushort.MaxValue;
private readonly byte[] _buffer = new byte[BufferSize]; private readonly byte[] _buffer = new byte[BufferSize];
private List<NetworkMessage> _messageBuffer = []; private readonly List<NetworkMessage> _messageBuffer = [];
public void Inject<T>(T dependency) public void Inject<T>(T dependency)
@@ -32,13 +31,10 @@ public class NextGenerationInteractionModule : INextGenerationInteractionModule
{ {
// Console.WriteLine(_currentReceiving?.Status); // Console.WriteLine(_currentReceiving?.Status);
if (_currentReceiving == null) if (_currentReceiving != null) return _currentReceiving;
{
_currentReceiving = Task.Run(GetNextMessage); _currentReceiving = Task.Run(GetNextMessage);
return _currentReceiving; return _currentReceiving;
}
return _currentReceiving;
} }
public async Task PostMessage(NetworkMessage message) public async Task PostMessage(NetworkMessage message)
@@ -46,6 +42,9 @@ public class NextGenerationInteractionModule : INextGenerationInteractionModule
if (BaseStream == null) if (BaseStream == null)
throw new NullReferenceException("BaseStream is null"); throw new NullReferenceException("BaseStream is null");
if (_serialization == null)
throw new NullReferenceException("Serialization toolkit is not initialized");
// Console.WriteLine("Sending {0}", JsonSerializer.Serialize(message)); // Console.WriteLine("Sending {0}", JsonSerializer.Serialize(message));
+10 -7
View File
@@ -5,8 +5,8 @@ namespace mROA.Implementation;
public class RemoteContextRepository : IContextRepository public class RemoteContextRepository : IContextRepository
{ {
private IRepresentationModuleProducer _representationProducer; private IRepresentationModuleProducer? _representationProducer;
public static FrozenDictionary<Type, Type> RemoteTypes; public static FrozenDictionary<Type, Type> RemoteTypes = FrozenDictionary<Type, Type>.Empty;
public int ResisterObject(object o) public int ResisterObject(object o)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
@@ -24,16 +24,19 @@ public class RemoteContextRepository : IContextRepository
public T GetObject<T>(int id) public T GetObject<T>(int id)
{ {
if (RemoteTypes.TryGetValue(typeof(T), out var remoteType)) if (_representationProducer == null)
{ throw new NullReferenceException("representation producer is not initialized");
var remote = (T)Activator.CreateInstance(remoteType, id, _representationProducer.Produce(TransmissionConfig.OwnershipRepository!.GetOwnershipId()))!;
if (!RemoteTypes.TryGetValue(typeof(T), out var remoteType)) throw new NotSupportedException();
var remote = (T)Activator.CreateInstance(remoteType, id, _representationProducer.Produce(TransmissionConfig.OwnershipRepository.GetOwnershipId()))!;
return remote; return remote;
} }
throw new NotSupportedException();
}
public object GetSingleObject(Type type) public object GetSingleObject(Type type)
{ {
if (_representationProducer == null)
throw new NullReferenceException("representation producer is not initialized");
return Activator.CreateInstance(RemoteTypes[type], -1, _representationProducer.Produce(TransmissionConfig.OwnershipRepository.GetOwnershipId()))!; return Activator.CreateInstance(RemoteTypes[type], -1, _representationProducer.Produce(TransmissionConfig.OwnershipRepository.GetOwnershipId()))!;
} }
+16 -23
View File
@@ -1,32 +1,25 @@
using mROA.Implementation; using mROA.Abstract;
// ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Global
namespace mROA.Abstract; namespace mROA.Implementation;
public abstract class RemoteObjectBase public abstract class RemoteObjectBase(int id, IRepresentationModule representationModule)
{ {
private readonly int _id; public int Id => id;
private readonly IRepresentationModule _representationModule; public int OwnerId => representationModule.Id;
public int Id => _id;
public int OwnerId => _representationModule.Id;
public RemoteObjectBase(int id, IRepresentationModule representationModule) protected async Task<T> GetResultAsync<T>(int methodId, object? parameter = default)
{
_id = id;
_representationModule = representationModule;
}
public async Task<T> GetResultAsync<T>(int methodId, object? parameter = default)
{ {
var request = new DefaultCallRequest var request = new DefaultCallRequest
{ CommandId = methodId, ObjectId = _id, Parameter = parameter, ParameterType = parameter?.GetType() }; { CommandId = methodId, ObjectId = id, Parameter = parameter, ParameterType = parameter?.GetType() };
await _representationModule.PostCallMessageAsync(request.Id, MessageType.CallRequest, request); await representationModule.PostCallMessageAsync(request.Id, MessageType.CallRequest, request);
var successResponse = var successResponse =
_representationModule.GetMessageAsync<FinalCommandExecution<T>>( representationModule.GetMessageAsync<FinalCommandExecution<T>>(
messageType: MessageType.FinishedCommandExecution, requestId: request.Id); messageType: MessageType.FinishedCommandExecution, requestId: request.Id);
var errorResponse = var errorResponse =
_representationModule.GetMessageAsync<ExceptionCommandExecution>( representationModule.GetMessageAsync<ExceptionCommandExecution>(
messageType: MessageType.ExceptionCommandExecution, requestId: request.Id); messageType: MessageType.ExceptionCommandExecution, requestId: request.Id);
Task.WaitAny(successResponse, errorResponse); Task.WaitAny(successResponse, errorResponse);
@@ -36,17 +29,17 @@ public abstract class RemoteObjectBase
throw errorResponse.Result.GetException(); throw errorResponse.Result.GetException();
} }
public async Task CallAsync(int methodId, object? parameter = default) protected async Task CallAsync(int methodId, object? parameter = default)
{ {
var request = new DefaultCallRequest var request = new DefaultCallRequest
{ CommandId = methodId, ObjectId = _id, Parameter = parameter, ParameterType = parameter?.GetType() }; { CommandId = methodId, ObjectId = id, Parameter = parameter, ParameterType = parameter?.GetType() };
await _representationModule.PostCallMessageAsync(request.Id, MessageType.CallRequest, request); await representationModule.PostCallMessageAsync(request.Id, MessageType.CallRequest, request);
var successResponse = var successResponse =
_representationModule.GetMessageAsync<FinalCommandExecution>( representationModule.GetMessageAsync<FinalCommandExecution>(
messageType: MessageType.FinishedCommandExecution, requestId: request.Id); messageType: MessageType.FinishedCommandExecution, requestId: request.Id);
var errorResponse = var errorResponse =
_representationModule.GetMessageAsync<ExceptionCommandExecution>( representationModule.GetMessageAsync<ExceptionCommandExecution>(
messageType: MessageType.ExceptionCommandExecution, requestId: request.Id); messageType: MessageType.ExceptionCommandExecution, requestId: request.Id);
Task.WaitAny(successResponse, errorResponse); Task.WaitAny(successResponse, errorResponse);
+23 -11
View File
@@ -1,12 +1,11 @@
using System.Text.Json; using mROA.Abstract;
using mROA.Abstract;
namespace mROA.Implementation; namespace mROA.Implementation;
public class RepresentationModule : IRepresentationModule public class RepresentationModule : IRepresentationModule
{ {
private ISerializationToolkit _serialization; private ISerializationToolkit? _serialization;
private INextGenerationInteractionModule _interaction; private INextGenerationInteractionModule? _interaction;
public void Inject<T>(T dependency) public void Inject<T>(T dependency)
{ {
@@ -21,20 +20,29 @@ public class RepresentationModule : IRepresentationModule
} }
} }
public int Id => _interaction.ConnectionId; public int Id => (_interaction ?? throw new NullReferenceException("Interaction is not initialized")).ConnectionId;
public async Task<T> GetMessageAsync<T>(Guid? requestId, MessageType? messageType) public async Task<T> GetMessageAsync<T>(Guid? requestId, MessageType? messageType)
{ {
if (_serialization == null)
throw new NullReferenceException("Serialization toolkit is not initialized");
return _serialization.Deserialize<T>(await GetRawMessage(requestId, messageType))!; return _serialization.Deserialize<T>(await GetRawMessage(requestId, messageType))!;
} }
public T GetMessage<T>(Guid? requestId = null, MessageType? messageType = null) public T GetMessage<T>(Guid? requestId = null, MessageType? messageType = null)
{ {
if (_serialization == null)
throw new NullReferenceException("Serialization toolkit is not initialized");
return _serialization.Deserialize<T>(GetRawMessage(requestId, messageType).GetAwaiter().GetResult())!; return _serialization.Deserialize<T>(GetRawMessage(requestId, messageType).GetAwaiter().GetResult())!;
} }
public async Task<byte[]> GetRawMessage(Guid? requestId = null, MessageType? messageType = null) public async Task<byte[]> GetRawMessage(Guid? requestId = null, MessageType? messageType = null)
{ {
if (_interaction == null)
throw new NullReferenceException("Interaction toolkit is not initialized");
var fromBuffer = var fromBuffer =
_interaction.UnhandledMessages.FirstOrDefault(message => _interaction.UnhandledMessages.FirstOrDefault(message =>
(requestId is null || message.Id == requestId) && (requestId is null || message.Id == requestId) &&
@@ -44,31 +52,35 @@ public class RepresentationModule : IRepresentationModule
while (true) while (true)
{ {
var message = await _interaction.GetNextMessageReceiving(); var message = await _interaction.GetNextMessageReceiving();
if ((requestId is null || message.Id == requestId) && if ((requestId is not null && message.Id != requestId) ||
(messageType is null || message.SchemaId == messageType)) (messageType is not null && message.SchemaId != messageType)) continue;
{
_interaction.HandleMessage(message); _interaction.HandleMessage(message);
return message.Data; return message.Data;
} }
} }
}
_interaction.HandleMessage(fromBuffer); _interaction.HandleMessage(fromBuffer);
return fromBuffer.Data; return fromBuffer.Data;
} }
public async Task PostCallMessageAsync<T>(Guid id, MessageType messageType, T payload) public async Task PostCallMessageAsync<T>(Guid id, MessageType messageType, T payload) where T : notnull
{ {
await PostCallMessageAsync(id, messageType, payload, typeof(T)); await PostCallMessageAsync(id, messageType, payload, typeof(T));
} }
public async Task PostCallMessageAsync(Guid id, MessageType messageType, object payload, Type payloadType) public async Task PostCallMessageAsync(Guid id, MessageType messageType, object payload, Type payloadType)
{ {
if (_interaction == null)
throw new NullReferenceException("Interaction toolkit is not initialized");
if (_serialization == null)
throw new NullReferenceException("Serialization toolkit is not initialized");
await _interaction.PostMessage(new NetworkMessage await _interaction.PostMessage(new NetworkMessage
{ Id = id, SchemaId = messageType, Data = _serialization.Serialize(payload, payloadType) }); { Id = id, SchemaId = messageType, Data = _serialization.Serialize(payload, payloadType) });
} }
public void PostCallMessage<T>(Guid id, MessageType messageType, T payload) public void PostCallMessage<T>(Guid id, MessageType messageType, T payload) where T : notnull
{ {
PostCallMessageAsync(id, messageType, payload).GetAwaiter().GetResult(); PostCallMessageAsync(id, messageType, payload).GetAwaiter().GetResult();
} }
+9 -6
View File
@@ -1,5 +1,7 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using mROA.Abstract; using mROA.Abstract;
// ReSharper disable UnusedMember.Global
#pragma warning disable CS8618, CS9264
namespace mROA.Implementation; namespace mROA.Implementation;
@@ -32,7 +34,7 @@ public static class TransmissionConfig
public class SharedObject<T> where T : notnull public class SharedObject<T> where T : notnull
{ {
private IContextRepository GetDefaultContextRepository() => private IContextRepository GetDefaultContextRepository() =>
(OwnerId == TransmissionConfig.OwnershipRepository!.GetHostOwnershipId() (OwnerId == TransmissionConfig.OwnershipRepository.GetHostOwnershipId()
? TransmissionConfig.RealContextRepository ? TransmissionConfig.RealContextRepository
: TransmissionConfig.RemoteEndpointContextRepository) ?? : TransmissionConfig.RemoteEndpointContextRepository) ??
throw new NullReferenceException( throw new NullReferenceException(
@@ -45,10 +47,10 @@ public class SharedObject<T> where T : notnull
{ {
get get
{ {
_ownerId = _ownerId == -1 ? TransmissionConfig.OwnershipRepository!.GetOwnershipId() : _ownerId; _ownerId = _ownerId == -1 ? TransmissionConfig.OwnershipRepository.GetOwnershipId() : _ownerId;
return _ownerId; return _ownerId;
} }
set => _ownerId = value; init => _ownerId = value;
} }
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
@@ -60,7 +62,7 @@ public class SharedObject<T> where T : notnull
if (_contextId != -2) if (_contextId != -2)
return _contextId; return _contextId;
_contextId = TransmissionConfig.RealContextRepository!.GetObjectIndex(Value); _contextId = TransmissionConfig.RealContextRepository.GetObjectIndex(Value);
return _contextId; return _contextId;
} }
init init
@@ -70,9 +72,10 @@ public class SharedObject<T> where T : notnull
} }
} }
[JsonIgnore] public T Value { get; private set; } [JsonIgnore] public T Value { get; private init; }
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once UnusedMember.Global
public SharedObject() public SharedObject()
{ {
} }
@@ -88,7 +91,7 @@ public class SharedObject<T> where T : notnull
_contextId = ro.Id; _contextId = ro.Id;
} }
else else
_ownerId = TransmissionConfig.OwnershipRepository!.GetHostOwnershipId(); _ownerId = TransmissionConfig.OwnershipRepository.GetHostOwnershipId();
} }
public static implicit operator T(SharedObject<T> value) => value.Value; public static implicit operator T(SharedObject<T> value) => value.Value;
@@ -4,16 +4,18 @@ namespace mROA.Implementation;
public class StaticRepresentationModuleProducer : IRepresentationModuleProducer public class StaticRepresentationModuleProducer : IRepresentationModuleProducer
{ {
private IRepresentationModule _reprModule; private IRepresentationModule? _representationModule;
public IRepresentationModule Produce(int ownership) public IRepresentationModule Produce(int ownership)
{ {
return _reprModule; if (_representationModule == null)
throw new NullReferenceException("The representation module is not initialized.");
return _representationModule;
} }
public void Inject<T>(T dependency) public void Inject<T>(T dependency)
{ {
if (dependency is IRepresentationModule serialisationModule) if (dependency is IRepresentationModule serialisationModule)
_reprModule = serialisationModule; _representationModule = serialisationModule;
} }
} }