From 5888be0903320b18961fa87021c8321de0220e56 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 4 Feb 2026 11:19:21 -0800 Subject: [PATCH 01/49] Remove use of deprecated downcast. PiperOrigin-RevId: 865496788 --- sharing/nearby_sharing_service_impl_test.cc | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index 7e55aeef..dd4bc07f 100644 --- a/sharing/nearby_sharing_service_impl_test.cc +++ b/sharing/nearby_sharing_service_impl_test.cc @@ -474,8 +474,7 @@ class NearbySharingServiceImplTest : public testing::Test { void SetLanConnected(bool connected) { FakeConnectivityManager* connectivity_manager = - down_cast( - fake_context_.GetConnectivityManager()); + fake_context_.fake_connectivity_manager(); connectivity_manager->SetLanConnected(connected); } @@ -502,14 +501,14 @@ class NearbySharingServiceImplTest : public testing::Test { void SetBluetoothIsPresent(bool present) { FakeBluetoothAdapter& bluetooth_adapter = - down_cast(fake_context_.GetBluetoothAdapter()); + *fake_context_.fake_bluetooth_adapter(); bluetooth_adapter.ReceivedAdapterPresentChangedFromOs(present); FlushTesting(); } void SetBluetoothIsPowered(bool powered) { FakeBluetoothAdapter& bluetooth_adapter = - down_cast(fake_context_.GetBluetoothAdapter()); + *fake_context_.fake_bluetooth_adapter(); bluetooth_adapter.ReceivedAdapterPoweredChangedFromOs(powered); fake_context_.fake_clock()->FastForward(absl::Milliseconds(500)); FlushTesting(); @@ -517,8 +516,7 @@ class NearbySharingServiceImplTest : public testing::Test { void SetLanIsConnected(bool connected) { FakeConnectivityManager* connectivity_manager = - down_cast( - fake_context_.GetConnectivityManager()); + fake_context_.fake_connectivity_manager(); connectivity_manager->SetLanConnected(connected); FlushTesting(); } From 26f03a641c50e9d32e680614f951598cdb094697 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 4 Feb 2026 12:30:36 -0800 Subject: [PATCH 02/49] Deprecate enable_payload_received_ack flag. PiperOrigin-RevId: 865529732 --- connections/implementation/BUILD | 1 - .../implementation/endpoint_manager_test.cc | 9 +++-- .../flags/nearby_connections_feature_flags.h | 3 ++ connections/implementation/payload_manager.cc | 30 ++++++++++++++-- connections/implementation/payload_manager.h | 3 ++ connections/implementation/simulation_user.cc | 14 -------- connections/implementation/simulation_user.h | 35 ++++++------------- 7 files changed, 51 insertions(+), 44 deletions(-) diff --git a/connections/implementation/BUILD b/connections/implementation/BUILD index a2312bf8..4f37d002 100644 --- a/connections/implementation/BUILD +++ b/connections/implementation/BUILD @@ -227,7 +227,6 @@ cc_library( "//connections:core_types", "//connections/implementation/analytics", "//connections/implementation/flags:connections_flags", - "//connections/implementation/mediums", "//connections/v3:v3_types", "//internal/flags:nearby_flags", "//internal/interop:device", diff --git a/connections/implementation/endpoint_manager_test.cc b/connections/implementation/endpoint_manager_test.cc index bba660f8..0f906e3c 100644 --- a/connections/implementation/endpoint_manager_test.cc +++ b/connections/implementation/endpoint_manager_test.cc @@ -137,6 +137,7 @@ class MockFrameProcessor : public EndpointManager::FrameProcessor { class SetSafeToDisconnect { public: SetSafeToDisconnect(bool safe_to_disconnect, bool auto_reconnect, + bool payload_received_ack, std::int32_t safe_to_disconnect_version) { NearbyFlags::GetInstance().OverrideBoolFlagValue( config_package_nearby::nearby_connections_feature:: @@ -145,6 +146,10 @@ class SetSafeToDisconnect { NearbyFlags::GetInstance().OverrideBoolFlagValue( config_package_nearby::nearby_connections_feature::kEnableAutoReconnect, auto_reconnect); + NearbyFlags::GetInstance().OverrideBoolFlagValue( + config_package_nearby::nearby_connections_feature:: + kEnablePayloadReceivedAck, + payload_received_ack); NearbyFlags::GetInstance().OverrideInt64FlagValue( config_package_nearby::nearby_connections_feature:: kSafeToDisconnectVersion, @@ -182,9 +187,7 @@ class EndpointManagerTest : public ::testing::Test { EXPECT_TRUE(done.Await(absl::Milliseconds(1000)).result()); } } - SetSafeToDisconnect set_safe_to_disconnect_{/*safe_to_disconnect=*/true, - /*auto_reconnect=*/false, - /*safe_to_disconnect_version=*/5}; + SetSafeToDisconnect set_safe_to_disconnect_{true, false, true, 5}; std::unique_ptr client_ = std::make_unique(); ConnectionOptions connection_options_{ .keep_alive_interval_millis = 5000, diff --git a/connections/implementation/flags/nearby_connections_feature_flags.h b/connections/implementation/flags/nearby_connections_feature_flags.h index e3812b85..8dbe6dbc 100644 --- a/connections/implementation/flags/nearby_connections_feature_flags.h +++ b/connections/implementation/flags/nearby_connections_feature_flags.h @@ -77,6 +77,9 @@ constexpr auto kEnableNearbyConnectionsPreferences = // Enable/Disable payload manager to skip chunk update. constexpr auto kEnablePayloadManagerToSkipChunkUpdate = flags::Flag(kConfigPackage, "45415729", true); +// Enable/Disable payload-received-ack feature. +constexpr auto kEnablePayloadReceivedAck = + flags::Flag(kConfigPackage, "45425840", false); // Enable/Disable safe-to-disconnect feature. constexpr auto kEnableSafeToDisconnect = flags::Flag(kConfigPackage, "45425789", false); diff --git a/connections/implementation/payload_manager.cc b/connections/implementation/payload_manager.cc index 38de706d..2ff3e716 100644 --- a/connections/implementation/payload_manager.cc +++ b/connections/implementation/payload_manager.cc @@ -539,6 +539,18 @@ void PayloadManager::OnIncomingFrame(OfflineFrame& offline_frame, // Block any payload before the connection been accepted by both sides // to prevent unauthorized transfer. if (!to_client->IsConnectedToEndpoint(from_endpoint_id)) { + if (frame.packet_type() == PayloadTransferFrame::DATA) { + PendingPayloadHandle pending_payload = + pending_payloads_.GetPayload(frame.payload_header().id()); + bool is_last = IsLastChunk(frame.payload_chunk()); + // If payload need to be ack'd receiving, then send back the ACK frame. + if (pending_payload && is_last && + IsPayloadReceivedAckEnabled(to_client, from_endpoint_id, + *pending_payload)) { + SendPayloadReceivedAck(to_client, *pending_payload, from_endpoint_id, + is_last); + } + } VLOG(1) << "PayloadManager skipped process payloads before PCP connected, " << frame.payload_header().id(); return; @@ -909,7 +921,8 @@ void PayloadManager::SendPayloadReceivedAck(ClientProxy* client, PendingPayload& pending_payload, const std::string& endpoint_id, bool is_last_chunk) { - if (!is_last_chunk) { + if (!is_last_chunk || + !IsPayloadReceivedAckEnabled(client, endpoint_id, pending_payload)) { return; } @@ -931,7 +944,8 @@ bool PayloadManager::WaitForReceivedAck( PendingPayload& pending_payload, const PayloadTransferFrame::PayloadHeader& payload_header, std::int64_t payload_chunk_offset, bool is_last_chunk) { - if (!is_last_chunk) { + if (!is_last_chunk || + !IsPayloadReceivedAckEnabled(client, endpoint_id, pending_payload)) { return true; } @@ -1019,6 +1033,18 @@ bool PayloadManager::WaitForReceivedAck( return true; } +bool PayloadManager::IsPayloadReceivedAckEnabled( + ClientProxy* client, const std::string& endpoint_id, + PendingPayload& pending_payload) { + return NearbyFlags::GetInstance().GetBoolFlag( + config_package_nearby::nearby_connections_feature:: + kEnablePayloadReceivedAck) && + client->IsPayloadReceivedAckEnabled(endpoint_id) && + (pending_payload.GetInternalPayload()->GetType() != + nearby::connections::PayloadTransferFrame::PayloadTransferFrame:: + PayloadHeader::BYTES); +} + void PayloadManager::HandleFinishedOutgoingPayload( ClientProxy* client, const EndpointIds& finished_endpoint_ids, const PayloadTransferFrame::PayloadHeader& payload_header, diff --git a/connections/implementation/payload_manager.h b/connections/implementation/payload_manager.h index f87b10ee..838af4f8 100644 --- a/connections/implementation/payload_manager.h +++ b/connections/implementation/payload_manager.h @@ -367,6 +367,9 @@ class PayloadManager : public EndpointManager::FrameProcessor { const location::nearby::connections::PayloadTransferFrame::PayloadHeader& payload_header, std::int64_t payload_chunk_offset, bool is_last_chunk); + bool IsPayloadReceivedAckEnabled(ClientProxy* client, + const std::string& endpoint_id, + PendingPayload& pending_payload); // Handles a finished outgoing payload for the given endpointIds. All // statuses except for SUCCESS are handled here. diff --git a/connections/implementation/simulation_user.cc b/connections/implementation/simulation_user.cc index d0676033..e0e494f8 100644 --- a/connections/implementation/simulation_user.cc +++ b/connections/implementation/simulation_user.cc @@ -14,25 +14,11 @@ #include "connections/implementation/simulation_user.h" -#include -#include - -#include "gtest/gtest.h" -#include "absl/functional/any_invocable.h" #include "absl/functional/bind_front.h" -#include "absl/strings/string_view.h" -#include "absl/time/time.h" #include "connections/listeners.h" -#include "connections/out_of_band_connection_metadata.h" -#include "connections/payload.h" -#include "connections/status.h" -#include "connections/v3/connection_listening_options.h" #include "internal/interop/device.h" -#include "internal/platform/byte_array.h" #include "internal/platform/count_down_latch.h" -#include "internal/platform/future.h" #include "internal/platform/logging.h" -#include "internal/platform/mutex_lock.h" namespace nearby { namespace connections { diff --git a/connections/implementation/simulation_user.h b/connections/implementation/simulation_user.h index 79fe80d8..417ab2f8 100644 --- a/connections/implementation/simulation_user.h +++ b/connections/implementation/simulation_user.h @@ -19,36 +19,21 @@ #include #include -#include "absl/functional/any_invocable.h" -#include "absl/strings/string_view.h" -#include "absl/time/time.h" -#include "connections/advertising_options.h" -#include "connections/connection_options.h" -#include "connections/discovery_options.h" +#include "gtest/gtest.h" #include "connections/implementation/bwu_manager.h" #include "connections/implementation/client_proxy.h" #include "connections/implementation/endpoint_channel_manager.h" #include "connections/implementation/endpoint_manager.h" #include "connections/implementation/flags/nearby_connections_feature_flags.h" #include "connections/implementation/injected_bluetooth_device_store.h" -#include "connections/implementation/mediums/mediums.h" #include "connections/implementation/payload_manager.h" #include "connections/implementation/pcp_manager.h" -#include "connections/listeners.h" -#include "connections/medium_selector.h" -#include "connections/out_of_band_connection_metadata.h" -#include "connections/payload.h" -#include "connections/status.h" -#include "connections/strategy.h" -#include "connections/v3/connection_listening_options.h" +#include "connections/v3/connections_device.h" #include "internal/flags/nearby_flags.h" -#include "internal/interop/device.h" -#include "internal/platform/byte_array.h" #include "internal/platform/condition_variable.h" #include "internal/platform/count_down_latch.h" #include "internal/platform/feature_flags.h" #include "internal/platform/future.h" -#include "internal/platform/mutex.h" // Test-only class to help run end-to-end simulations for nearby connections // protocol. @@ -62,6 +47,7 @@ namespace connections { class SetSafeToDisconnect { public: explicit SetSafeToDisconnect(bool safe_to_disconnect, bool auto_reconnect, + bool payload_received_ack, std::int32_t safe_to_disconnect_version) { NearbyFlags::GetInstance().OverrideBoolFlagValue( config_package_nearby::nearby_connections_feature:: @@ -70,6 +56,10 @@ class SetSafeToDisconnect { NearbyFlags::GetInstance().OverrideBoolFlagValue( config_package_nearby::nearby_connections_feature::kEnableAutoReconnect, auto_reconnect); + NearbyFlags::GetInstance().OverrideBoolFlagValue( + config_package_nearby::nearby_connections_feature:: + kEnablePayloadReceivedAck, + payload_received_ack); NearbyFlags::GetInstance().OverrideInt64FlagValue( config_package_nearby::nearby_connections_feature:: kSafeToDisconnectVersion, @@ -88,13 +78,10 @@ class SimulationUser { void Clear() { endpoint_id.clear(); } }; - explicit SimulationUser( - const std::string& device_name, - BooleanMediumSelector allowed = BooleanMediumSelector(), - SetSafeToDisconnect set_safe_to_disconnect = - SetSafeToDisconnect(/*safe_to_disconnect=*/true, - /*auto_reconnect=*/false, - /*safe_to_disconnect_version=*/5)) + SimulationUser(const std::string& device_name, + BooleanMediumSelector allowed = BooleanMediumSelector(), + SetSafeToDisconnect set_safe_to_disconnect = + SetSafeToDisconnect(true, false, true, 5)) : info_{ByteArray{device_name}}, advertising_options_{ { From fc510085e6eab36f5391c41a2ab93912774161e0 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 4 Feb 2026 15:04:19 -0800 Subject: [PATCH 03/49] Increase Wi-Fi connection timeout to 700ms. PiperOrigin-RevId: 865597140 --- .../platform/implementation/windows/wifi_hotspot_medium.cc | 5 ++++- internal/platform/implementation/windows/wifi_lan_medium.cc | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/platform/implementation/windows/wifi_hotspot_medium.cc b/internal/platform/implementation/windows/wifi_hotspot_medium.cc index 209b7e8c..288efe14 100644 --- a/internal/platform/implementation/windows/wifi_hotspot_medium.cc +++ b/internal/platform/implementation/windows/wifi_hotspot_medium.cc @@ -56,7 +56,10 @@ using ::winrt::Windows::Devices::WiFiDirect:: using ::winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionRequest; using ::winrt::Windows::Security::Credentials::PasswordCredential; -constexpr absl::Duration kConnectTimeout = absl::Milliseconds(500); +// Wifi connection metrics show P90 latency is just under 600ms. +// Assuming the hotspot connection latency is similar to the wifi +// connection latency. +constexpr absl::Duration kConnectTimeout = absl::Milliseconds(700); } // namespace WifiHotspotMedium::~WifiHotspotMedium() { diff --git a/internal/platform/implementation/windows/wifi_lan_medium.cc b/internal/platform/implementation/windows/wifi_lan_medium.cc index 2b078349..f67f507e 100644 --- a/internal/platform/implementation/windows/wifi_lan_medium.cc +++ b/internal/platform/implementation/windows/wifi_lan_medium.cc @@ -80,7 +80,9 @@ constexpr absl::string_view kMdnsDeviceSelectorFormat = constexpr absl::string_view kDisableMdnsAdvertisingRegistryValue = "disable_mdns_advertising"; -constexpr absl::Duration kConnectTimeout = absl::Milliseconds(500); +// From metrics, P90 wifi connection latency is just under 600ms. +// Set to 700ms to be slightly more generous than the P90. +constexpr absl::Duration kConnectTimeout = absl::Milliseconds(700); bool IsSelfInstance(IMapView properties, absl::string_view self_instance_name) { From a824f0fd11491a0fcc82a2f50475779933c877e1 Mon Sep 17 00:00:00 2001 From: hai007 Date: Thu, 5 Feb 2026 00:02:59 -0800 Subject: [PATCH 04/49] Automated Code Change PiperOrigin-RevId: 865782783 --- internal/platform/implementation/apple/BUILD | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/platform/implementation/apple/BUILD b/internal/platform/implementation/apple/BUILD index 401e6782..85b1dfba 100644 --- a/internal/platform/implementation/apple/BUILD +++ b/internal/platform/implementation/apple/BUILD @@ -22,7 +22,6 @@ package(default_visibility = [ "//ambient/nearby/testing/connection/mdc/ios:__subpackages__", "//connections:__subpackages__", "//connections:partners", - "//googlemac/iPhone/Nearby:__subpackages__", "//internal/platform:__subpackages__", "//internal/preferences:__subpackages__", "//location/nearby:__subpackages__", From 23fe8106b8d6c3a8754b5ccb4d6769801028af52 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 5 Feb 2026 10:32:50 -0800 Subject: [PATCH 05/49] Fix TSAN error. PiperOrigin-RevId: 866012758 --- sharing/internal/test/fake_connectivity_manager.h | 11 ++++++----- sharing/nearby_sharing_service_impl.cc | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/sharing/internal/test/fake_connectivity_manager.h b/sharing/internal/test/fake_connectivity_manager.h index 47135cdb..18a33de7 100644 --- a/sharing/internal/test/fake_connectivity_manager.h +++ b/sharing/internal/test/fake_connectivity_manager.h @@ -15,6 +15,7 @@ #ifndef THIRD_PARTY_NEARBY_SHARING_INTERNAL_TEST_FAKE_CONNECTIVITY_MANAGER_H_ #define THIRD_PARTY_NEARBY_SHARING_INTERNAL_TEST_FAKE_CONNECTIVITY_MANAGER_H_ +#include #include #include #include @@ -52,21 +53,21 @@ class FakeConnectivityManager : public ConnectivityManager { void SetLanConnected(bool connected) { is_lan_connected_ = connected; for (auto& listener : lan_listeners_) { - listener.second(is_lan_connected_); + listener.second(connected); } } void SetInternetConnected(bool connected) { is_internet_connected_ = connected; for (auto& listener : internet_listeners_) { - listener.second(is_internet_connected_); + listener.second(connected); } } private: - bool is_lan_connected_ = true; - bool is_internet_connected_ = true; - bool is_hp_realtek_device_ = false; + std::atomic is_lan_connected_ = true; + std::atomic is_internet_connected_ = true; + std::atomic is_hp_realtek_device_ = false; absl::flat_hash_map> lan_listeners_; absl::flat_hash_map> internet_listeners_; diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index ac3ed1f5..f8a8a96e 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -412,8 +412,8 @@ void NearbySharingServiceImpl::SendInitialAdapterState( void NearbySharingServiceImpl::AddObserver( NearbySharingService::Observer* observer) { - SendInitialAdapterState(observer); service_observers_.AddObserver(observer); + SendInitialAdapterState(observer); } void NearbySharingServiceImpl::RemoveObserver( From 183fdacb034a2f993d695f282ced52a7e06bef2b Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Fri, 6 Feb 2026 10:14:24 -0800 Subject: [PATCH 06/49] Set file save path on a per session basis. PiperOrigin-RevId: 866512037 --- connections/core.cc | 5 ++++ connections/core.h | 4 ++-- connections/implementation/client_proxy.cc | 21 +++++++++++++++++ connections/implementation/client_proxy.h | 8 +++++++ .../implementation/client_proxy_test.cc | 23 +++++++++++++++---- connections/implementation/payload_manager.cc | 10 +++++--- connections/implementation/payload_manager.h | 6 ++++- sharing/fake_nearby_connections_manager.cc | 5 ---- sharing/fake_nearby_connections_manager.h | 5 ++-- sharing/fake_nearby_connections_service.h | 4 ++++ sharing/nearby_connections_manager.h | 3 +++ sharing/nearby_connections_manager_impl.cc | 7 ++++++ sharing/nearby_connections_manager_impl.h | 2 ++ .../nearby_connections_manager_impl_test.cc | 8 +++++++ sharing/nearby_connections_service.h | 4 ++++ sharing/nearby_connections_service_impl.cc | 5 ++++ sharing/nearby_connections_service_impl.h | 3 +++ sharing/nearby_sharing_service_impl.cc | 8 ++++++- 18 files changed, 113 insertions(+), 18 deletions(-) diff --git a/connections/core.cc b/connections/core.cc index 61b77422..827715cc 100644 --- a/connections/core.cc +++ b/connections/core.cc @@ -207,6 +207,11 @@ void Core::SetCustomSavePath(absl::string_view path, ResultCallback callback) { router_->SetCustomSavePath(&client_, path, std::move(callback)); } +void Core::OverrideSavePath(absl::string_view endpoint_id, + absl::string_view path) { + client_.OverrideSavePath(endpoint_id, path); +} + std::string Core::Dump() { return client_.Dump(); } // V3 diff --git a/connections/core.h b/connections/core.h index d159767a..69edb815 100644 --- a/connections/core.h +++ b/connections/core.h @@ -19,7 +19,6 @@ #include #include #include -#include #include "absl/strings/string_view.h" #include "absl/types/span.h" @@ -29,7 +28,6 @@ #include "connections/implementation/client_proxy.h" #include "connections/implementation/service_controller_router.h" #include "connections/listeners.h" -#include "connections/medium_selector.h" #include "connections/out_of_band_connection_metadata.h" #include "connections/params.h" #include "connections/payload.h" @@ -254,6 +252,8 @@ class Core { // // path - The path where the received files will be saved to. void SetCustomSavePath(absl::string_view path, ResultCallback callback); + // Override the save path for payloads from a specific endpoint. + void OverrideSavePath(absl::string_view endpoint_id, absl::string_view path); // Gets the local endpoint generated by Nearby Connections. std::string GetLocalEndpointId() { return client_.GetLocalEndpointId(); } diff --git a/connections/implementation/client_proxy.cc b/connections/implementation/client_proxy.cc index 7c303b83..d53e1a18 100644 --- a/connections/implementation/client_proxy.cc +++ b/connections/implementation/client_proxy.cc @@ -196,6 +196,27 @@ std::string ClientProxy::GetConnectionToken(const std::string& endpoint_id) { return {}; } +bool ClientProxy::OverrideSavePath(absl::string_view endpoint_id, + absl::string_view path) { + MutexLock lock(&mutex_); + ConnectionPair* item = LookupConnection(endpoint_id); + if (item != nullptr) { + item->first.save_path = path; + return true; + } + return false; +} + +std::string ClientProxy::GetSavePath( + absl::string_view endpoint_id) const { + MutexLock lock(&mutex_); + const ConnectionPair* item = LookupConnection(endpoint_id); + if (item != nullptr) { + return item->first.save_path; + } + return ""; +} + std::optional ClientProxy::GetBluetoothMacAddress( const std::string& endpoint_id) { auto item = bluetooth_mac_addresses_.find(endpoint_id); diff --git a/connections/implementation/client_proxy.h b/connections/implementation/client_proxy.h index c567f574..05406a27 100644 --- a/connections/implementation/client_proxy.h +++ b/connections/implementation/client_proxy.h @@ -77,6 +77,13 @@ class ClientProxy final { std::string GetLocalEndpointId(); std::string GetLocalEndpointInfo() { return local_endpoint_info_; } + // Override the base for received file attachments from a specific endpoint. + // Returns true if the endpoint is found and the path is overridden. + bool OverrideSavePath(absl::string_view endpoint_id, absl::string_view path); + // Get the save path for a specific endpoint. Returns empty string if + // not set. + std::string GetSavePath(absl::string_view endpoint_id) const; + analytics::AnalyticsRecorder& GetAnalyticsRecorder() const { return *analytics_recorder_; } @@ -394,6 +401,7 @@ class ClientProxy final { std::optional os_info; std::int32_t safe_to_disconnect_version; std::int32_t remote_multiplex_socket_bitmask; + std::string save_path; }; using ConnectionPair = std::pair; diff --git a/connections/implementation/client_proxy_test.cc b/connections/implementation/client_proxy_test.cc index d87c6b7b..172a58d8 100644 --- a/connections/implementation/client_proxy_test.cc +++ b/connections/implementation/client_proxy_test.cc @@ -21,7 +21,6 @@ #include #include -#include "base/casts.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" @@ -65,6 +64,7 @@ using ::location::nearby::connections::OsInfo; using ::location::nearby::proto::connections::CLIENT_SESSION; using ::location::nearby::proto::connections::START_CLIENT_SESSION; using ::location::nearby::proto::connections::STOP_CLIENT_SESSION; +using ::testing::IsEmpty; using ::testing::MockFunction; using ::testing::StrictMock; @@ -1400,9 +1400,7 @@ TEST_F(ClientProxyTest, GetLocalDeviceWorksWithDeviceProvider) { MockDeviceProvider provider; client1()->RegisterDeviceProvider(&provider); ASSERT_NE(client1()->GetLocalDeviceProvider(), nullptr); - EXPECT_CALL(*(absl::down_cast( - client1()->GetLocalDeviceProvider())), - GetLocalDevice); + EXPECT_CALL(provider, GetLocalDevice); client1()->GetLocalDevice(); } @@ -1612,6 +1610,23 @@ TEST_F(ClientProxyTest, NotLoadClientInfoFromPreferencesOnExpired) { false); } +TEST_F(ClientProxyTest, OverrideSavePath) { + Endpoint advertising_endpoint = + StartAdvertising(client1(), advertising_connection_listener_); + OnAdvertisingConnectionInitiated(client1(), advertising_endpoint); + + client1()->OverrideSavePath(advertising_endpoint.id, "/tmp/test_path"); + EXPECT_EQ(client1()->GetSavePath(advertising_endpoint.id), "/tmp/test_path"); +} + +TEST_F(ClientProxyTest, GetSavePathDefaultsToEmpty) { + Endpoint advertising_endpoint = + StartAdvertising(client1(), advertising_connection_listener_); + OnAdvertisingConnectionInitiated(client1(), advertising_endpoint); + + EXPECT_THAT(client1()->GetSavePath(advertising_endpoint.id), IsEmpty()); +} + } // namespace } // namespace connections } // namespace nearby diff --git a/connections/implementation/payload_manager.cc b/connections/implementation/payload_manager.cc index 2ff3e716..9dbf2521 100644 --- a/connections/implementation/payload_manager.cc +++ b/connections/implementation/payload_manager.cc @@ -792,9 +792,12 @@ PayloadTransferFrame::PayloadChunk PayloadManager::CreatePayloadChunk( ErrorOr PayloadManager::CreateIncomingPayload(const PayloadTransferFrame& frame, - const std::string& endpoint_id) { + const std::string& endpoint_id, + const std::string& save_path) { ErrorOr> result = - CreateIncomingInternalPayload(frame, custom_save_path_); + CreateIncomingInternalPayload(frame, save_path.empty() + ? custom_save_path_ + : save_path); if (result.has_error()) { return {result.error()}; } @@ -1340,7 +1343,8 @@ void PayloadManager::ProcessDataPacket( }); ErrorOr result = - CreateIncomingPayload(payload_transfer_frame, from_endpoint_id); + CreateIncomingPayload(payload_transfer_frame, from_endpoint_id, + to_client->GetSavePath(from_endpoint_id)); if (result.has_error()) { LOG(WARNING) << "PayloadManager failed to create InternalPayload from " "PayloadTransferFrame with payload_id=" diff --git a/connections/implementation/payload_manager.h b/connections/implementation/payload_manager.h index 838af4f8..4ba438c5 100644 --- a/connections/implementation/payload_manager.h +++ b/connections/implementation/payload_manager.h @@ -323,9 +323,13 @@ class PayloadManager : public EndpointManager::FrameProcessor { LAST_CHUNK) != 0); } + // Creates an incoming payload and returns a handle to it. + // If `save_path` is empty, the payload will be saved to the default save + // path set in `SetCustomSavePath()`. ErrorOr CreateIncomingPayload( const location::nearby::connections::PayloadTransferFrame& frame, - const std::string& endpoint_id) ABSL_LOCKS_EXCLUDED(mutex_); + const std::string& endpoint_id, + const std::string& save_path) ABSL_LOCKS_EXCLUDED(mutex_); Payload::Id CreateOutgoingPayload(Payload payload, const EndpointIds& endpoint_ids) diff --git a/sharing/fake_nearby_connections_manager.cc b/sharing/fake_nearby_connections_manager.cc index b152fabb..e69fbb7d 100644 --- a/sharing/fake_nearby_connections_manager.cc +++ b/sharing/fake_nearby_connections_manager.cc @@ -311,11 +311,6 @@ void FakeNearbyConnectionsManager::HandleStopAdvertisingCallback( capture_next_stop_advertising_callback_ = false; } -void FakeNearbyConnectionsManager::SetCustomSavePath( - absl::string_view custom_save_path) { - custom_save_path_ = custom_save_path; -} - absl::flat_hash_set FakeNearbyConnectionsManager::GetAndClearUnknownFilePathsToDelete() { absl::flat_hash_set file_paths_to_delete = file_paths_to_delete_; diff --git a/sharing/fake_nearby_connections_manager.h b/sharing/fake_nearby_connections_manager.h index 9131b7c9..d62415c0 100644 --- a/sharing/fake_nearby_connections_manager.h +++ b/sharing/fake_nearby_connections_manager.h @@ -74,7 +74,9 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager { std::optional> GetRawAuthenticationToken( absl::string_view endpoint_id) override; void UpgradeBandwidth(absl::string_view endpoint_id) override; - void SetCustomSavePath(absl::string_view custom_save_path) override; + void SetCustomSavePath(absl::string_view custom_save_path) override {} + void OverrideSavePath(absl::string_view endpoint_id, + const FilePath& custom_save_path) override {} absl::flat_hash_set GetAndClearUnknownFilePathsToDelete() override; // Testing methods @@ -170,7 +172,6 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager { ConnectionsCallback pending_stop_advertising_callback_; bool capture_next_start_advertising_callback_ = false; ConnectionsCallback pending_start_advertising_callback_; - std::string custom_save_path_; absl::Mutex endpoints_mutex_; // Maps endpoint_id to endpoint_info. diff --git a/sharing/fake_nearby_connections_service.h b/sharing/fake_nearby_connections_service.h index d94363b1..cbe21c02 100644 --- a/sharing/fake_nearby_connections_service.h +++ b/sharing/fake_nearby_connections_service.h @@ -111,6 +111,10 @@ class FakeNearbyConnectionsService : public NearbyConnectionsService { std::function callback), (override)); + MOCK_METHOD(void, OverrideSavePath, + (absl::string_view endpoint_id, absl::string_view path), + (override)); + MOCK_METHOD(std::string, Dump, (), (const, override)); }; diff --git a/sharing/nearby_connections_manager.h b/sharing/nearby_connections_manager.h index 179c7718..27ecb953 100644 --- a/sharing/nearby_connections_manager.h +++ b/sharing/nearby_connections_manager.h @@ -156,6 +156,9 @@ class NearbyConnectionsManager { // Sets a custom save path. virtual void SetCustomSavePath(absl::string_view custom_save_path) = 0; + // Overrides the save path for transfers from a specific endpoint. + virtual void OverrideSavePath(absl::string_view endpoint_id, + const FilePath& custom_save_path) = 0; // Gets the file paths to delete and clear the hash set. virtual absl::flat_hash_set diff --git a/sharing/nearby_connections_manager_impl.cc b/sharing/nearby_connections_manager_impl.cc index 10457dca..16ae5a39 100644 --- a/sharing/nearby_connections_manager_impl.cc +++ b/sharing/nearby_connections_manager_impl.cc @@ -972,6 +972,13 @@ void NearbyConnectionsManagerImpl::SetCustomSavePath( }); } +void NearbyConnectionsManagerImpl::OverrideSavePath( + absl::string_view endpoint_id, const FilePath& custom_save_path) { + MutexLock lock(&mutex_); + nearby_connections_service_->OverrideSavePath(endpoint_id, + custom_save_path.ToString()); +} + absl::flat_hash_set NearbyConnectionsManagerImpl::GetUnknownFilePathsToDelete() { MutexLock lock(&mutex_); diff --git a/sharing/nearby_connections_manager_impl.h b/sharing/nearby_connections_manager_impl.h index bac82acf..ff6f064f 100644 --- a/sharing/nearby_connections_manager_impl.h +++ b/sharing/nearby_connections_manager_impl.h @@ -87,6 +87,8 @@ class NearbyConnectionsManagerImpl : public NearbyConnectionsManager { absl::string_view endpoint_id) override; void UpgradeBandwidth(absl::string_view endpoint_id) override; void SetCustomSavePath(absl::string_view custom_save_path) override; + void OverrideSavePath(absl::string_view endpoint_id, + const FilePath& custom_save_path) override; absl::flat_hash_set GetAndClearUnknownFilePathsToDelete() override; std::string Dump() const override; diff --git a/sharing/nearby_connections_manager_impl_test.cc b/sharing/nearby_connections_manager_impl_test.cc index 563f4346..325a9762 100644 --- a/sharing/nearby_connections_manager_impl_test.cc +++ b/sharing/nearby_connections_manager_impl_test.cc @@ -2050,5 +2050,13 @@ TEST_F(NearbyConnectionsManagerImplTest, ProcessUnknownFilePathsToDelete) { nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); } +TEST_F(NearbyConnectionsManagerImplTest, OverrideSavePath) { + EXPECT_CALL(*nearby_connections_, + OverrideSavePath(kRemoteEndpointId, "/tmp/test")); + + nearby_connections_manager_->OverrideSavePath(kRemoteEndpointId, + FilePath("/tmp/test")); +} + } // namespace NearbyConnectionsManagerUnitTests } // namespace nearby::sharing diff --git a/sharing/nearby_connections_service.h b/sharing/nearby_connections_service.h index 51a727fe..acbdd96b 100644 --- a/sharing/nearby_connections_service.h +++ b/sharing/nearby_connections_service.h @@ -137,6 +137,10 @@ class NearbyConnectionsService { virtual void SetCustomSavePath( absl::string_view path, std::function callback) = 0; + // Overrides the save path for transfers from a specific endpoint. + virtual void OverrideSavePath(absl::string_view endpoint_id, + absl::string_view path) = 0; + virtual std::string Dump() const = 0; }; diff --git a/sharing/nearby_connections_service_impl.cc b/sharing/nearby_connections_service_impl.cc index 7fec3154..b0d3a89d 100644 --- a/sharing/nearby_connections_service_impl.cc +++ b/sharing/nearby_connections_service_impl.cc @@ -381,6 +381,11 @@ void NearbyConnectionsServiceImpl::SetCustomSavePath( ->SetCustomSavePath(path, BuildResultCallback(callback)); } +void NearbyConnectionsServiceImpl::OverrideSavePath( + absl::string_view endpoint_id, absl::string_view path) { + GetService(service_handle_)->OverrideSavePath(endpoint_id, path); +} + std::string NearbyConnectionsServiceImpl::Dump() const { return GetService(service_handle_)->Dump(); } diff --git a/sharing/nearby_connections_service_impl.h b/sharing/nearby_connections_service_impl.h index 54bf1ab9..cdcfcf30 100644 --- a/sharing/nearby_connections_service_impl.h +++ b/sharing/nearby_connections_service_impl.h @@ -90,6 +90,9 @@ class NearbyConnectionsServiceImpl : public NearbyConnectionsService { void SetCustomSavePath(absl::string_view path, std::function callback) override; + void OverrideSavePath(absl::string_view endpoint_id, + absl::string_view path) override; + std::string Dump() const override; private: diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index f8a8a96e..ebbcb722 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -2520,13 +2520,19 @@ void NearbySharingServiceImpl::OnReceivedIntroduction( Fail(*session, *status); return; } + FilePath save_path{settings_->GetCustomSavePath()}; + // Override save path for this connection. + // This must be called before the transfer is accepted and payloads are being + // received. + nearby_connections_manager_->OverrideSavePath(session->endpoint_id(), + save_path); // Log analytics event of receiving introduction. analytics_recorder_.NewReceiveIntroduction( session->session_id(), session->share_target(), /*referrer_package=*/std::nullopt, session->os_type()); - if (IsOutOfStorage(device_info_, FilePath{settings_->GetCustomSavePath()}, + if (IsOutOfStorage(device_info_, save_path, session->attachment_container().GetStorageSize())) { Fail(*session, TransferMetadata::Status::kNotEnoughSpace); LOG(WARNING) << __func__ From b49414cb90f255648b753be74eae7010fa1af35b Mon Sep 17 00:00:00 2001 From: hai007 Date: Tue, 10 Feb 2026 09:56:04 -0800 Subject: [PATCH 07/49] Add more test cases for InternalPayloadFactoryTest to improve test coverage. PiperOrigin-RevId: 868195322 --- connections/implementation/BUILD | 1 + .../internal_payload_factory.cc | 32 ++-- .../internal_payload_factory_test.cc | 167 +++++++++++++++++- 3 files changed, 173 insertions(+), 27 deletions(-) diff --git a/connections/implementation/BUILD b/connections/implementation/BUILD index 4f37d002..ec42c3d2 100644 --- a/connections/implementation/BUILD +++ b/connections/implementation/BUILD @@ -582,6 +582,7 @@ cc_test( "//internal/platform/implementation/g3", # build_cleaner: keep "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_absl//absl/strings:string_view", + "@com_google_absl//absl/time", "@com_google_googletest//:gtest_main", ], ) diff --git a/connections/implementation/internal_payload_factory.cc b/connections/implementation/internal_payload_factory.cc index 8958ecc6..36d65718 100644 --- a/connections/implementation/internal_payload_factory.cc +++ b/connections/implementation/internal_payload_factory.cc @@ -46,6 +46,17 @@ namespace { using ::location::nearby::connections::PayloadTransferFrame; using ::location::nearby::proto::connections::OperationResultCode; +// if custom_save_path is empty, default download path is used +std::string make_path(const std::string& custom_save_path, + const std::string& parent_folder, + const std::string& file_name) { + if (!custom_save_path.empty()) { + std::string path = absl::StrCat(custom_save_path, "/", parent_folder); + return api::ImplementationPlatform::GetCustomSavePath(path, file_name); + } + return api::ImplementationPlatform::GetDownloadPath(parent_folder, file_name); +} + class BytesInternalPayload : public InternalPayload { public: explicit BytesInternalPayload(Payload payload) @@ -338,27 +349,6 @@ ErrorOr> CreateOutgoingInternalPayload( } } -// if custom_save_path is empty, default download path is used -std::string make_path(const std::string& custom_save_path, - std::string& parent_folder, std::string& file_name) { - if (!custom_save_path.empty()) { - std::string path = absl::StrCat(custom_save_path, "/", parent_folder); - return api::ImplementationPlatform::GetCustomSavePath(path, file_name); - } - return api::ImplementationPlatform::GetDownloadPath(parent_folder, file_name); -} - -// if custom_save_path is empty, default download path is used -std::string make_path(const std::string& custom_save_path, - std::string& parent_folder, int64_t id) { - std::string file_name(std::to_string(id)); - if (!custom_save_path.empty()) { - std::string path = absl::StrCat(custom_save_path, "/", parent_folder); - return api::ImplementationPlatform::GetCustomSavePath(path, file_name); - } - return api::ImplementationPlatform::GetDownloadPath(parent_folder, file_name); -} - ErrorOr> CreateIncomingInternalPayload( const location::nearby::connections::PayloadTransferFrame& frame, const std::string& custom_save_path) { diff --git a/connections/implementation/internal_payload_factory_test.cc b/connections/implementation/internal_payload_factory_test.cc index dc72bd5c..082b968a 100644 --- a/connections/implementation/internal_payload_factory_test.cc +++ b/connections/implementation/internal_payload_factory_test.cc @@ -14,6 +14,7 @@ #include "connections/implementation/internal_payload_factory.h" +#include #include #include #include @@ -22,6 +23,8 @@ #include "gtest/gtest.h" #include "absl/strings/string_view.h" +#include "absl/time/clock.h" +#include "absl/time/time.h" #include "connections/implementation/internal_payload.h" #include "connections/implementation/proto/offline_wire_formats.pb.h" #include "connections/payload.h" @@ -30,6 +33,7 @@ #include "internal/platform/exception.h" #include "internal/platform/expected.h" #include "internal/platform/file.h" +#include "internal/platform/input_stream.h" #include "internal/platform/pipe.h" namespace nearby { @@ -82,7 +86,7 @@ TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromFilePayload) { TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromByteMessage) { PayloadTransferFrame frame; - std::string path = "C:\\Downloads"; + std::string path = ::testing::TempDir(); frame.set_packet_type(PayloadTransferFrame::DATA); std::int64_t payload_chunk_offset = 0; ByteArray data(kText); @@ -108,7 +112,7 @@ TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromByteMessage) { TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromStreamMessage) { PayloadTransferFrame frame; - std::string path = "C:\\Downloads"; + std::string path = ::testing::TempDir(); frame.set_packet_type(PayloadTransferFrame::DATA); auto& header = *frame.mutable_payload_header(); header.set_type(PayloadTransferFrame::PayloadHeader::STREAM); @@ -133,7 +137,7 @@ TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromStreamMessage) { TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromFileMessage) { PayloadTransferFrame frame; - std::string path = "/tmp/Downloads"; + std::string path = ::testing::TempDir(); frame.set_packet_type(PayloadTransferFrame::DATA); auto& header = *frame.mutable_payload_header(); header.set_type(PayloadTransferFrame::PayloadHeader::FILE); @@ -154,7 +158,7 @@ TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromFileMessage) { TEST(InternalPayloadFactoryTest, InternalPayloadFromFileMessageWithoutIdReturnsNullptr) { PayloadTransferFrame frame; - std::string path = "/tmp/Downloads"; + std::string path = ::testing::TempDir(); frame.set_packet_type(PayloadTransferFrame::DATA); auto& header = *frame.mutable_payload_header(); header.set_type(PayloadTransferFrame::PayloadHeader::FILE); @@ -167,7 +171,7 @@ TEST(InternalPayloadFactoryTest, TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromFileMessageWithFileNameNotSet) { PayloadTransferFrame frame; - std::string path = "/tmp/Downloads"; + std::string path = ::testing::TempDir(); frame.set_packet_type(PayloadTransferFrame::DATA); auto& header = *frame.mutable_payload_header(); header.set_type(PayloadTransferFrame::PayloadHeader::FILE); @@ -185,7 +189,7 @@ TEST(InternalPayloadFactoryTest, TEST(InternalPayloadFactoryTest, CanCreateInternalPayloadFromFileMessageWithFileNameSet) { PayloadTransferFrame frame; - std::string path = "/tmp/Downloads"; + std::string path = ::testing::TempDir(); frame.set_packet_type(PayloadTransferFrame::DATA); auto& header = *frame.mutable_payload_header(); header.set_type(PayloadTransferFrame::PayloadHeader::FILE); @@ -202,6 +206,34 @@ TEST(InternalPayloadFactoryTest, EXPECT_EQ(payload.GetFileName(), "test.file.name"); } +TEST(InternalPayloadFactoryTest, + VerifyFilePayloadFileNameParentFolderAndLastModifiedTime) { + PayloadTransferFrame frame; + std::string path = ::testing::TempDir(); + frame.set_packet_type(PayloadTransferFrame::DATA); + auto& header = *frame.mutable_payload_header(); + header.set_type(PayloadTransferFrame::PayloadHeader::FILE); + header.set_id(12345); + header.set_total_size(512); + header.set_file_name("test_file_name"); + header.set_parent_folder("test_parent_folder"); + int64_t time_millis = absl::ToUnixMillis(absl::Now()); + header.set_last_modified_timestamp_millis(time_millis); + ErrorOr> result = + CreateIncomingInternalPayload(frame, path); + ASSERT_FALSE(result.has_error()); + std::unique_ptr internal_payload = std::move(result.value()); + EXPECT_NE(internal_payload, nullptr); + EXPECT_EQ(internal_payload->GetFileName(), "test_file_name"); + EXPECT_EQ(internal_payload->GetParentFolder(), "test_parent_folder"); + // Allow for a 1ms error in the timestamp. This is due to the time being + // converted to a double for the proto and then back to a time. + EXPECT_LE( + std::abs(absl::ToUnixMillis(internal_payload->GetLastModifiedTime()) - + time_millis), + 1); +} + TEST(InternalPayloadFactoryTest, CreateInternalPayloadFailsIfFileCannotBeCreated) { PayloadTransferFrame frame; @@ -251,6 +283,30 @@ TEST(InternalPayloadFactoryTest, EXPECT_EQ(contents_after_skip, ByteArray("456789")); } +TEST(InternalPayloadFactoryTest, + SkipToOffsetForBytesPayloadFailsIfOffsetIsTooLarge) { + ByteArray data(kText); + ErrorOr> result = + CreateOutgoingInternalPayload(Payload{data}); + ASSERT_FALSE(result.has_error()); + std::unique_ptr internal_payload = std::move(result.value()); + ASSERT_NE(internal_payload, nullptr); + EXPECT_EQ(internal_payload->SkipToOffset(1024).exception(), Exception::kIo); +} + +TEST(InternalPayloadFactoryTest, + AttachNextChunkForOutgoingStreamPayloadFails) { + auto [input, output] = CreatePipe(); + ErrorOr> internal_payload_result = + CreateOutgoingInternalPayload(Payload(std::move(input))); + ASSERT_FALSE(internal_payload_result.has_error()); + std::unique_ptr internal_payload = + std::move(internal_payload_result.value()); + EXPECT_NE(internal_payload, nullptr); + EXPECT_EQ(internal_payload->AttachNextChunk("data"), + Exception{Exception::kIo}); +} + TEST(InternalPayloadFactoryTest, SkipToOffset_StreamPayloadValidOffset_SkipsOffset) { absl::string_view contents("0123456789"); @@ -273,6 +329,105 @@ TEST(InternalPayloadFactoryTest, EXPECT_EQ(contents_after_skip, ByteArray("6789")); } +TEST(InternalPayloadFactoryTest, IncomingFilePayloadBehavesCorrectly) { + PayloadTransferFrame frame; + std::string path = ::testing::TempDir(); + frame.set_packet_type(PayloadTransferFrame::DATA); + auto& header = *frame.mutable_payload_header(); + header.set_type(PayloadTransferFrame::PayloadHeader::FILE); + header.set_id(12345); + const int64_t total_size = 512; + header.set_total_size(total_size); + header.set_file_name("test_file_name"); + header.set_parent_folder("test_parent_folder"); + header.set_last_modified_timestamp_millis(1234567890); + ErrorOr> result = + CreateIncomingInternalPayload(frame, path); + ASSERT_FALSE(result.has_error()); + std::unique_ptr internal_payload = std::move(result.value()); + ASSERT_NE(internal_payload, nullptr); + + EXPECT_EQ(internal_payload->GetType(), + PayloadTransferFrame::PayloadHeader::FILE); + EXPECT_EQ(internal_payload->GetTotalSize(), total_size); + EXPECT_TRUE(internal_payload->DetachNextChunk(1024).Empty()); + EXPECT_EQ(internal_payload->SkipToOffset(1024).exception(), + Exception::kIo); + + // Attach a chunk. + std::string chunk1 = "chunk1"; + ASSERT_TRUE(internal_payload->AttachNextChunk(chunk1).Ok()); + + // Attach another chunk. + std::string chunk2 = "chunk2"; + ASSERT_TRUE(internal_payload->AttachNextChunk(chunk2).Ok()); + + // Close payload by attaching empty chunk. + ASSERT_TRUE(internal_payload->AttachNextChunk("").Ok()); + + // Verify file content. + Payload payload = internal_payload->ReleasePayload(); + InputFile* input_file = payload.AsFile(); + ASSERT_NE(input_file, nullptr); + std::string expected_content_str = chunk1 + chunk2; + ByteArray expected_content(expected_content_str); + ExceptionOr file_content = + input_file->Read(expected_content.size()); + input_file->Close(); + ASSERT_TRUE(file_content.ok()); + EXPECT_EQ(file_content.result(), expected_content); +} + +TEST(InternalPayloadFactoryTest, IncomingStreamPayloadBehavesCorrectly) { + PayloadTransferFrame frame; + std::string path = ::testing::TempDir(); + frame.set_packet_type(PayloadTransferFrame::DATA); + auto& header = *frame.mutable_payload_header(); + header.set_type(PayloadTransferFrame::PayloadHeader::STREAM); + header.set_id(12345); + header.set_total_size(0); + ErrorOr> result = + CreateIncomingInternalPayload(frame, path); + ASSERT_FALSE(result.has_error()); + std::unique_ptr internal_payload = std::move(result.value()); + ASSERT_NE(internal_payload, nullptr); + + EXPECT_EQ(internal_payload->GetType(), + PayloadTransferFrame::PayloadHeader::STREAM); + EXPECT_EQ(internal_payload->GetTotalSize(), -1); + EXPECT_TRUE(internal_payload->DetachNextChunk(1024).Empty()); + EXPECT_EQ(internal_payload->SkipToOffset(1024).exception(), Exception::kIo); + + // Attach a chunk. + std::string chunk1 = "chunk1"; + ASSERT_TRUE(internal_payload->AttachNextChunk(chunk1).Ok()); + + // Attach another chunk. + std::string chunk2 = "chunk2"; + ASSERT_TRUE(internal_payload->AttachNextChunk(chunk2).Ok()); + + // Close payload by attaching empty chunk. + ASSERT_TRUE(internal_payload->AttachNextChunk("").Ok()); + + Payload payload = internal_payload->ReleasePayload(); + InputStream* input_stream = payload.AsStream(); + ASSERT_NE(input_stream, nullptr); + + // Read from input stream to verify. + std::string result_str; + while (true) { + ExceptionOr chunk = input_stream->Read(1024); + ASSERT_TRUE(chunk.ok()); + if (chunk.result().Empty()) break; + result_str.append(chunk.result().data(), chunk.result().size()); + } + ByteArray result_bytes(result_str); + std::string expected_content_str = chunk1 + chunk2; + ByteArray expected_content(expected_content_str); + EXPECT_EQ(result_bytes, expected_content); + input_stream->Close(); +} + } // namespace } // namespace connections } // namespace nearby From 0ea5d2362e90019205fa5a9fdcce8db0124a7cf5 Mon Sep 17 00:00:00 2001 From: hai007 Date: Wed, 11 Feb 2026 10:01:43 -0800 Subject: [PATCH 08/49] Add speed test results PiperOrigin-RevId: 868726957 --- internal/proto/analytics/connections_log.proto | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/internal/proto/analytics/connections_log.proto b/internal/proto/analytics/connections_log.proto index 77b0ea4f..08e1c99e 100644 --- a/internal/proto/analytics/connections_log.proto +++ b/internal/proto/analytics/connections_log.proto @@ -445,6 +445,17 @@ message ConnectionsLog { // The supported service. optional location.nearby.proto.connections.SupportedService supported_service = 14; + + // The speed test report. + optional SpeedTestReport speed_test_report = 15; + } + + message SpeedTestReport { + // The throughput in kbytes per second. + optional int32 throughput_kbytes_per_sec = 1; + + // Whether the throughput is incoming or outgoing. + optional bool is_incoming = 2; } // Contains the transfer statistics for a DCT payload. @@ -482,6 +493,9 @@ message ConnectionsLog { // True if this payload transfer is an attempt to resume an interrupted // payload after a reconnection. False if it's a new payload transfer. optional bool is_resumption = 5; + + // The data speed report in kbyte per second using global bytes counter + optional int32 data_speed_report_kbyte_per_sec = 6; } // A Payload transferred (or attempted to be transferred) between devices. From 743093a55d8008a4a2a81c175178029652d63938 Mon Sep 17 00:00:00 2001 From: hai007 Date: Wed, 11 Feb 2026 22:27:18 -0800 Subject: [PATCH 09/49] Automated Code Change PiperOrigin-RevId: 869030558 --- connections/implementation/mediums/ble/BUILD | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/connections/implementation/mediums/ble/BUILD b/connections/implementation/mediums/ble/BUILD index 3a1234f5..619672c2 100644 --- a/connections/implementation/mediums/ble/BUILD +++ b/connections/implementation/mediums/ble/BUILD @@ -56,10 +56,7 @@ cc_library( name = "ble_socket", srcs = ["ble_socket.cc"], hdrs = ["ble_socket.h"], - visibility = [ - "//connections/implementation:__subpackages__", - "//internal/platform/implementation/windows:__pkg__", - ], + visibility = ["//connections/implementation:__subpackages__"], deps = [ ":ble", "//connections/implementation/flags:connections_flags", From f92212b725217313ce014c75f7d381bce5784e72 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 12 Feb 2026 16:13:56 -0800 Subject: [PATCH 10/49] Add is_timeout param to ReadFrame and callback. PiperOrigin-RevId: 869430080 --- sharing/incoming_frames_reader.cc | 55 ++++---- sharing/incoming_frames_reader.h | 33 +++-- sharing/incoming_frames_reader_test.cc | 124 +++++++++++------- sharing/incoming_share_session.cc | 11 +- sharing/incoming_share_session.h | 3 +- sharing/incoming_share_session_test.cc | 80 ++++++----- sharing/nearby_connection_impl_test.cc | 12 +- sharing/nearby_sharing_service_impl.cc | 10 +- sharing/nearby_sharing_service_impl.h | 2 +- sharing/outgoing_share_session.cc | 9 +- sharing/outgoing_share_session.h | 3 +- sharing/outgoing_share_session_test.cc | 6 +- sharing/paired_key_verification_runner.cc | 6 +- .../paired_key_verification_runner_test.cc | 51 +++---- 14 files changed, 239 insertions(+), 166 deletions(-) diff --git a/sharing/incoming_frames_reader.cc b/sharing/incoming_frames_reader.cc index a1b9423d..73d6d49e 100644 --- a/sharing/incoming_frames_reader.cc +++ b/sharing/incoming_frames_reader.cc @@ -56,30 +56,31 @@ std::unique_ptr DecodeV1Frame(const std::vector& data) { IncomingFramesReader::IncomingFramesReader(TaskRunner& service_thread, NearbyConnection* connection) - : service_thread_(service_thread), - connection_(connection) { + : service_thread_(service_thread), connection_(connection) { DCHECK(connection); } IncomingFramesReader::~IncomingFramesReader() { VLOG(1) << "~IncomingFramesReader is called"; - CloseAllPendingReads(); + CloseAllPendingReads(/*is_timeout=*/false); } void IncomingFramesReader::ReadFrame( - std::function)> callback) { - ProcessReadRequest(std::nullopt, std::move(callback), absl::ZeroDuration()); + std::function)> callback, + absl::Duration timeout) { + ProcessReadRequest(std::nullopt, std::move(callback), timeout); } void IncomingFramesReader::ReadFrame( - FrameType frame_type, std::function)> callback, + FrameType frame_type, + std::function)> callback, absl::Duration timeout) { ProcessReadRequest(frame_type, std::move(callback), timeout); } void IncomingFramesReader::ProcessReadRequest( std::optional frame_type, - std::function)> callback, + std::function)> callback, absl::Duration timeout) { std::unique_ptr cached_frame; { @@ -95,7 +96,7 @@ void IncomingFramesReader::ProcessReadRequest( cached_frame = PopCachedFrame(frame_type); } if (cached_frame) { - callback(*cached_frame); + callback(/*is_timeout=*/false, std::move(*cached_frame)); return; } { @@ -105,17 +106,17 @@ void IncomingFramesReader::ProcessReadRequest( read_frame_info_queue_.push(std::move(read_frame_info)); if (timeout != absl::ZeroDuration()) { - timeout_timer_ = std::make_unique( - service_thread_, "frame_reader_timeout", timeout, - [reader = GetWeakPtr()]() { - auto frame_reader = reader.lock(); - if (frame_reader == nullptr) { - LOG(WARNING) << "IncomingFramesReader has already been released " - "before read timeout."; - return; - } - frame_reader->OnTimeout(); - }); + timeout_timer_ = std::make_unique( + service_thread_, "frame_reader_timeout", timeout, + [reader = GetWeakPtr()]() { + auto frame_reader = reader.lock(); + if (frame_reader == nullptr) { + LOG(WARNING) << "IncomingFramesReader has already been released " + "before read timeout."; + return; + } + frame_reader->OnTimeout(); + }); } } ReadNextFrame(); @@ -131,7 +132,7 @@ void IncomingFramesReader::ReadNextFrame() { } if (!bytes.has_value()) { LOG(WARNING) << __func__ << ": Failed to read frame"; - frame_reader->CloseAllPendingReads(); + frame_reader->CloseAllPendingReads(/*is_timeout=*/false); return; } frame_reader->OnDataReadFromConnection(*bytes); @@ -140,7 +141,7 @@ void IncomingFramesReader::ReadNextFrame() { void IncomingFramesReader::OnTimeout() { LOG(WARNING) << __func__ << ": Timed out reading from NearbyConnection."; - CloseAllPendingReads(); + CloseAllPendingReads(/*is_timeout=*/true); } void IncomingFramesReader::OnDataReadFromConnection( @@ -177,7 +178,7 @@ void IncomingFramesReader::OnDataReadFromConnection( Done(std::move(frame)); } -void IncomingFramesReader::CloseAllPendingReads() { +void IncomingFramesReader::CloseAllPendingReads(bool is_timeout) { std::queue queue; { absl::MutexLock lock(mutex_); @@ -186,7 +187,7 @@ void IncomingFramesReader::CloseAllPendingReads() { while (!queue.empty()) { ReadFrameInfo read_frame_info = std::move(queue.front()); queue.pop(); - read_frame_info.callback(std::nullopt); + read_frame_info.callback(is_timeout, std::nullopt); } } @@ -198,7 +199,7 @@ void IncomingFramesReader::Done(std::unique_ptr frame) { read_frame_info = std::move(read_frame_info_queue_.front()); read_frame_info_queue_.pop(); } - read_frame_info.callback(*frame); + read_frame_info.callback(/*is_timeout=*/false, *frame); { absl::MutexLock lock(mutex_); @@ -210,10 +211,10 @@ void IncomingFramesReader::Done(std::unique_ptr frame) { } if (read_frame_info.timeout != absl::ZeroDuration()) { - ReadFrame(*read_frame_info.frame_type, - std::move(read_frame_info.callback), read_frame_info.timeout); + ReadFrame(*read_frame_info.frame_type, std::move(read_frame_info.callback), + read_frame_info.timeout); } else { - ReadFrame(std::move(read_frame_info.callback)); + ReadFrame(std::move(read_frame_info.callback), read_frame_info.timeout); } } diff --git a/sharing/incoming_frames_reader.h b/sharing/incoming_frames_reader.h index 41e10640..cd3ba339 100644 --- a/sharing/incoming_frames_reader.h +++ b/sharing/incoming_frames_reader.h @@ -25,8 +25,8 @@ #include #include "absl/base/thread_annotations.h" -#include "absl/time/time.h" #include "absl/synchronization/mutex.h" +#include "absl/time/time.h" #include "internal/platform/task_runner.h" #include "sharing/nearby_connection.h" #include "sharing/proto/wire_format.pb.h" @@ -45,27 +45,34 @@ class IncomingFramesReader IncomingFramesReader(const IncomingFramesReader&) = delete; IncomingFramesReader& operator=(IncomingFramesReader&) = delete; - // Reads an incoming frame from |connection|. |callback| is called + // Reads an incoming frame from connection. `callback` is called // with the frame read from connection or nullopt if connection socket is - // closed. + // closed or timeout has occurred. If timeout has occurred, the `is_timeout` + // parameter will be true. Set `timeout` to absl::ZeroDuration() to disable + // timeout. // - // Note: Callers are expected wait for |callback| to be run before scheduling + // Note: Callers are expected wait for `callback` to be run before scheduling // subsequent calls to ReadFrame(..). virtual void ReadFrame( std::function< - void(std::optional)> - callback) ABSL_LOCKS_EXCLUDED(mutex_); + void(bool is_timeout, + std::optional)> + callback, + absl::Duration timeout) ABSL_LOCKS_EXCLUDED(mutex_); - // Reads a frame of type |frame_type| from |connection|. |callback| is called + // Reads a frame of type `frame_type` from `connection`. `callback` is called // with the frame read from connection or nullopt if connection socket is - // closed or |timeout| units of time have passed. + // closed or `timeout` units of time have passed. If timeout has occurred, + // the `is_timeout` parameter will be true. Set `timeout` to + // absl::ZeroDuration() to disable timeout. // // Note: Callers are expected wait for |callback| to be run before scheduling // subsequent calls to ReadFrame(..). virtual void ReadFrame( nearby::sharing::service::proto::V1Frame::FrameType frame_type, std::function< - void(std::optional)> + void(bool is_timeout, + std::optional)> callback, absl::Duration timeout) ABSL_LOCKS_EXCLUDED(mutex_); @@ -77,7 +84,8 @@ class IncomingFramesReader struct ReadFrameInfo { std::optional frame_type = std::nullopt; - std::function)> + std::function)> callback = nullptr; absl::Duration timeout = absl::ZeroDuration(); }; @@ -86,10 +94,11 @@ class IncomingFramesReader std::optional frame_type, std::function< - void(std::optional)> + void(bool is_timeout, + std::optional)> callback, absl::Duration timeout) ABSL_LOCKS_EXCLUDED(mutex_); - void CloseAllPendingReads() ABSL_LOCKS_EXCLUDED(mutex_); + void CloseAllPendingReads(bool is_timeout) ABSL_LOCKS_EXCLUDED(mutex_); void ReadNextFrame() ABSL_LOCKS_EXCLUDED(mutex_); void OnDataReadFromConnection(const std::vector& bytes) ABSL_LOCKS_EXCLUDED(mutex_); diff --git a/sharing/incoming_frames_reader_test.cc b/sharing/incoming_frames_reader_test.cc index d0f78654..34a23314 100644 --- a/sharing/incoming_frames_reader_test.cc +++ b/sharing/incoming_frames_reader_test.cc @@ -117,22 +117,16 @@ class IncomingFramesReaderTest : public testing::Test { IncomingFramesReader* frames_reader() { return frames_reader_.get(); } - void FastForward(absl::Duration delta) { - fake_clock_.FastForward(delta); - } + void FastForward(absl::Duration delta) { fake_clock_.FastForward(delta); } - void Sync() { - EXPECT_TRUE(fake_task_runner_.SyncWithTimeout(kTimeout)); - } + void Sync() { EXPECT_TRUE(fake_task_runner_.SyncWithTimeout(kTimeout)); } void ReleaseFrameReader() { frames_reader_.reset(); } - void CloseConnection() { - nearby_connection_ = nullptr; - } + void CloseConnection() { nearby_connection_ = nullptr; } private: FakeClock fake_clock_; - FakeTaskRunner fake_task_runner_ {&fake_clock_, 1}; + FakeTaskRunner fake_task_runner_{&fake_clock_, 1}; FakeDeviceInfo fake_device_info_; std::unique_ptr nearby_connection_; std::shared_ptr frames_reader_ = nullptr; @@ -142,7 +136,8 @@ TEST_F(IncomingFramesReaderTest, ReadTimedOut) { absl::Notification notification; frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_TRUE(is_timeout); EXPECT_EQ(frame, std::nullopt); notification.Notify(); }, @@ -168,10 +163,13 @@ TEST_F(IncomingFramesReaderTest, ReadNonV1FrameSkipped) { connection().WriteMessage(*introduction_frame); absl::Notification notification; - frames_reader()->ReadFrame([&](std::optional frame) { - EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); - notification.Notify(); - }); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); + notification.Notify(); + }, + absl::ZeroDuration()); EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kTimeout)); } @@ -182,10 +180,13 @@ TEST_F(IncomingFramesReaderTest, ReadAnyFrameSuccessful) { connection().WriteMessage(*introduction_frame); absl::Notification notification; - frames_reader()->ReadFrame([&](std::optional frame) { - EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); - notification.Notify(); - }); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); + notification.Notify(); + }, + absl::ZeroDuration()); EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kTimeout)); } @@ -198,7 +199,8 @@ TEST_F(IncomingFramesReaderTest, ReadSuccessful) { absl::Notification notification; frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); notification.Notify(); }, @@ -219,7 +221,8 @@ TEST_F(IncomingFramesReaderTest, ReadSuccessful_JumbledFramesOrdering) { absl::Notification notification; frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); notification.Notify(); }, @@ -243,7 +246,8 @@ TEST_F(IncomingFramesReaderTest, JumbledFramesOrdering_ReadFromCache) { absl::Notification notification; frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); notification.Notify(); }, @@ -252,18 +256,24 @@ TEST_F(IncomingFramesReaderTest, JumbledFramesOrdering_ReadFromCache) { EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kTimeout)); // Reading any frame should return cancel frame, then response frame. absl::Notification cancel_notification; - frames_reader()->ReadFrame([&](std::optional frame) { - ASSERT_NE(frame, std::nullopt); - EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); - cancel_notification.Notify(); - }); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + ASSERT_NE(frame, std::nullopt); + EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); + cancel_notification.Notify(); + }, + absl::ZeroDuration()); EXPECT_TRUE(cancel_notification.WaitForNotificationWithTimeout(kTimeout)); absl::Notification response_notification; - frames_reader()->ReadFrame([&](std::optional frame) { - ASSERT_NE(frame, std::nullopt); - EXPECT_EQ(frame->type(), service::proto::V1Frame::RESPONSE); - response_notification.Notify(); - }); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + ASSERT_NE(frame, std::nullopt); + EXPECT_EQ(frame->type(), service::proto::V1Frame::RESPONSE); + response_notification.Notify(); + }, + absl::ZeroDuration()); EXPECT_TRUE(response_notification.WaitForNotificationWithTimeout(kTimeout)); } @@ -271,7 +281,8 @@ TEST_F(IncomingFramesReaderTest, ReadAfterConnectionClosed) { absl::Notification notification; frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); EXPECT_EQ(frame, std::nullopt); notification.Notify(); }, @@ -285,13 +296,15 @@ TEST_F(IncomingFramesReaderTest, ReadTwoFramesWithTimeoutSuccessfully) { absl::Notification notification; frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); }, kTimeout); frames_reader()->ReadFrame( service::proto::V1Frame::CANCEL, - [&](std::optional frame) { + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); notification.Notify(); }, @@ -312,13 +325,19 @@ TEST_F(IncomingFramesReaderTest, ReadTwoFramesWithTimeoutSuccessfully) { TEST_F(IncomingFramesReaderTest, ReadTwoFramesWithoutTimeoutSuccessfully) { absl::Notification notification; - frames_reader()->ReadFrame([&](std::optional frame) { - EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); - }); - frames_reader()->ReadFrame([&](std::optional frame) { - EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); - notification.Notify(); - }); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame->type(), service::proto::V1Frame::INTRODUCTION); + }, + absl::ZeroDuration()); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); + notification.Notify(); + }, + absl::ZeroDuration()); std::optional> introduction_frame = GetIntroductionFrame(); @@ -336,11 +355,17 @@ TEST_F(IncomingFramesReaderTest, ReadTwoFramesWithoutTimeoutSuccessfully) { TEST_F(IncomingFramesReaderTest, ReleaseFrameReaderDuringRead) { frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { EXPECT_EQ(frame, std::nullopt); }, + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame, std::nullopt); + }, kTimeout); frames_reader()->ReadFrame( service::proto::V1Frame::INTRODUCTION, - [&](std::optional frame) { EXPECT_EQ(frame, std::nullopt); }, + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame, std::nullopt); + }, kTimeout); ReleaseFrameReader(); EXPECT_EQ(frames_reader(), nullptr); @@ -348,10 +373,13 @@ TEST_F(IncomingFramesReaderTest, ReleaseFrameReaderDuringRead) { TEST_F(IncomingFramesReaderTest, SkipInvalidFrame) { absl::Notification notification; - frames_reader()->ReadFrame([&](std::optional frame) { - EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); - notification.Notify(); - }); + frames_reader()->ReadFrame( + [&](bool is_timeout, std::optional frame) { + EXPECT_FALSE(is_timeout); + EXPECT_EQ(frame->type(), service::proto::V1Frame::CANCEL); + notification.Notify(); + }, + absl::ZeroDuration()); std::optional> invalid_frame = GetInvalidFrame(); ASSERT_TRUE(invalid_frame.has_value()); diff --git a/sharing/incoming_share_session.cc b/sharing/incoming_share_session.cc index ac8a1f94..9d74403d 100644 --- a/sharing/incoming_share_session.cc +++ b/sharing/incoming_share_session.cc @@ -26,6 +26,7 @@ #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" +#include "absl/time/time.h" #include "internal/base/file_path.h" #include "internal/platform/clock.h" #include "internal/platform/task_runner.h" @@ -203,8 +204,8 @@ bool IncomingShareSession::ProcessKeyVerificationResult( frames_reader()->ReadFrame( V1Frame::INTRODUCTION, - [callback = - std::move(introduction_callback)](std::optional frame) { + [callback = std::move(introduction_callback)]( + bool is_timeout, std::optional frame) { if (!frame.has_value()) { callback(std::nullopt); } else { @@ -217,7 +218,8 @@ bool IncomingShareSession::ProcessKeyVerificationResult( bool IncomingShareSession::ReadyForTransfer( std::function accept_timeout_callback, - std::function frame)> frame_read_callback) { + std::function frame)> + frame_read_callback) { if (!IsConnected()) { LOG(WARNING) << "ReadyForTransfer called when not connected"; return false; @@ -228,7 +230,8 @@ bool IncomingShareSession::ReadyForTransfer( mutual_acceptance_timeout_ = std::make_unique( service_thread(), "incoming_mutual_acceptance_timeout", kReadResponseFrameTimeout, std::move(accept_timeout_callback)); - frames_reader()->ReadFrame(std::move(frame_read_callback)); + frames_reader()->ReadFrame(std::move(frame_read_callback), + absl::ZeroDuration()); if (!self_share()) { TransferMetadataBuilder transfer_metadata_builder; diff --git a/sharing/incoming_share_session.h b/sharing/incoming_share_session.h index 0f145d99..3728d4cf 100644 --- a/sharing/incoming_share_session.h +++ b/sharing/incoming_share_session.h @@ -78,7 +78,8 @@ class IncomingShareSession : public ShareSession { bool ReadyForTransfer( std::function accept_timeout_callback, std::function< - void(std::optional frame)> + void(bool is_timeout, + std::optional frame)> frame_read_callback); // Accept the transfer and begin listening for payload transfer updates. diff --git a/sharing/incoming_share_session_test.cc b/sharing/incoming_share_session_test.cc index 596697f6..70fd119d 100644 --- a/sharing/incoming_share_session_test.cc +++ b/sharing/incoming_share_session_test.cc @@ -297,24 +297,25 @@ TEST_F(IncomingShareSessionTest, ProcessIntroductionSuccess) { TEST_F(IncomingShareSessionTest, ProcessIntroductionWithApkSuccess) { IntroductionFrame introduction_frame; - CHECK(proto2::TextFormat::ParseFromString(R"pb( - app_metadata { - app_name: "MyApp" - size: 300 - payload_id: 9876 - payload_id: 9877 - payload_id: 9878 - id: 1234 - file_name: "MyApp.apk" - file_name: "MyApp1.apk" - file_name: "MyApp2.apk" - file_size: 100 - file_size: 100 - file_size: 100 - package_name: "com.example.myapp" - } - )pb", - &introduction_frame)); + CHECK( + proto2::TextFormat::ParseFromString(R"pb( + app_metadata { + app_name: "MyApp" + size: 300 + payload_id: 9876 + payload_id: 9877 + payload_id: 9878 + id: 1234 + file_name: "MyApp.apk" + file_name: "MyApp1.apk" + file_name: "MyApp2.apk" + file_size: 100 + file_size: 100 + file_size: 100 + package_name: "com.example.myapp" + } + )pb", + &introduction_frame)); service::proto::AppMetadata app_metadata = introduction_frame.app_metadata(0); int64_t payload_id1 = app_metadata.payload_id(0); int64_t payload_id2 = app_metadata.payload_id(1); @@ -394,7 +395,8 @@ TEST_F(IncomingShareSessionTest, HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( @@ -496,7 +498,8 @@ TEST_F(IncomingShareSessionTest, HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( @@ -597,7 +600,8 @@ TEST_F(IncomingShareSessionTest, HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( std::make_unique( @@ -697,7 +701,8 @@ TEST_F(IncomingShareSessionTest, HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( @@ -798,7 +803,8 @@ TEST_F(IncomingShareSessionTest, GetPayloadFilePaths) { HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( std::make_unique( @@ -855,7 +861,8 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateCompleteWithSuccess) { HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( std::make_unique( @@ -953,7 +960,8 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateCancelled) { HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( std::make_unique( @@ -997,7 +1005,8 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateFailed) { connections_manager_.SetIncomingPayload( wifi_payload_id2_, CreateWifiCredentialsPayload(wifi_payload_id2_, "password2", true)); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( std::make_unique( @@ -1048,7 +1057,8 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateInProgress) { HasEventType(EventType::RECEIVE_ATTACHMENTS_START), Property(&SharingLog::receive_attachments_start, HasSessionId(1234))))))); - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}); + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( std::make_unique( @@ -1066,7 +1076,8 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateInProgress) { TEST_F(IncomingShareSessionTest, ReadyForTransferNotConnected) { EXPECT_THAT( - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}), + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}), IsFalse()); } @@ -1077,7 +1088,8 @@ TEST_F(IncomingShareSessionTest, ReadyForTransferNotSelfShare) { Call(_, HasStatus(TransferMetadata::Status::kAwaitingLocalConfirmation))); EXPECT_THAT( - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}), + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}), IsFalse()); } @@ -1096,7 +1108,8 @@ TEST_F(IncomingShareSessionTest, ReadyForTransferSelfShare) { .Times(0); EXPECT_THAT( - session.ReadyForTransfer([]() {}, [](std::optional frame) {}), + session.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}), IsTrue()); } @@ -1109,7 +1122,7 @@ TEST_F(IncomingShareSessionTest, ReadyForTransferTimeout) { EXPECT_THAT(session_.ReadyForTransfer( [&accept_timeout_called]() { accept_timeout_called = true; }, - [](std::optional frame) {}), + [](bool is_timeout, std::optional frame) {}), IsFalse()); clock_.FastForward(absl::Seconds(60)); task_runner_.SyncWithTimeout(absl::Milliseconds(100)); @@ -1142,7 +1155,7 @@ TEST_F(IncomingShareSessionTest, ReadyForTransferTimeoutCancelled) { bool accept_timeout_called = false; EXPECT_THAT(session_.ReadyForTransfer( [&accept_timeout_called]() { accept_timeout_called = true; }, - [](std::optional frame) {}), + [](bool is_timeout, std::optional frame) {}), IsFalse()); session_.AcceptTransfer([]() {}); session_.PushPayloadTransferUpdateForTest( @@ -1177,7 +1190,8 @@ TEST_F(IncomingShareSessionTest, AcceptTransferSuccess) { EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_), Eq(std::nullopt)); EXPECT_THAT( - session_.ReadyForTransfer([]() {}, [](std::optional frame) {}), + session_.ReadyForTransfer( + []() {}, [](bool is_timeout, std::optional frame) {}), IsFalse()); EXPECT_CALL( transfer_metadata_callback_, diff --git a/sharing/nearby_connection_impl_test.cc b/sharing/nearby_connection_impl_test.cc index 3ea55c63..f2a70f37 100644 --- a/sharing/nearby_connection_impl_test.cc +++ b/sharing/nearby_connection_impl_test.cc @@ -41,10 +41,12 @@ TEST(NearbyConnectionImpl, DestructorBeforeReaderDestructor) { absl::Notification notification; frames_reader->ReadFrame( - [&](std::optional frame) { + [&](bool is_timeout, + std::optional frame) { called = true; notification.Notify(); - }); + }, + absl::ZeroDuration()); EXPECT_TRUE(fake_task_runner.SyncWithTimeout(absl::Seconds(1))); connection.reset(); EXPECT_TRUE(notification.WaitForNotificationWithTimeout(absl::Seconds(1))); @@ -63,10 +65,12 @@ TEST(NearbyConnectionImpl, DestructorAfterReaderDestructor) { absl::Notification notification; frames_reader->ReadFrame( - [&](std::optional frame) { + [&](bool is_timeout, + std::optional frame) { frame_result = frame; notification.Notify(); - }); + }, + absl::ZeroDuration()); EXPECT_TRUE(fake_task_runner.SyncWithTimeout(absl::Seconds(1))); frames_reader.reset(); diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index ebbcb722..7f6b69c8 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -2563,8 +2563,9 @@ void NearbySharingServiceImpl::OnReceiveConnectionResponse( } session->SendPayloads( [this, share_target_id]( + bool is_timeout, std::optional frame) { - OnFrameRead(share_target_id, std::move(frame)); + OnFrameRead(share_target_id, is_timeout, std::move(frame)); }, absl::bind_front( &NearbySharingServiceImpl::OnOutgoingPayloadTransferUpdates, this, @@ -2597,7 +2598,7 @@ void NearbySharingServiceImpl::OnStorageCheckCompleted( } void NearbySharingServiceImpl::OnFrameRead( - int64_t share_target_id, + int64_t share_target_id, bool is_timeout, std::optional frame) { if (!frame.has_value()) { // This is the case when the connection has been closed since we wait @@ -2640,9 +2641,10 @@ void NearbySharingServiceImpl::OnFrameRead( session->frames_reader()->ReadFrame( [this, share_target_id]( + bool is_timeout, std::optional frame) { - OnFrameRead(share_target_id, std::move(frame)); - }); + OnFrameRead(share_target_id, is_timeout, std::move(frame)); + }, absl::ZeroDuration()); } void NearbySharingServiceImpl::OnConnectionDisconnected( diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index d2fbec13..f1e7b211 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -320,7 +320,7 @@ class NearbySharingServiceImpl frame); void OnStorageCheckCompleted(IncomingShareSession& session); void OnFrameRead( - int64_t share_target_id, + int64_t share_target_id, bool is_timeout, std::optional frame); void OnConnectionDisconnected(int64_t share_target_id); diff --git a/sharing/outgoing_share_session.cc b/sharing/outgoing_share_session.cc index 228f8244..6d89c6f2 100644 --- a/sharing/outgoing_share_session.cc +++ b/sharing/outgoing_share_session.cc @@ -342,7 +342,8 @@ bool OutgoingShareSession::AcceptTransfer( VLOG(1) << "Waiting for response frame from " << share_target().id; frames_reader()->ReadFrame( nearby::sharing::service::proto::V1Frame::RESPONSE, - [callback = std::move(response_callback)](std::optional frame) { + [callback = std::move(response_callback)](bool is_timeout, + std::optional frame) { if (!frame.has_value()) { callback(std::nullopt); return; @@ -355,14 +356,16 @@ bool OutgoingShareSession::AcceptTransfer( void OutgoingShareSession::SendPayloads( std::function< - void(std::optional frame)> + void(bool is_tiumeout, + std::optional frame)> frame_read_callback, std::function payload_transder_update_callback) { if (!IsConnected()) { LOG(WARNING) << "SendPayloads invoked for unconnected share target"; return; } - frames_reader()->ReadFrame(std::move(frame_read_callback)); + frames_reader()->ReadFrame(std::move(frame_read_callback), + absl::ZeroDuration()); // Log analytics event of sending attachment start. analytics_recorder().NewSendAttachmentsStart( diff --git a/sharing/outgoing_share_session.h b/sharing/outgoing_share_session.h index 27b7d8e7..d4742c6c 100644 --- a/sharing/outgoing_share_session.h +++ b/sharing/outgoing_share_session.h @@ -102,7 +102,8 @@ class OutgoingShareSession : public ShareSession { // Any other frames received will be passed to `frame_read_callback`. void SendPayloads( std::function< - void(std::optional frame)> + void(bool is_timeout, + std::optional frame)> frame_read_callback, std::function payload_transder_update_callback); // Send the next payload to NearbyConnectionManager. diff --git a/sharing/outgoing_share_session_test.cc b/sharing/outgoing_share_session_test.cc index e627b12d..b8f902d6 100644 --- a/sharing/outgoing_share_session_test.cc +++ b/sharing/outgoing_share_session_test.cc @@ -673,7 +673,7 @@ TEST_F(OutgoingShareSessionTest, SendPayloads) { NearbyConnectionImpl connection(device_info_); ConnectionSuccess(&connection); - session_.SendPayloads([](std::optional frame) {}, + session_.SendPayloads([](bool is_timeout, std::optional frame) {}, payload_transder_update_callback.AsStdFunction()); auto payload_listener = session_.payload_tracker().lock(); @@ -714,7 +714,7 @@ TEST_F(OutgoingShareSessionTest, SendPayloadsSetsAdvancedProtectionFlags) { session_.SetAdvancedProtectionStatus(/*advanced_protection_enabled=*/true, /*advanced_protection_mismatch=*/true); - session_.SendPayloads([](std::optional frame) {}, + session_.SendPayloads([](bool is_timeout, std::optional frame) {}, payload_transder_update_callback.AsStdFunction()); auto payload_listener = session_.payload_tracker().lock(); @@ -753,7 +753,7 @@ TEST_F(OutgoingShareSessionTest, SendNextPayload) { NearbyConnectionImpl connection(device_info_); ConnectionSuccess(&connection); - session_.SendPayloads([](std::optional frame) {}, + session_.SendPayloads([](bool is_timeout, std::optional frame) {}, payload_transder_update_callback.AsStdFunction()); EXPECT_CALL(send_payload_callback, Call(_, _)) diff --git a/sharing/paired_key_verification_runner.cc b/sharing/paired_key_verification_runner.cc index 7952d47c..e8cd74f3 100644 --- a/sharing/paired_key_verification_runner.cc +++ b/sharing/paired_key_verification_runner.cc @@ -137,7 +137,8 @@ void PairedKeyVerificationRunner::Run( SendPairedKeyEncryptionFrame(); frames_reader_->ReadFrame( V1Frame::PAIRED_KEY_ENCRYPTION, - [&, runner = GetWeakPtr()](std::optional frame) { + [&, runner = GetWeakPtr()](bool is_timeout, + std::optional frame) { auto verification_runner = runner.lock(); if (verification_runner == nullptr) { LOG(WARNING) << "PairedKeyVerificationRunner is released before."; @@ -182,7 +183,8 @@ void PairedKeyVerificationRunner::OnReadPairedKeyEncryptionFrame( frames_reader_->ReadFrame( V1Frame::PAIRED_KEY_RESULT, - [this, runner = GetWeakPtr()](std::optional frame) { + [this, runner = GetWeakPtr()](bool is_timeout, + std::optional frame) { auto verification_runner = runner.lock(); if (verification_runner == nullptr) { LOG(WARNING) << "PairedKeyVerificationRunner is released before."; diff --git a/sharing/paired_key_verification_runner_test.cc b/sharing/paired_key_verification_runner_test.cc index 1c293832..c022e972 100644 --- a/sharing/paired_key_verification_runner_test.cc +++ b/sharing/paired_key_verification_runner_test.cc @@ -142,15 +142,18 @@ class MockIncomingFramesReader : public IncomingFramesReader { NearbyConnection* connection) : IncomingFramesReader(service_thread, connection) {} - MOCK_METHOD(void, ReadFrame, - (std::function)> callback), - (override)); + MOCK_METHOD( + void, ReadFrame, + (std::function)> callback, + absl::Duration timeout), + (override)); - MOCK_METHOD(void, ReadFrame, - (service::proto::V1Frame_FrameType frame_type, - std::function)> callback, - absl::Duration timeout), - (override)); + MOCK_METHOD( + void, ReadFrame, + (service::proto::V1Frame_FrameType frame_type, + std::function)> callback, + absl::Duration timeout), + (override)); }; PairedKeyVerificationRunner::PairedKeyVerificationResult Merge( @@ -201,9 +204,7 @@ class PairedKeyVerificationRunnerTest : public testing::Test { }); } - void SetUp() override { - GetFakeClock()->FastForward(absl::Minutes(15)); - } + void SetUp() override { GetFakeClock()->FastForward(absl::Minutes(15)); } void RunVerification( bool is_incoming, bool use_valid_public_certificate, @@ -218,7 +219,8 @@ class PairedKeyVerificationRunnerTest : public testing::Test { auto runner = std::make_shared( &fake_clock_, OSType::WINDOWS, is_incoming, visibility_history, - GetAuthToken(), [this](const Frame& frame) { + GetAuthToken(), + [this](const Frame& frame) { frames_data_.push(std::make_unique(frame)); }, std::move(public_certificate), &certificate_manager_, &frames_reader_, @@ -237,10 +239,12 @@ class PairedKeyVerificationRunnerTest : public testing::Test { EXPECT_CALL(frames_reader_, ReadFrame(testing::Eq(V1Frame::PAIRED_KEY_ENCRYPTION), testing::_, testing::Eq(kTimeout))) - .WillOnce(testing::WithArg<1>(testing::Invoke( - [frame_type](std::function)> callback) { + .WillOnce(testing::WithArg<1>( + [frame_type]( + std::function)> + callback) { if (frame_type == ReturnFrameType::kNull) { - std::move(callback)(std::nullopt); + std::move(callback)(/*is_timeout=*/false, std::nullopt); return; } @@ -286,8 +290,8 @@ class PairedKeyVerificationRunnerTest : public testing::Test { encryption_frame->clear_secret_id_hash(); } - std::move(callback)(std::move(frame)); - }))); + std::move(callback)(/*is_timeout=*/false, std::move(frame)); + })); } void SetUpPairedKeyResultFrame( @@ -297,10 +301,11 @@ class PairedKeyVerificationRunnerTest : public testing::Test { EXPECT_CALL(frames_reader_, ReadFrame(testing::Eq(V1Frame::PAIRED_KEY_RESULT), testing::_, testing::Eq(kTimeout))) - .WillOnce(testing::WithArg<1>(testing::Invoke( - [=](std::function)> callback) { + .WillOnce(testing::WithArg<1>( + [=](std::function)> + callback) { if (frame_type == ReturnFrameType::kNull) { - std::move(callback)(std::nullopt); + std::move(callback)(/*is_timeout=*/false, std::nullopt); return; } @@ -312,8 +317,8 @@ class PairedKeyVerificationRunnerTest : public testing::Test { result_frame->set_status(status); result_frame->set_os_type(os_type); - std::move(callback)(std::move(frame)); - }))); + std::move(callback)(/*is_timeout=*/false, std::move(frame)); + })); } std::unique_ptr GetWrittenFrame() { std::unique_ptr frame = std::move(frames_data_.front()); @@ -338,7 +343,7 @@ class PairedKeyVerificationRunnerTest : public testing::Test { private: FakeClock fake_clock_; - FakeTaskRunner fake_task_runner_ {&fake_clock_, 1}; + FakeTaskRunner fake_task_runner_{&fake_clock_, 1}; FakeDeviceInfo fake_device_info_; FakeNearbyConnectionsManager fake_connections_manager_; NearbyConnectionImpl connection_; From 80a263efeb730cb17de3140844563af985ca622c Mon Sep 17 00:00:00 2001 From: hai007 Date: Fri, 13 Feb 2026 09:49:00 -0800 Subject: [PATCH 11/49] Internal change PiperOrigin-RevId: 869774557 --- proto/connections_enums.proto | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/proto/connections_enums.proto b/proto/connections_enums.proto index 3414b9c6..6ab2ebbf 100644 --- a/proto/connections_enums.proto +++ b/proto/connections_enums.proto @@ -97,7 +97,10 @@ enum Medium { // //depot/google3/java/com/google/android/gms/nearby/internal/connection/api.proto, // //depot/google3/third_party/nearby/connections/implementation/proto/offline_wire_formats.proto, // //depot/google3/wireless/android/stats/platform/westworld/public/protos/enums/android/nearby/connections/enums.proto, -// //depot/google3/third_party/nearby/connections/c/nc_types.h +// //depot/google3/third_party/nearby/connections/c/nc_types.h, +// //depot/google3/logs/proto/wireless/android/backup/os_migration_log.proto:BandwidthChangedEvent.Medium, +// //depot/google3/java/com/google/android/gmscore/integ/modules/smartdevice/src/com/google/android/gms/smartdevice/logging/gil/SemanticLogger.kt, +// //depot/google3/javatests/com/google/android/gmscore/integ/modules/smartdevice/tests/robolectric/src/com/google/android/gms/smartdevice/logging/gil/SemanticLoggerTest.kt // ) // LINT.IfChange From 91a06b6a7f9549fcbd114948a172b573fc614118 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 16 Feb 2026 08:49:06 -0800 Subject: [PATCH 12/49] Split frame handler for incoming and outgoing sessions. PiperOrigin-RevId: 870909627 --- sharing/incoming_frames_reader.cc | 10 +- sharing/incoming_share_session.cc | 24 ----- sharing/incoming_share_session.h | 11 -- sharing/incoming_share_session_test.cc | 133 ------------------------ sharing/nearby_sharing_service_impl.cc | 135 +++++++++++++++---------- sharing/nearby_sharing_service_impl.h | 10 +- sharing/outgoing_share_session.cc | 6 -- sharing/outgoing_share_session.h | 4 - sharing/outgoing_share_session_test.cc | 32 ------ sharing/share_session.cc | 78 +++++++------- sharing/share_session.h | 14 ++- sharing/share_session_test.cc | 31 +++--- 12 files changed, 153 insertions(+), 335 deletions(-) diff --git a/sharing/incoming_frames_reader.cc b/sharing/incoming_frames_reader.cc index 73d6d49e..72be3530 100644 --- a/sharing/incoming_frames_reader.cc +++ b/sharing/incoming_frames_reader.cc @@ -159,6 +159,7 @@ void IncomingFramesReader::OnDataReadFromConnection( { absl::MutexLock lock(mutex_); if (read_frame_info_queue_.empty()) { + // Drop the frame if no one is waiting. return; } const ReadFrameInfo& frame_info = read_frame_info_queue_.front(); @@ -210,12 +211,9 @@ void IncomingFramesReader::Done(std::unique_ptr frame) { read_frame_info_queue_.pop(); } - if (read_frame_info.timeout != absl::ZeroDuration()) { - ReadFrame(*read_frame_info.frame_type, std::move(read_frame_info.callback), - read_frame_info.timeout); - } else { - ReadFrame(std::move(read_frame_info.callback), read_frame_info.timeout); - } + ProcessReadRequest(read_frame_info.frame_type, + std::move(read_frame_info.callback), + read_frame_info.timeout); } std::unique_ptr IncomingFramesReader::PopCachedFrame( diff --git a/sharing/incoming_share_session.cc b/sharing/incoming_share_session.cc index 9d74403d..2cb7fd91 100644 --- a/sharing/incoming_share_session.cc +++ b/sharing/incoming_share_session.cc @@ -192,30 +192,6 @@ IncomingShareSession::ProcessIntroduction( return std::nullopt; } -bool IncomingShareSession::ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - OSType share_target_os_type, - std::function)> - introduction_callback) { - if (!HandleKeyVerificationResult(result, share_target_os_type)) { - return false; - } - LOG(INFO) << ":Waiting for introduction from " << share_target().id; - - frames_reader()->ReadFrame( - V1Frame::INTRODUCTION, - [callback = std::move(introduction_callback)]( - bool is_timeout, std::optional frame) { - if (!frame.has_value()) { - callback(std::nullopt); - } else { - callback(frame->introduction()); - } - }, - kReadFramesTimeout); - return true; -} - bool IncomingShareSession::ReadyForTransfer( std::function accept_timeout_callback, std::function frame)> diff --git a/sharing/incoming_share_session.h b/sharing/incoming_share_session.h index 3728d4cf..1ec0e519 100644 --- a/sharing/incoming_share_session.h +++ b/sharing/incoming_share_session.h @@ -61,17 +61,6 @@ class IncomingShareSession : public ShareSession { const nearby::sharing::service::proto::IntroductionFrame& introduction_frame); - // Processes the PairedKeyVerificationResult. - // Returns true if verification was successful and the session is now waiting - // for the introduction frame. Calls |introduction_callback| when it is - // received. - bool ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - location::nearby::proto::sharing::OSType share_target_os_type, - std::function)> - introduction_callback); - // Returns true if the transfer can begin and AcceptTransfer should be called // immediately. // Returns false if user needs to accept the transfer. diff --git a/sharing/incoming_share_session_test.cc b/sharing/incoming_share_session_test.cc index 70fd119d..b926f65b 100644 --- a/sharing/incoming_share_session_test.cc +++ b/sharing/incoming_share_session_test.cc @@ -1235,139 +1235,6 @@ TEST_F(IncomingShareSessionTest, AcceptTransferSuccess) { ConnectionResponseFrame::ACCEPT); } -TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultSuccess) { - session_.OnConnected(&connection_); - session_.SetTokenForTests("1234"); - - bool introduction_received = false; - EXPECT_THAT( - session_.ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess, - OSType::WINDOWS, - [&introduction_received](std::optional) { - introduction_received = true; - }), - IsTrue()); - - EXPECT_THAT(session_.self_share(), IsFalse()); - EXPECT_THAT(session_.token(), IsEmpty()); - EXPECT_THAT(session_.os_type(), Eq(OSType::WINDOWS)); - EXPECT_THAT(introduction_received, IsFalse()); - - // Send Introduction frame - nearby::sharing::service::proto::Frame frame = - nearby::sharing::service::proto::Frame(); - frame.set_version(nearby::sharing::service::proto::Frame::V1); - V1Frame* v1frame = frame.mutable_v1(); - v1frame->set_type(service::proto::V1Frame::INTRODUCTION); - v1frame->mutable_introduction(); - std::vector data; - data.resize(frame.ByteSizeLong()); - EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue()); - connection_.WriteMessage(std::move(data)); - - EXPECT_THAT(introduction_received, IsTrue()); -} - -TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultFail) { - session_.OnConnected(&connection_); - session_.SetTokenForTests("1234"); - - bool introduction_received = false; - EXPECT_THAT( - session_.ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail, - OSType::WINDOWS, - [&introduction_received](std::optional) { - introduction_received = true; - }), - IsFalse()); - - EXPECT_THAT(session_.token(), Eq("1234")); - EXPECT_THAT(session_.os_type(), Eq(OSType::WINDOWS)); - EXPECT_THAT(introduction_received, IsFalse()); - - // Send Introduction frame - nearby::sharing::service::proto::Frame frame = - nearby::sharing::service::proto::Frame(); - frame.set_version(nearby::sharing::service::proto::Frame::V1); - V1Frame* v1frame = frame.mutable_v1(); - v1frame->set_type(service::proto::V1Frame::INTRODUCTION); - v1frame->mutable_introduction(); - std::vector data; - data.resize(frame.ByteSizeLong()); - EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue()); - connection_.WriteMessage(std::move(data)); - - EXPECT_THAT(introduction_received, IsFalse()); -} - -TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultUnable) { - session_.OnConnected(&connection_); - session_.SetTokenForTests("1234"); - - bool introduction_received = false; - EXPECT_THAT( - session_.ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable, - OSType::WINDOWS, - [&introduction_received](std::optional) { - introduction_received = true; - }), - IsTrue()); - - EXPECT_THAT(session_.token(), Eq("1234")); - EXPECT_THAT(session_.os_type(), Eq(OSType::WINDOWS)); - EXPECT_THAT(introduction_received, IsFalse()); - - // Send Introduction frame - nearby::sharing::service::proto::Frame frame = - nearby::sharing::service::proto::Frame(); - frame.set_version(nearby::sharing::service::proto::Frame::V1); - V1Frame* v1frame = frame.mutable_v1(); - v1frame->set_type(service::proto::V1Frame::INTRODUCTION); - v1frame->mutable_introduction(); - std::vector data; - data.resize(frame.ByteSizeLong()); - EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue()); - connection_.WriteMessage(std::move(data)); - - EXPECT_THAT(introduction_received, IsTrue()); -} - -TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultUnknown) { - session_.OnConnected(&connection_); - session_.SetTokenForTests("1234"); - - bool introduction_received = false; - EXPECT_THAT( - session_.ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnknown, - OSType::WINDOWS, - [&introduction_received](std::optional) { - introduction_received = true; - }), - IsFalse()); - - EXPECT_THAT(session_.token(), Eq("1234")); - EXPECT_THAT(session_.os_type(), Eq(OSType::WINDOWS)); - EXPECT_THAT(introduction_received, IsFalse()); - - // Send Introduction frame - nearby::sharing::service::proto::Frame frame = - nearby::sharing::service::proto::Frame(); - frame.set_version(nearby::sharing::service::proto::Frame::V1); - V1Frame* v1frame = frame.mutable_v1(); - v1frame->set_type(service::proto::V1Frame::INTRODUCTION); - v1frame->mutable_introduction(); - std::vector data; - data.resize(frame.ByteSizeLong()); - EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue()); - connection_.WriteMessage(std::move(data)); - - EXPECT_THAT(introduction_received, IsFalse()); -} - TEST_F(IncomingShareSessionTest, TryUpgradeBandwidthNotNeeded) { session_.OnConnected(&connection_); diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index 7f6b69c8..ecdc59b3 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -2428,6 +2428,57 @@ void NearbySharingServiceImpl::OnIncomingDecryptedCertificate( this, share_target_id)); } +void NearbySharingServiceImpl::OnIncomingSessionFrameRead( + int64_t share_target_id, + bool is_timeout, + std::optional frame) { + IncomingShareSession* session = GetIncomingShareSession(share_target_id); + if (session == nullptr || !session->IsConnected()) { + LOG(WARNING) << __func__ + << ": Session not connected, stop reading frames from target: " + << share_target_id; + return; + } + if (is_timeout) { + LOG(WARNING) << __func__ << ": Timed out reading frame from target: " + << share_target_id; + session->Abort(TransferMetadata::Status::kFailed); + return; + } + if (!frame.has_value()) { + // This is the case when the connection has been closed since we wait + // indefinitely for incoming frames. + return; + } + + VLOG(1) << "Received incoming frame type: " + << static_cast(frame->type()) << " from " << share_target_id; + switch (frame->type()) { + case service::proto::V1Frame::CANCEL: + RunOnNearbySharingServiceThread("cancel_transfer", [this, + share_target_id]() { + LOG(INFO) << __func__ << ": Read the cancel frame, closing connection"; + DoCancel( + share_target_id, [](StatusCodes status_codes) {}, + /*is_initiator_of_cancellation=*/false); + }); + break; + case service::proto::V1Frame::INTRODUCTION: + OnReceivedIntroduction(*session, frame->introduction()); + // OnReceivedIntroduction will schedule the next ReadFrame. + return; + default: + LOG(ERROR) << __func__ << ": Discarding unknown frame of type: " + << static_cast(frame->type()); + break; + } + + session->frames_reader()->ReadFrame( + absl::bind_front(&NearbySharingServiceImpl::OnIncomingSessionFrameRead, + this, share_target_id), + absl::ZeroDuration()); +} + void NearbySharingServiceImpl::OnIncomingConnectionKeyVerificationDone( int64_t share_target_id, PairedKeyVerificationRunner::PairedKeyVerificationResult result, @@ -2438,11 +2489,15 @@ void NearbySharingServiceImpl::OnIncomingConnectionKeyVerificationDone( return; } if (!session->ProcessKeyVerificationResult( - result, share_target_os_type, - absl::bind_front(&NearbySharingServiceImpl::OnReceivedIntroduction, - this, share_target_id))) { + result, share_target_os_type)) { session->Abort(TransferMetadata::Status::kDeviceAuthenticationFailed); + return; } + LOG(INFO) << "Waiting for introduction from " << share_target_id; + session->frames_reader()->ReadFrame( + absl::bind_front(&NearbySharingServiceImpl::OnIncomingSessionFrameRead, + this, share_target_id), + kReadFramesTimeout); } void NearbySharingServiceImpl::OnOutgoingConnectionKeyVerificationDone( @@ -2497,51 +2552,37 @@ void NearbySharingServiceImpl::OnOutgoingConnectionKeyVerificationDone( } void NearbySharingServiceImpl::OnReceivedIntroduction( - int64_t share_target_id, std::optional frame) { - IncomingShareSession* session = GetIncomingShareSession(share_target_id); - if (!session || !session->IsConnected()) { - LOG(WARNING) - << __func__ - << ": Ignore received introduction, due to no connection established."; - return; - } - - if (!frame.has_value()) { - session->Abort(TransferMetadata::Status::kFailed); - LOG(WARNING) << __func__ << ": Invalid introduction frame"; - return; - } - + IncomingShareSession& session, const IntroductionFrame& frame) { LOG(INFO) << __func__ << ": Successfully read the introduction frame."; std::optional status = - session->ProcessIntroduction(*frame); + session.ProcessIntroduction(frame); if (status.has_value()) { - Fail(*session, *status); + Fail(session, *status); return; } FilePath save_path{settings_->GetCustomSavePath()}; // Override save path for this connection. // This must be called before the transfer is accepted and payloads are being // received. - nearby_connections_manager_->OverrideSavePath(session->endpoint_id(), + nearby_connections_manager_->OverrideSavePath(session.endpoint_id(), save_path); // Log analytics event of receiving introduction. analytics_recorder_.NewReceiveIntroduction( - session->session_id(), session->share_target(), - /*referrer_package=*/std::nullopt, session->os_type()); + session.session_id(), session.share_target(), + /*referrer_package=*/std::nullopt, session.os_type()); if (IsOutOfStorage(device_info_, save_path, - session->attachment_container().GetStorageSize())) { - Fail(*session, TransferMetadata::Status::kNotEnoughSpace); + session.attachment_container().GetStorageSize())) { + Fail(session, TransferMetadata::Status::kNotEnoughSpace); LOG(WARNING) << __func__ << ": Not enough space on the receiver. We have informed " - << share_target_id; + << session.share_target().id; return; } - OnStorageCheckCompleted(*session); + OnStorageCheckCompleted(session); } void NearbySharingServiceImpl::OnReceiveConnectionResponse( @@ -2562,11 +2603,8 @@ void NearbySharingServiceImpl::OnReceiveConnectionResponse( return; } session->SendPayloads( - [this, share_target_id]( - bool is_timeout, - std::optional frame) { - OnFrameRead(share_target_id, is_timeout, std::move(frame)); - }, + absl::bind_front(&NearbySharingServiceImpl::OnOutgoingSessionFrameRead, + this, share_target_id), absl::bind_front( &NearbySharingServiceImpl::OnOutgoingPayloadTransferUpdates, this, share_target_id)); @@ -2585,8 +2623,9 @@ void NearbySharingServiceImpl::OnStorageCheckCompleted( Fail(*session, TransferMetadata::Status::kTimedOut); } }, - absl::bind_front(&NearbySharingServiceImpl::OnFrameRead, this, - session.share_target().id))) { + absl::bind_front( + &NearbySharingServiceImpl::OnIncomingSessionFrameRead, this, + session.share_target().id))) { return; } // Don't need to wait for user to accept for Self share. @@ -2597,7 +2636,7 @@ void NearbySharingServiceImpl::OnStorageCheckCompleted( OnTransferStarted(/*is_incoming=*/true); } -void NearbySharingServiceImpl::OnFrameRead( +void NearbySharingServiceImpl::OnOutgoingSessionFrameRead( int64_t share_target_id, bool is_timeout, std::optional frame) { if (!frame.has_value()) { @@ -2616,35 +2655,25 @@ void NearbySharingServiceImpl::OnFrameRead( /*is_initiator_of_cancellation=*/false); }); break; - - case nearby::sharing::service::proto::V1Frame::CERTIFICATE_INFO: - // No-op, no longer used. - break; - - case nearby::sharing::service::proto::V1Frame::PROGRESS_UPDATE: - // No-op, no longer used. - break; - default: LOG(ERROR) << __func__ << ": Discarding unknown frame of type: " << static_cast(frame->type()); break; } - ShareSession* session = GetShareSession(share_target_id); - if (!session || !session->frames_reader()) { + OutgoingShareSession* session = + outgoing_targets_manager_.GetOutgoingShareSession(share_target_id); + if (!session || !session->IsConnected()) { LOG(WARNING) << __func__ - << ": Stopped reading further frames, due to no connection " - "established."; + << ": Session not connected, stop reading frames from target: " + << share_target_id; return; } session->frames_reader()->ReadFrame( - [this, share_target_id]( - bool is_timeout, - std::optional frame) { - OnFrameRead(share_target_id, is_timeout, std::move(frame)); - }, absl::ZeroDuration()); + absl::bind_front(&NearbySharingServiceImpl::OnOutgoingSessionFrameRead, + this, share_target_id), + absl::ZeroDuration()); } void NearbySharingServiceImpl::OnConnectionDisconnected( diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index f1e7b211..ec045249 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -311,15 +311,19 @@ class NearbySharingServiceImpl int64_t share_target_id, PairedKeyVerificationRunner::PairedKeyVerificationResult result, ::location::nearby::proto::sharing::OSType share_target_os_type); - void OnReceivedIntroduction( + void OnIncomingSessionFrameRead( int64_t share_target_id, - std::optional frame); + bool is_timeout, + std::optional frame); + void OnReceivedIntroduction( + IncomingShareSession& session, + const nearby::sharing::service::proto::IntroductionFrame& frame); void OnReceiveConnectionResponse( int64_t share_target_id, std::optional frame); void OnStorageCheckCompleted(IncomingShareSession& session); - void OnFrameRead( + void OnOutgoingSessionFrameRead( int64_t share_target_id, bool is_timeout, std::optional frame); diff --git a/sharing/outgoing_share_session.cc b/sharing/outgoing_share_session.cc index 6d89c6f2..2522d02a 100644 --- a/sharing/outgoing_share_session.cc +++ b/sharing/outgoing_share_session.cc @@ -188,12 +188,6 @@ bool OutgoingShareSession::InitiateSendAttachments( return success; } -bool OutgoingShareSession::ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - location::nearby::proto::sharing::OSType share_target_os_type) { - return HandleKeyVerificationResult(result, share_target_os_type); -} - void OutgoingShareSession::OnConnectionDisconnected() { disconnection_timeout_ = nullptr; if (pending_complete_metadata_.has_value()) { diff --git a/sharing/outgoing_share_session.h b/sharing/outgoing_share_session.h index d4742c6c..21b8b8e6 100644 --- a/sharing/outgoing_share_session.h +++ b/sharing/outgoing_share_session.h @@ -72,10 +72,6 @@ class OutgoingShareSession : public ShareSession { bool InitiateSendAttachments( std::unique_ptr attachment_container); - bool ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - location::nearby::proto::sharing::OSType share_target_os_type); - // Returns true if the introduction frame is written successfully. // `timeout_callback` is called if accept is not received from both sender and // receiver within the timeout. diff --git a/sharing/outgoing_share_session_test.cc b/sharing/outgoing_share_session_test.cc index b8f902d6..983fc8fb 100644 --- a/sharing/outgoing_share_session_test.cc +++ b/sharing/outgoing_share_session_test.cc @@ -784,38 +784,6 @@ TEST_F(OutgoingShareSessionTest, SendNextPayload) { session_.SendNextPayload(); } -TEST_F(OutgoingShareSessionTest, ProcessKeyVerificationResultFail) { - NearbyConnectionImpl connection(device_info_); - session_.set_session_id(1234); - ConnectionSuccess(&connection); - session_.SetTokenForTests("1234"); - - EXPECT_THAT( - session_.ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail, - OSType::WINDOWS), - IsFalse()); - - EXPECT_THAT(session_.token(), Eq("1234")); - EXPECT_THAT(session_.os_type(), Eq(OSType::WINDOWS)); -} - -TEST_F(OutgoingShareSessionTest, ProcessKeyVerificationResultSuccess) { - NearbyConnectionImpl connection(device_info_); - session_.set_session_id(1234); - ConnectionSuccess(&connection); - session_.SetTokenForTests("1234"); - - EXPECT_THAT( - session_.ProcessKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess, - OSType::WINDOWS), - IsTrue()); - - EXPECT_THAT(session_.token(), IsEmpty()); - EXPECT_THAT(session_.os_type(), Eq(OSType::WINDOWS)); -} - TEST_F(OutgoingShareSessionTest, DelayCompleteReceiverDisconnect) { NearbyConnectionImpl connection(device_info_); session_.set_session_id(1234); diff --git a/sharing/share_session.cc b/sharing/share_session.cc index 0c14e225..885e8396 100644 --- a/sharing/share_session.cc +++ b/sharing/share_session.cc @@ -203,6 +203,45 @@ void ShareSession::RunPairedKeyVerification( key_verification_runner_->Run(std::move(callback)); } +bool ShareSession::ProcessKeyVerificationResult( + PairedKeyVerificationRunner::PairedKeyVerificationResult result, + OSType share_target_os_type) { + os_type_ = share_target_os_type; + + switch (result) { + case PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail: + LOG(WARNING) << __func__ << ": Paired key handshake failed for target " + << share_target().id << ". Disconnecting."; + return false; + + case PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess: + VLOG(1) << __func__ << ": Paired key handshake succeeded for target - " + << share_target().id; + // If verification succeeds, this either means that the target is a + // self-share or a mutual contact. In either case, we should clear the + // token. + token_.resize(0); + break; + + case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable: + VLOG(1) << __func__ + << ": Unable to verify paired key encryption when " + "receiving connection from target - " + << share_target().id; + // If we are unable to verify the paired key, we should clear the self + // share flag. + self_share_ = false; + break; + + case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnknown: + LOG(WARNING) << __func__ + << ": Unknown PairedKeyVerificationResult for target " + << share_target().id << ". Disconnecting."; + return false; + } + return true; +} + void ShareSession::OnDisconnect() { OnConnectionDisconnected(); if (disconnect_status_ != TransferMetadata::Status::kUnknown) { @@ -267,45 +306,6 @@ void ShareSession::WriteCancelFrame() { WriteFrame(frame); } -bool ShareSession::HandleKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - location::nearby::proto::sharing::OSType share_target_os_type) { - os_type_ = share_target_os_type; - - switch (result) { - case PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail: - LOG(WARNING) << __func__ << ": Paired key handshake failed for target " - << share_target().id << ". Disconnecting."; - return false; - - case PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess: - VLOG(1) << __func__ << ": Paired key handshake succeeded for target - " - << share_target().id; - // If verification succeeds, this either means that the target is a - // self-share or a mutual contact. In either case, we should clear the - // token. - token_.resize(0); - break; - - case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable: - VLOG(1) << __func__ - << ": Unable to verify paired key encryption when " - "receiving connection from target - " - << share_target().id; - // If we are unable to verify the paired key, we should clear the self - // share flag. - self_share_ = false; - break; - - case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnknown: - LOG(WARNING) << __func__ - << ": Unknown PairedKeyVerificationResult for target " - << share_target().id << ". Disconnecting."; - return false; - } - return true; -} - void ShareSession::InitializePayloadTracker( absl::AnyInvocable payload_transfer_updates_callback) { auto payload_updates_queue = diff --git a/sharing/share_session.h b/sharing/share_session.h index 9a4f5816..d0dc0f03 100644 --- a/sharing/share_session.h +++ b/sharing/share_session.h @@ -23,6 +23,7 @@ #include #include "absl/container/flat_hash_map.h" +#include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" #include "internal/platform/clock.h" #include "internal/platform/task_runner.h" @@ -71,6 +72,9 @@ class ShareSession { void clear_certificate() { certificate_ = std::nullopt; } NearbyConnection* connection() const { return connection_; } + // Returns true if the session has a valid connection. + // When `IsConnected()` is true, `connection()` is non-null, as is + // `frames_reader()`. bool IsConnected() const { return connection_ != nullptr; } void UpdateTransferMetadata(const TransferMetadata& transfer_metadata); @@ -113,6 +117,11 @@ class ShareSession { void(PairedKeyVerificationRunner::PairedKeyVerificationResult, location::nearby::proto::sharing::OSType)> callback); + // Processes the PairedKeyVerificationResult. + // Returns true if verification was successful. + bool ProcessKeyVerificationResult( + PairedKeyVerificationRunner::PairedKeyVerificationResult result, + location::nearby::proto::sharing::OSType share_target_os_type); void OnDisconnect(); const AttachmentContainer& attachment_container() const { @@ -165,11 +174,6 @@ class ShareSession { return attachment_container_; } void WriteFrame(const nearby::sharing::service::proto::Frame& frame); - // Processes the PairedKeyVerificationResult. - // Returns true if verification was successful. - bool HandleKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - location::nearby::proto::sharing::OSType share_target_os_type); NearbyConnectionsManager& connections_manager() { return connections_manager_; diff --git a/sharing/share_session_test.cc b/sharing/share_session_test.cc index 53469e41..fc6d9211 100644 --- a/sharing/share_session_test.cc +++ b/sharing/share_session_test.cc @@ -69,13 +69,6 @@ class TestShareSession : public ShareSession { ShareSession::SetAttachmentPayloadId(attachment_id, payload_id); } - bool HandleKeyVerificationResult( - PairedKeyVerificationRunner::PairedKeyVerificationResult result, - OSType share_target_os_type) { - return ShareSession::HandleKeyVerificationResult(result, - share_target_os_type); - } - FakeNearbyConnectionsManager& connections_manager() { return connections_manager_; } @@ -319,21 +312,21 @@ TEST(ShareSessionTest, WriteCancelFrame) { EXPECT_EQ(frame.v1().type(), V1Frame::CANCEL); } -TEST(ShareSessionTest, HandleKeyVerificationResultFail) { +TEST(ShareSessionTest, ProcessKeyVerificationResultFail) { ShareTarget share_target; TestShareSession session(std::string(kEndpointId), share_target); NearbyConnectionImpl connection(session.device_info()); session.SetNearbyConnection(&connection); session.SetTokenForTests("9876"); - EXPECT_FALSE(session.HandleKeyVerificationResult( + EXPECT_FALSE(session.ProcessKeyVerificationResult( PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail, OSType::WINDOWS)); EXPECT_EQ(session.os_type(), OSType::WINDOWS); EXPECT_FALSE(session.token().empty()); } -TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareSuccess) { +TEST(ShareSessionTest, ProcessKeyVerificationResultSelfShareSuccess) { ShareTarget share_target; share_target.for_self_share = true; TestShareSession session(std::string(kEndpointId), share_target); @@ -341,7 +334,7 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareSuccess) { session.SetNearbyConnection(&connection); session.SetTokenForTests("9876"); - EXPECT_TRUE(session.HandleKeyVerificationResult( + EXPECT_TRUE(session.ProcessKeyVerificationResult( PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess, OSType::WINDOWS)); EXPECT_EQ(session.os_type(), OSType::WINDOWS); @@ -349,14 +342,14 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareSuccess) { EXPECT_TRUE(session.token().empty()); } -TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareSuccess) { +TEST(ShareSessionTest, ProcessKeyVerificationResultNotSelfShareSuccess) { ShareTarget share_target; TestShareSession session(std::string(kEndpointId), share_target); NearbyConnectionImpl connection(session.device_info()); session.SetNearbyConnection(&connection); session.SetTokenForTests("9876"); - EXPECT_TRUE(session.HandleKeyVerificationResult( + EXPECT_TRUE(session.ProcessKeyVerificationResult( PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess, OSType::WINDOWS)); EXPECT_EQ(session.os_type(), OSType::WINDOWS); @@ -365,7 +358,7 @@ TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareSuccess) { EXPECT_TRUE(session.token().empty()); } -TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareUnable) { +TEST(ShareSessionTest, ProcessKeyVerificationResultSelfShareUnable) { ShareTarget share_target; share_target.for_self_share = true; TestShareSession session(std::string(kEndpointId), share_target); @@ -373,7 +366,7 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareUnable) { session.SetNearbyConnection(&connection); session.SetTokenForTests("9876"); - EXPECT_TRUE(session.HandleKeyVerificationResult( + EXPECT_TRUE(session.ProcessKeyVerificationResult( PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable, OSType::WINDOWS)); EXPECT_EQ(session.os_type(), OSType::WINDOWS); @@ -381,14 +374,14 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareUnable) { EXPECT_FALSE(session.token().empty()); } -TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareUnable) { +TEST(ShareSessionTest, ProcessKeyVerificationResultNotSelfShareUnable) { ShareTarget share_target; TestShareSession session(std::string(kEndpointId), share_target); NearbyConnectionImpl connection(session.device_info()); session.SetNearbyConnection(&connection); session.SetTokenForTests("9876"); - EXPECT_TRUE(session.HandleKeyVerificationResult( + EXPECT_TRUE(session.ProcessKeyVerificationResult( PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable, OSType::WINDOWS)); EXPECT_EQ(session.os_type(), OSType::WINDOWS); @@ -396,14 +389,14 @@ TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareUnable) { EXPECT_FALSE(session.token().empty()); } -TEST(ShareSessionTest, HandleKeyVerificationResultUnknown) { +TEST(ShareSessionTest, ProcessKeyVerificationResultUnknown) { ShareTarget share_target; TestShareSession session(std::string(kEndpointId), share_target); NearbyConnectionImpl connection(session.device_info()); session.SetNearbyConnection(&connection); session.SetTokenForTests("9876"); - EXPECT_FALSE(session.HandleKeyVerificationResult( + EXPECT_FALSE(session.ProcessKeyVerificationResult( PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnknown, OSType::WINDOWS)); EXPECT_EQ(session.os_type(), OSType::WINDOWS); From 306e5df90a1ed20e5f0adee37031336d1a1c824b Mon Sep 17 00:00:00 2001 From: hai007 Date: Tue, 17 Feb 2026 07:09:12 -0800 Subject: [PATCH 13/49] Automated Code Change PiperOrigin-RevId: 871299383 --- .../windows/bluetooth_classic_device.cc | 6 ----- .../windows/bluetooth_classic_socket.cc | 22 +++++-------------- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/internal/platform/implementation/windows/bluetooth_classic_device.cc b/internal/platform/implementation/windows/bluetooth_classic_device.cc index c796c1e6..a419aabf 100644 --- a/internal/platform/implementation/windows/bluetooth_classic_device.cc +++ b/internal/platform/implementation/windows/bluetooth_classic_device.cc @@ -77,12 +77,6 @@ MacAddress BluetoothDevice::GetMacAddress() const { return mac_address_; } // Checks cache first, will check uncached if no result. RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdAsync( RfcommServiceId serviceId) { - if (nearby::NearbyFlags::GetInstance().GetBoolFlag( - platform::config_package_nearby::nearby_platform_feature:: - kEnableNewBluetoothRefactor)) { - return GetRfcommServiceForIdWithRetryAsync(serviceId); - } - try { LOG(INFO) << __func__ << ": Get RF services for service id:" << winrt::to_string(serviceId.AsString()); diff --git a/internal/platform/implementation/windows/bluetooth_classic_socket.cc b/internal/platform/implementation/windows/bluetooth_classic_socket.cc index 199f17b1..92316cc1 100644 --- a/internal/platform/implementation/windows/bluetooth_classic_socket.cc +++ b/internal/platform/implementation/windows/bluetooth_classic_socket.cc @@ -146,29 +146,19 @@ bool BluetoothSocket::Connect(HostName connection_host_name, LOG(INFO) << __func__ << ": start to connect to bluetooth service:" << winrt::to_string(connection_service_name); - if (nearby::NearbyFlags::GetInstance().GetBoolFlag( - platform::config_package_nearby::nearby_platform_feature:: - kEnableNewBluetoothRefactor)) { + int connect_called_count = 0; + while (connect_called_count < kMaxConnectRetryCount) { + connect_called_count += 1; bool connect_result = InternalConnect(connection_host_name, connection_service_name); if (connect_result) { return connect_result; } - } else { - int connect_called_count = 0; - while (connect_called_count < kMaxConnectRetryCount) { - connect_called_count += 1; - bool connect_result = - InternalConnect(connection_host_name, connection_service_name); - if (connect_result) { - return connect_result; - } - LOG(WARNING) << __func__ << ": Failed to connect bluetooth at the " - << connect_called_count << "th call."; + LOG(WARNING) << __func__ << ": Failed to connect bluetooth at the " + << connect_called_count << "th call."; - absl::SleepFor(kConnectInterval); - } + absl::SleepFor(kConnectInterval); } LOG(WARNING) << __func__ << ": Failed to connect bluetooth"; From f42933f7d91dd1e5a54ebb5f6ec6632d312592d5 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Tue, 17 Feb 2026 12:37:08 -0800 Subject: [PATCH 14/49] Deprecate kEnableWifiLanAddressCandidates flag. PiperOrigin-RevId: 871447144 --- .../flags/nearby_platform_feature_flags.h | 4 ---- .../implementation/windows/wifi_lan_medium.cc | 19 ++++--------------- 2 files changed, 4 insertions(+), 19 deletions(-) diff --git a/internal/platform/flags/nearby_platform_feature_flags.h b/internal/platform/flags/nearby_platform_feature_flags.h index 48c83f19..924d80f7 100644 --- a/internal/platform/flags/nearby_platform_feature_flags.h +++ b/internal/platform/flags/nearby_platform_feature_flags.h @@ -65,10 +65,6 @@ constexpr auto kEnableIntelPieSdk = constexpr auto kEnableNewBluetoothRefactor = flags::Flag(kConfigPackage, "45615156", false); -// Enable/Disable use of address candidates for WifiLan upgrade in Windows. -constexpr auto kEnableWifiLanAddressCandidates = - flags::Flag(kConfigPackage, "45739995", false); - // The send buffer size of blocking socket constexpr auto kSocketSendBufferSize = flags::Flag(kConfigPackage, "45673785", 524288); diff --git a/internal/platform/implementation/windows/wifi_lan_medium.cc b/internal/platform/implementation/windows/wifi_lan_medium.cc index f67f507e..f7ab9504 100644 --- a/internal/platform/implementation/windows/wifi_lan_medium.cc +++ b/internal/platform/implementation/windows/wifi_lan_medium.cc @@ -772,21 +772,10 @@ api::UpgradeAddressInfo WifiLanMedium::GetUpgradeAddressCandidates( } } } - if (NearbyFlags::GetInstance().GetBoolFlag( - platform::config_package_nearby::nearby_platform_feature:: - kEnableWifiLanAddressCandidates)) { - // Append v4 addresses to the end of the list. - result.address_candidates.insert(result.address_candidates.end(), - ipv4_addresses.begin(), - ipv4_addresses.end()); - } else { - // If kEnableWifiLanAddressCandidates is disabled, only return the last v4 - // address. - result.address_candidates.clear(); - if (!ipv4_addresses.empty()) { - result.address_candidates.push_back(ipv4_addresses.back()); - } - } + // Append v4 addresses to the end of the list. + result.address_candidates.insert(result.address_candidates.end(), + ipv4_addresses.begin(), + ipv4_addresses.end()); return result; } From a60821574f68f21a3a76addf5a6ded6311f10d5a Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 18 Feb 2026 10:54:28 -0800 Subject: [PATCH 15/49] Fix absl::WebSafeBase64Escape deprecation. PiperOrigin-RevId: 871947460 --- .../nearby_share_certificate_storage_impl.cc | 8 +------- .../nearby_share_certificate_storage_impl_test.cc | 8 +------- .../nearby_share_private_certificate.cc | 13 ++++--------- 3 files changed, 6 insertions(+), 23 deletions(-) diff --git a/sharing/certificates/nearby_share_certificate_storage_impl.cc b/sharing/certificates/nearby_share_certificate_storage_impl.cc index f0e4bf0d..9b1132a7 100644 --- a/sharing/certificates/nearby_share_certificate_storage_impl.cc +++ b/sharing/certificates/nearby_share_certificate_storage_impl.cc @@ -63,12 +63,6 @@ enum InitStatusMetric { kMaxValue = kInvalidOperation }; -std::string EncodeString(absl::string_view unencoded_string) { - std::string result; - absl::WebSafeBase64Escape(unencoded_string, &result); - return result; -} - std::optional DecodeString(const std::string* encoded_string) { std::string result; if (!encoded_string) return std::nullopt; @@ -536,7 +530,7 @@ void NearbyShareCertificateStorageImpl::SavePublicCertificateExpirations() { expirations.reserve(public_certificate_expirations_.size()); for (const std::pair& pair : public_certificate_expirations_) { - expirations.emplace_back(EncodeString(pair.first), + expirations.emplace_back(absl::WebSafeBase64Escape(pair.first), absl::ToUnixNanos(pair.second)); } diff --git a/sharing/certificates/nearby_share_certificate_storage_impl_test.cc b/sharing/certificates/nearby_share_certificate_storage_impl_test.cc index d0d94b8a..edf9b562 100644 --- a/sharing/certificates/nearby_share_certificate_storage_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_storage_impl_test.cc @@ -104,12 +104,6 @@ constexpr char kMetadataEncryptionKey4[] = "metadataencryptionkey4"; constexpr char kEncryptedMetadataBytes4[] = "encryptedmetadatabytes4"; constexpr char kMetadataEncryptionKeyTag4[] = "metadataencryptionkeytag4"; -std::string EncodeString(absl::string_view unencoded_string) { - std::string result; - absl::WebSafeBase64Escape(unencoded_string, &result); - return result; -} - PublicCertificate CreatePublicCertificate( absl::string_view secret_id, absl::string_view secret_key, absl::string_view public_key, int64_t start_seconds, int32_t start_nanos, @@ -186,7 +180,7 @@ class NearbyShareCertificateStorageImplTest : public ::testing::Test { std::vector> expirations; for (const auto& cert : pub_certs) { expirations.emplace_back( - EncodeString(cert.secret_id()), + absl::WebSafeBase64Escape(cert.secret_id()), absl::ToUnixNanos(TimestampToTime(cert.end_time()))); entries.emplace(cert.secret_id(), std::move(cert)); } diff --git a/sharing/certificates/nearby_share_private_certificate.cc b/sharing/certificates/nearby_share_private_certificate.cc index a2b83eab..28bca7f7 100644 --- a/sharing/certificates/nearby_share_private_certificate.cc +++ b/sharing/certificates/nearby_share_private_certificate.cc @@ -92,12 +92,6 @@ std::optional> CreateMetadataEncryptionKeyTag( return result; } -std::string EncodeString(absl::string_view unencoded_string) { - std::string result; - absl::WebSafeBase64Escape(unencoded_string, &result); - return result; -} - std::optional DecodeString(const std::string* encoded_string) { std::string result; if (!encoded_string) return std::nullopt; @@ -109,7 +103,8 @@ std::optional DecodeString(const std::string* encoded_string) { } std::string BytesToEncodedString(const std::vector& bytes) { - return EncodeString(std::string(bytes.begin(), bytes.end())); + return absl::WebSafeBase64Escape(std::string_view( + reinterpret_cast(bytes.data()), bytes.size())); } std::optional> EncodedStringToBytes( @@ -319,11 +314,11 @@ PrivateCertificateData NearbySharePrivateCertificate::ToCertificateData() .not_before = absl::ToUnixNanos(not_before_), .not_after = absl::ToUnixNanos(not_after_), .key_pair = BytesToEncodedString(key_pair), - .secret_key = EncodeString(secret_key_->key()), + .secret_key = absl::WebSafeBase64Escape(secret_key_->key()), .metadata_encryption_key = BytesToEncodedString(metadata_encryption_key_), .id = BytesToEncodedString(id_), .unencrypted_metadata_proto = - EncodeString(unencrypted_metadata_.SerializeAsString()), + absl::WebSafeBase64Escape(unencrypted_metadata_.SerializeAsString()), .consumed_salts = SaltsToString(consumed_salts_), }; } From 675b28c71756e6c4d0c983733b972292d7f574d8 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 19 Feb 2026 10:57:05 -0800 Subject: [PATCH 16/49] Internal changes PiperOrigin-RevId: 872474540 --- sharing/certificates/BUILD | 9 +++++---- .../nearby_share_certificate_manager_impl.cc | 10 +++++++--- .../nearby_share_certificate_manager_impl_test.cc | 4 ++-- sharing/internal/api/BUILD | 2 +- sharing/internal/api/sharing_rpc_client.h | 2 +- sharing/local_device_data/BUILD | 2 -- .../nearby_share_local_device_data_manager_impl.cc | 2 -- 7 files changed, 16 insertions(+), 15 deletions(-) diff --git a/sharing/certificates/BUILD b/sharing/certificates/BUILD index 6ee757bc..e303ab1e 100644 --- a/sharing/certificates/BUILD +++ b/sharing/certificates/BUILD @@ -42,14 +42,15 @@ cc_library( ], visibility = ["//visibility:public"], deps = [ + "//google/nearby/identity/v1:resources_cc_proto", + "//google/nearby/identity/v1:rpcs_cc_proto", + "//google/protobuf:timestamp_cc_proto", "//internal/base", "//internal/base:file_path", "//internal/crypto_cros", "//internal/platform:mac_address", "//internal/platform:types", "//internal/platform/implementation:account_manager", - "//proto/identity/v1:resources_cc_proto", - "//proto/identity/v1:rpcs_cc_proto", "//sharing/common", "//sharing/internal/api:platform", "//sharing/internal/base", @@ -122,12 +123,12 @@ cc_test( deps = [ ":certificates", ":test_support", + "//google/nearby/identity/v1:resources_cc_proto", + "//google/nearby/identity/v1:rpcs_cc_proto", "//internal/platform:mac_address", "//internal/platform/implementation:account_manager", "//internal/platform/implementation:platform_impl", "//internal/test", - "//proto/identity/v1:resources_cc_proto", - "//proto/identity/v1:rpcs_cc_proto", "//sharing/common", "//sharing/common:enum", "//sharing/internal/api:mock_sharing_platform", diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.cc b/sharing/certificates/nearby_share_certificate_manager_impl.cc index 19a745ed..e3b02823 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl.cc @@ -28,6 +28,9 @@ #include #include +#include "google/nearby/identity/v1/resources.pb.h" +#include "google/nearby/identity/v1/rpcs.pb.h" +#include "google/protobuf/timestamp.pb.h" #include "absl/algorithm/algorithm.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" @@ -41,8 +44,6 @@ #include "internal/base/file_path.h" #include "internal/platform/implementation/account_manager.h" #include "internal/platform/mac_address.h" -#include "proto/identity/v1/resources.pb.h" -#include "proto/identity/v1/rpcs.pb.h" #include "sharing/certificates/common.h" #include "sharing/certificates/constants.h" #include "sharing/certificates/nearby_share_certificate_manager.h" @@ -494,7 +495,10 @@ void NearbyShareCertificateManagerImpl::AddCertifactesToPublishDeviceRequest( shared_credential->set_data(public_cert->SerializeAsString()); shared_credential->set_data_type( SharedCredential::DATA_TYPE_PUBLIC_CERTIFICATE); - *shared_credential->mutable_expiration_time() = public_cert->end_time(); + shared_credential->mutable_expiration_time()->set_seconds( + public_cert->end_time().seconds()); + shared_credential->mutable_expiration_time()->set_nanos( + public_cert->end_time().nanos()); } LOG(INFO) << __func__ << ": PublishDevice: uploaded " << self_share_credential_count << " self share credentials and " diff --git a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc index 2624f568..544bc0df 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc @@ -25,6 +25,8 @@ #include #include +#include "google/nearby/identity/v1/resources.pb.h" +#include "google/nearby/identity/v1/rpcs.pb.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" @@ -38,8 +40,6 @@ #include "internal/platform/implementation/account_manager.h" #include "internal/platform/mac_address.h" #include "internal/test/fake_account_manager.h" -#include "proto/identity/v1/resources.pb.h" -#include "proto/identity/v1/rpcs.pb.h" #include "sharing/certificates/constants.h" #include "sharing/certificates/fake_nearby_share_certificate_storage.h" #include "sharing/certificates/nearby_share_certificate_manager.h" diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index 33466d23..502e9934 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -38,11 +38,11 @@ cc_library( "//sharing:__subpackages__", ], deps = [ + "//google/nearby/identity/v1:rpcs_cc_proto", "//internal/base:file_path", "//internal/platform:mac_address", "//internal/platform:types", "//internal/platform/implementation:account_manager", - "//proto/identity/v1:rpcs_cc_proto", "//sharing/analytics", "//sharing/proto:share_cc_proto", "@com_google_absl//absl/functional:any_invocable", diff --git a/sharing/internal/api/sharing_rpc_client.h b/sharing/internal/api/sharing_rpc_client.h index 0a9b6250..374d50b3 100644 --- a/sharing/internal/api/sharing_rpc_client.h +++ b/sharing/internal/api/sharing_rpc_client.h @@ -17,9 +17,9 @@ #include +#include "google/nearby/identity/v1/rpcs.pb.h" #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" -#include "proto/identity/v1/rpcs.pb.h" #include "sharing/proto/certificate_rpc.pb.h" #include "sharing/proto/contact_rpc.pb.h" #include "sharing/proto/device_rpc.pb.h" diff --git a/sharing/local_device_data/BUILD b/sharing/local_device_data/BUILD index 99c101c6..8323219a 100644 --- a/sharing/local_device_data/BUILD +++ b/sharing/local_device_data/BUILD @@ -33,8 +33,6 @@ cc_library( "//internal/platform:types", "//internal/platform/implementation:account_manager", "//internal/platform/implementation:types", - "//proto/identity/v1:resources_cc_proto", - "//proto/identity/v1:rpcs_cc_proto", "//sharing/common", "//sharing/common:enum", "//sharing/internal/api:platform", diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc index deedc608..aaaedea7 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc +++ b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc @@ -27,8 +27,6 @@ #include "internal/platform/device_info.h" #include "internal/platform/implementation/account_manager.h" #include "internal/platform/implementation/device_info.h" -#include "proto/identity/v1/resources.pb.h" -#include "proto/identity/v1/rpcs.pb.h" #include "sharing/common/nearby_share_enums.h" #include "sharing/common/nearby_share_prefs.h" #include "sharing/internal/api/preference_manager.h" From fbc906aaae976104a1db370a7d8b7a92591f052d Mon Sep 17 00:00:00 2001 From: hai007 Date: Fri, 20 Feb 2026 09:29:28 -0800 Subject: [PATCH 17/49] Add logs for play integrity error code PiperOrigin-RevId: 872937909 --- internal/proto/analytics/connections_log.proto | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/proto/analytics/connections_log.proto b/internal/proto/analytics/connections_log.proto index 08e1c99e..6dea3e48 100644 --- a/internal/proto/analytics/connections_log.proto +++ b/internal/proto/analytics/connections_log.proto @@ -352,6 +352,9 @@ message ConnectionsLog { // the device attestation is initiated, to the moment the device attestation // is finished. optional int64 device_attestation_latency_millis = 14; + + // The error code returned by Play Integrity API during device attestation. + optional int64 play_integrity_error_code = 15; } message DeviceInfo { From 4a059b066947a00c82e052ed93497c1708c6d1c4 Mon Sep 17 00:00:00 2001 From: hai007 Date: Fri, 20 Feb 2026 15:14:19 -0800 Subject: [PATCH 18/49] Add more test cases for BluetoothDeviceNameTest improve test coverage. PiperOrigin-RevId: 873094091 --- .../implementation/bluetooth_device_name.cc | 31 +- .../implementation/bluetooth_device_name.h | 3 +- .../bluetooth_device_name_test.cc | 286 +++++++++++------- 3 files changed, 193 insertions(+), 127 deletions(-) diff --git a/connections/implementation/bluetooth_device_name.cc b/connections/implementation/bluetooth_device_name.cc index daaed17b..806dfe7b 100644 --- a/connections/implementation/bluetooth_device_name.cc +++ b/connections/implementation/bluetooth_device_name.cc @@ -21,8 +21,8 @@ #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" -#include "connections/implementation/base_pcp_handler.h" #include "connections/implementation/pcp.h" +#include "connections/implementation/webrtc_state.h" #include "internal/platform/base64_utils.h" #include "internal/platform/byte_array.h" #include "internal/platform/logging.h" @@ -58,6 +58,14 @@ BluetoothDeviceName::BluetoothDeviceName(Version version, Pcp pcp, endpoint_info_ = endpoint_info; uwb_address_ = uwb_address; web_rtc_state_ = web_rtc_state; + if (endpoint_info_.size() > kMaxEndpointInfoLength) { + LOG(INFO) + << "While constructing bluetooth device name, truncating Endpoint Info " + << absl::BytesToHexString(std::string(endpoint_info_)) << " (" + << endpoint_info_.size() << " bytes) down to " << kMaxEndpointInfoLength + << " bytes"; + endpoint_info_ = ByteArray(endpoint_info_.data(), kMaxEndpointInfoLength); + } } BluetoothDeviceName::BluetoothDeviceName( @@ -154,6 +162,14 @@ BluetoothDeviceName::BluetoothDeviceName( return; } endpoint_info_ = *endpoint_info_bytes; + if (endpoint_info_.size() > kMaxEndpointInfoLength) { + LOG(INFO) << "While deserializing bluetooth device name, truncating " + "Endpoint Info " + << absl::BytesToHexString(std::string(endpoint_info_)) << " (" + << endpoint_info_.size() << " bytes) down to " + << kMaxEndpointInfoLength << " bytes"; + endpoint_info_ = ByteArray(endpoint_info_.data(), kMaxEndpointInfoLength); + } // If the input stream has extra bytes, it's for UWB address. The first byte // is the address length. It can be 2-byte short address or 8-byte extended @@ -203,23 +219,14 @@ BluetoothDeviceName::operator std::string() const { ByteArray reserved_bytes{kReservedLength}; - ByteArray usable_endpoint_info(endpoint_info_); - if (endpoint_info_.size() > kMaxEndpointInfoLength) { - LOG(INFO) << "While serializing Advertisement, truncating Endpoint Name " - << absl::BytesToHexString(endpoint_info_.data()) << " (" - << endpoint_info_.size() << " bytes) down to " - << kMaxEndpointInfoLength << " bytes"; - usable_endpoint_info.SetData(endpoint_info_.data(), kMaxEndpointInfoLength); - } - // clang-format off std::string out = absl::StrCat(std::string(1, version_and_pcp_byte), endpoint_id_, std::string(service_id_hash_), std::string(1, field_byte), std::string(reserved_bytes), - std::string(1, usable_endpoint_info.size()), - std::string(usable_endpoint_info)); + std::string(1, endpoint_info_.size()), + std::string(endpoint_info_)); // clang-format on // If UWB address is available, attach it at the end. diff --git a/connections/implementation/bluetooth_device_name.h b/connections/implementation/bluetooth_device_name.h index 8a1399cc..3c0aa500 100644 --- a/connections/implementation/bluetooth_device_name.h +++ b/connections/implementation/bluetooth_device_name.h @@ -18,8 +18,8 @@ #include #include "absl/strings/string_view.h" -#include "connections/implementation/base_pcp_handler.h" #include "connections/implementation/pcp.h" +#include "connections/implementation/webrtc_state.h" #include "internal/platform/byte_array.h" namespace nearby { @@ -80,7 +80,6 @@ class BluetoothDeviceName { std::string endpoint_id_; ByteArray service_id_hash_; ByteArray endpoint_info_; - // TODO(b/169550050): Define UWB address field. ByteArray uwb_address_; WebRtcState web_rtc_state_{WebRtcState::kUndefined}; }; diff --git a/connections/implementation/bluetooth_device_name_test.cc b/connections/implementation/bluetooth_device_name_test.cc index 56935078..cf288445 100644 --- a/connections/implementation/bluetooth_device_name_test.cc +++ b/connections/implementation/bluetooth_device_name_test.cc @@ -14,11 +14,12 @@ #include "connections/implementation/bluetooth_device_name.h" -#include -#include #include #include "gtest/gtest.h" +#include "absl/strings/string_view.h" +#include "connections/implementation/pcp.h" +#include "connections/implementation/webrtc_state.h" #include "internal/platform/base64_utils.h" #include "internal/platform/byte_array.h" @@ -29,138 +30,217 @@ namespace { constexpr BluetoothDeviceName::Version kVersion = BluetoothDeviceName::Version::kV1; constexpr Pcp kPcp = Pcp::kP2pCluster; -constexpr absl::string_view kEndPointID{"AB12"}; -constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"}; -constexpr absl::string_view kEndPointName{"RAWK + ROWL!"}; +constexpr absl::string_view kEndpointId = "ABCD"; +constexpr absl::string_view kServiceIdHash = "ABC"; +constexpr absl::string_view kEndpointInfo = "GG"; constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable; +constexpr int kMaxEndpointInfoLength = 131; -// TODO(b/169550050): Implement UWBAddress. -TEST(BluetoothDeviceNameTest, ConstructionWorks) { - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - kVersion, kPcp, kEndPointID, service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; - - EXPECT_TRUE(bluetooth_device_name.IsValid()); - EXPECT_EQ(kVersion, bluetooth_device_name.GetVersion()); - EXPECT_EQ(kPcp, bluetooth_device_name.GetPcp()); - EXPECT_EQ(kEndPointID, bluetooth_device_name.GetEndpointId()); - EXPECT_EQ(service_id_hash, bluetooth_device_name.GetServiceIdHash()); - EXPECT_EQ(endpoint_info, bluetooth_device_name.GetEndpointInfo()); - EXPECT_EQ(kWebRtcState, bluetooth_device_name.GetWebRtcState()); -} - -TEST(BluetoothDeviceNameTest, ConstructionWorksWithEmptyEndpointName) { - ByteArray empty_endpoint_info; - - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; +TEST(BluetoothDeviceNameTest, ConstructionWithUwbAddress) { + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + ByteArray uwb_address{{0x01, 0x02}}; BluetoothDeviceName bluetooth_device_name{kVersion, kPcp, - kEndPointID, + kEndpointId, service_id_hash, - empty_endpoint_info, - ByteArray{}, + endpoint_info, + uwb_address, kWebRtcState}; EXPECT_TRUE(bluetooth_device_name.IsValid()); - EXPECT_EQ(kVersion, bluetooth_device_name.GetVersion()); - EXPECT_EQ(kPcp, bluetooth_device_name.GetPcp()); - EXPECT_EQ(kEndPointID, bluetooth_device_name.GetEndpointId()); - EXPECT_EQ(service_id_hash, bluetooth_device_name.GetServiceIdHash()); - EXPECT_EQ(empty_endpoint_info, bluetooth_device_name.GetEndpointInfo()); - EXPECT_EQ(kWebRtcState, bluetooth_device_name.GetWebRtcState()); + EXPECT_EQ(bluetooth_device_name.GetVersion(), kVersion); + EXPECT_EQ(bluetooth_device_name.GetPcp(), kPcp); + EXPECT_EQ(bluetooth_device_name.GetEndpointId(), kEndpointId); + EXPECT_EQ(bluetooth_device_name.GetServiceIdHash(), service_id_hash); + EXPECT_EQ(bluetooth_device_name.GetEndpointInfo(), endpoint_info); + EXPECT_EQ(bluetooth_device_name.GetUwbAddress(), uwb_address); + EXPECT_EQ(bluetooth_device_name.GetWebRtcState(), kWebRtcState); +} + +TEST(BluetoothDeviceNameTest, DeserializationWithUwbAddress) { + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + ByteArray uwb_address{{0x01, 0x02}}; + BluetoothDeviceName bluetooth_device_name{kVersion, + kPcp, + kEndpointId, + service_id_hash, + endpoint_info, + uwb_address, + kWebRtcState}; + + std::string bluetooth_device_name_string = std::string(bluetooth_device_name); + + BluetoothDeviceName bluetooth_device_name_from_string( + bluetooth_device_name_string); + EXPECT_TRUE(bluetooth_device_name_from_string.IsValid()); + EXPECT_EQ(bluetooth_device_name_from_string.GetVersion(), kVersion); + EXPECT_EQ(bluetooth_device_name_from_string.GetPcp(), kPcp); + EXPECT_EQ(bluetooth_device_name_from_string.GetEndpointId(), kEndpointId); + EXPECT_EQ(bluetooth_device_name_from_string.GetServiceIdHash(), + service_id_hash); + EXPECT_EQ(bluetooth_device_name_from_string.GetEndpointInfo(), endpoint_info); + EXPECT_EQ(bluetooth_device_name_from_string.GetUwbAddress(), uwb_address); + EXPECT_EQ(bluetooth_device_name_from_string.GetWebRtcState(), kWebRtcState); +} + +TEST(BluetoothDeviceNameTest, + ConstructionWithEmptyUwbAddressAndEmptyEndpointName) { + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray empty_endpoint_info; + ByteArray uwb_address; + BluetoothDeviceName bluetooth_device_name{kVersion, + kPcp, + kEndpointId, + service_id_hash, + empty_endpoint_info, + uwb_address, + kWebRtcState}; + + EXPECT_TRUE(bluetooth_device_name.IsValid()); + EXPECT_EQ(bluetooth_device_name.GetVersion(), kVersion); + EXPECT_EQ(bluetooth_device_name.GetPcp(), kPcp); + EXPECT_EQ(bluetooth_device_name.GetEndpointId(), kEndpointId); + EXPECT_EQ(bluetooth_device_name.GetServiceIdHash(), service_id_hash); + EXPECT_TRUE(bluetooth_device_name.GetEndpointInfo().Empty()); + EXPECT_TRUE(bluetooth_device_name.GetUwbAddress().Empty()); + EXPECT_EQ(bluetooth_device_name.GetWebRtcState(), kWebRtcState); } TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadVersion) { auto bad_version = static_cast(666); - - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - bad_version, kPcp, kEndPointID, service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; - + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + ByteArray uwb_address; + BluetoothDeviceName bluetooth_device_name{bad_version, + kPcp, + kEndpointId, + service_id_hash, + endpoint_info, + uwb_address, + kWebRtcState}; EXPECT_FALSE(bluetooth_device_name.IsValid()); } TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadPcp) { auto bad_pcp = static_cast(666); - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - kVersion, bad_pcp, kEndPointID, service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + BluetoothDeviceName bluetooth_device_name{kVersion, + bad_pcp, + kEndpointId, + service_id_hash, + endpoint_info, + ByteArray{}, + kWebRtcState}; EXPECT_FALSE(bluetooth_device_name.IsValid()); } -TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortEndpointId) { - std::string short_endpoint_id("AB1"); - - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - kVersion, kPcp, short_endpoint_id, service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; - +TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadEndpointIdLength) { + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + ByteArray uwb_address; + BluetoothDeviceName bluetooth_device_name{kVersion, + kPcp, + "1", + service_id_hash, + endpoint_info, + uwb_address, + kWebRtcState}; EXPECT_FALSE(bluetooth_device_name.IsValid()); } -TEST(BluetoothDeviceNameTest, ConstructionFailsWithLongEndpointId) { - std::string long_endpoint_id("AB12X"); - - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - kVersion, kPcp, long_endpoint_id, service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; - +TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadServiceIdHashLength) { + ByteArray service_id_hash{"12"}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + ByteArray uwb_address; + BluetoothDeviceName bluetooth_device_name{kVersion, + kPcp, + kEndpointId, + service_id_hash, + endpoint_info, + uwb_address, + kWebRtcState}; EXPECT_FALSE(bluetooth_device_name.IsValid()); } -TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortServiceIdHash) { - char short_service_id_hash_bytes[] = "\x0a\x0b"; - - ByteArray short_service_id_hash{short_service_id_hash_bytes}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - kVersion, kPcp, kEndPointID, short_service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; - +TEST(BluetoothDeviceNameTest, DeserializationFailsWithBadInput) { + BluetoothDeviceName bluetooth_device_name{"bad input"}; EXPECT_FALSE(bluetooth_device_name.IsValid()); } -TEST(BluetoothDeviceNameTest, ConstructionFailsWithLongServiceIdHash) { - char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d"; - - ByteArray long_service_id_hash{long_service_id_hash_bytes}; - ByteArray endpoint_info{std::string(kEndPointName)}; +TEST(BluetoothDeviceNameTest, DeserializationFailsWithShortInput) { BluetoothDeviceName bluetooth_device_name{ - kVersion, kPcp, kEndPointID, long_service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; - + Base64Utils::Encode(ByteArray{"1"})}; EXPECT_FALSE(bluetooth_device_name.IsValid()); } -TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortStringLength) { - char bluetooth_device_name_string[] = "X"; +TEST(BluetoothDeviceNameTest, EndpointInfoTruncation) { + ByteArray service_id_hash{std::string(kServiceIdHash)}; + std::string long_endpoint_info_string(150, 'a'); + ByteArray endpoint_info{long_endpoint_info_string}; + ByteArray uwb_address; + BluetoothDeviceName bluetooth_device_name{kVersion, + kPcp, + kEndpointId, + service_id_hash, + endpoint_info, + uwb_address, + kWebRtcState}; + EXPECT_EQ(bluetooth_device_name.GetEndpointInfo().size(), + kMaxEndpointInfoLength); - ByteArray bluetooth_device_name_bytes{bluetooth_device_name_string}; - BluetoothDeviceName bluetooth_device_name{ - Base64Utils::Encode(bluetooth_device_name_bytes)}; + std::string bluetooth_device_name_string = std::string(bluetooth_device_name); - EXPECT_FALSE(bluetooth_device_name.IsValid()); + BluetoothDeviceName bluetooth_device_name_from_string( + bluetooth_device_name_string); + EXPECT_TRUE(bluetooth_device_name_from_string.IsValid()); + EXPECT_EQ(bluetooth_device_name_from_string.GetEndpointInfo(), + bluetooth_device_name.GetEndpointInfo()); + EXPECT_EQ(bluetooth_device_name_from_string.GetEndpointInfo().size(), + kMaxEndpointInfoLength); +} + +TEST(BluetoothDeviceNameTest, DeserializationFailsWithBadVersion) { + // version=7, pcp=1 + ByteArray bytes( + "\xE1" + "234567890123456", + 16); + BluetoothDeviceName device_name(Base64Utils::Encode(bytes)); + EXPECT_FALSE(device_name.IsValid()); +} + +TEST(BluetoothDeviceNameTest, DeserializationFailsWithBadPcp) { + // version=1, pcp=31 + ByteArray bytes( + "\x3F" + "234567890123456", + 16); + BluetoothDeviceName device_name(Base64Utils::Encode(bytes)); + EXPECT_FALSE(device_name.IsValid()); +} + +TEST(BluetoothDeviceNameTest, InvalidToString) { + BluetoothDeviceName device_name; + EXPECT_TRUE(std::string(device_name).empty()); + EXPECT_FALSE(device_name.IsValid()); } TEST(BluetoothDeviceNameTest, ConstructionFailsWithWrongEndpointNameLength) { // Serialize good data into a good Bluetooth Device Name. - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - BluetoothDeviceName bluetooth_device_name{ - kVersion, kPcp, kEndPointID, service_id_hash, - endpoint_info, ByteArray{}, kWebRtcState}; + ByteArray service_id_hash{std::string(kServiceIdHash)}; + ByteArray endpoint_info{std::string(kEndpointInfo)}; + BluetoothDeviceName bluetooth_device_name{kVersion, + kPcp, + kEndpointId, + service_id_hash, + endpoint_info, + ByteArray{}, + kWebRtcState}; auto bluetooth_device_name_string = std::string(bluetooth_device_name); // Base64-decode the good Bluetooth Device Name. @@ -182,26 +262,6 @@ TEST(BluetoothDeviceNameTest, ConstructionFailsWithWrongEndpointNameLength) { EXPECT_FALSE(corrupt_bluetooth_device_name.IsValid()); } - -TEST(BluetoothDeviceNameTest, CanParseGeneratedName) { - ByteArray service_id_hash{std::string(kServiceIDHashBytes)}; - ByteArray endpoint_info{std::string(kEndPointName)}; - // Build name1 from scratch. - BluetoothDeviceName name1{kVersion, kPcp, kEndPointID, - service_id_hash, endpoint_info, ByteArray{}, - kWebRtcState}; - // Build name2 from string composed from name1. - BluetoothDeviceName name2{std::string(name1)}; - EXPECT_TRUE(name1.IsValid()); - EXPECT_TRUE(name2.IsValid()); - EXPECT_EQ(name1.GetVersion(), name2.GetVersion()); - EXPECT_EQ(name1.GetPcp(), name2.GetPcp()); - EXPECT_EQ(name1.GetEndpointId(), name2.GetEndpointId()); - EXPECT_EQ(name1.GetServiceIdHash(), name2.GetServiceIdHash()); - EXPECT_EQ(name1.GetEndpointInfo(), name2.GetEndpointInfo()); - EXPECT_EQ(name1.GetWebRtcState(), name2.GetWebRtcState()); -} - } // namespace } // namespace connections } // namespace nearby From bfd0ce1ab4f364a59f5226bfdcb0ec31f8968116 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 23 Feb 2026 08:55:02 -0800 Subject: [PATCH 19/49] Deprecate DeleteUnexpectedReceivedFileFix flag. PiperOrigin-RevId: 874097299 --- .../generated/nearby_sharing_feature_flags.h | 4 -- sharing/nearby_connections_manager_impl.cc | 60 +++-------------- sharing/nearby_connections_manager_impl.h | 6 -- .../nearby_connections_manager_impl_test.cc | 64 ------------------- 4 files changed, 10 insertions(+), 124 deletions(-) diff --git a/sharing/flags/generated/nearby_sharing_feature_flags.h b/sharing/flags/generated/nearby_sharing_feature_flags.h index ceb825c6..2a30f858 100755 --- a/sharing/flags/generated/nearby_sharing_feature_flags.h +++ b/sharing/flags/generated/nearby_sharing_feature_flags.h @@ -61,9 +61,6 @@ constexpr auto kLoggingLevel = // Enable/disable auto-update on settings page constexpr auto kShowAutoUpdateSetting = flags::Flag(kConfigPackage, "45409033", false); -// When true, delete the file payload which received unexpectedly. -constexpr auto kDeleteUnexpectedReceivedFileFix = - flags::Flag(kConfigPackage, "45657036", false); // The default time in milliseconds a cached entry can be in LOST state. constexpr auto kDiscoveryCacheLostExpiryMs = flags::Flag(kConfigPackage, "45658774", 15000); @@ -112,7 +109,6 @@ inline absl::btree_map&> GetBoolFlags() { {45418908, kEnableSelfShareUi}, {45459748, kEnableSendingDesktopEvents}, {45409033, kShowAutoUpdateSetting}, - {45657036, kDeleteUnexpectedReceivedFileFix}, {45673628, kEnableWifiHotspotForHpRealtekDevices}, {45683539, kUseAlternateServiceUuidForDiscovery}, {45662570, kEnableBetaLabel}, diff --git a/sharing/nearby_connections_manager_impl.cc b/sharing/nearby_connections_manager_impl.cc index 16ae5a39..20b6e1ef 100644 --- a/sharing/nearby_connections_manager_impl.cc +++ b/sharing/nearby_connections_manager_impl.cc @@ -783,26 +783,18 @@ void NearbyConnectionsManagerImpl::OnPayloadReceived( absl::string_view endpoint_id, Payload& payload) { MutexLock lock(&mutex_); VLOG(1) << "Received payload id=" << payload.id; - if (NearbyFlags::GetInstance().GetBoolFlag( - sharing::config_package_nearby::nearby_sharing_feature:: - kDeleteUnexpectedReceivedFileFix)) { - if (payload.content.type != PayloadContent::Type::kBytes && - !payload_status_listeners_.contains(payload.id)) { - LOG(WARNING) << __func__ << ": Received unknown payload. Canceling."; - DeleteUnknownFilePayloadAndCancel(payload); - return; - } - if (!incoming_payloads_.contains(payload.id)) { - incoming_payloads_.emplace(payload.id, std::move(payload)); - return; - } - LOG(WARNING) << __func__ << ": Payload id already exists. Canceling."; + if (payload.content.type != PayloadContent::Type::kBytes && + !payload_status_listeners_.contains(payload.id)) { + LOG(WARNING) << __func__ << ": Received unknown payload. Canceling."; DeleteUnknownFilePayloadAndCancel(payload); - } else { - [[maybe_unused]] auto result = - incoming_payloads_.emplace(payload.id, std::move(payload)); - DCHECK(result.second); + return; } + if (!incoming_payloads_.contains(payload.id)) { + incoming_payloads_.emplace(payload.id, std::move(payload)); + return; + } + LOG(WARNING) << __func__ << ": Payload id already exists. Canceling."; + DeleteUnknownFilePayloadAndCancel(payload); } void NearbyConnectionsManagerImpl::DeleteUnknownFilePayloadAndCancel( @@ -814,20 +806,6 @@ void NearbyConnectionsManagerImpl::DeleteUnknownFilePayloadAndCancel( Cancel(payload.id); } -void NearbyConnectionsManagerImpl::ProcessUnknownFilePathsToDelete( - PayloadStatus status, PayloadContent::Type type, const FilePath& path) { - // Unknown payload comes as kInProgress and kCanceled status with kFile type - // from NearbyConnections. Delete it. - if ((status == PayloadStatus::kCanceled || - status == PayloadStatus::kInProgress) && - type == PayloadContent::Type::kFile) { - LOG(WARNING) << __func__ - << ": Unknown payload has been canceled, removing."; - MutexLock lock(&mutex_); - file_paths_to_delete_.insert(path); - } -} - std::optional< std::weak_ptr> NearbyConnectionsManagerImpl::GetStatusListenerForId(int64_t payload_id) const { @@ -892,19 +870,6 @@ void NearbyConnectionsManagerImpl::OnPayloadTransferUpdate( auto payload = GetIncomingPayload(update.payload_id); if (payload == nullptr) return; - if (!NearbyFlags::GetInstance().GetBoolFlag( - sharing::config_package_nearby::nearby_sharing_feature:: - kDeleteUnexpectedReceivedFileFix)) { - if (payload->content.type != PayloadContent::Type::kBytes) { - LOG(WARNING) << "Received unknown payload of file type. Cancelling."; - nearby_connections_service_->CancelPayload(kServiceId, payload->id, - [](Status status) {}); - ProcessUnknownFilePathsToDelete(update.status, payload->content.type, - payload->content.file_payload.file_path); - return; - } - } - if (update.status != PayloadStatus::kSuccess) return; NearbyConnectionImpl* connection = GetConnectionForId(endpoint_id); @@ -1004,11 +969,6 @@ void NearbyConnectionsManagerImpl::AddUnknownFilePathsToDeleteForTesting( file_paths_to_delete_.insert(file_path); } -void NearbyConnectionsManagerImpl::ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus status, PayloadContent::Type type, const FilePath& path) { - ProcessUnknownFilePathsToDelete(status, type, path); -} - void NearbyConnectionsManagerImpl::OnPayloadTransferUpdateForTesting( absl::string_view endpoint_id, const PayloadTransferUpdate& update) { OnPayloadTransferUpdate(endpoint_id, update); diff --git a/sharing/nearby_connections_manager_impl.h b/sharing/nearby_connections_manager_impl.h index ff6f064f..0de7d791 100644 --- a/sharing/nearby_connections_manager_impl.h +++ b/sharing/nearby_connections_manager_impl.h @@ -98,9 +98,6 @@ class NearbyConnectionsManagerImpl : public NearbyConnectionsManager { absl::flat_hash_set GetUnknownFilePathsToDeleteForTesting(); void AddUnknownFilePathsToDeleteForTesting(FilePath file_path); - void ProcessUnknownFilePathsToDeleteForTesting(PayloadStatus status, - PayloadContent::Type type, - const FilePath& path); void OnPayloadTransferUpdateForTesting(absl::string_view endpoint_id, const PayloadTransferUpdate& update); void OnPayloadReceivedForTesting(absl::string_view endpoint_id, @@ -127,9 +124,6 @@ class NearbyConnectionsManagerImpl : public NearbyConnectionsManager { void OnConnectionTimedOut(absl::string_view endpoint_id); void OnConnectionRequested(absl::string_view endpoint_id, ConnectionsStatus status); - void ProcessUnknownFilePathsToDelete(PayloadStatus status, - PayloadContent::Type type, - const FilePath& path); void DeleteUnknownFilePayloadAndCancel(Payload& payload); absl::flat_hash_set GetUnknownFilePathsToDelete(); diff --git a/sharing/nearby_connections_manager_impl_test.cc b/sharing/nearby_connections_manager_impl_test.cc index 325a9762..2e46ec1f 100644 --- a/sharing/nearby_connections_manager_impl_test.cc +++ b/sharing/nearby_connections_manager_impl_test.cc @@ -1897,12 +1897,6 @@ TEST_F(NearbyConnectionsManagerImplTest, OnPayloadReceivedForUnknownFile) { FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); payload_listener_remote.payload_cb(kRemoteEndpointId, Payload(kPayloadId, file)); - - // Flag is on. Add unknown file paths with kCanceled to the list. - NearbyFlags::GetInstance().OverrideBoolFlagValue( - config_package_nearby::nearby_sharing_feature:: - kDeleteUnexpectedReceivedFileFix, - true); nearby_connections_manager_->ClearIncomingPayloads(); Payload payload(kPayloadId, file); nearby_connections_manager_->OnPayloadReceivedForTesting(kRemoteEndpointId, @@ -1933,11 +1927,6 @@ TEST_F(NearbyConnectionsManagerImplTest, OnPayloadReceivedForUnknownFile) { TEST_F(NearbyConnectionsManagerImplTest, OnPayloadReceivedDeletePreviousFileWithSamePayloadId) { - NearbyFlags::GetInstance().OverrideBoolFlagValue( - config_package_nearby::nearby_sharing_feature:: - kDeleteUnexpectedReceivedFileFix, - true); - NearbyConnectionsService::ConnectionListener connection_listener_remote; testing::NiceMock incoming_connection_listener; @@ -1997,59 +1986,6 @@ TEST_F(NearbyConnectionsManagerImplTest, kSynchronizationTimeOut)); } -TEST_F(NearbyConnectionsManagerImplTest, ProcessUnknownFilePathsToDelete) { - FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kCanceled, PayloadContent::Type::kFile, file); - absl::flat_hash_set unknown_file_paths = - nearby_connections_manager_->GetUnknownFilePathsToDeleteForTesting(); - EXPECT_EQ(unknown_file_paths.size(), 1); - nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); - - // Check we add kInProgress status. - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kInProgress, PayloadContent::Type::kFile, file); - unknown_file_paths = - nearby_connections_manager_->GetUnknownFilePathsToDeleteForTesting(); - EXPECT_EQ(unknown_file_paths.size(), 1); - nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); - - // Check only one file is added to the list, since we use hash set. - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kInProgress, PayloadContent::Type::kFile, file); - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kCanceled, PayloadContent::Type::kFile, file); - unknown_file_paths = - nearby_connections_manager_->GetUnknownFilePathsToDeleteForTesting(); - EXPECT_EQ(unknown_file_paths.size(), 1); - nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); - - // Check kSuccess or kFailure are not added to the list. - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kSuccess, PayloadContent::Type::kFile, file); - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kFailure, PayloadContent::Type::kFile, file); - unknown_file_paths = - nearby_connections_manager_->GetUnknownFilePathsToDeleteForTesting(); - EXPECT_TRUE(unknown_file_paths.empty()); - nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); - - // Check only kFile type is added to the list. - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kSuccess, PayloadContent::Type::kBytes, file); - unknown_file_paths = - nearby_connections_manager_->GetUnknownFilePathsToDeleteForTesting(); - EXPECT_TRUE(unknown_file_paths.empty()); - nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); - - nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( - PayloadStatus::kFailure, PayloadContent::Type::kFile, file); - unknown_file_paths = - nearby_connections_manager_->GetUnknownFilePathsToDeleteForTesting(); - EXPECT_TRUE(unknown_file_paths.empty()); - nearby_connections_manager_->GetAndClearUnknownFilePathsToDelete(); -} - TEST_F(NearbyConnectionsManagerImplTest, OverrideSavePath) { EXPECT_CALL(*nearby_connections_, OverrideSavePath(kRemoteEndpointId, "/tmp/test")); From 703401512780575c839be2e292af826c44d42406 Mon Sep 17 00:00:00 2001 From: hai007 Date: Mon, 23 Feb 2026 09:17:42 -0800 Subject: [PATCH 20/49] Extend protobuf to include syncing related messages. PiperOrigin-RevId: 874107544 --- sharing/proto/wire_format.proto | 41 ++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/sharing/proto/wire_format.proto b/sharing/proto/wire_format.proto index 5a166991..2d35c6a7 100644 --- a/sharing/proto/wire_format.proto +++ b/sharing/proto/wire_format.proto @@ -183,7 +183,7 @@ message Frame { optional V1Frame v1 = 2; } -// NEXT_ID=8 +// NEXT_ID=9 message V1Frame { enum FrameType { UNKNOWN_FRAME_TYPE = 0; @@ -196,6 +196,7 @@ message V1Frame { CANCEL = 6; // No longer used. PROGRESS_UPDATE = 7; + FILE_SYNC = 8; } optional FrameType type = 1; @@ -207,6 +208,7 @@ message V1Frame { optional PairedKeyResultFrame paired_key_result = 5; optional CertificateInfoFrame certificate_info = 6 [deprecated = true]; optional ProgressUpdateFrame progress_update = 7 [deprecated = true]; + optional SyncFrame file_sync = 8; } // An introduction packet sent by the sending side. Contains a list of files @@ -241,6 +243,43 @@ message ProgressUpdateFrame { optional bool start_transfer = 2; } +// A packet for file sync messages. +// NEXT_ID=3 +message SyncFrame { + oneof content { + SyncHandshake handshake = 1; + SyncConfig config = 2; + } +} + +// A packet for file sync handshake messages. +// NEXT_ID=1 +message SyncHandshake {} + +// A packet for file sync config messages. +// NEXT_ID=2 +message SyncConfig { + repeated SyncFolder folders = 1; +} + +// A packet for file sync folder messages. +// NEXT_ID=5 +message SyncFolder { + // An identifier of the folder for the pair of source and target devices to + // uniquely identify it among all folders that are being synced. + optional string id = 1; + // Human readable name of the folder. + optional string label = 2; + // A randomly generated id when the index is created. Regenerate when the + // index is reset. + optional int32 index_id = 3; + // The maximum sequence number of the folder. Each number represents an update + // to a file in the folder. Sequence numbers are only valid within the scope + // of a valid index_id. If an index is reset, all sequence numbers need to be + // regenerated, including max_sequence. + optional int64 max_sequence = 4; +} + // A response packet sent by the receiving side. Accepts or rejects the list of // files. // NEXT_ID=4 From 295f480dc133e6a55cef821e31b5b05f7763b65e Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 23 Feb 2026 10:29:54 -0800 Subject: [PATCH 21/49] Add AdvertisementCapabilities to Nearby Share advertisements. PiperOrigin-RevId: 874144304 --- sharing/BUILD | 12 ++++ sharing/advertisement.cc | 45 ++++++++++---- sharing/advertisement.h | 19 +++--- sharing/advertisement_capabilities.cc | 61 +++++++++++++++++++ sharing/advertisement_capabilities.h | 55 +++++++++++++++++ sharing/advertisement_capabilities_test.cc | 67 +++++++++++++++++++++ sharing/advertisement_test.cc | 25 +++++++- sharing/nearby_sharing_service_impl.cc | 8 ++- sharing/nearby_sharing_service_impl.h | 1 + sharing/nearby_sharing_service_impl_test.cc | 8 +-- 10 files changed, 273 insertions(+), 28 deletions(-) create mode 100644 sharing/advertisement_capabilities.cc create mode 100644 sharing/advertisement_capabilities.h create mode 100644 sharing/advertisement_capabilities_test.cc diff --git a/sharing/BUILD b/sharing/BUILD index 43f6618d..a3f8f0a1 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -74,10 +74,12 @@ cc_library( name = "types", srcs = [ "advertisement.cc", + "advertisement_capabilities.cc", "share_target.cc", ], hdrs = [ "advertisement.h", + "advertisement_capabilities.h", "constants.h", "nearby_connection.h", "nearby_connections_manager.h", @@ -1000,3 +1002,13 @@ cc_test( "@com_google_googletest//:gtest_main", ], ) + +cc_test( + name = "advertisement_capabilities_test", + srcs = ["advertisement_capabilities_test.cc"], + deps = [ + ":types", + "@com_github_protobuf_matchers//protobuf-matchers", + "@com_google_googletest//:gtest_main", + ], +) diff --git a/sharing/advertisement.cc b/sharing/advertisement.cc index 16c7eaaf..322615e6 100644 --- a/sharing/advertisement.cc +++ b/sharing/advertisement.cc @@ -23,11 +23,11 @@ #include #include "absl/types/span.h" +#include "sharing/advertisement_capabilities.h" #include "sharing/common/nearby_share_enums.h" #include "sharing/internal/public/logging.h" -namespace nearby { -namespace sharing { +namespace nearby::sharing { namespace { // v1 advertisements: @@ -57,6 +57,7 @@ enum class TlvTypes : uint8_t { kUnknown = 0, kQrCode = 1, kVendorId = 2, + kCapabilities = 3, }; // The length in bytes of the vendor ID in the TLV advertisement. constexpr uint8_t kVendorIdLength = 1; @@ -126,7 +127,7 @@ bool ParseHasDeviceName(uint8_t b) { std::unique_ptr Advertisement::NewInstance( std::vector salt, std::vector encrypted_metadata_key, ShareTargetType device_type, std::optional device_name, - uint8_t vendor_id) { + uint8_t vendor_id, AdvertisementCapabilities capabilities) { if (salt.size() != Advertisement::kSaltSize) { LOG(ERROR) << "Failed to create advertisement because the salt did " "not match the expected length " @@ -153,17 +154,21 @@ std::unique_ptr Advertisement::NewInstance( // Using `new` to access a non-public constructor. return std::make_unique( /* version= */ 0, std::move(salt), std::move(encrypted_metadata_key), - device_type, std::move(device_name), vendor_id); + device_type, std::move(device_name), vendor_id, std::move(capabilities)); } std::vector Advertisement::ToEndpointInfo() const { + std::vector capabilities_data = capabilities_.ToBytes(); // We add 3 bytes for vendor ID because of type (1 byte), len (1 byte), and // the ID itself (1 byte). int size = kMinimumSize + (device_name_.has_value() ? 1 : 0) + (device_name_.has_value() ? device_name_->size() : 0) + (vendor_id_ != static_cast(BlockedVendorId::kNone) ? (kTlvMinimumLength + kVendorIdLength) - : 0); + : 0) + + (capabilities_.IsEmpty() || capabilities_data.empty() + ? 0 + : (kTlvMinimumLength + capabilities_data.size())); std::vector endpoint_info; endpoint_info.reserve(size); @@ -190,6 +195,14 @@ std::vector Advertisement::ToEndpointInfo() const { // The vendor ID itself. endpoint_info.push_back(vendor_id_); } + // Add capabilities TLV + if (!capabilities_.IsEmpty() && !capabilities_data.empty()) { + VLOG(1) << "Adding capabilities to advertisement"; + endpoint_info.push_back(static_cast(TlvTypes::kCapabilities)); + endpoint_info.push_back(static_cast(capabilities_data.size())); + endpoint_info.insert(endpoint_info.end(), capabilities_data.begin(), + capabilities_data.end()); + } return endpoint_info; } @@ -204,7 +217,7 @@ std::unique_ptr Advertisement::FromEndpointInfo( return nullptr; } - auto iter = endpoint_info.begin(); + auto iter = endpoint_info.cbegin(); uint8_t first_byte = *iter++; int version = ParseVersion(first_byte); @@ -242,6 +255,7 @@ std::unique_ptr Advertisement::FromEndpointInfo( } uint8_t vendor_id = static_cast(BlockedVendorId::kNone); + AdvertisementCapabilities capabilities{}; while (endpoint_info.end() - iter >= kTlvMinimumLength) { // We will parse a TLV element now. TlvTypes type = static_cast(*iter++); @@ -263,6 +277,11 @@ std::unique_ptr Advertisement::FromEndpointInfo( // TODO: b/341984671 - Implement handling for this TLV type. iter += value_len; break; + case TlvTypes::kCapabilities: + capabilities = AdvertisementCapabilities::Parse( + absl::MakeConstSpan(iter, value_len)); + iter += value_len; + break; default: LOG(ERROR) << "Unknown TLV type: " << static_cast(type); iter += value_len; @@ -272,7 +291,7 @@ std::unique_ptr Advertisement::FromEndpointInfo( return Advertisement::NewInstance( std::move(salt), std::move(encrypted_metadata_key), device_type, - std::move(optional_device_name), vendor_id); + std::move(optional_device_name), vendor_id, std::move(capabilities)); // LINT.ThenChange(//depot/google3/third_party/nearby/connections/implementation/mediums/advertisements/advertisement_util.cc) } @@ -280,7 +299,8 @@ bool Advertisement::operator==(const Advertisement& other) const { return version_ == other.version_ && salt_ == other.salt_ && encrypted_metadata_key_ == other.encrypted_metadata_key_ && device_type_ == other.device_type_ && - device_name_ == other.device_name_ && vendor_id_ == other.vendor_id_; + device_name_ == other.device_name_ && vendor_id_ == other.vendor_id_ && + capabilities_.ToBytes() == other.capabilities_.ToBytes(); } // private @@ -288,13 +308,14 @@ Advertisement::Advertisement(int version, std::vector salt, std::vector encrypted_metadata_key, ShareTargetType device_type, std::optional device_name, - uint8_t vendor_id) + uint8_t vendor_id, + AdvertisementCapabilities capabilities) : version_(version), salt_(std::move(salt)), encrypted_metadata_key_(std::move(encrypted_metadata_key)), device_type_(device_type), device_name_(std::move(device_name)), - vendor_id_(vendor_id) {} + vendor_id_(vendor_id), + capabilities_(std::move(capabilities)) {} -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing diff --git a/sharing/advertisement.h b/sharing/advertisement.h index 3ea3dcf6..83df79d5 100644 --- a/sharing/advertisement.h +++ b/sharing/advertisement.h @@ -23,10 +23,10 @@ #include #include "absl/types/span.h" +#include "sharing/advertisement_capabilities.h" #include "sharing/common/nearby_share_enums.h" -namespace nearby { -namespace sharing { +namespace nearby::sharing { // An advertisement in the form of // [VERSION|VISIBILITY][SALT][ACCOUNT_IDENTIFIER][LEN][DEVICE_NAME]. @@ -44,17 +44,17 @@ class Advertisement { }; // LINT.ThenChange(//depot/google3/java/com/google/android/gmscore/integ/client/nearby/src/com/google/android/gms/nearby/sharing/SharingOptions.java:VendorId) + static std::unique_ptr NewInstance( std::vector salt, std::vector encrypted_metadata_key, ShareTargetType device_type, std::optional device_name, - uint8_t vendor_id); + uint8_t vendor_id, AdvertisementCapabilities capabilities); - // TODO: b/341967036 - Remove uses of std::optional for device name. Empty - // string should be enough. Advertisement(int version, std::vector salt, std::vector encrypted_metadata_key, ShareTargetType device_type, - std::optional device_name, uint8_t vendor_id); + std::optional device_name, uint8_t vendor_id, + AdvertisementCapabilities capabilities); ~Advertisement() = default; Advertisement(const Advertisement&) = default; Advertisement& operator=(const Advertisement&) = default; @@ -96,14 +96,15 @@ class Advertisement { ShareTargetType device_type_ = ShareTargetType::kUnknown; // The human-readable name of the remote device. - std::optional device_name_ = std::nullopt; + const std::optional device_name_; // The vendor identifier of the remote device. Reference for vendor ID: // google3/java/com/google/android/gmscore/integ/client/nearby/src/com/google/android/gms/nearby/sharing/SharingOptions.java const uint8_t vendor_id_; + + const AdvertisementCapabilities capabilities_; }; -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing #endif // THIRD_PARTY_NEARBY_SHARING_ADVERTISEMENT_H_ diff --git a/sharing/advertisement_capabilities.cc b/sharing/advertisement_capabilities.cc new file mode 100644 index 00000000..8d664f91 --- /dev/null +++ b/sharing/advertisement_capabilities.cc @@ -0,0 +1,61 @@ +// Copyright 2025 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 "sharing/advertisement_capabilities.h" + +#include +#include + +#include "absl/types/span.h" +#include "sharing/internal/public/logging.h" + +namespace nearby::sharing { + +constexpr uint8_t kFileSyncMask = 0b00000001; + +AdvertisementCapabilities AdvertisementCapabilities::Parse( + absl::Span data) { + AdvertisementCapabilities capabilities{}; + for (const uint8_t byte : data) { + switch (byte) { + case static_cast(Capability::kFileSync): + capabilities.Add(Capability::kFileSync); + break; + default: + continue; + } + } + return capabilities; +} + +std::vector AdvertisementCapabilities::ToBytes() const { + std::vector bytes; + for (const Capability capability : capabilities_) { + switch (capability) { + case Capability::kFileSync: + if (bytes.empty()) { + bytes.resize(1); + } + bytes[0] |= kFileSyncMask; + break; + default: + LOG(DFATAL) << "Unhandled capability: " + << static_cast(capability); + break; + } + } + return bytes; +} + +} // namespace nearby::sharing diff --git a/sharing/advertisement_capabilities.h b/sharing/advertisement_capabilities.h new file mode 100644 index 00000000..30b32326 --- /dev/null +++ b/sharing/advertisement_capabilities.h @@ -0,0 +1,55 @@ +// Copyright 2025 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_SHARING_ADVERTISEMENT_CAPABILITIES_H_ +#define THIRD_PARTY_NEARBY_SHARING_ADVERTISEMENT_CAPABILITIES_H_ + +#include +#include +#include +#include "absl/types/span.h" + +namespace nearby::sharing { + +// A container class for storing capabilities to be added to QuickShare +// advertisements. +class AdvertisementCapabilities { + public: + enum class Capability { + kInvalid = 0, + kFileSync = 1, // File sync extension support. + }; + + // Parses serialized capabilities from an advertisement. + static AdvertisementCapabilities Parse(absl::Span data); + + AdvertisementCapabilities(std::initializer_list capabilities) + : capabilities_(capabilities) {} + + void Add(Capability capability) { capabilities_.push_back(capability); } + + // Returns true if there are no capabilities in this object. + bool IsEmpty() const { return capabilities_.empty(); } + + // Serializes the capabilities into a byte array for inclusion in an + // advertisement. + std::vector ToBytes() const; + + private: + std::vector capabilities_; +}; + +} // namespace nearby::sharing + +#endif // THIRD_PARTY_NEARBY_SHARING_ADVERTISEMENT_CAPABILITIES_H_ diff --git a/sharing/advertisement_capabilities_test.cc b/sharing/advertisement_capabilities_test.cc new file mode 100644 index 00000000..8bba3da6 --- /dev/null +++ b/sharing/advertisement_capabilities_test.cc @@ -0,0 +1,67 @@ +// Copyright 2025 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 "sharing/advertisement_capabilities.h" +#include + +#include "gmock/gmock.h" +#include "protobuf-matchers/protocol-buffer-matchers.h" +#include "gtest/gtest.h" + +namespace nearby::sharing { +namespace { + +TEST(AdvertisementCapabilitiesTest, ParseEmpty) { + EXPECT_TRUE(AdvertisementCapabilities::Parse({}).IsEmpty()); +} + +TEST(AdvertisementCapabilitiesTest, ParseFileSync) { + uint8_t data[] = { + static_cast(AdvertisementCapabilities::Capability::kFileSync)}; + AdvertisementCapabilities capabilities = + AdvertisementCapabilities::Parse(data); + EXPECT_FALSE(capabilities.IsEmpty()); + EXPECT_THAT(capabilities.ToBytes(), testing::ElementsAre(0x01)); +} + +TEST(AdvertisementCapabilitiesTest, ToBytesEmpty) { + AdvertisementCapabilities capabilities({}); + EXPECT_TRUE(capabilities.ToBytes().empty()); +} + +TEST(AdvertisementCapabilitiesTest, ToBytesFileSync) { + AdvertisementCapabilities capabilities( + {AdvertisementCapabilities::Capability::kFileSync}); + EXPECT_THAT(capabilities.ToBytes(), testing::ElementsAre(0x01)); +} + +TEST(AdvertisementCapabilitiesTest, AddCapability) { + AdvertisementCapabilities capabilities({}); + EXPECT_TRUE(capabilities.IsEmpty()); + capabilities.Add(AdvertisementCapabilities::Capability::kFileSync); + EXPECT_FALSE(capabilities.IsEmpty()); + EXPECT_THAT(capabilities.ToBytes(), testing::ElementsAre(0x01)); +} + +TEST(AdvertisementCapabilitiesTest, MultipleAdds) { + // Currently only kFileSync is supported. + AdvertisementCapabilities capabilities({}); + capabilities.Add(AdvertisementCapabilities::Capability::kFileSync); + capabilities.Add(AdvertisementCapabilities::Capability::kFileSync); + // Duplicate adds should still result in bit 0 being set. + EXPECT_THAT(capabilities.ToBytes(), testing::ElementsAre(0x01)); +} + +} // namespace +} // namespace nearby::sharing diff --git a/sharing/advertisement_test.cc b/sharing/advertisement_test.cc index ff286518..6d9277e6 100644 --- a/sharing/advertisement_test.cc +++ b/sharing/advertisement_test.cc @@ -21,6 +21,7 @@ #include "gtest/gtest.h" #include "absl/types/span.h" +#include "sharing/advertisement_capabilities.h" #include "sharing/common/nearby_share_enums.h" namespace nearby { @@ -43,6 +44,7 @@ struct TestParameters { ShareTargetType target_type; std::optional target_name; int vendor_id; + AdvertisementCapabilities capabilities; }; class AdvertisementTest : public testing::TestWithParam {}; @@ -51,17 +53,18 @@ TEST_P(AdvertisementTest, TestAdvertisementRoundTrip) { auto params = GetParam(); auto advertisement = Advertisement::NewInstance( params.salt, params.encrypted_metadata_key, params.target_type, - params.target_name, params.vendor_id); + params.target_name, params.vendor_id, params.capabilities); auto bytes = advertisement->ToEndpointInfo(); auto advertisement_from_bytes = Advertisement::FromEndpointInfo(bytes); EXPECT_EQ(*advertisement_from_bytes, *advertisement); } TEST(BadAdvertisementTest, TestTlvParsingOnAdvertisement) { + AdvertisementCapabilities capabilities{}; auto advertisement = Advertisement::NewInstance( std::vector(Advertisement::kSaltSize), std::vector(Advertisement::kMetadataEncryptionKeyHashByteSize), - ShareTargetType::kLaptop, std::nullopt, /*vendor_id=*/1); + ShareTargetType::kLaptop, std::nullopt, /*vendor_id=*/1, capabilities); auto bytes = advertisement->ToEndpointInfo(); // Add a TLV field for QR code. bytes.insert(bytes.end(), kQrCodeTlvBytes.begin(), kQrCodeTlvBytes.end()); @@ -149,6 +152,24 @@ INSTANTIATE_TEST_SUITE_P( .target_type = ShareTargetType::kLaptop, .target_name = std::nullopt, .vendor_id = 0})); +INSTANTIATE_TEST_SUITE_P( + Capabilities, AdvertisementTest, + testing::Values( + TestParameters{.salt = std::vector(Advertisement::kSaltSize), + .encrypted_metadata_key = std::vector( + Advertisement::kMetadataEncryptionKeyHashByteSize), + .target_type = ShareTargetType::kPhone, + .target_name = std::nullopt, + .vendor_id = 0, + .capabilities = AdvertisementCapabilities{}}, + TestParameters{.salt = std::vector(Advertisement::kSaltSize), + .encrypted_metadata_key = std::vector( + Advertisement::kMetadataEncryptionKeyHashByteSize), + .target_type = ShareTargetType::kPhone, + .target_name = std::nullopt, + .vendor_id = 0, + .capabilities = AdvertisementCapabilities{ + AdvertisementCapabilities::Capability::kFileSync}})); } // namespace } // namespace sharing diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index ecdc59b3..11de518d 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -51,6 +51,7 @@ #include "internal/platform/task_runner.h" #include "proto/sharing_enums.pb.h" #include "sharing/advertisement.h" +#include "sharing/advertisement_capabilities.h" #include "sharing/analytics/analytics_information.h" #include "sharing/analytics/analytics_recorder.h" #include "sharing/attachment_container.h" @@ -1503,11 +1504,16 @@ NearbySharingServiceImpl::CreateEndpointInfo( ShareTargetType device_type = static_cast(device_info_.GetDeviceType()); + AdvertisementCapabilities capabilities{}; + if (supports_file_sync_) { + capabilities.Add(AdvertisementCapabilities::Capability::kFileSync); + } std::unique_ptr advertisement = Advertisement::NewInstance( std::move(salt), std::move(encrypted_key), device_type, device_name, visibility == DeviceVisibility::DEVICE_VISIBILITY_EVERYONE ? static_cast(GetReceivingVendorId()) - : static_cast(BlockedVendorId::kNone)); + : static_cast(BlockedVendorId::kNone), + std::move(capabilities)); if (advertisement) { return advertisement->ToEndpointInfo(); } else { diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index ec045249..7f9a13ee 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -524,6 +524,7 @@ class NearbySharingServiceImpl // If true, a new endpoint id will be generated at the next advertisement. bool force_new_endpoint_id_ = false; OutgoingTargetsManager outgoing_targets_manager_; + bool supports_file_sync_ = false; }; } // namespace nearby::sharing diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index dd4bc07f..50ba2b95 100644 --- a/sharing/nearby_sharing_service_impl_test.cc +++ b/sharing/nearby_sharing_service_impl_test.cc @@ -30,7 +30,6 @@ #include #include -#include "base/casts.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" @@ -54,6 +53,7 @@ #include "internal/test/fake_task_runner.h" #include "internal/test/mock_account_observer.h" #include "sharing/advertisement.h" +#include "sharing/advertisement_capabilities.h" #include "sharing/analytics/analytics_recorder.h" #include "sharing/attachment_container.h" #include "sharing/certificates/fake_nearby_share_certificate_manager.h" @@ -739,7 +739,7 @@ class NearbySharingServiceImplTest : public testing::Test { std::unique_ptr advertisement = Advertisement::NewInstance( GetNearbyShareTestEncryptedMetadataKey().salt(), GetNearbyShareTestEncryptedMetadataKey().encrypted_key(), kDeviceType, - kDeviceName, vendor_id); + kDeviceName, vendor_id, AdvertisementCapabilities{}); return advertisement->ToEndpointInfo(); } @@ -1079,7 +1079,7 @@ class NearbySharingServiceImplTest : public testing::Test { std::unique_ptr advertisement = Advertisement::NewInstance( GetNearbyShareTestEncryptedMetadataKey().salt(), GetNearbyShareTestEncryptedMetadataKey().encrypted_key(), kDeviceType, - std::nullopt, kVendorId); + std::nullopt, kVendorId, AdvertisementCapabilities{}); return advertisement->ToEndpointInfo(); } @@ -4517,7 +4517,7 @@ TEST_F(NearbySharingServiceImplTest, CreateShareTarget) { std::unique_ptr advertisement = Advertisement::NewInstance( GetNearbyShareTestEncryptedMetadataKey().salt(), GetNearbyShareTestEncryptedMetadataKey().encrypted_key(), kDeviceType, - kDeviceName, kVendorId); + kDeviceName, kVendorId, AdvertisementCapabilities{}); // Flip |for_self_share| to true to ensure the resulting ShareTarget picks // this up. From 6308d5f200449942fec58c5bf636da7e7a188545 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 23 Feb 2026 12:26:09 -0800 Subject: [PATCH 22/49] Add flag for filesync. PiperOrigin-RevId: 874199291 --- sharing/flags/generated/nearby_sharing_feature_flags.h | 4 ++++ sharing/nearby_sharing_service_factory.cc | 5 +++-- sharing/nearby_sharing_service_factory.h | 3 ++- sharing/nearby_sharing_service_impl.cc | 6 ++++-- sharing/nearby_sharing_service_impl.h | 6 ++++-- sharing/nearby_sharing_service_impl_test.cc | 2 +- 6 files changed, 18 insertions(+), 8 deletions(-) diff --git a/sharing/flags/generated/nearby_sharing_feature_flags.h b/sharing/flags/generated/nearby_sharing_feature_flags.h index 2a30f858..71b1295a 100755 --- a/sharing/flags/generated/nearby_sharing_feature_flags.h +++ b/sharing/flags/generated/nearby_sharing_feature_flags.h @@ -64,6 +64,9 @@ constexpr auto kShowAutoUpdateSetting = // The default time in milliseconds a cached entry can be in LOST state. constexpr auto kDiscoveryCacheLostExpiryMs = flags::Flag(kConfigPackage, "45658774", 15000); +// When true, enable file sync feature. +constexpr auto kEnableFileSync = + flags::Flag(kConfigPackage, "45762616", false); // When true, enable wifi hotspot medium for HP Realtek devices. constexpr auto kEnableWifiHotspotForHpRealtekDevices = flags::Flag(kConfigPackage, "45673628", false); @@ -109,6 +112,7 @@ inline absl::btree_map&> GetBoolFlags() { {45418908, kEnableSelfShareUi}, {45459748, kEnableSendingDesktopEvents}, {45409033, kShowAutoUpdateSetting}, + {45762616, kEnableFileSync}, {45673628, kEnableWifiHotspotForHpRealtekDevices}, {45683539, kUseAlternateServiceUuidForDiscovery}, {45662570, kEnableBetaLabel}, diff --git a/sharing/nearby_sharing_service_factory.cc b/sharing/nearby_sharing_service_factory.cc index 01afe82c..baee53f8 100644 --- a/sharing/nearby_sharing_service_factory.cc +++ b/sharing/nearby_sharing_service_factory.cc @@ -40,7 +40,7 @@ NearbySharingServiceFactory* NearbySharingServiceFactory::GetInstance() { NearbySharingService* NearbySharingServiceFactory::CreateSharingService( SharingPlatform& sharing_platform, analytics::AnalyticsRecorder* analytics_recorder, - ::nearby::analytics::EventLogger* event_logger) { + ::nearby::analytics::EventLogger* event_logger, bool supports_file_sync) { if (nearby_sharing_service_ != nullptr) { return nullptr; } @@ -66,7 +66,8 @@ NearbySharingService* NearbySharingServiceFactory::CreateSharingService( std::move(service_thread), context_.get(), sharing_platform, std::move(nearby_share_client_factory), std::move(nearby_connections_manager), - std::move(nearby_share_contact_manager), analytics_recorder); + std::move(nearby_share_contact_manager), analytics_recorder, + supports_file_sync); return nearby_sharing_service_.get(); } diff --git a/sharing/nearby_sharing_service_factory.h b/sharing/nearby_sharing_service_factory.h index c7a60cac..a1612f76 100644 --- a/sharing/nearby_sharing_service_factory.h +++ b/sharing/nearby_sharing_service_factory.h @@ -33,7 +33,8 @@ class NearbySharingServiceFactory { NearbySharingService* CreateSharingService( nearby::sharing::api::SharingPlatform& sharing_platform, analytics::AnalyticsRecorder* analytics_recorder, - nearby::analytics::EventLogger* event_logger); + nearby::analytics::EventLogger* event_logger, + bool supports_file_sync); private: NearbySharingServiceFactory() = default; diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index 11de518d..fc21d2f4 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -237,13 +237,14 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( std::unique_ptr nearby_share_client_factory, std::unique_ptr nearby_connections_manager, std::unique_ptr contact_manager, - analytics::AnalyticsRecorder* analytics_recorder) + analytics::AnalyticsRecorder* analytics_recorder, bool supports_file_sync) : service_thread_(std::move(service_thread)), context_(context), device_info_(sharing_platform.GetDeviceInfo()), preference_manager_(sharing_platform.GetPreferenceManager()), account_manager_(sharing_platform.GetAccountManager()), analytics_recorder_(*analytics_recorder), + supports_file_sync_(supports_file_sync), nearby_connections_manager_(std::move(nearby_connections_manager)), nearby_share_client_factory_(std::move(nearby_share_client_factory)), local_device_data_manager_( @@ -1505,7 +1506,8 @@ NearbySharingServiceImpl::CreateEndpointInfo( static_cast(device_info_.GetDeviceType()); AdvertisementCapabilities capabilities{}; - if (supports_file_sync_) { + if (supports_file_sync_ && NearbyFlags::GetInstance().GetBoolFlag( + config_package_nearby::nearby_sharing_feature::kEnableFileSync)) { capabilities.Add(AdvertisementCapabilities::Capability::kFileSync); } std::unique_ptr advertisement = Advertisement::NewInstance( diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index 7f9a13ee..82813706 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -106,7 +106,8 @@ class NearbySharingServiceImpl nearby_share_client_factory, std::unique_ptr nearby_connections_manager, std::unique_ptr contact_manager, - analytics::AnalyticsRecorder* analytics_recorder); + analytics::AnalyticsRecorder* analytics_recorder, + bool supports_file_sync); ~NearbySharingServiceImpl() override; // NearbySharingService @@ -410,6 +411,8 @@ class NearbySharingServiceImpl AccountManager& account_manager_; // Used to create analytics events. analytics::AnalyticsRecorder& analytics_recorder_; + // Whether the device supports file sync extension. + const bool supports_file_sync_; std::unique_ptr nearby_connections_manager_; std::unique_ptr @@ -524,7 +527,6 @@ class NearbySharingServiceImpl // If true, a new endpoint id will be generated at the next advertisement. bool force_new_endpoint_id_ = false; OutgoingTargetsManager outgoing_targets_manager_; - bool supports_file_sync_ = false; }; } // namespace nearby::sharing diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index 50ba2b95..8cd68d1a 100644 --- a/sharing/nearby_sharing_service_impl_test.cc +++ b/sharing/nearby_sharing_service_impl_test.cc @@ -485,7 +485,7 @@ class NearbySharingServiceImplTest : public testing::Test { /*nearby_share_client_factory=*/nullptr, absl::WrapUnique(fake_nearby_connections_manager_), absl::WrapUnique(contact_manager_), - analytics_recorder_.get()); + analytics_recorder_.get(), /*supports_file_sync=*/false); } void SetVisibility(DeviceVisibility visibility) { From f5a6ec8a6ef9541e74af039221e21da1c997e853 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 25 Feb 2026 10:56:06 -0800 Subject: [PATCH 23/49] Fix use of deprecated absl::WebSafeBase64Escape. PiperOrigin-RevId: 875241580 --- internal/platform/base64_utils.cc | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/internal/platform/base64_utils.cc b/internal/platform/base64_utils.cc index e3e9d92d..aafcd7d2 100644 --- a/internal/platform/base64_utils.cc +++ b/internal/platform/base64_utils.cc @@ -28,11 +28,7 @@ namespace nearby { std::string Base64Utils::Encode(const ByteArray& bytes) { - std::string base64_string; - - absl::WebSafeBase64Escape(std::string(bytes), &base64_string); - - return base64_string; + return absl::WebSafeBase64Escape(bytes.AsStringView()); } ByteArray Base64Utils::Decode(absl::string_view base64_string) { From 44679a49e1898a8a7cb997a64735b66432b8f5ea Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 25 Feb 2026 15:31:08 -0800 Subject: [PATCH 24/49] Add support for removing preferences using key prefix. PiperOrigin-RevId: 875366484 --- .../apple/preferences_manager.h | 2 ++ .../implementation/g3/preferences_manager.cc | 13 +++++++++++ .../implementation/g3/preferences_manager.h | 2 ++ .../implementation/preferences_manager.h | 4 ++++ .../windows/preferences_manager.cc | 13 +++++++++++ .../windows/preferences_manager.h | 2 ++ .../windows/preferences_manager_test.cc | 23 +++++++++++++++++++ 7 files changed, 59 insertions(+) diff --git a/internal/platform/implementation/apple/preferences_manager.h b/internal/platform/implementation/apple/preferences_manager.h index 64ecee91..2d2dea30 100644 --- a/internal/platform/implementation/apple/preferences_manager.h +++ b/internal/platform/implementation/apple/preferences_manager.h @@ -90,6 +90,8 @@ class PreferencesManager : public nearby::api::PreferencesManager { // Removes preferences void Remove(absl::string_view key) override; + // TODO: b/485304482 - Implement this method if needed.. + bool RemoveKeyPrefix(absl::string_view prefix) override { return false; } }; } // namespace nearby::apple diff --git a/internal/platform/implementation/g3/preferences_manager.cc b/internal/platform/implementation/g3/preferences_manager.cc index 67d89aab..f02f6124 100644 --- a/internal/platform/implementation/g3/preferences_manager.cc +++ b/internal/platform/implementation/g3/preferences_manager.cc @@ -177,6 +177,19 @@ void PreferencesManager::Remove(absl::string_view key) { value_.erase(absl::StrCat(key)); } +bool PreferencesManager::RemoveKeyPrefix(absl::string_view prefix) { + absl::MutexLock lock(mutex_); + auto it = value_.begin(); + while (it != value_.end()) { + if (it.key().starts_with(prefix)) { + it = value_.erase(it); + } else { + ++it; + } + } + return true; +} + // Private methods // Writes data to storage. diff --git a/internal/platform/implementation/g3/preferences_manager.h b/internal/platform/implementation/g3/preferences_manager.h index bde0b853..998f68f7 100644 --- a/internal/platform/implementation/g3/preferences_manager.h +++ b/internal/platform/implementation/g3/preferences_manager.h @@ -108,6 +108,8 @@ class PreferencesManager : public api::PreferencesManager { // Removes preferences void Remove(absl::string_view key) override ABSL_LOCKS_EXCLUDED(mutex_); + bool RemoveKeyPrefix(absl::string_view prefix) override + ABSL_LOCKS_EXCLUDED(mutex_); private: // Writes data to storage. diff --git a/internal/platform/implementation/preferences_manager.h b/internal/platform/implementation/preferences_manager.h index 42944eea..059c6771 100644 --- a/internal/platform/implementation/preferences_manager.h +++ b/internal/platform/implementation/preferences_manager.h @@ -85,6 +85,10 @@ class PreferencesManager { // Removes preferences virtual void Remove(absl::string_view key) = 0; + + // Removes all preferences that start with the given prefix. + // Returns false on error. + virtual bool RemoveKeyPrefix(absl::string_view prefix) = 0; }; } // namespace api diff --git a/internal/platform/implementation/windows/preferences_manager.cc b/internal/platform/implementation/windows/preferences_manager.cc index b4b249d7..153185b6 100644 --- a/internal/platform/implementation/windows/preferences_manager.cc +++ b/internal/platform/implementation/windows/preferences_manager.cc @@ -176,6 +176,19 @@ void PreferencesManager::Remove(absl::string_view key) { value_.erase(absl::StrCat(key)); } +bool PreferencesManager::RemoveKeyPrefix(absl::string_view prefix) { + absl::MutexLock lock(mutex_); + auto it = value_.begin(); + while (it != value_.end()) { + if (it.key().starts_with(prefix)) { + it = value_.erase(it); + } else { + ++it; + } + } + return true; +} + // Private methods // Writes data to storage. diff --git a/internal/platform/implementation/windows/preferences_manager.h b/internal/platform/implementation/windows/preferences_manager.h index 363c07cd..c67a795d 100644 --- a/internal/platform/implementation/windows/preferences_manager.h +++ b/internal/platform/implementation/windows/preferences_manager.h @@ -108,6 +108,8 @@ class PreferencesManager : public api::PreferencesManager { // Removes preferences void Remove(absl::string_view key) override ABSL_LOCKS_EXCLUDED(mutex_); + bool RemoveKeyPrefix(absl::string_view prefix) override + ABSL_LOCKS_EXCLUDED(mutex_); private: // Writes data to storage. diff --git a/internal/platform/implementation/windows/preferences_manager_test.cc b/internal/platform/implementation/windows/preferences_manager_test.cc index fc9bb9f4..14d87ef3 100644 --- a/internal/platform/implementation/windows/preferences_manager_test.cc +++ b/internal/platform/implementation/windows/preferences_manager_test.cc @@ -21,7 +21,10 @@ #include #include +#include "gmock/gmock.h" +#include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" @@ -35,6 +38,8 @@ namespace nearby { namespace windows { namespace { +using ::testing::IsEmpty; + using json = ::nlohmann::json; constexpr absl::string_view kPreferencesFilePath = "Google/Nearby/Sharing"; } // namespace @@ -184,5 +189,23 @@ TEST(PreferencesManager, RemoveKey) { EXPECT_EQ(result, "default key"); } +TEST(PreferencesManager, RemoveKeyPrefix) { + constexpr absl::string_view kKeyPrefix = "test_key_prefix."; + auto pm = PreferencesManager(FilePath{kPreferencesFilePath}); + for (int i = 0; i < 10; ++i) { + pm.SetString(absl::StrCat(kKeyPrefix, i), absl::StrCat("value", i)); + } + constexpr absl::string_view string_key = "string_key"; + pm.SetString(string_key, "this is a test string"); + EXPECT_EQ(pm.GetString(string_key, ""), "this is a test string"); + + EXPECT_TRUE(pm.RemoveKeyPrefix(kKeyPrefix)); + for (int i = 0; i < 10; ++i) { + EXPECT_THAT(pm.GetString(absl::StrCat(kKeyPrefix, i), ""), + IsEmpty()); + } + EXPECT_EQ(pm.GetString(string_key, ""), "this is a test string"); +} + } // namespace windows } // namespace nearby From 230a6f23622bf7171e2b0d4e12ec9c30ecf3a500 Mon Sep 17 00:00:00 2001 From: hai007 Date: Wed, 25 Feb 2026 17:45:50 -0800 Subject: [PATCH 25/49] add remote disconnection reason. PiperOrigin-RevId: 875416939 --- proto/connections_enums.proto | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/proto/connections_enums.proto b/proto/connections_enums.proto index 6ab2ebbf..a739b43b 100644 --- a/proto/connections_enums.proto +++ b/proto/connections_enums.proto @@ -1392,6 +1392,36 @@ enum OperationResultCode { DCT_ERROR_LOCAL_ATTESTATION_TIMEOUT = 5032; // Parallel attestation timeout DCT_ERROR_PARALLEL_ATTESTATION_TIMEOUT = 5033; + // Failed to start MDNS discovery on the remote device + DCT_ERROR_REMOTE_MDNS_DISCOVERY_TIMEOUT = 5034; + // Failed to register MDNS service on the remote device + DCT_ERROR_REMOTE_MDNS_REGISTER_SERVICE = 5035; + // Failed to send request on the remote device + DCT_ERROR_REMOTE_REQUEST_FAILED = 5036; + // Failed to receive response on the remote device + DCT_ERROR_REMOTE_RESPONSE_FAILED = 5037; + // Failed to exchange control messages on the remote device + DCT_ERROR_REMOTE_CONTROL_MESSAGE_EXCHANGE = 5038; + // DCT device capability mismatch on the remote device + DCT_ERROR_REMOTE_CAPABILITY_MISMATCH = 5039; + // High speed medium is unavailable on the remote device + DCT_ERROR_REMOTE_HIGH_SPEED_MEDIUM_UNAVAILABLE = 5040; + // Wifi is disabled on the remote device + DCT_ERROR_REMOTE_WIFI_DISABLED = 5041; + // Wifi is disconnected on the remote device + DCT_ERROR_REMOTE_WIFI_DISCONNECTED = 5042; + // Failed to transfer wifi credential on the remote device + DCT_ERROR_REMOTE_WIFI_CREDENTIAL_TRANSFER = 5043; + // Failed to connect to wifi internet on the remote device + DCT_ERROR_REMOTE_WIFI_INTERNET_CONNECTION = 5044; + // Failed to upgrade to high speed medium on the remote device + DCT_ERROR_REMOTE_UPGRADE_HIGH_SPEED_MEDIUM_FAILED = 5045; + // User cancellation on the remote device + DCT_ERROR_REMOTE_USER_CANCELLED = 5046; + // Service cancellation on the remote device + DCT_ERROR_REMOTE_SERVICE_CANCELLED = 5047; + // Failed to verify integrity on the remote device + DCT_ERROR_REMOTE_UNVERIFIED_INTEGRITY = 5048; } enum StopAdvertisingReason { From e5046f6b5584f7f54c6f528b7491bc23721aab66 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 26 Feb 2026 08:57:40 -0800 Subject: [PATCH 26/49] Add support for storing proto messages in preferences. PiperOrigin-RevId: 875747055 --- .../implementation/mediums/webrtc/BUILD | 2 +- internal/platform/implementation/BUILD | 1 + .../apple/preferences_manager.h | 9 ++++++ internal/platform/implementation/g3/BUILD | 2 ++ .../implementation/g3/preferences_manager.cc | 25 +++++++++++++++ .../implementation/g3/preferences_manager.h | 9 ++++++ .../implementation/preferences_manager.h | 7 +++++ .../platform/implementation/windows/BUILD | 18 +++++++++++ .../windows/preferences_manager.cc | 25 +++++++++++++++ .../windows/preferences_manager.h | 9 ++++++ .../windows/preferences_manager_test.cc | 28 +++++++++++++++++ .../windows/preferences_manager_test.proto | 31 +++++++++++++++++++ internal/proto/analytics/BUILD | 2 +- sharing/BUILD | 2 +- 14 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 internal/platform/implementation/windows/preferences_manager_test.proto diff --git a/connections/implementation/mediums/webrtc/BUILD b/connections/implementation/mediums/webrtc/BUILD index 5e52c310..71662a36 100644 --- a/connections/implementation/mediums/webrtc/BUILD +++ b/connections/implementation/mediums/webrtc/BUILD @@ -97,12 +97,12 @@ cc_test( "//internal/platform:test_util", "//internal/platform:types", "//internal/platform/implementation/g3", # buildcleaner: keep - "//third_party/protobuf", "//third_party/webrtc/files/stable/webrtc/api:libjingle_peerconnection_api", "//third_party/webrtc/files/stable/webrtc/api:scoped_refptr", "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/time", "@com_google_googletest//:gtest_main", + "@com_google_protobuf//:protobuf", ], ) diff --git a/internal/platform/implementation/BUILD b/internal/platform/implementation/BUILD index 14778478..90e18df8 100644 --- a/internal/platform/implementation/BUILD +++ b/internal/platform/implementation/BUILD @@ -125,6 +125,7 @@ cc_library( "@com_google_absl//absl/strings", "@com_google_absl//absl/time", "@com_google_absl//absl/types:span", + "@com_google_protobuf//:protobuf", "@nlohmann_json//:json", ], ) diff --git a/internal/platform/implementation/apple/preferences_manager.h b/internal/platform/implementation/apple/preferences_manager.h index 2d2dea30..24065e1f 100644 --- a/internal/platform/implementation/apple/preferences_manager.h +++ b/internal/platform/implementation/apple/preferences_manager.h @@ -88,6 +88,15 @@ class PreferencesManager : public nearby::api::PreferencesManager { absl::Time GetTime(absl::string_view key, absl::Time default_value) const override; + bool SetProtoMessage(absl::string_view key, + const google::protobuf::Message& value) override { + return false; + } + bool GetProtoMessage(absl::string_view key, + google::protobuf::Message* value) const override { + return false; + } + // Removes preferences void Remove(absl::string_view key) override; // TODO: b/485304482 - Implement this method if needed.. diff --git a/internal/platform/implementation/g3/BUILD b/internal/platform/implementation/g3/BUILD index d4e099ff..f2a980a2 100644 --- a/internal/platform/implementation/g3/BUILD +++ b/internal/platform/implementation/g3/BUILD @@ -69,6 +69,8 @@ cc_library( "@com_google_absl//absl/time", "@com_google_absl//absl/types:span", "@com_google_nisaba//nisaba/port:thread_pool", + "@com_google_protobuf//:protobuf", + "@com_google_protobuf//json", "@nlohmann_json//:json", ], alwayslink = 1, diff --git a/internal/platform/implementation/g3/preferences_manager.cc b/internal/platform/implementation/g3/preferences_manager.cc index f02f6124..ab2f7d57 100644 --- a/internal/platform/implementation/g3/preferences_manager.cc +++ b/internal/platform/implementation/g3/preferences_manager.cc @@ -30,6 +30,8 @@ #include "internal/base/file_path.h" #include "internal/platform/implementation/g3/preferences_repository.h" #include "internal/platform/logging.h" +#include "google/protobuf/json/json.h" +#include "google/protobuf/message.h" namespace nearby { namespace g3 { @@ -105,6 +107,18 @@ bool PreferencesManager::SetTime(absl::string_view key, absl::Time value) { return Commit(); } +bool PreferencesManager::SetProtoMessage(absl::string_view key, + const google::protobuf::Message& value) { + std::string json_string; + if (!proto2::json::MessageToJsonString(value, &json_string).ok()) { + return false; + } + { + absl::MutexLock lock(mutex_); + return SetValue(key, json::parse(json_string)); + } +} + // Get JSON value. json PreferencesManager::Get(absl::string_view key, const json& default_value) const { @@ -171,6 +185,17 @@ absl::Time PreferencesManager::GetTime(absl::string_view key, return absl::FromUnixNanos(result->get()); } +bool PreferencesManager::GetProtoMessage(absl::string_view key, + google::protobuf::Message* value) const { + absl::MutexLock lock(mutex_); + auto result = value_.find(absl::StrCat(key)); + if (result == value_.end()) { + return false; + } + return proto2::json::JsonStringToMessage(result->dump(), value) + .ok(); +} + // Removes preferences void PreferencesManager::Remove(absl::string_view key) { absl::MutexLock lock(mutex_); diff --git a/internal/platform/implementation/g3/preferences_manager.h b/internal/platform/implementation/g3/preferences_manager.h index 998f68f7..b7c29770 100644 --- a/internal/platform/implementation/g3/preferences_manager.h +++ b/internal/platform/implementation/g3/preferences_manager.h @@ -31,6 +31,7 @@ #include "internal/base/file_path.h" #include "internal/platform/implementation/g3/preferences_repository.h" #include "internal/platform/implementation/preferences_manager.h" +#include "google/protobuf/message.h" namespace nearby { namespace g3 { @@ -73,6 +74,10 @@ class PreferencesManager : public api::PreferencesManager { bool SetTime(absl::string_view key, absl::Time value) override ABSL_LOCKS_EXCLUDED(mutex_); + bool SetProtoMessage(absl::string_view key, + const google::protobuf::Message& value) override + ABSL_LOCKS_EXCLUDED(mutex_); + // Gets values nlohmann::json Get(absl::string_view key, const nlohmann::json& default_value) const override @@ -106,6 +111,10 @@ class PreferencesManager : public api::PreferencesManager { absl::Time default_value) const override ABSL_LOCKS_EXCLUDED(mutex_); + bool GetProtoMessage(absl::string_view key, + google::protobuf::Message* value) const override + ABSL_LOCKS_EXCLUDED(mutex_); + // Removes preferences void Remove(absl::string_view key) override ABSL_LOCKS_EXCLUDED(mutex_); bool RemoveKeyPrefix(absl::string_view prefix) override diff --git a/internal/platform/implementation/preferences_manager.h b/internal/platform/implementation/preferences_manager.h index 059c6771..69a4b771 100644 --- a/internal/platform/implementation/preferences_manager.h +++ b/internal/platform/implementation/preferences_manager.h @@ -24,6 +24,7 @@ #include "absl/time/time.h" #include "absl/types/span.h" #include "nlohmann/json_fwd.hpp" +#include "google/protobuf/message.h" namespace nearby { namespace api { @@ -59,6 +60,9 @@ class PreferencesManager { virtual bool SetTime(absl::string_view key, absl::Time value) = 0; + virtual bool SetProtoMessage(absl::string_view key, + const google::protobuf::Message& value) = 0; + // Gets values virtual nlohmann::json Get(absl::string_view key, const nlohmann::json& default_value) const = 0; @@ -83,6 +87,9 @@ class PreferencesManager { virtual absl::Time GetTime(absl::string_view key, absl::Time default_value) const = 0; + virtual bool GetProtoMessage(absl::string_view key, + google::protobuf::Message* value) const = 0; + // Removes preferences virtual void Remove(absl::string_view key) = 0; diff --git a/internal/platform/implementation/windows/BUILD b/internal/platform/implementation/windows/BUILD index 2079db10..5bdc2a6e 100644 --- a/internal/platform/implementation/windows/BUILD +++ b/internal/platform/implementation/windows/BUILD @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +load("@com_google_protobuf//bazel:cc_proto_library.bzl", "cc_proto_library") +load("@com_google_protobuf//bazel:proto_library.bzl", "proto_library") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_cc//cc:cc_test.bzl", "cc_test") @@ -418,6 +420,20 @@ cc_library( ], ) +proto_library( + name = "preferences_manager_test_proto", + testonly = True, + srcs = ["preferences_manager_test.proto"], + compatible_with = ["//buildenv/target:non_prod"], +) + +cc_proto_library( + name = "preferences_manager_test_cc_proto", + testonly = True, + compatible_with = ["//buildenv/target:non_prod"], + deps = [":preferences_manager_test_proto"], +) + cc_test( name = "impl_test", size = "small", @@ -451,6 +467,7 @@ cc_test( tags = ["nozapfhahn"], deps = [ ":crypto", + ":preferences_manager_test_cc_proto", ":test_utils", ":types", ":windows", @@ -462,6 +479,7 @@ cc_test( "//internal/platform/implementation:types", "//internal/platform/implementation/shared:count_down_latch", "//internal/platform/implementation/windows/generated:types", + "//net/proto2/contrib/parse_proto:parse_text_proto", "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_absl//absl/status", "@com_google_absl//absl/strings", diff --git a/internal/platform/implementation/windows/preferences_manager.cc b/internal/platform/implementation/windows/preferences_manager.cc index 153185b6..359d08b9 100644 --- a/internal/platform/implementation/windows/preferences_manager.cc +++ b/internal/platform/implementation/windows/preferences_manager.cc @@ -30,6 +30,8 @@ #include "internal/base/file_path.h" #include "internal/platform/implementation/windows/preferences_repository.h" #include "internal/platform/logging.h" +#include "google/protobuf/json/json.h" +#include "google/protobuf/message.h" namespace nearby::windows { namespace { @@ -104,6 +106,18 @@ bool PreferencesManager::SetTime(absl::string_view key, absl::Time value) { return Commit(); } +bool PreferencesManager::SetProtoMessage(absl::string_view key, + const google::protobuf::Message& value) { + std::string json_string; + if (!proto2::json::MessageToJsonString(value, &json_string).ok()) { + return false; + } + { + absl::MutexLock lock(mutex_); + return SetValue(key, json::parse(json_string)); + } +} + // Get JSON value. json PreferencesManager::Get(absl::string_view key, const json& default_value) const { @@ -170,6 +184,17 @@ absl::Time PreferencesManager::GetTime(absl::string_view key, return absl::FromUnixNanos(result->get()); } +bool PreferencesManager::GetProtoMessage(absl::string_view key, + google::protobuf::Message* value) const { + absl::MutexLock lock(mutex_); + auto result = value_.find(absl::StrCat(key)); + if (result == value_.end()) { + return false; + } + return proto2::json::JsonStringToMessage(result->dump(), value) + .ok(); +} + // Removes preferences void PreferencesManager::Remove(absl::string_view key) { absl::MutexLock lock(mutex_); diff --git a/internal/platform/implementation/windows/preferences_manager.h b/internal/platform/implementation/windows/preferences_manager.h index c67a795d..b77b6f45 100644 --- a/internal/platform/implementation/windows/preferences_manager.h +++ b/internal/platform/implementation/windows/preferences_manager.h @@ -31,6 +31,7 @@ #include "internal/base/file_path.h" #include "internal/platform/implementation/preferences_manager.h" #include "internal/platform/implementation/windows/preferences_repository.h" +#include "google/protobuf/message.h" namespace nearby { namespace windows { @@ -73,6 +74,10 @@ class PreferencesManager : public api::PreferencesManager { bool SetTime(absl::string_view key, absl::Time value) override ABSL_LOCKS_EXCLUDED(mutex_); + bool SetProtoMessage(absl::string_view key, + const google::protobuf::Message& value) override + ABSL_LOCKS_EXCLUDED(mutex_); + // Gets values nlohmann::json Get(absl::string_view key, const nlohmann::json& default_value) const override @@ -106,6 +111,10 @@ class PreferencesManager : public api::PreferencesManager { absl::Time default_value) const override ABSL_LOCKS_EXCLUDED(mutex_); + bool GetProtoMessage(absl::string_view key, + google::protobuf::Message* value) const override + ABSL_LOCKS_EXCLUDED(mutex_); + // Removes preferences void Remove(absl::string_view key) override ABSL_LOCKS_EXCLUDED(mutex_); bool RemoveKeyPrefix(absl::string_view prefix) override diff --git a/internal/platform/implementation/windows/preferences_manager_test.cc b/internal/platform/implementation/windows/preferences_manager_test.cc index 14d87ef3..1ae0e126 100644 --- a/internal/platform/implementation/windows/preferences_manager_test.cc +++ b/internal/platform/implementation/windows/preferences_manager_test.cc @@ -21,6 +21,7 @@ #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" @@ -34,10 +35,13 @@ #include "internal/base/file_path.h" #include "internal/base/files.h" #include "internal/platform/logging.h" +#include "internal/platform/implementation/windows/preferences_manager_test.proto.h" namespace nearby { namespace windows { namespace { +using ::proto2::contrib::parse_proto::ParseTextProtoOrDie; +using ::protobuf_matchers::EqualsProto; using ::testing::IsEmpty; using json = ::nlohmann::json; @@ -207,5 +211,29 @@ TEST(PreferencesManager, RemoveKeyPrefix) { EXPECT_EQ(pm.GetString(string_key, ""), "this is a test string"); } +TEST(PreferencesManager, SetAndGetProtoMessage) { + std::string proto_key = "proto_key"; + PreferencesManager pm(FilePath{kPreferencesFilePath}); + windows::tests::SyncConfig sync_config = ParseTextProtoOrDie(R"pb( + folders { + id: "folder_id" + label: "test_folder" + index_id: 1 + max_sequence: 100 + } + folders { + id: "folder_id2" + label: "test_folder2" + index_id: 2 + max_sequence: 200 + } + )pb"); + windows::tests::SyncConfig sync_config_out; + EXPECT_FALSE(pm.GetProtoMessage(proto_key, &sync_config_out)); + pm.SetProtoMessage(proto_key, sync_config); + EXPECT_TRUE(pm.GetProtoMessage(proto_key, &sync_config_out)); + EXPECT_THAT(sync_config_out, EqualsProto(sync_config)); +} + } // namespace windows } // namespace nearby diff --git a/internal/platform/implementation/windows/preferences_manager_test.proto b/internal/platform/implementation/windows/preferences_manager_test.proto new file mode 100644 index 00000000..8c66e13a --- /dev/null +++ b/internal/platform/implementation/windows/preferences_manager_test.proto @@ -0,0 +1,31 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// 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. + +syntax = "proto2"; + +package nearby.windows.tests; + +option java_multiple_files = true; +option java_outer_classname = "PreferencesManagerTest"; + +message SyncConfig { + repeated SyncFolder folders = 1; +} + +message SyncFolder { + optional string id = 1; + optional string label = 2; + optional int32 index_id = 3; + optional int64 max_sequence = 4; +} diff --git a/internal/proto/analytics/BUILD b/internal/proto/analytics/BUILD index 7544541f..352db000 100644 --- a/internal/proto/analytics/BUILD +++ b/internal/proto/analytics/BUILD @@ -53,8 +53,8 @@ cc_test( "//internal/platform:logging", "//internal/platform/implementation/g3", # build_cleaner: keep "//proto:connections_enums_cc_proto", - "//third_party/protobuf", "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_googletest//:gtest_main", + "@com_google_protobuf//:protobuf", ], ) diff --git a/sharing/BUILD b/sharing/BUILD index a3f8f0a1..93a6d6be 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -931,11 +931,11 @@ cc_test( "//sharing/internal/public:logging", "//sharing/proto:wire_format_cc_proto", "//sharing/proto/analytics:sharing_log_cc_proto", - "//third_party/protobuf", "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/time", "@com_google_googletest//:gtest_main", + "@com_google_protobuf//:protobuf", ], ) From 1a543b0d7fbe6f9420a135659a8bd2c45e72b2ad Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Fri, 27 Feb 2026 09:57:38 -0800 Subject: [PATCH 27/49] Remove deprecated string aliases. PiperOrigin-RevId: 876303135 --- sharing/BUILD | 4 +- .../nearby_share_certificate_storage_impl.cc | 10 ++-- ...rby_share_certificate_storage_impl_test.cc | 20 +++---- sharing/common/nearby_share_prefs.cc | 44 +-------------- sharing/common/nearby_share_prefs.h | 27 ---------- sharing/local_device_data/BUILD | 2 +- ...by_share_local_device_data_manager_impl.cc | 8 +-- sharing/nearby_sharing_service_impl_test.cc | 41 +++++++------- sharing/nearby_sharing_settings.cc | 54 +++++++++---------- sharing/nearby_sharing_settings_test.cc | 35 ++++++------ 10 files changed, 83 insertions(+), 162 deletions(-) diff --git a/sharing/BUILD b/sharing/BUILD index 93a6d6be..2d00e45d 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -620,7 +620,6 @@ cc_test( ":transfer_metadata", ":transfer_metadata_matchers", ":types", - "//base:casts", "//internal/analytics:mock_event_logger", "//internal/base:file_path", "//internal/base:files", @@ -640,6 +639,7 @@ cc_test( "//sharing/flags/generated:generated_flags", "//sharing/internal/api:mock_sharing_platform", "//sharing/internal/api:platform", + "//sharing/internal/public:pref_names", "//sharing/internal/test:nearby_test", "//sharing/local_device_data", "//sharing/local_device_data:test_support", @@ -727,6 +727,7 @@ cc_test( "//internal/test", "//sharing/common", "//sharing/common:enum", + "//sharing/internal/public:pref_names", "//sharing/internal/test:nearby_test", "//sharing/local_device_data:test_support", "//sharing/proto:enums_cc_proto", @@ -735,7 +736,6 @@ cc_test( "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/synchronization", "@com_google_absl//absl/time", - "@com_google_absl//absl/types:span", "@com_google_googletest//:gtest_main", ], ) diff --git a/sharing/certificates/nearby_share_certificate_storage_impl.cc b/sharing/certificates/nearby_share_certificate_storage_impl.cc index 9b1132a7..b242e4b4 100644 --- a/sharing/certificates/nearby_share_certificate_storage_impl.cc +++ b/sharing/certificates/nearby_share_certificate_storage_impl.cc @@ -36,11 +36,11 @@ #include "sharing/certificates/constants.h" #include "sharing/certificates/nearby_share_certificate_storage.h" #include "sharing/certificates/nearby_share_private_certificate.h" -#include "sharing/common/nearby_share_prefs.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/private_certificate_data.h" #include "sharing/internal/api/public_certificate_database.h" #include "sharing/internal/public/logging.h" +#include "sharing/internal/public/pref_names.h" #include "sharing/proto/rpc_resources.pb.h" #include "sharing/proto/timestamp.pb.h" @@ -350,7 +350,7 @@ std::vector NearbyShareCertificateStorageImpl::GetPrivateCertificates() { std::vector list = preference_manager_.GetPrivateCertificateArray( - prefs::kNearbySharingPrivateCertificateListName); + PrefNames::kPrivateCertificateList); std::vector certs; certs.reserve(list.size()); for (const PrivateCertificateData& cert_data : list) { @@ -391,7 +391,7 @@ void NearbyShareCertificateStorageImpl::ReplacePrivateCertificates( list.push_back(cert.ToCertificateData()); } preference_manager_.SetPrivateCertificateArray( - prefs::kNearbySharingPrivateCertificateListName, list); + PrefNames::kPrivateCertificateList, list); } void NearbyShareCertificateStorageImpl::AddPublicCertificates( @@ -504,7 +504,7 @@ void NearbyShareCertificateStorageImpl::ClearPublicCertificates( bool NearbyShareCertificateStorageImpl::FetchPublicCertificateExpirations() { std::vector> expirations = preference_manager_.GetCertificateExpirationArray( - prefs::kNearbySharingPublicCertificateExpirationDictName); + PrefNames::kPublicCertificateExpirationDict); public_certificate_expirations_.clear(); if (expirations.empty()) { return false; @@ -535,7 +535,7 @@ void NearbyShareCertificateStorageImpl::SavePublicCertificateExpirations() { } preference_manager_.SetCertificateExpirationArray( - prefs::kNearbySharingPublicCertificateExpirationDictName, expirations); + PrefNames::kPublicCertificateExpirationDict, expirations); } } // namespace nearby::sharing diff --git a/sharing/certificates/nearby_share_certificate_storage_impl_test.cc b/sharing/certificates/nearby_share_certificate_storage_impl_test.cc index edf9b562..3d791b2f 100644 --- a/sharing/certificates/nearby_share_certificate_storage_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_storage_impl_test.cc @@ -38,9 +38,9 @@ #include "sharing/certificates/nearby_share_certificate_storage.h" #include "sharing/certificates/nearby_share_private_certificate.h" #include "sharing/certificates/test_util.h" -#include "sharing/common/nearby_share_prefs.h" #include "sharing/internal/api/mock_public_certificate_db.h" #include "sharing/internal/api/private_certificate_data.h" +#include "sharing/internal/public/pref_names.h" #include "sharing/internal/test/fake_preference_manager.h" #include "sharing/internal/test/fake_public_certificate_db.h" #include "sharing/proto/enums.pb.h" @@ -153,10 +153,8 @@ class NearbyShareCertificateStorageImplTest : public ::testing::Test { NearbyShareCertificateStorageImplTest&) = delete; void SetUp() override { - preference_manager_.Remove( - prefs::kNearbySharingPublicCertificateExpirationDictName); - preference_manager_.Remove( - prefs::kNearbySharingPrivateCertificateListName); + preference_manager_.Remove(PrefNames::kPublicCertificateExpirationDict); + preference_manager_.Remove(PrefNames::kPrivateCertificateList); } std::map PrepopulatePublicCertificates() { @@ -185,8 +183,7 @@ class NearbyShareCertificateStorageImplTest : public ::testing::Test { entries.emplace(cert.secret_id(), std::move(cert)); } preference_manager_.SetCertificateExpirationArray( - prefs::kNearbySharingPublicCertificateExpirationDictName, - expirations); + PrefNames::kPublicCertificateExpirationDict, expirations); return entries; } @@ -835,21 +832,20 @@ TEST_F(NearbyShareCertificateStorageImplTest, std::vector private_cert_data = preference_manager_.GetPrivateCertificateArray( - prefs::kNearbySharingPrivateCertificateListName); + PrefNames::kPrivateCertificateList); ASSERT_EQ(private_cert_data.size(), 3u); // Set to invalid base64 encoded string. private_cert_data[0].key_pair = "::..\\|@#"; preference_manager_.SetPrivateCertificateArray( - prefs::kNearbySharingPrivateCertificateListName, private_cert_data); + PrefNames::kPrivateCertificateList, private_cert_data); std::vector certs = cert_store->GetPrivateCertificates(); // Verify corrupted cert has been removed. EXPECT_TRUE(certs.empty()); - private_cert_data = - preference_manager_.GetPrivateCertificateArray( - prefs::kNearbySharingPrivateCertificateListName); + private_cert_data = preference_manager_.GetPrivateCertificateArray( + PrefNames::kPrivateCertificateList); EXPECT_TRUE(private_cert_data.empty()); } diff --git a/sharing/common/nearby_share_prefs.cc b/sharing/common/nearby_share_prefs.cc index 6c3fc35b..9e9200e5 100644 --- a/sharing/common/nearby_share_prefs.cc +++ b/sharing/common/nearby_share_prefs.cc @@ -16,7 +16,6 @@ #include -#include "absl/base/attributes.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/public/pref_names.h" #include "sharing/proto/enums.pb.h" @@ -27,49 +26,10 @@ namespace prefs { namespace { using ::nearby::sharing::PrefNames; using ::nearby::sharing::api::PreferenceManager; - -using DataUsage = ::nearby::sharing::proto::DataUsage; -using FastInitiationNotificationState = - ::nearby::sharing::proto::FastInitiationNotificationState; +using ::nearby::sharing::proto::DataUsage; +using ::nearby::sharing::proto::FastInitiationNotificationState; } // namespace -ABSL_CONST_INIT const char* kNearbySharingBackgroundVisibilityName = - PrefNames::kVisibility.data(); -ABSL_CONST_INIT const char* kNearbySharingBackgroundFallbackVisibilityName = - PrefNames::kFallbackVisibility.data(); -ABSL_CONST_INIT const char* - kNearbySharingBackgroundVisibilityExpirationSeconds = - PrefNames::kVisibilityExpirationSeconds.data(); -ABSL_CONST_INIT const char* kNearbySharingCustomSavePath = - PrefNames::kCustomSavePath.data(); -ABSL_CONST_INIT const char* kNearbySharingDataUsageName = - PrefNames::kDataUsage.data(); -ABSL_CONST_INIT const char* kNearbySharingDeviceIdName = - PrefNames::kDeviceId.data(); -ABSL_CONST_INIT const char* kNearbySharingDeviceNameName = - PrefNames::kDeviceName.data(); -ABSL_CONST_INIT const char* kNearbySharingFastInitiationNotificationStateName = - PrefNames::kFastInitiationNotificationState.data(); -ABSL_CONST_INIT const char* kNearbySharingPrivateCertificateListName = - PrefNames::kPrivateCertificateList.data(); -ABSL_CONST_INIT const char* kNearbySharingPublicCertificateExpirationDictName = - PrefNames::kPublicCertificateExpirationDict.data(); -ABSL_CONST_INIT const char* - kNearbySharingSchedulerDownloadPublicCertificatesName = - PrefNames::kSchedulerDownloadPublicCertificates.data(); -ABSL_CONST_INIT const char* - kNearbySharingSchedulerPrivateCertificateExpirationName = - PrefNames::kSchedulerPrivateCertificateExpiration.data(); -ABSL_CONST_INIT const char* - kNearbySharingSchedulerPublicCertificateExpirationName = - PrefNames::kSchedulerPublicCertificateExpiration.data(); -ABSL_CONST_INIT const char* - kNearbySharingSchedulerUploadLocalDeviceCertificatesName = - PrefNames::kSchedulerUploadLocalDeviceCertificates.data(); -ABSL_CONST_INIT const char* kNearbySharingUsersName = PrefNames::kUsers.data(); -ABSL_CONST_INIT const char* kNearbySharingIsAnalyticsEnabledName = - PrefNames::kIsAnalyticsEnabled.data(); - void RegisterNearbySharingPrefs(PreferenceManager& preference_manager, bool skip_persistent_ones) { // These prefs are not synced across devices on purpose. diff --git a/sharing/common/nearby_share_prefs.h b/sharing/common/nearby_share_prefs.h index 45830a94..cec24836 100644 --- a/sharing/common/nearby_share_prefs.h +++ b/sharing/common/nearby_share_prefs.h @@ -23,33 +23,6 @@ namespace nearby { namespace sharing { namespace prefs { -// These are for backward compatibility only. New code should use the -// nearby::sharing::api::PrefNames class instead. -ABSL_CONST_INIT extern const char* kNearbySharingBackgroundVisibilityName; -ABSL_CONST_INIT extern const char* - kNearbySharingBackgroundFallbackVisibilityName; -ABSL_CONST_INIT extern const char* - kNearbySharingBackgroundVisibilityExpirationSeconds; -ABSL_CONST_INIT extern const char* kNearbySharingCustomSavePath; -ABSL_CONST_INIT extern const char* kNearbySharingDataUsageName; -ABSL_CONST_INIT extern const char* kNearbySharingDeviceIdName; -ABSL_CONST_INIT extern const char* kNearbySharingDeviceNameName; -ABSL_CONST_INIT extern const char* - kNearbySharingFastInitiationNotificationStateName; -ABSL_CONST_INIT extern const char* kNearbySharingPrivateCertificateListName; -ABSL_CONST_INIT extern const char* - kNearbySharingPublicCertificateExpirationDictName; -ABSL_CONST_INIT extern const char* - kNearbySharingSchedulerDownloadPublicCertificatesName; -ABSL_CONST_INIT extern const char* - kNearbySharingSchedulerPrivateCertificateExpirationName; -ABSL_CONST_INIT extern const char* - kNearbySharingSchedulerPublicCertificateExpirationName; -ABSL_CONST_INIT extern const char* - kNearbySharingSchedulerUploadLocalDeviceCertificatesName; -ABSL_CONST_INIT extern const char* kNearbySharingUsersName; -ABSL_CONST_INIT extern const char* kNearbySharingIsAnalyticsEnabledName; - ABSL_CONST_INIT const proto::DeviceVisibility kDefaultVisibility = proto::DeviceVisibility::DEVICE_VISIBILITY_HIDDEN; ABSL_CONST_INIT const proto::DeviceVisibility kDefaultFallbackVisibility = diff --git a/sharing/local_device_data/BUILD b/sharing/local_device_data/BUILD index 8323219a..030085b3 100644 --- a/sharing/local_device_data/BUILD +++ b/sharing/local_device_data/BUILD @@ -33,11 +33,11 @@ cc_library( "//internal/platform:types", "//internal/platform/implementation:account_manager", "//internal/platform/implementation:types", - "//sharing/common", "//sharing/common:enum", "//sharing/internal/api:platform", "//sharing/internal/base:utf_utils", "//sharing/internal/public:logging", + "//sharing/internal/public:pref_names", "//sharing/proto:share_cc_proto", "@com_google_absl//absl/memory", "@com_google_absl//absl/strings", diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc index aaaedea7..80f2ffbb 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc +++ b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc @@ -28,9 +28,9 @@ #include "internal/platform/implementation/account_manager.h" #include "internal/platform/implementation/device_info.h" #include "sharing/common/nearby_share_enums.h" -#include "sharing/common/nearby_share_prefs.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/base/utf_string_conversions.h" +#include "sharing/internal/public/pref_names.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/device_rpc.pb.h" #include "sharing/proto/field_mask.pb.h" @@ -100,8 +100,8 @@ NearbyShareLocalDeviceDataManagerImpl:: ~NearbyShareLocalDeviceDataManagerImpl() = default; std::string NearbyShareLocalDeviceDataManagerImpl::GetDeviceName() const { - std::string device_name = preference_manager_.GetString( - prefs::kNearbySharingDeviceNameName, std::string()); + std::string device_name = + preference_manager_.GetString(PrefNames::kDeviceName, std::string()); return device_name.empty() ? GetDefaultDeviceName() : device_name; } @@ -126,7 +126,7 @@ DeviceNameValidationResult NearbyShareLocalDeviceDataManagerImpl::SetDeviceName( auto error = ValidateDeviceName(name); if (error != DeviceNameValidationResult::kValid) return error; - preference_manager_.SetString(prefs::kNearbySharingDeviceNameName, name); + preference_manager_.SetString(PrefNames::kDeviceName, name); NotifyLocalDeviceDataChanged(/*did_device_name_change=*/true, /*did_full_name_change=*/false, diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index 8cd68d1a..dc111ebb 100644 --- a/sharing/nearby_sharing_service_impl_test.cc +++ b/sharing/nearby_sharing_service_impl_test.cc @@ -73,6 +73,7 @@ #include "sharing/internal/api/mock_app_info.h" #include "sharing/internal/api/mock_sharing_platform.h" #include "sharing/internal/api/preference_manager.h" +#include "sharing/internal/public/pref_names.h" #include "sharing/internal/test/fake_bluetooth_adapter.h" #include "sharing/internal/test/fake_connectivity_manager.h" #include "sharing/internal/test/fake_context.h" @@ -1820,8 +1821,7 @@ TEST_F(NearbySharingServiceImplTest, SetLanConnected(true); SetVisibility(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS); preference_manager().SetInteger( - prefs::kNearbySharingDataUsageName, - static_cast(DataUsage::OFFLINE_DATA_USAGE)); + PrefNames::kDataUsage, static_cast(DataUsage::OFFLINE_DATA_USAGE)); FlushTesting(); MockTransferUpdateCallback callback; NearbySharingService::StatusCodes result = RegisterReceiveSurface( @@ -1833,8 +1833,7 @@ TEST_F(NearbySharingServiceImplTest, fake_nearby_connections_manager_->advertising_data_usage()); preference_manager().SetInteger( - prefs::kNearbySharingDataUsageName, - static_cast(DataUsage::ONLINE_DATA_USAGE)); + PrefNames::kDataUsage, static_cast(DataUsage::ONLINE_DATA_USAGE)); FlushTesting(); EXPECT_TRUE(fake_nearby_connections_manager_->IsAdvertising()); EXPECT_EQ(DataUsage::ONLINE_DATA_USAGE, @@ -1847,7 +1846,7 @@ TEST_F( TestObserver observer(service_.get()); SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS)); FlushTesting(); @@ -1893,7 +1892,7 @@ TEST_F(NearbySharingServiceImplTest, RegisterReceiveSurfaceWithVendorId_StartAdvertisingVendorId) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_EVERYONE)); FlushTesting(); @@ -1918,7 +1917,7 @@ TEST_F(NearbySharingServiceImplTest, RegisterReceiveSurfaceWithVendorId_DoesNotAdvertiseInContacts) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS)); FlushTesting(); @@ -1943,7 +1942,7 @@ TEST_F(NearbySharingServiceImplTest, RegisterReceiveSurfaceWithDifferentVendorIdIsBlocked) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS)); FlushTesting(); @@ -1969,7 +1968,7 @@ TEST_F(NearbySharingServiceImplTest, RegisterReceiveSurfaceWithVendorId_OkWithBgNoVendorId) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_EVERYONE)); FlushTesting(); @@ -2077,7 +2076,7 @@ TEST_F(NearbySharingServiceImplTest, ForegroundReceiveSurfaceNoOneVisibilityIsAdvertising) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE)); FlushTesting(); MockTransferUpdateCallback callback; @@ -2093,7 +2092,7 @@ TEST_F(NearbySharingServiceImplTest, SetLanConnected(true); SetVisibility(DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_UNSPECIFIED)); FlushTesting(); MockTransferUpdateCallback callback; @@ -2118,7 +2117,7 @@ TEST_F(NearbySharingServiceImplTest, EXPECT_TRUE(fake_nearby_connections_manager_->IsAdvertising()); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_HIDDEN)); FlushTesting(); EXPECT_FALSE(fake_nearby_connections_manager_->IsAdvertising()); @@ -2189,7 +2188,7 @@ TEST_F(NearbySharingServiceImplTest, ForegroundReceiveSurfaceSelectedContactsVisibilityIsAdvertising) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_SELECTED_CONTACTS)); FlushTesting(); MockTransferUpdateCallback callback; @@ -2204,7 +2203,7 @@ TEST_F(NearbySharingServiceImplTest, BackgroundReceiveSurfaceSelectedContactsVisibilityIsAdvertising) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_SELECTED_CONTACTS)); FlushTesting(); MockTransferUpdateCallback callback; @@ -2219,7 +2218,7 @@ TEST_F(NearbySharingServiceImplTest, ForegroundReceiveSurfaceAllContactsVisibilityIsAdvertising) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS)); FlushTesting(); MockTransferUpdateCallback callback; @@ -2234,7 +2233,7 @@ TEST_F(NearbySharingServiceImplTest, BackgroundReceiveSurfaceAllContactsVisibilityNotAdvertising) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS)); FlushTesting(); MockTransferUpdateCallback callback; @@ -2499,7 +2498,7 @@ TEST_F(NearbySharingServiceImplTest, TEST_F(NearbySharingServiceImplTest, IncomingConnectionOutOfStorage) { SetDiskSpace(kFreeDiskSpace); preference_manager().SetString( - prefs::kNearbySharingCustomSavePath, + PrefNames::kCustomSavePath, fake_device_info_.GetDownloadPath().ToString()); fake_nearby_connections_manager_->SetRawAuthenticationToken(kEndpointId, GetToken()); @@ -4453,7 +4452,7 @@ TEST_F(NearbySharingServiceImplTest, RegisterSendSurfaceWithDifferentVendorIdIsBlocked) { SetLanConnected(true); preference_manager().SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS)); FlushTesting(); @@ -4641,7 +4640,7 @@ TEST_F(NearbySharingServiceImplTest, LoginAndLogoutShouldResetSettings) { service_->GetSettings()->SetIsAnalyticsEnabled(true); std::string device_id = - preference_manager_.GetString(prefs::kNearbySharingDeviceIdName, ""); + preference_manager_.GetString(PrefNames::kDeviceId, ""); EXPECT_TRUE(device_id.empty()); // Create account. @@ -4660,7 +4659,7 @@ TEST_F(NearbySharingServiceImplTest, LoginAndLogoutShouldResetSettings) { EXPECT_EQ(service_->GetAccountManager()->GetCurrentAccount()->id, kTestAccountId); device_id = - preference_manager_.GetString(prefs::kNearbySharingDeviceIdName, ""); + preference_manager_.GetString(PrefNames::kDeviceId, ""); EXPECT_FALSE(device_id.empty()); EXPECT_EQ(device_id.size(), 10u); for (const char c : device_id) EXPECT_TRUE(std::isalnum(c)); @@ -4678,7 +4677,7 @@ TEST_F(NearbySharingServiceImplTest, LoginAndLogoutShouldResetSettings) { EXPECT_FALSE(service_->GetAccountManager()->GetCurrentAccount().has_value()); EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout)); device_id = - preference_manager_.GetString(prefs::kNearbySharingDeviceIdName, ""); + preference_manager_.GetString(PrefNames::kDeviceId, ""); EXPECT_TRUE(device_id.empty()); } diff --git a/sharing/nearby_sharing_settings.cc b/sharing/nearby_sharing_settings.cc index 78d983dc..9a189aed 100644 --- a/sharing/nearby_sharing_settings.cc +++ b/sharing/nearby_sharing_settings.cc @@ -34,6 +34,7 @@ #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/public/context.h" #include "sharing/internal/public/logging.h" +#include "sharing/internal/public/pref_names.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/enums.pb.h" #include "sharing/thread_timer.h" @@ -107,7 +108,7 @@ FastInitiationNotificationState NearbyShareSettings::GetFastInitiationNotificationState() const { return static_cast( preference_manager_.GetInteger( - prefs::kNearbySharingFastInitiationNotificationStateName, + PrefNames::kFastInitiationNotificationState, static_cast( FastInitiationNotificationState::ENABLED_FAST_INIT))); } @@ -133,7 +134,7 @@ std::string NearbyShareSettings::GetDeviceName() const { DataUsage NearbyShareSettings::GetDataUsage() const { return static_cast( - preference_manager_.GetInteger(prefs::kNearbySharingDataUsageName, 0)); + preference_manager_.GetInteger(PrefNames::kDataUsage, 0)); } void NearbyShareSettings::StartVisibilityTimer( @@ -156,9 +157,9 @@ void NearbyShareSettings::StartVisibilityTimer( void NearbyShareSettings::RestoreFallbackVisibility() { int64_t expiration_seconds = preference_manager_.GetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, 0); + PrefNames::kVisibilityExpirationSeconds, 0); int64_t fallback_visibility = preference_manager_.GetInteger( - prefs::kNearbySharingBackgroundFallbackVisibilityName, + PrefNames::kFallbackVisibility, static_cast(prefs::kDefaultFallbackVisibility)); fallback_visibility_ = static_cast(fallback_visibility); @@ -182,8 +183,7 @@ void NearbyShareSettings::RestoreFallbackVisibility() { std::string NearbyShareSettings::GetCustomSavePath() const { return preference_manager_.GetString( - prefs::kNearbySharingCustomSavePath, - device_info_.GetDownloadPath().ToString()); + PrefNames::kCustomSavePath, device_info_.GetDownloadPath().ToString()); } bool NearbyShareSettings::IsDisabledByPolicy() const { return false; } @@ -204,9 +204,8 @@ void NearbyShareSettings::SetFastInitiationNotificationState( GetNotificationStatus(state)); } - preference_manager_.SetInteger( - prefs::kNearbySharingFastInitiationNotificationStateName, - static_cast(state)); + preference_manager_.SetInteger(PrefNames::kFastInitiationNotificationState, + static_cast(state)); } void NearbyShareSettings::SetDeviceName( @@ -222,15 +221,14 @@ void NearbyShareSettings::SetDataUsage(DataUsage data_usage) { if (analytics_recorder_ != nullptr) { analytics_recorder_->NewSetDataUsage(GetDataUsage(), data_usage); } - preference_manager_.SetInteger(prefs::kNearbySharingDataUsageName, + preference_manager_.SetInteger(PrefNames::kDataUsage, static_cast(data_usage)); } DeviceVisibility NearbyShareSettings::GetVisibility() const { DeviceVisibility visibility = static_cast(preference_manager_.GetInteger( - prefs::kNearbySharingBackgroundVisibilityName, - static_cast(prefs::kDefaultVisibility))); + PrefNames::kVisibility, static_cast(prefs::kDefaultVisibility))); if (visibility == DeviceVisibility::DEVICE_VISIBILITY_SELECTED_CONTACTS) { // Set the visibility to self share if it's only visible to selected // contacts, as part of QuickShare rebrand work. @@ -272,17 +270,16 @@ void NearbyShareSettings::SetVisibility(DeviceVisibility visibility, VLOG(1) << __func__ << ": temporary visibility timer starts."; absl::Time fallback_visibility_timestamp = now + expiration; preference_manager_.SetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, + PrefNames::kVisibilityExpirationSeconds, absl::ToUnixSeconds(fallback_visibility_timestamp)); StartVisibilityTimer(expiration); } else { - preference_manager_.SetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, 0); + preference_manager_.SetInteger(PrefNames::kVisibilityExpirationSeconds, 0); } last_visibility_timestamp_ = now; last_visibility_ = last_visibility; - preference_manager_.SetInteger(prefs::kNearbySharingBackgroundVisibilityName, + preference_manager_.SetInteger(PrefNames::kVisibility, static_cast(visibility)); } @@ -301,7 +298,7 @@ NearbyShareSettings::GetRawFallbackVisibility() const { return { .visibility = fallback_visibility_, .fallback_time = absl::FromUnixSeconds(preference_manager_.GetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, 0)) + PrefNames::kVisibilityExpirationSeconds, 0)) }; } @@ -332,29 +329,28 @@ void NearbyShareSettings::SetFallbackVisibility(DeviceVisibility visibility) { } fallback_visibility_ = visibility; - preference_manager_.SetInteger( - prefs::kNearbySharingBackgroundFallbackVisibilityName, - static_cast(visibility)); + preference_manager_.SetInteger(PrefNames::kFallbackVisibility, + static_cast(visibility)); } void NearbyShareSettings::SetCustomSavePathAsync( absl::string_view save_path, const std::function& callback) { absl::MutexLock lock(mutex_); - preference_manager_.SetString(prefs::kNearbySharingCustomSavePath, save_path); + preference_manager_.SetString(PrefNames::kCustomSavePath, save_path); callback(); } void NearbyShareSettings::OnPreferenceChanged(absl::string_view key) { - if (key == prefs::kNearbySharingFastInitiationNotificationStateName) { + if (key == PrefNames::kFastInitiationNotificationState) { NotifyAllObservers(key, Observer::Data(static_cast( GetFastInitiationNotificationState()))); - } else if (key == prefs::kNearbySharingBackgroundVisibilityName) { + } else if (key == PrefNames::kVisibility) { NotifyAllObservers(key, Observer::Data(static_cast(GetVisibility()))); - } else if (key == prefs::kNearbySharingDataUsageName) { + } else if (key == PrefNames::kDataUsage) { NotifyAllObservers(key, Observer::Data(static_cast(GetDataUsage()))); - } else if (key == prefs::kNearbySharingCustomSavePath) { + } else if (key == PrefNames::kCustomSavePath) { NotifyAllObservers(key, Observer::Data(GetCustomSavePath())); } else { // Not a monitored key. @@ -368,8 +364,7 @@ void NearbyShareSettings::OnLocalDeviceDataChanged(bool did_device_name_change, if (!did_device_name_change) return; std::string device_name = GetDeviceName(); - NotifyAllObservers(prefs::kNearbySharingDeviceNameName, - Observer::Data(device_name)); + NotifyAllObservers(PrefNames::kDeviceName, Observer::Data(device_name)); } void NearbyShareSettings::NotifyAllObservers(absl::string_view key, @@ -380,12 +375,11 @@ void NearbyShareSettings::NotifyAllObservers(absl::string_view key, } bool NearbyShareSettings::GetIsAnalyticsEnabled() const { - return preference_manager_.GetBoolean( - prefs::kNearbySharingIsAnalyticsEnabledName, true); + return preference_manager_.GetBoolean(PrefNames::kIsAnalyticsEnabled, true); } void NearbyShareSettings::SetIsAnalyticsEnabled(bool is_analytics_enabled) { - preference_manager_.SetBoolean(prefs::kNearbySharingIsAnalyticsEnabledName, + preference_manager_.SetBoolean(PrefNames::kIsAnalyticsEnabled, is_analytics_enabled); } diff --git a/sharing/nearby_sharing_settings_test.cc b/sharing/nearby_sharing_settings_test.cc index ddd8eef2..531e4ed7 100644 --- a/sharing/nearby_sharing_settings_test.cc +++ b/sharing/nearby_sharing_settings_test.cc @@ -31,6 +31,7 @@ #include "internal/test/fake_task_runner.h" #include "sharing/common/nearby_share_enums.h" #include "sharing/common/nearby_share_prefs.h" +#include "sharing/internal/public/pref_names.h" #include "sharing/internal/test/fake_context.h" #include "sharing/internal/test/fake_preference_manager.h" #include "sharing/local_device_data/fake_nearby_share_local_device_data_manager.h" @@ -49,16 +50,16 @@ class FakeNearbyShareSettingsObserver : public NearbyShareSettings::Observer { public: void OnSettingChanged(absl::string_view key, const Data& data) override { absl::MutexLock lock(mutex_); - if (key == prefs::kNearbySharingFastInitiationNotificationStateName) { + if (key == PrefNames::kFastInitiationNotificationState) { fast_initiation_notification_state_ = static_cast(data.value.as_int64); - } else if (key == prefs::kNearbySharingDataUsageName) { + } else if (key == PrefNames::kDataUsage) { data_usage_ = static_cast(data.value.as_int64); - } else if (key == prefs::kNearbySharingCustomSavePath) { + } else if (key == PrefNames::kCustomSavePath) { custom_save_path_ = data.value.as_string; - } else if (key == prefs::kNearbySharingBackgroundVisibilityName) { + } else if (key == PrefNames::kVisibility) { visibility_ = static_cast(data.value.as_int64); - } else if (key == prefs::kNearbySharingDeviceNameName) { + } else if (key == PrefNames::kDeviceName) { device_name_ = data.value.as_string; } } @@ -132,13 +133,12 @@ class NearbyShareSettingsTest : public ::testing::Test { NearbyShareSettings* settings() { return nearby_share_settings_.get(); } void SetVisibilityExpirationPreference(int expiration) { - preference_manager_.SetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, expiration); + preference_manager_.SetInteger(PrefNames::kVisibilityExpirationSeconds, + expiration); } void SetCustomSavePath(absl::string_view path) { - preference_manager_.SetString( - prefs::kNearbySharingCustomSavePath, path); + preference_manager_.SetString(PrefNames::kCustomSavePath, path); } // Waits for running tasks to complete. @@ -332,9 +332,8 @@ TEST_F(NearbyShareSettingsTest, settings()->SetVisibility(DeviceVisibility::DEVICE_VISIBILITY_EVERYONE); // Verify that the saved fallback visibility is intact, since we can go back // to temporary. - EXPECT_EQ(preference_manager_.GetInteger( - prefs::kNearbySharingBackgroundFallbackVisibilityName, - prefs::kDefaultFallbackVisibility), + EXPECT_EQ(preference_manager_.GetInteger(PrefNames::kFallbackVisibility, + prefs::kDefaultFallbackVisibility), static_cast(DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE)); // Verify that the fallback visibility is unspecified. NearbyShareSettings::FallbackVisibilityInfo fallback_visibility = @@ -396,15 +395,15 @@ TEST(NearbyShareVisibilityTest, RestoresFallbackVisibility_ExpiredTimer) { kDefaultDeviceName); // Set everyone mode temporarily. preference_manager.SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_EVERYONE)); // Set expiration to 10 seconds ago. preference_manager.SetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, + PrefNames::kVisibilityExpirationSeconds, absl::ToUnixSeconds(context.GetClock()->Now() - absl::Seconds(10))); // Set fallback visibility to self share. preference_manager.SetInteger( - prefs::kNearbySharingBackgroundFallbackVisibilityName, + PrefNames::kFallbackVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE)); // Create a Nearby Share settings instance. NearbyShareSettings settings(&context, context.GetClock(), fake_device_info, @@ -424,15 +423,15 @@ TEST(NearbyShareVisibilityTest, RestoresFallbackVisibility_FutureTimer) { kDefaultDeviceName); // Set everyone mode temporarily. preference_manager.SetInteger( - prefs::kNearbySharingBackgroundVisibilityName, + PrefNames::kVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_EVERYONE)); // Set expiration to 10 seconds in the future. preference_manager.SetInteger( - prefs::kNearbySharingBackgroundVisibilityExpirationSeconds, + PrefNames::kVisibilityExpirationSeconds, absl::ToUnixSeconds(context.GetClock()->Now() + absl::Seconds(10))); // Set fallback visibility to self share. preference_manager.SetInteger( - prefs::kNearbySharingBackgroundFallbackVisibilityName, + PrefNames::kFallbackVisibility, static_cast(DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE)); // Create a Nearby Share settings instance. NearbyShareSettings settings(&context, context.GetClock(), fake_device_info, From f81ee02981919ca23de82cc92a4b4db96106aa08 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Fri, 27 Feb 2026 10:59:42 -0800 Subject: [PATCH 28/49] Add SyncConfig and BindingConfigs to preferences. PiperOrigin-RevId: 876332995 --- sharing/common/nearby_share_prefs.cc | 3 ++ sharing/internal/api/BUILD | 2 +- sharing/internal/api/preference_manager.h | 15 +++++++ sharing/internal/public/pref_names.h | 14 +++++++ sharing/internal/test/BUILD | 3 +- .../internal/test/fake_preference_manager.cc | 42 ++++++++++++++++++- .../internal/test/fake_preference_manager.h | 8 ++++ 7 files changed, 82 insertions(+), 5 deletions(-) diff --git a/sharing/common/nearby_share_prefs.cc b/sharing/common/nearby_share_prefs.cc index 9e9200e5..279b352b 100644 --- a/sharing/common/nearby_share_prefs.cc +++ b/sharing/common/nearby_share_prefs.cc @@ -66,6 +66,9 @@ void RegisterNearbySharingPrefs(PreferenceManager& preference_manager, preference_manager.Remove(PrefNames::kSchedulerUploadLocalDeviceCertificates); preference_manager.Remove(PrefNames::kUsers); preference_manager.SetBoolean(PrefNames::kAdvancedProtectionEnabled, false); + + preference_manager.RemoveAllSyncConfigs(); + preference_manager.RemoveAllBindingConfigs(); } void ResetSchedulers(PreferenceManager& preference_manager) { diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index 502e9934..e940ba7d 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -45,8 +45,8 @@ cc_library( "//internal/platform/implementation:account_manager", "//sharing/analytics", "//sharing/proto:share_cc_proto", + "//sharing/proto:wire_format_cc_proto", "@com_google_absl//absl/functional:any_invocable", - "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/time", diff --git a/sharing/internal/api/preference_manager.h b/sharing/internal/api/preference_manager.h index c15d57bb..83a9faa9 100644 --- a/sharing/internal/api/preference_manager.h +++ b/sharing/internal/api/preference_manager.h @@ -26,6 +26,7 @@ #include "absl/time/time.h" #include "absl/types/span.h" #include "sharing/internal/api/private_certificate_data.h" +#include "sharing/proto/wire_format.pb.h" namespace nearby::sharing::api { @@ -78,6 +79,11 @@ class PreferenceManager { std::string value) = 0; virtual void RemoveDictionaryItem(absl::string_view key, absl::string_view dictionary_item) = 0; + + virtual void SetSyncConfigValue( + absl::string_view binding_id, + const nearby::sharing::service::proto::SyncConfig& value) = 0; + // Gets values virtual bool GetBoolean(absl::string_view key, bool default_value) const = 0; virtual int GetInteger(absl::string_view key, int default_value) const = 0; @@ -117,8 +123,17 @@ class PreferenceManager { virtual std::optional GetDictionaryStringValue( absl::string_view key, absl::string_view dictionary_item) const = 0; + virtual std::optional + GetSyncConfigValue(absl::string_view binding_id) const = 0; + // Removes preferences virtual void Remove(absl::string_view key) = 0; + // Removes all sync configs. + // Observers are not notified for each removed config. + virtual void RemoveAllSyncConfigs() = 0; + // Removes all binding configs. + // Observers are not notified for each removed config. + virtual void RemoveAllBindingConfigs() = 0; // Adds preference observer virtual void AddObserver( diff --git a/sharing/internal/public/pref_names.h b/sharing/internal/public/pref_names.h index 0114690b..83ced43c 100644 --- a/sharing/internal/public/pref_names.h +++ b/sharing/internal/public/pref_names.h @@ -54,6 +54,20 @@ class PrefNames { "nearby_sharing.advanced_protection_enabled"; static constexpr absl::string_view kSchedulerGetAccountInfo = "nearby_sharing.scheduler.get_account_info"; + + // Binding configs preferences are stored in pref keys: + // kBindingConfigPrefix + + // Example: "nearby_sharing.binding_config.FileSync" + // TODO: b/485304482 - define data format for binding configs. + static constexpr absl::string_view kBindingConfigPrefix = + "nearby_sharing.binding_config."; + + // Sync configs preferences are stored in pref keys: + // kSyncConfigPrefix + + // Example: "nearby_sharing.sync_config.01243347-2343-4324-3423-432432432432" + // Data stored in sync config prefs is a SyncConfig proto. + static constexpr absl::string_view kSyncConfigPrefix = + "nearby_sharing.sync_config."; }; } // namespace nearby::sharing diff --git a/sharing/internal/test/BUILD b/sharing/internal/test/BUILD index cbee4bf8..b377f056 100644 --- a/sharing/internal/test/BUILD +++ b/sharing/internal/test/BUILD @@ -37,17 +37,16 @@ cc_library( visibility = ["//visibility:public"], deps = [ "//internal/base", - "//internal/base:bluetooth_address", "//internal/platform:mac_address", "//internal/platform:types", "//internal/test", "//sharing/internal/api:platform", + "//sharing/internal/public:pref_names", "//sharing/internal/public:types", "//sharing/proto:share_cc_proto", "@com_google_absl//absl/base:core_headers", "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/functional:any_invocable", - "@com_google_absl//absl/status", "@com_google_absl//absl/strings", "@com_google_absl//absl/synchronization", "@com_google_absl//absl/time", diff --git a/sharing/internal/test/fake_preference_manager.cc b/sharing/internal/test/fake_preference_manager.cc index b605ca56..cc1f637d 100644 --- a/sharing/internal/test/fake_preference_manager.cc +++ b/sharing/internal/test/fake_preference_manager.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "sharing/internal/test/fake_preference_manager.h" + #include #include #include @@ -22,13 +23,16 @@ #include #include "absl/container/flat_hash_map.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "sharing/internal/api/private_certificate_data.h" +#include "sharing/internal/public/pref_names.h" namespace nearby { +using ::nearby::sharing::PrefNames; using ::nearby::sharing::api::PrivateCertificateData; template @@ -180,8 +184,7 @@ void FakePreferenceManager::SetStringArray( } void FakePreferenceManager::SetPrivateCertificateArray( - absl::string_view key, - absl::Span value) { + absl::string_view key, absl::Span value) { absl::MutexLock lock(mutex_); if (certs_.contains(key)) { certs_.erase(key); @@ -235,6 +238,12 @@ void FakePreferenceManager::RemoveDictionaryItem( NotifyPreferenceChanged(key); } +void FakePreferenceManager::SetSyncConfigValue( + absl::string_view binding_id, + const nearby::sharing::service::proto::SyncConfig& value) { + SetValue(absl::StrCat(PrefNames::kSyncConfigPrefix, binding_id), + value.SerializeAsString()); +} bool FakePreferenceManager::GetBoolean(absl::string_view key, bool default_value) const { @@ -320,6 +329,21 @@ std::optional FakePreferenceManager::GetDictionaryStringValue( return GetDictionaryValue(key, dictionary_item); } +std::optional +FakePreferenceManager::GetSyncConfigValue(absl::string_view binding_id) const { + std::string serialized_sync_config; + serialized_sync_config = + GetString(absl::StrCat(PrefNames::kSyncConfigPrefix, binding_id), ""); + if (serialized_sync_config.empty()) { + return std::nullopt; + } + nearby::sharing::service::proto::SyncConfig sync_config; + if (!sync_config.ParseFromString(serialized_sync_config)) { + return std::nullopt; + } + return sync_config; +} + void FakePreferenceManager::Remove(absl::string_view key) { { absl::MutexLock lock(mutex_); @@ -330,6 +354,20 @@ void FakePreferenceManager::Remove(absl::string_view key) { NotifyPreferenceChanged(key); } +void FakePreferenceManager::RemoveAllSyncConfigs() { + absl::MutexLock lock(mutex_); + absl::erase_if(values_, [](const auto& item) { + return item.first.starts_with(PrefNames::kSyncConfigPrefix); + }); +} + +void FakePreferenceManager::RemoveAllBindingConfigs() { + absl::MutexLock lock(mutex_); + absl::erase_if(values_, [](const auto& item) { + return item.first.starts_with(PrefNames::kBindingConfigPrefix); + }); +} + void FakePreferenceManager::NotifyPreferenceChanged(absl::string_view key) { absl::flat_hash_map> observers; diff --git a/sharing/internal/test/fake_preference_manager.h b/sharing/internal/test/fake_preference_manager.h index c1a3fc0f..acff903d 100644 --- a/sharing/internal/test/fake_preference_manager.h +++ b/sharing/internal/test/fake_preference_manager.h @@ -74,6 +74,10 @@ class FakePreferenceManager : public nearby::sharing::api::PreferenceManager { void RemoveDictionaryItem(absl::string_view key, absl::string_view dictionary_item) override; + void SetSyncConfigValue( + absl::string_view binding_id, + const nearby::sharing::service::proto::SyncConfig& value) override; + bool GetBoolean(absl::string_view key, bool default_value) const override; int GetInteger(absl::string_view key, int default_value) const override; int64_t GetInt64(absl::string_view key, int64_t default_value) const override; @@ -107,8 +111,12 @@ class FakePreferenceManager : public nearby::sharing::api::PreferenceManager { absl::string_view key, absl::string_view dictionary_item) const override; std::optional GetDictionaryStringValue( absl::string_view key, absl::string_view dictionary_item) const override; + std::optional + GetSyncConfigValue(absl::string_view binding_id) const override; void Remove(absl::string_view key) override; + void RemoveAllSyncConfigs() override; + void RemoveAllBindingConfigs() override; void AddObserver( absl::string_view name, From 92f17e2daa744fe4caaae5918268d3b9f1dabebf Mon Sep 17 00:00:00 2001 From: Nick Bourdakos Date: Fri, 27 Feb 2026 15:19:51 -0800 Subject: [PATCH 29/49] Update Abseil-cpp SwiftPM dependency. PiperOrigin-RevId: 876437516 --- Package.resolved | 6 +++--- Package.swift | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Package.resolved b/Package.resolved index a79429cf..f4a64c64 100644 --- a/Package.resolved +++ b/Package.resolved @@ -3,10 +3,10 @@ { "identity" : "abseil-cpp-swiftpm", "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/abseil-cpp-SwiftPM.git", + "location" : "https://github.com/bourdakos1/abseil-cpp-SwiftPM.git", "state" : { - "branch" : "main", - "revision" : "1c50c2cd0bffe5a03cde6fe17129334dcf05071b" + "branch" : "jan-lts", + "revision" : "ecabd65f38702137240fd2599f710b0f5cd89cf1" } }, { diff --git a/Package.swift b/Package.swift index a70e97ee..6d3d5326 100644 --- a/Package.swift +++ b/Package.swift @@ -40,8 +40,8 @@ let package = Package( dependencies: [ // Dependencies declare other packages that this package depends on. .package( - url: "https://github.com/firebase/abseil-cpp-SwiftPM.git", - branch: "main" + url: "https://github.com/bourdakos1/abseil-cpp-SwiftPM.git", + branch: "jan-lts" ), .package( url: "https://github.com/firebase/boringssl-SwiftPM.git", From 079b5b94e90fbd1a0a0f16ae1be8b34eee07de8c Mon Sep 17 00:00:00 2001 From: hai007 Date: Sat, 28 Feb 2026 19:26:07 -0800 Subject: [PATCH 30/49] Automated Code Change PiperOrigin-RevId: 876835227 --- internal/platform/implementation/shared/count_down_latch.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/platform/implementation/shared/count_down_latch.cc b/internal/platform/implementation/shared/count_down_latch.cc index f951196b..636bab93 100644 --- a/internal/platform/implementation/shared/count_down_latch.cc +++ b/internal/platform/implementation/shared/count_down_latch.cc @@ -24,7 +24,7 @@ namespace shared { CountDownLatch::CountDownLatch(int count) : count_(count) {} ExceptionOr CountDownLatch::Await(absl::Duration timeout) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); absl::Time deadline = absl::Now() + timeout; while (count_ > 0) { if (cond_.WaitWithDeadline(&mutex_, deadline)) { @@ -35,14 +35,14 @@ ExceptionOr CountDownLatch::Await(absl::Duration timeout) { } Exception CountDownLatch::Await() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); while (count_ > 0) { cond_.Wait(&mutex_); } return {Exception::kSuccess}; } void CountDownLatch::CountDown() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (count_ > 0 && --count_ == 0) { cond_.SignalAll(); } From 622b4eca8bf674e71654649d96b3a0c6e97df285 Mon Sep 17 00:00:00 2001 From: hai007 Date: Sat, 28 Feb 2026 20:21:29 -0800 Subject: [PATCH 31/49] Automated Code Change PiperOrigin-RevId: 876848243 --- internal/platform/cancellation_flag.cc | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/platform/cancellation_flag.cc b/internal/platform/cancellation_flag.cc index 2836efa6..90b079bb 100644 --- a/internal/platform/cancellation_flag.cc +++ b/internal/platform/cancellation_flag.cc @@ -28,7 +28,7 @@ CancellationFlag::CancellationFlag(bool cancelled) { } CancellationFlag::~CancellationFlag() { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_.get()); listeners_.clear(); } @@ -40,7 +40,7 @@ void CancellationFlag::Cancel() { absl::flat_hash_set listeners; { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_.get()); if (cancelled_) { // Someone already cancelled. Return immediately. return; @@ -62,14 +62,14 @@ void CancellationFlag::Uncancel() { } { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_.get()); assert(cancelled_); cancelled_ = false; } } bool CancellationFlag::Cancelled() const { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_.get()); // Return false as no-op if feature flag is not enabled. if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) { @@ -80,13 +80,13 @@ bool CancellationFlag::Cancelled() const { } void CancellationFlag::RegisterOnCancelListener(CancelListener *listener) { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_.get()); listeners_.emplace(listener); } void CancellationFlag::UnregisterOnCancelListener(CancelListener *listener) { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_.get()); listeners_.erase(listener); } From 595e71a36d941711345b43488b666dea4c5d4fc7 Mon Sep 17 00:00:00 2001 From: hai007 Date: Sun, 1 Mar 2026 12:36:05 -0800 Subject: [PATCH 32/49] Automated Code Change PiperOrigin-RevId: 877067723 --- internal/test/fake_clock.cc | 16 ++++++++-------- internal/test/fake_task_runner.cc | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/test/fake_clock.cc b/internal/test/fake_clock.cc index f737d187..edb26a7f 100644 --- a/internal/test/fake_clock.cc +++ b/internal/test/fake_clock.cc @@ -22,30 +22,30 @@ namespace nearby { FakeClock::~FakeClock() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); observers_.clear(); } absl::Time FakeClock::Now() const { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return now_; } void FakeClock::AddObserver(absl::string_view name, std::function observer) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); observers_.emplace(name, std::move(observer)); } void FakeClock::RemoveObserver(absl::string_view name) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); observers_.erase(name); } void FakeClock::FastForward(absl::Duration duration) { std::vector timer_callback_ids; { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); now_ += duration; for (const auto& observer : observers_) { timer_callback_ids.push_back(observer.first); @@ -59,7 +59,7 @@ void FakeClock::FastForward(absl::Duration duration) { std::function callback; { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); is_alive_timer = observers_.contains(timer_callback_id); if (!is_alive_timer) { continue; @@ -72,12 +72,12 @@ void FakeClock::FastForward(absl::Duration duration) { } int FakeClock::GetObserversCount() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return observers_.size(); } void FakeClock::Reset() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return observers_.clear(); } diff --git a/internal/test/fake_task_runner.cc b/internal/test/fake_task_runner.cc index e752f117..129fe2cf 100644 --- a/internal/test/fake_task_runner.cc +++ b/internal/test/fake_task_runner.cc @@ -30,12 +30,12 @@ namespace nearby { FakeTaskRunner::~FakeTaskRunner() { Shutdown(); } void FakeTaskRunner::Shutdown() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); task_executor_->Shutdown(); } bool FakeTaskRunner::PostTask(absl::AnyInvocable task) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); task_executor_->Execute([task = std::move(task)]() mutable { task(); }); @@ -44,7 +44,7 @@ bool FakeTaskRunner::PostTask(absl::AnyInvocable task) { bool FakeTaskRunner::PostDelayedTask(absl::Duration delay, absl::AnyInvocable task) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); std::unique_ptr timer = std::make_unique(clock_); Timer* timer_ptr = timer.get(); timers_.push_back(std::move(timer)); From fa530d3becbc2c48d64a9b72d05e44aadd90887f Mon Sep 17 00:00:00 2001 From: hai007 Date: Sun, 1 Mar 2026 12:36:53 -0800 Subject: [PATCH 33/49] Automated Code Change PiperOrigin-RevId: 877067884 --- internal/platform/task_runner_impl.cc | 16 ++++++++-------- internal/platform/timer_impl.cc | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/platform/task_runner_impl.cc b/internal/platform/task_runner_impl.cc index c418634b..a06e3d18 100644 --- a/internal/platform/task_runner_impl.cc +++ b/internal/platform/task_runner_impl.cc @@ -40,7 +40,7 @@ TaskRunnerImpl::TaskRunnerImpl(uint32_t runner_count) { TaskRunnerImpl::~TaskRunnerImpl() { { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (closed_) { return; } @@ -51,7 +51,7 @@ TaskRunnerImpl::~TaskRunnerImpl() { void TaskRunnerImpl::Shutdown() { absl::flat_hash_map> timers; { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); closed_ = true; timers = std::move(timers_map_); } @@ -65,7 +65,7 @@ void TaskRunnerImpl::Shutdown() { bool TaskRunnerImpl::PostTask(absl::AnyInvocable task) { { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (closed_) { return false; } @@ -81,7 +81,7 @@ bool TaskRunnerImpl::PostTask(absl::AnyInvocable task) { bool TaskRunnerImpl::PostDelayedTask(absl::Duration delay, absl::AnyInvocable task) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (closed_) { return false; } @@ -94,10 +94,10 @@ bool TaskRunnerImpl::PostDelayedTask(absl::Duration delay, [this, id, task = std::move(task)]() mutable { std::unique_ptr timer; { - absl::MutexLock lock(&mutex_); - if (closed_) { - return; - } + absl::MutexLock lock(mutex_); + if (closed_) { + return; + } timer = std::move(timers_map_.extract(id).mapped()); } PostTask(std::move(task)); diff --git a/internal/platform/timer_impl.cc b/internal/platform/timer_impl.cc index 20aaf455..3140ed6f 100644 --- a/internal/platform/timer_impl.cc +++ b/internal/platform/timer_impl.cc @@ -31,7 +31,7 @@ bool TimerImpl::Start(int delay, int period, if (period < 0) { period = 0; } - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (internal_timer_ != nullptr) { LOG(INFO) << "The timer is already running."; return false; @@ -47,7 +47,7 @@ bool TimerImpl::Start(int delay, int period, } void TimerImpl::Stop() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (internal_timer_ == nullptr) { return; } @@ -57,7 +57,7 @@ void TimerImpl::Stop() { } bool TimerImpl::IsRunning() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return (internal_timer_ != nullptr); } From e91e5fab0fe7cb59ed70cf34d13c8d9870bea387 Mon Sep 17 00:00:00 2001 From: hai007 Date: Sun, 1 Mar 2026 12:38:39 -0800 Subject: [PATCH 34/49] Automated Code Change PiperOrigin-RevId: 877068221 --- internal/flags/nearby_flags.cc | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/flags/nearby_flags.cc b/internal/flags/nearby_flags.cc index ebab8bfa..38afbd88 100644 --- a/internal/flags/nearby_flags.cc +++ b/internal/flags/nearby_flags.cc @@ -30,7 +30,7 @@ NearbyFlags& NearbyFlags::GetInstance() { } bool NearbyFlags::GetBoolFlag(const flags::Flag& flag) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); const auto& it = overrided_bool_flag_values_.find(flag.name()); if (it != overrided_bool_flag_values_.end()) { @@ -44,7 +44,7 @@ bool NearbyFlags::GetBoolFlag(const flags::Flag& flag) { } int64_t NearbyFlags::GetInt64Flag(const flags::Flag& flag) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); const auto& it = overrided_int64_flag_values_.find(flag.name()); if (it != overrided_int64_flag_values_.end()) { @@ -58,7 +58,7 @@ int64_t NearbyFlags::GetInt64Flag(const flags::Flag& flag) { } double NearbyFlags::GetDoubleFlag(const flags::Flag& flag) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); const auto& it = overrided_double_flag_values_.find(flag.name()); if (it != overrided_double_flag_values_.end()) { @@ -73,7 +73,7 @@ double NearbyFlags::GetDoubleFlag(const flags::Flag& flag) { std::string NearbyFlags::GetStringFlag( const flags::Flag& flag) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); const auto& it = overrided_string_flag_values_.find(flag.name()); if (it != overrided_string_flag_values_.end()) { @@ -87,36 +87,36 @@ std::string NearbyFlags::GetStringFlag( } void NearbyFlags::SetFlagReader(flags::FlagReader& flag_reader) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); flag_reader_ = &flag_reader; } void NearbyFlags::OverrideBoolFlagValue(const flags::Flag& flag, bool new_value) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); overrided_bool_flag_values_[flag.name()] = new_value; } void NearbyFlags::OverrideInt64FlagValue(const flags::Flag& flag, int64_t new_value) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); overrided_int64_flag_values_[flag.name()] = new_value; } void NearbyFlags::OverrideDoubleFlagValue(const flags::Flag& flag, double new_value) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); overrided_double_flag_values_[flag.name()] = new_value; } void NearbyFlags::OverrideStringFlagValue( const flags::Flag& flag, absl::string_view new_value) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); overrided_string_flag_values_[flag.name()] = std::string(new_value); } void NearbyFlags::ResetOverridedValues() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); overrided_bool_flag_values_.clear(); overrided_int64_flag_values_.clear(); overrided_double_flag_values_.clear(); From 574808daa6053a7248ca4e81c8776cf324bebf44 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 2 Mar 2026 08:47:40 -0800 Subject: [PATCH 35/49] Fix use of deprecated MutexLock. PiperOrigin-RevId: 877419825 --- .../dart/nearby_connections_client_state.cc | 22 +++++++++---------- internal/platform/feature_flags.h | 2 +- .../apple/ble_l2cap_server_socket.mm | 10 ++++----- .../implementation/apple/ble_l2cap_socket.mm | 6 ++--- .../implementation/apple/ble_medium.mm | 22 +++++++++---------- .../implementation/apple/ble_server_socket.mm | 10 ++++----- .../implementation/apple/ble_socket.mm | 8 +++---- .../implementation/apple/count_down_latch.cc | 6 ++--- .../platform/implementation/apple/timer.mm | 8 +++---- .../platform/implementation/g3/wifi_hotspot.h | 6 ++--- sharing/fake_nearby_connections_manager.h | 4 ++-- 11 files changed, 52 insertions(+), 52 deletions(-) diff --git a/connections/dart/nearby_connections_client_state.cc b/connections/dart/nearby_connections_client_state.cc index 2aef752b..7049452d 100644 --- a/connections/dart/nearby_connections_client_state.cc +++ b/connections/dart/nearby_connections_client_state.cc @@ -27,54 +27,54 @@ namespace nearby::connections::dart { NC_INSTANCE NearbyConnectionsClientState::GetOpennedService() const { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return opened_instance_; } void NearbyConnectionsClientState::SetOpennedService(NC_INSTANCE nc_instance) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); opened_instance_ = nc_instance; } DiscoveryListenerDart* NearbyConnectionsClientState::GetDiscoveryListenerDart() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return discovery_listener_dart_.get(); } void NearbyConnectionsClientState::SetDiscoveryListenerDart( std::unique_ptr discovery_listener_dart) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); discovery_listener_dart_ = std::move(discovery_listener_dart); } ConnectionListenerDart* NearbyConnectionsClientState::GetConnectionListenerDart() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return connection_listener_dart_.get(); } void NearbyConnectionsClientState::SetConnectionListenerDart( std::unique_ptr connection_listener_dart) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); connection_listener_dart_ = std::move(connection_listener_dart); } PayloadListenerDart* NearbyConnectionsClientState::GetPayloadListenerDart() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return payload_listener_dart_.get(); } void NearbyConnectionsClientState::SetPayloadListenerDart( std::unique_ptr payload_listener_dart) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); payload_listener_dart_ = std::move(payload_listener_dart); } std::optional NearbyConnectionsClientState::PopNearbyConnectionsApiPort( NearbyConnectionsApi api) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); std::deque& port_list = nearby_connections_api_ports_[api]; if (port_list.empty()) { return std::nullopt; @@ -87,13 +87,13 @@ NearbyConnectionsClientState::PopNearbyConnectionsApiPort( void NearbyConnectionsClientState::PushNearbyConnectionsApiPort( NearbyConnectionsApi api, Dart_Port dart_port) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); std::deque& port_list = nearby_connections_api_ports_[api]; port_list.push_back(dart_port); } void NearbyConnectionsClientState::reset() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); opened_instance_ = nullptr; nearby_connections_api_ports_.clear(); discovery_listener_dart_.reset(); diff --git a/internal/platform/feature_flags.h b/internal/platform/feature_flags.h index 8b492396..02a574bc 100644 --- a/internal/platform/feature_flags.h +++ b/internal/platform/feature_flags.h @@ -137,7 +137,7 @@ class FeatureFlags { // SetFlags for feature controlling void SetFlags(const Flags& flags) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); flags_ = flags; } diff --git a/internal/platform/implementation/apple/ble_l2cap_server_socket.mm b/internal/platform/implementation/apple/ble_l2cap_server_socket.mm index 557fda38..7c8392d0 100644 --- a/internal/platform/implementation/apple/ble_l2cap_server_socket.mm +++ b/internal/platform/implementation/apple/ble_l2cap_server_socket.mm @@ -26,7 +26,7 @@ namespace nearby { namespace apple { BleL2capServerSocket::~BleL2capServerSocket() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); DoClose(); } @@ -36,7 +36,7 @@ void BleL2capServerSocket::SetPSM(int psm) { psm_ = psm; } // TODO: b/399815436 - Refactor Accept() and AddPendingSocket() for better readability. std::unique_ptr BleL2capServerSocket::Accept() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); while (!closed_ && pending_sockets_.empty()) { cond_.Wait(&mutex_); } @@ -48,7 +48,7 @@ std::unique_ptr BleL2capServerSocket::Accept() { } bool BleL2capServerSocket::AddPendingSocket(std::unique_ptr socket) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (closed_) { return false; } @@ -58,12 +58,12 @@ bool BleL2capServerSocket::AddPendingSocket(std::unique_ptr sock } void BleL2capServerSocket::SetCloseNotifier(absl::AnyInvocable notifier) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); close_notifier_ = std::move(notifier); } Exception BleL2capServerSocket::Close() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return DoClose(); } diff --git a/internal/platform/implementation/apple/ble_l2cap_socket.mm b/internal/platform/implementation/apple/ble_l2cap_socket.mm index c8176979..e44c6728 100644 --- a/internal/platform/implementation/apple/ble_l2cap_socket.mm +++ b/internal/platform/implementation/apple/ble_l2cap_socket.mm @@ -172,17 +172,17 @@ BleL2capSocket::BleL2capSocket(GNCBLEL2CAPConnection *connection, peripheral_id_(peripheral_id) {} BleL2capSocket::~BleL2capSocket() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); DoClose(); } bool BleL2capSocket::IsClosed() const { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return closed_; } Exception BleL2capSocket::Close() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); DoClose(); return {Exception::kSuccess}; } diff --git a/internal/platform/implementation/apple/ble_medium.mm b/internal/platform/implementation/apple/ble_medium.mm index ef458c36..afefac0b 100644 --- a/internal/platform/implementation/apple/ble_medium.mm +++ b/internal/platform/implementation/apple/ble_medium.mm @@ -522,11 +522,11 @@ std::unique_ptr BleMedium::OpenL2capServerSocket __block NSError *blockPSMPublishedError = nil; auto l2cap_server_socket = std::make_unique(); l2cap_server_socket->SetCloseNotifier([this]() { - absl::MutexLock lock(&l2cap_server_socket_mutex_); + absl::MutexLock lock(l2cap_server_socket_mutex_); l2cap_server_socket_ptr_ = nullptr; }); { - absl::MutexLock lock(&l2cap_server_socket_mutex_); + absl::MutexLock lock(l2cap_server_socket_mutex_); l2cap_server_socket_ptr_ = l2cap_server_socket.get(); } std::string service_id_str = service_id; @@ -538,7 +538,7 @@ std::unique_ptr BleMedium::OpenL2capServerSocket return; } { - absl::MutexLock lock(&l2cap_server_socket_mutex_); + absl::MutexLock lock(l2cap_server_socket_mutex_); if (l2cap_server_socket_ptr_) { l2cap_server_socket_ptr_->SetPSM(PSM); } @@ -558,7 +558,7 @@ std::unique_ptr BleMedium::OpenL2capServerSocket callbackQueue:connection_callback_queue_]; auto socket = std::make_unique(connection); { - absl::MutexLock lock(&l2cap_server_socket_mutex_); + absl::MutexLock lock(l2cap_server_socket_mutex_); if (l2cap_server_socket_ptr_) { l2cap_server_socket_ptr_->AddPendingSocket(std::move(socket)); } @@ -730,20 +730,20 @@ std::optional BleMedium::RetrieveBlePeriphera } void BleMedium::ClearAdvertisementPacketsMap() { - absl::MutexLock lock(&advertisement_packets_mutex_); + absl::MutexLock lock(advertisement_packets_mutex_); advertisement_packets_map_.clear(); last_timestamp_to_clean_expired_advertisement_packets_ = [NSDate date]; } NSDate *BleMedium::GetLastTimestampToCleanExpiredAdvertisementPackets() { - absl::MutexLock lock(&advertisement_packets_mutex_); + absl::MutexLock lock(advertisement_packets_mutex_); return last_timestamp_to_clean_expired_advertisement_packets_; } bool BleMedium::ShouldReportAdvertisement(NSDate *now, api::ble::BlePeripheral::UniqueId peripheral_id, NSDictionary *service_data) { - absl::MutexLock lock(&advertisement_packets_mutex_); + absl::MutexLock lock(advertisement_packets_mutex_); if (service_data == nil || service_data.count == 0) { return false; } @@ -775,19 +775,19 @@ bool BleMedium::ShouldReportAdvertisement(NSDate *now, void BleMedium::AddAdvertisementPacketInfo(api::ble::BlePeripheral::UniqueId peripheral_id, NSDictionary *service_data) { - absl::MutexLock lock(&advertisement_packets_mutex_); + absl::MutexLock lock(advertisement_packets_mutex_); advertisement_packets_map_[peripheral_id] = {[NSDate date], service_data}; } api::ble::BlePeripheral::UniqueId BleMedium::PeripheralsMap::Add(id peripheral) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); api::ble::BlePeripheral::UniqueId peripheral_id = peripheral.identifier.hash; peripherals_.insert({peripheral_id, peripheral}); return peripheral_id; } id BleMedium::PeripheralsMap::Get(api::ble::BlePeripheral::UniqueId peripheral_id) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); auto peripheral_it = peripherals_.find(peripheral_id); if (peripheral_it == peripherals_.end()) { return nil; @@ -796,7 +796,7 @@ id BleMedium::PeripheralsMap::Get(api::ble::BlePeripheral::Unique } void BleMedium::PeripheralsMap::Clear() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); peripherals_.clear(); } diff --git a/internal/platform/implementation/apple/ble_server_socket.mm b/internal/platform/implementation/apple/ble_server_socket.mm index 2bf3d898..d09def72 100644 --- a/internal/platform/implementation/apple/ble_server_socket.mm +++ b/internal/platform/implementation/apple/ble_server_socket.mm @@ -25,12 +25,12 @@ namespace nearby { namespace apple { BleServerSocket::~BleServerSocket() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); DoClose(); } std::unique_ptr BleServerSocket::Accept() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); while (!closed_ && pending_sockets_.empty()) { cond_.Wait(&mutex_); } @@ -42,7 +42,7 @@ std::unique_ptr BleServerSocket::Accept() { } bool BleServerSocket::Connect(std::unique_ptr socket) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (closed_) { return false; } @@ -52,12 +52,12 @@ bool BleServerSocket::Connect(std::unique_ptr socket) { } void BleServerSocket::SetCloseNotifier(absl::AnyInvocable notifier) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); close_notifier_ = std::move(notifier); } Exception BleServerSocket::Close() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return DoClose(); } diff --git a/internal/platform/implementation/apple/ble_socket.mm b/internal/platform/implementation/apple/ble_socket.mm index c1557c0e..e34eb9e1 100644 --- a/internal/platform/implementation/apple/ble_socket.mm +++ b/internal/platform/implementation/apple/ble_socket.mm @@ -185,23 +185,23 @@ BleSocket::BleSocket(id connection, api::ble::BlePeripheral::Uni peripheral_id_(peripheral_id) {} BleSocket::~BleSocket() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); DoClose(); } bool BleSocket::IsClosed() const { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return closed_; } Exception BleSocket::Close() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); DoClose(); return {Exception::kSuccess}; } void BleSocket::SetCloseNotifier(absl::AnyInvocable notifier) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); close_notifier_ = std::move(notifier); } diff --git a/internal/platform/implementation/apple/count_down_latch.cc b/internal/platform/implementation/apple/count_down_latch.cc index 69641502..1ace533f 100644 --- a/internal/platform/implementation/apple/count_down_latch.cc +++ b/internal/platform/implementation/apple/count_down_latch.cc @@ -21,19 +21,19 @@ namespace nearby { namespace apple { Exception CountDownLatch::Await() { - absl::MutexLock lock(&mutex_, absl::Condition(IsZeroOrNegative, &count_)); + absl::MutexLock lock(mutex_, absl::Condition(IsZeroOrNegative, &count_)); return {Exception::kSuccess}; } ExceptionOr CountDownLatch::Await(absl::Duration timeout) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); bool condition = mutex_.AwaitWithTimeout( absl::Condition(IsZeroOrNegative, &count_), timeout); return ExceptionOr(condition); } void CountDownLatch::CountDown() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); count_--; } diff --git a/internal/platform/implementation/apple/timer.mm b/internal/platform/implementation/apple/timer.mm index 8b714520..a02b7ddf 100644 --- a/internal/platform/implementation/apple/timer.mm +++ b/internal/platform/implementation/apple/timer.mm @@ -38,7 +38,7 @@ bool Timer::Create(int delay, int interval, absl::AnyInvocable callback) return false; } - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (timer_ != nullptr) { GNCLoggerError(@"Timer has already started."); return false; @@ -59,7 +59,7 @@ bool Timer::Create(int delay, int interval, absl::AnyInvocable callback) absl::AnyInvocable callback_to_run = nullptr; bool is_one_shot = (intervalInNanoseconds == DISPATCH_TIME_FOREVER); { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); // If Stop() was called concurrently, the callback will be null. if (!callback_ || callback_running_) { return; @@ -76,7 +76,7 @@ bool Timer::Create(int delay, int interval, absl::AnyInvocable callback) callback_to_run(); } { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (!is_one_shot && callback_to_run) { // For periodic timers, move the callback back for the next run. callback_ = std::move(callback_to_run); @@ -93,7 +93,7 @@ bool Timer::Create(int delay, int interval, absl::AnyInvocable callback) } bool Timer::Stop() { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); if (timer_ != nullptr) { dispatch_source_cancel(timer_); timer_ = nullptr; diff --git a/internal/platform/implementation/g3/wifi_hotspot.h b/internal/platform/implementation/g3/wifi_hotspot.h index 75f83276..5c02dc5f 100644 --- a/internal/platform/implementation/g3/wifi_hotspot.h +++ b/internal/platform/implementation/g3/wifi_hotspot.h @@ -66,17 +66,17 @@ class WifiHotspotServerSocket : public api::WifiHotspotServerSocket { static std::string GetName(absl::string_view ip_address, int port); void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); ip_address_ = ip_address; } int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); return port_; } void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(&mutex_); + absl::MutexLock lock(mutex_); port_ = port; } diff --git a/sharing/fake_nearby_connections_manager.h b/sharing/fake_nearby_connections_manager.h index d62415c0..94b3dddb 100644 --- a/sharing/fake_nearby_connections_manager.h +++ b/sharing/fake_nearby_connections_manager.h @@ -124,7 +124,7 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager { std::optional> connection_endpoint_info( absl::string_view endpoint_id) { - absl::MutexLock lock(&endpoints_mutex_); + absl::MutexLock lock(endpoints_mutex_); auto it = connection_endpoint_infos_.find(std::string(endpoint_id)); if (it == connection_endpoint_infos_.end()) return std::nullopt; @@ -132,7 +132,7 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager { } bool has_incoming_payloads() { - absl::MutexLock lock(&incoming_payloads_mutex_); + absl::MutexLock lock(incoming_payloads_mutex_); return !incoming_payloads_.empty(); } From 26852fb71b63695a85c89c818066be32c16fd6c9 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 2 Mar 2026 10:03:30 -0800 Subject: [PATCH 36/49] internal changes PiperOrigin-RevId: 877452385 --- internal/platform/BUILD | 1 + internal/platform/implementation/BUILD | 6 +++++- internal/rpc/BUILD | 5 ++++- sharing/internal/api/BUILD | 1 + 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/platform/BUILD b/internal/platform/BUILD index cc68ded0..de9638d8 100644 --- a/internal/platform/BUILD +++ b/internal/platform/BUILD @@ -257,6 +257,7 @@ cc_library( "//:__subpackages__", "//location/nearby/apps:__subpackages__", "//location/nearby/cpp:__subpackages__", + "//location/nearby/sharing/lib:__subpackages__", "//location/nearby/sharing/sdk:__subpackages__", "//location/nearby/testing/nearby_native:__subpackages__", ], diff --git a/internal/platform/implementation/BUILD b/internal/platform/implementation/BUILD index 90e18df8..d9a63885 100644 --- a/internal/platform/implementation/BUILD +++ b/internal/platform/implementation/BUILD @@ -46,6 +46,7 @@ cc_library( "//internal/platform/implementation:__subpackages__", "//internal/test:__subpackages__", "//location/nearby/cpp/sharing/clients/cpp:__subpackages__", + "//location/nearby/sharing/lib:__subpackages__", "//location/nearby/sharing/sdk/quick_share_server:__pkg__", "//sharing:__subpackages__", ], @@ -226,7 +227,10 @@ cc_library( name = "platform_impl", testonly = True, tags = ["keep_dep"], # Prevent build_cleaner from removing the dependency. - visibility = ["//:__subpackages__"], + visibility = [ + "//:__subpackages__", + "//location/nearby/sharing/lib:__subpackages__", + ], deps = [ ] + select({ "@platforms//os:windows": [ diff --git a/internal/rpc/BUILD b/internal/rpc/BUILD index 93ac2423..1a1aeecd 100644 --- a/internal/rpc/BUILD +++ b/internal/rpc/BUILD @@ -20,7 +20,10 @@ cc_library( name = "utils", hdrs = ["utils.h"], compatible_with = ["//buildenv/target:non_prod"], - visibility = ["//:__subpackages__"], + visibility = [ + "//:__subpackages__", + "//location/nearby/sharing/lib:__subpackages__", + ], deps = [ "//third_party/grpc:grpc++", "@com_google_absl//absl/functional:any_invocable", diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index e940ba7d..7efa83c8 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -34,6 +34,7 @@ cc_library( visibility = [ "//location/nearby/analytics/cpp/logging:__pkg__", "//location/nearby/cpp/sharing:__subpackages__", + "//location/nearby/sharing/lib:__subpackages__", "//location/nearby/sharing/sdk/test_client:__pkg__", "//sharing:__subpackages__", ], From 657591bce40961f875d4df6960f502c41a43e33a Mon Sep 17 00:00:00 2001 From: hai007 Date: Mon, 2 Mar 2026 11:16:29 -0800 Subject: [PATCH 37/49] Add more test cases for EncryptionRunner to improve test coverage. PiperOrigin-RevId: 877490825 --- .../implementation/encryption_runner_test.cc | 233 ++++++++++++++++++ 1 file changed, 233 insertions(+) diff --git a/connections/implementation/encryption_runner_test.cc b/connections/implementation/encryption_runner_test.cc index c1e3211f..c5ec1964 100644 --- a/connections/implementation/encryption_runner_test.cc +++ b/connections/implementation/encryption_runner_test.cc @@ -41,6 +41,8 @@ namespace { using ::location::nearby::proto::connections::Medium; constexpr size_t kChunkSize = 64 * 1024; +constexpr securegcm::UKey2Handshake::HandshakeCipher kCipher = + securegcm::UKey2Handshake::HandshakeCipher::P256_SHA512; class FakeEndpointChannel : public EndpointChannel { public: @@ -166,6 +168,7 @@ TEST(EncryptionRunnerTest, ReadWrite) { .on_failure_cb = [&response](const std::string& endpoint_id, EndpointChannel* channel) { + channel->Close(); response.server_status = Response::Status::kFailed; response.latch.CountDown(); }, @@ -184,6 +187,7 @@ TEST(EncryptionRunnerTest, ReadWrite) { .on_failure_cb = [&response](const std::string& endpoint_id, EndpointChannel* channel) { + channel->Close(); response.client_status = Response::Status::kFailed; response.latch.CountDown(); }, @@ -193,6 +197,235 @@ TEST(EncryptionRunnerTest, ReadWrite) { EXPECT_EQ(response.client_status, Response::Status::kDone); } +TEST(EncryptionRunnerTest, ClientWriteFails) { + auto from_a_to_b = CreatePipe(); + auto from_b_to_a = CreatePipe(); + User user_a(/*reader=*/from_b_to_a.first.get(), + /*writer=*/from_a_to_b.second.get()); + User user_b(/*reader=*/from_a_to_b.first.get(), + /*writer=*/from_b_to_a.second.get()); + Response response; + response.latch = CountDownLatch(1); + + // Close server's input stream, so client can't write to it. + from_b_to_a.first->Close(); + + user_b.crypto.StartClient( + &user_b.client, "endpoint_id", &user_b.channel, + { + .on_success_cb = + [&response](const std::string& endpoint_id, + std::unique_ptr ukey2, + const std::string& auth_token, + const ByteArray& raw_auth_token) { + response.client_status = Response::Status::kDone; + response.latch.CountDown(); + }, + .on_failure_cb = + [&response](const std::string& endpoint_id, + EndpointChannel* channel) { + channel->Close(); + response.client_status = Response::Status::kFailed; + response.latch.CountDown(); + }, + }); + EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result()); + EXPECT_EQ(response.client_status, Response::Status::kFailed); +} + +TEST(EncryptionRunnerTest, ServerWriteFails) { + auto from_a_to_b = CreatePipe(); + auto from_b_to_a = CreatePipe(); + User user_a(/*reader=*/from_b_to_a.first.get(), + /*writer=*/from_a_to_b.second.get()); + User user_b(/*reader=*/from_a_to_b.first.get(), + /*writer=*/from_b_to_a.second.get()); + Response response; + response.latch = CountDownLatch(1); + + // Close client's input stream, so server can't write to it. + from_a_to_b.first->Close(); + + user_a.crypto.StartServer( + &user_a.client, "endpoint_id", &user_a.channel, + { + .on_success_cb = + [&response](const std::string& endpoint_id, + std::unique_ptr ukey2, + const std::string& auth_token, + const ByteArray& raw_auth_token) { + response.server_status = Response::Status::kDone; + response.latch.CountDown(); + }, + .on_failure_cb = + [&response](const std::string& endpoint_id, + EndpointChannel* channel) { + channel->Close(); + response.server_status = Response::Status::kFailed; + response.latch.CountDown(); + }, + }); + user_b.crypto.StartClient( + &user_b.client, "endpoint_id", &user_b.channel, + { + .on_success_cb = + [](const std::string& endpoint_id, + std::unique_ptr ukey2, + const std::string& auth_token, + const ByteArray& raw_auth_token) {}, + .on_failure_cb = + [](const std::string& endpoint_id, EndpointChannel* channel) { + channel->Close(); + }, + }); + EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result()); + EXPECT_EQ(response.server_status, Response::Status::kFailed); +} + +TEST(EncryptionRunnerTest, ClientSendsGarbageMessage1) { + auto from_server_to_client = CreatePipe(); + auto from_client_to_server = CreatePipe(); + User user_a(/*reader=*/from_client_to_server.first.get(), + /*writer=*/from_server_to_client.second.get()); + Response response; + response.latch = CountDownLatch(1); + + user_a.crypto.StartServer( + &user_a.client, "endpoint_id", &user_a.channel, + { + .on_success_cb = + [&response](const std::string& endpoint_id, + std::unique_ptr ukey2, + const std::string& auth_token, + const ByteArray& raw_auth_token) { + response.server_status = Response::Status::kDone; + response.latch.CountDown(); + }, + .on_failure_cb = + [&response](const std::string& endpoint_id, + EndpointChannel* channel) { + channel->Close(); + response.server_status = Response::Status::kFailed; + response.latch.CountDown(); + }, + }); + + // Client writes garbage instead of message 1 + from_client_to_server.second->Write("Garbage"); + + EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result()); + EXPECT_EQ(response.server_status, Response::Status::kFailed); + + // Check if server sent alert message. + // The alert message should be readable from from_server_to_client.first. + auto alert = from_server_to_client.first->Read(kChunkSize); + EXPECT_TRUE(alert.ok()); + EXPECT_FALSE(alert.result().Empty()); +} + +TEST(EncryptionRunnerTest, ServerSendsGarbageMessage2) { + auto from_server_to_client = CreatePipe(); + auto from_client_to_server = CreatePipe(); + User user_b(/*reader=*/from_server_to_client.first.get(), + /*writer=*/from_client_to_server.second.get()); + Response response; + response.latch = CountDownLatch(1); + + user_b.crypto.StartClient( + &user_b.client, "endpoint_id", &user_b.channel, + { + .on_success_cb = + [&response](const std::string& endpoint_id, + std::unique_ptr ukey2, + const std::string& auth_token, + const ByteArray& raw_auth_token) { + response.client_status = Response::Status::kDone; + response.latch.CountDown(); + }, + .on_failure_cb = + [&response](const std::string& endpoint_id, + EndpointChannel* channel) { + channel->Close(); + response.client_status = Response::Status::kFailed; + response.latch.CountDown(); + }, + }); + + // Client sends message 1. + auto client_init = from_client_to_server.first->Read(kChunkSize); + EXPECT_TRUE(client_init.ok()); + + // Server writes garbage instead of message 2. + from_server_to_client.second->Write("Garbage"); + + EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result()); + EXPECT_EQ(response.client_status, Response::Status::kFailed); + + // Check if client sent alert message. + auto alert = from_client_to_server.first->Read(kChunkSize); + EXPECT_TRUE(alert.ok()); + EXPECT_FALSE(alert.result().Empty()); +} + +TEST(EncryptionRunnerTest, ClientSendsGarbageMessage3) { + auto from_server_to_client = CreatePipe(); + auto from_client_to_server = CreatePipe(); + User user_a(/*reader=*/from_client_to_server.first.get(), + /*writer=*/from_server_to_client.second.get()); + User user_b(/*reader=*/from_server_to_client.first.get(), + /*writer=*/from_client_to_server.second.get()); + Response response; + response.latch = CountDownLatch(1); + + user_a.crypto.StartServer( + &user_a.client, "endpoint_id", &user_a.channel, + { + .on_success_cb = + [&response](const std::string& endpoint_id, + std::unique_ptr ukey2, + const std::string& auth_token, + const ByteArray& raw_auth_token) { + response.server_status = Response::Status::kDone; + response.latch.CountDown(); + }, + .on_failure_cb = + [&response](const std::string& endpoint_id, + EndpointChannel* channel) { + channel->Close(); + response.server_status = Response::Status::kFailed; + response.latch.CountDown(); + }, + }); + + // Client starts, sends message 1 + std::unique_ptr client_crypto = + securegcm::UKey2Handshake::ForInitiator(kCipher); + std::unique_ptr client_init_str = + client_crypto->GetNextHandshakeMessage(); + from_client_to_server.second->Write( + ByteArray(*client_init_str).AsStringView()); + + // Server reads message 1, sends message 2. + // Read message 2 from server + auto server_init = from_server_to_client.first->Read(kChunkSize); + EXPECT_TRUE(server_init.ok()); + + // Client crypto parses message 2. + client_crypto->ParseHandshakeMessage(std::string(server_init.result())); + + // Client sends garbage instead of message 3 + from_client_to_server.second->Write("Garbage"); + + EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result()); + EXPECT_EQ(response.server_status, Response::Status::kFailed); + + // Check if server sent alert message. + // Message 3 doesn't send alert in current UKEY2 implementation. + auto alert = from_server_to_client.first->Read(kChunkSize); + EXPECT_TRUE(alert.ok()); + EXPECT_TRUE(alert.result().Empty()); +} + } // namespace } // namespace connections } // namespace nearby From 65276b68912e0fd4a7bec9081fff815e36bbab6f Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Mon, 2 Mar 2026 11:39:13 -0800 Subject: [PATCH 38/49] Fix build warnings. PiperOrigin-RevId: 877501913 --- connections/core.cc | 19 ++++++----- .../implementation/base_endpoint_channel.h | 2 +- .../implementation/base_pcp_handler.cc | 9 ++--- connections/implementation/bwu_manager.cc | 13 +++----- .../implementation/bwu_manager_test.cc | 33 ++++++++++--------- .../implementation/endpoint_manager.cc | 9 ++--- internal/platform/BUILD | 1 + internal/platform/cancellation_flag.cc | 15 +++++---- internal/platform/cancellation_flag.h | 3 +- internal/platform/feature_flags.h | 10 +++--- internal/platform/feature_flags_test.cc | 4 +-- internal/platform/medium_environment.cc | 2 +- 12 files changed, 63 insertions(+), 57 deletions(-) diff --git a/connections/core.cc b/connections/core.cc index 827715cc..db156133 100644 --- a/connections/core.cc +++ b/connections/core.cc @@ -137,11 +137,12 @@ void Core::RequestConnection(absl::string_view endpoint_id, << "Client request connection with keep-alive frame as interval=" << connection_options.keep_alive_interval_millis << ", timeout=" << connection_options.keep_alive_timeout_millis - << ", which is un-expected. Change to default.", - connection_options.keep_alive_interval_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis; + << ", which is un-expected. Change to default."; + FeatureFlags::Flags flags = FeatureFlags::GetInstance().GetFlags(); + connection_options.keep_alive_interval_millis = + flags.keep_alive_interval_millis; connection_options.keep_alive_timeout_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis; + flags.keep_alive_timeout_millis; } router_->RequestConnection(&client_, endpoint_id, info, connection_options, @@ -404,10 +405,11 @@ void Core::RequestConnectionV3(const NearbyDevice& local_device, << connection_options.keep_alive_interval_millis << ", timeout=" << connection_options.keep_alive_timeout_millis << ", which is un-expected. Change to default."; + FeatureFlags::Flags flags = FeatureFlags::GetInstance().GetFlags(); connection_options.keep_alive_interval_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis; + flags.keep_alive_interval_millis; connection_options.keep_alive_timeout_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis; + flags.keep_alive_timeout_millis; } router_->RequestConnectionV3(&client_, remote_device, std::move(info), connection_options, std::move(result_cb)); @@ -437,10 +439,11 @@ void Core::RequestConnectionV3(const NearbyDevice& remote_device, << connection_options.keep_alive_interval_millis << ", timeout=" << connection_options.keep_alive_timeout_millis << ", which is un-expected. Change to default."; + FeatureFlags::Flags flags = FeatureFlags::GetInstance().GetFlags(); connection_options.keep_alive_interval_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis; + flags.keep_alive_interval_millis; connection_options.keep_alive_timeout_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis; + flags.keep_alive_timeout_millis; } router_->RequestConnectionV3(&client_, remote_device, std::move(info), connection_options, std::move(result_cb)); diff --git a/connections/implementation/base_endpoint_channel.h b/connections/implementation/base_endpoint_channel.h index 0924c794..9946b9fa 100644 --- a/connections/implementation/base_endpoint_channel.h +++ b/connections/implementation/base_endpoint_channel.h @@ -158,7 +158,7 @@ class BaseEndpointChannel : public EndpointChannel { // An encryptor/decryptor. May be null. mutable Mutex crypto_mutex_; std::shared_ptr crypto_context_ - ABSL_GUARDED_BY(crypto_mutex_) ABSL_PT_GUARDED_BY(crypto_mutex_); + ABSL_GUARDED_BY(crypto_mutex_); mutable Mutex is_paused_mutex_; ConditionVariable is_paused_cond_{&is_paused_mutex_}; diff --git a/connections/implementation/base_pcp_handler.cc b/connections/implementation/base_pcp_handler.cc index 3108f357..406d35f2 100644 --- a/connections/implementation/base_pcp_handler.cc +++ b/connections/implementation/base_pcp_handler.cc @@ -2052,11 +2052,12 @@ Exception BasePcpHandler::OnIncomingConnection( LOG(WARNING) << "Incoming connection has wrong keep-alive frame interval=" << connection_options.keep_alive_interval_millis << ", timeout=" << connection_options.keep_alive_timeout_millis - << " values; correct them as default.", - connection_options.keep_alive_interval_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis; + << " values; correct them as default."; + FeatureFlags::Flags flags = FeatureFlags::GetInstance().GetFlags(); + connection_options.keep_alive_interval_millis = + flags.keep_alive_interval_millis; connection_options.keep_alive_timeout_millis = - FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis; + flags.keep_alive_timeout_millis; } const MediumMetadata& medium_metadata = connection_request.medium_metadata(); diff --git a/connections/implementation/bwu_manager.cc b/connections/implementation/bwu_manager.cc index 8f93a3de..fd41cfb2 100644 --- a/connections/implementation/bwu_manager.cc +++ b/connections/implementation/bwu_manager.cc @@ -83,22 +83,19 @@ BwuManager::BwuManager( mediums_(&mediums), endpoint_manager_(&endpoint_manager), channel_manager_(&channel_manager) { + FeatureFlags::Flags flags = FeatureFlags::GetInstance().GetFlags(); if (config_.bandwidth_upgrade_retry_delay == absl::ZeroDuration()) { - if (FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry) { + if (flags.use_exp_backoff_in_bwu_retry) { config_.bandwidth_upgrade_retry_delay = - FeatureFlags::GetInstance() - .GetFlags() - .bwu_retry_exp_backoff_initial_delay; + flags.bwu_retry_exp_backoff_initial_delay; } else { config_.bandwidth_upgrade_retry_delay = absl::Seconds(5); } } if (config_.bandwidth_upgrade_retry_max_delay == absl::ZeroDuration()) { - if (FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry) { + if (flags.use_exp_backoff_in_bwu_retry) { config_.bandwidth_upgrade_retry_max_delay = - FeatureFlags::GetInstance() - .GetFlags() - .bwu_retry_exp_backoff_maximum_delay; + flags.bwu_retry_exp_backoff_maximum_delay; } else { config_.bandwidth_upgrade_retry_max_delay = absl::Seconds(10); } diff --git a/connections/implementation/bwu_manager_test.cc b/connections/implementation/bwu_manager_test.cc index cbae93aa..40cd3e50 100644 --- a/connections/implementation/bwu_manager_test.cc +++ b/connections/implementation/bwu_manager_test.cc @@ -120,6 +120,13 @@ class BwuManagerTest : public ::testing::Test { ~BwuManagerTest() override { bwu_manager_->Shutdown(); } + void SetSupportMultipleBwuMediums(bool support_multiple_bwu_mediums) { + FeatureFlags& feature_flags = FeatureFlags::GetMutableInstanceForTesting(); + FeatureFlags::Flags flags = feature_flags.GetFlags(); + flags.support_multiple_bwu_mediums = support_multiple_bwu_mediums; + feature_flags.SetFlags(flags); + } + // Create the initial device-to-device connection, before bandwidth upgrade. // Typically |medium| will be Bluetooth. FakeEndpointChannel* CreateInitialEndpoint(ClientProxy* client, @@ -315,8 +322,7 @@ class BwuManagerTestParam : public BwuManagerTest, public ::testing::WithParamInterface { protected: BwuManagerTestParam() { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = - GetParam(); + SetSupportMultipleBwuMediums(GetParam()); } }; @@ -475,7 +481,7 @@ TEST_P(BwuManagerTestParam, TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_MultipleEndpoints_FlagEnabled) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); // Say we have two already upgraded WebRTC connections for the same service. CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -524,8 +530,7 @@ TEST_F(BwuManagerTest, TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_MultipleEndpoints_FlagDisabled) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = - false; + SetSupportMultipleBwuMediums(false); // Say we have two already upgraded WebRTC connections for the same service. CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -581,7 +586,7 @@ TEST_F(BwuManagerTest, TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_MultipleServices_FlagEnabled) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); // Say we have two already upgraded WLAN connections for different services. CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -635,8 +640,7 @@ TEST_F(BwuManagerTest, TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_MultipleServices_FlagDisabled) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = - false; + SetSupportMultipleBwuMediums(false); // Say we have two already upgraded WLAN connections for different services. CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -694,7 +698,7 @@ TEST_F( BwuManagerTest, InitiateBwu_Revert_OnDisconnect_MultipleServicesAndEndpoints_FlagEnabled) { // Need support_multiple_bwu_mediums_ to run this test with multiple mediums. - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); // Say we have three upgraded connections for two different services and two // different mediums. @@ -843,7 +847,7 @@ TEST_F( } TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagEnabled) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); // Say we have two already upgraded WebRTC connections for service A. CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -880,8 +884,7 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagEnabled) { } TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagDisabled) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = - false; + SetSupportMultipleBwuMediums(false); // Say we have two already upgraded WebRTC connections for service A. CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -917,7 +920,7 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagDisabled) { } TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_WifiDirect) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); OfflineFrame frame; CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -951,7 +954,7 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_WifiDirect) { } TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_Hotspot) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); @@ -981,7 +984,7 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_Hotspot) { } TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_Wlan) { - FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true; + SetSupportMultipleBwuMediums(true); CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH); diff --git a/connections/implementation/endpoint_manager.cc b/connections/implementation/endpoint_manager.cc index 82677bca..ecde9b08 100644 --- a/connections/implementation/endpoint_manager.cc +++ b/connections/implementation/endpoint_manager.cc @@ -813,9 +813,8 @@ bool EndpointManager::ApplySafeToDisconnect(const std::string& endpoint_id, // TODO(b/303544913): clean up the safe-to-disconnect logic bool is_safe_disconnection = false; bool send_disconnection_frame = true; - absl::Duration timeout_millis = FeatureFlags::GetInstance() - .GetFlags() - .safe_to_disconnect_ack_delay_millis; + FeatureFlags::Flags flags = FeatureFlags::GetInstance().GetFlags(); + absl::Duration timeout_millis = flags.safe_to_disconnect_ack_delay_millis; bool is_wait_for_ack = true; switch (reason) { case DisconnectionReason::UPGRADED: @@ -832,9 +831,7 @@ bool EndpointManager::ApplySafeToDisconnect(const std::string& endpoint_id, case DisconnectionReason::REMOTE_DISCONNECTION: is_safe_disconnection = true; send_disconnection_frame = false; - timeout_millis = FeatureFlags::GetInstance() - .GetFlags() - .safe_to_disconnect_remote_disc_delay_millis; + timeout_millis = flags.safe_to_disconnect_remote_disc_delay_millis; is_wait_for_ack = false; break; default: diff --git a/internal/platform/BUILD b/internal/platform/BUILD index de9638d8..67f362f5 100644 --- a/internal/platform/BUILD +++ b/internal/platform/BUILD @@ -128,6 +128,7 @@ cc_library( ], deps = [ ":base", + "@com_google_absl//absl/base:core_headers", "@com_google_absl//absl/container:flat_hash_set", "@com_google_absl//absl/functional:any_invocable", "@com_google_absl//absl/synchronization", diff --git a/internal/platform/cancellation_flag.cc b/internal/platform/cancellation_flag.cc index 90b079bb..a83f546b 100644 --- a/internal/platform/cancellation_flag.cc +++ b/internal/platform/cancellation_flag.cc @@ -13,7 +13,10 @@ // limitations under the License. #include "internal/platform/cancellation_flag.h" +#include +#include "absl/container/flat_hash_set.h" +#include "absl/synchronization/mutex.h" #include "internal/platform/feature_flags.h" namespace nearby { @@ -28,7 +31,7 @@ CancellationFlag::CancellationFlag(bool cancelled) { } CancellationFlag::~CancellationFlag() { - absl::MutexLock lock(*mutex_.get()); + absl::MutexLock lock(*mutex_); listeners_.clear(); } @@ -40,7 +43,7 @@ void CancellationFlag::Cancel() { absl::flat_hash_set listeners; { - absl::MutexLock lock(*mutex_.get()); + absl::MutexLock lock(*mutex_); if (cancelled_) { // Someone already cancelled. Return immediately. return; @@ -62,14 +65,14 @@ void CancellationFlag::Uncancel() { } { - absl::MutexLock lock(*mutex_.get()); + absl::MutexLock lock(*mutex_); assert(cancelled_); cancelled_ = false; } } bool CancellationFlag::Cancelled() const { - absl::MutexLock lock(*mutex_.get()); + absl::MutexLock lock(*mutex_); // Return false as no-op if feature flag is not enabled. if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) { @@ -80,13 +83,13 @@ bool CancellationFlag::Cancelled() const { } void CancellationFlag::RegisterOnCancelListener(CancelListener *listener) { - absl::MutexLock lock(*mutex_.get()); + absl::MutexLock lock(*mutex_); listeners_.emplace(listener); } void CancellationFlag::UnregisterOnCancelListener(CancelListener *listener) { - absl::MutexLock lock(*mutex_.get()); + absl::MutexLock lock(*mutex_); listeners_.erase(listener); } diff --git a/internal/platform/cancellation_flag.h b/internal/platform/cancellation_flag.h index 9a8b7280..1e05539e 100644 --- a/internal/platform/cancellation_flag.h +++ b/internal/platform/cancellation_flag.h @@ -17,6 +17,7 @@ #include +#include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/any_invocable.h" #include "absl/synchronization/mutex.h" @@ -74,7 +75,7 @@ class CancellationFlag { ABSL_LOCKS_EXCLUDED(mutex_); int CancelListenersSize() const ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_.get()); + absl::MutexLock lock(*mutex_); return listeners_.size(); } diff --git a/internal/platform/feature_flags.h b/internal/platform/feature_flags.h index 02a574bc..cad1ba6a 100644 --- a/internal/platform/feature_flags.h +++ b/internal/platform/feature_flags.h @@ -126,13 +126,13 @@ class FeatureFlags { return *instance; } - const Flags& GetFlags() const ABSL_LOCKS_EXCLUDED(mutex_) { - absl::ReaderMutexLock lock(&mutex_); - return flags_; + static FeatureFlags& GetMutableInstanceForTesting() { + return const_cast(GetInstance()); } - static Flags& GetMutableFlagsForTesting() { - return const_cast(GetInstance()).flags_; + Flags GetFlags() const ABSL_LOCKS_EXCLUDED(mutex_) { + absl::ReaderMutexLock lock(mutex_); + return flags_; } // SetFlags for feature controlling diff --git a/internal/platform/feature_flags_test.cc b/internal/platform/feature_flags_test.cc index c4f24ee6..2ca92d43 100644 --- a/internal/platform/feature_flags_test.cc +++ b/internal/platform/feature_flags_test.cc @@ -28,8 +28,8 @@ constexpr FeatureFlags::Flags kTestFeatureFlags{ TEST(FeatureFlagsTest, CastUpdateWorks) { const FeatureFlags& features = FeatureFlags::GetInstance(); EXPECT_TRUE(features.GetFlags().enable_async_bandwidth_upgrade); - const_cast(FeatureFlags::GetInstance()) - .SetFlags({.enable_async_bandwidth_upgrade = false}); + FeatureFlags::GetMutableInstanceForTesting().SetFlags( + {.enable_async_bandwidth_upgrade = false}); EXPECT_FALSE(features.GetFlags().enable_async_bandwidth_upgrade); } diff --git a/internal/platform/medium_environment.cc b/internal/platform/medium_environment.cc index cbbf246a..f932bfc4 100644 --- a/internal/platform/medium_environment.cc +++ b/internal/platform/medium_environment.cc @@ -1147,7 +1147,7 @@ void MediumEnvironment::UnregisterWifiHotspotMedium( } void MediumEnvironment::SetFeatureFlags(const FeatureFlags::Flags& flags) { - const_cast(FeatureFlags::GetInstance()).SetFlags(flags); + FeatureFlags::GetMutableInstanceForTesting().SetFlags(flags); } std::optional MediumEnvironment::GetSimulatedClock() { From 0cd9160cf4e3a38776b850acc4f45ef485fc50ad Mon Sep 17 00:00:00 2001 From: hai007 Date: Mon, 2 Mar 2026 14:43:45 -0800 Subject: [PATCH 39/49] Add more test cases for Awdl medium to improve test coverage. PiperOrigin-RevId: 877586175 --- connections/implementation/mediums/BUILD | 1 + .../implementation/mediums/awdl_test.cc | 195 +++++++++++++++++- 2 files changed, 192 insertions(+), 4 deletions(-) diff --git a/connections/implementation/mediums/BUILD b/connections/implementation/mediums/BUILD index eb101d01..e12c6e42 100644 --- a/connections/implementation/mediums/BUILD +++ b/connections/implementation/mediums/BUILD @@ -179,6 +179,7 @@ cc_test( "//internal/platform/implementation:types", "//internal/platform/implementation/g3", # build_cleaner: keep "@com_github_protobuf_matchers//protobuf-matchers", + "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/strings", "@com_google_absl//absl/time", "@com_google_googletest//:gtest_main", diff --git a/connections/implementation/mediums/awdl_test.cc b/connections/implementation/mediums/awdl_test.cc index b7e21ea6..ca05d7ab 100644 --- a/connections/implementation/mediums/awdl_test.cc +++ b/connections/implementation/mediums/awdl_test.cc @@ -20,18 +20,15 @@ #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" -#include "connections/implementation/flags/nearby_connections_feature_flags.h" -#include "internal/flags/nearby_flags.h" #include "internal/platform/awdl.h" -#include "internal/platform/base64_utils.h" #include "internal/platform/cancellation_flag.h" #include "internal/platform/count_down_latch.h" #include "internal/platform/expected.h" #include "internal/platform/feature_flags.h" +#include "internal/platform/implementation/psk_info.h" #include "internal/platform/logging.h" #include "internal/platform/medium_environment.h" #include "internal/platform/nsd_service_info.h" -#include "internal/platform/single_thread_executor.h" namespace nearby { namespace connections { @@ -113,6 +110,61 @@ TEST_P(AwdlTest, CanConnect) { env_.Stop(); } +TEST_P(AwdlTest, CanConnectWithPsk) { + FeatureFlags feature_flags = GetParam(); + env_.SetFeatureFlags(feature_flags); + env_.Start(); + Awdl awdl_client; + Awdl awdl_server; + std::string service_id(kServiceID); + std::string service_info_name(kServiceInfoName); + std::string endpoint_info_name(kEndpointName); + api::PskInfo psk_info; + psk_info.password = "password"; + CountDownLatch discovered_latch(1); + CountDownLatch accept_latch(1); + + AwdlSocket socket_for_server; + EXPECT_TRUE(awdl_server.StartAcceptingConnections( + service_id, psk_info, + [&](const std::string& service_id, AwdlSocket socket) { + socket_for_server = std::move(socket); + accept_latch.CountDown(); + })); + + NsdServiceInfo nsd_service_info; + nsd_service_info.SetServiceName(service_info_name); + nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey), + endpoint_info_name); + awdl_server.StartAdvertising(service_id, nsd_service_info); + + NsdServiceInfo discovered_service_info; + awdl_client.StartDiscovery( + service_id, + { + .service_discovered_cb = + [&discovered_latch, &discovered_service_info]( + NsdServiceInfo service_info, const std::string& service_id) { + LOG(INFO) << "Discovered service_info=" << &service_info; + discovered_service_info = service_info; + discovered_latch.CountDown(); + }, + }); + discovered_latch.Await(kWaitDuration).result(); + ASSERT_TRUE(discovered_service_info.IsValid()); + + CancellationFlag flag; + ErrorOr socket_for_client_result = + awdl_client.Connect(service_id, discovered_service_info, psk_info, &flag); + EXPECT_TRUE(accept_latch.Await(kWaitDuration).result()); + EXPECT_TRUE(awdl_server.StopAcceptingConnections(service_id)); + EXPECT_TRUE(awdl_server.StopAdvertising(service_id)); + EXPECT_TRUE(socket_for_server.IsValid()); + EXPECT_TRUE(socket_for_client_result.has_value()); + EXPECT_TRUE(socket_for_client_result.value().IsValid()); + env_.Stop(); +} + TEST_P(AwdlTest, CanCancelConnect) { FeatureFlags feature_flags = GetParam(); env_.SetFeatureFlags(feature_flags); @@ -206,6 +258,115 @@ TEST_F(AwdlTest, CanStartAdvertising) { env_.Stop(); } +TEST_F(AwdlTest, StartAdvertisingFailsWithInvalidNsdServiceInfo) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + + EXPECT_TRUE(awdl_a.StartAcceptingConnections(service_id, {})); + + NsdServiceInfo nsd_service_info; + ErrorOr result = awdl_a.StartAdvertising(service_id, nsd_service_info); + EXPECT_FALSE(result.has_value()); + EXPECT_EQ(result.error().operation_result_code().value(), + location::nearby::proto::connections::OperationResultCode:: + MEDIUM_UNAVAILABLE_NSD_NOT_AVAILABLE); + env_.Stop(); +} + +TEST_F(AwdlTest, StopAdvertisingFailsIfNotAdvertising) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + + EXPECT_FALSE(awdl_a.StopAdvertising(service_id)); + env_.Stop(); +} + +TEST_F(AwdlTest, StartAdvertisingFailsIfAlreadyAdvertising) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + std::string service_info_name(kServiceInfoName); + std::string endpoint_info_name(kEndpointName); + + EXPECT_TRUE(awdl_a.StartAcceptingConnections(service_id, {})); + + NsdServiceInfo nsd_service_info; + nsd_service_info.SetServiceName(service_info_name); + nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey), + endpoint_info_name); + EXPECT_TRUE(awdl_a.StartAdvertising(service_id, nsd_service_info)); + ErrorOr result = awdl_a.StartAdvertising(service_id, nsd_service_info); + EXPECT_FALSE(result.has_value()); + EXPECT_EQ(result.error().operation_result_code().value(), + location::nearby::proto::connections::OperationResultCode:: + CLIENT_AWDL_DUPLICATE_ADVERTISING); + EXPECT_TRUE(awdl_a.StopAdvertising(service_id)); + env_.Stop(); +} + +TEST_F(AwdlTest, StartAdvertisingFailsIfNotAcceptingConnections) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + std::string service_info_name(kServiceInfoName); + std::string endpoint_info_name(kEndpointName); + + NsdServiceInfo nsd_service_info; + nsd_service_info.SetServiceName(service_info_name); + nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey), + endpoint_info_name); + ErrorOr result = awdl_a.StartAdvertising(service_id, nsd_service_info); + EXPECT_FALSE(result.has_value()); + EXPECT_EQ(result.error().operation_result_code().value(), + location::nearby::proto::connections::OperationResultCode:: + CLIENT_DUPLICATE_ACCEPTING_AWDL_CONNECTION_REQUEST); + env_.Stop(); +} + +TEST_F(AwdlTest, StartAdvertisingUpdatesNsdServiceInfo) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + std::string service_info_name(kServiceInfoName); + std::string endpoint_info_name(kEndpointName); + + EXPECT_TRUE(awdl_a.StartAcceptingConnections(service_id, {})); + + NsdServiceInfo nsd_service_info; + nsd_service_info.SetServiceName(service_info_name); + nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey), + endpoint_info_name); + EXPECT_TRUE(awdl_a.StartAdvertising(service_id, nsd_service_info)); + EXPECT_FALSE(nsd_service_info.GetServiceType().empty()); + EXPECT_FALSE(nsd_service_info.GetIPAddress().empty()); + EXPECT_GT(nsd_service_info.GetPort(), 0); + EXPECT_TRUE(awdl_a.StopAdvertising(service_id)); + env_.Stop(); +} + +TEST_F(AwdlTest, CanStartAcceptingConnectionsWithPsk) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + std::string service_info_name(kServiceInfoName); + std::string endpoint_info_name(kEndpointName); + api::PskInfo psk_info; + psk_info.password = "password"; + + EXPECT_TRUE(awdl_a.StartAcceptingConnections(service_id, psk_info, {})); + + NsdServiceInfo nsd_service_info; + nsd_service_info.SetServiceName(service_info_name); + nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey), + endpoint_info_name); + EXPECT_TRUE(awdl_a.StartAdvertising(service_id, nsd_service_info)); + EXPECT_EQ(awdl_a.GetCredentials(service_id).password, "password"); + EXPECT_TRUE(awdl_a.StopAdvertising(service_id)); + env_.Stop(); +} + TEST_F(AwdlTest, CanStartMultipleAdvertising) { env_.Start(); Awdl awdl_a; @@ -235,6 +396,32 @@ TEST_F(AwdlTest, CanStartMultipleAdvertising) { env_.Stop(); } +TEST_F(AwdlTest, StartAcceptingConnectionsFailsWithEmptyServiceId) { + env_.Start(); + Awdl awdl_a; + ErrorOr result = awdl_a.StartAcceptingConnections("", {}); + EXPECT_FALSE(result.has_value()); + EXPECT_EQ(result.error().operation_result_code().value(), + location::nearby::proto::connections::OperationResultCode:: + NEARBY_LOCAL_CLIENT_STATE_WRONG); + env_.Stop(); +} + +TEST_F(AwdlTest, StartAcceptingConnectionsFailsIfAlreadyAccepting) { + env_.Start(); + Awdl awdl_a; + std::string service_id(kServiceID); + + EXPECT_TRUE(awdl_a.StartAcceptingConnections(service_id, {})); + ErrorOr result = awdl_a.StartAcceptingConnections(service_id, {}); + EXPECT_FALSE(result.has_value()); + EXPECT_EQ(result.error().operation_result_code().value(), + location::nearby::proto::connections::OperationResultCode:: + CLIENT_DUPLICATE_ACCEPTING_AWDL_CONNECTION_REQUEST); + awdl_a.StopAcceptingConnections(service_id); + env_.Stop(); +} + TEST_F(AwdlTest, CanStartDiscovery) { env_.Start(); Awdl awdl_a; From 2e33e009e5976c5821bcb86c934fc73b8ba5337f Mon Sep 17 00:00:00 2001 From: hai007 Date: Mon, 2 Mar 2026 14:58:53 -0800 Subject: [PATCH 40/49] add detailed error codes for medium upgrade failures. PiperOrigin-RevId: 877593149 --- proto/connections_enums.proto | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/proto/connections_enums.proto b/proto/connections_enums.proto index a739b43b..db519643 100644 --- a/proto/connections_enums.proto +++ b/proto/connections_enums.proto @@ -1422,6 +1422,31 @@ enum OperationResultCode { DCT_ERROR_REMOTE_SERVICE_CANCELLED = 5047; // Failed to verify integrity on the remote device DCT_ERROR_REMOTE_UNVERIFIED_INTEGRITY = 5048; + // Failed to upgrade to high speed medium due to low speed + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_LOW_SPEED = 5049; + // Failed to upgrade to high speed medium due to connection error + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_CONNECTION = 5050; + // Failed to upgrade to high speed medium because USB is not plugged in + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_USB_NOT_PLUGGED = 5051; + // Failed to upgrade to high speed medium because USB is not host + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_USB_NOT_HOST = 5052; + // Failed to upgrade to high speed medium because MDNS discovery is not + // started + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_MDNS_DISCOVERY_NOT_STARTED = 5053; + // Failed to upgrade to high speed medium because MDNS discovery is not + // started + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_NO_MEDIUM = 5054; + // Failed to upgrade to high speed medium because USB network is not started + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_USB_NETWORK_NOT_STARTED = 5055; + // Failed to upgrade to high speed medium because medium negotiation fails + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_MEDIUM_NEGOTIATION = 5056; + // Failed to upgrade to high speed medium because host fails to start + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_HOST_NOT_STARTED = 5057; + // Failed to upgrade to high speed medium because host network is not + // available + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_HOST_NETWORK_NOT_AVAILABLE = 5058; + // Failed to upgrade to high speed medium because no incoming HTTP connection + DCT_ERROR_UPGRADE_HIGH_SPEED_MEDIUM_FAILED_NO_INCOMING_HTTP_CONNECTION = 5059; } enum StopAdvertisingReason { From 93cb147c8227f9640e7125594b65f87fdf7510b4 Mon Sep 17 00:00:00 2001 From: Anay Wadhera Date: Mon, 2 Mar 2026 15:24:42 -0800 Subject: [PATCH 41/49] add folder attachment type PiperOrigin-RevId: 877603768 --- sharing/proto/analytics/nearby_sharing_log.proto | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sharing/proto/analytics/nearby_sharing_log.proto b/sharing/proto/analytics/nearby_sharing_log.proto index 7196bb20..0f7b30f6 100644 --- a/sharing/proto/analytics/nearby_sharing_log.proto +++ b/sharing/proto/analytics/nearby_sharing_log.proto @@ -894,6 +894,7 @@ message SharingLog { repeated WifiCredentialsAttachment wifi_credentials_attachment = 4; repeated AppAttachment app_attachment = 5; repeated StreamAttachment stream_attachment = 6; + repeated FolderAttachment folder_attachment = 7; } message TextAttachment { @@ -970,6 +971,8 @@ message SharingLog { optional int64 duration_millis = 8; } + message FolderAttachment {} + // EventType: APP_CRASH // Used only for Nearby Share Windows App now message AppCrash { From 115fa39dd3f22670f7337e2eb4de7f5c63e5b10c Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Tue, 3 Mar 2026 14:23:33 -0800 Subject: [PATCH 42/49] Add new rpcs. PiperOrigin-RevId: 878124598 --- ...rby_share_certificate_manager_impl_test.cc | 6 +- sharing/internal/api/BUILD | 2 + .../internal/api/fake_nearby_share_client.cc | 83 ++++++++++++ .../internal/api/fake_nearby_share_client.h | 128 +++++++++++++++++- sharing/internal/api/sharing_rpc_client.h | 31 +++++ 5 files changed, 242 insertions(+), 8 deletions(-) diff --git a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc index 544bc0df..bb826146 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc @@ -243,9 +243,11 @@ class NearbyShareCertificateManagerImplTest void VerifyCertificatesUpload(bool expected_force_update_contacts) { FakeNearbyIdentityClient* identity_client = GetIdentityClient(); - ASSERT_FALSE(identity_client->publish_device_requests().empty()); + std::vector publish_device_requests = + identity_client->publish_device_requests(); + ASSERT_FALSE(publish_device_requests.empty()); const PublishDeviceRequest& publish_device_request = - identity_client->publish_device_requests().back(); + publish_device_requests.back(); EXPECT_EQ(publish_device_request.device().name(), absl::StrCat("devices/", kDeviceId)); EXPECT_EQ(publish_device_request.device() diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index 7efa83c8..7e1f6eb2 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -39,6 +39,7 @@ cc_library( "//sharing:__subpackages__", ], deps = [ + "//google/nearby/identity/v1:binding_cc_proto", "//google/nearby/identity/v1:rpcs_cc_proto", "//internal/base:file_path", "//internal/platform:mac_address", @@ -75,6 +76,7 @@ cc_library( visibility = ["//visibility:public"], deps = [ ":platform", + "//google/nearby/identity/v1:binding_cc_proto", "//internal/base:file_path", "//internal/platform:mac_address", "//internal/platform:types", diff --git a/sharing/internal/api/fake_nearby_share_client.cc b/sharing/internal/api/fake_nearby_share_client.cc index 9ddc685b..61b7acd8 100644 --- a/sharing/internal/api/fake_nearby_share_client.cc +++ b/sharing/internal/api/fake_nearby_share_client.cc @@ -17,6 +17,7 @@ #include #include +#include "google/nearby/identity/v1/binding.pb.h" #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "absl/status/statusor.h" @@ -36,12 +37,23 @@ using ::google::nearby::identity::v1::PublishDeviceRequest; using ::google::nearby::identity::v1::PublishDeviceResponse; using ::google::nearby::identity::v1::QuerySharedCredentialsRequest; using ::google::nearby::identity::v1::QuerySharedCredentialsResponse; +using ::google::nearby::identity::v1:: + QuerySharedCredentialsWithBindingIdsRequest; +using ::google::nearby::identity::v1:: + QuerySharedCredentialsWithBindingIdsResponse; +using ::google::nearby::identity::v1::InitiateBindingRequest; +using ::google::nearby::identity::v1::InitiateBindingResponse; +using ::google::nearby::identity::v1::JoinBindingRequest; +using ::google::nearby::identity::v1::JoinBindingResponse; +using ::google::nearby::identity::v1::DeleteBindingRequest; +using ::google::nearby::identity::v1::DeleteBindingResponse; void FakeNearbyShareClient::ListContactPeople( proto::ListContactPeopleRequest request, absl::AnyInvocable& response) &&> callback) { + absl::MutexLock lock(mutex_); list_contact_people_requests_.emplace_back(request); if (list_contact_people_responses_.empty()) { std::move(callback)(absl::NotFoundError("")); @@ -52,6 +64,57 @@ void FakeNearbyShareClient::ListContactPeople( std::move(callback)(response); } +void FakeNearbyShareClient::InitiateBinding( + InitiateBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) { + absl::StatusOr response = absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + initiate_binding_requests_.emplace_back(request); + if (!initiate_binding_responses_.empty()) { + response = initiate_binding_responses_[0]; + initiate_binding_responses_.erase(initiate_binding_responses_.begin()); + } + } + std::move(callback)(response); +} + +void FakeNearbyShareClient::JoinBinding( + JoinBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) { + absl::StatusOr response = absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + join_binding_requests_.emplace_back(request); + if (!join_binding_responses_.empty()) { + response = join_binding_responses_[0]; + join_binding_responses_.erase(join_binding_responses_.begin()); + } + } + std::move(callback)(response); +} + +void FakeNearbyShareClient::DeleteBinding( + DeleteBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) { + absl::StatusOr response = absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + delete_binding_requests_.emplace_back(request); + if (!delete_binding_responses_.empty()) { + response = delete_binding_responses_[0]; + delete_binding_responses_.erase(delete_binding_responses_.begin()); + } + } + std::move(callback)(response); +} + void FakeNearbyIdentityClient::QuerySharedCredentials( QuerySharedCredentialsRequest request, absl::AnyInvocable< @@ -102,6 +165,26 @@ void FakeNearbyIdentityClient::GetAccountInfo( std::move(callback)(response); } +void FakeNearbyIdentityClient::QuerySharedCredentialsWithBindingIds( + QuerySharedCredentialsWithBindingIdsRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& + response) &&> + callback) { + absl::StatusOr response = + absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + query_shared_credentials_with_binding_ids_requests_.emplace_back(request); + if (!query_shared_credentials_with_binding_ids_responses_.empty()) { + response = query_shared_credentials_with_binding_ids_responses_[0]; + query_shared_credentials_with_binding_ids_responses_.erase( + query_shared_credentials_with_binding_ids_responses_.begin()); + } + } + std::move(callback)(response); +} + std::unique_ptr FakeNearbyShareClientFactory::CreateInstance() { auto instance = std::make_unique(); diff --git a/sharing/internal/api/fake_nearby_share_client.h b/sharing/internal/api/fake_nearby_share_client.h index 8b570918..487bef0b 100644 --- a/sharing/internal/api/fake_nearby_share_client.h +++ b/sharing/internal/api/fake_nearby_share_client.h @@ -37,13 +37,15 @@ class FakeNearbyShareClient : public nearby::sharing::api::SharingRpcClient { FakeNearbyShareClient() = default; ~FakeNearbyShareClient() override = default; - std::vector& + std::vector list_contact_people_requests() { + absl::MutexLock lock(mutex_); return list_contact_people_requests_; } void SetListContactPeopleResponses( std::vector> responses) { + absl::MutexLock lock(mutex_); list_contact_people_responses_ = responses; } @@ -53,10 +55,89 @@ class FakeNearbyShareClient : public nearby::sharing::api::SharingRpcClient { const absl::StatusOr& response) &&> callback) override; + std::vector + initiate_binding_requests() { + absl::MutexLock lock(mutex_); + return initiate_binding_requests_; + } + + void SetInitiateBindingResponses( + std::vector> + responses) { + absl::MutexLock lock(mutex_); + initiate_binding_responses_ = responses; + } + + void InitiateBinding( + google::nearby::identity::v1::InitiateBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) override; + + std::vector + join_binding_requests() { + absl::MutexLock lock(mutex_); + return join_binding_requests_; + } + + void SetJoinBindingResponses( + std::vector> + responses) { + absl::MutexLock lock(mutex_); + join_binding_responses_ = responses; + } + + void JoinBinding( + google::nearby::identity::v1::JoinBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) override; + + std::vector + delete_binding_requests() { + absl::MutexLock lock(mutex_); + return delete_binding_requests_; + } + + void SetDeleteBindingResponses( + std::vector> + responses) { + absl::MutexLock lock(mutex_); + delete_binding_responses_ = responses; + } + + void DeleteBinding( + google::nearby::identity::v1::DeleteBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) override; + + private: + absl::Mutex mutex_; std::vector - list_contact_people_requests_; + list_contact_people_requests_ ABSL_GUARDED_BY(mutex_); std::vector> - list_contact_people_responses_; + list_contact_people_responses_ ABSL_GUARDED_BY(mutex_); + std::vector + initiate_binding_requests_ ABSL_GUARDED_BY(mutex_); + std::vector< + absl::StatusOr> + initiate_binding_responses_ ABSL_GUARDED_BY(mutex_); + std::vector + join_binding_requests_ ABSL_GUARDED_BY(mutex_); + std::vector> + join_binding_responses_ ABSL_GUARDED_BY(mutex_); + std::vector + delete_binding_requests_ ABSL_GUARDED_BY(mutex_); + std::vector< + absl::StatusOr> + delete_binding_responses_ ABSL_GUARDED_BY(mutex_); }; // A fake implementation of the Nearby Identity RPC client that stores all @@ -67,13 +148,13 @@ class FakeNearbyIdentityClient FakeNearbyIdentityClient() = default; ~FakeNearbyIdentityClient() override = default; - std::vector& + std::vector publish_device_requests() ABSL_LOCKS_EXCLUDED(mutex_) { absl::MutexLock lock(mutex_); return publish_device_requests_; } - std::vector& + std::vector query_shared_credentials_requests() ABSL_LOCKS_EXCLUDED(mutex_) { absl::MutexLock lock(mutex_); return query_shared_credentials_requests_; @@ -110,7 +191,7 @@ class FakeNearbyIdentityClient query_shared_credentials_responses_ = responses; } - std::vector& + std::vector get_account_info_requests() ABSL_LOCKS_EXCLUDED(mutex_) { absl::MutexLock lock(mutex_); return get_account_info_requests_; @@ -130,6 +211,32 @@ class FakeNearbyIdentityClient get_account_info_response_ = response; } + std::vector + query_shared_credentials_with_binding_ids_requests() + ABSL_LOCKS_EXCLUDED(mutex_) { + absl::MutexLock lock(mutex_); + return query_shared_credentials_with_binding_ids_requests_; + } + + void QuerySharedCredentialsWithBindingIds( + google::nearby::identity::v1::QuerySharedCredentialsWithBindingIdsRequest + request, + absl::AnyInvocable< + void(const absl::StatusOr< + google::nearby::identity::v1:: + QuerySharedCredentialsWithBindingIdsResponse>& response) &&> + callback) ABSL_LOCKS_EXCLUDED(mutex_) override; + + void SetQuerySharedCredentialsWithBindingIdsResponse( + std::vector> + responses) ABSL_LOCKS_EXCLUDED(mutex_) { + absl::MutexLock lock(mutex_); + query_shared_credentials_with_binding_ids_responses_ = responses; + } + private: absl::Mutex mutex_; std::vector @@ -148,6 +255,15 @@ class FakeNearbyIdentityClient get_account_info_requests_ ABSL_GUARDED_BY(mutex_); absl::StatusOr get_account_info_response_ ABSL_GUARDED_BY(mutex_); + + std::vector< + google::nearby::identity::v1::QuerySharedCredentialsWithBindingIdsRequest> + query_shared_credentials_with_binding_ids_requests_ + ABSL_GUARDED_BY(mutex_); + std::vector> + query_shared_credentials_with_binding_ids_responses_ + ABSL_GUARDED_BY(mutex_); }; class FakeNearbyShareClientFactory diff --git a/sharing/internal/api/sharing_rpc_client.h b/sharing/internal/api/sharing_rpc_client.h index 374d50b3..7dcb91e6 100644 --- a/sharing/internal/api/sharing_rpc_client.h +++ b/sharing/internal/api/sharing_rpc_client.h @@ -17,6 +17,7 @@ #include +#include "google/nearby/identity/v1/binding.pb.h" #include "google/nearby/identity/v1/rpcs.pb.h" #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" @@ -53,6 +54,15 @@ class IdentityRpcClient { void(const absl::StatusOr& response) &&> callback) = 0; + + virtual void QuerySharedCredentialsWithBindingIds( + google::nearby::identity::v1::QuerySharedCredentialsWithBindingIdsRequest + request, + absl::AnyInvocable< + void(const absl::StatusOr< + google::nearby::identity::v1:: + QuerySharedCredentialsWithBindingIdsResponse>& response) &&> + callback) = 0; }; // SharingRpcClient is used to access Nearby Share backend APIs. @@ -67,6 +77,27 @@ class SharingRpcClient { absl::AnyInvocable& response) &&> callback) = 0; + + virtual void InitiateBinding( + google::nearby::identity::v1::InitiateBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) = 0; + + virtual void JoinBinding( + google::nearby::identity::v1::JoinBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) = 0; + + virtual void DeleteBinding( + google::nearby::identity::v1::DeleteBindingRequest request, + absl::AnyInvocable< + void(const absl::StatusOr& response) &&> + callback) = 0; }; // Interface for creating SharingRpcClient instances. Because each From f79846c4317abfd242b18bd6ce5f811a2f3f4131 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Tue, 3 Mar 2026 14:48:29 -0800 Subject: [PATCH 43/49] Remove rpc client from sharing platform. PiperOrigin-RevId: 878135348 --- sharing/BUILD | 2 + sharing/certificates/BUILD | 6 +- .../fake_nearby_share_certificate_manager.cc | 2 +- .../fake_nearby_share_certificate_manager.h | 2 +- .../nearby_share_certificate_manager_impl.cc | 2 +- .../nearby_share_certificate_manager_impl.h | 3 +- ...rby_share_certificate_manager_impl_test.cc | 3 +- sharing/contacts/BUILD | 4 +- .../nearby_share_contact_manager_impl.cc | 2 +- .../nearby_share_contact_manager_impl.h | 2 +- .../nearby_share_contact_manager_impl_test.cc | 3 +- sharing/internal/api/BUILD | 8 - .../internal/api/fake_nearby_share_client.cc | 203 ------------ .../internal/api/fake_nearby_share_client.h | 297 ------------------ sharing/internal/api/mock_sharing_platform.h | 8 - sharing/internal/api/sharing_platform.h | 8 - sharing/internal/api/sharing_rpc_client.h | 117 ------- sharing/nearby_sharing_service_factory.cc | 6 +- sharing/nearby_sharing_service_impl.cc | 2 +- sharing/nearby_sharing_service_impl.h | 2 +- 20 files changed, 21 insertions(+), 661 deletions(-) delete mode 100644 sharing/internal/api/fake_nearby_share_client.cc delete mode 100644 sharing/internal/api/fake_nearby_share_client.h delete mode 100644 sharing/internal/api/sharing_rpc_client.h diff --git a/sharing/BUILD b/sharing/BUILD index 2d00e45d..028ac35b 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -382,6 +382,8 @@ cc_library( "//internal/platform:types", "//internal/platform/implementation:account_manager", "//internal/platform/implementation:types", + "//location/nearby/sharing/lib/rpc:grpc_async_client_factory", + "//location/nearby/sharing/lib/rpc:sharing_rpc_client", "//proto:sharing_enums_cc_proto", "//sharing/analytics", "//sharing/certificates", diff --git a/sharing/certificates/BUILD b/sharing/certificates/BUILD index e303ab1e..f18cfbd8 100644 --- a/sharing/certificates/BUILD +++ b/sharing/certificates/BUILD @@ -51,7 +51,7 @@ cc_library( "//internal/platform:mac_address", "//internal/platform:types", "//internal/platform/implementation:account_manager", - "//sharing/common", + "//location/nearby/sharing/lib/rpc:sharing_rpc_client", "//sharing/internal/api:platform", "//sharing/internal/base", "//sharing/internal/public:logging", @@ -97,6 +97,7 @@ cc_library( "//internal/base:bluetooth_address", "//internal/base:file_path", "//internal/crypto_cros", + "//location/nearby/sharing/lib/rpc:sharing_rpc_client", "//sharing/common:enum", "//sharing/internal/api:platform", "//sharing/internal/public:types", @@ -129,7 +130,7 @@ cc_test( "//internal/platform/implementation:account_manager", "//internal/platform/implementation:platform_impl", "//internal/test", - "//sharing/common", + "//location/nearby/sharing/lib/rpc:fake_nearby_share_client", "//sharing/common:enum", "//sharing/internal/api:mock_sharing_platform", "//sharing/internal/api:platform", @@ -141,7 +142,6 @@ cc_test( "//sharing/scheduling", "//sharing/scheduling:test_support", "@com_github_protobuf_matchers//protobuf-matchers", - "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/functional:any_invocable", "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", diff --git a/sharing/certificates/fake_nearby_share_certificate_manager.cc b/sharing/certificates/fake_nearby_share_certificate_manager.cc index 5a6ba7d9..7895eda6 100644 --- a/sharing/certificates/fake_nearby_share_certificate_manager.cc +++ b/sharing/certificates/fake_nearby_share_certificate_manager.cc @@ -23,12 +23,12 @@ #include #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "internal/base/file_path.h" #include "sharing/certificates/nearby_share_certificate_manager.h" #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" #include "sharing/certificates/test_util.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/enums.pb.h" diff --git a/sharing/certificates/fake_nearby_share_certificate_manager.h b/sharing/certificates/fake_nearby_share_certificate_manager.h index 0ceb98b3..0a5c8f24 100644 --- a/sharing/certificates/fake_nearby_share_certificate_manager.h +++ b/sharing/certificates/fake_nearby_share_certificate_manager.h @@ -24,12 +24,12 @@ #include #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "internal/base/file_path.h" #include "sharing/certificates/nearby_share_certificate_manager.h" #include "sharing/certificates/nearby_share_certificate_manager_impl.h" #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/rpc_resources.pb.h" diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.cc b/sharing/certificates/nearby_share_certificate_manager_impl.cc index e3b02823..a79283d3 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl.cc @@ -31,6 +31,7 @@ #include "google/nearby/identity/v1/resources.pb.h" #include "google/nearby/identity/v1/rpcs.pb.h" #include "google/protobuf/timestamp.pb.h" +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "absl/algorithm/algorithm.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" @@ -56,7 +57,6 @@ #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/public_certificate_database.h" #include "sharing/internal/api/sharing_platform.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/base/encode.h" #include "sharing/internal/public/context.h" #include "sharing/internal/public/logging.h" diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.h b/sharing/certificates/nearby_share_certificate_manager_impl.h index 68d5adbc..a94598c4 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.h +++ b/sharing/certificates/nearby_share_certificate_manager_impl.h @@ -23,6 +23,7 @@ #include #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "absl/base/nullability.h" #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" @@ -37,7 +38,6 @@ #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/public_certificate_database.h" #include "sharing/internal/api/sharing_platform.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/enums.pb.h" @@ -197,7 +197,6 @@ class NearbyShareCertificateManagerImpl NearbyShareLocalDeviceDataManager* const local_device_data_manager_; nearby::sharing::api::PreferenceManager& preference_manager_; int32_t vendor_id_ = 0; // Defaults to GOOGLE. - std::unique_ptr nearby_client_; std::unique_ptr nearby_identity_client_; diff --git a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc index bb826146..cf4b5b24 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc @@ -27,10 +27,10 @@ #include "google/nearby/identity/v1/resources.pb.h" #include "google/nearby/identity/v1/rpcs.pb.h" +#include "location/nearby/sharing/lib/rpc/fake_nearby_share_client.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" -#include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" @@ -48,7 +48,6 @@ #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" #include "sharing/certificates/test_util.h" -#include "sharing/internal/api/fake_nearby_share_client.h" #include "sharing/internal/api/mock_sharing_platform.h" #include "sharing/internal/public/pref_names.h" #include "sharing/internal/test/fake_bluetooth_adapter.h" diff --git a/sharing/contacts/BUILD b/sharing/contacts/BUILD index d2848a3e..63c23367 100644 --- a/sharing/contacts/BUILD +++ b/sharing/contacts/BUILD @@ -43,7 +43,7 @@ cc_library( ":contacts_interface", "//internal/platform:types", "//internal/platform/implementation:account_manager", - "//sharing/internal/api:platform", + "//location/nearby/sharing/lib/rpc:sharing_rpc_client", "//sharing/internal/public:logging", "//sharing/internal/public:types", "//sharing/proto:share_cc_proto", @@ -72,7 +72,7 @@ cc_test( "//internal/platform/implementation:account_manager", "//internal/platform/implementation:platform_impl", "//internal/test", - "//sharing/internal/api:mock_sharing_platform", + "//location/nearby/sharing/lib/rpc:fake_nearby_share_client", "//sharing/internal/test:nearby_test", "//sharing/local_device_data:test_support", "//sharing/proto:share_cc_proto", diff --git a/sharing/contacts/nearby_share_contact_manager_impl.cc b/sharing/contacts/nearby_share_contact_manager_impl.cc index dfa1c28f..43244f96 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl.cc +++ b/sharing/contacts/nearby_share_contact_manager_impl.cc @@ -23,11 +23,11 @@ #include #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "absl/status/statusor.h" #include "absl/synchronization/notification.h" #include "internal/platform/implementation/account_manager.h" #include "sharing/contacts/nearby_share_contact_manager.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/internal/public/logging.h" #include "sharing/proto/contact_rpc.pb.h" diff --git a/sharing/contacts/nearby_share_contact_manager_impl.h b/sharing/contacts/nearby_share_contact_manager_impl.h index e6ad10bc..b40ef772 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl.h +++ b/sharing/contacts/nearby_share_contact_manager_impl.h @@ -17,10 +17,10 @@ #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "internal/platform/implementation/account_manager.h" #include "internal/platform/task_runner.h" #include "sharing/contacts/nearby_share_contact_manager.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" namespace nearby { diff --git a/sharing/contacts/nearby_share_contact_manager_impl_test.cc b/sharing/contacts/nearby_share_contact_manager_impl_test.cc index e9f5d345..7f246d6f 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl_test.cc +++ b/sharing/contacts/nearby_share_contact_manager_impl_test.cc @@ -18,15 +18,14 @@ #include #include -#include #include #include +#include "location/nearby/sharing/lib/rpc/fake_nearby_share_client.h" #include "gtest/gtest.h" #include "absl/time/time.h" #include "internal/platform/implementation/account_manager.h" #include "internal/test/fake_account_manager.h" -#include "sharing/internal/api/fake_nearby_share_client.h" #include "sharing/internal/test/fake_context.h" #include "sharing/local_device_data/fake_nearby_share_local_device_data_manager.h" #include "sharing/proto/contact_rpc.pb.h" diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index 7e1f6eb2..a0e132ed 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -28,7 +28,6 @@ cc_library( "private_certificate_data.h", "public_certificate_database.h", "sharing_platform.h", - "sharing_rpc_client.h", "system_info.h", ], visibility = [ @@ -39,8 +38,6 @@ cc_library( "//sharing:__subpackages__", ], deps = [ - "//google/nearby/identity/v1:binding_cc_proto", - "//google/nearby/identity/v1:rpcs_cc_proto", "//internal/base:file_path", "//internal/platform:mac_address", "//internal/platform:types", @@ -59,11 +56,7 @@ cc_library( cc_library( name = "mock_sharing_platform", testonly = True, - srcs = [ - "fake_nearby_share_client.cc", - ], hdrs = [ - "fake_nearby_share_client.h", "mock_app_info.h", "mock_bluetooth_adapter.h", "mock_fast_init_ble_beacon.h", @@ -76,7 +69,6 @@ cc_library( visibility = ["//visibility:public"], deps = [ ":platform", - "//google/nearby/identity/v1:binding_cc_proto", "//internal/base:file_path", "//internal/platform:mac_address", "//internal/platform:types", diff --git a/sharing/internal/api/fake_nearby_share_client.cc b/sharing/internal/api/fake_nearby_share_client.cc deleted file mode 100644 index 61b7acd8..00000000 --- a/sharing/internal/api/fake_nearby_share_client.cc +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 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 "sharing/internal/api/fake_nearby_share_client.h" - -#include -#include - -#include "google/nearby/identity/v1/binding.pb.h" -#include "absl/functional/any_invocable.h" -#include "absl/status/status.h" -#include "absl/status/statusor.h" -#include "absl/synchronization/mutex.h" -#include "sharing/internal/api/sharing_rpc_client.h" -#include "sharing/internal/public/logging.h" -#include "sharing/proto/certificate_rpc.pb.h" -#include "sharing/proto/contact_rpc.pb.h" -#include "sharing/proto/device_rpc.pb.h" - -namespace nearby { -namespace sharing { - -using ::google::nearby::identity::v1::GetAccountInfoRequest; -using ::google::nearby::identity::v1::GetAccountInfoResponse; -using ::google::nearby::identity::v1::PublishDeviceRequest; -using ::google::nearby::identity::v1::PublishDeviceResponse; -using ::google::nearby::identity::v1::QuerySharedCredentialsRequest; -using ::google::nearby::identity::v1::QuerySharedCredentialsResponse; -using ::google::nearby::identity::v1:: - QuerySharedCredentialsWithBindingIdsRequest; -using ::google::nearby::identity::v1:: - QuerySharedCredentialsWithBindingIdsResponse; -using ::google::nearby::identity::v1::InitiateBindingRequest; -using ::google::nearby::identity::v1::InitiateBindingResponse; -using ::google::nearby::identity::v1::JoinBindingRequest; -using ::google::nearby::identity::v1::JoinBindingResponse; -using ::google::nearby::identity::v1::DeleteBindingRequest; -using ::google::nearby::identity::v1::DeleteBindingResponse; - -void FakeNearbyShareClient::ListContactPeople( - proto::ListContactPeopleRequest request, - absl::AnyInvocable& response) &&> - callback) { - absl::MutexLock lock(mutex_); - list_contact_people_requests_.emplace_back(request); - if (list_contact_people_responses_.empty()) { - std::move(callback)(absl::NotFoundError("")); - return; - } - auto response = list_contact_people_responses_[0]; - list_contact_people_responses_.erase(list_contact_people_responses_.begin()); - std::move(callback)(response); -} - -void FakeNearbyShareClient::InitiateBinding( - InitiateBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) { - absl::StatusOr response = absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - initiate_binding_requests_.emplace_back(request); - if (!initiate_binding_responses_.empty()) { - response = initiate_binding_responses_[0]; - initiate_binding_responses_.erase(initiate_binding_responses_.begin()); - } - } - std::move(callback)(response); -} - -void FakeNearbyShareClient::JoinBinding( - JoinBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) { - absl::StatusOr response = absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - join_binding_requests_.emplace_back(request); - if (!join_binding_responses_.empty()) { - response = join_binding_responses_[0]; - join_binding_responses_.erase(join_binding_responses_.begin()); - } - } - std::move(callback)(response); -} - -void FakeNearbyShareClient::DeleteBinding( - DeleteBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) { - absl::StatusOr response = absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - delete_binding_requests_.emplace_back(request); - if (!delete_binding_responses_.empty()) { - response = delete_binding_responses_[0]; - delete_binding_responses_.erase(delete_binding_responses_.begin()); - } - } - std::move(callback)(response); -} - -void FakeNearbyIdentityClient::QuerySharedCredentials( - QuerySharedCredentialsRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) { - absl::StatusOr response = - absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - query_shared_credentials_requests_.emplace_back(request); - if (!query_shared_credentials_responses_.empty()) { - response = query_shared_credentials_responses_[0]; - query_shared_credentials_responses_.erase( - query_shared_credentials_responses_.begin()); - } - } - std::move(callback)(response); -} - -void FakeNearbyIdentityClient::PublishDevice( - PublishDeviceRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) { - absl::StatusOr response = absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - publish_device_requests_.emplace_back(request); - if (!publish_device_responses_.empty()) { - response = publish_device_responses_[0]; - publish_device_responses_.erase(publish_device_responses_.begin()); - } - } - std::move(callback)(response); -} - -void FakeNearbyIdentityClient::GetAccountInfo( - GetAccountInfoRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) { - absl::StatusOr response = absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - get_account_info_requests_.emplace_back(request); - response = get_account_info_response_; - } - std::move(callback)(response); -} - -void FakeNearbyIdentityClient::QuerySharedCredentialsWithBindingIds( - QuerySharedCredentialsWithBindingIdsRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& - response) &&> - callback) { - absl::StatusOr response = - absl::NotFoundError(""); - { - absl::MutexLock lock(mutex_); - query_shared_credentials_with_binding_ids_requests_.emplace_back(request); - if (!query_shared_credentials_with_binding_ids_responses_.empty()) { - response = query_shared_credentials_with_binding_ids_responses_[0]; - query_shared_credentials_with_binding_ids_responses_.erase( - query_shared_credentials_with_binding_ids_responses_.begin()); - } - } - std::move(callback)(response); -} - -std::unique_ptr -FakeNearbyShareClientFactory::CreateInstance() { - auto instance = std::make_unique(); - instances_.push_back(instance.get()); - return instance; -} - -std::unique_ptr -FakeNearbyShareClientFactory::CreateIdentityInstance() { - auto instance = std::make_unique(); - identity_instances_.push_back(instance.get()); - return instance; -} - -} // namespace sharing -} // namespace nearby diff --git a/sharing/internal/api/fake_nearby_share_client.h b/sharing/internal/api/fake_nearby_share_client.h deleted file mode 100644 index 487bef0b..00000000 --- a/sharing/internal/api/fake_nearby_share_client.h +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright 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 THIRD_PARTY_NEARBY_SHARING_INTERNAL_API_FAKE_NEARBY_SHARE_CLIENT_H_ -#define THIRD_PARTY_NEARBY_SHARING_INTERNAL_API_FAKE_NEARBY_SHARE_CLIENT_H_ - -#include -#include - -#include "absl/base/thread_annotations.h" -#include "absl/functional/any_invocable.h" -#include "absl/status/statusor.h" -#include "absl/synchronization/mutex.h" -#include "sharing/internal/api/sharing_rpc_client.h" -#include "sharing/proto/certificate_rpc.pb.h" -#include "sharing/proto/contact_rpc.pb.h" -#include "sharing/proto/device_rpc.pb.h" - -namespace nearby { -namespace sharing { - -// A fake implementation of the Nearby Share HTTP client that stores all request -// data. Only use in unit tests. -class FakeNearbyShareClient : public nearby::sharing::api::SharingRpcClient { - public: - FakeNearbyShareClient() = default; - ~FakeNearbyShareClient() override = default; - - std::vector - list_contact_people_requests() { - absl::MutexLock lock(mutex_); - return list_contact_people_requests_; - } - - void SetListContactPeopleResponses( - std::vector> responses) { - absl::MutexLock lock(mutex_); - list_contact_people_responses_ = responses; - } - - void ListContactPeople( - proto::ListContactPeopleRequest request, - absl::AnyInvocable& response) &&> - callback) override; - - std::vector - initiate_binding_requests() { - absl::MutexLock lock(mutex_); - return initiate_binding_requests_; - } - - void SetInitiateBindingResponses( - std::vector> - responses) { - absl::MutexLock lock(mutex_); - initiate_binding_responses_ = responses; - } - - void InitiateBinding( - google::nearby::identity::v1::InitiateBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) override; - - std::vector - join_binding_requests() { - absl::MutexLock lock(mutex_); - return join_binding_requests_; - } - - void SetJoinBindingResponses( - std::vector> - responses) { - absl::MutexLock lock(mutex_); - join_binding_responses_ = responses; - } - - void JoinBinding( - google::nearby::identity::v1::JoinBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) override; - - std::vector - delete_binding_requests() { - absl::MutexLock lock(mutex_); - return delete_binding_requests_; - } - - void SetDeleteBindingResponses( - std::vector> - responses) { - absl::MutexLock lock(mutex_); - delete_binding_responses_ = responses; - } - - void DeleteBinding( - google::nearby::identity::v1::DeleteBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) override; - - private: - absl::Mutex mutex_; - std::vector - list_contact_people_requests_ ABSL_GUARDED_BY(mutex_); - std::vector> - list_contact_people_responses_ ABSL_GUARDED_BY(mutex_); - std::vector - initiate_binding_requests_ ABSL_GUARDED_BY(mutex_); - std::vector< - absl::StatusOr> - initiate_binding_responses_ ABSL_GUARDED_BY(mutex_); - std::vector - join_binding_requests_ ABSL_GUARDED_BY(mutex_); - std::vector> - join_binding_responses_ ABSL_GUARDED_BY(mutex_); - std::vector - delete_binding_requests_ ABSL_GUARDED_BY(mutex_); - std::vector< - absl::StatusOr> - delete_binding_responses_ ABSL_GUARDED_BY(mutex_); -}; - -// A fake implementation of the Nearby Identity RPC client that stores all -// request data. Only use in unit tests. -class FakeNearbyIdentityClient - : public nearby::sharing::api::IdentityRpcClient { - public: - FakeNearbyIdentityClient() = default; - ~FakeNearbyIdentityClient() override = default; - - std::vector - publish_device_requests() ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - return publish_device_requests_; - } - - std::vector - query_shared_credentials_requests() ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - return query_shared_credentials_requests_; - } - - void PublishDevice( - google::nearby::identity::v1::PublishDeviceRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) ABSL_LOCKS_EXCLUDED(mutex_) override; - - void SetPublishDeviceResponses( - std::vector< - absl::StatusOr> - responses) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - publish_device_responses_ = responses; - } - - void QuerySharedCredentials( - google::nearby::identity::v1::QuerySharedCredentialsRequest request, - absl::AnyInvocable< - void(const absl::StatusOr< - google::nearby::identity::v1::QuerySharedCredentialsResponse>& - response) &&> - callback) ABSL_LOCKS_EXCLUDED(mutex_) override; - - void SetQuerySharedCredentialsResponses( - std::vector> - responses) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - query_shared_credentials_responses_ = responses; - } - - std::vector - get_account_info_requests() ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - return get_account_info_requests_; - } - - void GetAccountInfo( - google::nearby::identity::v1::GetAccountInfoRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) ABSL_LOCKS_EXCLUDED(mutex_) override; - - void SetGetAccountInfoResponse( - absl::StatusOr - response) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - get_account_info_response_ = response; - } - - std::vector - query_shared_credentials_with_binding_ids_requests() - ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - return query_shared_credentials_with_binding_ids_requests_; - } - - void QuerySharedCredentialsWithBindingIds( - google::nearby::identity::v1::QuerySharedCredentialsWithBindingIdsRequest - request, - absl::AnyInvocable< - void(const absl::StatusOr< - google::nearby::identity::v1:: - QuerySharedCredentialsWithBindingIdsResponse>& response) &&> - callback) ABSL_LOCKS_EXCLUDED(mutex_) override; - - void SetQuerySharedCredentialsWithBindingIdsResponse( - std::vector> - responses) ABSL_LOCKS_EXCLUDED(mutex_) { - absl::MutexLock lock(mutex_); - query_shared_credentials_with_binding_ids_responses_ = responses; - } - - private: - absl::Mutex mutex_; - std::vector - publish_device_requests_ ABSL_GUARDED_BY(mutex_); - std::vector< - absl::StatusOr> - publish_device_responses_ ABSL_GUARDED_BY(mutex_); - - std::vector - query_shared_credentials_requests_ ABSL_GUARDED_BY(mutex_); - std::vector> - query_shared_credentials_responses_ ABSL_GUARDED_BY(mutex_); - - std::vector - get_account_info_requests_ ABSL_GUARDED_BY(mutex_); - absl::StatusOr - get_account_info_response_ ABSL_GUARDED_BY(mutex_); - - std::vector< - google::nearby::identity::v1::QuerySharedCredentialsWithBindingIdsRequest> - query_shared_credentials_with_binding_ids_requests_ - ABSL_GUARDED_BY(mutex_); - std::vector> - query_shared_credentials_with_binding_ids_responses_ - ABSL_GUARDED_BY(mutex_); -}; - -class FakeNearbyShareClientFactory - : public nearby::sharing::api::SharingRpcClientFactory { - public: - FakeNearbyShareClientFactory() = default; - ~FakeNearbyShareClientFactory() override = default; - - public: - // Returns all FakeNearbyShareClient instances created by CreateInstance(). - std::vector& instances() { return instances_; } - std::vector& identity_instances() { - return identity_instances_; - } - - private: - // SharingRpcClientFactory: - std::unique_ptr CreateInstance() - override; - - std::unique_ptr - CreateIdentityInstance() override; - - std::vector instances_; - std::vector identity_instances_; -}; - -} // namespace sharing -} // namespace nearby - -#endif // THIRD_PARTY_NEARBY_SHARING_INTERNAL_API_FAKE_NEARBY_SHARE_CLIENT_H_ diff --git a/sharing/internal/api/mock_sharing_platform.h b/sharing/internal/api/mock_sharing_platform.h index fc7b547d..b5b64e18 100644 --- a/sharing/internal/api/mock_sharing_platform.h +++ b/sharing/internal/api/mock_sharing_platform.h @@ -22,11 +22,9 @@ #include "gmock/gmock.h" #include "absl/strings/string_view.h" #include "internal/base/file_path.h" -#include "internal/platform/clock.h" #include "internal/platform/device_info.h" #include "internal/platform/implementation/account_manager.h" #include "internal/platform/task_runner.h" -#include "sharing/analytics/analytics_recorder.h" #include "sharing/internal/api/app_info.h" #include "sharing/internal/api/bluetooth_adapter.h" #include "sharing/internal/api/fast_init_ble_beacon.h" @@ -35,7 +33,6 @@ #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/public_certificate_database.h" #include "sharing/internal/api/sharing_platform.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/api/system_info.h" namespace nearby::sharing::api { @@ -79,11 +76,6 @@ class MockSharingPlatform : public SharingPlatform { MOCK_METHOD(std::unique_ptr, CreatePublicCertificateDatabase, (const FilePath& database_path), (override)); - MOCK_METHOD( - std::unique_ptr, CreateSharingRpcClientFactory, - (Clock * clock, - nearby::sharing::analytics::AnalyticsRecorder* analytics_recorder), - (override)); MOCK_METHOD(bool, UpdateFileOriginMetadata, (std::vector & file_paths), (override)); }; diff --git a/sharing/internal/api/sharing_platform.h b/sharing/internal/api/sharing_platform.h index abc3703a..d5bab76a 100644 --- a/sharing/internal/api/sharing_platform.h +++ b/sharing/internal/api/sharing_platform.h @@ -21,11 +21,9 @@ #include "absl/strings/string_view.h" #include "internal/base/file_path.h" -#include "internal/platform/clock.h" #include "internal/platform/device_info.h" #include "internal/platform/implementation/account_manager.h" #include "internal/platform/task_runner.h" -#include "sharing/analytics/analytics_recorder.h" #include "sharing/internal/api/app_info.h" #include "sharing/internal/api/bluetooth_adapter.h" #include "sharing/internal/api/fast_init_ble_beacon.h" @@ -33,7 +31,6 @@ #include "sharing/internal/api/network_monitor.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/public_certificate_database.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/api/system_info.h" namespace nearby::sharing::api { @@ -72,11 +69,6 @@ class SharingPlatform { virtual std::unique_ptr CreatePublicCertificateDatabase(const FilePath& database_path) = 0; - virtual std::unique_ptr - CreateSharingRpcClientFactory( - Clock* clock, - nearby::sharing::analytics::AnalyticsRecorder* analytics_recorder) = 0; - // On platforms where it is supported, tag the transferred files as // originating from an untrusted source. // Returns true on success. diff --git a/sharing/internal/api/sharing_rpc_client.h b/sharing/internal/api/sharing_rpc_client.h deleted file mode 100644 index 7dcb91e6..00000000 --- a/sharing/internal/api/sharing_rpc_client.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 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 THIRD_PARTY_NEARBY_SHARING_INTERNAL_API_SHARING_RPC_CLIENT_H_ -#define THIRD_PARTY_NEARBY_SHARING_INTERNAL_API_SHARING_RPC_CLIENT_H_ - -#include - -#include "google/nearby/identity/v1/binding.pb.h" -#include "google/nearby/identity/v1/rpcs.pb.h" -#include "absl/functional/any_invocable.h" -#include "absl/status/statusor.h" -#include "sharing/proto/certificate_rpc.pb.h" -#include "sharing/proto/contact_rpc.pb.h" -#include "sharing/proto/device_rpc.pb.h" - -namespace nearby::sharing::api { - -// IdentityRpcClient is used to access Nearby Identity backend APIs. -class IdentityRpcClient { - public: - IdentityRpcClient() = default; - virtual ~IdentityRpcClient() = default; - - virtual void QuerySharedCredentials( - google::nearby::identity::v1::QuerySharedCredentialsRequest request, - absl::AnyInvocable< - void(const absl::StatusOr< - google::nearby::identity::v1::QuerySharedCredentialsResponse>& - response) &&> - callback) = 0; - - virtual void PublishDevice( - google::nearby::identity::v1::PublishDeviceRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) = 0; - - virtual void GetAccountInfo( - google::nearby::identity::v1::GetAccountInfoRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) = 0; - - virtual void QuerySharedCredentialsWithBindingIds( - google::nearby::identity::v1::QuerySharedCredentialsWithBindingIdsRequest - request, - absl::AnyInvocable< - void(const absl::StatusOr< - google::nearby::identity::v1:: - QuerySharedCredentialsWithBindingIdsResponse>& response) &&> - callback) = 0; -}; - -// SharingRpcClient is used to access Nearby Share backend APIs. -class SharingRpcClient { - public: - SharingRpcClient() = default; - virtual ~SharingRpcClient() = default; - - // NearbyShareService v1: ListContactPeople - virtual void ListContactPeople( - proto::ListContactPeopleRequest request, - absl::AnyInvocable& response) &&> - callback) = 0; - - virtual void InitiateBinding( - google::nearby::identity::v1::InitiateBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) = 0; - - virtual void JoinBinding( - google::nearby::identity::v1::JoinBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) = 0; - - virtual void DeleteBinding( - google::nearby::identity::v1::DeleteBindingRequest request, - absl::AnyInvocable< - void(const absl::StatusOr& response) &&> - callback) = 0; -}; - -// Interface for creating SharingRpcClient instances. Because each -// SharingRpcClient instance can only be used for one API call, a factory -// makes it easier to make multiple requests in sequence or in parallel. -class SharingRpcClientFactory { - public: - SharingRpcClientFactory() = default; - virtual ~SharingRpcClientFactory() = default; - - virtual std::unique_ptr CreateInstance() = 0; - virtual std::unique_ptr CreateIdentityInstance() = 0; -}; - -} // namespace nearby::sharing::api - -#endif // THIRD_PARTY_NEARBY_SHARING_INTERNAL_API_SHARING_RPC_CLIENT_H_ diff --git a/sharing/nearby_sharing_service_factory.cc b/sharing/nearby_sharing_service_factory.cc index baee53f8..f7aac28d 100644 --- a/sharing/nearby_sharing_service_factory.cc +++ b/sharing/nearby_sharing_service_factory.cc @@ -17,6 +17,7 @@ #include #include +#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" @@ -55,8 +56,9 @@ NearbySharingService* NearbySharingServiceFactory::CreateSharingService( sharing_platform.GetDeviceInfo(), event_logger); auto nearby_share_client_factory = - sharing_platform.CreateSharingRpcClientFactory(context_->GetClock(), - analytics_recorder); + std::make_unique( + &sharing_platform.GetAccountManager(), context_->GetClock(), + analytics_recorder); auto nearby_share_contact_manager = std::make_unique( context_.get(), sharing_platform.GetAccountManager(), diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index fc21d2f4..1d48bff6 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -31,6 +31,7 @@ #include #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/functional/bind_front.h" @@ -72,7 +73,6 @@ #include "sharing/incoming_share_session.h" #include "sharing/internal/api/bluetooth_adapter.h" #include "sharing/internal/api/sharing_platform.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/base/encode.h" #include "sharing/internal/public/connectivity_manager.h" #include "sharing/internal/public/context.h" diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index 82813706..21152726 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -27,6 +27,7 @@ #include #include +#include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/any_invocable.h" @@ -51,7 +52,6 @@ #include "sharing/internal/api/bluetooth_adapter.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/sharing_platform.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/nearby_connection.h" From 32fdca43fff6b656712225a0353484517b87b740 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Tue, 3 Mar 2026 15:08:01 -0800 Subject: [PATCH 44/49] Change ownership model of Rpc clients. PiperOrigin-RevId: 878144390 --- sharing/BUILD | 2 + .../fake_nearby_share_certificate_manager.cc | 2 +- .../fake_nearby_share_certificate_manager.h | 2 +- .../nearby_share_certificate_manager_impl.cc | 13 +++--- .../nearby_share_certificate_manager_impl.h | 15 ++++--- ...rby_share_certificate_manager_impl_test.cc | 42 +++++++------------ sharing/contacts/BUILD | 1 + .../nearby_share_contact_manager_impl.cc | 9 ++-- .../nearby_share_contact_manager_impl.h | 7 ++-- .../nearby_share_contact_manager_impl_test.cc | 8 +--- sharing/nearby_sharing_service_factory.cc | 10 +++-- sharing/nearby_sharing_service_factory.h | 7 ++++ sharing/nearby_sharing_service_impl.cc | 12 ++++-- sharing/nearby_sharing_service_impl.h | 10 +++-- sharing/nearby_sharing_service_impl_test.cc | 9 ++-- 15 files changed, 82 insertions(+), 67 deletions(-) diff --git a/sharing/BUILD b/sharing/BUILD index 028ac35b..da0faaeb 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -405,6 +405,7 @@ cc_library( "//sharing/proto:wire_format_cc_proto", "//sharing/scheduling", "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/base:nullability", "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/container:flat_hash_set", "@com_google_absl//absl/functional:any_invocable", @@ -630,6 +631,7 @@ cc_test( "//internal/platform/implementation:signin_attempt", "//internal/test", "//internal/test:mocks", + "//location/nearby/sharing/lib/rpc:fake_nearby_share_client", "//sharing/analytics", "//sharing/certificates", "//sharing/certificates:test_support", diff --git a/sharing/certificates/fake_nearby_share_certificate_manager.cc b/sharing/certificates/fake_nearby_share_certificate_manager.cc index 7895eda6..d20d0a9d 100644 --- a/sharing/certificates/fake_nearby_share_certificate_manager.cc +++ b/sharing/certificates/fake_nearby_share_certificate_manager.cc @@ -50,7 +50,7 @@ FakeNearbyShareCertificateManager::Factory::CreateInstance( nearby::Context* context, NearbyShareLocalDeviceDataManager* local_device_data_manager, const FilePath& profile_path, - nearby::sharing::api::SharingRpcClientFactory* client_factory) { + nearby::sharing::api::IdentityRpcClient* identity_client) { auto instance = std::make_unique(); instances_.push_back(instance.get()); diff --git a/sharing/certificates/fake_nearby_share_certificate_manager.h b/sharing/certificates/fake_nearby_share_certificate_manager.h index 0a5c8f24..6b2bd504 100644 --- a/sharing/certificates/fake_nearby_share_certificate_manager.h +++ b/sharing/certificates/fake_nearby_share_certificate_manager.h @@ -61,7 +61,7 @@ class FakeNearbyShareCertificateManager : public NearbyShareCertificateManager { Context* context, NearbyShareLocalDeviceDataManager* local_device_data_manager, const FilePath& profile_path, - nearby::sharing::api::SharingRpcClientFactory* client_factory) override; + nearby::sharing::api::IdentityRpcClient* identity_client) override; std::vector instances_; }; diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.cc b/sharing/certificates/nearby_share_certificate_manager_impl.cc index a79283d3..fe33848a 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl.cc @@ -33,6 +33,7 @@ #include "google/protobuf/timestamp.pb.h" #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" #include "absl/algorithm/algorithm.h" +#include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" #include "absl/status/statusor.h" @@ -200,12 +201,12 @@ NearbyShareCertificateManagerImpl::Factory::Create( Context* context, SharingPlatform& sharing_platform, NearbyShareLocalDeviceDataManager* local_device_data_manager, const FilePath& profile_path, - nearby::sharing::api::SharingRpcClientFactory* client_factory) { + nearby::sharing::api::IdentityRpcClient* absl_nonnull identity_client) { DCHECK(context); if (test_factory_) { return test_factory_->CreateInstance(context, local_device_data_manager, - profile_path, client_factory); + profile_path, identity_client); } FilePath database_path = profile_path; @@ -214,7 +215,7 @@ NearbyShareCertificateManagerImpl::Factory::Create( context, sharing_platform.GetPreferenceManager(), sharing_platform.GetAccountManager(), sharing_platform.CreatePublicCertificateDatabase(database_path), - local_device_data_manager, client_factory)); + local_device_data_manager, identity_client)); } // static @@ -230,12 +231,12 @@ NearbyShareCertificateManagerImpl::NearbyShareCertificateManagerImpl( AccountManager& account_manager, std::unique_ptr public_certificate_database, NearbyShareLocalDeviceDataManager* local_device_data_manager, - nearby::sharing::api::SharingRpcClientFactory* client_factory) + nearby::sharing::api::IdentityRpcClient* absl_nonnull identity_client) : context_(context), account_manager_(account_manager), local_device_data_manager_(local_device_data_manager), preference_manager_(preference_manager), - nearby_identity_client_(client_factory->CreateIdentityInstance()), + nearby_identity_client_(identity_client), certificate_storage_(NearbyShareCertificateStorageImpl::Factory::Create( preference_manager, std::move(public_certificate_database))), private_certificate_expiration_scheduler_( @@ -419,7 +420,7 @@ bool NearbyShareCertificateManagerImpl::DownloadPublicCertificatesInExecutor() { bool download_succeeded = false; absl::Notification notification; auto context = std::make_unique( - nearby_identity_client_.get(), std::move(device_id), + nearby_identity_client_, std::move(device_id), [this, &download_succeeded, ¬ification]( absl::StatusOr> certificates_status) { if (!certificates_status.ok()) { diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.h b/sharing/certificates/nearby_share_certificate_manager_impl.h index a94598c4..20ad389d 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.h +++ b/sharing/certificates/nearby_share_certificate_manager_impl.h @@ -68,7 +68,7 @@ class NearbyShareCertificateManagerImpl nearby::sharing::api::SharingPlatform& sharing_platform, NearbyShareLocalDeviceDataManager* local_device_data_manager, const FilePath& profile_path, - nearby::sharing::api::SharingRpcClientFactory* client_factory); + nearby::sharing::api::IdentityRpcClient* absl_nonnull identity_client); static void SetFactoryForTesting(Factory* test_factory); protected: @@ -77,7 +77,8 @@ class NearbyShareCertificateManagerImpl Context* context, NearbyShareLocalDeviceDataManager* local_device_data_manager, const FilePath& profile_path, - nearby::sharing::api::SharingRpcClientFactory* client_factory) = 0; + nearby::sharing::api::IdentityRpcClient* absl_nonnull + identity_client) = 0; private: static Factory* test_factory_; @@ -101,7 +102,8 @@ class NearbyShareCertificateManagerImpl class CertificateDownloadContext { public: CertificateDownloadContext( - nearby::sharing::api::IdentityRpcClient* nearby_identity_client, + nearby::sharing::api::IdentityRpcClient* absl_nonnull + nearby_identity_client, std::string device_id, absl::AnyInvocable> @@ -119,7 +121,8 @@ class NearbyShareCertificateManagerImpl void QuerySharedCredentialsFetchNextPage(); private: - nearby::sharing::api::IdentityRpcClient* const nearby_identity_client_; + nearby::sharing::api::IdentityRpcClient* absl_nonnull const + nearby_identity_client_; std::string device_id_; std::optional next_page_token_; int page_number_ = 1; @@ -137,7 +140,7 @@ class NearbyShareCertificateManagerImpl std::unique_ptr public_certificate_database, NearbyShareLocalDeviceDataManager* local_device_data_manager, - nearby::sharing::api::SharingRpcClientFactory* client_factory); + nearby::sharing::api::IdentityRpcClient* absl_nonnull identity_client); // NearbyShareCertificateManager: void OnStartScheduledTasks() override; @@ -197,7 +200,7 @@ class NearbyShareCertificateManagerImpl NearbyShareLocalDeviceDataManager* const local_device_data_manager_; nearby::sharing::api::PreferenceManager& preference_manager_; int32_t vendor_id_ = 0; // Defaults to GOOGLE. - std::unique_ptr + nearby::sharing::api::IdentityRpcClient* absl_nonnull const nearby_identity_client_; std::shared_ptr certificate_storage_; diff --git a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc index cf4b5b24..796c91e0 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc @@ -147,7 +147,7 @@ class NearbyShareCertificateManagerImplTest cert_manager_ = NearbyShareCertificateManagerImpl::Factory::Create( &fake_context_, mock_sharing_platform_, local_device_data_manager_.get(), - /*profile_path=*/{}, &client_factory_); + /*profile_path=*/{}, &identity_client_); cert_manager_->AddObserver(this); cert_store_ = cert_store_factory_.instances().back(); @@ -192,10 +192,6 @@ class NearbyShareCertificateManagerImplTest ++num_private_certs_changed_notifications_; } - FakeNearbyIdentityClient* GetIdentityClient() { - return client_factory_.identity_instances().back(); - } - protected: enum class DownloadPublicCertificatesResult { kSuccess, @@ -241,9 +237,8 @@ class NearbyShareCertificateManagerImplTest } void VerifyCertificatesUpload(bool expected_force_update_contacts) { - FakeNearbyIdentityClient* identity_client = GetIdentityClient(); std::vector publish_device_requests = - identity_client->publish_device_requests(); + identity_client_.publish_device_requests(); ASSERT_FALSE(publish_device_requests.empty()); const PublishDeviceRequest& publish_device_request = publish_device_requests.back(); @@ -331,7 +326,6 @@ class NearbyShareCertificateManagerImplTest void InvokeCertUploadPublishDevice(bool contacts_removed, bool publish_device_success) { - FakeNearbyIdentityClient* identity_client = GetIdentityClient(); std::vector> responses; if (contacts_removed) { // When contacts are removed, a second publish device call is scheduled. @@ -343,7 +337,7 @@ class NearbyShareCertificateManagerImplTest PublishDeviceResponse response; response.add_contact_updates(PublishDeviceResponse::CONTACT_UPDATE_ADDED); responses.push_back(response); - identity_client->SetPublishDeviceResponses(std::move(responses)); + identity_client_.SetPublishDeviceResponses(std::move(responses)); upload_scheduler_->InvokeRequestCallback(); Sync(); @@ -352,7 +346,7 @@ class NearbyShareCertificateManagerImplTest Sync(); Sync(); } - EXPECT_EQ(identity_client->publish_device_requests().size(), + EXPECT_EQ(identity_client_.publish_device_requests().size(), contacts_removed ? 2 : 1); VerifyCertificatesUpload( @@ -386,15 +380,14 @@ class NearbyShareCertificateManagerImplTest BuildQuerySharedCredentialsResponse(page_number, page_token)); } - FakeNearbyIdentityClient* identity_client = GetIdentityClient(); - identity_client->SetQuerySharedCredentialsResponses(responses); + identity_client_.SetQuerySharedCredentialsResponses(responses); cert_store_->SetAddPublicCertificatesResult( result != DownloadPublicCertificatesResult::kStorageError); download_scheduler_->InvokeRequestCallback(); Sync(); std::vector requests = - identity_client->query_shared_credentials_requests(); + identity_client_.query_shared_credentials_requests(); EXPECT_EQ(requests.size(), num_pages); EXPECT_EQ(requests.back().name(), absl::StrCat("devices/", kDeviceId)); ASSERT_EQ(download_scheduler_->handled_results().size(), @@ -495,7 +488,7 @@ class NearbyShareCertificateManagerImplTest std::vector public_certificates_; std::vector metadata_encryption_keys_; - FakeNearbyShareClientFactory client_factory_; + FakeNearbyIdentityClient identity_client_; FakeNearbyShareSchedulerFactory scheduler_factory_; FakeNearbyShareCertificateStorage::Factory cert_store_factory_; std::unique_ptr @@ -763,7 +756,7 @@ TEST_F(NearbyShareCertificateManagerImplTest, EXPECT_EQ(0, upload_scheduler_->num_immediate_requests()); EXPECT_TRUE(cert_store_->GetPrivateCertificates().empty()); - EXPECT_TRUE(GetIdentityClient()->publish_device_requests().empty()); + EXPECT_TRUE(identity_client_.publish_device_requests().empty()); } TEST_F(NearbyShareCertificateManagerImplTest, @@ -936,7 +929,7 @@ TEST_F(NearbyShareCertificateManagerImplTest, upload_scheduler_->InvokeRequestCallback(); Sync(); - EXPECT_TRUE(GetIdentityClient()->publish_device_requests().empty()); + EXPECT_TRUE(identity_client_.publish_device_requests().empty()); EXPECT_EQ(upload_scheduler_->handled_results().size(), 1); EXPECT_EQ(upload_scheduler_->handled_results().back(), false); } @@ -963,16 +956,15 @@ TEST_F(NearbyShareCertificateManagerImplTest, StopScheduledTasks) { TEST_F(NearbyShareCertificateManagerImplTest, UpdateAccountInfo_TitanumEnabled) { Initialize(); - FakeNearbyIdentityClient* identity_client = GetIdentityClient(); GetAccountInfoResponse response; response.mutable_account_info()->mutable_capabilities()->Add( AccountInfo::CAPABILITY_TITANIUM); - identity_client->SetGetAccountInfoResponse(response); + identity_client_.SetGetAccountInfoResponse(response); account_info_update_scheduler_->InvokeRequestCallback(); Sync(); - EXPECT_FALSE(GetIdentityClient()->get_account_info_requests().empty()); + EXPECT_FALSE(identity_client_.get_account_info_requests().empty()); EXPECT_TRUE(preference_manager_.GetBoolean( PrefNames::kAdvancedProtectionEnabled, /*default_value=*/false)); } @@ -981,14 +973,13 @@ TEST_F(NearbyShareCertificateManagerImplTest, UpdateAccountInfo_TitanumDisabled) { Initialize(); preference_manager_.SetBoolean(PrefNames::kAdvancedProtectionEnabled, true); - FakeNearbyIdentityClient* identity_client = GetIdentityClient(); GetAccountInfoResponse response; - identity_client->SetGetAccountInfoResponse(response); + identity_client_.SetGetAccountInfoResponse(response); account_info_update_scheduler_->InvokeRequestCallback(); Sync(); - EXPECT_FALSE(GetIdentityClient()->get_account_info_requests().empty()); + EXPECT_FALSE(identity_client_.get_account_info_requests().empty()); EXPECT_FALSE(preference_manager_.GetBoolean( PrefNames::kAdvancedProtectionEnabled, /*default_value=*/false)); } @@ -997,16 +988,15 @@ TEST_F(NearbyShareCertificateManagerImplTest, UpdateAccountInfo_TitanumUnspecified) { Initialize(); preference_manager_.SetBoolean(PrefNames::kAdvancedProtectionEnabled, true); - FakeNearbyIdentityClient* identity_client = GetIdentityClient(); GetAccountInfoResponse response; response.mutable_account_info()->mutable_capabilities()->Add( AccountInfo::CAPABILITY_UNSPECIFIED); - identity_client->SetGetAccountInfoResponse(response); + identity_client_.SetGetAccountInfoResponse(response); account_info_update_scheduler_->InvokeRequestCallback(); Sync(); - EXPECT_FALSE(GetIdentityClient()->get_account_info_requests().empty()); + EXPECT_FALSE(identity_client_.get_account_info_requests().empty()); EXPECT_FALSE(preference_manager_.GetBoolean( PrefNames::kAdvancedProtectionEnabled, /*default_value=*/false)); } @@ -1020,7 +1010,7 @@ TEST_F(NearbyShareCertificateManagerImplTest, Sync(); // Identity client by default return Status::NotFound. - EXPECT_FALSE(GetIdentityClient()->get_account_info_requests().empty()); + EXPECT_FALSE(identity_client_.get_account_info_requests().empty()); EXPECT_TRUE(preference_manager_.GetBoolean( PrefNames::kAdvancedProtectionEnabled, /*default_value=*/false)); } diff --git a/sharing/contacts/BUILD b/sharing/contacts/BUILD index 63c23367..61b4807b 100644 --- a/sharing/contacts/BUILD +++ b/sharing/contacts/BUILD @@ -47,6 +47,7 @@ cc_library( "//sharing/internal/public:logging", "//sharing/internal/public:types", "//sharing/proto:share_cc_proto", + "@com_google_absl//absl/base:nullability", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/synchronization", ], diff --git a/sharing/contacts/nearby_share_contact_manager_impl.cc b/sharing/contacts/nearby_share_contact_manager_impl.cc index 43244f96..37c9df39 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl.cc +++ b/sharing/contacts/nearby_share_contact_manager_impl.cc @@ -24,6 +24,7 @@ #include #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" +#include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "absl/synchronization/notification.h" #include "internal/platform/implementation/account_manager.h" @@ -111,10 +112,10 @@ void ContactDownloadContext::FetchNextPage() { } // namespace NearbyShareContactManagerImpl::NearbyShareContactManagerImpl( - Context* context, AccountManager& account_manager, - nearby::sharing::api::SharingRpcClientFactory* nearby_client_factory) + Context* absl_nonnull context, AccountManager& account_manager, + nearby::sharing::api::SharingRpcClient* absl_nonnull nearby_client) : account_manager_(account_manager), - nearby_share_client_(nearby_client_factory->CreateInstance()), + nearby_share_client_(*nearby_client), executor_(context->CreateSequencedTaskRunner()) {} void NearbyShareContactManagerImpl::GetContacts(ContactsCallback callback) { @@ -130,7 +131,7 @@ void NearbyShareContactManagerImpl::GetContacts(ContactsCallback callback) { absl::Notification notification; auto context = std::make_unique( - nearby_share_client_.get(), + &nearby_share_client_, [¬ification, callback = std::move(callback)]( absl::StatusOr> contacts, diff --git a/sharing/contacts/nearby_share_contact_manager_impl.h b/sharing/contacts/nearby_share_contact_manager_impl.h index b40ef772..43e23592 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl.h +++ b/sharing/contacts/nearby_share_contact_manager_impl.h @@ -18,6 +18,7 @@ #include #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" +#include "absl/base/nullability.h" #include "internal/platform/implementation/account_manager.h" #include "internal/platform/task_runner.h" #include "sharing/contacts/nearby_share_contact_manager.h" @@ -29,8 +30,8 @@ namespace sharing { class NearbyShareContactManagerImpl : public NearbyShareContactManager { public: NearbyShareContactManagerImpl( - Context* context, AccountManager& account_manager, - nearby::sharing::api::SharingRpcClientFactory* nearby_client_factory); + Context* absl_nonnull context, AccountManager& account_manager, + nearby::sharing::api::SharingRpcClient* absl_nonnull nearby_client); ~NearbyShareContactManagerImpl() override = default; @@ -39,7 +40,7 @@ class NearbyShareContactManagerImpl : public NearbyShareContactManager { void GetContacts(ContactsCallback callback) override; AccountManager& account_manager_; - std::unique_ptr nearby_share_client_; + nearby::sharing::api::SharingRpcClient& nearby_share_client_; std::unique_ptr executor_ = nullptr; }; diff --git a/sharing/contacts/nearby_share_contact_manager_impl_test.cc b/sharing/contacts/nearby_share_contact_manager_impl_test.cc index 7f246d6f..b2c7da8f 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl_test.cc +++ b/sharing/contacts/nearby_share_contact_manager_impl_test.cc @@ -63,7 +63,7 @@ class NearbyShareContactManagerImplTest fake_account_manager_.SetAccount(account); manager_ = std::make_unique( - &fake_context_, fake_account_manager_, &nearby_client_factory_); + &fake_context_, fake_account_manager_, &nearby_client_); } void TearDown() override { @@ -83,16 +83,12 @@ class NearbyShareContactManagerImplTest FakeContext& fake_context() { return fake_context_; } private: - FakeNearbyShareClient* client() { - return nearby_client_factory_.instances().back(); - } - FakeAccountManager fake_account_manager_; FakeContext fake_context_; std::vector contacts_downloaded_notifications_; std::vector contacts_uploaded_notifications_; - FakeNearbyShareClientFactory nearby_client_factory_; + FakeNearbyShareClient nearby_client_; FakeNearbyShareLocalDeviceDataManager local_device_data_manager_; std::unique_ptr account_manager_; std::unique_ptr manager_; diff --git a/sharing/nearby_sharing_service_factory.cc b/sharing/nearby_sharing_service_factory.cc index f7aac28d..63d1ea50 100644 --- a/sharing/nearby_sharing_service_factory.cc +++ b/sharing/nearby_sharing_service_factory.cc @@ -55,18 +55,22 @@ NearbySharingService* NearbySharingServiceFactory::CreateSharingService( service_thread.get(), context_.get(), sharing_platform.GetDeviceInfo(), event_logger); - auto nearby_share_client_factory = + nearby_share_client_factory_ = std::make_unique( &sharing_platform.GetAccountManager(), context_->GetClock(), analytics_recorder); + nearby_share_client_ = nearby_share_client_factory_->CreateInstance(); + nearby_identity_client_ = + nearby_share_client_factory_->CreateIdentityInstance(); auto nearby_share_contact_manager = std::make_unique( context_.get(), sharing_platform.GetAccountManager(), - nearby_share_client_factory.get()); + nearby_share_client_.get()); nearby_sharing_service_ = std::make_unique( std::move(service_thread), context_.get(), sharing_platform, - std::move(nearby_share_client_factory), + nearby_identity_client_.get(), + nearby_share_client_.get(), std::move(nearby_connections_manager), std::move(nearby_share_contact_manager), analytics_recorder, supports_file_sync); diff --git a/sharing/nearby_sharing_service_factory.h b/sharing/nearby_sharing_service_factory.h index a1612f76..3fe117a9 100644 --- a/sharing/nearby_sharing_service_factory.h +++ b/sharing/nearby_sharing_service_factory.h @@ -17,6 +17,8 @@ #include +#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" @@ -41,6 +43,11 @@ class NearbySharingServiceFactory { std::unique_ptr context_; std::unique_ptr nearby_sharing_service_; + std::unique_ptr + nearby_share_client_factory_; + std::unique_ptr nearby_share_client_; + std::unique_ptr + nearby_identity_client_; }; } // namespace nearby::sharing diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index 1d48bff6..7c08717f 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -32,6 +32,7 @@ #include #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" +#include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/functional/bind_front.h" @@ -113,7 +114,8 @@ using ::location::nearby::proto::sharing::OSType; using ::location::nearby::proto::sharing::ResponseToIntroduction; using ::location::nearby::proto::sharing::SessionStatus; using ::nearby::sharing::api::SharingPlatform; -using ::nearby::sharing::api::SharingRpcClientFactory; +using ::nearby::sharing::api::SharingRpcClient; +using ::nearby::sharing::api::IdentityRpcClient; using ::nearby::sharing::proto::DataUsage; using ::nearby::sharing::proto::DeviceVisibility; using ::nearby::sharing::service::proto::ConnectionResponseFrame; @@ -234,7 +236,9 @@ std::string SendSurfaceStateToString( NearbySharingServiceImpl::NearbySharingServiceImpl( std::unique_ptr service_thread, Context* context, SharingPlatform& sharing_platform, - std::unique_ptr nearby_share_client_factory, + nearby::sharing::api::IdentityRpcClient* absl_nonnull + nearby_identity_client, + nearby::sharing::api::SharingRpcClient* absl_nonnull nearby_share_client, std::unique_ptr nearby_connections_manager, std::unique_ptr contact_manager, analytics::AnalyticsRecorder* analytics_recorder, bool supports_file_sync) @@ -246,7 +250,7 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( analytics_recorder_(*analytics_recorder), supports_file_sync_(supports_file_sync), nearby_connections_manager_(std::move(nearby_connections_manager)), - nearby_share_client_factory_(std::move(nearby_share_client_factory)), + nearby_share_client_(nearby_share_client), local_device_data_manager_( NearbyShareLocalDeviceDataManagerImpl::Factory::Create( preference_manager_, account_manager_, device_info_)), @@ -279,7 +283,7 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( certificate_manager_ = NearbyShareCertificateManagerImpl::Factory::Create( context_, sharing_platform, local_device_data_manager_.get(), - profile_path, nearby_share_client_factory_.get()), + profile_path, nearby_identity_client); certificate_manager_->AddObserver(this); context_->GetConnectivityManager()->RegisterLanListener( diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index 21152726..bdf0b34b 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -28,6 +28,7 @@ #include #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" +#include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/any_invocable.h" @@ -102,8 +103,9 @@ class NearbySharingServiceImpl NearbySharingServiceImpl( std::unique_ptr service_thread, Context* context, nearby::sharing::api::SharingPlatform& sharing_platform, - std::unique_ptr - nearby_share_client_factory, + nearby::sharing::api::IdentityRpcClient* absl_nonnull + nearby_identity_client, + nearby::sharing::api::SharingRpcClient* absl_nonnull nearby_share_client, std::unique_ptr nearby_connections_manager, std::unique_ptr contact_manager, analytics::AnalyticsRecorder* analytics_recorder, @@ -415,8 +417,8 @@ class NearbySharingServiceImpl const bool supports_file_sync_; std::unique_ptr nearby_connections_manager_; - std::unique_ptr - nearby_share_client_factory_; + nearby::sharing::api::SharingRpcClient* absl_nonnull const + nearby_share_client_; std::unique_ptr local_device_data_manager_; std::unique_ptr contact_manager_; std::unique_ptr certificate_manager_; diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index dc111ebb..a009f000 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/sharing/lib/rpc/fake_nearby_share_client.h" #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" @@ -483,10 +484,10 @@ class NearbySharingServiceImplTest : public testing::Test { std::unique_ptr task_runner) { return std::make_unique( std::move(task_runner), &fake_context_, mock_sharing_platform_, - /*nearby_share_client_factory=*/nullptr, + &nearby_identity_client_, &nearby_share_client_, absl::WrapUnique(fake_nearby_connections_manager_), - absl::WrapUnique(contact_manager_), - analytics_recorder_.get(), /*supports_file_sync=*/false); + absl::WrapUnique(contact_manager_), analytics_recorder_.get(), + /*supports_file_sync=*/false); } void SetVisibility(DeviceVisibility visibility) { @@ -1278,6 +1279,8 @@ class NearbySharingServiceImplTest : public testing::Test { ABSL_GUARDED_BY(connection_output_mutex_); std::queue written_payloads_ ABSL_GUARDED_BY(connection_output_mutex_); + FakeNearbyIdentityClient nearby_identity_client_; + FakeNearbyShareClient nearby_share_client_; }; struct ValidSendSurfaceTestData { From 381b6c14a9679d5e34992243157de9269cddfe88 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Tue, 3 Mar 2026 19:11:21 -0800 Subject: [PATCH 45/49] internal PiperOrigin-RevId: 878228797 --- sharing/internal/api/BUILD | 5 +-- sharing/internal/api/preference_manager.h | 13 +++++-- sharing/internal/test/BUILD | 2 + .../internal/test/fake_preference_manager.cc | 39 ++++++++++++++++--- .../internal/test/fake_preference_manager.h | 10 ++++- 5 files changed, 55 insertions(+), 14 deletions(-) diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index a0e132ed..9fb16437 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -42,11 +42,10 @@ cc_library( "//internal/platform:mac_address", "//internal/platform:types", "//internal/platform/implementation:account_manager", - "//sharing/analytics", + "//location/nearby/sharing/lib/sync:sync_binding_prefs_cc_proto", + "//location/nearby/sharing/lib/sync:sync_config_prefs_cc_proto", "//sharing/proto:share_cc_proto", - "//sharing/proto:wire_format_cc_proto", "@com_google_absl//absl/functional:any_invocable", - "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/time", "@com_google_absl//absl/types:span", diff --git a/sharing/internal/api/preference_manager.h b/sharing/internal/api/preference_manager.h index 83a9faa9..7c6f00ca 100644 --- a/sharing/internal/api/preference_manager.h +++ b/sharing/internal/api/preference_manager.h @@ -22,11 +22,12 @@ #include #include +#include "location/nearby/sharing/lib/sync/sync_binding_prefs.pb.h" +#include "location/nearby/sharing/lib/sync/sync_config_prefs.pb.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "sharing/internal/api/private_certificate_data.h" -#include "sharing/proto/wire_format.pb.h" namespace nearby::sharing::api { @@ -82,7 +83,10 @@ class PreferenceManager { virtual void SetSyncConfigValue( absl::string_view binding_id, - const nearby::sharing::service::proto::SyncConfig& value) = 0; + const nearby::sharing::sync::SyncConfigPrefs& value) = 0; + + virtual void SetSyncBindingValue( + const nearby::sharing::sync::SyncBindingPrefs& value) = 0; // Gets values virtual bool GetBoolean(absl::string_view key, bool default_value) const = 0; @@ -123,9 +127,12 @@ class PreferenceManager { virtual std::optional GetDictionaryStringValue( absl::string_view key, absl::string_view dictionary_item) const = 0; - virtual std::optional + virtual std::optional GetSyncConfigValue(absl::string_view binding_id) const = 0; + virtual std::optional + GetSyncBindingValue() const = 0; + // Removes preferences virtual void Remove(absl::string_view key) = 0; // Removes all sync configs. diff --git a/sharing/internal/test/BUILD b/sharing/internal/test/BUILD index b377f056..0342ae4c 100644 --- a/sharing/internal/test/BUILD +++ b/sharing/internal/test/BUILD @@ -40,6 +40,8 @@ cc_library( "//internal/platform:mac_address", "//internal/platform:types", "//internal/test", + "//location/nearby/sharing/lib/sync:sync_binding_prefs_cc_proto", + "//location/nearby/sharing/lib/sync:sync_config_prefs_cc_proto", "//sharing/internal/api:platform", "//sharing/internal/public:pref_names", "//sharing/internal/public:types", diff --git a/sharing/internal/test/fake_preference_manager.cc b/sharing/internal/test/fake_preference_manager.cc index cc1f637d..cac1bb32 100644 --- a/sharing/internal/test/fake_preference_manager.cc +++ b/sharing/internal/test/fake_preference_manager.cc @@ -22,6 +22,8 @@ #include #include +#include "location/nearby/sharing/lib/sync/sync_binding_prefs.pb.h" +#include "location/nearby/sharing/lib/sync/sync_config_prefs.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" @@ -34,6 +36,11 @@ namespace nearby { using ::nearby::sharing::PrefNames; using ::nearby::sharing::api::PrivateCertificateData; +using ::nearby::sharing::sync::SyncBindingPrefs; +using ::nearby::sharing::sync::SyncConfigPrefs; + +// Preference suffix for the sync binding information. +constexpr absl::string_view kFileSyncBindingName = "FileSync"; template void FakePreferenceManager::SetValue(absl::string_view key, T value) { @@ -238,13 +245,18 @@ void FakePreferenceManager::RemoveDictionaryItem( NotifyPreferenceChanged(key); } -void FakePreferenceManager::SetSyncConfigValue( - absl::string_view binding_id, - const nearby::sharing::service::proto::SyncConfig& value) { +void FakePreferenceManager::SetSyncConfigValue(absl::string_view binding_id, + const SyncConfigPrefs& value) { SetValue(absl::StrCat(PrefNames::kSyncConfigPrefix, binding_id), value.SerializeAsString()); } +void FakePreferenceManager::SetSyncBindingValue( + const SyncBindingPrefs& value) { + SetValue(absl::StrCat(PrefNames::kBindingConfigPrefix, kFileSyncBindingName), + value.SerializeAsString()); +} + bool FakePreferenceManager::GetBoolean(absl::string_view key, bool default_value) const { return GetValue(key, default_value); @@ -329,21 +341,36 @@ std::optional FakePreferenceManager::GetDictionaryStringValue( return GetDictionaryValue(key, dictionary_item); } -std::optional -FakePreferenceManager::GetSyncConfigValue(absl::string_view binding_id) const { +std::optional FakePreferenceManager::GetSyncConfigValue( + absl::string_view binding_id) const { std::string serialized_sync_config; serialized_sync_config = GetString(absl::StrCat(PrefNames::kSyncConfigPrefix, binding_id), ""); if (serialized_sync_config.empty()) { return std::nullopt; } - nearby::sharing::service::proto::SyncConfig sync_config; + SyncConfigPrefs sync_config; if (!sync_config.ParseFromString(serialized_sync_config)) { return std::nullopt; } return sync_config; } +std::optional FakePreferenceManager::GetSyncBindingValue() + const { + std::string serialized_sync_binding; + serialized_sync_binding = GetString( + absl::StrCat(PrefNames::kBindingConfigPrefix, kFileSyncBindingName), ""); + if (serialized_sync_binding.empty()) { + return std::nullopt; + } + SyncBindingPrefs sync_binding; + if (!sync_binding.ParseFromString(serialized_sync_binding)) { + return std::nullopt; + } + return sync_binding; +} + void FakePreferenceManager::Remove(absl::string_view key) { { absl::MutexLock lock(mutex_); diff --git a/sharing/internal/test/fake_preference_manager.h b/sharing/internal/test/fake_preference_manager.h index acff903d..88f7eb1e 100644 --- a/sharing/internal/test/fake_preference_manager.h +++ b/sharing/internal/test/fake_preference_manager.h @@ -23,6 +23,8 @@ #include #include +#include "location/nearby/sharing/lib/sync/sync_binding_prefs.pb.h" +#include "location/nearby/sharing/lib/sync/sync_config_prefs.pb.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" @@ -76,7 +78,9 @@ class FakePreferenceManager : public nearby::sharing::api::PreferenceManager { void SetSyncConfigValue( absl::string_view binding_id, - const nearby::sharing::service::proto::SyncConfig& value) override; + const nearby::sharing::sync::SyncConfigPrefs& value) override; + void SetSyncBindingValue( + const nearby::sharing::sync::SyncBindingPrefs& value) override; bool GetBoolean(absl::string_view key, bool default_value) const override; int GetInteger(absl::string_view key, int default_value) const override; @@ -111,8 +115,10 @@ class FakePreferenceManager : public nearby::sharing::api::PreferenceManager { absl::string_view key, absl::string_view dictionary_item) const override; std::optional GetDictionaryStringValue( absl::string_view key, absl::string_view dictionary_item) const override; - std::optional + std::optional GetSyncConfigValue(absl::string_view binding_id) const override; + std::optional + GetSyncBindingValue() const override; void Remove(absl::string_view key) override; void RemoveAllSyncConfigs() override; From 38e660e37a62fb16c6a4e31ad27dfa5491d8bf1c Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 4 Mar 2026 15:21:19 -0800 Subject: [PATCH 46/49] Remove unused code. PiperOrigin-RevId: 878691812 --- .../platform/implementation/windows/BUILD | 2 ++ .../implementation/windows/ble_gatt_client.cc | 13 ++----- .../implementation/windows/ble_gatt_server.cc | 10 ++---- .../windows/ble_server_socket.cc | 10 ++---- .../windows/bluetooth_adapter.cc | 33 +++++++++--------- .../windows/bluetooth_pairing.cc | 8 ++--- .../implementation/windows/platform.cc | 34 ++----------------- .../implementation/windows/wifi_lan_mdns.cc | 1 - 8 files changed, 28 insertions(+), 83 deletions(-) diff --git a/internal/platform/implementation/windows/BUILD b/internal/platform/implementation/windows/BUILD index 5bdc2a6e..a8357302 100644 --- a/internal/platform/implementation/windows/BUILD +++ b/internal/platform/implementation/windows/BUILD @@ -376,6 +376,8 @@ cc_library( "@com_google_absl//absl/time", "@com_google_absl//absl/types:optional", "@com_google_absl//absl/types:span", + "@com_google_protobuf//:protobuf", + "@com_google_protobuf//json", "@nlohmann_json//:json", ], ) diff --git a/internal/platform/implementation/windows/ble_gatt_client.cc b/internal/platform/implementation/windows/ble_gatt_client.cc index d9a051d8..83ed7695 100644 --- a/internal/platform/implementation/windows/ble_gatt_client.cc +++ b/internal/platform/implementation/windows/ble_gatt_client.cc @@ -27,15 +27,10 @@ #include #include "absl/functional/any_invocable.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" -#include "internal/flags/nearby_flags.h" -#include "internal/platform/byte_array.h" -#include "internal/platform/flags/nearby_platform_feature_flags.h" #include "internal/platform/implementation/ble.h" #include "internal/platform/implementation/windows/bluetooth_adapter.h" #include "internal/platform/implementation/windows/utils.h" @@ -48,8 +43,7 @@ #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Storage.Streams.h" -namespace nearby { -namespace windows { +namespace nearby::windows { namespace { using ::winrt::Windows::Devices::Bluetooth::BluetoothCacheMode; @@ -66,8 +60,6 @@ using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: GattCommunicationStatus; using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: GattDeviceService; -using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: - GattDeviceServicesResult; using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: GattReadResult; using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: @@ -665,5 +657,4 @@ void BleGattClient::OnCharacteristicValueChanged( } } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/ble_gatt_server.cc b/internal/platform/implementation/windows/ble_gatt_server.cc index 52f27bf7..d3c2a939 100644 --- a/internal/platform/implementation/windows/ble_gatt_server.cc +++ b/internal/platform/implementation/windows/ble_gatt_server.cc @@ -25,11 +25,9 @@ #include #include -#include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" -#include "absl/strings/str_format.h" #include "absl/synchronization/mutex.h" #include "absl/time/clock.h" #include "absl/time/time.h" @@ -45,8 +43,7 @@ #include "winrt/Windows.Storage.Streams.h" #include "winrt/base.h" -namespace nearby { -namespace windows { +namespace nearby::windows { namespace { using ::winrt::Windows::Devices::Bluetooth::BluetoothError; @@ -78,8 +75,6 @@ using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: GattServiceProviderAdvertisingParameters; using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: GattServiceProviderResult; -using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: - GattSubscribedClient; using ::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: GattWriteRequestedEventArgs; using ::winrt::Windows::Foundation::Collections::IVectorView; @@ -753,5 +748,4 @@ BleGattServer::FindGattCharacteristicData( return nullptr; } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/ble_server_socket.cc b/internal/platform/implementation/windows/ble_server_socket.cc index 4b902b52..41fb39c1 100644 --- a/internal/platform/implementation/windows/ble_server_socket.cc +++ b/internal/platform/implementation/windows/ble_server_socket.cc @@ -19,17 +19,14 @@ #include #include "absl/synchronization/mutex.h" -#include "absl/synchronization/notification.h" #include "internal/platform/exception.h" #include "internal/platform/implementation/ble.h" #include "internal/platform/implementation/bluetooth_adapter.h" #include "internal/platform/implementation/windows/ble_socket.h" #include "internal/platform/implementation/windows/bluetooth_adapter.h" -#include "internal/platform/implementation/windows/utils.h" #include "internal/platform/logging.h" -namespace nearby { -namespace windows { +namespace nearby::windows { BleServerSocket::BleServerSocket(api::BluetoothAdapter* adapter) : adapter_(dynamic_cast(adapter)) { @@ -53,7 +50,6 @@ std::unique_ptr BleServerSocket::Accept() { } Exception BleServerSocket::Close() { - // TODO(b/271031645): implement BLE socket using weave absl::MutexLock lock(mutex_); VLOG(1) << __func__ << ": Close is called."; @@ -68,10 +64,8 @@ Exception BleServerSocket::Close() { } bool BleServerSocket::Bind() { - // TODO(b/271031645): implement BLE socket using weave LOG(ERROR) << __func__ << ": GATT socket started."; return true; } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/bluetooth_adapter.cc b/internal/platform/implementation/windows/bluetooth_adapter.cc index 0d757b2d..9bef1fae 100644 --- a/internal/platform/implementation/windows/bluetooth_adapter.cc +++ b/internal/platform/implementation/windows/bluetooth_adapter.cc @@ -57,8 +57,7 @@ typedef std::basic_string tstring; #define BLUETOOTH_RADIO_REGISTRY_NAME_KEY "Local Name" -namespace nearby { -namespace windows { +namespace nearby::windows { namespace { struct LocalSettings { std::string original_radio_name; @@ -545,7 +544,7 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) { // lpWideCharStr. nullptr, // Pointer to a buffer that receives the converted string. 0, // Size, in bytes, of the buffer indicated by lpMultiByteStr. - NULL, // Pointer to the character to use if a character cannot be + nullptr, // Pointer to the character to use if a character cannot be // represented in the specified code page. &defaultCharUsed); // Pointer to a flag that indicates if the function // has used a default character in the conversion. @@ -570,8 +569,8 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) { .data(), // Pointer to a buffer that receives the converted string. guid_str_size, // Size, in bytes, of the buffer indicated by // lpMultiByteStr. - NULL, // // Pointer to the character to use if a character cannot be - // represented in the specified code page. + nullptr, // Pointer to the character to use if a character cannot be + // represented in the specified code page. &defaultCharUsed); // // Pointer to a flag that indicates if the // function has used a default character in the // conversion. @@ -613,11 +612,11 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) { // opened. GENERIC_WRITE, // The requested access to the file or device. 0, // The requested sharing mode of the file or device. - NULL, // A pointer to a SECURITY_ATTRIBUTES structure. + nullptr, // A pointer to a SECURITY_ATTRIBUTES structure. OPEN_EXISTING, // An action to take on a file or device that exists or // does not exist. 0, // The file or device attributes and flags. - NULL); // A valid handle to a template file with the GENERIC_READ + nullptr); // A valid handle to a template file with the GENERIC_READ // access right. This parameter can be NULL. if (hDevice == INVALID_HANDLE_VALUE) { @@ -656,7 +655,7 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) { return false; } - if (name != "") { + if (!name.empty()) { // Sets the data and type of a specified value under a registry key. // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexa status = RegSetValueExA( @@ -703,12 +702,12 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) { &reload, // A pointer to the input buffer that contains the data // required to perform the operation. sizeof(reload), // The size of the input buffer, in bytes. - NULL, // A pointer to the output buffer that is to receive the data - // returned by the operation. - 0, // The size of the output buffer, in bytes. - &bytes, // A pointer to a variable that receives the size of the - // data stored in the output buffer, in bytes. - NULL)) { // A pointer to an OVERLAPPED structure. + nullptr, // A pointer to the output buffer that is to receive the + // data returned by the operation. + 0, // The size of the output buffer, in bytes. + &bytes, // A pointer to a variable that receives the size of the + // data stored in the output buffer, in bytes. + nullptr)) { // A pointer to an OVERLAPPED structure. LOG(ERROR) << __func__ << ": Failed to update radio module local name. Error code: " << GetLastError(); @@ -777,7 +776,8 @@ BluetoothAdapter::GetGenericBluetoothAdapterInstanceID() const { // computer. // https://docs.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdigetclassdevsa hDevInfo = - SetupDiGetClassDevsA(&GUID_DEVCLASS_BLUETOOTH, NULL, NULL, DIGCF_PRESENT); + SetupDiGetClassDevsA(&GUID_DEVCLASS_BLUETOOTH, /*Enumerator=*/nullptr, + /*hwndParent=*/nullptr, DIGCF_PRESENT); if (hDevInfo == INVALID_HANDLE_VALUE) { LOG(ERROR) << __func__ @@ -904,5 +904,4 @@ std::string BluetoothAdapter::GetNameFromComputerName() const { return ""; } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/bluetooth_pairing.cc b/internal/platform/implementation/windows/bluetooth_pairing.cc index 3ecb2c2a..2cddfeda 100644 --- a/internal/platform/implementation/windows/bluetooth_pairing.cc +++ b/internal/platform/implementation/windows/bluetooth_pairing.cc @@ -22,7 +22,6 @@ #include #include "absl/strings/string_view.h" -#include "absl/types/optional.h" #include "internal/platform/implementation/bluetooth_classic.h" #include "internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h" #include "internal/platform/logging.h" @@ -31,8 +30,7 @@ #include "winrt/Windows.Foundation.Collections.h" #include "winrt/base.h" -namespace nearby { -namespace windows { +namespace nearby::windows { namespace { using ::winrt::Windows::Devices::Bluetooth::BluetoothDevice; @@ -44,7 +42,6 @@ using ::winrt::Windows::Devices::Enumeration::DevicePairingResult; using ::winrt::Windows::Devices::Enumeration::DevicePairingResultStatus; using ::winrt::Windows::Devices::Enumeration::DeviceUnpairingResult; using ::winrt::Windows::Devices::Enumeration::DeviceUnpairingResultStatus; -using ::winrt::Windows::Foundation::IAsyncOperation; using PairingError = ::nearby::api::BluetoothPairingCallback::PairingError; using PairingType = ::nearby::api::PairingParams::PairingType; } // namespace @@ -322,5 +319,4 @@ void BluetoothPairing::OnPair(DevicePairingResult& pairing_result) { pairing_callback_.on_pairing_error_cb(PairingError::kFailed); } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/platform.cc b/internal/platform/implementation/windows/platform.cc index ce847292..4d896be9 100644 --- a/internal/platform/implementation/windows/platform.cc +++ b/internal/platform/implementation/windows/platform.cc @@ -83,38 +83,12 @@ #include "internal/platform/os_name.h" #include "internal/platform/payload_id.h" -namespace nearby { -namespace api { +namespace nearby::api { namespace { constexpr char kNCRelativePath[] = "Google/Nearby/Connections"; -std::string GetApplicationName(DWORD pid) { - HANDLE handle = - OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, - pid); // Modify pid to the pid of your application - if (!handle) { - return ""; - } - - std::string szProcessName("", MAX_PATH); - DWORD len = MAX_PATH; - - if (NULL != handle) { - GetModuleFileNameExA(handle, nullptr, szProcessName.data(), len); - } - - szProcessName.resize(szProcessName.find_first_of('\0') + 1); - - auto just_the_file_name_and_ext = szProcessName.substr( - szProcessName.find_last_of('\\') + 1, - szProcessName.length() - szProcessName.find_last_of('\\') + 1); - - return just_the_file_name_and_ext.substr( - 0, just_the_file_name_and_ext.find_last_of('.')); -} - } // namespace std::string ImplementationPlatform::GetCustomSavePath( @@ -253,7 +227,6 @@ ImplementationPlatform::CreateBluetoothClassicMedium( return std::make_unique(adapter); } -// TODO(b/184975123): replace with real implementation. std::unique_ptr ImplementationPlatform::CreateBleMedium( api::BluetoothAdapter& adapter) { return std::make_unique(adapter); @@ -264,7 +237,6 @@ ImplementationPlatform::CreateCredentialStorage() { return nullptr; } -// TODO(b/184975123): replace with real implementation. std::unique_ptr ImplementationPlatform::CreateWifiMedium() { return std::make_unique(); } @@ -287,7 +259,6 @@ ImplementationPlatform::CreateWifiDirectMedium() { return std::make_unique(); } -// TODO(b/261663238) replace with real implementation. std::unique_ptr ImplementationPlatform::CreateWebRtcMedium() { return nullptr; } @@ -318,5 +289,4 @@ ImplementationPlatform::CreatePreferencesManager(absl::string_view path) { return std::make_unique(FilePath{path}); } -} // namespace api -} // namespace nearby +} // namespace nearby::api diff --git a/internal/platform/implementation/windows/wifi_lan_mdns.cc b/internal/platform/implementation/windows/wifi_lan_mdns.cc index 9794573c..bb32848e 100644 --- a/internal/platform/implementation/windows/wifi_lan_mdns.cc +++ b/internal/platform/implementation/windows/wifi_lan_mdns.cc @@ -36,7 +36,6 @@ namespace nearby::windows { namespace { // mDNS information for advertising and discovery -const char kMdnsHostName[] = "%s.local"; const char kMdnsInstanceNameFormat[] = "%s.%slocal"; // Timeout for starting mDNS service From a2ec10a07e7d88f3d2d20bd781568938f52df2da Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Wed, 4 Mar 2026 18:05:31 -0800 Subject: [PATCH 47/49] Add bindingId to public certificate. PiperOrigin-RevId: 878755661 --- .../nearby_share_decrypted_public_certificate.cc | 8 +++++--- .../nearby_share_decrypted_public_certificate.h | 9 ++++++++- .../nearby_share_decrypted_public_certificate_test.cc | 2 ++ sharing/proto/rpc_resources.proto | 10 +++++++++- 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/sharing/certificates/nearby_share_decrypted_public_certificate.cc b/sharing/certificates/nearby_share_decrypted_public_certificate.cc index 02c8d9c5..bf52033d 100644 --- a/sharing/certificates/nearby_share_decrypted_public_certificate.cc +++ b/sharing/certificates/nearby_share_decrypted_public_certificate.cc @@ -188,7 +188,7 @@ NearbyShareDecryptedPublicCertificate::DecryptPublicCertificate( return NearbyShareDecryptedPublicCertificate( not_before, not_after, std::move(secret_key), std::move(public_key), std::move(id), std::move(unencrypted_metadata), - public_certificate.for_self_share()); + public_certificate.for_self_share(), public_certificate.binding_id()); } NearbyShareDecryptedPublicCertificate::NearbyShareDecryptedPublicCertificate( @@ -196,14 +196,15 @@ NearbyShareDecryptedPublicCertificate::NearbyShareDecryptedPublicCertificate( std::unique_ptr secret_key, std::vector public_key, std::vector id, nearby::sharing::proto::EncryptedMetadata unencrypted_metadata, - bool for_self_share) + bool for_self_share, std::string binding_id) : not_before_(not_before), not_after_(not_after), secret_key_(std::move(secret_key)), public_key_(std::move(public_key)), id_(std::move(id)), unencrypted_metadata_(std::move(unencrypted_metadata)), - for_self_share_(for_self_share) {} + for_self_share_(for_self_share), + binding_id_(std::move(binding_id)) {} NearbyShareDecryptedPublicCertificate::NearbyShareDecryptedPublicCertificate( const NearbyShareDecryptedPublicCertificate& other) { @@ -223,6 +224,7 @@ NearbyShareDecryptedPublicCertificate::operator=( id_ = other.id_; unencrypted_metadata_ = other.unencrypted_metadata_; for_self_share_ = other.for_self_share_; + binding_id_ = other.binding_id_; return *this; } diff --git a/sharing/certificates/nearby_share_decrypted_public_certificate.h b/sharing/certificates/nearby_share_decrypted_public_certificate.h index 58e4a137..23818b02 100644 --- a/sharing/certificates/nearby_share_decrypted_public_certificate.h +++ b/sharing/certificates/nearby_share_decrypted_public_certificate.h @@ -19,6 +19,7 @@ #include #include +#include #include #include "absl/time/time.h" @@ -68,6 +69,8 @@ class NearbyShareDecryptedPublicCertificate { bool for_self_share() const { return for_self_share_; } + const std::string& binding_id() const { return binding_id_; } + // Verifies the |signature| of the signed |payload| using |public_key_|. // Returns true if verification was successful. bool VerifySignature(absl::Span payload, @@ -85,7 +88,7 @@ class NearbyShareDecryptedPublicCertificate { std::unique_ptr secret_key, std::vector public_key, std::vector id, nearby::sharing::proto::EncryptedMetadata unencrypted_metadata, - bool for_self_share); + bool for_self_share, std::string binding_id); // The start and end times of the certificate's validity period. To avoid // issues with clock skew, these times may be offset compared to the @@ -111,6 +114,10 @@ class NearbyShareDecryptedPublicCertificate { // Indicates if this public certificate is from another device owned by the // same user. bool for_self_share_ = false; + + // The binding id of device pair binding. If multiple bindings exist + // between two devices, it will return the newest binding_id. + std::string binding_id_; }; } // namespace sharing diff --git a/sharing/certificates/nearby_share_decrypted_public_certificate_test.cc b/sharing/certificates/nearby_share_decrypted_public_certificate_test.cc index ec650da6..19dab6aa 100644 --- a/sharing/certificates/nearby_share_decrypted_public_certificate_test.cc +++ b/sharing/certificates/nearby_share_decrypted_public_certificate_test.cc @@ -50,6 +50,7 @@ TEST(NearbyShareDecryptedPublicCertificateTest, Decrypt) { PublicCertificate proto_cert = GetNearbyShareTestPublicCertificate(kTestPublicCertificateVisibility); proto_cert.set_for_self_share(true); + proto_cert.set_binding_id("binding_id"); std::optional cert = NearbyShareDecryptedPublicCertificate::DecryptPublicCertificate( @@ -65,6 +66,7 @@ TEST(NearbyShareDecryptedPublicCertificateTest, Decrypt) { EXPECT_EQ(GetNearbyShareTestMetadata().SerializeAsString(), cert->unencrypted_metadata().SerializeAsString()); EXPECT_EQ(proto_cert.for_self_share(), cert->for_self_share()); + EXPECT_EQ(proto_cert.binding_id(), cert->binding_id()); } TEST(NearbyShareDecryptedPublicCertificateTest, Decrypt_IncorrectKeyFailure) { diff --git a/sharing/proto/rpc_resources.proto b/sharing/proto/rpc_resources.proto index 59c9d756..95f1435b 100644 --- a/sharing/proto/rpc_resources.proto +++ b/sharing/proto/rpc_resources.proto @@ -27,7 +27,7 @@ option optimize_for = LITE_RUNTIME; // How a Certificate is distributed is determined by who is on a user's contact // list. For example, if Will adds Ryan to his contact list, Ryan will have a // ShareTarget with Will's Certificate attached to it. -// NextId=11 +// NextId=13 message PublicCertificate { // The secret (symmetric) identifier used when identifying the ShareTarget's // BLE advertisement. @@ -66,6 +66,12 @@ message PublicCertificate { // Indicates if this public certificate corresponds to a device owned by the // current user. bool for_self_share = 10; + + reserved 11; + + // The binding id of device pair binding. If multiple bindings exist + // between two devices, it will return the newest binding_id. + string binding_id = 12; } // A member of a contact list. This is not inlined on the recommendation of @@ -159,4 +165,6 @@ message Device { // The public certificates generated and uploaded from local device, to be // shared with contacts. repeated PublicCertificate public_certificates = 4; + + reserved 5; } From 79f9436ed00c07a7478f684793c2733549cabde3 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 5 Mar 2026 12:25:15 -0800 Subject: [PATCH 48/49] Remove ununsed dependencies. PiperOrigin-RevId: 879192569 --- internal/platform/implementation/apple/BUILD | 1 - internal/platform/implementation/apple/webrtc.mm | 2 -- 2 files changed, 3 deletions(-) diff --git a/internal/platform/implementation/apple/BUILD b/internal/platform/implementation/apple/BUILD index 85b1dfba..5a292734 100644 --- a/internal/platform/implementation/apple/BUILD +++ b/internal/platform/implementation/apple/BUILD @@ -105,7 +105,6 @@ objc_library( "//internal/platform/implementation/apple/Mediums/Hotspot", "//internal/account", "//internal/crypto_cros", - "//internal/platform/implementation:account_manager", "//internal/platform:comm", "//internal/platform:logging", "//internal/platform:types", diff --git a/internal/platform/implementation/apple/webrtc.mm b/internal/platform/implementation/apple/webrtc.mm index d222876b..a7a50f79 100644 --- a/internal/platform/implementation/apple/webrtc.mm +++ b/internal/platform/implementation/apple/webrtc.mm @@ -25,10 +25,8 @@ #include "absl/status/status.h" #include "absl/strings/string_view.h" -#include "internal/account/account_manager_impl.h" #include "internal/platform/count_down_latch.h" #include "internal/platform/crypto.h" -#include "internal/platform/implementation/account_manager.h" #include "internal/platform/logging.h" #include "internal/platform/tachyon_express_signaling_messenger.h" #include "internal/proto/tachyon.pb.h" From 0191c50e2a0ba2ec0b80fdcec08cf8bbb0e83e2b Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 5 Mar 2026 14:07:28 -0800 Subject: [PATCH 49/49] Process FileSync messages. PiperOrigin-RevId: 879237616 --- sharing/BUILD | 3 ++ sharing/incoming_share_session.cc | 46 +++++++++++++++++++++++++- sharing/incoming_share_session.h | 16 ++++++++- sharing/nearby_sharing_service_impl.cc | 9 ++++- sharing/nearby_sharing_service_impl.h | 2 ++ 5 files changed, 73 insertions(+), 3 deletions(-) diff --git a/sharing/BUILD b/sharing/BUILD index da0faaeb..6aadfd1e 100644 --- a/sharing/BUILD +++ b/sharing/BUILD @@ -232,6 +232,8 @@ cc_library( "//internal/base:file_path", "//internal/base:files", "//internal/platform:types", + "//location/nearby/sharing/lib/sync:sync_config_prefs_cc_proto", + "//location/nearby/sharing/lib/sync:sync_manager", "//proto:sharing_enums_cc_proto", "//sharing/analytics", "//sharing/certificates", @@ -384,6 +386,7 @@ cc_library( "//internal/platform/implementation:types", "//location/nearby/sharing/lib/rpc:grpc_async_client_factory", "//location/nearby/sharing/lib/rpc:sharing_rpc_client", + "//location/nearby/sharing/lib/sync:sync_manager", "//proto:sharing_enums_cc_proto", "//sharing/analytics", "//sharing/certificates", diff --git a/sharing/incoming_share_session.cc b/sharing/incoming_share_session.cc index 2cb7fd91..870c7787 100644 --- a/sharing/incoming_share_session.cc +++ b/sharing/incoming_share_session.cc @@ -24,6 +24,8 @@ #include #include +#include "location/nearby/sharing/lib/sync/sync_config_prefs.pb.h" +#include "location/nearby/sharing/lib/sync/sync_manager.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/time/time.h" @@ -38,7 +40,6 @@ #include "sharing/nearby_connection.h" #include "sharing/nearby_connections_manager.h" #include "sharing/nearby_connections_types.h" -#include "sharing/paired_key_verification_runner.h" #include "sharing/payload_tracker.h" #include "sharing/proto/wire_format.pb.h" #include "sharing/share_session.h" @@ -56,9 +57,12 @@ using ::location::nearby::proto::sharing::OSType; using ::location::nearby::proto::sharing::ResponseToIntroduction; using ::nearby::sharing::service::proto::AppMetadata; using ::nearby::sharing::service::proto::ConnectionResponseFrame; +using ::nearby::sharing::service::proto::Frame; using ::nearby::sharing::service::proto::IntroductionFrame; +using ::nearby::sharing::service::proto::SyncConfig; using ::nearby::sharing::service::proto::V1Frame; using ::nearby::sharing::service::proto::WifiCredentials; +using ::nearby::sharing::sync::SyncConfigPrefs; } // namespace @@ -85,6 +89,7 @@ void IncomingShareSession::InvokeTransferUpdateCallback( std::optional IncomingShareSession::ProcessIntroduction( const IntroductionFrame& introduction_frame) { + session_phase_ = SessionPhase::kTransfer; int64_t file_size_sum = 0; int app_file_count = 0; for (const AppMetadata& apk : introduction_frame.app_metadata()) { @@ -494,4 +499,43 @@ void IncomingShareSession::PushPayloadTransferUpdateForTest( payload_updates_queue()->Queue(std::move(update)); } +void IncomingShareSession::ProcessSyncFrame( + SyncManager& sync_manager, + const nearby::sharing::service::proto::SyncFrame& sync_frame) { + if (session_phase_ != SessionPhase::kUninitialized) { + LOG(WARNING) << "Ignore SyncFrame received in unexpected session phase: " + << static_cast(session_phase_); + return; + } + // TODO: b/485304482 - Check that the connected device is authenticated and is + // part of a sync pairing. + if (!certificate().has_value()) { + LOG(WARNING) << "Ignore SyncFrame received from unauthenticated device."; + return; + } + if (false && + !sync_manager.IsFileSyncBinding(certificate()->binding_id())) { + LOG(WARNING) << "Ignore SyncFrame received in unexpected binding id: " + << certificate()->binding_id(); + return; + } + session_phase_ = SessionPhase::kSync; + if (sync_frame.has_handshake()) { + VLOG(1) << __func__ << ": Received FileSync Handshake"; + WriteSyncConfigFrame( + sync_manager.GetSyncConfig(certificate()->binding_id()) + .value_or(SyncConfigPrefs()) + .sync_config()); + } +} + +void IncomingShareSession::WriteSyncConfigFrame(const SyncConfig& config) { + Frame frame; + frame.set_version(Frame::V1); + V1Frame* v1_frame = frame.mutable_v1(); + v1_frame->set_type(V1Frame::FILE_SYNC); + *v1_frame->mutable_file_sync()->mutable_config() = config; + WriteFrame(frame); +} + } // namespace nearby::sharing diff --git a/sharing/incoming_share_session.h b/sharing/incoming_share_session.h index 1ec0e519..5a9d91ee 100644 --- a/sharing/incoming_share_session.h +++ b/sharing/incoming_share_session.h @@ -21,6 +21,7 @@ #include #include +#include "location/nearby/sharing/lib/sync/sync_manager.h" #include "absl/functional/any_invocable.h" #include "internal/base/file_path.h" #include "internal/platform/clock.h" @@ -29,7 +30,6 @@ #include "sharing/nearby_connection.h" #include "sharing/nearby_connections_manager.h" #include "sharing/nearby_connections_types.h" -#include "sharing/paired_key_verification_runner.h" #include "sharing/proto/wire_format.pb.h" #include "sharing/share_session.h" #include "sharing/share_target.h" @@ -104,10 +104,19 @@ class IncomingShareSession : public ShareSession { // Called when an incoming connection is established. void OnConnected(NearbyConnection* connection); + void ProcessSyncFrame(nearby::sharing::SyncManager& sync_manager, + const nearby::sharing::service::proto::SyncFrame& sync_frame); + protected: void InvokeTransferUpdateCallback(const TransferMetadata& metadata) override; private: + enum class SessionPhase { + kUninitialized, + kTransfer, + kSync, + }; + // Update file attachment paths with payload paths. bool UpdateFilePayloadPaths(); @@ -119,6 +128,9 @@ class IncomingShareSession : public ShareSession { // Returns true if all payloads were successfully finalized. bool FinalizePayloads(); + void WriteSyncConfigFrame( + const nearby::sharing::service::proto::SyncConfig& config); + std::function transfer_update_callback_; @@ -127,6 +139,8 @@ class IncomingShareSession : public ShareSession { // This alarm is used to disconnect the sharing connection if both sides do // not press accept within the timeout. std::unique_ptr mutual_acceptance_timeout_; + + SessionPhase session_phase_ = SessionPhase::kUninitialized; }; } // namespace nearby::sharing diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index 7c08717f..7749dfda 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -273,7 +273,8 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( absl::bind_front(&NearbySharingServiceImpl::NotifyShareTargetLost, this), absl::bind_front(&NearbySharingServiceImpl::OnOutgoingTransferUpdate, - this)) { + this)), + sync_manager_(&preference_manager_) { CHECK(nearby_connections_manager_); CHECK(analytics_recorder); @@ -2479,6 +2480,12 @@ void NearbySharingServiceImpl::OnIncomingSessionFrameRead( OnReceivedIntroduction(*session, frame->introduction()); // OnReceivedIntroduction will schedule the next ReadFrame. return; + case service::proto::V1Frame::FILE_SYNC: + if (NearbyFlags::GetInstance().GetBoolFlag( + config_package_nearby::nearby_sharing_feature::kEnableFileSync)) { + session->ProcessSyncFrame(sync_manager_, frame->file_sync()); + } + break; default: LOG(ERROR) << __func__ << ": Discarding unknown frame of type: " << static_cast(frame->type()); diff --git a/sharing/nearby_sharing_service_impl.h b/sharing/nearby_sharing_service_impl.h index bdf0b34b..7b17c0e8 100644 --- a/sharing/nearby_sharing_service_impl.h +++ b/sharing/nearby_sharing_service_impl.h @@ -28,6 +28,7 @@ #include #include "location/nearby/sharing/lib/rpc/sharing_rpc_client.h" +#include "location/nearby/sharing/lib/sync/sync_manager.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" @@ -529,6 +530,7 @@ class NearbySharingServiceImpl // If true, a new endpoint id will be generated at the next advertisement. bool force_new_endpoint_id_ = false; OutgoingTargetsManager outgoing_targets_manager_; + nearby::sharing::SyncManager sync_manager_; }; } // namespace nearby::sharing