Code coverage report for node/as/http.js

Statements: 82.46% (141 / 171)      Branches: 64.29% (36 / 56)      Functions: 95.65% (22 / 23)      Lines: 82.46% (141 / 171)      Ignored: none     

All files » node/as/ » http.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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344                                            1 1 1 1 1 1 1   1     1   1 8 8 8 8     1           1 10 10 10 10     1           1 2         1 4   4 4 4     4   4 4 11     4 4 4       4   4 4   1 4 1 3     3   1 3     3         1       3 3   3     3 3 3           1     3 3 3 12     3 3               3   3               1 2 2 2     1 4             4       4 4             4 4     1 4             4 4 4     1 4       1 1       3 3 12 12   3 3   4       1     4           4 11 11     4   4 4   4   1 4 4   4       1                 1 2 2   2 2 2 2     1 4 4     4     4     1 4     4 4       1 4         4 4         4 4     4 4     4     4 4 1 1     1 4           4     1 4 3 3       1 3              
// 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';
 
var assert = require('assert');
var bufrw = require('bufrw');
var http = require('http');
var PassThrough = require('readable-stream').PassThrough;
var extend = require('xtend');
var extendInto = require('xtend/mutable');
var errors = require('../errors.js');
 
var headerRW = bufrw.Repeat(bufrw.UInt16BE,
    bufrw.Series(bufrw.str2, bufrw.str2));
 
module.exports = TChannelHTTP;
 
function HTTPReqArg2(method, url, headerPairs) {
    var self = this;
    self.method = method || '';
    self.url = url || '';
    self.headerPairs = headerPairs || [];
}
 
HTTPReqArg2.RW = bufrw.Struct(HTTPReqArg2, {
    method: bufrw.str1,   // method~1
    url: bufrw.strn,      // url~N
    headerPairs: headerRW // numHeaders:2 (headerName~2 headerValue~2){numHeaders}
});
 
function HTTPResArg2(statusCode, message, headerPairs) {
    var self = this;
    self.statusCode = statusCode || 0;
    self.message = message || '';
    self.headerPairs = headerPairs || [];
}
 
HTTPResArg2.RW = bufrw.Struct(HTTPResArg2, {
    statusCode: bufrw.UInt16BE, // statusCode:2
    message: bufrw.strn,        // message~N
    headerPairs: headerRW       // numHeaders:2 (headerName~2 headerValue~2){numHeaders}
});
 
function TChannelHTTP(options) {
    Iif (!(this instanceof TChannelHTTP)) {
        return new TChannelHTTP(options);
    }
}
 
TChannelHTTP.prototype.sendRequest = function send(treq, hreq, options, callback) {
    assert(treq.streamed, 'as http must have a streamed tchannel request');
 
    Eif (typeof options === 'function') {
        callback = options;
        options = null;
    }
 
    var head = new HTTPReqArg2(hreq.method, hreq.url);
    // TODO: get lower level access to raw request header pairs
    var keys = Object.keys(hreq.headers);
    for (var i = 0; i < keys.length; i++) {
        head.headerPairs.push([keys[i], hreq.headers[keys[i]]]);
    }
 
    var arg1 = ''; // TODO: left empty for now, could compute circuit names heuristically
    var arg2res = bufrw.toBufferResult(HTTPReqArg2.RW, head);
    Iif (arg2res.err) {
        callback(arg2res.err, null, null);
        return;
    }
    var arg2 = arg2res.value;
 
    treq.headers.as = 'http';
    return treq.sendStreams(arg1, arg2, hreq, onResponse);
 
    function onResponse(err, treq, tres) {
        if (err) {
            callback(err, null, null);
        } else Iif (tres.streamed) {
            tres.arg2.onValueReady(arg2Ready);
        } else {
            arg2Ready(null, tres.arg2);
        }
        function arg2Ready(err, arg2) {
            Iif (err) {
                callback(err, null, null);
            } else {
                readArg2(tres, arg2);
            }
        }
    }
 
    function readArg2(tres, arg2) {
        // TODO: currently does the wrong thing and doesn't implement a
        // multi-map, due to assuming node-like mangling on the other side
        // to ensure singularity
        var arg2res = bufrw.fromBufferResult(HTTPResArg2.RW, arg2);
        Iif (arg2res.err) {
            callback(arg2res.err, null, null);
        } else Iif (tres.streamed) {
            callback(null, arg2res.value, tres.arg3);
        } else {
            var body = PassThrough();
            body.end(tres.arg3);
            callback(null, arg2res.value, body);
        }
 
    }
};
 
TChannelHTTP.prototype.sendResponse = function send(buildResponse, hres, callback) {
    // TODO: map http response codes onto error frames and application errors
 
    var head = new HTTPResArg2(hres.statusCode, hres.statusMessage);
    var keys = Object.keys(hres.headers);
    for (var i = 0; i < keys.length; i++) {
        head.headerPairs.push([keys[i], hres.headers[keys[i]]]);
    }
 
    var arg2res = bufrw.toBufferResult(HTTPResArg2.RW, head);
    Iif (arg2res.err) {
        // TODO: wrapped error
        callback(arg2res.err, null, null);
        buildResponse().sendError('UnexpectedError',
            'Couldn\'t encode as-http response arg2: ' +
            arg2res.err.message);
        return;
    }
    var arg2 = arg2res.value;
 
    return buildResponse({
        streamed: true,
        headers: {
            as: 'http'
        }
    }).sendStreams(arg2, hres, callback);
};
 
