All files / centro/lib client.js

100% Statements 143/143
100% Branches 61/61
100% Functions 14/14
100% Lines 142/142

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462                1x 1x 1x 1x 1x 1x   1x 1x             4975x   4975x   4604x     4975x         4974x       4974x 4974x   3778x   4974x   4974x   4974x   4628x   4628x       60x         4568x     3080x       1488x     4568x   4568x               4568x                                                                                       433x   433x                             259x     174x     4135x       553006x     4135x   170x   170x 170x     170x   170x           4135x 4135x   2718x   1822x 1822x 1822x 1822x     2718x   74x     2644x   2644x 2644x   2528x     2644x 2644x   2549x 2549x     2644x 2644x   2622x   224802x   218566x           2622x 2622x     2644x     4135x 4135x   475x   391x 391x 391x 391x     475x   64x 64x 64x     475x   21x     454x       520x 520x   22x     498x 498x   21x     477x 477x   43x     434x 434x   369x 369x   348x       434x     454x   43x   108x   87x   87x     87x       21x           411x   411x   154x 154x   132x   176x           257x     411x           4135x 4135x   550025x   549328x 549328x 549328x 549328x     550025x   548883x 548883x     550025x   74x 74x     549951x         4135x     4974x     1x                         1x   2673x   1x 1x         2673x   2673x       1x     2672x   1480x                             1x       2302x   2302x   2302x   4604x       2302x   2302x                                                                          
/*eslint-env node */
 
/**
 * Centro client functions
 * @module centro-js/lib/client
 */
"use strict";
 
var frame = require('frame-stream'),
    async = require('async'),
    MQlobberClient = require('mqlobber/lib/client').MQlobberClient,
    Ajv = require('ajv'),
    ajv = new Ajv(),
    { get_topic_pattern } = require('./pattern');
 
exports.version = require('./version');
exports.version_buffer = Buffer.alloc(4),
/*jshint expr: true */
exports.version_buffer.writeUInt32BE(exports.version, 0, true);
/*jshint expr: false */
 
function get_stokens(config)
{
    var tokens = config.token;
 
    if (typeof tokens === 'string')
    {
        tokens = [tokens];
    }
 
    return tokens.join(',');
}
 
