Code coverage report for node/as/json.js

Statements: 83.9% (99 / 118)      Branches: 58.06% (36 / 62)      Functions: 100% (12 / 12)      Lines: 83.9% (99 / 118)      Ignored: none     

All files » node/as/ » json.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                                                1 1 1 1 1 1   1   1   1 8 4     4   4   4 4   4 4         1       3   3 3   3   3           3       3   3             1 3 1     2             2       2 2   2 1   1       2       1     4   4   1 4         4             4 1   1     3 3   1 3 1   1       1     2 2   2     2 1                       2             2         2 2               1 5   5 5                             5 5                             5           1 6   6 6 1           1 1             1     5 5                                   5           1 2   2 2 2     1 1       1 10     10 10           10     1 11       11     11 11   1       10    
// 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';
 
/* jshint maxparams:5 */
 
var Buffer = require('buffer').Buffer;
var assert = require('assert');
var NullLogtron = require('null-logtron');
var Result = require('bufrw/result');
var cyclicStringify = require('json-stringify-safe');
var isError = require('is-error');
 
var errors = require('../errors.js');
 
module.exports = TChannelJSON;
 
function TChannelJSON(options) {
    if (!(this instanceof TChannelJSON)) {
        return new TChannelJSON(options);
    }
 
    var self = this;
 
    self.logger = options && options.logger || NullLogtron();
 
    var bossMode = options && options.bossMode;
    self.bossMode = typeof bossMode === 'boolean' ? bossMode : false;
 
    var logParseFailures = options && options.logParseFailures;
    self.logParseFailures = typeof logParseFailures === 'boolean' ?
        logParseFailures : true;
}
 
/*eslint max-params: [2, 5]*/
TChannelJSON.prototype.send = function send(
    req, endpoint, head, body, callback
) {
 
    var self = this;
 
    assert(typeof endpoint === 'string', 'endpoint must be a string');
    assert(typeof req.serviceName === 'string' && req.serviceName !== '',
        'req.serviceName must be a string');
    assert(body !== undefined, 'must send a body');
 
    var stringifyResult = self._stringify({
        head: head,
        body: body,
        endpoint: endpoint,
        direction: 'out.request'
    });
    Iif (stringifyResult.err) {
        return callback(stringifyResult.err);
    }
 
    req.headers.as = 'json';
 
    req.send(
        new Buffer(endpoint),
        new Buffer(stringifyResult.value.head || ''),
        new Buffer(stringifyResult.value.body || ''),
        onResponse
    );
 
    function onResponse(err, resp, arg2, arg3) {
        if (err) {
            return callback(err);
        }
 
        var parseResult = self._parse({
            head: arg2.toString('utf8'),
            body: arg3.toString('utf8'),
            endpoint: endpoint,
            direction: 'in.response'
        });
 
        Iif (parseResult.err) {
            return callback(parseResult.err);
        }
 
        var v = parseResult.value;
        var response = null;
 
        if (resp.ok) {
            response = new TChannelJSONResponse(resp.ok, v.head, v.body);
        } else {
            response = new TChannelJSONResponse(
                resp.ok, v.head, errors.ReconstructedError(v.body)
            );
        }
        callback(null, response);
    }
};
 
TChannelJSON.prototype.register = function register(
    tchannel, arg1, opts, handlerFunc
) {
    var self = this;
 
    tchannel.register(arg1, endpointHandler);
 
    function endpointHandler(req, res, arg2, arg3) {
        Iif (req.headers.as !== 'json') {
            var message = 'Expected call request as header to be json';
            return res.sendError('BadRequest', message);
        }
 
        var parseResult = self._parse({
            head: arg2.toString('utf8'),
            body: arg3.toString('utf8'),
            endpoint: arg1,
            direction: 'in.request'
        });
 
        if (parseResult.err) {
            var message2 = parseResult.err.type + ': ' +
                parseResult.err.message;
            return res.sendError('BadRequest', message2);
        }
 
        var v = parseResult.value;
        handlerFunc(opts, req, v.head, v.body, onResponse);
 
        function onResponse(err, respObject) {
            if (err) {
                assert(isError(err), 'Error argument must be an error');
 
                self.logger.error('Got unexpected error in handler', {
                    endpoint: arg1,
                    err: err
                });
                return res.sendError('UnexpectedError', 'Unexpected Error');
            }
 
            Eif (!self.bossMode) {
                assert(typeof respObject.ok === 'boolean',
                    'expected respObject to have an `ok` boolean');
                assert(respObject.body !== undefined,
                    'expected respObject to have a body');
                // Assert that body is an error
                if (!respObject.ok) {
                    assert(isTypedError(respObject.body),
                        'not-ok body should be a typed error');
                }
            } else if (typeof respObject.ok !== 'boolean' ||
                       respObject.body === undefined ||
                       !(respObject.ok || isTypedError(respObject.body))) {
                respObject.body = errors.InvalidJSONBody({
                    head: respObject.head,
                    body: respObject.body
                });
            }
 
            var stringifyResult = self._stringify({
                head: respObject.head,
                body: respObject.body,
                endpoint: arg1,
                direction: 'out.response'
            });
 
            Iif (stringifyResult.err) {
                return res.sendError('UnexpectedError',
                    'Could not JSON stringify');
            }
 
            res.setOk(respObject.ok);
            res.send(
                stringifyResult.value.head,
                stringifyResult.value.body
            );
        }
    }
};
 