TChannelHTTP.prototype.setHandler = function register(tchannel, handler) {
    var self = this;
    tchannel.handler = new AsHTTPHandler(self, tchannel, handler);
    return tchannel.handler;
};
 
TChannelHTTP.prototype.forwardToTChannel = function forwardToTChannel(tchannel, hreq, hres, tchannelRequestOptions, callback) {
    var self = this;
 
    // TODO: no retrying due to:
    // - streamed bypasses TChannelRequest
    // - driving peer selection manually therefore
    // TODO: more http state machine integration
 
    var options = tchannel.requestOptions(extendInto({
        streamed: true,
        hasNoParent: true
    }, tchannelRequestOptions));
    var peer = tchannel.peers.choosePeer(null);
    Iif (!peer) {
        hres.writeHead(503, 'Service Unavailable: no tchannel peer');
        hres.end(); // TODO: error content
        callback(errors.NoPeerAvailable());
        return null;
    } else {
        // TODO: observable
        peer.waitForIdentified(onIdentified);
        return null;
    }
 
    function onIdentified(err) {
        Iif (err) {
            hres.writeHead(500, 'Connection failure');
            hres.end();
            callback(err);
            return null;
        }
 
        options.host = peer.hostPort;
        var treq = tchannel.request(options);
        self.sendRequest(treq, hreq, forwarded);
    }
 
    function forwarded(err, head, body) {
        if (err) {
            // TODO: better map of error type -> http status code, see
            // tchannel/errors.classify
            // TODO: observable
            hres.writeHead(500, err.type + ' - ' + err.message);
            hres.end(); // TODO: error content
        } else {
            // TODO: observable
            // TODO: better lower level mapping of headerPairs
            var headers = {};
            for (var i = 0; i < head.headerPairs.length; i++) {
                var pair = head.headerPairs[i];
                headers[pair[0]] = pair[1];
            }
            hres.writeHead(head.statusCode, head.message, headers);
            body.pipe(hres);
        }
        callback(err);
    }
};
 
TChannelHTTP.prototype.forwardToHTTP = function forwardToHTTP(ingressChan, options, inreq, outres) {
    // TODO: should use lb_pool
 
    options = extend(options, {
        method: inreq.head.method,
        path: inreq.head.url,
        headers: {},
        keepAlive: true
    });
    for (var i = 0; i < inreq.head.headerPairs.length; i++) {
        var pair = inreq.head.headerPairs[i];
        options.headers[pair[0]] = pair[1];
    }
 
    var sent = false;
    // TODO: observable
    var outreq = http.request(options, onResponse);
    outreq.on('error', onError);
    // TODO: more http state machine integration
    inreq.body.pipe(outreq);
 
    function onResponse(inres) {
        Eif (!sent) {
            sent = true;
            // TODO: observable
            outres.sendResponse(inres);
        }
    }
 
    function onError(err) {
        if (!sent) {
            sent = true;
            // TODO: observable
            outres.sendError(err);
        }
    }
};
 
function AsHTTPHandler(asHTTP, channel, handler) {
    Eif (typeof handler === 'function') {
        handler = {handleRequest: handler}; // TODO: explicate type?
    }
    var self = this;
    self.asHTTP = asHTTP;
    self.channel = channel;
    self.handler = handler;
}
 
AsHTTPHandler.prototype.handleRequest = function handleRequest(req, buildResponse) {
    var self = this;
    var hreq = {};
 
    // TODO: real soon arg1 won't be streamable / fragmentable
    Iif (req.streamed) {
        req.arg1.onValueReady(onArg1);
    } else {
        onArg1(null, req.arg1);
    }
 
    function onArg1(err, arg1) {
        Iif (err) {
            sendError(err);
        } else {
            hreq.url = arg1;
            req.withArg2(onArg2);
        }
    }
 
    function onArg2(err, arg2) {
        Iif (err) {
            sendError(err);
            return;
        }
 
        var arg2res = bufrw.fromBufferResult(HTTPReqArg2.RW, arg2);
        Iif (arg2res.err) {
            sendError(arg2res.err);
            return;
        }
 
        hreq.head = arg2res.value;
        Iif (req.streamed) {
            hreq.body = req.arg3;
        } else {
            hreq.body = PassThrough();
            hreq.body.end(req.arg3);
        }
 
        handle();
    }
 
    var sent = false;
    req.errorEvent.on(onError);
    function onError() {
        sent = true;
    }
 
    function handle() {
        var hres = { // TODO: explicate type
            head: new HTTPResArg2(200, 'Ok'),
            sendError: sendError,
            sendResponse: sendResponse
        };
        // TODO: observable
        self.handler.handleRequest(hreq, hres);
    }
 
    function sendResponse(hres) {
        if (!sent) {
            sent = true;
            self.asHTTP.sendResponse(buildResponse, hres, sendError);
        }
    }
 
    function sendError(err) {
        Iif (!sent) {
            // TODO: map type?
            sent = true;
            buildResponse().sendError('UnexpectedError', err.message);
        }
    }
};