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

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: TimeDelta.multiply_by(dbl) 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"
13 #include "base/process/process_info.h"
11 #include "base/strings/utf_string_conversions.h" 14 #include "base/strings/utf_string_conversions.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 namespace {
29 32
30 DOMStorageArea::CommitBatch::CommitBatch() 33 // Delay for a moment after a value is set in anticipation
31 : clear_all_first(false) { 34 // of other values being set, so changes are batched.
35 const int kCommitDefaultDelaySecs = 5;
36
37 // The delay used if a commit is scheduled during startup.
38 const int kCommitDuringStartupDelaySecs = 60;
39
40 // To avoid excessive IO we apply limits to the amount of data being written
41 // and the frequency of writes. The specific values used are somewhat arbitrary.
42 const int kMaxBytesPerDay = kPerStorageAreaQuota * 2;
43 const int kMaxCommitsPerHour = 6;
44
45 // TODO(michaeln): Put this somewhere appropiate for reuse.
46 bool IsBrowserStartingUp() {
47 auto process_creation_ticks = [] {
48 base::Time creation_time =
49 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
50 base::CurrentProcessInfo::CreationTime();
51 #else
52 base::Time::Now(); // Ok since its only used once.
53 #endif
54 return base::TimeTicks::Now() - (base::Time::Now() - creation_time);
55 };
56
57 // For now, consider the first 60 seconds as "starting up".
58 static const base::TimeTicks kProcessCreationTicks =
59 process_creation_ticks();
60 base::TimeDelta up_time = base::TimeTicks::Now() - kProcessCreationTicks;
61 return up_time < base::TimeDelta::FromSeconds(60);
62 }
63
64 } // namespace
65
66 DOMStorageArea::RateLimiter::RateLimiter(size_t desired_rate,
67 base::TimeDelta time_quantum)
68 : rate_(desired_rate), samples_(0), time_quantum_(time_quantum) {
69 DCHECK_GT(desired_rate, 0ul);
70 }
71
72 base::TimeDelta DOMStorageArea::RateLimiter::ComputeTimeNeeded() const {
73 return time_quantum_.multiply_by(samples_ / rate_);
74 }
75
76 base::TimeDelta DOMStorageArea::RateLimiter::ComputeDelayNeeded(
77 const base::TimeDelta elapsed_time) const {
78 base::TimeDelta time_needed = ComputeTimeNeeded();
79 if (time_needed > elapsed_time)
80 return time_needed - elapsed_time;
81 return base::TimeDelta();
82 }
83
84 DOMStorageArea::CommitBatch::CommitBatch() : clear_all_first(false) {
32 } 85 }
33 DOMStorageArea::CommitBatch::~CommitBatch() {} 86 DOMStorageArea::CommitBatch::~CommitBatch() {}
34 87
88 size_t DOMStorageArea::CommitBatch::GetDataSize() const {
89 return DOMStorageMap::CountBytes(changed_values);
90 }
35 91
36 // static 92 // static
37 const base::FilePath::CharType DOMStorageArea::kDatabaseFileExtension[] = 93 const base::FilePath::CharType DOMStorageArea::kDatabaseFileExtension[] =
38 FILE_PATH_LITERAL(".localstorage"); 94 FILE_PATH_LITERAL(".localstorage");
39 95
40 // static 96 // static
41 base::FilePath DOMStorageArea::DatabaseFileNameFromOrigin(const GURL& origin) { 97 base::FilePath DOMStorageArea::DatabaseFileNameFromOrigin(const GURL& origin) {
42 std::string filename = storage::GetIdentifierFromOrigin(origin); 98 std::string filename = storage::GetIdentifierFromOrigin(origin);
43 // There is no base::FilePath.AppendExtension() method, so start with just the 99 // There is no base::FilePath.AppendExtension() method, so start with just the
44 // extension as the filename, and then InsertBeforeExtension the desired 100 // extension as the filename, and then InsertBeforeExtension the desired
45 // name. 101 // name.
46 return base::FilePath().Append(kDatabaseFileExtension). 102 return base::FilePath().Append(kDatabaseFileExtension).
47 InsertBeforeExtensionASCII(filename); 103 InsertBeforeExtensionASCII(filename);
48 } 104 }
49 105
50 // static 106 // static
51 GURL DOMStorageArea::OriginFromDatabaseFileName(const base::FilePath& name) { 107 GURL DOMStorageArea::OriginFromDatabaseFileName(const base::FilePath& name) {
52 DCHECK(name.MatchesExtension(kDatabaseFileExtension)); 108 DCHECK(name.MatchesExtension(kDatabaseFileExtension));
53 std::string origin_id = 109 std::string origin_id =
54 name.BaseName().RemoveExtension().MaybeAsASCII(); 110 name.BaseName().RemoveExtension().MaybeAsASCII();
55 return storage::GetOriginFromIdentifier(origin_id); 111 return storage::GetOriginFromIdentifier(origin_id);
56 } 112 }
57 113
58 DOMStorageArea::DOMStorageArea( 114 DOMStorageArea::DOMStorageArea(const GURL& origin,
59 const GURL& origin, const base::FilePath& directory, 115 const base::FilePath& directory,
60 DOMStorageTaskRunner* task_runner) 116 DOMStorageTaskRunner* task_runner)
61 : namespace_id_(kLocalStorageNamespaceId), origin_(origin), 117 : namespace_id_(kLocalStorageNamespaceId),
118 origin_(origin),
62 directory_(directory), 119 directory_(directory),
63 task_runner_(task_runner), 120 task_runner_(task_runner),
64 map_(new DOMStorageMap(kPerStorageAreaQuota + 121 map_(new DOMStorageMap(kPerStorageAreaQuota +
65 kPerStorageAreaOverQuotaAllowance)), 122 kPerStorageAreaOverQuotaAllowance)),
66 is_initial_import_done_(true), 123 is_initial_import_done_(true),
67 is_shutdown_(false), 124 is_shutdown_(false),
68 commit_batches_in_flight_(0) { 125 commit_batches_in_flight_(0),
126 start_time_(base::TimeTicks::Now()),
127 data_rate_limiter_(kMaxBytesPerDay, base::TimeDelta::FromHours(24)),
128 commit_rate_limiter_(kMaxCommitsPerHour, base::TimeDelta::FromHours(1)) {
69 if (!directory.empty()) { 129 if (!directory.empty()) {
70 base::FilePath path = directory.Append(DatabaseFileNameFromOrigin(origin_)); 130 base::FilePath path = directory.Append(DatabaseFileNameFromOrigin(origin_));
71 backing_.reset(new LocalStorageDatabaseAdapter(path)); 131 backing_.reset(new LocalStorageDatabaseAdapter(path));
72 is_initial_import_done_ = false; 132 is_initial_import_done_ = false;
73 } 133 }
74 } 134 }
75 135
76 DOMStorageArea::DOMStorageArea( 136 DOMStorageArea::DOMStorageArea(int64 namespace_id,
77 int64 namespace_id, 137 const std::string& persistent_namespace_id,
78 const std::string& persistent_namespace_id, 138 const GURL& origin,
79 const GURL& origin, 139 SessionStorageDatabase* session_storage_backing,
80 SessionStorageDatabase* session_storage_backing, 140 DOMStorageTaskRunner* task_runner)
81 DOMStorageTaskRunner* task_runner)
82 : namespace_id_(namespace_id), 141 : namespace_id_(namespace_id),
83 persistent_namespace_id_(persistent_namespace_id), 142 persistent_namespace_id_(persistent_namespace_id),
84 origin_(origin), 143 origin_(origin),
85 task_runner_(task_runner), 144 task_runner_(task_runner),
86 map_(new DOMStorageMap(kPerStorageAreaQuota + 145 map_(new DOMStorageMap(kPerStorageAreaQuota +
87 kPerStorageAreaOverQuotaAllowance)), 146 kPerStorageAreaOverQuotaAllowance)),
88 session_storage_backing_(session_storage_backing), 147 session_storage_backing_(session_storage_backing),
89 is_initial_import_done_(true), 148 is_initial_import_done_(true),
90 is_shutdown_(false), 149 is_shutdown_(false),
91 commit_batches_in_flight_(0) { 150 commit_batches_in_flight_(0),
151 start_time_(base::TimeTicks::Now()),
152 data_rate_limiter_(kMaxBytesPerDay, base::TimeDelta::FromHours(24)),
153 commit_rate_limiter_(kMaxCommitsPerHour, base::TimeDelta::FromHours(1)) {
92 DCHECK(namespace_id != kLocalStorageNamespaceId); 154 DCHECK(namespace_id != kLocalStorageNamespaceId);
93 if (session_storage_backing) { 155 if (session_storage_backing) {
94 backing_.reset(new SessionStorageDatabaseAdapter( 156 backing_.reset(new SessionStorageDatabaseAdapter(
95 session_storage_backing, persistent_namespace_id, origin)); 157 session_storage_backing, persistent_namespace_id, origin));
96 is_initial_import_done_ = false; 158 is_initial_import_done_ = false;
97 } 159 }
98 } 160 }
99 161
100 DOMStorageArea::~DOMStorageArea() { 162 DOMStorageArea::~DOMStorageArea() {
101 } 163 }
(...skipping 28 matching lines...) Expand all
130 192
131 bool DOMStorageArea::SetItem(const base::string16& key, 193 bool DOMStorageArea::SetItem(const base::string16& key,
132 const base::string16& value, 194 const base::string16& value,
133 base::NullableString16* old_value) { 195 base::NullableString16* old_value) {
134 if (is_shutdown_) 196 if (is_shutdown_)
135 return false; 197 return false;
136 InitialImportIfNeeded(); 198 InitialImportIfNeeded();
137 if (!map_->HasOneRef()) 199 if (!map_->HasOneRef())
138 map_ = map_->DeepCopy(); 200 map_ = map_->DeepCopy();
139 bool success = map_->SetItem(key, value, old_value); 201 bool success = map_->SetItem(key, value, old_value);
140 if (success && backing_) { 202 if (success && backing_ &&
203 (old_value->is_null() || old_value->string() != value)) {
141 CommitBatch* commit_batch = CreateCommitBatchIfNeeded(); 204 CommitBatch* commit_batch = CreateCommitBatchIfNeeded();
142 commit_batch->changed_values[key] = base::NullableString16(value, false); 205 commit_batch->changed_values[key] = base::NullableString16(value, false);
143 } 206 }
144 return success; 207 return success;
145 } 208 }
146 209
147 bool DOMStorageArea::RemoveItem(const base::string16& key, 210 bool DOMStorageArea::RemoveItem(const base::string16& key,
148 base::string16* old_value) { 211 base::string16* old_value) {
149 if (is_shutdown_) 212 if (is_shutdown_)
150 return false; 213 return false;
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
205 DCHECK_NE(kLocalStorageNamespaceId, destination_namespace_id); 268 DCHECK_NE(kLocalStorageNamespaceId, destination_namespace_id);
206 269
207 DOMStorageArea* copy = new DOMStorageArea( 270 DOMStorageArea* copy = new DOMStorageArea(
208 destination_namespace_id, destination_persistent_namespace_id, origin_, 271 destination_namespace_id, destination_persistent_namespace_id, origin_,
209 session_storage_backing_.get(), task_runner_.get()); 272 session_storage_backing_.get(), task_runner_.get());
210 copy->map_ = map_; 273 copy->map_ = map_;
211 copy->is_shutdown_ = is_shutdown_; 274 copy->is_shutdown_ = is_shutdown_;
212 copy->is_initial_import_done_ = true; 275 copy->is_initial_import_done_ = true;
213 276
214 // All the uncommitted changes to this area need to happen before the actual 277 // 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 278 // 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_) 279 if (commit_batch_)
219 OnCommitTimer(); 280 ScheduleImmediateCommit();
220 return copy; 281 return copy;
221 } 282 }
222 283
223 bool DOMStorageArea::HasUncommittedChanges() const { 284 bool DOMStorageArea::HasUncommittedChanges() const {
224 DCHECK(!is_shutdown_);
225 return commit_batch_.get() || commit_batches_in_flight_; 285 return commit_batch_.get() || commit_batches_in_flight_;
226 } 286 }
227 287
288 void DOMStorageArea::ScheduleImmediateCommit() {
289 DCHECK(HasUncommittedChanges());
290 PostCommitTask();
291 }
292
228 void DOMStorageArea::DeleteOrigin() { 293 void DOMStorageArea::DeleteOrigin() {
229 DCHECK(!is_shutdown_); 294 DCHECK(!is_shutdown_);
230 // This function shouldn't be called for sessionStorage. 295 // This function shouldn't be called for sessionStorage.
231 DCHECK(!session_storage_backing_.get()); 296 DCHECK(!session_storage_backing_.get());
232 if (HasUncommittedChanges()) { 297 if (HasUncommittedChanges()) {
233 // TODO(michaeln): This logically deletes the data immediately, 298 // TODO(michaeln): This logically deletes the data immediately,
234 // and in a matter of a second, deletes the rows from the backing 299 // and in a matter of a second, deletes the rows from the backing
235 // database file, but the file itself will linger until shutdown 300 // database file, but the file itself will linger until shutdown
236 // or purge time. Ideally, this should delete the file more 301 // or purge time. Ideally, this should delete the file more
237 // quickly. 302 // quickly.
(...skipping 82 matching lines...) Expand 10 before | Expand all | Expand 10 after
320 DOMStorageArea::CommitBatch* DOMStorageArea::CreateCommitBatchIfNeeded() { 385 DOMStorageArea::CommitBatch* DOMStorageArea::CreateCommitBatchIfNeeded() {
321 DCHECK(!is_shutdown_); 386 DCHECK(!is_shutdown_);
322 if (!commit_batch_) { 387 if (!commit_batch_) {
323 commit_batch_.reset(new CommitBatch()); 388 commit_batch_.reset(new CommitBatch());
324 389
325 // Start a timer to commit any changes that accrue in the batch, but only if 390 // 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 391 // no commits are currently in flight. In that case the timer will be
327 // started after the commits have happened. 392 // started after the commits have happened.
328 if (!commit_batches_in_flight_) { 393 if (!commit_batches_in_flight_) {
329 task_runner_->PostDelayedTask( 394 task_runner_->PostDelayedTask(
330 FROM_HERE, 395 FROM_HERE, base::Bind(&DOMStorageArea::OnCommitTimer, this),
331 base::Bind(&DOMStorageArea::OnCommitTimer, this), 396 ComputeCommitDelay());
332 base::TimeDelta::FromSeconds(kCommitTimerSeconds));
333 } 397 }
334 } 398 }
335 return commit_batch_.get(); 399 return commit_batch_.get();
336 } 400 }
337 401
402 base::TimeDelta DOMStorageArea::ComputeCommitDelay() const {
403 base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time_;
404 base::TimeDelta delay = std::max(
405 base::TimeDelta::FromSeconds(kCommitDefaultDelaySecs),
406 std::max(commit_rate_limiter_.ComputeDelayNeeded(elapsed_time),
407 data_rate_limiter_.ComputeDelayNeeded(elapsed_time)));
408 UMA_HISTOGRAM_LONG_TIMES("LocalStorage.CommitDelay", delay);
409 return delay;
410 }
411
338 void DOMStorageArea::OnCommitTimer() { 412 void DOMStorageArea::OnCommitTimer() {
339 if (is_shutdown_) 413 if (is_shutdown_)
340 return; 414 return;
341 415
416 // It's possible that there is nothing to commit if an immediate
417 // commit occured after the timer was scheduled but before it fired.
418 if (!commit_batch_)
419 return;
420
421 // Don't mind the double counting of the few that are deferred compared
422 // to the masses that aren't.
423 bool defer_commit = IsBrowserStartingUp();
424 UMA_HISTOGRAM_BOOLEAN("LocalStorage.Commit", !defer_commit);
425 if (defer_commit) {
426 task_runner_->PostDelayedTask(
427 FROM_HERE, base::Bind(&DOMStorageArea::OnCommitTimer, this),
428 base::TimeDelta::FromSeconds(kCommitDuringStartupDelaySecs));
429 return;
430 }
431
432 PostCommitTask();
433 }
434
435 void DOMStorageArea::PostCommitTask() {
436 if (is_shutdown_ || !commit_batch_)
437 return;
438
342 DCHECK(backing_.get()); 439 DCHECK(backing_.get());
343 440
344 // It's possible that there is nothing to commit, since a shallow copy occured 441 commit_rate_limiter_.add_samples(1);
345 // before the timer fired. 442 data_rate_limiter_.add_samples(commit_batch_->GetDataSize());
346 if (!commit_batch_)
347 return;
348 443
349 // This method executes on the primary sequence, we schedule 444 // This method executes on the primary sequence, we schedule
350 // a task for immediate execution on the commit sequence. 445 // a task for immediate execution on the commit sequence.
351 DCHECK(task_runner_->IsRunningOnPrimarySequence()); 446 DCHECK(task_runner_->IsRunningOnPrimarySequence());
352 bool success = task_runner_->PostShutdownBlockingTask( 447 bool success = task_runner_->PostShutdownBlockingTask(
353 FROM_HERE, 448 FROM_HERE,
354 DOMStorageTaskRunner::COMMIT_SEQUENCE, 449 DOMStorageTaskRunner::COMMIT_SEQUENCE,
355 base::Bind(&DOMStorageArea::CommitChanges, this, 450 base::Bind(&DOMStorageArea::CommitChanges, this,
356 base::Owned(commit_batch_.release()))); 451 base::Owned(commit_batch_.release())));
357 ++commit_batches_in_flight_; 452 ++commit_batches_in_flight_;
358 DCHECK(success); 453 DCHECK(success);
359 } 454 }
360 455
361 void DOMStorageArea::CommitChanges(const CommitBatch* commit_batch) { 456 void DOMStorageArea::CommitChanges(const CommitBatch* commit_batch) {
362 // This method executes on the commit sequence. 457 // This method executes on the commit sequence.
363 DCHECK(task_runner_->IsRunningOnCommitSequence()); 458 DCHECK(task_runner_->IsRunningOnCommitSequence());
364 backing_->CommitChanges(commit_batch->clear_all_first, 459 backing_->CommitChanges(commit_batch->clear_all_first,
365 commit_batch->changed_values); 460 commit_batch->changed_values);
366 // TODO(michaeln): what if CommitChanges returns false (e.g., we're trying to 461 // TODO(michaeln): what if CommitChanges returns false (e.g., we're trying to
367 // commit to a DB which is in an inconsistent state?) 462 // commit to a DB which is in an inconsistent state?)
368 task_runner_->PostTask( 463 task_runner_->PostTask(
369 FROM_HERE, 464 FROM_HERE,
370 base::Bind(&DOMStorageArea::OnCommitComplete, this)); 465 base::Bind(&DOMStorageArea::OnCommitComplete, this));
371 } 466 }
372 467
373 void DOMStorageArea::OnCommitComplete() { 468 void DOMStorageArea::OnCommitComplete() {
374 // We're back on the primary sequence in this method. 469 // We're back on the primary sequence in this method.
375 DCHECK(task_runner_->IsRunningOnPrimarySequence()); 470 DCHECK(task_runner_->IsRunningOnPrimarySequence());
376 --commit_batches_in_flight_; 471 --commit_batches_in_flight_;
377 if (is_shutdown_) 472 if (is_shutdown_)
378 return; 473 return;
379 if (commit_batch_.get() && !commit_batches_in_flight_) { 474 if (commit_batch_.get() && !commit_batches_in_flight_) {
380 // More changes have accrued, restart the timer. 475 // More changes have accrued, restart the timer.
381 task_runner_->PostDelayedTask( 476 task_runner_->PostDelayedTask(
382 FROM_HERE, 477 FROM_HERE, base::Bind(&DOMStorageArea::OnCommitTimer, this),
383 base::Bind(&DOMStorageArea::OnCommitTimer, this), 478 ComputeCommitDelay());
384 base::TimeDelta::FromSeconds(kCommitTimerSeconds));
385 } 479 }
386 } 480 }
387 481
388 void DOMStorageArea::ShutdownInCommitSequence() { 482 void DOMStorageArea::ShutdownInCommitSequence() {
389 // This method executes on the commit sequence. 483 // This method executes on the commit sequence.
390 DCHECK(task_runner_->IsRunningOnCommitSequence()); 484 DCHECK(task_runner_->IsRunningOnCommitSequence());
391 DCHECK(backing_.get()); 485 DCHECK(backing_.get());
392 if (commit_batch_) { 486 if (commit_batch_) {
393 // Commit any changes that accrued prior to the timer firing. 487 // Commit any changes that accrued prior to the timer firing.
394 bool success = backing_->CommitChanges( 488 bool success = backing_->CommitChanges(
395 commit_batch_->clear_all_first, 489 commit_batch_->clear_all_first,
396 commit_batch_->changed_values); 490 commit_batch_->changed_values);
397 DCHECK(success); 491 DCHECK(success);
398 } 492 }
399 commit_batch_.reset(); 493 commit_batch_.reset();
400 backing_.reset(); 494 backing_.reset();
401 session_storage_backing_ = NULL; 495 session_storage_backing_ = NULL;
402 } 496 }
403 497
404 } // namespace content 498 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698