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

const { Service } = ChromeUtils.import("resource://services-sync/service.js");
const { HistoryEngine } = ChromeUtils.import(
  "resource://services-sync/engines/history.js"
);

// Use only for rawAddVisit.
XPCOMUtils.defineLazyServiceGetter(
  this,
  "asyncHistory",
  "@mozilla.org/browser/history;1",
  "mozIAsyncHistory"
);
async function rawAddVisit(id, uri, visitPRTime, transitionType) {
  return new Promise((resolve, reject) => {
    let results = [];
    let handler = {
      handleResult(result) {
        results.push(result);
      },
      handleError(resultCode, placeInfo) {
        do_throw(`updatePlaces gave error ${resultCode}!`);
      },
      handleCompletion(count) {
        resolve({ results, count });
      },
    };
    asyncHistory.updatePlaces(
      [
        {
          guid: id,
          uri: typeof uri == "string" ? CommonUtils.makeURI(uri) : uri,
          visits: [{ visitDate: visitPRTime, transitionType }],
        },
      ],
      handler
    );
  });
}

add_task(async function test_history_download_limit() {
  let engine = new HistoryEngine(Service);
  await engine.initialize();

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  let lastSync = new_timestamp();

  let collection = server.user("foo").collection("history");
  for (let i = 0; i < 15; i++) {
    let id = "place" + i.toString(10).padStart(7, "0");
    let wbo = new ServerWBO(
      id,
      encryptPayload({
        id,
        histUri: "http://example.com/" + i,
        title: "Page " + i,
        visits: [
          {
            date: Date.now() * 1000,
            type: PlacesUtils.history.TRANSITIONS.TYPED,
          },
          {
            date: Date.now() * 1000,
            type: PlacesUtils.history.TRANSITIONS.LINK,
          },
        ],
      }),
      lastSync + 1 + i
    );
    wbo.sortindex = 15 - i;
    collection.insertWBO(wbo);
  }

  // We have 15 records on the server since the last sync, but our download
  // limit is 5 records at a time. We should eventually fetch all 15.
  await engine.setLastSync(lastSync);
  engine.downloadBatchSize = 4;
  engine.downloadLimit = 5;

  // Don't actually fetch any backlogged records, so that we can inspect
  // the backlog between syncs.
  engine.guidFetchBatchSize = 0;

  let ping = await sync_engine_and_validate_telem(engine, false);
  deepEqual(ping.engines[0].incoming, { applied: 5 });

  let backlogAfterFirstSync = Array.from(engine.toFetch).sort();
  deepEqual(backlogAfterFirstSync, [
    "place0000000",
    "place0000001",
    "place0000002",
    "place0000003",
    "place0000004",
    "place0000005",
    "place0000006",
    "place0000007",
    "place0000008",
    "place0000009",
  ]);

  // We should have fast-forwarded the last sync time.
  equal(await engine.getLastSync(), lastSync + 15);

  engine.lastModified = collection.modified;
  ping = await sync_engine_and_validate_telem(engine, false);
  ok(!ping.engines[0].incoming);

  // After the second sync, our backlog still contains the same GUIDs: we
  // weren't able to make progress on fetching them, since our
  // `guidFetchBatchSize` is 0.
  let backlogAfterSecondSync = Array.from(engine.toFetch).sort();
  deepEqual(backlogAfterFirstSync, backlogAfterSecondSync);

  // Now add a newer record to the server.
  let newWBO = new ServerWBO(
    "placeAAAAAAA",
    encryptPayload({
      id: "placeAAAAAAA",
      histUri: "http://example.com/a",
      title: "New Page A",
      visits: [
        {
          date: Date.now() * 1000,
          type: PlacesUtils.history.TRANSITIONS.TYPED,
        },
      ],
    }),
    lastSync + 20
  );
  newWBO.sortindex = -1;
  collection.insertWBO(newWBO);

  engine.lastModified = collection.modified;
  ping = await sync_engine_and_validate_telem(engine, false);
  deepEqual(ping.engines[0].incoming, { applied: 1 });

  // Our backlog should remain the same.
  let backlogAfterThirdSync = Array.from(engine.toFetch).sort();
  deepEqual(backlogAfterSecondSync, backlogAfterThirdSync);

  equal(await engine.getLastSync(), lastSync + 20);

  // Bump the fetch batch size to let the backlog make progress. We should
  // make 3 requests to fetch 5 backlogged GUIDs.
  engine.guidFetchBatchSize = 2;

  engine.lastModified = collection.modified;
  ping = await sync_engine_and_validate_telem(engine, false);
  deepEqual(ping.engines[0].incoming, { applied: 5 });

  deepEqual(Array.from(engine.toFetch).sort(), [
    "place0000005",
    "place0000006",
    "place0000007",
    "place0000008",
    "place0000009",
  ]);

  // Sync again to clear out the backlog.
  engine.lastModified = collection.modified;
  ping = await sync_engine_and_validate_telem(engine, false);
  deepEqual(ping.engines[0].incoming, { applied: 5 });

  deepEqual(Array.from(engine.toFetch), []);

  await engine.wipeClient();
  await engine.finalize();
});

