HostConnection.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections.Generic;
  3. using BestHTTP.Connections;
  4. using BestHTTP.Extensions;
  5. using BestHTTP.Logger;
  6. namespace BestHTTP.Core
  7. {
  8. public enum HostProtocolSupport : byte
  9. {
  10. Unknown = 0x00,
  11. HTTP1 = 0x01,
  12. HTTP2 = 0x02
  13. }
  14. /// <summary>
  15. /// A HostConnection object manages the connections to a host and the request queue.
  16. /// </summary>
  17. public sealed class HostConnection
  18. {
  19. public HostDefinition Host { get; private set; }
  20. public string VariantId { get; private set; }
  21. public HostProtocolSupport ProtocolSupport { get; private set; }
  22. public DateTime LastProtocolSupportUpdate { get; private set; }
  23. public int QueuedRequests { get { return this.Queue.Count; } }
  24. public LoggingContext Context { get; private set; }
  25. private List<ConnectionBase> Connections = new List<ConnectionBase>();
  26. private List<HTTPRequest> Queue = new List<HTTPRequest>();
  27. public HostConnection(HostDefinition host, string variantId)
  28. {
  29. this.Host = host;
  30. this.VariantId = variantId;
  31. this.Context = new LoggingContext(this);
  32. this.Context.Add("Host", this.Host.Host);
  33. this.Context.Add("VariantId", this.VariantId);
  34. }
  35. internal void AddProtocol(HostProtocolSupport protocolSupport)
  36. {
  37. this.LastProtocolSupportUpdate = DateTime.UtcNow;
  38. var oldProtocol = this.ProtocolSupport;
  39. if (oldProtocol != protocolSupport)
  40. {
  41. this.ProtocolSupport = protocolSupport;
  42. HTTPManager.Logger.Information(typeof(HostConnection).Name, string.Format("AddProtocol({0}) - changing from {1} to {2}", this.VariantId, oldProtocol, protocolSupport), this.Context);
  43. HostManager.Save();
  44. TryToSendQueuedRequests();
  45. }
  46. }
  47. internal HostConnection Send(HTTPRequest request)
  48. {
  49. var conn = GetNextAvailable(request);
  50. if (conn != null)
  51. {
  52. request.State = HTTPRequestStates.Processing;
  53. request.Prepare();
  54. // then start process the request
  55. conn.Process(request);
  56. }
  57. else
  58. {
  59. // If no free connection found and creation prohibited, we will put back to the queue
  60. this.Queue.Add(request);
  61. }
  62. return this;
  63. }
  64. internal ConnectionBase GetNextAvailable(HTTPRequest request)
  65. {
  66. int activeConnections = 0;
  67. ConnectionBase conn = null;
  68. // Check the last created connection first. This way, if a higher level protocol is present that can handle more requests (== HTTP/2) that protocol will be chosen
  69. // and others will be closed when their inactivity time is reached.
  70. for (int i = Connections.Count - 1; i >= 0; --i)
  71. {
  72. conn = Connections[i];
  73. if (conn.State == HTTPConnectionStates.Initial || conn.State == HTTPConnectionStates.Free || conn.CanProcessMultiple)
  74. {
  75. if (!conn.TestConnection())
  76. {
  77. HTTPManager.Logger.Verbose("HostConnection", "GetNextAvailable - TestConnection returned false!", this.Context, request.Context, conn.Context);
  78. RemoveConnectionImpl(conn, HTTPConnectionStates.Closed);
  79. continue;
  80. }
  81. HTTPManager.Logger.Verbose("HostConnection", string.Format("GetNextAvailable - returning with connection. state: {0}, CanProcessMultiple: {1}", conn.State, conn.CanProcessMultiple), this.Context, request.Context, conn.Context);
  82. return conn;
  83. }
  84. activeConnections++;
  85. }
  86. if (activeConnections >= HTTPManager.MaxConnectionPerServer)
  87. {
  88. HTTPManager.Logger.Verbose("HostConnection", string.Format("GetNextAvailable - activeConnections({0}) >= HTTPManager.MaxConnectionPerServer({1})", activeConnections, HTTPManager.MaxConnectionPerServer), this.Context, request.Context);
  89. return null;
  90. }
  91. string key = HostDefinition.GetKeyForRequest(request);
  92. conn = null;
  93. #if UNITY_WEBGL && !UNITY_EDITOR
  94. conn = new WebGLConnection(key);
  95. #else
  96. if (request.CurrentUri.IsFile)
  97. conn = new FileConnection(key);
  98. else
  99. {
  100. #if !BESTHTTP_DISABLE_ALTERNATE_SSL
  101. // Hold back the creation of a new connection until we know more about the remote host's features.
  102. // If we send out multiple requests at once it will execute the first and delay the others.
  103. // While it will decrease performance initially, it will prevent the creation of TCP connections
  104. // that will be unused after their first request processing if the server supports HTTP/2.
  105. if (activeConnections >= 1 && (this.ProtocolSupport == HostProtocolSupport.Unknown || this.ProtocolSupport == HostProtocolSupport.HTTP2))
  106. {
  107. HTTPManager.Logger.Verbose("HostConnection", string.Format("GetNextAvailable - waiting for protocol support message. activeConnections: {0}, ProtocolSupport: {1} ", activeConnections, this.ProtocolSupport), this.Context, request.Context);
  108. return null;
  109. }
  110. #endif
  111. conn = new HTTPConnection(key);
  112. HTTPManager.Logger.Verbose("HostConnection", string.Format("GetNextAvailable - creating new connection, key: {0} ", key), this.Context, request.Context, conn.Context);
  113. }
  114. #endif
  115. Connections.Add(conn);
  116. return conn;
  117. }
  118. internal HostConnection RecycleConnection(ConnectionBase conn)
  119. {
  120. conn.State = HTTPConnectionStates.Free;
  121. BestHTTP.Extensions.Timer.Add(new TimerData(TimeSpan.FromSeconds(1), conn, CloseConnectionAfterInactivity));
  122. return this;
  123. }
  124. private bool RemoveConnectionImpl(ConnectionBase conn, HTTPConnectionStates setState)
  125. {
  126. conn.State = setState;
  127. conn.Dispose();
  128. bool found = this.Connections.Remove(conn);
  129. if (!found)
  130. HTTPManager.Logger.Information(typeof(HostConnection).Name, string.Format("RemoveConnection - Couldn't find connection! key: {0}", conn.ServerAddress), this.Context, conn.Context);
  131. return found;
  132. }
  133. internal HostConnection RemoveConnection(ConnectionBase conn, HTTPConnectionStates setState)
  134. {
  135. RemoveConnectionImpl(conn, setState);
  136. return this;
  137. }
  138. internal HostConnection TryToSendQueuedRequests()
  139. {
  140. while (this.Queue.Count > 0 && GetNextAvailable(this.Queue[0]) != null)
  141. {
  142. Send(this.Queue[0]);
  143. this.Queue.RemoveAt(0);
  144. }
  145. return this;
  146. }
  147. public ConnectionBase Find(Predicate<ConnectionBase> match)
  148. {
  149. return this.Connections.Find(match);
  150. }
  151. private bool CloseConnectionAfterInactivity(DateTime now, object context)
  152. {
  153. var conn = context as ConnectionBase;
  154. bool closeConnection = conn.State == HTTPConnectionStates.Free && now - conn.LastProcessTime >= conn.KeepAliveTime;
  155. if (closeConnection)
  156. {
  157. HTTPManager.Logger.Information(typeof(HostConnection).Name, string.Format("CloseConnectionAfterInactivity - [{0}] Closing! State: {1}, Now: {2}, LastProcessTime: {3}, KeepAliveTime: {4}",
  158. conn.ToString(), conn.State, now.ToString(System.Globalization.CultureInfo.InvariantCulture), conn.LastProcessTime.ToString(System.Globalization.CultureInfo.InvariantCulture), conn.KeepAliveTime), this.Context, conn.Context);
  159. RemoveConnection(conn, HTTPConnectionStates.Closed);
  160. return false;
  161. }
  162. // repeat until the connection's state is free
  163. return conn.State == HTTPConnectionStates.Free;
  164. }
  165. public void RemoveAllIdleConnections()
  166. {
  167. for (int i = 0; i < this.Connections.Count; i++)
  168. if (this.Connections[i].State == HTTPConnectionStates.Free)
  169. {
  170. int countBefore = this.Connections.Count;
  171. RemoveConnection(this.Connections[i], HTTPConnectionStates.Closed);
  172. if (countBefore != this.Connections.Count)
  173. i--;
  174. }
  175. }
  176. internal void Shutdown()
  177. {
  178. this.Queue.Clear();
  179. foreach (var conn in this.Connections)
  180. {
  181. // Swallow any exceptions, we are quitting anyway.
  182. try
  183. {
  184. conn.Shutdown(ShutdownTypes.Immediate);
  185. }
  186. catch { }
  187. }
  188. //this.Connections.Clear();
  189. }
  190. internal void SaveTo(System.IO.BinaryWriter bw)
  191. {
  192. bw.Write(this.LastProtocolSupportUpdate.ToBinary());
  193. bw.Write((byte)this.ProtocolSupport);
  194. }
  195. internal void LoadFrom(int version, System.IO.BinaryReader br)
  196. {
  197. this.LastProtocolSupportUpdate = DateTime.FromBinary(br.ReadInt64());
  198. this.ProtocolSupport = (HostProtocolSupport)br.ReadByte();
  199. if (DateTime.UtcNow - this.LastProtocolSupportUpdate >= TimeSpan.FromDays(1))
  200. {
  201. HTTPManager.Logger.Verbose("HostConnection", string.Format("LoadFrom - Too Old! LastProtocolSupportUpdate: {0}, ProtocolSupport: {1}", this.LastProtocolSupportUpdate.ToString(System.Globalization.CultureInfo.InvariantCulture), this.ProtocolSupport), this.Context);
  202. this.ProtocolSupport = HostProtocolSupport.Unknown;
  203. }
  204. else
  205. HTTPManager.Logger.Verbose("HostConnection", string.Format("LoadFrom - LastProtocolSupportUpdate: {0}, ProtocolSupport: {1}", this.LastProtocolSupportUpdate.ToString(System.Globalization.CultureInfo.InvariantCulture), this.ProtocolSupport), this.Context);
  206. }
  207. }
  208. }