summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/worker-utils.js
blob: bb5c54dac31abef20f0894e1085996a6a41371dc (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
/* 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";

class WorkerDispatcher {
  #msgId = 1;
  #worker = null;
  // Map of message ids -> promise resolution functions, for dispatching worker responses
  #pendingCalls = new Map();
  #url = "";

  constructor(url) {
    this.#url = url;
  }

  start() {
    // When running in debugger jest test, we don't have access to ChromeWorker
    if (typeof ChromeWorker == "function") {
      this.#worker = new ChromeWorker(this.#url);
    } else {
      this.#worker = new Worker(this.#url);
    }
    this.#worker.onerror = err => {
      console.error(`Error in worker ${this.#url}`, err.message);
    };
    this.#worker.addEventListener("message", this.#onMessage);
  }

  stop() {
    if (!this.#worker) {
      return;
    }

    this.#worker.removeEventListener("message", this.#onMessage);
    this.#worker.terminate();
    this.#worker = null;
    this.#pendingCalls.clear();
  }

  task(method, { queue = false } = {}) {
    const calls = [];
    const push = args => {
      return new Promise((resolve, reject) => {
        if (queue && calls.length === 0) {
          Promise.resolve().then(flush);
        }

        calls.push({ args, resolve, reject });

        if (!queue) {
          flush();
        }
      });
    };

    const flush = () => {
      const items = calls.slice();
      calls.length = 0;

      if (!this.#worker) {
        this.start();
      }

      const id = this.#msgId++;
      this.#worker.postMessage({
        id,
        method,
        calls: items.map(item => item.args),
      });

      this.#pendingCalls.set(id, items);
    };

    return (...args) => push(args);
  }

  invoke(method, ...args) {
    return this.task(method)(...args);
  }

  #onMessage = ({ data: result }) => {
    const items = this.#pendingCalls.get(result.id);
    this.#pendingCalls.delete(result.id);
    if (!items) {
      return;
    }

    if (!this.#worker) {
      return;
    }

    result.results.forEach((resultData, i) => {
      const { resolve, reject } = items[i];

      if (resultData.error) {
        const err = new Error(resultData.message);
        err.metadata = resultData.metadata;
        reject(err);
      } else {
        resolve(resultData.response);
      }
    });
  };
}

function workerHandler(publicInterface) {
  return function (msg) {
    const { id, method, calls } = msg.data;

    Promise.all(
      calls.map(args => {
        try {
          const response = publicInterface[method].apply(undefined, args);
          if (response instanceof Promise) {
            return response.then(
              val => ({ response: val }),
              err => asErrorMessage(err)
            );
          }
          return { response };
        } catch (error) {
          return asErrorMessage(error);
        }
      })
    ).then(results => {
      globalThis.postMessage({ id, results });
    });
  };
}

function asErrorMessage(error) {
  if (typeof error === "object" && error && "message" in error) {
    // Error can't be sent via postMessage, so be sure to convert to
    // string.
    return {
      error: true,
      message: error.message,
      metadata: error.metadata,
    };
  }

  return {
    error: true,
    message: error == null ? error : error.toString(),
    metadata: undefined,
  };
}

// Might be loaded within a worker thread where `module` isn't available.
if (typeof module !== "undefined") {
  module.exports = {
    WorkerDispatcher,
    workerHandler,
  };
}