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

Side by Side Diff: net/sdch/sdch_owner.cc

Issue 901303002: Make SDCH dictionaries persistent across browser restart. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fixes for bauerb Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "net/sdch/sdch_owner.h" 5 #include "net/sdch/sdch_owner.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/logging.h"
8 #include "base/metrics/histogram_macros.h" 9 #include "base/metrics/histogram_macros.h"
10 #include "base/prefs/persistent_pref_store.h"
11 #include "base/prefs/value_map_pref_store.h"
9 #include "base/time/default_clock.h" 12 #include "base/time/default_clock.h"
13 #include "base/values.h"
10 #include "net/base/sdch_manager.h" 14 #include "net/base/sdch_manager.h"
11 #include "net/base/sdch_net_log_params.h" 15 #include "net/base/sdch_net_log_params.h"
12 16
17 namespace net {
18
13 namespace { 19 namespace {
14 20
15 enum DictionaryFate { 21 enum DictionaryFate {
16 // A Get-Dictionary header wasn't acted on. 22 // A Get-Dictionary header wasn't acted on.
17 DICTIONARY_FATE_GET_IGNORED = 1, 23 DICTIONARY_FATE_GET_IGNORED = 1,
18 24
19 // A fetch was attempted, but failed. 25 // A fetch was attempted, but failed.
20 // TODO(rdsmith): Actually record this case. 26 // TODO(rdsmith): Actually record this case.
21 DICTIONARY_FATE_FETCH_FAILED = 2, 27 DICTIONARY_FATE_FETCH_FAILED = 2,
22 28
23 // A successful fetch was dropped on the floor, no space. 29 // A successful fetch was dropped on the floor, no space.
24 DICTIONARY_FATE_FETCH_IGNORED_NO_SPACE = 3, 30 DICTIONARY_FATE_FETCH_IGNORED_NO_SPACE = 3,
25 31
26 // A successful fetch was refused by the SdchManager. 32 // A successful fetch was refused by the SdchManager.
27 DICTIONARY_FATE_FETCH_MANAGER_REFUSED = 4, 33 DICTIONARY_FATE_FETCH_MANAGER_REFUSED = 4,
28 34
29 // A dictionary was successfully added. 35 // A dictionary was successfully added based on
30 DICTIONARY_FATE_ADDED = 5, 36 // a Get-Dictionary header in a response.
37 DICTIONARY_FATE_ADD_RESPONSE_TRIGGERED = 5,
31 38
32 // A dictionary was evicted by an incoming dict. 39 // A dictionary was evicted by an incoming dict.
33 DICTIONARY_FATE_EVICT_FOR_DICT = 6, 40 DICTIONARY_FATE_EVICT_FOR_DICT = 6,
34 41
35 // A dictionary was evicted by memory pressure. 42 // A dictionary was evicted by memory pressure.
36 DICTIONARY_FATE_EVICT_FOR_MEMORY = 7, 43 DICTIONARY_FATE_EVICT_FOR_MEMORY = 7,
37 44
38 // A dictionary was evicted on destruction. 45 // A dictionary was evicted on destruction.
39 DICTIONARY_FATE_EVICT_FOR_DESTRUCTION = 8, 46 DICTIONARY_FATE_EVICT_FOR_DESTRUCTION = 8,
40 47
41 DICTIONARY_FATE_MAX = 9 48 // A dictionary was successfully added based on
49 // persistence from a previous browser revision.
50 DICTIONARY_FATE_ADD_PERSISTENCE_TRIGGERED = 9,
51
52 DICTIONARY_FATE_MAX = 10
42 }; 53 };
43 54
55 enum PersistenceFailureReason {
56 // File didn't exist; is being created.
57 PERSISTENCE_FAILURE_REASON_NO_FILE = 1,
58
59 // Error reading in information, but should be able to write.
60 PERSISTENCE_FAILURE_REASON_READ_FAILED = 2,
61
62 // Error leading to abort on attempted persistence.
63 PERSISTENCE_FAILURE_REASON_WRITE_FAILED = 3,
64
65 PERSISTENCE_FAILURE_REASON_MAX = 4
66 };
67
68 // Dictionaries that haven't been touched in 24 hours may be evicted
69 // to make room for new dictionaries.
70 const int kFreshnessLifetimeHours = 24;
71
72 // Dictionaries that have never been used only stay fresh for one hour.
73 const int kNeverUsedFreshnessLifetimeHours = 1;
74
44 void RecordDictionaryFate(enum DictionaryFate fate) { 75 void RecordDictionaryFate(enum DictionaryFate fate) {
45 UMA_HISTOGRAM_ENUMERATION("Sdch3.DictionaryFate", fate, DICTIONARY_FATE_MAX); 76 UMA_HISTOGRAM_ENUMERATION("Sdch3.DictionaryFate", fate, DICTIONARY_FATE_MAX);
46 } 77 }
47 78
79 void RecordPersistenceFailure(PersistenceFailureReason failure_reason) {
80 UMA_HISTOGRAM_ENUMERATION("Sdch3.PersistenceFailureReason", failure_reason,
81 PERSISTENCE_FAILURE_REASON_MAX);
82 }
83
48 void RecordDictionaryEviction(int use_count, DictionaryFate fate) { 84 void RecordDictionaryEviction(int use_count, DictionaryFate fate) {
49 DCHECK(fate == DICTIONARY_FATE_EVICT_FOR_DICT || 85 DCHECK(fate == DICTIONARY_FATE_EVICT_FOR_DICT ||
50 fate == DICTIONARY_FATE_EVICT_FOR_MEMORY || 86 fate == DICTIONARY_FATE_EVICT_FOR_MEMORY ||
51 fate == DICTIONARY_FATE_EVICT_FOR_DESTRUCTION); 87 fate == DICTIONARY_FATE_EVICT_FOR_DESTRUCTION);
52 88
53 UMA_HISTOGRAM_COUNTS_100("Sdch3.DictionaryUseCount", use_count); 89 UMA_HISTOGRAM_COUNTS_100("Sdch3.DictionaryUseCount", use_count);
54 RecordDictionaryFate(fate); 90 RecordDictionaryFate(fate);
55 } 91 }
56 92
93 // Schema specifications and access routines.
94
95 // The persistent prefs store is conceptually shared with any other network
96 // stack systems that want to persist data over browser restarts, and so
97 // use of it must be namespace restricted.
98 // Schema:
99 // pref_store_->GetValue(kPreferenceName) -> Dictionary {
100 // 'version' -> 1 [int]
101 // 'dictionaries' -> Dictionary {
102 // server_hash -> {
103 // 'url' -> URL [string]
104 // 'last_used' -> seconds since unix epoch [double]
105 // 'use_count' -> use count [int]
106 // 'size' -> size [int]
107 // }
108 // }
109 const char kPreferenceName[] = "SDCH";
110 const char kVersionKey[] = "version";
111 const char kDictionariesKey[] = "dictionaries";
112 const char kDictionaryUrlKey[] = "url";
113 const char kDictionaryLastUsedKey[] = "last_used";
114 const char kDictionaryUseCountKey[] = "use_count";
115 const char kDictionarySizeKey[] = "size";
116
117 const int kVersion = 1;
118
119 // This function returns store[kPreferenceName/kDictionariesKey]. The caller
120 // is responsible for making sure any needed calls to
121 // |store->ReportValueChanged()| occur.
122 base::DictionaryValue* GetPersistentStoreDictionaryMap(
123 WriteablePrefStore* store) {
124 base::Value* result = nullptr;
125 bool success = store->GetMutableValue(kPreferenceName, &result);
126 DCHECK(success);
127
128 base::DictionaryValue* preference_dictionary = nullptr;
129 success = result->GetAsDictionary(&preference_dictionary);
130 DCHECK(success);
131 DCHECK(preference_dictionary);
132
133 base::DictionaryValue* dictionary_list_dictionary = nullptr;
134 success = preference_dictionary->GetDictionary(kDictionariesKey,
135 &dictionary_list_dictionary);
136 DCHECK(success);
137 DCHECK(dictionary_list_dictionary);
138
139 return dictionary_list_dictionary;
140 }
141
142 // This function initializes a pref store with an empty version of the
143 // above schema, removing anything previously in the store under
144 // kPreferenceName.
145 void InitializePersistentStore(WriteablePrefStore* store) {
146 base::DictionaryValue* empty_store(new base::DictionaryValue);
147 empty_store->SetInteger(kVersionKey, kVersion);
148 empty_store->Set(kDictionariesKey,
149 make_scoped_ptr(new base::DictionaryValue));
150 store->SetValue(kPreferenceName, empty_store);
151 }
152
153 // A class to allow iteration over all dictionaries in the pref store, and
154 // easy lookup of the information associated with those dictionaries.
155 // Note that this is an "Iterator" in the same sense (and for the same
156 // reasons) that base::Dictionary::Iterator is an iterator--it allows
157 // iterating over all the dictionaries in the preference store, but it
158 // does not allow use as an STL iterator because the container it
159 // is iterating over does not export begin()/end() methods.
160 class DictionaryPreferenceIterator {
161 public:
162 explicit DictionaryPreferenceIterator(WriteablePrefStore* pref_store);
163
164 bool IsAtEnd() const { return dictionary_iterator_.IsAtEnd(); }
mmenke 2015/02/06 22:29:41 Seems weird to inline this, but not the other meth
Elly Fong-Jones 2015/02/11 21:23:51 Done.
165 void Advance();
166
167 const std::string& server_hash() const { return server_hash_; }
168 GURL url() const { return url_; }
mmenke 2015/02/06 22:29:41 const GURL&
Elly Fong-Jones 2015/02/11 21:23:51 Done.
169 base::Time last_used() const { return last_used_; }
170 int use_count() const { return use_count_; }
171 int size() const { return size_; }
172
173 private:
174 void LoadDictionaryOrDie();
175
176 std::string server_hash_;
177 GURL url_;
178 base::Time last_used_;
179 int use_count_;
180 int size_;
181
182 base::DictionaryValue::Iterator dictionary_iterator_;
183 };
184
185 DictionaryPreferenceIterator::DictionaryPreferenceIterator(
186 WriteablePrefStore* pref_store)
187 : dictionary_iterator_(*GetPersistentStoreDictionaryMap(pref_store)) {
188 if (!IsAtEnd())
189 LoadDictionaryOrDie();
190 }
191
192 void DictionaryPreferenceIterator::Advance() {
193 dictionary_iterator_.Advance();
194 if (!IsAtEnd())
195 LoadDictionaryOrDie();
196 }
197
198 void DictionaryPreferenceIterator::LoadDictionaryOrDie() {
199 double last_used_seconds_from_epoch;
200 const base::DictionaryValue* dict = nullptr;
201 bool success =
202 dictionary_iterator_.value().GetAsDictionary(&dict);
203 DCHECK(success);
204
205 server_hash_ = dictionary_iterator_.key();
206
207 std::string url_spec;
208 success = dict->GetString(kDictionaryUrlKey, &url_spec);
209 DCHECK(success);
210 url_ = GURL(url_spec);
211
212 success = dict->GetDouble(kDictionaryLastUsedKey,
213 &last_used_seconds_from_epoch);
Bernhard Bauer 2015/02/06 20:12:18 This seems to be aligned weirdly.
Elly Fong-Jones 2015/02/11 21:23:51 Done.
214 DCHECK(success);
215 last_used_ = base::Time::FromDoubleT(last_used_seconds_from_epoch);
216
217 success = dict->GetInteger(kDictionaryUseCountKey, &use_count_);
218 DCHECK(success);
219
220 success = dict->GetInteger(kDictionarySizeKey, &size_);
221 DCHECK(success);
222 }
223
224 // Triggers a ReportValueChanged() on the specified WriteablePrefStore
225 // when the object goes out of scope.
226 class ScopedPrefNotifier {
227 public:
228 // Caller must guarantee lifetime of |*pref_store| exceeds the
229 // lifetime of this object.
230 ScopedPrefNotifier(WriteablePrefStore* pref_store)
231 : pref_store_(pref_store) {}
232 ~ScopedPrefNotifier() { pref_store_->ReportValueChanged(kPreferenceName); }
233
234 private:
235 WriteablePrefStore* pref_store_;
236
237 DISALLOW_COPY_AND_ASSIGN(ScopedPrefNotifier);
238 };
239
57 } // namespace 240 } // namespace
58 241
59 namespace net {
60
61 // Adjust SDCH limits downwards for mobile. 242 // Adjust SDCH limits downwards for mobile.
62 #if defined(OS_ANDROID) || defined(OS_IOS) 243 #if defined(OS_ANDROID) || defined(OS_IOS)
63 // static 244 // static
64 const size_t SdchOwner::kMaxTotalDictionarySize = 1000 * 1000; 245 const size_t SdchOwner::kMaxTotalDictionarySize = 1000 * 1000;
65 #else 246 #else
66 // static 247 // static
67 const size_t SdchOwner::kMaxTotalDictionarySize = 20 * 1000 * 1000; 248 const size_t SdchOwner::kMaxTotalDictionarySize = 20 * 1000 * 1000;
68 #endif 249 #endif
69 250
70 // Somewhat arbitrary, but we assume a dictionary smaller than 251 // Somewhat arbitrary, but we assume a dictionary smaller than
71 // 50K isn't going to do anyone any good. Note that this still doesn't 252 // 50K isn't going to do anyone any good. Note that this still doesn't
72 // prevent download and addition unless there is less than this 253 // prevent download and addition unless there is less than this
73 // amount of space available in storage. 254 // amount of space available in storage.
74 const size_t SdchOwner::kMinSpaceForDictionaryFetch = 50 * 1000; 255 const size_t SdchOwner::kMinSpaceForDictionaryFetch = 50 * 1000;
75 256
76 SdchOwner::SdchOwner(net::SdchManager* sdch_manager, 257 SdchOwner::SdchOwner(net::SdchManager* sdch_manager,
77 net::URLRequestContext* context) 258 net::URLRequestContext* context)
mmenke 2015/02/06 22:29:41 While you're here, these net::'s aren't needed.
Elly Fong-Jones 2015/02/11 21:23:51 Done.
78 : manager_(sdch_manager), 259 : manager_(sdch_manager),
79 fetcher_(context, 260 fetcher_(context),
80 base::Bind(&SdchOwner::OnDictionaryFetched,
81 // Because |fetcher_| is owned by SdchOwner, the
82 // SdchOwner object will be available for the lifetime
83 // of |fetcher_|.
84 base::Unretained(this))),
85 total_dictionary_bytes_(0), 261 total_dictionary_bytes_(0),
86 clock_(new base::DefaultClock), 262 clock_(new base::DefaultClock),
87 max_total_dictionary_size_(kMaxTotalDictionarySize), 263 max_total_dictionary_size_(kMaxTotalDictionarySize),
88 min_space_for_dictionary_fetch_(kMinSpaceForDictionaryFetch), 264 min_space_for_dictionary_fetch_(kMinSpaceForDictionaryFetch),
265 in_memory_pref_store_(new ValueMapPrefStore()),
266 external_pref_store_(nullptr),
267 pref_store_(in_memory_pref_store_.get()),
89 memory_pressure_listener_( 268 memory_pressure_listener_(
90 base::Bind(&SdchOwner::OnMemoryPressure, 269 base::Bind(&SdchOwner::OnMemoryPressure,
91 // Because |memory_pressure_listener_| is owned by 270 // Because |memory_pressure_listener_| is owned by
92 // SdchOwner, the SdchOwner object will be available 271 // SdchOwner, the SdchOwner object will be available
93 // for the lifetime of |memory_pressure_listener_|. 272 // for the lifetime of |memory_pressure_listener_|.
94 base::Unretained(this))) { 273 base::Unretained(this))) {
95 manager_->AddObserver(this); 274 manager_->AddObserver(this);
275 InitializePersistentStore(pref_store_);
mmenke 2015/02/06 22:29:42 "EnablePersistentStorage" is used to mean the on-d
Elly Fong-Jones 2015/02/11 21:23:51 Done.
96 } 276 }
97 277
98 SdchOwner::~SdchOwner() { 278 SdchOwner::~SdchOwner() {
99 for (auto it = local_dictionary_info_.begin(); 279 for (DictionaryPreferenceIterator it(pref_store_); !it.IsAtEnd();
100 it != local_dictionary_info_.end(); ++it) { 280 it.Advance()) {
101 RecordDictionaryEviction(it->second.use_count, 281 RecordDictionaryEviction(it.use_count(),
102 DICTIONARY_FATE_EVICT_FOR_DESTRUCTION); 282 DICTIONARY_FATE_EVICT_FOR_DESTRUCTION);
mmenke 2015/02/06 22:29:41 Hrm...Not sure "evict" is still accurate here, at
Elly Fong-Jones 2015/02/11 21:23:51 Done.
103 } 283 }
104 manager_->RemoveObserver(this); 284 manager_->RemoveObserver(this);
285
286 // This object only observes the external store during loading,
287 // i.e. before it's made the default preferences store.
288 if (external_pref_store_)
289 external_pref_store_->RemoveObserver(this);
290 }
291
292 void SdchOwner::EnablePersistentStorage(PersistentPrefStore* pref_store) {
293 DCHECK(!external_pref_store_);
294 external_pref_store_ = pref_store;
295 external_pref_store_->AddObserver(this);
296
297 if (external_pref_store_->IsInitializationComplete())
298 OnInitializationCompleted(true);
105 } 299 }
106 300
107 void SdchOwner::SetMaxTotalDictionarySize(size_t max_total_dictionary_size) { 301 void SdchOwner::SetMaxTotalDictionarySize(size_t max_total_dictionary_size) {
108 max_total_dictionary_size_ = max_total_dictionary_size; 302 max_total_dictionary_size_ = max_total_dictionary_size;
109 } 303 }
110 304
111 void SdchOwner::SetMinSpaceForDictionaryFetch( 305 void SdchOwner::SetMinSpaceForDictionaryFetch(
112 size_t min_space_for_dictionary_fetch) { 306 size_t min_space_for_dictionary_fetch) {
113 min_space_for_dictionary_fetch_ = min_space_for_dictionary_fetch; 307 min_space_for_dictionary_fetch_ = min_space_for_dictionary_fetch;
114 } 308 }
115 309
116 void SdchOwner::OnDictionaryFetched(const std::string& dictionary_text, 310 void SdchOwner::OnDictionaryFetched(base::Time last_used,
311 int use_count,
312 const std::string& dictionary_text,
117 const GURL& dictionary_url, 313 const GURL& dictionary_url,
118 const net::BoundNetLog& net_log) { 314 const net::BoundNetLog& net_log) {
119 struct DictionaryItem { 315 struct DictionaryItem {
120 base::Time last_used; 316 base::Time last_used;
121 std::string server_hash; 317 std::string server_hash;
122 int use_count; 318 int use_count;
123 size_t dictionary_size; 319 size_t dictionary_size;
124 320
125 DictionaryItem() : use_count(0), dictionary_size(0) {} 321 DictionaryItem() : use_count(0), dictionary_size(0) {}
126 DictionaryItem(const base::Time& last_used, 322 DictionaryItem(const base::Time& last_used,
127 const std::string& server_hash, 323 const std::string& server_hash,
128 int use_count, 324 int use_count,
129 size_t dictionary_size) 325 size_t dictionary_size)
130 : last_used(last_used), 326 : last_used(last_used),
131 server_hash(server_hash), 327 server_hash(server_hash),
132 use_count(use_count), 328 use_count(use_count),
133 dictionary_size(dictionary_size) {} 329 dictionary_size(dictionary_size) {}
134 DictionaryItem(const DictionaryItem& rhs) = default; 330 DictionaryItem(const DictionaryItem& rhs) = default;
135 DictionaryItem& operator=(const DictionaryItem& rhs) = default; 331 DictionaryItem& operator=(const DictionaryItem& rhs) = default;
136 bool operator<(const DictionaryItem& rhs) const { 332 bool operator<(const DictionaryItem& rhs) const {
137 return last_used < rhs.last_used; 333 return last_used < rhs.last_used;
138 } 334 }
139 }; 335 };
140 336
337 // Figure out if there is space for the incoming dictionary; evict
338 // stale dictionaries if needed to make space.
339
141 std::vector<DictionaryItem> stale_dictionary_list; 340 std::vector<DictionaryItem> stale_dictionary_list;
142 size_t recoverable_bytes = 0; 341 size_t recoverable_bytes = 0;
143 base::Time stale_boundary(clock_->Now() - base::TimeDelta::FromDays(1)); 342 base::Time now(clock_->Now());
144 for (auto used_it = local_dictionary_info_.begin(); 343 base::Time stale_boundary(
145 used_it != local_dictionary_info_.end(); ++used_it) { 344 now - base::TimeDelta::FromHours(kFreshnessLifetimeHours));
146 if (used_it->second.last_used < stale_boundary) { 345 base::Time never_used_stale_boundary(
mmenke 2015/02/06 22:29:42 Think these two "boundary" times are worth a short
Elly Fong-Jones 2015/02/11 21:23:51 Done.
147 stale_dictionary_list.push_back( 346 now - base::TimeDelta::FromHours(kNeverUsedFreshnessLifetimeHours));
148 DictionaryItem(used_it->second.last_used, used_it->first, 347 for (DictionaryPreferenceIterator it(pref_store_); !it.IsAtEnd();
149 used_it->second.use_count, used_it->second.size)); 348 it.Advance()) {
150 recoverable_bytes += used_it->second.size; 349 if (it.last_used() < stale_boundary ||
350 (it.use_count() == 0 && it.last_used() < never_used_stale_boundary)) {
351 stale_dictionary_list.push_back(DictionaryItem(
352 it.last_used(), it.server_hash(), it.use_count(), it.size()));
353 recoverable_bytes += it.size();
151 } 354 }
152 } 355 }
mmenke 2015/02/06 22:29:42 Probably a bit beyond the scope of this cl, but sh
Elly Fong-Jones 2015/02/11 21:23:51 It does, but I think n is small. I am going to not
153 356
154 if (total_dictionary_bytes_ + dictionary_text.size() - recoverable_bytes > 357 if (total_dictionary_bytes_ + dictionary_text.size() - recoverable_bytes >
155 max_total_dictionary_size_) { 358 max_total_dictionary_size_) {
156 RecordDictionaryFate(DICTIONARY_FATE_FETCH_IGNORED_NO_SPACE); 359 RecordDictionaryFate(DICTIONARY_FATE_FETCH_IGNORED_NO_SPACE);
157 net::SdchManager::SdchErrorRecovery(SDCH_DICTIONARY_NO_ROOM); 360 net::SdchManager::SdchErrorRecovery(SDCH_DICTIONARY_NO_ROOM);
158 net_log.AddEvent(net::NetLog::TYPE_SDCH_DICTIONARY_ERROR, 361 net_log.AddEvent(net::NetLog::TYPE_SDCH_DICTIONARY_ERROR,
159 base::Bind(&net::NetLogSdchDictionaryFetchProblemCallback, 362 base::Bind(&net::NetLogSdchDictionaryFetchProblemCallback,
160 SDCH_DICTIONARY_NO_ROOM, dictionary_url, true)); 363 SDCH_DICTIONARY_NO_ROOM, dictionary_url, true));
161 return; 364 return;
162 } 365 }
163 366
164 // Evict from oldest to youngest until we have space. 367 // Add the new dictionary. This is done before removing the stale
165 std::sort(stale_dictionary_list.begin(), stale_dictionary_list.end()); 368 // dictionaries so that no state change will occur if dictionary addition
166 size_t avail_bytes = max_total_dictionary_size_ - total_dictionary_bytes_; 369 // fails.
167 auto stale_it = stale_dictionary_list.begin();
168 while (avail_bytes < dictionary_text.size() &&
169 stale_it != stale_dictionary_list.end()) {
170 manager_->RemoveSdchDictionary(stale_it->server_hash);
171 RecordDictionaryEviction(stale_it->use_count,
172 DICTIONARY_FATE_EVICT_FOR_DICT);
173 local_dictionary_info_.erase(stale_it->server_hash);
174 avail_bytes += stale_it->dictionary_size;
175 ++stale_it;
176 }
177 DCHECK(avail_bytes >= dictionary_text.size());
178
179 std::string server_hash; 370 std::string server_hash;
180 net::SdchProblemCode rv = manager_->AddSdchDictionary( 371 net::SdchProblemCode rv = manager_->AddSdchDictionary(
181 dictionary_text, dictionary_url, &server_hash); 372 dictionary_text, dictionary_url, &server_hash);
182 if (rv != net::SDCH_OK) { 373 if (rv != net::SDCH_OK) {
183 RecordDictionaryFate(DICTIONARY_FATE_FETCH_MANAGER_REFUSED); 374 RecordDictionaryFate(DICTIONARY_FATE_FETCH_MANAGER_REFUSED);
184 net::SdchManager::SdchErrorRecovery(rv); 375 net::SdchManager::SdchErrorRecovery(rv);
185 net_log.AddEvent(net::NetLog::TYPE_SDCH_DICTIONARY_ERROR, 376 net_log.AddEvent(net::NetLog::TYPE_SDCH_DICTIONARY_ERROR,
186 base::Bind(&net::NetLogSdchDictionaryFetchProblemCallback, 377 base::Bind(&net::NetLogSdchDictionaryFetchProblemCallback,
187 rv, dictionary_url, true)); 378 rv, dictionary_url, true));
188 return; 379 return;
189 } 380 }
190 381
191 RecordDictionaryFate(DICTIONARY_FATE_ADDED); 382 base::DictionaryValue* pref_dictionary_map =
383 GetPersistentStoreDictionaryMap(pref_store_);
384 ScopedPrefNotifier scoped_pref_notifier(pref_store_);
192 385
193 DCHECK(local_dictionary_info_.end() == 386 // Remove the old dictionaries.
194 local_dictionary_info_.find(server_hash)); 387 std::sort(stale_dictionary_list.begin(), stale_dictionary_list.end());
388 size_t avail_bytes = max_total_dictionary_size_ - total_dictionary_bytes_;
389 auto stale_it = stale_dictionary_list.begin();
390 while (avail_bytes < dictionary_text.size() &&
391 stale_it != stale_dictionary_list.end()) {
392 manager_->RemoveSdchDictionary(stale_it->server_hash);
393
394 DCHECK(pref_dictionary_map->HasKey(stale_it->server_hash));
395 bool success = pref_dictionary_map->RemoveWithoutPathExpansion(
396 stale_it->server_hash, nullptr);
397 DCHECK(success);
398
399 avail_bytes += stale_it->dictionary_size;
400
401 RecordDictionaryEviction(stale_it->use_count,
402 DICTIONARY_FATE_EVICT_FOR_DICT);
403
404 ++stale_it;
405 }
406 DCHECK_GE(avail_bytes, dictionary_text.size());
407
408 RecordDictionaryFate(
409 // Distinguish between loads triggered by network responses and
410 // loads triggered by persistence.
411 last_used.is_null() ? DICTIONARY_FATE_ADD_RESPONSE_TRIGGERED
412 : DICTIONARY_FATE_ADD_PERSISTENCE_TRIGGERED);
413
414 // If a dictionary has never been used, its dictionary addition time
415 // is recorded as its last used time. Never used dictionaries are treated
416 // specially in the freshness logic.
417 if (last_used.is_null())
418 last_used = clock_->Now();
419
195 total_dictionary_bytes_ += dictionary_text.size(); 420 total_dictionary_bytes_ += dictionary_text.size();
196 local_dictionary_info_[server_hash] = DictionaryInfo( 421
197 // Set the time last used to something to avoid thrashing, but not recent, 422 // Record the addition in the pref store.
198 // to avoid taking too much time/space with useless dictionaries/one-off 423 scoped_ptr<base::DictionaryValue> dictionary_description(
199 // visits to web sites. 424 new base::DictionaryValue());
200 clock_->Now() - base::TimeDelta::FromHours(23), dictionary_text.size()); 425 dictionary_description->SetString(kDictionaryUrlKey, dictionary_url.spec());
426 dictionary_description->SetDouble(kDictionaryLastUsedKey,
427 last_used.ToDoubleT());
428 dictionary_description->SetInteger(kDictionaryUseCountKey, use_count);
429 dictionary_description->SetInteger(kDictionarySizeKey,
430 dictionary_text.size());
431 pref_dictionary_map->Set(server_hash, dictionary_description.Pass());
201 } 432 }
202 433
203 void SdchOwner::OnDictionaryUsed(SdchManager* manager, 434 void SdchOwner::OnDictionaryUsed(SdchManager* manager,
204 const std::string& server_hash) { 435 const std::string& server_hash) {
205 auto it = local_dictionary_info_.find(server_hash); 436 base::Time now(clock_->Now());
206 DCHECK(local_dictionary_info_.end() != it); 437 base::DictionaryValue* pref_dictionary_map =
438 GetPersistentStoreDictionaryMap(pref_store_);
439 ScopedPrefNotifier scoped_pref_notifier(pref_store_);
207 440
208 it->second.last_used = clock_->Now(); 441 base::Value* value = nullptr;
209 it->second.use_count++; 442 bool success = pref_dictionary_map->Get(server_hash, &value);
443 // TODO(rdsmith): Is the behavior of the SdchManager certain enough for
444 // the following DCHECKs?
mmenke 2015/02/06 22:29:41 This TODOs seem rather concerned. If they're not,
Elly Fong-Jones 2015/02/11 21:23:51 I admit that I have no idea what this TODO is refe
Randy Smith (Not in Mondays) 2015/02/16 01:10:04 +1. This was in the way of a note to myself to ju
445 DCHECK(success);
446 base::DictionaryValue* specific_dictionary_map = nullptr;
447 success = value->GetAsDictionary(&specific_dictionary_map);
448 DCHECK(success);
449
450 double last_used_time = 0.0;
451 success = specific_dictionary_map->GetDouble(kDictionaryLastUsedKey,
452 &last_used_time);
mmenke 2015/02/06 22:29:42 nit: Should use consistent variable names here an
Elly Fong-Jones 2015/02/11 21:23:51 Done.
453 DCHECK(success);
454 int use_count = 0;
455 success =
456 specific_dictionary_map->GetInteger(kDictionaryUseCountKey, &use_count);
457 DCHECK(success);
458
459 base::TimeDelta time_since_last_used(now -
460 base::Time::FromDoubleT(last_used_time));
461
462 // TODO(rdsmith): Distinguish between "Never used" and "Actually not
463 // touched for 48 hours".
464 UMA_HISTOGRAM_CUSTOM_TIMES(
465 "Sdch3.UsageInterval",
466 use_count ? time_since_last_used : base::TimeDelta::FromHours(48),
467 base::TimeDelta(), base::TimeDelta::FromHours(48), 50);
468
469 specific_dictionary_map->SetDouble(kDictionaryLastUsedKey, now.ToDoubleT());
470 specific_dictionary_map->SetInteger(kDictionaryUseCountKey, use_count + 1);
210 } 471 }
211 472
212 void SdchOwner::OnGetDictionary(net::SdchManager* manager, 473 void SdchOwner::OnGetDictionary(net::SdchManager* manager,
213 const GURL& request_url, 474 const GURL& request_url,
214 const GURL& dictionary_url) { 475 const GURL& dictionary_url) {
215 base::Time stale_boundary(clock_->Now() - base::TimeDelta::FromDays(1)); 476 base::Time stale_boundary(clock_->Now() - base::TimeDelta::FromDays(1));
216 size_t avail_bytes = 0; 477 size_t avail_bytes = 0;
217 for (auto it = local_dictionary_info_.begin(); 478 for (DictionaryPreferenceIterator it(pref_store_); !it.IsAtEnd();
218 it != local_dictionary_info_.end(); ++it) { 479 it.Advance()) {
219 if (it->second.last_used < stale_boundary) 480 if (it.last_used() < stale_boundary)
220 avail_bytes += it->second.size; 481 avail_bytes += it.size();
221 } 482 }
222 483
223 // Don't initiate the fetch if we wouldn't be able to store any 484 // Don't initiate the fetch if we wouldn't be able to store any
224 // reasonable dictionary. 485 // reasonable dictionary.
225 // TODO(rdsmith): Maybe do a HEAD request to figure out how much 486 // TODO(rdsmith): Maybe do a HEAD request to figure out how much
226 // storage we'd actually need? 487 // storage we'd actually need?
227 if (max_total_dictionary_size_ < (total_dictionary_bytes_ - avail_bytes + 488 if (max_total_dictionary_size_ < (total_dictionary_bytes_ - avail_bytes +
228 min_space_for_dictionary_fetch_)) { 489 min_space_for_dictionary_fetch_)) {
229 RecordDictionaryFate(DICTIONARY_FATE_GET_IGNORED); 490 RecordDictionaryFate(DICTIONARY_FATE_GET_IGNORED);
230 // TODO(rdsmith): Log a net-internals error. This requires 491 // TODO(rdsmith): Log a net-internals error. This requires
231 // SdchManager to forward the URLRequest that detected the 492 // SdchManager to forward the URLRequest that detected the
232 // Get-Dictionary header to its observers, which is tricky 493 // Get-Dictionary header to its observers, which is tricky
233 // because SdchManager is layered underneath URLRequest. 494 // because SdchManager is layered underneath URLRequest.
234 return; 495 return;
235 } 496 }
236 497
237 fetcher_.Schedule(dictionary_url); 498 fetcher_.Schedule(dictionary_url,
499 base::Bind(&SdchOwner::OnDictionaryFetched,
500 // SdchOwner will outlive its member variables.
501 base::Unretained(this), base::Time(), 0));
238 } 502 }
239 503
240 void SdchOwner::OnClearDictionaries(net::SdchManager* manager) { 504 void SdchOwner::OnClearDictionaries(net::SdchManager* manager) {
241 total_dictionary_bytes_ = 0; 505 total_dictionary_bytes_ = 0;
242 local_dictionary_info_.clear();
243 fetcher_.Cancel(); 506 fetcher_.Cancel();
507
508 InitializePersistentStore(pref_store_);
509 }
510
511 void SdchOwner::OnPrefValueChanged(const std::string& key) {
512 }
513
514 void SdchOwner::OnInitializationCompleted(bool succeeded) {
515 // Errors on load are self-correcting; if dictionaries were not
516 // persisted from the last instance of the browser, they will be
517 // faulted in by user action over time. However, if a load error
518 // means that the dictionary information won't be able to be persisted,
519 // the in memory pref store is left in place.
520 switch (external_pref_store_->GetReadError()) {
521 case PersistentPrefStore::PREF_READ_ERROR_NONE:
522 if (succeeded)
523 break;
mmenke 2015/02/06 22:29:41 Wonder if we should record something here - otherw
Elly Fong-Jones 2015/02/11 21:23:51 They still tell us the relative frequency of the d
Randy Smith (Not in Mondays) 2015/02/16 01:10:04 +1, sorta to each point :-}. I think these histog
524
525 case PersistentPrefStore::PREF_READ_ERROR_NO_FILE:
526 // First time reading; the file will be created.
527 if (succeeded) {
528 RecordPersistenceFailure(PERSISTENCE_FAILURE_REASON_NO_FILE);
529 break;
530 }
531
532 case PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE:
533 case PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE:
534 case PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER:
535 case PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED:
536 case PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT:
537 case PersistentPrefStore::PREF_READ_ERROR_LEVELDB_IO:
538 case PersistentPrefStore::PREF_READ_ERROR_LEVELDB_CORRUPTION_READ_ONLY:
539 case PersistentPrefStore::PREF_READ_ERROR_LEVELDB_CORRUPTION:
540 // If the load was marked as succeeding (meaning the directory
541 // was present), even if the file wasn't read, it can be written.
542 if (succeeded) {
543 RecordPersistenceFailure(PERSISTENCE_FAILURE_REASON_READ_FAILED);
544 break;
545 }
mmenke 2015/02/06 22:29:41 optional: I'm not a big fan of fallthrough behavi
Elly Fong-Jones 2015/02/11 21:23:51 Done.
546
547 case PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED:
548 case PersistentPrefStore::PREF_READ_ERROR_FILE_NOT_SPECIFIED:
549 // Unrecoverable failure; we default to the internal pref store.
550 external_pref_store_->RemoveObserver(this);
551 external_pref_store_ = nullptr;
552 RecordPersistenceFailure(PERSISTENCE_FAILURE_REASON_WRITE_FAILED);
553 return;
554
555 case PersistentPrefStore::PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE:
556 case PersistentPrefStore::PREF_READ_ERROR_MAX_ENUM:
557 // Shouldn't ever happen.
558 NOTREACHED();
559 break;
560 }
561
562 // TODO(rdsmith): Implement versioning.
563
564 // Load in what was stored before chrome exited previously.
565 const base::Value* sdch_persistence_value = nullptr;
566 const base::DictionaryValue* sdch_persistence_dictionary = nullptr;
567
568 // The GetPersistentStore() routine above assumes data formatted
569 // according to the schema described at the top of this file. Since
570 // this data comes from disk, to avoid disk corruption resulting in
571 // persistent chrome errors this code avoids those assupmtions.
572 if (external_pref_store_->GetValue(kPreferenceName,
573 &sdch_persistence_value) &&
574 sdch_persistence_value->GetAsDictionary(&sdch_persistence_dictionary)) {
575 SchedulePersistedDictionaryLoads(*sdch_persistence_dictionary);
576 }
577
578 // Reset the persistent store and update it with the accumulated
579 // information from the local store.
580 InitializePersistentStore(external_pref_store_);
581
582 ScopedPrefNotifier scoped_pref_notifier(external_pref_store_);
583 GetPersistentStoreDictionaryMap(external_pref_store_)
584 ->Swap(GetPersistentStoreDictionaryMap(in_memory_pref_store_.get()));
585
586 // This object can stop waiting on (i.e. observing) the external preference
587 // store and switch over to using it as the primary preference store.
588 pref_store_ = external_pref_store_;
589 external_pref_store_->RemoveObserver(this);
mmenke 2015/02/06 22:29:42 Should we do this on failure, too? (And maybe nul
Elly Fong-Jones 2015/02/11 21:23:51 We do do this on the failure case, I think?
mmenke 2015/02/12 16:51:32 Oops...You're right, we are.
590 external_pref_store_ = nullptr;
591 in_memory_pref_store_ = nullptr;
244 } 592 }
245 593
246 void SdchOwner::SetClockForTesting(scoped_ptr<base::Clock> clock) { 594 void SdchOwner::SetClockForTesting(scoped_ptr<base::Clock> clock) {
247 clock_ = clock.Pass(); 595 clock_ = clock.Pass();
248 } 596 }
249 597
250 void SdchOwner::OnMemoryPressure( 598 void SdchOwner::OnMemoryPressure(
251 base::MemoryPressureListener::MemoryPressureLevel level) { 599 base::MemoryPressureListener::MemoryPressureLevel level) {
252 DCHECK_NE(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE, level); 600 DCHECK_NE(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE, level);
253 601
254 for (auto it = local_dictionary_info_.begin(); 602 for (DictionaryPreferenceIterator it(pref_store_); !it.IsAtEnd();
255 it != local_dictionary_info_.end(); ++it) { 603 it.Advance()) {
256 RecordDictionaryEviction(it->second.use_count, 604 RecordDictionaryEviction(it.use_count(), DICTIONARY_FATE_EVICT_FOR_MEMORY);
257 DICTIONARY_FATE_EVICT_FOR_MEMORY);
258 } 605 }
259 606
260 // TODO(rdsmith): Make a distinction between moderate and critical 607 // TODO(rdsmith): Make a distinction between moderate and critical
261 // memory pressure. 608 // memory pressure.
262 manager_->ClearData(); 609 manager_->ClearData();
263 } 610 }
264 611
612 bool SdchOwner::SchedulePersistedDictionaryLoads(
613 const base::DictionaryValue& persisted_info) {
614 // Any schema error will result in dropping the persisted info.
615 int version = 0;
616 if (!persisted_info.GetInteger(kVersionKey, &version))
617 return false;
618
619 // Any version mismatch will result in dropping the persisted info;
620 // it will be faulted in at small performance cost as URLs using
621 // dictionaries for encoding are visited.
622 if (version != kVersion)
623 return false;
624
625 const base::DictionaryValue* dictionary_set = nullptr;
626 if (!persisted_info.GetDictionary(kDictionariesKey, &dictionary_set))
627 return false;
628
629 // Any formatting error will result in skipping that particular
630 // dictionary.
631 for (base::DictionaryValue::Iterator dict_it(*dictionary_set);
632 !dict_it.IsAtEnd(); dict_it.Advance()) {
633 const base::DictionaryValue* dict_info = nullptr;
634 if (!dict_it.value().GetAsDictionary(&dict_info))
635 continue;
636
637 std::string url_string;
638 if (!dict_info->GetString(kDictionaryUrlKey, &url_string))
639 continue;
640 GURL dict_url(url_string);
641
642 double last_used;
643 if (!dict_info->GetDouble(kDictionaryLastUsedKey, &last_used))
644 continue;
645
646 int use_count;
647 if (!dict_info->GetInteger(kDictionaryUseCountKey, &use_count))
648 continue;
649
650 fetcher_.ScheduleReload(
651 dict_url, base::Bind(&SdchOwner::OnDictionaryFetched,
652 // SdchOwner will outlive its member variables.
653 base::Unretained(this),
654 base::Time::FromDoubleT(last_used), use_count));
655 }
656
657 return true;
658 }
659
265 } // namespace net 660 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698