Code coverage report for node/as/thrift.js

Statements: 92.72% (140 / 151)      Branches: 81.94% (59 / 72)      Functions: 100% (14 / 14)      Lines: 92.72% (140 / 151)      Ignored: none     

All files » node/as/ » thrift.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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392                                            1 1 1 1   1   1   1   1 65 24     41   41     41     41   41 41   41 41       41     1 1   1 1 1     1   1   1 1     1 1   1   1           1     1   35   35 24     35   35   1 23 1         22             22 2       20 20   1 29 8   8         8     21 21   21     21 9   9         21                 21         21 21 21                 1   33   33   33 33       33           33         33   33             1 33 20     13               13       13 13   13       1 13   13 13 13 13   13 8   5       1 35   35 35   35 35   35 35 1             1                 1     34 34 21 13 13   13 8 5 5       34 1             1                 1     33           1 54   54 54   54 54   54   54 54                                 54 54 33 21 21 21 9   12     21     54                                 54             1 5 5 5         1 17    
// 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 Result = require('bufrw/result');
var thriftify = require('thriftify');
 
var errors = require('../errors.js');
 
var HeaderRW = require('../v2/header.js').header2;
 
module.exports = TChannelAsThrift;
 
function TChannelAsThrift(opts) {
    if (!(this instanceof TChannelAsThrift)) {
        return new TChannelAsThrift(opts);
    }
 
    var self = this;
 
    assert(opts && typeof opts.source === 'string',
        'must pass source as an argument');
 
    self.spec = thriftify.parseSpec(opts.source);
 
    // Pulled off of things in `.register` and `.send` rather than passed in
    self.logger = null;
 
    var bossMode = opts && opts.bossMode;
    self.bossMode = typeof bossMode === 'boolean' ? bossMode : false;
 
    var logParseFailures = opts && opts.logParseFailures;
    self.logParseFailures = typeof logParseFailures === 'boolean' ?
        logParseFailures : true;
 
    // only used in request()
    self.channel = opts.channel;
}
 
function TChannelThriftRequest(options) {
    var self = this;
 
    self.channel = options.channel;
    self.reqOptions = options.reqOptions;
    self.tchannelThrift = options.tchannelThrift;
}
 
TChannelThriftRequest.prototype.send =
function send(endpoint, head, body, callback) {
    var self = this;
 
    var outreq = self.channel.request(self.reqOptions);
    self.tchannelThrift.send(outreq, endpoint, head, body, callback);
};
 
TChannelAsThrift.prototype.request = function request(reqOptions) {
    var self = this;
 
    assert(self.channel, 'channel is required for thrift.request()');
 
    var req = new TChannelThriftRequest({
        channel: self.channel,
        reqOptions: reqOptions,
        tchannelThrift: self
    });
 
    return req;
};
 
TChannelAsThrift.prototype.register =
function register(channel, name, opts, handle) {
    var self = this;
 
    if (!self.logger) {
        self.logger = channel.logger;
    }
 
    assert(typeof name === 'string', 'endpoint has to be a string');
 
    channel.register(name, handleThriftRequest);
 
    function handleThriftRequest(req, res, inHeadBuffer, inBodyBuffer) {
        if (req.headers.as !== 'thrift') {
            return res.sendError('BadRequest',
                'Expected call request as header to be thrift');
        }
 
        // Process incoming thrift body
        var parseResult = self._parse({
            head: inHeadBuffer,
            body: inBodyBuffer,
            endpoint: name,
            direction: 'in.request'
        });
 
        if (parseResult.err) {
            return res.sendError('BadRequest',
                parseResult.err.type + ': ' + parseResult.err.message);
        }
 
        var v = parseResult.value;
        handle(opts, req, v.head, v.body, handleThriftResponse);
 
        function handleThriftResponse(err, thriftRes) {
            if (err) {
                assert(isError(err), 'Error argument must be an error');
 
                self.logger.error('Got unexpected error in handler', {
                    endpoint: name,
                    error: err
                });
 
                return res.sendError('UnexpectedError', 'Unexpected Error');
            }
 
            Eif (!self.bossMode) {
                assert(typeof thriftRes.ok === 'boolean',
                    'expected response.ok to be a boolean');
                assert(thriftRes.body !== undefined,
                    'expected response.body to exist');
 
                if (!thriftRes.ok) {
                    assert(isError(thriftRes.body),
                        'not-ok body should be an error');
                    assert(typeof thriftRes.typeName === 'string',
                        'expected not-ok response to have typeName');
                }
            }
 
            var stringifyResult = self._stringify({
                head: thriftRes.head,
                body: thriftRes.body,
                ok: thriftRes.ok,
                typeName: thriftRes.typeName,
                endpoint: name,
                direction: 'out.response'
            });
 
            Iif (stringifyResult.err) {
                return res.sendError('UnexpectedError',
                    'Could not serialize thrift');
            }
 
            res.headers.as = 'thrift';
            res.setOk(thriftRes.ok);
            res.send(
                stringifyResult.value.head,
                stringifyResult.value.body
            );
        }
    }
};
 
