summaryrefslogtreecommitdiffstats
path: root/toolkit/components/nimbus/test/browser/browser_remotesettingsexperimentloader_remote_defaults.js
blob: 1ba2718206bac14aaa0ea770b6cf6fc49aa723a6 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { RemoteSettings } = ChromeUtils.importESModule(
  "resource://services-settings/remote-settings.sys.mjs"
);
const {
  _ExperimentFeature: ExperimentFeature,

  ExperimentAPI,
} = ChromeUtils.importESModule("resource://nimbus/ExperimentAPI.sys.mjs");
const { ExperimentTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/NimbusTestUtils.sys.mjs"
);
const { ExperimentManager } = ChromeUtils.importESModule(
  "resource://nimbus/lib/ExperimentManager.sys.mjs"
);
const { RemoteSettingsExperimentLoader } = ChromeUtils.importESModule(
  "resource://nimbus/lib/RemoteSettingsExperimentLoader.sys.mjs"
);

const FOO_FAKE_FEATURE_MANIFEST = {
  isEarlyStartup: true,
  variables: {
    remoteValue: {
      type: "int",
    },
    enabled: {
      type: "boolean",
    },
  },
};

const BAR_FAKE_FEATURE_MANIFEST = {
  isEarlyStartup: true,
  variables: {
    remoteValue: {
      type: "int",
    },
    enabled: {
      type: "boolean",
    },
  },
};

const ENSURE_ENROLLMENT = {
  targeting: "true",
  bucketConfig: {
    namespace: "nimbus-test-utils",
    randomizationUnit: "normandy_id",
    start: 0,
    count: 1000,
    total: 1000,
  },
};

const REMOTE_CONFIGURATION_FOO = ExperimentFakes.recipe("foo-rollout", {
  isRollout: true,
  branches: [
    {
      slug: "foo-rollout-branch",
      ratio: 1,
      features: [
        {
          featureId: "foo",
          isEarlyStartup: true,
          value: { remoteValue: 42, enabled: true },
        },
      ],
    },
  ],
  ...ENSURE_ENROLLMENT,
});
const REMOTE_CONFIGURATION_BAR = ExperimentFakes.recipe("bar-rollout", {
  isRollout: true,
  branches: [
    {
      slug: "bar-rollout-branch",
      ratio: 1,
      features: [
        {
          featureId: "bar",
          isEarlyStartup: true,
          value: { remoteValue: 3, enabled: true },
        },
      ],
    },
  ],
  ...ENSURE_ENROLLMENT,
});

const SYNC_DEFAULTS_PREF_BRANCH = "nimbus.syncdefaultsstore.";

add_setup(function () {
  const client = RemoteSettings("nimbus-desktop-experiments");
  sinon.stub(client, "get").resolves([]);

  registerCleanupFunction(() => client.get.restore());
});

async function setup(configuration) {
  const client = RemoteSettings("nimbus-desktop-experiments");
  client.get.resolves(
    configuration ?? [REMOTE_CONFIGURATION_FOO, REMOTE_CONFIGURATION_BAR]
  );

  // Simulate a state where no experiment exists.
  const cleanup = () => client.get.resolves([]);
  return { client, cleanup };
}

