summaryrefslogtreecommitdiffstats
path: root/testing/talos/talos/talos-powers/api.js
blob: cb0ddaccefe49f0aec61cde57056f2540f3cfedc (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* globals ExtensionAPI, Services, XPCOMUtils */

const { ComponentUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/ComponentUtils.sys.mjs"
);

ChromeUtils.defineESModuleGetters(this, {
  AboutHomeStartupCache: "resource:///modules/BrowserGlue.sys.mjs",
  AboutNewTab: "resource:///modules/AboutNewTab.sys.mjs",
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
  PerTestCoverageUtils:
    "resource://testing-common/PerTestCoverageUtils.sys.mjs",
  SessionStore: "resource:///modules/sessionstore/SessionStore.sys.mjs",
  setTimeout: "resource://gre/modules/Timer.sys.mjs",
});

XPCOMUtils.defineLazyServiceGetter(
  this,
  "resProto",
  "@mozilla.org/network/protocol;1?name=resource",
  "nsISubstitutingProtocolHandler"
);

// These are not automagically defined for us because we are an extension.
//
// eslint-disable-next-line mozilla/reject-importGlobalProperties
Cu.importGlobalProperties(["IOUtils", "PathUtils"]);

const Cm = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);

let frameScriptURL;
let profilerSubtestStartTime;

function TalosPowersService() {
  this.wrappedJSObject = this;

  this.init();
}

