File: sync_scheduler_impl_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1857 lines) | stat: -rw-r--r-- 65,681 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sync/engine/sync_scheduler_impl.h"

#include <stddef.h>
#include <stdint.h>

#include <utility>
#include <vector>

#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "base/time/time.h"
#include "components/sync/base/extensions_activity.h"
#include "components/sync/engine/backoff_delay_provider.h"
#include "components/sync/engine/cancelation_signal.h"
#include "components/sync/engine/data_type_activation_response.h"
#include "components/sync/test/data_type_test_util.h"
#include "components/sync/test/fake_data_type_processor.h"
#include "components/sync/test/fake_sync_encryption_handler.h"
#include "components/sync/test/mock_connection_manager.h"
#include "components/sync/test/mock_invalidation.h"
#include "components/sync/test/mock_nudge_handler.h"
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::TimeTicks;
using testing::_;
using testing::AtLeast;
using testing::DoAll;
using testing::Eq;
using testing::Invoke;
using testing::Mock;
using testing::Return;
using testing::WithArg;
using testing::WithArgs;
using testing::WithoutArgs;

namespace syncer {

namespace {
base::OnceClosure g_quit_closure_;
void SimulatePollSuccess(DataTypeSet requested_types, SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::Success());
}

void SimulatePollFailed(DataTypeSet requested_types, SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::ProtocolError(TRANSIENT_ERROR));
}

ACTION_P(SimulateThrottled, throttle) {
  SyncCycle* cycle = arg0;
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::ProtocolError(THROTTLED));
  cycle->delegate()->OnThrottled(throttle);
}

ACTION_P2(SimulateTypeThrottled, type, throttle) {
  SyncCycle* cycle = arg0;
  cycle->mutable_status_controller()->set_commit_result(SyncerError::Success());
  cycle->delegate()->OnTypesThrottled({type}, throttle);
}

ACTION_P(SimulatePartialFailure, type) {
  SyncCycle* cycle = arg0;
  cycle->mutable_status_controller()->set_commit_result(SyncerError::Success());
  cycle->delegate()->OnTypesBackedOff({type});
}

ACTION_P(SimulatePollIntervalUpdate, new_poll) {
  const DataTypeSet requested_types = arg0;
  SyncCycle* cycle = arg1;
  SimulatePollSuccess(requested_types, cycle);
  cycle->delegate()->OnReceivedPollIntervalUpdate(new_poll);
}

void SimulateGetEncryptionKeyFailed(DataTypeSet requsted_types,
                                    sync_pb::SyncEnums::GetUpdatesOrigin origin,
                                    SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_get_key_failed(true);
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::Success());
}

void SimulateConfigureSuccess(DataTypeSet requsted_types,
                              sync_pb::SyncEnums::GetUpdatesOrigin origin,
                              SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_get_key_failed(false);
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::Success());
}

void SimulateConfigureFailed(DataTypeSet requsted_types,
                             sync_pb::SyncEnums::GetUpdatesOrigin origin,
                             SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_get_key_failed(false);
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::ProtocolError(TRANSIENT_ERROR));
}

void SimulateConfigureConnectionFailure(
    DataTypeSet requsted_types,
    sync_pb::SyncEnums::GetUpdatesOrigin origin,
    SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_get_key_failed(false);
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::NetworkError(net::ERR_FAILED));
}

void SimulateNormalSuccess(DataTypeSet requested_types,
                           NudgeTracker* nudge_tracker,
                           SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_commit_result(SyncerError::Success());
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::Success());
}

void SimulateDownloadUpdatesFailed(DataTypeSet requested_types,
                                   NudgeTracker* nudge_tracker,
                                   SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::ProtocolError(TRANSIENT_ERROR));
}

void SimulateCommitFailed(DataTypeSet requested_types,
                          NudgeTracker* nudge_tracker,
                          SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_get_key_failed(false);
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::Success());
  cycle->mutable_status_controller()->set_commit_result(
      SyncerError::ProtocolError(TRANSIENT_ERROR));
}

void SimulateConnectionFailure(DataTypeSet requested_types,
                               NudgeTracker* nudge_tracker,
                               SyncCycle* cycle) {
  cycle->mutable_status_controller()->set_last_download_updates_result(
      SyncerError::NetworkError(net::ERR_FAILED));
}

class MockSyncer : public Syncer {
 public:
  MockSyncer();
  MOCK_METHOD(bool,
              NormalSyncShare,
              (DataTypeSet, NudgeTracker*, SyncCycle*),
              (override));
  MOCK_METHOD(bool,
              ConfigureSyncShare,
              (const DataTypeSet&,
               sync_pb::SyncEnums::GetUpdatesOrigin,
               SyncCycle*),
              (override));
  MOCK_METHOD(bool, PollSyncShare, (DataTypeSet, SyncCycle*), (override));
};

std::unique_ptr<DataTypeActivationResponse> MakeFakeActivationResponse(
    DataType data_type) {
  auto response = std::make_unique<DataTypeActivationResponse>();
  response->type_processor = std::make_unique<FakeDataTypeProcessor>();
  response->data_type_state.mutable_progress_marker()->set_data_type_id(
      GetSpecificsFieldNumberFromDataType(data_type));
  return response;
}

MockSyncer::MockSyncer() : Syncer(nullptr) {}

using SyncShareTimes = std::vector<TimeTicks>;

void QuitLoopNow() {
  // We use QuitNow() instead of Quit() as the latter may get stalled
  // indefinitely in the presence of repeated timers with low delays
  // and a slow test (e.g., ThrottlingDoesThrottle [which has a poll
  // delay of 5ms] run under TSAN on the trybots).
  std::move(g_quit_closure_).Run();
}

void RunLoop() {
  base::RunLoop loop;
  g_quit_closure_ = loop.QuitClosure();
  loop.Run();
}

void PumpLoop() {
  // Do it this way instead of RunAllPending to pump loop exactly once
  // (necessary in the presence of timers; see comment in
  // QuitLoopNow).
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(&QuitLoopNow));
  RunLoop();
}

static const size_t kMinNumSamples = 5;

}  // namespace

// Test harness for the SyncScheduler.  Test the delays and backoff timers used
// in response to various events.  Mock time is used to avoid flakes.
class SyncSchedulerImplTest : public testing::Test {
 public:
  SyncSchedulerImplTest()
      : task_environment_(
            base::test::SingleThreadTaskEnvironment::ThreadPoolExecutionMode::
                ASYNC,
            base::test::SingleThreadTaskEnvironment::TimeSource::MOCK_TIME) {}