add_task(async function test_remote_fetch_and_ready() {
  const fooInstance = new ExperimentFeature("foo", FOO_FAKE_FEATURE_MANIFEST);
  const barInstance = new ExperimentFeature("bar", BAR_FAKE_FEATURE_MANIFEST);

  const cleanupTestFeatures = ExperimentTestUtils.addTestFeatures(
    fooInstance,
    barInstance
  );

  const sandbox = sinon.createSandbox();
  const setExperimentActiveStub = sandbox.stub(
    TelemetryEnvironment,
    "setExperimentActive"
  );
  const setExperimentInactiveStub = sandbox.stub(
    TelemetryEnvironment,
    "setExperimentInactive"
  );

  Assert.equal(
    fooInstance.getVariable("remoteValue"),
    undefined,
    "This prop does not exist before we sync"
  );

  // Create to promises that get resolved when the features update
  // with the remote setting rollouts
  let fooUpdate = new Promise(resolve => fooInstance.onUpdate(resolve));
  let barUpdate = new Promise(resolve => barInstance.onUpdate(resolve));

  await ExperimentAPI.ready();

  let { cleanup } = await setup();

  // Fake being initialized so we can update recipes
  // we don't need to start any timers
  RemoteSettingsExperimentLoader._initialized = true;
  await RemoteSettingsExperimentLoader.updateRecipes(
    "browser_rsel_remote_defaults"
  );

  // We need to await here because remote configurations are processed
  // async to evaluate targeting
  await Promise.all([fooUpdate, barUpdate]);

  Assert.equal(
    fooInstance.getVariable("remoteValue"),
    REMOTE_CONFIGURATION_FOO.branches[0].features[0].value.remoteValue,
    "`foo` feature is set by remote defaults"
  );
  Assert.equal(
    barInstance.getVariable("remoteValue"),
    REMOTE_CONFIGURATION_BAR.branches[0].features[0].value.remoteValue,
    "`bar` feature is set by remote defaults"
  );

  Assert.ok(
    Services.prefs.getStringPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar`),
    "Pref cache is set"
  );

  // Check if we sent active experiment data for defaults
  Assert.equal(
    setExperimentActiveStub.callCount,
    2,
    "setExperimentActive called once per feature"
  );

  Assert.ok(
    setExperimentActiveStub.calledWith(
      REMOTE_CONFIGURATION_FOO.slug,
      REMOTE_CONFIGURATION_FOO.branches[0].slug,
      {
        type: "nimbus-rollout",
      }
    ),
    "should call setExperimentActive with `foo` feature"
  );
  Assert.ok(
    setExperimentActiveStub.calledWith(
      REMOTE_CONFIGURATION_BAR.slug,
      REMOTE_CONFIGURATION_BAR.branches[0].slug,
      {
        type: "nimbus-rollout",
      }
    ),
    "should call setExperimentActive with `bar` feature"
  );

  // Test Glean experiment API interaction
  Assert.equal(
    Services.fog.testGetExperimentData(REMOTE_CONFIGURATION_FOO.slug).branch,
    REMOTE_CONFIGURATION_FOO.branches[0].slug,
    "Glean.setExperimentActive called with `foo` feature"
  );
  Assert.equal(
    Services.fog.testGetExperimentData(REMOTE_CONFIGURATION_BAR.slug).branch,
    REMOTE_CONFIGURATION_BAR.branches[0].slug,
    "Glean.setExperimentActive called with `bar` feature"
  );

  Assert.equal(fooInstance.getVariable("remoteValue"), 42, "Has rollout value");
  Assert.equal(barInstance.getVariable("remoteValue"), 3, "Has rollout value");

  // Clear RS db and load again. No configurations so should clear the cache.
  await cleanup();
  await RemoteSettingsExperimentLoader.updateRecipes(
    "browser_rsel_remote_defaults"
  );

  Assert.ok(
    !fooInstance.getVariable("remoteValue"),
    "foo-rollout should be removed"
  );
  Assert.ok(
    !barInstance.getVariable("remoteValue"),
    "bar-rollout should be removed"
  );

  // Check if we sent active experiment data for defaults
  Assert.equal(
    setExperimentInactiveStub.callCount,
    2,
    "setExperimentInactive called once per feature"
  );

  Assert.ok(
    setExperimentInactiveStub.calledWith(REMOTE_CONFIGURATION_FOO.slug),
    "should call setExperimentInactive with `foo` feature"
  );
  Assert.ok(
    setExperimentInactiveStub.calledWith(REMOTE_CONFIGURATION_BAR.slug),
    "should call setExperimentInactive with `bar` feature"
  );

  Assert.ok(
    !Services.prefs.getStringPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar`, ""),
    "Should clear the pref"
  );
  Assert.ok(!barInstance.getVariable("remoteValue"), "Should be missing");

  ExperimentAPI._store._deleteForTests("foo");
  ExperimentAPI._store._deleteForTests("bar");
  ExperimentAPI._store._deleteForTests(REMOTE_CONFIGURATION_FOO.slug);
  ExperimentAPI._store._deleteForTests(REMOTE_CONFIGURATION_BAR.slug);
  sandbox.restore();

  cleanupTestFeatures();
  await cleanup();
});

