summaryrefslogtreecommitdiffstats
path: root/testing/talos/talos/startup_test/sessionrestore/addon/api.js
blob: f621894623a12fa6a288a14b961a08b9bd2ab9ab (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
/* 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/. */

"use strict";

/* globals Services, XPCOMUtils */

ChromeUtils.defineESModuleGetters(this, {
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.sys.mjs",
  StartupPerformance:
    "resource:///modules/sessionstore/StartupPerformance.sys.mjs",
  setTimeout: "resource://gre/modules/Timer.sys.mjs",
});

/* globals ExtensionAPI */

this.sessionrestore = class extends ExtensionAPI {
  onStartup() {
    this.promiseIdleFinished = Promise.withResolvers();
    Services.obs.addObserver(this, "browser-idle-startup-tasks-finished");
    // run() is async but we don't want to await or return it here,
    // since the extension should be considered started even before
    // run() has finished all its work.
    this.run();
  }

  observe(subject, topic, data) {
    if (topic == "browser-idle-startup-tasks-finished") {
      this.promiseIdleFinished.resolve();
    }
  }

  async ensureTalosParentProfiler() {
    // TalosParentProfiler is part of TalosPowers, which is a separate WebExtension
    // that may or may not already have finished loading at this point. getTalosParentProfiler
    // is used to wait for TalosPowers to be around before continuing. This should
    // not be used to delay the execution of the test, but to delay the dumping of
    // the profile to disk.
    async function getTalosParentProfiler() {
      try {
        var { TalosParentProfiler } = ChromeUtils.importESModule(
          "resource://talos-powers/TalosParentProfiler.sys.mjs"
        );
        return TalosParentProfiler;
      } catch (err) {
        await new Promise(resolve => setTimeout(resolve, 500));
        return getTalosParentProfiler();
      }
    }

    this.TalosParentProfiler = await getTalosParentProfiler();
  }

  async finishProfiling(msg) {
    await this.ensureTalosParentProfiler();

    // In rare circumstances, it's possible for the session file to be read
    // into memory and for SessionStore to report itself as initialized before
    // the initial window has had a chance to finish setting itself up. To
    // account for this, we ensure that BrowserWindowTracker.windowCount is
    // not zero - and if it is, we wait for the first window to finish opening
    // before proceeding.
    if (!BrowserWindowTracker.windowCount) {
      const BROWSER_WINDOW_READY_TOPIC = "browser-delayed-startup-finished";
      await new Promise(resolve => {
        let observe = async () => {
          Services.obs.removeObserver(observe, BROWSER_WINDOW_READY_TOPIC);
          resolve();
        };
        Services.obs.addObserver(observe, BROWSER_WINDOW_READY_TOPIC);
      });
    }

    let win = BrowserWindowTracker.getTopWindow();
    let args = win.arguments[0];
    if (args && args instanceof Ci.nsIArray) {
      // For start-up tests Gecko Profiler arguments are passed to the first URL in
      // the query string, with the presumption that some tab that is loaded at start-up
      // will want to use them in the TalosContentProfiler.js script.
      //
      // Because we're running this part of the test in the parent process, we
      // pull those arguments from the top window directly. This is mainly so
      // that TalosParentProfiler knows where to save the profile.
      // eslint-disable-next-line mozilla/reject-importGlobalProperties
      Cu.importGlobalProperties(["URL"]);
      let url = new URL(args.queryElementAt(0, Ci.nsISupportsString).data);
      this.TalosParentProfiler.initFromURLQueryParams(url.search);
    }

    await this.TalosParentProfiler.subtestEnd(msg);
    await this.TalosParentProfiler.finishStartupProfiling();
  }

  async run() {
    try {
      let didRestore = true;

      if (!StartupPerformance.isRestored) {
        await SessionStartup.onceInitialized;

        if (
          SessionStartup.sessionType == SessionStartup.NO_SESSION ||
          SessionStartup.sessionType == SessionStartup.DEFER_SESSION
        ) {
          // We should only hit this patch in sessionrestore_no_auto_restore
          if (
            !Services.prefs.getBoolPref("talos.sessionrestore.norestore", false)
          ) {
            throw new Error("Session was not restored!");
          }
          await this.finishProfiling(
            "This test measures the time between process " +
              "creation and sessionRestored."
          );

          didRestore = false;
        } else {
          await new Promise(resolve => {
            let observe = async () => {
              Services.obs.removeObserver(
                observe,
                StartupPerformance.RESTORED_TOPIC
              );
              await this.finishProfiling(
                "This test measures the time between process " +
                  "creation and the last restored tab."
              );

              resolve();
            };
            Services.obs.addObserver(
              observe,
              StartupPerformance.RESTORED_TOPIC
            );
          });
        }
      }

      let startup_info = Services.startup.getStartupInfo();
      let restoreTime = didRestore
        ? StartupPerformance.latestRestoredTimeStamp
        : startup_info.sessionRestored;
      let duration = restoreTime - startup_info.process;
      let win = BrowserWindowTracker.getTopWindow();

      // Report data to Talos, if possible.
      dump("__start_report" + duration + "__end_report\n\n");

      // Next one is required by the test harness but not used.
      dump("__startTimestamp" + win.performance.now() + "__endTimestamp\n\n");
    } catch (ex) {
      dump(`SessionRestoreTalosTest: error ${ex}\n`);
      dump(ex.stack);
      dump("\n");
    }

    // Ensure we wait for idle to finish so that we can have a clean shutdown
    // that isn't happening in the middle of start-up.
    await this.promiseIdleFinished.promise;

    Services.startup.quit(Services.startup.eForceQuit);
  }
};