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