function start(stream, config)
{
    config = Object.assign(
        stream._no_keep_alive ? { keep_alive: false } : {},
        config);
 
    var bufs = [exports.version_buffer];
    if (config.handshake_data)
    {
        bufs.push(config.handshake_data);
    }
    config.handshake_data = Buffer.concat(bufs);
 
    var mqclient = new MQlobberClient(stream, config);
 
    mqclient.on('handshake', function (hsdata)
    {
        try
        {
            hsdata = JSON.parse(hsdata);
        }
        catch (ex)
        {
            return this.emit('error', ex);
        }
 
        var num_prefixes;
        
        if ((typeof config.token === 'string') ||
            (typeof config.token === 'undefined'))
        {
            num_prefixes = 1;
        }
        else
        {
            num_prefixes = config.token.length;
        }
 
        const matcher = mqclient._matcher;
 
        const pattern_config = {
            separator: matcher._separator,
            wildcard_some: matcher._wildcard_some,
            max_words: matcher._max_words,
            max_wildcard_somes: matcher._max_wildcard_somes,
            max_topic_length: config.max_topic_length
        };
 
        if (!ajv.validate({
            type: 'object',
            required: ['self', 'prefixes', 'version'],
            additionalProperties: false,
            properties: {
                self: {
                    type: 'string'
                },
                prefixes: {
                    type: 'array',
                    minItems: num_prefixes,
                    maxItems: num_prefixes,
                    items: {
                        type: 'string',
                        oneOf: [{
                            minLength: 65,
                            maxLength: 65
                        }, {
                            minLength: 0,
                            maxLength: 0
                        }]
                    }
                },
                subscriptions: {
                    type: 'array',
                    maxItems: num_prefixes,
                    items: {
                        type: 'object',
                        maxProperties: config.max_subscriptions,
                        additionalProperties: false,
                        patternProperties: {
                            [get_topic_pattern(pattern_config)]: {
                                type: 'boolean'
                            }
                        }
                    }
                },
                version: {
                    type: 'integer',
                    enum: [exports.version]
                }
            }
        }, hsdata))
        {
            var msg = ajv.errorsText(ajv.errors);
 
            if (ajv.validate({
                type: 'object',
                required: ['error', 'version'],
                additionalProperties: false,
                properties: {
                    error: {
                        type: 'string'
                    },
                    version: {
                        type: 'integer',
                        enum: [exports.version]
                    }
                }
            }, hsdata))
            {
                return this.emit('error', new Error(hsdata.error));
            }
 
            return this.emit('error', new Error(msg));
        }
 
        this.self = hsdata.self;
 
        function replace(topic)
        {
            return topic.split('${self}').join(hsdata.self);
        }
 
        if (hsdata.subscriptions)
        {
            for (var i = 0; i < hsdata.subscriptions.length; i += 1)
            {
                var subscription = hsdata.subscriptions[i];
                for (var topic in subscription)
                {
                    /* istanbul ignore else */
                    if (Object.prototype.hasOwnProperty.call(subscription, topic))
                    {
                        this.subs.set(hsdata.prefixes[i] + topic, new Set());
                    }
                }
            }
        }
 
        this._orig_subscribe = this.subscribe;
        this.subscribe = function (n, topic, handler, cb)
        {
            if (typeof n !== 'number')
            {
                cb = handler;
                handler = topic;
                topic = n;
                n = 0;
            }
 
            if (n >= hsdata.prefixes.length)
            {
                return cb(new Error('token out of range'));
            }
 
            topic = hsdata.prefixes[n] + replace(topic);
 
            var centro_subs = handler._centro_subs;
            if (!centro_subs)
            {
               centro_subs = handler._centro_subs = new Map();
            }
 
            var handlers = centro_subs.get(this);
            if (!handlers)
            {
                handlers = new Map();
                centro_subs.set(this, handlers);
            }
 
            var handler2 = handlers.get(topic);
            if (!handler2)
            {
                handler2 = function (s, info, done)
                {
                    if (handlers.get(topic) === handler2)
                    {
                        handler.call(this, s, Object.assign({}, info,
                        {
                            topic: info.topic.substr(hsdata.prefixes[n].length).split(hsdata.self).join('${self}')
                        }), done);
                    }
                };
                handler2.handler = handler;
                handlers.set(topic, handler2);
            }
                
            this._orig_subscribe(topic, handler2, cb);
        };
 
        this._orig_unsubscribe = this.unsubscribe;
        this.unsubscribe = function (n, topic, handler, cb)
        {
            if (typeof n !== 'number')
            {
                cb = handler;
                handler = topic;
                topic = n;
                n = 0;
            }
 
            if (typeof topic === 'function')
            {
                cb = topic;
                topic = undefined;
                handler = undefined;
            }
 
            if (n >= hsdata.prefixes.length)
            {
                return cb(new Error('token out of range'));
            }
 
            var ths = this;
 
            function unsub(t, h)
            {
                var centro_subs = h._centro_subs;
                if (!centro_subs)
                {
                    return h;
                }
 
                var handlers = centro_subs.get(ths);
                if (!handlers)
                {
                    return h;
                }
 
                var h2 = handlers.get(t);
                if (!h2)
                {
                    return h;
                }
 
                handlers.delete(t);
                if (handlers.size === 0)
                {
                    centro_subs.delete(ths);
                    if (centro_subs.size === 0)
                    {
                        delete h._centro_subs;
                    }
                }
 
                return h2;
            }
 
            if (topic === undefined)
            {
                async.eachSeries(this.subs, function (th, cb)
                {
                    if (th[0].lastIndexOf(hsdata.prefixes[n], 0) === 0)
                    {
                        for (var h of th[1])
                        {
                            unsub(th[0], h.handler);
                        }
                        // Remove while iterating on ES6 Maps is consistent
                        ths._orig_unsubscribe(th[0], undefined, cb);
                    }
                    else
                    {
                        cb();
                    }
                }, cb);
            }
            else
            {
                topic = hsdata.prefixes[n] + replace(topic);
 
                if (handler === undefined)
                {
                    var hs = this.subs.get(topic);
                    if (hs !== undefined)
                    {
                        for (var h of hs)
                        {
                            unsub(topic, h.handler);
                        }
                    }
                }
                else
                {
                    handler = unsub(topic, handler);
                }
 
                this._orig_unsubscribe(topic,
                                       handler,
                                       cb);
            }
        };
 
        this._orig_publish = this.publish;
        this.publish = function (n, topic, options, cb)
        {
            if (typeof n !== 'number')
            {
                cb = options;
                options = topic;
                topic = n;
                n = 0;
            }
 
            if (typeof options === 'function')
            {
                cb = options;
                options = undefined;
            }
 
            if (n >= hsdata.prefixes.length)
            {
                cb(new Error('token out of range'));
                return null;
            }
 
            return this._orig_publish(hsdata.prefixes[n] + replace(topic),
                                      options,
                                      cb);
        };
 
        this.emit('ready', hsdata.subscriptions);
    });
 
    return mqclient;
}
 
exports.start = start;
 
