1 // Copyright 2014 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_HEARTBEAT_MANAGER_H_
6 #define GOOGLE_APIS_GCM_ENGINE_HEARTBEAT_MANAGER_H_
8 #include "base/callback.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/memory/weak_ptr.h"
12 #include "google_apis/gcm/base/gcm_export.h"
19 class HeartbeatConfig;
24 // A heartbeat management class, capable of sending and handling heartbeat
25 // receipt/failures and triggering reconnection as necessary.
26 class GCM_EXPORT HeartbeatManager {
28 explicit HeartbeatManager(scoped_ptr<base::Timer> heartbeat_timer);
31 // Start the heartbeat logic.
32 // |send_heartbeat_callback_| is the callback the HeartbeatManager uses to
33 // send new heartbeats. Only one heartbeat can be outstanding at a time.
34 void Start(const base::Closure& send_heartbeat_callback,
35 const base::Closure& trigger_reconnect_callback);
37 // Stop the timer. Start(..) must be called again to begin sending heartbeats
41 // Reset the heartbeat timer. It is valid to call this even if no heartbeat
42 // is associated with the ack (for example if another signal is used to
43 // determine that the connection is alive).
44 void OnHeartbeatAcked();
46 // Updates the current heartbeat interval.
47 void UpdateHeartbeatConfig(const mcs_proto::HeartbeatConfig& config);
49 // Returns the next scheduled heartbeat time. A null time means
50 // no heartbeat is pending. If non-null and less than the
51 // current time (in ticks), the heartbeat has been triggered and an ack is
53 base::TimeTicks GetNextHeartbeatTime() const;
56 // Helper method to send heartbeat on timer trigger.
57 void OnHeartbeatTriggered();
59 // Periodic check to see if the heartbeat has been missed due to some system
60 // issue (e.g. the machine was suspended and the timer did not account for
62 void CheckForMissedHeartbeat();
65 // Restarts the heartbeat timer.
68 // The base::Time at which the heartbeat timer is expected to fire. Used to
69 // check if a heartbeat was somehow lost/delayed.
70 base::Time heartbeat_expected_time_;
72 // Whether the last heartbeat ping sent has been acknowledged or not.
73 bool waiting_for_ack_;
75 // The current heartbeat interval.
76 int heartbeat_interval_ms_;
77 // The most recent server-provided heartbeat interval (0 if none has been
79 int server_interval_ms_;
81 // Timer for triggering heartbeats.
82 scoped_ptr<base::Timer> heartbeat_timer_;
84 // Callbacks for interacting with the the connection.
85 base::Closure send_heartbeat_callback_;
86 base::Closure trigger_reconnect_callback_;
88 base::WeakPtrFactory<HeartbeatManager> weak_ptr_factory_;
90 DISALLOW_COPY_AND_ASSIGN(HeartbeatManager);
95 #endif // GOOGLE_APIS_GCM_ENGINE_HEARTBEAT_MANAGER_H_