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