  class MockDelayProvider : public BackoffDelayProvider {
   public:
    MockDelayProvider()
        : BackoffDelayProvider(kInitialBackoffRetryTime,
                               kInitialBackoffImmediateRetryTime) {}
    MOCK_METHOD(base::TimeDelta,
                GetDelay,
                (const base::TimeDelta&),
                (override));
  };

  void SetUp() override {
    delay_ = nullptr;
    extensions_activity_ = new ExtensionsActivity();

    connection_ = std::make_unique<MockConnectionManager>();
    connection_->SetServerReachable();

    data_type_registry_ = std::make_unique<DataTypeRegistry>(
        &mock_nudge_handler_, &cancelation_signal_, &encryption_handler_);
    data_type_registry_->ConnectDataType(
        HISTORY_DELETE_DIRECTIVES,
        MakeFakeActivationResponse(HISTORY_DELETE_DIRECTIVES));
    data_type_registry_->ConnectDataType(NIGORI,
                                         MakeFakeActivationResponse(NIGORI));
    data_type_registry_->ConnectDataType(THEMES,
                                         MakeFakeActivationResponse(THEMES));
    data_type_registry_->ConnectDataType(HISTORY,
                                         MakeFakeActivationResponse(HISTORY));

    context_ = std::make_unique<SyncCycleContext>(
        connection_.get(), extensions_activity_.get(),
        std::vector<SyncEngineEventListener*>(), nullptr,
        data_type_registry_.get(), "fake_cache_guid", "fake_birthday",
        "fake_bag_of_chips",
        /*poll_interval=*/base::Minutes(30));
    context_->set_notifications_enabled(true);
    context_->set_account_name("Test");
    RebuildScheduler();
  }

  void DisconnectDataType(DataType type) {
    data_type_registry_->DisconnectDataType(type);
  }

  void RebuildScheduler() {
    auto syncer = std::make_unique<testing::StrictMock<MockSyncer>>();
    // The syncer is destroyed with the scheduler that owns it.
    syncer_ = syncer.get();
    scheduler_ = std::make_unique<SyncSchedulerImpl>(
        "TestSyncScheduler", BackoffDelayProvider::FromDefaults(), context(),
        std::move(syncer), false);
    SetDefaultLocalChangeNudgeDelays();
  }

  SyncSchedulerImpl* scheduler() { return scheduler_.get(); }
  MockSyncer* syncer() { return syncer_; }
  MockDelayProvider* delay() { return delay_; }
  MockConnectionManager* connection() { return connection_.get(); }
  DataTypeRegistry* data_type_registry() { return data_type_registry_.get(); }
  base::TimeDelta default_delay() { return base::Seconds(0); }
  base::TimeDelta long_delay() { return base::Seconds(60); }
  base::TimeDelta timeout() { return TestTimeouts::action_timeout(); }

  void TearDown() override {
    PumpLoop();
    scheduler_.reset();
    PumpLoop();
  }

  void SetDefaultLocalChangeNudgeDelays() {
    for (DataType type : DataTypeSet::All()) {
      scheduler_->nudge_tracker_.SetLocalChangeDelayIgnoringMinForTest(
          type, default_delay());
    }
  }

  void AnalyzePollRun(const SyncShareTimes& times,
                      size_t min_num_samples,
                      const TimeTicks& optimal_start,
                      const base::TimeDelta& poll_interval) {
    EXPECT_GE(times.size(), min_num_samples);
    for (size_t i = 0; i < times.size(); i++) {
      SCOPED_TRACE(testing::Message() << "SyncShare # (" << i << ")");
      TimeTicks optimal_next_sync = optimal_start + poll_interval * i;
      EXPECT_GE(times[i], optimal_next_sync);
    }
  }

  void DoQuitLoopNow() { QuitLoopNow(); }

  void StartSyncConfiguration() {
    scheduler()->Start(SyncScheduler::CONFIGURATION_MODE, base::Time());
  }

  void StartSyncScheduler(base::Time last_poll_time) {
    scheduler()->Start(SyncScheduler::NORMAL_MODE, last_poll_time);
  }

  // This stops the scheduler synchronously.
  void StopSyncScheduler() {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&SyncSchedulerImplTest::DoQuitLoopNow,
                                  weak_ptr_factory_.GetWeakPtr()));
    RunLoop();
  }

  bool RunAndGetBackoff() {
    StartSyncScheduler(base::Time());

    scheduler()->ScheduleLocalNudge(THEMES);
    RunLoop();

    return scheduler()->IsGlobalBackoff();
  }

  void UseMockDelayProvider() {
    delay_ = new MockDelayProvider();
    scheduler_->delay_provider_.reset(delay_);
  }

  SyncCycleContext* context() { return context_.get(); }

  DataTypeSet GetThrottledTypes() {
    DataTypeSet throttled_types;
    DataTypeSet blocked_types = scheduler_->nudge_tracker_.GetBlockedTypes();
    for (DataType type : blocked_types) {
      if (scheduler_->nudge_tracker_.GetTypeBlockingMode(type) ==
          WaitInterval::BlockingMode::kThrottled) {
        throttled_types.Put(type);
      }
    }
    return throttled_types;
  }

  DataTypeSet GetBackedOffTypes() {
    DataTypeSet backed_off_types;
    DataTypeSet blocked_types = scheduler_->nudge_tracker_.GetBlockedTypes();
    for (DataType type : blocked_types) {
      if (scheduler_->nudge_tracker_.GetTypeBlockingMode(type) ==
          WaitInterval::BlockingMode::kExponentialBackoff) {
        backed_off_types.Put(type);
      }
    }
    return backed_off_types;
  }

  bool IsAnyTypeBlocked() {
    return scheduler_->nudge_tracker_.IsAnyTypeBlocked();
  }

  static std::unique_ptr<SyncInvalidation> BuildInvalidation(
      int64_t version,
      const std::string& payload) {
    return MockInvalidation::Build(version, payload);
  }

  base::TimeDelta GetTypeBlockingTime(DataType type) {
    NudgeTracker::TypeTrackerMap::const_iterator tracker_it =
        scheduler_->nudge_tracker_.type_trackers_.find(type);
    CHECK(tracker_it != scheduler_->nudge_tracker_.type_trackers_.end());
    DCHECK(tracker_it->second->wait_interval_);
    return tracker_it->second->wait_interval_->length;
  }

  void SetTypeBlockingMode(DataType type, WaitInterval::BlockingMode mode) {
    NudgeTracker::TypeTrackerMap::const_iterator tracker_it =
        scheduler_->nudge_tracker_.type_trackers_.find(type);
    CHECK(tracker_it != scheduler_->nudge_tracker_.type_trackers_.end());
    DCHECK(tracker_it->second->wait_interval_);
    tracker_it->second->wait_interval_->mode = mode;
  }

  void NewSchedulerForLocalBackend() {
    auto syncer = std::make_unique<testing::StrictMock<MockSyncer>>();
    // The syncer is destroyed with the scheduler that owns it.
    syncer_ = syncer.get();
    scheduler_ = std::make_unique<SyncSchedulerImpl>(
        "TestSyncScheduler", BackoffDelayProvider::FromDefaults(), context(),
        std::move(syncer), true);
    SetDefaultLocalChangeNudgeDelays();
  }

  bool BlockTimerIsRunning() const {
    return scheduler_->pending_wakeup_timer_.IsRunning();
  }

  base::TimeDelta GetPendingWakeupTimerDelay() {
    EXPECT_TRUE(scheduler_->pending_wakeup_timer_.IsRunning());
    return scheduler_->pending_wakeup_timer_.GetCurrentDelay();
  }

 protected:
  base::test::SingleThreadTaskEnvironment task_environment_;

 private:
  static const base::TickClock* tick_clock_;
  static base::TimeTicks GetMockTimeTicks() {
    if (!tick_clock_) {
      return base::TimeTicks();
    }
    return tick_clock_->NowTicks();
  }

  FakeSyncEncryptionHandler encryption_handler_;
  CancelationSignal cancelation_signal_;
  std::unique_ptr<MockConnectionManager> connection_;
  std::unique_ptr<DataTypeRegistry> data_type_registry_;
  std::unique_ptr<SyncCycleContext> context_;
  std::unique_ptr<SyncSchedulerImpl> scheduler_;
  MockNudgeHandler mock_nudge_handler_;
  raw_ptr<MockSyncer, DanglingUntriaged> syncer_ = nullptr;
  raw_ptr<MockDelayProvider, DanglingUntriaged> delay_ = nullptr;
  scoped_refptr<ExtensionsActivity> extensions_activity_;
  base::WeakPtrFactory<SyncSchedulerImplTest> weak_ptr_factory_{this};
};

