index.js
4.25 KB
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
'use strict';
var util = require('util');
var Duplex = require('readable-stream').Duplex;
function FirstChunkStream(options, cb) {
var _this = this;
var _state = {
sent: false,
chunks: [],
size: 0
};
if (!(this instanceof FirstChunkStream)) {
return new FirstChunkStream(options, cb);
}
options = options || {};
if (!(cb instanceof Function)) {
throw new Error('FirstChunkStream constructor requires a callback as its second argument.');
}
if (typeof options.chunkLength !== 'number') {
throw new Error('FirstChunkStream constructor requires `options.chunkLength` to be a number.');
}
if (options.objectMode) {
throw new Error('FirstChunkStream doesn\'t support `objectMode` yet.');
}
Duplex.call(this, options);
// Initialize the internal state
_state.manager = createReadStreamBackpressureManager(this);
// Errors management
// We need to execute the callback or emit en error dependending on the fact
// the firstChunk is sent or not
_state.errorHandler = function firstChunkStreamErrorHandler(err) {
processCallback(err, Buffer.concat(_state.chunks, _state.size), _state.encoding, function () {});
};
this.on('error', _state.errorHandler);
// Callback management
function processCallback(err, buf, encoding, done) {
// When doing sync writes + emiting an errror it can happen that
// Remove the error listener on the next tick if an error where fired
// to avoid unwanted error throwing
if (err) {
setImmediate(function () {
_this.removeListener('error', _state.errorHandler);
});
} else {
_this.removeListener('error', _state.errorHandler);
}
_state.sent = true;
cb(err, buf, encoding, function (err, buf, encoding) {
if (err) {
setImmediate(function () {
_this.emit('error', err);
});
return;
}
if (!buf) {
done();
return;
}
_state.manager.programPush(buf, encoding, done);
});
}
// Writes management
this._write = function firstChunkStreamWrite(chunk, encoding, done) {
_state.encoding = encoding;
if (_state.sent) {
_state.manager.programPush(chunk, _state.encoding, done);
} else if (chunk.length < options.chunkLength - _state.size) {
_state.chunks.push(chunk);
_state.size += chunk.length;
done();
} else {
_state.chunks.push(chunk.slice(0, options.chunkLength - _state.size));
chunk = chunk.slice(options.chunkLength - _state.size);
_state.size += _state.chunks[_state.chunks.length - 1].length;
processCallback(null, Buffer.concat(_state.chunks, _state.size), _state.encoding, function () {
if (!chunk.length) {
done();
return;
}
_state.manager.programPush(chunk, _state.encoding, done);
});
}
};
this.on('finish', function firstChunkStreamFinish() {
if (!_state.sent) {
return processCallback(null, Buffer.concat(_state.chunks, _state.size), _state.encoding, function () {
_state.manager.programPush(null, _state.encoding);
});
}
_state.manager.programPush(null, _state.encoding);
});
}
util.inherits(FirstChunkStream, Duplex);
// Utils to manage readable stream backpressure
function createReadStreamBackpressureManager(readableStream) {
var manager = {
waitPush: true,
programmedPushs: [],
programPush: function programPush(chunk, encoding, done) {
done = done || function () {};
// Store the current write
manager.programmedPushs.push([chunk, encoding, done]);
// Need to be async to avoid nested push attempts
// Programm a push attempt
setImmediate(manager.attemptPush);
// Let's say we're ready for a read
readableStream.emit('readable');
readableStream.emit('drain');
},
attemptPush: function () {
var nextPush;
if (manager.waitPush) {
if (manager.programmedPushs.length) {
nextPush = manager.programmedPushs.shift();
manager.waitPush = readableStream.push(nextPush[0], nextPush[1]);
(nextPush[2])();
}
} else {
setImmediate(function () {
// Need to be async to avoid nested push attempts
readableStream.emit('readable');
});
}
}
};
// Patch the readable stream to manage reads
readableStream._read = function streamFilterRestoreRead() {
manager.waitPush = true;
// Need to be async to avoid nested push attempts
setImmediate(manager.attemptPush);
};
return manager;
}
module.exports = FirstChunkStream;