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_ENGINE_MCS_CLIENT_H_
6 #define GOOGLE_APIS_GCM_ENGINE_MCS_CLIENT_H_
13 #include "base/files/file_path.h"
14 #include "base/memory/linked_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "google_apis/gcm/base/gcm_export.h"
17 #include "google_apis/gcm/base/mcs_message.h"
18 #include "google_apis/gcm/engine/connection_handler.h"
19 #include "google_apis/gcm/engine/gcm_store.h"
20 #include "google_apis/gcm/engine/heartbeat_manager.h"
29 } // namespace protobuf
39 class ConnectionFactory;
40 struct ReliablePacketInfo;
42 // An MCS client. This client is in charge of all communications with an
43 // MCS endpoint, and is capable of reliably sending/receiving GCM messages.
44 // NOTE: Not thread safe. This class should live on the same thread as that
45 // network requests are performed on.
46 class GCM_EXPORT MCSClient {
48 // Any change made to this enum should have corresponding change in the
49 // GetStateString(...) function.
51 UNINITIALIZED, // Uninitialized.
52 LOADED, // GCM Load finished, waiting to connect.
53 CONNECTING, // Connection in progress.
54 CONNECTED, // Connected and running.
57 enum MessageSendStatus {
58 // Message was queued succcessfully.
60 // Message was sent to the server and the ACK was received.
62 // Message not saved, because total queue size limit reached.
63 QUEUE_SIZE_LIMIT_REACHED,
64 // Messgae not saved, because app queue size limit reached.
65 APP_QUEUE_SIZE_LIMIT_REACHED,
66 // Message too large to send.
68 // Message not send becuase of TTL = 0 and no working connection.
69 NO_CONNECTION_ON_ZERO_TTL,
70 // Message exceeded TTL.
74 // Callback for MCSClient's error conditions.
75 // TODO(fgorski): Keeping it as a callback with intention to add meaningful
77 typedef base::Callback<void()> ErrorCallback;
78 // Callback when a message is received.
79 typedef base::Callback<void(const MCSMessage& message)>
80 OnMessageReceivedCallback;
81 // Callback when a message is sent (and receipt has been acknowledged by
83 typedef base::Callback<
84 void(int64 user_serial_number,
85 const std::string& app_id,
86 const std::string& message_id,
87 MessageSendStatus status)> OnMessageSentCallback;
89 MCSClient(const std::string& version_string,
91 ConnectionFactory* connection_factory,
95 // Initialize the client. Will load any previous id/token information as well
96 // as unacknowledged message information from the GCM storage, if it exists,
97 // passing the id/token information back via |initialization_callback| along
98 // with a |success == true| result. If no GCM information is present (and
99 // this is therefore a fresh client), a clean GCM store will be created and
100 // values of 0 will be returned via |initialization_callback| with
101 // |success == true|.
102 /// If an error loading the GCM store is encountered,
103 // |initialization_callback| will be invoked with |success == false|.
104 void Initialize(const ErrorCallback& initialization_callback,
105 const OnMessageReceivedCallback& message_received_callback,
106 const OnMessageSentCallback& message_sent_callback,
107 scoped_ptr<GCMStore::LoadResult> load_result);
109 // Logs the client into the server. Client must be initialized.
110 // |android_id| and |security_token| are optional if this is not a new
111 // client, else they must be non-zero.
112 // Successful login will result in |message_received_callback| being invoked
113 // with a valid LoginResponse.
114 // Login failure (typically invalid id/token) will shut down the client, and
115 // |initialization_callback| to be invoked with |success = false|.
116 virtual void Login(uint64 android_id, uint64 security_token);
118 // Sends a message, with or without reliable message queueing (RMQ) support.
119 // Will asynchronously invoke the OnMessageSent callback regardless.
120 // Whether to use RMQ depends on whether the protobuf has |ttl| set or not.
121 // |ttl == 0| denotes the message should only be sent if the connection is
122 // open. |ttl > 0| will keep the message saved for |ttl| seconds, after which
123 // it will be dropped if it was unable to be sent. When a message is dropped,
124 // |message_sent_callback_| is invoked with a TTL expiration error.
125 virtual void SendMessage(const MCSMessage& message);
127 // Returns the current state of the client.
128 State state() const { return state_; }
130 // Returns text representation of the state enum.
131 std::string GetStateString() const;
134 typedef uint32 StreamId;
135 typedef std::string PersistentId;
136 typedef std::vector<StreamId> StreamIdList;
137 typedef std::vector<PersistentId> PersistentIdList;
138 typedef std::map<StreamId, PersistentId> StreamIdToPersistentIdMap;
139 typedef linked_ptr<ReliablePacketInfo> MCSPacketInternal;
141 // Resets the internal state and builds a new login request, acknowledging
142 // any pending server-to-device messages and rebuilding the send queue
143 // from all unacknowledged device-to-server messages.
144 // Should only be called when the connection has been reset.
145 void ResetStateAndBuildLoginRequest(mcs_proto::LoginRequest* request);
147 // Send a heartbeat to the MCS server.
148 void SendHeartbeat();
150 // GCM Store callback.
151 void OnGCMUpdateFinished(bool success);
153 // Attempt to send a message.
154 void MaybeSendMessage();
156 // Helper for sending a protobuf along with any unacknowledged ids to the
158 void SendPacketToWire(ReliablePacketInfo* packet_info);
160 // Handle a data message sent to the MCS client system from the MCS server.
161 void HandleMCSDataMesssage(
162 scoped_ptr<google::protobuf::MessageLite> protobuf);
164 // Handle a packet received over the wire.
165 void HandlePacketFromWire(scoped_ptr<google::protobuf::MessageLite> protobuf);
167 // ReliableMessageQueue acknowledgment helpers.
168 // Handle a StreamAck sent by the server confirming receipt of all
169 // messages up to the message with stream id |last_stream_id_received|.
170 void HandleStreamAck(StreamId last_stream_id_received_);
171 // Handle a SelectiveAck sent by the server confirming all messages
173 void HandleSelectiveAck(const PersistentIdList& id_list);
174 // Handle server confirmation of a device message, including device's
175 // acknowledgment of receipt of messages.
176 void HandleServerConfirmedReceipt(StreamId device_stream_id);
178 // Generates a new persistent id for messages.
179 // Virtual for testing.
180 virtual PersistentId GetNextPersistentId();
182 // Helper for the heartbeat manager to signal a connection reset.
183 void OnConnectionResetByHeartbeat();
185 // Runs the message_sent_callback_ with send |status| of the |protobuf|.
186 void NotifyMessageSendStatus(const google::protobuf::MessageLite& protobuf,
187 MessageSendStatus status);
189 // Pops the next message from the front of the send queue (cleaning up
190 // any associated state).
191 MCSPacketInternal PopMessageForSend();
193 // Local version string. Sent on login.
194 const std::string version_string_;
196 // Clock for enforcing TTL. Passed in for testing.
197 base::Clock* const clock_;
202 // Callbacks for owner.
203 ErrorCallback mcs_error_callback_;
204 OnMessageReceivedCallback message_received_callback_;
205 OnMessageSentCallback message_sent_callback_;
207 // The android id and security token in use by this device.
209 uint64 security_token_;
211 // Factory for creating new connections and connection handlers.
212 ConnectionFactory* connection_factory_;
214 // Connection handler to handle all over-the-wire protocol communication
215 // with the mobile connection server.
216 ConnectionHandler* connection_handler_;
218 // ----- Reliablie Message Queue section -----
219 // Note: all queues/maps are ordered from oldest (front/begin) message to
220 // most recent (back/end).
222 // Send/acknowledge queues.
223 std::deque<MCSPacketInternal> to_send_;
224 std::deque<MCSPacketInternal> to_resend_;
226 // Map of collapse keys to their pending messages.
227 std::map<CollapseKey, ReliablePacketInfo*> collapse_key_map_;
229 // Last device_to_server stream id acknowledged by the server.
230 StreamId last_device_to_server_stream_id_received_;
231 // Last server_to_device stream id acknowledged by this device.
232 StreamId last_server_to_device_stream_id_received_;
233 // The stream id for the last sent message. A new message should consume
234 // stream_id_out_ + 1.
235 StreamId stream_id_out_;
236 // The stream id of the last received message. The LoginResponse will always
237 // have a stream id of 1, and stream ids increment by 1 for each received
239 StreamId stream_id_in_;
241 // The server messages that have not been acked by the device yet. Keyed by
243 StreamIdToPersistentIdMap unacked_server_ids_;
245 // Those server messages that have been acked. They must remain tracked
246 // until the ack message is itself confirmed. The list of all message ids
247 // acknowledged are keyed off the device stream id of the message that
248 // acknowledged them.
249 std::map<StreamId, PersistentIdList> acked_server_ids_;
251 // Those server messages from a previous connection that were not fully
252 // acknowledged. They do not have associated stream ids, and will be
253 // acknowledged on the next login attempt.
254 PersistentIdList restored_unackeds_server_ids_;
256 // The GCM persistent store. Not owned.
257 GCMStore* gcm_store_;
259 // Manager to handle triggering/detecting heartbeats.
260 HeartbeatManager heartbeat_manager_;
262 base::WeakPtrFactory<MCSClient> weak_ptr_factory_;
264 DISALLOW_COPY_AND_ASSIGN(MCSClient);
269 #endif // GOOGLE_APIS_GCM_ENGINE_MCS_CLIENT_H_