const base::TickClock* SyncSchedulerImplTest::tick_clock_ = nullptr;

void RecordSyncShareImpl(SyncShareTimes* times) {
  times->push_back(TimeTicks::Now());
}

ACTION_P2(RecordSyncShare, times, success) {
  RecordSyncShareImpl(times);
  if (base::RunLoop::IsRunningOnCurrentThread()) {
    QuitLoopNow();
  }
  return success;
}

ACTION_P3(RecordSyncShareMultiple, times, quit_after, success) {
  RecordSyncShareImpl(times);
  EXPECT_LE(times->size(), quit_after);
  if (times->size() >= quit_after &&
      base::RunLoop::IsRunningOnCurrentThread()) {
    QuitLoopNow();
  }
  return success;
}

ACTION_P(StopScheduler, scheduler) {
  scheduler->Stop();
}

ACTION(AddFailureAndQuitLoopNow) {
  ADD_FAILURE();
  QuitLoopNow();
  return true;
}

ACTION_P(QuitLoopNowAction, success) {
  QuitLoopNow();
  return success;
}

// Test nudge scheduling.
TEST_F(SyncSchedulerImplTest, Nudge) {
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());

  scheduler()->ScheduleLocalNudge(THEMES);
  RunLoop();

  Mock::VerifyAndClearExpectations(syncer());

  // Make sure a second, later, nudge is unaffected by first (no coalescing).
  SyncShareTimes times2;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times2, true)));
  scheduler()->ScheduleLocalNudge(HISTORY);
  RunLoop();
}

TEST_F(SyncSchedulerImplTest, NudgeForDisabledType) {
  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(HISTORY_DELETE_DIRECTIVES);

  // The user enables a custom passphrase at this point, so
  // HISTORY_DELETE_DIRECTIVES gets disabled.
  DisconnectDataType(HISTORY_DELETE_DIRECTIVES);
  ASSERT_FALSE(context()->GetConnectedTypes().Has(HISTORY_DELETE_DIRECTIVES));

  // There should be no sync cycle.
  EXPECT_CALL(*syncer(), NormalSyncShare).Times(0);
  PumpLoop();
}

// Make sure a regular config command is scheduled fine in the absence of any
// errors.
TEST_F(SyncSchedulerImplTest, Config) {
  SyncShareTimes times;

  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureSuccess),
                      RecordSyncShare(&times, true)));

  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(1);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  PumpLoop();
}

// Simulate a failure and make sure the config request is retried.
TEST_F(SyncSchedulerImplTest, ConfigWithBackingOff) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay)
      .WillRepeatedly(Return(base::Milliseconds(20)));

  StartSyncConfiguration();

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureFailed),
                      RecordSyncShare(&times, false)))
      .WillOnce(DoAll(Invoke(SimulateConfigureFailed),
                      RecordSyncShare(&times, false)));

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(1);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  RunLoop();

  // RunLoop() will trigger a sync cycle job which will retry configuration.
  // Since ready_task was already called it shouldn't be called again.
  RunLoop();

  Mock::VerifyAndClearExpectations(syncer());

  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureSuccess),
                      RecordSyncShare(&times, true)));
  RunLoop();
}

// Simuilate SyncSchedulerImpl::Stop being called in the middle of Configure.
// This can happen if server returns NOT_MY_BIRTHDAY.
TEST_F(SyncSchedulerImplTest, ConfigWithStop) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay)
      .WillRepeatedly(Return(base::Milliseconds(20)));

  StartSyncConfiguration();

  // Make ConfigureSyncShare call scheduler->Stop(). It is not supposed to call
  // retry_task or dereference configuration params.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureFailed),
                      StopScheduler(scheduler()),
                      RecordSyncShare(&times, false)));

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  PumpLoop();
}

// Verify that in the absence of valid access token the command will fail.
TEST_F(SyncSchedulerImplTest, ConfigNoAccessToken) {
  connection()->ResetAccessToken();

  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  PumpLoop();
}

// Verify that in the absence of valid access token the command will pass if
// local sync backend is used.
TEST_F(SyncSchedulerImplTest, ConfigNoAccessTokenLocalSync) {
  NewSchedulerForLocalBackend();
  connection()->ResetAccessToken();

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureSuccess),
                      RecordSyncShare(&times, true)));

  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(1);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  PumpLoop();
}

