2023-10-20 12:33:18 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Diagnostics;
|
|
|
|
|
using System.Linq;
|
2023-10-20 14:13:53 +08:00
|
|
|
using System.Text.Json;
|
2024-07-26 05:03:28 +08:00
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
2024-07-26 08:11:21 +08:00
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2023-10-20 12:33:18 +08:00
|
|
|
using Microsoft.Extensions.Logging;
|
2024-07-26 05:03:28 +08:00
|
|
|
using MQTTnet;
|
|
|
|
|
using MQTTnet.Client;
|
|
|
|
|
using MQTTnet.Formatter;
|
2023-10-20 12:33:18 +08:00
|
|
|
using SimApi.Attributes;
|
|
|
|
|
using SimApi.Communications;
|
2024-04-16 06:57:56 +08:00
|
|
|
using SimApi.Configurations;
|
2024-08-25 00:08:06 +08:00
|
|
|
using SimApi.Exceptions;
|
2023-10-20 12:33:18 +08:00
|
|
|
using SimApi.Helpers;
|
|
|
|
|
|
|
|
|
|
namespace SimApi;
|
|
|
|
|
|
2024-07-26 05:03:28 +08:00
|
|
|
public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
2023-10-20 12:33:18 +08:00
|
|
|
|
2024-07-26 05:03:28 +08:00
|
|
|
private MqttFactory MqttFactory { get; } = new();
|
2024-07-26 08:11:21 +08:00
|
|
|
public IMqttClient? Client { get; set; }
|
2023-10-20 12:33:18 +08:00
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
private List<RegisterItem> EventRegistry { get; set; } = new();
|
2023-10-20 12:33:18 +08:00
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
private List<RegisterItem> RpcRegistry { get; set; } = new();
|
2023-10-20 12:33:18 +08:00
|
|
|
|
|
|
|
|
public void Init()
|
|
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
|
2023-10-20 12:33:18 +08:00
|
|
|
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
|
|
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogCritical("Synapse初始化失败: AppName 和 SysName 不能为空");
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-04-16 06:57:56 +08:00
|
|
|
|
2023-10-20 12:33:18 +08:00
|
|
|
Options.AppId ??= Guid.NewGuid().ToString();
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogInformation("Synapse Sys Name: {SysName}\nSynapse App Name: {AppName}\nSynapse App Id: {AppId}",
|
|
|
|
|
Options.SysName, Options.AppName, Options.AppId);
|
2023-10-20 12:33:18 +08:00
|
|
|
CreateConnection();
|
2024-07-26 08:11:21 +08:00
|
|
|
ProcessAttribute();
|
2024-08-03 19:19:42 +08:00
|
|
|
//事件客户端
|
|
|
|
|
if (Options.DisableEventClient)
|
|
|
|
|
{
|
|
|
|
|
logger.LogWarning("Synapse Event Client Disabled: DisableEventClient set true");
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
logger.LogInformation("Synapse Event Client Ready");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//RPC客户端
|
|
|
|
|
if (Options.DisableRpcClient)
|
|
|
|
|
{
|
|
|
|
|
logger.LogWarning("Synapse Rpc Client Disabled: DisableEventClient set true");
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
RunRpcClient();
|
|
|
|
|
logger.LogInformation("Synapse Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (RpcRegistry.Count > 0)
|
|
|
|
|
{
|
|
|
|
|
RunRpcServer();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (EventRegistry.Count > 0)
|
|
|
|
|
{
|
|
|
|
|
RunEventServer();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (Options.EnableConfigStore)
|
|
|
|
|
{
|
|
|
|
|
RunConfigStoreServer();
|
|
|
|
|
logger.LogInformation("Synapse Config Store Ready [{SysName}] ...", Options.SysName);
|
|
|
|
|
}
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-08-03 19:19:42 +08:00
|
|
|
|
|
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 调用RPC使用明确的返回值类型
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="appName"></param>
|
|
|
|
|
/// <param name="method"></param>
|
|
|
|
|
/// <param name="param"></param>
|
|
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null)
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
2023-10-20 12:33:18 +08:00
|
|
|
if (Options.DisableRpcClient)
|
|
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogError("Synapse Rpc Client Disabled!");
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2023-10-30 03:45:15 +08:00
|
|
|
var data = FireRpc(appName, method, param);
|
|
|
|
|
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-04-16 06:57:56 +08:00
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
return (res as SimApiBaseResponse<T>)!;
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
|
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 调用RPC使用object作为返回值类型
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="appName"></param>
|
|
|
|
|
/// <param name="method"></param>
|
|
|
|
|
/// <param name="param"></param>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null)
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
|
|
|
|
return Rpc<object>(appName, method, param);
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-25 00:08:06 +08:00
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 只能在Rpc方法中使用,快捷抛出异常返回
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="code"></param>
|
|
|
|
|
/// <param name="message"></param>
|
|
|
|
|
/// <exception cref="SimApiException"></exception>
|
|
|
|
|
public void RpcError(int code, string message = "")
|
|
|
|
|
{
|
|
|
|
|
throw new SimApiException(code, message);
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
/// <summary>
|
|
|
|
|
///
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="eventName"></param>
|
|
|
|
|
/// <param name="param"></param>
|
|
|
|
|
public bool Event(string eventName, dynamic? param = null)
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 08:11:21 +08:00
|
|
|
if (!Options.DisableEventClient) return FireEvent(eventName, param);
|
|
|
|
|
logger.LogError("Synapse Event Client Disabled!");
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 设置一个系统配置项
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="key"></param>
|
|
|
|
|
/// <param name="value"></param>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public bool SetConfig(string key, string value)
|
|
|
|
|
{
|
|
|
|
|
if (Options.EnableConfigStore) return FireSetConfig(key, value);
|
|
|
|
|
logger.LogError("Synapse Config Store Disabled!");
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 读取一个配置项,如果没有则为空
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="key"></param>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public string? GetConfig(string key)
|
|
|
|
|
{
|
|
|
|
|
if (Options.EnableConfigStore) return FireGetConfig(key);
|
|
|
|
|
logger.LogError("Synapse Config Store Disabled!");
|
|
|
|
|
return null;
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void CreateConnection()
|
|
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
Client = MqttFactory.CreateMqttClient();
|
|
|
|
|
var clientOpts = new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)
|
|
|
|
|
.WithWebSocketServer(o => o.WithUri(Options.Websocket))
|
|
|
|
|
.WithCredentials(Options.Username, Options.Password)
|
|
|
|
|
.WithClientId($"{Options.AppName}:{Options.AppId}")
|
|
|
|
|
.Build();
|
|
|
|
|
Client!.ConnectAsync(clientOpts, CancellationToken.None).Wait();
|
|
|
|
|
Client.ConnectedAsync += _ =>
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
|
2024-08-03 18:35:01 +08:00
|
|
|
//RPC客户端
|
2024-08-03 19:19:42 +08:00
|
|
|
if (!Options.DisableRpcClient) SubRpcClientTopic();
|
|
|
|
|
if (RpcRegistry.Count > 0) SubRpcServerTopic();
|
|
|
|
|
if (EventRegistry.Count > 0) SubEventServerTopic();
|
|
|
|
|
if (Options.EnableConfigStore) SubConfigStoreServerTopic();
|
2024-07-26 05:03:28 +08:00
|
|
|
return Task.CompletedTask;
|
2023-10-20 12:33:18 +08:00
|
|
|
};
|
2024-07-26 05:03:28 +08:00
|
|
|
//重连
|
|
|
|
|
Client.DisconnectedAsync += async _ =>
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 断开连接,开始重连...", Options.AppName, Options.AppId);
|
2024-08-03 19:19:42 +08:00
|
|
|
await Task.Delay(TimeSpan.FromSeconds(5));
|
2024-07-26 05:03:28 +08:00
|
|
|
try
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 05:03:28 +08:00
|
|
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 开始连接MQTT服务器...", Options.AppName, Options.AppId);
|
|
|
|
|
Client.ConnectAsync(clientOpts).Wait();
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-07-26 05:03:28 +08:00
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 重连失败...", Options.AppName, Options.AppId);
|
|
|
|
|
}
|
|
|
|
|
};
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void ProcessAttribute()
|
|
|
|
|
{
|
|
|
|
|
var stackTrace = new StackTrace();
|
2024-07-26 05:03:28 +08:00
|
|
|
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
|
|
|
|
var assembly = callingMethod?.DeclaringType?.Assembly;
|
|
|
|
|
var types = assembly!.GetTypes(); // 获取程序集中的所有类型
|
2023-10-20 12:33:18 +08:00
|
|
|
foreach (var type in types)
|
|
|
|
|
{
|
|
|
|
|
var methods = type.GetMethods(); // 获取类型中的所有方法
|
|
|
|
|
foreach (var method in methods)
|
|
|
|
|
{
|
|
|
|
|
if (method.IsDefined(typeof(SynapseEventAttribute), false))
|
|
|
|
|
{
|
|
|
|
|
var attribute =
|
2024-07-26 08:11:21 +08:00
|
|
|
(SynapseEventAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseEventAttribute))!;
|
|
|
|
|
var tmp = new RegisterItem
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 08:11:21 +08:00
|
|
|
Key = attribute.Name ?? method.Name,
|
|
|
|
|
Class = type,
|
|
|
|
|
Method = method.Name
|
|
|
|
|
};
|
|
|
|
|
if (tmp.Key.StartsWith('/') || tmp.Key.EndsWith('/'))
|
|
|
|
|
{
|
|
|
|
|
logger.LogError("Synapse Event Register Error: {Key} Can't start or end of '/'", tmp.Key);
|
|
|
|
|
continue;
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-08-03 18:35:01 +08:00
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
|
|
|
|
var mt = callClass.GetType().GetMethod(tmp.Method);
|
2024-08-03 18:35:01 +08:00
|
|
|
if (mt!.GetParameters().Length > 2 || mt.GetParameters().Length < 1)
|
2024-07-26 08:11:21 +08:00
|
|
|
{
|
|
|
|
|
logger.LogError(
|
|
|
|
|
"Synapse Event Register Error: Only one or two parameter supported. {Key} -> {Method}@{Class}",
|
|
|
|
|
tmp.Key, tmp.Method, tmp.Class.Name);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
EventRegistry.Add(tmp);
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-04-16 06:57:56 +08:00
|
|
|
|
2023-10-20 12:33:18 +08:00
|
|
|
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
|
|
|
|
|
{
|
|
|
|
|
var attribute =
|
2024-07-26 08:11:21 +08:00
|
|
|
(SynapseRpcAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseRpcAttribute))!;
|
|
|
|
|
var tmp = new RegisterItem
|
2023-10-20 12:33:18 +08:00
|
|
|
{
|
2024-07-26 08:11:21 +08:00
|
|
|
Key = attribute.Name ?? $"{type.Name}.{method.Name}",
|
|
|
|
|
Class = type,
|
|
|
|
|
Method = method.Name
|
|
|
|
|
};
|
|
|
|
|
if (tmp.Key.Contains('/') || tmp.Key.Contains('#') || tmp.Key.Contains('+'))
|
|
|
|
|
{
|
|
|
|
|
logger.LogError("Synapse Rpc Register Error: {Key} contains '/' , '#' , '+'", tmp.Key);
|
|
|
|
|
continue;
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
2024-07-26 08:11:21 +08:00
|
|
|
|
|
|
|
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
|
|
|
|
var mt = callClass.GetType().GetMethod(tmp.Method);
|
|
|
|
|
if (mt!.GetParameters().Length > 1)
|
|
|
|
|
{
|
|
|
|
|
logger.LogError(
|
|
|
|
|
"Synapse Rpc Register Error: Only one or none parameter supported. {Key} -> {Method}@{Class}",
|
|
|
|
|
tmp.Key, tmp.Method, tmp.Class.Name);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (RpcRegistry.Any(x => x.Key == tmp.Key))
|
|
|
|
|
{
|
|
|
|
|
logger.LogError("Synapse Rpc Register Error: {Key} Already Exists -> {Method}@{Class}", tmp.Key,
|
|
|
|
|
tmp.Method, tmp.Class.Name);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
RpcRegistry.Add(tmp);
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-04-16 06:57:56 +08:00
|
|
|
|
2023-10-20 12:33:18 +08:00
|
|
|
var events = EventRegistry.Aggregate(string.Empty,
|
2024-07-26 08:11:21 +08:00
|
|
|
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class!.Name}");
|
2023-10-20 12:33:18 +08:00
|
|
|
var rpcList = RpcRegistry.Aggregate(string.Empty,
|
2024-07-26 08:11:21 +08:00
|
|
|
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class!.Name}");
|
|
|
|
|
if (EventRegistry.Count > 0) logger.LogInformation(" >> Synapse System 读取Event方法:{Event}", events);
|
|
|
|
|
if (RpcRegistry.Count > 0) logger.LogInformation(" >> Synapse System 读取RPC方法:{Rpc}", rpcList);
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class RegisterItem
|
|
|
|
|
{
|
2024-07-26 08:11:21 +08:00
|
|
|
public string? Key { get; init; }
|
2023-10-20 12:33:18 +08:00
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
public Type? Class { get; init; }
|
2023-10-20 12:33:18 +08:00
|
|
|
|
2024-07-26 08:11:21 +08:00
|
|
|
public string? Method { get; init; }
|
2023-10-20 12:33:18 +08:00
|
|
|
}
|