summaryrefslogtreecommitdiffstats
path: root/devtools/server/connectors/js-process-actor/DevToolsProcessParent.sys.mjs
blob: 303c85e68f7f2fccadd8abf9977f0c942b9d41dd (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
/* 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/. */

import { loader } from "resource://devtools/shared/loader/Loader.sys.mjs";
import { EventEmitter } from "resource://gre/modules/EventEmitter.sys.mjs";

const { ParentProcessWatcherRegistry } = ChromeUtils.importESModule(
  "resource://devtools/server/actors/watcher/ParentProcessWatcherRegistry.sys.mjs",
  // ParentProcessWatcherRegistry needs to be a true singleton and loads ActorManagerParent
  // which also has to be a true singleton.
  { global: "shared" }
);

const lazy = {};
loader.lazyRequireGetter(
  lazy,
  "JsWindowActorTransport",
  "devtools/shared/transport/js-window-actor-transport",
  true
);

export class DevToolsProcessParent extends JSProcessActorParent {
  constructor() {
    super();

    // Map of DevToolsServerConnection's used to forward the messages from/to
    // the client. The connections run in the parent process, as this code. We
    // may have more than one when there is more than one client debugging the
    // same frame. For example, a content toolbox and the browser toolbox.
    //
    // The map is indexed by the connection prefix.
    // The values are objects containing the following properties:
    // - actor: the frame target actor(as a form)
    // - connection: the DevToolsServerConnection used to communicate with the
    //   frame target actor
    // - prefix: the forwarding prefix used by the connection to know
    //   how to forward packets to the frame target
    // - transport: the JsWindowActorTransport
    //
    // Reminder about prefixes: all DevToolsServerConnections have a `prefix`
    // which can be considered as a kind of id. On top of this, parent process
    // DevToolsServerConnections also have forwarding prefixes because they are
    // responsible for forwarding messages to content process connections.

    EventEmitter.decorate(this);
  }

  #destroyed = false;
  #connections = new Map();

  /**
   * Request the content process to create all the targets currently watched
   * and start observing for new ones to be created later.
   */
  watchTargets({ watcherActorID, targetType }) {
    return this.sendQuery("DevToolsProcessParent:watchTargets", {
      watcherActorID,
      targetType,
    });
  }

  /**
   * Request the content process to stop observing for currently watched targets
   * and destroy all the currently active ones.
   */
  unwatchTargets({ watcherActorID, targetType, options }) {
    this.sendAsyncMessage("DevToolsProcessParent:unwatchTargets", {
      watcherActorID,
      targetType,
      options,
    });
  }

  /**
   * Communicate to the content process that some data have been added or set.
   */
  addOrSetSessionDataEntry({ watcherActorID, type, entries, updateType }) {
    return this.sendQuery("DevToolsProcessParent:addOrSetSessionDataEntry", {
      watcherActorID,
      type,
      entries,
      updateType,
    });
  }

  /**
   * Communicate to the content process that some data have been removed.
   */
  removeSessionDataEntry({ watcherActorID, type, entries }) {
    this.sendAsyncMessage("DevToolsProcessParent:removeSessionDataEntry", {
      watcherActorID,
      type,
      entries,
    });
  }

  destroyWatcher({ watcherActorID }) {
    return this.sendAsyncMessage("DevToolsProcessParent:destroyWatcher", {
      watcherActorID,
    });
  }

  /**
   * Called when the content process notified us about a new target actor
   */
  #onTargetAvailable({ watcherActorID, forwardingPrefix, targetActorForm }) {
    const watcher = ParentProcessWatcherRegistry.getWatcher(watcherActorID);

    if (!watcher) {
      throw new Error(
        `Watcher Actor with ID '${watcherActorID}' can't be found.`
      );
    }
    const connection = watcher.conn;

    // If this is the first target actor for this watcher,
    // hook up the DevToolsServerConnection which will bridge
    // communication between the parent process DevToolsServer
    // and the content process.
    if (!this.#connections.get(watcher.conn.prefix)) {
      connection.on("closed", this.#onConnectionClosed);

      // Create a js-window-actor based transport.
      const transport = new lazy.JsWindowActorTransport(
        this,
        forwardingPrefix,
        "DevToolsProcessParent:packet"
      );
      transport.hooks = {
        onPacket: connection.send.bind(connection),
        onClosed() {},
      };
      transport.ready();

      connection.setForwarding(forwardingPrefix, transport);

      this.#connections.set(watcher.conn.prefix, {
        watcher,
        connection,
        // This prefix is the prefix of the DevToolsServerConnection, running
        // in the content process, for which we should forward packets to, based on its prefix.
        // While `watcher.connection` is also a DevToolsServerConnection, but from this process,
        // the parent process. It is the one receiving Client packets and the one, from which
        // we should forward packets from.
        forwardingPrefix,
        transport,
        targetActorForms: [],
      });
    }

    this.#connections
      .get(watcher.conn.prefix)
      .targetActorForms.push(targetActorForm);

    watcher.notifyTargetAvailable(targetActorForm);
  }

  /**
   * Called when the content process notified us about a target actor that has been destroyed.
   */
  #onTargetDestroyed({ actors, options }) {
    for (const { watcherActorID, targetActorForm } of actors) {
      const watcher = ParentProcessWatcherRegistry.getWatcher(watcherActorID);
      // As we instruct to destroy all targets when the watcher is destroyed,
      // we may easily receive the target destruction notification *after*
      // the watcher has been removed from the registry.
      if (!watcher || watcher.isDestroyed()) {
        continue;
      }
      watcher.notifyTargetDestroyed(targetActorForm, options);
      const connectionInfo = this.#connections.get(watcher.conn.prefix);
      if (connectionInfo) {
        const idx = connectionInfo.targetActorForms.findIndex(
          form => form.actor == targetActorForm.actor
        );
        if (idx != -1) {
          connectionInfo.targetActorForms.splice(idx, 1);
        }
        // Once the last active target is removed, disconnect the DevTools transport
        // and cleanup everything bound to this DOM Process. We will re-instantiate
        // a new connection/transport on the next reported target actor.
        if (!connectionInfo.targetActorForms.length) {
          this.#cleanupConnection(connectionInfo.connection);
        }
      }
    }
  }

  #onConnectionClosed = (status, prefix) => {
    if (this.#connections.has(prefix)) {
      const { connection } = this.#connections.get(prefix);
      this.#cleanupConnection(connection);
    }
  };

  /**
   * Close and unregister a given DevToolsServerConnection.
   *
   * @param {DevToolsServerConnection} connection
   * @param {object} options
   * @param {boolean} options.isModeSwitching
   *        true when this is called as the result of a change to the devtools.browsertoolbox.scope pref
   */
  async #cleanupConnection(connection, options = {}) {
    const watcherConnectionInfo = this.#connections.get(connection.prefix);
    if (watcherConnectionInfo) {
      const { forwardingPrefix, transport } = watcherConnectionInfo;
      if (transport) {
        // If we have a child transport, the actor has already
        // been created. We need to stop using this transport.
        transport.close(options);
      }
      // When cancelling the forwarding, one RDP event is sent to the client to purge all requests
      // and actors related to a given prefix.
      // Be careful that any late RDP event would be ignored by the client passed this call.
      connection.cancelForwarding(forwardingPrefix);
    }

    connection.off("closed", this.#onConnectionClosed);

    this.#connections.delete(connection.prefix);
    if (!this.#connections.size) {
      this.#destroy(options);
    }
  }

  /**
   * Destroy and cleanup everything for this DOM Process.
   *
   * @param {object} options
   * @param {boolean} options.isModeSwitching
   *        true when this is called as the result of a change to the devtools.browsertoolbox.scope pref
   */
  #destroy(options) {
    if (this.#destroyed) {
      return;
    }
    this.#destroyed = true;

    for (const {
      targetActorForms,
      connection,
      watcher,
    } of this.#connections.values()) {
      for (const actor of targetActorForms) {
        watcher.notifyTargetDestroyed(actor, options);
      }
      this.#cleanupConnection(connection, options);
    }
  }

  /**
   * Used by DevTools Transport to send packets to the content process.
   */

  sendPacket(packet, prefix) {
    this.sendAsyncMessage("DevToolsProcessParent:packet", { packet, prefix });
  }

  /**
   * JsProcessActor API
   */

  async sendQuery(msg, args) {
    try {
      const res = await super.sendQuery(msg, args);
      return res;
    } catch (e) {
      console.error("Failed to sendQuery in DevToolsProcessParent", msg);
      console.error(e.toString());
      throw e;
    }
  }

  /**
   * Called by the JSProcessActor API when the content process sent us a message
   */
  receiveMessage(message) {
    switch (message.name) {
      case "DevToolsProcessChild:targetAvailable":
        return this.#onTargetAvailable(message.data);
      case "DevToolsProcessChild:packet":
        return this.emit("packet-received", message);
      case "DevToolsProcessChild:targetDestroyed":
        return this.#onTargetDestroyed(message.data);
      case "DevToolsProcessChild:bf-cache-navigation-pageshow": {
        const browsingContext = BrowsingContext.get(
          message.data.browsingContextId
        );
        for (const watcherActor of ParentProcessWatcherRegistry.getWatchersForBrowserId(
          browsingContext.browserId
        )) {
          watcherActor.emit("bf-cache-navigation-pageshow", {
            windowGlobal: browsingContext.currentWindowGlobal,
          });
        }
        return null;
      }
      case "DevToolsProcessChild:bf-cache-navigation-pagehide": {
        const browsingContext = BrowsingContext.get(
          message.data.browsingContextId
        );
        for (const watcherActor of ParentProcessWatcherRegistry.getWatchersForBrowserId(
          browsingContext.browserId
        )) {
          watcherActor.emit("bf-cache-navigation-pagehide", {
            windowGlobal: browsingContext.currentWindowGlobal,
          });
        }
        return null;
      }
      default:
        throw new Error(
          "Unsupported message in DevToolsProcessParent: " + message.name
        );
    }
  }

  /**
   * Called by the JSProcessActor API when this content process is destroyed.
   */
  didDestroy() {
    this.#destroy();
  }
}

export class BrowserToolboxDevToolsProcessParent extends DevToolsProcessParent {}