[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / google_apis / gcm / gcm_client_impl.h
blob5c4c84ad172b7c3db78e00db0c5901e05c289d88
1 // Copyright 2013 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.
5 #ifndef GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_
6 #define GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_
8 #include <map>
9 #include <string>
10 #include <vector>
12 #include "base/compiler_specific.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/stl_util.h"
16 #include "google_apis/gcm/base/mcs_message.h"
17 #include "google_apis/gcm/engine/gcm_store.h"
18 #include "google_apis/gcm/engine/gservices_settings.h"
19 #include "google_apis/gcm/engine/mcs_client.h"
20 #include "google_apis/gcm/engine/registration_request.h"
21 #include "google_apis/gcm/engine/unregistration_request.h"
22 #include "google_apis/gcm/gcm_client.h"
23 #include "google_apis/gcm/monitoring/gcm_stats_recorder.h"
24 #include "google_apis/gcm/protocol/android_checkin.pb.h"
25 #include "google_apis/gcm/protocol/checkin.pb.h"
26 #include "net/base/net_log.h"
27 #include "net/url_request/url_request_context_getter.h"
29 class GURL;
31 namespace base {
32 class Clock;
33 class Time;
34 } // namespace base
36 namespace mcs_proto {
37 class DataMessageStanza;
38 } // namespace mcs_proto
40 namespace net {
41 class HttpNetworkSession;
42 } // namespace net
44 namespace gcm {
46 class CheckinRequest;
47 class ConnectionFactory;
48 class GCMClientImplTest;
50 // Helper class for building GCM internals. Allows tests to inject fake versions
51 // as necessary.
52 class GCM_EXPORT GCMInternalsBuilder {
53 public:
54 GCMInternalsBuilder();
55 virtual ~GCMInternalsBuilder();
57 virtual scoped_ptr<base::Clock> BuildClock();
58 virtual scoped_ptr<MCSClient> BuildMCSClient(
59 const std::string& version,
60 base::Clock* clock,
61 ConnectionFactory* connection_factory,
62 GCMStore* gcm_store,
63 GCMStatsRecorder* recorder);
64 virtual scoped_ptr<ConnectionFactory> BuildConnectionFactory(
65 const std::vector<GURL>& endpoints,
66 const net::BackoffEntry::Policy& backoff_policy,
67 scoped_refptr<net::HttpNetworkSession> network_session,
68 net::NetLog* net_log,
69 GCMStatsRecorder* recorder);
72 // Implements the GCM Client. It is used to coordinate MCS Client (communication
73 // with MCS) and other pieces of GCM infrastructure like Registration and
74 // Checkins. It also allows for registering user delegates that host
75 // applications that send and receive messages.
76 class GCM_EXPORT GCMClientImpl
77 : public GCMClient, public GCMStatsRecorder::Delegate {
78 public:
79 explicit GCMClientImpl(scoped_ptr<GCMInternalsBuilder> internals_builder);
80 virtual ~GCMClientImpl();
82 // Overridden from GCMClient:
83 virtual void Initialize(
84 const checkin_proto::ChromeBuildProto& chrome_build_proto,
85 const base::FilePath& store_path,
86 const std::vector<std::string>& account_ids,
87 const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner,
88 const scoped_refptr<net::URLRequestContextGetter>&
89 url_request_context_getter,
90 scoped_ptr<Encryptor> encryptor,
91 GCMClient::Delegate* delegate) OVERRIDE;
92 virtual void Start() OVERRIDE;
93 virtual void Stop() OVERRIDE;
94 virtual void CheckOut() OVERRIDE;
95 virtual void Register(const std::string& app_id,
96 const std::vector<std::string>& sender_ids) OVERRIDE;
97 virtual void Unregister(const std::string& app_id) OVERRIDE;
98 virtual void Send(const std::string& app_id,
99 const std::string& receiver_id,
100 const OutgoingMessage& message) OVERRIDE;
101 virtual void SetRecording(bool recording) OVERRIDE;
102 virtual void ClearActivityLogs() OVERRIDE;
103 virtual GCMStatistics GetStatistics() const OVERRIDE;
104 virtual void OnActivityRecorded() OVERRIDE;
106 private:
107 // State representation of the GCMClient.
108 // Any change made to this enum should have corresponding change in the
109 // GetStateString(...) function.
110 enum State {
111 // Uninitialized.
112 UNINITIALIZED,
113 // Initialized,
114 INITIALIZED,
115 // GCM store loading is in progress.
116 LOADING,
117 // Initial device checkin is in progress.
118 INITIAL_DEVICE_CHECKIN,
119 // Ready to accept requests.
120 READY,
123 // The check-in info for the user. Returned by the server.
124 struct GCM_EXPORT CheckinInfo {
125 CheckinInfo() : android_id(0), secret(0) {}
126 bool IsValid() const { return android_id != 0 && secret != 0; }
127 void Reset() {
128 android_id = 0;
129 secret = 0;
132 uint64 android_id;
133 uint64 secret;
136 // Collection of pending registration requests. Keys are app IDs, while values
137 // are pending registration requests to obtain a registration ID for
138 // requesting application.
139 typedef std::map<std::string, RegistrationRequest*>
140 PendingRegistrationRequests;
142 // Collection of pending unregistration requests. Keys are app IDs, while
143 // values are pending unregistration requests to disable the registration ID
144 // currently assigned to the application.
145 typedef std::map<std::string, UnregistrationRequest*>
146 PendingUnregistrationRequests;
148 friend class GCMClientImplTest;
150 // Returns text representation of the enum State.
151 std::string GetStateString() const;
153 // Callbacks for the MCSClient.
154 // Receives messages and dispatches them to relevant user delegates.
155 void OnMessageReceivedFromMCS(const gcm::MCSMessage& message);
156 // Receives confirmation of sent messages or information about errors.
157 void OnMessageSentToMCS(int64 user_serial_number,
158 const std::string& app_id,
159 const std::string& message_id,
160 MCSClient::MessageSendStatus status);
161 // Receives information about mcs_client_ errors.
162 void OnMCSError();
164 // Runs after GCM Store load is done to trigger continuation of the
165 // initialization.
166 void OnLoadCompleted(scoped_ptr<GCMStore::LoadResult> result);
167 // Initializes mcs_client_, which handles the connection to MCS.
168 void InitializeMCSClient(scoped_ptr<GCMStore::LoadResult> result);
169 // Complets the first time device checkin.
170 void OnFirstTimeDeviceCheckinCompleted(const CheckinInfo& checkin_info);
171 // Starts a login on mcs_client_.
172 void StartMCSLogin();
173 // Resets state to before initialization.
174 void ResetState();
175 // Sets state to ready. This will initiate the MCS login and notify the
176 // delegates.
177 void OnReady();
179 // Starts a first time device checkin.
180 void StartCheckin();
181 // Completes the device checkin request by parsing the |checkin_response|.
182 // Function also cleans up the pending checkin.
183 void OnCheckinCompleted(
184 const checkin_proto::AndroidCheckinResponse& checkin_response);
186 // Callback passed to GCMStore::SetGServicesSettings.
187 void SetGServicesSettingsCallback(bool success);
189 // Schedules next periodic device checkin and makes sure there is at most one
190 // pending checkin at a time. This function is meant to be called after a
191 // successful checkin.
192 void SchedulePeriodicCheckin();
193 // Gets the time until next checkin.
194 base::TimeDelta GetTimeToNextCheckin() const;
195 // Callback for setting last checkin time in the |gcm_store_|.
196 void SetLastCheckinTimeCallback(bool success);
198 // Callback for persisting device credentials in the |gcm_store_|.
199 void SetDeviceCredentialsCallback(bool success);
201 // Callback for persisting registration info in the |gcm_store_|.
202 void UpdateRegistrationCallback(bool success);
204 // Completes the registration request.
205 void OnRegisterCompleted(const std::string& app_id,
206 const std::vector<std::string>& sender_ids,
207 RegistrationRequest::Status status,
208 const std::string& registration_id);
210 // Completes the unregistration request.
211 void OnUnregisterCompleted(const std::string& app_id,
212 UnregistrationRequest::Status status);
214 // Completes the GCM store destroy request.
215 void OnGCMStoreDestroyed(bool success);
217 // Handles incoming data message and dispatches it the delegate of this class.
218 void HandleIncomingMessage(const gcm::MCSMessage& message);
220 // Fires OnMessageReceived event on the delegate of this class, based on the
221 // details in |data_message_stanza| and |message_data|.
222 void HandleIncomingDataMessage(
223 const mcs_proto::DataMessageStanza& data_message_stanza,
224 MessageData& message_data);
226 // Fires OnMessageSendError event on the delegate of this calss, based on the
227 // details in |data_message_stanza| and |message_data|.
228 void HandleIncomingSendError(
229 const mcs_proto::DataMessageStanza& data_message_stanza,
230 MessageData& message_data);
232 // Builder for the GCM internals (mcs client, etc.).
233 scoped_ptr<GCMInternalsBuilder> internals_builder_;
235 // Recorder that logs GCM activities.
236 GCMStatsRecorder recorder_;
238 // State of the GCM Client Implementation.
239 State state_;
241 GCMClient::Delegate* delegate_;
243 // Device checkin info (android ID and security token used by device).
244 CheckinInfo device_checkin_info_;
246 // Clock used for timing of retry logic. Passed in for testing. Owned by
247 // GCMClientImpl.
248 scoped_ptr<base::Clock> clock_;
250 // Information about the chrome build.
251 // TODO(fgorski): Check if it can be passed in constructor and made const.
252 checkin_proto::ChromeBuildProto chrome_build_proto_;
254 // Persistent data store for keeping device credentials, messages and user to
255 // serial number mappings.
256 scoped_ptr<GCMStore> gcm_store_;
258 scoped_refptr<net::HttpNetworkSession> network_session_;
259 net::BoundNetLog net_log_;
260 scoped_ptr<ConnectionFactory> connection_factory_;
261 scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
263 // Controls receiving and sending of packets and reliable message queueing.
264 scoped_ptr<MCSClient> mcs_client_;
266 scoped_ptr<CheckinRequest> checkin_request_;
267 std::vector<std::string> account_ids_;
269 // Cached registration info.
270 RegistrationInfoMap registrations_;
272 // Currently pending registration requests. GCMClientImpl owns the
273 // RegistrationRequests.
274 PendingRegistrationRequests pending_registration_requests_;
275 STLValueDeleter<PendingRegistrationRequests>
276 pending_registration_requests_deleter_;
278 // Currently pending unregistration requests. GCMClientImpl owns the
279 // UnregistrationRequests.
280 PendingUnregistrationRequests pending_unregistration_requests_;
281 STLValueDeleter<PendingUnregistrationRequests>
282 pending_unregistration_requests_deleter_;
284 // G-services settings that were provided by MCS.
285 GServicesSettings gservices_settings_;
287 // Time of the last successful checkin.
288 base::Time last_checkin_time_;
290 // Factory for creating references when scheduling periodic checkin.
291 base::WeakPtrFactory<GCMClientImpl> periodic_checkin_ptr_factory_;
293 // Factory for creating references in callbacks.
294 base::WeakPtrFactory<GCMClientImpl> weak_ptr_factory_;
296 DISALLOW_COPY_AND_ASSIGN(GCMClientImpl);
299 } // namespace gcm
301 #endif // GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_