/* jshint maxparams:5 */
TChannelAsThrift.prototype.send =
function send(request, endpoint, outHead, outBody, callback) {
    var self = this;
 
    self.logger = self.logger || request.channel.logger;
 
    assert(typeof endpoint === 'string', 'send requires endpoint');
    assert(typeof request.serviceName === 'string' &&
        request.serviceName !== '',
        'req.serviceName must be a string');
 
    var stringifyResult = self._stringify({
        head: outHead,
        body: outBody,
        endpoint: endpoint,
        direction: 'out.request'
    });
    Iif (stringifyResult.err) {
        return callback(stringifyResult.err);
    }
 
    // Punch as=thrift into the transport headers
    request.headers.as = 'thrift';
 
    request.send(
        endpoint,
        stringifyResult.value.head,
        stringifyResult.value.body,
        handleResponse
    );
 
    function handleResponse(err, res, arg2, arg3) {
        if (err) {
            return callback(err);
        }
 
        var parseResult = self._parse({
            head: arg2,
            body: arg3,
            ok: res.ok,
            endpoint: endpoint,
            direction: 'in.response'
        });
 
        Iif (parseResult.err) {
            return callback(parseResult.err);
        }
 
        var v = parseResult.value;
        var resp = new TChannelThriftResponse(res, v);
 
        callback(null, resp);
    }
};
 
function TChannelThriftResponse(response, parseResult) {
    var self = this;
 
    self.ok = response.ok;
    self.head = parseResult.head;
    self.body = null;
    self.headers = response.headers;
 
    if (response.ok) {
        self.body = parseResult.body;
    } else {
        self.body = errors.ReconstructedError(parseResult.body);
    }
}
 
TChannelAsThrift.prototype._parse = function parse(opts) {
    var self = this;
 
    var argsName = opts.endpoint + '_args';
    var argsType = self.spec.getType(argsName);
 
    var returnName = opts.endpoint + '_result';
    var resultType = self.spec.getType(returnName);
 
    var headRes = bufrw.fromBufferResult(HeaderRW, opts.head);
    if (headRes.err) {
        var headParseErr = errors.ThriftHeadParserError(headRes.err, {
            endpoint: opts.endpoint,
            direction: opts.direction,
            ok: opts.ok,
            headBuf: opts.head.slice(0, 10)
        });
 
        Iif (self.logParseFailures) {
            self.logger.warn('Got unexpected invalid thrift arg2', {
                endpoint: opts.endpoint,
                direction: opts.direction,
                ok: opts.ok,
                headErr: headParseErr
            });
        }
 
        return new Result(headParseErr);
    }
 
    var bodyRes;
    if (opts.direction === 'in.request') {
        bodyRes = argsType.fromBuffer(opts.body);
    } else Eif (opts.direction === 'in.response') {
        bodyRes = resultType.fromBuffer(opts.body);
 
        if (bodyRes.value && opts.ok) {
            bodyRes.value = bodyRes.value.success;
        } else Eif (bodyRes.value && !opts.ok) {
            bodyRes.value = onlyProperty(bodyRes.value);
        }
    }
 
    if (bodyRes.err) {
        var bodyParseErr = errors.ThriftBodyParserError(bodyRes.err, {
            endpoint: opts.endpoint,
            direction: opts.direction,
            ok: opts.ok,
            bodyBuf: opts.body.slice(0, 10)
        });
 
        Iif (self.logParseFailures) {
            self.logger.warn('Got unexpected invalid thrift for arg3', {
                endpoint: opts.endpoint,
                ok: opts.ok,
                direction: opts.direction,
                bodyErr: bodyParseErr
            });
        }
 
        return new Result(bodyParseErr);
    }
 
    return new Result(null, {
        head: headRes.value,
        body: bodyRes.value
    });
};
 
TChannelAsThrift.prototype._stringify = function stringify(opts) {
    var self = this;
 
    var argsName = opts.endpoint + '_args';
    var argsType = self.spec.getType(argsName);
 
    var returnName = opts.endpoint + '_result';
    var resultType = self.spec.getType(returnName);
 
    opts.head = opts.head || {};
 
    var headRes = bufrw.toBufferResult(HeaderRW, opts.head);
    Iif (headRes.err) {
        var headStringifyErr = errors.ThriftHeadStringifyError(headRes.err, {
            endpoint: opts.endpoint,
            ok: opts.ok,
            direction: opts.direction,
            head: opts.head
        });
 
        self.logger.error('Got unexpected unserializable thrift for arg2', {
            endpoint: opts.endpoint,
            ok: opts.ok,
            direction: opts.direction,
            headErr: headStringifyErr
        });
        return new Result(headStringifyErr);
    }
 
    var bodyRes;
    if (opts.direction === 'out.request') {
        bodyRes = argsType.toBuffer(opts.body);
    } else Eif (opts.direction === 'out.response') {
        var thriftResult = {};
        if (!opts.ok) {
            thriftResult[opts.typeName] = opts.body;
        } else {
            thriftResult.success = opts.body;
        }
 
        bodyRes = resultType.toBuffer(thriftResult);
    }
 
    Iif (bodyRes.err) {
        var bodyStringifyErr = errors.ThriftBodyStringifyError(bodyRes.err, {
            endpoint: opts.endpoint,
            ok: opts.ok,
            direction: opts.direction,
            body: opts.body
        });
 
        self.logger.error('Got unexpected unserializable thrift for arg3', {
            endpoint: opts.endpoint,
            direction: opts.direction,
            ok: opts.ok,
            bodyErr: bodyStringifyErr
        });
        return new Result(bodyStringifyErr);
    }
 
    return new Result(null, {
        head: headRes.value,
        body: bodyRes.value
    });
};
 
// TODO proper Thriftify result union that reifies as the selected field.
function onlyProperty(object) {
    for (var name in object) {
        Eif (object[name] !== null) {
            return object[name];
        }
    }
}
 
function isError(err) {
    return Object.prototype.toString.call(err) === '[object Error]';
}