GoverApiCenterService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Linq;
  6. using Sers.Core.CL.MessageOrganize;
  7. using Sers.Core.Module.Api.ApiDesc;
  8. using Sers.Core.Module.Api.Data;
  9. using Sers.Core.Module.Api.RouteMap;
  10. using Sers.Core.Module.Env;
  11. using Sers.Core.Module.Message;
  12. using Sers.Core.Module.Rpc;
  13. using Sers.Gover.Base.Model;
  14. using Sers.Gover.Persistence;
  15. using Sers.Gover.RateLimit;
  16. using Sers.ServiceCenter.ApiCenter;
  17. using Sers.ServiceCenter.Entity;
  18. using Vit.Core.Module.Log;
  19. using Vit.Core.Util.ComponentModel.SsError;
  20. using Vit.Core.Util.ConfigurationManager;
  21. using Vit.Extensions;
  22. using Vit.Extensions.Json_Extensions;
  23. using Vit.Extensions.Object_Serialize_Extensions;
  24. namespace Sers.Gover.Base
  25. {
  26. [JsonObject(MemberSerialization.OptIn)]
  27. public class GoverApiCenterService : ApiCenterService
  28. {
  29. #region static
  30. public static readonly GoverApiCenterService Instance = LoadFromFile();
  31. static GoverApiCenterService LoadFromFile()
  32. {
  33. var mng = new GoverApiCenterService();
  34. Persistence_ApiDesc.ApiDesc_LoadAllFromJsonFile(mng.apiStationMng);
  35. Persistence_Counter.LoadCounterFromJsonFile(mng.apiStationMng);
  36. return mng;
  37. }
  38. public static void SaveToFile()
  39. {
  40. Persistence_Counter.SaveCounterToJsonFile(Instance.apiStationMng);
  41. }
  42. #endregion
  43. public GoverApiCenterService()
  44. {
  45. //init apiLoadBalancingMng
  46. switch (Appsettings.json.GetStringByPath("Sers.ServiceCenter.ApiRouteType"))
  47. {
  48. case "IgnoreHttpMethod": apiLoadBalancingMng = new ApiLoadBalancingMng(); break;
  49. default: apiLoadBalancingMng = new ApiLoadBalancingMng_RESTful(); break;
  50. }
  51. serviceStationMng = new ServiceStationMng();
  52. serviceStationMng.Init(this);
  53. apiStationMng = new ApiStationMng();
  54. apiStationMng.Init(this);
  55. }
  56. internal readonly ApiLoadBalancingMng apiLoadBalancingMng;
  57. [JsonProperty]
  58. internal ApiStationMng apiStationMng { get; private set; }
  59. [JsonIgnore]
  60. internal ServiceStationMng serviceStationMng { get; private set; }
  61. [JsonIgnore]
  62. public RateLimitMng rateLimitMng { get; private set; } = new RateLimitMng();
  63. public void SaveUsageInfo(EnvUsageInfo item)
  64. {
  65. serviceStationMng.SaveUsageInfo(item);
  66. }
  67. #region ServiceStation
  68. public IEnumerable<SsApiDesc> ApiDesc_GetActive()
  69. {
  70. return apiLoadBalancingMng.GetAllApiDesc();
  71. }
  72. public IEnumerable<SsApiDesc> ApiDesc_GetAll()
  73. {
  74. return apiStationMng.ApiDesc_GetAll();
  75. }
  76. #endregion
  77. #region CallApi
  78. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  79. public override void CallApiAsync(ApiMessage requestMessage, Object sender, Action<object, Vit.Core.Util.Pipelines.ByteData> callback)
  80. {
  81. RpcContextData rpcData = null;
  82. try
  83. {
  84. rpcData = RpcContextData.FromBytes(requestMessage.rpcContextData_OriData);
  85. #region (x.0)ApiScopeEvent
  86. apiScopeEventList?.ForEach(onScope =>
  87. {
  88. try
  89. {
  90. var onDispose = onScope(rpcData, requestMessage);
  91. if (onDispose != null)
  92. {
  93. callback += onDispose;
  94. }
  95. }
  96. catch (Exception ex)
  97. {
  98. Logger.Error(ex);
  99. }
  100. });
  101. #endregion
  102. #region (x.1)route 判空
  103. if (string.IsNullOrWhiteSpace(rpcData.route))
  104. {
  105. //返回api 不存在
  106. SendReply(SsError.Err_ApiNotExists);
  107. return;
  108. }
  109. #endregion
  110. #region (x.2) 服务限流 BeforeLoadBalancing
  111. var error = rateLimitMng.BeforeLoadBalancing(rpcData, requestMessage);
  112. if (null != error)
  113. {
  114. SendReply(error);
  115. return;
  116. }
  117. #endregion
  118. #region (x.3) 负载均衡,获取对应服务端
  119. var apiNode = apiLoadBalancingMng.GetCurApiNodeByLoadBalancing(rpcData, out var routeType);
  120. if (null == apiNode)
  121. {
  122. //返回api 不存在
  123. SendReply(SsError.Err_ApiNotExists);
  124. return;
  125. }
  126. #endregion
  127. #region (x.4) 服务限流 BeforeCallRemoteApi
  128. error = rateLimitMng.BeforeCallRemoteApi(rpcData, requestMessage, apiNode);
  129. if (null != error)
  130. {
  131. SendReply(error);
  132. return;
  133. }
  134. #endregion
  135. #region (x.5) BeforeCallApi
  136. try
  137. {
  138. BeforeCallApi?.Invoke(rpcData, requestMessage);
  139. }
  140. catch (Exception ex)
  141. {
  142. Logger.Error(ex);
  143. }
  144. #endregion
  145. #region (x.6) 权限校验 SsValid
  146. // 权限校验不通过,调用次数也计数
  147. // TODO:应当有其他计数
  148. JObject oriJson = null;
  149. //(x.x.1) rpcValidations Sers1校验
  150. if (apiNode.apiDesc.rpcValidations != null && apiNode.apiDesc.rpcValidations.Count > 0)
  151. {
  152. if (oriJson == null) oriJson = rpcData.ConvertBySerialize<JObject>();
  153. if (!Sers.Core.Module.Valid.Sers1.RpcVerify1.Verify(oriJson, apiNode.apiDesc.rpcValidations, out var validError))
  154. {
  155. SendReply(validError);
  156. return;
  157. }
  158. }
  159. //(x.x.2) rpcVerify2 Sers2校验
  160. if (apiNode.apiDesc.rpcVerify2 != null && apiNode.apiDesc.rpcVerify2.Count > 0)
  161. {
  162. if (oriJson == null) oriJson = rpcData.ConvertBySerialize<JObject>();
  163. if (!Sers.Core.Module.Valid.Sers2.RpcVerify2.Verify(oriJson, apiNode.apiDesc.rpcVerify2, out var verifyError))
  164. {
  165. SendReply(verifyError);
  166. return;
  167. }
  168. }
  169. #endregion
  170. #region (x.7) RpcContextData 修正
  171. //(x.x.1) 修正route
  172. // 调用服务端 泛接口(如: "/station1/fold2/*")时,route应修正为"/station1/fold2/*",而不是原始 地址(如: "/station1/fold2/index.html")
  173. if (routeType == ERouteType.genericRoute)
  174. {
  175. rpcData.route = apiNode.apiDesc.route;
  176. requestMessage.rpcContextData_OriData = ArraySegmentByteExtensions.Null;
  177. }
  178. //(x.x.2) 修正 requestMessage
  179. if (requestMessage.rpcContextData_OriData.Count <= 0)
  180. {
  181. requestMessage.RpcContextData_OriData_Set(rpcData);
  182. }
  183. #endregion
  184. #region (x.8)服务调用
  185. apiNode.CallApiAsync(rpcData, requestMessage, sender, callback);
  186. #endregion
  187. }
  188. catch (Exception ex)
  189. {
  190. Logger.Error(ex);
  191. ApiSysError.LogSysError(rpcData, requestMessage, ex.ToSsError());
  192. SendReply(SsError.Err_SysErr);
  193. return;
  194. }
  195. void SendReply(SsError error)
  196. {
  197. //callback(sender, new ApiMessage().InitByError(error).SetSysErrToRpcData(error).Package().ByteDataToBytes().BytesToArraySegmentByte());
  198. callback(sender, new ApiMessage().InitAsApiReplyMessageByError(error).Package());
  199. }
  200. }
  201. #endregion
  202. #region ServiceStation
  203. public List<ServiceStationData> ServiceStation_GetAll()
  204. {
  205. return serviceStationMng.ServiceStation_GetAll();
  206. }
  207. public override void ServiceStation_Regist(ServiceStation serviceStation)
  208. {
  209. Logger.Info("[ApiCenterService]Regist serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  210. serviceStationMng.ServiceStation_Add(serviceStation);
  211. }
  212. /// <summary>
  213. /// 更新服务站点设备硬件信息
  214. /// </summary>
  215. /// <param name="serviceStation"></param>
  216. public override bool ServiceStation_UpdateStationInfo(ServiceStation serviceStation)
  217. {
  218. Logger.Info("[ApiCenterService]ServiceStation_UpdateStationInfo", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  219. return serviceStationMng.ServiceStation_UpdateStationInfo(serviceStation);
  220. }
  221. public override void ServiceStation_Remove(IOrganizeConnection conn)
  222. {
  223. string connKey = "" + conn.GetHashCode();
  224. var serviceStation = serviceStationMng.ServiceStation_Remove(connKey);
  225. if (serviceStation != null)
  226. {
  227. Logger.Info("[ApiCenterService]Remove serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  228. }
  229. }
  230. public bool ServiceStation_Pause(string connKey)
  231. {
  232. var serviceStation = serviceStationMng.ServiceStation_Pause(connKey);
  233. if (serviceStation != null)
  234. {
  235. Logger.Info("[ApiCenterService]Pause serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  236. }
  237. return serviceStation != null;
  238. }
  239. public bool ServiceStation_Start(string connKey)
  240. {
  241. var serviceStation = serviceStationMng.ServiceStation_Start(connKey);
  242. if (serviceStation != null)
  243. {
  244. Logger.Info("[ApiCenterService]Start serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  245. }
  246. return serviceStation != null;
  247. }
  248. public bool ServiceStation_Stop(string connKey)
  249. {
  250. var serviceStation = serviceStationMng.ServiceStation_Remove(connKey);
  251. if (serviceStation != null)
  252. {
  253. Logger.Info("[ApiCenterService]Stop serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  254. serviceStation.connection.Close();
  255. }
  256. return serviceStation != null;
  257. }
  258. #endregion
  259. #region ApiStation
  260. public List<ApiStationData> ApiStation_GetAll()
  261. {
  262. return apiStationMng.ApiStation_GetAll();
  263. }
  264. public bool ApiStation_Pause(string stationName)
  265. {
  266. Logger.Info("[ApiCenterService]Pause ApiStation", new { stationName });
  267. return apiStationMng.ApiStation_Pause(stationName);
  268. }
  269. public bool ApiStation_Start(string stationName)
  270. {
  271. Logger.Info("[ApiCenterService]Start ApiStation", new { stationName });
  272. return apiStationMng.ApiStation_Start(stationName);
  273. }
  274. #endregion
  275. #region ApiScopeEvent
  276. /// <summary>
  277. ///
  278. /// </summary>
  279. List<Func<RpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>>> apiScopeEventList = null;
  280. /// <summary>
  281. /// 在调用api前调用onScope,若onScope返回的结果(onDispose)不为空,则在api调用结束前调用onDispose
  282. /// </summary>
  283. /// <param name="apiScopeEvent"></param>
  284. public void AddApiScopeEvent(Func<RpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>> apiScopeEvent)
  285. {
  286. if (apiScopeEventList == null) apiScopeEventList = new List<Func<RpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>>>();
  287. apiScopeEventList.Add(apiScopeEvent);
  288. }
  289. #endregion
  290. }
  291. }