summaryrefslogtreecommitdiffstats
path: root/browser/components/search/test/browser/telemetry/head.js
blob: 416451e400a0d31f84bcd664e8f756a27ff7940c (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

ChromeUtils.defineESModuleGetters(this, {
  ADLINK_CHECK_TIMEOUT_MS:
    "resource:///actors/SearchSERPTelemetryChild.sys.mjs",
  CustomizableUITestUtils:
    "resource://testing-common/CustomizableUITestUtils.sys.mjs",
  Region: "resource://gre/modules/Region.sys.mjs",
  RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
  SEARCH_TELEMETRY_SHARED: "resource:///modules/SearchSERPTelemetry.sys.mjs",
  SearchSERPTelemetry: "resource:///modules/SearchSERPTelemetry.sys.mjs",
  SearchSERPTelemetryUtils: "resource:///modules/SearchSERPTelemetry.sys.mjs",
  SearchTestUtils: "resource://testing-common/SearchTestUtils.sys.mjs",
  SearchUtils: "resource://gre/modules/SearchUtils.sys.mjs",
  SERPCategorizationRecorder: "resource:///modules/SearchSERPTelemetry.sys.mjs",
  sinon: "resource://testing-common/Sinon.sys.mjs",
  SPA_ADLINK_CHECK_TIMEOUT_MS:
    "resource:///modules/SearchSERPTelemetry.sys.mjs",
  TELEMETRY_CATEGORIZATION_KEY:
    "resource:///modules/SearchSERPTelemetry.sys.mjs",
  TelemetryTestUtils: "resource://testing-common/TelemetryTestUtils.sys.mjs",
});

ChromeUtils.defineLazyGetter(this, "UrlbarTestUtils", () => {
  const { UrlbarTestUtils: module } = ChromeUtils.importESModule(
    "resource://testing-common/UrlbarTestUtils.sys.mjs"
  );
  module.init(this);
  return module;
});

ChromeUtils.defineLazyGetter(this, "searchCounts", () => {
  return Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
});

ChromeUtils.defineLazyGetter(this, "SEARCH_AD_CLICK_SCALARS", () => {
  const sources = [
    ...BrowserSearchTelemetry.KNOWN_SEARCH_SOURCES.values(),
    "unknown",
  ];
  return [
    ...sources.map(v => `browser.search.withads.${v}`),
    ...sources.map(v => `browser.search.adclicks.${v}`),
  ];
});

// For use with categorization.
const APP_MAJOR_VERSION = parseInt(Services.appinfo.version).toString();
const CHANNEL = SearchUtils.MODIFIED_APP_CHANNEL;
const REGION = Region.home;

let gCUITestUtils = new CustomizableUITestUtils(window);

SearchTestUtils.init(this);

const UUID_REGEX =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

// sharedData messages are only passed to the child on idle. Therefore
// we wait for a few idles to try and ensure the messages have been able
// to be passed across and handled.
async function waitForIdle() {
  for (let i = 0; i < 10; i++) {
    await new Promise(resolve => Services.tm.idleDispatchToMainThread(resolve));
  }
}

function getPageUrl(useAdPage = false) {
  let page = useAdPage ? "searchTelemetryAd.html" : "searchTelemetry.html";
  return `https://example.org/browser/browser/components/search/test/browser/telemetry/${page}`;
}

function getSERPUrl(page, organic = false) {
  let url =
    getRootDirectory(gTestPath).replace(
      "chrome://mochitests/content",
      "https://example.org"
    ) + page;
  return `${url}?s=test${organic ? "" : "&abc=ff"}`;
}

async function typeInSearchField(browser, text, fieldName) {
  await SpecialPowers.spawn(
    browser,
    [[fieldName, text]],
    async function ([contentFieldName, contentText]) {
      // Put the focus on the search box.
      let searchInput = content.document.getElementById(contentFieldName);
      searchInput.focus();
      searchInput.value = contentText;
    }
  );
}

async function searchInSearchbar(inputText, win = window) {
  await new Promise(r => waitForFocus(r, win));
  let sb = win.BrowserSearch.searchBar;
  // Write the search query in the searchbar.
  sb.focus();
  sb.value = inputText;
  sb.textbox.controller.startSearch(inputText);
  // Wait for the popup to show.
  await BrowserTestUtils.waitForEvent(sb.textbox.popup, "popupshown");
  // And then for the search to complete.
  await TestUtils.waitForCondition(
    () =>
      sb.textbox.controller.searchStatus >=
      Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH,
    "The search in the searchbar must complete."
  );
  return sb.textbox.popup;
}

// Ad links are processed after a small delay. We need to allow tests to wait
// for that before checking telemetry, otherwise the received values may be
// too small in some cases.
function promiseWaitForAdLinkCheck() {
  return new Promise(resolve =>
    /* eslint-disable-next-line mozilla/no-arbitrary-setTimeout */
    setTimeout(resolve, ADLINK_CHECK_TIMEOUT_MS)
  );
}

async function assertSearchSourcesTelemetry(
  expectedHistograms,
  expectedScalars
) {
  let histSnapshot = {};
  let scalars = {};

  // This used to rely on the implied 100ms initial timer of
  // TestUtils.waitForCondition. See bug 1515466.
  await new Promise(resolve => setTimeout(resolve, 100));

  await TestUtils.waitForCondition(() => {
    histSnapshot = searchCounts.snapshot();
    return (
      Object.getOwnPropertyNames(histSnapshot).length ==
      Object.getOwnPropertyNames(expectedHistograms).length
    );
  }, "should have the correct number of histograms");

  if (Object.entries(expectedScalars).length) {
    await TestUtils.waitForCondition(() => {
      scalars =
        Services.telemetry.getSnapshotForKeyedScalars("main", false).parent ||
        {};
      return Object.getOwnPropertyNames(expectedScalars).every(
        scalar => scalar in scalars
      );
    }, "should have the expected keyed scalars");
  }

  Assert.equal(
    Object.getOwnPropertyNames(histSnapshot).length,
    Object.getOwnPropertyNames(expectedHistograms).length,
    "Should only have one key"
  );

  for (let [key, value] of Object.entries(expectedHistograms)) {
    Assert.ok(
      key in histSnapshot,
      `Histogram should have the expected key: ${key}`
    );
    Assert.equal(
      histSnapshot[key].sum,
      value,
      `Should have counted the correct number of visits for ${key}`
    );
  }

  for (let [name, value] of Object.entries(expectedScalars)) {
    Assert.ok(name in scalars, `Scalar ${name} should have been added.`);
    Assert.deepEqual(
      scalars[name],
      value,
      `Should have counted the correct number of visits for ${name}`
    );
  }

  for (let name of SEARCH_AD_CLICK_SCALARS) {
    Assert.equal(
      name in scalars,
      name in expectedScalars,
      `Should have matched ${name} in scalars and expectedScalars`
    );
  }
}

function resetTelemetry() {
  // TODO Bug 1868476: Replace when we're using Glean telemetry.
  fakeTelemetryStorage = [];
  searchCounts.clear();
  Services.telemetry.clearScalars();
  Services.fog.testResetFOG();
}

/**
 * First checks that we get the correct number of recorded Glean impression events
 * and the recorded Glean impression events have the correct keys and values.
 *
 * Then it checks that there are the the correct engagement events associated with the
 * impression events.
 *
 * @param {Array} expectedEvents The expected impression events whose keys and
 * values we use to validate the recorded Glean impression events.
 */
function assertSERPTelemetry(expectedEvents) {
  // A single test might run assertImpressionEvents more than once
  // so the Set needs to be cleared or else the impression event
  // check will throw.
  const impressionIdsSet = new Set();

  let recordedImpressions = Glean.serp.impression.testGetValue() ?? [];

  Assert.equal(
    recordedImpressions.length,
    expectedEvents.length,
    "Number of impressions matches expected events."
  );

  // Assert the impression events.
  for (let [idx, expectedEvent] of expectedEvents.entries()) {
    let impressionId = recordedImpressions[idx].extra.impression_id;
    Assert.ok(
      UUID_REGEX.test(impressionId),
      "Impression has an impression_id with a valid UUID."
    );

    Assert.ok(
      !impressionIdsSet.has(impressionId),
      "Impression has a unique impression_id."
    );

    impressionIdsSet.add(impressionId);

    // If we want to use deepEqual checks, we have to add the impressionId
    // to each impression since they are randomly generated at runtime.
    expectedEvent.impression.impression_id = impressionId;

    Assert.deepEqual(
      recordedImpressions[idx].extra,
      expectedEvent.impression,
      "Matching SERP impression values."
    );

    // Once the impression check is sufficient, add the impression_id to
    // each of the expected engagements, ad impressions, and abandonments for
    // deep equal checks.
    if (expectedEvent.engagements) {
      for (let expectedEngagment of expectedEvent.engagements) {
        expectedEngagment.impression_id = impressionId;
      }
    }
    if (expectedEvent.adImpressions) {
      for (let adImpression of expectedEvent.adImpressions) {
        adImpression.impression_id = impressionId;
      }
    }
    if (expectedEvent.abandonment) {
      expectedEvent.abandonment.impression_id = impressionId;
    }
  }

  // Group engagement events into separate array fetchable by their
  // impression_id.
  let recordedEngagements = Glean.serp.engagement.testGetValue() ?? [];
  let idToEngagements = new Map();
  let totalExpectedEngagements = 0;

  for (let recordedEngagement of recordedEngagements) {
    let impressionId = recordedEngagement.extra.impression_id;
    Assert.ok(impressionId, "Engagement event has impression_id.");

    let arr = idToEngagements.get(impressionId) ?? [];
    arr.push(recordedEngagement.extra);

    idToEngagements.set(impressionId, arr);
  }

  // Assert the engagement events.
  for (let expectedEvent of expectedEvents) {
    let impressionId = expectedEvent.impression.impression_id;
    let expectedEngagements = expectedEvent.engagements;
    if (expectedEngagements) {
      let recorded = idToEngagements.get(impressionId);
      Assert.deepEqual(
        recorded,
        expectedEngagements,
        "Matching engagement value."
      );
      totalExpectedEngagements += expectedEngagements.length;
    }
  }

  Assert.equal(
    recordedEngagements.length,
    totalExpectedEngagements,
    "Number of engagements"
  );

  let recordedAdImpressions = Glean.serp.adImpression.testGetValue() ?? [];
  let idToAdImpressions = new Map();
  let totalExpectedAdImpressions = 0;

  // The list of ad impressions are contained in a flat list. Separate them
  // into arrays organized by impressionId to make it easier to determine if
  // the page load that matches the expected ads on the page.
  for (let recordedAdImpression of recordedAdImpressions) {
    let impressionId = recordedAdImpression.extra.impression_id;
    Assert.ok(impressionId, "Ad impression has impression_id");

    let arr = idToAdImpressions.get(impressionId) ?? [];
    arr.push(recordedAdImpression.extra);
    idToAdImpressions.set(impressionId, arr);
  }

  for (let expectedEvent of expectedEvents) {
    let impressionId = expectedEvent.impression.impression_id;
    let expectedAdImpressions = expectedEvent.adImpressions ?? [];
    if (expectedAdImpressions.length) {
      let recorded = idToAdImpressions.get(impressionId) ?? {};
      Assert.deepEqual(
        recorded,
        expectedAdImpressions,
        "Matching ad impression value."
      );
    }
    totalExpectedAdImpressions += expectedAdImpressions.length;
  }

  Assert.equal(
    recordedAdImpressions.length,
    totalExpectedAdImpressions,
    "Recorded and expected ad impression counts match."
  );

  // Assert abandonment events.
  let recordedAbandonments = Glean.serp.abandonment.testGetValue() ?? [];
  let idTorecordedAbandonments = new Map();
  let totalExpectedrecordedAbandonments = 0;

  for (let recordedAbandonment of recordedAbandonments) {
    let impressionId = recordedAbandonment.extra.impression_id;
    Assert.ok(impressionId, "Abandonment event has an impression_id.");
    idTorecordedAbandonments.set(impressionId, recordedAbandonment.extra);
  }

  for (let expectedEvent of expectedEvents) {
    let impressionId = expectedEvent.impression.impression_id;
    let expectedAbandonment = expectedEvent.abandonment;
    if (expectedAbandonment) {
      let recorded = idTorecordedAbandonments.get(impressionId);
      Assert.deepEqual(
        recorded,
        expectedAbandonment,
        "Matching abandonment value."
      );
    }
    totalExpectedrecordedAbandonments += expectedAbandonment ? 1 : 0;
  }

  Assert.equal(
    recordedAbandonments.length,
    totalExpectedrecordedAbandonments,
    "Recorded and expected abandonment counts match."
  );
}

// TODO Bug 1868476: Replace when we're using Glean telemetry.
let categorizationSandbox;
let fakeTelemetryStorage = [];
add_setup(function () {
  categorizationSandbox = sinon.createSandbox();
  categorizationSandbox
    .stub(SERPCategorizationRecorder, "recordCategorizationTelemetry")
    .callsFake(input => {
      fakeTelemetryStorage.push(input);
    });

  registerCleanupFunction(() => {
    categorizationSandbox.restore();
    fakeTelemetryStorage = [];
  });
});

function assertCategorizationValues(expectedResults) {
  // TODO Bug 1868476: Replace with calls to Glean telemetry.
  let actualResults = [...fakeTelemetryStorage];

  Assert.equal(
    expectedResults.length,
    actualResults.length,
    "Should have the correct number of categorization impressions."
  );

  if (!expectedResults.length) {
    return;
  }

  // We use keys in the result vs. Assert.deepEqual to make it easier to
  // identify exact discrepancies in comparisons, because it can be tedious to
  // parse a giant list of values.
  let keys = new Set();
  for (let expected of expectedResults) {
    for (let key in expected) {
      keys.add(key);
    }
  }
  for (let actual of actualResults) {
    for (let key in actual) {
      keys.add(key);
    }
  }
  keys = Array.from(keys);

  for (let index = 0; index < expectedResults.length; ++index) {
    info(`Checking categorization at index: ${index}`);
    let expected = expectedResults[index];
    let actual = actualResults[index];
    for (let key of keys) {
      // TODO Bug 1868476: This conversion to strings is to mimic Glean
      // converting all values into strings. Once we receive real values from
      // Glean, it can be removed.
      if (actual[key] != null && typeof actual[key] !== "string") {
        actual[key] = actual[key].toString();
      }
      Assert.equal(
        actual[key],
        expected[key],
        `Actual and expected values for ${key} should match.`
      );
    }
  }
}

function waitForPageWithAdImpressions() {
  return TestUtils.topicObserved("reported-page-with-ad-impressions");
}

function waitForPageWithCategorizedDomains() {
  return TestUtils.topicObserved("reported-page-with-categorized-domains");
}

function waitForSingleCategorizedEvent() {
  return TestUtils.topicObserved("recorded-single-categorization-event");
}

function waitForAllCategorizedEvents() {
  return TestUtils.topicObserved("recorded-all-categorization-events");
}

function waitForDomainToCategoriesUpdate() {
  return TestUtils.topicObserved("domain-to-categories-map-update-complete");
}

registerCleanupFunction(async () => {
  await PlacesUtils.history.clear();
});

async function mockRecordWithAttachment({ id, version, filename }) {
  // Get the bytes of the file for the hash and size for attachment metadata.
  let data = await IOUtils.readUTF8(getTestFilePath(filename));
  let buffer = new TextEncoder().encode(data).buffer;
  let stream = Cc["@mozilla.org/io/arraybuffer-input-stream;1"].createInstance(
    Ci.nsIArrayBufferInputStream
  );
  stream.setData(buffer, 0, buffer.byteLength);

  // Generate a hash.
  let hasher = Cc["@mozilla.org/security/hash;1"].createInstance(
    Ci.nsICryptoHash
  );
  hasher.init(Ci.nsICryptoHash.SHA256);
  hasher.updateFromStream(stream, -1);
  let hash = hasher.finish(false);
  hash = Array.from(hash, (_, i) =>
    ("0" + hash.charCodeAt(i).toString(16)).slice(-2)
  ).join("");

  let record = {
    id,
    version,
    attachment: {
      hash,
      location: `main-workspace/search-categorization/${filename}`,
      filename,
      size: buffer.byteLength,
      mimetype: "application/json",
    },
  };

  let attachment = {
    record,
    blob: new Blob([buffer]),
  };

  return { record, attachment };
}

async function resetCategorizationCollection(record) {
  const client = RemoteSettings(TELEMETRY_CATEGORIZATION_KEY);
  await client.attachments.cacheImpl.delete(record.id);
  await client.db.clear();
  await client.db.importChanges({}, Date.now());
}

async function insertRecordIntoCollection() {
  const client = RemoteSettings(TELEMETRY_CATEGORIZATION_KEY);
  const db = client.db;

  await db.clear();
  let { record, attachment } = await mockRecordWithAttachment({
    id: "example_id",
    version: 1,
    filename: "domain_category_mappings.json",
  });
  await db.create(record);
  await client.attachments.cacheImpl.set(record.id, attachment);
  await db.importChanges({}, Date.now());

  return { record, attachment };
}

async function insertRecordIntoCollectionAndSync() {
  let { record } = await insertRecordIntoCollection();

  registerCleanupFunction(async () => {
    await resetCategorizationCollection(record);
  });

  await syncCollection(record);
}

async function syncCollection(record) {
  let arrayWithRecord = record ? [record] : [];
  await RemoteSettings(TELEMETRY_CATEGORIZATION_KEY).emit("sync", {
    data: {
      current: arrayWithRecord,
      created: arrayWithRecord,
      updated: [],
      deleted: [],
    },
  });
}

async function initSinglePageAppTest() {
  /* import-globals-from head-spa.js */
  Services.scriptloader.loadSubScript(
    "chrome://mochitests/content/browser/browser/components/search/test/browser/telemetry/head-spa.js",
    this
  );

  const BASE_PROVIDER = {
    telemetryId: "example1",
    searchPageRegexp:
      /^https:\/\/example.org\/browser\/browser\/components\/search\/test\/browser\/telemetry\/searchTelemetrySinglePageApp/,
    queryParamNames: ["s"],
    codeParamName: "abc",
    taggedCodes: ["ff"],
    adServerAttributes: ["mozAttr"],
    extraAdServersRegexps: [
      /^https:\/\/example\.com\/ad/,
      /^https:\/\/example.org\/browser\/browser\/components\/search\/test\/browser\/telemetry\/redirect_ad/,
    ],
    components: [
      {
        included: {
          parent: {
            selector: "#searchbox-container",
          },
          related: {
            selector: "#searchbox-suggestions",
          },
          children: [
            {
              selector: "#searchbox",
            },
          ],
        },
        topDown: true,
        type: SearchSERPTelemetryUtils.COMPONENTS.INCONTENT_SEARCHBOX,
      },
      {
        type: SearchSERPTelemetryUtils.COMPONENTS.AD_LINK,
        default: true,
      },
    ],
    isSPA: true,
    defaultPageQueryParam: {
      key: "page",
      value: "web",
    },
  };

  const SPA_PROVIDER_INFO = [
    BASE_PROVIDER,
    {
      ...BASE_PROVIDER,
      telemetryId: "example2",
      // Use example.com instead of example.org so that we have two providers
      // with different TLD's and won't share the same web process.
      searchPageRegexp:
        /^https:\/\/example.com\/browser\/browser\/components\/search\/test\/browser\/telemetry\/searchTelemetrySinglePageApp/,
    },
  ];

  SearchSERPTelemetry.overrideSearchTelemetryForTests(SPA_PROVIDER_INFO);
  await waitForIdle();

  // Shorten delay to avoid potential TV timeouts.
  Services.ppmm.sharedData.set(SEARCH_TELEMETRY_SHARED.SPA_LOAD_TIMEOUT, 100);

  registerCleanupFunction(function () {
    Services.ppmm.sharedData.set(
      SEARCH_TELEMETRY_SHARED.SPA_LOAD_TIMEOUT,
      SPA_ADLINK_CHECK_TIMEOUT_MS
    );
  });
}