Make ResourceLoader::willSendRequestInternal asynchronous
[WebKit-https.git] / Source / WebKitLegacy / WebCoreSupport / WebResourceLoadScheduler.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-2008, 2015 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 "WebResourceLoadScheduler.h"
26
27 #include <WebCore/Document.h>
28 #include <WebCore/DocumentLoader.h>
29 #include <WebCore/FetchOptions.h>
30 #include <WebCore/Frame.h>
31 #include <WebCore/FrameLoader.h>
32 #include <WebCore/NetscapePlugInStreamLoader.h>
33 #include <WebCore/PingHandle.h>
34 #include <WebCore/PlatformStrategies.h>
35 #include <WebCore/ResourceHandle.h>
36 #include <WebCore/ResourceRequest.h>
37 #include <WebCore/SubresourceLoader.h>
38 #include <WebCore/URL.h>
39 #include <wtf/MainThread.h>
40 #include <wtf/SetForScope.h>
41 #include <wtf/text/CString.h>
42
43 #if PLATFORM(IOS)
44 #include <WebCore/RuntimeApplicationChecks.h>
45 #endif
46
47 // Match the parallel connection count used by the networking layer.
48 static unsigned maxRequestsInFlightPerHost;
49 #if !PLATFORM(IOS)
50 static const unsigned maxRequestsInFlightForNonHTTPProtocols = 20;
51 #else
52 // Limiting this seems to regress performance in some local cases so let's just make it large.
53 static const unsigned maxRequestsInFlightForNonHTTPProtocols = 10000;
54 #endif
55
56 using namespace WebCore;
57
58 WebResourceLoadScheduler& webResourceLoadScheduler()
59 {
60     return static_cast<WebResourceLoadScheduler&>(*platformStrategies()->loaderStrategy());
61 }
62
63 WebResourceLoadScheduler::HostInformation* WebResourceLoadScheduler::hostForURL(const URL& url, CreateHostPolicy createHostPolicy)
64 {
65     if (!url.protocolIsInHTTPFamily())
66         return m_nonHTTPProtocolHost;
67
68     m_hosts.checkConsistency();
69     String hostName = url.host();
70     HostInformation* host = m_hosts.get(hostName);
71     if (!host && createHostPolicy == CreateIfNotFound) {
72         host = new HostInformation(hostName, maxRequestsInFlightPerHost);
73         m_hosts.add(hostName, host);
74     }
75     return host;
76 }
77
78 WebResourceLoadScheduler::WebResourceLoadScheduler()
79     : m_nonHTTPProtocolHost(new HostInformation(String(), maxRequestsInFlightForNonHTTPProtocols))
80     , m_requestTimer(*this, &WebResourceLoadScheduler::requestTimerFired)
81     , m_suspendPendingRequestsCount(0)
82     , m_isSerialLoadingEnabled(false)
83 {
84     maxRequestsInFlightPerHost = initializeMaximumHTTPConnectionCountPerHost();
85 }
86
87 WebResourceLoadScheduler::~WebResourceLoadScheduler()
88 {
89 }
90
91 void WebResourceLoadScheduler::loadResource(Frame& frame, CachedResource& resource, ResourceRequest&& request, const ResourceLoaderOptions& options, CompletionHandler<void(RefPtr<WebCore::SubresourceLoader>&&)>&& completionHandler)
92 {
93     SubresourceLoader::create(frame, resource, WTFMove(request), options, [this, completionHandler = WTFMove(completionHandler)] (RefPtr<WebCore::SubresourceLoader>&& loader) mutable {
94         if (loader)
95             scheduleLoad(loader.get());
96 #if PLATFORM(IOS)
97         // Since we defer loader initialization until scheduling on iOS, the frame
98         // load delegate that would be called in SubresourceLoader::create() on
99         // other ports might be called in scheduleLoad() instead. Our contract to
100         // callers of this method is that a null loader is returned if the load was
101         // cancelled by a frame load delegate.
102         if (!loader || loader->reachedTerminalState())
103             return completionHandler(nullptr);
104 #endif
105         completionHandler(WTFMove(loader));
106     });
107 }
108
109 void WebResourceLoadScheduler::loadResourceSynchronously(NetworkingContext* context, unsigned long, const ResourceRequest& request, StoredCredentialsPolicy storedCredentialsPolicy, ClientCredentialPolicy, ResourceError& error, ResourceResponse& response, Vector<char>& data)
110 {
111     ResourceHandle::loadResourceSynchronously(context, request, storedCredentialsPolicy, error, response, data);
112 }
113
114 void WebResourceLoadScheduler::schedulePluginStreamLoad(Frame& frame, NetscapePlugInStreamLoaderClient& client, ResourceRequest&& request, CompletionHandler<void(RefPtr<WebCore::NetscapePlugInStreamLoader>&&)>&& completionHandler)
115 {
116     NetscapePlugInStreamLoader::create(frame, client, WTFMove(request), [this, completionHandler = WTFMove(completionHandler)] (RefPtr<WebCore::NetscapePlugInStreamLoader>&& loader) mutable {
117         if (loader)
118             scheduleLoad(loader.get());
119         completionHandler(WTFMove(loader));
120     });
121 }
122
123 void WebResourceLoadScheduler::scheduleLoad(ResourceLoader* resourceLoader)
124 {
125     ASSERT(resourceLoader);
126
127 #if PLATFORM(IOS)
128     // If there's a web archive resource for this URL, we don't need to schedule the load since it will never touch the network.
129     if (!isSuspendingPendingRequests() && resourceLoader->documentLoader()->archiveResourceForURL(resourceLoader->iOSOriginalRequest().url())) {
130         resourceLoader->startLoading();
131         return;
132     }
133 #else
134     if (resourceLoader->documentLoader()->archiveResourceForURL(resourceLoader->request().url())) {
135         resourceLoader->start();
136         return;
137     }
138 #endif
139
140 #if PLATFORM(IOS)
141     HostInformation* host = hostForURL(resourceLoader->iOSOriginalRequest().url(), CreateIfNotFound);
142 #else
143     HostInformation* host = hostForURL(resourceLoader->url(), CreateIfNotFound);
144 #endif
145
146     ResourceLoadPriority priority = resourceLoader->request().priority();
147
148     bool hadRequests = host->hasRequests();
149     host->schedule(resourceLoader, priority);
150
151 #if PLATFORM(COCOA) || USE(CFURLCONNECTION)
152     if (ResourceRequest::resourcePrioritiesEnabled() && !isSuspendingPendingRequests()) {
153         // Serve all requests at once to keep the pipeline full at the network layer.
154         // FIXME: Does this code do anything useful, given that we also set maxRequestsInFlightPerHost to effectively unlimited on these platforms?
155         servePendingRequests(host, ResourceLoadPriority::VeryLow);
156         return;
157     }
158 #endif
159
160 #if PLATFORM(IOS)
161     if ((priority > ResourceLoadPriority::Low || !resourceLoader->iOSOriginalRequest().url().protocolIsInHTTPFamily() || (priority == ResourceLoadPriority::Low && !hadRequests)) && !isSuspendingPendingRequests()) {
162         // Try to request important resources immediately.
163         servePendingRequests(host, priority);
164         return;
165     }
166 #else
167     if (priority > ResourceLoadPriority::Low || !resourceLoader->url().protocolIsInHTTPFamily() || (priority == ResourceLoadPriority::Low && !hadRequests)) {
168         // Try to request important resources immediately.
169         servePendingRequests(host, priority);
170         return;
171     }
172 #endif
173
174     // Handle asynchronously so early low priority requests don't
175     // get scheduled before later high priority ones.
176     scheduleServePendingRequests();
177 }
178
179 void WebResourceLoadScheduler::remove(ResourceLoader* resourceLoader)
180 {
181     ASSERT(resourceLoader);
182
183     HostInformation* host = hostForURL(resourceLoader->url());
184     if (host)
185         host->remove(resourceLoader);
186 #if PLATFORM(IOS)
187     // ResourceLoader::url() doesn't start returning the correct value until the load starts. If we get canceled before that, we need to look for originalRequest url instead.
188     // FIXME: ResourceLoader::url() should be made to return a sensible value at all times.
189     if (!resourceLoader->iOSOriginalRequest().isNull()) {
190         HostInformation* originalHost = hostForURL(resourceLoader->iOSOriginalRequest().url());
191         if (originalHost && originalHost != host)
192             originalHost->remove(resourceLoader);
193     }
194 #endif
195     scheduleServePendingRequests();
196 }
197
198 void WebResourceLoadScheduler::setDefersLoading(ResourceLoader*, bool)
199 {
200 }
201
202 void WebResourceLoadScheduler::crossOriginRedirectReceived(ResourceLoader* resourceLoader, const URL& redirectURL)
203 {
204     HostInformation* oldHost = hostForURL(resourceLoader->url());
205     ASSERT(oldHost);
206     if (!oldHost)
207         return;
208
209     HostInformation* newHost = hostForURL(redirectURL, CreateIfNotFound);
210
211     if (oldHost->name() == newHost->name())
212         return;
213
214     newHost->addLoadInProgress(resourceLoader);
215     oldHost->remove(resourceLoader);
216 }
217
218 void WebResourceLoadScheduler::servePendingRequests(ResourceLoadPriority minimumPriority)
219 {
220     if (isSuspendingPendingRequests())
221         return;
222
223     m_requestTimer.stop();
224     
225     servePendingRequests(m_nonHTTPProtocolHost, minimumPriority);
226
227     for (auto* host : copyToVector(m_hosts.values())) {
228         if (host->hasRequests())
229             servePendingRequests(host, minimumPriority);
230         else
231             delete m_hosts.take(host->name());
232     }
233 }
234
235 void WebResourceLoadScheduler::servePendingRequests(HostInformation* host, ResourceLoadPriority minimumPriority)
236 {
237     auto priority = ResourceLoadPriority::Highest;
238     while (true) {
239         auto& requestsPending = host->requestsPending(priority);
240         while (!requestsPending.isEmpty()) {
241             RefPtr<ResourceLoader> resourceLoader = requestsPending.first();
242
243             // For named hosts - which are only http(s) hosts - we should always enforce the connection limit.
244             // For non-named hosts - everything but http(s) - we should only enforce the limit if the document isn't done parsing 
245             // and we don't know all stylesheets yet.
246             Document* document = resourceLoader->frameLoader() ? resourceLoader->frameLoader()->frame().document() : 0;
247             bool shouldLimitRequests = !host->name().isNull() || (document && (document->parsing() || !document->haveStylesheetsLoaded()));
248             if (shouldLimitRequests && host->limitRequests(priority))
249                 return;
250
251             requestsPending.removeFirst();
252             host->addLoadInProgress(resourceLoader.get());
253 #if PLATFORM(IOS)
254             if (!IOSApplication::isWebProcess()) {
255                 resourceLoader->startLoading();
256                 return;
257             }
258 #endif
259             resourceLoader->start();
260         }
261         if (priority == minimumPriority)
262             return;
263         --priority;
264     }
265 }
266
267 void WebResourceLoadScheduler::suspendPendingRequests()
268 {
269     ++m_suspendPendingRequestsCount;
270 }
271
272 void WebResourceLoadScheduler::resumePendingRequests()
273 {
274     ASSERT(m_suspendPendingRequestsCount);
275     --m_suspendPendingRequestsCount;
276     if (m_suspendPendingRequestsCount)
277         return;
278     if (!m_hosts.isEmpty() || m_nonHTTPProtocolHost->hasRequests())
279         scheduleServePendingRequests();
280 }
281     
282 void WebResourceLoadScheduler::scheduleServePendingRequests()
283 {
284     if (!m_requestTimer.isActive())
285         m_requestTimer.startOneShot(0_s);
286 }
287
288 void WebResourceLoadScheduler::requestTimerFired()
289 {
290     servePendingRequests();
291 }
292
293 WebResourceLoadScheduler::HostInformation::HostInformation(const String& name, unsigned maxRequestsInFlight)
294     : m_name(name)
295     , m_maxRequestsInFlight(maxRequestsInFlight)
296 {
297 }
298
299 WebResourceLoadScheduler::HostInformation::~HostInformation()
300 {
301     ASSERT(!hasRequests());
302 }
303
304 unsigned WebResourceLoadScheduler::HostInformation::priorityToIndex(ResourceLoadPriority priority)
305 {
306     switch (priority) {
307     case ResourceLoadPriority::VeryLow:
308         return 0;
309     case ResourceLoadPriority::Low:
310         return 1;
311     case ResourceLoadPriority::Medium:
312         return 2;
313     case ResourceLoadPriority::High:
314         return 3;
315     case ResourceLoadPriority::VeryHigh:
316         return 4;
317     }
318     ASSERT_NOT_REACHED();
319     return 0;
320 }
321
322 void WebResourceLoadScheduler::HostInformation::schedule(ResourceLoader* resourceLoader, ResourceLoadPriority priority)
323 {
324     m_requestsPending[priorityToIndex(priority)].append(resourceLoader);
325 }
326     
327 void WebResourceLoadScheduler::HostInformation::addLoadInProgress(ResourceLoader* resourceLoader)
328 {
329     m_requestsLoading.add(resourceLoader);
330 }
331     
332 void WebResourceLoadScheduler::HostInformation::remove(ResourceLoader* resourceLoader)
333 {
334     if (m_requestsLoading.remove(resourceLoader))
335         return;
336     
337     for (auto& requestQueue : m_requestsPending) {
338         for (auto it = requestQueue.begin(), end = requestQueue.end(); it != end; ++it) {
339             if (*it == resourceLoader) {
340                 requestQueue.remove(it);
341                 return;
342             }
343         }
344     }
345 }
346
347 bool WebResourceLoadScheduler::HostInformation::hasRequests() const
348 {
349     if (!m_requestsLoading.isEmpty())
350         return true;
351     for (auto& requestQueue : m_requestsPending) {
352         if (!requestQueue.isEmpty())
353             return true;
354     }
355     return false;
356 }
357
358 bool WebResourceLoadScheduler::HostInformation::limitRequests(ResourceLoadPriority priority) const 
359 {
360     if (priority == ResourceLoadPriority::VeryLow && !m_requestsLoading.isEmpty())
361         return true;
362     return m_requestsLoading.size() >= (webResourceLoadScheduler().isSerialLoadingEnabled() ? 1 : m_maxRequestsInFlight);
363 }
364
365 void WebResourceLoadScheduler::startPingLoad(Frame& frame, ResourceRequest& request, const HTTPHeaderMap&, const FetchOptions& options, PingLoadCompletionHandler&& completionHandler)
366 {
367     // PingHandle manages its own lifetime, deleting itself when its purpose has been fulfilled.
368     new PingHandle(frame.loader().networkingContext(), request, options.credentials != FetchOptions::Credentials::Omit, options.redirect == FetchOptions::Redirect::Follow, WTFMove(completionHandler));
369 }
370
371 void WebResourceLoadScheduler::preconnectTo(NetworkingContext&, const URL&, StoredCredentialsPolicy, PreconnectCompletionHandler&&)
372 {
373 }
374