1 // Copyright 2012 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 SYNC_ENGINE_SYNC_SCHEDULER_IMPL_H_
6 #define SYNC_ENGINE_SYNC_SCHEDULER_IMPL_H_
11 #include "base/callback.h"
12 #include "base/cancelable_callback.h"
13 #include "base/compiler_specific.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/memory/linked_ptr.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/weak_ptr.h"
18 #include "base/threading/non_thread_safe.h"
19 #include "base/time/time.h"
20 #include "base/timer/timer.h"
21 #include "sync/base/sync_export.h"
22 #include "sync/engine/net/server_connection_manager.h"
23 #include "sync/engine/nudge_source.h"
24 #include "sync/engine/sync_scheduler.h"
25 #include "sync/engine/syncer.h"
26 #include "sync/internal_api/public/engine/polling_constants.h"
27 #include "sync/internal_api/public/util/weak_handle.h"
28 #include "sync/sessions/nudge_tracker.h"
29 #include "sync/sessions/sync_session.h"
30 #include "sync/sessions/sync_session_context.h"
34 class BackoffDelayProvider
;
37 struct ModelNeutralState
;
40 class SYNC_EXPORT_PRIVATE SyncSchedulerImpl
41 : public SyncScheduler
,
42 public base::NonThreadSafe
{
44 // |name| is a display string to identify the syncer thread. Takes
45 // |ownership of |syncer| and |delay_provider|.
46 SyncSchedulerImpl(const std::string
& name
,
47 BackoffDelayProvider
* delay_provider
,
48 sessions::SyncSessionContext
* context
,
52 virtual ~SyncSchedulerImpl();
54 virtual void Start(Mode mode
) OVERRIDE
;
55 virtual void ScheduleConfiguration(
56 const ConfigurationParams
& params
) OVERRIDE
;
57 virtual void Stop() OVERRIDE
;
58 virtual void ScheduleLocalNudge(
59 const base::TimeDelta
& desired_delay
,
61 const tracked_objects::Location
& nudge_location
) OVERRIDE
;
62 virtual void ScheduleLocalRefreshRequest(
63 const base::TimeDelta
& desired_delay
,
65 const tracked_objects::Location
& nudge_location
) OVERRIDE
;
66 virtual void ScheduleInvalidationNudge(
67 const base::TimeDelta
& desired_delay
,
68 syncer::ModelType type
,
69 scoped_ptr
<InvalidationInterface
> invalidation
,
70 const tracked_objects::Location
& nudge_location
) OVERRIDE
;
71 virtual void SetNotificationsEnabled(bool notifications_enabled
) OVERRIDE
;
73 virtual base::TimeDelta
GetSessionsCommitDelay() const OVERRIDE
;
75 virtual void OnCredentialsUpdated() OVERRIDE
;
76 virtual void OnConnectionStatusChange() OVERRIDE
;
78 // SyncSession::Delegate implementation.
79 virtual void OnThrottled(const base::TimeDelta
& throttle_duration
) OVERRIDE
;
80 virtual void OnTypesThrottled(
82 const base::TimeDelta
& throttle_duration
) OVERRIDE
;
83 virtual bool IsCurrentlyThrottled() OVERRIDE
;
84 virtual void OnReceivedShortPollIntervalUpdate(
85 const base::TimeDelta
& new_interval
) OVERRIDE
;
86 virtual void OnReceivedLongPollIntervalUpdate(
87 const base::TimeDelta
& new_interval
) OVERRIDE
;
88 virtual void OnReceivedSessionsCommitDelay(
89 const base::TimeDelta
& new_delay
) OVERRIDE
;
90 virtual void OnReceivedClientInvalidationHintBufferSize(int size
) OVERRIDE
;
91 virtual void OnSyncProtocolError(
92 const SyncProtocolError
& sync_protocol_error
) OVERRIDE
;
93 virtual void OnReceivedGuRetryDelay(const base::TimeDelta
& delay
) OVERRIDE
;
94 virtual void OnReceivedMigrationRequest(syncer::ModelTypeSet types
) OVERRIDE
;
96 // Returns true if the client is currently in exponential backoff.
97 bool IsBackingOff() const;
101 // Non-canary jobs respect exponential backoff.
103 // Canary jobs bypass exponential backoff, so use with extreme caution.
107 enum PollAdjustType
{
108 // Restart the poll interval.
110 // Restart the poll interval only if its length has changed.
114 friend class SyncSchedulerTest
;
115 friend class SyncSchedulerWhiteboxTest
;
116 friend class SyncerTest
;
118 FRIEND_TEST_ALL_PREFIXES(SyncSchedulerTest
, TransientPollFailure
);
119 FRIEND_TEST_ALL_PREFIXES(SyncSchedulerTest
,
120 ServerConnectionChangeDuringBackoff
);
121 FRIEND_TEST_ALL_PREFIXES(SyncSchedulerTest
,
122 ConnectionChangeCanaryPreemptedByNudge
);
123 FRIEND_TEST_ALL_PREFIXES(BackoffTriggersSyncSchedulerTest
,
124 FailGetEncryptionKey
);
125 FRIEND_TEST_ALL_PREFIXES(SyncSchedulerTest
, SuccessfulRetry
);
126 FRIEND_TEST_ALL_PREFIXES(SyncSchedulerTest
, FailedRetry
);
127 FRIEND_TEST_ALL_PREFIXES(SyncSchedulerTest
, ReceiveNewRetryDelay
);
129 struct SYNC_EXPORT_PRIVATE WaitInterval
{
131 // Uninitialized state, should not be set in practice.
133 // We enter a series of increasingly longer WaitIntervals if we experience
134 // repeated transient failures. We retry at the end of each interval.
136 // A server-initiated throttled interval. We do not allow any syncing
137 // during such an interval.
142 WaitInterval(Mode mode
, base::TimeDelta length
);
144 static const char* GetModeString(Mode mode
);
147 base::TimeDelta length
;
150 static const char* GetModeString(Mode mode
);
152 // Invoke the syncer to perform a nudge job.
153 void DoNudgeSyncSessionJob(JobPriority priority
);
155 // Invoke the syncer to perform a configuration job.
156 void DoConfigurationSyncSessionJob(JobPriority priority
);
158 // Helper function for Do{Nudge,Configuration}SyncSessionJob.
160 const sessions::ModelNeutralState
& model_neutral_state
);
162 // Invoke the Syncer to perform a poll job.
163 void DoPollSyncSessionJob();
165 // Helper function to calculate poll interval.
166 base::TimeDelta
GetPollInterval();
168 // Adjusts the poll timer to account for new poll interval, and possibly
169 // resets the poll interval, depedning on the flag's value.
170 void AdjustPolling(PollAdjustType type
);
172 // Helper to restart waiting with |wait_interval_|'s timer.
173 void RestartWaiting();
175 // Determines if we're allowed to contact the server right now.
176 bool CanRunJobNow(JobPriority priority
);
178 // Determines if we're allowed to contact the server right now.
179 bool CanRunNudgeJobNow(JobPriority priority
);
181 // If the scheduler's current state supports it, this will create a job based
182 // on the passed in parameters and coalesce it with any other pending jobs,
183 // then post a delayed task to run it. It may also choose to drop the job or
184 // save it for later, depending on the scheduler's current state.
185 void ScheduleNudgeImpl(
186 const base::TimeDelta
& delay
,
187 const tracked_objects::Location
& nudge_location
);
189 // Helper to signal listeners about changed retry time.
190 void NotifyRetryTime(base::Time retry_time
);
192 // Helper to signal listeners about changed throttled types.
193 void NotifyThrottledTypesChanged(ModelTypeSet types
);
195 // Looks for pending work and, if it finds any, run this work at "canary"
199 // At the moment TrySyncSessionJob just posts call to TrySyncSessionJobImpl on
200 // current thread. In the future it will request access token here.
201 void TrySyncSessionJob();
202 void TrySyncSessionJobImpl();
204 // Transitions out of the THROTTLED WaitInterval then calls TryCanaryJob().
207 // Called when a per-type throttling interval expires.
208 void TypeUnthrottle(base::TimeTicks unthrottle_time
);
210 // Runs a normal nudge job when the scheduled timer expires.
211 void PerformDelayedNudge();
213 // Attempts to exit EXPONENTIAL_BACKOFF by calling TryCanaryJob().
214 void ExponentialBackoffRetry();
216 // Called when the root cause of the current connection error is fixed.
217 void OnServerConnectionErrorFixed();
219 // Creates a session for a poll and performs the sync.
220 void PollTimerCallback();
222 // Creates a session for a retry and performs the sync.
223 void RetryTimerCallback();
225 // Returns the set of types that are enabled and not currently throttled.
226 ModelTypeSet
GetEnabledAndUnthrottledTypes();
228 // Called as we are started to broadcast an initial session snapshot
229 // containing data like initial_sync_ended. Important when the client starts
230 // up and does not need to perform an initial sync.
231 void SendInitialSnapshot();
233 // This is used for histogramming and analysis of ScheduleNudge* APIs.
234 // SyncScheduler is the ultimate choke-point for all such invocations (with
235 // and without InvalidationState variants, all NudgeSources, etc) and as such
236 // is the most flexible place to do this bookkeeping.
237 void UpdateNudgeTimeRecords(ModelTypeSet types
);
239 // For certain methods that need to worry about X-thread posting.
240 WeakHandle
<SyncSchedulerImpl
> weak_handle_this_
;
243 const std::string name_
;
245 // Set in Start(), unset in Stop().
248 // Modifiable versions of kDefaultLongPollIntervalSeconds which can be
249 // updated by the server.
250 base::TimeDelta syncer_short_poll_interval_seconds_
;
251 base::TimeDelta syncer_long_poll_interval_seconds_
;
253 // Server-tweakable sessions commit delay.
254 base::TimeDelta sessions_commit_delay_
;
256 // Periodic timer for polling. See AdjustPolling.
257 base::RepeatingTimer
<SyncSchedulerImpl
> poll_timer_
;
259 // The mode of operation.
262 // Current wait state. Null if we're not in backoff and not throttled.
263 scoped_ptr
<WaitInterval
> wait_interval_
;
265 scoped_ptr
<BackoffDelayProvider
> delay_provider_
;
267 // The event that will wake us up.
268 base::OneShotTimer
<SyncSchedulerImpl
> pending_wakeup_timer_
;
270 // An event that fires when data type throttling expires.
271 base::OneShotTimer
<SyncSchedulerImpl
> type_unthrottle_timer_
;
273 // Storage for variables related to an in-progress configure request. Note
274 // that (mode_ != CONFIGURATION_MODE) \implies !pending_configure_params_.
275 scoped_ptr
<ConfigurationParams
> pending_configure_params_
;
277 // If we have a nudge pending to run soon, it will be listed here.
278 base::TimeTicks scheduled_nudge_time_
;
280 // Keeps track of work that the syncer needs to handle.
281 sessions::NudgeTracker nudge_tracker_
;
283 // Invoked to run through the sync cycle.
284 scoped_ptr
<Syncer
> syncer_
;
286 sessions::SyncSessionContext
* session_context_
;
288 // A map tracking LOCAL NudgeSource invocations of ScheduleNudge* APIs,
289 // organized by datatype. Each datatype that was part of the types requested
290 // in the call will have its TimeTicks value updated.
291 typedef std::map
<ModelType
, base::TimeTicks
> ModelTypeTimeMap
;
292 ModelTypeTimeMap last_local_nudges_by_model_type_
;
294 // Used as an "anti-reentrancy defensive assertion".
295 // While true, it is illegal for any new scheduling activity to take place.
296 // Ensures that higher layers don't break this law in response to events that
297 // take place during a sync cycle. We call this out because such violations
298 // could result in tight sync loops hitting sync servers.
299 bool no_scheduling_allowed_
;
301 // crbug/251307. This is a workaround for M29. crbug/259913 tracks proper fix
303 // The issue is that poll job runs after few hours of inactivity and therefore
304 // will always fail with auth error because of expired access token. Once
305 // fresh access token is requested poll job is not retried.
306 // The change is to remember that poll timer just fired and retry poll job
307 // after credentials are updated.
308 bool do_poll_after_credentials_updated_
;
310 // TryJob might get called for multiple reasons. It should only call
311 // DoPollSyncSessionJob after some time since the last attempt.
312 // last_poll_reset_ keeps track of when was last attempt.
313 base::TimeTicks last_poll_reset_
;
315 // next_sync_session_job_priority_ defines which priority will be used next
316 // time TrySyncSessionJobImpl is called. CANARY_PRIORITY allows syncer to run
317 // even if scheduler is in exponential backoff. This is needed for events that
318 // have chance of resolving previous error (e.g. network connection change
319 // after NETWORK_UNAVAILABLE error).
320 // It is reset back to NORMAL_PRIORITY on every call to TrySyncSessionJobImpl.
321 JobPriority next_sync_session_job_priority_
;
323 // One-shot timer for scheduling GU retry according to delay set by server.
324 base::OneShotTimer
<SyncSchedulerImpl
> retry_timer_
;
326 base::WeakPtrFactory
<SyncSchedulerImpl
> weak_ptr_factory_
;
328 // A second factory specially for weak_handle_this_, to allow the handle
329 // to be const and alleviate threading concerns.
330 base::WeakPtrFactory
<SyncSchedulerImpl
> weak_ptr_factory_for_weak_handle_
;
332 DISALLOW_COPY_AND_ASSIGN(SyncSchedulerImpl
);
335 } // namespace syncer
337 #endif // SYNC_ENGINE_SYNC_SCHEDULER_IMPL_H_