add_task(async function test_history_visit_roundtrip() {
  let engine = new HistoryEngine(Service);
  await engine.initialize();
  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  engine._tracker.start();

  let id = "aaaaaaaaaaaa";
  let oneHourMS = 60 * 60 * 1000;
  // Insert a visit with a non-round microsecond timestamp (e.g. it's not evenly
  // divisible by 1000). This will typically be the case for visits that occur
  // during normal navigation.
  let time = (Date.now() - oneHourMS) * 1000 + 555;
  // We use the low level history api since it lets us provide microseconds
  let { count } = await rawAddVisit(
    id,
    "https://www.example.com",
    time,
    PlacesUtils.history.TRANSITIONS.TYPED
  );
  equal(count, 1);
  // Check that it was inserted and that we didn't round on the insert.
  let visits = await PlacesSyncUtils.history.fetchVisitsForURL(
    "https://www.example.com"
  );
  equal(visits.length, 1);
  equal(visits[0].date, time);

  let collection = server.user("foo").collection("history");

  // Sync the visit up to the server.
  await sync_engine_and_validate_telem(engine, false);

  collection.updateRecord(
    id,
    cleartext => {
      // Double-check that we didn't round the visit's timestamp to the nearest
      // millisecond when uploading.
      equal(cleartext.visits[0].date, time);
      // Add a remote visit so that we get past the deepEquals check in reconcile
      // (otherwise the history engine will skip applying this record). The
      // contents of this visit don't matter, beyond the fact that it needs to
      // exist.
      cleartext.visits.push({
        date: (Date.now() - oneHourMS / 2) * 1000,
        type: PlacesUtils.history.TRANSITIONS.LINK,
      });
    },
    new_timestamp() + 10
  );

  // Force a remote sync.
  await engine.setLastSync(new_timestamp() - 30);
  await sync_engine_and_validate_telem(engine, false);

  // Make sure that we didn't duplicate the visit when inserting. (Prior to bug
  // 1423395, we would insert a duplicate visit, where the timestamp was
  // effectively `Math.round(microsecondTimestamp / 1000) * 1000`.)
  visits = await PlacesSyncUtils.history.fetchVisitsForURL(
    "https://www.example.com"
  );
  equal(visits.length, 2);

  await engine.wipeClient();
  await engine.finalize();
});

add_task(async function test_history_visit_dedupe_old() {
  let engine = new HistoryEngine(Service);
  await engine.initialize();
  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  let initialVisits = Array.from({ length: 25 }, (_, index) => ({
    transition: PlacesUtils.history.TRANSITION_LINK,
    date: new Date(Date.UTC(2017, 10, 1 + index)),
  }));
  initialVisits.push({
    transition: PlacesUtils.history.TRANSITION_LINK,
    date: new Date(),
  });
  await PlacesUtils.history.insert({
    url: "https://www.example.com",
    visits: initialVisits,
  });

  let recentVisits = await PlacesSyncUtils.history.fetchVisitsForURL(
    "https://www.example.com"
  );
  equal(recentVisits.length, 20);
  let { visits: allVisits, guid } = await PlacesUtils.history.fetch(
    "https://www.example.com",
    {
      includeVisits: true,
    }
  );
  equal(allVisits.length, 26);

  let collection = server.user("foo").collection("history");

  await sync_engine_and_validate_telem(engine, false);

  collection.updateRecord(
    guid,
    data => {
      data.visits.push(
        // Add a couple remote visit equivalent to some old visits we have already
        {
          date: Date.UTC(2017, 10, 1) * 1000, // Nov 1, 2017
          type: PlacesUtils.history.TRANSITIONS.LINK,
        },
        {
          date: Date.UTC(2017, 10, 2) * 1000, // Nov 2, 2017
          type: PlacesUtils.history.TRANSITIONS.LINK,
        },
        // Add a couple new visits to make sure we are still applying them.
        {
          date: Date.UTC(2017, 11, 4) * 1000, // Dec 4, 2017
          type: PlacesUtils.history.TRANSITIONS.LINK,
        },
        {
          date: Date.UTC(2017, 11, 5) * 1000, // Dec 5, 2017
          type: PlacesUtils.history.TRANSITIONS.LINK,
        }
      );
    },
    new_timestamp() + 10
  );

  await engine.setLastSync(new_timestamp() - 30);
  await sync_engine_and_validate_telem(engine, false);

  allVisits = (
    await PlacesUtils.history.fetch("https://www.example.com", {
      includeVisits: true,
    })
  ).visits;

  equal(allVisits.length, 28);
  ok(
    allVisits.find(x => x.date.getTime() === Date.UTC(2017, 11, 4)),
    "Should contain the Dec. 4th visit"
  );
  ok(
    allVisits.find(x => x.date.getTime() === Date.UTC(2017, 11, 5)),
    "Should contain the Dec. 5th visit"
  );

  await engine.wipeClient();
  await engine.finalize();
});