[Resource Timing] Gather timing information with reliable responseEnd time
[WebKit-https.git] / Source / WebCore / loader / WorkerThreadableLoader.cpp
1 /*
2  * Copyright (C) 2009, 2010 Google Inc. All rights reserved.
3  * Copyright (C) 2016 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include "config.h"
33 #include "WorkerThreadableLoader.h"
34
35 #include "ContentSecurityPolicy.h"
36 #include "Document.h"
37 #include "DocumentThreadableLoader.h"
38 #include "Performance.h"
39 #include "ResourceError.h"
40 #include "ResourceRequest.h"
41 #include "ResourceResponse.h"
42 #include "ResourceTiming.h"
43 #include "SecurityOrigin.h"
44 #include "ThreadableLoader.h"
45 #include "WorkerGlobalScope.h"
46 #include "WorkerLoaderProxy.h"
47 #include "WorkerThread.h"
48 #include <wtf/MainThread.h>
49 #include <wtf/Vector.h>
50
51 namespace WebCore {
52
53 static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode";
54
55 WorkerThreadableLoader::WorkerThreadableLoader(WorkerGlobalScope& workerGlobalScope, ThreadableLoaderClient& client, const String& taskMode, ResourceRequest&& request, const ThreadableLoaderOptions& options, const String& referrer)
56     : m_workerGlobalScope(workerGlobalScope)
57     , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client, options.initiator))
58     , m_bridge(*new MainThreadBridge(m_workerClientWrapper.get(), workerGlobalScope.thread().workerLoaderProxy(), taskMode, WTFMove(request), options, referrer.isEmpty() ? workerGlobalScope.url().strippedForUseAsReferrer() : referrer, workerGlobalScope.securityOrigin(), workerGlobalScope.contentSecurityPolicy()))
59 {
60 }
61
62 WorkerThreadableLoader::~WorkerThreadableLoader()
63 {
64     m_bridge.destroy();
65 }
66
67 void WorkerThreadableLoader::loadResourceSynchronously(WorkerGlobalScope& workerGlobalScope, ResourceRequest&& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
68 {
69     WorkerRunLoop& runLoop = workerGlobalScope.thread().runLoop();
70
71     // Create a unique mode just for this synchronous resource load.
72     String mode = loadResourceSynchronouslyMode;
73     mode.append(String::number(runLoop.createUniqueId()));
74
75     RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerGlobalScope, client, mode, WTFMove(request), options, String());
76     MessageQueueWaitResult result = MessageQueueMessageReceived;
77     while (!loader->done() && result != MessageQueueTerminated)
78         result = runLoop.runInMode(&workerGlobalScope, mode);
79
80     if (!loader->done() && result == MessageQueueTerminated)
81         loader->cancel();
82 }
83
84 void WorkerThreadableLoader::cancel()
85 {
86     m_bridge.cancel();
87 }
88
89 struct LoaderTaskOptions {
90     LoaderTaskOptions(const ThreadableLoaderOptions&, const String&, Ref<SecurityOrigin>&&);
91     ThreadableLoaderOptions options;
92     String referrer;
93     Ref<SecurityOrigin> origin;
94 };
95
96 LoaderTaskOptions::LoaderTaskOptions(const ThreadableLoaderOptions& options, const String& referrer, Ref<SecurityOrigin>&& origin)
97     : options(options, options.preflightPolicy, options.contentSecurityPolicyEnforcement, options.initiator.isolatedCopy(), options.filteringPolicy)
98     , referrer(referrer.isolatedCopy())
99     , origin(WTFMove(origin))
100 {
101 }
102
103 WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(ThreadableLoaderClientWrapper& workerClientWrapper, WorkerLoaderProxy& loaderProxy, const String& taskMode,
104     ResourceRequest&& request, const ThreadableLoaderOptions& options, const String& outgoingReferrer,
105     const SecurityOrigin* securityOrigin, const ContentSecurityPolicy* contentSecurityPolicy)
106     : m_workerClientWrapper(&workerClientWrapper)
107     , m_loaderProxy(loaderProxy)
108     , m_taskMode(taskMode.isolatedCopy())
109 {
110     ASSERT(securityOrigin);
111     ASSERT(contentSecurityPolicy);
112
113     auto securityOriginCopy = securityOrigin->isolatedCopy();
114     auto contentSecurityPolicyCopy = std::make_unique<ContentSecurityPolicy>(securityOriginCopy);
115     contentSecurityPolicyCopy->copyStateFrom(contentSecurityPolicy);
116     contentSecurityPolicyCopy->copyUpgradeInsecureRequestStateFrom(*contentSecurityPolicy);
117
118     auto optionsCopy = std::make_unique<LoaderTaskOptions>(options, request.httpReferrer().isNull() ? outgoingReferrer : request.httpReferrer(), WTFMove(securityOriginCopy));
119
120     // All loads start out as Document. Inside WorkerThreadableLoader we upgrade this to a Worker load.
121     ASSERT(optionsCopy->options.initiatorContext == InitiatorContext::Document);
122     optionsCopy->options.initiatorContext = InitiatorContext::Worker;
123
124     // Can we benefit from request being an r-value to create more efficiently its isolated copy?
125     m_loaderProxy.postTaskToLoader([this, request = request.isolatedCopy(), options = WTFMove(optionsCopy), contentSecurityPolicyCopy = WTFMove(contentSecurityPolicyCopy)](ScriptExecutionContext& context) mutable {
126         ASSERT(isMainThread());
127         Document& document = downcast<Document>(context);
128
129         // FIXME: If the site requests a local resource, then this will return a non-zero value but the sync path will return a 0 value.
130         // Either this should return 0 or the other code path should call a failure callback.
131         m_mainThreadLoader = DocumentThreadableLoader::create(document, *this, WTFMove(request), options->options, WTFMove(options->origin), WTFMove(contentSecurityPolicyCopy), WTFMove(options->referrer), DocumentThreadableLoader::ShouldLogError::No);
132         ASSERT(m_mainThreadLoader || m_loadingFinished);
133     });
134 }
135
136 void WorkerThreadableLoader::MainThreadBridge::destroy()
137 {
138     // Ensure that no more client callbacks are done in the worker context's thread.
139     clearClientWrapper();
140
141     // "delete this" and m_mainThreadLoader::deref() on the worker object's thread.
142     m_loaderProxy.postTaskToLoader([self = std::unique_ptr<WorkerThreadableLoader::MainThreadBridge>(this)] (ScriptExecutionContext& context) {
143         ASSERT(isMainThread());
144         ASSERT_UNUSED(context, context.isDocument());
145     });
146 }
147
148 void WorkerThreadableLoader::MainThreadBridge::cancel()
149 {
150     m_loaderProxy.postTaskToLoader([this] (ScriptExecutionContext& context) {
151         ASSERT(isMainThread());
152         ASSERT_UNUSED(context, context.isDocument());
153
154         if (!m_mainThreadLoader)
155             return;
156         m_mainThreadLoader->cancel();
157         m_mainThreadLoader = nullptr;
158     });
159
160     if (m_workerClientWrapper->done()) {
161         clearClientWrapper();
162         return;
163     }
164     // Taking a ref of client wrapper as call to didFail may take out the last reference of it.
165     Ref<ThreadableLoaderClientWrapper> protectedWorkerClientWrapper(*m_workerClientWrapper);
166     // If the client hasn't reached a termination state, then transition it by sending a cancellation error.
167     // Note: no more client callbacks will be done after this method -- we clear the client wrapper to ensure that.
168     ResourceError error(ResourceError::Type::Cancellation);
169     protectedWorkerClientWrapper->didFail(error);
170     protectedWorkerClientWrapper->clearClient();
171 }
172
173 void WorkerThreadableLoader::MainThreadBridge::clearClientWrapper()
174 {
175     m_workerClientWrapper->clearClient();
176 }
177
178 void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
179 {
180     m_loaderProxy.postTaskForModeToWorkerGlobalScope([protectedWorkerClientWrapper = makeRef(*m_workerClientWrapper), bytesSent, totalBytesToBeSent] (ScriptExecutionContext& context) mutable {
181         ASSERT_UNUSED(context, context.isWorkerGlobalScope());
182         protectedWorkerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
183     }, m_taskMode);
184 }
185
186 void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
187 {
188     m_loaderProxy.postTaskForModeToWorkerGlobalScope([protectedWorkerClientWrapper = makeRef(*m_workerClientWrapper), identifier, responseData = response.crossThreadData()] (ScriptExecutionContext& context) mutable {
189         ASSERT_UNUSED(context, context.isWorkerGlobalScope());
190         protectedWorkerClientWrapper->didReceiveResponse(identifier, ResourceResponse::fromCrossThreadData(WTFMove(responseData)));
191     }, m_taskMode);
192 }
193
194 void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data, int dataLength)
195 {
196     Vector<char> vector(dataLength);
197     memcpy(vector.data(), data, dataLength);
198     m_loaderProxy.postTaskForModeToWorkerGlobalScope([protectedWorkerClientWrapper = makeRef(*m_workerClientWrapper), vector = WTFMove(vector)] (ScriptExecutionContext& context) mutable {
199         ASSERT_UNUSED(context, context.isWorkerGlobalScope());
200         protectedWorkerClientWrapper->didReceiveData(vector.data(), vector.size());
201     }, m_taskMode);
202 }
203
204 void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long identifier)
205 {
206     m_loadingFinished = true;
207     m_loaderProxy.postTaskForModeToWorkerGlobalScope([protectedWorkerClientWrapper = makeRef(*m_workerClientWrapper), identifier] (ScriptExecutionContext& context) mutable {
208         ASSERT_UNUSED(context, context.isWorkerGlobalScope());
209         protectedWorkerClientWrapper->didFinishLoading(identifier);
210     }, m_taskMode);
211 }
212
213 void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error)
214 {
215     m_loadingFinished = true;
216     m_loaderProxy.postTaskForModeToWorkerGlobalScope([workerClientWrapper = Ref<ThreadableLoaderClientWrapper>(*m_workerClientWrapper), error = error.isolatedCopy()] (ScriptExecutionContext& context) mutable {
217         ASSERT(context.isWorkerGlobalScope());
218
219         ThreadableLoader::logError(context, error, workerClientWrapper->initiator());
220
221         workerClientWrapper->didFail(error);
222     }, m_taskMode);
223 }
224
225 #if ENABLE(WEB_TIMING)
226 void WorkerThreadableLoader::MainThreadBridge::didFinishTiming(const ResourceTiming& resourceTiming)
227 {
228     m_loaderProxy.postTaskForModeToWorkerGlobalScope([protectedWorkerClientWrapper = makeRef(*m_workerClientWrapper), resourceTiming = resourceTiming.isolatedCopy()] (ScriptExecutionContext& context) mutable {
229         ASSERT(context.isWorkerGlobalScope());
230         ASSERT(!resourceTiming.initiator().isEmpty());
231
232         // No need to notify clients, just add the performance timing entry.
233         downcast<WorkerGlobalScope>(context).performance().addResourceTiming(WTFMove(resourceTiming));
234     }, m_taskMode);
235 }
236 #endif
237
238 } // namespace WebCore