summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/watcher/target-helpers/frame-helper.js
blob: 0e6f4f80d331ea7fc64faa8aed7c4531703548a8 (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
/* 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";

const { WatcherRegistry } = ChromeUtils.importESModule(
  "resource://devtools/server/actors/watcher/WatcherRegistry.sys.mjs",
  {
    // WatcherRegistry needs to be a true singleton and loads ActorManagerParent
    // which also has to be a true singleton.
    loadInDevToolsLoader: false,
  }
);
const { WindowGlobalLogger } = ChromeUtils.importESModule(
  "resource://devtools/server/connectors/js-window-actor/WindowGlobalLogger.sys.mjs"
);
const Targets = require("resource://devtools/server/actors/targets/index.js");

const browsingContextAttachedObserverByWatcher = new Map();

/**
 * Force creating targets for all existing BrowsingContext, that, for a given Watcher Actor.
 *
 * @param WatcherActor watcher
 *        The Watcher Actor requesting to watch for new targets.
 */
async function createTargets(watcher) {
  // Go over all existing BrowsingContext in order to:
  // - Force the instantiation of a DevToolsFrameChild
  // - Have the DevToolsFrameChild to spawn the WindowGlobalTargetActor

  // If we have a browserElement, set the watchedByDevTools flag on its related browsing context
  // TODO: We should also set the flag for the "parent process" browsing context when we're
  // in the browser toolbox. This is blocked by Bug 1675763, and should be handled as part
  // of Bug 1709529.
  if (watcher.sessionContext.type == "browser-element") {
    // The `watchedByDevTools` enables gecko behavior tied to this flag, such as:
    //  - reporting the contents of HTML loaded in the docshells
    //  - capturing stacks for the network monitor.
    watcher.browserElement.browsingContext.watchedByDevTools = true;
  }

  if (!browsingContextAttachedObserverByWatcher.has(watcher)) {
    // We store the browserId here as watcher.browserElement.browserId can momentary be
    // set to 0 when there's a navigation to a new browsing context.
    const browserId = watcher.sessionContext.browserId;
    const onBrowsingContextAttached = browsingContext => {
      // We want to set watchedByDevTools on new top-level browsing contexts:
      // - in the case of the BrowserToolbox/BrowserConsole, that would be the browsing
      //   contexts of all the tabs we want to handle.
      // - for the regular toolbox, browsing context that are being created when navigating
      //   to a page that forces a new browsing context.
      // Then BrowsingContext will propagate to all the tree of children BrowsingContext's.
      if (
        !browsingContext.parent &&
        (watcher.sessionContext.type != "browser-element" ||
          browserId === browsingContext.browserId)
      ) {
        browsingContext.watchedByDevTools = true;
      }
    };
    Services.obs.addObserver(
      onBrowsingContextAttached,
      "browsing-context-attached"
    );
    // We store the observer so we can retrieve it elsewhere (e.g. for removal in destroyTargets).
    browsingContextAttachedObserverByWatcher.set(
      watcher,
      onBrowsingContextAttached
    );
  }

  if (
    watcher.sessionContext.isServerTargetSwitchingEnabled &&
    watcher.sessionContext.type == "browser-element"
  ) {
    // If server side target switching is enabled, process the top level browsing context first,
    // so that we guarantee it is notified to the client first.
    // If it is disabled, the top level target will be created from the client instead.
    await createTargetForBrowsingContext({
      watcher,
      browsingContext: watcher.browserElement.browsingContext,
      retryOnAbortError: true,
    });
  }

  const browsingContexts = watcher.getAllBrowsingContexts().filter(
    // Filter out the top browsing context we just processed.
    browsingContext =>
      browsingContext != watcher.browserElement?.browsingContext
  );
  // Await for the all the queries in order to resolve only *after* we received all
  // already available targets.
  // i.e. each call to `createTargetForBrowsingContext` should end up emitting
  // a target-available-form event via the WatcherActor.
  await Promise.allSettled(
    browsingContexts.map(browsingContext =>
      createTargetForBrowsingContext({ watcher, browsingContext })
    )
  );
}

/**
 * (internal helper method) Force creating the target actor for a given BrowsingContext.
 *
 * @param WatcherActor watcher
 *        The Watcher Actor requesting to watch for new targets.
 * @param BrowsingContext browsingContext
 *        The context for which a target should be created.
 * @param Boolean retryOnAbortError
 *        Set to true to retry creating existing targets when receiving an AbortError.
 *        An AbortError is sent when the JSWindowActor pair was destroyed before the query
 *        was complete, which can happen if the document navigates while the query is pending.
 */
async function createTargetForBrowsingContext({
  watcher,
  browsingContext,
  retryOnAbortError = false,
}) {
  logWindowGlobal(browsingContext.currentWindowGlobal, "Existing WindowGlobal");

  // We need to set the watchedByDevTools flag on all top-level browsing context. In the
  // case of a content toolbox, this is done in the tab descriptor, but when we're in the
  // browser toolbox, such descriptor is not created.
  // Then BrowsingContext will propagate to all the tree of children BbrowsingContext's.
  if (!browsingContext.parent) {
    browsingContext.watchedByDevTools = true;
  }

  try {
    await browsingContext.currentWindowGlobal
      .getActor("DevToolsFrame")
      .instantiateTarget({
        watcherActorID: watcher.actorID,
        connectionPrefix: watcher.conn.prefix,
        sessionContext: watcher.sessionContext,
        sessionData: watcher.sessionData,
      });
  } catch (e) {
    console.warn(
      "Failed to create DevTools Frame target for browsingContext",
      browsingContext.id,
      ": ",
      e,
      retryOnAbortError ? "retrying" : ""
    );
    if (retryOnAbortError && e.name === "AbortError") {
      await createTargetForBrowsingContext({
        watcher,
        browsingContext,
        retryOnAbortError,
      });
    } else {
      throw e;
    }
  }
}

/**
 * Force destroying all BrowsingContext targets which were related to a given watcher.
 *
 * @param WatcherActor watcher
 *        The Watcher Actor requesting to stop watching for new targets.
 * @param {object} options
 * @param {boolean} options.isModeSwitching
 *        true when this is called as the result of a change to the devtools.browsertoolbox.scope pref
 */
function destroyTargets(watcher, options) {
  // Go over all existing BrowsingContext in order to destroy all targets
  const browsingContexts = watcher.getAllBrowsingContexts();

  for (const browsingContext of browsingContexts) {
    logWindowGlobal(
      browsingContext.currentWindowGlobal,
      "Existing WindowGlobal"
    );

    if (!browsingContext.parent) {
      browsingContext.watchedByDevTools = false;
    }

    browsingContext.currentWindowGlobal
      .getActor("DevToolsFrame")
      .destroyTarget({
        watcherActorID: watcher.actorID,
        sessionContext: watcher.sessionContext,
        options,
      });
  }

  if (watcher.sessionContext.type == "browser-element") {
    watcher.browserElement.browsingContext.watchedByDevTools = false;
  }

  if (browsingContextAttachedObserverByWatcher.has(watcher)) {
    Services.obs.removeObserver(
      browsingContextAttachedObserverByWatcher.get(watcher),
      "browsing-context-attached"
    );
    browsingContextAttachedObserverByWatcher.delete(watcher);
  }
}

/**
 * Go over all existing BrowsingContext in order to communicate about new data entries
 *
 * @param WatcherActor watcher
 *        The Watcher Actor requesting to stop watching for new targets.
 * @param string type
 *        The type of data to be added
 * @param Array<Object> entries
 *        The values to be added to this type of data
 * @param String updateType
 *        "add" will only add the new entries in the existing data set.
 *        "set" will update the data set with the new entries.
 */
async function addOrSetSessionDataEntry({
  watcher,
  type,
  entries,
  updateType,
}) {
  const browsingContexts = getWatchingBrowsingContexts(watcher);
  const promises = [];
  for (const browsingContext of browsingContexts) {
    logWindowGlobal(
      browsingContext.currentWindowGlobal,
      "Existing WindowGlobal"
    );

    const promise = browsingContext.currentWindowGlobal
      .getActor("DevToolsFrame")
      .addOrSetSessionDataEntry({
        watcherActorID: watcher.actorID,
        sessionContext: watcher.sessionContext,
        type,
        entries,
        updateType,
      });
    promises.push(promise);
  }
  // Await for the queries in order to try to resolve only *after* the remote code processed the new data
  return Promise.all(promises);
}

/**
 * Notify all existing frame targets that some data entries have been removed
 *
 * See addOrSetSessionDataEntry for argument documentation.
 */
function removeSessionDataEntry({ watcher, type, entries }) {
  const browsingContexts = getWatchingBrowsingContexts(watcher);
  for (const browsingContext of browsingContexts) {
    logWindowGlobal(
      browsingContext.currentWindowGlobal,
      "Existing WindowGlobal"
    );

    browsingContext.currentWindowGlobal
      .getActor("DevToolsFrame")
      .removeSessionDataEntry({
        watcherActorID: watcher.actorID,
        sessionContext: watcher.sessionContext,
        type,
        entries,
      });
  }
}

module.exports = {
  createTargets,
  destroyTargets,
  addOrSetSessionDataEntry,
  removeSessionDataEntry,
};

/**
 * Return the list of BrowsingContexts which should be targeted in order to communicate
 * updated session data.
 *
 * @param WatcherActor watcher
 *        The watcher actor will be used to know which target we debug
 *        and what BrowsingContext should be considered.
 */
function getWatchingBrowsingContexts(watcher) {
  // If we are watching for additional frame targets, it means that the multiprocess or fission mode is enabled,
  // either for a content toolbox or a BrowserToolbox via scope set to everything.
  const watchingAdditionalTargets = WatcherRegistry.isWatchingTargets(
    watcher,
    Targets.TYPES.FRAME
  );
  if (watchingAdditionalTargets) {
    return watcher.getAllBrowsingContexts();
  }
  // By default, when we are no longer watching for frame targets, we should no longer try to
  // communicate with any browsing-context. But.
  //
  // For "browser-element" debugging, all targets are provided by watching by watching for frame targets.
  // So, when we are no longer watching for frame, we don't expect to have any frame target to talk to.
  // => we should no longer reach any browsing context.
  //
  // For "all" (=browser toolbox), there is only the special ParentProcessTargetActor we might want to return here.
  // But this is actually handled by the WatcherActor which uses `WatcherActor.getTargetActorInParentProcess` to convey session data.
  // => we should no longer reach any browsing context.
  //
  // For "webextension" debugging, there is the special WebExtensionTargetActor, which doesn't run in the parent process,
  // so that we can't rely on the same code as the browser toolbox.
  // => we should always reach out this particular browsing context.
  if (watcher.sessionContext.type == "webextension") {
    const browsingContext = BrowsingContext.get(
      watcher.sessionContext.addonBrowsingContextID
    );
    // The add-on browsing context may be destroying, in which case we shouldn't try to communicate with it
    if (browsingContext.currentWindowGlobal) {
      return [browsingContext];
    }
  }
  return [];
}

// Set to true to log info about about WindowGlobal's being watched.
const DEBUG = false;

function logWindowGlobal(windowGlobal, message) {
  if (!DEBUG) {
    return;
  }

  WindowGlobalLogger.logWindowGlobal(windowGlobal, message);
}