2009-02-25 David Levin <levin@chromium.org>
[WebKit-https.git] / WebCore / loader / WorkerThreadableLoader.cpp
1 /*
2  * Copyright (C) 2009 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
33 #if ENABLE(WORKERS)
34
35 #include "WorkerThreadableLoader.h"
36
37 #include "GenericWorkerTask.h"
38 #include "ResourceError.h"
39 #include "ResourceRequest.h"
40 #include "ResourceResponse.h"
41 #include "ThreadableLoader.h"
42 #include "WorkerContext.h"
43 #include "WorkerMessagingProxy.h"
44 #include "WorkerThread.h"
45 #include <memory>
46 #include <wtf/OwnPtr.h>
47 #include <wtf/Threading.h>
48 #include <wtf/Vector.h>
49
50 using namespace std;
51
52 namespace WebCore {
53
54 static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode";
55
56 // FIXME: The assumption that we can upcast worker object proxy to WorkerMessagingProxy will not be true in multi-process implementation.
57 WorkerThreadableLoader::WorkerThreadableLoader(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, LoadCallbacks callbacksSetting,
58                                                ContentSniff contentSniff)
59     : m_workerContext(workerContext)
60     , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client))
61     , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, *(static_cast<WorkerMessagingProxy*>(m_workerContext->thread()->workerObjectProxy())), taskMode, request, callbacksSetting,
62                                       contentSniff)))
63 {
64 }
65
66 WorkerThreadableLoader::~WorkerThreadableLoader()
67 {
68     m_bridge.destroy();
69 }
70
71 void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerContext, const ResourceRequest& request, ThreadableLoaderClient& client)
72 {
73     WorkerRunLoop& runLoop = workerContext->thread()->runLoop();
74
75     // Create a unique mode just for this synchronous resource load.
76     String mode = loadResourceSynchronouslyMode;
77     mode.append(String::number(runLoop.createUniqueId()));
78
79     ContentSniff contentSniff = request.url().isLocalFile() ? SniffContent : DoNotSniffContent;
80     RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerContext, &client, mode, request, DoNotSendLoadCallbacks, contentSniff);
81     while (!loader->done())
82         runLoop.runInMode(workerContext, mode);
83 }
84
85 void WorkerThreadableLoader::cancel()
86 {
87     m_bridge.cancel();
88 }
89
90 WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, WorkerMessagingProxy& messagingProxy, const String& taskMode,
91                                                            const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff)
92     : m_workerClientWrapper(workerClientWrapper)
93     , m_messagingProxy(messagingProxy)
94     , m_taskMode(taskMode.copy())
95 {
96     ASSERT(m_workerClientWrapper.get());
97     m_messagingProxy.postTaskToWorkerObject(createCallbackTask(&MainThreadBridge::mainThreadCreateLoader, this, request, callbacksSetting, contentSniff));
98 }
99
100 WorkerThreadableLoader::MainThreadBridge::~MainThreadBridge()
101 {
102 }
103
104 void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExecutionContext* context, MainThreadBridge* thisPtr, auto_ptr<CrossThreadResourceRequestData> requestData, LoadCallbacks callbacksSetting, ContentSniff contentSniff)
105 {
106     // FIXME: This assert fails for nested workers.  Removing the assert would allow it to work,
107     // but then there would be one WorkerThreadableLoader in every intermediate worker simply
108     // chaining the requests, which is not very good. Instead, the postTaskToWorkerObject should be a
109     // postTaskToDocumentContext.
110     ASSERT(isMainThread());
111     ASSERT(context->isDocument());
112
113     if (thisPtr->m_messagingProxy.askedToTerminate())
114         return;
115
116     // FIXME: the created loader has no knowledge of the origin of the worker doing the load request.
117     // Basically every setting done in SubresourceLoader::create (including the contents of addExtraFieldsToRequest)
118     // needs to be examined for how it should take into account a different originator.
119     OwnPtr<ResourceRequest> request(ResourceRequest::adopt(requestData));
120     // FIXME: If the a site requests a local resource, then this will return a non-zero value but the sync path
121     // will return a 0 value.  Either this should return 0 or the other code path should do a callback with
122     // a failure.
123     thisPtr->m_mainThreadLoader = ThreadableLoader::create(context, thisPtr, *request, callbacksSetting, contentSniff);
124     ASSERT(thisPtr->m_mainThreadLoader);
125 }
126
127 void WorkerThreadableLoader::MainThreadBridge::mainThreadDestroy(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
128 {
129     ASSERT(isMainThread());
130     ASSERT_UNUSED(context, context->isDocument());
131     delete thisPtr;
132 }
133
134 void WorkerThreadableLoader::MainThreadBridge::destroy()
135 {
136     // Ensure that no more client callbacks are done in the worker context's thread.
137     clearClientWrapper();
138
139     // "delete this" and m_mainThreadLoader::deref() on the worker object's thread.
140     m_messagingProxy.postTaskToWorkerObject(createCallbackTask(&MainThreadBridge::mainThreadDestroy, this));
141 }
142
143 void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
144 {
145     ASSERT(isMainThread());
146     ASSERT_UNUSED(context, context->isDocument());
147
148     if (!thisPtr->m_mainThreadLoader)
149         return;
150     thisPtr->m_mainThreadLoader->cancel();
151     thisPtr->m_mainThreadLoader = 0;
152 }
153
154 void WorkerThreadableLoader::MainThreadBridge::cancel()
155 {
156     m_messagingProxy.postTaskToWorkerObject(createCallbackTask(&MainThreadBridge::mainThreadCancel, this));
157     clearClientWrapper();
158 }
159
160 void WorkerThreadableLoader::MainThreadBridge::clearClientWrapper()
161 {
162     static_cast<ThreadableLoaderClientWrapper*>(m_workerClientWrapper.get())->clearClient();
163 }
164
165 static void workerContextDidSendData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
166 {
167     ASSERT_UNUSED(context, context->isWorkerContext());
168     workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
169 }
170
171 void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
172 {
173     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
174 }
175
176 static void workerContextDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<CrossThreadResourceResponseData> responseData)
177 {
178     ASSERT_UNUSED(context, context->isWorkerContext());
179     OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
180     workerClientWrapper->didReceiveResponse(*response);
181 }
182
183 void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(const ResourceResponse& response)
184 {
185     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveResponse, m_workerClientWrapper, response), m_taskMode);
186 }
187
188 static void workerContextDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<Vector<char> > vectorData)
189 {
190     ASSERT_UNUSED(context, context->isWorkerContext());
191     workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
192 }
193
194 void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data, int lengthReceived)
195 {
196     auto_ptr<Vector<char> > vector(new Vector<char>(lengthReceived)); // needs to be an auto_ptr for usage with createCallbackTask.
197     memcpy(vector->data(), data, lengthReceived);
198     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveData, m_workerClientWrapper, vector), m_taskMode);
199 }
200
201 static void workerContextDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, int identifier)
202 {
203     ASSERT_UNUSED(context, context->isWorkerContext());
204     workerClientWrapper->didFinishLoading(identifier);
205 }
206
207 void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(int identifier)
208 {
209     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFinishLoading, m_workerClientWrapper, identifier), m_taskMode);
210 }
211
212 static void workerContextDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
213 {
214     ASSERT_UNUSED(context, context->isWorkerContext());
215     workerClientWrapper->didFail(error);
216 }
217
218 void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error)
219 {
220     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFail, m_workerClientWrapper, error), m_taskMode);
221 }
222
223 static void workerContextDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
224 {
225     ASSERT_UNUSED(context, context->isWorkerContext());
226     workerClientWrapper->didFailRedirectCheck();
227 }
228
229 void WorkerThreadableLoader::MainThreadBridge::didFailRedirectCheck()
230 {
231     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailRedirectCheck, m_workerClientWrapper), m_taskMode);
232 }
233
234 static void workerContextDidReceiveAuthenticationCancellation(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<CrossThreadResourceResponseData> responseData)
235 {
236     ASSERT_UNUSED(context, context->isWorkerContext());
237     OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
238     workerClientWrapper->didReceiveAuthenticationCancellation(*response);
239 }
240
241 void WorkerThreadableLoader::MainThreadBridge::didReceiveAuthenticationCancellation(const ResourceResponse& response)
242 {
243     m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveAuthenticationCancellation, m_workerClientWrapper, response), m_taskMode);
244 }
245
246 } // namespace WebCore
247
248 #endif // ENABLE(WORKERS)