GoverApiCenterService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. requestMessage.RpcContextData_OriData_Set(rpcData);
  180. }
  181. #endregion
  182. #region (x.8)服务调用
  183. apiNode.CallApiAsync(rpcData, requestMessage, sender,callback);
  184. #endregion
  185. }
  186. catch (Exception ex)
  187. {
  188. Logger.Error(ex);
  189. ApiSysError.LogSysError(rpcData, requestMessage, ex.ToSsError());
  190. SendReply(SsError.Err_SysErr);
  191. return;
  192. }
  193. void SendReply(SsError error)
  194. {
  195. //callback(sender, new ApiMessage().InitByError(error).SetSysErrToRpcData(error).Package().ByteDataToBytes().BytesToArraySegmentByte());
  196. callback(sender, new ApiMessage().InitAsApiReplyMessageByError(error).Package());
  197. }
  198. }
  199. #endregion
  200. #region ServiceStation
  201. public List<ServiceStationData> ServiceStation_GetAll()
  202. {
  203. return serviceStationMng.ServiceStation_GetAll();
  204. }
  205. public override void ServiceStation_Regist(ServiceStation serviceStation)
  206. {
  207. Logger.Info("[ApiCenterService]Regist serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  208. serviceStationMng.ServiceStation_Add(serviceStation);
  209. }
  210. /// <summary>
  211. /// 更新服务站点设备硬件信息
  212. /// </summary>
  213. /// <param name="serviceStation"></param>
  214. public override bool ServiceStation_UpdateStationInfo(ServiceStation serviceStation)
  215. {
  216. Logger.Info("[ApiCenterService]ServiceStation_UpdateStationInfo", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  217. return serviceStationMng.ServiceStation_UpdateStationInfo(serviceStation);
  218. }
  219. public override void ServiceStation_Remove(IOrganizeConnection conn)
  220. {
  221. string connKey = ""+ conn.GetHashCode();
  222. var serviceStation = serviceStationMng.ServiceStation_Remove(connKey);
  223. if (serviceStation != null)
  224. {
  225. Logger.Info("[ApiCenterService]Remove serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  226. }
  227. }
  228. public bool ServiceStation_Pause(string connKey)
  229. {
  230. var serviceStation = serviceStationMng.ServiceStation_Pause(connKey);
  231. if (serviceStation != null)
  232. {
  233. Logger.Info("[ApiCenterService]Pause serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  234. }
  235. return serviceStation != null;
  236. }
  237. public bool ServiceStation_Start(string connKey)
  238. {
  239. var serviceStation = serviceStationMng.ServiceStation_Start(connKey);
  240. if (serviceStation != null)
  241. {
  242. Logger.Info("[ApiCenterService]Start serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  243. }
  244. return serviceStation != null;
  245. }
  246. public bool ServiceStation_Stop(string connKey)
  247. {
  248. var serviceStation = serviceStationMng.ServiceStation_Remove(connKey);
  249. if (serviceStation != null)
  250. {
  251. Logger.Info("[ApiCenterService]Stop serviceStation", new { stationName = serviceStation?.serviceStationInfo?.serviceStationName });
  252. serviceStation.connection.Close();
  253. }
  254. return serviceStation != null;
  255. }
  256. #endregion
  257. #region ApiStation
  258. public List<ApiStationData> ApiStation_GetAll()
  259. {
  260. return apiStationMng.ApiStation_GetAll();
  261. }
  262. public bool ApiStation_Pause(string stationName)
  263. {
  264. Logger.Info("[ApiCenterService]Pause ApiStation", new { stationName });
  265. return apiStationMng.ApiStation_Pause(stationName);
  266. }
  267. public bool ApiStation_Start(string stationName)
  268. {
  269. Logger.Info("[ApiCenterService]Start ApiStation", new { stationName });
  270. return apiStationMng.ApiStation_Start(stationName);
  271. }
  272. #endregion
  273. #region ApiScopeEvent
  274. /// <summary>
  275. ///
  276. /// </summary>
  277. List<Func<RpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>>> apiScopeEventList = null;
  278. /// <summary>
  279. /// 在调用api前调用onScope,若onScope返回的结果(onDispose)不为空,则在api调用结束前调用onDispose
  280. /// </summary>
  281. /// <param name="apiScopeEvent"></param>
  282. public void AddApiScopeEvent(Func<RpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>> apiScopeEvent)
  283. {
  284. if (apiScopeEventList == null) apiScopeEventList=new List<Func<RpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>>>();
  285. apiScopeEventList.Add(apiScopeEvent);
  286. }
  287. #endregion
  288. }
  289. }