Code coverage report for node/argstream.js

Statements: 94.55% (156 / 165)      Branches: 78.85% (41 / 52)      Functions: 96.15% (25 / 26)      Lines: 94.87% (148 / 156)      Ignored: none     

All files » node/ » argstream.js
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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269                                                                            1 1 1 1 1   1 2270 2270 2270 2270 2270   2270 2270 2270   2270 2270 2270 1       2270 1987   2270 2022       1   1 1055 203   852 852 852 852 852 852 852 852 852 1 2555 851 851         1   1 4020 4020   4020 851 851     3169       3169 4873 4873 4873   3169       1 2555 2555 2555   2555       1 2187 769   1418 1418 1418 1418 1418 1418 1418 1305   1418 1963   1418 2407     1418 1418   1418 1418   1418 1418 1418 1418 1418       1   1 9929 9929         9929                 9929 4254 2836     5675   9929     1 5675 5675 5675 5675 826   4849       1 9929 9929 3455 2037         1 3455 3455 3455 3455   3455 3454 3454 3454 3454     1 13620 6810   6810 6810 6810 6810   1   1 10505 10505 5916 5916   10505     1 108 108 108 108     1 108 108 108 108 1 124   1 108 108 108 108 108 108       1 1  
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
 
'use strict';
 
/*
 * Provides federated streams for handling call arguments
 *
 * InArgStream is for handling incoming arg parts from call frames.  It handles
 * dispatching the arg chunks into .arg{1,2,3} streams.
 *
 * OutArgStream is for creating outgoing arg parts by writing to .arg{1,2,3}
 * streams.  It handles buffering as many parts as are written within one event
 * loop tick into an Array of arg chunks.  Such array is then flushed using
 * setImmediate.
 *
 * Due to the semantic complexity involved here, this code is tested by an
 * accompanying exhaistive search test in test/argstream.js.  This test has
 * both unit tests (disabled by default for speed) and an integration test.
 */
 
var inherits = require('util').inherits;
var EventEmitter = require('./lib/event_emitter');
var PassThrough = require('readable-stream').PassThrough;
var Ready = require('ready-signal');
var errors = require('./errors');
 
function ArgStream() {
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.frameEvent = self.defineEvent('frame');
    self.finishEvent = self.defineEvent('finish');
 
    self.arg1 = StreamArg();
    self.arg2 = StreamArg();
    self.arg3 = StreamArg();
 
    self.arg1.on('error', passError);
    self.arg2.on('error', passError);
    self.arg3.on('error', passError);
    function passError(err) {
        self.errorEvent.emit(self, err);
    }
 
    self.arg2.on('start', function onArg2Start() {
        if (!self.arg1._writableState.ended) self.arg1.end();
    });
    self.arg3.on('start', function onArg3Start() {
        if (!self.arg2._writableState.ended) self.arg2.end();
    });
}
 
inherits(ArgStream, EventEmitter);
 
function InArgStream() {
    if (!(this instanceof InArgStream)) {
        return new InArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self.streams = [self.arg1, self.arg2, self.arg3];
    self._iStream = 0;
    self.finished = false;
    self._numFinished = 0;
    self.arg1.on('finish', argFinished);
    self.arg2.on('finish', argFinished);
    self.arg3.on('finish', argFinished);
    function argFinished() {
        if (++self._numFinished >= 3 && !self.finished) {
            self.finished = true;
            self.finishEvent.emit(self);
        }
    }
}
 
inherits(InArgStream, ArgStream);
 
InArgStream.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    var stream = self.streams[self._iStream];
 
    if (parts === null) {
        while (stream) stream = advance();
        return;
    }
 
    Iif (self.finished) {
        self.errorEvent.emit(self, new Error('arg stream finished')); // TODO typed error
    }
 
    for (var i = 0; i < parts.length; i++) {
        if (i > 0) stream = advance();
        Iif (!stream) break;
        if (parts[i].length) stream.write(parts[i]);
    }
    Iif (i < parts.length) {
        self.errorEvent.emit(self, new Error('frame parts exceeded stream arity')); // TODO clearer / typed error
    }
 
    function advance() {
        Eif (self._iStream < self.streams.length) {
            self.streams[self._iStream].end();
            self._iStream++;
        }
        return self.streams[self._iStream];
    }
};
 
