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

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: fix 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;
33
34 // MimeTypeResourceHandler *implicitly* requires that the buffer size
35 // returned from OnWillRead should be larger than certain size.
36 // TODO(yhirano): Fix MimeTypeResourceHandler.
37 constexpr size_t kMinAllocationSize = 2 * net::kMaxBytesToSniff;
38
39 constexpr size_t kMaxChunkSize = 32 * 1024;
40
41 void GetNumericArg(const std::string& name, int* result) {
42 const std::string& value =
43 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(name);
44 if (!value.empty())
45 base::StringToInt(value, result);
46 }
47
48 void InitializeResourceBufferConstants() {
49 static bool did_init = false;
50 if (did_init)
51 return;
52 did_init = true;
53
54 GetNumericArg("resource-buffer-size", &g_allocation_size);
55 }
56
57 } // namespace
58
59 // This class is for sharing the ownership of a ScopedDataPipeProducerHandle
60 // between WriterIOBuffer and MojoAsyncResourceHandler.
61 class MojoAsyncResourceHandler::SharedWriter final
62 : public base::RefCountedThreadSafe<SharedWriter> {
63 public:
64 explicit SharedWriter(mojo::ScopedDataPipeProducerHandle writer)
65 : writer_(std::move(writer)) {}
66 mojo::DataPipeProducerHandle writer() { return writer_.get(); }
67
68 private:
69 friend class base::RefCountedThreadSafe<SharedWriter>;
70 ~SharedWriter() {}
71
72 const mojo::ScopedDataPipeProducerHandle writer_;
73
74 DISALLOW_COPY_AND_ASSIGN(SharedWriter);
75 };
76
77 // This class is a IOBuffer subclass for data gotten from a
78 // ScopedDataPipeProducerHandle.
79 class MojoAsyncResourceHandler::WriterIOBuffer final
80 : public net::IOBufferWithSize {
81 public:
82 // |data| and |size| should be gotten from |writer| via BeginWriteDataRaw.
83 // They will be accesible via IOBuffer methods. As |writer| is stored in this
84 // instance, |data| will be kept valid as long as the following conditions
85 // hold:
86 // 1. |data| is not invalidated via EndWriteDataRaw.
87 // 2. |this| instance is alive.
88 WriterIOBuffer(scoped_refptr<SharedWriter> writer, void* data, 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<SharedWriter> writer_;
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 (!AllocateWriterIOBuffer(&buffer, &defer))
178 return false;
179 if (!defer) {
180 if (static_cast<size_t>(buffer->size()) >= kMinAllocationSize) {
181 *buf = buffer_ = buffer;
182 *buf_size = buffer_->size();
183 return true;
184 }
185
186 // The allocated buffer is too small.
187 if (EndWrite(0) != MOJO_RESULT_OK)
188 return false;
189 }
190 DCHECK(!is_using_io_buffer_not_from_writer_);
191 is_using_io_buffer_not_from_writer_ = true;
192 buffer_ = new net::IOBufferWithSize(kMinAllocationSize);
193 }
194
195 DCHECK_EQ(0u, buffer_offset_);
196 *buf = buffer_;
197 *buf_size = buffer_->size();
198 return true;
199 }
200
201 bool MojoAsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
202 DCHECK_GE(bytes_read, 0);
203 DCHECK(buffer_);
204
205 if (!bytes_read)
206 return true;
207
208 if (is_using_io_buffer_not_from_writer_) {
209 // Couldn't allocate a buffer on the data pipe in OnWillRead.
210 DCHECK_EQ(0u, buffer_bytes_read_);
211 buffer_bytes_read_ = bytes_read;
212 if (!CopyReadDataToDataPipe(defer))
213 return false;
214 if (*defer)
215 OnDefer();
216 return true;
217 }
218
219 if (EndWrite(bytes_read) != MOJO_RESULT_OK)
220 return false;
221 // Allocate a buffer for the next OnWillRead call here, because OnWillRead
222 // doesn't have |defer| parameter.
223 if (!AllocateWriterIOBuffer(&buffer_, defer))
224 return false;
225 if (*defer)
226 OnDefer();
227 return true;
228 }
229
230 void MojoAsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) {
231 // Not implemented.
232 }
233
234 void MojoAsyncResourceHandler::FollowRedirect() {
235 NOTIMPLEMENTED();
236 }
237
238 void MojoAsyncResourceHandler::Cancel() {
239 NOTIMPLEMENTED();
240 }
241
242 void MojoAsyncResourceHandler::ResumeForTesting() {
243 Resume();
244 }
245
246 void MojoAsyncResourceHandler::SetAllocationSizeForTesting(size_t size) {
247 g_allocation_size = size;
248 }
249
250 MojoResult MojoAsyncResourceHandler::BeginWrite(void** data,
251 uint32_t* available) {
252 MojoResult result = mojo::BeginWriteDataRaw(
253 shared_writer_->writer(), data, available, MOJO_WRITE_DATA_FLAG_NONE);
254 if (result == MOJO_RESULT_OK)
255 *available = std::min(*available, static_cast<uint32_t>(kMaxChunkSize));
256 return result;
257 }
258
259 MojoResult MojoAsyncResourceHandler::EndWrite(uint32_t written) {
260 return mojo::EndWriteDataRaw(shared_writer_->writer(), written);
261 }
262
263 void MojoAsyncResourceHandler::OnResponseCompleted(
264 const net::URLRequestStatus& status,
265 const std::string& security_info,
266 bool* defer) {
267 shared_writer_ = nullptr;
268 buffer_ = nullptr;
269 handle_watcher_.Stop();
270
271 const ResourceRequestInfoImpl* info = GetRequestInfo();
272
273 // TODO(gavinp): Remove this CHECK when we figure out the cause of
274 // http://crbug.com/124680 . This check mirrors closely check in
275 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
276 // ResourceHandleInternal which asserts on its state and crashes. By crashing
277 // when the message is sent, we should get better crash reports.
278 CHECK(status.status() != net::URLRequestStatus::SUCCESS ||
279 sent_received_response_message_);
280
281 int error_code = status.error();
282 bool was_ignored_by_handler = info->WasIgnoredByHandler();
283
284 DCHECK_NE(status.status(), net::URLRequestStatus::IO_PENDING);
285 // If this check fails, then we're in an inconsistent state because all
286 // requests ignored by the handler should be canceled (which should result in
287 // the ERR_ABORTED error code).
288 DCHECK(!was_ignored_by_handler || error_code == net::ERR_ABORTED);
289
290 ResourceRequestCompletionStatus request_complete_data;
291 request_complete_data.error_code = error_code;
292 request_complete_data.was_ignored_by_handler = was_ignored_by_handler;
293 request_complete_data.exists_in_cache = request()->response_info().was_cached;
294 request_complete_data.security_info = security_info;
295 request_complete_data.completion_time = base::TimeTicks::Now();
296 request_complete_data.encoded_data_length =
297 request()->GetTotalReceivedBytes();
298
299 url_loader_client_->OnComplete(request_complete_data);
300 }
301
302 bool MojoAsyncResourceHandler::CopyReadDataToDataPipe(bool* defer) {
303 while (true) {
304 scoped_refptr<net::IOBufferWithSize> dest;
305 if (!AllocateWriterIOBuffer(&dest, defer))
306 return false;
307 if (*defer)
308 return true;
309 if (buffer_bytes_read_ == 0) {
310 // All bytes are copied. Save the buffer for the next OnWillRead call.
311 buffer_ = std::move(dest);
312 return true;
313 }
314
315 size_t copied_size =
316 std::min(buffer_bytes_read_, static_cast<size_t>(dest->size()));
317 memcpy(dest->data(), buffer_->data() + buffer_offset_, copied_size);
318 buffer_offset_ += copied_size;
319 buffer_bytes_read_ -= copied_size;
320 if (EndWrite(copied_size) != MOJO_RESULT_OK)
321 return false;
322
323 if (buffer_bytes_read_ == 0) {
324 // All bytes are copied.
325 buffer_offset_ = 0;
326 is_using_io_buffer_not_from_writer_ = false;
327 }
328 }
329 }
330
331 bool MojoAsyncResourceHandler::AllocateWriterIOBuffer(
332 scoped_refptr<net::IOBufferWithSize>* buf,
333 bool* defer) {
334 void* data = nullptr;
335 uint32_t available = 0;
336 MojoResult result = BeginWrite(&data, &available);
337 if (result == MOJO_RESULT_SHOULD_WAIT) {
338 *defer = true;
339 return true;
340 }
341 if (result != MOJO_RESULT_OK)
342 return false;
343 *buf = new WriterIOBuffer(shared_writer_, data, available);
344 return true;
345 }
346
347 void MojoAsyncResourceHandler::Resume() {
348 bool defer = false;
349 if (is_using_io_buffer_not_from_writer_) {
350 // |buffer_| is set to a net::IOBufferWithSize. Write the buffer contents
351 // to the data pipe.
352 DCHECK_GT(buffer_bytes_read_, 0u);
353 if (!CopyReadDataToDataPipe(&defer)) {
354 controller()->CancelWithError(net::ERR_FAILED);
355 return;
356 }
357 } else {
358 // Allocate a buffer for the next OnWillRead call here.
359 if (!AllocateWriterIOBuffer(&buffer_, &defer)) {
360 controller()->CancelWithError(net::ERR_FAILED);
361 return;
362 }
363 }
364
365 if (defer) {
366 // Continue waiting.
367 handle_watcher_.Start(shared_writer_->writer(), MOJO_HANDLE_SIGNAL_WRITABLE,
368 MOJO_DEADLINE_INDEFINITE,
369 base::Bind(&MojoAsyncResourceHandler::OnWritable,
370 base::Unretained(this)));
371 return;
372 }
373 request()->LogUnblocked();
374 controller()->Resume();
375 }
376
377 void MojoAsyncResourceHandler::OnDefer() {
378 request()->LogBlockedBy("MojoAsyncResourceHandler");
379 handle_watcher_.Start(shared_writer_->writer(), MOJO_HANDLE_SIGNAL_WRITABLE,
380 MOJO_DEADLINE_INDEFINITE,
381 base::Bind(&MojoAsyncResourceHandler::OnWritable,
382 base::Unretained(this)));
383 }
384
385 bool MojoAsyncResourceHandler::CheckForSufficientResource() {
386 if (has_checked_for_sufficient_resources_)
387 return true;
388 has_checked_for_sufficient_resources_ = true;
389
390 if (rdh_->HasSufficientResourcesForRequest(request()))
391 return true;
392
393 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
394 return false;
395 }
396
397 void MojoAsyncResourceHandler::OnWritable(MojoResult unused) {
398 Resume();
399 }
400
401 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698