GoverApiCenterService.cs 13 KB

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