add_task(async function test_remote_fetch_on_updateRecipes() {
  let sandbox = sinon.createSandbox();
  let updateRecipesStub = sandbox.stub(
    RemoteSettingsExperimentLoader,
    "updateRecipes"
  );
  // Work around the pref change callback that would trigger `setTimer`
  sandbox.replaceGetter(
    RemoteSettingsExperimentLoader,
    "intervalInSeconds",
    () => 1
  );

  // This will un-register the timer
  RemoteSettingsExperimentLoader._initialized = true;
  RemoteSettingsExperimentLoader.uninit();
  Services.prefs.clearUserPref(
    "app.update.lastUpdateTime.rs-experiment-loader-timer"
  );

  RemoteSettingsExperimentLoader.setTimer();

  await BrowserTestUtils.waitForCondition(
    () => updateRecipesStub.called,
    "Wait for timer to call"
  );

  Assert.ok(updateRecipesStub.calledOnce, "Timer calls function");
  Assert.equal(updateRecipesStub.firstCall.args[0], "timer", "Called by timer");
  sandbox.restore();
  // This will un-register the timer
  RemoteSettingsExperimentLoader._initialized = true;
  RemoteSettingsExperimentLoader.uninit();
  Services.prefs.clearUserPref(
    "app.update.lastUpdateTime.rs-experiment-loader-timer"
  );
});

