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