summaryrefslogtreecommitdiffstats
path: root/remote/shared/messagehandler/EventsDispatcher.sys.mjs
blob: 9620febcc1a8f264bcaa0c1c0d6b79fc5f07762f (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
/* 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/. */

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ContextDescriptorType:
    "chrome://remote/content/shared/messagehandler/MessageHandler.sys.mjs",
  Log: "chrome://remote/content/shared/Log.sys.mjs",
  SessionDataCategory:
    "chrome://remote/content/shared/messagehandler/sessiondata/SessionData.sys.mjs",
  SessionDataMethod:
    "chrome://remote/content/shared/messagehandler/sessiondata/SessionData.sys.mjs",
  TabManager: "chrome://remote/content/shared/TabManager.sys.mjs",
});

ChromeUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get());

/**
 * Helper to listen to events which rely on SessionData.
 * In order to support the EventsDispatcher, a module emitting events should
 * subscribe and unsubscribe to those events based on SessionData updates
 * and should use the "event" SessionData category.
 */
export class EventsDispatcher {
  // The MessageHandler owning this EventsDispatcher.
  #messageHandler;

  /**
   * @typedef {object} EventListenerInfo
   * @property {ContextDescriptor} contextDescriptor
   *     The ContextDescriptor to which those callbacks are associated
   * @property {Set<Function>} callbacks
   *     The callbacks to trigger when an event matching the ContextDescriptor
   *     is received.
   */

  // Map from event name to map of strings (context keys) to EventListenerInfo.
  #listenersByEventName;

  /**
   * Create a new EventsDispatcher instance.
   *
   * @param {MessageHandler} messageHandler
   *     The MessageHandler owning this EventsDispatcher.
   */
  constructor(messageHandler) {
    this.#messageHandler = messageHandler;

    this.#listenersByEventName = new Map();
  }

  destroy() {
    for (const event of this.#listenersByEventName.keys()) {
      this.#messageHandler.off(event, this.#onMessageHandlerEvent);
    }

    this.#listenersByEventName = null;
  }

