summaryrefslogtreecommitdiffstats
path: root/devtools/client/aboutdebugging/src/middleware/worker-component-data.js
blob: 178c99e32288d029a33ba15ff965662f594ef39b (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
/* 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/. */

"use strict";

const {
  DEBUG_TARGETS,
  REQUEST_WORKERS_SUCCESS,
  SERVICE_WORKER_FETCH_STATES,
  SERVICE_WORKER_STATUSES,
} = require("resource://devtools/client/aboutdebugging/src/constants.js");

/**
 * This middleware converts workers object that get from DevToolsClient.listAllWorkers()
 * to data which is used in DebugTargetItem.
 */
const workerComponentDataMiddleware = store => next => action => {
  switch (action.type) {
    case REQUEST_WORKERS_SUCCESS: {
      action.otherWorkers = toComponentData(action.otherWorkers);
      action.serviceWorkers = toComponentData(action.serviceWorkers, true);
      action.sharedWorkers = toComponentData(action.sharedWorkers);
      break;
    }
  }

  return next(action);
};

function getServiceWorkerStatus(worker) {
  const isActive = worker.state === Ci.nsIServiceWorkerInfo.STATE_ACTIVATED;
  const isRunning = !!worker.workerDescriptorFront;

  if (isActive && isRunning) {
    return SERVICE_WORKER_STATUSES.RUNNING;
  } else if (isActive) {
    return SERVICE_WORKER_STATUSES.STOPPED;
  }

  // We cannot get service worker registrations unless the registration is in
  // ACTIVE state. Unable to know the actual state ("installing", "waiting"), we
  // display a custom state "registering" for now. See Bug 1153292.
  return SERVICE_WORKER_STATUSES.REGISTERING;
}

function toComponentData(workers, isServiceWorker) {
  return workers.map(worker => {
    // Here `worker` is the worker object created by RootFront.listAllWorkers
    const type = DEBUG_TARGETS.WORKER;
    const icon = "chrome://devtools/skin/images/debugging-workers.svg";
    let { fetch } = worker;
    const { id, name, registrationFront, scope, subscription } = worker;

    let pushServiceEndpoint = null;
    let status = null;

    if (isServiceWorker) {
      fetch = fetch
        ? SERVICE_WORKER_FETCH_STATES.LISTENING
        : SERVICE_WORKER_FETCH_STATES.NOT_LISTENING;
      status = getServiceWorkerStatus(worker);
      pushServiceEndpoint = subscription ? subscription.endpoint : null;
    }

    return {
      details: {
        fetch,
        pushServiceEndpoint,
        registrationFront,
        scope,
        status,
      },
      icon,
      id,
      name,
      type,
    };
  });
}

module.exports = workerComponentDataMiddleware;