summaryrefslogtreecommitdiff
path: root/lib/internal/wrap_js_stream.js
blob: 611095655b5a65b5e5b3ba4ad60e8b54d5ce4af5 (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
'use strict';

const assert = require('assert');
const util = require('util');
const { Socket } = require('net');
const { JSStream } = process.binding('js_stream');
const uv = process.binding('uv');
const debug = util.debuglog('stream_wrap');
const errors = require('internal/errors');

/* This class serves as a wrapper for when the C++ side of Node wants access
 * to a standard JS stream. For example, TLS or HTTP do not operate on network
 * resources conceptually, although that is the common case and what we are
 * optimizing for; in theory, they are completely composable and can work with
 * any stream resource they see.
 *
 * For the common case, i.e. a TLS socket wrapping around a net.Socket, we
 * can skip going through the JS layer and let TLS access the raw C++ handle
 * of a net.Socket. The flipside of this is that, to maintain composability,
 * we need a way to create "fake" net.Socket instances that call back into a
 * "real" JavaScript stream. JSStreamWrap is exactly this.
 */
class JSStreamWrap extends Socket {
  constructor(stream) {
    const handle = new JSStream();
    handle.close = (cb) => {
      debug('close');
      this.doClose(cb);
    };
    handle.isAlive = () => this.isAlive();
    handle.isClosing = () => this.isClosing();
    handle.onreadstart = () => this.readStart();
    handle.onreadstop = () => this.readStop();
    handle.onshutdown = (req) => this.doShutdown(req);
    handle.onwrite = (req, bufs) => this.doWrite(req, bufs);

    stream.pause();
    stream.on('error', (err) => this.emit('error', err));
    const ondata = (chunk) => {
      if (typeof chunk === 'string' ||
          stream._readableState.objectMode === true) {
        // Make sure that no further `data` events will happen.
        stream.pause();
        stream.removeListener('data', ondata);

        this.emit('error', new errors.Error('ERR_STREAM_WRAP'));
        return;
      }

      debug('data', chunk.length);
      if (this._handle)
        this._handle.readBuffer(chunk);
    };
    stream.on('data', ondata);
    stream.once('end', () => {
      debug('end');
      if (this._handle)
        this._handle.emitEOF();
    });

    super({ handle, manualStart: true });
    this.stream = stream;
    this._list = null;
    this.read(0);
  }

  // Legacy
  static get StreamWrap() {
    return JSStreamWrap;
  }

  isAlive() {
    return true;
  }

  isClosing() {
    return !this.readable || !this.writable;
  }

  readStart() {
    this.stream.resume();
    return 0;
  }

  readStop() {
    this.stream.pause();
    return 0;
  }

  doShutdown(req) {
    const handle = this._handle;
    const item = this._enqueue('shutdown', req);

    this.stream.end(() => {
      // Ensure that write was dispatched
      setImmediate(() => {
        if (!this._dequeue(item))
          return;

        handle.finishShutdown(req, 0);
      });
    });
    return 0;
  }

  doWrite(req, bufs) {
    const self = this;
    const handle = this._handle;

    var pending = bufs.length;

    // Queue the request to be able to cancel it
    const item = this._enqueue('write', req);

    this.stream.cork();
    for (var n = 0; n < bufs.length; n++)
      this.stream.write(bufs[n], done);
    this.stream.uncork();

    function done(err) {
      if (!err && --pending !== 0)
        return;

      // Ensure that this is called once in case of error
      pending = 0;

      let errCode = 0;
      if (err) {
        const code = uv[`UV_${err.code}`];
        errCode = (err.code && code) ? code : uv.UV_EPIPE;
      }

      // Ensure that write was dispatched
      setImmediate(function() {
        // Do not invoke callback twice
        if (!self._dequeue(item))
          return;

        handle.finishWrite(req, errCode);
      });
    }

    return 0;
  }

  _enqueue(type, req) {
    const item = new QueueItem(type, req);
    if (this._list === null) {
      this._list = item;
      return item;
    }

    item.next = this._list.next;
    item.prev = this._list;
    item.next.prev = item;
    item.prev.next = item;

    return item;
  }

  _dequeue(item) {
    assert(item instanceof QueueItem);

    var next = item.next;
    var prev = item.prev;

    if (next === null && prev === null)
      return false;

    item.next = null;
    item.prev = null;

    if (next === item) {
      prev = null;
      next = null;
    } else {
      prev.next = next;
      next.prev = prev;
    }

    if (this._list === item)
      this._list = next;

    return true;
  }

  doClose(cb) {
    const handle = this._handle;

    setImmediate(() => {
      while (this._list !== null) {
        const item = this._list;
        const req = item.req;
        this._dequeue(item);

        const errCode = uv.UV_ECANCELED;
        if (item.type === 'write') {
          handle.finishWrite(req, errCode);
        } else if (item.type === 'shutdown') {
          handle.finishShutdown(req, errCode);
        }
      }

      // Should be already set by net.js
      assert.strictEqual(this._handle, null);
      cb();
    });
  }
}

function QueueItem(type, req) {
  this.type = type;
  this.req = req;
  this.prev = this;
  this.next = this;
}

module.exports = JSStreamWrap;