add_task(async function test_finalizeRemoteConfigs_cleanup() {
  const featureFoo = new ExperimentFeature("foo", {
    description: "mochitests",
    variables: {
      foo: { type: "boolean" },
    },
  });
  const featureBar = new ExperimentFeature("bar", {
    description: "mochitests",
    variables: {
      bar: { type: "boolean" },
    },
  });

  const cleanupTestFeatures = ExperimentTestUtils.addTestFeatures(
    featureFoo,
    featureBar
  );

  let fooCleanup = await ExperimentFakes.enrollWithRollout(
    {
      featureId: "foo",
      isEarlyStartup: true,
      value: { foo: true },
    },
    {
      source: "rs-loader",
    }
  );
  await ExperimentFakes.enrollWithRollout(
    {
      featureId: "bar",
      isEarlyStartup: true,
      value: { bar: true },
    },
    {
      source: "rs-loader",
    }
  );
  let stubFoo = sinon.stub();
  let stubBar = sinon.stub();
  featureFoo.onUpdate(stubFoo);
  featureBar.onUpdate(stubBar);
  let cleanupPromise = new Promise(resolve => featureBar.onUpdate(resolve));

  // stubFoo and stubBar will be called because the store is ready. We are not interested in these calls.
  // Reset call history and check calls stats after cleanup.
  Assert.ok(
    stubFoo.called,
    "feature foo update triggered becuase store is ready"
  );
  Assert.ok(
    stubBar.called,
    "feature bar update triggered because store is ready"
  );
  stubFoo.resetHistory();
  stubBar.resetHistory();

  Services.prefs.setStringPref(
    `${SYNC_DEFAULTS_PREF_BRANCH}foo`,
    JSON.stringify({ foo: true, branch: { feature: { featureId: "foo" } } })
  );
  Services.prefs.setStringPref(
    `${SYNC_DEFAULTS_PREF_BRANCH}bar`,
    JSON.stringify({ bar: true, branch: { feature: { featureId: "bar" } } })
  );

  const remoteConfiguration = {
    ...REMOTE_CONFIGURATION_FOO,
    branches: [
      {
        ...REMOTE_CONFIGURATION_FOO.branches[0],
        features: [
          {
            ...REMOTE_CONFIGURATION_FOO.branches[0].features[0],
            value: {
              foo: true,
            },
          },
        ],
      },
    ],
  };

  const { cleanup } = await setup([remoteConfiguration]);
  RemoteSettingsExperimentLoader._initialized = true;
  await RemoteSettingsExperimentLoader.updateRecipes();
  await cleanupPromise;

  Assert.ok(
    stubFoo.notCalled,
    "Not called, not enrolling in rollout feature already exists"
  );
  Assert.ok(stubBar.called, "Called because no recipe is seen, cleanup");
  Assert.ok(
    Services.prefs.getStringPref(`${SYNC_DEFAULTS_PREF_BRANCH}foo`),
    "Pref is not cleared"
  );
  Assert.ok(
    !Services.prefs.getStringPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar`, ""),
    "Pref was cleared"
  );

  await fooCleanup();
  // This will also remove the inactive recipe from the store
  // the previous update (from recipe not seen code path)
  // only sets the recipe as inactive
  ExperimentAPI._store._deleteForTests("bar-rollout");
  ExperimentAPI._store._deleteForTests("foo-rollout");

  cleanupTestFeatures();
  cleanup();
});

// If the remote config data returned from the store is not modified
// this test should not throw
add_task(async function remote_defaults_no_mutation() {
  let sandbox = sinon.createSandbox();
  sandbox.stub(ExperimentAPI._store, "getRolloutForFeature").returns(
    Cu.cloneInto(
      {
        featureIds: ["foo"],
        branch: {
          features: [{ featureId: "foo", value: { remoteStub: true } }],
        },
      },
      {},
      { deepFreeze: true }
    )
  );

  let fooInstance = new ExperimentFeature("foo", FOO_FAKE_FEATURE_MANIFEST);
  let config = fooInstance.getAllVariables();

  Assert.ok(config.remoteStub, "Got back the expected value");

  sandbox.restore();
});

add_task(async function remote_defaults_active_remote_defaults() {
  ExperimentAPI._store._deleteForTests("foo");
  ExperimentAPI._store._deleteForTests("bar");
  let barFeature = new ExperimentFeature("bar", {
    description: "mochitest",
    variables: { enabled: { type: "boolean" } },
  });
  let fooFeature = new ExperimentFeature("foo", {
    description: "mochitest",
    variables: { enabled: { type: "boolean" } },
  });

  const cleanupTestFeatures = ExperimentTestUtils.addTestFeatures(
    barFeature,
    fooFeature
  );

  let rollout1 = ExperimentFakes.recipe("bar", {
    branches: [
      {
        slug: "bar-rollout-branch",
        ratio: 1,
        features: [
          {
            featureId: "bar",
            value: { enabled: true },
          },
        ],
      },
    ],
    isRollout: true,
    ...ENSURE_ENROLLMENT,
    targeting: "true",
  });

  let rollout2 = ExperimentFakes.recipe("foo", {
    branches: [
      {
        slug: "foo-rollout-branch",
        ratio: 1,
        features: [
          {
            featureId: "foo",
            value: { enabled: true },
          },
        ],
      },
    ],
    isRollout: true,
    ...ENSURE_ENROLLMENT,
    targeting: "'bar' in activeRollouts",
  });

  // Order is important, rollout2 won't match at first
  const { cleanup } = await setup([rollout2, rollout1]);
  let updatePromise = new Promise(resolve => barFeature.onUpdate(resolve));
  RemoteSettingsExperimentLoader._initialized = true;
  await RemoteSettingsExperimentLoader.updateRecipes("mochitest");

  await updatePromise;

  Assert.ok(barFeature.getVariable("enabled"), "Enabled on first sync");
  Assert.ok(!fooFeature.getVariable("enabled"), "Targeting doesn't match");

  let featureUpdate = new Promise(resolve => fooFeature.onUpdate(resolve));
  await RemoteSettingsExperimentLoader.updateRecipes("mochitest");
  await featureUpdate;

  Assert.ok(fooFeature.getVariable("enabled"), "Targeting should match");
  ExperimentAPI._store._deleteForTests("foo");
  ExperimentAPI._store._deleteForTests("bar");

  cleanup();
  cleanupTestFeatures();
});

add_task(async function remote_defaults_variables_storage() {
  let barFeature = new ExperimentFeature("bar", {
    description: "mochitest",
    variables: {
      enabled: {
        type: "boolean",
      },
      storage: {
        type: "int",
      },
      object: {
        type: "json",
      },
      string: {
        type: "string",
      },
      bool: {
        type: "boolean",
      },
    },
  });
  let rolloutValue = {
    storage: 42,
    object: { foo: "foo" },
    string: "string",
    bool: true,
    enabled: true,
  };

  let doCleanup = await ExperimentFakes.enrollWithRollout({
    featureId: "bar",
    isEarlyStartup: true,
    value: rolloutValue,
  });

  Assert.ok(
    Services.prefs.getStringPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar`, ""),
    "Experiment stored in prefs"
  );
  Assert.ok(
    Services.prefs.getIntPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar.storage`, 0),
    "Stores variable in separate pref"
  );
  Assert.equal(
    Services.prefs.getIntPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar.storage`, 0),
    42,
    "Stores variable in correct type"
  );
  Assert.deepEqual(
    barFeature.getAllVariables(),
    rolloutValue,
    "Test types are returned correctly"
  );

  await doCleanup();

  Assert.equal(
    Services.prefs.getIntPref(`${SYNC_DEFAULTS_PREF_BRANCH}bar.storage`, -1),
    -1,
    "Variable pref is cleared"
  );
  Assert.ok(!barFeature.getVariable("string"), "Variable is no longer defined");
  ExperimentAPI._store._deleteForTests("bar");
  ExperimentAPI._store._deleteForTests("bar-rollout");
});