<http://webkit.org/b/53192> Add experimental support for HTTP pipelining in CFNetwork
[WebKit-https.git] / Source / WebCore / loader / ResourceLoadScheduler.cpp
1 /*
2     Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3     Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
4     Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
5     Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
6     Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
7     Copyright (C) 2010 Google Inc. All rights reserved.
8
9     This library is free software; you can redistribute it and/or
10     modify it under the terms of the GNU Library General Public
11     License as published by the Free Software Foundation; either
12     version 2 of the License, or (at your option) any later version.
13
14     This library is distributed in the hope that it will be useful,
15     but WITHOUT ANY WARRANTY; without even the implied warranty of
16     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17     Library General Public License for more details.
18
19     You should have received a copy of the GNU Library General Public License
20     along with this library; see the file COPYING.LIB.  If not, write to
21     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22     Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "ResourceLoadScheduler.h"
27
28 #include "Document.h"
29 #include "Frame.h"
30 #include "FrameLoader.h"
31 #include "InspectorInstrumentation.h"
32 #include "KURL.h"
33 #include "Logging.h"
34 #include "NetscapePlugInStreamLoader.h"
35 #include "ResourceLoader.h"
36 #include "ResourceRequest.h"
37 #include "SubresourceLoader.h"
38 #include <wtf/text/CString.h>
39
40 #define REQUEST_MANAGEMENT_ENABLED 1
41
42 namespace WebCore {
43
44 #if REQUEST_MANAGEMENT_ENABLED
45 static const unsigned maxRequestsInFlightForNonHTTPProtocols = 20;
46 // Match the parallel connection count used by the networking layer.
47 static unsigned maxRequestsInFlightPerHost;
48 #else
49 static const unsigned maxRequestsInFlightForNonHTTPProtocols = 10000;
50 static const unsigned maxRequestsInFlightPerHost = 10000;
51 #endif
52
53 ResourceLoadScheduler::HostInformation* ResourceLoadScheduler::hostForURL(const KURL& url, CreateHostPolicy createHostPolicy)
54 {
55     if (!url.protocolInHTTPFamily())
56         return m_nonHTTPProtocolHost;
57
58     m_hosts.checkConsistency();
59     String hostName = url.host();
60     HostInformation* host = m_hosts.get(hostName);
61     if (!host && createHostPolicy == CreateIfNotFound) {
62         host = new HostInformation(hostName, maxRequestsInFlightPerHost);
63         m_hosts.add(hostName, host);
64     }
65     return host;
66 }
67
68 ResourceLoadScheduler* resourceLoadScheduler()
69 {
70     ASSERT(isMainThread());
71     DEFINE_STATIC_LOCAL(ResourceLoadScheduler, resourceLoadScheduler, ());
72     return &resourceLoadScheduler;
73 }
74
75 ResourceLoadScheduler::ResourceLoadScheduler()
76     : m_nonHTTPProtocolHost(new HostInformation(String(), maxRequestsInFlightForNonHTTPProtocols))
77     , m_requestTimer(this, &ResourceLoadScheduler::requestTimerFired)
78     , m_isSuspendingPendingRequests(false)
79     , m_isSerialLoadingEnabled(false)
80 {
81 #if REQUEST_MANAGEMENT_ENABLED
82     maxRequestsInFlightPerHost = initializeMaximumHTTPConnectionCountPerHost();
83 #endif
84 }
85
86 PassRefPtr<SubresourceLoader> ResourceLoadScheduler::scheduleSubresourceLoad(Frame* frame, SubresourceLoaderClient* client, const ResourceRequest& request, ResourceLoadPriority priority, SecurityCheckPolicy securityCheck, bool sendResourceLoadCallbacks, bool shouldContentSniff)
87 {
88     PassRefPtr<SubresourceLoader> loader = SubresourceLoader::create(frame, client, request, securityCheck, sendResourceLoadCallbacks, shouldContentSniff);
89     if (loader)
90         scheduleLoad(loader.get(), priority);
91     return loader;
92 }
93
94 PassRefPtr<NetscapePlugInStreamLoader> ResourceLoadScheduler::schedulePluginStreamLoad(Frame* frame, NetscapePlugInStreamLoaderClient* client, const ResourceRequest& request)
95 {
96     PassRefPtr<NetscapePlugInStreamLoader> loader = NetscapePlugInStreamLoader::create(frame, client, request);
97     if (loader)
98         scheduleLoad(loader.get(), ResourceLoadPriorityLow);
99     return loader;
100 }
101
102 void ResourceLoadScheduler::addMainResourceLoad(ResourceLoader* resourceLoader)
103 {
104     hostForURL(resourceLoader->url(), CreateIfNotFound)->addLoadInProgress(resourceLoader);
105 }
106
107 void ResourceLoadScheduler::scheduleLoad(ResourceLoader* resourceLoader, ResourceLoadPriority priority)
108 {
109     ASSERT(resourceLoader);
110     ASSERT(priority != ResourceLoadPriorityUnresolved);
111 #if !REQUEST_MANAGEMENT_ENABLED
112     priority = ResourceLoadPriorityHighest;
113 #endif
114
115     LOG(ResourceLoading, "ResourceLoadScheduler::load resource %p '%s'", resourceLoader, resourceLoader->url().string().latin1().data());
116     HostInformation* host = hostForURL(resourceLoader->url(), CreateIfNotFound);    
117     bool hadRequests = host->hasRequests();
118     host->schedule(resourceLoader, priority);
119
120     if (priority > ResourceLoadPriorityLow || !resourceLoader->url().protocolInHTTPFamily() || (priority == ResourceLoadPriorityLow && !hadRequests)) {
121         // Try to request important resources immediately.
122         servePendingRequests(host, priority);
123         return;
124     }
125
126     // Handle asynchronously so early low priority requests don't get scheduled before later high priority ones.
127     InspectorInstrumentation::didScheduleResourceRequest(resourceLoader->frameLoader() ? resourceLoader->frameLoader()->frame()->document() : 0, resourceLoader->url());
128     scheduleServePendingRequests();
129 }
130
131 void ResourceLoadScheduler::remove(ResourceLoader* resourceLoader)
132 {
133     ASSERT(resourceLoader);
134
135     HostInformation* host = hostForURL(resourceLoader->url());
136     if (host)
137         host->remove(resourceLoader);
138     scheduleServePendingRequests();
139 }
140
141 void ResourceLoadScheduler::crossOriginRedirectReceived(ResourceLoader* resourceLoader, const KURL& redirectURL)
142 {
143     HostInformation* oldHost = hostForURL(resourceLoader->url());
144     ASSERT(oldHost);
145     HostInformation* newHost = hostForURL(redirectURL, CreateIfNotFound);
146
147     if (oldHost->name() == newHost->name())
148         return;
149     
150     newHost->addLoadInProgress(resourceLoader);
151     oldHost->remove(resourceLoader);
152 }
153
154 void ResourceLoadScheduler::servePendingRequests(ResourceLoadPriority minimumPriority)
155 {
156     LOG(ResourceLoading, "ResourceLoadScheduler::servePendingRequests. m_isSuspendingPendingRequests=%d", m_isSuspendingPendingRequests); 
157     if (m_isSuspendingPendingRequests)
158         return;
159
160     m_requestTimer.stop();
161     
162     servePendingRequests(m_nonHTTPProtocolHost, minimumPriority);
163
164     Vector<HostInformation*> hostsToServe;
165     m_hosts.checkConsistency();
166     HostMap::iterator end = m_hosts.end();
167     for (HostMap::iterator iter = m_hosts.begin(); iter != end; ++iter)
168         hostsToServe.append(iter->second);
169
170     int size = hostsToServe.size();
171     for (int i = 0; i < size; ++i) {
172         HostInformation* host = hostsToServe[i];
173         if (host->hasRequests())
174             servePendingRequests(host, minimumPriority);
175         else
176             delete m_hosts.take(host->name());
177     }
178 }
179
180 void ResourceLoadScheduler::servePendingRequests(HostInformation* host, ResourceLoadPriority minimumPriority)
181 {
182     LOG(ResourceLoading, "ResourceLoadScheduler::servePendingRequests HostInformation.m_name='%s'", host->name().latin1().data());
183
184     for (int priority = ResourceLoadPriorityHighest; priority >= minimumPriority; --priority) {
185         HostInformation::RequestQueue& requestsPending = host->requestsPending((ResourceLoadPriority) priority);
186
187         while (!requestsPending.isEmpty()) {
188             RefPtr<ResourceLoader> resourceLoader = requestsPending.first();
189
190             // For named hosts - which are only http(s) hosts - we should always enforce the connection limit.
191             // For non-named hosts - everything but http(s) - we should only enforce the limit if the document isn't done parsing 
192             // and we don't know all stylesheets yet.
193             Document* document = resourceLoader->frameLoader() ? resourceLoader->frameLoader()->frame()->document() : 0;
194             bool shouldLimitRequests = !host->name().isNull() || (document && (document->parsing() || !document->haveStylesheetsLoaded()));
195             if (shouldLimitRequests && host->limitRequests())
196                 return;
197
198             requestsPending.removeFirst();
199             host->addLoadInProgress(resourceLoader.get());
200             resourceLoader->start();
201         }
202     }
203 }
204
205 void ResourceLoadScheduler::suspendPendingRequests()
206 {
207     ASSERT(!m_isSuspendingPendingRequests);
208     m_isSuspendingPendingRequests = true;
209 }
210
211 void ResourceLoadScheduler::resumePendingRequests()
212 {
213     ASSERT(m_isSuspendingPendingRequests);
214     m_isSuspendingPendingRequests = false;
215     if (!m_hosts.isEmpty() || m_nonHTTPProtocolHost->hasRequests())
216         scheduleServePendingRequests();
217 }
218     
219 void ResourceLoadScheduler::scheduleServePendingRequests()
220 {
221     LOG(ResourceLoading, "ResourceLoadScheduler::scheduleServePendingRequests, m_requestTimer.isActive()=%u", m_requestTimer.isActive());
222     if (!m_requestTimer.isActive())
223         m_requestTimer.startOneShot(0);
224 }
225
226 void ResourceLoadScheduler::requestTimerFired(Timer<ResourceLoadScheduler>*) 
227 {
228     LOG(ResourceLoading, "ResourceLoadScheduler::requestTimerFired\n");
229     servePendingRequests();
230 }
231
232 ResourceLoadScheduler::HostInformation::HostInformation(const String& name, unsigned maxRequestsInFlight)
233     : m_name(name)
234     , m_maxRequestsInFlight(maxRequestsInFlight)
235 {
236 }
237
238 ResourceLoadScheduler::HostInformation::~HostInformation()
239 {
240     ASSERT(m_requestsLoading.isEmpty());
241     for (unsigned p = 0; p <= ResourceLoadPriorityHighest; p++)
242         ASSERT(m_requestsPending[p].isEmpty());
243 }
244     
245 void ResourceLoadScheduler::HostInformation::schedule(ResourceLoader* resourceLoader, ResourceLoadPriority priority)
246 {
247     m_requestsPending[priority].append(resourceLoader);
248 }
249     
250 void ResourceLoadScheduler::HostInformation::addLoadInProgress(ResourceLoader* resourceLoader)
251 {
252     LOG(ResourceLoading, "HostInformation '%s' loading '%s'. Current count %d", m_name.latin1().data(), resourceLoader->url().string().latin1().data(), m_requestsLoading.size());
253     m_requestsLoading.add(resourceLoader);
254 }
255     
256 void ResourceLoadScheduler::HostInformation::remove(ResourceLoader* resourceLoader)
257 {
258     if (m_requestsLoading.contains(resourceLoader)) {
259         m_requestsLoading.remove(resourceLoader);
260         return;
261     }
262     
263     for (int priority = ResourceLoadPriorityHighest; priority >= ResourceLoadPriorityLowest; --priority) {  
264         RequestQueue::iterator end = m_requestsPending[priority].end();
265         for (RequestQueue::iterator it = m_requestsPending[priority].begin(); it != end; ++it) {
266             if (*it == resourceLoader) {
267                 m_requestsPending[priority].remove(it);
268                 return;
269             }
270         }
271     }
272 }
273
274 bool ResourceLoadScheduler::HostInformation::hasRequests() const
275 {
276     if (!m_requestsLoading.isEmpty())
277         return true;
278     for (unsigned p = 0; p <= ResourceLoadPriorityHighest; p++) {
279         if (!m_requestsPending[p].isEmpty())
280             return true;
281     }
282     return false;
283 }
284
285 bool ResourceLoadScheduler::HostInformation::limitRequests() const 
286
287     return m_requestsLoading.size() >= (resourceLoadScheduler()->isSerialLoadingEnabled() ? 1 : m_maxRequestsInFlight);
288 }
289
290 } // namespace WebCore