HTTP1ContentConsumer.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. #if !UNITY_WEBGL || UNITY_EDITOR
  2. using System;
  3. using System.Threading;
  4. using Best.HTTP.Request.Timings;
  5. using Best.HTTP.Request.Upload;
  6. using Best.HTTP.Response;
  7. using Best.HTTP.Shared;
  8. using Best.HTTP.Shared.Extensions;
  9. using Best.HTTP.Shared.Logger;
  10. using Best.HTTP.Shared.PlatformSupport.Memory;
  11. using Best.HTTP.Shared.PlatformSupport.Network.Tcp;
  12. using Best.HTTP.Shared.PlatformSupport.Threading;
  13. using Best.HTTP.Shared.Streams;
  14. using static Best.HTTP.Hosts.Connections.HTTP1.Constants;
  15. namespace Best.HTTP.Hosts.Connections.HTTP1
  16. {
  17. public sealed class HTTP1ContentConsumer : IHTTPRequestHandler, IContentConsumer, IDownloadContentBufferAvailable, IThreadSignaler
  18. {
  19. public ShutdownTypes ShutdownType { get; private set; }
  20. public KeepAliveHeader KeepAlive { get { return this._keepAlive; } }
  21. private KeepAliveHeader _keepAlive;
  22. public bool CanProcessMultiple { get { return false; } }
  23. /// <summary>
  24. /// Number of assigned requests to process.
  25. /// </summary>
  26. public int AssignedRequests => this.conn.CurrentRequest == null ? 0 : 1;
  27. /// <summary>
  28. /// Maximum number of assignable requests
  29. /// </summary>
  30. public int MaxAssignedRequests => 1;
  31. public LoggingContext Context { get; private set; }
  32. public PeekableContentProviderStream ContentProvider { get; private set; }
  33. private readonly HTTPOverTCPConnection conn;
  34. private PeekableHTTP1Response _response;
  35. private int _isAlreadyProcessingContent;
  36. private AutoResetEvent _are = new AutoResetEvent(false);
  37. public HTTP1ContentConsumer(HTTPOverTCPConnection conn)
  38. {
  39. this.Context = new LoggingContext(this);
  40. this.conn = conn;
  41. }
  42. public void RunHandler()
  43. {
  44. HTTPManager.Logger.Information(nameof(HTTP1ContentConsumer), "Started processing request", this.Context);
  45. ThreadedRunner.SetThreadName("Best.HTTP1 Write");
  46. try
  47. {
  48. var now = DateTime.Now;
  49. if (this.conn.CurrentRequest.TimeoutSettings.IsTimedOut(now))
  50. throw new TimeoutException();
  51. if (this.conn.CurrentRequest.IsCancellationRequested)
  52. throw new Exception("Cancellation requested!");
  53. // create the response before we would send out the request, because sending out might cause an exception
  54. // and the response is used for decision making in the FinishedProcessing call.
  55. if (this._response == null)
  56. this.conn.CurrentRequest.Response = this._response = new PeekableHTTP1Response(this.conn.CurrentRequest, false, this);
  57. // Write the request to the stream
  58. this.conn.CurrentRequest.TimeoutSettings.SetProcessing(now);
  59. this.conn.CurrentRequest.Timing.StartNext(TimingEventNames.Request_Sent);
  60. SendOutTo(this.conn.CurrentRequest, this.conn.TopStream);
  61. this.conn.CurrentRequest.OnCancellationRequested += OnCancellationRequested;
  62. }
  63. catch (Exception e)
  64. {
  65. if (this.ShutdownType == ShutdownTypes.Immediate)
  66. return;
  67. FinishedProcessing(e);
  68. }
  69. }
  70. private void SendOutTo(HTTPRequest request, System.IO.Stream stream)
  71. {
  72. request.Prepare();
  73. string requestPathAndQuery =
  74. request.ProxySettings.HasProxyFor(request.CurrentUri) ?
  75. request.ProxySettings.Proxy.GetRequestPath(request.CurrentUri) :
  76. request.CurrentUri.GetRequestPathAndQueryURL();
  77. string requestLine = string.Format("{0} {1} HTTP/1.1", HTTPRequest.MethodNames[(byte)request.MethodType], requestPathAndQuery);
  78. if (HTTPManager.Logger.Level <= Loglevels.Information)
  79. HTTPManager.Logger.Information("HTTPRequest", string.Format("Sending request: '{0}'", requestLine), request.Context);
  80. // Create a buffer stream that will not close 'stream' when disposed or closed.
  81. // buffersize should be larger than UploadChunkSize as it might be used for uploading user data and
  82. // it should have enough room for UploadChunkSize data and additional chunk information.
  83. using (WriteOnlyBufferedStream bufferStream = new WriteOnlyBufferedStream(stream, (int)(request.UploadSettings.UploadChunkSize * 1.5f), request.Context))
  84. {
  85. var requestLineBytes = requestLine.GetASCIIBytes();
  86. bufferStream.WriteBufferSegment(requestLineBytes);
  87. bufferStream.WriteArray(EOL);
  88. BufferPool.Release(requestLineBytes);
  89. // Write headers to the buffer
  90. request.EnumerateHeaders((header, values) =>
  91. {
  92. if (string.IsNullOrEmpty(header) || values == null)
  93. return;
  94. //var headerName = string.Concat(header, ": ").GetASCIIBytes();
  95. var headerName = header.GetASCIIBytes();
  96. for (int i = 0; i < values.Count; ++i)
  97. {
  98. if (string.IsNullOrEmpty(values[i]))
  99. {
  100. HTTPManager.Logger.Warning("HTTPRequest", string.Format("Null/empty value for header: {0}", header), request.Context);
  101. continue;
  102. }
  103. if (HTTPManager.Logger.Level <= Loglevels.Information)
  104. HTTPManager.Logger.Verbose("HTTPRequest", $"Header - '{header}': '{values[i]}'", request.Context);
  105. var valueBytes = values[i].GetASCIIBytes();
  106. bufferStream.WriteBufferSegment(headerName);
  107. bufferStream.WriteArray(HeaderValueSeparator);
  108. bufferStream.WriteBufferSegment(valueBytes);
  109. bufferStream.WriteArray(EOL);
  110. BufferPool.Release(valueBytes);
  111. }
  112. BufferPool.Release(headerName);
  113. }, /*callBeforeSendCallback:*/ true);
  114. bufferStream.WriteArray(EOL);
  115. // Send remaining data to the wire
  116. bufferStream.Flush();
  117. this.conn.CurrentRequest.Timing.StartNext(TimingEventNames.Waiting_TTFB);
  118. } // bufferStream.Dispose
  119. //if (!request.UploadSettings.Expect100Continue)
  120. SendContent();
  121. HTTPManager.Logger.Information("HTTPRequest", "Sent out '" + requestLine + "'", this.Context);
  122. }
  123. void SendContent()
  124. {
  125. System.IO.Stream uploadStream = this.conn.CurrentRequest.UploadSettings.UploadStream;
  126. if (uploadStream != null)
  127. {
  128. try
  129. {
  130. if (uploadStream is Request.Upload.UploadStreamBase upStream)
  131. upStream.BeforeSendBody(this.conn.CurrentRequest, this);
  132. using WriteOnlyBufferedStream bufferStream = new WriteOnlyBufferedStream(this.conn.TopStream,
  133. (int)(this.conn.CurrentRequest.UploadSettings.UploadChunkSize * 1.5f),
  134. this.conn.CurrentRequest.Context);
  135. long uploadLength = uploadStream.Length;
  136. bool isChunked = uploadLength == BodyLengths.UnknownWithChunkedTransferEncoding;
  137. // Initialize the progress report variables
  138. long Uploaded = 0;
  139. // Upload buffer. First we will read the data into this buffer from the UploadStream, then write this buffer to our outStream
  140. byte[] buffer = BufferPool.Get(this.conn.CurrentRequest.UploadSettings.UploadChunkSize, true);
  141. using var _ = new AutoReleaseBuffer(buffer);
  142. // How many bytes was read from the UploadStream
  143. int count = uploadStream.Read(buffer, 0, buffer.Length);
  144. while (count != 0)
  145. {
  146. if (count <= 0)
  147. {
  148. this._are.WaitOne();
  149. count = uploadStream.Read(buffer, 0, buffer.Length);
  150. continue;
  151. }
  152. if (isChunked)
  153. {
  154. var countBytes = count.ToString("X").GetASCIIBytes();
  155. bufferStream.WriteBufferSegment(countBytes);
  156. bufferStream.WriteArray(EOL);
  157. BufferPool.Release(countBytes);
  158. }
  159. // write out the buffer to the wire
  160. bufferStream.Write(buffer, 0, count);
  161. // chunk trailing EOL
  162. if (uploadLength < 0)
  163. bufferStream.WriteArray(EOL);
  164. // update how many bytes are uploaded
  165. Uploaded += count;
  166. // Write to the wire
  167. bufferStream.Flush();
  168. if (this.conn.CurrentRequest.UploadSettings.OnUploadProgress != null)
  169. RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.conn.CurrentRequest, RequestEvents.UploadProgress, Uploaded, uploadLength));
  170. if (this.conn.CurrentRequest.IsCancellationRequested)
  171. return;
  172. count = uploadStream.Read(buffer, 0, buffer.Length);
  173. }
  174. // All data from the stream are sent, write the 'end' chunk if necessary
  175. if (isChunked)
  176. {
  177. byte[] noMoreChunkBytes = BufferPool.Get(1, true);
  178. noMoreChunkBytes[0] = (byte)'0';
  179. bufferStream.Write(noMoreChunkBytes, 0, 1);
  180. bufferStream.WriteArray(EOL);
  181. bufferStream.WriteArray(EOL);
  182. BufferPool.Release(noMoreChunkBytes);
  183. }
  184. // Make sure all remaining data will be on the wire
  185. bufferStream.Flush();
  186. }
  187. finally
  188. {
  189. if (this.conn.CurrentRequest.UploadSettings.DisposeStream)
  190. uploadStream.Dispose();
  191. }
  192. }
  193. }
  194. void IDownloadContentBufferAvailable.BufferAvailable(DownloadContentStream stream)
  195. {
  196. //HTTPManager.Logger.Verbose(nameof(HTTP1ContentConsumer), "IDownloadContentBufferAvailable.BufferAvailable", this.Context);
  197. // TODO: Do NOT call OnContent on the Unity main thread
  198. if (this._response != null)
  199. OnContent();
  200. }
  201. public void SetBinding(PeekableContentProviderStream contentProvider) => this.ContentProvider = contentProvider;
  202. public void UnsetBinding() => this.ContentProvider = null;
  203. public void OnContent()
  204. {
  205. if (Interlocked.CompareExchange(ref this._isAlreadyProcessingContent, 1, 0) != 0)
  206. return;
  207. try
  208. {
  209. //HTTPManager.Logger.Information(nameof(HTTP1ContentConsumer), $"OnContent({peekable?.Length}, {this._response?.ReadState})", this.Context, this.conn.CurrentRequest.Context);
  210. try
  211. {
  212. if (this.conn.CurrentRequest.TimeoutSettings.IsTimedOut(DateTime.Now))
  213. throw new TimeoutException();
  214. if (this.conn.CurrentRequest.IsCancellationRequested)
  215. throw new Exception("Cancellation requested!");
  216. this._response.ProcessPeekable(this.ContentProvider);
  217. }
  218. catch (Exception e)
  219. {
  220. if (this.ShutdownType == ShutdownTypes.Immediate)
  221. return;
  222. FinishedProcessing(e);
  223. }
  224. // After an exception, this._response will be null!
  225. if (this._response != null)
  226. {
  227. if (this._response.ReadState == PeekableHTTP1Response.PeekableReadState.Finished)
  228. FinishedProcessing(null);
  229. else if (this._response.ReadState == PeekableHTTP1Response.PeekableReadState.WaitForContentSent)
  230. {
  231. SendContent();
  232. this.conn.CurrentRequest.Timing.StartNext(TimingEventNames.Waiting_TTFB);
  233. }
  234. }
  235. }
  236. finally
  237. {
  238. Interlocked.Exchange(ref this._isAlreadyProcessingContent, 0);
  239. }
  240. }
  241. public void OnConnectionClosed()
  242. {
  243. HTTPManager.Logger.Information(nameof(HTTP1ContentConsumer), $"OnConnectionClosed({this.ContentProvider?.Length}, {this._response?.ReadState})", this.Context);
  244. if (this._response != null &&
  245. this._response.ReadState == PeekableHTTP1Response.PeekableReadState.Content &&
  246. this._response.DeliveryMode == PeekableHTTP1Response.ContentDeliveryMode.RawUnknownLength &&
  247. "close".Equals(this._response.GetFirstHeaderValue("connection"), StringComparison.OrdinalIgnoreCase))
  248. {
  249. FinishedProcessing(null);
  250. }
  251. else if (this.ContentProvider.Length > 0 &&
  252. this._response != null &&
  253. this._response.ReadState == PeekableHTTP1Response.PeekableReadState.Content &&
  254. this._response.DownStream != null)
  255. {
  256. // Let the stream comsume any buffered data first, and handle closure when the buffer depletes.
  257. // TODO: This require however that the PeekableResponse ping this HTTP1ContentConsumer when buffer space is available in the down-stream.
  258. // Or force-add all remaining data to the stream and see whether we finished downloading or not.
  259. // Problems:
  260. // 1.) OnContent might be already called and a call to it would be dropped. We could spin up a new thread waiting for its finish, then call it again.
  261. //throw new NotImplementedException();
  262. ThreadedRunner.RunShortLiving(() =>
  263. {
  264. SpinWait spinWait = new SpinWait();
  265. while (Interlocked.CompareExchange(ref this._isAlreadyProcessingContent, 1, 0) == 1)
  266. spinWait.SpinOnce();
  267. try
  268. {
  269. try
  270. {
  271. this._response.DownStream.EmergencyIncreaseMaxBuffered();
  272. this._response.ProcessPeekable(this.ContentProvider);
  273. }
  274. catch (Exception e)
  275. {
  276. if (this.ShutdownType == ShutdownTypes.Immediate)
  277. return;
  278. FinishedProcessing(e);
  279. }
  280. finally
  281. {
  282. // After an exception, this._response will be null!
  283. if (this._response != null)
  284. {
  285. if (this._response.ReadState == PeekableHTTP1Response.PeekableReadState.Finished)
  286. FinishedProcessing(null);
  287. else
  288. FinishedProcessing(new Exception("Underlying TCP connection closed unexpectedly!"));
  289. }
  290. }
  291. }
  292. finally
  293. {
  294. Interlocked.Exchange(ref this._isAlreadyProcessingContent, 0);
  295. }
  296. });
  297. return;
  298. }
  299. // If the consumer still have a request: error it and close the connection
  300. if (this.conn.CurrentRequest != null && this._response != null)
  301. {
  302. FinishedProcessing(new Exception("Underlying TCP connection closed unexpectedly!"));
  303. }
  304. else // If no current request: close the connection
  305. ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, HTTPConnectionStates.Closed));
  306. }
  307. public void OnError(Exception e)
  308. {
  309. HTTPManager.Logger.Information(nameof(HTTP1ContentConsumer), $"OnError({this.ContentProvider?.Length}, {this._response?.ReadState}, {this.ShutdownType})", this.Context);
  310. if (this.ShutdownType == ShutdownTypes.Immediate)
  311. return;
  312. FinishedProcessing(e);
  313. }
  314. private void OnCancellationRequested(HTTPRequest req)
  315. {
  316. HTTPManager.Logger.Information(nameof(HTTP1ContentConsumer), "OnCancellationRequested()", this.Context);
  317. Interlocked.Exchange(ref this._response, null);
  318. req.OnCancellationRequested -= OnCancellationRequested;
  319. this.conn?.Streamer?.Dispose();
  320. }
  321. void FinishedProcessing(Exception ex)
  322. {
  323. // Warning: FinishedProcessing might be called from different threads in parallel:
  324. // - send thread triggered by a write failure
  325. // - read thread oncontent/OnError/OnConnectionClosed
  326. var resp = Interlocked.Exchange(ref this._response, null);
  327. if (resp == null)
  328. return;
  329. HTTPManager.Logger.Verbose(nameof(HTTP1ContentConsumer), $"{nameof(FinishedProcessing)}({resp.ReadState}, {ex})", this.Context);
  330. // Unset the consumer, we no longer expect another OnContent call until further notice.
  331. //if (conn.TopStream is IPeekableContentProvider provider && provider?.Consumer == this)
  332. // provider.Consumer = null;
  333. this.ContentProvider.UnbindIf(this);
  334. var req = this.conn.CurrentRequest;
  335. req.OnCancellationRequested -= OnCancellationRequested;
  336. bool resendRequest = false;
  337. HTTPRequestStates requestState = HTTPRequestStates.Finished;
  338. HTTPConnectionStates connectionState = ex != null ? HTTPConnectionStates.Closed : HTTPConnectionStates.Recycle;
  339. // We could finish the request, ignore the error.
  340. if (resp.ReadState == PeekableHTTP1Response.PeekableReadState.Finished)
  341. ex = null;
  342. Exception error = ex;
  343. if (error != null)
  344. {
  345. // Timeout is a non-retryable error
  346. if (ex is TimeoutException)
  347. {
  348. error = null;
  349. requestState = HTTPRequestStates.TimedOut;
  350. }
  351. else
  352. {
  353. if (req.RetrySettings.Retries < req.RetrySettings.MaxRetries)
  354. {
  355. req.RetrySettings.Retries++;
  356. error = null;
  357. resendRequest = true;
  358. }
  359. else
  360. {
  361. requestState = HTTPRequestStates.Error;
  362. }
  363. }
  364. // Any exception means that the connection is in an unknown state, we shouldn't try to reuse it.
  365. connectionState = HTTPConnectionStates.Closed;
  366. resp.Dispose();
  367. }
  368. else
  369. {
  370. // After HandleResponse connectionState can have the following values:
  371. // - Processing: nothing interesting, caller side can decide what happens with the connection (recycle connection).
  372. // - Closed: server sent an connection: close header.
  373. // - ClosedResendRequest: in this case resendRequest is true, and the connection must not be reused.
  374. // In this case we can send only one ConnectionEvent to handle both case and avoid concurrency issues.
  375. error = ConnectionHelper.HandleResponse(req, out resendRequest, out connectionState, ref this._keepAlive, this.Context);
  376. if (error != null)
  377. requestState = HTTPRequestStates.Error;
  378. else if (!resendRequest && resp.IsUpgraded)
  379. requestState = HTTPRequestStates.Processing;
  380. }
  381. req.Timing.StartNext(TimingEventNames.Queued);
  382. HTTPManager.Logger.Verbose(nameof(HTTP1ContentConsumer), $"{nameof(FinishedProcessing)} final decision. ResendRequest: {resendRequest}, RequestState: {requestState}, ConnectionState: {connectionState}", this.Context);
  383. // If HandleResponse returned with ClosedResendRequest or there were an error and we can retry the request
  384. if (connectionState == HTTPConnectionStates.ClosedResendRequest || (resendRequest && connectionState == HTTPConnectionStates.Closed))
  385. {
  386. ConnectionHelper.ResendRequestAndCloseConnection(this.conn, req);
  387. }
  388. else if (resendRequest && requestState == HTTPRequestStates.Finished)
  389. {
  390. RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(req, RequestEvents.Resend));
  391. ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, connectionState));
  392. }
  393. else
  394. {
  395. // Otherwise set the request's then the connection's state
  396. ConnectionHelper.EnqueueEvents(this.conn, connectionState, req, requestState, error);
  397. }
  398. }
  399. public void Process(HTTPRequest request)
  400. {
  401. (conn.TopStream as IPeekableContentProvider).SetTwoWayBinding(this);
  402. // https://github.com/Benedicht/BestHTTP-Issues/issues/179
  403. // Toughts:
  404. // - Many requests, especially if they are uploading slowly, can occupy all background threads.
  405. // Use short-living thread when:
  406. // - It's a GET request
  407. // - It's not an upgrade request
  408. bool isRequestWithoutBody = request.MethodType == HTTPMethods.Get ||
  409. request.MethodType == HTTPMethods.Head ||
  410. request.MethodType == HTTPMethods.Delete ||
  411. request.MethodType == HTTPMethods.Options;
  412. bool isUpgrade = request.HasHeader("upgrade");
  413. var useShortLivingThread = HTTPManager.PerHostSettings.Get(request.CurrentHostKey).HTTP1ConnectionSettings.ForceUseThreadPool ||
  414. (isRequestWithoutBody && !isUpgrade);
  415. if (useShortLivingThread)
  416. ThreadedRunner.RunShortLiving(RunHandler);
  417. else
  418. ThreadedRunner.RunLongLiving(RunHandler);
  419. }
  420. public void Shutdown(ShutdownTypes type)
  421. {
  422. HTTPManager.Logger.Verbose(nameof(HTTP1ContentConsumer), string.Format($"Shutdown({type})"), this.Context);
  423. this.ShutdownType = type;
  424. }
  425. public void Dispose()
  426. {
  427. Dispose(true);
  428. GC.SuppressFinalize(this);
  429. }
  430. private void Dispose(bool disposing)
  431. {
  432. if (disposing)
  433. {
  434. this._are.Dispose();
  435. this._are = null;
  436. }
  437. }
  438. void IThreadSignaler.SignalThread()
  439. {
  440. this._are?.Set();
  441. }
  442. }
  443. }
  444. #endif