SerslotServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Hosting.Server;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.AspNetCore.Http.Features;
  11. using Vit.Core.Module.Log;
  12. using Vit.Extensions;
  13. namespace Sers.Serslot
  14. {
  15. public class SerslotServer : IServer
  16. {
  17. public IServiceProvider serviceProvider { get; set; }
  18. #region PairingToken
  19. string pairingToken;
  20. public void InitPairingToken(IWebHostBuilder hostBuilder)
  21. {
  22. //search "MS-ASPNETCORE-TOKEN" to know why
  23. string PairingToken = "TOKEN";
  24. pairingToken = hostBuilder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");
  25. }
  26. #endregion
  27. #region ProcessRequest
  28. Action<FeatureCollection> OnProcessRequest;
  29. public IHttpResponseFeature ProcessRequest(HttpRequestFeature requestFeature)
  30. {
  31. if (requestFeature.Headers == null)
  32. requestFeature.Headers = new HeaderDictionary();
  33. //var header = "{\"Cache-Control\":\"max-age=0\",\"Connection\":\"Keep-Alive\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Accept-Encoding\":\"gzip, deflate\",\"Accept-Language\":\"zh-CN,zh;q=0.8\",\"Host\":\"localhost:44308\",\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0\",\"Upgrade-Insecure-Requests\":\"1\",\"X-Forwarded-For\":\"127.0.0.1:53093\",\"X-Forwarded-Proto\":\"https\"}";
  34. //header = "{\"Host\":\"localhost:44308\",\"X-Forwarded-For\":\"127.0.0.1:53093\",\"X-Forwarded-Proto\":\"https\"}";
  35. //ʹÓÃAdd¿ÉÄܱ¨´í An item with the same key has already been added. Key: X-Forwarded-Proto"
  36. //requestFeature.Headers.Add("MS-ASPNETCORE-TOKEN", pairingToken);
  37. //requestFeature.Headers.Add("X-Forwarded-Proto", "https");
  38. requestFeature.Headers["MS-ASPNETCORE-TOKEN"] = pairingToken;
  39. requestFeature.Headers["X-Forwarded-Proto"] = "https";
  40. var features = new FeatureCollection();
  41. features.Set<IHttpRequestFeature>(requestFeature);
  42. //var _responseFeature = new SerslotResponseFeature() { Body = new MemoryStream() };
  43. var _responseFeature = new HttpResponseFeature() { Body = new MemoryStream() };
  44. features.Set<IHttpResponseFeature>(_responseFeature);
  45. OnProcessRequest(features);
  46. return _responseFeature;
  47. }
  48. #region SerslotResponseFeature
  49. class SerslotResponseFeature : IHttpResponseFeature
  50. {
  51. public int StatusCode
  52. {
  53. get;
  54. set;
  55. }
  56. public string ReasonPhrase
  57. {
  58. get;
  59. set;
  60. }
  61. public IHeaderDictionary Headers
  62. {
  63. get;
  64. set;
  65. }
  66. public Stream Body
  67. {
  68. get;
  69. set;
  70. }
  71. public virtual bool HasStarted { get; set; } = false;
  72. public SerslotResponseFeature()
  73. {
  74. StatusCode = 200;
  75. Headers = new HeaderDictionary();
  76. Body = Stream.Null;
  77. }
  78. private Stack<KeyValuePair<Func<object, Task>, object>> _onStarting;
  79. private Stack<KeyValuePair<Func<object, Task>, object>> _onCompleted;
  80. #region OnStarting
  81. public virtual void OnStarting(Func<object, Task> callback, object state)
  82. {
  83. lock (this)
  84. {
  85. if (HasStarted)
  86. {
  87. throw new InvalidOperationException(nameof(OnStarting));
  88. }
  89. if (_onStarting == null)
  90. {
  91. _onStarting = new Stack<KeyValuePair<Func<object, Task>, object>>();
  92. }
  93. _onStarting.Push(new KeyValuePair<Func<object, Task>, object>(callback, state));
  94. }
  95. }
  96. public Task FireOnStarting()
  97. {
  98. Stack<KeyValuePair<Func<object, Task>, object>> onStarting;
  99. lock (this)
  100. {
  101. onStarting = _onStarting;
  102. _onStarting = null;
  103. }
  104. if (onStarting == null)
  105. {
  106. return Task.CompletedTask;
  107. }
  108. else
  109. {
  110. return FireOnStartingMayAwait(onStarting);
  111. }
  112. }
  113. private Task FireOnStartingMayAwait(Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
  114. {
  115. try
  116. {
  117. var count = onStarting.Count;
  118. for (var i = 0; i < count; i++)
  119. {
  120. var entry = onStarting.Pop();
  121. var task = entry.Key.Invoke(entry.Value);
  122. if (!ReferenceEquals(task, Task.CompletedTask))
  123. {
  124. return FireOnStartingAwaited(task, onStarting);
  125. }
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. Logger.Error(ex);
  131. }
  132. return Task.CompletedTask;
  133. }
  134. private async Task FireOnStartingAwaited(Task currentTask, Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
  135. {
  136. try
  137. {
  138. await currentTask;
  139. var count = onStarting.Count;
  140. for (var i = 0; i < count; i++)
  141. {
  142. var entry = onStarting.Pop();
  143. await entry.Key.Invoke(entry.Value);
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. Logger.Error(ex);
  149. }
  150. }
  151. #endregion
  152. #region OnCompleted
  153. public virtual void OnCompleted(Func<object, Task> callback, object state)
  154. {
  155. lock (this)
  156. {
  157. if (onCompleted == null)
  158. {
  159. onCompleted = new Stack<KeyValuePair<Func<object, Task>, object>>();
  160. }
  161. onCompleted.Push(new KeyValuePair<Func<object, Task>, object>(callback, state));
  162. }
  163. }
  164. Stack<KeyValuePair<Func<object, Task>, object>> onCompleted = null;
  165. public Task FireOnCompleted()
  166. {
  167. Stack<KeyValuePair<Func<object, Task>, object>> onCompleted;
  168. lock (this)
  169. {
  170. onCompleted = _onCompleted;
  171. _onCompleted = null;
  172. }
  173. if (onCompleted == null)
  174. {
  175. return Task.CompletedTask;
  176. }
  177. return FireOnCompletedAwaited(onCompleted);
  178. }
  179. private async Task FireOnCompletedAwaited(Stack<KeyValuePair<Func<object, Task>, object>> onCompleted)
  180. {
  181. foreach (var entry in onCompleted)
  182. {
  183. try
  184. {
  185. await entry.Key.Invoke(entry.Value);
  186. }
  187. catch (Exception ex)
  188. {
  189. Logger.Error(ex);
  190. }
  191. }
  192. }
  193. #endregion
  194. }
  195. #endregion
  196. #endregion
  197. public IFeatureCollection Features { get; } = new FeatureCollection();
  198. public async Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken)
  199. {
  200. try
  201. {
  202. #region (x.1) build OnProcessRequest
  203. OnProcessRequest = (features) =>
  204. {
  205. Exception _applicationException = null;
  206. var httpContext = application.CreateContext(features);
  207. try
  208. {
  209. // Run the application code for this request
  210. application.ProcessRequestAsync(httpContext).GetAwaiter().GetResult();
  211. //var _responseFeature = features.Get<IHttpResponseFeature>() as SerslotResponseFeature;
  212. //if (_responseFeature != null)
  213. //{
  214. // _responseFeature.FireOnStarting();
  215. // _responseFeature.FireOnCompleted();
  216. //}
  217. }
  218. catch (Exception ex)
  219. {
  220. _applicationException = ex;
  221. Logger.Error(ex);
  222. }
  223. application.DisposeContext(httpContext, _applicationException);
  224. };
  225. #endregion
  226. #region (x.2) start ServiceStation
  227. #region (x.x.1) Init
  228. ServiceStation.ServiceStation.Init();
  229. Sers.Core.Module.App.SersApplication.onStop += () =>
  230. {
  231. if (serviceProvider.GetService(typeof(IApplicationLifetime)) is IApplicationLifetime lifetime)
  232. {
  233. lifetime.StopApplication();
  234. }
  235. };
  236. #endregion
  237. #region (x.x.2)¼ÓÔØapi
  238. ServiceStation.ServiceStation.Instance.LoadApi();
  239. ServiceStation.ServiceStation.Instance.localApiService.LoadSerslotApi(Assembly.GetEntryAssembly(),this);
  240. #endregion
  241. //(x.x.3)Start ServiceStation
  242. if (!ServiceStation.ServiceStation.Start())
  243. {
  244. Dispose();
  245. }
  246. #endregion
  247. }
  248. catch (Exception ex)
  249. {
  250. Dispose();
  251. throw;
  252. }
  253. }
  254. // Graceful shutdown if possible
  255. public async Task StopAsync(CancellationToken cancellationToken)
  256. {
  257. try
  258. {
  259. ServiceStation.ServiceStation.Stop();
  260. }
  261. catch (Exception ex)
  262. {
  263. Logger.Error(ex);
  264. }
  265. }
  266. // Ungraceful shutdown
  267. public void Dispose()
  268. {
  269. var cancelledTokenSource = new CancellationTokenSource();
  270. cancelledTokenSource.Cancel();
  271. StopAsync(cancelledTokenSource.Token).GetAwaiter().GetResult();
  272. }
  273. }
  274. }