1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/indexed_db/instance/transaction.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/trace_event/base_tracing.h"
#include "base/types/expected_macros.h"
#include "base/unguessable_token.h"
#include "components/services/storage/indexed_db/locks/partitioned_lock_manager.h"
#include "components/services/storage/privileged/mojom/indexed_db_client_state_checker.mojom-shared.h"
#include "components/services/storage/privileged/mojom/indexed_db_internals_types.mojom-forward.h"
#include "components/services/storage/privileged/mojom/indexed_db_internals_types.mojom-shared.h"
#include "components/services/storage/privileged/mojom/indexed_db_internals_types.mojom.h"
#include "components/services/storage/public/mojom/blob_storage_context.mojom-shared.h"
#include "content/browser/indexed_db/indexed_db_external_object.h"
#include "content/browser/indexed_db/indexed_db_external_object_storage.h"
#include "content/browser/indexed_db/indexed_db_leveldb_coding.h"
#include "content/browser/indexed_db/instance/bucket_context.h"
#include "content/browser/indexed_db/instance/bucket_context_handle.h"
#include "content/browser/indexed_db/instance/callback_helpers.h"
#include "content/browser/indexed_db/instance/connection.h"
#include "content/browser/indexed_db/instance/cursor.h"
#include "content/browser/indexed_db/instance/database.h"
#include "content/browser/indexed_db/instance/database_callbacks.h"
#include "content/browser/indexed_db/instance/index_writer.h"
#include "content/browser/indexed_db/instance/lock_request_data.h"
#include "content/browser/indexed_db/status.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom.h"
#include "third_party/leveldatabase/env_chromium.h"
namespace content::indexed_db {
namespace {
std::string WriteBlobToFileResultToString(
storage::mojom::WriteBlobToFileResult result) {
switch (result) {
case storage::mojom::WriteBlobToFileResult::kError:
return "Error";
case storage::mojom::WriteBlobToFileResult::kBadPath:
return "BadPath";
case storage::mojom::WriteBlobToFileResult::kInvalidBlob:
return "InvalidBlob";
case storage::mojom::WriteBlobToFileResult::kIOError:
return "IOError";
case storage::mojom::WriteBlobToFileResult::kTimestampError:
return "TimestampError";
case storage::mojom::WriteBlobToFileResult::kSuccess:
return "Success";
}
NOTREACHED();
}
// Disabled in some tests.
bool g_inactivity_timeout_enabled = true;
// Used for UMA metrics - do not change values.
enum UmaIDBException {
UmaIDBExceptionUnknownError = 0,
UmaIDBExceptionConstraintError = 1,
UmaIDBExceptionDataError = 2,
UmaIDBExceptionVersionError = 3,
UmaIDBExceptionAbortError = 4,
UmaIDBExceptionQuotaError = 5,
UmaIDBExceptionTimeoutError = 6,
UmaIDBExceptionExclusiveMaxValue = 7
};
// Used for UMA metrics - do not change mappings.
UmaIDBException ExceptionCodeToUmaEnum(blink::mojom::IDBException code) {
switch (code) {
case blink::mojom::IDBException::kUnknownError:
return UmaIDBExceptionUnknownError;
case blink::mojom::IDBException::kConstraintError:
return UmaIDBExceptionConstraintError;
case blink::mojom::IDBException::kDataError:
return UmaIDBExceptionDataError;
case blink::mojom::IDBException::kVersionError:
return UmaIDBExceptionVersionError;
case blink::mojom::IDBException::kAbortError:
return UmaIDBExceptionAbortError;
case blink::mojom::IDBException::kQuotaError:
return UmaIDBExceptionQuotaError;
case blink::mojom::IDBException::kTimeoutError:
return UmaIDBExceptionTimeoutError;
default:
NOTREACHED();
}
}
} // namespace
Transaction::TaskQueue::TaskQueue() = default;
Transaction::TaskQueue::~TaskQueue() = default;
void Transaction::TaskQueue::clear() {
while (!queue_.empty()) {
queue_.pop();
}
}
Transaction::Operation Transaction::TaskQueue::pop() {
DCHECK(!queue_.empty());
Operation task = std::move(queue_.front());
queue_.pop();
return task;
}
Transaction::Transaction(
int64_t id,
Connection* connection,
const std::set<int64_t>& object_store_ids,
blink::mojom::IDBTransactionMode mode,
blink::mojom::IDBTransactionDurability durability,
BucketContextHandle bucket_context,
std::unique_ptr<BackingStore::Transaction> backing_store_transaction)
: id_(id),
object_store_ids_(object_store_ids),
mode_(mode),
durability_(durability),
connection_(connection->GetWeakPtr()),
bucket_context_(std::move(bucket_context)),
backing_store_transaction_(std::move(backing_store_transaction)),
receiver_(this) {
TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("IndexedDB", "Transaction::lifetime", this);
locks_receiver_.SetUserData(
LockRequestData::kKey,
std::make_unique<LockRequestData>(connection->client_token(),
connection->scheduling_priority()));
database_ = connection_->database();
if (database_) {
if (mode_ == blink::mojom::IDBTransactionMode::VersionChange) {
lock_ids_.insert(GetDatabaseLockId(database_->name()));
} else {
for (const PartitionedLockManager::PartitionedLockRequest& lock_request :
BuildLockRequests()) {
lock_ids_.insert(lock_request.lock_id);
}
}
}
diagnostics_.tasks_scheduled = 0;
diagnostics_.tasks_completed = 0;
diagnostics_.creation_time = base::Time::Now();
SetState(state_); // Process the initial state.
}
Transaction::~Transaction() {
TRACE_EVENT_NESTABLE_ASYNC_END0("IndexedDB", "Transaction::lifetime", this);
// It shouldn't be possible for this object to get deleted until it's either
// complete or aborted.
DCHECK_EQ(state_, FINISHED);
DCHECK(preemptive_task_queue_.empty());
DCHECK_EQ(pending_preemptive_events_, 0);
DCHECK(task_queue_.empty());
DCHECK(!processing_event_queue_);
}
void Transaction::BindReceiver(
mojo::PendingAssociatedReceiver<blink::mojom::IDBTransaction>
mojo_receiver) {
receiver_.Bind(std::move(mojo_receiver));
}
void Transaction::SetCommitFlag() {
// The frontend suggests that we commit, but we may have previously initiated
// an abort.
if (!IsAcceptingRequests()) {
return;
}
is_commit_pending_ = true;
bucket_context_->QueueRunTasks();
}
void Transaction::ScheduleTask(blink::mojom::IDBTaskType type, Operation task) {
if (state_ == FINISHED) {
return;
}
ResetTimeoutTimer();
used_ = true;
if (type == blink::mojom::IDBTaskType::Normal) {
task_queue_.push(std::move(task));
++diagnostics_.tasks_scheduled;
NotifyOfIdbInternalsRelevantChange();
} else {
preemptive_task_queue_.push(std::move(task));
}
if (state() == STARTED) {
bucket_context_->QueueRunTasks();
}
}
Status Transaction::Abort(const DatabaseError& error) {
if (state_ == FINISHED) {
return Status::OK();
}
base::UmaHistogramEnumeration("WebCore.IndexedDB.TransactionAbortReason",
ExceptionCodeToUmaEnum(error.code()),
UmaIDBExceptionExclusiveMaxValue);
aborted_ = true;
ResetTimeoutTimer();
SetState(FINISHED);
if (backing_store_transaction_begun_) {
backing_store_transaction_->Rollback();
}
preemptive_task_queue_.clear();
pending_preemptive_events_ = 0;
task_queue_.clear();
// Backing store resources (held via cursors) must be released
// before script callbacks are fired, as the script callbacks may
// release references and allow the backing store itself to be
// released, and order is critical.
CloseOpenCursors();
backing_store_transaction_->Reset();
// Transactions must also be marked as completed before the
// front-end is notified, as the transaction completion unblocks
// operations like closing connections.
locks_receiver_.locks.clear();
locks_receiver_.CancelLockRequest();
connection()->callbacks()->OnAbort(*this, error);
bucket_context_->QueueRunTasks();
bucket_context_.Release();
return Status::OK();
}
// static
Status Transaction::CommitPhaseTwoProxy(Transaction* transaction) {
return transaction->CommitPhaseTwo();
}
bool Transaction::IsTaskQueueEmpty() const {
return preemptive_task_queue_.empty() && task_queue_.empty();
}
bool Transaction::HasPendingTasks() const {
return pending_preemptive_events_ || !IsTaskQueueEmpty();
}
void Transaction::RegisterOpenCursor(Cursor* cursor) {
open_cursors_.insert(cursor);
}
void Transaction::UnregisterOpenCursor(Cursor* cursor) {
open_cursors_.erase(cursor);
}
void Transaction::DontAllowInactiveClientToBlockOthers(
storage::mojom::DisallowInactiveClientReason reason) {
if (state_ == STARTED && IsTransactionBlockingOtherClients()) {
connection_->DisallowInactiveClient(reason, base::DoNothing());
}
}
bool Transaction::IsTransactionBlockingOtherClients(
bool consider_priority) const {
CHECK_EQ(state_, STARTED);
if (database_->OnlyHasOneClient()) {
return false;
}
base::TimeTicks start = base::TimeTicks::Now();
std::optional<int> scheduling_priority;
if (consider_priority) {
scheduling_priority = connection_->scheduling_priority();
}
const bool is_blocking_others =
bucket_context_->lock_manager().IsBlockingAnyRequest(
lock_ids(),
base::BindRepeating(
[](std::optional<int> this_priority,
const base::UnguessableToken& this_token,
PartitionedLockHolder* blocked_lock_holder) {
auto* lock_request_data = static_cast<LockRequestData*>(
blocked_lock_holder->GetUserData(LockRequestData::kKey));
if (!lock_request_data) {
return true;
}
// If `this`
// * comes from a background client (priority > 0), and
// * is equal or higher priority than the blocked
// transaction's client
// (aka equally or less severely throttled)
// then don't worry about blocking it.
if (this_priority && (*this_priority > 0) &&
(*this_priority <=
lock_request_data->scheduling_priority)) {
return false;
}
return lock_request_data->client_token != this_token;
},
scheduling_priority, connection_->client_token()));
base::TimeDelta duration = base::TimeTicks::Now() - start;
if (duration > base::Milliseconds(2)) {
base::UmaHistogramTimes("IndexedDB.CalculateBlockingStatusLongTimes",
duration);
base::UmaHistogramCounts100000(
"IndexedDB.CalculateBlockingStatusRequestQueueSize",
bucket_context_->lock_manager().RequestsWaitingForMetrics());
}
return is_blocking_others;
}
void Transaction::Start() {
// The transaction has the potential to be aborted after the Start() task was
// posted.
if (state_ == FINISHED) {
DCHECK(locks_receiver_.locks.empty());
return;
}
DCHECK_EQ(CREATED, state_);
std::optional scheduling_priority_at_last_state_change =
scheduling_priority_at_last_state_change_;
SetState(STARTED);
DCHECK(!locks_receiver_.locks.empty());
diagnostics_.start_time = base::Time::Now();
// If the client is in BFCache, the transaction will get stuck, so evict it if
// necessary.
DontAllowInactiveClientToBlockOthers(
storage::mojom::DisallowInactiveClientReason::
kTransactionIsStartingWhileBlockingOthers);
const base::TimeDelta time_queued =
diagnostics_.start_time - diagnostics_.creation_time;
switch (mode_) {
case blink::mojom::IDBTransactionMode::ReadOnly:
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadOnly.TimeQueued", time_queued);
if (scheduling_priority_at_last_state_change == 0) {
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadOnly.TimeQueued.Foreground",
time_queued);
}
break;
case blink::mojom::IDBTransactionMode::ReadWrite:
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadWrite.TimeQueued", time_queued);
if (scheduling_priority_at_last_state_change == 0) {
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadWrite.TimeQueued.Foreground",
time_queued);
}
break;
case blink::mojom::IDBTransactionMode::VersionChange:
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.VersionChange.TimeQueued",
time_queued);
if (scheduling_priority_at_last_state_change == 0) {
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.VersionChange.TimeQueued.Foreground",
time_queued);
}
break;
}
bucket_context_->QueueRunTasks();
}
// static
void Transaction::DisableInactivityTimeoutForTesting() {
g_inactivity_timeout_enabled = false;
}
void Transaction::CreateObjectStore(int64_t object_store_id,
const std::u16string& name,
const blink::IndexedDBKeyPath& key_path,
bool auto_increment) {
if (mode() != blink::mojom::IDBTransactionMode::VersionChange) {
mojo::ReportBadMessage(
"CreateObjectStore must be called from a version change transaction.");
return;
}
if (!IsAcceptingRequests() || !connection()->IsConnected()) {
return;
}
ScheduleTask(
blink::mojom::IDBTaskType::Preemptive,
base::BindOnce(
[](int64_t object_store_id, const std::u16string& name,
const blink::IndexedDBKeyPath& key_path, bool auto_increment,
Transaction* transaction) {
return transaction->BackingStoreTransaction()->CreateObjectStore(
object_store_id, name, key_path, auto_increment);
},
object_store_id, name, key_path, auto_increment));
}
void Transaction::DeleteObjectStore(int64_t object_store_id) {
if (mode() != blink::mojom::IDBTransactionMode::VersionChange) {
mojo::ReportBadMessage(
"DeleteObjectStore must be called from a version change transaction.");
return;
}
if (!IsAcceptingRequests() || !connection()->IsConnected()) {
return;
}
ScheduleTask(base::BindOnce(
[](int64_t object_store_id, Transaction* transaction) {
return transaction->BackingStoreTransaction()->DeleteObjectStore(
object_store_id);
},
object_store_id));
}
void Transaction::Put(int64_t object_store_id,
blink::mojom::IDBValuePtr input_value,
blink::IndexedDBKey key,
blink::mojom::IDBPutMode mode,
std::vector<blink::IndexedDBIndexKeys> index_keys,
blink::mojom::IDBTransaction::PutCallback callback) {
if (!IsAcceptingRequests()) {
return;
}
if (!connection()->IsConnected()) {
DatabaseError error(blink::mojom::IDBException::kUnknownError,
"Not connected.");
std::move(callback).Run(
blink::mojom::IDBTransactionPutResult::NewErrorResult(
blink::mojom::IDBError::New(error.code(), error.message())));
return;
}
std::vector<IndexedDBExternalObject> external_objects;
uint64_t total_blob_size = 0;
if (!input_value->external_objects.empty()) {
total_blob_size = CreateExternalObjects(input_value, &external_objects);
}
// Increment the total transaction size by the size of this put.
preliminary_size_estimate_ +=
input_value->bits.size() + key.size_estimate() + total_blob_size;
// Warm up the disk space cache.
bucket_context()->CheckCanUseDiskSpace(preliminary_size_estimate_, {});
IndexedDBValue value;
value.bits = std::move(input_value->bits);
value.external_objects = std::move(external_objects);
blink::mojom::IDBTransaction::PutCallback wrapped_callback =
CreateCallbackAbortOnDestruct<blink::mojom::IDBTransaction::PutCallback,
blink::mojom::IDBTransactionPutResultPtr>(
std::move(callback), AsWeakPtr());
// This is decremented in DoPut.
in_flight_memory_ += value.SizeEstimate();
ScheduleTask(BindWeakOperation(&Transaction::DoPut, AsWeakPtr(),
object_store_id, std::move(value),
std::move(key), mode, std::move(index_keys),
std::move(wrapped_callback)));
}
Status Transaction::DoPut(int64_t object_store_id,
IndexedDBValue value,
blink::IndexedDBKey key,
blink::mojom::IDBPutMode put_mode,
std::vector<blink::IndexedDBIndexKeys> index_keys,
blink::mojom::IDBTransaction::PutCallback callback,
Transaction* txn) {
DCHECK_EQ(this, txn);
TRACE_EVENT2("IndexedDB", "Database::PutOperation", "txn.id", id(), "size",
value.SizeEstimate());
DCHECK_NE(mode(), blink::mojom::IDBTransactionMode::ReadOnly);
bool key_was_generated = false;
in_flight_memory_ -= value.SizeEstimate();
DCHECK(in_flight_memory_.IsValid());
auto on_put_error = [&txn](blink::mojom::IDBTransaction::PutCallback callback,
blink::mojom::IDBException code,
const std::u16string& message) {
txn->IncrementNumErrorsSent();
std::move(callback).Run(
blink::mojom::IDBTransactionPutResult::NewErrorResult(
blink::mojom::IDBError::New(code, message)));
};
if (!connection()->database()->IsObjectStoreIdInMetadata(object_store_id)) {
on_put_error(std::move(callback), blink::mojom::IDBException::kUnknownError,
u"Bad request");
return Status::InvalidArgument("Invalid object_store_id.");
}
const blink::IndexedDBObjectStoreMetadata& object_store =
connection()->database()->GetObjectStoreMetadata(object_store_id);
DCHECK(object_store.auto_increment || key.IsValid());
if (put_mode != blink::mojom::IDBPutMode::CursorUpdate &&
object_store.auto_increment && !key.IsValid()) {
blink::IndexedDBKey auto_inc_key =
GenerateAutoIncrementKey(object_store_id);
key_was_generated = true;
if (!auto_inc_key.IsValid()) {
on_put_error(std::move(callback),
blink::mojom::IDBException::kConstraintError,
u"Maximum key generator value reached.");
return Status::OK();
}
key = std::move(auto_inc_key);
}
if (!key.IsValid()) {
return Status::InvalidArgument("Invalid key");
}
if (put_mode == blink::mojom::IDBPutMode::AddOnly) {
ASSIGN_OR_RETURN(
std::optional<BackingStore::RecordIdentifier> preexisting_record,
BackingStoreTransaction()->KeyExistsInObjectStore(object_store_id,
key));
if (preexisting_record) {
on_put_error(std::move(callback),
blink::mojom::IDBException::kConstraintError,
u"Key already exists in the object store.");
return Status::OK();
}
}
std::vector<std::unique_ptr<IndexWriter>> index_writers;
std::string error_message;
bool obeys_constraints = false;
bool backing_store_success = MakeIndexWriters(
this, object_store, key, key_was_generated, std::move(index_keys),
&index_writers, &error_message, &obeys_constraints);
if (!backing_store_success) {
on_put_error(std::move(callback), blink::mojom::IDBException::kUnknownError,
u"Internal error: backing store error updating index keys.");
return Status::OK();
}
if (!obeys_constraints) {
on_put_error(std::move(callback),
blink::mojom::IDBException::kConstraintError,
base::UTF8ToUTF16(error_message));
return Status::OK();
}
// Before this point, don't do any mutation. After this point, rollback the
// transaction in case of error.
ASSIGN_OR_RETURN(BackingStore::RecordIdentifier new_record,
BackingStoreTransaction()->PutRecord(object_store_id, key,
std::move(value)));
{
TRACE_EVENT1("IndexedDB", "Database::PutOperation.UpdateIndexes", "txn.id",
id());
for (const auto& writer : index_writers) {
writer->WriteIndexKeys(new_record, BackingStoreTransaction(),
object_store_id);
}
}
if (object_store.auto_increment &&
put_mode != blink::mojom::IDBPutMode::CursorUpdate &&
key.type() == blink::mojom::IDBKeyType::Number) {
TRACE_EVENT1("IndexedDB", "Database::PutOperation.AutoIncrement", "txn.id",
id());
// Maximum integer uniquely representable as ECMAScript number.
const double max_generator_value = 9007199254740992.0;
int64_t new_max = 1 + base::saturated_cast<int64_t>(floor(
std::min(key.number(), max_generator_value)));
// The key is a number that was either generated by the generator which now
// needs to be incremented (so `check_current` is false) or was
// user-supplied so we only conditionally use (and `check_current` is true).
IDB_RETURN_IF_ERROR(
BackingStoreTransaction()->MaybeUpdateKeyGeneratorCurrentNumber(
object_store_id, new_max, /*check_current=*/!key_was_generated));
}
{
TRACE_EVENT1("IndexedDB", "Database::PutOperation.Callbacks", "txn.id",
id());
std::move(callback).Run(
blink::mojom::IDBTransactionPutResult::NewKey(std::move(key)));
}
bucket_context()->delegate().on_content_changed.Run(
connection()->database()->name(), object_store.name);
return Status::OK();
}
void Transaction::Commit(int64_t num_errors_handled) {
if (!IsAcceptingRequests() || !connection()->IsConnected()) {
return;
}
num_errors_handled_ = num_errors_handled;
// Always allow empty or delete-only transactions.
if (preliminary_size_estimate_ <= 0) {
SetCommitFlag();
return;
}
bucket_context()->CheckCanUseDiskSpace(
preliminary_size_estimate_, base::BindOnce(&Transaction::OnQuotaCheckDone,
ptr_factory_.GetWeakPtr()));
}
void Transaction::OnQuotaCheckDone(bool allowed) {
// May have disconnected while quota check was pending.
if (!connection()->IsConnected()) {
return;
}
if (allowed) {
SetCommitFlag();
} else {
connection()->AbortTransactionAndTearDownOnError(
this, DatabaseError(blink::mojom::IDBException::kQuotaError));
}
}
uint64_t Transaction::CreateExternalObjects(
blink::mojom::IDBValuePtr& value,
std::vector<IndexedDBExternalObject>* external_objects) {
// Should only be called if there are external objects to process.
CHECK(!value->external_objects.empty());
base::CheckedNumeric<uint64_t> total_blob_size = 0;
external_objects->resize(value->external_objects.size());
for (size_t i = 0; i < value->external_objects.size(); ++i) {
auto& object = value->external_objects[i];
switch (object->which()) {
case blink::mojom::IDBExternalObject::Tag::kBlobOrFile: {
blink::mojom::IDBBlobInfoPtr& info = object->get_blob_or_file();
uint64_t size = info->size;
total_blob_size += size;
if (info->file) {
DCHECK_NE(info->size, IndexedDBExternalObject::kUnknownSize);
(*external_objects)[i] = IndexedDBExternalObject(
std::move(info->blob), info->file->name, info->mime_type,
info->file->last_modified, info->size);
} else {
(*external_objects)[i] = IndexedDBExternalObject(
std::move(info->blob), info->mime_type, info->size);
}
break;
}
case blink::mojom::IDBExternalObject::Tag::kFileSystemAccessToken:
(*external_objects)[i] = IndexedDBExternalObject(
std::move(object->get_file_system_access_token()));
break;
}
}
return total_blob_size.ValueOrDie();
}
Status Transaction::BlobWriteComplete(
BlobWriteResult result,
storage::mojom::WriteBlobToFileResult error) {
TRACE_EVENT0("IndexedDB", "Transaction::BlobWriteComplete");
if (state_ == FINISHED) { // aborted
return Status::OK();
}
DCHECK_EQ(state_, COMMITTING);
switch (result) {
case BlobWriteResult::kFailure: {
Status status = Abort(
DatabaseError(blink::mojom::IDBException::kDataError,
base::ASCIIToUTF16(base::StringPrintf(
"Failed to write blobs (%s)",
WriteBlobToFileResultToString(error).c_str()))));
if (!status.ok()) {
bucket_context_->OnDatabaseError(status, {});
}
// The result is ignored.
return Status::OK();
}
case BlobWriteResult::kRunPhaseTwoAsync:
ScheduleTask(base::BindOnce(&CommitPhaseTwoProxy));
bucket_context_->QueueRunTasks();
return Status::OK();
case BlobWriteResult::kRunPhaseTwoAndReturnResult: {
return CommitPhaseTwo();
}
}
NOTREACHED();
}
Status Transaction::DoPendingCommit() {
TRACE_EVENT1("IndexedDB", "Transaction::DoPendingCommit", "txn.id", id());
ResetTimeoutTimer();
// In multiprocess ports, front-end may have requested a commit but
// an abort has already been initiated asynchronously by the
// back-end.
if (state_ == FINISHED) {
return Status::OK();
}
DCHECK_NE(state_, COMMITTING);
is_commit_pending_ = true;
// Front-end has requested a commit, but this transaction is blocked by
// other transactions. The commit will be initiated when the transaction
// coordinator unblocks this transaction.
if (state_ != STARTED) {
return Status::OK();
}
// Front-end has requested a commit, but there may be tasks like
// create_index which are considered synchronous by the front-end
// but are processed asynchronously.
if (HasPendingTasks()) {
return Status::OK();
}
// If a transaction is being committed but it has sent more errors to the
// front end than have been handled at this point, the transaction should be
// aborted as it is unknown whether or not any errors unaccounted for will be
// properly handled.
if (num_errors_sent_ != num_errors_handled_) {
is_commit_pending_ = false;
return Abort(DatabaseError(blink::mojom::IDBException::kUnknownError));
}
SetState(COMMITTING);
Status s;
if (!used_) {
s = CommitPhaseTwo();
} else {
// CommitPhaseOne will call the callback synchronously if there are no blobs
// to write.
s = backing_store_transaction_->CommitPhaseOne(base::BindOnce(
[](base::WeakPtr<Transaction> transaction, BlobWriteResult result,
storage::mojom::WriteBlobToFileResult error) {
if (!transaction) {
return Status::OK();
}
return transaction->BlobWriteComplete(result, error);
},
ptr_factory_.GetWeakPtr()));
}
return s;
}
Status Transaction::CommitPhaseTwo() {
// Abort may have been called just as the blob write completed.
if (state_ == FINISHED) {
return Status::OK();
}
DCHECK_EQ(state_, COMMITTING);
std::optional scheduling_priority_at_last_state_change =
scheduling_priority_at_last_state_change_;
SetState(FINISHED);
Status s;
bool committed;
if (!used_) {
committed = true;
} else {
s = backing_store_transaction_->CommitPhaseTwo();
// This measurement includes the time it takes to commit to the backing
// store (i.e. LevelDB), not just the blobs.
const base::TimeDelta active_time =
base::Time::Now() - diagnostics_.start_time;
switch (mode_) {
case blink::mojom::IDBTransactionMode::ReadOnly:
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadOnly.TimeActive2", active_time);
if (scheduling_priority_at_last_state_change == 0) {
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadOnly.TimeActive2.Foreground",
active_time);
}
break;
case blink::mojom::IDBTransactionMode::ReadWrite:
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadWrite.TimeActive2", active_time);
if (scheduling_priority_at_last_state_change == 0) {
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.ReadWrite.TimeActive2.Foreground",
active_time);
}
break;
case blink::mojom::IDBTransactionMode::VersionChange:
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.VersionChange.TimeActive2",
active_time);
if (scheduling_priority_at_last_state_change == 0) {
base::UmaHistogramMediumTimes(
"WebCore.IndexedDB.Transaction.VersionChange.TimeActive2."
"Foreground",
active_time);
}
break;
default:
NOTREACHED();
}
committed = s.ok();
}
// Backing store resources (held via cursors) must be released
// before script callbacks are fired, as the script callbacks may
// release references and allow the backing store itself to be
// released, and order is critical.
CloseOpenCursors();
backing_store_transaction_->Reset();
// Transactions must also be marked as completed before the
// front-end is notified, as the transaction completion unblocks
// operations like closing connections.
locks_receiver_.locks.clear();
if (committed) {
{
TRACE_EVENT1("IndexedDB",
"Transaction::CommitPhaseTwo.TransactionCompleteCallbacks",
"txn.id", id());
connection()->callbacks()->OnComplete(*this);
}
if (mode() != blink::mojom::IDBTransactionMode::ReadOnly) {
const bool did_sync =
mode() == blink::mojom::IDBTransactionMode::VersionChange ||
durability_ == blink::mojom::IDBTransactionDurability::Strict;
bucket_context_->delegate().on_files_written.Run(did_sync);
}
return s;
}
DatabaseError error;
if (s.IndicatesDiskFull()) {
error =
DatabaseError(blink::mojom::IDBException::kQuotaError,
"Encountered disk full while committing transaction.");
} else {
error = DatabaseError(blink::mojom::IDBException::kUnknownError,
"Internal error committing transaction.");
}
connection()->callbacks()->OnAbort(*this, error);
return s;
}
std::tuple<Transaction::RunTasksResult, Status> Transaction::RunTasks() {
TRACE_EVENT1("IndexedDB", "Transaction::RunTasks", "txn.id", id());
DCHECK(!processing_event_queue_);
// May have been aborted.
if (aborted_) {
return {RunTasksResult::kAborted, Status::OK()};
}
if (IsTaskQueueEmpty() && !is_commit_pending_) {
return {RunTasksResult::kNotFinished, Status::OK()};
}
processing_event_queue_ = true;
if (!backing_store_transaction_begun_) {
backing_store_transaction_->Begin(std::move(locks_receiver_.locks));
backing_store_transaction_begun_ = true;
}
bool run_preemptive_queue =
!preemptive_task_queue_.empty() || pending_preemptive_events_ != 0;
TaskQueue* task_queue =
run_preemptive_queue ? &preemptive_task_queue_ : &task_queue_;
while (!task_queue->empty() && state_ != FINISHED) {
DCHECK(state_ == STARTED || state_ == COMMITTING) << state_;
Operation task(task_queue->pop());
Status result = std::move(task).Run(this);
if (!run_preemptive_queue) {
DCHECK(diagnostics_.tasks_completed < diagnostics_.tasks_scheduled);
++diagnostics_.tasks_completed;
NotifyOfIdbInternalsRelevantChange();
}
if (!result.ok()) {
processing_event_queue_ = false;
return {
RunTasksResult::kError,
result,
};
}
run_preemptive_queue =
!preemptive_task_queue_.empty() || pending_preemptive_events_ != 0;
// Event itself may change which queue should be processed next.
task_queue = run_preemptive_queue ? &preemptive_task_queue_ : &task_queue_;
}
// If there are no pending tasks, we haven't already committed/aborted,
// and the front-end requested a commit, it is now safe to do so.
if (!HasPendingTasks() && state_ == STARTED && is_commit_pending_) {
processing_event_queue_ = false;
// This can delete |this|.
Status result = DoPendingCommit();
if (!result.ok()) {
return {RunTasksResult::kError, result};
}
}
// The transaction may have been aborted while processing tasks.
if (state_ == FINISHED) {
processing_event_queue_ = false;
return {aborted_ ? RunTasksResult::kAborted : RunTasksResult::kCommitted,
Status::OK()};
}
DCHECK(state_ == STARTED || state_ == COMMITTING) << state_;
// Otherwise, start a timer in case the front-end gets wedged and never
// requests further activity.
if (!HasPendingTasks() && state_ == STARTED && g_inactivity_timeout_enabled) {
timeout_timer_.Start(FROM_HERE, kInactivityTimeoutPollPeriod,
base::BindRepeating(&Transaction::TimeoutFired,
ptr_factory_.GetWeakPtr()));
}
processing_event_queue_ = false;
return {RunTasksResult::kNotFinished, Status::OK()};
}
storage::mojom::IdbTransactionMetadataPtr Transaction::GetIdbInternalsMetadata()
const {
storage::mojom::IdbTransactionMetadataPtr info =
storage::mojom::IdbTransactionMetadata::New();
info->mode = static_cast<storage::mojom::IdbTransactionMode>(mode());
switch (state()) {
case Transaction::CREATED:
info->state = storage::mojom::IdbTransactionState::kBlocked;
break;
case Transaction::STARTED:
info->state = diagnostics().tasks_scheduled > 0
? storage::mojom::IdbTransactionState::kRunning
: storage::mojom::IdbTransactionState::kStarted;
break;
case Transaction::COMMITTING:
info->state = storage::mojom::IdbTransactionState::kCommitting;
break;
case Transaction::FINISHED:
info->state = storage::mojom::IdbTransactionState::kFinished;
break;
}
info->tid = id();
info->connection_id = connection()->id();
info->client_token = connection()->client_token().ToString();
info->age =
(base::Time::Now() - diagnostics().creation_time).InMillisecondsF();
if (diagnostics().start_time.InMillisecondsSinceUnixEpoch() > 0) {
info->runtime =
(base::Time::Now() - diagnostics().start_time).InMillisecondsF();
}
info->tasks_scheduled = diagnostics().tasks_scheduled;
info->tasks_completed = diagnostics().tasks_completed;
for (int64_t id : scope()) {
auto stores_it = database_->metadata().object_stores.find(id);
if (stores_it != database_->metadata().object_stores.end()) {
info->scope.emplace_back(stores_it->second.name);
}
}
return info;
}
void Transaction::NotifyOfIdbInternalsRelevantChange() {
// This metadata is included in the databases metadata, so call up the chain.
if (database_) {
database_->NotifyOfIdbInternalsRelevantChange();
}
}
void Transaction::TimeoutFired() {
if (!IsTransactionBlockingOtherClients(/*consider_priority=*/true)) {
return;
}
if (++timeout_strikes_ >= kMaxTimeoutStrikes) {
Status result =
Abort(DatabaseError(blink::mojom::IDBException::kTimeoutError,
u"Transaction timed out due to inactivity."));
if (!result.ok()) {
bucket_context_->OnDatabaseError(result, {});
}
ResetTimeoutTimer();
}
}
void Transaction::ResetTimeoutTimer() {
timeout_timer_.Stop();
timeout_strikes_ = 0;
}
void Transaction::SetState(State state) {
state_ = state;
if (connection_) {
scheduling_priority_at_last_state_change_ =
connection_->scheduling_priority();
} else {
scheduling_priority_at_last_state_change_ = std::nullopt;
}
NotifyOfIdbInternalsRelevantChange();
}
void Transaction::CloseOpenCursors() {
TRACE_EVENT1("IndexedDB", "Transaction::CloseOpenCursors", "txn.id", id());
// Cursor::Close() indirectly mutates |open_cursors_|, when it calls
// Transaction::UnregisterOpenCursor().
std::set<raw_ptr<Cursor, SetExperimental>> open_cursors =
std::move(open_cursors_);
open_cursors_.clear();
for (Cursor* cursor : open_cursors) {
cursor->Close();
}
}
std::vector<PartitionedLockManager::PartitionedLockRequest>
Transaction::BuildLockRequests() const {
// Locks for version change transactions are covered by `ConnectionRequest`.
DCHECK_NE(mode(), blink::mojom::IDBTransactionMode::VersionChange);
std::vector<PartitionedLockManager::PartitionedLockRequest> lock_requests;
lock_requests.reserve(1 + scope().size());
lock_requests.emplace_back(GetDatabaseLockId(database_->name()),
PartitionedLockManager::LockType::kShared);
const auto object_store_lock_type =
mode() == blink::mojom::IDBTransactionMode::ReadOnly
? PartitionedLockManager::LockType::kShared
: PartitionedLockManager::LockType::kExclusive;
for (int64_t object_store : scope()) {
lock_requests.emplace_back(
database_->backing_store_db()->GetLockId(object_store),
object_store_lock_type);
}
return lock_requests;
}
void Transaction::OnSchedulingPriorityUpdated(int new_priority) {
auto* lock_request_data = static_cast<LockRequestData*>(
locks_receiver_.GetUserData(LockRequestData::kKey));
DCHECK(lock_request_data);
lock_request_data->scheduling_priority = new_priority;
}
blink::IndexedDBKey Transaction::GenerateAutoIncrementKey(
int64_t object_store_id) {
ASSIGN_OR_RETURN(
int64_t current_number,
BackingStoreTransaction()->GetKeyGeneratorCurrentNumber(object_store_id),
[](auto) {
LOG(ERROR) << "Failed to GetKeyGeneratorCurrentNumber";
return blink::IndexedDBKey();
});
// Maximum integer uniquely representable as ECMAScript number.
const int64_t max_generator_value = 9007199254740992LL;
if (current_number < 0 || current_number > max_generator_value) {
return {};
}
return blink::IndexedDBKey(current_number, blink::mojom::IDBKeyType::Number);
}
} // namespace content::indexed_db
|