device_activity_client.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef ASH_COMPONENTS_DEVICE_ACTIVITY_DEVICE_ACTIVITY_CLIENT_H_
  5. #define ASH_COMPONENTS_DEVICE_ACTIVITY_DEVICE_ACTIVITY_CLIENT_H_
  6. #include <memory>
  7. #include "base/component_export.h"
  8. #include "base/containers/queue.h"
  9. #include "base/memory/scoped_refptr.h"
  10. #include "base/memory/weak_ptr.h"
  11. #include "base/time/time.h"
  12. #include "base/timer/elapsed_timer.h"
  13. #include "base/timer/timer.h"
  14. #include "chromeos/ash/components/network/network_state.h"
  15. #include "chromeos/ash/components/network/network_state_handler.h"
  16. #include "chromeos/ash/components/network/network_state_handler_observer.h"
  17. #include "services/network/public/cpp/resource_request.h"
  18. #include "third_party/private_membership/src/private_membership_rlwe_client.h"
  19. #include "url/gurl.h"
  20. namespace network {
  21. class SimpleURLLoader;
  22. class SharedURLLoaderFactory;
  23. } // namespace network
  24. namespace ash {
  25. class SystemClockSyncObservation;
  26. namespace device_activity {
  27. // Forward declaration from device_active_use_case.h
  28. class DeviceActiveUseCase;
  29. // Create a delegate which can be used to create fakes in unit tests.
  30. // Fake via. delegate is required for creating deterministic unit tests.
  31. class COMPONENT_EXPORT(ASH_DEVICE_ACTIVITY) PsmDelegate {
  32. public:
  33. virtual ~PsmDelegate() = default;
  34. virtual rlwe::StatusOr<
  35. std::unique_ptr<private_membership::rlwe::PrivateMembershipRlweClient>>
  36. CreatePsmClient(private_membership::rlwe::RlweUseCase use_case,
  37. const std::vector<private_membership::rlwe::RlwePlaintextId>&
  38. plaintext_ids) = 0;
  39. };
  40. // Observes the network for connected state to determine whether the device
  41. // is active in a given window.
  42. // State Transition flow:
  43. // kIdle -> kCheckingMembershipOprf -> kCheckingMembershipQuery
  44. // -> kIdle or (kCheckingIn -> kIdle)
  45. //
  46. // TODO(https://crbug.com/1302175): Move methods passing DeviceActiveUseCase* to
  47. // methods of DeviceActiveUseCase class.
  48. class COMPONENT_EXPORT(ASH_DEVICE_ACTIVITY) DeviceActivityClient
  49. : public NetworkStateHandlerObserver {
  50. public:
  51. // Tracks the state the client is in, given the use case (i.e DAILY).
  52. // These values are persisted to logs. Entries should not be renumbered and
  53. // numeric values should never be reused.
  54. enum class State {
  55. kUnknown = 0, // Default value, typically we should never be in this state.
  56. kIdle = 1, // Wait on network connection OR |report_timer_| to trigger.
  57. kCheckingMembershipOprf = 2, // Phase 1 of the |CheckMembership| request.
  58. kCheckingMembershipQuery = 3, // Phase 2 of the |CheckMembership| request.
  59. kCheckingIn = 4, // |CheckIn| PSM device active request.
  60. kHealthCheck = 5, // Query to perform server health check.
  61. kMaxValue = kHealthCheck,
  62. };
  63. // Categorize PSM response codes which will be used when bucketing UMA
  64. // histograms.
  65. //
  66. // These values are persisted to logs. Entries should not be renumbered and
  67. // numeric values should never be reused.
  68. enum class PsmResponse {
  69. kUnknown = 0, // Uncategorized response type returned.
  70. kSuccess = 1, // Successfully completed PSM request.
  71. kError = 2, // Error completing PSM request.
  72. kTimeout = 3, // Timed out while completing PSM request.
  73. kMaxValue = kTimeout,
  74. };
  75. // Categorize device activity methods which will be used when bucketing UMA
  76. // histograms by number of calls to each method.
  77. // Enum listed keys map to methods in |DeviceActivityController| and
  78. // |DeviceActivityClient|.
  79. //
  80. // These values are persisted to logs. Entries should not be renumbered and
  81. // numeric values should never be reused.
  82. enum class DeviceActivityMethod {
  83. kUnknown = 0,
  84. kDeviceActivityControllerConstructor = 1,
  85. kDeviceActivityControllerDestructor = 2,
  86. kDeviceActivityControllerStart = 3,
  87. kDeviceActivityControllerOnPsmDeviceActiveSecretFetched = 4,
  88. kDeviceActivityControllerOnMachineStatisticsLoaded = 5,
  89. kDeviceActivityClientConstructor = 6,
  90. kDeviceActivityClientDestructor = 7,
  91. kDeviceActivityClientOnNetworkOnline = 8,
  92. kDeviceActivityClientOnNetworkOffline = 9,
  93. kDeviceActivityClientReportUseCases = 10,
  94. kDeviceActivityClientCancelUseCases = 11,
  95. kDeviceActivityClientTransitionOutOfIdle = 12,
  96. kDeviceActivityClientTransitionToHealthCheck = 13,
  97. kDeviceActivityClientOnHealthCheckDone = 14,
  98. kDeviceActivityClientTransitionToCheckMembershipOprf = 15,
  99. kDeviceActivityClientOnCheckMembershipOprfDone = 16,
  100. kDeviceActivityClientTransitionToCheckMembershipQuery = 17,
  101. kDeviceActivityClientOnCheckMembershipQueryDone = 18,
  102. kDeviceActivityClientTransitionToCheckIn = 19,
  103. kDeviceActivityClientOnCheckInDone = 20,
  104. kDeviceActivityClientTransitionToIdle = 21,
  105. kDeviceActivityClientOnSystemClockSyncResult = 22,
  106. kDeviceActivityClientReportingTriggeredByTimer = 23,
  107. kMaxValue = kDeviceActivityClientReportingTriggeredByTimer,
  108. };
  109. // Records UMA histogram for number of times various methods are called in
  110. // device_activity/.
  111. static void RecordDeviceActivityMethodCalled(
  112. DeviceActivityMethod method_name);
  113. // Fires device active pings while the device network is connected.
  114. DeviceActivityClient(
  115. NetworkStateHandler* handler,
  116. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
  117. std::unique_ptr<PsmDelegate> psm_delegate,
  118. std::unique_ptr<base::RepeatingTimer> report_timer,
  119. const std::string& fresnel_server_url,
  120. const std::string& api_key,
  121. std::vector<std::unique_ptr<DeviceActiveUseCase>> use_cases);
  122. DeviceActivityClient(const DeviceActivityClient&) = delete;
  123. DeviceActivityClient& operator=(const DeviceActivityClient&) = delete;
  124. ~DeviceActivityClient() override;
  125. // Returns pointer to |report_timer_|.
  126. base::RepeatingTimer* GetReportTimer();
  127. // NetworkStateHandlerObserver overridden method.
  128. void DefaultNetworkChanged(const NetworkState* network) override;
  129. State GetState() const;
  130. // Used for testing.
  131. std::vector<DeviceActiveUseCase*> GetUseCases() const;
  132. private:
  133. // |report_timer_| triggers method to retry reporting device actives if
  134. // necessary.
  135. void ReportingTriggeredByTimer();
  136. // Handles device network connecting successfully.
  137. void OnNetworkOnline();
  138. // Called when the system clock has been synchronized or a timeout has been
  139. // reached while waiting for the system clock sync.
  140. // Report use cases if the system clock sync was successful.
  141. void OnSystemClockSyncResult(bool system_clock_synchronized);
  142. // Handle device network disconnecting successfully.
  143. void OnNetworkOffline();
  144. // Return Fresnel server network request endpoints determined by the |state_|.
  145. GURL GetFresnelURL() const;
  146. // Called when device network comes online or |report_timer_| executing.
  147. // Reports each use case in a sequenced order.
  148. void ReportUseCases();
  149. // Called when device network goes offline.
  150. // Since the network connection is severed, any pending network requests will
  151. // be cleaned up.
  152. // After calling this method: |state_| set to |kIdle|.
  153. void CancelUseCases();
  154. // Callback from |ReportUseCases()| handling whether a use case needs
  155. // to be reported for the time window.
  156. void TransitionOutOfIdle(DeviceActiveUseCase* current_use_case);
  157. // Send Health Check network request and update |state_|.
  158. // Before calling this method: |state_| is expected to be |kIdle|.
  159. // After calling this method: |state_| set to |kHealthCheck|.
  160. void TransitionToHealthCheck();
  161. // Callback from asynchronous method |TransitionToHealthCheck|.
  162. void OnHealthCheckDone(std::unique_ptr<std::string> response_body);
  163. // Send Oprf network request and update |state_|.
  164. // Before calling this method: |state_| is expected to be |kIdle|.
  165. // After calling this method: |state_| set to |kCheckingMembershipOprf|.
  166. void TransitionToCheckMembershipOprf(DeviceActiveUseCase* current_use_case);
  167. // Callback from asynchronous method |TransitionToCheckMembershipOprf|.
  168. void OnCheckMembershipOprfDone(DeviceActiveUseCase* current_use_case,
  169. std::unique_ptr<std::string> response_body);
  170. // Send Query network request and update |state_|.
  171. // Before calling this method: |state_| is expected to be
  172. // |kCheckingMembershipOprf|.
  173. // After calling this method: |state_| set to |kCheckingMembershipQuery|.
  174. void TransitionToCheckMembershipQuery(
  175. const private_membership::rlwe::PrivateMembershipRlweOprfResponse&
  176. oprf_response,
  177. DeviceActiveUseCase* current_use_case);
  178. // Callback from asynchronous method |TransitionToCheckMembershipQuery|.
  179. // Check in PSM id based on |response_body| from CheckMembershipQuery.
  180. void OnCheckMembershipQueryDone(DeviceActiveUseCase* current_use_case,
  181. std::unique_ptr<std::string> response_body);
  182. // Send Import network request and update |state_|.
  183. // Before calling this method: |state_| is expected to be either
  184. // |kCheckingMembershipQuery| or |kIdle|.
  185. // After calling this method: |state_| set to |kCheckingIn|.
  186. void TransitionToCheckIn(DeviceActiveUseCase* current_use_case);
  187. // Callback from asynchronous method |TransitionToCheckIn|.
  188. void OnCheckInDone(DeviceActiveUseCase* current_use_case,
  189. std::unique_ptr<std::string> response_body);
  190. // Updates |state_| to |kIdle| and resets state based member variables.
  191. void TransitionToIdle(DeviceActiveUseCase* current_use_case);
  192. // Tracks the current state of the DeviceActivityClient.
  193. State state_ = State::kIdle;
  194. // Keep track of whether the device is connected to the network.
  195. bool network_connected_ = false;
  196. // Time the device last transitioned out of idle state.
  197. base::Time last_transition_out_of_idle_time_;
  198. // Generated when entering new |state_| and reset when leaving |state_|.
  199. // This field is only used to determine total state duration, which is
  200. // reported to UMA via. histograms.
  201. base::ElapsedTimer state_timer_;
  202. // Tracks the visible networks and their properties.
  203. // |network_state_handler_| outlives the lifetime of this class.
  204. // |ChromeBrowserMainPartsAsh| initializes the network_state object as
  205. // part of the |dbus_services_|, before |DeviceActivityClient| is initialized.
  206. // Similarly, |DeviceActivityClient| is destructed before |dbus_services_|.
  207. NetworkStateHandler* const network_state_handler_;
  208. // Shared |url_loader_| object used to handle ongoing network requests.
  209. std::unique_ptr<network::SimpleURLLoader> url_loader_;
  210. // The URLLoaderFactory we use to issue network requests.
  211. // |url_loader_factory_| outlives |url_loader_|.
  212. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  213. // Abstract class used to generate the |psm_rlwe_client_|.
  214. std::unique_ptr<PsmDelegate> psm_delegate_;
  215. // Tries reporting device actives every |kTimeToRepeat| from when this class
  216. // is initialized. Time of class initialization depends on when the device is
  217. // turned on (when |ChromeBrowserMainPartsAsh::PostBrowserStart| is run).
  218. std::unique_ptr<base::RepeatingTimer> report_timer_;
  219. // Base Fresnel server URL is set by |DeviceActivityClient| constructor.
  220. const std::string fresnel_base_url_;
  221. // API key used to authenticate with the Fresnel server. This key is read from
  222. // the chrome-internal repository and is not publicly exposed in Chromium.
  223. const std::string api_key_;
  224. // Vector of supported use cases containing the methods and metadata required
  225. // to counting device actives.
  226. const std::vector<std::unique_ptr<DeviceActiveUseCase>> use_cases_;
  227. // Contains the use cases to report active for.
  228. // The front of the queue represents the use case trying to be reported.
  229. // |ReportUseCases| initializes this field using the |use_cases_|.
  230. // |TransitionToIdle| pops from this field to report each pending use case.
  231. std::queue<DeviceActiveUseCase*> pending_use_cases_;
  232. // Used to wait until the system clock to be synchronized.
  233. std::unique_ptr<SystemClockSyncObservation> system_clock_sync_observation_;
  234. // Automatically cancels callbacks when the referent of weakptr gets
  235. // destroyed.
  236. base::WeakPtrFactory<DeviceActivityClient> weak_factory_{this};
  237. };
  238. } // namespace device_activity
  239. } // namespace ash
  240. #endif // ASH_COMPONENTS_DEVICE_ACTIVITY_DEVICE_ACTIVITY_CLIENT_H_