SerslotServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. requestFeature.Headers.Add("MS-ASPNETCORE-TOKEN", pairingToken);
  36. requestFeature.Headers.Add("X-Forwarded-Proto", "https");
  37. var features = new FeatureCollection();
  38. features.Set<IHttpRequestFeature>(requestFeature);
  39. //var _responseFeature = new SerslotResponseFeature() { Body = new MemoryStream() };
  40. var _responseFeature = new HttpResponseFeature() { Body = new MemoryStream() };
  41. features.Set<IHttpResponseFeature>(_responseFeature);
  42. OnProcessRequest(features);
  43. return _responseFeature;
  44. }
  45. #region SerslotResponseFeature
  46. class SerslotResponseFeature : IHttpResponseFeature
  47. {
  48. public int StatusCode
  49. {
  50. get;
  51. set;
  52. }
  53. public string ReasonPhrase
  54. {
  55. get;
  56. set;
  57. }
  58. public IHeaderDictionary Headers
  59. {
  60. get;
  61. set;
  62. }
  63. public Stream Body
  64. {
  65. get;
  66. set;
  67. }
  68. public virtual bool HasStarted { get; set; } = false;
  69. public SerslotResponseFeature()
  70. {
  71. StatusCode = 200;
  72. Headers = new HeaderDictionary();
  73. Body = Stream.Null;
  74. }
  75. private Stack<KeyValuePair<Func<object, Task>, object>> _onStarting;
  76. private Stack<KeyValuePair<Func<object, Task>, object>> _onCompleted;
  77. #region OnStarting
  78. public virtual void OnStarting(Func<object, Task> callback, object state)
  79. {
  80. lock (this)
  81. {
  82. if (HasStarted)
  83. {
  84. throw new InvalidOperationException(nameof(OnStarting));
  85. }
  86. if (_onStarting == null)
  87. {
  88. _onStarting = new Stack<KeyValuePair<Func<object, Task>, object>>();
  89. }
  90. _onStarting.Push(new KeyValuePair<Func<object, Task>, object>(callback, state));
  91. }
  92. }
  93. public Task FireOnStarting()
  94. {
  95. Stack<KeyValuePair<Func<object, Task>, object>> onStarting;
  96. lock (this)
  97. {
  98. onStarting = _onStarting;
  99. _onStarting = null;
  100. }
  101. if (onStarting == null)
  102. {
  103. return Task.CompletedTask;
  104. }
  105. else
  106. {
  107. return FireOnStartingMayAwait(onStarting);
  108. }
  109. }
  110. private Task FireOnStartingMayAwait(Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
  111. {
  112. try
  113. {
  114. var count = onStarting.Count;
  115. for (var i = 0; i < count; i++)
  116. {
  117. var entry = onStarting.Pop();
  118. var task = entry.Key.Invoke(entry.Value);
  119. if (!ReferenceEquals(task, Task.CompletedTask))
  120. {
  121. return FireOnStartingAwaited(task, onStarting);
  122. }
  123. }
  124. }
  125. catch (Exception ex)
  126. {
  127. Logger.Error(ex);
  128. }
  129. return Task.CompletedTask;
  130. }
  131. private async Task FireOnStartingAwaited(Task currentTask, Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
  132. {
  133. try
  134. {
  135. await currentTask;
  136. var count = onStarting.Count;
  137. for (var i = 0; i < count; i++)
  138. {
  139. var entry = onStarting.Pop();
  140. await entry.Key.Invoke(entry.Value);
  141. }
  142. }
  143. catch (Exception ex)
  144. {
  145. Logger.Error(ex);
  146. }
  147. }
  148. #endregion
  149. #region OnCompleted
  150. public virtual void OnCompleted(Func<object, Task> callback, object state)
  151. {
  152. lock (this)
  153. {
  154. if (onCompleted == null)
  155. {
  156. onCompleted = new Stack<KeyValuePair<Func<object, Task>, object>>();
  157. }
  158. onCompleted.Push(new KeyValuePair<Func<object, Task>, object>(callback, state));
  159. }
  160. }
  161. Stack<KeyValuePair<Func<object, Task>, object>> onCompleted = null;
  162. public Task FireOnCompleted()
  163. {
  164. Stack<KeyValuePair<Func<object, Task>, object>> onCompleted;
  165. lock (this)
  166. {
  167. onCompleted = _onCompleted;
  168. _onCompleted = null;
  169. }
  170. if (onCompleted == null)
  171. {
  172. return Task.CompletedTask;
  173. }
  174. return FireOnCompletedAwaited(onCompleted);
  175. }
  176. private async Task FireOnCompletedAwaited(Stack<KeyValuePair<Func<object, Task>, object>> onCompleted)
  177. {
  178. foreach (var entry in onCompleted)
  179. {
  180. try
  181. {
  182. await entry.Key.Invoke(entry.Value);
  183. }
  184. catch (Exception ex)
  185. {
  186. Logger.Error(ex);
  187. }
  188. }
  189. }
  190. #endregion
  191. }
  192. #endregion
  193. #endregion
  194. public IFeatureCollection Features { get; } = new FeatureCollection();
  195. public async Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken)
  196. {
  197. try
  198. {
  199. #region (x.1) build OnProcessRequest
  200. OnProcessRequest = (features) =>
  201. {
  202. Exception _applicationException = null;
  203. var httpContext = application.CreateContext(features);
  204. try
  205. {
  206. // Run the application code for this request
  207. application.ProcessRequestAsync(httpContext).GetAwaiter().GetResult();
  208. //var _responseFeature = features.Get<IHttpResponseFeature>() as SerslotResponseFeature;
  209. //if (_responseFeature != null)
  210. //{
  211. // _responseFeature.FireOnStarting();
  212. // _responseFeature.FireOnCompleted();
  213. //}
  214. }
  215. catch (Exception ex)
  216. {
  217. _applicationException = ex;
  218. Logger.Error(ex);
  219. }
  220. application.DisposeContext(httpContext, _applicationException);
  221. };
  222. #endregion
  223. #region (x.2) start ServiceStation
  224. #region (x.x.1) Init
  225. ServiceStation.ServiceStation.Init();
  226. Sers.Core.Module.App.SersApplication.onStop += () =>
  227. {
  228. IApplicationLifetime lifetime = serviceProvider.GetService(typeof(IApplicationLifetime)) as IApplicationLifetime;
  229. if (lifetime != null) {
  230. lifetime.StopApplication();
  231. }
  232. };
  233. #endregion
  234. #region (x.x.2)¼ÓÔØapi
  235. ServiceStation.ServiceStation.Instance.LoadApi();
  236. ServiceStation.ServiceStation.Instance.localApiService.LoadSerslotApi(Assembly.GetEntryAssembly(),this);
  237. #endregion
  238. //(x.x.3)Start ServiceStation
  239. if (!ServiceStation.ServiceStation.Start())
  240. {
  241. Dispose();
  242. }
  243. #endregion
  244. }
  245. catch (Exception ex)
  246. {
  247. Dispose();
  248. throw;
  249. }
  250. }
  251. // Graceful shutdown if possible
  252. public async Task StopAsync(CancellationToken cancellationToken)
  253. {
  254. try
  255. {
  256. ServiceStation.ServiceStation.Stop();
  257. }
  258. catch (Exception ex)
  259. {
  260. Logger.Error(ex);
  261. }
  262. }
  263. // Ungraceful shutdown
  264. public void Dispose()
  265. {
  266. var cancelledTokenSource = new CancellationTokenSource();
  267. cancelledTokenSource.Cancel();
  268. StopAsync(cancelledTokenSource.Token).GetAwaiter().GetResult();
  269. }
  270. }
  271. }