summaryrefslogtreecommitdiffstats
path: root/browser/modules/test/browser/browser_TabUnloader.js
blob: a4af0dbdc8a203beeb842a0d0082771f7fa55034 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

const { TabUnloader } = ChromeUtils.import(
  "resource:///modules/TabUnloader.jsm"
);

const BASE_URL = "https://example.com/browser/browser/modules/test/browser/";

async function play(tab) {
  let browser = tab.linkedBrowser;

  let waitForAudioPromise = BrowserTestUtils.waitForEvent(
    tab,
    "TabAttrModified",
    false,
    event => {
      return (
        event.detail.changed.includes("soundplaying") &&
        tab.hasAttribute("soundplaying")
      );
    }
  );

  await SpecialPowers.spawn(browser, [], async function () {
    let audio = content.document.querySelector("audio");
    await audio.play();
  });

  await waitForAudioPromise;
}

async function addTab(win = window) {
  return BrowserTestUtils.openNewForegroundTab({
    gBrowser: win.gBrowser,
    url: BASE_URL + "dummy_page.html",
    waitForLoad: true,
  });
}

async function addPrivTab(win = window) {
  const tab = BrowserTestUtils.addTab(
    win.gBrowser,
    BASE_URL + "dummy_page.html"
  );
  const browser = win.gBrowser.getBrowserForTab(tab);
  await BrowserTestUtils.browserLoaded(browser);
  return tab;
}

async function addAudioTab(win = window) {
  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser: win.gBrowser,
    url: BASE_URL + "file_mediaPlayback.html",
    waitForLoad: true,
    waitForStateStop: true,
  });

  await play(tab);
  return tab;
}

async function addWebRTCTab(win = window) {
  let popupPromise = new Promise(resolve => {
    win.PopupNotifications.panel.addEventListener(
      "popupshown",
      function () {
        executeSoon(resolve);
      },
      { once: true }
    );
  });

  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser: win.gBrowser,
    url: BASE_URL + "file_webrtc.html",
    waitForLoad: true,
    waitForStateStop: true,
  });

  await popupPromise;

  let recordingPromise = BrowserTestUtils.contentTopicObserved(
    tab.linkedBrowser.browsingContext,
    "recording-device-events"
  );
  win.PopupNotifications.panel.firstElementChild.button.click();
  await recordingPromise;

  return tab;
}

async function pressure() {
  let tabDiscarded = BrowserTestUtils.waitForEvent(
    document,
    "TabBrowserDiscarded",
    true
  );
  TabUnloader.unloadTabAsync(null);
  return tabDiscarded;
}

function pressureAndObserve(aExpectedTopic) {
  const promise = new Promise(resolve => {
    const observer = {
      QueryInterface: ChromeUtils.generateQI([
        "nsIObserver",
        "nsISupportsWeakReference",
      ]),
      observe(aSubject, aTopicInner, aData) {
        if (aTopicInner == aExpectedTopic) {
          Services.obs.removeObserver(observer, aTopicInner);
          resolve(aData);
        }
      },
    };
    Services.obs.addObserver(observer, aExpectedTopic);
  });
  TabUnloader.unloadTabAsync(null);
  return promise;
}

async function compareTabOrder(expectedOrder) {
  let tabInfo = await TabUnloader.getSortedTabs(null);

  is(
    tabInfo.length,
    expectedOrder.length,
    "right number of tabs in discard sort list"
  );
  for (let idx = 0; idx < expectedOrder.length; idx++) {
    is(tabInfo[idx].tab, expectedOrder[idx], "index " + idx + " is correct");
  }
}

const PREF_PERMISSION_FAKE = "media.navigator.permission.fake";
const PREF_AUDIO_LOOPBACK = "media.audio_loopback_dev";
const PREF_VIDEO_LOOPBACK = "media.video_loopback_dev";
const PREF_FAKE_STREAMS = "media.navigator.streams.fake";
const PREF_ENABLE_UNLOADER = "browser.tabs.unloadOnLowMemory";
const PREF_MAC_LOW_MEM_RESPONSE = "browser.lowMemoryResponseMask";

