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

Side by Side Diff: content/browser/dom_storage/dom_storage_area.cc

Issue 896643002: [DOMStorage] Rate limiting writes to disk. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: switched to UMA_HISTOGRAM_LONG_TIMES 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 2013 The Chromium Authors. All rights reserved. 1 // Copyright 2013 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 "content/browser/dom_storage/dom_storage_area.h" 5 #include "content/browser/dom_storage/dom_storage_area.h"
6 6
7 #include <algorithm>
8
7 #include "base/bind.h" 9 #include "base/bind.h"
8 #include "base/location.h" 10 #include "base/location.h"
9 #include "base/logging.h" 11 #include "base/logging.h"
10 #include "base/metrics/histogram.h" 12 #include "base/metrics/histogram.h"
11 #include "base/strings/utf_string_conversions.h" 13 #include "base/strings/utf_string_conversions.h"
14 #include "base/sys_info.h"
12 #include "base/time/time.h" 15 #include "base/time/time.h"
13 #include "content/browser/dom_storage/dom_storage_namespace.h" 16 #include "content/browser/dom_storage/dom_storage_namespace.h"
14 #include "content/browser/dom_storage/dom_storage_task_runner.h" 17 #include "content/browser/dom_storage/dom_storage_task_runner.h"
15 #include "content/browser/dom_storage/local_storage_database_adapter.h" 18 #include "content/browser/dom_storage/local_storage_database_adapter.h"
16 #include "content/browser/dom_storage/session_storage_database.h" 19 #include "content/browser/dom_storage/session_storage_database.h"
17 #include "content/browser/dom_storage/session_storage_database_adapter.h" 20 #include "content/browser/dom_storage/session_storage_database_adapter.h"
18 #include "content/common/dom_storage/dom_storage_map.h" 21 #include "content/common/dom_storage/dom_storage_map.h"
19 #include "content/common/dom_storage/dom_storage_types.h" 22 #include "content/common/dom_storage/dom_storage_types.h"
20 #include "storage/browser/database/database_util.h" 23 #include "storage/browser/database/database_util.h"
21 #include "storage/common/database/database_identifier.h" 24 #include "storage/common/database/database_identifier.h"
22 #include "storage/common/fileapi/file_system_util.h" 25 #include "storage/common/fileapi/file_system_util.h"
23 26
24 using storage::DatabaseUtil; 27 using storage::DatabaseUtil;
25 28
26 namespace content { 29 namespace content {
27 30
28 static const int kCommitTimerSeconds = 1; 31 // Delay for a moment after a value is set in anticipation
32 // of other values being set, so changes are batched.
33 static const int kCommitDefaultDelay = 5;
cmumford 2015/02/11 22:52:27 What is best practice regarding units? Like kCommi
michaeln 2015/02/11 23:30:27 yup, done
29 34
30 DOMStorageArea::CommitBatch::CommitBatch() 35 // The delay used if a commit is scheduled during startup, also the
31 : clear_all_first(false) { 36 // process uptime duration used as a proxy for 'during startup'.
37 static const int kCommitDuringStartupDelay = 60;
38
39 // To avoid excessive IO we apply limits to the amount of data being written
40 // and the frequency of writes. The specific values used are somewhat arbitrary.
41 static const int kMaxDataPerDay = kPerStorageAreaQuota * 2;
cmumford 2015/02/11 22:52:27 kMaxBytesPerDay?
michaeln 2015/02/11 23:30:28 Done.
42 static const int kMaxCommitsPerHour = 6;
43
44 DOMStorageArea::RateLimiter::RateLimiter(size_t desired_rate,
45 base::TimeDelta time_quantum)
46 : rate_(desired_rate), samples_(0), time_quantum_(time_quantum) {
47 DCHECK_GT(desired_rate, 0ul);
48 }
49
50 void DOMStorageArea::RateLimiter::add_samples(size_t samples) {
51 samples_ += samples;
52 }
53
54 // Computes the total time needed to process the total samples seen
55 // at the desired rate.
56 base::TimeDelta DOMStorageArea::RateLimiter::ComputeTimeNeeded() const {
57 return base::TimeDelta::FromInternalValue((samples_ / rate_) *
58 time_quantum_.ToInternalValue());
59 }
60
61 // Given the elapsed time since the start of the rate limiting session,
62 // computes the delay needed to mimic having processed the total samples
63 // seen at the desired rate.
64 base::TimeDelta DOMStorageArea::RateLimiter::ComputeDelayNeeded(
65 const base::TimeDelta elapsed_time) const {
66 base::TimeDelta time_needed = ComputeTimeNeeded();
67 if (time_needed > elapsed_time)
68 return time_needed - elapsed_time;
69 return base::TimeDelta();
70 }
71
72 DOMStorageArea::CommitBatch::CommitBatch() : clear_all_first(false) {
32 } 73 }
33 DOMStorageArea::CommitBatch::~CommitBatch() {} 74 DOMStorageArea::CommitBatch::~CommitBatch() {}
34 75
76 size_t DOMStorageArea::CommitBatch::GetDataSize() const {
77 return DOMStorageMap::CountBytes(changed_values);
78 }
35 79
36 // static 80 // static
37 const base::FilePath::CharType DOMStorageArea::kDatabaseFileExtension[] = 81 const base::FilePath::CharType DOMStorageArea::kDatabaseFileExtension[] =
38 FILE_PATH_LITERAL(".localstorage"); 82 FILE_PATH_LITERAL(".localstorage");
39 83
40 // static 84 // static
41 base::FilePath DOMStorageArea::DatabaseFileNameFromOrigin(const GURL& origin) { 85 base::FilePath DOMStorageArea::DatabaseFileNameFromOrigin(const GURL& origin) {
42 std::string filename = storage::GetIdentifierFromOrigin(origin); 86 std::string filename = storage::GetIdentifierFromOrigin(origin);
43 // There is no base::FilePath.AppendExtension() method, so start with just the 87 // There is no base::FilePath.AppendExtension() method, so start with just the
44 // extension as the filename, and then InsertBeforeExtension the desired 88 // extension as the filename, and then InsertBeforeExtension the desired
45 // name. 89 // name.
46 return base::FilePath().Append(kDatabaseFileExtension). 90 return base::FilePath().Append(kDatabaseFileExtension).
47 InsertBeforeExtensionASCII(filename); 91 InsertBeforeExtensionASCII(filename);
48 } 92 }
49 93
50 // static 94 // static
51 GURL DOMStorageArea::OriginFromDatabaseFileName(const base::FilePath& name) { 95 GURL DOMStorageArea::OriginFromDatabaseFileName(const base::FilePath& name) {
52 DCHECK(name.MatchesExtension(kDatabaseFileExtension)); 96 DCHECK(name.MatchesExtension(kDatabaseFileExtension));
53 std::string origin_id = 97 std::string origin_id =
54 name.BaseName().RemoveExtension().MaybeAsASCII(); 98 name.BaseName().RemoveExtension().MaybeAsASCII();
55 return storage::GetOriginFromIdentifier(origin_id); 99 return storage::GetOriginFromIdentifier(origin_id);
56 } 100 }
57 101
58 DOMStorageArea::DOMStorageArea( 102 DOMStorageArea::DOMStorageArea(const GURL& origin,
59 const GURL& origin, const base::FilePath& directory, 103 const base::FilePath& directory,
60 DOMStorageTaskRunner* task_runner) 104 DOMStorageTaskRunner* task_runner)
61 : namespace_id_(kLocalStorageNamespaceId), origin_(origin), 105 : namespace_id_(kLocalStorageNamespaceId),
106 origin_(origin),
62 directory_(directory), 107 directory_(directory),
63 task_runner_(task_runner), 108 task_runner_(task_runner),
64 map_(new DOMStorageMap(kPerStorageAreaQuota + 109 map_(new DOMStorageMap(kPerStorageAreaQuota +
65 kPerStorageAreaOverQuotaAllowance)), 110 kPerStorageAreaOverQuotaAllowance)),
66 is_initial_import_done_(true), 111 is_initial_import_done_(true),
67 is_shutdown_(false), 112 is_shutdown_(false),
68 commit_batches_in_flight_(0) { 113 commit_batches_in_flight_(0),
114 start_time_(base::TimeTicks::Now()),
115 data_rate_limiter_(kMaxDataPerDay, base::TimeDelta::FromHours(24)),
116 commit_rate_limiter_(kMaxCommitsPerHour, base::TimeDelta::FromHours(1)) {
69 if (!directory.empty()) { 117 if (!directory.empty()) {
70 base::FilePath path = directory.Append(DatabaseFileNameFromOrigin(origin_)); 118 base::FilePath path = directory.Append(DatabaseFileNameFromOrigin(origin_));
71 backing_.reset(new LocalStorageDatabaseAdapter(path)); 119 backing_.reset(new LocalStorageDatabaseAdapter(path));
72 is_initial_import_done_ = false; 120 is_initial_import_done_ = false;
73 } 121 }
74 } 122 }
75 123
76 DOMStorageArea::DOMStorageArea( 124 DOMStorageArea::DOMStorageArea(int64 namespace_id,
77 int64 namespace_id, 125 const std::string& persistent_namespace_id,
78 const std::string& persistent_namespace_id, 126 const GURL& origin,
79 const GURL& origin, 127 SessionStorageDatabase* session_storage_backing,
80 SessionStorageDatabase* session_storage_backing, 128 DOMStorageTaskRunner* task_runner)
81 DOMStorageTaskRunner* task_runner)
82 : namespace_id_(namespace_id), 129 : namespace_id_(namespace_id),
83 persistent_namespace_id_(persistent_namespace_id), 130 persistent_namespace_id_(persistent_namespace_id),
84 origin_(origin), 131 origin_(origin),
85 task_runner_(task_runner), 132 task_runner_(task_runner),
86 map_(new DOMStorageMap(kPerStorageAreaQuota + 133 map_(new DOMStorageMap(kPerStorageAreaQuota +
87 kPerStorageAreaOverQuotaAllowance)), 134 kPerStorageAreaOverQuotaAllowance)),
88 session_storage_backing_(session_storage_backing), 135 session_storage_backing_(session_storage_backing),
89 is_initial_import_done_(true), 136 is_initial_import_done_(true),
90 is_shutdown_(false), 137 is_shutdown_(false),
91 commit_batches_in_flight_(0) { 138 commit_batches_in_flight_(0),
139 start_time_(base::TimeTicks::Now()),
140 data_rate_limiter_(kMaxDataPerDay, base::TimeDelta::FromHours(24)),
141 commit_rate_limiter_(kMaxCommitsPerHour, base::TimeDelta::FromHours(1)) {
92 DCHECK(namespace_id != kLocalStorageNamespaceId); 142 DCHECK(namespace_id != kLocalStorageNamespaceId);
93 if (session_storage_backing) { 143 if (session_storage_backing) {
94 backing_.reset(new SessionStorageDatabaseAdapter( 144 backing_.reset(new SessionStorageDatabaseAdapter(
95 session_storage_backing, persistent_namespace_id, origin)); 145 session_storage_backing, persistent_namespace_id, origin));
96 is_initial_import_done_ = false; 146 is_initial_import_done_ = false;
97 } 147 }
98 } 148 }
99 149
100 DOMStorageArea::~DOMStorageArea() { 150 DOMStorageArea::~DOMStorageArea() {
101 } 151 }
(...skipping 28 matching lines...) Expand all
130 180
131 bool DOMStorageArea::SetItem(const base::string16& key, 181 bool DOMStorageArea::SetItem(const base::string16& key,
132 const base::string16& value, 182 const base::string16& value,
133 base::NullableString16* old_value) { 183 base::NullableString16* old_value) {
134 if (is_shutdown_) 184 if (is_shutdown_)
135 return false; 185 return false;
136 InitialImportIfNeeded(); 186 InitialImportIfNeeded();
137 if (!map_->HasOneRef()) 187 if (!map_->HasOneRef())
138 map_ = map_->DeepCopy(); 188 map_ = map_->DeepCopy();
139 bool success = map_->SetItem(key, value, old_value); 189 bool success = map_->SetItem(key, value, old_value);
140 if (success && backing_) { 190 if (success && backing_ &&
191 (old_value->is_null() || old_value->string() != value)) {
141 CommitBatch* commit_batch = CreateCommitBatchIfNeeded(); 192 CommitBatch* commit_batch = CreateCommitBatchIfNeeded();
142 commit_batch->changed_values[key] = base::NullableString16(value, false); 193 commit_batch->changed_values[key] = base::NullableString16(value, false);
143 } 194 }
144 return success; 195 return success;
145 } 196 }
146 197
147 bool DOMStorageArea::RemoveItem(const base::string16& key, 198 bool DOMStorageArea::RemoveItem(const base::string16& key,
148 base::string16* old_value) { 199 base::string16* old_value) {
149 if (is_shutdown_) 200 if (is_shutdown_)
150 return false; 201 return false;
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
205 DCHECK_NE(kLocalStorageNamespaceId, destination_namespace_id); 256 DCHECK_NE(kLocalStorageNamespaceId, destination_namespace_id);
206 257
207 DOMStorageArea* copy = new DOMStorageArea( 258 DOMStorageArea* copy = new DOMStorageArea(
208 destination_namespace_id, destination_persistent_namespace_id, origin_, 259 destination_namespace_id, destination_persistent_namespace_id, origin_,
209 session_storage_backing_.get(), task_runner_.get()); 260 session_storage_backing_.get(), task_runner_.get());
210 copy->map_ = map_; 261 copy->map_ = map_;
211 copy->is_shutdown_ = is_shutdown_; 262 copy->is_shutdown_ = is_shutdown_;
212 copy->is_initial_import_done_ = true; 263 copy->is_initial_import_done_ = true;
213 264
214 // All the uncommitted changes to this area need to happen before the actual 265 // All the uncommitted changes to this area need to happen before the actual
215 // shallow copy is made (scheduled by the upper layer). Another OnCommitTimer 266 // shallow copy is made (scheduled by the upper layer sometime after return).
216 // call might be in the event queue at this point, but it's handled gracefully
217 // when it fires.
218 if (commit_batch_) 267 if (commit_batch_)
219 OnCommitTimer(); 268 ScheduleImmediateCommit();
220 return copy; 269 return copy;
221 } 270 }
222 271
223 bool DOMStorageArea::HasUncommittedChanges() const { 272 bool DOMStorageArea::HasUncommittedChanges() const {
224 DCHECK(!is_shutdown_);
225 return commit_batch_.get() || commit_batches_in_flight_; 273 return commit_batch_.get() || commit_batches_in_flight_;
226 } 274 }
227 275
276 void DOMStorageArea::ScheduleImmediateCommit() {
277 DCHECK(HasUncommittedChanges());
278 OnCommitTimer();
279 }
280
228 void DOMStorageArea::DeleteOrigin() { 281 void DOMStorageArea::DeleteOrigin() {
229 DCHECK(!is_shutdown_); 282 DCHECK(!is_shutdown_);
230 // This function shouldn't be called for sessionStorage. 283 // This function shouldn't be called for sessionStorage.
231 DCHECK(!session_storage_backing_.get()); 284 DCHECK(!session_storage_backing_.get());
232 if (HasUncommittedChanges()) { 285 if (HasUncommittedChanges()) {
233 // TODO(michaeln): This logically deletes the data immediately, 286 // TODO(michaeln): This logically deletes the data immediately,
234 // and in a matter of a second, deletes the rows from the backing 287 // and in a matter of a second, deletes the rows from the backing
235 // database file, but the file itself will linger until shutdown 288 // database file, but the file itself will linger until shutdown
236 // or purge time. Ideally, this should delete the file more 289 // or purge time. Ideally, this should delete the file more
237 // quickly. 290 // quickly.
(...skipping 82 matching lines...) Expand 10 before | Expand all | Expand 10 after
320 DOMStorageArea::CommitBatch* DOMStorageArea::CreateCommitBatchIfNeeded() { 373 DOMStorageArea::CommitBatch* DOMStorageArea::CreateCommitBatchIfNeeded() {
321 DCHECK(!is_shutdown_); 374 DCHECK(!is_shutdown_);
322 if (!commit_batch_) { 375 if (!commit_batch_) {
323 commit_batch_.reset(new CommitBatch()); 376 commit_batch_.reset(new CommitBatch());
324 377
325 // Start a timer to commit any changes that accrue in the batch, but only if 378 // Start a timer to commit any changes that accrue in the batch, but only if
326 // no commits are currently in flight. In that case the timer will be 379 // no commits are currently in flight. In that case the timer will be
327 // started after the commits have happened. 380 // started after the commits have happened.
328 if (!commit_batches_in_flight_) { 381 if (!commit_batches_in_flight_) {
329 task_runner_->PostDelayedTask( 382 task_runner_->PostDelayedTask(
330 FROM_HERE, 383 FROM_HERE, base::Bind(&DOMStorageArea::OnCommitTimer, this),
331 base::Bind(&DOMStorageArea::OnCommitTimer, this), 384 ComputeCommitDelay());
332 base::TimeDelta::FromSeconds(kCommitTimerSeconds));
333 } 385 }
334 } 386 }
335 return commit_batch_.get(); 387 return commit_batch_.get();
336 } 388 }
337 389
390 base::TimeDelta DOMStorageArea::ComputeCommitDelay() const {
391 base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time_;
392 base::TimeDelta delay;
393 if (base::SysInfo::Uptime() < kCommitDuringStartupDelay * 1000)
394 base::TimeDelta::FromSeconds(kCommitDuringStartupDelay);
cmumford 2015/02/11 22:52:27 Did you want to assign these values to delay?
michaeln 2015/02/11 23:30:28 that would be a huge improvement!
395 else
396 base::TimeDelta::FromSeconds(kCommitDefaultDelay);
397 delay = std::max(
398 delay,
399 std::max(commit_rate_limiter_.ComputeDelayNeeded(elapsed_time),
400 data_rate_limiter_.ComputeDelayNeeded(elapsed_time)));
401 UMA_HISTOGRAM_LONG_TIMES("LocalStorage.CommitDelay", delay);
402 return delay;
403 }
404
338 void DOMStorageArea::OnCommitTimer() { 405 void DOMStorageArea::OnCommitTimer() {
339 if (is_shutdown_) 406 if (is_shutdown_)
340 return; 407 return;
341 408
342 DCHECK(backing_.get()); 409 DCHECK(backing_.get());
343 410
344 // It's possible that there is nothing to commit, since a shallow copy occured 411 // It's possible that there is nothing to commit if an immediate
345 // before the timer fired. 412 // commit occured after the timer was scheduled but before it fired.
346 if (!commit_batch_) 413 if (!commit_batch_)
347 return; 414 return;
348 415
416 commit_rate_limiter_.add_samples(1);
417 data_rate_limiter_.add_samples(commit_batch_->GetDataSize());
418
349 // This method executes on the primary sequence, we schedule 419 // This method executes on the primary sequence, we schedule
350 // a task for immediate execution on the commit sequence. 420 // a task for immediate execution on the commit sequence.
351 DCHECK(task_runner_->IsRunningOnPrimarySequence()); 421 DCHECK(task_runner_->IsRunningOnPrimarySequence());
352 bool success = task_runner_->PostShutdownBlockingTask( 422 bool success = task_runner_->PostShutdownBlockingTask(
353 FROM_HERE, 423 FROM_HERE,
354 DOMStorageTaskRunner::COMMIT_SEQUENCE, 424 DOMStorageTaskRunner::COMMIT_SEQUENCE,
355 base::Bind(&DOMStorageArea::CommitChanges, this, 425 base::Bind(&DOMStorageArea::CommitChanges, this,
356 base::Owned(commit_batch_.release()))); 426 base::Owned(commit_batch_.release())));
357 ++commit_batches_in_flight_; 427 ++commit_batches_in_flight_;
358 DCHECK(success); 428 DCHECK(success);
(...skipping 13 matching lines...) Expand all
372 442
373 void DOMStorageArea::OnCommitComplete() { 443 void DOMStorageArea::OnCommitComplete() {
374 // We're back on the primary sequence in this method. 444 // We're back on the primary sequence in this method.
375 DCHECK(task_runner_->IsRunningOnPrimarySequence()); 445 DCHECK(task_runner_->IsRunningOnPrimarySequence());
376 --commit_batches_in_flight_; 446 --commit_batches_in_flight_;
377 if (is_shutdown_) 447 if (is_shutdown_)
378 return; 448 return;
379 if (commit_batch_.get() && !commit_batches_in_flight_) { 449 if (commit_batch_.get() && !commit_batches_in_flight_) {
380 // More changes have accrued, restart the timer. 450 // More changes have accrued, restart the timer.
381 task_runner_->PostDelayedTask( 451 task_runner_->PostDelayedTask(
382 FROM_HERE, 452 FROM_HERE, base::Bind(&DOMStorageArea::OnCommitTimer, this),
383 base::Bind(&DOMStorageArea::OnCommitTimer, this), 453 ComputeCommitDelay());
384 base::TimeDelta::FromSeconds(kCommitTimerSeconds));
385 } 454 }
386 } 455 }
387 456
388 void DOMStorageArea::ShutdownInCommitSequence() { 457 void DOMStorageArea::ShutdownInCommitSequence() {
389 // This method executes on the commit sequence. 458 // This method executes on the commit sequence.
390 DCHECK(task_runner_->IsRunningOnCommitSequence()); 459 DCHECK(task_runner_->IsRunningOnCommitSequence());
391 DCHECK(backing_.get()); 460 DCHECK(backing_.get());
392 if (commit_batch_) { 461 if (commit_batch_) {
393 // Commit any changes that accrued prior to the timer firing. 462 // Commit any changes that accrued prior to the timer firing.
394 bool success = backing_->CommitChanges( 463 bool success = backing_->CommitChanges(
395 commit_batch_->clear_all_first, 464 commit_batch_->clear_all_first,
396 commit_batch_->changed_values); 465 commit_batch_->changed_values);
397 DCHECK(success); 466 DCHECK(success);
398 } 467 }
399 commit_batch_.reset(); 468 commit_batch_.reset();
400 backing_.reset(); 469 backing_.reset();
401 session_storage_backing_ = NULL; 470 session_storage_backing_ = NULL;
402 } 471 }
403 472
404 } // namespace content 473 } // namespace content
OLDNEW
« no previous file with comments | « content/browser/dom_storage/dom_storage_area.h ('k') | content/browser/dom_storage/dom_storage_area_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698