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