/**
 * Get authorization data for transports which use HTTP Basic Authentication
 * (currently Primus) and then initiate communication with a server on a stream
 * you supply.
 *
 * @param {Object} [config] - Configuration options. This supports all the options supported by {@link https://github.com/davedoesdev/mqlobber#mqlobberclientstream-options|MQlobberClient} as well as the following:
 * @param {string|string[]} [config.token] - JSON Web Token(s) to present to the server.
 * @param {integer} [config.max_subscriptions] - If the server returns pre-subscription data (see the {@link centro-js/lib/client.event:MQlobberClient#ready|ready} event), emit an `error` event if there are more entries than this maximum. If not specified, no limit is applied.
 * @param {integer} [config.max_topic_length] - If the server returns pre-subscription data (see the {@link centro-js/lib/client.event:MQlobberClient#ready|ready} event), emit an `error` event if one of the topics exceeds this length. If not specified, no limit is applied.
 * @param {centro-js/lib/client.authzCallback} cb - Called with authorization data.
 */
exports.separate_auth = function (config, cb)
{
    if (!cb)
    {
        cb = config;
        config = {};
    }
 
    var stokens;
    
    try
    {
        stokens = get_stokens(config);
    }
    catch (ex)
    {
        return cb(ex);
    }
 
    cb(null, 'centro:' + stokens, function (stream)
    {
        return start(stream, config);
    });
};
 
/**
 * Authorize with a server on a stream, for transports which send authorization
 * data as a stream header (currently all except Primus and HTTP).
 *
 * @param {stream.Duplex} stream - Connection you've already made to the server.
 * @param {Object} [config] - Configuration options. This supports all the options supported by {@link https://github.com/davedoesdev/mqlobber#mqlobberclientstream-options|MQlobberClient} as well as the following:
 * @param {string|string[]} [config.token] - JSON Web Token(s) to present to the server.
 * @param {integer} [config.max_subscriptions] - If the server returns pre-subscription data (see the {@link centro-js/lib/client.event:MQlobberClient#ready|ready} event), emit an `error` event if there are more entries than this maximum. If not specified, no limit is applied.
 * @param {integer} [config.max_topic_length] - If the server returns pre-subscription data (see the {@link centro-js/lib/client.event:MQlobberClient#ready|ready} event), emit an `error` event if one of the topics exceeds this length. If not specified, no limit is applied.
 * @returns {MQlobberClient} - Object you can use for publishing and subscribing to messages. See the {@link https://github.com/davedoesdev/mqlobber#mqlobberclientstream-options|mqlobber documentation}.
 */
exports.stream_auth = function (stream, config)
{
    // write frame
 
    var out_stream = frame.encode(config);
 
    out_stream._pushFrameData = function (bufs)
    {
        for (var buf of bufs)
        {
            stream.write(buf);
        }
    };
 
    out_stream.end(get_stokens(config));
 
    return start(stream, config);
};
 
/*eslint-disable no-unused-vars */
 
/**
 * Callback type for HTTP Basic Authentication data.
 *
 * @callback authzCallback
 * @memberof centro-js/lib/client
 * @param {?Error} err - Error, if one occurred.
 * @param {string} userpass - Authentication data in the form `centro:<tokens>` where `<tokens>` a comma-separated list of tokens you passed to {@link centro-js/lib/client.separate_auth}.
 * @param {streamCallback} cb - Call this when you've made a connection to the server.
 */
/* istanbul ignore next */
exports._authzCallback = function (err, userpass, cb) {};
 
/**
  * Callback type for connection to server.
  *
  * @callback streamCallback
  * @memberof centro-js/lib/client
  * @param {stream.Duplex} stream - Connection you've made to the server.
  * @returns {MQlobberClient} - Object you can use for publishing and subscribing to messages. See the {@link https://github.com/davedoesdev/mqlobber#mqlobberclientstream-options|mqlobber documentation}.
  */
/* istanbul ignore next */
exports._streamCallback = function (stream) {};
 
/**
  * Ready event. This is an extra event added to {@link https://github.com/davedoesdev/mqlobber#mqlobberclientstream-options|MQlobberClient} and is emitted when the server has authorized the client and a connection is established.
  *
  * @event MQlobberClient#ready
  * @memberof centro-js/lib/client
  * @param {Object.<string, boolean>[]} [subscriptions] - For each authorization token you supplied to {@link centro-js/lib/client.separate_auth} or {@link centro-js/lib/client.stream_auth}, a map containing the topics to which the client has been pre-subscribed. Each topic maps to whether the client will receive existing messages for the topic (`true`) or just new ones (`false`). If no tokens specified any pre-subscriptions then this will be `undefined`.
  */
/* istanbul ignore next */
exports._ready_event = function (subscriptions) {};