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
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_database.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key_path.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_metadata.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_object_store.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_test_helper.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_value.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h"
#include "third_party/blink/renderer/modules/indexeddb/mock_idb_database.h"
#include "third_party/blink/renderer/modules/indexeddb/mock_idb_transaction.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/testing/task_environment.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/url_loader_mock_factory.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "v8/include/v8.h"
namespace blink {
namespace {
class IDBTransactionTest : public testing::Test,
public ScopedMockOverlayScrollbars {
protected:
void SetUp() override {
url_loader_mock_factory_ = URLLoaderMockFactory::GetSingletonInstance();
WebURLResponse response;
response.SetCurrentRequestUrl(KURL("blob:"));
url_loader_mock_factory_->RegisterURLProtocol(WebString("blob"), response,
"");
}
void TearDown() override {
url_loader_mock_factory_->UnregisterAllURLsAndClearMemoryCache();
}
void BuildTransaction(V8TestingScope& scope,
MockIDBDatabase& mock_database,
MockIDBTransaction& mock_transaction_remote) {
auto* execution_context = scope.GetExecutionContext();
db_ = MakeGarbageCollected<IDBDatabase>(
execution_context, mojo::NullAssociatedReceiver(),
mock_database.BindNewEndpointAndPassDedicatedRemote(), /*priority=*/0);
IDBTransaction::TransactionMojoRemote transaction_remote(execution_context);
mojo::PendingAssociatedReceiver<mojom::blink::IDBTransaction> receiver =
transaction_remote.BindNewEndpointAndPassReceiver(
blink::scheduler::GetSingleThreadTaskRunnerForTesting());
receiver.EnableUnassociatedUsage();
mock_transaction_remote.Bind(std::move(receiver));
HashSet<String> transaction_scope = {"store"};
transaction_ = IDBTransaction::CreateNonVersionChange(
scope.GetScriptState(), std::move(transaction_remote), kTransactionId,
transaction_scope, mojom::IDBTransactionMode::ReadOnly,
mojom::IDBTransactionDurability::Relaxed, db_.Get());
IDBKeyPath store_key_path("primaryKey");
scoped_refptr<IDBObjectStoreMetadata> store_metadata = base::AdoptRef(
new IDBObjectStoreMetadata("store", kStoreId, store_key_path, true, 1));
store_ = MakeGarbageCollected<IDBObjectStore>(store_metadata, transaction_);
}
test::TaskEnvironment task_environment_;
raw_ptr<URLLoaderMockFactory> url_loader_mock_factory_;
Persistent<IDBDatabase> db_;
Persistent<IDBTransaction> transaction_;
Persistent<IDBObjectStore> store_;
ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
static constexpr int64_t kTransactionId = 1234;
static constexpr int64_t kStoreId = 5678;
};
const int64_t IDBTransactionTest::kTransactionId;
TEST_F(IDBTransactionTest, ContextDestroyedEarlyDeath) {
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
EXPECT_CALL(database_backend, OnDisconnect()).Times(1);
BuildTransaction(scope, database_backend, transaction_backend);
Persistent<GCedHeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
MakeGarbageCollected<GCedHeapHashSet<WeakMember<IDBTransaction>>>();
live_transactions->insert(transaction_);
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1u, live_transactions->size());
Persistent<IDBRequest> request =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
scope.PerformMicrotaskCheckpoint();
request.Clear(); // The transaction is holding onto the request.
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1u, live_transactions->size());
// This will generate an Abort() call to the back end which is dropped by the
// fake proxy, so an explicit OnAbort call is made.
scope.GetExecutionContext()->NotifyContextDestroyed();
transaction_->OnAbort(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "Aborted"));
transaction_->FlushForTesting();
transaction_.Clear();
store_.Clear();
database_backend.Flush();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(0U, live_transactions->size());
}
TEST_F(IDBTransactionTest, ContextDestroyedAfterDone) {
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
EXPECT_CALL(database_backend, OnDisconnect()).Times(1);
BuildTransaction(scope, database_backend, transaction_backend);
Persistent<GCedHeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
MakeGarbageCollected<GCedHeapHashSet<WeakMember<IDBTransaction>>>();
live_transactions->insert(transaction_);
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
Persistent<IDBRequest> request =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
scope.PerformMicrotaskCheckpoint();
request.Clear(); // The transaction is holding onto the request.
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
// This will generate an Abort() call to the back end which is dropped by the
// fake proxy, so an explicit OnAbort call is made.
scope.GetExecutionContext()->NotifyContextDestroyed();
transaction_->OnAbort(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "Aborted"));
transaction_->FlushForTesting();
transaction_.Clear();
store_.Clear();
database_backend.Flush();
EXPECT_EQ(1U, live_transactions->size());
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(0U, live_transactions->size());
}
TEST_F(IDBTransactionTest, ContextDestroyedWithQueuedResult) {
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
EXPECT_CALL(database_backend, OnDisconnect()).Times(1);
BuildTransaction(scope, database_backend, transaction_backend);
Persistent<GCedHeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
MakeGarbageCollected<GCedHeapHashSet<WeakMember<IDBTransaction>>>();
live_transactions->insert(transaction_);
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
Persistent<IDBRequest> request =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
scope.PerformMicrotaskCheckpoint();
request->HandleResponse(CreateIDBValueForTesting(scope.GetIsolate(), true));
request.Clear(); // The transaction is holding onto the request.
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
// This will generate an Abort() call to the back end which is dropped by the
// fake proxy, so an explicit OnAbort call is made.
scope.GetExecutionContext()->NotifyContextDestroyed();
transaction_->OnAbort(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "Aborted"));
transaction_->FlushForTesting();
transaction_.Clear();
store_.Clear();
database_backend.Flush();
url_loader_mock_factory_->ServeAsynchronousRequests();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(0U, live_transactions->size());
}
TEST_F(IDBTransactionTest, ContextDestroyedWithTwoQueuedResults) {
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
EXPECT_CALL(database_backend, OnDisconnect()).Times(1);
BuildTransaction(scope, database_backend, transaction_backend);
Persistent<GCedHeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
MakeGarbageCollected<GCedHeapHashSet<WeakMember<IDBTransaction>>>();
live_transactions->insert(transaction_);
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
Persistent<IDBRequest> request1 =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
Persistent<IDBRequest> request2 =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
scope.PerformMicrotaskCheckpoint();
request1->HandleResponse(CreateIDBValueForTesting(scope.GetIsolate(), true));
request2->HandleResponse(CreateIDBValueForTesting(scope.GetIsolate(), true));
request1.Clear(); // The transaction is holding onto the requests.
request2.Clear();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
// This will generate an Abort() call to the back end which is dropped by the
// fake proxy, so an explicit OnAbort call is made.
scope.GetExecutionContext()->NotifyContextDestroyed();
transaction_->OnAbort(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "Aborted"));
transaction_->FlushForTesting();
transaction_.Clear();
store_.Clear();
database_backend.Flush();
url_loader_mock_factory_->ServeAsynchronousRequests();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(0U, live_transactions->size());
}
TEST_F(IDBTransactionTest, DocumentShutdownWithQueuedAndBlockedResults) {
// This test covers the conditions of https://crbug.com/733642
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
EXPECT_CALL(database_backend, OnDisconnect()).Times(1);
{
// The database isn't actually closed until `scope` is destroyed, so create
// this object in a nested scope to allow mock expectations to be verified.
V8TestingScope scope;
BuildTransaction(scope, database_backend, transaction_backend);
Persistent<GCedHeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
MakeGarbageCollected<GCedHeapHashSet<WeakMember<IDBTransaction>>>();
live_transactions->insert(transaction_);
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
Persistent<IDBRequest> request1 =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
Persistent<IDBRequest> request2 =
IDBRequest::Create(scope.GetScriptState(), store_.Get(),
transaction_.Get(), IDBRequest::AsyncTraceState());
scope.PerformMicrotaskCheckpoint();
request1->HandleResponse(
CreateIDBValueForTesting(scope.GetIsolate(), true));
request2->HandleResponse(
CreateIDBValueForTesting(scope.GetIsolate(), false));
request1.Clear(); // The transaction is holding onto the requests.
request2.Clear();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
// This will generate an Abort() call to the back end which is dropped by
// the fake proxy, so an explicit OnAbort call is made.
scope.GetDocument().Shutdown();
transaction_->OnAbort(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "Aborted"));
transaction_->FlushForTesting();
transaction_.Clear();
store_.Clear();
url_loader_mock_factory_->ServeAsynchronousRequests();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(0U, live_transactions->size());
}
database_backend.Flush();
}
TEST_F(IDBTransactionTest, TransactionFinish) {
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
EXPECT_CALL(transaction_backend, Commit(0)).Times(1);
EXPECT_CALL(database_backend, OnDisconnect()).Times(1);
BuildTransaction(scope, database_backend, transaction_backend);
Persistent<GCedHeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
MakeGarbageCollected<GCedHeapHashSet<WeakMember<IDBTransaction>>>();
live_transactions->insert(transaction_);
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
scope.PerformMicrotaskCheckpoint();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
transaction_->FlushForTesting();
transaction_.Clear();
store_.Clear();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(1U, live_transactions->size());
// Stop the context, so events don't get queued (which would keep the
// transaction alive).
scope.GetExecutionContext()->NotifyContextDestroyed();
// Fire an abort to make sure this doesn't free the transaction during use.
// The test will not fail if it is, but ASAN would notice the error.
db_->Abort(kTransactionId, mojom::blink::IDBException::kAbortError,
"Aborted");
database_backend.Flush();
// OnAbort() should have cleared the transaction's reference to the database.
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_EQ(0U, live_transactions->size());
}
TEST_F(IDBTransactionTest, ValueSizeTest) {
// For testing use a much smaller maximum size to prevent allocating >100 MB
// of memory, which crashes on memory-constrained systems.
const size_t kMaxValueSizeForTesting = 10 * 1024 * 1024; // 10 MB
const Vector<char> value_data(kMaxValueSizeForTesting + 1);
auto value = std::make_unique<IDBValue>();
value->SetData(Vector<char>(value_data));
std::unique_ptr<IDBKey> key = IDBKey::CreateNumber(0);
const int64_t object_store_id = 2;
ASSERT_GT(value_data.size() + key->SizeEstimate(), kMaxValueSizeForTesting);
ThreadState::Current()->CollectAllGarbageForTesting();
bool got_error = false;
auto callback = WTF::BindOnce(
[](bool* got_error, mojom::blink::IDBTransactionPutResultPtr result) {
*got_error = result->is_error_result();
},
WTF::Unretained(&got_error));
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
BuildTransaction(scope, database_backend, transaction_backend);
transaction_->set_max_put_value_size_for_testing(kMaxValueSizeForTesting);
transaction_->Put(object_store_id, std::move(value), std::move(key),
mojom::IDBPutMode::AddOrUpdate, Vector<IDBIndexKeys>(),
std::move(callback));
EXPECT_TRUE(got_error);
}
TEST_F(IDBTransactionTest, KeyAndValueSizeTest) {
// For testing use a much smaller maximum size to prevent allocating >100 MB
// of memory, which crashes on memory-constrained systems.
const size_t kMaxValueSizeForTesting = 10 * 1024 * 1024; // 10 MB
const size_t kKeySize = 1024 * 1024;
const Vector<char> value_data(kMaxValueSizeForTesting - kKeySize);
auto value = std::make_unique<IDBValue>();
value->SetData(Vector<char>(value_data));
const int64_t object_store_id = 2;
// For this test, we want IDBKey::SizeEstimate() minus kKeySize to be the
// smallest value > 0. An IDBKey with a string has a size_estimate_ equal to
// kOverheadSize (~16) + (string.length * sizeof(UChar)). Create
// |kKeySize / sizeof(UChar)| characters in String.
const unsigned int number_of_chars = kKeySize / sizeof(UChar);
Vector<UChar> key_string_vector;
key_string_vector.ReserveInitialCapacity(number_of_chars);
key_string_vector.Fill(u'0', number_of_chars);
String key_string(key_string_vector);
DCHECK_EQ(key_string.length(), number_of_chars);
std::unique_ptr<IDBKey> key = IDBKey::CreateString(key_string);
DCHECK_EQ(value_data.size(), kMaxValueSizeForTesting - kKeySize);
DCHECK_GT(key->SizeEstimate() - kKeySize, static_cast<size_t>(0));
DCHECK_GT(value_data.size() + key->SizeEstimate(), kMaxValueSizeForTesting);
ThreadState::Current()->CollectAllGarbageForTesting();
bool got_error = false;
auto callback = WTF::BindOnce(
[](bool* got_error, mojom::blink::IDBTransactionPutResultPtr result) {
*got_error = result->is_error_result();
},
WTF::Unretained(&got_error));
V8TestingScope scope;
MockIDBDatabase database_backend;
MockIDBTransaction transaction_backend;
BuildTransaction(scope, database_backend, transaction_backend);
transaction_->set_max_put_value_size_for_testing(kMaxValueSizeForTesting);
transaction_->Put(object_store_id, std::move(value), std::move(key),
mojom::IDBPutMode::AddOrUpdate, Vector<IDBIndexKeys>(),
std::move(callback));
EXPECT_TRUE(got_error);
}
} // namespace
} // namespace blink
|