Compare commits
2 Commits
6f4f87ddd9
...
c1a707139c
| Author | SHA1 | Date |
|---|---|---|
|
|
c1a707139c | |
|
|
a24f0c1681 |
|
|
@ -1,10 +1,12 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq.Expressions;
|
||||
using AyCode.Core.Interfaces;
|
||||
using MessagePack.Resolvers;
|
||||
using AyCode.Core.Interfaces;
|
||||
using MessagePack;
|
||||
using MessagePack.Resolvers;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace AyCode.Core.Extensions;
|
||||
|
|
@ -16,30 +18,30 @@ public static class SerializeObjectExtensions
|
|||
//TypeNameHandling = TypeNameHandling.All,
|
||||
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
|
||||
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
|
||||
NullValueHandling = NullValueHandling.Ignore
|
||||
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
|
||||
////System.Text.Json
|
||||
//ReferenceHandler.Preserve
|
||||
//ReferenceHandler.IgnoreCycles
|
||||
};
|
||||
|
||||
|
||||
public static string ToJson<T>(this T source) => JsonConvert.SerializeObject(source, Options);
|
||||
public static string ToJson<T>(this IQueryable<T> source) where T : class, IAcSerializableToJson => JsonConvert.SerializeObject(source, Options);
|
||||
public static string ToJson<T>(this IEnumerable<T> source) where T : class, IAcSerializableToJson => JsonConvert.SerializeObject(source, Options);
|
||||
|
||||
public static T? JsonTo<T>(this string json)
|
||||
public static string ToJson<T>(this T source, JsonSerializerSettings? options = null) => JsonConvert.SerializeObject(source, options ?? Options);
|
||||
public static string ToJson<T>(this IQueryable<T> source, JsonSerializerSettings? options = null) where T : class, IAcSerializableToJson => JsonConvert.SerializeObject(source, options ?? Options);
|
||||
public static string ToJson<T>(this IEnumerable<T> source, JsonSerializerSettings? options = null) where T : class, IAcSerializableToJson => JsonConvert.SerializeObject(source, options ?? Options);
|
||||
|
||||
public static T? JsonTo<T>(this string json, JsonSerializerSettings? options = null)
|
||||
{
|
||||
if (json.StartsWith("\"") && json.EndsWith("\"")) json = Regex.Unescape(json).TrimStart('"').TrimEnd('"');
|
||||
|
||||
return JsonConvert.DeserializeObject<T>(json, Options);
|
||||
return JsonConvert.DeserializeObject<T>(json, options ?? Options);
|
||||
}
|
||||
|
||||
public static object? JsonTo(this string json, Type toType)
|
||||
public static object? JsonTo(this string json, Type toType, JsonSerializerSettings? options = null)
|
||||
{
|
||||
if (json.StartsWith("\"") && json.EndsWith("\"")) json = Regex.Unescape(json).TrimStart('"').TrimEnd('"');
|
||||
|
||||
return JsonConvert.DeserializeObject(json, toType, Options);
|
||||
return JsonConvert.DeserializeObject(json, toType, options ?? Options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -47,9 +49,10 @@ public static class SerializeObjectExtensions
|
|||
/// </summary>
|
||||
/// <typeparam name="TDestination"></typeparam>
|
||||
/// <param name="src"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
[return: NotNullIfNotNull(nameof(src))]
|
||||
public static TDestination? CloneTo<TDestination>(this object? src) where TDestination : class => src?.ToJson().JsonTo<TDestination>();
|
||||
public static TDestination? CloneTo<TDestination>(this object? src, JsonSerializerSettings? options = null) where TDestination : class => src?.ToJson(options).JsonTo<TDestination>(options);
|
||||
|
||||
//public static string ToJson(this Expression source) => JsonConvert.SerializeObject(source, Options);
|
||||
|
||||
|
|
@ -58,4 +61,65 @@ public static class SerializeObjectExtensions
|
|||
|
||||
public static T MessagePackTo<T>(this byte[] message) => MessagePackSerializer.Deserialize<T>(message);
|
||||
public static T MessagePackTo<T>(this byte[] message, MessagePackSerializerOptions options) => MessagePackSerializer.Deserialize<T>(message, options);
|
||||
}
|
||||
}
|
||||
|
||||
public class IgnoreAndRenamePropertySerializerContractResolver : DefaultContractResolver
|
||||
{
|
||||
private readonly Dictionary<Type, HashSet<string>> _ignores = new();
|
||||
private readonly Dictionary<Type, HashSet<string>> _includes = new();
|
||||
private readonly Dictionary<Type, Dictionary<string, string>> _renames = new();
|
||||
|
||||
public void IgnoreProperty(Type type, params string[] jsonPropertyNames)
|
||||
{
|
||||
if (!_ignores.ContainsKey(type)) _ignores[type] = [];
|
||||
|
||||
foreach (var prop in jsonPropertyNames) _ignores[type].Add(prop);
|
||||
}
|
||||
|
||||
public void IncludesProperty(Type type, params string[] jsonPropertyNames)
|
||||
{
|
||||
if (!_includes.ContainsKey(type)) _includes[type] = [];
|
||||
|
||||
foreach (var prop in jsonPropertyNames) _includes[type].Add(prop);
|
||||
}
|
||||
|
||||
public void RenameProperty(Type type, string propertyName, string newJsonPropertyName)
|
||||
{
|
||||
if (!_renames.ContainsKey(type)) _renames[type] = new Dictionary<string, string>();
|
||||
|
||||
_renames[type][propertyName] = newJsonPropertyName;
|
||||
}
|
||||
|
||||
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
||||
{
|
||||
var property = base.CreateProperty(member, memberSerialization);
|
||||
|
||||
if (IsIgnored(property.DeclaringType, property.PropertyName) || !IsIncluded(property.DeclaringType, property.PropertyName))
|
||||
{
|
||||
property.ShouldSerialize = i => false;
|
||||
property.Ignored = true;
|
||||
}
|
||||
|
||||
if (IsRenamed(property.DeclaringType, property.PropertyName, out var newJsonPropertyName))
|
||||
property.PropertyName = newJsonPropertyName;
|
||||
|
||||
return property;
|
||||
}
|
||||
|
||||
private bool IsIgnored(Type type, string jsonPropertyName)
|
||||
{
|
||||
return _ignores.ContainsKey(type) && _ignores[type].Contains(jsonPropertyName);
|
||||
}
|
||||
private bool IsIncluded(Type type, string jsonPropertyName)
|
||||
{
|
||||
return _includes.Count == 0 || (_includes.ContainsKey(type) && _includes[type].Contains(jsonPropertyName));
|
||||
}
|
||||
|
||||
private bool IsRenamed(Type type, string jsonPropertyName, out string? newJsonPropertyName)
|
||||
{
|
||||
if (_renames.TryGetValue(type, out var renames) && renames.TryGetValue(jsonPropertyName, out newJsonPropertyName)) return true;
|
||||
|
||||
newJsonPropertyName = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
using AyCode.Core.Extensions;
|
||||
using AyCode.Core.Helpers;
|
||||
using AyCode.Core.Loggers;
|
||||
using AyCode.Services.Loggers;
|
||||
using AyCode.Services.SignalRs;
|
||||
using MessagePack.Resolvers;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AyCode.Services.Server.SignalRs;
|
||||
|
||||
public abstract class AcSignalRSendToClientService<TSignalRHub, TSignalRTags, TLogger>(IHubContext<TSignalRHub, IAcSignalRHubItemServer> signalRHub, IAcLoggerBase logger) //: IAcSignalRHubServer
|
||||
where TSignalRHub: Hub<IAcSignalRHubItemServer>, IAcSignalRHubServer where TSignalRTags : AcSignalRTags where TLogger : IAcLoggerBase
|
||||
{
|
||||
protected IAcLoggerBase Logger => logger;
|
||||
|
||||
protected virtual async Task SendMessageToClient(IAcSignalRHubItemServer sendTo, int messageTag, object? content)
|
||||
{
|
||||
var jsonContent = new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content);
|
||||
await SendMessageToClient(sendTo, messageTag, jsonContent, null);
|
||||
}
|
||||
|
||||
protected virtual async Task SendMessageToClient(IAcSignalRHubItemServer sendTo, int messageTag, ISignalRMessage message, int? requestId = null)
|
||||
{
|
||||
var sendingDataMessagePack = message.ToMessagePack(ContractlessStandardResolver.Options);
|
||||
|
||||
Logger.Info($"[{(sendingDataMessagePack.Length/1024)}kb] Server sending dataMessagePack to client; {nameof(requestId)}: {requestId}; {ConstHelper.NameByValue<TSignalRTags>(messageTag)}");
|
||||
//Logger.Info($"[{(responseDataMessagePack.Length/1024)}kb] Server sending dataMessagePack to client; {nameof(requestId)}: {requestId}; ConnectionId: {signalRHub.ConnectionId}; {ConstHelper.NameByValue<TSignalRTags>(messageTag)}");
|
||||
|
||||
await sendTo.OnReceiveMessage(messageTag, sendingDataMessagePack, requestId);
|
||||
}
|
||||
|
||||
public virtual async Task SendMessageToAllClients(int messageTag, object? content)
|
||||
{
|
||||
await SendMessageToClient(signalRHub.Clients.All, messageTag, content);
|
||||
}
|
||||
|
||||
public virtual async Task SendMessageToConnection(string connectionId, int messageTag, object? content)
|
||||
{
|
||||
await SendMessageToClient(signalRHub.Clients.Client(connectionId), messageTag, content);
|
||||
}
|
||||
|
||||
public virtual async Task SendMessageToConnections(IEnumerable<string> connectionIds, int messageTag, object? content)
|
||||
{
|
||||
await SendMessageToClient(signalRHub.Clients.Clients(connectionIds), messageTag, content);
|
||||
}
|
||||
|
||||
public virtual async Task SendMessageToUser(string user, int messageTag, object? content)
|
||||
{
|
||||
await SendMessageToClient(signalRHub.Clients.User(user), messageTag, content);
|
||||
}
|
||||
|
||||
public virtual async Task SendMessageToUsers(IEnumerable<string> users, int messageTag, object? content)
|
||||
{
|
||||
await SendMessageToClient(signalRHub.Clients.Users(users), messageTag, content);
|
||||
}
|
||||
}
|
||||
|
|
@ -52,9 +52,9 @@ public abstract class AcWebSignalRHubBase<TSignalRTags, TLogger>(IConfiguration
|
|||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
|
||||
public virtual Task OnReceiveMessage(int messageTag, byte[]? message, int? requestId)
|
||||
public virtual Task OnReceiveMessage(int messageTag, byte[]? messageBytes, int? requestId)
|
||||
{
|
||||
return ProcessOnReceiveMessage(messageTag, message, requestId, null);
|
||||
return ProcessOnReceiveMessage(messageTag, messageBytes, requestId, null);
|
||||
}
|
||||
|
||||
protected async Task ProcessOnReceiveMessage(int messageTag, byte[]? message, int? requestId, Func<string, Task>? notFoundCallback)
|
||||
|
|
@ -133,14 +133,19 @@ public abstract class AcWebSignalRHubBase<TSignalRTags, TLogger>(IConfiguration
|
|||
}
|
||||
else Logger.Debug($"{logText}(); {tagName}");
|
||||
|
||||
var responseDataJson = new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, methodInfoModel.MethodInfo.InvokeMethod(methodsByDeclaringObject.InstanceObject, paramValues));
|
||||
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.Info($"[{responseDataJsonKiloBytes}kb] responseData serialized to json");
|
||||
|
||||
await ResponseToCaller(messageTag, responseDataJson, requestId);
|
||||
|
||||
|
||||
if (methodInfoModel.Attribute.SendToOtherClientType != SendToClientType.None)
|
||||
SendMessageToOtherClients(methodInfoModel.Attribute.SendToOtherClientTag, responseData).Forget();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -155,15 +160,31 @@ public abstract class AcWebSignalRHubBase<TSignalRTags, TLogger>(IConfiguration
|
|||
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 async Task ResponseToCaller(int messageTag, ISignalRMessage message, int? requestId)
|
||||
=> await 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 async Task SendMessageToUserId(string userId, int messageTag, ISignalRMessage message, int? requestId)
|
||||
=> await SendMessageToClient(Clients.User(userId), messageTag, message, requestId);
|
||||
|
||||
public async Task SendMessageToConnectionId2(string connectionId, int messageTag, object? content)
|
||||
=> await SendMessageToConnectionId(connectionId, messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
||||
|
||||
public async Task SendMessageToConnectionId(string connectionId, int messageTag, ISignalRMessage message, int? requestId)
|
||||
=> await SendMessageToClient(Clients.Client(Context.ConnectionId), messageTag, message, requestId);
|
||||
|
||||
public async Task SendMessageToOtherClients(int messageTag, object? content)
|
||||
=> await SendMessageToClient(Clients.Others, messageTag, new SignalResponseJsonMessage(messageTag, SignalResponseStatus.Success, content), null);
|
||||
|
||||
public async Task SendMessageToAllClients(int messageTag, object? content)
|
||||
=> await 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);
|
||||
|
|
|
|||
|
|
@ -16,8 +16,8 @@ namespace AyCode.Services.SignalRs
|
|||
protected readonly HubConnection HubConnection;
|
||||
protected readonly AcLoggerBase Logger;
|
||||
|
||||
public event Action<int, byte[], int?> OnMessageReceived = null!;
|
||||
//public event Action<int, int> OnMessageRequested;
|
||||
//protected event Action<int, byte[], int?> OnMessageReceived = null!;
|
||||
protected abstract Task MessageReceived(int messageTag, byte[] messageBytes);
|
||||
|
||||
public int Timeout = 10000;
|
||||
private const string TagsName = "SignalRTags";
|
||||
|
|
@ -27,9 +27,13 @@ namespace AyCode.Services.SignalRs
|
|||
Logger = logger;
|
||||
Logger.Detail(fullHubName);
|
||||
|
||||
//TODO: HubConnectionBuilder constructor!!! - J.
|
||||
HubConnection = new HubConnectionBuilder()
|
||||
.WithUrl(fullHubName)
|
||||
//.WithAutomaticReconnect()
|
||||
.WithAutomaticReconnect()
|
||||
.WithStatefulReconnect()
|
||||
.WithKeepAliveInterval(TimeSpan.FromSeconds(60))
|
||||
.WithServerTimeout(TimeSpan.FromSeconds(120))
|
||||
//.AddMessagePackProtocol(options => {
|
||||
// options.SerializerOptions = MessagePackSerializerOptions.Standard
|
||||
// .WithResolver(MessagePack.Resolvers.StandardResolver.Instance)
|
||||
|
|
@ -206,11 +210,11 @@ namespace AyCode.Services.SignalRs
|
|||
return SendMessageToServerAsync(messageTag, message, requestId);
|
||||
}
|
||||
|
||||
public virtual Task OnReceiveMessage(int messageTag, byte[] message, int? requestId)
|
||||
public virtual Task OnReceiveMessage(int messageTag, byte[] messageBytes, int? requestId)
|
||||
{
|
||||
var logText = $"Client OnReceiveMessage; {nameof(requestId)}: {requestId}; {ConstHelper.NameByValue(TagsName, messageTag)}";
|
||||
|
||||
if (message.Length == 0) Logger.Warning($"message.Length == 0! {logText}");
|
||||
if (messageBytes.Length == 0) Logger.Warning($"message.Length == 0! {logText}");
|
||||
|
||||
try
|
||||
{
|
||||
|
|
@ -219,9 +223,9 @@ namespace AyCode.Services.SignalRs
|
|||
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}");
|
||||
Logger.Info($"[{_responseByRequestId[reqId].ResponseDateTime.Subtract(_responseByRequestId[reqId].RequestDateTime).TotalMilliseconds:N0}ms][{(messageBytes.Length/1024)}kb]{logText}");
|
||||
|
||||
var responseMessage = message.MessagePackTo<SignalResponseJsonMessage>(ContractlessStandardResolver.Options);
|
||||
var responseMessage = messageBytes.MessagePackTo<SignalResponseJsonMessage>(ContractlessStandardResolver.Options);
|
||||
|
||||
switch (_responseByRequestId[reqId].ResponseByRequestId)
|
||||
{
|
||||
|
|
@ -250,7 +254,7 @@ namespace AyCode.Services.SignalRs
|
|||
}
|
||||
else Logger.Info(logText);
|
||||
|
||||
OnMessageReceived(messageTag, message, requestId);
|
||||
MessageReceived(messageTag, messageBytes).Forget();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -3,5 +3,5 @@
|
|||
public interface IAcSignalRHubBase
|
||||
{
|
||||
//Task OnRequestMessage(int messageTag, int requestId);
|
||||
Task OnReceiveMessage(int messageTag, byte[] message, int? requestId);
|
||||
Task OnReceiveMessage(int messageTag, byte[] messageBytes, int? requestId);
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
namespace AyCode.Services.SignalRs;
|
||||
|
||||
public enum SendToClientType
|
||||
{
|
||||
None = 0,
|
||||
Others = 10,
|
||||
Caller = 20,
|
||||
All = 30
|
||||
}
|
||||
|
|
@ -1,12 +1,31 @@
|
|||
namespace AyCode.Services.SignalRs;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="messageTag">Milyen SignalR tag-eket fogadjon a metódus</param>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class TagAttribute(int messageTag) : Attribute
|
||||
{
|
||||
public int MessageTag { get; init; } = messageTag;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="messageTag">Milyen SignalR tag-eket fogadjon a metódus.</param>
|
||||
/// <param name="sendToOtherClientTag">Milyen Tag-el küldje ki a többi kliens-nek a response-t.</param>
|
||||
/// <param name="sendToOtherClientType">Kiknek küldje még el a response-t.</param>
|
||||
/// <param name="sendToOtherClientNotificationMessage">Notification message. Jelenleg nincs implementálva!</param>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class SignalRAttribute(int messageTag) : TagAttribute(messageTag)
|
||||
public class SignalRAttribute(int messageTag, int sendToOtherClientTag = 0, SendToClientType sendToOtherClientType = SendToClientType.None, string? sendToOtherClientNotificationMessage = null) : TagAttribute(messageTag)
|
||||
{
|
||||
public int SendToOtherClientTag { get; init; } = sendToOtherClientTag;
|
||||
public SendToClientType SendToOtherClientType { get; init; } = sendToOtherClientType;
|
||||
public string? SendToOtherClientNotificationMessage { get; init; } = sendToOtherClientNotificationMessage;
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class SignalRSendToClientAttribute(int messageTag) : TagAttribute(messageTag)
|
||||
{
|
||||
}
|
||||
Loading…
Reference in New Issue