diff --git a/database/CMakeLists.txt b/database/CMakeLists.txt index a6b07b3ddf..90a82e5aa4 100644 --- a/database/CMakeLists.txt +++ b/database/CMakeLists.txt @@ -97,6 +97,7 @@ set(desktop_SRCS src/desktop/connection/connection.cc src/desktop/connection/host_info.cc src/desktop/connection/persistent_connection.cc + src/desktop/connection/retry_helper.cc src/desktop/connection/util_connection.cc src/desktop/connection/web_socket_client_impl.cc src/desktop/core/cache_policy.cc diff --git a/database/src/desktop/connection/persistent_connection.cc b/database/src/desktop/connection/persistent_connection.cc index 5e2ef2e55c..156d9cacff 100644 --- a/database/src/desktop/connection/persistent_connection.cc +++ b/database/src/desktop/connection/persistent_connection.cc @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -43,6 +44,13 @@ Error kErrorDataStale = static_cast(-1); namespace internal { namespace connection { +namespace { + +constexpr std::chrono::milliseconds kSuccessfulConnectionEstablishedDelay( + 30000); + +} // namespace + const char* PersistentConnection::kRequestError = "error"; const char* PersistentConnection::kRequestQueries = "q"; const char* PersistentConnection::kRequestTag = "t"; @@ -106,7 +114,10 @@ PersistentConnection::PersistentConnection( App* app, const HostInfo& info, PersistentConnectionEventHandler* event_handler, scheduler::Scheduler* scheduler, Logger* logger) - : app_(app), + : auth_token_future_status_(kInvalidTokenFuture), + app_check_token_future_status_(kInvalidTokenFuture), + pending_get_token_attempt_(0), + app_(app), safe_this_(this), scheduler_(scheduler), host_info_(info), @@ -114,12 +125,14 @@ PersistentConnection::PersistentConnection( realtime_(nullptr), connection_state_(kDisconnected), is_first_connection_(true), + current_get_token_attempt_(0), invalid_auth_token_count(0), next_request_id_(0), force_auth_refresh_(false), next_listen_id_(0), next_write_id_(0), - logger_(logger) { + logger_(logger), + retry_helper_(scheduler, logger) { FIREBASE_DEV_ASSERT(app); FIREBASE_DEV_ASSERT(scheduler); FIREBASE_DEV_ASSERT(event_handler_); @@ -134,15 +147,10 @@ PersistentConnection::~PersistentConnection() { // Clear safe reference immediately so that scheduled callback can skip // executing code which requires reference to this. safe_this_.ClearReference(); + retry_helper_.Cancel(); // Clear pending token futures - { - MutexLock future_lock(pending_token_future_mutex_); - pending_auth_token_future_ = Future(); - auth_token_future_status_ = kInvalidTokenFuture; - pending_app_check_token_future_ = Future(); - app_check_token_future_status_ = kInvalidTokenFuture; - } + ClearPendingTokenFutures(); // Destroy the client so that no more event will be triggered from this point. realtime_.reset(nullptr); @@ -186,6 +194,7 @@ void PersistentConnection::OnReady(int64_t timestamp, SAFE_REFERENCE_RETURN_VOID_IF_INVALID(ThisRefLock, lock, safe_this_); logger_->LogDebug("%s OnReady", log_id_.c_str()); + last_connection_established_time_ = std::chrono::steady_clock::now(); // Trigger OnServerInfoUpdate based on timestamp delta logger_->LogDebug("%s Handle timestamp: %lld in ms", log_id_.c_str(), @@ -318,8 +327,20 @@ void PersistentConnection::OnDisconnect(Connection::DisconnectReason reason) { CancelSentTransactions(); if (ShouldReconnect()) { + bool last_connection_was_successful = false; + if (last_connection_established_time_.has_value()) { + auto elapsed = + std::chrono::steady_clock::now() - *last_connection_established_time_; + last_connection_was_successful = + elapsed > kSuccessfulConnectionEstablishedDelay; + } + if (reason == Connection::kDisconnectReasonServerReset || + last_connection_was_successful) { + retry_helper_.SignalSuccess(); + } TryScheduleReconnect(); } + last_connection_established_time_.reset(); // Trigger OnDisconnect event event_handler_->OnDisconnect(); @@ -487,17 +508,17 @@ void PersistentConnection::InterruptInternal(InterruptReason reason) { static_cast(reason)); interrupt_reasons_.insert(reason); + ++current_get_token_attempt_; + ClearPendingTokenFutures(); if (realtime_) { realtime_->Close(); realtime_.reset(nullptr); } else { - // TODO(chkuang): Implement Retry - // retryHelper.cancel(); connection_state_ = kDisconnected; } - // TODO(chkuang): Implement Retry - // retryHelper.signalSuccess(); + retry_helper_.Cancel(); + retry_helper_.SignalSuccess(); } void PersistentConnection::ResumeInternal(InterruptReason reason) { @@ -521,179 +542,213 @@ void PersistentConnection::TryScheduleReconnect() { force_auth_refresh_ = false; logger_->LogDebug("%s Scheduling connection attempt", log_id_.c_str()); - scheduler_->Schedule(new callback::CallbackValue2( - safe_this_, force_refresh, [](ThisRef ref, bool force_refresh) { - ThisRefLock lock(&ref); - auto* connection = lock.GetReference(); - if (!connection) return; - // TODO(chkuang): Implement Exponential Backoff Retry - connection->connection_state_ = kGettingToken; - connection->logger_->LogDebug("%s Trying to fetch auth token", - connection->log_id_.c_str()); - - // Get Token Asynchronously to make sure the token is not expired. - Future auth_future; - bool auth_succeeded = - connection->app_->function_registry()->CallFunction( - ::firebase::internal::FnAuthGetTokenAsync, connection->app_, - &force_refresh, &auth_future); - Future app_check_future; - bool app_check_succeeded = - connection->app_->function_registry()->CallFunction( - ::firebase::internal::FnAppCheckGetTokenAsync, connection->app_, - nullptr, &app_check_future); - - // Check that the futures are actually valid (assuming they were made) - auth_succeeded &= auth_future.status() != kFutureStatusInvalid; - app_check_succeeded &= - app_check_future.status() != kFutureStatusInvalid; - - if (auth_succeeded || app_check_succeeded) { - // If either succeeded, we need to wait for the successful one(s) to - // finish. - MutexLock future_lock(connection->pending_token_future_mutex_); - if (auth_succeeded) { - connection->pending_auth_token_future_ = auth_future; - connection->auth_token_future_status_ = kWaitingForTokenFuture; - } else { - connection->pending_auth_token_future_ = Future(); - connection->auth_token_future_status_ = kInvalidTokenFuture; - } - - if (app_check_succeeded) { - connection->pending_app_check_token_future_ = app_check_future; - connection->app_check_token_future_status_ = kWaitingForTokenFuture; - } else { - connection->pending_app_check_token_future_ = Future(); - connection->app_check_token_future_status_ = kInvalidTokenFuture; - } + ThisRef safe_ref = safe_this_; + retry_helper_.Retry([safe_ref, force_refresh]() mutable { + ThisRefLock lock(&safe_ref); + auto* connection = lock.GetReference(); + if (!connection) return; + if (!connection->ShouldReconnect()) return; + + FIREBASE_DEV_ASSERT(connection->connection_state_ == kDisconnected); + connection->connection_state_ = kGettingToken; + const uint64_t attempt = ++connection->current_get_token_attempt_; + connection->logger_->LogDebug("%s Trying to fetch auth token", + connection->log_id_.c_str()); + + // Get Token Asynchronously to make sure the token is not expired. + Future auth_future; + bool auth_succeeded = connection->app_->function_registry()->CallFunction( + ::firebase::internal::FnAuthGetTokenAsync, connection->app_, + &force_refresh, &auth_future); + Future app_check_future; + bool app_check_succeeded = + connection->app_->function_registry()->CallFunction( + ::firebase::internal::FnAppCheckGetTokenAsync, connection->app_, + nullptr, &app_check_future); + + // Check that the futures are actually valid (assuming they were made) + auth_succeeded &= auth_future.status() != kFutureStatusInvalid; + app_check_succeeded &= app_check_future.status() != kFutureStatusInvalid; + + if (auth_succeeded || app_check_succeeded) { + // If either succeeded, we need to wait for the successful one(s) to + // finish. + { + MutexLock future_lock(connection->pending_token_future_mutex_); + connection->pending_get_token_attempt_ = attempt; + if (auth_succeeded) { + connection->pending_auth_token_future_ = auth_future; + connection->auth_token_future_status_ = kWaitingForTokenFuture; + } else { + connection->pending_auth_token_future_ = Future(); + connection->auth_token_future_status_ = kInvalidTokenFuture; + } - // Note: purposefully wait to add callbacks in case they are called - // immediately. - if (auth_succeeded) { - auth_future.OnCompletion(OnAuthTokenFutureComplete, connection); - } - if (app_check_succeeded) { - app_check_future.OnCompletion(OnAppCheckTokenFutureComplete, - connection); - } + if (app_check_succeeded) { + connection->pending_app_check_token_future_ = app_check_future; + connection->app_check_token_future_status_ = kWaitingForTokenFuture; } else { - // If both failed, assume neither are present, and start the - // connection anyway. - connection->auth_token_.clear(); - connection->app_check_token_.clear(); - connection->OpenNetworkConnection(); + connection->pending_app_check_token_future_ = Future(); + connection->app_check_token_future_status_ = kInvalidTokenFuture; } - })); + } + + // Note: purposefully wait to add callbacks in case they are called + // immediately. + if (auth_succeeded) { + auth_future.OnCompletion( + [safe_ref](const Future& result_data) { + OnAuthTokenFutureComplete(safe_ref, result_data); + }); + } + if (app_check_succeeded) { + app_check_future.OnCompletion( + [safe_ref](const Future& result_data) { + OnAppCheckTokenFutureComplete(safe_ref, result_data); + }); + } + } else { + // If both failed, assume neither are present, and start the + // connection anyway. + connection->auth_token_.clear(); + connection->app_check_token_.clear(); + connection->OpenNetworkConnection(); + } + }); } void PersistentConnection::OnAuthTokenFutureComplete( - const Future& result_data, void* user_data) { - FIREBASE_DEV_ASSERT(user_data); - PersistentConnection* connection = - static_cast(user_data); - ThisRefLock lock(&connection->safe_this_); + ThisRef safe_ref, const Future& result_data) { + OnTokenFutureComplete(std::move(safe_ref), result_data, /*is_auth=*/true); +} + +void PersistentConnection::OnAppCheckTokenFutureComplete( + ThisRef safe_ref, const Future& result_data) { + OnTokenFutureComplete(std::move(safe_ref), result_data, /*is_auth=*/false); +} + +void PersistentConnection::OnTokenFutureComplete( + ThisRef safe_ref, const Future& result_data, bool is_auth) { + ThisRefLock outer_lock(&safe_ref); + auto* connection = outer_lock.GetReference(); // If the connection is destroyed or being destroyed, do nothing. - if (!lock.GetReference()) return; + if (!connection) return; + uint64_t attempt = 0; { - // Update your own status, and check if App Check is finished. + // Update your own status, and check if the other token future is finished. MutexLock future_lock(connection->pending_token_future_mutex_); + const Future& expected_future = + is_auth ? connection->pending_auth_token_future_ + : connection->pending_app_check_token_future_; + TokenFutureStatus& self_status = + is_auth ? connection->auth_token_future_status_ + : connection->app_check_token_future_status_; + TokenFutureStatus other_status = + is_auth ? connection->app_check_token_future_status_ + : connection->auth_token_future_status_; // If this future doesn't match the pending future, a different set is // underway. - if (connection->pending_auth_token_future_ != result_data) { + if (expected_future != result_data) { return; } - connection->auth_token_future_status_ = kCompletedTokenFuture; - if (connection->app_check_token_future_status_ == kWaitingForTokenFuture) { - // Still waiting for App Check, so return and let the App Check - // callback finish the connection. + self_status = kCompletedTokenFuture; + if (other_status == kWaitingForTokenFuture) { + // Still waiting for the other token, so return and let its callback + // finish the connection. return; } + attempt = connection->pending_get_token_attempt_; } - connection->scheduler_->Schedule(new callback::CallbackValue1( - connection->safe_this_, [](ThisRef ref) { - ThisRefLock lock(&ref); - if (lock.GetReference()) { - lock.GetReference()->HandleTokenFutures(); - } - })); + connection->scheduler_->Schedule( + new callback::CallbackValue2( + connection->safe_this_, attempt, + [](ThisRef ref, uint64_t scheduled_attempt) { + ThisRefLock lock(&ref); + if (lock.GetReference()) { + lock.GetReference()->HandleTokenFutures(scheduled_attempt); + } + })); } -void PersistentConnection::OnAppCheckTokenFutureComplete( - const Future& result_data, void* user_data) { - FIREBASE_DEV_ASSERT(user_data); - PersistentConnection* connection = - static_cast(user_data); - ThisRefLock lock(&connection->safe_this_); - // If the connection is destroyed or being destroyed, do nothing. - if (!lock.GetReference()) return; +void PersistentConnection::HandleTokenFutures(uint64_t get_token_attempt) { + if (get_token_attempt != current_get_token_attempt_) { + logger_->LogDebug( + "%s Ignoring getToken result, because this was not the latest attempt.", + log_id_.c_str()); + return; + } + Future auth_future; + TokenFutureStatus auth_status = kInvalidTokenFuture; + Future app_check_future; + TokenFutureStatus app_check_status = kInvalidTokenFuture; { - // Update your own status, and check if Auth is finished. - MutexLock future_lock(connection->pending_token_future_mutex_); - // If this future doesn't match the pending future, a different set is - // underway. - if (connection->pending_app_check_token_future_ != result_data) { - return; - } - connection->app_check_token_future_status_ = kCompletedTokenFuture; - if (connection->auth_token_future_status_ == kWaitingForTokenFuture) { - // Still waiting for Auth, so return and let the Auth - // callback finish the connection. + MutexLock lock(pending_token_future_mutex_); + if (pending_get_token_attempt_ != get_token_attempt) { return; } + auth_future = std::move(pending_auth_token_future_); + auth_status = auth_token_future_status_; + app_check_future = std::move(pending_app_check_token_future_); + app_check_status = app_check_token_future_status_; + auth_token_future_status_ = kInvalidTokenFuture; + app_check_token_future_status_ = kInvalidTokenFuture; + pending_get_token_attempt_ = 0; } - connection->scheduler_->Schedule(new callback::CallbackValue1( - connection->safe_this_, [](ThisRef ref) { - ThisRefLock lock(&ref); - if (lock.GetReference()) { - lock.GetReference()->HandleTokenFutures(); - } - })); -} + FIREBASE_DEV_ASSERT(auth_status != kWaitingForTokenFuture); + FIREBASE_DEV_ASSERT(app_check_status != kWaitingForTokenFuture); -void PersistentConnection::HandleTokenFutures() { - FIREBASE_DEV_ASSERT(auth_token_future_status_ != kWaitingForTokenFuture); - FIREBASE_DEV_ASSERT(app_check_token_future_status_ != kWaitingForTokenFuture); + if (connection_state_ != kGettingToken) { + FIREBASE_DEV_ASSERT(connection_state_ == kDisconnected); + logger_->LogDebug( + "%s Not opening connection after token refresh, because " + "connection was set to disconnected", + log_id_.c_str()); + return; + } - bool auth_error = auth_token_future_status_ == kCompletedTokenFuture && - pending_auth_token_future_.error() != 0; + bool auth_error = + auth_status == kCompletedTokenFuture && auth_future.error() != 0; if (auth_error) { // Only care about Auth errors, because App Check errors are handled by the // backend. connection_state_ = kDisconnected; + const char* error_message = auth_future.error_message(); logger_->LogDebug("%s Error fetching token: %s", log_id_.c_str(), - pending_auth_token_future_.error_message()); + error_message ? error_message : ""); TryScheduleReconnect(); } else { - if (connection_state_ == kGettingToken) { - logger_->LogDebug("%s Successfully fetched token, opening connection", - log_id_.c_str()); - if (auth_token_future_status_ == kCompletedTokenFuture) { - auth_token_ = *pending_auth_token_future_.result(); - } else { - auth_token_.clear(); - } - if (app_check_token_future_status_ == kCompletedTokenFuture) { - app_check_token_ = *pending_app_check_token_future_.result(); - } else { - app_check_token_.clear(); - } - OpenNetworkConnection(); + logger_->LogDebug("%s Successfully fetched token, opening connection", + log_id_.c_str()); + if (auth_status == kCompletedTokenFuture && auth_future.error() == 0 && + auth_future.result() != nullptr) { + auth_token_ = *auth_future.result(); } else { - FIREBASE_DEV_ASSERT(connection_state_ == kDisconnected); - logger_->LogDebug( - "%s Not opening connection after token refresh, because " - "connection was set to disconnected", - log_id_.c_str()); + auth_token_.clear(); } + if (app_check_status == kCompletedTokenFuture && + app_check_future.error() == 0 && app_check_future.result() != nullptr) { + app_check_token_ = *app_check_future.result(); + } else { + app_check_token_.clear(); + } + OpenNetworkConnection(); } } +void PersistentConnection::ClearPendingTokenFutures() { + MutexLock lock(pending_token_future_mutex_); + pending_auth_token_future_ = Future(); + auth_token_future_status_ = kInvalidTokenFuture; + pending_app_check_token_future_ = Future(); + app_check_token_future_status_ = kInvalidTokenFuture; + pending_get_token_attempt_ = 0; +} + void PersistentConnection::OpenNetworkConnection() { FIREBASE_DEV_ASSERT(connection_state_ == kGettingToken); @@ -1165,8 +1220,8 @@ void PersistentConnection::HandleAuthTokenResponse(const Variant& message, ++invalid_auth_token_count; if (invalid_auth_token_count >= kInvalidAuthTokenThreshold) { - // TODO(chkuang): Maximize retry interval (after retry is properly - // implemented). + // Set a long reconnect delay because recovery is unlikely. + retry_helper_.SetMaxDelay(); logger_->LogWarning( "Provided authentication credentials are invalid. This indicates " "your FirebaseApp instance was not initialized correctly. Make " diff --git a/database/src/desktop/connection/persistent_connection.h b/database/src/desktop/connection/persistent_connection.h index 09da1ac829..99eb809b81 100644 --- a/database/src/desktop/connection/persistent_connection.h +++ b/database/src/desktop/connection/persistent_connection.h @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -37,6 +38,7 @@ #include "database/src/common/query_spec.h" #include "database/src/desktop/connection/connection.h" #include "database/src/desktop/connection/host_info.h" +#include "database/src/desktop/connection/retry_helper.h" #include "database/src/desktop/core/tag.h" #include "database/src/include/firebase/database/common.h" @@ -327,13 +329,21 @@ class PersistentConnection : public ConnectionEventHandler { // Try to reconnect to RT DB server. void TryScheduleReconnect(); + typedef firebase::internal::SafeReference ThisRef; + typedef firebase::internal::SafeReferenceLock + ThisRefLock; + // Callback function when the Auth future to fetch token is complete. - static void OnAuthTokenFutureComplete(const Future& auth_future, - void* user_data); + static void OnAuthTokenFutureComplete(ThisRef safe_ref, + const Future& result_data); // Callback function when the App Check future to fetch token is complete. static void OnAppCheckTokenFutureComplete( - const Future& app_check_future, void* user_data); - void HandleTokenFutures(); + ThisRef safe_ref, const Future& result_data); + static void OnTokenFutureComplete(ThisRef safe_ref, + const Future& result_data, + bool is_auth); + void HandleTokenFutures(uint64_t get_token_attempt); + void ClearPendingTokenFutures(); // Mutex to protect pending_token_future_ Mutex pending_token_future_mutex_; @@ -347,6 +357,7 @@ class PersistentConnection : public ConnectionEventHandler { TokenFutureStatus auth_token_future_status_; Future pending_app_check_token_future_; TokenFutureStatus app_check_token_future_status_; + uint64_t pending_get_token_attempt_; // Start to establish connection to RT DB server. void OpenNetworkConnection(); @@ -506,9 +517,6 @@ class PersistentConnection : public ConnectionEventHandler { // Safe reference to this. Set in constructor and cleared in destructor // Should be safe to be copied in any thread because the std::shared_ptr never // changes, until safe_this_ is completely destroyed. - typedef firebase::internal::SafeReference ThisRef; - typedef firebase::internal::SafeReferenceLock - ThisRefLock; ThisRef safe_this_; // Scheduler to make sure all Connection events are handled in worker @@ -526,6 +534,9 @@ class PersistentConnection : public ConnectionEventHandler { // States ConnectionState connection_state_; bool is_first_connection_; + Optional + last_connection_established_time_; + uint64_t current_get_token_attempt_; // Session std::string last_session_id_; @@ -575,6 +586,8 @@ class PersistentConnection : public ConnectionEventHandler { uint64_t next_write_id_; Logger* logger_; + + RetryHelper retry_helper_; }; class PersistentConnectionEventHandler { diff --git a/database/src/desktop/connection/retry_helper.cc b/database/src/desktop/connection/retry_helper.cc new file mode 100644 index 0000000000..c5d1c78ae6 --- /dev/null +++ b/database/src/desktop/connection/retry_helper.cc @@ -0,0 +1,242 @@ +// 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/connection/retry_helper.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/src/assert.h" + +namespace firebase { +namespace database { +namespace internal { +namespace connection { +namespace { + +std::minstd_rand::result_type SeedRng(const void* instance_addr) { + static std::atomic counter{0}; + const uint64_t time_ticks = static_cast( + std::chrono::steady_clock::now().time_since_epoch().count()); + const uint64_t addr_bits = + static_cast(reinterpret_cast(instance_addr)); + const uint64_t count = counter.fetch_add(1, std::memory_order_relaxed) + 1; + uint64_t z = time_ticks ^ (addr_bits * 0x9e3779b97f4a7c15ULL) ^ + (count * 0xbf58476d1ce4e5b9ULL); + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; + z = z ^ (z >> 31); + return static_cast( + (z % (std::minstd_rand::modulus - 1)) + 1); +} + +} // namespace + +RetryHelper::RetryHelper(scheduler::Scheduler* scheduler, Logger* logger) + : RetryHelper(scheduler, logger, Options()) {} + +RetryHelper::RetryHelper(scheduler::Scheduler* scheduler, Logger* logger, + Options options) + : scheduler_(scheduler), + logger_(logger), + min_retry_delay_after_failure_ms_( + options.min_retry_delay_after_failure_ms), + max_retry_delay_ms_(options.max_retry_delay_ms), + retry_exponent_(options.retry_exponent), + jitter_factor_(options.jitter_factor), + random_generator_(std::move(options.random_generator)), + rng_(random_generator_ ? std::minstd_rand::default_seed : SeedRng(this)), + safe_this_(this), + scheduled_retry_id_(0), + next_task_id_(0), + current_retry_delay_ms_(0), + last_scheduled_delay_ms_(0), + last_was_success_(true) { + FIREBASE_ASSERT(scheduler_ != nullptr); + FIREBASE_ASSERT(min_retry_delay_after_failure_ms_ <= max_retry_delay_ms_); + FIREBASE_ASSERT(std::isfinite(retry_exponent_) && retry_exponent_ >= 1.0); + FIREBASE_ASSERT(jitter_factor_ >= 0.0 && jitter_factor_ <= 1.0); +} + +RetryHelper::~RetryHelper() { + // Clear SafeReference first so any callback checking/clearing state completes + // under SafeReferenceLock before this object is torn down, and any unstarted + // callback becomes a no-op. + safe_this_.ClearReference(); + if (scheduled_retry_.IsValid()) { + scheduled_retry_.Cancel(); + } +} + +void RetryHelper::Retry(std::function callback) { + scheduler::RequestHandle previous_retry; + { + ThisRefLock lock(&safe_this_); + + if (scheduled_retry_.IsValid()) { + if (logger_) { + logger_->LogDebug("[RetryHelper] Cancelling previous scheduled retry"); + } + std::swap(previous_retry, scheduled_retry_); + scheduled_retry_id_ = 0; + } + + uint64_t delay_ms = 0; + if (last_was_success_) { + delay_ms = 0; + } else { + if (current_retry_delay_ms_ == 0) { + current_retry_delay_ms_ = min_retry_delay_after_failure_ms_; + } else { + const double new_delay_double = + static_cast(current_retry_delay_ms_) * retry_exponent_; + if (!(new_delay_double < static_cast(max_retry_delay_ms_))) { + current_retry_delay_ms_ = max_retry_delay_ms_; + } else { + current_retry_delay_ms_ = static_cast(new_delay_double); + } + } + if (jitter_factor_ == 0.0 || current_retry_delay_ms_ == 0) { + delay_ms = current_retry_delay_ms_; + } else { + const double random_value = NextRandom(); + const double base_double = static_cast(current_retry_delay_ms_); + const double jittered = ((1.0 - jitter_factor_) * base_double) + + (jitter_factor_ * base_double * random_value); + if (!(jittered > 0.0)) { + delay_ms = 0; + } else if (jittered >= base_double) { + delay_ms = current_retry_delay_ms_; + } else { + delay_ms = static_cast(jittered); + } + } + } + + last_was_success_ = false; + last_scheduled_delay_ms_ = delay_ms; + if (logger_) { + logger_->LogDebug("[RetryHelper] Scheduling retry in %" PRIu64 "ms", + delay_ms); + } + + const uint64_t task_id = ++next_task_id_; + scheduled_retry_id_ = task_id; + scheduled_retry_ = scheduler_->Schedule( + [safe_ref = safe_this_, task_id, + callback = std::move(callback)]() mutable { + { + ThisRefLock callback_lock(&safe_ref); + RetryHelper* helper = callback_lock.GetReference(); + if (!helper || helper->scheduled_retry_id_ != task_id) { + return; + } + // Clear scheduled_retry_ before invoking the user callback so + // re-entrant Retry() or Cancel() calls will not invoke + // RequestHandle::Cancel() on the currently running request while + // Scheduler::TriggerCallback() holds status->mutex. + helper->scheduled_retry_ = scheduler::RequestHandle(); + helper->scheduled_retry_id_ = 0; + } + if (callback) { + callback(); + } + }, + delay_ms); + } + + // Cancel the previous handle outside safe_this_ lock to avoid lock-order + // inversion with Scheduler::TriggerCallback() (which holds status->mutex). + if (previous_retry.IsValid()) { + previous_retry.Cancel(); + } +} + +void RetryHelper::SignalSuccess() { + ThisRefLock lock(&safe_this_); + last_was_success_ = true; + current_retry_delay_ms_ = 0; +} + +void RetryHelper::SetMaxDelay() { + ThisRefLock lock(&safe_this_); + current_retry_delay_ms_ = max_retry_delay_ms_; +} + +void RetryHelper::Cancel() { + scheduler::RequestHandle to_cancel; + { + ThisRefLock lock(&safe_this_); + if (scheduled_retry_.IsValid()) { + if (logger_) { + logger_->LogDebug("[RetryHelper] Cancelling existing retry attempt"); + } + std::swap(to_cancel, scheduled_retry_); + scheduled_retry_id_ = 0; + } else if (logger_) { + logger_->LogDebug("[RetryHelper] No existing retry attempt to cancel"); + } + current_retry_delay_ms_ = 0; + } + + if (to_cancel.IsValid()) { + to_cancel.Cancel(); + } +} + +uint64_t RetryHelper::current_retry_delay_ms() const { + ThisRefLock lock(&safe_this_); + return current_retry_delay_ms_; +} + +uint64_t RetryHelper::last_scheduled_delay_ms() const { + ThisRefLock lock(&safe_this_); + return last_scheduled_delay_ms_; +} + +bool RetryHelper::last_was_success() const { + ThisRefLock lock(&safe_this_); + return last_was_success_; +} + +double RetryHelper::NextRandom() { + double val = 0.0; + if (random_generator_) { + val = random_generator_(); + // Allow a closed upper bound (<= 1.0) merely to accept buggy standard + // library implementations (e.g. LWG 2524) that occasionally return 1.0. + FIREBASE_DEV_ASSERT(std::isfinite(val) && val >= 0.0 && val <= 1.0); + } else { + std::uniform_real_distribution dist(0.0, 1.0); + val = dist(rng_); + } + if (!std::isfinite(val) || val < 0.0) { + return 0.0; + } + if (val >= 1.0) { + return std::nextafter(1.0, 0.0); + } + return val; +} + +} // namespace connection +} // namespace internal +} // namespace database +} // namespace firebase diff --git a/database/src/desktop/connection/retry_helper.h b/database/src/desktop/connection/retry_helper.h new file mode 100644 index 0000000000..71f933481c --- /dev/null +++ b/database/src/desktop/connection/retry_helper.h @@ -0,0 +1,132 @@ +// 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. + +#ifndef FIREBASE_DATABASE_SRC_DESKTOP_CONNECTION_RETRY_HELPER_H_ +#define FIREBASE_DATABASE_SRC_DESKTOP_CONNECTION_RETRY_HELPER_H_ + +#include +#include +#include + +#include "app/src/logger.h" +#include "app/src/safe_reference.h" +#include "app/src/scheduler.h" + +namespace firebase { +namespace database { +namespace internal { +namespace connection { + +// Schedules retry attempts with exponential backoff and random jitter on a +// Scheduler, matching the Android/iOS RTDB connection retry behavior. +// Callbacks passed to Retry() execute on the Scheduler worker thread without +// holding RetryHelper's internal lock and must guard any external lifetimes +// (e.g., via SafeReference or std::shared_ptr). +// Lifetime: |scheduler| must be non-null and outlive RetryHelper. |logger| is +// nullable and, if non-null, must also outlive RetryHelper. +class RetryHelper { + public: + // Returns a uniform random double in [0.0, 1.0). + // Runs synchronously under RetryHelper's internal lock, so implementations + // must be lightweight and non-reentrant. + using RandomGenerator = std::function; + + static constexpr uint64_t kDefaultMinRetryDelayAfterFailureMs = 1000; + static constexpr uint64_t kDefaultMaxRetryDelayMs = 30000; + static constexpr double kDefaultRetryExponent = 1.3; + static constexpr double kDefaultJitterFactor = 0.7; + + struct Options { + uint64_t min_retry_delay_after_failure_ms = + kDefaultMinRetryDelayAfterFailureMs; + uint64_t max_retry_delay_ms = kDefaultMaxRetryDelayMs; + double retry_exponent = kDefaultRetryExponent; + double jitter_factor = kDefaultJitterFactor; + // Optional deterministic/custom RNG. Executed synchronously while holding + // RetryHelper's internal lock; must be lightweight and non-reentrant. + RandomGenerator random_generator = nullptr; + }; + + // |scheduler| must be non-null and outlive RetryHelper. |logger| may be + // nullptr; if non-null, it must outlive RetryHelper. Invalid |options| + // (min > max, non-finite or < 1.0 exponent, or jitter outside [0.0, 1.0]) + // fail via release-active FIREBASE_ASSERT. + RetryHelper(scheduler::Scheduler* scheduler, Logger* logger); + RetryHelper(scheduler::Scheduler* scheduler, Logger* logger, Options options); + ~RetryHelper(); + + // RetryHelper is neither copyable nor movable. + RetryHelper(const RetryHelper&) = delete; + RetryHelper& operator=(const RetryHelper&) = delete; + + // Schedules |callback| to run after the next backoff delay, cancelling any + // previously scheduled pending retry. + // Note: |callback| executes without holding RetryHelper's internal lock, so + // it may run concurrently with RetryHelper destruction and must guard any + // external object lifetimes (e.g., via SafeReference or std::shared_ptr). + void Retry(std::function callback); + + // Resets backoff state after a successful connection or interrupt. + // Note: Matching Android's RetryHelper, this does NOT cancel an + // already-scheduled pending retry. + void SignalSuccess(); + + // Jumps the current backoff delay directly to |max_retry_delay_ms_|. + // Note: Matching Android's RetryHelper, this does not clear + // |last_was_success_|; if |last_was_success_| is true, the next Retry() + // still runs at 0 ms before subsequent failures use |max_retry_delay_ms_|. + void SetMaxDelay(); + + // Cancels any pending scheduled retry and resets the current retry delay. + // Note: This does NOT reset |last_was_success_| and does NOT wait for an + // already-executing callback to finish. + void Cancel(); + + private: + friend class RetryHelperTestPeer; + + using ThisRef = firebase::internal::SafeReference; + using ThisRefLock = firebase::internal::SafeReferenceLock; + + // Inspection helpers for unit tests via RetryHelperTestPeer. + uint64_t current_retry_delay_ms() const; + uint64_t last_scheduled_delay_ms() const; + bool last_was_success() const; + + double NextRandom(); + + scheduler::Scheduler* const scheduler_; + Logger* const logger_; + const uint64_t min_retry_delay_after_failure_ms_; + const uint64_t max_retry_delay_ms_; + const double retry_exponent_; + const double jitter_factor_; + const RandomGenerator random_generator_; + std::minstd_rand rng_; + + mutable ThisRef safe_this_; + scheduler::RequestHandle scheduled_retry_; + uint64_t scheduled_retry_id_; + uint64_t next_task_id_; + uint64_t current_retry_delay_ms_; + uint64_t last_scheduled_delay_ms_; + bool last_was_success_; +}; + +} // namespace connection +} // namespace internal +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_DESKTOP_CONNECTION_RETRY_HELPER_H_ diff --git a/database/src/desktop/database_desktop.cc b/database/src/desktop/database_desktop.cc index a7e0a5e544..d97af82375 100644 --- a/database/src/desktop/database_desktop.cc +++ b/database/src/desktop/database_desktop.cc @@ -15,9 +15,11 @@ #include "database/src/desktop/database_desktop.h" #include +#include #include #include #include +#include #include "app/src/app_common.h" #include "app/src/assert.h" @@ -43,6 +45,34 @@ namespace internal { Mutex g_database_reference_constructor_mutex; // NOLINT +namespace { + +using PersistenceKey = std::pair; + +std::string NormalizeDatabaseUrl(const std::string& url) { + ParseUrl parser; + if (parser.Parse(url) == ParseUrl::kParseOk) { + connection::HostInfo host_info(parser.hostname.c_str(), parser.ns.c_str(), + parser.secure); + return host_info.ToString(); + } + return url; +} + +PersistenceKey MakePersistenceKey(App* app, const std::string& url) { + return std::make_pair(app ? std::string(app->name()) : std::string(), + NormalizeDatabaseUrl(url)); +} + +Mutex g_persistence_enabled_mutex; // NOLINT + +std::map* GetPersistenceEnabledMap() { + static auto* persistence_enabled_map = new std::map(); + return persistence_enabled_map; +} + +} // namespace + SingleValueListener::SingleValueListener(DatabaseInternal* database, const QuerySpec& query_spec, ReferenceCountedFutureImpl* future, @@ -79,6 +109,15 @@ DatabaseInternal::DatabaseInternal(App* app, const char* url) assert(app); assert(url); + { + MutexLock lock(g_persistence_enabled_mutex); + auto* persistence_map = GetPersistenceEnabledMap(); + auto it = persistence_map->find(MakePersistenceKey(app_, database_url_)); + if (it != persistence_map->end()) { + persistence_enabled_ = it->second; + } + } + // Spin up the token auto-update thread in Auth. app_->function_registry()->CallFunction( ::firebase::internal::FnAuthStartTokenListener, app_, nullptr, nullptr); @@ -184,6 +223,9 @@ void DatabaseInternal::SetPersistenceEnabled(bool enabled) { // Only set persistence if the repo has not yet been initialized. if (!repo_) { persistence_enabled_ = enabled; + MutexLock persistence_lock(g_persistence_enabled_mutex); + (*GetPersistenceEnabledMap())[MakePersistenceKey(app_, database_url_)] = + enabled; } } 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..26c8968420 100644 --- a/database/src/desktop/persistence/level_db_persistence_storage_engine.cc +++ b/database/src/desktop/persistence/level_db_persistence_storage_engine.cc @@ -413,7 +413,7 @@ static void VariantAddCachedValue(Variant* variant, const Path& path, // 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)) { + 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..900a197033 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 @@ -369,6 +379,15 @@ if(MSVC) ) endif() +firebase_cpp_cc_test( + firebase_rtdb_desktop_connection_retry_helper_test + SOURCES + desktop/connection/retry_helper_test.cc + DEPENDS + firebase_database + firebase_testing +) + firebase_cpp_cc_test( firebase_rtdb_desktop_connection_connection_test SOURCES diff --git a/database/tests/desktop/connection/retry_helper_test.cc b/database/tests/desktop/connection/retry_helper_test.cc new file mode 100644 index 0000000000..e15dc8578c --- /dev/null +++ b/database/tests/desktop/connection/retry_helper_test.cc @@ -0,0 +1,476 @@ +// 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/connection/retry_helper.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "app/src/logger.h" +#include "app/src/scheduler.h" +#include "app/src/semaphore.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace database { +namespace internal { +namespace connection { + +class RetryHelperTestPeer { + public: + static uint64_t current_retry_delay_ms(const RetryHelper& helper) { + return helper.current_retry_delay_ms(); + } + static uint64_t last_scheduled_delay_ms(const RetryHelper& helper) { + return helper.last_scheduled_delay_ms(); + } + static bool last_was_success(const RetryHelper& helper) { + return helper.last_was_success(); + } +}; + +namespace { + +constexpr int kWaitTimeoutMs = 5000; + +struct SharedTestState { + Semaphore sem{0}; + Semaphore extra_sem{0}; + std::atomic count{0}; + std::atomic second_count{0}; + std::atomic lock_executed_count{0}; + std::atomic flag{false}; + std::atomic cancelled_cb_ran{false}; +}; + +RetryHelper::Options MakeOptions( + uint64_t min_delay_ms, uint64_t max_delay_ms, double retry_exponent, + double jitter_factor, RetryHelper::RandomGenerator random_generator) { + RetryHelper::Options options; + options.min_retry_delay_after_failure_ms = min_delay_ms; + options.max_retry_delay_ms = max_delay_ms; + options.retry_exponent = retry_exponent; + options.jitter_factor = jitter_factor; + options.random_generator = std::move(random_generator); + return options; +} + +class RetryHelperTest : public ::testing::Test { + protected: + RetryHelperTest() : logger_(nullptr) {} + + Logger logger_; + scheduler::Scheduler scheduler_; +}; + +TEST_F(RetryHelperTest, FirstRetryIsImmediate) { + RetryHelper::Options options; + options.random_generator = []() { return 0.5; }; + RetryHelper helper(&scheduler_, &logger_, std::move(options)); + + EXPECT_TRUE(RetryHelperTestPeer::last_was_success(helper)); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + + auto state = std::make_shared(); + helper.Retry([state]() { state->sem.Post(); }); + + EXPECT_FALSE(RetryHelperTestPeer::last_was_success(helper)); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 0u); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + EXPECT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); +} + +TEST_F(RetryHelperTest, ExponentialBackoffCurveWithDeterministicRng) { + const std::vector expected_base_delays = { + 1000, 1300, 1690, 2197, 2856, 3712, 4825, 6272, + 8153, 10598, 13777, 17910, 23283, 30000, 30000, + }; + + const std::vector rng_values = {0.0, 0.5, 0.999999}; + + for (double rng_value : rng_values) { + SCOPED_TRACE(::testing::Message() << "rng_value=" << rng_value); + RetryHelper helper(&scheduler_, &logger_, + MakeOptions(1000, 30000, 1.3, 0.7, + [rng_value]() { return rng_value; })); + + // Initial retry is immediate (0 ms). + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 0u); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + + for (uint64_t expected_base : expected_base_delays) { + SCOPED_TRACE(::testing::Message() << "expected_base=" << expected_base); + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), + expected_base); + + const double expected_base_double = static_cast(expected_base); + const uint64_t min_expected = + static_cast(0.3 * expected_base_double); + const uint64_t expected_jittered = + static_cast(((1.0 - 0.7) * expected_base_double) + + (0.7 * expected_base_double * rng_value)); + + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), + expected_jittered); + EXPECT_GE(RetryHelperTestPeer::last_scheduled_delay_ms(helper), + min_expected); + EXPECT_LT(RetryHelperTestPeer::last_scheduled_delay_ms(helper), + expected_base); + } + helper.Cancel(); + } +} + +TEST_F(RetryHelperTest, CapIsAppliedBeforeJitter) { + // With rng = 0.0 and max = 30000, jittered delay at cap is 0.3 * 30000 = + // 9000, never exceeding 30000 and never computing jitter on an uncapped + // 23283 * 1.3 = 30267. + double rng_value = 0.0; + RetryHelper helper( + &scheduler_, &logger_, + MakeOptions(1000, 30000, 1.3, 0.7, [&rng_value]() { return rng_value; })); + + // Advance to the step just before cap (23283) and then to cap (30000). + helper.Retry([]() {}); // 0 + for (int i = 0; i < 13; ++i) { + helper.Retry([]() {}); + } + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 23283u); + + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 9000u); + + rng_value = 0.999999; + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 29999u); + helper.Cancel(); +} + +TEST_F(RetryHelperTest, SignalSuccessResetsBackoffAndMakesNextRetryImmediate) { + RetryHelper helper(&scheduler_, &logger_, + MakeOptions(1000, 30000, 1.3, 0.7, []() { return 0.5; })); + + helper.Retry([]() {}); // 0 + helper.Retry([]() {}); // 1000 -> 650 + helper.Retry([]() {}); // 1300 -> 845 + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 1300u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 845u); + + helper.SignalSuccess(); + EXPECT_TRUE(RetryHelperTestPeer::last_was_success(helper)); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + + auto state = std::make_shared(); + helper.Retry([state]() { state->sem.Post(); }); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 0u); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 1000u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 650u); + helper.Cancel(); +} + +TEST_F(RetryHelperTest, SetMaxDelayJumpsToMaxDelay) { + double rng_value = 0.5; + RetryHelper helper( + &scheduler_, &logger_, + MakeOptions(1000, 30000, 1.3, 0.7, [&rng_value]() { return rng_value; })); + + // Simulate initial attempt that failed auth before delay built up. + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 0u); + + helper.SetMaxDelay(); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 19500u); + + rng_value = 0.0; + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 9000u); + + // When last_was_success_ is true, first retry is still 0 ms, then max. + helper.SignalSuccess(); + helper.SetMaxDelay(); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 0u); + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 30000u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 9000u); + helper.Cancel(); +} + +TEST_F(RetryHelperTest, CancelPreventsPendingTaskAndResetsCurrentDelay) { + RetryHelper helper(&scheduler_, &logger_, + MakeOptions(20, 1000, 1.3, 0.0, []() { return 0.0; })); + + // Cancel when nothing is scheduled should be safe and leave delay at 0. + helper.Cancel(); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + + // First retry is immediate; wait for it to finish so second retry is delayed. + auto state = std::make_shared(); + helper.Retry([state]() { state->sem.Post(); }); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + + helper.Retry([state]() { state->flag.store(true); }); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 20u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 20u); + + helper.Cancel(); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + + // Wait past the 20ms delay via sentinel barrier to verify the cancelled + // callback never runs. + scheduler_.Schedule([state]() { state->extra_sem.Post(); }, 21); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + EXPECT_FALSE(state->flag.load()); + + // Next Retry() after Cancel() (without SignalSuccess) starts at min delay. + helper.Retry([]() {}); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 20u); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 20u); + helper.Cancel(); +} + +TEST_F(RetryHelperTest, OverlappingRetryCancelsPreviousTask) { + RetryHelper helper(&scheduler_, &logger_, + MakeOptions(25, 1000, 1.3, 0.0, []() { return 0.0; })); + + // Burn the immediate 0ms first attempt. + auto state = std::make_shared(); + helper.Retry([state]() { state->extra_sem.Post(); }); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + + // Schedule a 25ms retry, then immediately supersede it with another Retry(). + helper.Retry([state]() { state->count.fetch_add(1); }); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 25u); + + // Reset to 0ms via SignalSuccess so the replacement runs immediately while + // ensuring the cancelled 25ms task never fires even after the sentinel + // barrier. + helper.SignalSuccess(); + helper.Retry([state]() { + state->second_count.fetch_add(1); + state->sem.Post(); + }); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 0u); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + + scheduler_.Schedule([state]() { state->extra_sem.Post(); }, 26); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + EXPECT_EQ(state->count.load(), 0); + EXPECT_EQ(state->second_count.load(), 1); +} + +TEST_F(RetryHelperTest, ReentrantRetryInsideCallbackDoesNotDeadlock) { + auto state = std::make_shared(); + auto helper = std::make_shared( + &scheduler_, &logger_, + MakeOptions(10, 100, 1.3, 0.0, []() { return 0.0; })); + std::weak_ptr weak_helper = helper; + + helper->Retry([weak_helper, state]() { + state->count.fetch_add(1); + if (auto locked_helper = weak_helper.lock()) { + state->lock_executed_count.fetch_add(1); + locked_helper->Retry([state]() { + state->count.fetch_add(1); + state->sem.Post(); + }); + } + state->extra_sem.Post(); + }); + + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + EXPECT_EQ(state->lock_executed_count.load(), 1); + EXPECT_EQ(state->count.load(), 2); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(*helper), 10u); +} + +TEST_F(RetryHelperTest, ReentrantCancelInsideCallbackDoesNotDeadlock) { + auto state = std::make_shared(); + auto helper = std::make_shared( + &scheduler_, &logger_, + MakeOptions(20, 100, 1.3, 0.0, []() { return 0.0; })); + std::weak_ptr weak_helper = helper; + + helper->Retry([weak_helper, state]() { + if (auto locked_helper = weak_helper.lock()) { + state->lock_executed_count.fetch_add(1); + locked_helper->Cancel(); + } + state->extra_sem.Post(); + }); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + EXPECT_EQ(state->lock_executed_count.load(), 1); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(*helper), 0u); + + helper->Retry([weak_helper, state]() { + if (auto locked_helper = weak_helper.lock()) { + state->lock_executed_count.fetch_add(1); + // Re-entrantly schedule and then cancel inside the active callback. + locked_helper->Retry([state]() { state->cancelled_cb_ran.store(true); }); + locked_helper->Cancel(); + } + state->sem.Post(); + }); + + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + EXPECT_EQ(state->lock_executed_count.load(), 2); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(*helper), 0u); + + scheduler_.Schedule([state]() { state->extra_sem.Post(); }, 27); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + EXPECT_FALSE(state->cancelled_cb_ran.load()); +} + +TEST_F(RetryHelperTest, DestructorCancelsPendingTaskWithoutUaf) { + auto state = std::make_shared(); + { + auto helper = std::make_unique( + &scheduler_, &logger_, + MakeOptions(20, 1000, 1.3, 0.0, []() { return 0.0; })); + + helper->Retry([state]() { state->sem.Post(); }); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + + helper->Retry([state]() { state->flag.store(true); }); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(*helper), 20u); + } // Destroy RetryHelper while 20ms task is queued. + + scheduler_.Schedule([state]() { state->extra_sem.Post(); }, 21); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + EXPECT_FALSE(state->flag.load()); +} + +TEST_F(RetryHelperTest, + DestructorCompletesWhileCallbackIsInFlightWithoutDeadlockOrUaf) { + struct InFlightState { + Semaphore entered{0}; + Semaphore allow_finish{0}; + Semaphore finished{0}; + std::atomic allow_finish_succeeded{false}; + std::atomic callback_finished{false}; + }; + auto state = std::make_shared(); + auto helper = std::make_unique( + &scheduler_, &logger_, + MakeOptions(10, 100, 1.3, 0.0, []() { return 0.0; })); + + helper->Retry([state]() { + state->entered.Post(); + state->allow_finish_succeeded.store( + state->allow_finish.TimedWait(kWaitTimeoutMs)); + state->callback_finished.store(true); + state->finished.Post(); + }); + + ASSERT_TRUE(state->entered.TimedWait(kWaitTimeoutMs)); + helper.reset(); + state->allow_finish.Post(); + ASSERT_TRUE(state->finished.TimedWait(kWaitTimeoutMs)); + EXPECT_TRUE(state->allow_finish_succeeded.load()); + EXPECT_TRUE(state->callback_finished.load()); +} + +TEST_F(RetryHelperTest, DefaultRngProducesValuesWithinExpectedJitterBounds) { + RetryHelper helper(&scheduler_, &logger_); + + std::set observed_delays; + for (int i = 0; i < 64; ++i) { + SCOPED_TRACE(::testing::Message() << "iteration=" << i); + helper.SignalSuccess(); + helper.Retry([]() {}); // 0 ms + helper.Retry([]() {}); // 1000 ms * [0.3, 1.0) -> [300, 1000] + uint64_t delay = RetryHelperTestPeer::last_scheduled_delay_ms(helper); + EXPECT_GE(delay, 300u); + EXPECT_LE(delay, 1000u); + observed_delays.insert(delay); + helper.Cancel(); + } + // With 64 uniform draws over [300, 1000], collisions across all 64 draws + // are astronomically unlikely. + EXPECT_GT(observed_delays.size(), 1u); +} + +TEST_F(RetryHelperTest, SecondRetryRespectsScheduledDelay) { + RetryHelper helper(&scheduler_, &logger_, + MakeOptions(40, 500, 1.3, 0.0, []() { return 0.0; })); + + auto state = std::make_shared(); + helper.Retry([state]() { state->extra_sem.Post(); }); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + + const auto start_time = std::chrono::steady_clock::now(); + helper.Retry([state]() { state->sem.Post(); }); + EXPECT_EQ(RetryHelperTestPeer::last_scheduled_delay_ms(helper), 40u); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + const auto elapsed_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_time) + .count(); + + // Allow slight OS timer granularity slack while ensuring it actually waited. + EXPECT_GE(elapsed_ms, 20); +} + +TEST_F(RetryHelperTest, HandlesNullLoggerAndEmptyCallbackSafely) { + RetryHelper helper(&scheduler_, /*logger=*/nullptr, + MakeOptions(10, 100, 1.3, 0.0, []() { return 0.0; })); + + auto state = std::make_shared(); + + // Empty callback at 0 ms should execute without crashing. + helper.Retry(nullptr); + scheduler_.Schedule([state]() { state->sem.Post(); }, 0); + ASSERT_TRUE(state->sem.TimedWait(kWaitTimeoutMs)); + + // Empty callback at delayed backoff should execute without crashing. + helper.Retry(nullptr); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 10u); + scheduler_.Schedule([state]() { state->extra_sem.Post(); }, 10); + ASSERT_TRUE(state->extra_sem.TimedWait(kWaitTimeoutMs)); + + // Cancel() with nullptr logger should be safe both with no pending task and + // with a pending task. + helper.Cancel(); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); + + helper.Retry(nullptr); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 10u); + helper.Cancel(); + EXPECT_EQ(RetryHelperTestPeer::current_retry_delay_ms(helper), 0u); +} + +} // namespace +} // namespace connection +} // 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..7ee3b988c8 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,23 @@ #include "database/src/desktop/persistence/level_db_persistence_storage_engine.h" +#include #include #include #include +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif // WIN32_LEAN_AND_MEAN +#include +#endif // defined(_WIN32) + #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" using testing::Eq; using testing::Pointwise; @@ -249,6 +257,41 @@ TEST_F(LevelDbPersistenceStorageEngineTest, OverwriteServerCache) { }); } +TEST_F(LevelDbPersistenceStorageEngineTest, + OverwriteServerCacheMapWithPriorityAndLaterKeys) { + InitializeLevelDb(test_info_->name()); + + // ".priority" sorts lexicographically before child keys like "subkey" and + // "value". Reconstructing the map from LevelDB must not wrap the empty + // Variant::Null() placeholder into {".value": Null}. + // 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("scalar_with_priority", std::map{ + std::make_pair(".value", "hello"), + std::make_pair(".priority", 42), + }), + }; + // 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("scalar_with_priority")), + data.map().at("scalar_with_priority")); + }); +} + TEST_F(LevelDbPersistenceStorageEngineTest, OverwriteServerCache_Overwrite) { InitializeLevelDb(test_info_->name()); @@ -388,8 +431,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.