diff --git a/connections/c/BUILD b/connections/c/BUILD index b747460e..930b191c 100644 --- a/connections/c/BUILD +++ b/connections/c/BUILD @@ -53,7 +53,6 @@ cc_library( "//connections:core_types", "//connections/implementation/analytics:analytics_recorder_impl", "//connections/implementation/flags:connections_flags", - "//internal/analytics:event_logger", "//internal/flags:flag_reader", "//internal/flags:nearby_flags", "//internal/platform:base", @@ -61,7 +60,8 @@ cc_library( "//internal/platform:logging", "//internal/platform:mac_address", "//internal/platform:types", - "//internal/proto/analytics:connections_log_cc_proto", + "//location/nearby/analytics/cpp/logging:event_logger", + "//location/nearby/analytics/cpp/proto:connections_log_cc_proto", "//sharing/proto/analytics:sharing_log_cc_proto", "@com_google_absl//absl/base:no_destructor", "@com_google_absl//absl/container:flat_hash_map", diff --git a/connections/c/nc.cc b/connections/c/nc.cc index 5d631859..f31d1c8f 100644 --- a/connections/c/nc.cc +++ b/connections/c/nc.cc @@ -25,6 +25,10 @@ #include #include +#if !defined(NC_OSS_BUILD) +#include "location/nearby/analytics/cpp/logging/event_logger.h" +#include "location/nearby/analytics/cpp/proto/connections_log.pb.h" +#endif // !defined(NC_OSS_BUILD) #include "absl/base/no_destructor.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" @@ -45,7 +49,6 @@ #include "connections/payload.h" #include "connections/status.h" #include "connections/strategy.h" -#include "internal/analytics/event_logger.h" #include "internal/flags/flag.h" #include "internal/flags/flag_reader.h" #include "internal/flags/nearby_flags.h" @@ -53,7 +56,6 @@ #include "internal/platform/file.h" #include "internal/platform/logging.h" #include "internal/platform/mac_address.h" -#include "internal/proto/analytics/connections_log.pb.h" #include "sharing/proto/analytics/nearby_sharing_log.pb.h" #if TARGET_OS_IOS #include "internal/platform/implementation/apple/nearby_logger.h" @@ -122,6 +124,7 @@ class FlagReaderWrapper : public nearby::flags::FlagReader { NC_PHENOTYPE_FLAG_READER phenotype_flag_reader_; }; +#if !defined(NC_OSS_BUILD) // This is a bridging class between the C API and the C++ EventLogger interface. class NcEventLogger : public ::nearby::analytics::EventLogger { public: @@ -149,6 +152,10 @@ class NcEventLogger : public ::nearby::analytics::EventLogger { private: const NC_EVENT_LOGGER* event_logger_; }; +#else // !defined(NC_OSS_BUILD) +class NcEventLogger; +#endif // !defined(NC_OSS_BUILD) + } // namespace typedef struct NcContext { diff --git a/connections/implementation/BUILD b/connections/implementation/BUILD index 4f026fbb..334a3149 100644 --- a/connections/implementation/BUILD +++ b/connections/implementation/BUILD @@ -468,7 +468,6 @@ cc_test( "//connections/implementation/analytics:mock_analytics_recorder", "//connections/implementation/flags:connections_flags", "//connections/v3:v3_types", - "//internal/analytics:mock_event_logger", "//internal/flags:nearby_flags", "//internal/interop:device", "//internal/platform:base", @@ -478,7 +477,6 @@ cc_test( "//internal/platform/implementation/g3", # build_cleaner: keep "//proto:connections_enums_cc_proto", "@com_github_protobuf_matchers//protobuf-matchers", - "@com_google_absl//absl/base:core_headers", "@com_google_absl//absl/strings", "@com_google_absl//absl/strings:str_format", "@com_google_absl//absl/time", diff --git a/connections/implementation/analytics/BUILD b/connections/implementation/analytics/BUILD index 006a2292..d893305c 100644 --- a/connections/implementation/analytics/BUILD +++ b/connections/implementation/analytics/BUILD @@ -54,12 +54,12 @@ cc_library( deps = [ ":analytics", "//connections:core_types", - "//internal/analytics:event_logger", "//internal/platform:error_code_recorder", "//internal/platform:logging", "//internal/platform:types", "//internal/platform/implementation:types", - "//internal/proto/analytics:connections_log_cc_proto", + "//location/nearby/analytics/cpp/logging:event_logger", + "//location/nearby/analytics/cpp/proto:connections_log_cc_proto", "//proto:connections_enums_cc_proto", "@com_google_absl//absl/algorithm:container", "@com_google_absl//absl/base:core_headers", @@ -99,15 +99,13 @@ cc_test( ":analytics", ":analytics_recorder_impl", "//connections:core_types", - "//internal/analytics:mock_event_logger", "//internal/platform:base", "//internal/platform:error_code_recorder", - "//internal/platform:logging", "//internal/platform:test_util", "//internal/platform:types", "//internal/platform/implementation/g3", # build_cleaner: keep - "//internal/proto/analytics:connections_log_cc_proto", - "//internal/test", + "//location/nearby/analytics/cpp/logging:mock_event_logger", + "//location/nearby/analytics/cpp/proto:connections_log_cc_proto", "//net/proto2/contrib/parse_proto:parse_text_proto", "//proto:connections_enums_cc_proto", "@com_github_protobuf_matchers//protobuf-matchers", diff --git a/connections/implementation/analytics/analytics_recorder_impl.cc b/connections/implementation/analytics/analytics_recorder_impl.cc deleted file mode 100644 index 211cc2dd..00000000 --- a/connections/implementation/analytics/analytics_recorder_impl.cc +++ /dev/null @@ -1,1643 +0,0 @@ -// Copyright 2022-2023 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 -// -// https://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 "connections/implementation/analytics/analytics_recorder_impl.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "absl/algorithm/container.h" -#include "absl/container/btree_map.h" -#include "absl/strings/string_view.h" -#include "absl/time/time.h" -#include "connections/implementation/analytics/advertising_metadata_params.h" -#include "connections/implementation/analytics/analytics_recorder.h" -#include "connections/implementation/analytics/connection_attempt_metadata_params.h" -#include "connections/implementation/analytics/discovery_metadata_params.h" -#include "connections/implementation/analytics/operation_result_with_medium.h" -#include "connections/payload_type.h" -#include "connections/strategy.h" -#include "internal/analytics/event_logger.h" -#include "internal/platform/error_code_params.h" -#include "internal/platform/implementation/system_clock.h" -#include "internal/platform/logging.h" -#include "internal/platform/mutex_lock.h" -#include "internal/proto/analytics/connections_log.pb.h" -#include "proto/connections_enums.pb.h" -#include "google/protobuf/repeated_ptr_field.h" - -namespace nearby::analytics { - -namespace { -// const char kVersion_1_0_0[] = "v1.0.0"; -const char kVersion[] = "v1.5.0"; -constexpr absl::string_view kOnStartClientSession = "OnStartClientSession"; -const absl::Duration kConnectionTokenMaxLife = absl::Hours(24); - -using ::location::nearby::analytics::proto::ConnectionsLog; -using ::location::nearby::proto::connections::ACCEPTED; -using ::location::nearby::proto::connections::ADVERTISER; -using ::location::nearby::proto::connections::BandwidthUpgradeErrorStage; -using ::location::nearby::proto::connections::BandwidthUpgradeResult; -using ::location::nearby::proto::connections::BYTES; -using ::location::nearby::proto::connections::CLIENT_SESSION; -using ::location::nearby::proto::connections::CONNECTION_CLOSED; -using ::location::nearby::proto::connections::ConnectionAttemptDirection; -using ::location::nearby::proto::connections::ConnectionAttemptResult; -using ::location::nearby::proto::connections::ConnectionAttemptType; -using ::location::nearby::proto::connections::ConnectionRequestResponse; -using ::location::nearby::proto::connections::ConnectionsStrategy; -using ::location::nearby::proto::connections::DisconnectionReason; -using ::location::nearby::proto::connections::DISCOVERER; -using ::location::nearby::proto::connections::ERROR_CODE; -using ::location::nearby::proto::connections::EventType; -using ::location::nearby::proto::connections::FILE; -using ::location::nearby::proto::connections::IGNORED; -using ::location::nearby::proto::connections::INCOMING; -using ::location::nearby::proto::connections::INITIAL; -using ::location::nearby::proto::connections::Medium; -using ::location::nearby::proto::connections::MOVED_TO_NEW_MEDIUM; -using ::location::nearby::proto::connections::NOT_SENT; -using ::location::nearby::proto::connections::OperationResultCategory; -using ::location::nearby::proto::connections::OperationResultCode; -using ::location::nearby::proto::connections::OUTGOING; -using ::location::nearby::proto::connections::P2P_CLUSTER; -using ::location::nearby::proto::connections::P2P_POINT_TO_POINT; -using ::location::nearby::proto::connections::P2P_STAR; -using ::location::nearby::proto::connections::PayloadStatus; -using ::location::nearby::proto::connections::PayloadType; -using ::location::nearby::proto::connections::REJECTED; -using ::location::nearby::proto::connections::RESULT_SUCCESS; -using ::location::nearby::proto::connections::SessionRole; -using ::location::nearby::proto::connections::START_CLIENT_SESSION; -using ::location::nearby::proto::connections::START_STRATEGY_SESSION; -using ::location::nearby::proto::connections::STOP_CLIENT_SESSION; -using ::location::nearby::proto::connections::STOP_STRATEGY_SESSION; -using ::location::nearby::proto::connections::StopAdvertisingReason; -using ::location::nearby::proto::connections::StopDiscoveringReason; -using ::location::nearby::proto::connections::STREAM; -using ::location::nearby::proto::connections::UNFINISHED; -using ::location::nearby::proto::connections::UNFINISHED_ERROR; -using ::location::nearby::proto::connections::UNKNOWN_MEDIUM; -using ::location::nearby::proto::connections::UNKNOWN_PAYLOAD_TYPE; -using ::location::nearby::proto::connections::UNKNOWN_STRATEGY; -using ::location::nearby::proto::connections::UPGRADE_RESULT_SUCCESS; -using ::location::nearby::proto::connections::UPGRADE_SUCCESS; -using ::location::nearby::proto::connections::UPGRADE_UNFINISHED; -using ::location::nearby::proto::connections::UPGRADED; -using ::nearby::analytics::EventLogger; -using ProtoSafeDisconnectionResult = ::location::nearby::analytics::proto:: - ConnectionsLog::EstablishedConnection::SafeDisconnectionResult; - -OperationResultCategory ConvertToOperationResultCategory( - OperationResultCode result_code) { - if (result_code == OperationResultCode::DETAIL_SUCCESS) { - return OperationResultCategory::CATEGORY_SUCCESS; - } - // TODO(b/409865630): check later if we need to add back the dct error. - // Section of CATEGORY_DCT_ERROR, from 5000 to 5499 if (result_code - // >= OperationResultCode::DCT_ERROR_BLE_DISABLED) { - // return OperationResultCategory::CATEGORY_DCT_ERROR; - //} - - // Section of CATEGORY_NEARBY_ERROR, starting from 4500 to 4999 - if (result_code >= - OperationResultCode::NEARBY_BLE_ADVERTISEMENT_MAPPING_TO_MAC_ERROR) { - return OperationResultCategory::CATEGORY_NEARBY_ERROR; - } - // Section of CATEGORY_CONNECTIVITY_ERROR, starting from 3500 to 4499 - if (result_code >= - OperationResultCode::CONNECTIVITY_WIFI_AWARE_ATTACH_FAILURE) { - return OperationResultCategory::CATEGORY_CONNECTIVITY_ERROR; - } - // Section of CATEGORY_IO_ERROR, from 3000 to 3499 - if (result_code >= OperationResultCode::IO_FILE_OPENING_ERROR) { - return OperationResultCategory::CATEGORY_IO_ERROR; - } - // Section of CATEGORY_MISCELLANEOUS, from 2500 to 2999 - if (result_code >= - OperationResultCode::MISCELLEANEOUS_BLUETOOTH_MAC_ADDRESS_NULL) { - return OperationResultCategory::CATEGORY_MISCELLANEOUS; - } - // Section of CATEGORY_CLIENT_ERROR, from 2000 to 2499 - if (result_code >= - OperationResultCode:: - CLIENT_WIFI_DIRECT_ALREADY_HOSTING_DIRECT_GROUP_FOR_THIS_CLIENT) { - return OperationResultCategory::CATEGORY_CLIENT_ERROR; - } - // Section of CATEGORY_MEDIUM_UNAVAILABLE, from 1500 to 1999 - if (result_code >= OperationResultCode:: - MEDIUM_UNAVAILABLE_WIFI_AWARE_RESOURCE_NOT_AVAILABLE) { - return OperationResultCategory::CATEGORY_MEDIUM_UNAVAILABLE; - } - // Section of CATEGORY_DEVICE_STATE_ERROR, from 1000 to 1499 - if (result_code >= - OperationResultCode::DEVICE_STATE_ERROR_UNFINISHED_UPGRADE_ATTEMPTS) { - return OperationResultCategory::CATEGORY_DEVICE_STATE_ERROR; - } - // Section of CATEGORY_CLIENT_CANCELLATION, from 500 to 999 - if (result_code >= - OperationResultCode::CLIENT_CANCELLATION_REMOTE_IN_CANCELED_STATE) { - return OperationResultCategory::CATEGORY_CLIENT_CANCELLATION; - } - // Clarify other non success cases as unknown - return OperationResultCategory::CATEGORY_UNKNOWN; -} - -ProtoSafeDisconnectionResult ConvertToProtoSafeDisconnectionResult( - SafeDisconnectionResult result) { - switch (result) { - case SafeDisconnectionResult::kSafeDisconnection: - return ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION; - case SafeDisconnectionResult::kUnsafeDisconnection: - return ConnectionsLog::EstablishedConnection::UNSAFE_DISCONNECTION; - default: - return ConnectionsLog::EstablishedConnection:: - UNKNOWN_SAFE_DISCONNECTION_RESULT; - } -} - -ConnectionsLog::OperationResultWithMedium -ConvertToProtoOperationResultWithMedium( - const nearby::analytics::OperationResultWithMedium& cpp_result) { - ConnectionsLog::OperationResultWithMedium proto_result; - proto_result.set_medium(cpp_result.medium); - if (cpp_result.update_index.has_value()) { - proto_result.set_update_index(cpp_result.update_index.value()); - } - proto_result.set_result_category(cpp_result.result_category); - proto_result.set_result_code(cpp_result.result_code); - if (cpp_result.connection_mode.has_value()) { - proto_result.set_connection_mode(cpp_result.connection_mode.value()); - } - return proto_result; -} - -} // namespace - -AnalyticsRecorderImpl::AnalyticsRecorderImpl(EventLogger* event_logger) - : event_logger_(event_logger) { - VLOG(1) << "Start AnalyticsRecorderImpl ctor event_logger_=" << event_logger_; - LogStartSession(); -} - -AnalyticsRecorderImpl::~AnalyticsRecorderImpl() = default; - -bool AnalyticsRecorderImpl::IsSessionLogged() { - MutexLock lock(&mutex_); - return session_was_logged_; -} - -int AnalyticsRecorderImpl::GetLatestUpdateIndexLocked( - const std::vector& list) { - int latest_update_index = 0; - for (const auto& operation_result_with_medium : list) { - if (operation_result_with_medium.update_index() > latest_update_index) { - latest_update_index = operation_result_with_medium.update_index(); - } - } - return latest_update_index; -} - -void AnalyticsRecorderImpl::OnStartAdvertising( - connections::Strategy strategy, const std::vector& mediums, - AdvertisingMetadataParams* advertising_metadata_params) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnStartAdvertising")) { - return; - } - if (!strategy.IsValid()) { - LOG(INFO) << "AnalyticsRecorderImpl OnStartAdvertising with unknown " - "strategy, bail out."; - return; - } - // Initialize/update a StrategySession. - UpdateStrategySessionLocked(strategy, ADVERTISER); - - // Initialize and set a AdvertisingPhase. - started_advertising_phase_time_ = SystemClock::ElapsedRealtime(); - current_advertising_phase_ = - std::make_unique(); - absl::c_copy(mediums, RepeatedFieldBackInserter( - current_advertising_phase_->mutable_medium())); - // Set a AdvertisingMetadata. - AdvertisingMetadataParams default_params = {}; - if (advertising_metadata_params == nullptr) { - advertising_metadata_params = &default_params; - } - if (!advertising_metadata_params->operation_result_with_mediums.empty()) { - for (const auto& cpp_result : - advertising_metadata_params->operation_result_with_mediums) { - *current_advertising_phase_->add_adv_dis_result() = - ConvertToProtoOperationResultWithMedium(cpp_result); - } - } - auto* advertising_metadata = - current_advertising_phase_->mutable_advertising_metadata(); - advertising_metadata->set_supports_extended_ble_advertisements( - advertising_metadata_params->is_extended_advertisement_supported); - advertising_metadata->set_connected_ap_frequency( - advertising_metadata_params->connected_ap_frequency); - advertising_metadata->set_supports_nfc_technology( - advertising_metadata_params->is_nfc_available); -} - -void AnalyticsRecorderImpl::OnStopAdvertising() { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnStopAdvertising")) { - return; - } - RecordAdvertisingPhaseDurationAndReasonLocked(/* on_stop= */ true); -} - -int AnalyticsRecorderImpl::GetNextAdvertisingUpdateIndex() { - MutexLock lock(&mutex_); - - if (current_advertising_phase_ == nullptr) { - return 0; - } - return GetLatestUpdateIndexLocked( - std::vector( - current_advertising_phase_->adv_dis_result().begin(), - current_advertising_phase_->adv_dis_result().end())) + - 1; -} - -void AnalyticsRecorderImpl::OnStartDiscovery( - connections::Strategy strategy, const std::vector& mediums, - DiscoveryMetadataParams* discovery_metadata_params) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnStartDiscovery")) { - return; - } - if (!strategy.IsValid()) { - LOG(INFO) << "AnalyticsRecorderImpl OnStartDiscovery unknown " - "strategy enter, bail out."; - return; - } - - // Initialize/update a StrategySession. - UpdateStrategySessionLocked(strategy, DISCOVERER); - - // Initialize and set a DiscoveryPhase. - started_discovery_phase_time_ = SystemClock::ElapsedRealtime(); - current_discovery_phase_ = std::make_unique(); - absl::c_copy(mediums, RepeatedFieldBackInserter( - current_discovery_phase_->mutable_medium())); - // Set a DiscoveryMetadata. - DiscoveryMetadataParams default_params = {}; - if (discovery_metadata_params == nullptr) { - discovery_metadata_params = &default_params; - } - if (!discovery_metadata_params->operation_result_with_mediums.empty()) { - for (const auto& cpp_result : - discovery_metadata_params->operation_result_with_mediums) { - *current_discovery_phase_->add_adv_dis_result() = - ConvertToProtoOperationResultWithMedium(cpp_result); - } - } - auto* discovery_metadata = - current_discovery_phase_->mutable_discovery_metadata(); - discovery_metadata->set_supports_extended_ble_advertisements( - discovery_metadata_params->is_extended_advertisement_supported); - discovery_metadata->set_connected_ap_frequency( - discovery_metadata_params->connected_ap_frequency); - discovery_metadata->set_supports_nfc_technology( - discovery_metadata_params->is_nfc_available); -} - -void AnalyticsRecorderImpl::OnStopDiscovery() { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnStopDiscovery")) { - return; - } - RecordDiscoveryPhaseDurationAndReasonLocked(/*on_stop=*/true); -} - -int AnalyticsRecorderImpl::GetNextDiscoveryUpdateIndex() { - MutexLock lock(&mutex_); - if (current_discovery_phase_ == nullptr) { - return 0; - } - return GetLatestUpdateIndexLocked( - std::vector( - current_discovery_phase_->adv_dis_result().begin(), - current_discovery_phase_->adv_dis_result().end())) + - 1; -} - -void AnalyticsRecorderImpl::OnStartedIncomingConnectionListening( - connections::Strategy strategy) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnStartedIncomingConnectionListening")) { - return; - } - UpdateStrategySessionLocked(strategy, ADVERTISER); - if (started_advertising_phase_time_ == absl::InfinitePast()) { - started_advertising_phase_time_ = SystemClock::ElapsedRealtime(); - } -} - -void AnalyticsRecorderImpl::OnStoppedIncomingConnectionListening() { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnStoppedIncomingConnectionListening")) { - return; - } - RecordAdvertisingPhaseDurationAndReasonLocked(/* on_stop= */ false); -} - -void AnalyticsRecorderImpl::OnEndpointFound(Medium medium) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnEndpointFound")) { - return; - } - if (current_discovery_phase_ == nullptr) { - LOG(INFO) << "Unable to record discovered endpoint due to null " - "current_discovery_phase_"; - return; - } - ConnectionsLog::DiscoveredEndpoint* discovered_endpoint = - current_discovery_phase_->add_discovered_endpoint(); - discovered_endpoint->set_medium(medium); - discovered_endpoint->set_latency_millis(absl::ToInt64Milliseconds( - SystemClock::ElapsedRealtime() - started_discovery_phase_time_)); -} - -void AnalyticsRecorderImpl::OnRequestConnection( - const connections::Strategy& strategy, const std::string& endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("onRequestConnection")) { - return; - } - - UpdateStrategySessionLocked(strategy, DISCOVERER); - if (started_discovery_phase_time_ == absl::InfinitePast()) { - started_discovery_phase_time_ = SystemClock::ElapsedRealtime(); - } -} - -void AnalyticsRecorderImpl::OnConnectionRequestReceived( - const std::string& remote_endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnConnectionRequestReceived")) { - return; - } - absl::Time current_time = SystemClock::ElapsedRealtime(); - auto connection_request = - std::make_unique(); - connection_request->set_duration_millis(absl::ToUnixMillis(current_time)); - connection_request->set_request_delay_millis(absl::ToInt64Milliseconds( - current_time - started_advertising_phase_time_)); - incoming_connection_requests_.insert( - {remote_endpoint_id, std::move(connection_request)}); -} - -void AnalyticsRecorderImpl::OnConnectionRequestSent( - const std::string& remote_endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnConnectionRequestSent")) { - return; - } - absl::Time current_time = SystemClock::ElapsedRealtime(); - auto connection_request = - std::make_unique(); - connection_request->set_duration_millis(absl::ToUnixMillis(current_time)); - connection_request->set_request_delay_millis( - absl::ToInt64Milliseconds(current_time - started_discovery_phase_time_)); - outgoing_connection_requests_.insert( - {remote_endpoint_id, std::move(connection_request)}); -} - -void AnalyticsRecorderImpl::OnRemoteEndpointAccepted( - const std::string& remote_endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnRemoteEndpointAccepted")) { - return; - } - RemoteEndpointRespondedLocked(remote_endpoint_id, ACCEPTED); -} - -void AnalyticsRecorderImpl::OnLocalEndpointAccepted( - const std::string& remote_endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnLocalEndpointAccepted")) { - return; - } - LocalEndpointRespondedLocked(remote_endpoint_id, ACCEPTED); -} - -void AnalyticsRecorderImpl::OnRemoteEndpointRejected( - const std::string& remote_endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnRemoteEndpointRejected")) { - return; - } - RemoteEndpointRespondedLocked(remote_endpoint_id, REJECTED); -} - -void AnalyticsRecorderImpl::OnLocalEndpointRejected( - const std::string& remote_endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnLocalEndpointRejected")) { - return; - } - LocalEndpointRespondedLocked(remote_endpoint_id, REJECTED); -} - -void AnalyticsRecorderImpl::OnIncomingConnectionAttempt( - ConnectionAttemptType type, Medium medium, ConnectionAttemptResult result, - absl::Duration duration, const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnIncomingConnectionAttempt")) { - return; - } - if (current_strategy_session_ == nullptr) { - LOG(INFO) << "Unable to record incoming connection attempt due to " - "null current_strategy_session_"; - return; - } - - ConnectionAttemptMetadataParams default_params = {}; - if (connection_attempt_metadata_params == nullptr) { - connection_attempt_metadata_params = &default_params; - } - OnIncomingConnectionAttemptLocked(type, medium, result, duration, - connection_token, - connection_attempt_metadata_params); -} - -void AnalyticsRecorderImpl::OnIncomingConnectionAttemptLocked( - location::nearby::proto::connections::ConnectionAttemptType type, - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::ConnectionAttemptResult result, - absl::Duration duration, const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) { - auto* connection_attempt = - current_strategy_session_->add_connection_attempt(); - connection_attempt->set_duration_millis(absl::ToInt64Milliseconds(duration)); - connection_attempt->set_type(type); - connection_attempt->set_direction(INCOMING); - connection_attempt->set_medium(medium); - connection_attempt->set_attempt_result(result); - connection_attempt->set_connection_token(connection_token); - - auto* connection_attempt_metadata = - connection_attempt->mutable_connection_attempt_metadata(); - connection_attempt_metadata->set_technology( - connection_attempt_metadata_params->technology); - connection_attempt_metadata->set_band( - connection_attempt_metadata_params->band); - connection_attempt_metadata->set_frequency( - connection_attempt_metadata_params->frequency); - connection_attempt_metadata->set_network_operator( - connection_attempt_metadata_params->network_operator); - connection_attempt_metadata->set_country_code( - connection_attempt_metadata_params->country_code); - connection_attempt_metadata->set_frequency( - connection_attempt_metadata_params->frequency); - connection_attempt_metadata->set_is_tdls_used( - connection_attempt_metadata_params->is_tdls_used); - connection_attempt_metadata->set_wifi_hotspot_status( - connection_attempt_metadata_params->wifi_hotspot_enabled); - connection_attempt_metadata->set_try_counts( - connection_attempt_metadata_params->try_count); - connection_attempt_metadata->set_max_tx_speed( - connection_attempt_metadata_params->max_wifi_tx_speed); - connection_attempt_metadata->set_max_rx_speed( - connection_attempt_metadata_params->max_wifi_rx_speed); - connection_attempt_metadata->set_wifi_channel_width( - connection_attempt_metadata_params->channel_width); - - auto operation_result_proto = - std::make_unique(); - operation_result_proto->set_result_code( - connection_attempt_metadata_params->operation_result_code); - operation_result_proto->set_result_category(ConvertToOperationResultCategory( - connection_attempt_metadata_params->operation_result_code)); - connection_attempt->set_allocated_operation_result( - operation_result_proto.release()); -} - -void AnalyticsRecorderImpl::OnOutgoingConnectionAttempt( - const std::string& remote_endpoint_id, ConnectionAttemptType type, - Medium medium, ConnectionAttemptResult result, absl::Duration duration, - const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnOutgoingConnectionAttempt")) { - return; - } - if (current_strategy_session_ == nullptr) { - LOG(INFO) << "Unable to record outgoing connection attempt due to " - "null current_strategy_session_"; - return; - } - - ConnectionAttemptMetadataParams default_params = {}; - if (connection_attempt_metadata_params == nullptr) { - connection_attempt_metadata_params = &default_params; - } - - // For the case of transfer a big file and the upgrades always failure, then - // there will have repeating upgrade attempt and cause many same attempt value - // be log. So add a method to skip. - if (ConnectionAttemptResultCodeExistedLocked( - medium, OUTGOING, connection_token, type, - connection_attempt_metadata_params->operation_result_code)) { - return; - } - - OnOutgoingConnectionAttemptLocked(remote_endpoint_id, type, medium, result, - duration, connection_token, - connection_attempt_metadata_params); -} - -void AnalyticsRecorderImpl::OnOutgoingConnectionAttemptLocked( - const std::string& remote_endpoint_id, ConnectionAttemptType type, - Medium medium, ConnectionAttemptResult result, absl::Duration duration, - const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) { - auto* connection_attempt = - current_strategy_session_->add_connection_attempt(); - connection_attempt->set_duration_millis(absl::ToInt64Milliseconds(duration)); - connection_attempt->set_type(type); - connection_attempt->set_direction(OUTGOING); - connection_attempt->set_medium(medium); - connection_attempt->set_attempt_result(result); - connection_attempt->set_connection_token(connection_token); - - auto* connection_attempt_metadata = - connection_attempt->mutable_connection_attempt_metadata(); - connection_attempt_metadata->set_technology( - connection_attempt_metadata_params->technology); - connection_attempt_metadata->set_band( - connection_attempt_metadata_params->band); - connection_attempt_metadata->set_frequency( - connection_attempt_metadata_params->frequency); - connection_attempt_metadata->set_network_operator( - connection_attempt_metadata_params->network_operator); - connection_attempt_metadata->set_country_code( - connection_attempt_metadata_params->country_code); - connection_attempt_metadata->set_frequency( - connection_attempt_metadata_params->frequency); - connection_attempt_metadata->set_is_tdls_used( - connection_attempt_metadata_params->is_tdls_used); - connection_attempt_metadata->set_wifi_hotspot_status( - connection_attempt_metadata_params->wifi_hotspot_enabled); - connection_attempt_metadata->set_try_counts( - connection_attempt_metadata_params->try_count); - connection_attempt_metadata->set_max_tx_speed( - connection_attempt_metadata_params->max_wifi_tx_speed); - connection_attempt_metadata->set_max_rx_speed( - connection_attempt_metadata_params->max_wifi_rx_speed); - connection_attempt_metadata->set_wifi_channel_width( - connection_attempt_metadata_params->channel_width); - - auto operation_result_proto = - std::make_unique(); - operation_result_proto->set_result_code( - connection_attempt_metadata_params->operation_result_code); - operation_result_proto->set_result_category(ConvertToOperationResultCategory( - connection_attempt_metadata_params->operation_result_code)); - connection_attempt->set_allocated_operation_result( - operation_result_proto.release()); - - if (type == INITIAL && result != RESULT_SUCCESS) { - auto it = outgoing_connection_requests_.find(remote_endpoint_id); - if (it != outgoing_connection_requests_.end()) { - // An outgoing, initial ConnectionAttempt has a corresponding - // ConnectionRequest that, since the ConnectionAttempt has failed, will - // never be delivered to the advertiser. - auto pair = outgoing_connection_requests_.extract(it); - std::unique_ptr& connection_request = - pair.mapped(); - connection_request->set_local_response(NOT_SENT); - connection_request->set_remote_response(NOT_SENT); - UpdateDiscovererConnectionRequestLocked(connection_request.get()); - } - } -} - -void AnalyticsRecorderImpl::OnConnectionEstablished( - const std::string& endpoint_id, Medium medium, - const std::string& connection_token) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnConnectionEstablished")) { - return; - } - auto it = active_connections_.find(endpoint_id); - if (it != active_connections_.end()) { - const std::unique_ptr& logical_connection = it->second; - logical_connection->PhysicalConnectionEstablished(medium, connection_token); - } else { - active_connections_.insert( - {endpoint_id, - std::make_unique(medium, connection_token)}); - } -} - -void AnalyticsRecorderImpl::OnConnectionClosed(const std::string& endpoint_id, - Medium medium, - DisconnectionReason reason, - SafeDisconnectionResult result) { - MutexLock lock(&mutex_); - LOG(INFO) << __func__ - << ": OnConnectionClosed is called with endpoint_id:" << endpoint_id - << ", medium:" << Medium_Name(medium) - << ", reason:" << DisconnectionReason_Name(reason) - << ", result:" << static_cast(result); - - if (!CanRecordAnalyticsLocked("OnConnectionClosed")) { - return; - } - - if (current_strategy_session_ == nullptr) { - VLOG(1) << "AnalyticsRecorderImpl CanRecordAnalytics Unexpected call " - << __func__ << " since current_strategy_session_ is required."; - return; - } - - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - return; - } - const std::unique_ptr& logical_connection = it->second; - logical_connection->PhysicalConnectionClosed(medium, reason, result); - if (reason != UPGRADED) { - // Unless this is an upgraded connection, remove this from our active - // connections. Any future communication with an endpoint will need to be - // re-established with a new ConnectionRequest. - auto pair = active_connections_.extract(it); - std::unique_ptr& logical_connection = pair.mapped(); - - absl::c_copy( - logical_connection->GetEstablisedConnections(), - RepeatedFieldBackInserter( - current_strategy_session_->mutable_established_connection())); - } -} - -void AnalyticsRecorderImpl::OnIncomingPayloadStarted( - const std::string& endpoint_id, std::int64_t payload_id, - connections::PayloadType type, std::int64_t total_size_bytes) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnIncomingPayloadStarted")) { - return; - } - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - return; - } - const std::unique_ptr& logical_connection = it->second; - logical_connection->IncomingPayloadStarted( - payload_id, PayloadTypeToProtoPayloadType(type), total_size_bytes); -} - -void AnalyticsRecorderImpl::OnPayloadChunkReceived( - const std::string& endpoint_id, std::int64_t payload_id, - std::int64_t chunk_size_bytes) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnPayloadChunkReceived")) { - return; - } - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - return; - } - const std::unique_ptr& logical_connection = it->second; - logical_connection->ChunkReceived(payload_id, chunk_size_bytes); -} - -void AnalyticsRecorderImpl::OnIncomingPayloadDone( - const std::string& endpoint_id, std::int64_t payload_id, - PayloadStatus status, OperationResultCode operation_result_code) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnIncomingPayloadDone")) { - return; - } - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - return; - } - const std::unique_ptr& logical_connection = it->second; - logical_connection->IncomingPayloadDone(payload_id, status, - operation_result_code); -} - -void AnalyticsRecorderImpl::OnOutgoingPayloadStarted( - const std::vector& endpoint_ids, std::int64_t payload_id, - connections::PayloadType type, std::int64_t total_size_bytes) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnOutgoingPayloadStarted")) { - return; - } - for (const auto& endpoint_id : endpoint_ids) { - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - continue; - } - const std::unique_ptr& logical_connection = it->second; - logical_connection->OutgoingPayloadStarted( - payload_id, PayloadTypeToProtoPayloadType(type), total_size_bytes); - } -} - -void AnalyticsRecorderImpl::OnPayloadChunkSent(const std::string& endpoint_id, - std::int64_t payload_id, - std::int64_t chunk_size_bytes) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnPayloadChunkSent")) { - return; - } - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - return; - } - const std::unique_ptr& logical_connection = it->second; - logical_connection->ChunkSent(payload_id, chunk_size_bytes); -} - -void AnalyticsRecorderImpl::OnOutgoingPayloadDone( - const std::string& endpoint_id, std::int64_t payload_id, - PayloadStatus status, OperationResultCode operation_result_code) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnOutgoingPayloadDone")) { - return; - } - auto it = active_connections_.find(endpoint_id); - if (it == active_connections_.end()) { - return; - } - - const std::unique_ptr& logical_connection = it->second; - logical_connection->OutgoingPayloadDone(payload_id, status, - operation_result_code); -} - -void AnalyticsRecorderImpl::OnBandwidthUpgradeStarted( - const std::string& endpoint_id, Medium from_medium, Medium to_medium, - ConnectionAttemptDirection direction, const std::string& connection_token) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeStarted")) { - return; - } - auto bandwidth_upgrade_attempt = - std::make_unique(); - bandwidth_upgrade_attempt->set_duration_millis( - absl::ToUnixMillis(SystemClock::ElapsedRealtime())); - bandwidth_upgrade_attempt->set_from_medium(from_medium); - bandwidth_upgrade_attempt->set_to_medium(to_medium); - bandwidth_upgrade_attempt->set_direction(direction); - bandwidth_upgrade_attempt->set_connection_token(connection_token); - bandwidth_upgrade_attempts_.insert( - {endpoint_id, std::move(bandwidth_upgrade_attempt)}); -} - -void AnalyticsRecorderImpl::UpdateBwUpgradeNetworkInfo( - const std::string& endpoint_id, int num_interfaces, - int num_ipv6_only_interfaces) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("UpdateBwUpgradeNetworkInfo")) { - return; - } - auto it = bandwidth_upgrade_attempts_.find(endpoint_id); - if (it == bandwidth_upgrade_attempts_.end()) { - return; - } - ConnectionsLog::BandwidthUpgradeAttempt* bandwidth_upgrade_attempt = - it->second.get(); - bandwidth_upgrade_attempt->set_num_interfaces(num_interfaces); - bandwidth_upgrade_attempt->set_num_ipv6_only_interfaces( - num_ipv6_only_interfaces); -} - -void AnalyticsRecorderImpl::OnBandwidthUpgradeError( - const std::string& endpoint_id, BandwidthUpgradeResult result, - BandwidthUpgradeErrorStage error_stage, - OperationResultCode operation_result_code) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeError")) { - return; - } - // If the same records existed, drop this one. - if (EraseIfBandwidthUpgradeRecordExistedLocked( - endpoint_id, result, error_stage, operation_result_code)) { - return; - } - FinishUpgradeAttemptLocked(endpoint_id, result, error_stage, - operation_result_code); -} - -void AnalyticsRecorderImpl::OnBandwidthUpgradeSuccess( - const std::string& endpoint_id) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeSuccess")) { - return; - } - FinishUpgradeAttemptLocked(endpoint_id, UPGRADE_RESULT_SUCCESS, - UPGRADE_SUCCESS, - OperationResultCode::DETAIL_SUCCESS); -} - -void AnalyticsRecorderImpl::OnErrorCode(const ErrorCodeParams& params) { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("OnErrorCode")) { - return; - } - auto error_code = std::make_unique(); - error_code->set_medium(params.medium); - error_code->set_event(params.event); - error_code->set_connection_token(params.connection_token); - error_code->set_description(params.description); - - if (params.is_common_error) { - error_code->set_common_error(params.common_error); - } else { - switch (params.event) { - case location::nearby::errorcode::proto::START_ADVERTISING: - error_code->set_start_advertising_error(params.start_advertising_error); - break; - case location::nearby::errorcode::proto::STOP_ADVERTISING: - error_code->set_stop_advertising_error(params.stop_advertising_error); - break; - case location::nearby::errorcode::proto:: - START_LISTENING_INCOMING_CONNECTION: - error_code->set_start_listening_incoming_connection_error( - params.start_listening_incoming_connection_error); - break; - case location::nearby::errorcode::proto:: - STOP_LISTENING_INCOMING_CONNECTION: - error_code->set_stop_listening_incoming_connection_error( - params.stop_listening_incoming_connection_error); - break; - case location::nearby::errorcode::proto::START_DISCOVERING: - error_code->set_start_discovering_error(params.start_discovering_error); - break; - case location::nearby::errorcode::proto::STOP_DISCOVERING: - error_code->set_stop_discovering_error(params.stop_discovering_error); - break; - case location::nearby::errorcode::proto::CONNECT: - error_code->set_connect_error(params.connect_error); - break; - case location::nearby::errorcode::proto::DISCONNECT: - error_code->set_disconnect_error(params.disconnect_error); - break; - case location::nearby::errorcode::proto::UNKNOWN_EVENT: - default: - error_code->set_common_error(params.common_error); - break; - } - } - - ConnectionsLog connections_log; - connections_log.set_event_type(ERROR_CODE); - connections_log.set_version(kVersion); - connections_log.set_allocated_error_code(error_code.release()); - - VLOG(1) << "AnalyticsRecorderImpl LogErrorCode connections_log=" - << connections_log.DebugString(); // NOLINT - - event_logger_->Log(connections_log); -} - -void AnalyticsRecorderImpl::LogStartSession() { - MutexLock lock(&mutex_); - if (start_client_session_was_logged_) { - LOG(WARNING) << "AnalyticsRecorderImpl CanRecordAnalytics Unexpected call " - << kOnStartClientSession - << " after start client session has already been logged."; - return; - } - - session_was_logged_ = false; - if (CanRecordAnalyticsLocked(kOnStartClientSession)) { - client_session_ = std::make_unique(); - started_client_session_time_ = SystemClock::ElapsedRealtime(); - start_client_session_was_logged_ = true; - LogEvent(START_CLIENT_SESSION); - } -} - -void AnalyticsRecorderImpl::LogSession() { - MutexLock lock(&mutex_); - if (!CanRecordAnalyticsLocked("LogSession")) { - return; - } - FinishStrategySessionLocked(); - client_session_->set_duration_millis(absl::ToInt64Milliseconds( - SystemClock::ElapsedRealtime() - started_client_session_time_)); - LogClientSessionLocked(); - LogEvent(STOP_CLIENT_SESSION); - start_client_session_was_logged_ = false; - session_was_logged_ = true; -} - -bool AnalyticsRecorderImpl::CanRecordAnalyticsLocked( - absl::string_view method_name) { - VLOG(1) << "AnalyticsRecorderImpl LogEvent " << method_name << " is calling."; - if (event_logger_ == nullptr) { - return false; - } - - if (session_was_logged_) { - VLOG(1) << "AnalyticsRecorderImpl CanRecordAnalytics Unexpected call " - << method_name << " after session has already been logged."; - return false; - } - - return true; -} - -// TODO: b/391339677 - Investigate why we need to reset the resources. And -// verify in b/238375695 to see if we still meet the issue after removing the -// Reset function. -void AnalyticsRecorderImpl::LogClientSessionLocked() { - ConnectionsLog connections_log; - connections_log.set_event_type(CLIENT_SESSION); - connections_log.set_allocated_client_session(client_session_.release()); - connections_log.set_version(kVersion); - - VLOG(1) << "AnalyticsRecorderImpl LogClientSession connections_log=" - << connections_log.DebugString(); // NOLINT - - event_logger_->Log(connections_log); - client_session_ = nullptr; -} - -void AnalyticsRecorderImpl::LogEvent(EventType event_type) { - ConnectionsLog connections_log; - connections_log.set_event_type(event_type); - connections_log.set_version(kVersion); - - VLOG(1) << "AnalyticsRecorderImpl LogEvent connections_log=" - << connections_log.DebugString(); // NOLINT - - event_logger_->Log(connections_log); -} - -void AnalyticsRecorderImpl::UpdateStrategySessionLocked( - connections::Strategy strategy, SessionRole role) { - // If we're not switching strategies, just update the current StrategySession - // with the new role. - if (strategy == current_strategy_ && current_strategy_session_ != nullptr) { - if (absl::c_linear_search(current_strategy_session_->role(), role)) { - // We've already acted as this role before, so make sure we've finished - // recording the previous round. - switch (role) { - case ADVERTISER: - FinishAdvertisingPhaseLocked(); - break; - case DISCOVERER: - FinishDiscoveryPhaseLocked(); - break; - default: - break; - } - } else { - current_strategy_session_->add_role(role); - } - } else { - // Otherwise, we're starting a new Strategy. - current_strategy_ = strategy; - FinishStrategySessionLocked(); - LogEvent(START_STRATEGY_SESSION); - current_strategy_session_ = - std::make_unique(); - started_strategy_session_time_ = SystemClock::ElapsedRealtime(); - current_strategy_session_->set_strategy( - StrategyToConnectionStrategy(strategy)); - current_strategy_session_->add_role(role); - } -} - -void AnalyticsRecorderImpl::RecordAdvertisingPhaseDurationAndReasonLocked( - bool on_stop) const { - if (current_advertising_phase_ == nullptr) { - LOG(INFO) << "Unable to record advertising phase duration due to " - "null current_advertising_phase_"; - return; - } - if (!current_advertising_phase_->has_duration_millis()) { - current_advertising_phase_->set_duration_millis(absl::ToInt64Milliseconds( - SystemClock::ElapsedRealtime() - started_advertising_phase_time_)); - } - if (!current_advertising_phase_->has_stop_reason()) { - current_advertising_phase_->set_stop_reason( - on_stop ? StopAdvertisingReason::CLIENT_STOP_ADVERTISING - : StopAdvertisingReason::FINISH_SESSION_STOP_ADVERTISING); - } -} - -void AnalyticsRecorderImpl::FinishAdvertisingPhaseLocked() { - if (current_advertising_phase_ != nullptr) { - for (const auto& item : incoming_connection_requests_) { - // ConnectionRequests still pending have been ignored by the local or - // remote (or both) endpoints. - const std::unique_ptr& - connection_request = item.second; - MarkConnectionRequestIgnoredLocked(connection_request.get()); - UpdateAdvertiserConnectionRequestLocked(connection_request.get()); - } - RecordAdvertisingPhaseDurationAndReasonLocked(/* on_stop= */ false); - if (current_strategy_session_ != nullptr) { - *current_strategy_session_->add_advertising_phase() = - *std::move(current_advertising_phase_); - } else { - LOG(INFO) << "Unable to record advertising phase due to null " - "current_strategy_session_"; - } - } - incoming_connection_requests_.clear(); -} - -void AnalyticsRecorderImpl::RecordDiscoveryPhaseDurationAndReasonLocked( - bool on_stop) const { - if (current_discovery_phase_ == nullptr) { - LOG(INFO) << "Unable to record discovery phase duration due to " - "null current_discovery_phase_"; - return; - } - if (!current_discovery_phase_->has_duration_millis()) { - current_discovery_phase_->set_duration_millis(absl::ToInt64Milliseconds( - SystemClock::ElapsedRealtime() - started_discovery_phase_time_)); - } - // If the stop reason haven't been set yet, then set it. - if (!current_discovery_phase_->has_stop_reason()) { - current_discovery_phase_->set_stop_reason( - on_stop ? StopDiscoveringReason::CLIENT_STOP_DISCOVERING - : StopDiscoveringReason::FINISH_SESSION_STOP_DISCOVERING); - } -} - -void AnalyticsRecorderImpl::FinishDiscoveryPhaseLocked() { - if (current_discovery_phase_ != nullptr) { - for (const auto& item : outgoing_connection_requests_) { - // ConnectionRequests still pending have been ignored by the local or - // remote (or both) endpoints. - const std::unique_ptr& - connection_request = item.second; - MarkConnectionRequestIgnoredLocked(connection_request.get()); - UpdateDiscovererConnectionRequestLocked(connection_request.get()); - } - RecordDiscoveryPhaseDurationAndReasonLocked(/* on_stop=*/false); - if (current_strategy_session_ != nullptr) { - *current_strategy_session_->add_discovery_phase() = - *std::move(current_discovery_phase_); - } else { - LOG(INFO) << "Unable to record discovery phase due to null " - "current_strategy_session_"; - } - } - outgoing_connection_requests_.clear(); -} - -bool AnalyticsRecorderImpl::UpdateAdvertiserConnectionRequestLocked( - ConnectionsLog::ConnectionRequest* request) { - if (current_advertising_phase_ == nullptr) { - LOG(INFO) << "Unable to record advertiser connection request due to null " - "current_advertising_phase_"; - return false; - } - if (BothEndpointsRespondedLocked(request)) { - request->set_duration_millis( - absl::ToUnixMillis(SystemClock::ElapsedRealtime()) - - request->duration_millis()); - *current_advertising_phase_->add_received_connection_request() = *request; - return true; - } - return false; -} - -bool AnalyticsRecorderImpl::UpdateDiscovererConnectionRequestLocked( - ConnectionsLog::ConnectionRequest* request) { - if (current_discovery_phase_ == nullptr) { - LOG(INFO) << "Unable to record discoverer connection request due " - "to null current_discovery_phase_."; - return false; - } - if (BothEndpointsRespondedLocked(request) || - request->local_response() == NOT_SENT) { - request->set_duration_millis( - absl::ToUnixMillis(SystemClock::ElapsedRealtime()) - - request->duration_millis()); - *current_discovery_phase_->add_sent_connection_request() = *request; - return true; - } - return false; -} - -bool AnalyticsRecorderImpl::BothEndpointsRespondedLocked( - ConnectionsLog::ConnectionRequest* request) { - return request->has_local_response() && request->has_remote_response(); -} - -void AnalyticsRecorderImpl::LocalEndpointRespondedLocked( - const std::string& remote_endpoint_id, ConnectionRequestResponse response) { - auto out = outgoing_connection_requests_.find(remote_endpoint_id); - if (out != outgoing_connection_requests_.end()) { - ConnectionsLog::ConnectionRequest* connection_request = out->second.get(); - connection_request->set_local_response(response); - if (UpdateDiscovererConnectionRequestLocked(connection_request)) { - outgoing_connection_requests_.erase(out); - } - } - auto in = incoming_connection_requests_.find(remote_endpoint_id); - if (in != incoming_connection_requests_.end()) { - ConnectionsLog::ConnectionRequest* connection_request = in->second.get(); - connection_request->set_local_response(response); - if (UpdateAdvertiserConnectionRequestLocked(connection_request)) { - incoming_connection_requests_.erase(in); - } - } -} - -void AnalyticsRecorderImpl::RemoteEndpointRespondedLocked( - const std::string& remote_endpoint_id, ConnectionRequestResponse response) { - auto out = outgoing_connection_requests_.find(remote_endpoint_id); - if (out != outgoing_connection_requests_.end()) { - ConnectionsLog::ConnectionRequest* connection_request = out->second.get(); - connection_request->set_remote_response(response); - if (UpdateDiscovererConnectionRequestLocked(connection_request)) { - outgoing_connection_requests_.erase(out); - } - } - auto in = incoming_connection_requests_.find(remote_endpoint_id); - if (in != incoming_connection_requests_.end()) { - ConnectionsLog::ConnectionRequest* connection_request = in->second.get(); - connection_request->set_remote_response(response); - if (UpdateAdvertiserConnectionRequestLocked(connection_request)) { - incoming_connection_requests_.erase(in); - } - } -} - -void AnalyticsRecorderImpl::MarkConnectionRequestIgnoredLocked( - ConnectionsLog::ConnectionRequest* request) { - if (!request->has_local_response()) { - request->set_local_response(IGNORED); - } - if (!request->has_remote_response()) { - request->set_remote_response(IGNORED); - } -} - -bool AnalyticsRecorderImpl::ConnectionAttemptResultCodeExistedLocked( - Medium medium, ConnectionAttemptDirection direction, - const std::string& connection_token, ConnectionAttemptType type, - OperationResultCode operation_result_code) { - if (current_strategy_session_ == nullptr || - current_strategy_session_->connection_attempt_size() == 0) { - return false; - } - for (auto& connection_attempt : - current_strategy_session_->connection_attempt()) { - if (connection_attempt.medium() == medium && - connection_attempt.direction() == direction && - connection_attempt.connection_token() == connection_token && - connection_attempt.type() == type && - connection_attempt.operation_result().result_code() == - operation_result_code) { - return true; - } - } - - return false; -} - -// If bandwidth upgrade always failed on the same fromMedium, toMedium, result, -// stage and result code, we'll drop the duplicate logs for preventing the waste -// of log storage space -bool AnalyticsRecorderImpl::EraseIfBandwidthUpgradeRecordExistedLocked( - const std::string& endpoint_id, BandwidthUpgradeResult result, - BandwidthUpgradeErrorStage error_stage, - OperationResultCode operation_result_code) { - if (current_strategy_session_ == nullptr) { - return false; - } - auto it = bandwidth_upgrade_attempts_.find(endpoint_id); - if (it != bandwidth_upgrade_attempts_.end()) { - ConnectionsLog::BandwidthUpgradeAttempt* attempt = it->second.get(); - for (auto& existing_attempt : - current_strategy_session_->upgrade_attempt()) { - if (attempt->from_medium() == existing_attempt.from_medium() && - attempt->to_medium() == existing_attempt.to_medium() && - result == existing_attempt.upgrade_result() && - error_stage == existing_attempt.error_stage() && - operation_result_code == - existing_attempt.operation_result().result_code()) { - bandwidth_upgrade_attempts_.erase(it); - return true; - } - } - } - return false; -} - -void AnalyticsRecorderImpl::FinishUpgradeAttemptLocked( - const std::string& endpoint_id, BandwidthUpgradeResult result, - BandwidthUpgradeErrorStage error_stage, - OperationResultCode operation_result_code, bool erase_item) { - if (current_strategy_session_ == nullptr) { - LOG(INFO) << "Unable to record upgrade attempt due to null " - "current_strategy_session_"; - return; - } - // Add the BandwidthUpgradeAttempt in the current StrategySession. - auto it = bandwidth_upgrade_attempts_.find(endpoint_id); - if (it != bandwidth_upgrade_attempts_.end()) { - ConnectionsLog::BandwidthUpgradeAttempt* attempt = it->second.get(); - attempt->set_duration_millis( - absl::ToUnixMillis(SystemClock::ElapsedRealtime()) - - attempt->duration_millis()); - attempt->set_error_stage(error_stage); - attempt->set_upgrade_result(result); - - auto operation_result_proto = - std::make_unique(); - operation_result_proto->set_result_code(operation_result_code); - operation_result_proto->set_result_category( - ConvertToOperationResultCategory(operation_result_code)); - attempt->set_allocated_operation_result(operation_result_proto.release()); - *current_strategy_session_->add_upgrade_attempt() = *attempt; - if (erase_item) { - bandwidth_upgrade_attempts_.erase(it); - } - } -} - -void AnalyticsRecorderImpl::FinishStrategySessionLocked() { - if (current_strategy_session_ != nullptr) { - FinishAdvertisingPhaseLocked(); - FinishDiscoveryPhaseLocked(); - - // Finish any unfinished LogicalConnections. - for (const auto& item : active_connections_) { - const std::unique_ptr& logical_connection = - item.second; - logical_connection->CloseAllPhysicalConnections(); - absl::c_copy( - logical_connection->GetEstablisedConnections(), - RepeatedFieldBackInserter( - current_strategy_session_->mutable_established_connection())); - } - active_connections_.clear(); - - // Finish any pending upgrade attempts. - for (const auto& item : bandwidth_upgrade_attempts_) { - FinishUpgradeAttemptLocked( - item.first, UNFINISHED_ERROR, UPGRADE_UNFINISHED, - OperationResultCode::DEVICE_STATE_ERROR_UNFINISHED_UPGRADE_ATTEMPTS, - /*erase_item=*/false); - } - bandwidth_upgrade_attempts_.clear(); - - // Add the StrategySession in ClientSession - if (current_strategy_session_ != nullptr) { - current_strategy_session_->set_duration_millis(absl::ToInt64Milliseconds( - SystemClock::ElapsedRealtime() - started_strategy_session_time_)); - *client_session_->add_strategy_session() = - *std::move(current_strategy_session_); - } - - current_strategy_session_ = nullptr; - current_strategy_ = connections::Strategy::kNone; - LogEvent(STOP_STRATEGY_SESSION); - } -} - -ConnectionsStrategy AnalyticsRecorderImpl::StrategyToConnectionStrategy( - connections::Strategy strategy) { - if (strategy == connections::Strategy::kP2pCluster) { - return P2P_CLUSTER; - } - if (strategy == connections::Strategy::kP2pStar) { - return P2P_STAR; - } - if (strategy == connections::Strategy::kP2pPointToPoint) { - return P2P_POINT_TO_POINT; - } - return UNKNOWN_STRATEGY; -} - -PayloadType AnalyticsRecorderImpl::PayloadTypeToProtoPayloadType( - connections::PayloadType type) { - switch (type) { - case connections::PayloadType::kBytes: - return BYTES; - case connections::PayloadType::kFile: - return FILE; - case connections::PayloadType::kStream: - return STREAM; - default: - return UNKNOWN_PAYLOAD_TYPE; - } -} - -void AnalyticsRecorderImpl::PendingPayload::AddChunk( - std::int64_t chunk_size_bytes) { - num_bytes_transferred_ += chunk_size_bytes; - num_chunks_++; -} - -ConnectionsLog::Payload AnalyticsRecorderImpl::PendingPayload::GetProtoPayload( - PayloadStatus status) { - ConnectionsLog::Payload payload; - payload.set_duration_millis( - absl::ToInt64Milliseconds(SystemClock::ElapsedRealtime() - start_time_)); - payload.set_type(type_); - payload.set_total_size_bytes(total_size_bytes_); - payload.set_num_bytes_transferred(num_bytes_transferred_); - payload.set_num_chunks(num_chunks_); - payload.set_status(status); - - auto operation_result_proto = - std::make_unique(); - operation_result_proto->set_result_code(operation_result_code_); - operation_result_proto->set_result_category( - ConvertToOperationResultCategory(operation_result_code_)); - payload.set_allocated_operation_result(operation_result_proto.release()); - - return payload; -} - -void AnalyticsRecorderImpl::LogicalConnection::PhysicalConnectionEstablished( - Medium medium, const std::string& connection_token) { - if (current_medium_ != UNKNOWN_MEDIUM) { - LOG(WARNING) << "Unexpected call to PhysicalConnectionEstablished while " - "AnalyticsRecorderImpl still has an active current medium."; - } - - auto established_connection = - std::make_unique(); - established_connection->set_medium(medium); - established_connection->set_duration_millis( - absl::ToUnixMillis(SystemClock::ElapsedRealtime())); - established_connection->set_connection_token(connection_token); - - auto operation_result_proto = - std::make_unique(); - operation_result_proto->set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result_proto->set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - established_connection->set_allocated_operation_result( - operation_result_proto.release()); - physical_connections_.insert({medium, std::move(established_connection)}); - current_medium_ = medium; -} - -void AnalyticsRecorderImpl::LogicalConnection::PhysicalConnectionClosed( - Medium medium, DisconnectionReason reason, SafeDisconnectionResult result) { - if (current_medium_ == UNKNOWN_MEDIUM) { - LOG(WARNING) << "Unexpected call to PhysicalConnectionClosed() for medium " - << Medium_Name(medium) - << " while AnalyticsRecorderImpl has no active current medium"; - } else if (current_medium_ != medium) { - LOG(WARNING) << "Unexpected call to PhysicalConnectionClosed() for medium " - << Medium_Name(medium) - << "while AnalyticsRecorderImpl has active medium " - << Medium_Name(current_medium_); - } - - auto it = physical_connections_.find(medium); - if (it == physical_connections_.end()) { - LOG(WARNING) - << "Unexpected call to physicalConnectionClosed() for medium " - << Medium_Name(medium) - << " with no corresponding EstablishedConnection that was previously" - " opened."; - return; - } - ConnectionsLog::EstablishedConnection* established_connection = - it->second.get(); - if (established_connection->has_disconnection_reason()) { - LOG(WARNING) << "Unexpected call to physicalConnectionClosed() for medium " - << Medium_Name(medium) - << " which already has disconnection reason " - << DisconnectionReason_Name( - established_connection->disconnection_reason()); - return; - } - FinishPhysicalConnection(established_connection, reason, result); - - if (medium == current_medium_) { - // If the EstablishedConnection we just closed was the one that we have - // marked as current, unset currentMedium. - current_medium_ = UNKNOWN_MEDIUM; - } -} - -void AnalyticsRecorderImpl::LogicalConnection::CloseAllPhysicalConnections() { - for (const auto& physical_connection : physical_connections_) { - ConnectionsLog::EstablishedConnection* established_connection = - physical_connection.second.get(); - if (!established_connection->has_disconnection_reason()) { - FinishPhysicalConnection(established_connection, UNFINISHED, - SafeDisconnectionResult::kSafeDisconnection); - } - } - current_medium_ = UNKNOWN_MEDIUM; -} - -std::vector -AnalyticsRecorderImpl::LogicalConnection::GetEstablisedConnections() { - std::vector established_connections; - if (current_medium_ != UNKNOWN_MEDIUM) { - LOG(WARNING) - << "AnalyticsRecorderImpl expected no more active physical connections " - "before logging this endpoint connection."; - return established_connections; - } - std::transform(physical_connections_.begin(), physical_connections_.end(), - std::back_inserter(established_connections), - [](auto& kv) { return *kv.second; }); - physical_connections_.clear(); - - for (auto& established_connection : established_connections) { - if (absl::Milliseconds(established_connection.duration_millis()) >= - kConnectionTokenMaxLife) { - LOG(INFO) << "connection token exceed TTL, drop token."; - established_connection.set_connection_token(""); - } - } - - return established_connections; -} - -void AnalyticsRecorderImpl::LogicalConnection::IncomingPayloadStarted( - std::int64_t payload_id, PayloadType type, std::int64_t total_size_bytes) { - incoming_payloads_.insert( - {payload_id, std::make_unique(type, total_size_bytes)}); -} - -void AnalyticsRecorderImpl::LogicalConnection::ChunkReceived( - std::int64_t payload_id, std::int64_t size_bytes) { - auto it = incoming_payloads_.find(payload_id); - if (it == incoming_payloads_.end()) { - return; - } - PendingPayload* pending_payload = it->second.get(); - pending_payload->AddChunk(size_bytes); -} - -void AnalyticsRecorderImpl::LogicalConnection::IncomingPayloadDone( - std::int64_t payload_id, PayloadStatus status, - OperationResultCode operation_result_code) { - if (current_medium_ == UNKNOWN_MEDIUM) { - LOG(WARNING) << "Unexpected call to incomingPayloadDone() while " - "AnalyticsRecorderImpl has no active current medium."; - return; - } - auto it = physical_connections_.find(current_medium_); - if (it != physical_connections_.end()) { - const std::unique_ptr& - established_connection = it->second; - auto it = incoming_payloads_.find(payload_id); - if (it != incoming_payloads_.end()) { - it->second->SetOperationResultCode(operation_result_code); - *established_connection->add_received_payload() = - it->second->GetProtoPayload(status); - incoming_payloads_.erase(it); - } - } -} - -void AnalyticsRecorderImpl::LogicalConnection::OutgoingPayloadStarted( - std::int64_t payload_id, PayloadType type, std::int64_t total_size_bytes) { - outgoing_payloads_.insert( - {payload_id, std::make_unique(type, total_size_bytes)}); -} - -void AnalyticsRecorderImpl::LogicalConnection::ChunkSent( - std::int64_t payload_id, std::int64_t size_bytes) { - auto it = outgoing_payloads_.find(payload_id); - if (it == outgoing_payloads_.end()) { - return; - } - PendingPayload* payload = it->second.get(); - payload->AddChunk(size_bytes); -} - -void AnalyticsRecorderImpl::LogicalConnection::OutgoingPayloadDone( - std::int64_t payload_id, PayloadStatus status, - OperationResultCode operation_result_code) { - if (current_medium_ == UNKNOWN_MEDIUM) { - LOG(WARNING) << "Unexpected call to outgoingPayloadDone() while " - "AnalyticsRecorderImpl has no active current medium."; - return; - } - auto it = physical_connections_.find(current_medium_); - if (it != physical_connections_.end()) { - const std::unique_ptr& - established_connection = it->second; - auto it = outgoing_payloads_.find(payload_id); - if (it != outgoing_payloads_.end()) { - it->second->SetOperationResultCode(operation_result_code); - *established_connection->add_sent_payload() = - it->second->GetProtoPayload(status); - outgoing_payloads_.erase(it); - } - } -} - -void AnalyticsRecorderImpl::LogicalConnection::FinishPhysicalConnection( - ConnectionsLog::EstablishedConnection* established_connection, - DisconnectionReason reason, SafeDisconnectionResult result) { - established_connection->set_disconnection_reason(reason); - established_connection->set_safe_disconnection_result( - ConvertToProtoSafeDisconnectionResult(result)); - established_connection->set_duration_millis( - absl::ToUnixMillis(SystemClock::ElapsedRealtime()) - - established_connection->duration_millis()); - - // Add any not-yet-finished payloads to this EstablishedConnection. - std::vector in_payloads = - ResolvePendingPayloads(incoming_payloads_, reason); - absl::c_move(in_payloads, - RepeatedFieldBackInserter( - established_connection->mutable_received_payload())); - std::vector out_payloads = - ResolvePendingPayloads(outgoing_payloads_, reason); - absl::c_move(out_payloads, - RepeatedFieldBackInserter( - established_connection->mutable_sent_payload())); -} - -std::vector -AnalyticsRecorderImpl::LogicalConnection::ResolvePendingPayloads( - absl::btree_map>& - pending_payloads, - DisconnectionReason reason) { - std::vector completed_payloads; - absl::btree_map> - upgraded_payloads; - PayloadStatus status = - reason == UPGRADED ? MOVED_TO_NEW_MEDIUM : CONNECTION_CLOSED; - - OperationResultCode operation_result_code = - GetPendingPayloadResultCodeFromReason(reason); - for (const auto& item : pending_payloads) { - const std::unique_ptr& pending_payload = item.second; - pending_payload->SetOperationResultCode(operation_result_code); - ConnectionsLog::Payload proto_payload = - pending_payload->GetProtoPayload(status); - completed_payloads.push_back(proto_payload); - if (reason == UPGRADED) { - upgraded_payloads.insert( - {item.first, - std::make_unique(pending_payload->type(), - pending_payload->total_size_bytes(), - operation_result_code)}); - } - } - pending_payloads.clear(); - - if (reason == UPGRADED) { - // Re-populate the map with a new PendingPayload for each pending payload, - // since we expect them to be completed on the next EstablishedConnection. - pending_payloads = std::move(upgraded_payloads); - } - // Return the list of completed payloads to be added to the current - // EstablishedConnection. - return completed_payloads; -} - -OperationResultCode -AnalyticsRecorderImpl::LogicalConnection::GetPendingPayloadResultCodeFromReason( - DisconnectionReason reason) { - switch (reason) { - case UPGRADED: - return OperationResultCode::MISCELLEANEOUS_MOVE_TO_NEW_MEDIUM; - case DisconnectionReason::LOCAL_DISCONNECTION: - return OperationResultCode::CLIENT_CANCELLATION_LOCAL_DISCONNECT; - case DisconnectionReason::REMOTE_DISCONNECTION: - return OperationResultCode::CLIENT_CANCELLATION_REMOTE_DISCONNECT; - default: - return OperationResultCode::NEARBY_GENERIC_CONNECTION_CLOSED; - } -} - -OperationResultCategory AnalyticsRecorderImpl::GetOperationResultCategory( - location::nearby::proto::connections::OperationResultCode result_code) { - return ConvertToOperationResultCategory(result_code); -} - -void AnalyticsRecorderImpl::Sync() { MutexLock lock(&mutex_); } - -} // namespace nearby::analytics diff --git a/connections/implementation/analytics/analytics_recorder_impl.h b/connections/implementation/analytics/analytics_recorder_impl.h deleted file mode 100644 index dfe0a342..00000000 --- a/connections/implementation/analytics/analytics_recorder_impl.h +++ /dev/null @@ -1,459 +0,0 @@ -// Copyright 2022-2023 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 -// -// https://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 ANALYTICS_ANALYTICS_RECORDER_IMPL_H_ -#define ANALYTICS_ANALYTICS_RECORDER_IMPL_H_ - -#include -#include -#include -#include -#include - -#include "absl/base/thread_annotations.h" -#include "absl/container/btree_map.h" -#include "absl/strings/string_view.h" -#include "absl/time/time.h" -#include "connections/implementation/analytics/advertising_metadata_params.h" -#include "connections/implementation/analytics/analytics_recorder.h" -#include "connections/implementation/analytics/connection_attempt_metadata_params.h" -#include "connections/implementation/analytics/discovery_metadata_params.h" -#include "connections/payload_type.h" -#include "connections/strategy.h" -#include "internal/analytics/event_logger.h" -#include "internal/platform/error_code_params.h" -#include "internal/platform/implementation/system_clock.h" -#include "internal/platform/mutex.h" -#include "internal/proto/analytics/connections_log.pb.h" -#include "proto/connections_enums.pb.h" - -namespace nearby::analytics { - -class AnalyticsRecorderImpl : public AnalyticsRecorder { - public: - explicit AnalyticsRecorderImpl( - ::nearby::analytics::EventLogger* event_logger); - ~AnalyticsRecorderImpl() override; - - // Advertising phase - void OnStartAdvertising( - connections::Strategy strategy, - const std::vector& mediums, - AdvertisingMetadataParams* advertising_metadata_params) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnStopAdvertising() override ABSL_LOCKS_EXCLUDED(mutex_); - - int GetNextAdvertisingUpdateIndex() override ABSL_LOCKS_EXCLUDED(mutex_); - - // Connection listening - void OnStartedIncomingConnectionListening( - connections::Strategy strategy) override ABSL_LOCKS_EXCLUDED(mutex_); - void OnStoppedIncomingConnectionListening() override - ABSL_LOCKS_EXCLUDED(mutex_); - - // Discovery phase - void OnStartDiscovery( - connections::Strategy strategy, - const std::vector& mediums, - DiscoveryMetadataParams* discovery_metadata_params) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnStopDiscovery() override ABSL_LOCKS_EXCLUDED(mutex_); - - int GetNextDiscoveryUpdateIndex() override ABSL_LOCKS_EXCLUDED(mutex_); - void OnEndpointFound(location::nearby::proto::connections::Medium medium) - override ABSL_LOCKS_EXCLUDED(mutex_); - - // Connection request - void OnRequestConnection(const connections::Strategy& strategy, - const std::string& endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - - void OnConnectionRequestReceived(const std::string& remote_endpoint_id) - override ABSL_LOCKS_EXCLUDED(mutex_); - void OnConnectionRequestSent(const std::string& remote_endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnRemoteEndpointAccepted(const std::string& remote_endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnLocalEndpointAccepted(const std::string& remote_endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnRemoteEndpointRejected(const std::string& remote_endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnLocalEndpointRejected(const std::string& remote_endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - - // Connection attempt - void OnIncomingConnectionAttempt( - location::nearby::proto::connections::ConnectionAttemptType type, - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::ConnectionAttemptResult result, - absl::Duration duration, const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) - override ABSL_LOCKS_EXCLUDED(mutex_); - void OnOutgoingConnectionAttempt( - const std::string& remote_endpoint_id, - location::nearby::proto::connections::ConnectionAttemptType type, - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::ConnectionAttemptResult result, - absl::Duration duration, const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) - override ABSL_LOCKS_EXCLUDED(mutex_); - - // Connection established - void OnConnectionEstablished( - const std::string& endpoint_id, - location::nearby::proto::connections::Medium medium, - const std::string& connection_token) override ABSL_LOCKS_EXCLUDED(mutex_); - void OnConnectionClosed( - const std::string& endpoint_id, - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::DisconnectionReason reason, - SafeDisconnectionResult result) override ABSL_LOCKS_EXCLUDED(mutex_); - - // Payload - void OnIncomingPayloadStarted(const std::string& endpoint_id, - std::int64_t payload_id, - connections::PayloadType type, - std::int64_t total_size_bytes) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnPayloadChunkReceived(const std::string& endpoint_id, - std::int64_t payload_id, - std::int64_t chunk_size_bytes) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnIncomingPayloadDone( - const std::string& endpoint_id, std::int64_t payload_id, - location::nearby::proto::connections::PayloadStatus status, - location::nearby::proto::connections::OperationResultCode - operation_result_code) override ABSL_LOCKS_EXCLUDED(mutex_); - void OnOutgoingPayloadStarted(const std::vector& endpoint_ids, - std::int64_t payload_id, - connections::PayloadType type, - std::int64_t total_size_bytes) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnPayloadChunkSent(const std::string& endpoint_id, - std::int64_t payload_id, - std::int64_t chunk_size_bytes) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnOutgoingPayloadDone( - const std::string& endpoint_id, std::int64_t payload_id, - location::nearby::proto::connections::PayloadStatus status, - location::nearby::proto::connections::OperationResultCode - operation_result_code) override ABSL_LOCKS_EXCLUDED(mutex_); - - // BandwidthUpgrade - void OnBandwidthUpgradeStarted( - const std::string& endpoint_id, - location::nearby::proto::connections::Medium from_medium, - location::nearby::proto::connections::Medium to_medium, - location::nearby::proto::connections::ConnectionAttemptDirection - direction, - const std::string& connection_token) override ABSL_LOCKS_EXCLUDED(mutex_); - void UpdateBwUpgradeNetworkInfo(const std::string& endpoint_id, - int num_interfaces, - int num_ipv6_only_interfaces) override - ABSL_LOCKS_EXCLUDED(mutex_); - void OnBandwidthUpgradeError( - const std::string& endpoint_id, - location::nearby::proto::connections::BandwidthUpgradeResult result, - location::nearby::proto::connections::BandwidthUpgradeErrorStage - error_stage, - location::nearby::proto::connections::OperationResultCode - operation_result_code) override ABSL_LOCKS_EXCLUDED(mutex_); - void OnBandwidthUpgradeSuccess(const std::string& endpoint_id) override - ABSL_LOCKS_EXCLUDED(mutex_); - - // Error Code - void OnErrorCode(const ErrorCodeParams& params) override; - - void LogStartSession() override ABSL_LOCKS_EXCLUDED(mutex_); - void LogSession() override ABSL_LOCKS_EXCLUDED(mutex_); - - bool IsSessionLogged() override; - - location::nearby::proto::connections::OperationResultCategory - GetOperationResultCategory( - location::nearby::proto::connections::OperationResultCode result_code) - override; - - void Sync() override; - - private: - // Tracks the chunks and duration of a Payload on a particular medium. - class PendingPayload { - public: - PendingPayload(location::nearby::proto::connections::PayloadType type, - std::int64_t total_size_bytes) - : PendingPayload(type, total_size_bytes, - location::nearby::proto::connections:: - OperationResultCode::DETAIL_UNKNOWN) {} - PendingPayload(location::nearby::proto::connections::PayloadType type, - std::int64_t total_size_bytes, - location::nearby::proto::connections::OperationResultCode - operation_result_code) - : start_time_(SystemClock::ElapsedRealtime()), - type_(type), - total_size_bytes_(total_size_bytes), - num_bytes_transferred_(0), - num_chunks_(0), - operation_result_code_(operation_result_code) {} - ~PendingPayload() = default; - - void AddChunk(std::int64_t chunk_size_bytes); - - location::nearby::analytics::proto::ConnectionsLog::Payload GetProtoPayload( - location::nearby::proto::connections::PayloadStatus status); - - location::nearby::proto::connections::PayloadType type() const { - return type_; - } - - std::int64_t total_size_bytes() const { return total_size_bytes_; } - - void SetOperationResultCode( - location::nearby::proto::connections::OperationResultCode - operation_result_code) { - operation_result_code_ = operation_result_code; - } - - private: - absl::Time start_time_; - location::nearby::proto::connections::PayloadType type_; - std::int64_t total_size_bytes_; - std::int64_t num_bytes_transferred_; - int num_chunks_; - location::nearby::proto::connections::OperationResultCode - operation_result_code_ = location::nearby::proto::connections:: - OperationResultCode::DETAIL_UNKNOWN; - }; - - class LogicalConnection { - public: - LogicalConnection( - location::nearby::proto::connections::Medium initial_medium, - const std::string& connection_token) { - PhysicalConnectionEstablished(initial_medium, connection_token); - } - LogicalConnection(const LogicalConnection&) = delete; - LogicalConnection(LogicalConnection&& other) - : current_medium_(std::move(other.current_medium_)), - physical_connections_(std::move(other.physical_connections_)), - incoming_payloads_(std::move(other.incoming_payloads_)), - outgoing_payloads_(std::move(other.outgoing_payloads_)) {} - LogicalConnection& operator=(const LogicalConnection&) = delete; - LogicalConnection&& operator=(LogicalConnection&&) = delete; - ~LogicalConnection() = default; - - void PhysicalConnectionEstablished( - location::nearby::proto::connections::Medium medium, - const std::string& connection_token); - void PhysicalConnectionClosed( - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::DisconnectionReason reason, - SafeDisconnectionResult result); - void CloseAllPhysicalConnections(); - - void IncomingPayloadStarted( - std::int64_t payload_id, - location::nearby::proto::connections::PayloadType type, - std::int64_t total_size_bytes); - void ChunkReceived(std::int64_t payload_id, std::int64_t size_bytes); - void IncomingPayloadDone( - std::int64_t payload_id, - location::nearby::proto::connections::PayloadStatus status, - location::nearby::proto::connections::OperationResultCode - operation_result_code); - void OutgoingPayloadStarted( - std::int64_t payload_id, - location::nearby::proto::connections::PayloadType type, - std::int64_t total_size_bytes); - void ChunkSent(std::int64_t payload_id, std::int64_t size_bytes); - void OutgoingPayloadDone( - std::int64_t payload_id, - location::nearby::proto::connections::PayloadStatus status, - location::nearby::proto::connections::OperationResultCode - operation_result_code); - - std::vector - GetEstablisedConnections(); - - private: - void FinishPhysicalConnection( - location::nearby::analytics::proto::ConnectionsLog:: - EstablishedConnection* established_connection, - location::nearby::proto::connections::DisconnectionReason reason, - SafeDisconnectionResult result); - std::vector - ResolvePendingPayloads( - absl::btree_map>& - pending_payloads, - location::nearby::proto::connections::DisconnectionReason reason); - location::nearby::proto::connections::OperationResultCode - GetPendingPayloadResultCodeFromReason( - location::nearby::proto::connections::DisconnectionReason reason); - - location::nearby::proto::connections::Medium current_medium_ = - location::nearby::proto::connections::UNKNOWN_MEDIUM; - absl::btree_map> - physical_connections_; - absl::btree_map> - incoming_payloads_; - absl::btree_map> - outgoing_payloads_; - }; - - bool CanRecordAnalyticsLocked(absl::string_view method_name) - ABSL_SHARED_LOCKS_REQUIRED(mutex_); - - // Callbacks the ConnectionsLog proto byte array data to the EventLogger with - // ClientSession sub-proto. - void LogClientSessionLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - // Callbacks the ConnectionsLog proto byte array data to the EventLogger. - void LogEvent(location::nearby::proto::connections::EventType event_type); - - void UpdateStrategySessionLocked( - connections::Strategy strategy, - location::nearby::proto::connections::SessionRole role) - ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - void RecordAdvertisingPhaseDurationAndReasonLocked(bool on_stop) const - ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void FinishAdvertisingPhaseLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - void RecordDiscoveryPhaseDurationAndReasonLocked(bool on_stop) const - ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void FinishDiscoveryPhaseLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - bool UpdateAdvertiserConnectionRequestLocked( - location::nearby::analytics::proto::ConnectionsLog::ConnectionRequest* - request) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - bool UpdateDiscovererConnectionRequestLocked( - location::nearby::analytics::proto::ConnectionsLog::ConnectionRequest* - request) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - bool BothEndpointsRespondedLocked( - location::nearby::analytics::proto::ConnectionsLog::ConnectionRequest* - request) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void LocalEndpointRespondedLocked( - const std::string& remote_endpoint_id, - location::nearby::proto::connections::ConnectionRequestResponse response) - ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - void RemoteEndpointRespondedLocked( - const std::string& remote_endpoint_id, - location::nearby::proto::connections::ConnectionRequestResponse response) - ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - void MarkConnectionRequestIgnoredLocked( - location::nearby::analytics::proto::ConnectionsLog::ConnectionRequest* - request) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void OnIncomingConnectionAttemptLocked( - location::nearby::proto::connections::ConnectionAttemptType type, - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::ConnectionAttemptResult result, - absl::Duration duration, const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) - ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void OnOutgoingConnectionAttemptLocked( - const std::string& remote_endpoint_id, - location::nearby::proto::connections::ConnectionAttemptType type, - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::ConnectionAttemptResult result, - absl::Duration duration, const std::string& connection_token, - ConnectionAttemptMetadataParams* connection_attempt_metadata_params) - ABSL_SHARED_LOCKS_REQUIRED(mutex_); - bool ConnectionAttemptResultCodeExistedLocked( - location::nearby::proto::connections::Medium medium, - location::nearby::proto::connections::ConnectionAttemptDirection - direction, - const std::string& connection_token, - location::nearby::proto::connections::ConnectionAttemptType type, - location::nearby::proto::connections::OperationResultCode - operation_result_code) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - bool EraseIfBandwidthUpgradeRecordExistedLocked( - const std::string& endpoint_id, - location::nearby::proto::connections::BandwidthUpgradeResult result, - location::nearby::proto::connections::BandwidthUpgradeErrorStage - error_stage, - location::nearby::proto::connections::OperationResultCode - operation_result_code) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void FinishUpgradeAttemptLocked( - const std::string& endpoint_id, - location::nearby::proto::connections::BandwidthUpgradeResult result, - location::nearby::proto::connections::BandwidthUpgradeErrorStage - error_stage, - location::nearby::proto::connections::OperationResultCode - operation_result_code, - bool erase_item = true) ABSL_SHARED_LOCKS_REQUIRED(mutex_); - void FinishStrategySessionLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - - int GetLatestUpdateIndexLocked( - const std::vector& list) - ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - - location::nearby::proto::connections::ConnectionsStrategy - StrategyToConnectionStrategy(connections::Strategy strategy); - location::nearby::proto::connections::PayloadType - PayloadTypeToProtoPayloadType(connections::PayloadType type); - - // Not owned by AnalyticsRecorderImpl. Pointer must refer to a valid object - // that outlives the one constructed. - ::nearby::analytics::EventLogger* event_logger_; - - // Protects all sub-protos reading and writing in ConnectionLog. - Mutex mutex_; - - // ClientSession - std::unique_ptr< - location::nearby::analytics::proto::ConnectionsLog::ClientSession> - client_session_; - absl::Time started_client_session_time_; - bool session_was_logged_ ABSL_GUARDED_BY(mutex_) = false; - bool start_client_session_was_logged_ ABSL_GUARDED_BY(mutex_) = false; - - // Current StrategySession - connections::Strategy current_strategy_ ABSL_GUARDED_BY(mutex_) = - connections::Strategy::kNone; - std::unique_ptr< - location::nearby::analytics::proto::ConnectionsLog::StrategySession> - current_strategy_session_ ABSL_GUARDED_BY(mutex_); - absl::Time started_strategy_session_time_ ABSL_GUARDED_BY(mutex_); - - // Current AdvertisingPhase - std::unique_ptr< - location::nearby::analytics::proto::ConnectionsLog::AdvertisingPhase> - current_advertising_phase_; - absl::Time started_advertising_phase_time_ = absl::InfinitePast(); - - // Current DiscoveryPhase - std::unique_ptr< - location::nearby::analytics::proto::ConnectionsLog::DiscoveryPhase> - current_discovery_phase_; - absl::Time started_discovery_phase_time_ = absl::InfinitePast(); - - absl::btree_map> - incoming_connection_requests_ ABSL_GUARDED_BY(mutex_); - absl::btree_map> - outgoing_connection_requests_ ABSL_GUARDED_BY(mutex_); - absl::btree_map> - active_connections_ ABSL_GUARDED_BY(mutex_); - absl::btree_map> - bandwidth_upgrade_attempts_ ABSL_GUARDED_BY(mutex_); -}; - -} // namespace nearby::analytics - -#endif // ANALYTICS_ANALYTICS_RECORDER_IMPL_H_ diff --git a/connections/implementation/analytics/analytics_recorder_impl_test.cc b/connections/implementation/analytics/analytics_recorder_impl_test.cc deleted file mode 100644 index 53bf6afe..00000000 --- a/connections/implementation/analytics/analytics_recorder_impl_test.cc +++ /dev/null @@ -1,2579 +0,0 @@ -// Copyright 2022-2023 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 -// -// https://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 "connections/implementation/analytics/analytics_recorder_impl.h" - -#include - -#include -#include -#include -#include - -#include "net/proto2/contrib/parse_proto/parse_text_proto.h" -#include "gmock/gmock.h" -#include "protobuf-matchers/protocol-buffer-matchers.h" -#include "gtest/gtest.h" -#include "absl/time/time.h" -#include "connections/implementation/analytics/analytics_recorder.h" -#include "connections/implementation/analytics/connection_attempt_metadata_params.h" -#include "connections/implementation/analytics/operation_result_with_medium.h" -#include "connections/payload_type.h" -#include "connections/strategy.h" -#include "internal/analytics/mock_event_logger.h" -#include "internal/platform/count_down_latch.h" -#include "internal/platform/error_code_params.h" -#include "internal/platform/error_code_recorder.h" -#include "internal/platform/exception.h" -#include "internal/platform/medium_environment.h" -#include "internal/proto/analytics/connections_log.proto.h" -#include "proto/connections_enums.proto.h" - -namespace nearby::analytics { -namespace { - -using ::location::nearby::analytics::proto::ConnectionsLog; -using SafeDisconnectionResult = nearby::analytics::SafeDisconnectionResult; -using ::location::nearby::errorcode::proto::DISCONNECT; -using ::location::nearby::errorcode::proto::DISCONNECT_NETWORK_FAILED; -using ::location::nearby::errorcode::proto::INVALID_PARAMETER; -using ::location::nearby::errorcode::proto::NULL_BLUETOOTH_DEVICE_NAME; -using ::location::nearby::errorcode::proto::START_DISCOVERING; -using ::location::nearby::errorcode::proto::START_EXTENDED_DISCOVERING_FAILED; -using ::location::nearby::errorcode::proto:: - TACHYON_SEND_MESSAGE_STATUS_EXCEPTION; -using ::location::nearby::proto::connections::BLE; -using ::location::nearby::proto::connections::BLUETOOTH; -using ::location::nearby::proto::connections::CLIENT_SESSION; -using ::location::nearby::proto::connections::ERROR_CODE; -using ::location::nearby::proto::connections::EventType; -using ::location::nearby::proto::connections::INCOMING; -using ::location::nearby::proto::connections::INITIAL; -using ::location::nearby::proto::connections::LOCAL_DISCONNECTION; -using ::location::nearby::proto::connections::Medium; -using ::location::nearby::proto::connections::OperationResultCategory; -using ::location::nearby::proto::connections::OperationResultCode; -using ::location::nearby::proto::connections::RESULT_ERROR; -using ::location::nearby::proto::connections::RESULT_SUCCESS; -using ::location::nearby::proto::connections::START_CLIENT_SESSION; -using ::location::nearby::proto::connections::START_STRATEGY_SESSION; -using ::location::nearby::proto::connections::STOP_CLIENT_SESSION; -using ::location::nearby::proto::connections::STOP_STRATEGY_SESSION; -using ::location::nearby::proto::connections::SUCCESS; -using ::location::nearby::proto::connections::UPGRADED; -using ::location::nearby::proto::connections::WEB_RTC; -using ::location::nearby::proto::connections::WIFI_LAN; -using ::location::nearby::proto::connections::WIFI_LAN_MEDIUM_ERROR; -using ::location::nearby::proto::connections::WIFI_LAN_SOCKET_CREATION; -using ::nearby::analytics::MockEventLogger; -using ::proto2::contrib::parse_proto::ParseTextProtoOrDie; -using ::testing::Contains; -using ::protobuf_matchers::EqualsProto; -using ::testing::Not; - -constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000); - -class FakeEventLogger : public MockEventLogger { - public: - explicit FakeEventLogger(CountDownLatch& client_session_done_latch) - : client_session_done_latch_(client_session_done_latch) {} - - FakeEventLogger(CountDownLatch& client_session_done_latch, - CountDownLatch* start_client_session_done_latch_ptr) - : client_session_done_latch_(client_session_done_latch), - start_client_session_done_latch_ptr_( - start_client_session_done_latch_ptr) {} - - void Log(const ConnectionsLog& message) override { - EventType event_type = message.event_type(); - logged_event_types_.push_back(event_type); - if (event_type == CLIENT_SESSION) { - logged_client_session_count_++; - logged_client_session_ = message.client_session(); - } - if (event_type == ERROR_CODE) { - error_code_ = message.error_code(); - } - if (event_type == STOP_CLIENT_SESSION) { - client_session_done_latch_.CountDown(); - } - if (start_client_session_done_latch_ptr_ != nullptr && - event_type == START_CLIENT_SESSION) { - start_client_session_done_latch_ptr_->CountDown(); - } - } - - int GetLoggedClientSessionCount() const { - return logged_client_session_count_; - } - - const ConnectionsLog::ClientSession& GetLoggedClientSession() { - return logged_client_session_; - } - - const ConnectionsLog::ErrorCode& GetErrorCode() { return error_code_; } - - std::vector GetLoggedEventTypes() { return logged_event_types_; } - - void SetClientSessionDoneLatch( - const CountDownLatch& client_session_done_latch) { - client_session_done_latch_ = client_session_done_latch; - } - - void SetStartClientSessionDoneLatchPtr( - CountDownLatch* start_client_session_done_latch_ptr) { - start_client_session_done_latch_ptr_ = start_client_session_done_latch_ptr; - } - - private: - int logged_client_session_count_ = 0; - CountDownLatch& client_session_done_latch_; - CountDownLatch* start_client_session_done_latch_ptr_ = nullptr; - ConnectionsLog::ClientSession logged_client_session_; - ConnectionsLog::ErrorCode error_code_; - std::vector logged_event_types_; -}; - -class AnalyticsRecorderTest : public ::testing::Test { - protected: - void SetUp() override { - MediumEnvironment::Instance().Start({.use_simulated_clock = true}); - } - - void TearDown() override { MediumEnvironment::Instance().Stop(); } -}; - -// Test if session_was_logged_ is reset by checking if LogSession can take -// effect again or not. -TEST_F(AnalyticsRecorderTest, SessionOnlyLoggedOnceWorks) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - analytics_recorder.LogSession(); - analytics_recorder.LogSession(); - analytics_recorder.LogSession(); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - // Only called once. - EXPECT_EQ(event_logger.GetLoggedClientSessionCount(), 1); -} - -TEST_F(AnalyticsRecorderTest, SetFieldsCorrectlyForNestedAdvertisingCalls) { - connections::Strategy strategy = connections::Strategy::kP2pStar; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLUETOOTH); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - advertising_metadata_params->operation_result_with_mediums = { - operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(50)); - analytics_recorder.OnStartAdvertising(strategy, /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStopAdvertising(); - operation_result.set_medium(BLE); - advertising_metadata_params->operation_result_with_mediums = { - operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStartAdvertising(strategy, /*mediums=*/{BLUETOOTH}, - advertising_metadata_params.get()); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 650 - strategy_session { - duration_millis: 600 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 100 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: CLIENT_STOP_ADVERTISING - } - advertising_phase { - duration_millis: 300 - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLE - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - (EqualsProto(strategy_session_proto))); -} - -TEST_F(AnalyticsRecorderTest, SetFieldsCorrectlyForNestedDiscoveryCalls) { - connections::Strategy strategy = connections::Strategy::kP2pStar; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLUETOOTH); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - OperationResultWithMedium operation_result2; - operation_result2.set_medium(BLE); - operation_result2.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result2.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams( - /*is_extended_advertisement_supported*/ true, - /*connected_ap_frequency*/ 1, /*is_nfc_available=*/false, - {operation_result, operation_result2}); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(strategy, /*mediums=*/{BLE, BLUETOOTH}, - discovery_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStopDiscovery(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnEndpointFound(BLUETOOTH); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnEndpointFound(BLE); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - - auto discovery_metadata_params2 = - analytics_recorder.BuildDiscoveryMetadataParams( - /*is_extended_advertisement_supported*/ true, - /*connected_ap_frequency*/ 1, /*is_nfc_available=*/false, - {operation_result}); - analytics_recorder.OnStartDiscovery(strategy, /*mediums=*/{BLUETOOTH}, - discovery_metadata_params2.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 2100 - strategy_session { - duration_millis: 2000 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 200 - medium: BLE - medium: BLUETOOTH - discovered_endpoint { medium: BLUETOOTH latency_millis: 500 } - discovered_endpoint { medium: BLE latency_millis: 900 } - discovery_metadata { - supports_extended_ble_advertisements: true - connected_ap_frequency: 1 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - adv_dis_result { - medium: BLE - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: CLIENT_STOP_DISCOVERING - } - discovery_phase { - duration_millis: 600 - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: true - connected_ap_frequency: 1 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: FINISH_SESSION_STOP_DISCOVERING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, - OneStrategySessionForMultipleRoundsOfDiscoveryAdvertising) { - connections::Strategy strategy = connections::Strategy::kP2pStar; - std::vector mediums = {BLE, BLUETOOTH}; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(strategy, mediums, - advertising_metadata_params.get()); - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStartDiscovery(strategy, mediums, - discovery_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnStopDiscovery(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnStartAdvertising(strategy, mediums, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - analytics_recorder.OnStartDiscovery(strategy, mediums, - discovery_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.OnStopDiscovery(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - analytics_recorder.OnStartDiscovery(strategy, mediums, {}); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1000)); - analytics_recorder.OnStartAdvertising(strategy, mediums, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1100)); - analytics_recorder.OnStopDiscovery(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1200)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1300)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - std::vector event_types = event_logger.GetLoggedEventTypes(); - EXPECT_THAT(event_types, Contains(START_STRATEGY_SESSION).Times(1)); - EXPECT_THAT(event_types, Contains(STOP_STRATEGY_SESSION).Times(1)); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 9100 - strategy_session { - duration_millis: 9000 - strategy: P2P_STAR - role: ADVERTISER - role: DISCOVERER - discovery_phase { - duration_millis: 700 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_DISCOVERING - } - discovery_phase { - duration_millis: 800 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_DISCOVERING - } - discovery_phase { - duration_millis: 2100 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_DISCOVERING - } - advertising_phase { - duration_millis: 500 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - } - advertising_phase { - duration_millis: 600 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - } - advertising_phase { - duration_millis: 2300 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, AdvertiserConnectionRequestsWorks) { - std::string endpoint_id_0 = "endpoint_id_0"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - std::string endpoint_id_3 = "endpoint_id_3"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLE); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - advertising_metadata_params->operation_result_with_mediums = { - operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - analytics_recorder.OnRemoteEndpointRejected(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - analytics_recorder.OnLocalEndpointRejected(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1000)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1100)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_3); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1200)); - analytics_recorder.OnLocalEndpointRejected(endpoint_id_3); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1300)); - analytics_recorder.OnRemoteEndpointRejected(endpoint_id_3); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1400)); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 10500 - strategy_session { - duration_millis: 10400 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 10400 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLE - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - received_connection_request { - duration_millis: 700 - request_delay_millis: 200 - local_response: ACCEPTED - remote_response: ACCEPTED - } - received_connection_request { - duration_millis: 1300 - request_delay_millis: 1400 - local_response: ACCEPTED - remote_response: REJECTED - } - received_connection_request { - duration_millis: 1900 - request_delay_millis: 3500 - local_response: REJECTED - remote_response: ACCEPTED - } - received_connection_request { - duration_millis: 2500 - request_delay_millis: 6500 - local_response: REJECTED - remote_response: REJECTED - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, DiscoveryConnectionRequestsWorks) { - std::string endpoint_id_0 = "endpoint_id_0"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - std::string endpoint_id_3 = "endpoint_id_3"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLUETOOTH); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - discovery_metadata_params->operation_result_with_mediums = {operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - discovery_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionRequestSent(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnConnectionRequestSent(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - analytics_recorder.OnRemoteEndpointRejected(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.OnConnectionRequestSent(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - analytics_recorder.OnLocalEndpointRejected(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1000)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1100)); - - analytics_recorder.OnConnectionRequestSent(endpoint_id_3); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1200)); - analytics_recorder.OnLocalEndpointRejected(endpoint_id_3); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1300)); - analytics_recorder.OnRemoteEndpointRejected(endpoint_id_3); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1400)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 10500 - strategy_session { - duration_millis: 10400 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 10400 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: FINISH_SESSION_STOP_DISCOVERING - sent_connection_request { - duration_millis: 700 - request_delay_millis: 200 - local_response: ACCEPTED - remote_response: ACCEPTED - } - sent_connection_request { - duration_millis: 1300 - request_delay_millis: 1400 - local_response: ACCEPTED - remote_response: REJECTED - } - sent_connection_request { - duration_millis: 1900 - request_delay_millis: 3500 - local_response: REJECTED - remote_response: ACCEPTED - } - sent_connection_request { - duration_millis: 2500 - request_delay_millis: 6500 - local_response: REJECTED - remote_response: REJECTED - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, - AdvertiserUnfinishedConnectionRequestsIncludedAsIgnored) { - std::string endpoint_id_0 = "endpoint_id_0"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLUETOOTH); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - advertising_metadata_params->operation_result_with_mediums = { - operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - // Ignored by local. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - - // Ignored by remote. - analytics_recorder.OnConnectionRequestReceived(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - - // Ignored by both. - analytics_recorder.OnConnectionRequestReceived(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 2800 - strategy_session { - duration_millis: 2700 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 2700 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - received_connection_request { - duration_millis: 2500 - request_delay_millis: 200 - local_response: IGNORED - remote_response: ACCEPTED - } - received_connection_request { - duration_millis: 1800 - request_delay_millis: 900 - local_response: ACCEPTED - remote_response: IGNORED - } - received_connection_request { - duration_millis: 700 - request_delay_millis: 2000 - local_response: IGNORED - remote_response: IGNORED - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, - DiscovererUnfinishedConnectionRequestsIncludedAsIgnored) { - std::string endpoint_id_0 = "endpoint_id_0"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLUETOOTH); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - discovery_metadata_params->operation_result_with_mediums = {operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - discovery_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - - // Ignored by local. - analytics_recorder.OnConnectionRequestSent(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - - // Ignored by remote. - analytics_recorder.OnConnectionRequestSent(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - - // Ignored by both. - analytics_recorder.OnConnectionRequestSent(endpoint_id_2); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 2800 - strategy_session { - duration_millis: 2700 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 2700 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - stop_reason: FINISH_SESSION_STOP_DISCOVERING - sent_connection_request { - duration_millis: 2500 - request_delay_millis: 200 - local_response: IGNORED - remote_response: ACCEPTED - } - sent_connection_request { - duration_millis: 1800 - request_delay_millis: 900 - local_response: ACCEPTED - remote_response: IGNORED - } - sent_connection_request { - duration_millis: 700 - request_delay_millis: 2000 - local_response: IGNORED - remote_response: IGNORED - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, SuccessfulIncomingConnectionAttempt) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - OperationResultWithMedium operation_result; - operation_result.set_medium(BLUETOOTH); - operation_result.set_result_code(OperationResultCode::DETAIL_SUCCESS); - operation_result.set_result_category( - OperationResultCategory::CATEGORY_SUCCESS); - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - advertising_metadata_params->operation_result_with_mediums = { - operation_result}; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - - auto connections_attempt_metadata_params = - std::make_unique(); - connections_attempt_metadata_params->operation_result_code = - OperationResultCode::DETAIL_SUCCESS; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnIncomingConnectionAttempt( - INITIAL, BLUETOOTH, RESULT_SUCCESS, absl::Duration{}, - /*connection_token=*/"", connections_attempt_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 1000 - strategy_session { - duration_millis: 900 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 500 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - adv_dis_result { - medium: BLUETOOTH - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - connection_attempt { - duration_millis: 0 - type: INITIAL - direction: INCOMING - medium: BLUETOOTH - attempt_result: RESULT_SUCCESS - connection_token: "" - connection_attempt_metadata { - technology: CONNECTION_TECHNOLOGY_UNKNOWN_TECHNOLOGY - band: CONNECTION_BAND_UNKNOWN_BAND - frequency: -1 - network_operator: "" - country_code: "" - is_tdls_used: false - try_counts: 0 - wifi_hotspot_status: false - max_tx_speed: 0 - max_rx_speed: 0 - wifi_channel_width: -1 - } - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, - FailedConnectionAttemptUpdatesConnectionRequestNotSent) { - std::string endpoint_id = "endpoint_id"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto connections_attempt_metadata_params = - analytics_recorder.BuildConnectionAttemptMetadataParams( - ::location::nearby::proto::connections:: - CONNECTION_TECHNOLOGY_HOTSPOT_LOCALONLY, - ::location::nearby::proto::connections:: - CONNECTION_BAND_WIFI_BAND_6GHZ, - /*frequency*/ 2400, /*try_count*/ 0, /*network_operator*/ {}, - /*country_code*/ {}, /*is_tdls_used*/ false, - /*wifi_hotspot_enabled*/ false, /*max_wifi_tx_speed*/ 0, - /*max_wifi_rx_speed*/ 0, /*channel_width*/ 0, - OperationResultCode::CONNECTIVITY_BT_CLIENT_SOCKET_CREATION_FAILURE); - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - discovery_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionRequestSent(endpoint_id); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnOutgoingConnectionAttempt( - endpoint_id, INITIAL, BLUETOOTH, RESULT_ERROR, absl::Duration{}, - /*connection_token=*/"", connections_attempt_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 1000 - strategy_session { - duration_millis: 900 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 900 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_DISCOVERING - sent_connection_request { - duration_millis: 300 - request_delay_millis: 200 - local_response: NOT_SENT - remote_response: NOT_SENT - } - } - connection_attempt { - duration_millis: 0 - type: INITIAL - direction: OUTGOING - medium: BLUETOOTH - attempt_result: RESULT_ERROR - connection_token: "" - connection_attempt_metadata { - technology: CONNECTION_TECHNOLOGY_HOTSPOT_LOCALONLY - band: CONNECTION_BAND_WIFI_BAND_6GHZ - frequency: 2400 - network_operator: "" - country_code: "" - is_tdls_used: false - try_counts: 0 - wifi_hotspot_status: false - max_tx_speed: 0 - max_rx_speed: 0 - wifi_channel_width: 0 - } - operation_result { - result_category: CATEGORY_CONNECTIVITY_ERROR - result_code: CONNECTIVITY_BT_CLIENT_SOCKET_CREATION_FAILURE - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, - UnfinishedEstablishedConnectionsAddedAsUnfinished) { - std::string endpoint_id = "endpoint_id"; - std::string connection_token = "connection_token"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH, - connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED, - SafeDisconnectionResult::kUnknown); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN, - connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 1500 - strategy_session { - duration_millis: 1400 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 1400 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - } - established_connection { - duration_millis: 300 - medium: BLUETOOTH - disconnection_reason: UPGRADED - connection_token: "connection_token" - safe_disconnection_result: UNKNOWN_SAFE_DISCONNECTION_RESULT - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - established_connection { - duration_millis: 500 - medium: WIFI_LAN - disconnection_reason: UNFINISHED - connection_token: "connection_token" - safe_disconnection_result: SAFE_DISCONNECTION - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, OutgoingPayloadUpgraded) { - std::string endpoint_id = "endpoint_id"; - std::int64_t payload_id = 123456789; - std::string connection_token = "connection_token"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH, - connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnOutgoingPayloadStarted( - {endpoint_id}, payload_id, connections::PayloadType::kFile, 50); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnConnectionClosed( - endpoint_id, BLUETOOTH, UPGRADED, - SafeDisconnectionResult::kSafeDisconnection); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN, - connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1000)); - analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1100)); - analytics_recorder.OnOutgoingPayloadDone(endpoint_id, payload_id, SUCCESS, - OperationResultCode::DETAIL_SUCCESS); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1200)); - analytics_recorder.OnConnectionClosed( - endpoint_id, WIFI_LAN, LOCAL_DISCONNECTION, - SafeDisconnectionResult::kSafeDisconnection); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1300)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 9100 - strategy_session { - duration_millis: 9000 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 9000 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - } - established_connection { - duration_millis: 1800 - medium: BLUETOOTH - sent_payload { - duration_millis: 1500 - type: FILE - total_size_bytes: 50 - num_bytes_transferred: 20 - num_chunks: 2 - status: MOVED_TO_NEW_MEDIUM - operation_result { - result_category: CATEGORY_MISCELLANEOUS - result_code: MISCELLEANEOUS_MOVE_TO_NEW_MEDIUM - } - } - disconnection_reason: UPGRADED - connection_token: "connection_token" - safe_disconnection_result: SAFE_DISCONNECTION - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - established_connection { - duration_millis: 5000 - medium: WIFI_LAN - sent_payload { - duration_millis: 4500 - type: FILE - total_size_bytes: 50 - num_bytes_transferred: 30 - num_chunks: 3 - status: SUCCESS - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - disconnection_reason: LOCAL_DISCONNECTION - connection_token: "connection_token" - safe_disconnection_result: SAFE_DISCONNECTION - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, UpgradeAttemptWorks) { - std::string endpoint_id = "endpoint_id"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - std::string connection_token = "connection_token"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - - analytics_recorder.OnBandwidthUpgradeStarted(endpoint_id, BLE, WIFI_LAN, - INCOMING, connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - analytics_recorder.OnBandwidthUpgradeStarted( - endpoint_id_1, BLUETOOTH, WIFI_LAN, INCOMING, connection_token); - // Error to upgrade. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnBandwidthUpgradeError( - endpoint_id, WIFI_LAN_MEDIUM_ERROR, WIFI_LAN_SOCKET_CREATION, - OperationResultCode::CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL); - // Success to upgrade. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnBandwidthUpgradeSuccess(endpoint_id_1); - // Upgrade is unfinished. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnBandwidthUpgradeStarted( - endpoint_id_2, BLUETOOTH, WIFI_LAN, INCOMING, connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 2800 - strategy_session { - duration_millis: 2700 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 2700 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - } - upgrade_attempt { - duration_millis: 700 - direction: INCOMING - from_medium: BLE - to_medium: WIFI_LAN - upgrade_result: WIFI_LAN_MEDIUM_ERROR - error_stage: WIFI_LAN_SOCKET_CREATION - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_CONNECTIVITY_ERROR - result_code: CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL - } - } - upgrade_attempt { - duration_millis: 900 - direction: INCOMING - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UPGRADE_RESULT_SUCCESS - error_stage: UPGRADE_SUCCESS - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - upgrade_attempt { - duration_millis: 700 - direction: INCOMING - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UNFINISHED_ERROR - error_stage: UPGRADE_UNFINISHED - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_DEVICE_STATE_ERROR - result_code: DEVICE_STATE_ERROR_UNFINISHED_UPGRADE_ATTEMPTS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, StartListeningForIncomingConnectionsWorks) { - std::string endpoint_id = "endpoint_id"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - std::string connection_token = "connection_token"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartedIncomingConnectionListening( - connections::Strategy::kP2pStar); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - - analytics_recorder.OnBandwidthUpgradeStarted(endpoint_id, BLE, WIFI_LAN, - INCOMING, connection_token); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnBandwidthUpgradeStarted( - endpoint_id_1, BLUETOOTH, WIFI_LAN, INCOMING, connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - // Error to upgrade. - analytics_recorder.OnBandwidthUpgradeError( - endpoint_id, WIFI_LAN_MEDIUM_ERROR, WIFI_LAN_SOCKET_CREATION, - OperationResultCode::CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - // Success to upgrade. - analytics_recorder.OnBandwidthUpgradeSuccess(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - - analytics_recorder.LogSession(); - // ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 2100 - strategy_session { - duration_millis: 2000 - strategy: P2P_STAR - role: ADVERTISER - upgrade_attempt { - direction: INCOMING - duration_millis: 700 - from_medium: BLE - to_medium: WIFI_LAN - upgrade_result: WIFI_LAN_MEDIUM_ERROR - error_stage: WIFI_LAN_SOCKET_CREATION - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_CONNECTIVITY_ERROR - result_code: CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL - } - } - upgrade_attempt { - direction: INCOMING - duration_millis: 900 - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UPGRADE_RESULT_SUCCESS - error_stage: UPGRADE_SUCCESS - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -TEST_F(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectly) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{WEB_RTC}, - discovery_metadata_params.get()); - - ErrorCodeParams error_code_params = ErrorCodeRecorder::BuildErrorCodeParams( - WEB_RTC, DISCONNECT, DISCONNECT_NETWORK_FAILED, - TACHYON_SEND_MESSAGE_STATUS_EXCEPTION, "", "connection_token"); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnErrorCode(error_code_params); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ErrorCode error_code_proto = ParseTextProtoOrDie(R"pb( - medium: WEB_RTC - event: DISCONNECT - description: TACHYON_SEND_MESSAGE_STATUS_EXCEPTION - disconnect_error: DISCONNECT_NETWORK_FAILED - connection_token: "connection_token" - )pb"); - - EXPECT_THAT(event_logger.GetErrorCode(), EqualsProto(error_code_proto)); -} - -TEST_F(AnalyticsRecorderTest, - SetErrorCodeFieldsCorrectlyForUnknownDescription) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{BLUETOOTH}, - discovery_metadata_params.get()); - - ErrorCodeParams error_code_params; - // Skip setting error_code_params.description - error_code_params.medium = BLUETOOTH; - error_code_params.event = START_DISCOVERING; - error_code_params.start_discovering_error = START_EXTENDED_DISCOVERING_FAILED; - error_code_params.connection_token = "connection_token"; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnErrorCode(error_code_params); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ErrorCode error_code_proto = ParseTextProtoOrDie(R"pb( - medium: BLUETOOTH - event: START_DISCOVERING - description: UNKNOWN - start_discovering_error: START_EXTENDED_DISCOVERING_FAILED - connection_token: "connection_token" - )pb"); - - EXPECT_THAT(event_logger.GetErrorCode(), EqualsProto(error_code_proto)); -} - -TEST_F(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectlyForCommonError) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{BLUETOOTH}, - discovery_metadata_params.get()); - - ErrorCodeParams error_code_params = ErrorCodeRecorder::BuildErrorCodeParams( - BLUETOOTH, START_DISCOVERING, INVALID_PARAMETER, - NULL_BLUETOOTH_DEVICE_NAME, "", "connection_token"); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnErrorCode(error_code_params); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ErrorCode error_code_proto = ParseTextProtoOrDie(R"pb( - medium: BLUETOOTH - event: START_DISCOVERING - description: NULL_BLUETOOTH_DEVICE_NAME - common_error: INVALID_PARAMETER - connection_token: "connection_token" - )pb"); - - EXPECT_THAT(event_logger.GetErrorCode(), EqualsProto(error_code_proto)); -} - -TEST_F(AnalyticsRecorderTest, CheckIfSessionWasLogged) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - // LogSession to count down client_session_done_latch. - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - EXPECT_TRUE(analytics_recorder.IsSessionLogged()); -} - -TEST_F(AnalyticsRecorderTest, ConstructAnalyticsRecorder) { - CountDownLatch client_session_done_latch(0); - CountDownLatch start_client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch, - &start_client_session_done_latch); - - // Call the constructor to count down the session_done_latch. - AnalyticsRecorderImpl analytics_recorder(&event_logger); - ASSERT_TRUE(start_client_session_done_latch.Await(kDefaultTimeout).result()); - - std::vector event_types = event_logger.GetLoggedEventTypes(); - EXPECT_EQ(event_types.size(), 1); - EXPECT_THAT(event_types, Contains(START_CLIENT_SESSION).Times(1)); -} - -TEST_F( - AnalyticsRecorderTest, - StartClientSessionOnlyLoggedOnceWorksAfterAnalyticsRecorderIsConstructed) { - CountDownLatch client_session_done_latch(0); - CountDownLatch start_client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch, - &start_client_session_done_latch); - - // Call the constructor to count down the start_client_session_done_latch. - AnalyticsRecorderImpl analytics_recorder(&event_logger); - ASSERT_TRUE(start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // Log start client session once. - EXPECT_THAT(event_logger.GetLoggedEventTypes(), - Contains(START_CLIENT_SESSION).Times(1)); - - // Reset the start_client_session_done_latch. However, LogStartSession cannot - // count down the start_client_session_done_latch. - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - analytics_recorder.LogStartSession(); - ASSERT_FALSE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // No more start client session was logged. - EXPECT_THAT(event_logger.GetLoggedEventTypes(), - Contains(START_CLIENT_SESSION).Times(1)); -} - -TEST_F(AnalyticsRecorderTest, - CanLogStartClientSessionOnceAgainAfterSessionWasLogged) { - CountDownLatch client_session_done_latch(0); - CountDownLatch start_client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch, - &start_client_session_done_latch); - - // Call the constructor to count down the start_client_session_done_latch. - AnalyticsRecorderImpl analytics_recorder(&event_logger); - ASSERT_TRUE(start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // Log start client session once. - EXPECT_THAT(event_logger.GetLoggedEventTypes(), - Contains(START_CLIENT_SESSION).Times(1)); - - // Reset the client_session_done_latch. Call LogSession to count down the - // client_session_done_latch. - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - // Reset the start_client_session_done_latch. Call LogStartSession to count - // down the start_client_session_done_latch. - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - analytics_recorder.LogStartSession(); - analytics_recorder.LogStartSession(); - analytics_recorder.LogStartSession(); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // Can log start client session once again. - EXPECT_THAT(event_logger.GetLoggedEventTypes(), - Contains(START_CLIENT_SESSION).Times(2)); -} - -TEST_F(AnalyticsRecorderTest, - ClearcIncomingConnectionRequestsAfterSessionWasLogged) { - std::string endpoint_id_0 = "endpoint_id_0"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - - // LogSession - analytics_recorder.LogSession(); // call ResetClientSessionLoggingResouces - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto1 = - ParseTextProtoOrDie(R"pb( - duration_millis: 1500 - strategy_session { - duration_millis: 1400 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 1400 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - received_connection_request { - duration_millis: 700 - request_delay_millis: 200 - local_response: ACCEPTED - remote_response: ACCEPTED - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - std::string endpoint_id_1 = "endpoint_id_1"; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - analytics_recorder.OnConnectionRequestReceived(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(1000)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(new_client_session_done_latch.Await(kDefaultTimeout).result()); - - // - if the current_strategy_session_ and current_advertising_phase_ are not - // reset, the duplicate advertising_phase (with the additional - // received_connection_request) will append to the strategy_session) - ConnectionsLog::ClientSession strategy_session_proto2 = ParseTextProtoOrDie( - R"pb( - duration_millis: 0 - strategy_session { - duration_millis: 0 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - received_connection_request { - duration_millis: 0 - request_delay_millis: 0 - local_response: ACCEPTED - remote_response: ACCEPTED - } - } - advertising_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - received_connection_request { - duration_millis: 0 - request_delay_millis: 0 - local_response: ACCEPTED - remote_response: ACCEPTED - } - received_connection_request { - duration_millis: 0 - request_delay_millis: 0 - local_response: ACCEPTED - remote_response: ACCEPTED - } - } - })pb"); - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto2))); -} - -TEST_F(AnalyticsRecorderTest, - ClearcOutgoingConnectionRequestsAfterSessionWasLogged) { - std::string endpoint_id_0 = "endpoint_id_0"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - discovery_metadata_params.get()); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionRequestSent(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - - // LogSession - analytics_recorder.LogSession(); // call ResetClientSessionLoggingResouces - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto1 = - ParseTextProtoOrDie(R"pb( - duration_millis: 1500 - strategy_session { - duration_millis: 1400 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 1400 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_DISCOVERING - sent_connection_request { - duration_millis: 700 - request_delay_millis: 200 - local_response: ACCEPTED - remote_response: ACCEPTED - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - std::string endpoint_id_1 = "endpoint_id_1"; - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnConnectionRequestSent(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_1); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - // - if the current_strategy_session_ and current_discovery_phase_ are - // not reset, the duplicate discovery_phase (with the additional - // sent_connection_request) will append to the strategy_session) - ConnectionsLog::ClientSession strategy_session_proto2 = - ParseTextProtoOrDie(R"pb( - duration_millis: 0 - strategy_session { - duration_millis: 0 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - sent_connection_request { - duration_millis: 0 - request_delay_millis: 0 - local_response: ACCEPTED - remote_response: ACCEPTED - } - } - discovery_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - sent_connection_request { - duration_millis: 0 - request_delay_millis: 0 - local_response: ACCEPTED - remote_response: ACCEPTED - } - sent_connection_request { - duration_millis: 0 - request_delay_millis: 0 - local_response: ACCEPTED - remote_response: ACCEPTED - } - } - })pb"); - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto2))); -} - -TEST_F(AnalyticsRecorderTest, ClearcActiveConnectionsAfterSessionWasLogged) { - connections::Strategy strategy = connections::Strategy::kP2pStar; - std::vector mediums = {BLE, BLUETOOTH}; - std::string endpoint_id = "endpoint_id"; - std::string connection_token = "connection_token"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(strategy, mediums, - advertising_metadata_params.get()); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH, - connection_token); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - // LogSession - analytics_recorder.LogSession(); // call ResetClientSessionLoggingResouces - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - ConnectionsLog::ClientSession strategy_session_proto1 = - ParseTextProtoOrDie(R"pb( - duration_millis: 600 - strategy_session { - duration_millis: 500 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 500 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - } - established_connection { - duration_millis: 300 - medium: BLUETOOTH - disconnection_reason: UNFINISHED - connection_token: "connection_token" - safe_disconnection_result: SAFE_DISCONNECTION - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - // - if the current_strategy_session_ and advertising_phase_ are not - // reset, the duplicate advertising_phase_ (with the additional - // will append to the strategy_session), and the active connection (i.e. - // established_connection) will stay there. - ConnectionsLog::ClientSession strategy_session_proto2 = - ParseTextProtoOrDie(R"pb( - duration_millis: 0 - strategy_session { - duration_millis: 0 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - } - advertising_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - } - established_connection { - duration_millis: 0 - medium: BLUETOOTH - disconnection_reason: UNFINISHED - connection_token: "connection_token" - safe_disconnection_result: SAFE_DISCONNECTION - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto2))); -} - -TEST_F(AnalyticsRecorderTest, - ClearBandwidthUpgradeAttemptsAfterSessionWasLogged) { - std::string endpoint_id = "endpoint_id"; - std::string endpoint_id_1 = "endpoint_id_1"; - std::string endpoint_id_2 = "endpoint_id_2"; - std::string connection_token = "connection_token"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnBandwidthUpgradeStarted(endpoint_id, BLE, WIFI_LAN, - INCOMING, connection_token); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnBandwidthUpgradeStarted( - endpoint_id_1, BLUETOOTH, WIFI_LAN, INCOMING, connection_token); - // - Error to upgrade. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnBandwidthUpgradeError( - endpoint_id, WIFI_LAN_MEDIUM_ERROR, WIFI_LAN_SOCKET_CREATION, - OperationResultCode::CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL); - // - Success to upgrade. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnBandwidthUpgradeSuccess(endpoint_id_1); - - // - Upgrade is unfinished. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnBandwidthUpgradeStarted( - endpoint_id_2, BLUETOOTH, WIFI_LAN, INCOMING, connection_token); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - // LogSession - analytics_recorder.LogSession(); // call ResetClientSessionLoggingResouces - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - // - if the current_strategy_session_ and advertising_phase_ are not - // reset, the duplicate advertising_phase_, and the upgrade_attempts (i.e. - // bandwidth_upgrade_attempts_) will stay there. - ConnectionsLog::ClientSession strategy_session_proto1 = - ParseTextProtoOrDie(R"pb( - duration_millis: 2800 - strategy_session { - duration_millis: 2700 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 2700 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: FINISH_SESSION_STOP_ADVERTISING - } - upgrade_attempt { - direction: INCOMING - duration_millis: 700 - from_medium: BLE - to_medium: WIFI_LAN - upgrade_result: WIFI_LAN_MEDIUM_ERROR - error_stage: WIFI_LAN_SOCKET_CREATION - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_CONNECTIVITY_ERROR - result_code: CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL - } - } - upgrade_attempt { - direction: INCOMING - duration_millis: 900 - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UPGRADE_RESULT_SUCCESS - error_stage: UPGRADE_SUCCESS - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - upgrade_attempt { - direction: INCOMING - duration_millis: 700 - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UNFINISHED_ERROR - error_stage: UPGRADE_UNFINISHED - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_DEVICE_STATE_ERROR - result_code: DEVICE_STATE_ERROR_UNFINISHED_UPGRADE_ATTEMPTS - } - } - })pb"); - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(800)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(900)); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto2 = - ParseTextProtoOrDie(R"pb( - duration_millis: 0 - strategy_session { - duration_millis: 0 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - } - advertising_phase { - duration_millis: 0 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - } - upgrade_attempt { - direction: INCOMING - from_medium: BLE - to_medium: WIFI_LAN - upgrade_result: WIFI_LAN_MEDIUM_ERROR - error_stage: WIFI_LAN_SOCKET_CREATION - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_CONNECTIVITY_ERROR - result_code: CONNECTIVITY_WIFI_LAN_INVALID_CREDENTIAL - } - } - upgrade_attempt { - direction: INCOMING - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UPGRADE_RESULT_SUCCESS - error_stage: UPGRADE_SUCCESS - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_SUCCESS - result_code: DETAIL_SUCCESS - } - } - upgrade_attempt { - direction: INCOMING - from_medium: BLUETOOTH - to_medium: WIFI_LAN - upgrade_result: UNFINISHED_ERROR - error_stage: UPGRADE_UNFINISHED - connection_token: "connection_token" - operation_result { - result_category: CATEGORY_DEVICE_STATE_ERROR - result_code: DEVICE_STATE_ERROR_UNFINISHED_UPGRADE_ATTEMPTS - } - } - })pb"); - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto2))); -} - -// Test if current_strategy_ is reset by checking if the same strategy would -// be logged for different client sessions or not. If yes, it should be logged. -// Otherwise, not. -TEST_F(AnalyticsRecorderTest, - CanLogSeparateStartStrategySessionForSameStrategyAfterSessionWasLogged) { - connections::Strategy strategy = connections::Strategy::kP2pStar; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStopAdvertising(); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - // LogSession - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - // The same strategy session shouldn't be logged again with the same client - // session. - EXPECT_THAT(event_logger.GetLoggedEventTypes(), - Contains(START_STRATEGY_SESSION).Times(1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnStartAdvertising(strategy, /*mediums=*/{BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(700)); - - analytics_recorder.LogSession(); - ASSERT_TRUE(new_client_session_done_latch.Await(kDefaultTimeout).result()); - - EXPECT_THAT(event_logger.GetLoggedEventTypes(), - Contains(START_STRATEGY_SESSION).Times(2)); -} - -// Test if current_strategy_session_ is reset. If not, the same strategy session -// proto will be logged. -TEST_F(AnalyticsRecorderTest, - NotLogSameStrategySessionProtoAfterSessionWasLogged) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - // Via OnStartAdvertising, current_strategy_session_is set in - // UpdateStrategySessionLocked. - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - // LogSession - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 600 - strategy_session { - duration_millis: 500 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 200 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - // - if current_strategy_session_ is reset, the same - // strategy_session_proto will be logged. - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.LogSession(); - ASSERT_TRUE(new_client_session_done_latch.Await(kDefaultTimeout).result()); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto))); -} - -// Test if current_advertising_phase_ is reset. -TEST_F(AnalyticsRecorderTest, - NotLogDuplicateAdvertisingPhaseAfterSessionWasLogged) { - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising( - connections::Strategy::kP2pStar, - /*mediums=*/{BLUETOOTH}, - advertising_metadata_params.get()); // set current_advertising_phase_ - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - // LogSession - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto1 = - ParseTextProtoOrDie(R"pb( - duration_millis: 600 - strategy_session { - duration_millis: 500 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 200 - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - // - if the current_strategy_session_ and current_advertising_phase_ are - // not reset, the same strategy_session with two same advertising_phase will - // be logged. - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto2 = - ParseTextProtoOrDie(R"pb( - duration_millis: 0 - strategy_session { - duration_millis: 0 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 0 - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - } - advertising_phase { - duration_millis: 0 - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - } - })pb"); - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto2))); -} - -// Test if current_discovery_phase_ is reset. -TEST_F(AnalyticsRecorderTest, - NotLogDuplicateDiscoveryPhaseAfterSessionWasLogged) { - connections::Strategy strategy = connections::Strategy::kP2pStar; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - auto discovery_metadata_params = - analytics_recorder.BuildDiscoveryMetadataParams( - /*is_extended_advertisement_supported*/ true, - /*connected_ap_frequency*/ 1, /*is_nfc_available=*/false); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartDiscovery( - strategy, {BLUETOOTH}, - discovery_metadata_params.get()); // set current_discovery_phase_ - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStopDiscovery(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - analytics_recorder.OnEndpointFound(BLUETOOTH); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - // LogSession - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto1 = - ParseTextProtoOrDie(R"pb( - duration_millis: 1000 - strategy_session { - duration_millis: 900 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 200 - medium: BLUETOOTH - discovered_endpoint { medium: BLUETOOTH latency_millis: 500 } - discovery_metadata { - supports_extended_ble_advertisements: true - connected_ap_frequency: 1 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_DISCOVERING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto1)); - - // LogStartSession - CountDownLatch new_start_client_session_done_latch(1); - event_logger.SetStartClientSessionDoneLatchPtr( - &new_start_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.LogStartSession(); - ASSERT_TRUE( - new_start_client_session_done_latch.Await(kDefaultTimeout).result()); - - // LogSession again - // - if the current_strategy_session_ and current_discovery_phase_ are not - // reset, the same strategy_session with two same discovery_phase will be - // logged. - CountDownLatch new_client_session_done_latch(1); - event_logger.SetClientSessionDoneLatch(new_client_session_done_latch); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto2 = - ParseTextProtoOrDie(R"pb( - duration_millis: 0 - strategy_session { - duration_millis: 0 - strategy: P2P_STAR - role: DISCOVERER - discovery_phase { - duration_millis: 0 - medium: BLUETOOTH - discovered_endpoint { medium: BLUETOOTH } - discovery_metadata { - supports_extended_ble_advertisements: true - connected_ap_frequency: 1 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_DISCOVERING - } - discovery_phase { - duration_millis: 0 - medium: BLUETOOTH - discovery_metadata { - supports_extended_ble_advertisements: true - connected_ap_frequency: 1 - supports_nfc_technology: false - } - } - })pb"); - EXPECT_THAT(event_logger.GetLoggedClientSession(), - Not(EqualsProto(strategy_session_proto2))); -} - -TEST_F(AnalyticsRecorderTest, - NotAddNewConnectionWithoutCallingOnStartAdvertising) { - std::string endpoint_id = "endpoint_id"; - - CountDownLatch client_session_done_latch(1); - FakeEventLogger event_logger(client_session_done_latch); - AnalyticsRecorderImpl analytics_recorder(&event_logger); - - // via OnStartAdvertising, current_strategy_session_ is set in - // UpdateStrategySessionLocked. - auto advertising_metadata_params = - analytics_recorder.BuildAdvertisingMetadataParams(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(100)); - analytics_recorder.OnStartAdvertising(connections::Strategy::kP2pStar, - /*mediums=*/{BLE, BLUETOOTH}, - advertising_metadata_params.get()); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(200)); - analytics_recorder.OnStopAdvertising(); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(300)); - - // LogSession - analytics_recorder.LogSession(); - ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result()); - - ConnectionsLog::ClientSession strategy_session_proto = - ParseTextProtoOrDie(R"pb( - duration_millis: 600 - strategy_session { - duration_millis: 500 - strategy: P2P_STAR - role: ADVERTISER - advertising_phase { - duration_millis: 200 - medium: BLE - medium: BLUETOOTH - advertising_metadata { - supports_extended_ble_advertisements: false - connected_ap_frequency: 0 - supports_nfc_technology: false - } - stop_reason: CLIENT_STOP_ADVERTISING - } - })pb"); - - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); - - // Without calling OnStartAdvertising won't create new - // current_strategy_session_. - MediumEnvironment::Instance().FastForward(absl::Milliseconds(400)); - analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH, - /*connection_token=*/""); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(500)); - analytics_recorder.OnConnectionClosed( - endpoint_id, BLUETOOTH, UPGRADED, - SafeDisconnectionResult::kSafeDisconnection); - MediumEnvironment::Instance().FastForward(absl::Milliseconds(600)); - analytics_recorder.LogSession(); - - // The proto won't change. - EXPECT_THAT(event_logger.GetLoggedClientSession(), - EqualsProto(strategy_session_proto)); -} - -} // namespace -} // namespace nearby::analytics diff --git a/internal/analytics/BUILD b/internal/analytics/BUILD deleted file mode 100644 index 9b22ebf8..00000000 --- a/internal/analytics/BUILD +++ /dev/null @@ -1,50 +0,0 @@ -load("@rules_cc//cc:cc_library.bzl", "cc_library") - -licenses(["notice"]) -# Copyright 2020 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 -# -# https://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. - -cc_library( - name = "event_logger", - hdrs = [ - "event_logger.h", - ], - visibility = [ - "//connections:__subpackages__", - "//location/nearby/analytics/cpp:__subpackages__", - "//location/nearby/cpp/experiments:__subpackages__", - "//location/nearby/sharing/lib:__subpackages__", - "//sharing:__subpackages__", - ], - deps = [ - "//internal/proto/analytics:connections_log_cc_proto", - "//sharing/proto/analytics:sharing_log_cc_proto", - ], -) - -cc_library( - name = "mock_event_logger", - testonly = True, - hdrs = [ - "mock_event_logger.h", - "sharing_log_matchers.h", - ], - compatible_with = ["//buildenv/target:non_prod"], - visibility = ["//visibility:public"], - deps = [ - ":event_logger", - "@com_google_googletest//:gtest_for_library_testonly", - "@com_google_protobuf//:protobuf_lite", - ], -) diff --git a/internal/analytics/event_logger.h b/internal/analytics/event_logger.h deleted file mode 100644 index b360c659..00000000 --- a/internal/analytics/event_logger.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2022 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 -// -// https://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 NEARBY_ANALYTICS_EVENT_LOGGER_H_ -#define NEARBY_ANALYTICS_EVENT_LOGGER_H_ - -#include "internal/proto/analytics/connections_log.pb.h" -#include "sharing/proto/analytics/nearby_sharing_log.pb.h" - -namespace nearby { -namespace analytics { - -// Allows callers to log the proto collected at the client (e.g. Nearby -// Connections, Nearby Sharing, etc). Callers need to implement the API -// if they want to collect this log. -class EventLogger { - public: - virtual ~EventLogger() = default; - - // Logs the proto details. Might block to do I/O, e.g. upload - // synchronously to some metrics server. - virtual void Log( - const location::nearby::analytics::proto::ConnectionsLog& message) = 0; - virtual void Log(const sharing::analytics::proto::SharingLog& message) = 0; -}; - -} // namespace analytics -} // namespace nearby - -#endif // NEARBY_ANALYTICS_EVENT_LOGGER_H_ diff --git a/internal/analytics/mock_event_logger.h b/internal/analytics/mock_event_logger.h deleted file mode 100644 index 2a6b5774..00000000 --- a/internal/analytics/mock_event_logger.h +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2024 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 -// -// https://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 THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_MOCK_EVENT_LOGGER_H_ -#define THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_MOCK_EVENT_LOGGER_H_ - -#include "gmock/gmock.h" -#include "internal/analytics/event_logger.h" - -namespace nearby::analytics { - -class MockEventLogger : public ::nearby::analytics::EventLogger { - public: - MockEventLogger() = default; - ~MockEventLogger() override = default; - - MOCK_METHOD( - void, Log, - (const location::nearby::analytics::proto::ConnectionsLog& message), - (override)); - MOCK_METHOD(void, Log, (const sharing::analytics::proto::SharingLog& message), - (override)); -}; - -} // namespace nearby::analytics - -#endif // THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_MOCK_EVENT_LOGGER_H_ diff --git a/internal/analytics/sharing_log_matchers.h b/internal/analytics/sharing_log_matchers.h deleted file mode 100644 index ce01eb84..00000000 --- a/internal/analytics/sharing_log_matchers.h +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2024 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 -// -// https://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 THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_SHARING_LOG_MATCHERS_H_ -#define THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_SHARING_LOG_MATCHERS_H_ - -#include "gmock/gmock.h" - -namespace nearby::analytics { - -MATCHER_P(HasCategory, category, "has category") { - return arg.event_category() == category; -} - -MATCHER_P(HasEventType, event_type, "has event type") { - return arg.event_type() == event_type; -} - -MATCHER_P(HasAction, action, "has action") { - return arg.action() == action; -} - -MATCHER_P(HasSessionId, session_id, "has session id") { - return arg.session_id() == session_id; -} - -MATCHER_P(HasDurationMillis, duration_millis, "has duration millis") { - return arg.duration_millis() == duration_millis; -} - -MATCHER_P(SharingLogHasStatus, status, "has status") { - return arg.status() == status; -} - -MATCHER_P(HasRpcName, rpc_name, "has rpc_name") { - return arg.rpc_name() == rpc_name; -} - -MATCHER_P(HasDirection, direction, "has direction") { - return arg.direction() == direction; -} - -MATCHER_P(HasErrorCode, error_code, "has error_code") { - return arg.error_code() == error_code; -} - -MATCHER_P(HasLatencyMillis, latency_millis, "has latency_millis") { - return arg.latency_millis() == latency_millis; -} - -} // namespace nearby::analytics - -#endif // THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_SHARING_LOG_MATCHERS_H_ diff --git a/internal/platform/implementation/BUILD b/internal/platform/implementation/BUILD index 22a42037..94a03367 100644 --- a/internal/platform/implementation/BUILD +++ b/internal/platform/implementation/BUILD @@ -182,6 +182,8 @@ cc_library( tags = ["keep_dep"], # Prevent build_cleaner from removing the dependency. visibility = [ "//:__subpackages__", + "//location/nearby/analytics/cpp:__subpackages__", + "//location/nearby/cpp:__subpackages__", "//location/nearby/sharing/lib:__subpackages__", ], deps = [ diff --git a/internal/platform/implementation/g3/BUILD b/internal/platform/implementation/g3/BUILD index ef0c9b3f..6fb81f20 100644 --- a/internal/platform/implementation/g3/BUILD +++ b/internal/platform/implementation/g3/BUILD @@ -196,7 +196,6 @@ cc_library( "//internal/preferences:__subpackages__", "//internal/proto/analytics:__subpackages__", "//internal/weave:__subpackages__", - "//location/nearby/cpp:__subpackages__", "//location/nearby/sharing/sdk:__subpackages__", "//sharing:__subpackages__", "//third_party/nearby/presence:__subpackages__", diff --git a/internal/proto/analytics/BUILD b/internal/proto/analytics/BUILD index 352db000..f4beb852 100644 --- a/internal/proto/analytics/BUILD +++ b/internal/proto/analytics/BUILD @@ -13,7 +13,9 @@ # limitations under the License. load("@com_google_protobuf//bazel:cc_proto_library.bzl", "cc_proto_library") +load("@com_google_protobuf//bazel:java_lite_proto_library.bzl", "java_lite_proto_library") load("@com_google_protobuf//bazel:proto_library.bzl", "proto_library") +load("@com_google_protobuf//rust:defs.bzl", "rust_proto_library") load("@rules_cc//cc:cc_test.bzl", "cc_test") licenses(["notice"]) @@ -25,14 +27,17 @@ proto_library( srcs = [ "connections_log.proto", ], + compatible_with = ["//buildenv/target:non_prod"], deps = [ "//proto:connections_enums_proto", "//proto/errorcode:error_code_enums_proto", + "//storage/datapol/annotations/proto:datapol_annotations", ], ) cc_proto_library( name = "connections_log_cc_proto", + compatible_with = ["//buildenv/target:non_prod"], visibility = [ "//connections:__subpackages__", "//internal/analytics:__pkg__", @@ -52,9 +57,20 @@ cc_test( ":connections_log_cc_proto", "//internal/platform:logging", "//internal/platform/implementation/g3", # build_cleaner: keep + "//logs/proto/location/nearby:nearby_client_log_cc_proto", "//proto:connections_enums_cc_proto", "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_googletest//:gtest_main", "@com_google_protobuf//:protobuf", ], ) + +rust_proto_library( + name = "connections_log_rust_proto", + deps = [":connections_log_proto"], +) + +java_lite_proto_library( + name = "connections_log_java_proto_lite", + deps = [":connections_log_proto"], +) diff --git a/sharing/BUILD b/sharing/BUILD index 5020ce68..8ab13f26 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -390,7 +390,6 @@ cc_library( "//connections:core_types", "//connections/implementation:internal", "//connections/implementation/analytics:analytics_recorder_impl", - "//internal/analytics:event_logger", "//internal/base", "//internal/base:file_path", "//internal/flags:nearby_flags", @@ -401,6 +400,7 @@ cc_library( "//internal/platform:mac_address", "//internal/platform:types", "//internal/platform/implementation:types", + "//location/nearby/analytics/cpp/logging:event_logger", "//location/nearby/sharing/lib/account:account_manager", "//location/nearby/sharing/lib/rpc:grpc_async_client_factory", "//location/nearby/sharing/lib/rpc:sharing_rpc_client", @@ -653,12 +653,12 @@ cc_test( ":transfer_metadata", ":transfer_metadata_matchers", ":types", - "//internal/analytics:mock_event_logger", "//internal/base:file_path", "//internal/base:files", "//internal/flags:nearby_flags", "//internal/platform/implementation:platform_impl", "//internal/test", + "//location/nearby/analytics/cpp/logging:mock_event_logger", "//location/nearby/sharing/lib/account:fake_account_manager", "//location/nearby/sharing/lib/account:mock_account_manager", "//location/nearby/sharing/lib/account:signin_attempt", @@ -873,9 +873,9 @@ cc_test( ":transfer_metadata", ":transfer_metadata_matchers", ":types", - "//internal/analytics:mock_event_logger", "//internal/platform/implementation:platform_impl", "//internal/test", + "//location/nearby/analytics/cpp/logging:mock_event_logger", "//location/nearby/sharing/lib/analytics", "//sharing/certificates:test_support", "@com_github_protobuf_matchers//protobuf-matchers", @@ -924,12 +924,12 @@ cc_test( ":transfer_metadata", ":transfer_metadata_matchers", ":types", - "//internal/analytics:mock_event_logger", "//internal/base:file_path", "//internal/base:files", "//internal/network:url", "//internal/platform/implementation:platform_impl", "//internal/test", + "//location/nearby/analytics/cpp/logging:mock_event_logger", "//location/nearby/sharing/lib/analytics", "//net/proto2/contrib/parse_proto:parse_text_proto", "//sharing/certificates:test_support", @@ -957,10 +957,10 @@ cc_test( ":transfer_metadata", ":transfer_metadata_matchers", ":types", - "//internal/analytics:mock_event_logger", "//internal/base:file_path", "//internal/platform/implementation:platform_impl", "//internal/test", + "//location/nearby/analytics/cpp/logging:mock_event_logger", "//location/nearby/sharing/lib/analytics", "//proto:sharing_enums_cc_proto", "//sharing/internal/public:logging", diff --git a/sharing/incoming_share_session_test.cc b/sharing/incoming_share_session_test.cc index f90be90a..fe19813e 100644 --- a/sharing/incoming_share_session_test.cc +++ b/sharing/incoming_share_session_test.cc @@ -24,14 +24,14 @@ #include #include +#include "location/nearby/analytics/cpp/logging/mock_event_logger.h" +#include "location/nearby/analytics/cpp/logging/sharing_log_matchers.h" #include "location/nearby/sharing/lib/analytics/analytics_recorder_impl.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" -#include "internal/analytics/mock_event_logger.h" -#include "internal/analytics/sharing_log_matchers.h" #include "internal/base/file_path.h" #include "internal/test/fake_clock.h" #include "internal/test/fake_device_info.h" diff --git a/sharing/nearby_connections_manager_factory.cc b/sharing/nearby_connections_manager_factory.cc index 9f0d40e3..cba3ccbd 100644 --- a/sharing/nearby_connections_manager_factory.cc +++ b/sharing/nearby_connections_manager_factory.cc @@ -16,7 +16,7 @@ #include -#include "internal/analytics/event_logger.h" +#include "location/nearby/analytics/cpp/logging/event_logger.h" #include "internal/platform/implementation/device_info.h" #include "internal/platform/task_runner.h" #include "sharing/internal/public/context.h" diff --git a/sharing/nearby_connections_manager_factory.h b/sharing/nearby_connections_manager_factory.h index bb45b9c7..f856a140 100644 --- a/sharing/nearby_connections_manager_factory.h +++ b/sharing/nearby_connections_manager_factory.h @@ -17,7 +17,7 @@ #include -#include "internal/analytics/event_logger.h" +#include "location/nearby/analytics/cpp/logging/event_logger.h" #include "internal/platform/implementation/device_info.h" #include "internal/platform/task_runner.h" #include "sharing/internal/public/context.h" diff --git a/sharing/nearby_connections_service_impl.cc b/sharing/nearby_connections_service_impl.cc index 51d235fc..42a8ba75 100644 --- a/sharing/nearby_connections_service_impl.cc +++ b/sharing/nearby_connections_service_impl.cc @@ -23,6 +23,7 @@ #include #include +#include "location/nearby/analytics/cpp/logging/event_logger.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" @@ -40,7 +41,6 @@ #include "connections/payload_type.h" #include "connections/status.h" #include "connections/strategy.h" -#include "internal/analytics/event_logger.h" #include "internal/platform/byte_array.h" #include "internal/platform/logging.h" #include "internal/platform/mac_address.h" diff --git a/sharing/nearby_connections_service_impl.h b/sharing/nearby_connections_service_impl.h index cdcfcf30..76d34891 100644 --- a/sharing/nearby_connections_service_impl.h +++ b/sharing/nearby_connections_service_impl.h @@ -22,10 +22,10 @@ #include #include +#include "location/nearby/analytics/cpp/logging/event_logger.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" -#include "internal/analytics/event_logger.h" #include "sharing/internal/public/connectivity_manager.h" #include "sharing/nearby_connections_service.h" #include "sharing/nearby_connections_types.h" diff --git a/sharing/nearby_sharing_service_factory.cc b/sharing/nearby_sharing_service_factory.cc index 06ef08b3..3bbb801c 100644 --- a/sharing/nearby_sharing_service_factory.cc +++ b/sharing/nearby_sharing_service_factory.cc @@ -17,8 +17,8 @@ #include #include +#include "location/nearby/analytics/cpp/logging/event_logger.h" #include "location/nearby/sharing/lib/rpc/grpc_async_client_factory.h" -#include "internal/analytics/event_logger.h" #include "internal/platform/task_runner.h" #include "sharing/analytics/analytics_recorder.h" #include "sharing/internal/api/sharing_platform.h" diff --git a/sharing/nearby_sharing_service_factory.h b/sharing/nearby_sharing_service_factory.h index 6370de1d..100221cf 100644 --- a/sharing/nearby_sharing_service_factory.h +++ b/sharing/nearby_sharing_service_factory.h @@ -17,9 +17,9 @@ #include +#include "location/nearby/analytics/cpp/logging/event_logger.h" #include "location/nearby/sharing/lib/rpc/grpc_async_client_factory.h" #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" -#include "internal/analytics/event_logger.h" #include "sharing/analytics/analytics_recorder.h" #include "sharing/internal/api/sharing_platform.h" #include "sharing/internal/public/context.h" diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index 20bd479d..491a56ef 100644 --- a/sharing/nearby_sharing_service_impl_test.cc +++ b/sharing/nearby_sharing_service_impl_test.cc @@ -30,6 +30,7 @@ #include #include +#include "location/nearby/analytics/cpp/logging/mock_event_logger.h" #include "location/nearby/sharing/lib/account/fake_account_manager.h" #include "location/nearby/sharing/lib/account/mock_account_observer.h" #include "location/nearby/sharing/lib/account/signin_attempt.h" @@ -48,7 +49,6 @@ #include "absl/time/clock.h" #include "absl/time/time.h" #include "absl/types/span.h" -#include "internal/analytics/mock_event_logger.h" #include "internal/base/file_path.h" #include "internal/base/files.h" #include "internal/flags/nearby_flags.h" diff --git a/sharing/outgoing_share_session_test.cc b/sharing/outgoing_share_session_test.cc index 6aed6372..f314a90e 100644 --- a/sharing/outgoing_share_session_test.cc +++ b/sharing/outgoing_share_session_test.cc @@ -22,6 +22,8 @@ #include #include +#include "location/nearby/analytics/cpp/logging/mock_event_logger.h" +#include "location/nearby/analytics/cpp/logging/sharing_log_matchers.h" #include "location/nearby/sharing/lib/analytics/analytics_recorder_impl.h" #include "net/proto2/contrib/parse_proto/parse_text_proto.h" #include "gmock/gmock.h" @@ -29,8 +31,6 @@ #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" -#include "internal/analytics/mock_event_logger.h" -#include "internal/analytics/sharing_log_matchers.h" #include "internal/base/file_path.h" #include "internal/base/files.h" #include "internal/network/url.h" diff --git a/sharing/share_session_test.cc b/sharing/share_session_test.cc index d82b8c14..98a969fb 100644 --- a/sharing/share_session_test.cc +++ b/sharing/share_session_test.cc @@ -21,6 +21,7 @@ #include #include +#include "location/nearby/analytics/cpp/logging/mock_event_logger.h" #include "location/nearby/sharing/lib/analytics/analytics_recorder_impl.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" @@ -29,7 +30,6 @@ #include "absl/synchronization/notification.h" #include "absl/time/clock.h" #include "absl/time/time.h" -#include "internal/analytics/mock_event_logger.h" #include "internal/test/fake_clock.h" #include "internal/test/fake_device_info.h" #include "internal/test/fake_task_runner.h"