218 lines
11 KiB
C#
218 lines
11 KiB
C#
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[]? messageBytes, int? requestId)
|
|
{
|
|
return ProcessOnReceiveMessage(messageTag, messageBytes, 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.Debug($"[{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 responseData = methodInfoModel.MethodInfo.InvokeMethod(methodsByDeclaringObject.InstanceObject, paramValues);
|
|
var responseDataJson = new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, responseData);
|
|
var responseDataJsonKiloBytes = System.Text.Encoding.Unicode.GetByteCount(responseDataJson.ResponseData!) / 1024;
|
|
|
|
//File.WriteAllText(Path.Combine("h:", $"{requestId}.json"), responseDataJson.ResponseData);
|
|
|
|
Logger.Debug($"[{responseDataJsonKiloBytes}kb] responseData serialized to json");
|
|
|
|
await ResponseToCaller(messageTag, responseDataJson, requestId);
|
|
|
|
if (methodInfoModel.Attribute.SendToOtherClientType != SendToClientType.None)
|
|
SendMessageToOtherClients(methodInfoModel.Attribute.SendToOtherClientTag, responseData).Forget();
|
|
|
|
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 Task ResponseToCaller2(int messageTag, object? content)
|
|
=> ResponseToCaller(messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
|
|
|
protected Task ResponseToCaller(int messageTag, ISignalRMessage message, int? requestId)
|
|
=> SendMessageToClient(Clients.Caller, messageTag, message, requestId);
|
|
|
|
protected Task SendMessageToUserId2(string userId, int messageTag, object? content)
|
|
=> SendMessageToUserId(userId, messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
|
|
|
public Task SendMessageToUserId(string userId, int messageTag, ISignalRMessage message, int? requestId)
|
|
=> SendMessageToClient(Clients.User(userId), messageTag, message, requestId);
|
|
|
|
public Task SendMessageToConnectionId2(string connectionId, int messageTag, object? content)
|
|
=> SendMessageToConnectionId(connectionId, messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
|
|
|
public Task SendMessageToConnectionId(string connectionId, int messageTag, ISignalRMessage message, int? requestId)
|
|
=> SendMessageToClient(Clients.Client(Context.ConnectionId), messageTag, message, requestId);
|
|
|
|
public Task SendMessageToOtherClients(int messageTag, object? content)
|
|
=> SendMessageToClient(Clients.Others, messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
|
|
|
public Task SendMessageToAllClients(int messageTag, object? content)
|
|
=> SendMessageToClient(Clients.All, messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
|
|
|
|
|
protected async Task SendMessageToClient(IAcSignalRHubItemServer sendTo, int messageTag, ISignalRMessage message, int? requestId = null)
|
|
{
|
|
var responseDataMessagePack = message.ToMessagePack(ContractlessStandardResolver.Options);
|
|
Logger.Debug($"[{(responseDataMessagePack.Length/1024)}kb] Server sending responseDataMessagePack to client; {nameof(requestId)}: {requestId}; Aborted: {Context.ConnectionAborted.IsCancellationRequested}; ConnectionId: {Context.ConnectionId}; {ConstHelper.NameByValue<TSignalRTags>(messageTag)}");
|
|
|
|
await sendTo.OnReceiveMessage(messageTag, responseDataMessagePack, requestId);
|
|
|
|
Logger.Debug($"Server sent responseDataMessagePack to client; {nameof(requestId)}: {requestId}; Aborted: {Context.ConnectionAborted.IsCancellationRequested}; ConnectionId: {Context.ConnectionId}; {ConstHelper.NameByValue<TSignalRTags>(messageTag)}");
|
|
}
|
|
|
|
public async Task SendMessageToGroup(string groupId, int messageTag, string message)
|
|
{
|
|
//await Clients.Group(groupId).Post("", messageTag, message);
|
|
}
|
|
|
|
//[Conditional("DEBUG")]
|
|
protected virtual void LogContextUserNameAndId()
|
|
{
|
|
string? userName = null;
|
|
var userId = Guid.Empty;
|
|
|
|
if (Context.User != null)
|
|
{
|
|
userName = Context.User.Identity?.Name;
|
|
Guid.TryParse(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}");
|
|
}
|
|
} |