OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2012 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 "chrome/browser/predictors/resource_prefetch_predictor.h" | |
6 | |
7 #include <utility> | |
8 | |
9 #include "base/command_line.h" | |
10 #include "base/metrics/histogram.h" | |
11 #include "base/stl_util.h" | |
12 #include "base/time.h" | |
13 #include "chrome/browser/history/history.h" | |
14 #include "chrome/browser/history/history_notifications.h" | |
15 #include "chrome/browser/history/in_memory_database.h" | |
16 #include "chrome/browser/history/url_database.h" | |
17 #include "chrome/browser/predictors/predictor_database.h" | |
18 #include "chrome/browser/predictors/predictor_database_factory.h" | |
19 #include "chrome/browser/profiles/profile.h" | |
20 #include "chrome/common/chrome_notification_types.h" | |
21 #include "chrome/common/chrome_switches.h" | |
22 #include "chrome/common/url_constants.h" | |
23 #include "content/browser/load_from_memory_cache_details.h" | |
24 #include "content/public/browser/browser_thread.h" | |
25 #include "content/public/browser/navigation_controller.h" | |
26 #include "content/public/browser/notification_service.h" | |
27 #include "content/public/browser/notification_source.h" | |
28 #include "content/public/browser/notification_types.h" | |
29 #include "content/public/browser/resource_request_info.h" | |
30 #include "content/public/browser/web_contents.h" | |
31 #include "net/base/mime_util.h" | |
32 #include "net/http/http_response_headers.h" | |
33 #include "net/url_request/url_request.h" | |
34 #include "net/url_request/url_request_context_getter.h" | |
35 | |
36 using content::BrowserThread; | |
37 | |
38 namespace { | |
39 | |
40 // If a navigation hasn't seen a load complete event in this much time, it is | |
41 // considered abandoned. | |
42 static const int kMaxNavigationLifetimeSeconds = 60; | |
43 | |
44 // Size of LRU caches for the Url data. | |
45 static const size_t kMaxNumUrlsToTrack = 500; | |
46 | |
47 // The number of times, we should have seen visit to this Url in history | |
48 // to start tracking it. This is to ensure we dont bother with oneoff entries. | |
49 static const int kMinUrlVisitCount = 3; | |
50 | |
51 // The maximum number of resources to store per entry. This is about double of | |
52 // the expected 25 we expect to prefetch. | |
53 static const int kMaxResourcesPerEntry = 50; | |
54 | |
55 // Don't store subresources whose Urls are longer than this. | |
56 static const size_t kMaxSubresourceUrlLengthBytes = 1000; | |
57 | |
58 // The number of consecutive misses after we stop tracking a resource Url. | |
59 static const int kMaxConsecutiveMisses = 3; | |
60 | |
61 // The number of resources we should report accuracy stats on. | |
62 static const int kNumResourcesAssumedPrefetched = 25; | |
63 | |
64 ResourceType::Type GetResourceTypeFromMimeType(const std::string& mime_type, | |
65 ResourceType::Type fallback) { | |
66 if (net::IsSupportedImageMimeType(mime_type.c_str())) | |
67 return ResourceType::IMAGE; | |
68 else if (net::IsSupportedJavascriptMimeType(mime_type.c_str())) | |
69 return ResourceType::SCRIPT; | |
70 else if (net::MatchesMimeType("text/css", mime_type)) | |
71 return ResourceType::STYLESHEET; | |
72 else | |
73 return fallback; | |
74 } | |
75 | |
76 // For reporting histograms about navigation status. | |
77 enum NavigationStatus { | |
78 NAVIGATION_STATUS_COMPLETE = 0, | |
79 NAVIGATION_STATUS_COMPLETE_ABANDONED = 1, | |
80 NAVIGATION_STATUS_ABANDONED = 2, | |
81 NAVIGATION_STATUS_COUNT = 3 | |
82 }; | |
83 | |
84 } // namespace | |
85 | |
86 namespace predictors { | |
87 | |
88 ResourcePrefetchPredictor::URLRequestSummary::URLRequestSummary() | |
89 : resource_type_(ResourceType::LAST_TYPE), | |
90 was_cached_(false) { | |
91 } | |
92 | |
93 ResourcePrefetchPredictor::URLRequestSummary::URLRequestSummary( | |
94 const URLRequestSummary& other) | |
95 : navigation_id_(other.navigation_id_), | |
96 resource_url_(other.resource_url_), | |
97 resource_type_(other.resource_type_), | |
98 mime_type_(other.mime_type_), | |
99 was_cached_(other.was_cached_) { | |
100 } | |
101 | |
102 ResourcePrefetchPredictor::URLRequestSummary::~URLRequestSummary() { | |
103 } | |
104 | |
105 bool ResourcePrefetchPredictor::URLRequestSummary::InitFromURLRequest( | |
106 net::URLRequest* request, | |
107 bool is_response) { | |
108 const content::ResourceRequestInfo* info = | |
109 content::ResourceRequestInfo::ForRequest(request); | |
110 if (!info) { | |
111 LOG(ERROR) << "No ResourceRequestInfo in request"; | |
112 return false; | |
113 } | |
114 | |
115 int render_process_id, render_view_id; | |
116 if (!info->GetAssociatedRenderView(&render_process_id, &render_view_id)) { | |
117 LOG(ERROR) << "Could not get RenderViewId from request info."; | |
118 return false; | |
119 } | |
120 | |
121 navigation_id_.render_process_id_ = render_process_id; | |
122 navigation_id_.render_view_id_ = render_view_id; | |
123 navigation_id_.main_frame_url_ = request->first_party_for_cookies(); | |
124 navigation_id_.creation_time_ = request->creation_time(); | |
125 resource_url_ = request->original_url(); | |
126 resource_type_ = info->GetResourceType(); | |
127 if (is_response) { | |
128 request->GetMimeType(&mime_type_); | |
129 was_cached_ = request->was_cached(); | |
130 // We want to rely on the mime_type for the resource type. | |
131 resource_type_ = GetResourceTypeFromMimeType(mime_type_, resource_type_); | |
132 } | |
133 | |
134 return true; | |
135 } | |
136 | |
137 ResourcePrefetchPredictor::ResourcePrefetchPredictor(Profile* profile) | |
138 : profile_(profile), | |
139 initialization_state_(NOT_INITIALIZED), | |
140 tables_(PredictorDatabaseFactory::GetForProfile( | |
141 profile)->resource_prefetch_tables()), | |
142 notification_registrar_(new content::NotificationRegistrar()) { | |
143 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
144 } | |
145 | |
146 ResourcePrefetchPredictor::~ResourcePrefetchPredictor() { | |
willchan no longer on Chromium
2012/05/31 02:08:58
This is deleted on the UI thread, right?
Shishir
2012/06/02 01:19:29
Yes. Added assertion.
| |
147 } | |
148 | |
149 // static | |
150 bool ResourcePrefetchPredictor::IsEnabled() { | |
151 CommandLine* command_line = CommandLine::ForCurrentProcess(); | |
152 return command_line->HasSwitch( | |
153 switches::kEnableSpeculativeResourcePrefetching); | |
willchan no longer on Chromium
2012/05/31 02:08:58
Is this supposed to dynamically checked? Do you wa
Shishir
2012/06/02 01:19:29
It can presently be set by about:flags. But i thou
| |
154 } | |
155 | |
156 void ResourcePrefetchPredictor::LazilyInitialize() { | |
157 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
158 | |
159 DCHECK_EQ(initialization_state_, NOT_INITIALIZED); | |
160 initialization_state_ = INITIALIZING; | |
161 | |
162 // Request the in-memory database from the history to force it to load so it's | |
163 // available as soon as possible. | |
164 HistoryService* history_service = | |
165 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS); | |
166 if (history_service) | |
167 history_service->InMemoryDatabase(); | |
168 | |
169 // Create local caches using the database as loaded. | |
170 std::vector<UrlTableRow>* url_rows = new std::vector<UrlTableRow>(); | |
171 BrowserThread::PostTaskAndReply( | |
172 BrowserThread::DB, FROM_HERE, | |
173 base::Bind(&ResourcePrefetchPredictorTables::GetAllRows, | |
174 tables_, url_rows), | |
175 base::Bind(&ResourcePrefetchPredictor::CreateCaches, AsWeakPtr(), | |
176 base::Owned(url_rows))); | |
177 } | |
178 | |
179 void ResourcePrefetchPredictor::CreateCaches( | |
180 std::vector<UrlTableRow>* url_rows) { | |
181 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
182 | |
183 DCHECK_EQ(initialization_state_, INITIALIZING); | |
184 DCHECK(url_table_cache_.empty()); | |
185 DCHECK(inflight_navigations_.empty()); | |
186 | |
187 // Copy the data to local caches. | |
188 for (UrlTableRowVector::iterator it = url_rows->begin(); | |
189 it != url_rows->end(); ++it) { | |
190 url_table_cache_[it->main_frame_url_].rows_.push_back(*it); | |
191 } | |
192 | |
193 // Score and sort the database caches. | |
194 // TODO(shishir): The following would be much more efficient if we used | |
195 // pointers. | |
196 for (UrlTableCacheMap::iterator it = url_table_cache_.begin(); | |
197 it != url_table_cache_.end(); ++it) { | |
198 std::sort(it->second.rows_.begin(), | |
199 it->second.rows_.end(), | |
200 ResourcePrefetchPredictorTables::UrlTableRowSorter()); | |
201 } | |
202 | |
203 // Add notifications for history loading if it is not ready. | |
204 if (!profile_->GetHistoryService(Profile::EXPLICIT_ACCESS)) { | |
205 notification_registrar_->Add(this, chrome::NOTIFICATION_HISTORY_LOADED, | |
206 content::Source<Profile>(profile_)); | |
207 } else { | |
208 OnHistoryAndCacheLoaded(); | |
209 } | |
210 } | |
211 | |
212 // static | |
213 bool ResourcePrefetchPredictor::ShouldRecordRequest( | |
214 net::URLRequest* request, | |
215 ResourceType::Type resource_type) { | |
216 return resource_type == ResourceType::MAIN_FRAME && | |
217 IsHandledMainPage(request); | |
218 } | |
219 | |
220 // static | |
221 bool ResourcePrefetchPredictor::ShouldRecordResponse( | |
222 net::URLRequest* response) { | |
223 const content::ResourceRequestInfo* request_info = | |
224 content::ResourceRequestInfo::ForRequest(response); | |
225 if (!request_info) | |
226 return false; | |
227 | |
228 return request_info->GetResourceType() == ResourceType::MAIN_FRAME ? | |
229 IsHandledMainPage(response) : IsHandledSubresource(response); | |
230 } | |
231 | |
232 // static | |
233 bool ResourcePrefetchPredictor::ShouldRecordRedirect( | |
234 net::URLRequest* response) { | |
235 const content::ResourceRequestInfo* request_info = | |
236 content::ResourceRequestInfo::ForRequest(response); | |
237 if (!request_info) | |
238 return false; | |
239 | |
240 return request_info->GetResourceType() == ResourceType::MAIN_FRAME && | |
241 IsHandledMainPage(response); | |
242 } | |
243 | |
244 // static | |
245 bool ResourcePrefetchPredictor::IsHandledMainPage(net::URLRequest* request) { | |
246 return request->original_url().scheme() == chrome::kHttpScheme; | |
247 } | |
248 | |
249 // static | |
250 bool ResourcePrefetchPredictor::IsHandledSubresource( | |
251 net::URLRequest* response) { | |
252 if (response->first_party_for_cookies().scheme() != chrome::kHttpScheme) | |
253 return false; | |
254 | |
255 if (response->original_url().scheme() != chrome::kHttpScheme) | |
256 return false; | |
257 | |
258 std::string mime_type; | |
259 response->GetMimeType(&mime_type); | |
260 if (!mime_type.empty() && | |
261 !net::IsSupportedImageMimeType(mime_type.c_str()) && | |
262 !net::IsSupportedJavascriptMimeType(mime_type.c_str()) && | |
263 !net::MatchesMimeType("text/css", mime_type)) { | |
264 return false; | |
265 } | |
266 | |
267 if (response->method() != "GET") | |
268 return false; | |
269 | |
270 if (response->original_url().spec().length() > kMaxSubresourceUrlLengthBytes) | |
271 return false; | |
272 | |
273 bool is_cacheable = IsCacheable(response); | |
274 UMA_HISTOGRAM_BOOLEAN("ResourcePrefetchPredictor.IsCacheableResource", | |
275 is_cacheable); | |
276 return is_cacheable; | |
277 } | |
278 | |
279 // static | |
280 bool ResourcePrefetchPredictor::IsCacheable(const net::URLRequest* response) { | |
281 if (response->was_cached()) | |
282 return true; | |
283 | |
284 // For non cached responses, we will ensure that the freshness lifetime is | |
285 // some sane value. | |
286 const net::HttpResponseInfo& response_info = response->response_info(); | |
287 base::Time response_time(response_info.response_time); | |
288 response_time += base::TimeDelta::FromSeconds(1); | |
289 base::TimeDelta freshness = response_info.headers->GetFreshnessLifetime( | |
290 response_time); | |
291 return freshness > base::TimeDelta(); | |
292 } | |
293 | |
294 void ResourcePrefetchPredictor::RecordURLRequest( | |
295 const URLRequestSummary& request) { | |
296 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
297 | |
298 if (initialization_state_ == NOT_INITIALIZED) { | |
299 LazilyInitialize(); | |
300 return; | |
301 } else if (initialization_state_ != INITIALIZED) { | |
302 return; | |
303 } | |
304 DCHECK_EQ(INITIALIZED, initialization_state_); | |
305 | |
306 CHECK_EQ(request.resource_type_, ResourceType::MAIN_FRAME); | |
307 OnMainFrameRequest(request); | |
308 } | |
309 | |
310 void ResourcePrefetchPredictor::RecordUrlResponse( | |
311 const URLRequestSummary& response) { | |
312 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
313 if (initialization_state_ != INITIALIZED) | |
314 return; | |
315 | |
316 if (response.resource_type_ == ResourceType::MAIN_FRAME) | |
317 OnMainFrameResponse(response); | |
318 else | |
319 OnSubresourceResponse(response); | |
320 } | |
321 | |
322 void ResourcePrefetchPredictor::RecordUrlRedirect( | |
323 const URLRequestSummary& response) { | |
324 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
325 if (initialization_state_ != INITIALIZED) | |
326 return; | |
327 | |
328 CHECK_EQ(response.resource_type_, ResourceType::MAIN_FRAME); | |
329 OnMainFrameRedirect(response); | |
330 } | |
331 | |
332 void ResourcePrefetchPredictor::OnMainFrameRequest( | |
333 const URLRequestSummary& request) { | |
334 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
335 DCHECK_EQ(INITIALIZED, initialization_state_); | |
336 | |
337 // TODO(shishir): Remove this code after verifying that the same navigation is | |
338 // not seen multiple times. | |
339 NavigationMap::const_iterator it = | |
340 inflight_navigations_.find(request.navigation_id_); | |
341 if (it != inflight_navigations_.end()) { | |
342 DCHECK(it->first.creation_time_ != request.navigation_id_.creation_time_); | |
343 } | |
344 | |
345 // Cleanup older navigations. | |
346 CleanupAbandonedNavigations(request.navigation_id_); | |
347 | |
348 // New empty navigation entry. | |
349 inflight_navigations_.insert(std::make_pair( | |
350 request.navigation_id_, std::vector<URLRequestSummary>())); | |
351 } | |
352 | |
353 void ResourcePrefetchPredictor::OnMainFrameResponse( | |
354 const URLRequestSummary& response) { | |
355 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
356 | |
357 // TODO(shishir): The prefreshing will be stopped here. | |
358 } | |
359 | |
360 void ResourcePrefetchPredictor::OnMainFrameRedirect( | |
361 const URLRequestSummary& response) { | |
362 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
363 | |
364 inflight_navigations_.erase(response.navigation_id_); | |
365 } | |
366 | |
367 void ResourcePrefetchPredictor::OnSubresourceResponse( | |
368 const URLRequestSummary& response) { | |
369 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
370 | |
371 if (inflight_navigations_.find(response.navigation_id_) == | |
372 inflight_navigations_.end()) | |
373 return; | |
374 | |
375 inflight_navigations_[response.navigation_id_].push_back(response); | |
376 } | |
377 | |
378 void ResourcePrefetchPredictor::OnSubresourceLoadedFromMemory( | |
379 const NavigationID& navigation_id, | |
380 const GURL& resource_url) { | |
381 if (inflight_navigations_.find(navigation_id) == inflight_navigations_.end()) | |
382 return; | |
383 | |
384 URLRequestSummary summary; | |
385 summary.navigation_id_ = navigation_id; | |
386 summary.resource_url_ = resource_url; | |
387 // The mime_type is currently not available in this notification. | |
388 // TODO(shishir): Set correct type when CL:10413064 is committed. | |
389 summary.resource_type_ = ResourceType::LAST_TYPE; | |
390 summary.was_cached_ = true; | |
391 inflight_navigations_[navigation_id].push_back(summary); | |
392 } | |
393 | |
394 void ResourcePrefetchPredictor::CleanupAbandonedNavigations( | |
395 const NavigationID& navigation_id) { | |
396 static const base::TimeDelta max_navigation_age = | |
397 base::TimeDelta::FromSeconds(kMaxNavigationLifetimeSeconds); | |
398 | |
399 base::TimeTicks time_now = base::TimeTicks::Now(); | |
400 for (NavigationMap::iterator it = inflight_navigations_.begin(); | |
401 it != inflight_navigations_.end();) { | |
402 if (it->first.IsSameRenderer(navigation_id) || | |
403 (time_now - it->first.creation_time_ > max_navigation_age)) { | |
404 inflight_navigations_.erase(it++); | |
405 UMA_HISTOGRAM_ENUMERATION("ResourcePrefetchPredictor.NavigationStatus", | |
406 NAVIGATION_STATUS_ABANDONED, | |
407 NAVIGATION_STATUS_COUNT); | |
408 } else { | |
409 ++it; | |
410 } | |
411 } | |
412 } | |
413 | |
414 void ResourcePrefetchPredictor::Observe( | |
415 int type, | |
416 const content::NotificationSource& source, | |
417 const content::NotificationDetails& details) { | |
418 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
419 | |
420 switch (type) { | |
421 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: { | |
422 const content::WebContents* web_contents = | |
423 content::Source<content::WebContents>(source).ptr(); | |
424 NavigationID navigation_id(*web_contents); | |
425 OnNavigationComplete(navigation_id); | |
426 break; | |
427 } | |
428 | |
429 case content::NOTIFICATION_LOAD_FROM_MEMORY_CACHE: { | |
430 const LoadFromMemoryCacheDetails* load_details = | |
431 content::Details<LoadFromMemoryCacheDetails>(details).ptr(); | |
432 const content::WebContents* web_contents = | |
433 content::Source<content::NavigationController>( | |
434 source).ptr()->GetWebContents(); | |
435 | |
436 NavigationID navigation_id(*web_contents); | |
437 OnSubresourceLoadedFromMemory(navigation_id, load_details->url()); | |
438 break; | |
439 } | |
440 | |
441 case chrome::NOTIFICATION_HISTORY_LOADED: { | |
442 DCHECK_EQ(initialization_state_, INITIALIZING); | |
443 notification_registrar_->Remove(this, | |
444 chrome::NOTIFICATION_HISTORY_LOADED, | |
445 content::Source<Profile>(profile_)); | |
446 OnHistoryAndCacheLoaded(); | |
447 break; | |
448 } | |
449 | |
450 default: | |
451 NOTREACHED() << "Unexpected notification observed."; | |
452 break; | |
453 } | |
454 } | |
455 | |
456 void ResourcePrefetchPredictor::OnHistoryAndCacheLoaded() { | |
willchan no longer on Chromium
2012/05/31 02:08:58
In locations like this where you populate internal
Shishir
2012/06/02 01:19:29
I think that it would be unnecessary at this stage
| |
457 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
458 DCHECK_EQ(initialization_state_, INITIALIZING); | |
459 | |
460 // Update the data with last visit info from in memory history db. | |
461 HistoryService* history_service = | |
462 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS); | |
463 DCHECK(history_service); | |
464 history::URLDatabase* url_db = history_service->InMemoryDatabase(); | |
465 if (url_db) { | |
466 std::vector<GURL> urls_to_delete; | |
467 for (UrlTableCacheMap::iterator it = url_table_cache_.begin(); | |
468 it != url_table_cache_.end();) { | |
469 history::URLRow url_row; | |
470 if (url_db->GetRowForURL(it->first, &url_row) == 0) { | |
471 urls_to_delete.push_back(it->first); | |
472 url_table_cache_.erase(it++); | |
473 } else { | |
474 it->second.last_visit_ = url_row.last_visit(); | |
475 ++it; | |
476 } | |
477 } | |
478 if (!urls_to_delete.empty()) | |
479 BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, | |
480 base::Bind(&ResourcePrefetchPredictorTables::DeleteUrlRows, | |
481 tables_, | |
482 urls_to_delete)); | |
483 } | |
484 | |
485 notification_registrar_->Add( | |
486 this, | |
487 content::NOTIFICATION_LOAD_FROM_MEMORY_CACHE, | |
488 content::NotificationService::AllSources()); | |
489 | |
490 notification_registrar_->Add( | |
491 this, | |
492 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, | |
493 content::NotificationService::AllSources()); | |
494 | |
495 // TODO(shishir): Maybe listen for notifications for navigation being | |
496 // abandoned and cleanup the inflight_navigations_. | |
497 | |
498 initialization_state_ = INITIALIZED; | |
499 } | |
500 | |
501 bool ResourcePrefetchPredictor::ShouldTrackUrl(const GURL& url) { | |
502 if (url_table_cache_.find(url) != url_table_cache_.end()) | |
503 return true; | |
504 | |
505 HistoryService* history_service = | |
506 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS); | |
507 DCHECK(history_service); | |
508 history::URLDatabase* url_db = history_service->InMemoryDatabase(); | |
509 if (!url_db) | |
510 return false; | |
511 | |
512 history::URLRow url_row; | |
513 return url_db->GetRowForURL(url, &url_row) != 0 && | |
514 url_row.visit_count() >= kMinUrlVisitCount; | |
515 } | |
516 | |
517 void ResourcePrefetchPredictor::OnNavigationComplete( | |
518 const NavigationID& navigation_id) { | |
519 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
520 | |
521 if (inflight_navigations_.find(navigation_id) == | |
522 inflight_navigations_.end()) { | |
523 UMA_HISTOGRAM_ENUMERATION("ResourcePrefetchPredictor.NavigationStatus", | |
524 NAVIGATION_STATUS_COMPLETE_ABANDONED, | |
525 NAVIGATION_STATUS_COUNT); | |
526 return; | |
527 } | |
528 | |
529 UMA_HISTOGRAM_ENUMERATION("ResourcePrefetchPredictor.NavigationStatus", | |
530 NAVIGATION_STATUS_COMPLETE, | |
531 NAVIGATION_STATUS_COUNT); | |
532 | |
533 // Report any stats. | |
534 MaybeReportAccuracyStats(navigation_id); | |
535 | |
536 // Update the URL table. | |
537 const GURL& main_frame_url = navigation_id.main_frame_url_; | |
538 if (ShouldTrackUrl(main_frame_url)) | |
539 LearnUrlNavigation(main_frame_url, inflight_navigations_[navigation_id]); | |
540 | |
541 // Remove the navigation. | |
542 inflight_navigations_.erase(navigation_id); | |
543 } | |
544 | |
545 void ResourcePrefetchPredictor::LearnUrlNavigation( | |
546 const GURL& main_frame_url, | |
547 const std::vector<URLRequestSummary>& new_resources) { | |
548 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
549 | |
550 if (url_table_cache_.find(main_frame_url) == url_table_cache_.end()) { | |
551 if (url_table_cache_.size() >= kMaxNumUrlsToTrack) | |
552 RemoveAnEntryFromUrlDB(); | |
553 | |
554 url_table_cache_[main_frame_url].last_visit_ = base::Time::Now(); | |
555 int new_resources_size = static_cast<int>(new_resources.size()); | |
556 for (int i = 0; i < new_resources_size; ++i) { | |
557 UrlTableRow row_to_add; | |
558 row_to_add.main_frame_url_ = main_frame_url; | |
559 row_to_add.resource_url_ = new_resources[i].resource_url_; | |
560 row_to_add.resource_type_ = new_resources[i].resource_type_; | |
561 row_to_add.number_of_hits_ = 1; | |
562 row_to_add.average_position_ = i + 1; | |
563 url_table_cache_[main_frame_url].rows_.push_back(row_to_add); | |
564 } | |
565 } else { | |
566 UrlTableRowVector& old_resources = url_table_cache_[main_frame_url].rows_; | |
567 url_table_cache_[main_frame_url].last_visit_ = base::Time::Now(); | |
568 | |
569 // Build indices over the data. | |
570 std::map<GURL, int> new_index, old_index; | |
571 int new_resources_size = static_cast<int>(new_resources.size()); | |
572 for (int i = 0; i < new_resources_size; ++i) { | |
573 const URLRequestSummary& summary = new_resources[i]; | |
574 // Take the first occurence of every url. | |
575 if (new_index.find(summary.resource_url_) == new_index.end()) | |
576 new_index[summary.resource_url_] = i; | |
577 } | |
578 int old_resources_size = static_cast<int>(old_resources.size()); | |
579 for (int i = 0; i < old_resources_size; ++i) { | |
580 const UrlTableRow& row = old_resources[i]; | |
581 DCHECK(old_index.find(row.resource_url_) == old_index.end()); | |
582 old_index[row.resource_url_] = i; | |
583 } | |
584 | |
585 // Go through the old urls and update their hit/miss counts. | |
586 for (int i = 0; i < old_resources_size; ++i) { | |
587 UrlTableRow& old_row = old_resources[i]; | |
588 if (new_index.find(old_row.resource_url_) == new_index.end()) { | |
589 ++old_row.number_of_misses_; | |
590 ++old_row.consecutive_misses_; | |
591 } else { | |
592 const URLRequestSummary& new_row = | |
593 new_resources[new_index[old_row.resource_url_]]; | |
594 | |
595 // Update the resource type since it could have changed. | |
596 if (new_row.resource_type_ != ResourceType::LAST_TYPE) | |
597 old_row.resource_type_ = new_row.resource_type_; | |
598 | |
599 int position = new_index[old_row.resource_url_] + 1; | |
600 int total = old_row.number_of_hits_ + old_row.number_of_misses_; | |
601 old_row.average_position_ = | |
602 ((old_row.average_position_ * total) + position) / (total + 1); | |
603 ++old_row.number_of_hits_; | |
604 old_row.consecutive_misses_ = 0; | |
605 } | |
606 } | |
607 | |
608 // Add the new ones that we have not seen before. | |
609 for (int i = 0; i < new_resources_size; ++i) { | |
610 const URLRequestSummary& summary = new_resources[i]; | |
611 if (old_index.find(summary.resource_url_) != old_index.end()) | |
612 continue; | |
613 | |
614 // Only need to add new stuff. | |
615 UrlTableRow row_to_add; | |
616 row_to_add.main_frame_url_ = main_frame_url; | |
617 row_to_add.resource_url_ = summary.resource_url_; | |
618 row_to_add.resource_type_ = summary.resource_type_; | |
619 row_to_add.number_of_hits_ = 1; | |
620 row_to_add.average_position_ = i + 1; | |
621 old_resources.push_back(row_to_add); | |
622 | |
623 // To ensure we dont add the same url twice. | |
624 old_index[summary.resource_url_] = 0; | |
625 } | |
626 } | |
627 | |
628 // Trim and sort the rows after the update. | |
629 UrlTableRowVector& rows = url_table_cache_[main_frame_url].rows_; | |
630 for (UrlTableRowVector::iterator it = rows.begin(); it != rows.end();) { | |
631 it->UpdateScore(); | |
632 if (it->consecutive_misses_ >= kMaxConsecutiveMisses) | |
633 it = rows.erase(it); | |
634 else | |
635 ++it; | |
636 } | |
637 std::sort(rows.begin(), rows.end(), | |
638 ResourcePrefetchPredictorTables::UrlTableRowSorter()); | |
639 | |
640 BrowserThread::PostTask( | |
641 BrowserThread::DB, FROM_HERE, | |
642 base::Bind(&ResourcePrefetchPredictorTables::UpdateRowsForUrl, | |
643 tables_, | |
644 main_frame_url, | |
645 rows)); | |
646 } | |
647 | |
648 void ResourcePrefetchPredictor::RemoveAnEntryFromUrlDB() { | |
649 if (url_table_cache_.empty()) | |
650 return; | |
651 | |
652 // TODO(shishir): Maybe use a heap to do this more efficiently. | |
653 base::Time oldest_time; | |
654 GURL url_to_erase; | |
655 for (UrlTableCacheMap::iterator it = url_table_cache_.begin(); | |
656 it != url_table_cache_.end(); ++it) { | |
657 if (url_to_erase.is_empty() || it->second.last_visit_ < oldest_time) { | |
658 url_to_erase = it->first; | |
659 oldest_time = it->second.last_visit_; | |
660 } | |
661 } | |
662 url_table_cache_.erase(url_to_erase); | |
663 | |
664 std::vector<GURL> urls_to_delete(1, url_to_erase); | |
665 BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, | |
666 base::Bind(&ResourcePrefetchPredictorTables::DeleteUrlRows, | |
667 tables_, | |
668 urls_to_delete)); | |
669 } | |
670 | |
671 void ResourcePrefetchPredictor::MaybeReportAccuracyStats( | |
672 const NavigationID& navigation_id) { | |
673 const GURL& main_frame_url = navigation_id.main_frame_url_; | |
674 DCHECK(inflight_navigations_.find(navigation_id) != | |
675 inflight_navigations_.end()); | |
676 | |
677 bool have_predictions_for_url = | |
678 url_table_cache_.find(main_frame_url) != url_table_cache_.end(); | |
679 UMA_HISTOGRAM_BOOLEAN("ResourcePrefetchPredictor.HavePredictionsForUrl", | |
680 have_predictions_for_url); | |
681 if (!have_predictions_for_url) | |
682 return; | |
683 | |
684 const std::vector<URLRequestSummary>& actual = | |
685 inflight_navigations_[navigation_id]; | |
686 const UrlTableRowVector& predicted = url_table_cache_[main_frame_url].rows_; | |
687 | |
688 std::map<GURL, bool> actual_resources; | |
689 for (std::vector<URLRequestSummary>::const_iterator it = actual.begin(); | |
690 it != actual.end(); ++it) { | |
691 actual_resources[it->resource_url_] = it->was_cached_; | |
692 } | |
693 | |
694 int prefetch_cached = 0, prefetch_network = 0, prefetch_missed = 0; | |
695 int num_assumed_prefetched = std::min(static_cast<int>(predicted.size()), | |
696 kNumResourcesAssumedPrefetched); | |
697 for (int i = 0; i < num_assumed_prefetched; ++i) { | |
698 const UrlTableRow& row = predicted[i]; | |
699 if (actual_resources.find(row.resource_url_) == actual_resources.end()) { | |
700 ++prefetch_missed; | |
701 } else if (actual_resources[row.resource_url_]) { | |
702 ++prefetch_cached; | |
703 } else { | |
704 ++prefetch_network; | |
705 } | |
706 } | |
707 | |
708 UMA_HISTOGRAM_PERCENTAGE( | |
709 "ResourcePrefetchPredictor.PredictedPrefetchMisses", | |
710 prefetch_missed * 100.0 / num_assumed_prefetched); | |
711 UMA_HISTOGRAM_PERCENTAGE( | |
712 "ResourcePrefetchPredictor.PredictedPrefetchFromCache", | |
713 prefetch_cached * 100.0 / num_assumed_prefetched); | |
714 UMA_HISTOGRAM_PERCENTAGE( | |
715 "ResourcePrefetchPredictor.PredictedPrefetchFromNetwork", | |
716 prefetch_network * 100.0 / num_assumed_prefetched); | |
717 } | |
718 | |
719 } // namespace predictors | |
OLD | NEW |