1// Copyright (c) 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.
4
5#include "base/message_loop/message_loop.h"
6#include "base/run_loop.h"
7#include "sync/internal_api/public/base/model_type_test_util.h"
8#include "sync/notifier/invalidation_util.h"
9#include "sync/notifier/mock_ack_handler.h"
10#include "sync/notifier/object_id_invalidation_map.h"
11#include "sync/sessions/nudge_tracker.h"
12#include "testing/gtest/include/gtest/gtest.h"
13
14namespace syncer {
15
16namespace {
17
18testing::AssertionResult ModelTypeSetEquals(ModelTypeSet a, ModelTypeSet b) {
19  if (a.Equals(b)) {
20    return testing::AssertionSuccess();
21  } else {
22    return testing::AssertionFailure()
23        << "Left side " << ModelTypeSetToString(a)
24        << ", does not match rigth side: " << ModelTypeSetToString(b);
25  }
26}
27
28syncer::Invalidation BuildUnknownVersionInvalidation(ModelType type) {
29  invalidation::ObjectId id;
30  bool result = RealModelTypeToObjectId(type, &id);
31  DCHECK(result);
32  return Invalidation::InitUnknownVersion(id);
33}
34
35
36}  // namespace
37
38namespace sessions {
39
40class NudgeTrackerTest : public ::testing::Test {
41 public:
42  NudgeTrackerTest() {
43    SetInvalidationsInSync();
44  }
45
46  static size_t GetHintBufferSize() {
47    // Assumes that no test has adjusted this size.
48    return NudgeTracker::kDefaultMaxPayloadsPerType;
49  }
50
51  bool InvalidationsOutOfSync() const {
52    // We don't currently track invalidations out of sync on a per-type basis.
53    sync_pb::GetUpdateTriggers gu_trigger;
54    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
55    return gu_trigger.invalidations_out_of_sync();
56  }
57
58  int ProtoLocallyModifiedCount(ModelType type) const {
59    sync_pb::GetUpdateTriggers gu_trigger;
60    nudge_tracker_.FillProtoMessage(type, &gu_trigger);
61    return gu_trigger.local_modification_nudges();
62  }
63
64  int ProtoRefreshRequestedCount(ModelType type) const {
65    sync_pb::GetUpdateTriggers gu_trigger;
66    nudge_tracker_.FillProtoMessage(type, &gu_trigger);
67    return gu_trigger.datatype_refresh_nudges();
68  }
69
70  void SetInvalidationsInSync() {
71    nudge_tracker_.OnInvalidationsEnabled();
72    nudge_tracker_.RecordSuccessfulSyncCycle();
73  }
74
75 protected:
76  NudgeTracker nudge_tracker_;
77};
78
79// Exercise an empty NudgeTracker.
80// Use with valgrind to detect uninitialized members.
81TEST_F(NudgeTrackerTest, EmptyNudgeTracker) {
82  // Now we're at the normal, "idle" state.
83  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
84  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
85  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::UNKNOWN,
86            nudge_tracker_.GetLegacySource());
87
88  sync_pb::GetUpdateTriggers gu_trigger;
89  nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
90
91  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::UNKNOWN,
92            nudge_tracker_.GetLegacySource());
93}
94
95// Verify that nudges override each other based on a priority order.
96// RETRY < LOCAL < DATATYPE_REFRESH < NOTIFICATION
97TEST_F(NudgeTrackerTest, SourcePriorities) {
98  // Start with a retry request.
99  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(1234);
100  const base::TimeTicks t1 = t0 + base::TimeDelta::FromSeconds(10);
101  nudge_tracker_.SetNextRetryTime(t0);
102  nudge_tracker_.SetSyncCycleStartTime(t1);
103  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RETRY,
104            nudge_tracker_.GetLegacySource());
105
106  // Track a local nudge.
107  nudge_tracker_.RecordLocalChange(ModelTypeSet(BOOKMARKS));
108  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::LOCAL,
109            nudge_tracker_.GetLegacySource());
110
111  // A refresh request will override it.
112  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(TYPED_URLS));
113  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::DATATYPE_REFRESH,
114            nudge_tracker_.GetLegacySource());
115
116  // Another local nudge will not be enough to change it.
117  nudge_tracker_.RecordLocalChange(ModelTypeSet(BOOKMARKS));
118  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::DATATYPE_REFRESH,
119            nudge_tracker_.GetLegacySource());
120
121  // An invalidation will override the refresh request source.
122  ObjectIdInvalidationMap invalidation_map =
123      BuildInvalidationMap(PREFERENCES, 1, "hint");
124  nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
125  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::NOTIFICATION,
126            nudge_tracker_.GetLegacySource());
127
128  // Neither local nudges nor refresh requests will override it.
129  nudge_tracker_.RecordLocalChange(ModelTypeSet(BOOKMARKS));
130  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::NOTIFICATION,
131            nudge_tracker_.GetLegacySource());
132  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(TYPED_URLS));
133  EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::NOTIFICATION,
134            nudge_tracker_.GetLegacySource());
135}
136
137// Verifies the management of invalidation hints and GU trigger fields.
138TEST_F(NudgeTrackerTest, HintCoalescing) {
139  // Easy case: record one hint.
140  {
141    ObjectIdInvalidationMap invalidation_map =
142        BuildInvalidationMap(BOOKMARKS, 1, "bm_hint_1");
143    nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
144
145    sync_pb::GetUpdateTriggers gu_trigger;
146    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
147    ASSERT_EQ(1, gu_trigger.notification_hint_size());
148    EXPECT_EQ("bm_hint_1", gu_trigger.notification_hint(0));
149    EXPECT_FALSE(gu_trigger.client_dropped_hints());
150  }
151
152  // Record a second hint for the same type.
153  {
154    ObjectIdInvalidationMap invalidation_map =
155        BuildInvalidationMap(BOOKMARKS, 2, "bm_hint_2");
156    nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
157
158    sync_pb::GetUpdateTriggers gu_trigger;
159    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
160    ASSERT_EQ(2, gu_trigger.notification_hint_size());
161
162    // Expect the most hint recent is last in the list.
163    EXPECT_EQ("bm_hint_1", gu_trigger.notification_hint(0));
164    EXPECT_EQ("bm_hint_2", gu_trigger.notification_hint(1));
165    EXPECT_FALSE(gu_trigger.client_dropped_hints());
166  }
167
168  // Record a hint for a different type.
169  {
170    ObjectIdInvalidationMap invalidation_map =
171        BuildInvalidationMap(PASSWORDS, 1, "pw_hint_1");
172    nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
173
174    // Re-verify the bookmarks to make sure they're unaffected.
175    sync_pb::GetUpdateTriggers bm_gu_trigger;
176    nudge_tracker_.FillProtoMessage(BOOKMARKS, &bm_gu_trigger);
177    ASSERT_EQ(2, bm_gu_trigger.notification_hint_size());
178    EXPECT_EQ("bm_hint_1", bm_gu_trigger.notification_hint(0));
179    EXPECT_EQ("bm_hint_2",
180              bm_gu_trigger.notification_hint(1)); // most recent last.
181    EXPECT_FALSE(bm_gu_trigger.client_dropped_hints());
182
183    // Verify the new type, too.
184    sync_pb::GetUpdateTriggers pw_gu_trigger;
185    nudge_tracker_.FillProtoMessage(PASSWORDS, &pw_gu_trigger);
186    ASSERT_EQ(1, pw_gu_trigger.notification_hint_size());
187    EXPECT_EQ("pw_hint_1", pw_gu_trigger.notification_hint(0));
188    EXPECT_FALSE(pw_gu_trigger.client_dropped_hints());
189  }
190}
191
192// Test the dropping of invalidation hints.  Receives invalidations one by one.
193TEST_F(NudgeTrackerTest, DropHintsLocally_OneAtATime) {
194  for (size_t i = 0; i < GetHintBufferSize(); ++i) {
195    ObjectIdInvalidationMap invalidation_map =
196        BuildInvalidationMap(BOOKMARKS, i, "hint");
197    nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
198  }
199  {
200    sync_pb::GetUpdateTriggers gu_trigger;
201    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
202    EXPECT_EQ(GetHintBufferSize(),
203              static_cast<size_t>(gu_trigger.notification_hint_size()));
204    EXPECT_FALSE(gu_trigger.client_dropped_hints());
205  }
206
207  // Force an overflow.
208  ObjectIdInvalidationMap invalidation_map2 =
209      BuildInvalidationMap(BOOKMARKS, 1000, "new_hint");
210  nudge_tracker_.RecordRemoteInvalidation(invalidation_map2);
211
212  {
213    sync_pb::GetUpdateTriggers gu_trigger;
214    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
215    EXPECT_TRUE(gu_trigger.client_dropped_hints());
216    ASSERT_EQ(GetHintBufferSize(),
217              static_cast<size_t>(gu_trigger.notification_hint_size()));
218
219    // Verify the newest hint was not dropped and is the last in the list.
220    EXPECT_EQ("new_hint", gu_trigger.notification_hint(GetHintBufferSize()-1));
221
222    // Verify the oldest hint, too.
223    EXPECT_EQ("hint", gu_trigger.notification_hint(0));
224  }
225}
226
227// Test the dropping of invalidation hints.
228// Receives invalidations in large batches.
229TEST_F(NudgeTrackerTest, DropHintsLocally_ManyHints) {
230  ObjectIdInvalidationMap invalidation_map;
231  for (size_t i = 0; i < GetHintBufferSize(); ++i) {
232    invalidation_map.Insert(BuildInvalidation(BOOKMARKS, i, "hint"));
233  }
234  nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
235  {
236    sync_pb::GetUpdateTriggers gu_trigger;
237    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
238    EXPECT_EQ(GetHintBufferSize(),
239              static_cast<size_t>(gu_trigger.notification_hint_size()));
240    EXPECT_FALSE(gu_trigger.client_dropped_hints());
241  }
242
243  // Force an overflow.
244  ObjectIdInvalidationMap invalidation_map2;
245  invalidation_map2.Insert(BuildInvalidation(BOOKMARKS, 1000, "new_hint"));
246  invalidation_map2.Insert(BuildInvalidation(BOOKMARKS, 1001, "newer_hint"));
247  nudge_tracker_.RecordRemoteInvalidation(invalidation_map2);
248
249  {
250    sync_pb::GetUpdateTriggers gu_trigger;
251    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
252    EXPECT_TRUE(gu_trigger.client_dropped_hints());
253    ASSERT_EQ(GetHintBufferSize(),
254              static_cast<size_t>(gu_trigger.notification_hint_size()));
255
256    // Verify the newest hints were not dropped and are the last in the list.
257    EXPECT_EQ("newer_hint",
258              gu_trigger.notification_hint(GetHintBufferSize()-1));
259    EXPECT_EQ("new_hint", gu_trigger.notification_hint(GetHintBufferSize()-2));
260
261    // Verify the oldest hint, too.
262    EXPECT_EQ("hint", gu_trigger.notification_hint(0));
263  }
264}
265
266// Tests the receipt of 'unknown version' invalidations.
267TEST_F(NudgeTrackerTest, DropHintsAtServer_Alone) {
268  ObjectIdInvalidationMap invalidation_map;
269  invalidation_map.Insert(BuildUnknownVersionInvalidation(BOOKMARKS));
270
271  // Record the unknown version invalidation.
272  nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
273  {
274    sync_pb::GetUpdateTriggers gu_trigger;
275    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
276    EXPECT_TRUE(gu_trigger.server_dropped_hints());
277    EXPECT_FALSE(gu_trigger.client_dropped_hints());
278    ASSERT_EQ(0, gu_trigger.notification_hint_size());
279  }
280
281  // Clear status then verify.
282  nudge_tracker_.RecordSuccessfulSyncCycle();
283  {
284    sync_pb::GetUpdateTriggers gu_trigger;
285    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
286    EXPECT_FALSE(gu_trigger.client_dropped_hints());
287    EXPECT_FALSE(gu_trigger.server_dropped_hints());
288    ASSERT_EQ(0, gu_trigger.notification_hint_size());
289  }
290}
291
292// Tests the receipt of 'unknown version' invalidations.  This test also
293// includes a known version invalidation to mix things up a bit.
294TEST_F(NudgeTrackerTest, DropHintsAtServer_WithOtherInvalidations) {
295  ObjectIdInvalidationMap invalidation_map;
296  invalidation_map.Insert(BuildUnknownVersionInvalidation(BOOKMARKS));
297  invalidation_map.Insert(BuildInvalidation(BOOKMARKS, 10, "hint"));
298
299  // Record the two invalidations, one with unknown version, the other unknown.
300  nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
301  {
302    sync_pb::GetUpdateTriggers gu_trigger;
303    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
304    EXPECT_TRUE(gu_trigger.server_dropped_hints());
305    EXPECT_FALSE(gu_trigger.client_dropped_hints());
306    ASSERT_EQ(1, gu_trigger.notification_hint_size());
307    EXPECT_EQ("hint", gu_trigger.notification_hint(0));
308  }
309
310  // Clear status then verify.
311  nudge_tracker_.RecordSuccessfulSyncCycle();
312  {
313    sync_pb::GetUpdateTriggers gu_trigger;
314    nudge_tracker_.FillProtoMessage(BOOKMARKS, &gu_trigger);
315    EXPECT_FALSE(gu_trigger.client_dropped_hints());
316    EXPECT_FALSE(gu_trigger.server_dropped_hints());
317    ASSERT_EQ(0, gu_trigger.notification_hint_size());
318  }
319}
320
321// Checks the behaviour of the invalidations-out-of-sync flag.
322TEST_F(NudgeTrackerTest, EnableDisableInvalidations) {
323  // Start with invalidations offline.
324  nudge_tracker_.OnInvalidationsDisabled();
325  EXPECT_TRUE(InvalidationsOutOfSync());
326  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
327
328  // Simply enabling invalidations does not bring us back into sync.
329  nudge_tracker_.OnInvalidationsEnabled();
330  EXPECT_TRUE(InvalidationsOutOfSync());
331  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
332
333  // We must successfully complete a sync cycle while invalidations are enabled
334  // to be sure that we're in sync.
335  nudge_tracker_.RecordSuccessfulSyncCycle();
336  EXPECT_FALSE(InvalidationsOutOfSync());
337  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
338
339  // If the invalidator malfunctions, we go become unsynced again.
340  nudge_tracker_.OnInvalidationsDisabled();
341  EXPECT_TRUE(InvalidationsOutOfSync());
342  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
343
344  // A sync cycle while invalidations are disabled won't reset the flag.
345  nudge_tracker_.RecordSuccessfulSyncCycle();
346  EXPECT_TRUE(InvalidationsOutOfSync());
347  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
348
349  // Nor will the re-enabling of invalidations be sufficient, even now that
350  // we've had a successful sync cycle.
351  nudge_tracker_.RecordSuccessfulSyncCycle();
352  EXPECT_TRUE(InvalidationsOutOfSync());
353  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
354}
355
356// Tests that locally modified types are correctly written out to the
357// GetUpdateTriggers proto.
358TEST_F(NudgeTrackerTest, WriteLocallyModifiedTypesToProto) {
359  // Should not be locally modified by default.
360  EXPECT_EQ(0, ProtoLocallyModifiedCount(PREFERENCES));
361
362  // Record a local bookmark change.  Verify it was registered correctly.
363  nudge_tracker_.RecordLocalChange(ModelTypeSet(PREFERENCES));
364  EXPECT_EQ(1, ProtoLocallyModifiedCount(PREFERENCES));
365
366  // Record a successful sync cycle.  Verify the count is cleared.
367  nudge_tracker_.RecordSuccessfulSyncCycle();
368  EXPECT_EQ(0, ProtoLocallyModifiedCount(PREFERENCES));
369}
370
371// Tests that refresh requested types are correctly written out to the
372// GetUpdateTriggers proto.
373TEST_F(NudgeTrackerTest, WriteRefreshRequestedTypesToProto) {
374  // There should be no refresh requested by default.
375  EXPECT_EQ(0, ProtoRefreshRequestedCount(SESSIONS));
376
377  // Record a local refresh request.  Verify it was registered correctly.
378  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS));
379  EXPECT_EQ(1, ProtoRefreshRequestedCount(SESSIONS));
380
381  // Record a successful sync cycle.  Verify the count is cleared.
382  nudge_tracker_.RecordSuccessfulSyncCycle();
383  EXPECT_EQ(0, ProtoRefreshRequestedCount(SESSIONS));
384}
385
386// Basic tests for the IsSyncRequired() flag.
387TEST_F(NudgeTrackerTest, IsSyncRequired) {
388  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
389
390  // Local changes.
391  nudge_tracker_.RecordLocalChange(ModelTypeSet(SESSIONS));
392  EXPECT_TRUE(nudge_tracker_.IsSyncRequired());
393  nudge_tracker_.RecordSuccessfulSyncCycle();
394  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
395
396  // Refresh requests.
397  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS));
398  EXPECT_TRUE(nudge_tracker_.IsSyncRequired());
399  nudge_tracker_.RecordSuccessfulSyncCycle();
400  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
401
402  // Invalidations.
403  ObjectIdInvalidationMap invalidation_map =
404      BuildInvalidationMap(PREFERENCES, 1, "hint");
405  nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
406  EXPECT_TRUE(nudge_tracker_.IsSyncRequired());
407  nudge_tracker_.RecordSuccessfulSyncCycle();
408  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
409}
410
411// Basic tests for the IsGetUpdatesRequired() flag.
412TEST_F(NudgeTrackerTest, IsGetUpdatesRequired) {
413  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
414
415  // Local changes.
416  nudge_tracker_.RecordLocalChange(ModelTypeSet(SESSIONS));
417  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
418  nudge_tracker_.RecordSuccessfulSyncCycle();
419  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
420
421  // Refresh requests.
422  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS));
423  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
424  nudge_tracker_.RecordSuccessfulSyncCycle();
425  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
426
427  // Invalidations.
428  ObjectIdInvalidationMap invalidation_map =
429      BuildInvalidationMap(PREFERENCES, 1, "hint");
430  nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
431  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
432  nudge_tracker_.RecordSuccessfulSyncCycle();
433  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
434}
435
436// Test IsSyncRequired() responds correctly to data type throttling.
437TEST_F(NudgeTrackerTest, IsSyncRequired_Throttling) {
438  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(1234);
439  const base::TimeDelta throttle_length = base::TimeDelta::FromMinutes(10);
440  const base::TimeTicks t1 = t0 + throttle_length;
441
442  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
443
444  // A local change to sessions enables the flag.
445  nudge_tracker_.RecordLocalChange(ModelTypeSet(SESSIONS));
446  EXPECT_TRUE(nudge_tracker_.IsSyncRequired());
447
448  // But the throttling of sessions unsets it.
449  nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS),
450                                       throttle_length,
451                                       t0);
452  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
453
454  // A refresh request for bookmarks means we have reason to sync again.
455  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(BOOKMARKS));
456  EXPECT_TRUE(nudge_tracker_.IsSyncRequired());
457
458  // A successful sync cycle means we took care of bookmarks.
459  nudge_tracker_.RecordSuccessfulSyncCycle();
460  EXPECT_FALSE(nudge_tracker_.IsSyncRequired());
461
462  // But we still haven't dealt with sessions.  We'll need to remember
463  // that sessions are out of sync and re-enable the flag when their
464  // throttling interval expires.
465  nudge_tracker_.UpdateTypeThrottlingState(t1);
466  EXPECT_FALSE(nudge_tracker_.IsTypeThrottled(SESSIONS));
467  EXPECT_TRUE(nudge_tracker_.IsSyncRequired());
468}
469
470// Test IsGetUpdatesRequired() responds correctly to data type throttling.
471TEST_F(NudgeTrackerTest, IsGetUpdatesRequired_Throttling) {
472  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(1234);
473  const base::TimeDelta throttle_length = base::TimeDelta::FromMinutes(10);
474  const base::TimeTicks t1 = t0 + throttle_length;
475
476  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
477
478  // A refresh request to sessions enables the flag.
479  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS));
480  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
481
482  // But the throttling of sessions unsets it.
483  nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS),
484                                       throttle_length,
485                                       t0);
486  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
487
488  // A refresh request for bookmarks means we have reason to sync again.
489  nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(BOOKMARKS));
490  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
491
492  // A successful sync cycle means we took care of bookmarks.
493  nudge_tracker_.RecordSuccessfulSyncCycle();
494  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
495
496  // But we still haven't dealt with sessions.  We'll need to remember
497  // that sessions are out of sync and re-enable the flag when their
498  // throttling interval expires.
499  nudge_tracker_.UpdateTypeThrottlingState(t1);
500  EXPECT_FALSE(nudge_tracker_.IsTypeThrottled(SESSIONS));
501  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
502}
503
504// Tests throttling-related getter functions when no types are throttled.
505TEST_F(NudgeTrackerTest, NoTypesThrottled) {
506  EXPECT_FALSE(nudge_tracker_.IsAnyTypeThrottled());
507  EXPECT_FALSE(nudge_tracker_.IsTypeThrottled(SESSIONS));
508  EXPECT_TRUE(nudge_tracker_.GetThrottledTypes().Empty());
509}
510
511// Tests throttling-related getter functions when some types are throttled.
512TEST_F(NudgeTrackerTest, ThrottleAndUnthrottle) {
513  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(1234);
514  const base::TimeDelta throttle_length = base::TimeDelta::FromMinutes(10);
515  const base::TimeTicks t1 = t0 + throttle_length;
516
517  nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS, PREFERENCES),
518                                       throttle_length,
519                                       t0);
520
521  EXPECT_TRUE(nudge_tracker_.IsAnyTypeThrottled());
522  EXPECT_TRUE(nudge_tracker_.IsTypeThrottled(SESSIONS));
523  EXPECT_TRUE(nudge_tracker_.IsTypeThrottled(PREFERENCES));
524  EXPECT_FALSE(nudge_tracker_.GetThrottledTypes().Empty());
525  EXPECT_EQ(throttle_length, nudge_tracker_.GetTimeUntilNextUnthrottle(t0));
526
527  nudge_tracker_.UpdateTypeThrottlingState(t1);
528
529  EXPECT_FALSE(nudge_tracker_.IsAnyTypeThrottled());
530  EXPECT_FALSE(nudge_tracker_.IsTypeThrottled(SESSIONS));
531  EXPECT_TRUE(nudge_tracker_.GetThrottledTypes().Empty());
532}
533
534TEST_F(NudgeTrackerTest, OverlappingThrottleIntervals) {
535  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(1234);
536  const base::TimeDelta throttle1_length = base::TimeDelta::FromMinutes(10);
537  const base::TimeDelta throttle2_length = base::TimeDelta::FromMinutes(20);
538  const base::TimeTicks t1 = t0 + throttle1_length;
539  const base::TimeTicks t2 = t0 + throttle2_length;
540
541  // Setup the longer of two intervals.
542  nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS, PREFERENCES),
543                                       throttle2_length,
544                                       t0);
545  EXPECT_TRUE(ModelTypeSetEquals(
546          ModelTypeSet(SESSIONS, PREFERENCES),
547          nudge_tracker_.GetThrottledTypes()));
548  EXPECT_EQ(throttle2_length,
549            nudge_tracker_.GetTimeUntilNextUnthrottle(t0));
550
551  // Setup the shorter interval.
552  nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS, BOOKMARKS),
553                                       throttle1_length,
554                                       t0);
555  EXPECT_TRUE(ModelTypeSetEquals(
556          ModelTypeSet(SESSIONS, PREFERENCES, BOOKMARKS),
557          nudge_tracker_.GetThrottledTypes()));
558  EXPECT_EQ(throttle1_length,
559            nudge_tracker_.GetTimeUntilNextUnthrottle(t0));
560
561  // Expire the first interval.
562  nudge_tracker_.UpdateTypeThrottlingState(t1);
563
564  // SESSIONS appeared in both intervals.  We expect it will be throttled for
565  // the longer of the two, so it's still throttled at time t1.
566  EXPECT_TRUE(ModelTypeSetEquals(
567          ModelTypeSet(SESSIONS, PREFERENCES),
568          nudge_tracker_.GetThrottledTypes()));
569  EXPECT_EQ(throttle2_length - throttle1_length,
570            nudge_tracker_.GetTimeUntilNextUnthrottle(t1));
571
572  // Expire the second interval.
573  nudge_tracker_.UpdateTypeThrottlingState(t2);
574  EXPECT_TRUE(nudge_tracker_.GetThrottledTypes().Empty());
575}
576
577TEST_F(NudgeTrackerTest, Retry) {
578  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(12345);
579  const base::TimeTicks t3 = t0 + base::TimeDelta::FromSeconds(3);
580  const base::TimeTicks t4 = t0 + base::TimeDelta::FromSeconds(4);
581
582  // Set retry for t3.
583  nudge_tracker_.SetNextRetryTime(t3);
584
585  // Not due yet at t0.
586  nudge_tracker_.SetSyncCycleStartTime(t0);
587  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
588  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
589
590  // Successful sync cycle at t0 changes nothing.
591  nudge_tracker_.RecordSuccessfulSyncCycle();
592  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
593  EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired());
594
595  // At t4, the retry becomes due.
596  nudge_tracker_.SetSyncCycleStartTime(t4);
597  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
598  EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired());
599
600  // A sync cycle unsets the flag.
601  nudge_tracker_.RecordSuccessfulSyncCycle();
602  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
603
604  // It's still unset at the start of the next sync cycle.
605  nudge_tracker_.SetSyncCycleStartTime(t4);
606  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
607}
608
609// Test a mid-cycle update when IsRetryRequired() was true before the cycle
610// began.
611TEST_F(NudgeTrackerTest, IsRetryRequired_MidCycleUpdate1) {
612  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(12345);
613  const base::TimeTicks t1 = t0 + base::TimeDelta::FromSeconds(1);
614  const base::TimeTicks t2 = t0 + base::TimeDelta::FromSeconds(2);
615  const base::TimeTicks t5 = t0 + base::TimeDelta::FromSeconds(5);
616  const base::TimeTicks t6 = t0 + base::TimeDelta::FromSeconds(6);
617
618  nudge_tracker_.SetNextRetryTime(t0);
619  nudge_tracker_.SetSyncCycleStartTime(t1);
620
621  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
622
623  // Pretend that we were updated mid-cycle.  SetSyncCycleStartTime is
624  // called only at the start of the sync cycle, so don't call it here.
625  // The update should have no effect on IsRetryRequired().
626  nudge_tracker_.SetNextRetryTime(t5);
627
628  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
629
630  // Verify that the successful sync cycle clears the flag.
631  nudge_tracker_.RecordSuccessfulSyncCycle();
632  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
633
634  // Verify expecations around the new retry time.
635  nudge_tracker_.SetSyncCycleStartTime(t2);
636  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
637
638  nudge_tracker_.SetSyncCycleStartTime(t6);
639  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
640}
641
642// Test a mid-cycle update when IsRetryRequired() was false before the cycle
643// began.
644TEST_F(NudgeTrackerTest, IsRetryRequired_MidCycleUpdate2) {
645  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(12345);
646  const base::TimeTicks t1 = t0 + base::TimeDelta::FromSeconds(1);
647  const base::TimeTicks t3 = t0 + base::TimeDelta::FromSeconds(3);
648  const base::TimeTicks t5 = t0 + base::TimeDelta::FromSeconds(5);
649  const base::TimeTicks t6 = t0 + base::TimeDelta::FromSeconds(6);
650
651  // Schedule a future retry, and a nudge unrelated to it.
652  nudge_tracker_.RecordLocalChange(ModelTypeSet(BOOKMARKS));
653  nudge_tracker_.SetNextRetryTime(t1);
654  nudge_tracker_.SetSyncCycleStartTime(t0);
655  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
656
657  // Pretend this happened in mid-cycle.  This should have no effect on
658  // IsRetryRequired().
659  nudge_tracker_.SetNextRetryTime(t5);
660  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
661
662  // The cycle succeeded.
663  nudge_tracker_.RecordSuccessfulSyncCycle();
664
665  // The time t3 is greater than the GU retry time scheduled at the beginning of
666  // the test, but later than the retry time that overwrote it during the
667  // pretend 'sync cycle'.
668  nudge_tracker_.SetSyncCycleStartTime(t3);
669  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
670
671  // Finally, the retry established during the sync cycle becomes due.
672  nudge_tracker_.SetSyncCycleStartTime(t6);
673  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
674}
675
676// Simulate the case where a sync cycle fails.
677TEST_F(NudgeTrackerTest, IsRetryRequired_FailedCycle) {
678  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(12345);
679  const base::TimeTicks t1 = t0 + base::TimeDelta::FromSeconds(1);
680  const base::TimeTicks t2 = t0 + base::TimeDelta::FromSeconds(2);
681
682  nudge_tracker_.SetNextRetryTime(t0);
683  nudge_tracker_.SetSyncCycleStartTime(t1);
684  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
685
686  // The nudge tracker receives no notifications for a failed sync cycle.
687  // Pretend one happened here.
688  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
689
690  // Think of this as the retry cycle.
691  nudge_tracker_.SetSyncCycleStartTime(t2);
692  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
693
694  // The second cycle is a success.
695  nudge_tracker_.RecordSuccessfulSyncCycle();
696  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
697}
698
699// Simulate a partially failed sync cycle.  The callback to update the GU retry
700// was invoked, but the sync cycle did not complete successfully.
701TEST_F(NudgeTrackerTest, IsRetryRequired_FailedCycleIncludesUpdate) {
702  const base::TimeTicks t0 = base::TimeTicks::FromInternalValue(12345);
703  const base::TimeTicks t1 = t0 + base::TimeDelta::FromSeconds(1);
704  const base::TimeTicks t3 = t0 + base::TimeDelta::FromSeconds(3);
705  const base::TimeTicks t4 = t0 + base::TimeDelta::FromSeconds(4);
706  const base::TimeTicks t5 = t0 + base::TimeDelta::FromSeconds(5);
707  const base::TimeTicks t6 = t0 + base::TimeDelta::FromSeconds(6);
708
709  nudge_tracker_.SetNextRetryTime(t0);
710  nudge_tracker_.SetSyncCycleStartTime(t1);
711  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
712
713  // The cycle is in progress.  A new GU Retry time is received.
714  // The flag is not because this cycle is still in progress.
715  nudge_tracker_.SetNextRetryTime(t5);
716  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
717
718  // The nudge tracker receives no notifications for a failed sync cycle.
719  // Pretend the cycle failed here.
720
721  // The next sync cycle starts.  The new GU time has not taken effect by this
722  // time, but the NudgeTracker hasn't forgotten that we have not yet serviced
723  // the retry from the previous cycle.
724  nudge_tracker_.SetSyncCycleStartTime(t3);
725  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
726
727  // It succeeds.  The retry time is not updated, so it should remain at t5.
728  nudge_tracker_.RecordSuccessfulSyncCycle();
729
730  // Another sync cycle.  This one is still before the scheduled retry.  It does
731  // not change the scheduled retry time.
732  nudge_tracker_.SetSyncCycleStartTime(t4);
733  EXPECT_FALSE(nudge_tracker_.IsRetryRequired());
734  nudge_tracker_.RecordSuccessfulSyncCycle();
735
736  // The retry scheduled way back during the first cycle of this test finally
737  // becomes due.  Perform a successful sync cycle to service it.
738  nudge_tracker_.SetSyncCycleStartTime(t6);
739  EXPECT_TRUE(nudge_tracker_.IsRetryRequired());
740  nudge_tracker_.RecordSuccessfulSyncCycle();
741}
742
743class NudgeTrackerAckTrackingTest : public NudgeTrackerTest {
744 public:
745  NudgeTrackerAckTrackingTest() {}
746
747  bool IsInvalidationUnacknowledged(const syncer::Invalidation& invalidation) {
748    // Run pending tasks before checking with the MockAckHandler.
749    // The WeakHandle may have posted some tasks for it.
750    base::RunLoop().RunUntilIdle();
751    return mock_ack_handler_.IsUnacked(invalidation);
752  }
753
754  bool IsInvalidationAcknowledged(const syncer::Invalidation& invalidation) {
755    // Run pending tasks before checking with the MockAckHandler.
756    // The WeakHandle may have posted some tasks for it.
757    base::RunLoop().RunUntilIdle();
758    return mock_ack_handler_.IsAcknowledged(invalidation);
759  }
760
761  bool IsInvalidationDropped(const syncer::Invalidation& invalidation) {
762    // Run pending tasks before checking with the MockAckHandler.
763    // The WeakHandle may have posted some tasks for it.
764    base::RunLoop().RunUntilIdle();
765    return mock_ack_handler_.IsDropped(invalidation);
766  }
767
768  bool AllInvalidationsAccountedFor() {
769    return mock_ack_handler_.AllInvalidationsAccountedFor();
770  }
771
772  Invalidation SendInvalidation(
773      ModelType type,
774      int64 version,
775      const std::string& hint) {
776    // Build and register the invalidation.
777    syncer::Invalidation invalidation = BuildInvalidation(type, version, hint);
778    mock_ack_handler_.RegisterInvalidation(&invalidation);
779
780    // Send it to the NudgeTracker.
781    ObjectIdInvalidationMap invalidation_map;
782    invalidation_map.Insert(invalidation);
783    nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
784
785    // Return it to the test framework for use in assertions.
786    return invalidation;
787  }
788
789  Invalidation SendUnknownVersionInvalidation(ModelType type) {
790    // Build and register the invalidation.
791    syncer::Invalidation invalidation = BuildUnknownVersionInvalidation(type);
792    mock_ack_handler_.RegisterInvalidation(&invalidation);
793
794    // Send it to the NudgeTracker.
795    ObjectIdInvalidationMap invalidation_map;
796    invalidation_map.Insert(invalidation);
797    nudge_tracker_.RecordRemoteInvalidation(invalidation_map);
798
799    // Return it to the test framework for use in assertions.
800    return invalidation;
801  }
802
803  void RecordSuccessfulSyncCycle() {
804    nudge_tracker_.RecordSuccessfulSyncCycle();
805  }
806
807 private:
808  syncer::MockAckHandler mock_ack_handler_;
809  base::MessageLoop loop_;
810};
811
812// Test the acknowledgement of a single invalidation.
813TEST_F(NudgeTrackerAckTrackingTest, SimpleAcknowledgement) {
814  Invalidation inv = SendInvalidation(BOOKMARKS, 10, "hint");
815
816  EXPECT_TRUE(IsInvalidationUnacknowledged(inv));
817
818  RecordSuccessfulSyncCycle();
819  EXPECT_TRUE(IsInvalidationAcknowledged(inv));
820
821  EXPECT_TRUE(AllInvalidationsAccountedFor());
822}
823
824// Test the acknowledgement of many invalidations.
825TEST_F(NudgeTrackerAckTrackingTest, ManyAcknowledgements) {
826  Invalidation inv1 = SendInvalidation(BOOKMARKS, 10, "hint");
827  Invalidation inv2 = SendInvalidation(BOOKMARKS, 14, "hint2");
828  Invalidation inv3 = SendInvalidation(PREFERENCES, 8, "hint3");
829
830  EXPECT_TRUE(IsInvalidationUnacknowledged(inv1));
831  EXPECT_TRUE(IsInvalidationUnacknowledged(inv2));
832  EXPECT_TRUE(IsInvalidationUnacknowledged(inv3));
833
834  RecordSuccessfulSyncCycle();
835  EXPECT_TRUE(IsInvalidationAcknowledged(inv1));
836  EXPECT_TRUE(IsInvalidationAcknowledged(inv2));
837  EXPECT_TRUE(IsInvalidationAcknowledged(inv3));
838
839  EXPECT_TRUE(AllInvalidationsAccountedFor());
840}
841
842// Test dropping when the buffer overflows and subsequent drop recovery.
843TEST_F(NudgeTrackerAckTrackingTest, OverflowAndRecover) {
844  std::vector<Invalidation> invalidations;
845
846  Invalidation inv10 = SendInvalidation(BOOKMARKS, 10, "hint");
847  for (size_t i = 1; i < GetHintBufferSize(); ++i) {
848    invalidations.push_back(SendInvalidation(BOOKMARKS, i+10, "hint"));
849  }
850
851  for (std::vector<Invalidation>::iterator it = invalidations.begin();
852       it != invalidations.end(); ++it) {
853    EXPECT_TRUE(IsInvalidationUnacknowledged(*it));
854  }
855
856  // This invalidation, though arriving the most recently, has the oldest
857  // version number so it should be dropped first.
858  Invalidation inv5 = SendInvalidation(BOOKMARKS, 5, "old_hint");
859  EXPECT_TRUE(IsInvalidationDropped(inv5));
860
861  // This invalidation has a larger version number, so it will force a
862  // previously delivered invalidation to be dropped.
863  Invalidation inv100 = SendInvalidation(BOOKMARKS, 100, "new_hint");
864  EXPECT_TRUE(IsInvalidationDropped(inv10));
865
866  // This should recover from the drop and bring us back into sync.
867  RecordSuccessfulSyncCycle();
868
869  for (std::vector<Invalidation>::iterator it = invalidations.begin();
870       it != invalidations.end(); ++it) {
871    EXPECT_TRUE(IsInvalidationAcknowledged(*it));
872  }
873  EXPECT_TRUE(IsInvalidationAcknowledged(inv100));
874
875  EXPECT_TRUE(AllInvalidationsAccountedFor());
876}
877
878// Test receipt of an unknown version invalidation from the server.
879TEST_F(NudgeTrackerAckTrackingTest, UnknownVersionFromServer_Simple) {
880  Invalidation inv = SendUnknownVersionInvalidation(BOOKMARKS);
881  EXPECT_TRUE(IsInvalidationUnacknowledged(inv));
882  RecordSuccessfulSyncCycle();
883  EXPECT_TRUE(IsInvalidationAcknowledged(inv));
884  EXPECT_TRUE(AllInvalidationsAccountedFor());
885}
886
887// Test receipt of multiple unknown version invalidations from the server.
888TEST_F(NudgeTrackerAckTrackingTest, UnknownVersionFromServer_Complex) {
889  Invalidation inv1 = SendUnknownVersionInvalidation(BOOKMARKS);
890  Invalidation inv2 = SendInvalidation(BOOKMARKS, 10, "hint");
891  Invalidation inv3 = SendUnknownVersionInvalidation(BOOKMARKS);
892  Invalidation inv4 = SendUnknownVersionInvalidation(BOOKMARKS);
893  Invalidation inv5 = SendInvalidation(BOOKMARKS, 20, "hint2");
894
895  // These invalidations have been overridden, so they got acked early.
896  EXPECT_TRUE(IsInvalidationAcknowledged(inv1));
897  EXPECT_TRUE(IsInvalidationAcknowledged(inv3));
898
899  // These invalidations are still waiting to be used.
900  EXPECT_TRUE(IsInvalidationUnacknowledged(inv2));
901  EXPECT_TRUE(IsInvalidationUnacknowledged(inv4));
902  EXPECT_TRUE(IsInvalidationUnacknowledged(inv5));
903
904  // Finish the sync cycle and expect all remaining invalidations to be acked.
905  RecordSuccessfulSyncCycle();
906  EXPECT_TRUE(IsInvalidationAcknowledged(inv1));
907  EXPECT_TRUE(IsInvalidationAcknowledged(inv2));
908  EXPECT_TRUE(IsInvalidationAcknowledged(inv3));
909  EXPECT_TRUE(IsInvalidationAcknowledged(inv4));
910  EXPECT_TRUE(IsInvalidationAcknowledged(inv5));
911
912  EXPECT_TRUE(AllInvalidationsAccountedFor());
913}
914
915}  // namespace sessions
916}  // namespace syncer
917