Global refactoring with ReSharper

This commit is contained in:
2025-07-20 00:20:05 +03:00
parent 5cbfb4d2b1
commit f8998178ff
43 changed files with 157 additions and 280 deletions
-1
View File
@@ -1,6 +1,5 @@
using System.Net; using System.Net;
using Example.Shared; using Example.Shared;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using mROA.Abstract; using mROA.Abstract;
-1
View File
@@ -1,7 +1,6 @@
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
namespace Example.Shared namespace Example.Shared
-1
View File
@@ -1,5 +1,4 @@
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
namespace Example.Shared namespace Example.Shared
-1
View File
@@ -1,5 +1,4 @@
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
namespace Example.Shared namespace Example.Shared
+2 -3
View File
@@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Text;
using mROA.CodegenTools; using mROA.CodegenTools;
using mROA.CodegenTools.Reading; using mROA.CodegenTools.Reading;
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
namespace mROA.Codegen namespace mROA.Codegen
{ {
@@ -314,7 +313,7 @@ namespace mROA.Codegen
parametersInsertList.Add("(CancellationToken)special[1]"); parametersInsertList.Add("(CancellationToken)special[1]");
break; break;
case "RequestContext": case "RequestContext":
parametersInsertList.Add("special[0] as RequestContext"); parametersInsertList.Add("(RequestContext)special[0]");
break; break;
default: default:
parametersInsertList.Add(Caster(parameter.Type, parametersInsertList.Add(Caster(parameter.Type,
@@ -428,7 +427,7 @@ namespace mROA.Codegen
parametersInsertList.Add("(CancellationToken)special[1]"); parametersInsertList.Add("(CancellationToken)special[1]");
break; break;
case "RequestContext": case "RequestContext":
parametersInsertList.Add("special[0] as RequestContext"); parametersInsertList.Add("(RequestContext)special[0]");
break; break;
default: default:
parametersInsertList.Add(Caster(parameter.i, parametersInsertList.Add(Caster(parameter.i,
+1 -1
View File
@@ -13,7 +13,7 @@ namespace mROA.Abstract
ChannelReader<NetworkMessageHeader> TrustedPostChanel { get; } ChannelReader<NetworkMessageHeader> TrustedPostChanel { get; }
ChannelReader<NetworkMessageHeader> UntrustedPostChanel { get; } ChannelReader<NetworkMessageHeader> UntrustedPostChanel { get; }
Func<bool> IsConnected { get; set; } Func<bool> IsConnected { get; set; }
ValueTask<NetworkMessageHeader> GetNextMessageReceiving(bool infinite = true); ValueTask<NetworkMessageHeader> GetNextMessageReceiving();
Task PostMessageAsync(NetworkMessageHeader messageHeader); Task PostMessageAsync(NetworkMessageHeader messageHeader);
Task PostMessageUntrustedAsync(NetworkMessageHeader messageHeader); Task PostMessageUntrustedAsync(NetworkMessageHeader messageHeader);
event Action<int> OnDisconnected; event Action<int> OnDisconnected;
-6
View File
@@ -1,14 +1,8 @@
namespace mROA.Abstract namespace mROA.Abstract
{ {
public delegate void ConnectionHandler(IRepresentationModule representationModule);
public delegate void DisconnectionHandler(IRepresentationModule representationModule);
public interface IConnectionHub public interface IConnectionHub
{ {
void RegisterInteraction(IChannelInteractionModule interaction); void RegisterInteraction(IChannelInteractionModule interaction);
IChannelInteractionModule GetInteraction(int id); IChannelInteractionModule GetInteraction(int id);
event ConnectionHandler? OnConnected;
event DisconnectionHandler? OnDisconnected;
} }
} }
@@ -9,8 +9,6 @@ namespace mROA.Abstract
T Deserialize<T>(byte[] rawData, IEndPointContext? context); T Deserialize<T>(byte[] rawData, IEndPointContext? context);
object? Deserialize(byte[] rawData, Type type, IEndPointContext? context); object? Deserialize(byte[] rawData, Type type, IEndPointContext? context);
T Deserialize<T>(ReadOnlyMemory<byte> rawMemory, IEndPointContext? context); T Deserialize<T>(ReadOnlyMemory<byte> rawMemory, IEndPointContext? context);
object? Deserialize(ReadOnlyMemory<byte> rawMemory, Type type, IEndPointContext? context);
T Cast<T>(object nonCasted, IEndPointContext? context);
object? Cast(object? nonCasted, Type type, IEndPointContext? context); object? Cast(object? nonCasted, Type type, IEndPointContext? context);
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
namespace mROA.Abstract namespace mROA.Abstract
{ {
public interface IEventBinder<T> : IEventBinder public interface IEventBinder<in T> : IEventBinder
{ {
public void BindEvents(T source, IEndPointContext context, public void BindEvents(T source, IEndPointContext context,
IRepresentationModuleProducer representationModuleProducer, int index); IRepresentationModuleProducer representationModuleProducer, int index);
-8
View File
@@ -1,8 +0,0 @@
namespace mROA.Abstract
{
public interface IOwnershipRepository
{
int GetOwnershipId();
int GetHostOwnershipId();
}
}
@@ -2,6 +2,5 @@ namespace mROA.Abstract
{ {
public interface IRealStoreInstanceRepository : IInstanceRepository public interface IRealStoreInstanceRepository : IInstanceRepository
{ {
} }
} }
-9
View File
@@ -1,9 +0,0 @@
using mROA.Implementation;
namespace mROA.Abstract
{
public interface IRemoteObjectFactory
{
T Produce<T>(ComplexObjectIdentifier id, IEndPointContext context);
}
}
+1 -1
View File
@@ -9,6 +9,6 @@ namespace mROA.Abstract
Task StartExtraction(); Task StartExtraction();
void PushMessage(object parced, EMessageType originalType); void PushMessage(object parced, EMessageType originalType);
Predicate<NetworkMessageHeader> Rule { get; } Predicate<NetworkMessageHeader> Rule { get; }
Func<NetworkMessageHeader,Type?>[] Converters { get; } Func<NetworkMessageHeader, Type?>[] Converters { get; }
} }
} }
@@ -1,6 +1,5 @@
using System; using System;
using System.Threading; using System.Threading;
using Microsoft.Extensions.Logging;
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation.CommandExecution; using mROA.Implementation.CommandExecution;
@@ -11,14 +10,13 @@ namespace mROA.Implementation.Backend
private readonly ICancellationRepository _cancellationRepo; private readonly ICancellationRepository _cancellationRepo;
private readonly IMethodRepository _methodRepo; private readonly IMethodRepository _methodRepo;
private readonly IContextualSerializationToolKit _serialization; private readonly IContextualSerializationToolKit _serialization;
private readonly ILogger<BasicExecutionModule> _logger;
public BasicExecutionModule(ICancellationRepository cancellationRepo, IMethodRepository methodRepo, IContextualSerializationToolKit serialization, ILogger<BasicExecutionModule> logger) public BasicExecutionModule(ICancellationRepository cancellationRepo, IMethodRepository methodRepo,
IContextualSerializationToolKit serialization)
{ {
_cancellationRepo = cancellationRepo; _cancellationRepo = cancellationRepo;
_methodRepo = methodRepo; _methodRepo = methodRepo;
_serialization = serialization; _serialization = serialization;
_logger = logger;
} }
public ICommandExecution Execute(ICallRequest command, IInstanceRepository instanceRepository, public ICommandExecution Execute(ICallRequest command, IInstanceRepository instanceRepository,
@@ -36,9 +34,9 @@ namespace mROA.Implementation.Backend
if (invoker == null) if (invoker == null)
throw new Exception($"Command {command.CommandId} not found"); throw new Exception($"Command {command.CommandId} not found");
var context = GetContext(command, instanceRepository, invoker, endPointContext); var instance = GetInstance(command, instanceRepository, invoker, endPointContext);
if (context == null) if (instance is null)
throw new NullReferenceException("Instance can't be null"); throw new NullReferenceException("Instance can't be null");
@@ -50,24 +48,10 @@ namespace mROA.Implementation.Backend
var execContext = new RequestContext(command.Id, representationModule.Id); var execContext = new RequestContext(command.Id, representationModule.Id);
switch (invoker) var executionResult = ExecuteRequest(command, instanceRepository, representationModule, endPointContext,
{ invoker,
case AsyncMethodInvoker { IsVoid: false } asyncNonVoidMethodInvoker: instance, castedParams, execContext);
return TypedExecuteAsync(asyncNonVoidMethodInvoker, context, castedParams, command, return executionResult;
_cancellationRepo,
representationModule, execContext, endPointContext);
case AsyncMethodInvoker asyncMethodInvoker:
return ExecuteAsync(asyncMethodInvoker, context, castedParams, command, _cancellationRepo,
representationModule, execContext, endPointContext);
default:
var result = Execute((invoker as MethodInvoker)!, context, castedParams!, command, execContext);
if (command.CommandId == -1)
{
instanceRepository.ClearObject(command.ObjectId, endPointContext);
}
return result;
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -79,12 +63,37 @@ namespace mROA.Implementation.Backend
} }
} }
private static object GetContext(ICallRequest command, IInstanceRepository instanceRepository, private ICommandExecution ExecuteRequest(ICallRequest command, IInstanceRepository instanceRepository,
IRepresentationModule representationModule, IEndPointContext endPointContext, IMethodInvoker invoker,
object context, object?[]? castedParams, RequestContext execContext)
{
switch (invoker)
{
case AsyncMethodInvoker { IsVoid: false } asyncNonVoidMethodInvoker:
return TypedExecuteAsync(asyncNonVoidMethodInvoker, context, castedParams, command,
_cancellationRepo,
representationModule, execContext, endPointContext);
case AsyncMethodInvoker asyncMethodInvoker:
return ExecuteAsync(asyncMethodInvoker, context, castedParams, command, _cancellationRepo,
representationModule, execContext, endPointContext);
default:
var result = Execute((invoker as MethodInvoker)!, context, castedParams!, command, execContext);
if (command.CommandId == -1)
{
instanceRepository.ClearObject(command.ObjectId, endPointContext);
}
return result;
}
}
private static object GetInstance(ICallRequest command, IInstanceRepository instanceRepository,
IMethodInvoker invoker, IEndPointContext endPointContext) IMethodInvoker invoker, IEndPointContext endPointContext)
{ {
var context = command.ObjectId.ContextId != -1 var context = command.ObjectId.ContextId != -1
? instanceRepository.GetObject<object>(command.ObjectId, endPointContext) ? instanceRepository.GetObject<object>(command.ObjectId, endPointContext)
: instanceRepository.GetSingletonObject(invoker.SuitableType, endPointContext); : instanceRepository.GetSingletonObject(invoker.SuitableType, endPointContext);
return context; return context;
} }
@@ -116,42 +125,26 @@ namespace mROA.Implementation.Backend
private static ICommandExecution Execute(MethodInvoker invoker, object instance, object?[] parameter, private static ICommandExecution Execute(MethodInvoker invoker, object instance, object?[] parameter,
ICallRequest command, RequestContext executionContext) ICallRequest command, RequestContext executionContext)
{ {
try var finalResult = invoker.Invoke(instance, parameter, new object[] { executionContext });
if (!invoker.IsTrusted)
{ {
var finalResult = invoker.Invoke(instance, parameter, new object[] { executionContext }); return new AsyncCommandExecution();
if (!invoker.IsTrusted)
{
return new AsyncCommandExecution();
}
if (invoker.IsVoid)
{
return new FinalCommandExecution
{
Id = command.Id
};
}
return new FinalCommandExecution<object>
{
Result = finalResult,
Id = command.Id
};
} }
catch (Exception e)
if (invoker.IsVoid)
{ {
if (invoker.IsTrusted) return new FinalCommandExecution
return new ExceptionCommandExecution
{
Id = command.Id,
Exception = e.ToString()
};
return new AsyncCommandExecution
{ {
Id = command.Id Id = command.Id
}; };
} }
return new FinalCommandExecution<object>
{
Result = finalResult,
Id = command.Id
};
} }
private ICommandExecution ExecuteAsync(AsyncMethodInvoker invoker, object instance, object?[]? parameters, private ICommandExecution ExecuteAsync(AsyncMethodInvoker invoker, object instance, object?[]? parameters,
@@ -162,43 +155,27 @@ namespace mROA.Implementation.Backend
cancellationRepository.RegisterCancellation(command.Id, tokenSource); cancellationRepository.RegisterCancellation(command.Id, tokenSource);
var token = tokenSource.Token; var token = tokenSource.Token;
try invoker.Invoke(instance, parameters, new object[] { executionContext, token }, _ =>
{ {
invoker.Invoke(instance, parameters, new object[] { executionContext, token }, _ => if (token.IsCancellationRequested)
{ return;
if (token.IsCancellationRequested)
return;
var payload = new FinalCommandExecution var payload = new FinalCommandExecution
{
Id = command.Id
};
_cancellationRepo?.FreeCancelation(command.Id);
if (invoker.IsTrusted)
representationModule.PostCallMessage(command.Id, EMessageType.FinishedCommandExecution,
payload, context);
});
return new AsyncCommandExecution
{ {
Id = command.Id Id = command.Id
}; };
} _cancellationRepo.FreeCancelation(command.Id);
catch (Exception e)
{
if (invoker.IsTrusted) if (invoker.IsTrusted)
return new ExceptionCommandExecution representationModule.PostCallMessage(command.Id, EMessageType.FinishedCommandExecution,
{ payload, context);
Id = command.Id, });
Exception = e.ToString()
}; return new AsyncCommandExecution
return new AsyncCommandExecution {
{ Id = command.Id
Id = command.Id };
};
}
} }
private ICommandExecution TypedExecuteAsync(AsyncMethodInvoker invoker, object instance, object?[]? parameters, private ICommandExecution TypedExecuteAsync(AsyncMethodInvoker invoker, object instance, object?[]? parameters,
@@ -209,35 +186,25 @@ namespace mROA.Implementation.Backend
cancellationRepository.RegisterCancellation(command.Id, tokenSource); cancellationRepository.RegisterCancellation(command.Id, tokenSource);
var token = tokenSource.Token; var token = tokenSource.Token;
try
{ invoker.Invoke(instance, parameters, new object[] { executionContext, token },
invoker.Invoke(instance, parameters, new object[] { executionContext, token }, finalResult =>
finalResult => {
var payload = new FinalCommandExecution<object>
{ {
var payload = new FinalCommandExecution<object> Id = command.Id,
{ Result = finalResult
Id = command.Id, };
Result = finalResult _cancellationRepo.FreeCancelation(command.Id);
};
_cancellationRepo.FreeCancelation(command.Id);
representationModule.PostCallMessage(command.Id, EMessageType.FinishedCommandExecution, representationModule.PostCallMessage(command.Id, EMessageType.FinishedCommandExecution,
payload, context); payload, context);
}); });
return new AsyncCommandExecution return new AsyncCommandExecution
{
Id = command.Id
};
}
catch (Exception e)
{ {
return new ExceptionCommandExecution Id = command.Id
{ };
Id = command.Id,
Exception = e.ToString()
};
}
} }
} }
} }
@@ -18,8 +18,5 @@ namespace mROA.Implementation.Backend
return _connections!.GetValueOrDefault(id, null) ?? _connections!.GetValueOrDefault(-id, null) ?? return _connections!.GetValueOrDefault(id, null) ?? _connections!.GetValueOrDefault(-id, null) ??
throw new Exception("No connection found"); throw new Exception("No connection found");
} }
public event ConnectionHandler? OnConnected;
public event DisconnectionHandler? OnDisconnected;
} }
} }
@@ -11,7 +11,7 @@ namespace mROA.Implementation.Backend
private readonly IInstanceRepository _remoteContextRepository; private readonly IInstanceRepository _remoteContextRepository;
private readonly IExecuteModule _executeModule; private readonly IExecuteModule _executeModule;
private readonly DistributionOptions _mode; private readonly DistributionOptions _mode;
private Dictionary<int, IRequestExtractor> _producedExtractors = new(); private readonly Dictionary<int, IRequestExtractor> _producedExtractors = new();
public HubRequestExtractor(IRealStoreInstanceRepository contextRepository, public HubRequestExtractor(IRealStoreInstanceRepository contextRepository,
IInstanceRepository remoteContextRepository, IExecuteModule executeModule, IInstanceRepository remoteContextRepository, IExecuteModule executeModule,
@@ -22,8 +22,6 @@ namespace mROA.Implementation.Backend
_storage = new ExtensibleStorage<object>(); _storage = new ExtensibleStorage<object>();
} }
public int HostId { get; set; }
public int ResisterObject<T>(object o, IEndPointContext context) public int ResisterObject<T>(object o, IEndPointContext context)
{ {
var last = _storage.Place(o); var last = _storage.Place(o);
@@ -14,8 +14,6 @@ namespace mROA.Implementation.Backend
_produceRepository = produceRepository; _produceRepository = produceRepository;
} }
public int HostId { get; set; }
public int ResisterObject<T>(object o, IEndPointContext context) public int ResisterObject<T>(object o, IEndPointContext context)
{ {
var repository = GetRepositoryByClientId(context.OwnerId); var repository = GetRepositoryByClientId(context.OwnerId);
@@ -24,7 +24,8 @@ namespace mROA.Implementation.Backend
public NetworkGatewayModule(IOptions<GatewayOptions> options, IIdentityGenerator identityGenerator, public NetworkGatewayModule(IOptions<GatewayOptions> options, IIdentityGenerator identityGenerator,
IContextualSerializationToolKit serialization, ICallIndexProvider callIndexProvider, IConnectionHub hub, IContextualSerializationToolKit serialization, ICallIndexProvider callIndexProvider, IConnectionHub hub,
IOptions<DistributionOptions> distribution, HubRequestExtractor hre, ILogger<ChannelInteractionModule.StreamExtractor> logger) IOptions<DistributionOptions> distribution, HubRequestExtractor hre,
ILogger<ChannelInteractionModule.StreamExtractor> logger)
{ {
_tcpListener = new(options.Value.Endpoint); _tcpListener = new(options.Value.Endpoint);
_identityGenerator = identityGenerator; _identityGenerator = identityGenerator;
@@ -69,7 +70,7 @@ namespace mROA.Implementation.Backend
CallIndexProvider = _callIndexProvider CallIndexProvider = _callIndexProvider
}; };
var streamExtractor = var streamExtractor =
new ChannelInteractionModule.StreamExtractor(client.GetStream(), _serialization, context, _logger); new ChannelInteractionModule.StreamExtractor(client.GetStream(), _serialization, context);
interaction.IsConnected = () => streamExtractor.IsConnected; interaction.IsConnected = () => streamExtractor.IsConnected;
streamExtractor.MessageReceived = async message => streamExtractor.MessageReceived = async message =>
{ {
@@ -124,15 +125,14 @@ namespace mROA.Implementation.Backend
{ {
if (requestExtractor.Rule(message)) if (requestExtractor.Rule(message))
{ {
for (int i = 0; i < converters.Length; i++) for (var i = 0; i < converters.Length; i++)
{ {
var func = converters[i]; var func = converters[i];
if (func(message) is { } t) if (func(message) is not { } t) continue;
{
var deserialized = _serialization.Deserialize(message.Data, t, context); var deserialized = _serialization.Deserialize(message.Data, t, context);
Task.Run(() => requestExtractor.PushMessage(deserialized, message.MessageType)); Task.Run(() => requestExtractor.PushMessage(deserialized, message.MessageType));
break; break;
}
} }
return; return;
@@ -160,7 +160,8 @@ namespace mROA.Implementation.Backend
if (_distribution.DistributionType == EDistributionType.ExtractorFirst) if (_distribution.DistributionType == EDistributionType.ExtractorFirst)
{ {
BindRequestFirstDistribution(recoveryInteraction.Context, recoveryInteraction, streamExtractor, _hre[recoveryInteraction.ConnectionId]); BindRequestFirstDistribution(recoveryInteraction.Context, recoveryInteraction, streamExtractor,
_hre[recoveryInteraction.ConnectionId]);
} }
Task.Run(async () => await streamExtractor.LoopedReceive(cts.Token).ConfigureAwait(false)); Task.Run(async () => await streamExtractor.LoopedReceive(cts.Token).ConfigureAwait(false));
@@ -172,6 +173,5 @@ namespace mROA.Implementation.Backend
public class GatewayOptions public class GatewayOptions
{ {
public IPEndPoint Endpoint { get; set; } public IPEndPoint Endpoint { get; set; }
public Type InteractionModuleType { get; set; }
} }
} }
+2 -1
View File
@@ -18,7 +18,8 @@ namespace mROA.Implementation.Backend
private readonly CancellationTokenSource _tokenSource = new(); private readonly CancellationTokenSource _tokenSource = new();
private readonly IContextualSerializationToolKit _serializationToolkit; private readonly IContextualSerializationToolKit _serializationToolkit;
public UdpGateway(IOptions<GatewayOptions> options, IConnectionHub hub, IContextualSerializationToolKit serializationToolkit) public UdpGateway(IOptions<GatewayOptions> options, IConnectionHub hub,
IContextualSerializationToolKit serializationToolkit)
{ {
_hub = hub; _hub = hub;
_serializationToolkit = serializationToolkit; _serializationToolkit = serializationToolkit;
-3
View File
@@ -1,8 +1,5 @@
using System; using System;
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
namespace mROA.Implementation namespace mROA.Implementation
{ {
public interface ICallRequest public interface ICallRequest
@@ -1,10 +1,8 @@
using System; using System;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Channels; using System.Threading.Channels;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using mROA.Abstract; using mROA.Abstract;
namespace mROA.Implementation namespace mROA.Implementation
@@ -60,10 +58,11 @@ namespace mROA.Implementation
public ChannelReader<NetworkMessageHeader> UntrustedPostChanel => _outputUntrustedChannel.Reader; public ChannelReader<NetworkMessageHeader> UntrustedPostChanel => _outputUntrustedChannel.Reader;
public Func<bool> IsConnected { get; set; } = () => false; public Func<bool> IsConnected { get; set; } = () => false;
public ValueTask<NetworkMessageHeader> GetNextMessageReceiving(bool infinite = true) public ValueTask<NetworkMessageHeader> GetNextMessageReceiving()
{ {
return _receiveReader.ReadAsync(); return _receiveReader.ReadAsync();
} }
private async ValueTask<bool> PostMessageInternal(NetworkMessageHeader messageHeader) private async ValueTask<bool> PostMessageInternal(NetworkMessageHeader messageHeader)
{ {
if (!IsConnected()) if (!IsConnected())
@@ -148,16 +147,14 @@ namespace mROA.Implementation
private readonly IContextualSerializationToolKit _serializationToolkit; private readonly IContextualSerializationToolKit _serializationToolkit;
private readonly Memory<byte> _buffer = new byte[BufferSize]; private readonly Memory<byte> _buffer = new byte[BufferSize];
private readonly IEndPointContext _context; private readonly IEndPointContext _context;
private readonly ILogger _logger;
private readonly byte[] _lenBuffer; private readonly byte[] _lenBuffer;
public StreamExtractor(Stream ioStream, IContextualSerializationToolKit serializationToolkit, public StreamExtractor(Stream ioStream, IContextualSerializationToolKit serializationToolkit,
IEndPointContext context, ILogger logger) IEndPointContext context)
{ {
_ioStream = ioStream; _ioStream = ioStream;
_serializationToolkit = serializationToolkit; _serializationToolkit = serializationToolkit;
_context = context; _context = context;
_logger = logger;
_lenBuffer = new byte[2]; _lenBuffer = new byte[2];
} }
@@ -200,7 +197,6 @@ namespace mROA.Implementation
var sendingSpan = _buffer[..(len + 2)]; var sendingSpan = _buffer[..(len + 2)];
await _ioStream.WriteAsync(sendingSpan, token); await _ioStream.WriteAsync(sendingSpan, token);
// _logger.LogTrace("SEND {0}", message.ToString()); // _logger.LogTrace("SEND {0}", message.ToString());
} }
public async Task SendFromChannel(ChannelReader<NetworkMessageHeader> channel, public async Task SendFromChannel(ChannelReader<NetworkMessageHeader> channel,
@@ -14,10 +14,7 @@ namespace mROA.Implementation
public IMethodInvoker GetMethod(int id) public IMethodInvoker GetMethod(int id)
{ {
if (id == -1) return id == -1 ? MethodInvoker.Dispose : _methods[id];
return MethodInvoker.Dispose;
return _methods[id];
} }
} }
} }
@@ -1,8 +1,6 @@
using System; using System;
using mROA.Abstract; using mROA.Abstract;
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace mROA.Implementation.CommandExecution namespace mROA.Implementation.CommandExecution
{ {
public struct FinalCommandExecution : ICommandExecution public struct FinalCommandExecution : ICommandExecution
@@ -2,7 +2,6 @@ using System;
namespace mROA.Implementation namespace mROA.Implementation
{ {
#pragma warning disable CS8618, CS9264
public struct ComplexObjectIdentifier : IEquatable<ComplexObjectIdentifier> public struct ComplexObjectIdentifier : IEquatable<ComplexObjectIdentifier>
{ {
public int ContextId; public int ContextId;
@@ -14,14 +13,9 @@ namespace mROA.Implementation
OwnerId = ownerId; OwnerId = ownerId;
} }
public static ComplexObjectIdentifier Singleton(int ownerId) => new() { ContextId = -1, OwnerId = ownerId }; public static ComplexObjectIdentifier Null = new() { ContextId = -2, OwnerId = 0 };
public static ComplexObjectIdentifier Null = new ComplexObjectIdentifier { ContextId = -2, OwnerId = 0 };
public static ComplexObjectIdentifier FromFlat(ulong flat) => new() { Flat = flat }; public static ComplexObjectIdentifier FromFlat(ulong flat) => new() { Flat = flat };
public int ClientId => Math.Abs(OwnerId);
public bool IsSererStored => OwnerId > 0;
public bool IsClientStored => OwnerId < 0;
public override string ToString() public override string ToString()
{ {
@@ -6,6 +6,7 @@ namespace mROA.Implementation
{ {
private readonly IConnectionHub _hub; private readonly IConnectionHub _hub;
private readonly IContextualSerializationToolKit _serialization; private readonly IContextualSerializationToolKit _serialization;
public CreativeRepresentationModuleProducer(IConnectionHub hub, IContextualSerializationToolKit serialization) public CreativeRepresentationModuleProducer(IConnectionHub hub, IContextualSerializationToolKit serialization)
{ {
_hub = hub; _hub = hub;
+1 -1
View File
@@ -12,6 +12,6 @@ namespace mROA.Implementation
ClientRecovery, ClientRecovery,
ClientConnect, ClientConnect,
ClientDisconnect, ClientDisconnect,
UntrustedConnect, UntrustedConnect
} }
} }
+1 -1
View File
@@ -6,8 +6,8 @@ namespace mROA.Implementation
{ {
public EndPointContext() public EndPointContext()
{ {
} }
public EndPointContext(IRealStoreInstanceRepository realRepository, IInstanceRepository remoteRepository) public EndPointContext(IRealStoreInstanceRepository realRepository, IInstanceRepository remoteRepository)
{ {
RealRepository = realRepository; RealRepository = realRepository;
+1 -1
View File
@@ -55,7 +55,7 @@ namespace mROA.Implementation
public void Free(int index) public void Free(int index)
{ {
_freePlaces.AddFirst(index); _freePlaces.AddFirst(index);
_array[index] = default; _array[index] = null;
} }
} }
} }
@@ -1,9 +1,8 @@
using System; using System.IO;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation.Backend; using mROA.Implementation.Backend;
@@ -16,20 +15,20 @@ namespace mROA.Implementation.Frontend
private readonly IPEndPoint _serverEndPoint; private readonly IPEndPoint _serverEndPoint;
private TcpClient _tcpClient = new(); private TcpClient _tcpClient = new();
private readonly IChannelInteractionModule _interactionModule; private readonly IChannelInteractionModule _interactionModule;
private readonly ILogger _logger;
private readonly IContextualSerializationToolKit _serialization; private readonly IContextualSerializationToolKit _serialization;
private ChannelInteractionModule.StreamExtractor? _currentExtractor; private ChannelInteractionModule.StreamExtractor _currentExtractor;
private CancellationTokenSource _rawExtractorCancellation; private CancellationTokenSource _rawExtractorCancellation;
private readonly IEndPointContext _context; private readonly IEndPointContext _context;
public NetworkFrontendBridge(IOptions<GatewayOptions> options, IEndPointContext context, IContextualSerializationToolKit serialization, IChannelInteractionModule interactionModule, ILogger<ChannelInteractionModule.StreamExtractor> logger) public NetworkFrontendBridge(IOptions<GatewayOptions> options, IEndPointContext context,
IContextualSerializationToolKit serialization, IChannelInteractionModule interactionModule)
{ {
_serverEndPoint = options.Value.Endpoint; _serverEndPoint = options.Value.Endpoint;
_context = context; _context = context;
_serialization = serialization; _serialization = serialization;
_interactionModule = interactionModule; _interactionModule = interactionModule;
_logger = logger;
_rawExtractorCancellation = new CancellationTokenSource(); _rawExtractorCancellation = new CancellationTokenSource();
_currentExtractor = new ChannelInteractionModule.StreamExtractor(Stream.Null, _serialization, context);
} }
public async Task Connect() public async Task Connect()
@@ -38,13 +37,13 @@ namespace mROA.Implementation.Frontend
_tcpClient.NoDelay = true; _tcpClient.NoDelay = true;
PrepareExtractor(); PrepareExtractor();
_interactionModule.IsConnected = () => _currentExtractor.IsConnected; _interactionModule.IsConnected = () => _currentExtractor.IsConnected;
_interactionModule.OnDisconnected += _ => { Reconnect(); }; _interactionModule.OnDisconnected += _ => { Reconnect().ConfigureAwait(false); };
_interactionModule.PostMessageAsync(new NetworkMessageHeader(_serialization, new ClientConnect(), _context)) _interactionModule.PostMessageAsync(new NetworkMessageHeader(_serialization, new ClientConnect(), _context))
.Wait(); .Wait();
_currentExtractor.SingleReceive(); _ = _currentExtractor.SingleReceive().ConfigureAwait(false);
var idMessage = await _interactionModule.GetNextMessageReceiving(false); var idMessage = await _interactionModule.GetNextMessageReceiving();
if (idMessage.MessageType != EMessageType.IdAssigning) if (idMessage.MessageType != EMessageType.IdAssigning)
{ {
@@ -53,7 +52,7 @@ namespace mROA.Implementation.Frontend
} }
Task.Run(async () => await _currentExtractor.LoopedReceive(_rawExtractorCancellation.Token)); _ = Task.Run(async () => await _currentExtractor.LoopedReceive(_rawExtractorCancellation.Token));
var assignment = _serialization.Deserialize<IdAssignment>(idMessage.Data, _context); var assignment = _serialization.Deserialize<IdAssignment>(idMessage.Data, _context);
_interactionModule.ConnectionId = -assignment.Id; _interactionModule.ConnectionId = -assignment.Id;
@@ -64,7 +63,7 @@ namespace mROA.Implementation.Frontend
private void PrepareExtractor() private void PrepareExtractor()
{ {
_currentExtractor = _currentExtractor =
new ChannelInteractionModule.StreamExtractor(_tcpClient.GetStream(), _serialization, _context, _logger); new ChannelInteractionModule.StreamExtractor(_tcpClient.GetStream(), _serialization, _context);
_ = _currentExtractor.SendFromChannel(_interactionModule.TrustedPostChanel, _ = _currentExtractor.SendFromChannel(_interactionModule.TrustedPostChanel,
_rawExtractorCancellation.Token); _rawExtractorCancellation.Token);
@@ -84,7 +83,7 @@ namespace mROA.Implementation.Frontend
PrepareExtractor(); PrepareExtractor();
Task.Run(async () => await _currentExtractor.LoopedReceive(_rawExtractorCancellation.Token)); _ = Task.Run(async () => await _currentExtractor.LoopedReceive(_rawExtractorCancellation.Token));
await _interactionModule.Restart(true); await _interactionModule.Restart(true);
} }
@@ -3,19 +3,18 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using mROA.Abstract; using mROA.Abstract;
// ReSharper disable MethodHasAsyncOverload
namespace mROA.Implementation.Frontend namespace mROA.Implementation.Frontend
{ {
public class RequestExtractor : IRequestExtractor public class RequestExtractor : IRequestExtractor
{ {
private readonly IExecuteModule _executeModule; private readonly IExecuteModule _executeModule;
private readonly IRepresentationModule _representationModule; private readonly IRepresentationModule _representationModule;
private readonly IEndPointContext _context; private readonly IEndPointContext _context;
public RequestExtractor(IExecuteModule executeModule, IRepresentationModule representationModule, IEndPointContext context) public RequestExtractor(IExecuteModule executeModule, IRepresentationModule representationModule,
IEndPointContext context)
{ {
_executeModule = executeModule; _executeModule = executeModule;
_representationModule = representationModule; _representationModule = representationModule;
@@ -53,7 +52,7 @@ namespace mROA.Implementation.Frontend
HandleCancelRequest((parced as CancelRequest)!); HandleCancelRequest((parced as CancelRequest)!);
break; break;
default: default:
return; throw new ArgumentOutOfRangeException();
} }
} }
@@ -61,7 +60,8 @@ namespace mROA.Implementation.Frontend
m.MessageType is EMessageType.CallRequest or EMessageType.CancelRequest m.MessageType is EMessageType.CallRequest or EMessageType.CancelRequest
or EMessageType.EventRequest or EMessageType.ClientDisconnect; or EMessageType.EventRequest or EMessageType.ClientDisconnect;
public Func<NetworkMessageHeader, Type?>[] Converters { get; } = { public Func<NetworkMessageHeader, Type?>[] Converters { get; } =
{
m => m.MessageType == EMessageType.CallRequest ? typeof(DefaultCallRequest) : null, m => m.MessageType == EMessageType.CallRequest ? typeof(DefaultCallRequest) : null,
m => m.MessageType == EMessageType.CancelRequest ? typeof(CancelRequest) : null, m => m.MessageType == EMessageType.CancelRequest ? typeof(CancelRequest) : null,
m => m.MessageType == EMessageType.EventRequest ? typeof(DefaultCallRequest) : null, m => m.MessageType == EMessageType.EventRequest ? typeof(DefaultCallRequest) : null,
@@ -1,24 +0,0 @@
using mROA.Abstract;
namespace mROA.Implementation.Frontend
{
public class StaticOwnershipRepository : IOwnershipRepository
{
private readonly int _id;
public StaticOwnershipRepository(int id)
{
_id = id;
}
public int GetOwnershipId()
{
return _id;
}
public int GetHostOwnershipId()
{
return _id;
}
}
}
@@ -14,7 +14,8 @@ namespace mROA.Implementation.Frontend
private readonly CancellationTokenSource _tokenSource = new(); private readonly CancellationTokenSource _tokenSource = new();
private readonly IEndPointContext _context; private readonly IEndPointContext _context;
public UdpUntrustedInteraction(IContextualSerializationToolKit serializationToolkit, IChannelInteractionModule channelInteractionModule, IEndPointContext context) public UdpUntrustedInteraction(IContextualSerializationToolKit serializationToolkit,
IChannelInteractionModule channelInteractionModule, IEndPointContext context)
{ {
_serializationToolkit = serializationToolkit; _serializationToolkit = serializationToolkit;
_channelInteractionModule = channelInteractionModule; _channelInteractionModule = channelInteractionModule;
+1
View File
@@ -9,6 +9,7 @@ namespace mROA.Implementation
public class ClientRecovery : INetworkMessage public class ClientRecovery : INetworkMessage
{ {
// ReSharper disable once UnusedMember.Global
public ClientRecovery() public ClientRecovery()
{ {
Id = 0; Id = 0;
+1 -6
View File
@@ -1,8 +1,6 @@
using System; using System;
using mROA.Abstract; using mROA.Abstract;
// ReSharper disable UnusedMember.Global
namespace mROA.Implementation namespace mROA.Implementation
{ {
public class NetworkMessageHeader public class NetworkMessageHeader
@@ -16,12 +14,9 @@ namespace mROA.Implementation
{ {
if (obj is null) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false; return obj.GetType() == GetType() && Equals((NetworkMessageHeader)obj);
return Equals((NetworkMessageHeader)obj);
} }
public static readonly NetworkMessageHeader Null = new();
public NetworkMessageHeader() public NetworkMessageHeader()
{ {
Data = Array.Empty<byte>(); Data = Array.Empty<byte>();
@@ -12,7 +12,8 @@ namespace mROA.Implementation
private readonly IRepresentationModuleProducer _representationProducer; private readonly IRepresentationModuleProducer _representationProducer;
public RemoteInstanceRepository(ICallIndexProvider callIndexProvider, IRepresentationModuleProducer representationProducer) public RemoteInstanceRepository(ICallIndexProvider callIndexProvider,
IRepresentationModuleProducer representationProducer)
{ {
_callIndexProvider = callIndexProvider; _callIndexProvider = callIndexProvider;
_representationProducer = representationProducer; _representationProducer = representationProducer;
@@ -60,9 +61,7 @@ namespace mROA.Implementation
var instance = _callIndexProvider.Activators[type](-1, representationModule, context, var instance = _callIndexProvider.Activators[type](-1, representationModule, context,
_callIndexProvider.GetIndices(type))!; _callIndexProvider.GetIndices(type))!;
var remoteObjectBase = instance; _producedProxies.Add(instance);
_producedProxies.Add(remoteObjectBase);
return _producedProxies.Last(); return _producedProxies.Last();
} }
+3 -3
View File
@@ -4,7 +4,6 @@ using System.Threading.Tasks;
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation.CommandExecution; using mROA.Implementation.CommandExecution;
// ReSharper disable UnusedMember.Global
namespace mROA.Implementation namespace mROA.Implementation
{ {
@@ -21,8 +20,7 @@ namespace mROA.Implementation
{ {
if (obj is null) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false; return obj.GetType() == GetType() && Equals((RemoteObjectBase)obj);
return Equals((RemoteObjectBase)obj);
} }
public override int GetHashCode() public override int GetHashCode()
@@ -142,6 +140,8 @@ namespace mROA.Implementation
return; return;
case EMessageType.ExceptionCommandExecution: case EMessageType.ExceptionCommandExecution:
throw (responseRequest.Deserialized as ExceptionCommandExecution)!.GetException(); throw (responseRequest.Deserialized as ExceptionCommandExecution)!.GetException();
default:
throw new ArgumentOutOfRangeException();
} }
} }
+4 -4
View File
@@ -6,7 +6,6 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using mROA.Abstract; using mROA.Abstract;
#pragma warning disable CS8602 // Dereference of a possibly null reference.
namespace mROA.Implementation namespace mROA.Implementation
{ {
@@ -15,7 +14,8 @@ namespace mROA.Implementation
private readonly IChannelInteractionModule _interaction; private readonly IChannelInteractionModule _interaction;
private readonly IContextualSerializationToolKit _serialization; private readonly IContextualSerializationToolKit _serialization;
public RepresentationModule(IChannelInteractionModule interaction, IContextualSerializationToolKit serialization) public RepresentationModule(IChannelInteractionModule interaction,
IContextualSerializationToolKit serialization)
{ {
_interaction = interaction; _interaction = interaction;
_serialization = serialization; _serialization = serialization;
@@ -56,7 +56,7 @@ namespace mROA.Implementation
[EnumeratorCancellation] CancellationToken token = default, [EnumeratorCancellation] CancellationToken token = default,
params Func<NetworkMessageHeader, Type?>[] converter) params Func<NetworkMessageHeader, Type?>[] converter)
{ {
var writer = _interaction?.ReceiveChanel.Writer; var writer = _interaction.ReceiveChanel.Writer;
await foreach (var message in _interaction.ReceiveChanel.Reader.ReadAllAsync(token)) await foreach (var message in _interaction.ReceiveChanel.Reader.ReadAllAsync(token))
{ {
if (!rule(message)) if (!rule(message))
@@ -66,7 +66,7 @@ namespace mROA.Implementation
} }
for (int i = 0; i < converter.Length; i++) for (var i = 0; i < converter.Length; i++)
{ {
var func = converter[i]; var func = converter[i];
if (func(message) is { } t) if (func(message) is { } t)
+1 -1
View File
@@ -2,7 +2,7 @@ using System;
namespace mROA.Implementation namespace mROA.Implementation
{ {
public sealed class RequestContext public struct RequestContext
{ {
public int OwnerId { get; } public int OwnerId { get; }
public Guid RequestId { get; } public Guid RequestId { get; }
-4
View File
@@ -3,14 +3,10 @@ using System.Text.Json.Serialization;
using mROA.Abstract; using mROA.Abstract;
using mROA.Implementation.Attributes; using mROA.Implementation.Attributes;
// ReSharper disable UnusedMember.Global
// #pragma warning disable CS8618, CS9264
namespace mROA.Implementation namespace mROA.Implementation
{ {
public interface ISharedObjectShell public interface ISharedObjectShell
{ {
// ReSharper disable once UnusedMemberInSuper.Global
IEndPointContext EndPointContext { get; set; } IEndPointContext EndPointContext { get; set; }
ComplexObjectIdentifier Identifier { get; set; } ComplexObjectIdentifier Identifier { get; set; }
object UniversalValue { get; set; } object UniversalValue { get; set; }
@@ -1,5 +1,4 @@
using System; using mROA.Abstract;
using mROA.Abstract;
namespace mROA.Implementation namespace mROA.Implementation
{ {
+7 -9
View File
@@ -9,11 +9,11 @@ namespace mROA
{ {
public static async ValueTask<int> ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count) public static async ValueTask<int> ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count)
{ {
return await stream.ReadAtLeastAsyncCore(buffer.AsMemory(offset, count), count, true, default); return await stream.ReadAtLeastAsyncCore(buffer.AsMemory(offset, count), count, true, CancellationToken.None);
} }
public static ValueTask<int> ReadExactlyAsync(this Stream stream, Memory<byte> buffer, public static ValueTask<int> ReadExactlyAsync(this Stream stream, Memory<byte> buffer,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default)
{ {
return stream.ReadAtLeastAsyncCore(buffer, buffer.Length, true, cancellationToken); return stream.ReadAtLeastAsyncCore(buffer, buffer.Length, true, cancellationToken);
} }
@@ -28,13 +28,11 @@ namespace mROA
int num; int num;
for (totalRead = 0; totalRead < minimumBytes; totalRead += num) for (totalRead = 0; totalRead < minimumBytes; totalRead += num)
{ {
num = await stream.ReadAsync(buffer.Slice(totalRead), cancellationToken).ConfigureAwait(false); num = await stream.ReadAsync(buffer[totalRead..], cancellationToken).ConfigureAwait(false);
if (num == 0) if (num != 0) continue;
{ if (throwOnEndOfStream)
if (throwOnEndOfStream) throw new EndOfStreamException();
throw new EndOfStreamException(); return totalRead;
return totalRead;
}
} }
return totalRead; return totalRead;
+5 -5
View File
@@ -26,8 +26,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.7" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.7"/>
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.7" /> <PackageReference Include="Microsoft.Extensions.Options" Version="9.0.7"/>
<PackageReference Include="System.Text.Json" Version="9.0.5"/> <PackageReference Include="System.Text.Json" Version="9.0.5"/>
<PackageReference Include="System.Threading.Channels" Version="9.0.5"/> <PackageReference Include="System.Threading.Channels" Version="9.0.5"/>
</ItemGroup> </ItemGroup>
@@ -40,9 +40,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Extensions.Logging.Abstractions"> <Reference Include="Microsoft.Extensions.Logging.Abstractions">
<HintPath>..\..\..\..\.nuget\packages\microsoft.extensions.logging.abstractions\9.0.7\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath> <HintPath>..\..\..\..\.nuget\packages\microsoft.extensions.logging.abstractions\9.0.7\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
</Project> </Project>