// Issue a nudge when the config has failed. Make sure both the config and
// nudge are executed.
TEST_F(SyncSchedulerImplTest, NudgeWithConfigWithBackingOff) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay)
      .WillRepeatedly(Return(base::Milliseconds(50)));

  StartSyncConfiguration();

  // Request a configure and make sure it fails.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureFailed),
                      RecordSyncShare(&times, false)));
  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  const DataType data_type = THEMES;
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {data_type}, ready_task.Get());
  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());
  Mock::VerifyAndClearExpectations(&ready_task);

  // Ask for a nudge while dealing with repeated configure failure.
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureFailed),
                      RecordSyncShare(&times, false)));
  scheduler()->ScheduleLocalNudge(data_type);
  RunLoop();
  // Note that we're not RunLoop()ing for the NUDGE we just scheduled, but
  // for the first retry attempt from the config job (after
  // waiting ~+/- 50ms).
  Mock::VerifyAndClearExpectations(syncer());

  // Let the next configure retry succeed.
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureSuccess),
                      RecordSyncShare(&times, true)));
  RunLoop();

  // Now change the mode so nudge can execute.
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  StartSyncScheduler(base::Time());
  PumpLoop();
}

// Test that nudges are coalesced.
TEST_F(SyncSchedulerImplTest, NudgeCoalescing) {
  StartSyncScheduler(base::Time());

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  TimeTicks optimal_time = TimeTicks::Now() + default_delay();
  scheduler()->ScheduleLocalNudge(THEMES);
  scheduler()->ScheduleLocalNudge(HISTORY);
  RunLoop();

  ASSERT_EQ(1U, times.size());
  EXPECT_GE(times[0], optimal_time);

  Mock::VerifyAndClearExpectations(syncer());

  SyncShareTimes times2;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times2, true)));
  scheduler()->ScheduleLocalNudge(THEMES);
  RunLoop();
}

// Test that nudges are coalesced.
TEST_F(SyncSchedulerImplTest, NudgeCoalescingWithDifferentTimings) {
  StartSyncScheduler(base::Time());

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));

  // Create a huge time delay.
  base::TimeDelta delay = base::Days(1);

  std::map<DataType, base::TimeDelta> delay_map;
  delay_map[THEMES] = delay;
  scheduler()->OnReceivedCustomNudgeDelays(delay_map);
  scheduler()->ScheduleLocalNudge(THEMES);
  scheduler()->ScheduleLocalNudge(HISTORY);

  TimeTicks min_time = TimeTicks::Now();
  TimeTicks max_time = TimeTicks::Now() + delay;

  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());

  // Make sure the sync happened at the right time.
  ASSERT_EQ(1U, times.size());
  EXPECT_GE(times[0], min_time);
  EXPECT_LE(times[0], max_time);
}

// Test nudge scheduling.
TEST_F(SyncSchedulerImplTest, NudgeWithStates) {
  StartSyncScheduler(base::Time());

  SyncShareTimes times1;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times1, true)))
      .RetiresOnSaturation();
  scheduler()->SetHasPendingInvalidations(THEMES, true);
  scheduler()->ScheduleInvalidationNudge(THEMES);
  RunLoop();

  Mock::VerifyAndClearExpectations(syncer());

  // Make sure a second, later, nudge is unaffected by first (no coalescing).
  SyncShareTimes times2;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times2, true)));
  scheduler()->SetHasPendingInvalidations(HISTORY, true);
  scheduler()->ScheduleInvalidationNudge(HISTORY);
  RunLoop();
}

// Test that polling works as expected.
TEST_F(SyncSchedulerImplTest, Polling) {
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .Times(AtLeast(kMinNumSamples))
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));

  base::TimeDelta poll_interval(base::Milliseconds(30));
  scheduler()->OnReceivedPollIntervalUpdate(poll_interval);

  TimeTicks optimal_start = TimeTicks::Now() + poll_interval;
  StartSyncScheduler(base::Time());

  // Run again to wait for polling.
  RunLoop();

  StopSyncScheduler();
  AnalyzePollRun(times, kMinNumSamples, optimal_start, poll_interval);
}

TEST_F(SyncSchedulerImplTest, ShouldPollOnBrowserStartup) {
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillOnce(DoAll(Invoke(SimulatePollSuccess), Return(true)));

  // The last polling request happened longer ago than the polling period.
  StartSyncScheduler(/*last_poll_time=*/base::Time::Now() - base::Hours(24));

  // Waits for all the scheduled tasks to finish. If the poll request would be
  // delayed, PollSyncShare() wouldn't be called because it requires posting
  // another task (see SyncSchedulerImpl::TrySyncCycleJob).
  StopSyncScheduler();
}

// Test that polling gets the intervals from the provided context.
TEST_F(SyncSchedulerImplTest, ShouldUseInitialPollIntervalFromContext) {
  base::TimeDelta poll_interval(base::Milliseconds(30));
  context()->set_poll_interval(poll_interval);
  RebuildScheduler();

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .Times(AtLeast(kMinNumSamples))
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));

  TimeTicks optimal_start = TimeTicks::Now() + poll_interval;
  StartSyncScheduler(base::Time());

  // Run again to wait for polling.
  RunLoop();

  StopSyncScheduler();
  AnalyzePollRun(times, kMinNumSamples, optimal_start, poll_interval);
}

// Test that we reuse the previous poll time on startup, triggering the first
// poll based on when the last one happened. Subsequent polls should have the
// normal delay.
TEST_F(SyncSchedulerImplTest, PollingPersistence) {
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .Times(AtLeast(kMinNumSamples))
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));

  // Use a large poll interval that wouldn't normally get hit on its own for
  // some time yet.
  base::TimeDelta poll_interval(base::Milliseconds(500));
  scheduler()->OnReceivedPollIntervalUpdate(poll_interval);

  // Set the start time to now, as the poll was overdue.
  TimeTicks optimal_start = TimeTicks::Now();
  StartSyncScheduler(base::Time::Now() - poll_interval);

  // Run again to wait for polling.
  RunLoop();

  StopSyncScheduler();
  AnalyzePollRun(times, kMinNumSamples, optimal_start, poll_interval);
}

// Test that if the persisted poll is in the future, it's ignored (the case
// where the local time has been modified).
TEST_F(SyncSchedulerImplTest, PollingPersistenceBadClock) {
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .Times(AtLeast(kMinNumSamples))
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));

  base::TimeDelta poll_interval(base::Milliseconds(30));
  scheduler()->OnReceivedPollIntervalUpdate(poll_interval);

  // Set the start time to `poll_interval` in the future.
  TimeTicks optimal_start = TimeTicks::Now() + poll_interval;
  StartSyncScheduler(base::Time::Now() + base::Minutes(10));

  // Run again to wait for polling.
  RunLoop();

  StopSyncScheduler();
  AnalyzePollRun(times, kMinNumSamples, optimal_start, poll_interval);
}