add_task(async function test() {
  registerCleanupFunction(() => {
    Services.prefs.clearUserPref(PREF_ENABLE_UNLOADER);
    if (AppConstants.platform == "macosx") {
      Services.prefs.clearUserPref(PREF_MAC_LOW_MEM_RESPONSE);
    }
  });
  Services.prefs.setBoolPref(PREF_ENABLE_UNLOADER, true);

  // On Mac, tab unloading and memory pressure notifications are limited
  // to Nightly so force them on for this test for non-Nightly builds. i.e.,
  // tests on Release and Beta builds. Mac tab unloading and memory pressure
  // notifications require this pref to be set.
  if (AppConstants.platform == "macosx") {
    Services.prefs.setIntPref(PREF_MAC_LOW_MEM_RESPONSE, 3);
  }

  TabUnloader.init();

  // Set some WebRTC simulation preferences.
  let prefs = [
    [PREF_PERMISSION_FAKE, true],
    [PREF_AUDIO_LOOPBACK, ""],
    [PREF_VIDEO_LOOPBACK, ""],
    [PREF_FAKE_STREAMS, true],
  ];
  await SpecialPowers.pushPrefEnv({ set: prefs });

  // Set up 6 tabs, three normal ones, one pinned, one playing sound and one
  // pinned playing sound
  let tab0 = gBrowser.tabs[0];
  let tab1 = await addTab();
  let tab2 = await addTab();
  let pinnedTab = await addTab();
  gBrowser.pinTab(pinnedTab);
  let soundTab = await addAudioTab();
  let pinnedSoundTab = await addAudioTab();
  gBrowser.pinTab(pinnedSoundTab);

  // Open a new private window and add a tab
  const windowPriv = await BrowserTestUtils.openNewBrowserWindow({
    private: true,
  });
  const tabPriv0 = windowPriv.gBrowser.tabs[0];
  const tabPriv1 = await addPrivTab(windowPriv);

  // Move the original window to the foreground to pass the tests
  gBrowser.selectedTab = tab0;
  tab0.ownerGlobal.focus();

  // Pretend we've visited the tabs
  await BrowserTestUtils.switchTab(windowPriv.gBrowser, tabPriv1);
  await BrowserTestUtils.switchTab(windowPriv.gBrowser, tabPriv0);
  await BrowserTestUtils.switchTab(gBrowser, tab1);
  await BrowserTestUtils.switchTab(gBrowser, tab2);
  await BrowserTestUtils.switchTab(gBrowser, pinnedTab);
  await BrowserTestUtils.switchTab(gBrowser, soundTab);
  await BrowserTestUtils.switchTab(gBrowser, pinnedSoundTab);
  await BrowserTestUtils.switchTab(gBrowser, tab0);

  // Checks the tabs are in the state we expect them to be
  ok(pinnedTab.pinned, "tab is pinned");
  ok(pinnedSoundTab.soundPlaying, "tab is playing sound");
  ok(
    pinnedSoundTab.pinned && pinnedSoundTab.soundPlaying,
    "tab is pinned and playing sound"
  );

  await compareTabOrder([
    tab1,
    tab2,
    pinnedTab,
    tabPriv1,
    soundTab,
    tab0,
    pinnedSoundTab,
    tabPriv0,
  ]);

  // Check that the tabs are present
  ok(
    tab1.linkedPanel &&
      tab2.linkedPanel &&
      pinnedTab.linkedPanel &&
      soundTab.linkedPanel &&
      pinnedSoundTab.linkedPanel &&
      tabPriv0.linkedPanel &&
      tabPriv1.linkedPanel,
    "tabs are present"
  );

  // Check that low-memory memory-pressure events unload tabs
  await pressure();
  ok(
    !tab1.linkedPanel,
    "low-memory memory-pressure notification unloaded the LRU tab"
  );

  await compareTabOrder([
    tab2,
    pinnedTab,
    tabPriv1,
    soundTab,
    tab0,
    pinnedSoundTab,
    tabPriv0,
  ]);

  // If no normal tab is available unload pinned tabs
  await pressure();
  ok(!tab2.linkedPanel, "unloaded a second tab in LRU order");
  await compareTabOrder([
    pinnedTab,
    tabPriv1,
    soundTab,
    tab0,
    pinnedSoundTab,
    tabPriv0,
  ]);

  ok(soundTab.soundPlaying, "tab is still playing sound");

  await pressure();
  ok(!pinnedTab.linkedPanel, "unloaded a pinned tab");
  await compareTabOrder([tabPriv1, soundTab, tab0, pinnedSoundTab, tabPriv0]);

  ok(pinnedSoundTab.soundPlaying, "tab is still playing sound");

  // There are no unloadable tabs.
  TabUnloader.unloadTabAsync(null);
  ok(tabPriv1.linkedPanel, "a tab in a private window is never unloaded");

  const histogram = TelemetryTestUtils.getAndClearHistogram(
    "TAB_UNLOAD_TO_RELOAD"
  );

  // It's possible that we're already in the memory-pressure state
  // and we may receive the "ongoing" message.
  const message = await pressureAndObserve("memory-pressure");
  Assert.ok(
    message == "low-memory" || message == "low-memory-ongoing",
    "observed the memory-pressure notification because of no discardable tab"
  );

  // Add a WebRTC tab and another sound tab.
  let webrtcTab = await addWebRTCTab();
  let anotherSoundTab = await addAudioTab();

  await BrowserTestUtils.switchTab(gBrowser, tab1);
  await BrowserTestUtils.switchTab(gBrowser, pinnedTab);

  const hist = histogram.snapshot();
  const numEvents = Object.values(hist.values).reduce((a, b) => a + b);
  Assert.equal(numEvents, 2, "two tabs have been reloaded.");

  // tab0 has never been unloaded.  No data is added to the histogram.
  await BrowserTestUtils.switchTab(gBrowser, tab0);

  await compareTabOrder([
    tab1,
    pinnedTab,
    tabPriv1,
    soundTab,
    webrtcTab,
    anotherSoundTab,
    tab0,
    pinnedSoundTab,
    tabPriv0,
  ]);

  await BrowserTestUtils.closeWindow(windowPriv);

  let window2 = await BrowserTestUtils.openNewBrowserWindow();
  let win2tab1 = window2.gBrowser.selectedTab;
  let win2tab2 = await addTab(window2);
  let win2winrtcTab = await addWebRTCTab(window2);
  let win2tab3 = await addTab(window2);

  await compareTabOrder([
    tab1,
    win2tab1,
    win2tab2,
    pinnedTab,
    soundTab,
    webrtcTab,
    anotherSoundTab,
    win2winrtcTab,
    tab0,
    win2tab3,
    pinnedSoundTab,
  ]);

  await BrowserTestUtils.closeWindow(window2);

  await compareTabOrder([
    tab1,
    pinnedTab,
    soundTab,
    webrtcTab,
    anotherSoundTab,
    tab0,
    pinnedSoundTab,
  ]);

  // Cleanup
  BrowserTestUtils.removeTab(tab1);
  BrowserTestUtils.removeTab(tab2);
  BrowserTestUtils.removeTab(pinnedTab);
  BrowserTestUtils.removeTab(soundTab);
  BrowserTestUtils.removeTab(pinnedSoundTab);
  BrowserTestUtils.removeTab(webrtcTab);
  BrowserTestUtils.removeTab(anotherSoundTab);

  await awaitWebRTCClose();
});

// Wait for the WebRTC indicator window to close.
function awaitWebRTCClose() {
  if (
    Services.prefs.getBoolPref("privacy.webrtc.legacyGlobalIndicator", false) ||
    AppConstants.platform == "macosx"
  ) {
    return null;
  }

  let win = Services.wm.getMostRecentWindow("Browser:WebRTCGlobalIndicator");
  if (!win) {
    return null;
  }

  return new Promise(resolve => {
    win.addEventListener("unload", function listener(e) {
      if (e.target == win.document) {
        win.removeEventListener("unload", listener);
        executeSoon(resolve);
      }
    });
  });
}