Add SignalR common services and dependencies
This commit is contained in:
parent
9ed82f8f5e
commit
d1ff3af365
|
|
@ -20,6 +20,7 @@
|
|||
<ProjectReference Include="..\AyCode.Interfaces.Server\AyCode.Interfaces.Server.csproj" />
|
||||
<ProjectReference Include="..\AyCode.Interfaces\AyCode.Interfaces.csproj" />
|
||||
<ProjectReference Include="..\AyCode.Models\AyCode.Models.csproj" />
|
||||
<ProjectReference Include="..\AyCode.Services\AyCode.Services.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Reflection;
|
||||
using AyCode.Services.SignalRs;
|
||||
|
||||
namespace AyCode.Models.Server.DynamicMethods;
|
||||
|
||||
public class AcDynamicMethodCallModel<TAttribute> where TAttribute : TagAttribute
|
||||
{
|
||||
public object InstanceObject { get; init; }
|
||||
public ConcurrentDictionary<int, AcMethodInfoModel<TAttribute>> MethodsByMessageTag { get; init; } = new();
|
||||
|
||||
|
||||
public AcDynamicMethodCallModel(Type instanceObjectType) : this(instanceObjectType, null!)
|
||||
{
|
||||
}
|
||||
|
||||
public AcDynamicMethodCallModel(Type instanceObjectType, params object[] constructorParams) : this(Activator.CreateInstance(instanceObjectType, constructorParams)!)
|
||||
{
|
||||
}
|
||||
|
||||
public AcDynamicMethodCallModel(object instanceObject)
|
||||
{
|
||||
InstanceObject = instanceObject;
|
||||
|
||||
foreach (var methodInfo in instanceObject.GetType().GetMethods())
|
||||
{
|
||||
if (methodInfo.GetCustomAttribute(typeof(TAttribute)) is not TAttribute attribute) continue;
|
||||
|
||||
if (MethodsByMessageTag.ContainsKey(attribute.MessageTag))
|
||||
throw new Exception($"Multiple SignaRMessageTag! messageTag: {attribute.MessageTag}; methodName: {methodInfo.Name}");
|
||||
|
||||
MethodsByMessageTag[attribute.MessageTag] = new AcMethodInfoModel<TAttribute>(attribute, methodInfo!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
using System.Reflection;
|
||||
using AyCode.Services.SignalRs;
|
||||
|
||||
namespace AyCode.Models.Server.DynamicMethods;
|
||||
|
||||
public class AcMethodInfoModel<TAttribute> where TAttribute : TagAttribute
|
||||
{
|
||||
public ParameterInfo[]? ParamInfos { get; init; } = null;
|
||||
public TAttribute Attribute { get; init; }
|
||||
public MethodInfo MethodInfo { get; init; }
|
||||
|
||||
public AcMethodInfoModel(TAttribute attribute, MethodInfo methodInfo)
|
||||
{
|
||||
Attribute = attribute;
|
||||
MethodInfo = methodInfo;
|
||||
|
||||
var parameters = methodInfo.GetParameters();
|
||||
|
||||
//if (parameters.Length > 1)
|
||||
// throw new Exception("MethodInfoModel; parameters.Length > 1");
|
||||
|
||||
ParamInfos = parameters;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,9 @@
|
|||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="9.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="9.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Common" Version="9.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson" Version="9.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.8" />
|
||||
<PackageReference Include="SendGrid" Version="9.29.3" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public class AcSessionService<TSessionItem, TSessionItemId> where TSessionItem : IAcSessionItem<TSessionItemId> where TSessionItemId : notnull
|
||||
{
|
||||
public ConcurrentDictionary<TSessionItemId, TSessionItem> Sessions { get; private set; } = [];
|
||||
|
||||
public AcSessionService()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,283 @@
|
|||
using System.Collections.Concurrent;
|
||||
using AyCode.Core;
|
||||
using AyCode.Core.Extensions;
|
||||
using AyCode.Core.Helpers;
|
||||
using AyCode.Core.Loggers;
|
||||
using AyCode.Interfaces.Entities;
|
||||
using AyCode.Services.SignalRs;
|
||||
using MessagePack.Resolvers;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
|
||||
namespace AyCode.Services.Server.SignalRs
|
||||
{
|
||||
public abstract class AcSignalRClientBase : IAcSignalRHubClient
|
||||
{
|
||||
private readonly ConcurrentDictionary<int, SignalRRequestModel> _responseByRequestId = new();
|
||||
|
||||
protected readonly HubConnection HubConnection;
|
||||
protected readonly AcLoggerBase Logger;
|
||||
|
||||
public event Action<int, byte[], int?> OnMessageReceived = null!;
|
||||
//public event Action<int, int> OnMessageRequested;
|
||||
|
||||
public int Timeout = 10000;
|
||||
private const string TagsName = "SignalRTags";
|
||||
|
||||
protected AcSignalRClientBase(string fullHubName, AcLoggerBase logger)
|
||||
{
|
||||
Logger = logger;
|
||||
|
||||
HubConnection = new HubConnectionBuilder()
|
||||
.WithUrl(fullHubName)
|
||||
//.AddMessagePackProtocol(options => {
|
||||
// options.SerializerOptions = MessagePackSerializerOptions.Standard
|
||||
// .WithResolver(MessagePack.Resolvers.StandardResolver.Instance)
|
||||
// .WithSecurity(MessagePackSecurity.UntrustedData)
|
||||
// .WithCompression(MessagePackCompression.Lz4Block)
|
||||
// .WithCompressionMinLength(256);})
|
||||
.Build();
|
||||
|
||||
HubConnection.Closed += HubConnection_Closed;
|
||||
|
||||
_ = HubConnection.On<int, byte[], int?>(nameof(IAcSignalRHubClient.OnReceiveMessage), OnReceiveMessage);
|
||||
//_ = HubConnection.On<int, int>(nameof(IAcSignalRHubClient.OnRequestMessage), OnRequestMessage);
|
||||
|
||||
HubConnection.StartAsync().Forget();
|
||||
}
|
||||
|
||||
private Task HubConnection_Closed(Exception? arg)
|
||||
{
|
||||
if (_responseByRequestId.IsEmpty) Logger.DebugConditional($"Client HubConnection_Closed");
|
||||
else Logger.Warning($"Client HubConnection_Closed; {nameof(_responseByRequestId)} count: {_responseByRequestId.Count}");
|
||||
|
||||
_responseByRequestId.Clear();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task StartConnection()
|
||||
{
|
||||
if (HubConnection.State == HubConnectionState.Disconnected)
|
||||
await HubConnection.StartAsync();
|
||||
|
||||
if (HubConnection.State != HubConnectionState.Connected)
|
||||
await TaskHelper.WaitToAsync(() => HubConnection.State == HubConnectionState.Connected, Timeout, 10, 25);
|
||||
}
|
||||
|
||||
public async Task StopConnection()
|
||||
{
|
||||
await HubConnection.StopAsync();
|
||||
await HubConnection.DisposeAsync();
|
||||
}
|
||||
|
||||
public virtual Task SendMessageToServerAsync(int messageTag)
|
||||
=> SendMessageToServerAsync(messageTag, null, AcDomain.NextUniqueInt32);
|
||||
|
||||
public virtual Task SendMessageToServerAsync(int messageTag, ISignalRMessage? message, int? requestId)
|
||||
{
|
||||
Logger.DebugConditional($"Client SendMessageToServerAsync; {nameof(requestId)}: {requestId}; {ConstHelper.NameByValue(TagsName, messageTag)}");
|
||||
|
||||
return StartConnection().ContinueWith(_ =>
|
||||
{
|
||||
var msgp = message?.ToMessagePack(ContractlessStandardResolver.Options);
|
||||
return HubConnection.SendAsync(nameof(IAcSignalRHubClient.OnReceiveMessage), messageTag, msgp, requestId);
|
||||
});
|
||||
}
|
||||
|
||||
#region CRUD
|
||||
public virtual Task<TResponseData?> GetByIdAsync<TResponseData>(int messageTag, object id) //where TResponseData : class
|
||||
=> SendMessageToServerAsync<TResponseData>(messageTag, new SignalPostJsonDataMessage<IdMessage>(new IdMessage(id)), AcDomain.NextUniqueInt32);
|
||||
public virtual Task GetByIdAsync<TResponseData>(int messageTag, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback, object id)
|
||||
=> SendMessageToServerAsync(messageTag, new SignalPostJsonDataMessage<IdMessage>(new IdMessage(id)), responseCallback);
|
||||
|
||||
public virtual Task<TResponseData?> GetByIdAsync<TResponseData>(int messageTag, object[] ids) //where TResponseData : class
|
||||
=> SendMessageToServerAsync<TResponseData>(messageTag, new SignalPostJsonDataMessage<IdMessage>(new IdMessage(ids)), AcDomain.NextUniqueInt32);
|
||||
public virtual Task GetByIdAsync<TResponseData>(int messageTag, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback, object[] ids)
|
||||
=> SendMessageToServerAsync(messageTag, new SignalPostJsonDataMessage<IdMessage>(new IdMessage(ids)), responseCallback);
|
||||
|
||||
public virtual Task<TResponseData?> GetAllAsync<TResponseData>(int messageTag) //where TResponseData : class
|
||||
=> SendMessageToServerAsync<TResponseData>(messageTag);
|
||||
public virtual Task GetAllAsync<TResponseData>(int messageTag, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback)
|
||||
=> SendMessageToServerAsync(messageTag, null, responseCallback);
|
||||
|
||||
public virtual Task GetAllAsync<TResponseData>(int messageTag, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback, object[]? contextParams)
|
||||
=> SendMessageToServerAsync(messageTag, (contextParams == null || contextParams.Length == 0 ? null : new SignalPostJsonDataMessage<IdMessage>(new IdMessage(contextParams))), responseCallback);
|
||||
public virtual Task<TResponseData?> GetAllAsync<TResponseData>(int messageTag, object[]? contextParams) //where TResponseData : class
|
||||
=> SendMessageToServerAsync<TResponseData>(messageTag, contextParams == null || contextParams.Length == 0 ? null : new SignalPostJsonDataMessage<IdMessage>(new IdMessage(contextParams)), AcDomain.NextUniqueInt32);
|
||||
|
||||
public virtual Task<TPostData?> PostDataAsync<TPostData>(int messageTag, TPostData postData) where TPostData : class
|
||||
=> SendMessageToServerAsync<TPostData>(messageTag, new SignalPostJsonDataMessage<TPostData>(postData), AcDomain.NextUniqueInt32);
|
||||
public virtual Task<TResponseData?> PostDataAsync<TPostData, TResponseData>(int messageTag, TPostData postData) //where TPostData : class where TResponseData : class
|
||||
=> SendMessageToServerAsync<TResponseData>(messageTag, new SignalPostJsonDataMessage<TPostData>(postData), AcDomain.NextUniqueInt32);
|
||||
|
||||
public virtual Task PostDataAsync<TPostData>(int messageTag, TPostData postData, Func<ISignalResponseMessage<TPostData?>, Task> responseCallback) //where TPostData : class
|
||||
=> SendMessageToServerAsync(messageTag, new SignalPostJsonDataMessage<TPostData>(postData), responseCallback);
|
||||
public virtual Task PostDataAsync<TPostData, TResponseData>(int messageTag, TPostData postData, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback) //where TPostData : class where TResponseData : class
|
||||
=> SendMessageToServerAsync(messageTag, new SignalPostJsonDataMessage<TPostData>(postData), responseCallback);
|
||||
|
||||
public Task GetAllIntoAsync<TResponseItem>(List<TResponseItem> intoList, int messageTag, object[]? contextParams = null, Action? callback = null) where TResponseItem : IEntityGuid
|
||||
{
|
||||
return GetAllAsync<List<TResponseItem>>(messageTag, response =>
|
||||
{
|
||||
var logText = $"GetAllIntoAsync<{typeof(TResponseItem).Name}>(); status: {response.Status}; dataCount: {response.ResponseData?.Count}; {ConstHelper.NameByValue(TagsName, messageTag)};";
|
||||
|
||||
intoList.Clear();
|
||||
|
||||
if (response.Status == SignalResponseStatus.Success && response.ResponseData != null)
|
||||
{
|
||||
Logger.Debug(logText);
|
||||
intoList.AddRange(response.ResponseData);
|
||||
}
|
||||
else Logger.Error(logText);
|
||||
|
||||
callback?.Invoke();
|
||||
return Task.CompletedTask;
|
||||
}, contextParams);
|
||||
}
|
||||
|
||||
#endregion CRUD
|
||||
|
||||
public virtual Task<TResponse?> SendMessageToServerAsync<TResponse>(int messageTag) //where TResponse : class
|
||||
=> SendMessageToServerAsync<TResponse>(messageTag, null, AcDomain.NextUniqueInt32);
|
||||
|
||||
public virtual Task<TResponse?> SendMessageToServerAsync<TResponse>(int messageTag, ISignalRMessage? message) //where TResponse : class
|
||||
=> SendMessageToServerAsync<TResponse>(messageTag, message, AcDomain.NextUniqueInt32);
|
||||
|
||||
protected virtual async Task<TResponse?> SendMessageToServerAsync<TResponse>(int messageTag, ISignalRMessage? message, int requestId) //where TResponse : class
|
||||
{
|
||||
Logger.DebugConditional($"Client SendMessageToServerAsync<TResult>; {nameof(requestId)}: {requestId}; {ConstHelper.NameByValue(TagsName, messageTag)}");
|
||||
|
||||
_responseByRequestId[requestId] = new SignalRRequestModel();
|
||||
await SendMessageToServerAsync(messageTag, message, requestId);
|
||||
|
||||
try
|
||||
{
|
||||
if (await TaskHelper.WaitToAsync(() => _responseByRequestId[requestId].ResponseByRequestId != null, Timeout, 25, 50) &&
|
||||
_responseByRequestId.TryRemove(requestId, out var obj) && obj.ResponseByRequestId is ISignalResponseMessage<string> responseMessage)
|
||||
{
|
||||
if (responseMessage.Status == SignalResponseStatus.Error || responseMessage.ResponseData == null)
|
||||
{
|
||||
var errorText = $"Client SendMessageToServerAsync<TResponseData> response error; await; tag: {messageTag}; Status: {responseMessage.Status}; requestId: {requestId};";
|
||||
|
||||
Logger.Error(errorText);
|
||||
|
||||
//TODO: Ideiglenes, majd a ResponseMessage-et kell visszaadni a Status miatt! - J.
|
||||
return await Task.FromException<TResponse>(new Exception(errorText));
|
||||
|
||||
//throw new Exception(errorText);
|
||||
//return default;
|
||||
}
|
||||
|
||||
return responseMessage.ResponseData.JsonTo<TResponse>();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"SendMessageToServerAsync; requestId: {requestId}; {ex.Message}; {ConstHelper.NameByValue(TagsName, messageTag)}", ex);
|
||||
}
|
||||
|
||||
_responseByRequestId.TryRemove(requestId, out _);
|
||||
return default;
|
||||
}
|
||||
|
||||
public virtual Task SendMessageToServerAsync<TResponseData>(int messageTag, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback)
|
||||
=> SendMessageToServerAsync(messageTag, null, responseCallback);
|
||||
|
||||
public virtual Task SendMessageToServerAsync<TResponseData>(int messageTag, ISignalRMessage? message, Func<ISignalResponseMessage<TResponseData?>, Task> responseCallback)
|
||||
{
|
||||
if (messageTag == 0)
|
||||
Logger.Error($"SendMessageToServerAsync; messageTag == 0");
|
||||
|
||||
var requestId = AcDomain.NextUniqueInt32;
|
||||
|
||||
_responseByRequestId[requestId] = new SignalRRequestModel(new Action<ISignalResponseMessage<string>>(responseMessage =>
|
||||
{
|
||||
TResponseData? responseData = default;
|
||||
|
||||
if (responseMessage.Status == SignalResponseStatus.Success)
|
||||
{
|
||||
responseData = string.IsNullOrEmpty(responseMessage.ResponseData) ? default : responseMessage.ResponseData.JsonTo<TResponseData?>();
|
||||
}
|
||||
else Logger.Error($"Client SendMessageToServerAsync<TResponseData> response error; callback; Status: {responseMessage.Status}; requestId: {requestId}; {ConstHelper.NameByValue(TagsName, messageTag)}");
|
||||
|
||||
responseCallback(new SignalResponseMessage<TResponseData?>(messageTag, responseMessage.Status, responseData));
|
||||
}));
|
||||
|
||||
return SendMessageToServerAsync(messageTag, message, requestId);
|
||||
}
|
||||
|
||||
public virtual Task OnReceiveMessage(int messageTag, byte[] message, int? requestId)
|
||||
{
|
||||
var logText = $"Client OnReceiveMessage; {nameof(requestId)}: {requestId}; {ConstHelper.NameByValue(TagsName, messageTag)}";
|
||||
|
||||
if (message.Length == 0) Logger.Warning($"message.Length == 0! {logText}");
|
||||
|
||||
try
|
||||
{
|
||||
if (requestId.HasValue && _responseByRequestId.ContainsKey(requestId.Value))
|
||||
{
|
||||
var reqId = requestId.Value;
|
||||
|
||||
_responseByRequestId[reqId].ResponseDateTime = DateTime.UtcNow;
|
||||
Logger.Info($"[{_responseByRequestId[reqId].ResponseDateTime.Subtract(_responseByRequestId[reqId].RequestDateTime).TotalMilliseconds:N0}ms][{(message.Length/1024)}kb]{logText}");
|
||||
|
||||
var responseMessage = message.MessagePackTo<SignalResponseJsonMessage>(ContractlessStandardResolver.Options);
|
||||
|
||||
switch (_responseByRequestId[reqId].ResponseByRequestId)
|
||||
{
|
||||
case null:
|
||||
_responseByRequestId[reqId].ResponseByRequestId = responseMessage;
|
||||
return Task.CompletedTask;
|
||||
|
||||
case Action<ISignalResponseMessage<string>> messagePackCallback:
|
||||
_responseByRequestId.TryRemove(reqId, out _);
|
||||
|
||||
messagePackCallback.Invoke(responseMessage);
|
||||
return Task.CompletedTask;
|
||||
|
||||
//case Action<string> jsonCallback:
|
||||
// _responseByRequestId.TryRemove(reqId, out _);
|
||||
|
||||
// jsonCallback.Invoke(responseMessage);
|
||||
// return Task.CompletedTask;
|
||||
|
||||
default:
|
||||
Logger.Error($"Client OnReceiveMessage switch; unknown message type: {_responseByRequestId[reqId].ResponseByRequestId?.GetType().Name}; {ConstHelper.NameByValue(TagsName, messageTag)}");
|
||||
break;
|
||||
}
|
||||
|
||||
_responseByRequestId.TryRemove(reqId, out _);
|
||||
}
|
||||
else Logger.Info(logText);
|
||||
|
||||
OnMessageReceived(messageTag, message, requestId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (requestId.HasValue)
|
||||
_responseByRequestId.TryRemove(requestId.Value, out _);
|
||||
|
||||
Logger.Error($"Client OnReceiveMessage; requestId: {requestId}; {ex.Message}; {ConstHelper.NameByValue(TagsName, messageTag)}", ex);
|
||||
throw;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
//public virtual Task OnRequestMessage(int messageTag, int requestId)
|
||||
//{
|
||||
// Logger.DebugConditional($"Client OnRequestMessage; {nameof(messageTag)}: {messageTag}; {nameof(requestId)}: {requestId};");
|
||||
|
||||
// try
|
||||
// {
|
||||
// OnMessageRequested(messageTag, requestId);
|
||||
// }
|
||||
// catch(Exception ex)
|
||||
// {
|
||||
// Logger.Error($"Client OnReceiveMessage; {nameof(messageTag)}: {messageTag}; {nameof(requestId)}: {requestId}; {ex.Message}", ex);
|
||||
// throw;
|
||||
// }
|
||||
|
||||
// return Task.CompletedTask;
|
||||
|
||||
//}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,195 @@
|
|||
using System.Linq.Expressions;
|
||||
using System.Security.Claims;
|
||||
using AyCode.Core;
|
||||
using AyCode.Core.Extensions;
|
||||
using AyCode.Core.Helpers;
|
||||
using AyCode.Core.Loggers;
|
||||
using AyCode.Models.Server.DynamicMethods;
|
||||
using AyCode.Services.SignalRs;
|
||||
using MessagePack;
|
||||
using MessagePack.Resolvers;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public abstract class AcWebSignalRHubBase<TSignalRTags, TLogger>(IConfiguration configuration, TLogger logger)
|
||||
: Hub<IAcSignalRHubItemServer>, IAcSignalRHubServer where TSignalRTags : AcSignalRTags where TLogger : AcLoggerBase
|
||||
{
|
||||
protected readonly List<AcDynamicMethodCallModel<SignalRAttribute>> DynamicMethodCallModels = [];
|
||||
//protected readonly TIAM.Core.Loggers.Logger<AcWebSignalRHubBase<TSignalRTags>> Logger = new(logWriters.ToArray());
|
||||
protected TLogger Logger = logger;
|
||||
protected IConfiguration Configuration = configuration;
|
||||
|
||||
//private readonly ServiceProviderAPIController _serviceProviderApiController;
|
||||
//private readonly TransferDataAPIController _transferDataApiController;
|
||||
|
||||
//_serviceProviderApiController = serviceProviderApiController;
|
||||
//_transferDataApiController = transferDataApiController;
|
||||
|
||||
// https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-3.1#strongly-typed-hubs
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
Logger.Debug($"Server OnConnectedAsync; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}");
|
||||
|
||||
LogContextUserNameAndId();
|
||||
|
||||
await base.OnConnectedAsync();
|
||||
|
||||
//Clients.Caller.ConnectionId = Context.ConnectionId;
|
||||
//Clients.Caller.UserIdentifier = Context.UserIdentifier;
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
var logText = $"Server OnDisconnectedAsync; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier};";
|
||||
|
||||
if (exception == null) Logger.Debug(logText);
|
||||
else Logger.Error(logText, exception);
|
||||
|
||||
LogContextUserNameAndId();
|
||||
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
|
||||
public virtual Task OnReceiveMessage(int messageTag, byte[]? message, int? requestId)
|
||||
{
|
||||
return ProcessOnReceiveMessage(messageTag, message, requestId, null);
|
||||
}
|
||||
|
||||
protected async Task ProcessOnReceiveMessage(int messageTag, byte[]? message, int? requestId, Func<string, Task>? notFoundCallback)
|
||||
{
|
||||
var tagName = ConstHelper.NameByValue<TSignalRTags>(messageTag);
|
||||
var logText = $"Server OnReceiveMessage; {nameof(requestId)}: {requestId}; ConnectionId: {Context.ConnectionId}; {tagName}";
|
||||
|
||||
if (message is { Length: 0 }) Logger.Warning($"message.Length == 0! {logText}");
|
||||
else Logger.Info($"[{message?.Length:N0}b] {logText}");
|
||||
|
||||
try
|
||||
{
|
||||
if (AcDomain.IsDeveloperVersion) LogContextUserNameAndId();
|
||||
|
||||
foreach (var methodsByDeclaringObject in DynamicMethodCallModels)
|
||||
{
|
||||
if (!methodsByDeclaringObject.MethodsByMessageTag.TryGetValue(messageTag, out var methodInfoModel)) continue;
|
||||
|
||||
object[]? paramValues = null;
|
||||
|
||||
logText = $"Found dynamic method for the tag! method: {methodsByDeclaringObject.InstanceObject.GetType().Name}.{methodInfoModel.MethodInfo.Name}";
|
||||
|
||||
if (methodInfoModel.ParamInfos is { Length: > 0 })
|
||||
{
|
||||
Logger.Debug($"{logText}({string.Join(", ", methodInfoModel.ParamInfos.Select(x => x.Name))}); {tagName}");
|
||||
|
||||
paramValues = new object[methodInfoModel.ParamInfos.Length];
|
||||
|
||||
var firstParamType = methodInfoModel.ParamInfos[0].ParameterType;
|
||||
if (methodInfoModel.ParamInfos.Length > 1 || firstParamType == typeof(string) || firstParamType.IsEnum || firstParamType.IsValueType || firstParamType == typeof(DateTime))
|
||||
{
|
||||
var msg = message!.MessagePackTo<SignalPostJsonDataMessage<IdMessage>>();
|
||||
|
||||
for (var i = 0; i < msg.PostData.Ids.Count; i++)
|
||||
{
|
||||
//var obj = (string)msg.PostData.Ids[i];
|
||||
//if (msg.PostData.Ids[i] is Guid id)
|
||||
//{
|
||||
// if (id.IsNullOrEmpty()) throw new NullReferenceException($"PostData.Id.IsNullOrEmpty(); Ids: {msg.PostData.Ids}");
|
||||
// paramValues[i] = id;
|
||||
//}
|
||||
//else if (Guid.TryParse(obj, out id))
|
||||
//{
|
||||
// if (id.IsNullOrEmpty()) throw new NullReferenceException($"PostData.Id.IsNullOrEmpty(); Ids: {msg.PostData.Ids}");
|
||||
// paramValues[i] = id;
|
||||
//}
|
||||
//else if (Enum.TryParse(methodInfoModel.ParameterType, obj, out var enumObj))
|
||||
//{
|
||||
// paramValues[i] = enumObj;
|
||||
//}
|
||||
//else paramValues[i] = Convert.ChangeType(obj, methodInfoModel.ParameterType);
|
||||
|
||||
var obj = msg.PostData.Ids[i];
|
||||
//var config = new MapperConfiguration(cfg =>
|
||||
//{
|
||||
// cfg.CreateMap(obj.GetType(), methodInfoModel.ParameterType);
|
||||
//});
|
||||
|
||||
//var mapper = new Mapper(config);
|
||||
//paramValues[i] = mapper.Map(obj, methodInfoModel.ParameterType);
|
||||
|
||||
//paramValues[i] = obj;
|
||||
|
||||
var a = Array.CreateInstance(methodInfoModel.ParamInfos[i].ParameterType, 1);
|
||||
|
||||
if (methodInfoModel.ParamInfos[i].ParameterType == typeof(Expression))
|
||||
{
|
||||
//var serializer = new ExpressionSerializer(new JsonSerializer());
|
||||
//paramValues[i] = serializer.DeserializeText((string)(obj.JsonTo(a.GetType()) as Array)?.GetValue(0)!);
|
||||
}
|
||||
else paramValues[i] = (obj.JsonTo(a.GetType()) as Array)?.GetValue(0)!;
|
||||
|
||||
}
|
||||
}
|
||||
else paramValues[0] = message!.MessagePackTo<SignalPostJsonDataMessage<object>>(MessagePackSerializerOptions.Standard).PostDataJson.JsonTo(firstParamType)!;
|
||||
}
|
||||
else Logger.Debug($"{logText}(); {tagName}");
|
||||
|
||||
var responseDataJson = new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, methodInfoModel.MethodInfo.InvokeMethod(methodsByDeclaringObject.InstanceObject, paramValues));
|
||||
var responseDataJsonKiloBytes = System.Text.Encoding.Unicode.GetByteCount(responseDataJson.ResponseData!) / 1024;
|
||||
|
||||
//File.WriteAllText(Path.Combine("h:", $"{requestId}.json"), responseDataJson.ResponseData);
|
||||
|
||||
Logger.Info($"[{responseDataJsonKiloBytes}kb] responseData serialized to json");
|
||||
await ResponseToCaller(messageTag, responseDataJson, requestId);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.Debug($"Not found dynamic method for the tag! {tagName}");
|
||||
notFoundCallback?.Invoke(tagName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"Server OnReceiveMessage; {ex.Message}; {tagName}", ex);
|
||||
}
|
||||
|
||||
await ResponseToCaller(messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Error), requestId);
|
||||
}
|
||||
|
||||
protected async Task ResponseToCaller(int messageTag, ISignalRMessage message, int? requestId)
|
||||
=> await SendMessageToClient(Clients.Caller, messageTag, message, requestId);
|
||||
|
||||
public async Task SendMessageToUserId(string userId, int messageTag, ISignalRMessage message, int? requestId)
|
||||
=> await SendMessageToClient(Clients.User(userId), messageTag, message, requestId);
|
||||
|
||||
public async Task SendMessageToConnectionId(string connectionId, int messageTag, ISignalRMessage message, int? requestId)
|
||||
=> await SendMessageToClient(Clients.Client(Context.ConnectionId), messageTag, message, requestId);
|
||||
|
||||
protected async Task SendMessageToClient(IAcSignalRHubItemServer sendTo, int messageTag, ISignalRMessage message, int? requestId = null)
|
||||
{
|
||||
var responseDataMessagePack = message.ToMessagePack(ContractlessStandardResolver.Options);
|
||||
Logger.Info($"[{(responseDataMessagePack.Length/1024)}kb] Server sending responseDataMessagePack to client; {nameof(requestId)}: {requestId}; ConnectionId: {Context.ConnectionId}; {ConstHelper.NameByValue<TSignalRTags>(messageTag)}");
|
||||
|
||||
await sendTo.OnReceiveMessage(messageTag, responseDataMessagePack, requestId);
|
||||
}
|
||||
|
||||
public async Task SendMessageToGroup(string groupId, int messageTag, string message)
|
||||
{
|
||||
//await Clients.Group(groupId).Post("", messageTag, message);
|
||||
}
|
||||
|
||||
//[Conditional("DEBUG")]
|
||||
private void LogContextUserNameAndId()
|
||||
{
|
||||
string? userName = null;
|
||||
var userId = Guid.Empty;
|
||||
|
||||
if (Context.User != null)
|
||||
{
|
||||
userName = Context.User.Identity?.Name;
|
||||
Guid.TryParse((string?)Context.User.FindFirstValue(ClaimTypes.NameIdentifier), out userId);
|
||||
}
|
||||
|
||||
if (AcDomain.IsDeveloperVersion) Logger.WarningConditional($"SignalR.Context; userName: {userName}; userId: {userId}");
|
||||
else Logger.Debug($"SignalR.Context; userName: {userName}; userId: {userId}");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public static class ExtensionMethods
|
||||
{
|
||||
public static object? InvokeMethod(this MethodInfo methodInfo, object obj, params object[]? parameters)
|
||||
{
|
||||
if (methodInfo.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) is AsyncStateMachineAttribute isAsyncTask)
|
||||
{
|
||||
dynamic awaitable = methodInfo.Invoke(obj, parameters)!;
|
||||
return awaitable.GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
return methodInfo.Invoke(obj, parameters);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public interface IAcSessionItem<TSessionItemId> where TSessionItemId : notnull
|
||||
{
|
||||
public TSessionItemId SessionId { get; set; }
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public class SignalRRequestModel
|
||||
{
|
||||
public DateTime RequestDateTime;
|
||||
public DateTime ResponseDateTime;
|
||||
public object? ResponseByRequestId = null;
|
||||
|
||||
public SignalRRequestModel()
|
||||
{
|
||||
RequestDateTime = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public SignalRRequestModel(object responseByRequestId) : this()
|
||||
{
|
||||
ResponseByRequestId = responseByRequestId;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
using System.Reflection;
|
||||
using AyCode.Core.Extensions;
|
||||
|
||||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public static class TrackingItemHelpers
|
||||
{
|
||||
public static T JsonClone<T>(T source) => source.ToJson().JsonTo<T>()!;
|
||||
|
||||
public static T ReflectionClone<T>(T source)
|
||||
{
|
||||
var type = source!.GetType();
|
||||
|
||||
if (type.IsPrimitive || typeof(string) == type)
|
||||
return source;
|
||||
|
||||
if (type.IsArray)
|
||||
{
|
||||
var elementType = Type.GetType(type.FullName!.Replace("[]", string.Empty))!;
|
||||
var array = (source as Array)!;
|
||||
var cloned = Array.CreateInstance(elementType, array.Length);
|
||||
|
||||
for (var i = 0; i < array.Length; i++)
|
||||
cloned.SetValue(ReflectionClone(array.GetValue(i)), i);
|
||||
|
||||
return (T)Convert.ChangeType(cloned, type);
|
||||
}
|
||||
|
||||
var clone = Activator.CreateInstance(type);
|
||||
|
||||
while (type != null && type != typeof(object))
|
||||
{
|
||||
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
|
||||
{
|
||||
var fieldValue = field.GetValue(source);
|
||||
if (fieldValue == null) continue;
|
||||
|
||||
field.SetValue(clone, ReflectionClone(fieldValue));
|
||||
}
|
||||
|
||||
type = type.BaseType;
|
||||
}
|
||||
|
||||
return (T)clone!;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue