HTTP1Handler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #if !UNITY_WEBGL || UNITY_EDITOR
  2. using System;
  3. using BestHTTP.Core;
  4. using BestHTTP.Logger;
  5. using BestHTTP.PlatformSupport.Threading;
  6. #if !BESTHTTP_DISABLE_CACHING
  7. using BestHTTP.Caching;
  8. #endif
  9. using BestHTTP.Timings;
  10. namespace BestHTTP.Connections
  11. {
  12. public sealed class HTTP1Handler : IHTTPRequestHandler
  13. {
  14. public bool HasCustomRequestProcessor { get { return false; } }
  15. public KeepAliveHeader KeepAlive { get { return this._keepAlive; } }
  16. private KeepAliveHeader _keepAlive;
  17. public bool CanProcessMultiple { get { return false; } }
  18. private readonly HTTPConnection conn;
  19. public LoggingContext Context { get; private set; }
  20. public HTTP1Handler(HTTPConnection conn)
  21. {
  22. this.Context = new LoggingContext(this);
  23. this.conn = conn;
  24. }
  25. public void Process(HTTPRequest request)
  26. {
  27. }
  28. public void RunHandler()
  29. {
  30. HTTPManager.Logger.Information("HTTP1Handler", string.Format("[{0}] started processing request '{1}'", this, this.conn.CurrentRequest.CurrentUri.ToString()), this.Context, this.conn.CurrentRequest.Context);
  31. ThreadedRunner.SetThreadName("BestHTTP.HTTP1 R&W");
  32. HTTPConnectionStates proposedConnectionState = HTTPConnectionStates.Processing;
  33. bool resendRequest = false;
  34. try
  35. {
  36. if (this.conn.CurrentRequest.IsCancellationRequested)
  37. return;
  38. #if !BESTHTTP_DISABLE_CACHING
  39. // Setup cache control headers before we send out the request
  40. if (!this.conn.CurrentRequest.DisableCache)
  41. HTTPCacheService.SetHeaders(this.conn.CurrentRequest);
  42. #endif
  43. // Write the request to the stream
  44. this.conn.CurrentRequest.QueuedAt = DateTime.MinValue;
  45. this.conn.CurrentRequest.ProcessingStarted = DateTime.UtcNow;
  46. this.conn.CurrentRequest.SendOutTo(this.conn.connector.Stream);
  47. this.conn.CurrentRequest.Timing.Add(TimingEventNames.Request_Sent);
  48. if (this.conn.CurrentRequest.IsCancellationRequested)
  49. return;
  50. this.conn.CurrentRequest.OnCancellationRequested += OnCancellationRequested;
  51. // Receive response from the server
  52. bool received = Receive(this.conn.CurrentRequest);
  53. this.conn.CurrentRequest.Timing.Add(TimingEventNames.Response_Received);
  54. if (this.conn.CurrentRequest.IsCancellationRequested)
  55. return;
  56. if (!received && this.conn.CurrentRequest.Retries < this.conn.CurrentRequest.MaxRetries)
  57. {
  58. proposedConnectionState = HTTPConnectionStates.Closed;
  59. this.conn.CurrentRequest.Retries++;
  60. resendRequest = true;
  61. return;
  62. }
  63. ConnectionHelper.HandleResponse(this.conn.ToString(), this.conn.CurrentRequest, out resendRequest, out proposedConnectionState, ref this._keepAlive, this.conn.Context, this.conn.CurrentRequest.Context);
  64. }
  65. catch (TimeoutException e)
  66. {
  67. this.conn.CurrentRequest.Response = null;
  68. // Do nothing here if Abort() got called on the request, its State is already set.
  69. if (!this.conn.CurrentRequest.IsTimedOut)
  70. {
  71. // We will try again only once
  72. if (this.conn.CurrentRequest.Retries < this.conn.CurrentRequest.MaxRetries)
  73. {
  74. this.conn.CurrentRequest.Retries++;
  75. resendRequest = true;
  76. }
  77. else
  78. {
  79. this.conn.CurrentRequest.Exception = e;
  80. this.conn.CurrentRequest.State = HTTPRequestStates.ConnectionTimedOut;
  81. }
  82. }
  83. proposedConnectionState = HTTPConnectionStates.Closed;
  84. }
  85. catch (Exception e)
  86. {
  87. if (this.ShutdownType == ShutdownTypes.Immediate)
  88. return;
  89. string exceptionMessage = string.Empty;
  90. if (e == null)
  91. exceptionMessage = "null";
  92. else
  93. {
  94. System.Text.StringBuilder sb = PlatformSupport.Text.StringBuilderPool.Get(1);
  95. Exception exception = e;
  96. int counter = 1;
  97. while (exception != null)
  98. {
  99. sb.AppendFormat("{0}: {1} {2}", counter++.ToString(), exception.Message, exception.StackTrace);
  100. exception = exception.InnerException;
  101. if (exception != null)
  102. sb.AppendLine();
  103. }
  104. exceptionMessage = PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb);
  105. }
  106. HTTPManager.Logger.Verbose("HTTP1Handler", exceptionMessage, this.Context, this.conn.CurrentRequest.Context);
  107. #if !BESTHTTP_DISABLE_CACHING
  108. if (this.conn.CurrentRequest.UseStreaming)
  109. HTTPCacheService.DeleteEntity(this.conn.CurrentRequest.CurrentUri);
  110. #endif
  111. // Something gone bad, Response must be null!
  112. this.conn.CurrentRequest.Response = null;
  113. // Do nothing here if Abort() got called on the request, its State is already set.
  114. if (!this.conn.CurrentRequest.IsCancellationRequested)
  115. {
  116. this.conn.CurrentRequest.Exception = e;
  117. this.conn.CurrentRequest.State = HTTPRequestStates.Error;
  118. }
  119. proposedConnectionState = HTTPConnectionStates.Closed;
  120. }
  121. finally
  122. {
  123. this.conn.CurrentRequest.OnCancellationRequested -= OnCancellationRequested;
  124. // Exit ASAP
  125. if (this.ShutdownType != ShutdownTypes.Immediate)
  126. {
  127. if (this.conn.CurrentRequest.IsCancellationRequested)
  128. {
  129. // we don't know what stage the request is canceled, we can't safely reuse the tcp channel.
  130. proposedConnectionState = HTTPConnectionStates.Closed;
  131. this.conn.CurrentRequest.Response = null;
  132. // The request's State already set, or going to be set soon in RequestEvents.cs.
  133. //this.conn.CurrentRequest.State = this.conn.CurrentRequest.IsTimedOut ? HTTPRequestStates.TimedOut : HTTPRequestStates.Aborted;
  134. }
  135. else if (resendRequest)
  136. {
  137. // Here introducing a ClosedResendRequest connection state, where we have to process the connection's state change to Closed
  138. // than we have to resend the request.
  139. // If we would send the Resend request here, than a few lines below the Closed connection state change,
  140. // request events are processed before connection events (just switching the EnqueueRequestEvent and EnqueueConnectionEvent wouldn't work
  141. // see order of ProcessQueues in HTTPManager.OnUpdate!) and it would pick this very same closing/closed connection!
  142. if (proposedConnectionState == HTTPConnectionStates.Closed || proposedConnectionState == HTTPConnectionStates.ClosedResendRequest)
  143. ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, this.conn.CurrentRequest));
  144. else
  145. RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.conn.CurrentRequest, RequestEvents.Resend));
  146. }
  147. else if (this.conn.CurrentRequest.Response != null && this.conn.CurrentRequest.Response.IsUpgraded)
  148. {
  149. proposedConnectionState = HTTPConnectionStates.WaitForProtocolShutdown;
  150. }
  151. else if (this.conn.CurrentRequest.State == HTTPRequestStates.Processing)
  152. {
  153. if (this.conn.CurrentRequest.Response != null)
  154. this.conn.CurrentRequest.State = HTTPRequestStates.Finished;
  155. else
  156. {
  157. this.conn.CurrentRequest.Exception = new Exception(string.Format("[{0}] Remote server closed the connection before sending response header! Previous request state: {1}. Connection state: {2}",
  158. this.ToString(),
  159. this.conn.CurrentRequest.State.ToString(),
  160. this.conn.State.ToString()));
  161. this.conn.CurrentRequest.State = HTTPRequestStates.Error;
  162. proposedConnectionState = HTTPConnectionStates.Closed;
  163. }
  164. }
  165. this.conn.CurrentRequest = null;
  166. if (proposedConnectionState == HTTPConnectionStates.Processing)
  167. proposedConnectionState = HTTPConnectionStates.Recycle;
  168. if (proposedConnectionState != HTTPConnectionStates.ClosedResendRequest)
  169. ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, proposedConnectionState));
  170. }
  171. }
  172. }
  173. private void OnCancellationRequested(HTTPRequest obj)
  174. {
  175. if (this.conn != null && this.conn.connector != null)
  176. this.conn.connector.Dispose();
  177. }
  178. private bool Receive(HTTPRequest request)
  179. {
  180. SupportedProtocols protocol = HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri);
  181. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  182. HTTPManager.Logger.Verbose("HTTPConnection", string.Format("[{0}] - Receive - protocol: {1}", this.ToString(), protocol.ToString()), this.Context, request.Context);
  183. request.Response = HTTPProtocolFactory.Get(protocol, request, this.conn.connector.Stream, request.UseStreaming, false);
  184. if (!request.Response.Receive())
  185. {
  186. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  187. HTTPManager.Logger.Verbose("HTTP1Handler", string.Format("[{0}] - Receive - Failed! Response will be null, returning with false.", this.ToString()), this.Context, request.Context);
  188. request.Response = null;
  189. return false;
  190. }
  191. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  192. HTTPManager.Logger.Verbose("HTTP1Handler", string.Format("[{0}] - Receive - Finished Successfully!", this.ToString()), this.Context, request.Context);
  193. return true;
  194. }
  195. public ShutdownTypes ShutdownType { get; private set; }
  196. public void Shutdown(ShutdownTypes type)
  197. {
  198. this.ShutdownType = type;
  199. }
  200. public void Dispose()
  201. {
  202. Dispose(true);
  203. GC.SuppressFinalize(this);
  204. }
  205. private void Dispose(bool disposing)
  206. {
  207. }
  208. ~HTTP1Handler()
  209. {
  210. Dispose(false);
  211. }
  212. }
  213. }
  214. #endif