summaryrefslogtreecommitdiffstats
path: root/toolkit/modules/subprocess/subprocess_worker_common.js
blob: a0370326d71cae5778523a266289fe4bb7774359 (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
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* 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";

// This file is loaded into the same context as subprocess_worker_unix.js
// and subprocess_worker_win.js
/* import-globals-from subprocess_worker_unix.js */

/* exported BasePipe, BaseProcess, debug */

function debug(message) {
  self.postMessage({ msg: "debug", message });
}

class BasePipe {
  constructor() {
    this.closing = false;
    this.closed = false;

    this.closedPromise = new Promise(resolve => {
      this.resolveClosed = resolve;
    });

    this.pending = [];
  }

  shiftPending() {
    let result = this.pending.shift();

    if (this.closing && !this.pending.length) {
      this.close();
    }

    return result;
  }
}

let nextProcessId = 0;

class BaseProcess {
  constructor(options) {
    this.id = nextProcessId++;

    this.exitCode = null;

    this.exitPromise = new Promise(resolve => {
      this.resolveExit = resolve;
    });
    this.exitPromise.then(() => {
      // The input file descriptors will be closed after poll
      // reports that their input buffers are empty. If we close
      // them now, we may lose output.
      this.pipes[0].close(true);
    });

    this.pid = null;
    this.pipes = [];

    this.spawn(options);
  }

  /**
   * Waits for the process to exit and all of its pending IO operations to
   * complete.
   *
   * @returns {Promise<void>}
   */
  awaitFinished() {
    return Promise.all([
      this.exitPromise,
      ...this.pipes.map(pipe => pipe.closedPromise),
    ]);
  }
}

let requests = {
  init(details) {
    io.init(details);

    return { data: {} };
  },

  shutdown() {
    io.shutdown();

    return { data: {} };
  },

  close(pipeId, force = false) {
    let pipe = io.getPipe(pipeId);

    return pipe.close(force).then(() => ({ data: {} }));
  },

  spawn(options) {
    let process = new Process(options);
    let processId = process.id;

    io.addProcess(process);

    let fds = process.pipes.map(pipe => pipe.id);

    return { data: { processId, fds, pid: process.pid } };
  },

  kill(processId, force = false) {
    let process = io.getProcess(processId);

    process.kill(force ? 9 : 15);

    return { data: {} };
  },

  wait(processId) {
    let process = io.getProcess(processId);

    process.wait();

    process.awaitFinished().then(() => {
      io.cleanupProcess(process);
    });

    return process.exitPromise.then(exitCode => {
      return { data: { exitCode } };
    });
  },

  read(pipeId, count) {
    let pipe = io.getPipe(pipeId);

    return pipe.read(count).then(buffer => {
      return { data: { buffer } };
    });
  },

  write(pipeId, buffer) {
    let pipe = io.getPipe(pipeId);

    return pipe.write(buffer).then(bytesWritten => {
      return { data: { bytesWritten } };
    });
  },

  getOpenFiles() {
    return { data: new Set(io.pipes.keys()) };
  },

  getProcesses() {
    let data = new Map(
      Array.from(io.processes.values())
        .filter(proc => proc.exitCode == null)
        .map(proc => [proc.id, proc.pid])
    );
    return { data };
  },

  waitForNoProcesses() {
    return Promise.all(
      Array.from(io.processes.values(), proc => proc.awaitFinished())
    );
  },
};

onmessage = event => {
  io.messageCount--;

  let { msg, msgId, args } = event.data;

  new Promise(resolve => {
    resolve(requests[msg](...args));
  })
    .then(result => {
      let response = {
        msg: "success",
        msgId,
        data: result.data,
      };

      self.postMessage(response, result.transfer || []);
    })
    .catch(error => {
      if (error instanceof Error) {
        error = {
          message: error.message,
          fileName: error.fileName,
          lineNumber: error.lineNumber,
          column: error.column,
          stack: error.stack,
          errorCode: error.errorCode,
        };
      }

      self.postMessage({
        msg: "failure",
        msgId,
        error,
      });
    })
    .catch(error => {
      console.error(error);

      self.postMessage({
        msg: "failure",
        msgId,
        error: {},
      });
    });
};