// Test that polling intervals are updated when needed.
TEST_F(SyncSchedulerImplTest, PollIntervalUpdate) {
  SyncShareTimes times;
  base::TimeDelta poll1(base::Milliseconds(120));
  base::TimeDelta poll2(base::Milliseconds(30));
  scheduler()->OnReceivedPollIntervalUpdate(poll1);
  EXPECT_CALL(*syncer(), PollSyncShare)
      .Times(AtLeast(kMinNumSamples))
      .WillOnce(DoAll(WithArgs<0, 1>(SimulatePollIntervalUpdate(poll2)),
                      Return(true)))
      .WillRepeatedly(DoAll(
          Invoke(SimulatePollSuccess),
          WithArg<1>(RecordSyncShareMultiple(&times, kMinNumSamples, true))));

  TimeTicks optimal_start = TimeTicks::Now() + poll1 + poll2;
  StartSyncScheduler(base::Time());

  // Run again to wait for polling.
  RunLoop();

  StopSyncScheduler();
  AnalyzePollRun(times, kMinNumSamples, optimal_start, poll2);
}

// Test that no syncing occurs when throttled.
TEST_F(SyncSchedulerImplTest, ThrottlingDoesThrottle) {
  base::TimeDelta poll(base::Milliseconds(20));
  base::TimeDelta throttle(base::Minutes(10));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulateThrottled(throttle)), Return(false)))
      .WillRepeatedly(AddFailureAndQuitLoopNow());

  StartSyncScheduler(base::Time());

  const DataType type = THEMES;
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();

  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {type}, ready_task.Get());
  PumpLoop();
}

TEST_F(SyncSchedulerImplTest, ThrottlingExpiresFromPoll) {
  base::TimeDelta poll(base::Milliseconds(15));
  base::TimeDelta throttle1(base::Milliseconds(150));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillOnce(DoAll(WithArg<1>(SimulateThrottled(throttle1)), Return(false)))
      .RetiresOnSaturation();
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));

  TimeTicks optimal_start = TimeTicks::Now() + poll + throttle1;
  StartSyncScheduler(base::Time());

  // Run again to wait for polling.
  RunLoop();

  StopSyncScheduler();
  AnalyzePollRun(times, kMinNumSamples, optimal_start, poll);
}

TEST_F(SyncSchedulerImplTest, ThrottlingExpiresFromNudge) {
  base::TimeDelta poll(base::Days(1));
  base::TimeDelta throttle1(base::Milliseconds(150));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulateThrottled(throttle1)), Return(false)))
      .RetiresOnSaturation();
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateNormalSuccess), QuitLoopNowAction(true)));

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(THEMES);

  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(scheduler()->IsGlobalThrottle());
  RunLoop();
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, ThrottlingExpiresFromConfigure) {
  scheduler()->OnReceivedPollIntervalUpdate(base::Days(1));

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulateThrottled(base::Milliseconds(150))),
                      Return(false)))
      .RetiresOnSaturation();
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateConfigureSuccess), QuitLoopNowAction(true)));

  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  PumpLoop();
  Mock::VerifyAndClearExpectations(&ready_task);
  EXPECT_TRUE(scheduler()->IsGlobalThrottle());

  RunLoop();
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeThrottlingBlocksNudge) {
  base::TimeDelta poll(base::Days(1));
  base::TimeDelta throttle1(base::Seconds(60));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulateTypeThrottled(type, throttle1)),
                      Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetThrottledTypes().Has(type));
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // This won't cause a sync cycle because the types are throttled.
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeBackingOffBlocksNudge) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(long_delay()));

  base::TimeDelta poll(base::Days(1));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(type)), Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // This won't cause a sync cycle because the types are backed off.
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeBackingOffWillExpire) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(default_delay()));

  base::TimeDelta poll(base::Days(1));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(type)), Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_FALSE(IsAnyTypeBlocked());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeBackingOffAndThrottling) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(long_delay()));

  base::TimeDelta poll(base::Days(1));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(type)), Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  base::TimeDelta throttle1(base::Milliseconds(150));

  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulateThrottled(throttle1)), Return(false)))
      .RetiresOnSaturation();

  // Sync still can throttle.
  scheduler()->ScheduleLocalNudge(HISTORY);
  PumpLoop();  // TO get TypesUnblock called.
  PumpLoop();  // To get TrySyncCycleJob called.

  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_TRUE(scheduler()->IsGlobalThrottle());

  // Unthrottled client, but the backingoff datatype is still in backoff and
  // scheduled.
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateNormalSuccess), QuitLoopNowAction(true)));
  RunLoop();
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_TRUE(BlockTimerIsRunning());

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeThrottlingBackingOffBlocksNudge) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(long_delay()));

  base::TimeDelta poll(base::Days(1));
  base::TimeDelta throttle(base::Seconds(60));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType throttled_type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(WithArg<2>(SimulateTypeThrottled(throttled_type, throttle)),
                Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(throttled_type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called

  const DataType backed_off_type = HISTORY;

  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(backed_off_type)),
                      Return(true)))
      .RetiresOnSaturation();

  scheduler()->ScheduleLocalNudge(backed_off_type);

  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called

  EXPECT_TRUE(GetThrottledTypes().Has(throttled_type));
  EXPECT_TRUE(GetBackedOffTypes().Has(backed_off_type));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // Neither of these will cause a sync cycle because the types are throttled or
  // backed off.
  scheduler()->ScheduleLocalNudge(throttled_type);
  PumpLoop();
  scheduler()->ScheduleLocalNudge(backed_off_type);
  PumpLoop();

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeThrottlingDoesBlockOtherSources) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(default_delay()));

  base::TimeDelta poll(base::Days(1));
  base::TimeDelta throttle1(base::Seconds(60));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType throttled_type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(WithArg<2>(SimulateTypeThrottled(throttled_type, throttle1)),
                Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(throttled_type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetThrottledTypes().Has(throttled_type));
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // Ignore invalidations for throttled types.
  scheduler()->ScheduleInvalidationNudge(throttled_type);
  PumpLoop();

  // Ignore refresh requests for throttled types.
  scheduler()->ScheduleLocalRefreshRequest({throttled_type});
  PumpLoop();

  Mock::VerifyAndClearExpectations(syncer());

  // Local nudges for non-throttled types will trigger a sync.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  scheduler()->ScheduleLocalNudge(PREFERENCES);
  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, TypeBackingOffDoesBlockOtherSources) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(long_delay()));

  base::TimeDelta poll(base::Days(1));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  const DataType backed_off_type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(backed_off_type)),
                      Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(backed_off_type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(backed_off_type));
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // Ignore invalidations for backed off types.
  scheduler()->ScheduleInvalidationNudge(backed_off_type);
  PumpLoop();

  // Ignore refresh requests for backed off types.
  scheduler()->ScheduleLocalRefreshRequest({backed_off_type});
  PumpLoop();

  Mock::VerifyAndClearExpectations(syncer());

  // Local nudges for non-backed off types will trigger a sync.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  scheduler()->ScheduleLocalNudge(PREFERENCES);
  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());

  StopSyncScheduler();
}

