diff --git a/database/src/desktop/database_desktop.cc b/database/src/desktop/database_desktop.cc index a7e0a5e544..71167f4c3e 100644 --- a/database/src/desktop/database_desktop.cc +++ b/database/src/desktop/database_desktop.cc @@ -14,10 +14,15 @@ #include "database/src/desktop/database_desktop.h" +#include #include +#include +#include #include #include #include +#include +#include #include "app/src/app_common.h" #include "app/src/assert.h" @@ -43,6 +48,40 @@ namespace internal { Mutex g_database_reference_constructor_mutex; // NOLINT +namespace { + +struct AppPersistenceState { + explicit AppPersistenceState(App* app) : app(app) {} + App* app; + std::unordered_map by_url; +}; + +std::string NormalizeDatabaseUrl(const std::string& url) { + ParseUrl parser; + if (parser.Parse(url) != ParseUrl::kParseOk) { + return url; + } + std::string normalized_host = parser.hostname; + std::transform( + normalized_host.begin(), normalized_host.end(), normalized_host.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return std::string(parser.secure ? "https://" : "http://") + normalized_host; +} + +// Leaf lock guarding GetPersistenceEnabledMap(). Never acquire another lock +// while holding g_persistence_enabled_mutex. Intentionally leaked so it +// outlives static teardown. +Mutex* g_persistence_enabled_mutex = new Mutex(); + +std::unordered_map>* +GetPersistenceEnabledMap() { + static auto* persistence_enabled_map = + new std::unordered_map>(); + return persistence_enabled_map; +} + +} // namespace + SingleValueListener::SingleValueListener(DatabaseInternal* database, const QuerySpec& query_spec, ReferenceCountedFutureImpl* future, @@ -79,6 +118,21 @@ DatabaseInternal::DatabaseInternal(App* app, const char* url) assert(app); assert(url); + { + // Restore persistence_enabled_ for this (App, URL) if it was configured + // on a prior Database instance. + MutexLock lock(*g_persistence_enabled_mutex); + auto* persistence_map = GetPersistenceEnabledMap(); + auto app_it = persistence_map->find(app_); + if (app_it != persistence_map->end()) { + const auto& by_url = app_it->second->by_url; + auto url_it = by_url.find(NormalizeDatabaseUrl(database_url_)); + if (url_it != by_url.end()) { + persistence_enabled_ = url_it->second; + } + } + } + // Spin up the token auto-update thread in Auth. app_->function_registry()->CallFunction( ::firebase::internal::FnAuthStartTokenListener, app_, nullptr, nullptr); @@ -180,10 +234,38 @@ const char* DatabaseInternal::GetSdkVersion() { } void DatabaseInternal::SetPersistenceEnabled(bool enabled) { - MutexLock lock(repo_mutex_); - // Only set persistence if the repo has not yet been initialized. - if (!repo_) { + AppPersistenceState* state_to_register = nullptr; + { + MutexLock lock(repo_mutex_); + // Only set persistence if the repo has not yet been initialized. + if (repo_) { + return; + } persistence_enabled_ = enabled; + MutexLock persistence_lock(*g_persistence_enabled_mutex); + auto* persistence_map = GetPersistenceEnabledMap(); + auto it = persistence_map->find(app_); + if (it == persistence_map->end()) { + auto state = std::make_unique(app_); + state_to_register = state.get(); + it = persistence_map->emplace(app_, std::move(state)).first; + } + it->second->by_url[NormalizeDatabaseUrl(database_url_)] = enabled; + } + + // Register cleanup outside repo_mutex_ and g_persistence_enabled_mutex so + // CleanupNotifier::CleanupAll() (which holds its own mutex while invoking + // callbacks) cannot invert lock order with g_persistence_enabled_mutex. + if (state_to_register != nullptr) { + CleanupNotifier* app_notifier = CleanupNotifier::FindByOwner(app_); + if (app_notifier != nullptr) { + app_notifier->RegisterObject(state_to_register, [](void* object) { + auto* state = static_cast(object); + App* app = state->app; + MutexLock lock(*g_persistence_enabled_mutex); + GetPersistenceEnabledMap()->erase(app); + }); + } } } diff --git a/database/src/desktop/database_desktop.h b/database/src/desktop/database_desktop.h index 6dc991111d..7cae5fb236 100644 --- a/database/src/desktop/database_desktop.h +++ b/database/src/desktop/database_desktop.h @@ -94,6 +94,8 @@ class DatabaseInternal { void SetPersistenceEnabled(bool enabled); + bool persistence_enabled() const { return persistence_enabled_; } + // Set the logging verbosity. void set_log_level(LogLevel log_level); diff --git a/database/src/desktop/persistence/level_db_persistence_storage_engine.cc b/database/src/desktop/persistence/level_db_persistence_storage_engine.cc index fca50038b8..16d15f28a0 100644 --- a/database/src/desktop/persistence/level_db_persistence_storage_engine.cc +++ b/database/src/desktop/persistence/level_db_persistence_storage_engine.cc @@ -409,11 +409,13 @@ static void VariantAddCachedValue(Variant* variant, const Path& path, for (const std::string& directory : path.GetDirectories()) { // Ensure we're operating on a map. if (!variant->is_map()) { - // Special case: If we are adding a priority, then ensure we do not blow - // away the value, which at this point will be directly in the - // variant and not in a .value field. Note that values will never be - // stored in a .value peudofield. - if (IsPriorityKey(directory)) { + // Special case: If we are adding a priority to an existing scalar value, + // ensure we do not blow away the value, which at this point will be + // directly in the variant and not in a .value field. Note that values + // will never be stored in a .value pseudofield. If the variant is null, + // this is a map node whose .priority key sorted before its child keys, + // so initialize it as an empty map instead of wrapping Null in .value. + if (IsPriorityKey(directory) && !variant->is_null()) { *variant = std::map{ std::make_pair(kValueKey, std::move(*variant)), }; diff --git a/database/tests/CMakeLists.txt b/database/tests/CMakeLists.txt index d498817f4d..fbc29d7540 100644 --- a/database/tests/CMakeLists.txt +++ b/database/tests/CMakeLists.txt @@ -200,6 +200,16 @@ firebase_cpp_cc_test( firebase_testing ) +firebase_cpp_cc_test( + firebase_rtdb_desktop_level_db_persistence_storage_engine_test + SOURCES + desktop/persistence/level_db_persistence_storage_engine_test.cc + DEPENDS + firebase_database + firebase_testing + leveldb +) + firebase_cpp_cc_test( firebase_rtdb_desktop_flatbuffer_conversion_test SOURCES @@ -327,6 +337,16 @@ firebase_cpp_cc_test( firebase_testing ) +firebase_cpp_cc_test( + firebase_rtdb_desktop_database_desktop_test + SOURCES + desktop/database_desktop_test.cc + DEPENDS + firebase_app_for_testing + firebase_database + firebase_testing +) + firebase_cpp_cc_test( firebase_rtdb_common_database_reference_test SOURCES diff --git a/database/tests/desktop/database_desktop_test.cc b/database/tests/desktop/database_desktop_test.cc new file mode 100644 index 0000000000..12424ff1a9 --- /dev/null +++ b/database/tests/desktop/database_desktop_test.cc @@ -0,0 +1,225 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "database/src/desktop/database_desktop.h" + +#include + +#include "app/src/include/firebase/app.h" +#include "app/tests/include/firebase/app_for_testing.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace database { +namespace internal { +namespace { + +constexpr char kDefaultDatabaseUrl[] = "https://abc-xyz-123.firebaseio.com"; + +class DatabaseDesktopTest : public ::testing::Test { + protected: + void SetUp() override { + AppOptions options = firebase::testing::MockAppOptions(); + options.set_database_url(kDefaultDatabaseUrl); + app_.reset(firebase::testing::CreateApp(options)); + } + + void TearDown() override { app_.reset(); } + + std::unique_ptr app_; +}; + +TEST_F(DatabaseDesktopTest, PersistenceEnabledDefaultsToFalse) { + DatabaseInternal db(app_.get()); + EXPECT_FALSE(db.persistence_enabled()); +} + +TEST_F(DatabaseDesktopTest, PersistenceEnabledPersistsAcrossInstances) { + { + DatabaseInternal db(app_.get()); + EXPECT_FALSE(db.persistence_enabled()); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + } + + // A new DatabaseInternal instance for the same App and URL should retain + // persistence_enabled_ = true. + { + DatabaseInternal db(app_.get()); + EXPECT_TRUE(db.persistence_enabled()); + } +} + +TEST_F(DatabaseDesktopTest, SetPersistenceEnabledFalseOverridesTrue) { + { + DatabaseInternal db(app_.get()); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + } + { + DatabaseInternal db(app_.get()); + EXPECT_TRUE(db.persistence_enabled()); + db.SetPersistenceEnabled(false); + EXPECT_FALSE(db.persistence_enabled()); + } + { + DatabaseInternal db(app_.get()); + EXPECT_FALSE(db.persistence_enabled()); + } +} + +TEST_F(DatabaseDesktopTest, PersistenceEnabledNormalizesUrls) { + // Set with trailing slash and uppercase host. + { + DatabaseInternal db(app_.get(), "https://ABC-XYZ-123.firebaseio.com/"); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Default URL (from AppOptions) should match. + { + DatabaseInternal db(app_.get()); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Explicit URL without trailing slash should match. + { + DatabaseInternal db(app_.get(), "https://abc-xyz-123.firebaseio.com"); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Omitted scheme defaults to https:// in ParseUrl and should match. + { + DatabaseInternal db(app_.get(), "abc-xyz-123.firebaseio.com"); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Subpath on the same host should normalize to the same host URL. + { + DatabaseInternal db(app_.get(), "https://abc-xyz-123.firebaseio.com/child"); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Different scheme (http:// vs https://) should NOT match. + { + DatabaseInternal db(app_.get(), "http://abc-xyz-123.firebaseio.com"); + EXPECT_FALSE(db.persistence_enabled()); + } +} + +TEST_F(DatabaseDesktopTest, PersistenceEnabledInvalidUrlFallback) { + { + DatabaseInternal db(app_.get(), "not-a-valid-url"); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + } + { + DatabaseInternal db(app_.get(), "not-a-valid-url"); + EXPECT_TRUE(db.persistence_enabled()); + } + { + DatabaseInternal db(app_.get(), "other-invalid-url"); + EXPECT_FALSE(db.persistence_enabled()); + } +} + +TEST_F(DatabaseDesktopTest, PersistenceEnabledIsolatedAcrossAppsAndUrls) { + AppOptions options = firebase::testing::MockAppOptions(); + options.set_database_url(kDefaultDatabaseUrl); + std::unique_ptr second_app( + firebase::testing::CreateApp(options, "second_app")); + + { + DatabaseInternal db(app_.get(), "https://db-one.firebaseio.com"); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Same App, different URL should remain false. + { + DatabaseInternal db(app_.get(), "https://db-two.firebaseio.com"); + EXPECT_FALSE(db.persistence_enabled()); + } + + // Different App, same URL should remain false. + { + DatabaseInternal db(second_app.get(), "https://db-one.firebaseio.com"); + EXPECT_FALSE(db.persistence_enabled()); + } +} + +TEST_F(DatabaseDesktopTest, SetPersistenceEnabledIsNoOpAfterRepoInitialized) { + // Use an unparseable URL so Repo::Repo returns early without spinning up a + // network connection or writing to disk, while still initializing repo_. + constexpr char kLocalOnlyUrl[] = "invalid-url-for-repo-init"; + + // Case 1: persistence enabled -> init repo -> attempt to disable -> no-op. + { + DatabaseInternal db(app_.get(), kLocalOnlyUrl); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + db.GetReference(); + ASSERT_NE(db.repo(), nullptr); + + db.SetPersistenceEnabled(false); + EXPECT_TRUE(db.persistence_enabled()); + } + { + DatabaseInternal db(app_.get(), kLocalOnlyUrl); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Case 2: persistence disabled -> init repo -> attempt to enable -> no-op. + constexpr char kLocalOnlyUrl2[] = "invalid-url-for-repo-init-2"; + { + DatabaseInternal db(app_.get(), kLocalOnlyUrl2); + EXPECT_FALSE(db.persistence_enabled()); + db.GetReference(); + ASSERT_NE(db.repo(), nullptr); + + db.SetPersistenceEnabled(true); + EXPECT_FALSE(db.persistence_enabled()); + } + { + DatabaseInternal db(app_.get(), kLocalOnlyUrl2); + EXPECT_FALSE(db.persistence_enabled()); + } +} + +TEST_F(DatabaseDesktopTest, PersistenceEnabledClearedWhenAppDestroyed) { + AppOptions options = firebase::testing::MockAppOptions(); + options.set_database_url(kDefaultDatabaseUrl); + + { + std::unique_ptr temp_app( + firebase::testing::CreateApp(options, "ephemeral_app")); + DatabaseInternal db(temp_app.get()); + db.SetPersistenceEnabled(true); + EXPECT_TRUE(db.persistence_enabled()); + } + + // Recreating an App with the same name must start with fresh persistence + // state, matching Android and iOS App lifecycle semantics. + { + std::unique_ptr recreated_app( + firebase::testing::CreateApp(options, "ephemeral_app")); + DatabaseInternal db(recreated_app.get()); + EXPECT_FALSE(db.persistence_enabled()); + } +} + +} // namespace +} // namespace internal +} // namespace database +} // namespace firebase diff --git a/database/tests/desktop/persistence/level_db_persistence_storage_engine_test.cc b/database/tests/desktop/persistence/level_db_persistence_storage_engine_test.cc index d8a6ca66e8..f420cc930a 100644 --- a/database/tests/desktop/persistence/level_db_persistence_storage_engine_test.cc +++ b/database/tests/desktop/persistence/level_db_persistence_storage_engine_test.cc @@ -14,15 +14,19 @@ #include "database/src/desktop/persistence/level_db_persistence_storage_engine.h" +#include #include #include #include +#include #include "app/src/logger.h" #include "app/src/variant_util.h" #include "database/src/desktop/persistence/flatbuffer_conversions.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" -#include "testing/base/public/gmock.h" +#include "leveldb/db.h" +#include "leveldb/options.h" using testing::Eq; using testing::Pointwise; @@ -32,36 +36,22 @@ namespace database { namespace internal { namespace { -// TODO(amablue): Consider refactoring this into a common location. -#if defined(_WIN32) -static const char kDirectorySeparator[] = "\\"; -#else -static const char kDirectorySeparator[] = "/"; -#endif // defined(_WIN32) - -static std::string GetTestTmpDir(const char test_namespace[]) { -#if defined(_WIN32) - char buf[MAX_PATH + 1]; - if (GetEnvironmentVariableA("TEST_TMPDIR", buf, sizeof(buf))) { - return std::string(buf) + kDirectorySeparator + test_namespace; - } -#else - // Linux and OS X should either have the TEST_TMPDIR environment variable set. - if (const char* value = getenv("TEST_TMPDIR")) { - return std::string(value) + kDirectorySeparator + test_namespace; - } -#endif // defined(_WIN32) - // If we weren't able to get TEST_TMPDIR, just use a subdirectory. - return test_namespace; +static std::string GetTestTmpDir(const ::testing::TestInfo* test_info) { + return testing::TempDir() + "level_db_persistence_storage_engine_test_" + + test_info->test_suite_name() + "_" + test_info->name(); } TEST(LevelDbPersistenceStorageEngine, ConstructorBasic) { - const std::string kDatabaseFilename = GetTestTmpDir(test_info_->name()); + const std::string kDatabaseFilename = GetTestTmpDir(test_info_); + leveldb::DestroyDB(kDatabaseFilename, leveldb::Options()); // Just ensure that nothing crashes. - SystemLogger logger; - LevelDbPersistenceStorageEngine engine(&logger); - engine.Initialize(kDatabaseFilename); + { + SystemLogger logger; + LevelDbPersistenceStorageEngine engine(&logger); + engine.Initialize(kDatabaseFilename); + } + leveldb::DestroyDB(kDatabaseFilename, leveldb::Options()); } class LevelDbPersistenceStorageEngineTest : public ::testing::Test { @@ -70,13 +60,21 @@ class LevelDbPersistenceStorageEngineTest : public ::testing::Test { engine_ = new LevelDbPersistenceStorageEngine(&logger_); } - void TearDown() override { delete engine_; } + void TearDown() override { + delete engine_; + engine_ = nullptr; + if (!database_path_.empty()) { + leveldb::DestroyDB(database_path_, leveldb::Options()); + } + } // All tests should start with this. This sets the path Level DB should read // from and write to, and caches that path so that when we re-start Level DB // we have the path we used on the previous run. - void InitializeLevelDb(const std::string& test_name) { - database_path_ = GetTestTmpDir(test_name.c_str()); + void InitializeLevelDb(const std::string& /*test_name*/) { + database_path_ = + GetTestTmpDir(::testing::UnitTest::GetInstance()->current_test_info()); + leveldb::DestroyDB(database_path_, leveldb::Options()); engine_->Initialize(database_path_); } @@ -86,8 +84,8 @@ class LevelDbPersistenceStorageEngineTest : public ::testing::Test { template void RunTwice(const Func& func) { func(); - TearDown(); - SetUp(); + delete engine_; + engine_ = new LevelDbPersistenceStorageEngine(&logger_); engine_->Initialize(database_path_); func(); } @@ -249,6 +247,122 @@ TEST_F(LevelDbPersistenceStorageEngineTest, OverwriteServerCache) { }); } +TEST_F(LevelDbPersistenceStorageEngineTest, + OverwriteServerCacheMapWithPriorityAndLaterKeys) { + InitializeLevelDb(test_info_->name()); + + // ".priority" sorts lexicographically before child keys like "subkey" and + // "value", and after keys starting with '-' (e.g., push IDs). Reconstructing + // maps from LevelDB must not wrap the empty Variant::Null() placeholder into + // {".value": Null}, while scalars with ".priority" (including falsy values + // like 0, false, and "") must preserve their {".value", ".priority"} form. + // clang-format off + Variant data = std::map{ + std::make_pair("cranberry", std::map{ + std::make_pair(".priority", 100), + std::make_pair("subkey", 500), + std::make_pair("value", 9), + }), + std::make_pair("mixed_order", std::map{ + std::make_pair("-push_id_before_dot", "first"), + std::make_pair(".priority", 200), + std::make_pair("after_dot", "second"), + }), + std::make_pair("nested", std::map{ + std::make_pair(".priority", 1), + std::make_pair("inner", std::map{ + std::make_pair(".priority", 2), + std::make_pair("child", "val"), + std::make_pair("scalar_child", std::map{ + std::make_pair(".value", 123), + std::make_pair(".priority", "p"), + }), + }), + }), + std::make_pair("scalar_with_priority", std::map{ + std::make_pair(".value", "hello"), + std::make_pair(".priority", 42), + }), + std::make_pair("zero_with_priority", std::map{ + std::make_pair(".value", 0), + std::make_pair(".priority", 1), + }), + std::make_pair("false_with_priority", std::map{ + std::make_pair(".value", false), + std::make_pair(".priority", 2), + }), + std::make_pair("empty_string_with_priority", std::map{ + std::make_pair(".value", ""), + std::make_pair(".priority", 3), + }), + }; + // clang-format on + + engine_->BeginTransaction(); + engine_->OverwriteServerCache(Path(), data); + engine_->SetTransactionSuccessful(); + engine_->EndTransaction(); + + RunTwice([this, &data]() { + EXPECT_EQ(engine_->ServerCache(Path()), data); + EXPECT_EQ(engine_->ServerCache(Path("cranberry")), + data.map().at("cranberry")); + EXPECT_EQ(engine_->ServerCache(Path("mixed_order")), + data.map().at("mixed_order")); + EXPECT_EQ(engine_->ServerCache(Path("nested")), data.map().at("nested")); + EXPECT_EQ(engine_->ServerCache(Path("nested/inner")), + data.map().at("nested").map().at("inner")); + EXPECT_EQ( + engine_->ServerCache(Path("nested/inner/scalar_child")), + data.map().at("nested").map().at("inner").map().at("scalar_child")); + EXPECT_EQ(engine_->ServerCache(Path("scalar_with_priority")), + data.map().at("scalar_with_priority")); + EXPECT_EQ(engine_->ServerCache(Path("zero_with_priority")), + data.map().at("zero_with_priority")); + EXPECT_EQ(engine_->ServerCache(Path("false_with_priority")), + data.map().at("false_with_priority")); + EXPECT_EQ(engine_->ServerCache(Path("empty_string_with_priority")), + data.map().at("empty_string_with_priority")); + }); +} + +TEST_F(LevelDbPersistenceStorageEngineTest, + OverwriteServerCachePriorityScalarAndMapTransitions) { + InitializeLevelDb(test_info_->name()); + + // clang-format off + Variant scalar_with_priority = std::map{ + std::make_pair(".value", "initial"), + std::make_pair(".priority", 10), + }; + Variant map_with_priority = std::map{ + std::make_pair(".priority", 20), + std::make_pair("child", "value"), + }; + // clang-format on + + // Scalar with priority -> overwrite with map with priority. + engine_->BeginTransaction(); + engine_->OverwriteServerCache(Path("node"), scalar_with_priority); + engine_->OverwriteServerCache(Path("node"), map_with_priority); + engine_->SetTransactionSuccessful(); + engine_->EndTransaction(); + + RunTwice([this, &map_with_priority]() { + EXPECT_EQ(engine_->ServerCache(Path("node")), map_with_priority); + }); + + // Map with priority -> overwrite with scalar with priority. + engine_->BeginTransaction(); + engine_->OverwriteServerCache(Path("node"), scalar_with_priority); + engine_->SetTransactionSuccessful(); + engine_->EndTransaction(); + + RunTwice([this, &scalar_with_priority]() { + EXPECT_EQ(engine_->ServerCache(Path("node")), scalar_with_priority); + }); +} + TEST_F(LevelDbPersistenceStorageEngineTest, OverwriteServerCache_Overwrite) { InitializeLevelDb(test_info_->name()); @@ -388,8 +502,8 @@ TEST_F(LevelDbPersistenceStorageEngineTest, ServerCacheEstimatedSizeInBytes) { engine_->EndTransaction(); RunTwice([this]() { - uint64 result = engine_->ServerCacheEstimatedSizeInBytes(); - uint64 expected = 1024 + strlen("aaa"); + uint64_t result = engine_->ServerCacheEstimatedSizeInBytes(); + uint64_t expected = 1024 + strlen("aaa"); // This is only an estimate, so as long as we're within a few bytes it's // okay. diff --git a/release_build_files/readme.md b/release_build_files/readme.md index 4c99e1ee91..4988efa008 100644 --- a/release_build_files/readme.md +++ b/release_build_files/readme.md @@ -618,6 +618,12 @@ code. - General (Desktop): Fixed Auth and App Check staying registered with their `App` after being deleted. Previously a deleted `AppCheck` instance could be silently re-created by other products using the same `App`. + - Database (Desktop): Fixed `Database::set_persistence_enabled()` not being + preserved across recreated `Database` instances for the same `App` and + database URL. + - Database (Desktop): Fixed cached objects with priorities set (via + `SetPriority()` or `SetValueAndPriority()`) being read back from the + offline persistence cache as corrupted or null values. ### 14.2.0 - Changes