summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_syncengine_sync.js
blob: 6a6d047bf54ac15a30712e7ca23e6fb01d7c6467 (plain)
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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/policies.js");
Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/resource.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/rotaryengine.js");
Cu.import("resource://testing-common/services/sync/utils.js");

function makeRotaryEngine() {
  return new RotaryEngine(Service);
}

function cleanAndGo(server) {
  Svc.Prefs.resetBranch("");
  Svc.Prefs.set("log.logger.engine.rotary", "Trace");
  Service.recordManager.clearCache();
  server.stop(run_next_test);
}

function configureService(server, username, password) {
  Service.clusterURL = server.baseURI;

  Service.identity.account = username || "foo";
  Service.identity.basicPassword = password || "password";
}

function createServerAndConfigureClient() {
  let engine = new RotaryEngine(Service);

  let contents = {
    meta: {global: {engines: {rotary: {version: engine.version,
                                       syncID:  engine.syncID}}}},
    crypto: {},
    rotary: {}
  };

  const USER = "foo";
  let server = new SyncServer();
  server.registerUser(USER, "password");
  server.createContents(USER, contents);
  server.start();

  Service.serverURL = server.baseURI;
  Service.clusterURL = server.baseURI;
  Service.identity.username = USER;
  Service._updateCachedURLs();

  return [engine, server, USER];
}

function run_test() {
  generateNewKeys(Service.collectionKeys);
  Svc.Prefs.set("log.logger.engine.rotary", "Trace");
  run_next_test();
}

/*
 * Tests
 *
 * SyncEngine._sync() is divided into four rather independent steps:
 *
 * - _syncStartup()
 * - _processIncoming()
 * - _uploadOutgoing()
 * - _syncFinish()
 *
 * In the spirit of unit testing, these are tested individually for
 * different scenarios below.
 */

add_test(function test_syncStartup_emptyOrOutdatedGlobalsResetsSync() {
  _("SyncEngine._syncStartup resets sync and wipes server data if there's no or an outdated global record");

  // Some server side data that's going to be wiped
  let collection = new ServerCollection();
  collection.insert('flying',
                    encryptPayload({id: 'flying',
                                    denomination: "LNER Class A3 4472"}));
  collection.insert('scotsman',
                    encryptPayload({id: 'scotsman',
                                    denomination: "Flying Scotsman"}));

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  Service.identity.username = "foo";

  let engine = makeRotaryEngine();
  engine._store.items = {rekolok: "Rekonstruktionslokomotive"};
  try {

    // Confirm initial environment
    do_check_eq(engine._tracker.changedIDs["rekolok"], undefined);
    let metaGlobal = Service.recordManager.get(engine.metaURL);
    do_check_eq(metaGlobal.payload.engines, undefined);
    do_check_true(!!collection.payload("flying"));
    do_check_true(!!collection.payload("scotsman"));

    engine.lastSync = Date.now() / 1000;
    engine.lastSyncLocal = Date.now();

    // Trying to prompt a wipe -- we no longer track CryptoMeta per engine,
    // so it has nothing to check.
    engine._syncStartup();

    // The meta/global WBO has been filled with data about the engine
    let engineData = metaGlobal.payload.engines["rotary"];
    do_check_eq(engineData.version, engine.version);
    do_check_eq(engineData.syncID, engine.syncID);

    // Sync was reset and server data was wiped
    do_check_eq(engine.lastSync, 0);
    do_check_eq(collection.payload("flying"), undefined);
    do_check_eq(collection.payload("scotsman"), undefined);

  } finally {
    cleanAndGo(server);
  }
});

