Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(425)

Side by Side Diff: content/browser/loader/mojo_async_resource_handler.cc

Issue 1970693002: Use mojo for Chrome Loading, Part 1 (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: rebase Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "content/browser/loader/mojo_async_resource_handler.h"
6
7 #include <utility>
8
9 #include "base/command_line.h"
10 #include "base/containers/hash_tables.h"
11 #include "base/logging.h"
12 #include "base/macros.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/time/time.h"
15 #include "content/browser/loader/netlog_observer.h"
16 #include "content/browser/loader/resource_dispatcher_host_impl.h"
17 #include "content/browser/loader/resource_request_info_impl.h"
18 #include "content/common/resource_request_completion_status.h"
19 #include "content/public/browser/resource_dispatcher_host_delegate.h"
20 #include "content/public/common/resource_response.h"
21 #include "mojo/public/c/system/data_pipe.h"
22 #include "mojo/public/cpp/system/data_pipe.h"
23 #include "net/base/io_buffer.h"
24 #include "net/base/load_flags.h"
25 #include "net/base/mime_sniffer.h"
26 #include "net/log/net_log.h"
27 #include "net/url_request/redirect_info.h"
28
29 namespace content {
30 namespace {
31
32 int g_allocation_size = MojoAsyncResourceHandler::kDefaultAllocationSize;
kinuko 2016/08/03 18:20:07 nit: add a blank line here?
yhirano 2016/08/04 12:50:51 Done.
33 // MimeTypeResourceHandler *implicitly* requires that the buffer size
34 // returned from OnWillRead should be larger than certain size.
35 // TODO(yhirano): Fix MimeTypeResourceHandler.
36 constexpr size_t kMinAllocationSize = 2 * net::kMaxBytesToSniff;
37
38 constexpr size_t kMaxChunkSize = 32 * 1024;
39
40 void GetNumericArg(const std::string& name, int* result) {
41 const std::string& value =
42 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(name);
43 if (!value.empty())
44 base::StringToInt(value, result);
45 }
46
47 void InitializeResourceBufferConstants() {
48 static bool did_init = false;
49 if (did_init)
50 return;
51 did_init = true;
52
53 GetNumericArg("resource-buffer-size", &g_allocation_size);
54 }
55
56 } // namespace
57
58 // This class is for sharing the ownership of a ScopedDataPipeProducerHandle.
kinuko 2016/08/03 18:20:07 nit: maybe this comment could be even more specifi
yhirano 2016/08/04 12:50:51 Done.
59 class MojoAsyncResourceHandler::SharedWriter final
60 : public base::RefCountedThreadSafe<SharedWriter> {
61 public:
62 explicit SharedWriter(mojo::ScopedDataPipeProducerHandle writer)
63 : writer_(std::move(writer)) {}
64 mojo::DataPipeProducerHandle writer() { return writer_.get(); }
65
66 private:
67 friend class base::RefCountedThreadSafe<SharedWriter>;
68 ~SharedWriter() {}
69
70 const mojo::ScopedDataPipeProducerHandle writer_;
71
72 DISALLOW_COPY_AND_ASSIGN(SharedWriter);
73 };
74
75 // This class is a IOBuffer subclass for data gotten from a
76 // ScopedDataPipeProducerHandle.
77 class MojoAsyncResourceHandler::WriterIOBuffer final
78 : public net::IOBufferWithSize {
79 public:
80 // |data| and |size| should be gotten from |writer| via BeginWriteDataRaw.
81 // They will be accesible via IOBuffer methods. As |writer| is stored in this
82 // instance, |data| will be kept valid as long as the following conditions
83 // hold:
84 // 1. |data| is not invalidated via EndWriteDataRaw.
85 // 2. |this| instance is alive.
86 WriterIOBuffer(scoped_refptr<MojoAsyncResourceHandler::SharedWriter> writer,
kinuko 2016/08/03 18:20:07 nit: I guess MojoAsyncResourceHandler:: is not nec
yhirano 2016/08/04 12:50:51 Done.
87 void* data,
88 size_t size)
89 : net::IOBufferWithSize(static_cast<char*>(data), size),
90 writer_(std::move(writer)) {}
91
92 private:
93 ~WriterIOBuffer() override {
94 // Avoid deleting |data_| in the IOBuffer destructor.
95 data_ = nullptr;
96 }
97
98 // This member is for keeping the writer alive.
99 scoped_refptr<MojoAsyncResourceHandler::SharedWriter> writer_;
kinuko 2016/08/03 18:20:07 ditto
yhirano 2016/08/04 12:50:51 Done.
100
101 DISALLOW_COPY_AND_ASSIGN(WriterIOBuffer);
102 };
103
104 MojoAsyncResourceHandler::MojoAsyncResourceHandler(
105 net::URLRequest* request,
106 ResourceDispatcherHostImpl* rdh,
107 mojo::InterfaceRequest<mojom::URLLoader> mojo_request,
108 mojom::URLLoaderClientPtr url_loader_client)
109 : ResourceHandler(request),
110 rdh_(rdh),
111 binding_(this, std::move(mojo_request)),
112 url_loader_client_(std::move(url_loader_client)) {
113 DCHECK(url_loader_client_);
114 InitializeResourceBufferConstants();
115 }
116
117 MojoAsyncResourceHandler::~MojoAsyncResourceHandler() {
118 if (has_checked_for_sufficient_resources_)
119 rdh_->FinishedWithResourcesForRequest(request());
120 }
121
122 bool MojoAsyncResourceHandler::OnRequestRedirected(
123 const net::RedirectInfo& redirect_info,
124 ResourceResponse* response,
125 bool* defer) {
126 // Not implemented.
127 return false;
128 }
129
130 bool MojoAsyncResourceHandler::OnResponseStarted(ResourceResponse* response,
131 bool* defer) {
132 const ResourceRequestInfoImpl* info = GetRequestInfo();
133
134 if (rdh_->delegate()) {
135 rdh_->delegate()->OnResponseStarted(request(), info->GetContext(),
136 response);
137 }
138
139 NetLogObserver::PopulateResponseInfo(request(), response);
140
141 response->head.request_start = request()->creation_time();
142 response->head.response_start = base::TimeTicks::Now();
143 sent_received_response_message_ = true;
144 url_loader_client_->OnReceiveResponse(response->head);
145 return true;
146 }
147
148 bool MojoAsyncResourceHandler::OnWillStart(const GURL& url, bool* defer) {
149 return true;
150 }
151
152 bool MojoAsyncResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf,
153 int* buf_size,
154 int min_size) {
155 DCHECK_EQ(-1, min_size);
156
157 if (!CheckForSufficientResource())
158 return false;
159
160 if (!shared_writer_) {
161 MojoCreateDataPipeOptions options;
162 options.struct_size = sizeof(MojoCreateDataPipeOptions);
163 options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE;
164 options.element_num_bytes = 1;
165 options.capacity_num_bytes = g_allocation_size;
166 mojo::DataPipe data_pipe(options);
167
168 url_loader_client_->OnStartLoadingResponseBody(
169 std::move(data_pipe.consumer_handle));
170 if (!data_pipe.producer_handle.is_valid())
171 return false;
172
173 shared_writer_ = new SharedWriter(std::move(data_pipe.producer_handle));
174
175 bool defer = false;
176 scoped_refptr<net::IOBufferWithSize> buffer;
177 if (!AllocateBuffer(&buffer, &defer))
178 return false;
179 if (!defer && static_cast<size_t>(buffer->size()) >= kMinAllocationSize) {
180 *buf = buffer_ = buffer;
181 *buf_size = buffer_->size();
182 return true;
183 }
184 if (!defer) {
185 // The allocated buffer is too small.
186 if (EndWrite(0) != MOJO_RESULT_OK)
187 return false;
188 }
kinuko 2016/08/04 16:07:02 nit: I feel merging the above two conditions might
yhirano 2016/08/05 12:21:39 Done.
189 DCHECK(!is_using_io_buffer_not_from_writer_);
190 is_using_io_buffer_not_from_writer_ = true;
kinuko 2016/08/03 18:20:07 (Hm this flag feels a bit unfortunate...)
mmenke 2016/08/03 18:25:57 I agree - we may want to make this method able to
yhirano 2016/08/04 12:50:51 +1
kinuko 2016/08/04 16:07:02 Yup, sounds good.
191 buffer_ = new net::IOBufferWithSize(kMinAllocationSize);
192 }
193
194 DCHECK_EQ(0u, buffer_offset_);
195 *buf = buffer_;
196 *buf_size = buffer_->size();
197 return true;
198 }
199
200 bool MojoAsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
201 DCHECK_GE(bytes_read, 0);
202 DCHECK(buffer_);
203
204 if (!bytes_read)
205 return true;
206
207 if (is_using_io_buffer_not_from_writer_) {
208 // Couldn't allocate a buffer on the data pipe in OnWillRead.
209 DCHECK_EQ(0u, buffer_bytes_read_);
210 buffer_bytes_read_ = bytes_read;
211 if (!CopyReadData(defer))
212 return false;
213 if (*defer)
214 OnDefer();
215 return true;
216 }
217
218 if (EndWrite(bytes_read) != MOJO_RESULT_OK)
219 return false;
220 // Allocate a buffer for the next OnWillRead call here, because OnWillRead
221 // doesn't have |defer| parameter.
222 if (!AllocateBuffer(&buffer_, defer))
223 return false;
224 if (*defer)
225 OnDefer();
226 return true;
227 }
228
229 void MojoAsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) {
230 // Not implemented.
231 }
232
233 void MojoAsyncResourceHandler::FollowRedirect() {
234 NOTIMPLEMENTED();
235 }
236
237 void MojoAsyncResourceHandler::Cancel() {
238 NOTIMPLEMENTED();
239 }
240
241 void MojoAsyncResourceHandler::ResumeForTesting() {
242 Resume();
243 }
244
245 void MojoAsyncResourceHandler::SetAllocationSizeForTesting(size_t size) {
246 g_allocation_size = size;
247 }
248
249 MojoResult MojoAsyncResourceHandler::BeginWrite(void** data,
250 uint32_t* available) {
251 MojoResult result = mojo::BeginWriteDataRaw(
252 shared_writer_->writer(), data, available, MOJO_WRITE_DATA_FLAG_NONE);
253 if (result == MOJO_RESULT_OK)
254 *available = std::min(*available, static_cast<uint32_t>(kMaxChunkSize));
255 return result;
256 }
257
258 MojoResult MojoAsyncResourceHandler::EndWrite(uint32_t written) {
259 return mojo::EndWriteDataRaw(shared_writer_->writer(), written);
260 }
261
262 void MojoAsyncResourceHandler::OnResponseCompleted(
263 const net::URLRequestStatus& status,
264 const std::string& security_info,
265 bool* defer) {
266 shared_writer_ = nullptr;
267 buffer_ = nullptr;
268 handle_watcher_.Stop();
269
270 const ResourceRequestInfoImpl* info = GetRequestInfo();
271
272 // TODO(gavinp): Remove this CHECK when we figure out the cause of
273 // http://crbug.com/124680 . This check mirrors closely check in
274 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
275 // ResourceHandleInternal which asserts on its state and crashes. By crashing
276 // when the message is sent, we should get better crash reports.
277 CHECK(status.status() != net::URLRequestStatus::SUCCESS ||
278 sent_received_response_message_);
279
280 int error_code = status.error();
281 bool was_ignored_by_handler = info->WasIgnoredByHandler();
282
283 DCHECK_NE(status.status(), net::URLRequestStatus::IO_PENDING);
284 // If this check fails, then we're in an inconsistent state because all
285 // requests ignored by the handler should be canceled (which should result in
286 // the ERR_ABORTED error code).
287 DCHECK(!was_ignored_by_handler || error_code == net::ERR_ABORTED);
288
289 ResourceRequestCompletionStatus request_complete_data;
290 request_complete_data.error_code = error_code;
291 request_complete_data.was_ignored_by_handler = was_ignored_by_handler;
292 request_complete_data.exists_in_cache = request()->response_info().was_cached;
293 request_complete_data.security_info = security_info;
294 request_complete_data.completion_time = base::TimeTicks::Now();
295 request_complete_data.encoded_data_length =
296 request()->GetTotalReceivedBytes();
297
298 url_loader_client_->OnComplete(request_complete_data);
299 }
300
301 bool MojoAsyncResourceHandler::CopyReadData(bool* defer) {
302 while (true) {
303 scoped_refptr<net::IOBufferWithSize> dest;
304 if (!AllocateBuffer(&dest, defer))
305 return false;
306 if (*defer)
307 return true;
308 if (buffer_bytes_read_ == 0) {
309 // All bytes are copied. Save the buffer for the next OnWillRead call.
310 buffer_ = std::move(dest);
311 return true;
312 }
313
314 size_t copied_size =
315 std::min(buffer_bytes_read_, static_cast<size_t>(dest->size()));
316 memcpy(dest->data(), buffer_->data() + buffer_offset_, copied_size);
317 buffer_offset_ += copied_size;
318 buffer_bytes_read_ -= copied_size;
319 if (EndWrite(copied_size) != MOJO_RESULT_OK)
320 return false;
321
322 if (buffer_bytes_read_ == 0) {
323 // All bytes are copied.
324 buffer_offset_ = 0;
325 is_using_io_buffer_not_from_writer_ = false;
326 }
327 }
328 }
329
330 bool MojoAsyncResourceHandler::AllocateBuffer(
331 scoped_refptr<net::IOBufferWithSize>* buf,
332 bool* defer) {
333 void* data = nullptr;
334 uint32_t available = 0;
335 MojoResult result = BeginWrite(&data, &available);
336 if (result == MOJO_RESULT_SHOULD_WAIT) {
337 *defer = true;
338 return true;
339 }
340 if (result != MOJO_RESULT_OK)
341 return false;
342 *buf = new WriterIOBuffer(shared_writer_, data, available);
343 return true;
344 }
345
346 void MojoAsyncResourceHandler::Resume() {
347 bool defer = false;
348 if (is_using_io_buffer_not_from_writer_) {
349 // |buffer_| is set to a net::IOBufferWithSize. Write the buffer contents
350 // to the data pipe.
351 DCHECK_GT(buffer_bytes_read_, 0u);
352 if (!CopyReadData(&defer)) {
353 controller()->CancelWithError(net::ERR_FAILED);
354 return;
355 }
356 } else {
357 // Allocate a buffer for the next OnWillRead call here.
358 if (!AllocateBuffer(&buffer_, &defer)) {
359 controller()->CancelWithError(net::ERR_FAILED);
360 return;
361 }
362 }
363
364 if (defer) {
365 // Continue waiting.
366 handle_watcher_.Start(shared_writer_->writer(), MOJO_HANDLE_SIGNAL_WRITABLE,
367 MOJO_DEADLINE_INDEFINITE,
368 base::Bind(&MojoAsyncResourceHandler::OnWritable,
369 base::Unretained(this)));
370 return;
371 }
372 request()->LogUnblocked();
373 controller()->Resume();
374 }
375
376 void MojoAsyncResourceHandler::OnDefer() {
377 request()->LogBlockedBy("MojoAsyncResourceHandler");
378 handle_watcher_.Start(shared_writer_->writer(), MOJO_HANDLE_SIGNAL_WRITABLE,
379 MOJO_DEADLINE_INDEFINITE,
380 base::Bind(&MojoAsyncResourceHandler::OnWritable,
381 base::Unretained(this)));
382 }
383
384 bool MojoAsyncResourceHandler::CheckForSufficientResource() {
385 if (has_checked_for_sufficient_resources_)
386 return true;
387 has_checked_for_sufficient_resources_ = true;
388
389 if (rdh_->HasSufficientResourcesForRequest(request()))
390 return true;
391
392 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
393 return false;
394 }
395
396 void MojoAsyncResourceHandler::OnWritable(MojoResult unused) {
397 Resume();
398 }
399
400 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698