  /**
   * Check for existing listeners for a given event name and a given context.
   *
   * @param {string} name
   *     Name of the event to check.
   * @param {ContextInfo} contextInfo
   *     ContextInfo identifying the context to check.
   *
   * @returns {boolean}
   *     True if there is a registered listener matching the provided arguments.
   */
  hasListener(name, contextInfo) {
    if (!this.#listenersByEventName.has(name)) {
      return false;
    }

    const listeners = this.#listenersByEventName.get(name);
    for (const { contextDescriptor } of listeners.values()) {
      if (this.#matchesContext(contextInfo, contextDescriptor)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Stop listening for an event relying on SessionData and relayed by the
   * message handler.
   *
   * @param {string} event
   *     Name of the event to unsubscribe from.
   * @param {ContextDescriptor} contextDescriptor
   *     Context descriptor for this event.
   * @param {Function} callback
   *     Event listener callback.
   * @returns {Promise}
   *     Promise which resolves when the event fully unsubscribed, including
   *     propagating the necessary session data.
   */
  async off(event, contextDescriptor, callback) {
    return this.update([{ event, contextDescriptor, callback, enable: false }]);
  }

  /**
   * Listen for an event relying on SessionData and relayed by the message
   * handler.
   *
   * @param {string} event
   *     Name of the event to subscribe to.
   * @param {ContextDescriptor} contextDescriptor
   *     Context descriptor for this event.
   * @param {Function} callback
   *     Event listener callback.
   * @returns {Promise}
   *     Promise which resolves when the event fully subscribed to, including
   *     propagating the necessary session data.
   */
  async on(event, contextDescriptor, callback) {
    return this.update([{ event, contextDescriptor, callback, enable: true }]);
  }

  /**
   * An object that holds information about subscription/unsubscription
   * of an event.
   *
   * @typedef Subscription
   *
   * @param {string} event
   *     Name of the event to subscribe/unsubscribe to.
   * @param {ContextDescriptor} contextDescriptor
   *     Context descriptor for this event.
   * @param {Function} callback
   *     Event listener callback.
   * @param {boolean} enable
   *     True, if we need to subscribe to an event.
   *     Otherwise false.
   */

  /**
   * Start or stop listening to a list of events relying on SessionData
   * and relayed by the message handler.
   *
   * @param {Array<Subscription>} subscriptions
   *     The list of information to subscribe/unsubscribe to.
   *
   * @returns {Promise}
   *     Promise which resolves when the events fully subscribed/unsubscribed to,
   *     including propagating the necessary session data.
   */
  async update(subscriptions) {
    const sessionDataItemUpdates = [];
    subscriptions.forEach(({ event, contextDescriptor, callback, enable }) => {
      if (enable) {
        // Setup listeners.
        if (!this.#listenersByEventName.has(event)) {
          this.#listenersByEventName.set(event, new Map());
          this.#messageHandler.on(event, this.#onMessageHandlerEvent);
        }

        const key = this.#getContextKey(contextDescriptor);
        const listeners = this.#listenersByEventName.get(event);
        if (listeners.has(key)) {
          const { callbacks } = listeners.get(key);
          callbacks.add(callback);
        } else {
          const callbacks = new Set([callback]);
          listeners.set(key, { callbacks, contextDescriptor });

          sessionDataItemUpdates.push({
            ...this.#getSessionDataItem(event, contextDescriptor),
            method: lazy.SessionDataMethod.Add,
          });
        }
      } else {
        // Remove listeners.
        const listeners = this.#listenersByEventName.get(event);
        if (!listeners) {
          return;
        }

        const key = this.#getContextKey(contextDescriptor);
        if (!listeners.has(key)) {
          return;
        }

        const { callbacks } = listeners.get(key);
        if (callbacks.has(callback)) {
          callbacks.delete(callback);
          if (callbacks.size === 0) {
            listeners.delete(key);
            if (listeners.size === 0) {
              this.#messageHandler.off(event, this.#onMessageHandlerEvent);
              this.#listenersByEventName.delete(event);
            }

            sessionDataItemUpdates.push({
              ...this.#getSessionDataItem(event, contextDescriptor),
              method: lazy.SessionDataMethod.Remove,
            });
          }
        }
      }
    });

    // Update all sessionData at once.
    await this.#messageHandler.updateSessionData(sessionDataItemUpdates);
  }

  #getContextKey(contextDescriptor) {
    const { id, type } = contextDescriptor;
    return `${type}-${id}`;
  }

  #getSessionDataItem(event, contextDescriptor) {
    const [moduleName] = event.split(".");
    return {
      moduleName,
      category: lazy.SessionDataCategory.Event,
      contextDescriptor,
      values: [event],
    };
  }

  #matchesContext(contextInfo, contextDescriptor) {
    if (contextDescriptor.type === lazy.ContextDescriptorType.All) {
      return true;
    }

    if (
      contextDescriptor.type === lazy.ContextDescriptorType.TopBrowsingContext
    ) {
      const eventBrowsingContext = lazy.TabManager.getBrowsingContextById(
        contextInfo.contextId
      );
      return eventBrowsingContext?.browserId === contextDescriptor.id;
    }

    return false;
  }

  #onMessageHandlerEvent = (name, event, contextInfo) => {
    const listeners = this.#listenersByEventName.get(name);
    for (const { callbacks, contextDescriptor } of listeners.values()) {
      if (!this.#matchesContext(contextInfo, contextDescriptor)) {
        continue;
      }

      for (const callback of callbacks) {
        try {
          callback(name, event);
        } catch (e) {
          lazy.logger.debug(
            `Error while executing callback for ${name}: ${e.message}`
          );
        }
      }
    }
  };
}