TalosPowersService.prototype = {
  factory: ComponentUtils.generateSingletonFactory(TalosPowersService),
  classDescription: "Talos Powers",
  classID: Components.ID("{f5d53443-d58d-4a2f-8df0-98525d4f91ad}"),
  contractID: "@mozilla.org/talos/talos-powers-service;1",
  QueryInterface: ChromeUtils.generateQI([]),

  register() {
    Cm.registerFactory(
      this.classID,
      this.classDescription,
      this.contractID,
      this.factory
    );

    void Cc[this.contractID].getService();
  },

  unregister() {
    Cm.unregisterFactory(this.classID, this.factory);
  },

  init() {
    if (!frameScriptURL) {
      throw new Error("Cannot find frame script url (extension not started?)");
    }
    Services.mm.loadFrameScript(frameScriptURL, true);
    Services.mm.addMessageListener("Talos:ForceQuit", this);
    Services.mm.addMessageListener("TalosContentProfiler:Command", this);
    Services.mm.addMessageListener("TalosPowersContent:ForceCCAndGC", this);
    Services.mm.addMessageListener("TalosPowersContent:GetStartupInfo", this);
    Services.mm.addMessageListener("TalosPowers:ParentExec:QueryMsg", this);
  },

  receiveMessage(message) {
    switch (message.name) {
      case "Talos:ForceQuit": {
        this.forceQuit(message.data);
        break;
      }
      case "TalosContentProfiler:Command": {
        this.receiveProfileCommand(message);
        break;
      }
      case "TalosPowersContent:ForceCCAndGC": {
        Cu.forceGC();
        Cu.forceCC();
        Cu.forceShrinkingGC();
        break;
      }
      case "TalosPowersContent:GetStartupInfo": {
        this.receiveGetStartupInfo(message);
        break;
      }
      case "TalosPowers:ParentExec:QueryMsg": {
        this.RecieveParentExecCommand(message);
        break;
      }
    }
  },

  /**
   * Enable the Gecko Profiler with some settings.
   *
   * @param data (object)
   *        A JavaScript object with the following properties:
   *
   *        entries (int):
   *          The sampling buffer size in bytes.
   *
   *        interval (int):
   *          The sampling interval in milliseconds.
   *
   *        threadsArray (array of strings):
   *          The thread names to sample.
   */
  profilerBegin(data) {
    Services.profiler.StartProfiler(
      data.entries,
      data.interval,
      data.featuresArray,
      data.threadsArray
    );
  },

  /**
   * Assuming the Profiler is running, dumps the Profile from all sampled
   * processes and threads to the disk. The Profiler will be stopped once
   * the profiles have been dumped. This method returns a Promise that
   * will resolve once this has occurred.
   *
   * @param profileDir (string)
   *        The name of the directory to write the profile in.
   * @param profileFile (string)
   *        The name of the file to write to.
   *
   * @returns Promise
   */
  profilerFinish(profileDir, profileFile) {
    const profilePath = PathUtils.join(profileDir, profileFile);
    return new Promise((resolve, reject) => {
      Services.profiler.Pause();
      Services.profiler.getProfileDataAsync().then(
        profile =>
          IOUtils.writeJSON(profilePath, profile, {
            tmpPath: `${profilePath}.tmp`,
          }).then(() => {
            Services.profiler.StopProfiler();
            resolve();
            Services.obs.notifyObservers(null, "talos-profile-gathered");
          }),
        error => {
          console.error("Failed to gather profile:", error);
          // FIXME: We should probably send a message down to the
          // child which causes it to reject the waiting Promise.
          reject();
        }
      );
    });
  },

  /**
   * Add a parent process marker to the profiler to indicate the subtest duration.
   *
   * @param marker (string, optional)
   *        Marker name.
   */
  profilerSubtestEnd(marker = null, startTime = undefined) {
    if (marker) {
      this.addIntervalMarker(marker, startTime ?? profilerSubtestStartTime);
    }
  },

  /**
   * * Add a parent process marker to the profiler to indicate the start of the subtest.
   *
   * @param marker (string, optional)
   *        Marker name.
   */
  profilerSubtestStart(marker = null) {
    profilerSubtestStartTime = Cu.now();

    if (marker) {
      this.addInstantMarker(marker);
    }
  },

  /**
   * Adds an instant marker to the Profile in the parent process.
   *
   * @param marker (string)  A marker to set.
   *
   */
  addInstantMarker(marker) {
    ChromeUtils.addProfilerMarker("Talos", { category: "Test" }, marker);
  },

  /**
   * Adds a marker to the Profile in the parent process.
   *
   * @param marker (string)
   *        A marker to set.
   *
   * @param startTime (number)
   *        Start time, used to create an interval profile marker. If
   *        undefined, a single instance marker will be placed.
   */
  addIntervalMarker(marker, startTime) {
    ChromeUtils.addProfilerMarker(
      "Talos",
      { startTime, category: "Test" },
      marker
    );
  },

  receiveProfileCommand(message) {
    const ACK_NAME = "TalosContentProfiler:Response";
    let mm = message.target.messageManager;
    let name = message.data.name;
    let data = message.data.data;

    switch (name) {
      case "Profiler:Begin": {
        this.profilerBegin(data);
        // profilerBegin will cause the parent to send an async message to any
        // child processes to start profiling. Because messages are serviced
        // in order, we know that by the time that the child services the
        // ACK message, that the profiler has started in its process.
        mm.sendAsyncMessage(ACK_NAME, { name });
        break;
      }

      case "Profiler:Finish": {
        // The test is done. Dump the profile.
        this.profilerFinish(data.profileDir, data.profileFile).then(() => {
          mm.sendAsyncMessage(ACK_NAME, { name });
        });
        break;
      }

      case "Profiler:SubtestEnd": {
        this.profilerSubtestEnd(data.marker, data.startTime);
        mm.sendAsyncMessage(ACK_NAME, { name });
        break;
      }

      case "Profiler:SubtestStart": {
        this.profilerSubtestStart(data.marker);
        mm.sendAsyncMessage(ACK_NAME, { name });
        break;
      }

      case "Profiler:Marker": {
        this.profilerMarker(data.marker, data.startTime);
        mm.sendAsyncMessage(ACK_NAME, { name });
        break;
      }
    }
  },

  async forceQuit(messageData) {
    if (messageData && messageData.waitForStartupFinished) {
      // We can wait for various startup items here to complete during
      // the getInfo.html step for Talos so that subsequent runs don't
      // have to do things like re-request the SafeBrowsing list.
      let { SafeBrowsing } = ChromeUtils.importESModule(
        "resource://gre/modules/SafeBrowsing.sys.mjs"
      );

      // Speed things up in case nobody else called this:
      SafeBrowsing.init();

      try {
        await SafeBrowsing.addMozEntriesFinishedPromise;
      } catch (e) {
        // We don't care if things go wrong here - let's just shut down.
      }

      // We wait for the AboutNewTab's TopSitesFeed (and its "Contile"
      // integration, which shows the sponsored Top Sites) to finish
      // being enabled here. This is because it's possible for getInfo.html
      // to run so quickly that the feed will still be initializing, and
      // that would cause us to write a mostly empty cache to the
      // about:home startup cache on shutdown, which causes that test
      // to break periodically.
      AboutNewTab.onBrowserReady();
      // There aren't currently any easily observable notifications or
      // events to let us know when the feed is ready, so we'll just poll
      // for now.
      let pollForFeed = async function () {
        let foundFeed = AboutNewTab.activityStream.store.feeds.get(
          "feeds.system.topsites"
        );
        if (!foundFeed) {
          await new Promise(resolve => setTimeout(resolve, 500));
          return pollForFeed();
        }
        return foundFeed;
      };
      let feed = await pollForFeed();
      await feed._contile.refresh();
      await feed.refresh({ broadcast: true });
      await AboutHomeStartupCache.cacheNow();
    }

    await SessionStore.promiseAllWindowsRestored;

    // Check to see if the top-most browser window still needs to fire its
    // idle tasks notification. If so, we'll wait for it before shutting
    // down, since some caching that can influence future runs in this profile
    // keys off of that notification.
    let topWin = BrowserWindowTracker.getTopWindow();
    if (topWin && topWin.gBrowserInit) {
      await topWin.gBrowserInit.idleTasksFinishedPromise;
    }

    for (let domWindow of Services.wm.getEnumerator(null)) {
      domWindow.close();
    }

    try {
      Services.startup.quit(Services.startup.eForceQuit);
    } catch (e) {
      dump("Force Quit failed: " + e);
    }
  },

  receiveGetStartupInfo(message) {
    let mm = message.target.messageManager;
    let startupInfo = Services.startup.getStartupInfo();

    if (!startupInfo.firstPaint) {
      // It's possible that we were called early enough that
      // the firstPaint measurement hasn't been set yet. In
      // that case, we set up an observer for the next time
      // a window is painted and re-retrieve the startup info.
      let obs = function (subject, topic) {
        Services.obs.removeObserver(this, topic);
        startupInfo = Services.startup.getStartupInfo();
        mm.sendAsyncMessage(
          "TalosPowersContent:GetStartupInfo:Result",
          startupInfo
        );
      };
      Services.obs.addObserver(obs, "widget-first-paint");
    } else {
      mm.sendAsyncMessage(
        "TalosPowersContent:GetStartupInfo:Result",
        startupInfo
      );
    }
  },

  // These services are exposed to local unprivileged content.
  // Each service is a function which accepts an argument, a callback for sending
  // the reply (possibly async), and the parent window as a utility.
  // arg/reply semantice are service-specific.
  // To add a service: add a method at ParentExecServices here, then at the content:
  // <script src="chrome://talos-powers-content/content/TalosPowersContent.js"></script>
  // and then e.g. TalosPowersParent.exec("sampleParentService", myArg, myCallback)
  // Sample service:
  /*
    // arg: anything. return: sample reply
    sampleParentService: function(arg, callback, win) {
      win.setTimeout(function() {
        callback("sample reply for: " + arg);
      }, 500);
    },
  */
  ParentExecServices: {
    ping(arg, callback, win) {
      callback();
    },

    // arg: ignored. return: handle (number) for use with stopFrameTimeRecording
    startFrameTimeRecording(arg, callback, win) {
      var rv = win.windowUtils.startFrameTimeRecording();
      callback(rv);
    },

    // arg: handle from startFrameTimeRecording. return: array with composition intervals
    stopFrameTimeRecording(arg, callback, win) {
      var rv = win.windowUtils.stopFrameTimeRecording(arg);
      callback(rv);
    },

    requestDumpCoverageCounters(arg, callback, win) {
      PerTestCoverageUtils.afterTest().then(callback);
    },

    requestResetCoverageCounters(arg, callback, win) {
      PerTestCoverageUtils.beforeTest().then(callback);
    },

    dumpAboutSupport(arg, callback, win) {
      const { Troubleshoot } = ChromeUtils.importESModule(
        "resource://gre/modules/Troubleshoot.sys.mjs"
      );
      Troubleshoot.snapshot().then(snapshot => {
        dump("about:support\t" + JSON.stringify(snapshot) + "\n");
        callback();
      });
    },
  },

  RecieveParentExecCommand(msg) {
    function sendResult(result) {
      let mm = msg.target.messageManager;
      mm.sendAsyncMessage("TalosPowers:ParentExec:ReplyMsg", {
        id: msg.data.id,
        result,
      });
    }

    let command = msg.data.command;
    if (!this.ParentExecServices.hasOwnProperty(command.name)) {
      throw new Error(
        "TalosPowers:ParentExec: Invalid service '" + command.name + "'"
      );
    }

    this.ParentExecServices[command.name](
      command.data,
      sendResult,
      msg.target.ownerGlobal
    );
  },
};

this.talos_powers = class extends ExtensionAPI {
  onStartup() {
    let uri = Services.io.newURI("content/", null, this.extension.rootURI);
    resProto.setSubstitutionWithFlags(
      "talos-powers",
      uri,
      resProto.ALLOW_CONTENT_ACCESS
    );

    frameScriptURL = this.extension.rootURI.resolve(
      "chrome/talos-powers-content.js"
    );

    TalosPowersService.prototype.register();
  }

  onShutdown() {
    TalosPowersService.prototype.unregister();

    frameScriptURL = null;
    resProto.setSubstitution("talos-powers", null);
  }
};