// Test nudges / polls don't run in config mode and config tasks do.
TEST_F(SyncSchedulerImplTest, ConfigurationMode) {
  scheduler()->OnReceivedPollIntervalUpdate(base::Milliseconds(15));

  StartSyncConfiguration();

  scheduler()->ScheduleLocalNudge(HISTORY);
  scheduler()->ScheduleLocalNudge(HISTORY);

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConfigureSuccess),
                      RecordSyncShare(&times, true)))
      .RetiresOnSaturation();
  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(1);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  RunLoop();

  Mock::VerifyAndClearExpectations(syncer());

  // Switch to NORMAL_MODE to ensure NUDGES were properly saved and run.
  scheduler()->OnReceivedPollIntervalUpdate(base::Days(1));
  SyncShareTimes times2;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times2, true)));

  StartSyncScheduler(base::Time());

  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());
}

class BackoffTriggersSyncSchedulerImplTest : public SyncSchedulerImplTest {
  void SetUp() override {
    SyncSchedulerImplTest::SetUp();
    UseMockDelayProvider();
    EXPECT_CALL(*delay(), GetDelay)
        .WillRepeatedly(Return(base::Milliseconds(10)));
  }

  void TearDown() override {
    StopSyncScheduler();
    SyncSchedulerImplTest::TearDown();
  }
};

// Have the syncer fail during commit.  Expect that the scheduler enters
// backoff.
TEST_F(BackoffTriggersSyncSchedulerImplTest, FailCommitOnce) {
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateCommitFailed), QuitLoopNowAction(false)));
  EXPECT_TRUE(RunAndGetBackoff());
}

// Have the syncer fail during download updates and succeed on the first
// retry.  Expect that this clears the backoff state.
TEST_F(BackoffTriggersSyncSchedulerImplTest, FailDownloadOnceThenSucceed) {
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateDownloadUpdatesFailed), Return(false)))
      .WillOnce(DoAll(Invoke(SimulateNormalSuccess), QuitLoopNowAction(true)));
  EXPECT_FALSE(RunAndGetBackoff());
}

// Have the syncer fail during commit and succeed on the first retry.  Expect
// that this clears the backoff state.
TEST_F(BackoffTriggersSyncSchedulerImplTest, FailCommitOnceThenSucceed) {
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateCommitFailed), Return(false)))
      .WillOnce(DoAll(Invoke(SimulateNormalSuccess), QuitLoopNowAction(true)));
  EXPECT_FALSE(RunAndGetBackoff());
}

// Have the syncer fail to download updates and fail again on the retry.
// Expect this will leave the scheduler in backoff.
TEST_F(BackoffTriggersSyncSchedulerImplTest, FailDownloadTwice) {
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateDownloadUpdatesFailed), Return(false)))
      .WillRepeatedly(DoAll(Invoke(SimulateDownloadUpdatesFailed),
                            QuitLoopNowAction(false)));
  EXPECT_TRUE(RunAndGetBackoff());
}

// Have the syncer fail to get the encryption key yet succeed in downloading
// updates. Expect this will leave the scheduler in backoff.
TEST_F(BackoffTriggersSyncSchedulerImplTest, FailGetEncryptionKey) {
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillOnce(DoAll(Invoke(SimulateGetEncryptionKeyFailed), Return(false)))
      .WillRepeatedly(DoAll(Invoke(SimulateGetEncryptionKeyFailed),
                            QuitLoopNowAction(false)));
  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, ready_task.Get());
  RunLoop();

  EXPECT_TRUE(scheduler()->IsGlobalBackoff());
}

// Test that no polls or extraneous nudges occur when in backoff.
TEST_F(SyncSchedulerImplTest, BackoffDropsJobs) {
  base::TimeDelta poll(base::Milliseconds(10));
  scheduler()->OnReceivedPollIntervalUpdate(poll);
  UseMockDelayProvider();

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateCommitFailed),
                      RecordSyncShareMultiple(&times, 1U, false)));
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(base::Days(1)));

  StartSyncScheduler(base::Time());

  // This nudge should fail and put us into backoff.  Thanks to our mock
  // GetDelay() setup above, this will be a long backoff.
  const DataType type = THEMES;
  scheduler()->ScheduleLocalNudge(type);
  RunLoop();

  // From this point forward, no SyncShare functions should be invoked.
  Mock::VerifyAndClearExpectations(syncer());

  // Wait a while (10x poll interval) so a few poll jobs will be attempted.
  task_environment_.FastForwardBy(poll * 10);

  // Try (and fail) to schedule a nudge.
  scheduler()->ScheduleLocalNudge(type);

  Mock::VerifyAndClearExpectations(syncer());
  Mock::VerifyAndClearExpectations(delay());

  EXPECT_CALL(*delay(), GetDelay).Times(0);

  StartSyncConfiguration();

  base::MockOnceClosure ready_task;
  EXPECT_CALL(ready_task, Run).Times(0);
  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {type}, ready_task.Get());
  PumpLoop();
}

// Test that backoff is shaping traffic properly with consecutive errors.
TEST_F(SyncSchedulerImplTest, BackoffElevation) {
  UseMockDelayProvider();

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .Times(kMinNumSamples)
      .WillRepeatedly(
          DoAll(Invoke(SimulateCommitFailed),
                RecordSyncShareMultiple(&times, kMinNumSamples, false)));

  const base::TimeDelta first = kInitialBackoffRetryTime;
  const base::TimeDelta second = base::Milliseconds(20);
  const base::TimeDelta third = base::Milliseconds(30);
  const base::TimeDelta fourth = base::Milliseconds(40);
  const base::TimeDelta fifth = base::Milliseconds(50);
  const base::TimeDelta sixth = base::Days(1);

  EXPECT_CALL(*delay(), GetDelay(first))
      .WillOnce(Return(second))
      .RetiresOnSaturation();
  EXPECT_CALL(*delay(), GetDelay(second))
      .WillOnce(Return(third))
      .RetiresOnSaturation();
  EXPECT_CALL(*delay(), GetDelay(third))
      .WillOnce(Return(fourth))
      .RetiresOnSaturation();
  EXPECT_CALL(*delay(), GetDelay(fourth))
      .WillOnce(Return(fifth))
      .RetiresOnSaturation();
  EXPECT_CALL(*delay(), GetDelay(fifth)).WillOnce(Return(sixth));

  StartSyncScheduler(base::Time());

  // Run again with a nudge.
  scheduler()->ScheduleLocalNudge(THEMES);
  RunLoop();

  ASSERT_EQ(kMinNumSamples, times.size());
  EXPECT_GE(times[1] - times[0], second);
  EXPECT_GE(times[2] - times[1], third);
  EXPECT_GE(times[3] - times[2], fourth);
  EXPECT_GE(times[4] - times[3], fifth);
}

