Files
simapi-net/Synapse/Synapse.cs
T

324 lines
12 KiB
C#
Raw Normal View History

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.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
2025-01-16 22:05:59 +08:00
private MqttClientFactory 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>
2024-09-05 12:59:57 +08:00
/// <param name="headers"></param>
2024-09-05 15:06:44 +08:00
/// <param name="timeout"></param>
2024-07-26 08:11:21 +08:00
/// <typeparam name="T"></typeparam>
/// <returns></returns>
2024-09-05 12:59:57 +08:00
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null,
2024-09-05 15:06:44 +08:00
Dictionary<string, string>? headers = null, int? timeout = 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
{
2024-09-05 15:06:44 +08:00
var data = FireRpc(appName, method, param, headers, timeout);
2023-10-30 03:45:15 +08:00
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>
2024-09-05 12:59:57 +08:00
/// <param name="headers"></param>
2024-09-05 15:06:44 +08:00
/// <param name="timeout"></param>
2024-07-26 08:11:21 +08:00
/// <returns></returns>
2024-09-05 12:59:57 +08:00
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null,
2024-09-05 15:06:44 +08:00
Dictionary<string, string>? headers = null, int? timeout = null)
2023-10-20 12:33:18 +08:00
{
2024-09-05 15:06:44 +08:00
return Rpc<object>(appName, method, param, headers, timeout);
2023-10-20 12:33:18 +08:00
}
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-08-25 00:10:00 +08:00
/// <summary>
/// 如果条件成立,则爆出错误
/// </summary>
/// <param name="condition"></param>
/// <param name="code"></param>
/// <param name="message"></param>
public void RpcErrorWhen(bool condition, int code, string message = "")
{
if (condition) RpcError(code, message);
}
2024-07-26 08:11:21 +08:00
/// <summary>
2024-09-05 12:59:57 +08:00
/// 发送一个事件x
2024-07-26 08:11:21 +08:00
/// </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);
2024-09-05 12:59:57 +08:00
if (mt!.GetParameters().Length > 2)
2024-07-26 08:11:21 +08:00
{
logger.LogError(
2024-09-05 12:59:57 +08:00
"Synapse Rpc Register Error: Only 1,2 or none parameter supported. {Key} -> {Method}@{Class}",
tmp.Key, tmp.Method, tmp.Class.Name);
continue;
}
if (mt.GetParameters().Length == 2 &&
mt.GetParameters()[1].ParameterType != typeof(Dictionary<string, string>))
{
logger.LogError(
"Synapse Rpc Register Error: RpcMethod Parameter 2 must be Dictionary<string, string>. {Key} -> {Method}@{Class}",
2024-07-26 08:11:21 +08:00
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
}