summaryrefslogtreecommitdiffstats
path: root/dom/push/test/mockpushserviceparent.js
blob: a6089f6dad29ca00148828cca864623549d48b0a (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
/* eslint-env mozilla/chrome-script */

"use strict";

/**
 * Defers one or more callbacks until the next turn of the event loop. Multiple
 * callbacks are executed in order.
 *
 * @param {Function[]} callbacks The callbacks to execute. One callback will be
 *  executed per tick.
 */
function waterfall(...callbacks) {
  callbacks
    .reduce(
      (promise, callback) =>
        promise.then(() => {
          callback();
        }),
      Promise.resolve()
    )
    .catch(Cu.reportError);
}

/**
 * Minimal implementation of a mock WebSocket connect to be used with
 * PushService. Forwards and receive messages from the implementation
 * that lives in the content process.
 */
function MockWebSocketParent(originalURI) {
  this._originalURI = originalURI;
}

MockWebSocketParent.prototype = {
  _originalURI: null,

  _listener: null,
  _context: null,

  QueryInterface: ChromeUtils.generateQI(["nsIWebSocketChannel"]),

  get originalURI() {
    return this._originalURI;
  },

  asyncOpen(uri, origin, originAttributes, windowId, listener, context) {
    this._listener = listener;
    this._context = context;
    waterfall(() => this._listener.onStart(this._context));
  },

  sendMsg(msg) {
    sendAsyncMessage("socket-client-msg", msg);
  },

  close() {
    waterfall(() => this._listener.onStop(this._context, Cr.NS_OK));
  },

  serverSendMsg(msg) {
    waterfall(
      () => this._listener.onMessageAvailable(this._context, msg),
      () => this._listener.onAcknowledge(this._context, 0)
    );
  },
};

var pushService = Cc["@mozilla.org/push/Service;1"].getService(
  Ci.nsIPushService
).wrappedJSObject;

var mockSocket;
var serverMsgs = [];

addMessageListener("socket-setup", function () {
  pushService.replaceServiceBackend({
    serverURI: "wss://push.example.org/",
    makeWebSocket(uri) {
      mockSocket = new MockWebSocketParent(uri);
      while (serverMsgs.length) {
        let msg = serverMsgs.shift();
        mockSocket.serverSendMsg(msg);
      }
      return mockSocket;
    },
  });
});

addMessageListener("socket-teardown", function (msg) {
  pushService
    .restoreServiceBackend()
    .then(_ => {
      serverMsgs.length = 0;
      if (mockSocket) {
        mockSocket.close();
        mockSocket = null;
      }
      sendAsyncMessage("socket-server-teardown");
    })
    .catch(error => {
      Cu.reportError(`Error restoring service backend: ${error}`);
    });
});

addMessageListener("socket-server-msg", function (msg) {
  if (mockSocket) {
    mockSocket.serverSendMsg(msg);
  } else {
    serverMsgs.push(msg);
  }
});

var MockService = {
  requestID: 1,
  resolvers: new Map(),

  sendRequest(name, params) {
    return new Promise((resolve, reject) => {
      let id = this.requestID++;
      this.resolvers.set(id, { resolve, reject });
      sendAsyncMessage("service-request", {
        name,
        id,
        // The request params from the real push service may contain a
        // principal, which cannot be passed to the unprivileged
        // mochitest scope, and will cause the message to be dropped if
        // present. The mochitest scope fortunately does not need the
        // principal, though, so set it to null before sending.
        params: Object.assign({}, params, { principal: null }),
      });
    });
  },

  handleResponse(response) {
    if (!this.resolvers.has(response.id)) {
      Cu.reportError(`Unexpected response for request ${response.id}`);
      return;
    }
    let resolver = this.resolvers.get(response.id);
    this.resolvers.delete(response.id);
    if (response.error) {
      resolver.reject(response.error);
    } else {
      resolver.resolve(response.result);
    }
  },

  init() {},

  register(pageRecord) {
    return this.sendRequest("register", pageRecord);
  },

  registration(pageRecord) {
    return this.sendRequest("registration", pageRecord);
  },

  unregister(pageRecord) {
    return this.sendRequest("unregister", pageRecord);
  },

  reportDeliveryError(messageId, reason) {
    sendAsyncMessage("service-delivery-error", {
      messageId,
      reason,
    });
  },

  uninit() {
    return Promise.resolve();
  },
};

async function replaceService(service) {
  await pushService.service.uninit();
  pushService.service = service;
  await pushService.service.init();
}

addMessageListener("service-replace", function () {
  replaceService(MockService)
    .then(_ => {
      sendAsyncMessage("service-replaced");
    })
    .catch(error => {
      Cu.reportError(`Error replacing service: ${error}`);
    });
});

addMessageListener("service-restore", function () {
  replaceService(null)
    .then(_ => {
      sendAsyncMessage("service-restored");
    })
    .catch(error => {
      Cu.reportError(`Error restoring service: ${error}`);
    });
});

addMessageListener("service-response", function (response) {
  MockService.handleResponse(response);
});