function OutArgStream() {
    if (!(this instanceof OutArgStream)) {
        return new OutArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self._flushImmed = null;
    self.finished = false;
    self.frame = [Buffer(0)];
    self.currentArgN = 1;
    self.arg1.on('data', function onArg1Data(chunk) {
        self._handleFrameChunk(1, chunk);
    });
    self.arg2.on('data', function onArg2Data(chunk) {
        self._handleFrameChunk(2, chunk);
    });
    self.arg3.on('data', function onArg3Data(chunk) {
        self._handleFrameChunk(3, chunk);
    });
 
    self.arg1.on('finish', function onArg1Finish() {
        self._handleFrameChunk(1, null);
    });
    self.arg2.on('finish', function onArg2Finish() {
        self._handleFrameChunk(2, null);
    });
    self.arg3.on('finish', function onArg3Finish() {
        self._handleFrameChunk(3, null);
        self._flushParts(true);
        self.finished = true;
        self.finishEvent.emit(self);
    });
}
 
inherits(OutArgStream, ArgStream);
 
OutArgStream.prototype._handleFrameChunk = function _handleFrameChunk(n, chunk) {
    var self = this;
    Iif (n < self.currentArgN) {
        self.errorEvent.emit(self, errors.ArgChunkOutOfOrderError({
            current: self.currentArgN,
            got: n
        }));
    } else Iif (n > self.currentArgN) {
        if (n - self.currentArgN > 1) {
            self.errorEvent.emit(self, errors.ArgChunkGapError({
                current: self.currentArgN,
                got: n
            }));
        }
        self.currentArgN++;
        self.frame.push(chunk);
    } else if (chunk === null) {
        if (++self.currentArgN <= 3) {
            self.frame.push(Buffer(0));
        }
    } else {
        self._appendFrameChunk(chunk);
    }
    self._deferFlushParts();
};
 
OutArgStream.prototype._appendFrameChunk = function _appendFrameChunk(chunk) {
    var self = this;
    var i = self.frame.length - 1;
    var buf = self.frame[i];
    if (buf.length) {
        self.frame[i] = Buffer.concat([buf, chunk]);
    } else {
        self.frame[i] = chunk;
    }
};
 
OutArgStream.prototype._deferFlushParts = function _deferFlushParts() {
    var self = this;
    if (!self._flushImmed) {
        self._flushImmed = setImmediate(function() {
            self._flushParts();
        });
    }
};
 
OutArgStream.prototype._flushParts = function _flushParts(isLast) {
    var self = this;
    Eif (self._flushImmed) {
        clearImmediate(self._flushImmed);
        self._flushImmed = null;
    }
    if (self.finished) return;
    isLast = Boolean(isLast);
    var frame = self.frame;
    self.frame = [Buffer(0)];
    Eif (frame.length) self.frameEvent.emit(self, [frame, isLast]);
};
 
function StreamArg(options) {
    if (!(this instanceof StreamArg)) {
        return new StreamArg(options);
    }
    var self = this;
    PassThrough.call(self, options);
    self.started = false;
    self.onValueReady = self.onValueReady.bind(self);
}
inherits(StreamArg, PassThrough);
 
StreamArg.prototype._write = function _write(chunk, encoding, callback) {
    var self = this;
    if (!self.started) {
        self.started = true;
        self.emit('start');
    }
    PassThrough.prototype._write.call(self, chunk, encoding, callback);
};
 
StreamArg.prototype.onValueReady = function onValueReady(callback) {
    var self = this;
    self.onValueReady = Ready();
    bufferStreamData(self, self.onValueReady.signal);
    self.onValueReady(callback);
};
 
function bufferStreamData(stream, callback) {
    var parts = [];
    stream.on('data', onData);
    stream.on('error', finish);
    stream.on('end', finish);
    function onData(chunk) {
        parts.push(chunk);
    }
    function finish(err) {
        stream.removeListener('data', onData);
        stream.removeListener('error', finish);
        stream.removeListener('end', finish);
        var buf = Buffer.concat(parts);
        Eif (err === undefined) err = null;
        callback(err, buf);
    }
}
 
module.exports.InArgStream = InArgStream;
module.exports.OutArgStream = OutArgStream;