// Test that things go back to normal once a retry makes forward progress.
TEST_F(SyncSchedulerImplTest, BackoffRelief) {
  UseMockDelayProvider();

  const base::TimeDelta backoff = base::Milliseconds(10);
  EXPECT_CALL(*delay(), GetDelay).WillOnce(Return(backoff));

  // Optimal start for the post-backoff poll party.
  TimeTicks optimal_start = TimeTicks::Now();
  StartSyncScheduler(base::Time());

  // Kick off the test with a failed nudge.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateCommitFailed), RecordSyncShare(&times, false)));
  scheduler()->ScheduleLocalNudge(THEMES);
  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());
  TimeTicks optimal_job_time = optimal_start;
  ASSERT_EQ(1U, times.size());
  EXPECT_GE(times[0], optimal_job_time);

  // The retry succeeds.
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());
  optimal_job_time = optimal_job_time + backoff;
  ASSERT_EQ(2U, times.size());
  EXPECT_GE(times[1], optimal_job_time);

  // Now let the Poll timer do its thing.
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));
  const base::TimeDelta poll(base::Milliseconds(10));
  scheduler()->OnReceivedPollIntervalUpdate(poll);

  // The new optimal time is now, since the desired poll should have happened
  // in the past.
  optimal_job_time = TimeTicks::Now();
  RunLoop();
  Mock::VerifyAndClearExpectations(syncer());
  ASSERT_EQ(kMinNumSamples, times.size());
  for (size_t i = 2; i < times.size(); i++) {
    SCOPED_TRACE(testing::Message() << "SyncShare # (" << i << ")");
    EXPECT_GE(times[i], optimal_job_time);
    optimal_job_time = optimal_job_time + poll;
  }

  StopSyncScheduler();
}

// Test that poll failures are treated like any other failure. They should
// result in retry with backoff.
TEST_F(SyncSchedulerImplTest, TransientPollFailure) {
  scheduler()->OnReceivedPollIntervalUpdate(base::Milliseconds(10));
  UseMockDelayProvider();  // Will cause test failure if backoff is initiated.
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(base::Milliseconds(0)));

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulatePollFailed), RecordSyncShare(&times, false)))
      .WillOnce(
          DoAll(Invoke(SimulatePollSuccess), RecordSyncShare(&times, true)));

  StartSyncScheduler(base::Time());

  // Run the unsuccessful poll. The failed poll should not trigger backoff.
  RunLoop();
  EXPECT_TRUE(scheduler()->IsGlobalBackoff());

  // Run the successful poll.
  RunLoop();
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
}

// Test that starting the syncer thread without a valid connection doesn't
// break things when a connection is detected.
TEST_F(SyncSchedulerImplTest, StartWhenNotConnected) {
  connection()->SetServerNotReachable();
  connection()->UpdateConnectionStatus();
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConnectionFailure), Return(false)))
      .WillOnce(DoAll(Invoke(SimulateNormalSuccess), Return(true)));
  StartSyncScheduler(base::Time());

  scheduler()->ScheduleLocalNudge(THEMES);
  // Should save the nudge for until after the server is reachable.
  base::RunLoop().RunUntilIdle();

  scheduler()->OnConnectionStatusChange(
      network::mojom::ConnectionType::CONNECTION_WIFI);
  connection()->SetServerReachable();
  connection()->UpdateConnectionStatus();
  base::RunLoop().RunUntilIdle();
}

// Test that when disconnect signal (CONNECTION_NONE) is received, normal sync
// share is not called.
TEST_F(SyncSchedulerImplTest, SyncShareNotCalledWhenDisconnected) {
  // Set server unavailable, so SyncSchedulerImpl will try to fix connection
  // error upon OnConnectionStatusChange().
  connection()->SetServerNotReachable();
  connection()->UpdateConnectionStatus();
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .Times(1)
      .WillOnce(DoAll(Invoke(SimulateConnectionFailure), Return(false)));
  StartSyncScheduler(base::Time());

  scheduler()->ScheduleLocalNudge(THEMES);
  // The nudge fails because of the connection failure.
  base::RunLoop().RunUntilIdle();

  // Simulate a disconnect signal. The scheduler should not retry the previously
  // failed nudge.
  scheduler()->OnConnectionStatusChange(
      network::mojom::ConnectionType::CONNECTION_NONE);
  base::RunLoop().RunUntilIdle();
}

TEST_F(SyncSchedulerImplTest, ServerConnectionChangeDuringBackoff) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(base::Milliseconds(0)));

  StartSyncScheduler(base::Time());
  connection()->SetServerNotReachable();
  connection()->UpdateConnectionStatus();

  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(Invoke(SimulateConnectionFailure), Return(false)))
      .WillOnce(DoAll(Invoke(SimulateNormalSuccess), Return(true)));

  scheduler()->ScheduleLocalNudge(THEMES);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // Run the nudge, that will fail and schedule a quick retry.
  ASSERT_TRUE(scheduler()->IsGlobalBackoff());

  // Before we run the scheduled retry, trigger a server connection change.
  scheduler()->OnConnectionStatusChange(
      network::mojom::ConnectionType::CONNECTION_WIFI);
  connection()->SetServerReachable();
  connection()->UpdateConnectionStatus();
  base::RunLoop().RunUntilIdle();
}

// Tests that there's no crash trying to run two jobs at once if the scheduler
// received extra connection status change notifications.  See crbug.com/190085.
TEST_F(SyncSchedulerImplTest, DoubleConnectionChangeDuringConfigure) {
  EXPECT_CALL(*syncer(), ConfigureSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulateConfigureConnectionFailure), Return(true)));
  StartSyncConfiguration();
  connection()->SetServerNotReachable();
  connection()->UpdateConnectionStatus();

  scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION,
                                     {THEMES}, base::DoNothing());

  scheduler()->OnConnectionStatusChange(
      network::mojom::ConnectionType::CONNECTION_WIFI);
  scheduler()->OnConnectionStatusChange(
      network::mojom::ConnectionType::CONNECTION_WIFI);

  PumpLoop();  // Run the nudge, that will fail and schedule a quick retry.
}

