summaryrefslogtreecommitdiffstats
path: root/dom/push/PushBroadcastService.sys.mjs
blob: eea31ef1921ce5b350ac1c94a44594de37e50df9 (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
/* 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, {
  JSONFile: "resource://gre/modules/JSONFile.sys.mjs",
  PushService: "resource://gre/modules/PushService.sys.mjs",
});

// BroadcastService is exported for test purposes.
// We are supposed to ignore any updates with this version.
const DUMMY_VERSION_STRING = "____NOP____";

ChromeUtils.defineLazyGetter(lazy, "console", () => {
  let { ConsoleAPI } = ChromeUtils.importESModule(
    "resource://gre/modules/Console.sys.mjs"
  );
  return new ConsoleAPI({
    maxLogLevelPref: "dom.push.loglevel",
    prefix: "BroadcastService",
  });
});

class InvalidSourceInfo extends Error {
  constructor(message) {
    super(message);
    this.name = "InvalidSourceInfo";
  }
}

const BROADCAST_SERVICE_VERSION = 1;

export var BroadcastService = class {
  constructor(pushService, path) {
    this.PHASES = {
      HELLO: "hello",
      REGISTER: "register",
      BROADCAST: "broadcast",
    };

    this.pushService = pushService;
    this.jsonFile = new lazy.JSONFile({
      path,
      dataPostProcessor: this._initializeJSONFile,
    });
    this.initializePromise = this.jsonFile.load();
  }

  /**
   * Convert the listeners from our on-disk format to the format
   * needed by a hello message.
   */
  async getListeners() {
    await this.initializePromise;
    return Object.entries(this.jsonFile.data.listeners).reduce(
      (acc, [k, v]) => {
        acc[k] = v.version;
        return acc;
      },
      {}
    );
  }

  _initializeJSONFile(data) {
    if (!data.version) {
      data.version = BROADCAST_SERVICE_VERSION;
    }
    if (!data.hasOwnProperty("listeners")) {
      data.listeners = {};
    }
    return data;
  }

  /**
   * Reset to a state akin to what you would get in a new profile.
   * In particular, wipe anything from storage.
   *
   * Used mainly for testing.
   */
  async _resetListeners() {
    await this.initializePromise;
    this.jsonFile.data = this._initializeJSONFile({});
    this.initializePromise = Promise.resolve();
  }

  /**
   * Ensure that a sourceInfo is correct (has the expected fields).
   */
  _validateSourceInfo(sourceInfo) {
    const { moduleURI, symbolName } = sourceInfo;
    if (typeof moduleURI !== "string") {
      throw new InvalidSourceInfo(
        `moduleURI must be a string (got ${typeof moduleURI})`
      );
    }
    if (typeof symbolName !== "string") {
      throw new InvalidSourceInfo(
        `symbolName must be a string (got ${typeof symbolName})`
      );
    }
  }

  /**
   * Add an entry for a given listener if it isn't present, or update
   * one if it is already present.
   *
   * Note that this means only a single listener can be set for a
   * given subscription. This is a limitation in the current API that
   * stems from the fact that there can only be one source of truth
   * for the subscriber's version. As a workaround, you can define a
   * listener which calls multiple other listeners.
   *
   * @param {string} broadcastId The broadcastID to listen for
   * @param {string} version The most recent version we have for
   *   updates from this broadcastID
   * @param {Object} sourceInfo A description of the handler for
   *   updates on this broadcastID
   */
  async addListener(broadcastId, version, sourceInfo) {
    lazy.console.info(
      "addListener: adding listener",
      broadcastId,
      version,
      sourceInfo
    );
    await this.initializePromise;
    this._validateSourceInfo(sourceInfo);
    if (typeof version !== "string") {
      throw new TypeError("version should be a string");
    }
    if (!version) {
      throw new TypeError("version should not be an empty string");
    }

    const isNew = !this.jsonFile.data.listeners.hasOwnProperty(broadcastId);
    const oldVersion =
      !isNew && this.jsonFile.data.listeners[broadcastId].version;
    if (!isNew && oldVersion != version) {
      lazy.console.warn(
        "Versions differ while adding listener for",
        broadcastId,
        ". Got",
        version,
        "but JSON file says",
        oldVersion,
        "."
      );
    }

    // Update listeners before telling the pushService to subscribe,
    // in case it would disregard the update in the small window
    // between getting listeners and setting state to RUNNING.
    //
    // Keep the old version (if we have it) because Megaphone is
    // really the source of truth for the current version of this
    // broadcaster, and the old version is whatever we've either
    // gotten from Megaphone or what we've told to Megaphone and
    // haven't been corrected.
    this.jsonFile.data.listeners[broadcastId] = {
      version: oldVersion || version,
      sourceInfo,
    };
    this.jsonFile.saveSoon();

    if (isNew) {
      await this.pushService.subscribeBroadcast(broadcastId, version);
    }
  }

  /**
   * Call the listeners of the specified broadcasts.
   *
   * @param {Array<Object>} broadcasts Map between broadcast ids and versions.
   * @param {Object} context Additional information about the context in which the
   *  broadcast notification was originally received. This is transmitted to listeners.
   * @param {String} context.phase One of `BroadcastService.PHASES`
   */
  async receivedBroadcastMessage(broadcasts, context) {
    lazy.console.info("receivedBroadcastMessage:", broadcasts, context);
    await this.initializePromise;
    for (const broadcastId in broadcasts) {
      const version = broadcasts[broadcastId];
      if (version === DUMMY_VERSION_STRING) {
        lazy.console.info(
          "Ignoring",
          version,
          "because it's the dummy version"
        );
        continue;
      }
      // We don't know this broadcastID. This is probably a bug?
      if (!this.jsonFile.data.listeners.hasOwnProperty(broadcastId)) {
        lazy.console.warn(
          "receivedBroadcastMessage: unknown broadcastId",
          broadcastId
        );
        continue;
      }

      const { sourceInfo } = this.jsonFile.data.listeners[broadcastId];
      try {
        this._validateSourceInfo(sourceInfo);
      } catch (e) {
        lazy.console.error(
          "receivedBroadcastMessage: malformed sourceInfo",
          sourceInfo,
          e
        );
        continue;
      }

      const { moduleURI, symbolName } = sourceInfo;

      let module;
      try {
        module = ChromeUtils.importESModule(moduleURI);
      } catch (e) {
        lazy.console.error(
          "receivedBroadcastMessage: couldn't invoke",
          broadcastId,
          "because import of module",
          moduleURI,
          "failed",
          e
        );
        continue;
      }

      if (!module[symbolName]) {
        lazy.console.error(
          "receivedBroadcastMessage: couldn't invoke",
          broadcastId,
          "because module",
          moduleURI,
          "missing attribute",
          symbolName
        );
        continue;
      }

      const handler = module[symbolName];

      if (!handler.receivedBroadcastMessage) {
        lazy.console.error(
          "receivedBroadcastMessage: couldn't invoke",
          broadcastId,
          "because handler returned by",
          `${moduleURI}.${symbolName}`,
          "has no receivedBroadcastMessage method"
        );
        continue;
      }

      try {
        await handler.receivedBroadcastMessage(version, broadcastId, context);
      } catch (e) {
        lazy.console.error(
          "receivedBroadcastMessage: handler for",
          broadcastId,
          "threw error:",
          e
        );
        continue;
      }

      // Broadcast message applied successfully. Update the version we
      // received if it's different than the one we had.  We don't
      // enforce an ordering here (i.e. we use != instead of <)
      // because we don't know what the ordering of the service's
      // versions is going to be.
      if (this.jsonFile.data.listeners[broadcastId].version != version) {
        this.jsonFile.data.listeners[broadcastId].version = version;
        this.jsonFile.saveSoon();
      }
    }
  }

  // For test only.
  _saveImmediately() {
    return this.jsonFile._save();
  }
};

function initializeBroadcastService() {
  // Fallback path for xpcshell tests.
  let path = "broadcast-listeners.json";
  try {
    if (PathUtils.profileDir) {
      // Real path for use in a real profile.
      path = PathUtils.join(PathUtils.profileDir, path);
    }
  } catch (e) {}
  return new BroadcastService(lazy.PushService, path);
}

export var pushBroadcastService = initializeBroadcastService();