TChannelJSON.prototype._stringify = function stringify(opts) {
    var self = this;
 
    var headR = safeJSONStringify(opts.head);
    Iif (headR.err) {
        var headStringifyErr = errors.HeadStringifyError(headR.err, {
            endpoint: opts.endpoint,
            direction: opts.direction,
            head: cyclicStringify(opts.head)
        });
 
        self.logger.error('Got unexpected unserializable JSON for arg2', {
            endpoint: opts.endpoint,
            direction: opts.direction,
            headErr: headStringifyErr
        });
        return new Result(headStringifyErr);
    }
 
    var bodyR = safeJSONStringify(opts.body);
    Iif (bodyR.err) {
        var bodyStringifyErr = errors.BodyStringifyError(bodyR.err, {
            endpoint: opts.endpoint,
            direction: opts.direction,
            body: cyclicStringify(opts.body)
        });
 
        self.logger.error('Got unexpected unserializable JSON for arg3', {
            endpoint: opts.endpoint,
            direction: opts.direction,
            bodyErr: bodyStringifyErr
        });
        return new Result(bodyStringifyErr);
    }
 
    return new Result(null, {
        head: headR.value,
        body: bodyR.value
    });
};
 
TChannelJSON.prototype._parse = function parse(opts) {
    var self = this;
 
    var headR = safeJSONParse(opts.head);
    if (headR.err) {
        var headParseErr = errors.HeadParserError(headR.err, {
            endpoint: opts.endpoint,
            direction: opts.direction,
            headStr: opts.head.slice(0, 10)
        });
 
        Eif (self.logParseFailures) {
            self.logger.warn('Got unexpected invalid JSON for arg2', {
                endpoint: opts.endpoint,
                direction: opts.direction,
                headErr: headParseErr
            });
        }
 
        return new Result(headParseErr);
    }
 
    var bodyR = safeJSONParse(opts.body);
    Iif (bodyR.err) {
        var bodyParseErr = errors.BodyParserError(bodyR.err, {
            endpoint: opts.endpoint,
            direction: opts.direction,
            bodyStr: opts.body.slice(0, 10)
        });
 
        if (self.logParseFailures) {
            self.logger.warn('Got unexpected invalid JSON for arg3', {
                endpoint: opts.endpoint,
                direction: opts.direction,
                bodyErr: bodyParseErr
            });
        }
 
        return new Result(bodyParseErr);
    }
 
    return new Result(null, {
        head: headR.value,
        body: bodyR.value
    });
};
 
function TChannelJSONResponse(ok, head, body) {
    var self = this;
 
    self.ok = ok;
    self.head = head;
    self.body = body;
}
 
function isTypedError(obj) {
    return isError(obj) &&
           typeof obj.type === 'string';
}
 
function safeJSONStringify(obj) {
    var str;
 
    // jscs:disable
    try {
        str = JSON.stringify(obj);
    } catch (e) {
        return new Result(e);
    }
    // jscs:enable
 
    return new Result(null, str);
}
 
function safeJSONParse(str) {
    Iif (str === '') {
        return new Result(null, null);
    }
 
    var json;
 
    // jscs:disable
    try {
        json = JSON.parse(str);
    } catch (e) {
        return new Result(e);
    }
    // jscs:enable
 
    return new Result(null, json);
}