JsonRpcHttpServerEngineBase.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. using JsonRpcLite.Log;
  2. using JsonRpcLite.Rpc;
  3. using JsonRpcLite.Services;
  4. using JsonRpcLite.Utilities;
  5. using System;
  6. using System.Buffers;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.IO.Compression;
  10. using System.Net;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace JsonRpcLite.Network
  15. {
  16. public abstract class JsonRpcHttpServerEngineBase : IJsonRpcServerEngine
  17. {
  18. /// <summary>
  19. /// Gets the registered plugins.
  20. /// </summary>
  21. protected List<IJsonRpcHttpServerEnginePlugin> Plugins { get; } = new List<IJsonRpcHttpServerEnginePlugin>();
  22. /// <summary>
  23. /// Gets the engine name.
  24. /// </summary>
  25. public string Name { get; protected set; }
  26. /// <summary>
  27. /// Start the engine and use given router to handle request.
  28. /// </summary>
  29. /// <param name="router">The router which will handle the request.</param>
  30. public abstract void Start(IJsonRpcRouter router);
  31. /// <summary>
  32. /// Stop the engine.
  33. /// </summary>
  34. public abstract void Stop();
  35. /// <summary>
  36. /// Register the plugin into the engine.
  37. /// </summary>
  38. /// <param name="plugin">The plugin to register.</param>
  39. public void RegisterPlugin(IJsonRpcHttpServerEnginePlugin plugin)
  40. {
  41. Plugins.Add(plugin);
  42. }
  43. /// <summary>
  44. /// Read the request data from the input stream.
  45. /// </summary>
  46. /// <param name="inputStream">The stream to handle.</param>
  47. /// <param name="requestData">The request data to fill.</param>
  48. /// <param name="dataLength">The data length to read.</param>
  49. /// <param name="cancellationToken"></param>
  50. private async Task ReadRequestDataAsync(Stream inputStream, byte[] requestData, int dataLength, CancellationToken cancellationToken = default)
  51. {
  52. var length = dataLength;
  53. var offset = 0;
  54. while (length > 0)
  55. {
  56. cancellationToken.ThrowIfCancellationRequested();
  57. var readLength = await inputStream.ReadAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false);
  58. length -= readLength;
  59. offset += readLength;
  60. }
  61. }
  62. /// <summary>
  63. /// Dispatch request to specified service.
  64. /// </summary>
  65. /// <param name="context">The HttpListenerContext</param>
  66. /// <param name="router">The router to handle the rpc request</param>
  67. /// <param name="serviceName">The name of the service</param>
  68. /// <param name="cancellationToken">The cancellation token which can cancel this method</param>
  69. /// <returns>Void</returns>
  70. private async Task DispatchAsync(IJsonRpcHttpContext context, IJsonRpcRouter router, string serviceName, CancellationToken cancellationToken = default)
  71. {
  72. var dataLength = (int)context.GetRequestContentLength();
  73. var requestData = ArrayPool<byte>.Shared.Rent(dataLength);
  74. JsonRpcRequest[] requests;
  75. try
  76. {
  77. var inputStream = context.GetInputStream();
  78. await ReadRequestDataAsync(inputStream, requestData, dataLength, cancellationToken).ConfigureAwait(false);
  79. if (Logger.DebugMode)
  80. {
  81. var requestString = Encoding.UTF8.GetString(requestData);
  82. Logger.WriteDebug($"Receive request data:{requestString}");
  83. }
  84. var handled = false;
  85. //let the plugin pre process the request data.
  86. foreach (var plugin in Plugins)
  87. {
  88. var result = plugin.PreProcess(context, requestData);
  89. requestData = result.Data;
  90. handled = result.Handled;
  91. if (handled)
  92. {
  93. break;
  94. }
  95. }
  96. if (!handled)
  97. {
  98. requests = await JsonRpcCodec.DecodeRequestsAsync(requestData, cancellationToken, dataLength).ConfigureAwait(false);
  99. var responses = await router.DispatchRequestsAsync(serviceName, requests, cancellationToken).ConfigureAwait(false);
  100. var responseData = await JsonRpcCodec.EncodeResponsesAsync(responses, cancellationToken).ConfigureAwait(false);
  101. //let the plugin post process the response data.
  102. foreach (var plugin in Plugins)
  103. {
  104. var result = plugin.PostProcess(context, responseData);
  105. responseData = result.Data;
  106. handled = result.Handled;
  107. if (handled)
  108. {
  109. break;
  110. }
  111. }
  112. if (!handled)
  113. {
  114. await WriteRpcResponsesAsync(context, responseData, cancellationToken).ConfigureAwait(false);
  115. }
  116. else
  117. {
  118. //The response data has been post-processed by the plugin, so just return the data to the remote side.
  119. await WriteHttpResultAsync(context, (int)HttpStatusCode.OK, Encoding.UTF8.GetString(responseData), cancellationToken).ConfigureAwait(false);
  120. }
  121. }
  122. else
  123. {
  124. //The request has been pre-processed by the plugin and no need dispatch, so just return the data to the remote side.
  125. await WriteHttpResultAsync(context, (int)HttpStatusCode.OK, Encoding.UTF8.GetString(requestData), cancellationToken).ConfigureAwait(false);
  126. }
  127. }
  128. finally
  129. {
  130. ArrayPool<byte>.Shared.Return(requestData);
  131. }
  132. }
  133. /// <summary>
  134. /// Parser the request url, get the calling information.
  135. /// </summary>
  136. /// <param name="requestPath">The path requested by the caller.</param>
  137. /// <returns>The service name parsed from the uri.</returns>
  138. private string GetRpcServiceName(string requestPath)
  139. {
  140. var url = $"{requestPath.Trim('/')}";
  141. var urlParts = url.Split('/');
  142. if (urlParts.Length != 1) return null;
  143. return urlParts[0];
  144. }
  145. /// <summary>
  146. /// Write smd data back to the client.
  147. /// </summary>
  148. /// <param name="context">The http context</param>
  149. /// <param name="smdData">The smd data to write back.</param>
  150. /// <param name="cancellationToken">The cancellation token which will cancel this method.</param>
  151. /// <returns>Void</returns>
  152. private async Task WriteSmdDataAsync(IJsonRpcHttpContext context, byte[] smdData, CancellationToken cancellationToken = default)
  153. {
  154. try
  155. {
  156. await WriteRpcResultAsync(context, smdData, cancellationToken).ConfigureAwait(false);
  157. }
  158. catch (Exception ex)
  159. {
  160. Logger.WriteWarning($"Write smd data back to client error:{ex}");
  161. }
  162. }
  163. /// <summary>
  164. /// Write http exception back to the client.
  165. /// </summary>
  166. /// <param name="context">The http context</param>
  167. /// <param name="exception">The exception to write back.</param>
  168. /// <param name="cancellationToken">The cancel token which will cancel this method.</param>
  169. /// <returns>Void</returns>
  170. private async Task WriteHttpExceptionAsync(IJsonRpcHttpContext context, HttpException exception, CancellationToken cancellationToken = default)
  171. {
  172. try
  173. {
  174. await WriteHttpResultAsync(context, exception.ErrorCode, exception.Message, cancellationToken).ConfigureAwait(false);
  175. }
  176. catch (Exception ex)
  177. {
  178. Logger.WriteWarning($"Write http exception back to client error:{ex}");
  179. }
  180. }
  181. /// <summary>
  182. /// Write rpc responses back to the client.
  183. /// </summary>
  184. /// <param name="context">The http context</param>
  185. /// <param name="responses">The responses to write back.</param>
  186. /// <param name="cancellationToken">The cancel token which will cancel this method.</param>
  187. /// <returns>Void</returns>
  188. private async Task WriteRpcResponsesAsync(IJsonRpcHttpContext context, byte[] responseData, CancellationToken cancellationToken = default)
  189. {
  190. try
  191. {
  192. await WriteRpcResultAsync(context, responseData, cancellationToken).ConfigureAwait(false);
  193. }
  194. catch (Exception ex)
  195. {
  196. Logger.WriteWarning($"Write rpc response back to client error:{ex}");
  197. }
  198. }
  199. /// <summary>
  200. /// Get the compressed(or not) output data according to request.
  201. /// </summary>
  202. /// <param name="context">The http context.</param>
  203. /// <param name="data">The data to output.</param>
  204. /// <param name="cancellationToken">The cancellation token which will cancel this method.</param>
  205. /// <returns>The compressed or not output data.</returns>
  206. private async Task<byte[]> GetOutputDataAsync(IJsonRpcHttpContext context, byte[] data, CancellationToken cancellationToken = default)
  207. {
  208. var outputData = data;
  209. var acceptEncoding = context.GetRequestHeader("Accept-Encoding");
  210. if (acceptEncoding != null && acceptEncoding.Contains("gzip"))
  211. {
  212. context.SetResponseHeader("Content-Encoding", "gzip");
  213. using var memoryStream = new MemoryStream();
  214. using var outputStream = new GZipStream(memoryStream, CompressionMode.Compress);
  215. await outputStream.WriteAsync(outputData, 0, outputData.Length, cancellationToken).ConfigureAwait(false);
  216. await outputStream.FlushAsync(cancellationToken).ConfigureAwait(false);
  217. outputData = memoryStream.ToArray();
  218. }
  219. else if (acceptEncoding != null && acceptEncoding.Contains("deflate"))
  220. {
  221. context.SetResponseHeader("Content-Encoding", "deflate");
  222. using var memoryStream = new MemoryStream();
  223. using var outputStream = new DeflateStream(memoryStream, CompressionMode.Compress);
  224. await outputStream.WriteAsync(outputData, 0, outputData.Length, cancellationToken).ConfigureAwait(false);
  225. await outputStream.FlushAsync(cancellationToken).ConfigureAwait(false);
  226. outputData = memoryStream.ToArray();
  227. }
  228. return outputData;
  229. }
  230. /// <summary>
  231. /// Write http message to remote side.
  232. /// </summary>
  233. /// <param name="context">The http context.</param>
  234. /// <param name="statusCode">The status code to return</param>
  235. /// <param name="message">The message to write back.</param>
  236. /// <param name="cancellationToken">The cancellation token which will cancel this method.</param>
  237. /// <returns>Void</returns>
  238. private async Task WriteHttpResultAsync(IJsonRpcHttpContext context, int statusCode, string message, CancellationToken cancellationToken = default)
  239. {
  240. context.SetResponseHeader("Server", "JsonRpcLite");
  241. context.SetResponseHeader("Access-Control-Allow-Origin", "*");
  242. context.SetResponseHeader("Access-Control-Allow-Methods", "*");
  243. context.SetResponseHeader("Access-Control-Allow-Headers", "*");
  244. context.SetResponseStatusCode(statusCode);
  245. context.SetResponseContentType("text/html");
  246. var outputData = await GetOutputDataAsync(context, Encoding.UTF8.GetBytes(message), cancellationToken).ConfigureAwait(false);
  247. context.SetResponseContentLength(outputData.Length);
  248. var outputStream = context.GetOutputStream();
  249. await outputStream.WriteAsync(outputData, 0, outputData.Length, cancellationToken).ConfigureAwait(false);
  250. await outputStream.FlushAsync(cancellationToken).ConfigureAwait(false);
  251. if (Logger.DebugMode)
  252. {
  253. Logger.WriteDebug($"Response data sent:{message}");
  254. }
  255. }
  256. /// <summary>
  257. /// Write rpc result struct data to remote side.
  258. /// </summary>
  259. /// <param name="context">The context of the http.</param>
  260. /// <param name="result">The result data to write</param>
  261. /// <param name="cancellationToken">The cancellation which can cancel this method</param>
  262. /// <returns>Void</returns>
  263. private async Task WriteRpcResultAsync(IJsonRpcHttpContext context, byte[] result, CancellationToken cancellationToken = default)
  264. {
  265. context.SetResponseHeader("Server", "JsonRpcLite");
  266. context.SetResponseHeader("Access-Control-Allow-Origin", "*");
  267. context.SetResponseHeader("Access-Control-Allow-Methods", "*");
  268. context.SetResponseHeader("Access-Control-Allow-Headers", "*");
  269. context.SetResponseStatusCode((int)HttpStatusCode.OK);
  270. context.SetResponseContentType("application/json");
  271. if (result != null)
  272. {
  273. var outputData = await GetOutputDataAsync(context, result, cancellationToken).ConfigureAwait(false);
  274. context.SetResponseContentLength(outputData.Length);
  275. var outputStream = context.GetOutputStream();
  276. await outputStream.WriteAsync(outputData, 0, outputData.Length, cancellationToken).ConfigureAwait(false);
  277. await outputStream.FlushAsync(cancellationToken).ConfigureAwait(false);
  278. }
  279. if (Logger.DebugMode)
  280. {
  281. if (result != null)
  282. {
  283. var resultString = Encoding.UTF8.GetString(result);
  284. Logger.WriteDebug($"Response data sent:{resultString}");
  285. }
  286. }
  287. }
  288. /// <summary>
  289. /// Handle connected request and return result.
  290. /// </summary>
  291. /// <param name="context">The http context to handle.</param>
  292. /// <param name="router">The router to dispatch the request data.</param>
  293. /// <param name="cancellationToken">The cancellation token which can cancel this method.</param>
  294. /// <returns>Void</returns>
  295. protected async Task HandleContextAsync(IJsonRpcHttpContext context, IJsonRpcRouter router, CancellationToken cancellationToken = default)
  296. {
  297. var httpMethod = context.GetRequestHttpMethod();
  298. var requestPath = context.GetRequestPath();
  299. Logger.WriteVerbose($"Handle request [{httpMethod}]: {requestPath}");
  300. try
  301. {
  302. var serviceName = GetRpcServiceName(requestPath);
  303. if (string.IsNullOrEmpty(serviceName))
  304. {
  305. Logger.WriteWarning($"Service for request: {requestPath} not found.");
  306. throw new HttpException((int)HttpStatusCode.ServiceUnavailable, "Service does not exist.");
  307. }
  308. if (httpMethod == "options")
  309. {
  310. try
  311. {
  312. await WriteHttpResultAsync(context, (int)HttpStatusCode.OK, string.Empty, cancellationToken).ConfigureAwait(false);
  313. }
  314. catch (Exception ex)
  315. {
  316. throw new HttpException((int)HttpStatusCode.InternalServerError, ex.Message);
  317. }
  318. }
  319. else if (httpMethod == "get")
  320. {
  321. var smdRequest = false;
  322. var smdIndex = serviceName.LastIndexOf(".smd", StringComparison.InvariantCultureIgnoreCase);
  323. if (smdIndex != -1)
  324. {
  325. serviceName = serviceName.Substring(0, smdIndex);
  326. smdRequest = true;
  327. }
  328. if (!router.ServiceExists(serviceName))
  329. {
  330. Logger.WriteWarning($"Service for request: {requestPath} not found.");
  331. throw new HttpException((int)HttpStatusCode.ServiceUnavailable, $"Service [{serviceName}] does not exist.");
  332. }
  333. if (smdRequest)
  334. {
  335. try
  336. {
  337. var smdData = await router.GetServiceSmdData(serviceName).ConfigureAwait(false);
  338. if (smdData != null)
  339. {
  340. await WriteSmdDataAsync(context, smdData, cancellationToken).ConfigureAwait(false);
  341. }
  342. else
  343. {
  344. throw new HttpException((int)HttpStatusCode.NotFound, $"Resource for {requestPath} does not exist.");
  345. }
  346. }
  347. catch (Exception ex)
  348. {
  349. throw new HttpException((int)HttpStatusCode.InternalServerError, ex.Message);
  350. }
  351. }
  352. else
  353. {
  354. throw new HttpException((int)HttpStatusCode.NotFound, $"Resource for {requestPath} does not exist.");
  355. }
  356. }
  357. else if (httpMethod == "post")
  358. {
  359. if (!router.ServiceExists(serviceName))
  360. {
  361. Logger.WriteWarning($"Service for request: {requestPath} not found.");
  362. throw new ServerErrorException("Service does not exist.", $"Service [{serviceName}] does not exist.");
  363. }
  364. try
  365. {
  366. await DispatchAsync(context, router, serviceName, cancellationToken).ConfigureAwait(false);
  367. }
  368. catch (RpcException)
  369. {
  370. throw;
  371. }
  372. catch (Exception ex)
  373. {
  374. throw new ServerErrorException("Internal server error.", ex.Message);
  375. }
  376. }
  377. else
  378. {
  379. throw new HttpException((int)HttpStatusCode.MethodNotAllowed, $"Invalid http-method:{httpMethod}");
  380. }
  381. }
  382. catch (RpcException rpcException)
  383. {
  384. var response = new JsonRpcResponse();
  385. response.WriteResult(rpcException);
  386. var responseData = await JsonRpcCodec.EncodeResponsesAsync(new[] { response }, cancellationToken).ConfigureAwait(false);
  387. await WriteRpcResponsesAsync(context, responseData, cancellationToken).ConfigureAwait(false);
  388. }
  389. catch (Exception ex)
  390. {
  391. Logger.WriteError($"Handle request {requestPath} error: {ex.Message}");
  392. if (ex is HttpException httpException)
  393. {
  394. await WriteHttpExceptionAsync(context, httpException, cancellationToken).ConfigureAwait(false);
  395. }
  396. else
  397. {
  398. var response = new JsonRpcResponse();
  399. var serverError = new InternalErrorException($"Handle request {requestPath} error: {ex.Message}");
  400. response.WriteResult(serverError);
  401. var responseData = await JsonRpcCodec.EncodeResponsesAsync(new[] { response }, cancellationToken).ConfigureAwait(false);
  402. await WriteRpcResponsesAsync(context, responseData, cancellationToken).ConfigureAwait(false);
  403. }
  404. }
  405. finally
  406. {
  407. context.Close();
  408. }
  409. }
  410. }
  411. }