TEST_F(SyncSchedulerImplTest, PollAfterAuthError) {
  scheduler()->OnReceivedPollIntervalUpdate(base::Milliseconds(15));

  SyncShareTimes times;
  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulatePollSuccess),
                RecordSyncShareMultiple(&times, kMinNumSamples, true)));

  connection()->SetServerResponse(
      HttpResponse::ForHttpStatusCode(net::HTTP_UNAUTHORIZED));
  StartSyncScheduler(base::Time());

  // Run to wait for polling.
  RunLoop();

  // Normally OnCredentialsUpdated runs a non-poll job, but after a poll
  // finished with an auth error, it should retry polling once more.
  EXPECT_CALL(*syncer(), PollSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulatePollSuccess), RecordSyncShare(&times, true)));
  scheduler()->OnCredentialsUpdated();
  connection()->SetServerResponse(HttpResponse::ForSuccessForTest());
  RunLoop();
  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, PartialFailureWillExponentialBackoff) {
  scheduler()->OnReceivedPollIntervalUpdate(base::Days(1));

  const DataType type = THEMES;

  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillRepeatedly(
          DoAll(WithArg<2>(SimulatePartialFailure(type)), Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());
  base::TimeDelta first_blocking_time = GetTypeBlockingTime(THEMES);

  SetTypeBlockingMode(THEMES,
                      WaitInterval::BlockingMode::kExponentialBackoffRetrying);
  // This won't cause a sync cycle because the types are backed off.
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();
  PumpLoop();
  base::TimeDelta second_blocking_time = GetTypeBlockingTime(THEMES);

  // The Exponential backoff should be between previous backoff 1.5 and 2.5
  // times.
  EXPECT_LE(first_blocking_time * 1.5, second_blocking_time);
  EXPECT_GE(first_blocking_time * 2.5, second_blocking_time);

  StopSyncScheduler();
}

// If a datatype is in backoff or throttling, pending_wakeup_timer_ should
// schedule a delay job for OnTypesUnblocked. SyncScheduler sometimes use
// pending_wakeup_timer_ to schdule PerformDelayedNudge job before
// OnTypesUnblocked got run. This test will verify after ran
// PerformDelayedNudge, OnTypesUnblocked will be rescheduled if any datatype is
// in backoff or throttling.
TEST_F(SyncSchedulerImplTest, TypeBackoffAndSuccessfulSync) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(long_delay()));

  scheduler()->OnReceivedPollIntervalUpdate(base::Days(1));

  const DataType type = THEMES;

  // Set backoff datatype.
  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(type)), Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)))
      .RetiresOnSaturation();

  // Do a successful Sync.
  scheduler()->ScheduleLocalNudge(HISTORY);
  PumpLoop();  // TO get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called.

  // Timer is still running for backoff datatype after Sync success.
  EXPECT_TRUE(GetBackedOffTypes().Has(type));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  StopSyncScheduler();
}

// Verify that the timer is scheduled for an unblock job after one datatype is
// unblocked, and there is another one still blocked.
TEST_F(SyncSchedulerImplTest, TypeBackingOffAndFailureSync) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay)
      .WillOnce(Return(long_delay()))
      .RetiresOnSaturation();

  scheduler()->OnReceivedPollIntervalUpdate(base::Days(1));

  // Set a backoff datatype.
  const DataType backed_off_type = THEMES;
  ::testing::InSequence seq;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(backed_off_type)),
                      Return(true)))
      .RetiresOnSaturation();

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(backed_off_type);
  PumpLoop();  // To get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called
  EXPECT_TRUE(GetBackedOffTypes().Has(backed_off_type));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // Set anther backoff datatype.
  const DataType backed_off_type2 = HISTORY;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(DoAll(WithArg<2>(SimulatePartialFailure(backed_off_type2)),
                      Return(true)))
      .RetiresOnSaturation();
  EXPECT_CALL(*delay(), GetDelay)
      .WillOnce(Return(default_delay()))
      .RetiresOnSaturation();

  scheduler()->ScheduleLocalNudge(backed_off_type2);
  PumpLoop();  // TO get PerformDelayedNudge called.
  PumpLoop();  // To get TrySyncCycleJob called.

  EXPECT_TRUE(GetBackedOffTypes().Has(backed_off_type));
  EXPECT_TRUE(GetBackedOffTypes().Has(backed_off_type2));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  // Unblock one datatype.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillRepeatedly(
          DoAll(Invoke(SimulateNormalSuccess), RecordSyncShare(&times, true)));
  EXPECT_CALL(*delay(), GetDelay).WillRepeatedly(Return(long_delay()));

  PumpLoop();  // TO get OnTypesUnblocked called.
  PumpLoop();  // To get TrySyncCycleJob called.

  // Timer is still scheduled for another backoff datatype.
  EXPECT_TRUE(GetBackedOffTypes().Has(backed_off_type));
  EXPECT_FALSE(GetBackedOffTypes().Has(backed_off_type2));
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());
  EXPECT_FALSE(scheduler()->IsGlobalThrottle());

  StopSyncScheduler();
}

TEST_F(SyncSchedulerImplTest, InterleavedNudgesStillRestart) {
  UseMockDelayProvider();
  EXPECT_CALL(*delay(), GetDelay)
      .WillOnce(Return(long_delay()))
      .RetiresOnSaturation();
  scheduler()->OnReceivedPollIntervalUpdate(base::Days(1));

  StartSyncScheduler(base::Time());
  scheduler()->ScheduleLocalNudge(THEMES);
  PumpLoop();  // To get PerformDelayedNudge called.
  EXPECT_FALSE(BlockTimerIsRunning());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());

  // This is the tricky piece. We have a gap while the sync job is bouncing to
  // get onto the `pending_wakeup_timer_`, should be scheduled with no delay.
  scheduler()->ScheduleLocalNudge(HISTORY);
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_EQ(base::TimeDelta(), GetPendingWakeupTimerDelay());
  EXPECT_FALSE(scheduler()->IsGlobalBackoff());

  // Setup mock as we're about to attempt to sync.
  SyncShareTimes times;
  EXPECT_CALL(*syncer(), NormalSyncShare)
      .WillOnce(
          DoAll(Invoke(SimulateCommitFailed), RecordSyncShare(&times, false)));
  // Triggers the THEMES TrySyncCycleJobImpl(), which we've setup to fail. Its
  // RestartWaiting won't schedule a delayed retry, as the HISTORY nudge has
  // a smaller delay. We verify this by making sure the delay is still zero.
  PumpLoop();
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_EQ(base::TimeDelta(), GetPendingWakeupTimerDelay());
  EXPECT_TRUE(scheduler()->IsGlobalBackoff());

  // Triggers HISTORY PerformDelayedNudge(), which should no-op, because the
  // scheduler is in global backoff. However, it does need to setup the
  // `pending_wakeup_timer_`. The delay should be ~60 seconds, so verifying it's
  // greater than 50 should be safe.
  PumpLoop();
  EXPECT_TRUE(BlockTimerIsRunning());
  EXPECT_LT(base::Seconds(50), GetPendingWakeupTimerDelay());
  EXPECT_TRUE(scheduler()->IsGlobalBackoff());
}

}  // namespace syncer