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

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, 5 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 // 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.
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,
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_;
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::OnBeforeNetworkStart(const GURL& url,
153 bool* defer) {
154 return true;
155 }
156
157 bool MojoAsyncResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf,
158 int* buf_size,
159 int min_size) {
160 DCHECK_EQ(-1, min_size);
161
162 if (!CheckForSufficientResource())
163 return false;
164
165 if (!shared_writer_) {
166 MojoCreateDataPipeOptions options;
167 options.struct_size = sizeof(MojoCreateDataPipeOptions);
168 options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE;
169 options.element_num_bytes = 1;
170 options.capacity_num_bytes = g_allocation_size;
171 mojo::DataPipe data_pipe(options);
172
173 url_loader_client_->OnStartLoadingResponseBody(
174 std::move(data_pipe.consumer_handle));
175 if (!data_pipe.producer_handle.is_valid())
176 return false;
177
178 shared_writer_ = new SharedWriter(std::move(data_pipe.producer_handle));
179
180 bool defer = false;
181 scoped_refptr<net::IOBufferWithSize> buffer;
182 if (!AllocateBuffer(&buffer, &defer))
183 return false;
184 if (!defer && static_cast<size_t>(buffer->size()) >= kMinAllocationSize) {
185 *buf = buffer_ = buffer;
186 *buf_size = buffer_->size();
187 return true;
188 }
189 if (!defer) {
190 // The allocated buffer is too small.
191 if (EndWrite(0) != MOJO_RESULT_OK)
192 return false;
193 }
194 DCHECK(!is_using_io_buffer_not_from_writer_);
195 is_using_io_buffer_not_from_writer_ = true;
196 buffer_ = new net::IOBufferWithSize(kMinAllocationSize);
197 }
198
199 DCHECK_EQ(0u, buffer_offset_);
200 *buf = buffer_;
201 *buf_size = buffer_->size();
202 return true;
203 }
204
205 bool MojoAsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
206 DCHECK_GE(bytes_read, 0);
207 DCHECK(buffer_);
208
209 if (!bytes_read)
210 return true;
211
212 if (is_using_io_buffer_not_from_writer_) {
213 // Couldn't allocate a buffer on the data pipe in OnWillRead.
214 DCHECK_EQ(0u, buffer_bytes_read_);
215 buffer_bytes_read_ = bytes_read;
216 if (!CopyReadData(defer))
217 return false;
218 if (*defer)
219 OnDefer();
220 return true;
221 }
222
223 if (EndWrite(bytes_read) != MOJO_RESULT_OK)
224 return false;
225 // Allocate a buffer for the next OnWillRead call here, because OnWillRead
226 // doesn't have |defer| parameter.
227 if (!AllocateBuffer(&buffer_, defer))
228 return false;
229 if (*defer)
230 OnDefer();
231 return true;
232 }
233
234 void MojoAsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) {
235 // Not implemented.
236 }
237
238 void MojoAsyncResourceHandler::FollowRedirect() {
239 NOTIMPLEMENTED();
240 }
241
242 void MojoAsyncResourceHandler::Cancel() {
243 NOTIMPLEMENTED();
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(status.status() != net::URLRequestStatus::IO_PENDING);
mmenke 2016/07/25 22:03:53 DCHECK_NE
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::CopyReadData(bool* defer) {
303 while (true) {
304 scoped_refptr<net::IOBufferWithSize> dest;
305 if (!AllocateBuffer(&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::AllocateBuffer(
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 (!CopyReadData(&defer)) {
354 controller()->CancelWithError(net::ERR_FAILED);
355 return;
356 }
357 } else {
358 // Allocate a buffer for the next OnWillRead call here.
359 if (!AllocateBuffer(&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