add_test(function test_syncStartup_serverHasNewerVersion() {
  _("SyncEngine._syncStartup ");

  let global = new ServerWBO('global', {engines: {rotary: {version: 23456}}});
  let server = httpd_setup({
      "/1.1/foo/storage/meta/global": global.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  Service.identity.username = "foo";

  let engine = makeRotaryEngine();
  try {

    // The server has a newer version of the data and our engine can
    // handle.  That should give us an exception.
    let error;
    try {
      engine._syncStartup();
    } catch (ex) {
      error = ex;
    }
    do_check_eq(error.failureCode, VERSION_OUT_OF_DATE);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_syncStartup_syncIDMismatchResetsClient() {
  _("SyncEngine._syncStartup resets sync if syncIDs don't match");

  let server = sync_httpd_setup({});
  let syncTesting = new SyncTestingInfrastructure(server);
  Service.identity.username = "foo";

  // global record with a different syncID than our engine has
  let engine = makeRotaryEngine();
  let global = new ServerWBO('global',
                             {engines: {rotary: {version: engine.version,
                                                syncID: 'foobar'}}});
  server.registerPathHandler("/1.1/foo/storage/meta/global", global.handler());

  try {

    // Confirm initial environment
    do_check_eq(engine.syncID, 'fake-guid-0');
    do_check_eq(engine._tracker.changedIDs["rekolok"], undefined);

    engine.lastSync = Date.now() / 1000;
    engine.lastSyncLocal = Date.now();
    engine._syncStartup();

    // The engine has assumed the server's syncID
    do_check_eq(engine.syncID, 'foobar');

    // Sync was reset
    do_check_eq(engine.lastSync, 0);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_emptyServer() {
  _("SyncEngine._processIncoming working with an empty server backend");

  let collection = new ServerCollection();
  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  Service.identity.username = "foo";

  let engine = makeRotaryEngine();
  try {

    // Merely ensure that this code path is run without any errors
    engine._processIncoming();
    do_check_eq(engine.lastSync, 0);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_createFromServer() {
  _("SyncEngine._processIncoming creates new records from server data");

  // Some server records that will be downloaded
  let collection = new ServerCollection();
  collection.insert('flying',
                    encryptPayload({id: 'flying',
                                    denomination: "LNER Class A3 4472"}));
  collection.insert('scotsman',
                    encryptPayload({id: 'scotsman',
                                    denomination: "Flying Scotsman"}));

  // Two pathological cases involving relative URIs gone wrong.
  let pathologicalPayload = encryptPayload({id: '../pathological',
                                            denomination: "Pathological Case"});
  collection.insert('../pathological', pathologicalPayload);

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler(),
      "/1.1/foo/storage/rotary/flying": collection.wbo("flying").handler(),
      "/1.1/foo/storage/rotary/scotsman": collection.wbo("scotsman").handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  Service.identity.username = "foo";

  generateNewKeys(Service.collectionKeys);

  let engine = makeRotaryEngine();
  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    // Confirm initial environment
    do_check_eq(engine.lastSync, 0);
    do_check_eq(engine.lastModified, null);
    do_check_eq(engine._store.items.flying, undefined);
    do_check_eq(engine._store.items.scotsman, undefined);
    do_check_eq(engine._store.items['../pathological'], undefined);

    engine._syncStartup();
    engine._processIncoming();

    // Timestamps of last sync and last server modification are set.
    do_check_true(engine.lastSync > 0);
    do_check_true(engine.lastModified > 0);

    // Local records have been created from the server data.
    do_check_eq(engine._store.items.flying, "LNER Class A3 4472");
    do_check_eq(engine._store.items.scotsman, "Flying Scotsman");
    do_check_eq(engine._store.items['../pathological'], "Pathological Case");

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_reconcile() {
  _("SyncEngine._processIncoming updates local records");

  let collection = new ServerCollection();

  // This server record is newer than the corresponding client one,
  // so it'll update its data.
  collection.insert('newrecord',
                    encryptPayload({id: 'newrecord',
                                    denomination: "New stuff..."}));

  // This server record is newer than the corresponding client one,
  // so it'll update its data.
  collection.insert('newerserver',
                    encryptPayload({id: 'newerserver',
                                    denomination: "New data!"}));

  // This server record is 2 mins older than the client counterpart
  // but identical to it, so we're expecting the client record's
  // changedID to be reset.
  collection.insert('olderidentical',
                    encryptPayload({id: 'olderidentical',
                                    denomination: "Older but identical"}));
  collection._wbos.olderidentical.modified -= 120;

  // This item simply has different data than the corresponding client
  // record (which is unmodified), so it will update the client as well
  collection.insert('updateclient',
                    encryptPayload({id: 'updateclient',
                                    denomination: "Get this!"}));

  // This is a dupe of 'original'.
  collection.insert('duplication',
                    encryptPayload({id: 'duplication',
                                    denomination: "Original Entry"}));

  // This record is marked as deleted, so we're expecting the client
  // record to be removed.
  collection.insert('nukeme',
                    encryptPayload({id: 'nukeme',
                                    denomination: "Nuke me!",
                                    deleted: true}));

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  Service.identity.username = "foo";

  let engine = makeRotaryEngine();
  engine._store.items = {newerserver: "New data, but not as new as server!",
                         olderidentical: "Older but identical",
                         updateclient: "Got data?",
                         original: "Original Entry",
                         long_original: "Long Original Entry",
                         nukeme: "Nuke me!"};
  // Make this record 1 min old, thus older than the one on the server
  engine._tracker.addChangedID('newerserver', Date.now()/1000 - 60);
  // This record has been changed 2 mins later than the one on the server
  engine._tracker.addChangedID('olderidentical', Date.now()/1000);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    // Confirm initial environment
    do_check_eq(engine._store.items.newrecord, undefined);
    do_check_eq(engine._store.items.newerserver, "New data, but not as new as server!");
    do_check_eq(engine._store.items.olderidentical, "Older but identical");
    do_check_eq(engine._store.items.updateclient, "Got data?");
    do_check_eq(engine._store.items.nukeme, "Nuke me!");
    do_check_true(engine._tracker.changedIDs['olderidentical'] > 0);

    engine._syncStartup();
    engine._processIncoming();

    // Timestamps of last sync and last server modification are set.
    do_check_true(engine.lastSync > 0);
    do_check_true(engine.lastModified > 0);

    // The new record is created.
    do_check_eq(engine._store.items.newrecord, "New stuff...");

    // The 'newerserver' record is updated since the server data is newer.
    do_check_eq(engine._store.items.newerserver, "New data!");

    // The data for 'olderidentical' is identical on the server, so
    // it's no longer marked as changed anymore.
    do_check_eq(engine._store.items.olderidentical, "Older but identical");
    do_check_eq(engine._tracker.changedIDs['olderidentical'], undefined);

    // Updated with server data.
    do_check_eq(engine._store.items.updateclient, "Get this!");

    // The incoming ID is preferred.
    do_check_eq(engine._store.items.original, undefined);
    do_check_eq(engine._store.items.duplication, "Original Entry");
    do_check_neq(engine._delete.ids.indexOf("original"), -1);

    // The 'nukeme' record marked as deleted is removed.
    do_check_eq(engine._store.items.nukeme, undefined);
  } finally {
    cleanAndGo(server);
  }
});

add_test(function test_processIncoming_reconcile_local_deleted() {
  _("Ensure local, duplicate ID is deleted on server.");

  // When a duplicate is resolved, the local ID (which is never taken) should
  // be deleted on the server.
  let [engine, server, user] = createServerAndConfigureClient();

  let now = Date.now() / 1000 - 10;
  engine.lastSync = now;
  engine.lastModified = now + 1;

  let record = encryptPayload({id: "DUPE_INCOMING", denomination: "incoming"});
  let wbo = new ServerWBO("DUPE_INCOMING", record, now + 2);
  server.insertWBO(user, "rotary", wbo);

  record = encryptPayload({id: "DUPE_LOCAL", denomination: "local"});
  wbo = new ServerWBO("DUPE_LOCAL", record, now - 1);
  server.insertWBO(user, "rotary", wbo);

  engine._store.create({id: "DUPE_LOCAL", denomination: "local"});
  do_check_true(engine._store.itemExists("DUPE_LOCAL"));
  do_check_eq("DUPE_LOCAL", engine._findDupe({id: "DUPE_INCOMING"}));

  engine._sync();

  do_check_attribute_count(engine._store.items, 1);
  do_check_true("DUPE_INCOMING" in engine._store.items);

  let collection = server.getCollection(user, "rotary");
  do_check_eq(1, collection.count());
  do_check_neq(undefined, collection.wbo("DUPE_INCOMING"));

  cleanAndGo(server);
});

add_test(function test_processIncoming_reconcile_equivalent() {
  _("Ensure proper handling of incoming records that match local.");

  let [engine, server, user] = createServerAndConfigureClient();

  let now = Date.now() / 1000 - 10;
  engine.lastSync = now;
  engine.lastModified = now + 1;

  let record = encryptPayload({id: "entry", denomination: "denomination"});
  let wbo = new ServerWBO("entry", record, now + 2);
  server.insertWBO(user, "rotary", wbo);

  engine._store.items = {entry: "denomination"};
  do_check_true(engine._store.itemExists("entry"));

  engine._sync();

  do_check_attribute_count(engine._store.items, 1);

  cleanAndGo(server);
});

add_test(function test_processIncoming_reconcile_locally_deleted_dupe_new() {
  _("Ensure locally deleted duplicate record newer than incoming is handled.");

  // This is a somewhat complicated test. It ensures that if a client receives
  // a modified record for an item that is deleted locally but with a different
  // ID that the incoming record is ignored. This is a corner case for record
  // handling, but it needs to be supported.
  let [engine, server, user] = createServerAndConfigureClient();

  let now = Date.now() / 1000 - 10;
  engine.lastSync = now;
  engine.lastModified = now + 1;

  let record = encryptPayload({id: "DUPE_INCOMING", denomination: "incoming"});
  let wbo = new ServerWBO("DUPE_INCOMING", record, now + 2);
  server.insertWBO(user, "rotary", wbo);

  // Simulate a locally-deleted item.
  engine._store.items = {};
  engine._tracker.addChangedID("DUPE_LOCAL", now + 3);
  do_check_false(engine._store.itemExists("DUPE_LOCAL"));
  do_check_false(engine._store.itemExists("DUPE_INCOMING"));
  do_check_eq("DUPE_LOCAL", engine._findDupe({id: "DUPE_INCOMING"}));

  engine._sync();

  // After the sync, the server's payload for the original ID should be marked
  // as deleted.
  do_check_empty(engine._store.items);
  let collection = server.getCollection(user, "rotary");
  do_check_eq(1, collection.count());
  wbo = collection.wbo("DUPE_INCOMING");
  do_check_neq(null, wbo);
  let payload = JSON.parse(JSON.parse(wbo.payload).ciphertext);
  do_check_true(payload.deleted);

  cleanAndGo(server);
});

add_test(function test_processIncoming_reconcile_locally_deleted_dupe_old() {
  _("Ensure locally deleted duplicate record older than incoming is restored.");

  // This is similar to the above test except it tests the condition where the
  // incoming record is newer than the local deletion, therefore overriding it.

  let [engine, server, user] = createServerAndConfigureClient();

  let now = Date.now() / 1000 - 10;
  engine.lastSync = now;
  engine.lastModified = now + 1;

  let record = encryptPayload({id: "DUPE_INCOMING", denomination: "incoming"});
  let wbo = new ServerWBO("DUPE_INCOMING", record, now + 2);
  server.insertWBO(user, "rotary", wbo);

  // Simulate a locally-deleted item.
  engine._store.items = {};
  engine._tracker.addChangedID("DUPE_LOCAL", now + 1);
  do_check_false(engine._store.itemExists("DUPE_LOCAL"));
  do_check_false(engine._store.itemExists("DUPE_INCOMING"));
  do_check_eq("DUPE_LOCAL", engine._findDupe({id: "DUPE_INCOMING"}));

  engine._sync();

  // Since the remote change is newer, the incoming item should exist locally.
  do_check_attribute_count(engine._store.items, 1);
  do_check_true("DUPE_INCOMING" in engine._store.items);
  do_check_eq("incoming", engine._store.items.DUPE_INCOMING);

  let collection = server.getCollection(user, "rotary");
  do_check_eq(1, collection.count());
  wbo = collection.wbo("DUPE_INCOMING");
  let payload = JSON.parse(JSON.parse(wbo.payload).ciphertext);
  do_check_eq("incoming", payload.denomination);

  cleanAndGo(server);
});

add_test(function test_processIncoming_reconcile_changed_dupe() {
  _("Ensure that locally changed duplicate record is handled properly.");

  let [engine, server, user] = createServerAndConfigureClient();

  let now = Date.now() / 1000 - 10;
  engine.lastSync = now;
  engine.lastModified = now + 1;

  // The local record is newer than the incoming one, so it should be retained.
  let record = encryptPayload({id: "DUPE_INCOMING", denomination: "incoming"});
  let wbo = new ServerWBO("DUPE_INCOMING", record, now + 2);
  server.insertWBO(user, "rotary", wbo);

  engine._store.create({id: "DUPE_LOCAL", denomination: "local"});
  engine._tracker.addChangedID("DUPE_LOCAL", now + 3);
  do_check_true(engine._store.itemExists("DUPE_LOCAL"));
  do_check_eq("DUPE_LOCAL", engine._findDupe({id: "DUPE_INCOMING"}));

  engine._sync();

  // The ID should have been changed to incoming.
  do_check_attribute_count(engine._store.items, 1);
  do_check_true("DUPE_INCOMING" in engine._store.items);

  // On the server, the local ID should be deleted and the incoming ID should
  // have its payload set to what was in the local record.
  let collection = server.getCollection(user, "rotary");
  do_check_eq(1, collection.count());
  wbo = collection.wbo("DUPE_INCOMING");
  do_check_neq(undefined, wbo);
  let payload = JSON.parse(JSON.parse(wbo.payload).ciphertext);
  do_check_eq("local", payload.denomination);

  cleanAndGo(server);
});

add_test(function test_processIncoming_reconcile_changed_dupe_new() {
  _("Ensure locally changed duplicate record older than incoming is ignored.");

  // This test is similar to the above except the incoming record is younger
  // than the local record. The incoming record should be authoritative.
  let [engine, server, user] = createServerAndConfigureClient();

  let now = Date.now() / 1000 - 10;
  engine.lastSync = now;
  engine.lastModified = now + 1;

  let record = encryptPayload({id: "DUPE_INCOMING", denomination: "incoming"});
  let wbo = new ServerWBO("DUPE_INCOMING", record, now + 2);
  server.insertWBO(user, "rotary", wbo);

  engine._store.create({id: "DUPE_LOCAL", denomination: "local"});
  engine._tracker.addChangedID("DUPE_LOCAL", now + 1);
  do_check_true(engine._store.itemExists("DUPE_LOCAL"));
  do_check_eq("DUPE_LOCAL", engine._findDupe({id: "DUPE_INCOMING"}));

  engine._sync();

  // The ID should have been changed to incoming.
  do_check_attribute_count(engine._store.items, 1);
  do_check_true("DUPE_INCOMING" in engine._store.items);

  // On the server, the local ID should be deleted and the incoming ID should
  // have its payload retained.
  let collection = server.getCollection(user, "rotary");
  do_check_eq(1, collection.count());
  wbo = collection.wbo("DUPE_INCOMING");
  do_check_neq(undefined, wbo);
  let payload = JSON.parse(JSON.parse(wbo.payload).ciphertext);
  do_check_eq("incoming", payload.denomination);
  cleanAndGo(server);
});

add_test(function test_processIncoming_mobile_batchSize() {
  _("SyncEngine._processIncoming doesn't fetch everything at once on mobile clients");

  Svc.Prefs.set("client.type", "mobile");
  Service.identity.username = "foo";

  // A collection that logs each GET
  let collection = new ServerCollection();
  collection.get_log = [];
  collection._get = collection.get;
  collection.get = function (options) {
    this.get_log.push(options);
    return this._get(options);
  };

  // Let's create some 234 server side records. They're all at least
  // 10 minutes old.
  for (let i = 0; i < 234; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + i});
    let wbo = new ServerWBO(id, payload);
    wbo.modified = Date.now()/1000 - 60*(i+10);
    collection.insertWBO(wbo);
  }

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let engine = makeRotaryEngine();
  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    _("On a mobile client, we get new records from the server in batches of 50.");
    engine._syncStartup();
    engine._processIncoming();
    do_check_attribute_count(engine._store.items, 234);
    do_check_true('record-no-0' in engine._store.items);
    do_check_true('record-no-49' in engine._store.items);
    do_check_true('record-no-50' in engine._store.items);
    do_check_true('record-no-233' in engine._store.items);

    // Verify that the right number of GET requests with the right
    // kind of parameters were made.
    do_check_eq(collection.get_log.length,
                Math.ceil(234 / MOBILE_BATCH_SIZE) + 1);
    do_check_eq(collection.get_log[0].full, 1);
    do_check_eq(collection.get_log[0].limit, MOBILE_BATCH_SIZE);
    do_check_eq(collection.get_log[1].full, undefined);
    do_check_eq(collection.get_log[1].limit, undefined);
    for (let i = 1; i <= Math.floor(234 / MOBILE_BATCH_SIZE); i++) {
      do_check_eq(collection.get_log[i+1].full, 1);
      do_check_eq(collection.get_log[i+1].limit, undefined);
      if (i < Math.floor(234 / MOBILE_BATCH_SIZE))
        do_check_eq(collection.get_log[i+1].ids.length, MOBILE_BATCH_SIZE);
      else
        do_check_eq(collection.get_log[i+1].ids.length, 234 % MOBILE_BATCH_SIZE);
    }

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_store_toFetch() {
  _("If processIncoming fails in the middle of a batch on mobile, state is saved in toFetch and lastSync.");
  Service.identity.username = "foo";
  Svc.Prefs.set("client.type", "mobile");

  // A collection that throws at the fourth get.
  let collection = new ServerCollection();
  collection._get_calls = 0;
  collection._get = collection.get;
  collection.get = function() {
    this._get_calls += 1;
    if (this._get_calls > 3) {
      throw "Abort on fourth call!";
    }
    return this._get.apply(this, arguments);
  };

  // Let's create three batches worth of server side records.
  for (var i = 0; i < MOBILE_BATCH_SIZE * 3; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + id});
    let wbo = new ServerWBO(id, payload);
    wbo.modified = Date.now()/1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
    collection.insertWBO(wbo);
  }

  let engine = makeRotaryEngine();
  engine.enabled = true;

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {

    // Confirm initial environment
    do_check_eq(engine.lastSync, 0);
    do_check_empty(engine._store.items);

    let error;
    try {
      engine.sync();
    } catch (ex) {
      error = ex;
    }
    do_check_true(!!error);

    // Only the first two batches have been applied.
    do_check_eq(Object.keys(engine._store.items).length,
                MOBILE_BATCH_SIZE * 2);

    // The third batch is stuck in toFetch. lastSync has been moved forward to
    // the last successful item's timestamp.
    do_check_eq(engine.toFetch.length, MOBILE_BATCH_SIZE);
    do_check_eq(engine.lastSync, collection.wbo("record-no-99").modified);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_resume_toFetch() {
  _("toFetch and previousFailed items left over from previous syncs are fetched on the next sync, along with new items.");
  Service.identity.username = "foo";

  const LASTSYNC = Date.now() / 1000;

  // Server records that will be downloaded
  let collection = new ServerCollection();
  collection.insert('flying',
                    encryptPayload({id: 'flying',
                                    denomination: "LNER Class A3 4472"}));
  collection.insert('scotsman',
                    encryptPayload({id: 'scotsman',
                                    denomination: "Flying Scotsman"}));
  collection.insert('rekolok',
                    encryptPayload({id: 'rekolok',
                                    denomination: "Rekonstruktionslokomotive"}));
  for (let i = 0; i < 3; i++) {
    let id = 'failed' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + i});
    let wbo = new ServerWBO(id, payload);
    wbo.modified = LASTSYNC - 10;
    collection.insertWBO(wbo);
  }

  collection.wbo("flying").modified =
    collection.wbo("scotsman").modified = LASTSYNC - 10;
  collection._wbos.rekolok.modified = LASTSYNC + 10;

  // Time travel 10 seconds into the future but still download the above WBOs.
  let engine = makeRotaryEngine();
  engine.lastSync = LASTSYNC;
  engine.toFetch = ["flying", "scotsman"];
  engine.previousFailed = ["failed0", "failed1", "failed2"];

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {

    // Confirm initial environment
    do_check_eq(engine._store.items.flying, undefined);
    do_check_eq(engine._store.items.scotsman, undefined);
    do_check_eq(engine._store.items.rekolok, undefined);

    engine._syncStartup();
    engine._processIncoming();

    // Local records have been created from the server data.
    do_check_eq(engine._store.items.flying, "LNER Class A3 4472");
    do_check_eq(engine._store.items.scotsman, "Flying Scotsman");
    do_check_eq(engine._store.items.rekolok, "Rekonstruktionslokomotive");
    do_check_eq(engine._store.items.failed0, "Record No. 0");
    do_check_eq(engine._store.items.failed1, "Record No. 1");
    do_check_eq(engine._store.items.failed2, "Record No. 2");
    do_check_eq(engine.previousFailed.length, 0);
  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_applyIncomingBatchSize_smaller() {
  _("Ensure that a number of incoming items less than applyIncomingBatchSize is still applied.");
  Service.identity.username = "foo";

  // Engine that doesn't like the first and last record it's given.
  const APPLY_BATCH_SIZE = 10;
  let engine = makeRotaryEngine();
  engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
  engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
  engine._store.applyIncomingBatch = function (records) {
    let failed1 = records.shift();
    let failed2 = records.pop();
    this._applyIncomingBatch(records);
    return [failed1.id, failed2.id];
  };

  // Let's create less than a batch worth of server side records.
  let collection = new ServerCollection();
  for (let i = 0; i < APPLY_BATCH_SIZE - 1; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + id});
    collection.insert(id, payload);
  }

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {

    // Confirm initial environment
    do_check_empty(engine._store.items);

    engine._syncStartup();
    engine._processIncoming();

    // Records have been applied and the expected failures have failed.
    do_check_attribute_count(engine._store.items, APPLY_BATCH_SIZE - 1 - 2);
    do_check_eq(engine.toFetch.length, 0);
    do_check_eq(engine.previousFailed.length, 2);
    do_check_eq(engine.previousFailed[0], "record-no-0");
    do_check_eq(engine.previousFailed[1], "record-no-8");

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_applyIncomingBatchSize_multiple() {
  _("Ensure that incoming items are applied according to applyIncomingBatchSize.");
  Service.identity.username = "foo";

  const APPLY_BATCH_SIZE = 10;

  // Engine that applies records in batches.
  let engine = makeRotaryEngine();
  engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
  let batchCalls = 0;
  engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
  engine._store.applyIncomingBatch = function (records) {
    batchCalls += 1;
    do_check_eq(records.length, APPLY_BATCH_SIZE);
    this._applyIncomingBatch.apply(this, arguments);
  };

  // Let's create three batches worth of server side records.
  let collection = new ServerCollection();
  for (let i = 0; i < APPLY_BATCH_SIZE * 3; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + id});
    collection.insert(id, payload);
  }

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {

    // Confirm initial environment
    do_check_empty(engine._store.items);

    engine._syncStartup();
    engine._processIncoming();

    // Records have been applied in 3 batches.
    do_check_eq(batchCalls, 3);
    do_check_attribute_count(engine._store.items, APPLY_BATCH_SIZE * 3);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_notify_count() {
  _("Ensure that failed records are reported only once.");
  Service.identity.username = "foo";

  const APPLY_BATCH_SIZE = 5;
  const NUMBER_OF_RECORDS = 15;

  // Engine that fails the first record.
  let engine = makeRotaryEngine();
  engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
  engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
  engine._store.applyIncomingBatch = function (records) {
    engine._store._applyIncomingBatch(records.slice(1));
    return [records[0].id];
  };

  // Create a batch of server side records.
  let collection = new ServerCollection();
  for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + id});
    collection.insert(id, payload);
  }

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {
    // Confirm initial environment.
    do_check_eq(engine.lastSync, 0);
    do_check_eq(engine.toFetch.length, 0);
    do_check_eq(engine.previousFailed.length, 0);
    do_check_empty(engine._store.items);

    let called = 0;
    let counts;
    function onApplied(count) {
      _("Called with " + JSON.stringify(counts));
      counts = count;
      called++;
    }
    Svc.Obs.add("weave:engine:sync:applied", onApplied);

    // Do sync.
    engine._syncStartup();
    engine._processIncoming();

    // Confirm failures.
    do_check_attribute_count(engine._store.items, 12);
    do_check_eq(engine.previousFailed.length, 3);
    do_check_eq(engine.previousFailed[0], "record-no-0");
    do_check_eq(engine.previousFailed[1], "record-no-5");
    do_check_eq(engine.previousFailed[2], "record-no-10");

    // There are newly failed records and they are reported.
    do_check_eq(called, 1);
    do_check_eq(counts.failed, 3);
    do_check_eq(counts.applied, 15);
    do_check_eq(counts.newFailed, 3);
    do_check_eq(counts.succeeded, 12);

    // Sync again, 1 of the failed items are the same, the rest didn't fail.
    engine._processIncoming();

    // Confirming removed failures.
    do_check_attribute_count(engine._store.items, 14);
    do_check_eq(engine.previousFailed.length, 1);
    do_check_eq(engine.previousFailed[0], "record-no-0");

    do_check_eq(called, 2);
    do_check_eq(counts.failed, 1);
    do_check_eq(counts.applied, 3);
    do_check_eq(counts.newFailed, 0);
    do_check_eq(counts.succeeded, 2);

    Svc.Obs.remove("weave:engine:sync:applied", onApplied);
  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_previousFailed() {
  _("Ensure that failed records are retried.");
  Service.identity.username = "foo";
  Svc.Prefs.set("client.type", "mobile");

  const APPLY_BATCH_SIZE = 4;
  const NUMBER_OF_RECORDS = 14;

  // Engine that fails the first 2 records.
  let engine = makeRotaryEngine();
  engine.mobileGUIDFetchBatchSize = engine.applyIncomingBatchSize = APPLY_BATCH_SIZE;
  engine._store._applyIncomingBatch = engine._store.applyIncomingBatch;
  engine._store.applyIncomingBatch = function (records) {
    engine._store._applyIncomingBatch(records.slice(2));
    return [records[0].id, records[1].id];
  };

  // Create a batch of server side records.
  let collection = new ServerCollection();
  for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + i});
    collection.insert(id, payload);
  }

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {
    // Confirm initial environment.
    do_check_eq(engine.lastSync, 0);
    do_check_eq(engine.toFetch.length, 0);
    do_check_eq(engine.previousFailed.length, 0);
    do_check_empty(engine._store.items);

    // Initial failed items in previousFailed to be reset.
    let previousFailed = [Utils.makeGUID(), Utils.makeGUID(), Utils.makeGUID()];
    engine.previousFailed = previousFailed;
    do_check_eq(engine.previousFailed, previousFailed);

    // Do sync.
    engine._syncStartup();
    engine._processIncoming();

    // Expected result: 4 sync batches with 2 failures each => 8 failures
    do_check_attribute_count(engine._store.items, 6);
    do_check_eq(engine.previousFailed.length, 8);
    do_check_eq(engine.previousFailed[0], "record-no-0");
    do_check_eq(engine.previousFailed[1], "record-no-1");
    do_check_eq(engine.previousFailed[2], "record-no-4");
    do_check_eq(engine.previousFailed[3], "record-no-5");
    do_check_eq(engine.previousFailed[4], "record-no-8");
    do_check_eq(engine.previousFailed[5], "record-no-9");
    do_check_eq(engine.previousFailed[6], "record-no-12");
    do_check_eq(engine.previousFailed[7], "record-no-13");

    // Sync again with the same failed items (records 0, 1, 8, 9).
    engine._processIncoming();

    // A second sync with the same failed items should not add the same items again.
    // Items that did not fail a second time should no longer be in previousFailed.
    do_check_attribute_count(engine._store.items, 10);
    do_check_eq(engine.previousFailed.length, 4);
    do_check_eq(engine.previousFailed[0], "record-no-0");
    do_check_eq(engine.previousFailed[1], "record-no-1");
    do_check_eq(engine.previousFailed[2], "record-no-8");
    do_check_eq(engine.previousFailed[3], "record-no-9");

    // Refetched items that didn't fail the second time are in engine._store.items.
    do_check_eq(engine._store.items['record-no-4'], "Record No. 4");
    do_check_eq(engine._store.items['record-no-5'], "Record No. 5");
    do_check_eq(engine._store.items['record-no-12'], "Record No. 12");
    do_check_eq(engine._store.items['record-no-13'], "Record No. 13");
  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_failed_records() {
  _("Ensure that failed records from _reconcile and applyIncomingBatch are refetched.");
  Service.identity.username = "foo";

  // Let's create three and a bit batches worth of server side records.
  let collection = new ServerCollection();
  const NUMBER_OF_RECORDS = MOBILE_BATCH_SIZE * 3 + 5;
  for (let i = 0; i < NUMBER_OF_RECORDS; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + id});
    let wbo = new ServerWBO(id, payload);
    wbo.modified = Date.now()/1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
    collection.insertWBO(wbo);
  }

  // Engine that batches but likes to throw on a couple of records,
  // two in each batch: the even ones fail in reconcile, the odd ones
  // in applyIncoming.
  const BOGUS_RECORDS = ["record-no-" + 42,
                         "record-no-" + 23,
                         "record-no-" + (42 + MOBILE_BATCH_SIZE),
                         "record-no-" + (23 + MOBILE_BATCH_SIZE),
                         "record-no-" + (42 + MOBILE_BATCH_SIZE * 2),
                         "record-no-" + (23 + MOBILE_BATCH_SIZE * 2),
                         "record-no-" + (2 + MOBILE_BATCH_SIZE * 3),
                         "record-no-" + (1 + MOBILE_BATCH_SIZE * 3)];
  let engine = makeRotaryEngine();
  engine.applyIncomingBatchSize = MOBILE_BATCH_SIZE;

  engine.__reconcile = engine._reconcile;
  engine._reconcile = function _reconcile(record) {
    if (BOGUS_RECORDS.indexOf(record.id) % 2 == 0) {
      throw "I don't like this record! Baaaaaah!";
    }
    return this.__reconcile.apply(this, arguments);
  };
  engine._store._applyIncoming = engine._store.applyIncoming;
  engine._store.applyIncoming = function (record) {
    if (BOGUS_RECORDS.indexOf(record.id) % 2 == 1) {
      throw "I don't like this record! Baaaaaah!";
    }
    return this._applyIncoming.apply(this, arguments);
  };

  // Keep track of requests made of a collection.
  let count = 0;
  let uris  = [];
  function recording_handler(collection) {
    let h = collection.handler();
    return function(req, res) {
      ++count;
      uris.push(req.path + "?" + req.queryString);
      return h(req, res);
    };
  }
  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": recording_handler(collection)
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    // Confirm initial environment
    do_check_eq(engine.lastSync, 0);
    do_check_eq(engine.toFetch.length, 0);
    do_check_eq(engine.previousFailed.length, 0);
    do_check_empty(engine._store.items);

    let observerSubject;
    let observerData;
    Svc.Obs.add("weave:engine:sync:applied", function onApplied(subject, data) {
      Svc.Obs.remove("weave:engine:sync:applied", onApplied);
      observerSubject = subject;
      observerData = data;
    });

    engine._syncStartup();
    engine._processIncoming();

    // Ensure that all records but the bogus 4 have been applied.
    do_check_attribute_count(engine._store.items,
                             NUMBER_OF_RECORDS - BOGUS_RECORDS.length);

    // Ensure that the bogus records will be fetched again on the next sync.
    do_check_eq(engine.previousFailed.length, BOGUS_RECORDS.length);
    engine.previousFailed.sort();
    BOGUS_RECORDS.sort();
    for (let i = 0; i < engine.previousFailed.length; i++) {
      do_check_eq(engine.previousFailed[i], BOGUS_RECORDS[i]);
    }

    // Ensure the observer was notified
    do_check_eq(observerData, engine.name);
    do_check_eq(observerSubject.failed, BOGUS_RECORDS.length);
    do_check_eq(observerSubject.newFailed, BOGUS_RECORDS.length);

    // Testing batching of failed item fetches.
    // Try to sync again. Ensure that we split the request into chunks to avoid
    // URI length limitations.
    function batchDownload(batchSize) {
      count = 0;
      uris  = [];
      engine.guidFetchBatchSize = batchSize;
      engine._processIncoming();
      _("Tried again. Requests: " + count + "; URIs: " + JSON.stringify(uris));
      return count;
    }

    // There are 8 bad records, so this needs 3 fetches.
    _("Test batching with ID batch size 3, normal mobile batch size.");
    do_check_eq(batchDownload(3), 3);

    // Now see with a more realistic limit.
    _("Test batching with sufficient ID batch size.");
    do_check_eq(batchDownload(BOGUS_RECORDS.length), 1);

    // If we're on mobile, that limit is used by default.
    _("Test batching with tiny mobile batch size.");
    Svc.Prefs.set("client.type", "mobile");
    engine.mobileGUIDFetchBatchSize = 2;
    do_check_eq(batchDownload(BOGUS_RECORDS.length), 4);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_processIncoming_decrypt_failed() {
  _("Ensure that records failing to decrypt are either replaced or refetched.");

  Service.identity.username = "foo";

  // Some good and some bogus records. One doesn't contain valid JSON,
  // the other will throw during decrypt.
  let collection = new ServerCollection();
  collection._wbos.flying = new ServerWBO(
      'flying', encryptPayload({id: 'flying',
                                denomination: "LNER Class A3 4472"}));
  collection._wbos.nojson = new ServerWBO("nojson", "This is invalid JSON");
  collection._wbos.nojson2 = new ServerWBO("nojson2", "This is invalid JSON");
  collection._wbos.scotsman = new ServerWBO(
      'scotsman', encryptPayload({id: 'scotsman',
                                  denomination: "Flying Scotsman"}));
  collection._wbos.nodecrypt = new ServerWBO("nodecrypt", "Decrypt this!");
  collection._wbos.nodecrypt2 = new ServerWBO("nodecrypt2", "Decrypt this!");

  // Patch the fake crypto service to throw on the record above.
  Svc.Crypto._decrypt = Svc.Crypto.decrypt;
  Svc.Crypto.decrypt = function (ciphertext) {
    if (ciphertext == "Decrypt this!") {
      throw "Derp! Cipher finalized failed. Im ur crypto destroyin ur recordz.";
    }
    return this._decrypt.apply(this, arguments);
  };

  // Some broken records also exist locally.
  let engine = makeRotaryEngine();
  engine.enabled = true;
  engine._store.items = {nojson: "Valid JSON",
                         nodecrypt: "Valid ciphertext"};

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};
  try {

    // Confirm initial state
    do_check_eq(engine.toFetch.length, 0);
    do_check_eq(engine.previousFailed.length, 0);

    let observerSubject;
    let observerData;
    Svc.Obs.add("weave:engine:sync:applied", function onApplied(subject, data) {
      Svc.Obs.remove("weave:engine:sync:applied", onApplied);
      observerSubject = subject;
      observerData = data;
    });

    engine.lastSync = collection.wbo("nojson").modified - 1;
    engine.sync();

    do_check_eq(engine.previousFailed.length, 4);
    do_check_eq(engine.previousFailed[0], "nojson");
    do_check_eq(engine.previousFailed[1], "nojson2");
    do_check_eq(engine.previousFailed[2], "nodecrypt");
    do_check_eq(engine.previousFailed[3], "nodecrypt2");

    // Ensure the observer was notified
    do_check_eq(observerData, engine.name);
    do_check_eq(observerSubject.applied, 2);
    do_check_eq(observerSubject.failed, 4);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_uploadOutgoing_toEmptyServer() {
  _("SyncEngine._uploadOutgoing uploads new records to server");

  Service.identity.username = "foo";
  let collection = new ServerCollection();
  collection._wbos.flying = new ServerWBO('flying');
  collection._wbos.scotsman = new ServerWBO('scotsman');

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler(),
      "/1.1/foo/storage/rotary/flying": collection.wbo("flying").handler(),
      "/1.1/foo/storage/rotary/scotsman": collection.wbo("scotsman").handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  generateNewKeys(Service.collectionKeys);

  let engine = makeRotaryEngine();
  engine.lastSync = 123; // needs to be non-zero so that tracker is queried
  engine._store.items = {flying: "LNER Class A3 4472",
                         scotsman: "Flying Scotsman"};
  // Mark one of these records as changed
  engine._tracker.addChangedID('scotsman', 0);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    // Confirm initial environment
    do_check_eq(engine.lastSyncLocal, 0);
    do_check_eq(collection.payload("flying"), undefined);
    do_check_eq(collection.payload("scotsman"), undefined);

    engine._syncStartup();
    engine._uploadOutgoing();

    // Local timestamp has been set.
    do_check_true(engine.lastSyncLocal > 0);

    // Ensure the marked record ('scotsman') has been uploaded and is
    // no longer marked.
    do_check_eq(collection.payload("flying"), undefined);
    do_check_true(!!collection.payload("scotsman"));
    do_check_eq(JSON.parse(collection.wbo("scotsman").data.ciphertext).id,
                "scotsman");
    do_check_eq(engine._tracker.changedIDs["scotsman"], undefined);

    // The 'flying' record wasn't marked so it wasn't uploaded
    do_check_eq(collection.payload("flying"), undefined);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_uploadOutgoing_failed() {
  _("SyncEngine._uploadOutgoing doesn't clear the tracker of objects that failed to upload.");

  Service.identity.username = "foo";
  let collection = new ServerCollection();
  // We only define the "flying" WBO on the server, not the "scotsman"
  // and "peppercorn" ones.
  collection._wbos.flying = new ServerWBO('flying');

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let engine = makeRotaryEngine();
  engine.lastSync = 123; // needs to be non-zero so that tracker is queried
  engine._store.items = {flying: "LNER Class A3 4472",
                         scotsman: "Flying Scotsman",
                         peppercorn: "Peppercorn Class"};
  // Mark these records as changed
  const FLYING_CHANGED = 12345;
  const SCOTSMAN_CHANGED = 23456;
  const PEPPERCORN_CHANGED = 34567;
  engine._tracker.addChangedID('flying', FLYING_CHANGED);
  engine._tracker.addChangedID('scotsman', SCOTSMAN_CHANGED);
  engine._tracker.addChangedID('peppercorn', PEPPERCORN_CHANGED);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    // Confirm initial environment
    do_check_eq(engine.lastSyncLocal, 0);
    do_check_eq(collection.payload("flying"), undefined);
    do_check_eq(engine._tracker.changedIDs['flying'], FLYING_CHANGED);
    do_check_eq(engine._tracker.changedIDs['scotsman'], SCOTSMAN_CHANGED);
    do_check_eq(engine._tracker.changedIDs['peppercorn'], PEPPERCORN_CHANGED);

    engine.enabled = true;
    engine.sync();

    // Local timestamp has been set.
    do_check_true(engine.lastSyncLocal > 0);

    // Ensure the 'flying' record has been uploaded and is no longer marked.
    do_check_true(!!collection.payload("flying"));
    do_check_eq(engine._tracker.changedIDs['flying'], undefined);

    // The 'scotsman' and 'peppercorn' records couldn't be uploaded so
    // they weren't cleared from the tracker.
    do_check_eq(engine._tracker.changedIDs['scotsman'], SCOTSMAN_CHANGED);
    do_check_eq(engine._tracker.changedIDs['peppercorn'], PEPPERCORN_CHANGED);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_uploadOutgoing_MAX_UPLOAD_RECORDS() {
  _("SyncEngine._uploadOutgoing uploads in batches of MAX_UPLOAD_RECORDS");

  Service.identity.username = "foo";
  let collection = new ServerCollection();

  // Let's count how many times the client posts to the server
  var noOfUploads = 0;
  collection.post = (function(orig) {
    return function() {
      noOfUploads++;
      return orig.apply(this, arguments);
    };
  }(collection.post));

  // Create a bunch of records (and server side handlers)
  let engine = makeRotaryEngine();
  for (var i = 0; i < 234; i++) {
    let id = 'record-no-' + i;
    engine._store.items[id] = "Record No. " + i;
    engine._tracker.addChangedID(id, 0);
    collection.insert(id);
  }

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  try {

    // Confirm initial environment.
    do_check_eq(noOfUploads, 0);

    engine._syncStartup();
    engine._uploadOutgoing();

    // Ensure all records have been uploaded.
    for (i = 0; i < 234; i++) {
      do_check_true(!!collection.payload('record-no-' + i));
    }

    // Ensure that the uploads were performed in batches of MAX_UPLOAD_RECORDS.
    do_check_eq(noOfUploads, Math.ceil(234/MAX_UPLOAD_RECORDS));

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_syncFinish_noDelete() {
  _("SyncEngine._syncFinish resets tracker's score");

  let server = httpd_setup({});

  let syncTesting = new SyncTestingInfrastructure(server);
  let engine = makeRotaryEngine();
  engine._delete = {}; // Nothing to delete
  engine._tracker.score = 100;

  // _syncFinish() will reset the engine's score.
  engine._syncFinish();
  do_check_eq(engine.score, 0);
  server.stop(run_next_test);
});


add_test(function test_syncFinish_deleteByIds() {
  _("SyncEngine._syncFinish deletes server records slated for deletion (list of record IDs).");

  Service.identity.username = "foo";
  let collection = new ServerCollection();
  collection._wbos.flying = new ServerWBO(
      'flying', encryptPayload({id: 'flying',
                                denomination: "LNER Class A3 4472"}));
  collection._wbos.scotsman = new ServerWBO(
      'scotsman', encryptPayload({id: 'scotsman',
                                  denomination: "Flying Scotsman"}));
  collection._wbos.rekolok = new ServerWBO(
      'rekolok', encryptPayload({id: 'rekolok',
                                denomination: "Rekonstruktionslokomotive"}));

  let server = httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });
  let syncTesting = new SyncTestingInfrastructure(server);

  let engine = makeRotaryEngine();
  try {
    engine._delete = {ids: ['flying', 'rekolok']};
    engine._syncFinish();

    // The 'flying' and 'rekolok' records were deleted while the
    // 'scotsman' one wasn't.
    do_check_eq(collection.payload("flying"), undefined);
    do_check_true(!!collection.payload("scotsman"));
    do_check_eq(collection.payload("rekolok"), undefined);

    // The deletion todo list has been reset.
    do_check_eq(engine._delete.ids, undefined);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_syncFinish_deleteLotsInBatches() {
  _("SyncEngine._syncFinish deletes server records in batches of 100 (list of record IDs).");

  Service.identity.username = "foo";
  let collection = new ServerCollection();

  // Let's count how many times the client does a DELETE request to the server
  var noOfUploads = 0;
  collection.delete = (function(orig) {
    return function() {
      noOfUploads++;
      return orig.apply(this, arguments);
    };
  }(collection.delete));

  // Create a bunch of records on the server
  let now = Date.now();
  for (var i = 0; i < 234; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + i});
    let wbo = new ServerWBO(id, payload);
    wbo.modified = now / 1000 - 60 * (i + 110);
    collection.insertWBO(wbo);
  }

  let server = httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let engine = makeRotaryEngine();
  try {

    // Confirm initial environment
    do_check_eq(noOfUploads, 0);

    // Declare what we want to have deleted: all records no. 100 and
    // up and all records that are less than 200 mins old (which are
    // records 0 thru 90).
    engine._delete = {ids: [],
                      newer: now / 1000 - 60 * 200.5};
    for (i = 100; i < 234; i++) {
      engine._delete.ids.push('record-no-' + i);
    }

    engine._syncFinish();

    // Ensure that the appropriate server data has been wiped while
    // preserving records 90 thru 200.
    for (i = 0; i < 234; i++) {
      let id = 'record-no-' + i;
      if (i <= 90 || i >= 100) {
        do_check_eq(collection.payload(id), undefined);
      } else {
        do_check_true(!!collection.payload(id));
      }
    }

    // The deletion was done in batches
    do_check_eq(noOfUploads, 2 + 1);

    // The deletion todo list has been reset.
    do_check_eq(engine._delete.ids, undefined);

  } finally {
    cleanAndGo(server);
  }
});


add_test(function test_sync_partialUpload() {
  _("SyncEngine.sync() keeps changedIDs that couldn't be uploaded.");

  Service.identity.username = "foo";

  let collection = new ServerCollection();
  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });
  let syncTesting = new SyncTestingInfrastructure(server);
  generateNewKeys(Service.collectionKeys);

  let engine = makeRotaryEngine();
  engine.lastSync = 123; // needs to be non-zero so that tracker is queried
  engine.lastSyncLocal = 456;

  // Let the third upload fail completely
  var noOfUploads = 0;
  collection.post = (function(orig) {
    return function() {
      if (noOfUploads == 2)
        throw "FAIL!";
      noOfUploads++;
      return orig.apply(this, arguments);
    };
  }(collection.post));

  // Create a bunch of records (and server side handlers)
  for (let i = 0; i < 234; i++) {
    let id = 'record-no-' + i;
    engine._store.items[id] = "Record No. " + i;
    engine._tracker.addChangedID(id, i);
    // Let two items in the first upload batch fail.
    if ((i != 23) && (i != 42)) {
      collection.insert(id);
    }
  }

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  try {

    engine.enabled = true;
    let error;
    try {
      engine.sync();
    } catch (ex) {
      error = ex;
    }
    do_check_true(!!error);

    // The timestamp has been updated.
    do_check_true(engine.lastSyncLocal > 456);

    for (let i = 0; i < 234; i++) {
      let id = 'record-no-' + i;
      // Ensure failed records are back in the tracker:
      // * records no. 23 and 42 were rejected by the server,
      // * records no. 200 and higher couldn't be uploaded because we failed
      //   hard on the 3rd upload.
      if ((i == 23) || (i == 42) || (i >= 200))
        do_check_eq(engine._tracker.changedIDs[id], i);
      else
        do_check_false(id in engine._tracker.changedIDs);
    }

  } finally {
    cleanAndGo(server);
  }
});

add_test(function test_canDecrypt_noCryptoKeys() {
  _("SyncEngine.canDecrypt returns false if the engine fails to decrypt items on the server, e.g. due to a missing crypto key collection.");
  Service.identity.username = "foo";

  // Wipe collection keys so we can test the desired scenario.
  Service.collectionKeys.clear();

  let collection = new ServerCollection();
  collection._wbos.flying = new ServerWBO(
      'flying', encryptPayload({id: 'flying',
                                denomination: "LNER Class A3 4472"}));

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  let engine = makeRotaryEngine();
  try {

    do_check_false(engine.canDecrypt());

  } finally {
    cleanAndGo(server);
  }
});

add_test(function test_canDecrypt_true() {
  _("SyncEngine.canDecrypt returns true if the engine can decrypt the items on the server.");
  Service.identity.username = "foo";

  generateNewKeys(Service.collectionKeys);

  let collection = new ServerCollection();
  collection._wbos.flying = new ServerWBO(
      'flying', encryptPayload({id: 'flying',
                                denomination: "LNER Class A3 4472"}));

  let server = sync_httpd_setup({
      "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);
  let engine = makeRotaryEngine();
  try {

    do_check_true(engine.canDecrypt());

  } finally {
    cleanAndGo(server);
  }

});

add_test(function test_syncapplied_observer() {
  Service.identity.username = "foo";

  const NUMBER_OF_RECORDS = 10;

  let engine = makeRotaryEngine();

  // Create a batch of server side records.
  let collection = new ServerCollection();
  for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
    let id = 'record-no-' + i;
    let payload = encryptPayload({id: id, denomination: "Record No. " + id});
    collection.insert(id, payload);
  }

  let server = httpd_setup({
    "/1.1/foo/storage/rotary": collection.handler()
  });

  let syncTesting = new SyncTestingInfrastructure(server);

  let meta_global = Service.recordManager.set(engine.metaURL,
                                              new WBORecord(engine.metaURL));
  meta_global.payload.engines = {rotary: {version: engine.version,
                                         syncID: engine.syncID}};

  let numApplyCalls = 0;
  let engine_name;
  let count;
  function onApplied(subject, data) {
    numApplyCalls++;
    engine_name = data;
    count = subject;
  }

  Svc.Obs.add("weave:engine:sync:applied", onApplied);

  try {
    Service.scheduler.hasIncomingItems = false;

    // Do sync.
    engine._syncStartup();
    engine._processIncoming();

    do_check_attribute_count(engine._store.items, 10);

    do_check_eq(numApplyCalls, 1);
    do_check_eq(engine_name, "rotary");
    do_check_eq(count.applied, 10);

    do_check_true(Service.scheduler.hasIncomingItems);
  } finally {
    cleanAndGo(server);
    Service.scheduler.hasIncomingItems = false;
    Svc.Obs.remove("weave:engine:sync:applied", onApplied);
  }
});