summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_background_service_worker.js
blob: 2efbc52739436c5ce0f816c19520da504c7d1260 (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
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";

const { TestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/TestUtils.sys.mjs"
);

ChromeUtils.defineESModuleGetters(this, {
  AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
});

AddonTestUtils.init(this);
AddonTestUtils.createAppInfo(
  "xpcshell@tests.mozilla.org",
  "XPCShell",
  "1",
  "42"
);
AddonTestUtils.overrideCertDB();

add_task(async function setup() {
  ok(
    WebExtensionPolicy.useRemoteWebExtensions,
    "Expect remote-webextensions mode enabled"
  );
  ok(
    WebExtensionPolicy.backgroundServiceWorkerEnabled,
    "Expect remote-webextensions mode enabled"
  );

  await AddonTestUtils.promiseStartupManager();

  Services.prefs.setBoolPref("dom.serviceWorkers.testing.enabled", true);

  registerCleanupFunction(() => {
    Services.prefs.clearUserPref("dom.serviceWorkers.testing.enabled");
    Services.prefs.clearUserPref("dom.serviceWorkers.idle_timeout");
  });
});

add_task(
  async function test_fail_spawn_extension_worker_for_disabled_extension() {
    const extension = ExtensionTestUtils.loadExtension({
      useAddonManager: "temporary",
      manifest: {
        version: "1.0",
        background: {
          service_worker: "sw.js",
        },
        browser_specific_settings: { gecko: { id: "test-bg-sw@mochi.test" } },
      },
      files: {
        "page.html": "<!DOCTYPE html><body></body>",
        "sw.js": "dump('Background ServiceWorker - executed\\n');",
      },
    });

    const testWorkerWatcher = new TestWorkerWatcher();
    let watcher = await testWorkerWatcher.watchExtensionServiceWorker(
      extension
    );

    await extension.startup();

    info("Wait for the background service worker to be spawned");

    ok(
      await watcher.promiseWorkerSpawned,
      "The extension service worker has been spawned as expected"
    );

    info("Wait for the background service worker to be terminated");
    ok(
      await watcher.terminate(),
      "The extension service worker has been terminated as expected"
    );

    const swReg = testWorkerWatcher.getRegistration(extension);
    ok(swReg, "Got a service worker registration");
    ok(swReg?.activeWorker, "Got an active worker");

    info("Spawn the active worker by attaching the debugger");

    watcher = await testWorkerWatcher.watchExtensionServiceWorker(extension);

    swReg.activeWorker.attachDebugger();
    info(
      "Wait for the background service worker to be spawned after attaching the debugger"
    );
    ok(
      await watcher.promiseWorkerSpawned,
      "The extension service worker has been spawned as expected"
    );

    swReg.activeWorker.detachDebugger();
    info(
      "Wait for the background service worker to be terminated after detaching the debugger"
    );
    ok(
      await watcher.terminate(),
      "The extension service worker has been terminated as expected"
    );

    info(
      "Disabling the addon policy, and then double-check that the worker can't be spawned"
    );
    const policy = WebExtensionPolicy.getByID(extension.id);
    policy.active = false;

    await Assert.throws(
      () => swReg.activeWorker.attachDebugger(),
      /InvalidStateError/,
      "Got the expected extension when trying to spawn a worker for a disabled addon"
    );

    info(
      "Enabling the addon policy and double-check the worker is spawned successfully"
    );
    policy.active = true;

    watcher = await testWorkerWatcher.watchExtensionServiceWorker(extension);

    swReg.activeWorker.attachDebugger();
    info(
      "Wait for the background service worker to be spawned after attaching the debugger"
    );
    ok(
      await watcher.promiseWorkerSpawned,
      "The extension service worker has been spawned as expected"
    );

    swReg.activeWorker.detachDebugger();
    info(
      "Wait for the background service worker to be terminated after detaching the debugger"
    );
    ok(
      await watcher.terminate(),
      "The extension service worker has been terminated as expected"
    );

    await testWorkerWatcher.destroy();
    await extension.unload();
  }
);

add_task(async function test_serviceworker_lifecycle_events() {
  async function assertLifecycleEvents({ extension, expected, message }) {
    const getLifecycleEvents = async () => {
      const { active } = await this.content.navigator.serviceWorker.ready;
      const { port1, port2 } = new content.MessageChannel();

      return new Promise(resolve => {
        port1.onmessage = msg => resolve(msg.data.lifecycleEvents);
        active.postMessage("test", [port2]);
      });
    };
    const page = await ExtensionTestUtils.loadContentPage(
      extension.extension.baseURI.resolve("page.html"),
      { extension }
    );
    Assert.deepEqual(
      await page.spawn([], getLifecycleEvents),
      expected,
      `Got the expected lifecycle events on ${message}`
    );
    await page.close();
  }

  const swm = Cc["@mozilla.org/serviceworkers/manager;1"].getService(
    Ci.nsIServiceWorkerManager
  );

  const extension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      version: "1.0",
      background: {
        service_worker: "sw.js",
      },
      browser_specific_settings: { gecko: { id: "test-bg-sw@mochi.test" } },
    },
    files: {
      "page.html": "<!DOCTYPE html><body></body>",
      "sw.js": `
        dump('Background ServiceWorker - executed\\n');

        const lifecycleEvents = [];
        self.oninstall = () => {
          dump('Background ServiceWorker - oninstall\\n');
          lifecycleEvents.push("install");
        };
        self.onactivate = () => {
          dump('Background ServiceWorker - onactivate\\n');
          lifecycleEvents.push("activate");
        };
        self.onmessage = (evt) => {
          dump('Background ServiceWorker - onmessage\\n');
          evt.ports[0].postMessage({ lifecycleEvents });
          dump('Background ServiceWorker - postMessage\\n');
        };
      `,
    },
  });

  const testWorkerWatcher = new TestWorkerWatcher();
  let watcher = await testWorkerWatcher.watchExtensionServiceWorker(extension);

  await extension.startup();

  await assertLifecycleEvents({
    extension,
    expected: ["install", "activate"],
    message: "initial worker registration",
  });

  const file = Services.dirsvc.get("ProfD", Ci.nsIFile);
  file.append("serviceworker.txt");
  await TestUtils.waitForCondition(
    () => file.exists(),
    "Wait for service worker registrations to have been dumped on disk"
  );

  const managerShutdownCompleted = AddonTestUtils.promiseShutdownManager();

  const firstSwReg = swm.getRegistrationByPrincipal(
    extension.extension.principal,
    extension.extension.principal.spec
  );
  // Force the worker shutdown (in normal condition the worker would have been
  // terminated as part of the entire application shutting down).
  firstSwReg.forceShutdown();

  info(
    "Wait for the background service worker to be terminated while the app is shutting down"
  );
  ok(
    await watcher.promiseWorkerTerminated,
    "The extension service worker has been terminated as expected"
  );
  await managerShutdownCompleted;

  Assert.equal(
    firstSwReg,
    swm.getRegistrationByPrincipal(
      extension.extension.principal,
      extension.extension.principal.spec
    ),
    "Expect the service worker to not be unregistered on application shutdown"
  );

  info("Restart AddonManager (mocking Browser instance restart)");
  // Start the addon manager with `earlyStartup: false` to keep the background service worker
  // from being started right away:
  //
  // - the call to `swm.reloadRegistrationForTest()` that follows is making sure that
  //   the previously registered service worker is in the same state it would be when
  //   the entire browser is restarted.
  //
  // - if the background service worker is being spawned again by the time we call
  //   `swm.reloadRegistrationForTest()`, ServiceWorkerUpdateJob would fail and trigger
  //   an `mState == State::Started` diagnostic assertion from ServiceWorkerJob::Finish
  //   and the xpcshell test will fail for the crash triggered by the assertion.
  await AddonTestUtils.promiseStartupManager({ lateStartup: false });
  await extension.awaitStartup();

  info(
    "Force reload ServiceWorkerManager registrations (mocking a Browser instance restart)"
  );
  swm.reloadRegistrationsForTest();

  info(
    "trigger delayed call to nsIServiceWorkerManager.registerForAddonPrincipal"
  );
  // complete the startup notifications, then start the background
  AddonTestUtils.notifyLateStartup();
  extension.extension.emit("start-background-script");

  info("Force activate the extension worker");
  const newSwReg = swm.getRegistrationByPrincipal(
    extension.extension.principal,
    extension.extension.principal.spec
  );

  Assert.notEqual(
    newSwReg,
    firstSwReg,
    "Expect the service worker registration to have been recreated"
  );

  await assertLifecycleEvents({
    extension,
    expected: [],
    message: "on previous registration loaded",
  });

  const { principal } = extension.extension;
  const addon = await AddonManager.getAddonByID(extension.id);
  await addon.disable();

  ok(
    await watcher.promiseWorkerTerminated,
    "The extension service worker has been terminated as expected"
  );

  Assert.throws(
    () => swm.getRegistrationByPrincipal(principal, principal.spec),
    /NS_ERROR_FAILURE/,
    "Expect the service worker to have been unregistered on addon disabled"
  );

  await addon.enable();
  await assertLifecycleEvents({
    extension,
    expected: ["install", "activate"],
    message: "on disabled addon re-enabled",
  });

  await testWorkerWatcher.destroy();
  await extension.unload();
});