Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(367)

Side by Side Diff: chrome/browser/sync/engine/syncer_thread2.cc

Issue 6812004: sync: Make nudge + config jobs reliable in SyncerThread2 (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix sync backend host to call configure on right thread. Created 9 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/sync/engine/syncer_thread2.h" 5 #include "chrome/browser/sync/engine/syncer_thread2.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 8
9 #include "base/rand_util.h" 9 #include "base/rand_util.h"
10 #include "chrome/browser/sync/engine/syncer.h" 10 #include "chrome/browser/sync/engine/syncer.h"
11 11
12 using base::TimeDelta; 12 using base::TimeDelta;
13 using base::TimeTicks; 13 using base::TimeTicks;
14 14
15 namespace browser_sync { 15 namespace browser_sync {
16 16
17 using sessions::SyncSession; 17 using sessions::SyncSession;
18 using sessions::SyncSessionSnapshot; 18 using sessions::SyncSessionSnapshot;
19 using sessions::SyncSourceInfo; 19 using sessions::SyncSourceInfo;
20 using syncable::ModelTypePayloadMap; 20 using syncable::ModelTypePayloadMap;
21 using syncable::ModelTypeBitSet; 21 using syncable::ModelTypeBitSet;
22 using sync_pb::GetUpdatesCallerInfo; 22 using sync_pb::GetUpdatesCallerInfo;
23 23
24 namespace s3 { 24 namespace s3 {
25 25
26 struct SyncerThread::WaitInterval {
27 enum Mode {
28 // A wait interval whose duration has been affected by exponential
29 // backoff.
30 // EXPONENTIAL_BACKOFF intervals are nudge-rate limited to 1 per interval.
31 EXPONENTIAL_BACKOFF,
32 // A server-initiated throttled interval. We do not allow any syncing
33 // during such an interval.
34 THROTTLED,
35 };
36 Mode mode;
37
38 // This bool is set to true if we have observed a nudge during this
39 // interval and mode == EXPONENTIAL_BACKOFF.
40 bool had_nudge;
41 base::TimeDelta length;
42 base::OneShotTimer<SyncerThread> timer;
43 WaitInterval(Mode mode, base::TimeDelta length);
44 };
45
46 struct SyncerThread::SyncSessionJob {
47 SyncSessionJobPurpose purpose;
48 base::TimeTicks scheduled_start;
49 linked_ptr<sessions::SyncSession> session;
50
51 // This is the location the nudge came from. used for debugging purpose.
52 // In case of multiple nudges getting coalesced this stores the first nudge
53 // that came in.
54 tracked_objects::Location nudge_location;
55 };
56
57 SyncerThread::DelayProvider::DelayProvider() {} 26 SyncerThread::DelayProvider::DelayProvider() {}
58 SyncerThread::DelayProvider::~DelayProvider() {} 27 SyncerThread::DelayProvider::~DelayProvider() {}
59 28
29 SyncerThread::WaitInterval::WaitInterval() {}
30 SyncerThread::WaitInterval::~WaitInterval() {}
31
32 SyncerThread::SyncSessionJob::SyncSessionJob() {}
33 SyncerThread::SyncSessionJob::~SyncSessionJob() {}
34
35 SyncerThread::SyncSessionJob::SyncSessionJob(SyncSessionJobPurpose purpose,
36 base::TimeTicks start,
37 linked_ptr<sessions::SyncSession> session, bool is_canary_job,
38 const tracked_objects::Location& nudge_location) : purpose(purpose),
39 scheduled_start(start),
40 session(session),
41 is_canary_job(is_canary_job),
42 nudge_location(nudge_location) {
43 }
44
60 TimeDelta SyncerThread::DelayProvider::GetDelay( 45 TimeDelta SyncerThread::DelayProvider::GetDelay(
61 const base::TimeDelta& last_delay) { 46 const base::TimeDelta& last_delay) {
62 return SyncerThread::GetRecommendedDelay(last_delay); 47 return SyncerThread::GetRecommendedDelay(last_delay);
63 } 48 }
64 49
50 GetUpdatesCallerInfo::GetUpdatesSource GetUpdatesFromNudgeSource(
51 NudgeSource source) {
52 switch (source) {
53 case NUDGE_SOURCE_NOTIFICATION:
54 return GetUpdatesCallerInfo::NOTIFICATION;
55 case NUDGE_SOURCE_LOCAL:
56 return GetUpdatesCallerInfo::LOCAL;
57 case NUDGE_SOURCE_CONTINUATION:
58 return GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION;
59 case NUDGE_SOURCE_UNKNOWN:
60 return GetUpdatesCallerInfo::UNKNOWN;
61 default:
62 NOTREACHED();
63 return GetUpdatesCallerInfo::UNKNOWN;
64 }
65 }
66
65 SyncerThread::WaitInterval::WaitInterval(Mode mode, TimeDelta length) 67 SyncerThread::WaitInterval::WaitInterval(Mode mode, TimeDelta length)
66 : mode(mode), had_nudge(false), length(length) { } 68 : mode(mode), had_nudge(false), length(length) { }
67 69
68 SyncerThread::SyncerThread(sessions::SyncSessionContext* context, 70 SyncerThread::SyncerThread(sessions::SyncSessionContext* context,
69 Syncer* syncer) 71 Syncer* syncer)
70 : thread_("SyncEngine_SyncerThread"), 72 : thread_("SyncEngine_SyncerThread"),
71 syncer_short_poll_interval_seconds_( 73 syncer_short_poll_interval_seconds_(
72 TimeDelta::FromSeconds(kDefaultShortPollIntervalSeconds)), 74 TimeDelta::FromSeconds(kDefaultShortPollIntervalSeconds)),
73 syncer_long_poll_interval_seconds_( 75 syncer_long_poll_interval_seconds_(
74 TimeDelta::FromSeconds(kDefaultLongPollIntervalSeconds)), 76 TimeDelta::FromSeconds(kDefaultLongPollIntervalSeconds)),
75 mode_(NORMAL_MODE), 77 mode_(NORMAL_MODE),
76 server_connection_ok_(false), 78 server_connection_ok_(true),
tim (not reviewing) 2011/04/15 00:21:43 this can't be right...
lipalani1 2011/04/15 01:24:39 ha ha!! Not sure if it is incorrect. However I hav
77 delay_provider_(new DelayProvider()), 79 delay_provider_(new DelayProvider()),
78 syncer_(syncer), 80 syncer_(syncer),
79 session_context_(context) { 81 session_context_(context) {
80 } 82 }
81 83
82 SyncerThread::~SyncerThread() { 84 SyncerThread::~SyncerThread() {
83 DCHECK(!thread_.IsRunning()); 85 DCHECK(!thread_.IsRunning());
84 } 86 }
85 87
86 void SyncerThread::CheckServerConnectionManagerStatus( 88 void SyncerThread::CheckServerConnectionManagerStatus(
87 HttpResponse::ServerConnectionCode code) { 89 HttpResponse::ServerConnectionCode code) {
90
91 VLOG(2) << this << " Server connection changed. Old mode:"
92 << server_connection_ok_ << " Code: " << code;
88 // Note, be careful when adding cases here because if the SyncerThread 93 // Note, be careful when adding cases here because if the SyncerThread
89 // thinks there is no valid connection as determined by this method, it 94 // thinks there is no valid connection as determined by this method, it
90 // will drop out of *all* forward progress sync loops (it won't poll and it 95 // will drop out of *all* forward progress sync loops (it won't poll and it
91 // will queue up Talk notifications but not actually call SyncShare) until 96 // will queue up Talk notifications but not actually call SyncShare) until
92 // some external action causes a ServerConnectionManager to broadcast that 97 // some external action causes a ServerConnectionManager to broadcast that
93 // a valid connection has been re-established. 98 // a valid connection has been re-established.
94 if (HttpResponse::CONNECTION_UNAVAILABLE == code || 99 if (HttpResponse::CONNECTION_UNAVAILABLE == code ||
95 HttpResponse::SYNC_AUTH_ERROR == code) { 100 HttpResponse::SYNC_AUTH_ERROR == code) {
96 server_connection_ok_ = false; 101 server_connection_ok_ = false;
102 VLOG(2) << this << " Server connection changed. new mode:"
103 << server_connection_ok_;
97 } else if (HttpResponse::SERVER_CONNECTION_OK == code) { 104 } else if (HttpResponse::SERVER_CONNECTION_OK == code) {
98 server_connection_ok_ = true; 105 server_connection_ok_ = true;
106 VLOG(2) << this << " Server connection changed. new mode:"
107 << server_connection_ok_;
108 DoCanaryJob();
99 } 109 }
100 } 110 }
101 111
102 void SyncerThread::Start(Mode mode, ModeChangeCallback* callback) { 112 void SyncerThread::Start(Mode mode, ModeChangeCallback* callback) {
113 VLOG(2) << this << " Start called from thread " <<
114 MessageLoop::current()->thread_name();
103 if (!thread_.IsRunning()) { 115 if (!thread_.IsRunning()) {
116 VLOG(2) << this << " Starting thread with mode " << mode;
104 if (!thread_.Start()) { 117 if (!thread_.Start()) {
105 NOTREACHED() << "Unable to start SyncerThread."; 118 NOTREACHED() << "Unable to start SyncerThread.";
106 return; 119 return;
107 } 120 }
108 WatchConnectionManager(); 121 WatchConnectionManager();
109 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod( 122 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
110 this, &SyncerThread::SendInitialSnapshot)); 123 this, &SyncerThread::SendInitialSnapshot));
111 } 124 }
112 125
126 VLOG(2) << this << " Entering start with mode = " << mode;
127
113 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod( 128 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
114 this, &SyncerThread::StartImpl, mode, make_linked_ptr(callback))); 129 this, &SyncerThread::StartImpl, mode, make_linked_ptr(callback)));
115 } 130 }
116 131
117 void SyncerThread::SendInitialSnapshot() { 132 void SyncerThread::SendInitialSnapshot() {
118 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 133 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
119 scoped_ptr<SyncSession> dummy(new SyncSession(session_context_.get(), this, 134 scoped_ptr<SyncSession> dummy(new SyncSession(session_context_.get(), this,
120 SyncSourceInfo(), ModelSafeRoutingInfo(), 135 SyncSourceInfo(), ModelSafeRoutingInfo(),
121 std::vector<ModelSafeWorker*>())); 136 std::vector<ModelSafeWorker*>()));
122 SyncEngineEvent event(SyncEngineEvent::STATUS_CHANGED); 137 SyncEngineEvent event(SyncEngineEvent::STATUS_CHANGED);
123 sessions::SyncSessionSnapshot snapshot(dummy->TakeSnapshot()); 138 sessions::SyncSessionSnapshot snapshot(dummy->TakeSnapshot());
124 event.snapshot = &snapshot; 139 event.snapshot = &snapshot;
125 session_context_->NotifyListeners(event); 140 session_context_->NotifyListeners(event);
126 } 141 }
127 142
128 void SyncerThread::WatchConnectionManager() { 143 void SyncerThread::WatchConnectionManager() {
129 ServerConnectionManager* scm = session_context_->connection_manager(); 144 ServerConnectionManager* scm = session_context_->connection_manager();
130 CheckServerConnectionManagerStatus(scm->server_status()); 145 CheckServerConnectionManagerStatus(scm->server_status());
131 scm->AddListener(this); 146 scm->AddListener(this);
132 } 147 }
133 148
134 void SyncerThread::StartImpl(Mode mode, 149 void SyncerThread::StartImpl(Mode mode,
135 linked_ptr<ModeChangeCallback> callback) { 150 linked_ptr<ModeChangeCallback> callback) {
151 VLOG(2) << this << " Doing StartImpl with mode " << mode;
136 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 152 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
137 DCHECK(!session_context_->account_name().empty()); 153 DCHECK(!session_context_->account_name().empty());
138 DCHECK(syncer_.get()); 154 DCHECK(syncer_.get());
139 mode_ = mode; 155 mode_ = mode;
140 AdjustPolling(NULL); // Will kick start poll timer if needed. 156 AdjustPolling(NULL); // Will kick start poll timer if needed.
141 if (callback.get()) 157 if (callback.get())
142 callback->Run(); 158 callback->Run();
159
160 // We just changed our mode. See if there are any pending jobs that we could
161 // execute in the new mode.
162 DoPendingJobIfPossible(false);
143 } 163 }
144 164
145 bool SyncerThread::ShouldRunJob(SyncSessionJobPurpose purpose, 165 SyncerThread::JobProcessDecision SyncerThread::DecideWhileInWaitInterval(
146 const TimeTicks& scheduled_start) { 166 const SyncSessionJob& job) {
147 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
148 167
149 // Check wait interval. 168 DCHECK(wait_interval_.get());
150 if (wait_interval_.get()) { 169 DCHECK_NE(job.purpose, SyncSessionJob::CLEAR_USER_DATA);
151 // TODO(tim): Consider different handling for CLEAR_USER_DATA (i.e. permit
152 // when throttled).
153 if (wait_interval_->mode == WaitInterval::THROTTLED)
154 return false;
155 170
156 DCHECK_EQ(wait_interval_->mode, WaitInterval::EXPONENTIAL_BACKOFF); 171 VLOG(2) << this << " Wait interval mode : " << wait_interval_->mode
157 if ((purpose != NUDGE) || wait_interval_->had_nudge) 172 << "Wait interval had nudge : " << wait_interval_->had_nudge
158 return false; 173 << "is canary job : " << job.is_canary_job;
174
175 if (job.purpose == SyncSessionJob::POLL)
176 return DROP;
177
178 DCHECK(job.purpose == SyncSessionJob::NUDGE ||
179 job.purpose == SyncSessionJob::CONFIGURATION);
180 if (wait_interval_->mode == WaitInterval::THROTTLED)
181 return SAVE;
182
183 DCHECK_EQ(wait_interval_->mode, WaitInterval::EXPONENTIAL_BACKOFF);
184 if (job.purpose == SyncSessionJob::NUDGE) {
185 if (mode_ == CONFIGURATION_MODE)
186 return SAVE;
187
188 // If we already had one nudge then just drop this nudge. We will retry
189 // later when the timer runs out.
190 return wait_interval_->had_nudge ? DROP : CONTINUE;
191 }
192 // This is a config job.
193 return job.is_canary_job ? CONTINUE : SAVE;
194 }
195
196 SyncerThread::JobProcessDecision SyncerThread::DecideOnJob(
197 const SyncSessionJob& job) {
198 if (job.purpose == SyncSessionJob::CLEAR_USER_DATA)
199 return CONTINUE;
200
201 if (wait_interval_.get())
202 return DecideWhileInWaitInterval(job);
203
204 if (mode_ == CONFIGURATION_MODE) {
205 if (job.purpose == SyncSessionJob::NUDGE)
206 return SAVE;
207 else if (job.purpose == SyncSessionJob::CONFIGURATION)
208 return CONTINUE;
209 else
210 return DROP;
159 } 211 }
160 212
161 // Mode / purpose contract (See 'Mode' enum in header). Don't run jobs that 213 // We are in normal mode.
162 // were intended for a normal sync if we are in configuration mode, and vice 214 DCHECK_EQ(mode_, NORMAL_MODE);
163 // versa. 215 DCHECK_NE(job.purpose, SyncSessionJob::CONFIGURATION);
164 switch (mode_) { 216
165 case CONFIGURATION_MODE: 217 // Freshness condition
166 if (purpose != CONFIGURATION) 218 if (job.scheduled_start < last_sync_session_end_time_) {
167 return false; 219 VLOG(2) << this << " Dropping job because of freshness";
168 break; 220 return DROP;
169 case NORMAL_MODE:
170 if (purpose == CONFIGURATION)
171 return false;
172 break;
173 default:
174 NOTREACHED() << "Unknown SyncerThread Mode: " << mode_;
175 return false;
176 } 221 }
177 222
178 // Continuation NUDGE tasks have priority over POLLs because they are the 223 if (server_connection_ok_)
179 // only tasks that trigger exponential backoff, so this prevents them from 224 return CONTINUE;
180 // being starved from running (e.g. due to a very, very low poll interval, 225
181 // such as 0ms). It's rare that this would ever matter in practice. 226 VLOG(2) << this << " Bad server connection. Using that to decide on job.";
182 if (purpose == POLL && (pending_nudge_.get() && 227 return job.purpose == SyncSessionJob::NUDGE ? SAVE : DROP;
183 pending_nudge_->session->source().updates_source == 228 }
184 GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION)) { 229
185 return false; 230 void SyncerThread::InitOrCoalescePendingJob(const SyncSessionJob& job) {
231 DCHECK(job.purpose != SyncSessionJob::CONFIGURATION);
232 if (pending_nudge_.get() == NULL) {
233 VLOG(2) << this << " Creating a pending nudge job";
234 SyncSession* s = job.session.get();
235 scoped_ptr<SyncSession> session(new SyncSession(s->context(),
236 s->delegate(), s->source(), s->routing_info(), s->workers()));
237
238 SyncSessionJob new_job(SyncSessionJob::NUDGE, job.scheduled_start,
239 make_linked_ptr(session.release()), false, job.nudge_location);
240 pending_nudge_.reset(new SyncSessionJob(new_job));
241
242 return;
186 } 243 }
187 244
188 // Freshness condition. 245 VLOG(2) << this << " Coalescing a pending nudge";
189 if (purpose == NUDGE && 246 pending_nudge_->session->Coalesce(*(job.session.get()));
190 (scheduled_start < last_sync_session_end_time_)) { 247 pending_nudge_->scheduled_start = job.scheduled_start;
191 return false;
192 }
193 248
194 return server_connection_ok_; 249 // Unfortunately the nudge location cannot be modified. So it stores the
250 // location of the first caller.
195 } 251 }
196 252
197 GetUpdatesCallerInfo::GetUpdatesSource GetUpdatesFromNudgeSource( 253 bool SyncerThread::ShouldRunJob(const SyncSessionJob& job) {
198 NudgeSource source) { 254 JobProcessDecision decision = DecideOnJob(job);
199 switch (source) { 255 VLOG(2) << this << " Should run job, decision: " << decision
200 case NUDGE_SOURCE_NOTIFICATION: 256 << " Job purpose " << job.purpose << "mode " << mode_;
201 return GetUpdatesCallerInfo::NOTIFICATION; 257 if (decision != SAVE)
202 case NUDGE_SOURCE_LOCAL: 258 return decision == CONTINUE;
203 return GetUpdatesCallerInfo::LOCAL; 259
204 case NUDGE_SOURCE_CONTINUATION: 260 DCHECK(job.purpose == SyncSessionJob::NUDGE || job.purpose ==
205 return GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION; 261 SyncSessionJob::CONFIGURATION);
206 case NUDGE_SOURCE_UNKNOWN: 262
207 return GetUpdatesCallerInfo::UNKNOWN; 263 SaveJob(job);
208 default: 264 return false;
209 NOTREACHED(); 265 }
210 return GetUpdatesCallerInfo::UNKNOWN; 266
211 } 267 void SyncerThread::SaveJob(const SyncSessionJob& job) {
268 DCHECK(job.purpose != SyncSessionJob::CLEAR_USER_DATA);
269 if (job.purpose == SyncSessionJob::NUDGE) {
270 VLOG(2) << this << " Saving a nudge job";
tim (not reviewing) 2011/04/15 00:21:43 using 'this' in these is a bit messy... prefix wit
lipalani1 2011/04/15 01:24:39 Done.
271 InitOrCoalescePendingJob(job);
272 } else if (job.purpose == SyncSessionJob::CONFIGURATION){
273 VLOG(2) << this << " Saving a configuration job";
274 DCHECK(wait_interval_.get());
275 DCHECK(mode_ == CONFIGURATION_MODE);
276
277 SyncSession* old = job.session.get();
278 SyncSession* s(new SyncSession(session_context_.get(), this,
279 old->source(), old->routing_info(), old->workers()));
280 SyncSessionJob new_job(job.purpose, TimeTicks::Now(),
281 make_linked_ptr(s), false, job.nudge_location);
282 wait_interval_->pending_configure_job.reset(new SyncSessionJob(new_job));
283 } // drop the rest.
212 } 284 }
213 285
214 // Functor for std::find_if to search by ModelSafeGroup. 286 // Functor for std::find_if to search by ModelSafeGroup.
215 struct ModelSafeWorkerGroupIs { 287 struct ModelSafeWorkerGroupIs {
216 explicit ModelSafeWorkerGroupIs(ModelSafeGroup group) : group(group) {} 288 explicit ModelSafeWorkerGroupIs(ModelSafeGroup group) : group(group) {}
217 bool operator()(ModelSafeWorker* w) { 289 bool operator()(ModelSafeWorker* w) {
218 return group == w->GetModelSafeGroup(); 290 return group == w->GetModelSafeGroup();
219 } 291 }
220 ModelSafeGroup group; 292 ModelSafeGroup group;
221 }; 293 };
222 294
223 void SyncerThread::ScheduleClearUserData() { 295 void SyncerThread::ScheduleClearUserData() {
224 if (!thread_.IsRunning()) { 296 if (!thread_.IsRunning()) {
225 NOTREACHED(); 297 NOTREACHED();
226 return; 298 return;
227 } 299 }
228 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod( 300 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
229 this, &SyncerThread::ScheduleClearUserDataImpl)); 301 this, &SyncerThread::ScheduleClearUserDataImpl));
230 } 302 }
231 303
232 void SyncerThread::ScheduleNudge(const TimeDelta& delay, 304 void SyncerThread::ScheduleNudge(const TimeDelta& delay,
233 NudgeSource source, const ModelTypeBitSet& types, 305 NudgeSource source, const ModelTypeBitSet& types,
234 const tracked_objects::Location& nudge_location) { 306 const tracked_objects::Location& nudge_location) {
235 if (!thread_.IsRunning()) { 307 if (!thread_.IsRunning()) {
236 NOTREACHED(); 308 NOTREACHED();
237 return; 309 return;
238 } 310 }
239 311
312 VLOG(2) << this << " Nudge scheduled";
313
240 ModelTypePayloadMap types_with_payloads = 314 ModelTypePayloadMap types_with_payloads =
241 syncable::ModelTypePayloadMapFromBitSet(types, std::string()); 315 syncable::ModelTypePayloadMapFromBitSet(types, std::string());
242 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod( 316 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
243 this, &SyncerThread::ScheduleNudgeImpl, delay, source, 317 this, &SyncerThread::ScheduleNudgeImpl, delay,
244 types_with_payloads, nudge_location)); 318 GetUpdatesFromNudgeSource(source), types_with_payloads, false,
319 nudge_location));
245 } 320 }
246 321
247 void SyncerThread::ScheduleNudgeWithPayloads(const TimeDelta& delay, 322 void SyncerThread::ScheduleNudgeWithPayloads(const TimeDelta& delay,
248 NudgeSource source, const ModelTypePayloadMap& types_with_payloads, 323 NudgeSource source, const ModelTypePayloadMap& types_with_payloads,
249 const tracked_objects::Location& nudge_location) { 324 const tracked_objects::Location& nudge_location) {
250 if (!thread_.IsRunning()) { 325 if (!thread_.IsRunning()) {
251 NOTREACHED(); 326 NOTREACHED();
252 return; 327 return;
253 } 328 }
254 329
330 VLOG(2) << this << " Nudge scheduled with payloads";
331
255 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod( 332 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
256 this, &SyncerThread::ScheduleNudgeImpl, delay, source, 333 this, &SyncerThread::ScheduleNudgeImpl, delay,
257 types_with_payloads, nudge_location)); 334 GetUpdatesFromNudgeSource(source), types_with_payloads, false,
335 nudge_location));
258 } 336 }
259 337
260 void SyncerThread::ScheduleClearUserDataImpl() { 338 void SyncerThread::ScheduleClearUserDataImpl() {
261 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 339 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
262 SyncSession* session = new SyncSession(session_context_.get(), this, 340 SyncSession* session = new SyncSession(session_context_.get(), this,
263 SyncSourceInfo(), ModelSafeRoutingInfo(), 341 SyncSourceInfo(), ModelSafeRoutingInfo(),
264 std::vector<ModelSafeWorker*>()); 342 std::vector<ModelSafeWorker*>());
265 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0), CLEAR_USER_DATA, session, 343 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0),
266 FROM_HERE); 344 SyncSessionJob::CLEAR_USER_DATA, session, FROM_HERE);
267 } 345 }
268 346
269 void SyncerThread::ScheduleNudgeImpl(const TimeDelta& delay, 347 void SyncerThread::ScheduleNudgeImpl(const TimeDelta& delay,
270 NudgeSource source, const ModelTypePayloadMap& types_with_payloads, 348 GetUpdatesCallerInfo::GetUpdatesSource source,
271 const tracked_objects::Location& nudge_location) { 349 const ModelTypePayloadMap& types_with_payloads,
350 bool is_canary_job, const tracked_objects::Location& nudge_location) {
272 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 351 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
273 TimeTicks rough_start = TimeTicks::Now() + delay;
274 if (!ShouldRunJob(NUDGE, rough_start)) {
275 LOG(WARNING) << "Dropping nudge at scheduling time, source = "
276 << source;
277 return;
278 }
279 352
353 VLOG(2) << this << " Running Schedule nudge impl";
280 // Note we currently nudge for all types regardless of the ones incurring 354 // Note we currently nudge for all types regardless of the ones incurring
281 // the nudge. Doing different would throw off some syncer commands like 355 // the nudge. Doing different would throw off some syncer commands like
282 // CleanupDisabledTypes. We may want to change this in the future. 356 // CleanupDisabledTypes. We may want to change this in the future.
283 ModelSafeRoutingInfo routes; 357 SyncSourceInfo info(source, types_with_payloads);
284 std::vector<ModelSafeWorker*> workers;
285 session_context_->registrar()->GetModelSafeRoutingInfo(&routes);
286 session_context_->registrar()->GetWorkers(&workers);
287 SyncSourceInfo info(GetUpdatesFromNudgeSource(source),
288 types_with_payloads);
289 358
290 scoped_ptr<SyncSession> session(new SyncSession( 359 SyncSession* session(CreateSyncSession(info));
291 session_context_.get(), this, info, routes, workers)); 360 SyncSessionJob job(SyncSessionJob::NUDGE, TimeTicks::Now() + delay,
361 make_linked_ptr(session), is_canary_job,
362 nudge_location);
363
364 session = NULL;
365 if (!ShouldRunJob(job))
366 return;
292 367
293 if (pending_nudge_.get()) { 368 if (pending_nudge_.get()) {
294 if (IsBackingOff() && delay > TimeDelta::FromSeconds(1)) 369 if (IsBackingOff() && delay > TimeDelta::FromSeconds(1)) {
370 VLOG(2) << this << " Dropping the nudge because we are in backoff";
295 return; 371 return;
372 }
296 373
297 pending_nudge_->session->Coalesce(*session.get()); 374 VLOG(2) << this << " Coalescing pending nudge";
375 pending_nudge_->session->Coalesce(*(job.session.get()));
298 376
299 if (!IsBackingOff()) { 377 if (!IsBackingOff()) {
378 VLOG(2) << this << " Dropping a nudge because we are not in backoff"
379 << " and the job was coalesced";
300 return; 380 return;
301 } else { 381 } else {
302 // Re-schedule the current pending nudge. 382 VLOG(2) << this << " Rescheduling pending nudge";
303 SyncSession* s = pending_nudge_->session.get(); 383 SyncSession* s = pending_nudge_->session.get();
304 session.reset(new SyncSession(s->context(), s->delegate(), s->source(), 384 job.session.reset(new SyncSession(s->context(), s->delegate(),
305 s->routing_info(), s->workers())); 385 s->source(), s->routing_info(), s->workers()));
306 pending_nudge_.reset(); 386 pending_nudge_.reset();
307 } 387 }
308 } 388 }
309 ScheduleSyncSessionJob(delay, NUDGE, session.release(), nudge_location); 389
390 // TODO(lipalani) - pass the job itself to ScheduleSyncSessionJob.
391 ScheduleSyncSessionJob(delay, SyncSessionJob::NUDGE, job.session.release(),
392 nudge_location);
310 } 393 }
311 394
312 // Helper to extract the routing info and workers corresponding to types in 395 // Helper to extract the routing info and workers corresponding to types in
313 // |types| from |registrar|. 396 // |types| from |registrar|.
314 void GetModelSafeParamsForTypes(const ModelTypeBitSet& types, 397 void GetModelSafeParamsForTypes(const ModelTypeBitSet& types,
315 ModelSafeWorkerRegistrar* registrar, ModelSafeRoutingInfo* routes, 398 ModelSafeWorkerRegistrar* registrar, ModelSafeRoutingInfo* routes,
316 std::vector<ModelSafeWorker*>* workers) { 399 std::vector<ModelSafeWorker*>* workers) {
317 ModelSafeRoutingInfo r_tmp; 400 ModelSafeRoutingInfo r_tmp;
318 std::vector<ModelSafeWorker*> w_tmp; 401 std::vector<ModelSafeWorker*> w_tmp;
319 registrar->GetModelSafeRoutingInfo(&r_tmp); 402 registrar->GetModelSafeRoutingInfo(&r_tmp);
(...skipping 21 matching lines...) Expand all
341 else 424 else
342 NOTREACHED(); 425 NOTREACHED();
343 } 426 }
344 427
345 void SyncerThread::ScheduleConfig(const ModelTypeBitSet& types) { 428 void SyncerThread::ScheduleConfig(const ModelTypeBitSet& types) {
346 if (!thread_.IsRunning()) { 429 if (!thread_.IsRunning()) {
347 NOTREACHED(); 430 NOTREACHED();
348 return; 431 return;
349 } 432 }
350 433
434 VLOG(2) << this << " Scheduling a config";
351 ModelSafeRoutingInfo routes; 435 ModelSafeRoutingInfo routes;
352 std::vector<ModelSafeWorker*> workers; 436 std::vector<ModelSafeWorker*> workers;
353 GetModelSafeParamsForTypes(types, session_context_->registrar(), 437 GetModelSafeParamsForTypes(types, session_context_->registrar(),
354 &routes, &workers); 438 &routes, &workers);
355 439
356 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod( 440 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
357 this, &SyncerThread::ScheduleConfigImpl, routes, workers)); 441 this, &SyncerThread::ScheduleConfigImpl, routes, workers,
442 GetUpdatesCallerInfo::FIRST_UPDATE));
358 } 443 }
359 444
360 void SyncerThread::ScheduleConfigImpl(const ModelSafeRoutingInfo& routing_info, 445 void SyncerThread::ScheduleConfigImpl(const ModelSafeRoutingInfo& routing_info,
361 const std::vector<ModelSafeWorker*>& workers) { 446 const std::vector<ModelSafeWorker*>& workers,
447 const sync_pb::GetUpdatesCallerInfo::GetUpdatesSource source) {
362 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 448 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
363 449
450 VLOG(2) << this << " ScheduleConfigImpl...";
364 // TODO(tim): config-specific GetUpdatesCallerInfo value? 451 // TODO(tim): config-specific GetUpdatesCallerInfo value?
365 SyncSession* session = new SyncSession(session_context_.get(), this, 452 SyncSession* session = new SyncSession(session_context_.get(), this,
366 SyncSourceInfo(GetUpdatesCallerInfo::FIRST_UPDATE, 453 SyncSourceInfo(source,
367 syncable::ModelTypePayloadMapFromRoutingInfo( 454 syncable::ModelTypePayloadMapFromRoutingInfo(
368 routing_info, std::string())), 455 routing_info, std::string())),
369 routing_info, workers); 456 routing_info, workers);
370 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0), CONFIGURATION, session, 457 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0),
371 FROM_HERE); 458 SyncSessionJob::CONFIGURATION, session, FROM_HERE);
372 } 459 }
373 460
374 void SyncerThread::ScheduleSyncSessionJob(const base::TimeDelta& delay, 461 void SyncerThread::ScheduleSyncSessionJob(const base::TimeDelta& delay,
375 SyncSessionJobPurpose purpose, sessions::SyncSession* session, 462 SyncSessionJob::SyncSessionJobPurpose purpose,
463 sessions::SyncSession* session,
376 const tracked_objects::Location& nudge_location) { 464 const tracked_objects::Location& nudge_location) {
377 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 465 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
378 466
379 SyncSessionJob job = {purpose, TimeTicks::Now() + delay, 467 SyncSessionJob job(purpose, TimeTicks::Now() + delay,
380 make_linked_ptr(session), nudge_location}; 468 make_linked_ptr(session), false, nudge_location);
381 if (purpose == NUDGE) { 469 if (purpose == SyncSessionJob::NUDGE) {
470 VLOG(2) << this << " Resetting pending_nudge in ScheduleSyncSessionJob";
382 DCHECK(!pending_nudge_.get() || pending_nudge_->session.get() == session); 471 DCHECK(!pending_nudge_.get() || pending_nudge_->session.get() == session);
383 pending_nudge_.reset(new SyncSessionJob(job)); 472 pending_nudge_.reset(new SyncSessionJob(job));
384 } 473 }
474 VLOG(2) << this << " Posting job to execute in DoSyncSessionJob. Job purpose "
475 << job.purpose;
385 MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(this, 476 MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(this,
386 &SyncerThread::DoSyncSessionJob, job), 477 &SyncerThread::DoSyncSessionJob, job),
387 delay.InMilliseconds()); 478 delay.InMilliseconds());
388 } 479 }
389 480
390 void SyncerThread::SetSyncerStepsForPurpose(SyncSessionJobPurpose purpose, 481 void SyncerThread::SetSyncerStepsForPurpose(
482 SyncSessionJob::SyncSessionJobPurpose purpose,
391 SyncerStep* start, SyncerStep* end) { 483 SyncerStep* start, SyncerStep* end) {
392 *end = SYNCER_END; 484 *end = SYNCER_END;
393 switch (purpose) { 485 switch (purpose) {
394 case CONFIGURATION: 486 case SyncSessionJob::CONFIGURATION:
395 *start = DOWNLOAD_UPDATES; 487 *start = DOWNLOAD_UPDATES;
396 *end = APPLY_UPDATES; 488 *end = APPLY_UPDATES;
397 return; 489 return;
398 case CLEAR_USER_DATA: 490 case SyncSessionJob::CLEAR_USER_DATA:
399 *start = CLEAR_PRIVATE_DATA; 491 *start = CLEAR_PRIVATE_DATA;
400 return; 492 return;
401 case NUDGE: 493 case SyncSessionJob::NUDGE:
402 case POLL: 494 case SyncSessionJob::POLL:
403 *start = SYNCER_BEGIN; 495 *start = SYNCER_BEGIN;
404 return; 496 return;
405 default: 497 default:
406 NOTREACHED(); 498 NOTREACHED();
407 } 499 }
408 } 500 }
409 501
410 void SyncerThread::DoSyncSessionJob(const SyncSessionJob& job) { 502 void SyncerThread::DoSyncSessionJob(const SyncSessionJob& job) {
411 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 503 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
412 if (!ShouldRunJob(job.purpose, job.scheduled_start)) { 504 if (!ShouldRunJob(job))
413 LOG(WARNING) << "Dropping nudge at DoSyncSessionJob, source = "
414 << job.session->source().updates_source;
415 return; 505 return;
416 }
417 506
418 if (job.purpose == NUDGE) { 507 if (job.purpose == SyncSessionJob::NUDGE) {
419 DCHECK(pending_nudge_.get()); 508 DCHECK(pending_nudge_.get());
420 if (pending_nudge_->session != job.session) 509 if (pending_nudge_->session != job.session)
421 return; // Another nudge must have been scheduled in in the meantime. 510 return; // Another nudge must have been scheduled in in the meantime.
422 pending_nudge_.reset(); 511 pending_nudge_.reset();
423 } 512 }
513 VLOG(2) << this << " DoSyncSessionJob. job purpose " << job.purpose;
424 514
425 SyncerStep begin(SYNCER_BEGIN); 515 SyncerStep begin(SYNCER_BEGIN);
426 SyncerStep end(SYNCER_END); 516 SyncerStep end(SYNCER_END);
427 SetSyncerStepsForPurpose(job.purpose, &begin, &end); 517 SetSyncerStepsForPurpose(job.purpose, &begin, &end);
428 518
429 bool has_more_to_sync = true; 519 bool has_more_to_sync = true;
430 while (ShouldRunJob(job.purpose, job.scheduled_start) && has_more_to_sync) { 520 while (ShouldRunJob(job) && has_more_to_sync) {
431 VLOG(1) << "SyncerThread: Calling SyncShare."; 521 VLOG(2) << this << " SyncerThread: Calling SyncShare.";
432 // Synchronously perform the sync session from this thread. 522 // Synchronously perform the sync session from this thread.
433 syncer_->SyncShare(job.session.get(), begin, end); 523 syncer_->SyncShare(job.session.get(), begin, end);
434 has_more_to_sync = job.session->HasMoreToSync(); 524 has_more_to_sync = job.session->HasMoreToSync();
435 if (has_more_to_sync) 525 if (has_more_to_sync)
436 job.session->ResetTransientState(); 526 job.session->ResetTransientState();
437 } 527 }
438 VLOG(1) << "SyncerThread: Done SyncShare looping."; 528 VLOG(2) << this << " SyncerThread: Done SyncShare looping.";
439 FinishSyncSessionJob(job); 529 FinishSyncSessionJob(job);
440 } 530 }
441 531
442 void SyncerThread::UpdateCarryoverSessionState(const SyncSessionJob& old_job) { 532 void SyncerThread::UpdateCarryoverSessionState(const SyncSessionJob& old_job) {
443 if (old_job.purpose == CONFIGURATION) { 533 if (old_job.purpose == SyncSessionJob::CONFIGURATION) {
444 // Whatever types were part of a configuration task will have had updates 534 // Whatever types were part of a configuration task will have had updates
445 // downloaded. For that reason, we make sure they get recorded in the 535 // downloaded. For that reason, we make sure they get recorded in the
446 // event that they get disabled at a later time. 536 // event that they get disabled at a later time.
447 ModelSafeRoutingInfo r(session_context_->previous_session_routing_info()); 537 ModelSafeRoutingInfo r(session_context_->previous_session_routing_info());
448 if (!r.empty()) { 538 if (!r.empty()) {
449 ModelSafeRoutingInfo temp_r; 539 ModelSafeRoutingInfo temp_r;
450 ModelSafeRoutingInfo old_info(old_job.session->routing_info()); 540 ModelSafeRoutingInfo old_info(old_job.session->routing_info());
451 std::set_union(r.begin(), r.end(), old_info.begin(), old_info.end(), 541 std::set_union(r.begin(), r.end(), old_info.begin(), old_info.end(),
452 std::insert_iterator<ModelSafeRoutingInfo>(temp_r, temp_r.begin())); 542 std::insert_iterator<ModelSafeRoutingInfo>(temp_r, temp_r.begin()));
453 session_context_->set_previous_session_routing_info(temp_r); 543 session_context_->set_previous_session_routing_info(temp_r);
(...skipping 12 matching lines...) Expand all
466 ModelTypePayloadMap::const_iterator iter; 556 ModelTypePayloadMap::const_iterator iter;
467 for (iter = job.session->source().types.begin(); 557 for (iter = job.session->source().types.begin();
468 iter != job.session->source().types.end(); 558 iter != job.session->source().types.end();
469 ++iter) { 559 ++iter) {
470 syncable::PostTimeToTypeHistogram(iter->first, 560 syncable::PostTimeToTypeHistogram(iter->first,
471 now - last_sync_session_end_time_); 561 now - last_sync_session_end_time_);
472 } 562 }
473 } 563 }
474 last_sync_session_end_time_ = now; 564 last_sync_session_end_time_ = now;
475 UpdateCarryoverSessionState(job); 565 UpdateCarryoverSessionState(job);
476 if (IsSyncingCurrentlySilenced()) 566 if (IsSyncingCurrentlySilenced()) {
567 VLOG(2) << this << " We are currently throttled. So not scheduling the next"
568 << " sync";
569 SaveJob(job);
477 return; // Nothing to do. 570 return; // Nothing to do.
571 }
478 572
479 VLOG(1) << "Updating the next polling time after SyncMain"; 573 VLOG(2) << this << " Updating the next polling time after SyncMain";
480 ScheduleNextSync(job); 574 ScheduleNextSync(job);
481 } 575 }
482 576
483 void SyncerThread::ScheduleNextSync(const SyncSessionJob& old_job) { 577 void SyncerThread::ScheduleNextSync(const SyncSessionJob& old_job) {
484 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 578 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
485 DCHECK(!old_job.session->HasMoreToSync()); 579 DCHECK(!old_job.session->HasMoreToSync());
486 // Note: |num_server_changes_remaining| > 0 here implies that we received a 580 // Note: |num_server_changes_remaining| > 0 here implies that we received a
487 // broken response while trying to download all updates, because the Syncer 581 // broken response while trying to download all updates, because the Syncer
488 // will loop until this value is exhausted. Also, if unsynced_handles exist 582 // will loop until this value is exhausted. Also, if unsynced_handles exist
489 // but HasMoreToSync is false, this implies that the Syncer determined no 583 // but HasMoreToSync is false, this implies that the Syncer determined no
490 // forward progress was possible at this time (an error, such as an HTTP 584 // forward progress was possible at this time (an error, such as an HTTP
491 // 500, is likely to have occurred during commit). 585 // 500, is likely to have occurred during commit).
492 const bool work_to_do = 586 const bool work_to_do =
493 old_job.session->status_controller()->num_server_changes_remaining() > 0 587 old_job.session->status_controller()->num_server_changes_remaining() > 0
494 || old_job.session->status_controller()->unsynced_handles().size() > 0; 588 || old_job.session->status_controller()->unsynced_handles().size() > 0;
495 VLOG(1) << "syncer has work to do: " << work_to_do; 589 VLOG(2) << this << " syncer has work to do: " << work_to_do;
496 590
497 AdjustPolling(&old_job); 591 AdjustPolling(&old_job);
498 592
499 // TODO(tim): Old impl had special code if notifications disabled. Needed? 593 // TODO(tim): Old impl had special code if notifications disabled. Needed?
500 if (!work_to_do) { 594 if (!work_to_do) {
501 // Success implies backoff relief. Note that if this was a "one-off" job 595 // Success implies backoff relief. Note that if this was a "one-off" job
502 // (i.e. purpose == CLEAR_USER_DATA), if there was work_to_do before it 596 // (i.e. purpose == SyncSessionJob::CLEAR_USER_DATA), if there was
503 // ran this wont have changed, as jobs like this don't run a full sync 597 // work_to_do before it ran this wont have changed, as jobs like this don't
504 // cycle. So we don't need special code here. 598 // run a full sync cycle. So we don't need special code here.
505 wait_interval_.reset(); 599 wait_interval_.reset();
600 VLOG(2) << this << " Job suceeded so not scheduling more jobs";
506 return; 601 return;
507 } 602 }
508 603
509 if (old_job.session->source().updates_source == 604 if (old_job.session->source().updates_source ==
510 GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION) { 605 GetUpdatesCallerInfo::SYNC_CYCLE_CONTINUATION) {
606 VLOG(2) << this << " Job failed with source continuation";
511 // We don't seem to have made forward progress. Start or extend backoff. 607 // We don't seem to have made forward progress. Start or extend backoff.
512 HandleConsecutiveContinuationError(old_job); 608 HandleConsecutiveContinuationError(old_job);
513 } else if (IsBackingOff()) { 609 } else if (IsBackingOff()) {
610 VLOG(2) << this << " A nudge during backoff failed";
514 // We weren't continuing but we're in backoff; must have been a nudge. 611 // We weren't continuing but we're in backoff; must have been a nudge.
515 DCHECK_EQ(NUDGE, old_job.purpose); 612 DCHECK_EQ(SyncSessionJob::NUDGE, old_job.purpose);
516 DCHECK(!wait_interval_->had_nudge); 613 DCHECK(!wait_interval_->had_nudge);
517 wait_interval_->had_nudge = true; 614 wait_interval_->had_nudge = true;
518 wait_interval_->timer.Reset(); 615 wait_interval_->timer.Reset();
519 } else { 616 } else {
617 VLOG(2) << this << " Failed. Schedule a job with continuation as source";
520 // We weren't continuing and we aren't in backoff. Schedule a normal 618 // We weren't continuing and we aren't in backoff. Schedule a normal
521 // continuation. 619 // continuation.
522 ScheduleNudgeImpl(TimeDelta::FromSeconds(0), NUDGE_SOURCE_CONTINUATION, 620 if (old_job.purpose == SyncSessionJob::CONFIGURATION) {
523 old_job.session->source().types, FROM_HERE); 621 ScheduleConfigImpl(old_job.session->routing_info(),
622 old_job.session->workers(),
623 GetUpdatesFromNudgeSource(NUDGE_SOURCE_CONTINUATION));
624 } else {
625 // For all other purposes(nudge and poll) we schedule a retry nudge.
626 ScheduleNudgeImpl(TimeDelta::FromSeconds(0),
627 GetUpdatesFromNudgeSource(NUDGE_SOURCE_CONTINUATION),
628 old_job.session->source().types, false, FROM_HERE);
629 }
524 } 630 }
525 } 631 }
526 632
527 void SyncerThread::AdjustPolling(const SyncSessionJob* old_job) { 633 void SyncerThread::AdjustPolling(const SyncSessionJob* old_job) {
528 DCHECK(thread_.IsRunning()); 634 DCHECK(thread_.IsRunning());
529 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 635 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
530 636
531 TimeDelta poll = (!session_context_->notifications_enabled()) ? 637 TimeDelta poll = (!session_context_->notifications_enabled()) ?
532 syncer_short_poll_interval_seconds_ : 638 syncer_short_poll_interval_seconds_ :
533 syncer_long_poll_interval_seconds_; 639 syncer_long_poll_interval_seconds_;
534 bool rate_changed = !poll_timer_.IsRunning() || 640 bool rate_changed = !poll_timer_.IsRunning() ||
535 poll != poll_timer_.GetCurrentDelay(); 641 poll != poll_timer_.GetCurrentDelay();
536 642
537 if (old_job && old_job->purpose != POLL && !rate_changed) 643 if (old_job && old_job->purpose != SyncSessionJob::POLL && !rate_changed)
538 poll_timer_.Reset(); 644 poll_timer_.Reset();
539 645
540 if (!rate_changed) 646 if (!rate_changed)
541 return; 647 return;
542 648
543 // Adjust poll rate. 649 // Adjust poll rate.
544 poll_timer_.Stop(); 650 poll_timer_.Stop();
545 poll_timer_.Start(poll, this, &SyncerThread::PollTimerCallback); 651 poll_timer_.Start(poll, this, &SyncerThread::PollTimerCallback);
546 } 652 }
547 653
548 void SyncerThread::HandleConsecutiveContinuationError( 654 void SyncerThread::HandleConsecutiveContinuationError(
549 const SyncSessionJob& old_job) { 655 const SyncSessionJob& old_job) {
550 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 656 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
551 DCHECK(!IsBackingOff() || !wait_interval_->timer.IsRunning()); 657 // This if conditions should be compiled out in retail builds.
658 if (IsBackingOff()) {
659 DCHECK(wait_interval_->timer.IsRunning() || old_job.is_canary_job);
660 }
552 SyncSession* old = old_job.session.get(); 661 SyncSession* old = old_job.session.get();
553 SyncSession* s(new SyncSession(session_context_.get(), this, 662 SyncSession* s(new SyncSession(session_context_.get(), this,
554 old->source(), old->routing_info(), old->workers())); 663 old->source(), old->routing_info(), old->workers()));
555 TimeDelta length = delay_provider_->GetDelay( 664 TimeDelta length = delay_provider_->GetDelay(
556 IsBackingOff() ? wait_interval_->length : TimeDelta::FromSeconds(1)); 665 IsBackingOff() ? wait_interval_->length : TimeDelta::FromSeconds(1));
666
667 VLOG(2) << this << " In handle continuation error. Old job purpose is "
668 << old_job.purpose;
669 VLOG(2) << this << " In Handle continuation error. The time delta(ms)"
670 " calculated is "
671 << length.InMilliseconds();
672
673 // This will reset the had_nudge variable as well.
557 wait_interval_.reset(new WaitInterval(WaitInterval::EXPONENTIAL_BACKOFF, 674 wait_interval_.reset(new WaitInterval(WaitInterval::EXPONENTIAL_BACKOFF,
558 length)); 675 length));
559 SyncSessionJob job = {NUDGE, TimeTicks::Now() + length, 676 if (old_job.purpose == SyncSessionJob::CONFIGURATION) {
560 make_linked_ptr(s), FROM_HERE}; 677 SyncSessionJob job(old_job.purpose, TimeTicks::Now() + length,
561 pending_nudge_.reset(new SyncSessionJob(job)); 678 make_linked_ptr(s), false, FROM_HERE);
679 wait_interval_->pending_configure_job.reset(new SyncSessionJob(job));
680 } else {
681 // We are not in configuration mode. So wait_interval's pending job
682 // should be null.
683 DCHECK(wait_interval_->pending_configure_job.get() == NULL);
684
685 // TODO(lipalani) - handle clear user data.
686 InitOrCoalescePendingJob(old_job);
687 }
562 wait_interval_->timer.Start(length, this, &SyncerThread::DoCanaryJob); 688 wait_interval_->timer.Start(length, this, &SyncerThread::DoCanaryJob);
563 } 689 }
564 690
565 // static 691 // static
566 TimeDelta SyncerThread::GetRecommendedDelay(const TimeDelta& last_delay) { 692 TimeDelta SyncerThread::GetRecommendedDelay(const TimeDelta& last_delay) {
567 if (last_delay.InSeconds() >= kMaxBackoffSeconds) 693 if (last_delay.InSeconds() >= kMaxBackoffSeconds)
568 return TimeDelta::FromSeconds(kMaxBackoffSeconds); 694 return TimeDelta::FromSeconds(kMaxBackoffSeconds);
569 695
570 // This calculates approx. base_delay_seconds * 2 +/- base_delay_seconds / 2 696 // This calculates approx. base_delay_seconds * 2 +/- base_delay_seconds / 2
571 int64 backoff_s = 697 int64 backoff_s =
572 std::max(static_cast<int64>(1), 698 std::max(static_cast<int64>(1),
573 last_delay.InSeconds() * kBackoffRandomizationFactor); 699 last_delay.InSeconds() * kBackoffRandomizationFactor);
574 700
575 // Flip a coin to randomize backoff interval by +/- 50%. 701 // Flip a coin to randomize backoff interval by +/- 50%.
576 int rand_sign = base::RandInt(0, 1) * 2 - 1; 702 int rand_sign = base::RandInt(0, 1) * 2 - 1;
577 703
578 // Truncation is adequate for rounding here. 704 // Truncation is adequate for rounding here.
579 backoff_s = backoff_s + 705 backoff_s = backoff_s +
580 (rand_sign * (last_delay.InSeconds() / kBackoffRandomizationFactor)); 706 (rand_sign * (last_delay.InSeconds() / kBackoffRandomizationFactor));
581 707
582 // Cap the backoff interval. 708 // Cap the backoff interval.
583 backoff_s = std::max(static_cast<int64>(1), 709 backoff_s = std::max(static_cast<int64>(1),
584 std::min(backoff_s, kMaxBackoffSeconds)); 710 std::min(backoff_s, kMaxBackoffSeconds));
585 711
586 return TimeDelta::FromSeconds(backoff_s); 712 return TimeDelta::FromSeconds(backoff_s);
587 } 713 }
588 714
589 void SyncerThread::Stop() { 715 void SyncerThread::Stop() {
716 VLOG(2) << this << " stop called";
590 syncer_->RequestEarlyExit(); // Safe to call from any thread. 717 syncer_->RequestEarlyExit(); // Safe to call from any thread.
591 session_context_->connection_manager()->RemoveListener(this); 718 session_context_->connection_manager()->RemoveListener(this);
592 thread_.Stop(); 719 thread_.Stop();
593 } 720 }
594 721
595 void SyncerThread::DoCanaryJob() { 722 void SyncerThread::DoCanaryJob() {
596 DCHECK(pending_nudge_.get()); 723 VLOG(2) << this << " Do canary job";
597 wait_interval_->had_nudge = false; 724 DoPendingJobIfPossible(true);
598 SyncSessionJob copy = *pending_nudge_; 725 }
599 DoSyncSessionJob(copy); 726
727 void SyncerThread::DoPendingJobIfPossible(bool is_canary_job) {
728 SyncSessionJob* job_to_execute = NULL;
729 if (mode_ == CONFIGURATION_MODE && wait_interval_.get()
730 && wait_interval_->pending_configure_job.get()) {
731 VLOG(2) << this << " Found pending configure job";
732 job_to_execute = wait_interval_->pending_configure_job.get();
733 } else if (mode_ == NORMAL_MODE && pending_nudge_.get()) {
734 VLOG(2) << this << " Found pending nudge job";
735 // Pending jobs mostly have time from the past. Reset it so this job
736 // will get executed.
737 if (pending_nudge_->scheduled_start < TimeTicks::Now())
738 pending_nudge_->scheduled_start = TimeTicks::Now();
739
740 scoped_ptr<SyncSession> session(CreateSyncSession(
741 pending_nudge_->session->source()));
742
743 // Also the routing info might have been changed since we cached the
744 // pending nudge. Update it by coalescing to the latest.
745 pending_nudge_->session->Coalesce(*(session.get()));
746 // The pending nudge would be cleared in the DoSyncSessionJob function.
747 job_to_execute = pending_nudge_.get();
748 }
749
750 if (job_to_execute != NULL) {
751 VLOG(2) << this << " Executing pending job";
752 SyncSessionJob copy = *job_to_execute;
753 copy.is_canary_job = is_canary_job;
754 DoSyncSessionJob(copy);
755 }
756 }
757
758 SyncSession* SyncerThread::CreateSyncSession(const SyncSourceInfo& source) {
759 ModelSafeRoutingInfo routes;
760 std::vector<ModelSafeWorker*> workers;
761 session_context_->registrar()->GetModelSafeRoutingInfo(&routes);
762 session_context_->registrar()->GetWorkers(&workers);
763 SyncSourceInfo info(source);
764
765 SyncSession* session(new SyncSession(session_context_.get(), this, info,
766 routes, workers));
767
768 return session;
600 } 769 }
601 770
602 void SyncerThread::PollTimerCallback() { 771 void SyncerThread::PollTimerCallback() {
603 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 772 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
604 ModelSafeRoutingInfo r; 773 ModelSafeRoutingInfo r;
605 std::vector<ModelSafeWorker*> w;
606 session_context_->registrar()->GetModelSafeRoutingInfo(&r);
607 session_context_->registrar()->GetWorkers(&w);
608 ModelTypePayloadMap types_with_payloads = 774 ModelTypePayloadMap types_with_payloads =
609 syncable::ModelTypePayloadMapFromRoutingInfo(r, std::string()); 775 syncable::ModelTypePayloadMapFromRoutingInfo(r, std::string());
610 SyncSourceInfo info(GetUpdatesCallerInfo::PERIODIC, types_with_payloads); 776 SyncSourceInfo info(GetUpdatesCallerInfo::PERIODIC, types_with_payloads);
611 SyncSession* s = new SyncSession(session_context_.get(), this, info, r, w); 777 SyncSession* s = CreateSyncSession(info);
612 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0), POLL, s, FROM_HERE); 778 ScheduleSyncSessionJob(TimeDelta::FromSeconds(0), SyncSessionJob::POLL, s,
779 FROM_HERE);
613 } 780 }
614 781
615 void SyncerThread::Unthrottle() { 782 void SyncerThread::Unthrottle() {
616 DCHECK_EQ(WaitInterval::THROTTLED, wait_interval_->mode); 783 DCHECK_EQ(WaitInterval::THROTTLED, wait_interval_->mode);
784 VLOG(2) << this << " Unthrottled..";
785 DoCanaryJob();
617 wait_interval_.reset(); 786 wait_interval_.reset();
618 } 787 }
619 788
620 void SyncerThread::Notify(SyncEngineEvent::EventCause cause) { 789 void SyncerThread::Notify(SyncEngineEvent::EventCause cause) {
621 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 790 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
622 session_context_->NotifyListeners(SyncEngineEvent(cause)); 791 session_context_->NotifyListeners(SyncEngineEvent(cause));
623 } 792 }
624 793
625 bool SyncerThread::IsBackingOff() const { 794 bool SyncerThread::IsBackingOff() const {
626 return wait_interval_.get() && wait_interval_->mode == 795 return wait_interval_.get() && wait_interval_->mode ==
(...skipping 18 matching lines...) Expand all
645 syncer_short_poll_interval_seconds_ = new_interval; 814 syncer_short_poll_interval_seconds_ = new_interval;
646 } 815 }
647 816
648 void SyncerThread::OnReceivedLongPollIntervalUpdate( 817 void SyncerThread::OnReceivedLongPollIntervalUpdate(
649 const base::TimeDelta& new_interval) { 818 const base::TimeDelta& new_interval) {
650 DCHECK_EQ(MessageLoop::current(), thread_.message_loop()); 819 DCHECK_EQ(MessageLoop::current(), thread_.message_loop());
651 syncer_long_poll_interval_seconds_ = new_interval; 820 syncer_long_poll_interval_seconds_ = new_interval;
652 } 821 }
653 822
654 void SyncerThread::OnShouldStopSyncingPermanently() { 823 void SyncerThread::OnShouldStopSyncingPermanently() {
824 VLOG(2) << this << " OnShouldStopSyncingPermanently";
655 syncer_->RequestEarlyExit(); // Thread-safe. 825 syncer_->RequestEarlyExit(); // Thread-safe.
656 Notify(SyncEngineEvent::STOP_SYNCING_PERMANENTLY); 826 Notify(SyncEngineEvent::STOP_SYNCING_PERMANENTLY);
657 } 827 }
658 828
659 void SyncerThread::OnServerConnectionEvent( 829 void SyncerThread::OnServerConnectionEvent(
660 const ServerConnectionEvent2& event) { 830 const ServerConnectionEvent2& event) {
661 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, 831 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this,
662 &SyncerThread::CheckServerConnectionManagerStatus, 832 &SyncerThread::CheckServerConnectionManagerStatus,
663 event.connection_code)); 833 event.connection_code));
664 } 834 }
665 835
666 void SyncerThread::set_notifications_enabled(bool notifications_enabled) { 836 void SyncerThread::set_notifications_enabled(bool notifications_enabled) {
667 session_context_->set_notifications_enabled(notifications_enabled); 837 session_context_->set_notifications_enabled(notifications_enabled);
668 } 838 }
669 839
670 } // s3 840 } // s3
671 } // browser_sync 841 } // browser_sync
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698