All files / mq lib.js

100% Statements 80/80
97.43% Branches 76/78
100% Functions 6/6
100% Lines 80/80

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    1x   1x 1x 1x 1x 1x 1x   1x                                                                                                                                                                 46x 4x     42x 42x                         1x 1x                         82x   82x 82x 36x       46x     21x 21x     21x 21x   4x   42x 42x 42x 42x                           50x 50x 8x 8x       42x 42x 38x   42x 42x 42x                                         90x 4x 86x 4x 82x 4x 78x 4x 74x 4x 70x 4x 66x 4x 62x 4x 58x       4x 54x 4x 50x 4x     46x 4x     42x 42x   42x                 42x   42x 42x 42x   42x 42x 42x   42x 42x 42x   42x 42x 42x   42x                 1x            
'use strict';
 
const { URL } = require('url');
 
const gmq = require('general-mq');
const { AmqpConnection } = require('general-mq/lib/amqp-connection');
const { AmqpQueue } = require('general-mq/lib/amqp-queue');
const { DataTypes } = require('general-mq/lib/constants');
const { MqttConnection } = require('general-mq/lib/mqtt-connection');
const { MqttQueue } = require('general-mq/lib/mqtt-queue');
 
const { Status } = require('./constants');
 
/**
 * Detail queue connection status.
 *
 * @typedef {Object} DataMqStatus
 * @property {Status} uldata
 * @property {Status} dldata
 * @property {Status} dldataResp
 * @property {Status} dldataResult
 * @property {Status} ctrl
 */
 
/**
 * The options of the application/network manager.
 *
 * @typedef {Object} Options
 * @property {string} [unitId] The associated unit ID of the application/network. Empty or undefined
 *           for public network.
 * @property {string} [unitCode] The associated unit code of the application/network. Empty or
 *           undefined for public network.
 * @property {string} id The associated application/network ID.
 * @property {string} name The associated application/network code.
 * @property {number} [prefetch=100] AMQP prefetch option.
 * @property {boolean} [persistent=false] AMQP persistent option.
 * @property {string} [sharedPrefix] MQTT shared queue prefix option.
 */
 
/**
 * @typedef {Object} CtrlAddDevice
 * @property {string} networkAddr
 */
 
/**
 * @typedef {Object} CtrlAddDeviceBulk
 * @property {string[]} networkAddrs
 */
 
/**
 * @typedef {Object} CtrlAddDeviceRange
 * @property {string} startAddr
 * @property {string} endAddr
 */
 
/**
 * @typedef {Object} CtrlDelDevice
 * @property {string} networkAddr
 */
 
/**
 * @typedef {Object} CtrlDelDeviceBulk
 * @property {string[]} networkAddrs
 */
 
/**
 * @typedef {Object} CtrlDelDeviceRange
 * @property {string} startAddr
 * @property {string} endAddr
 */
 
/**
 * @private
 * @typedef {Object} DataMqQueues
 * @property {AmqpQueue|MqttQueue} uldata
 * @property {AmqpQueue|MqttQueue} dldata
 * @property {?AmqpQueue|?MqttQueue} dldataResp (for application only)
 * @property {AmqpQueue|MqttQueue} dldataResult
 * @property {?AmqpQueue|?MqttQueue} ctrl (for network only)
 */
 
/**
 * The connection object with reference count for pool management.
 *
 * @class Connection
 */
class Connection {
  /**
   * @param {AmqpConnection|MqttConnection} conn
   * @throws {Error} Wrong host scheme.
   */
  constructor(conn) {
    if (!(conn instanceof AmqpConnection) && !(conn instanceof MqttConnection)) {
      throw Error('invalid `conn`');
    }
 
    this.conn = conn;
    this.count = 0;
  }
 
  /** @type {AmqpConnection|MqttConnection} */
  conn;
  /**
   * Reference count.
   *
   * @type {number}
   */
  count;
}
 
const DEF_PREFETCH = 100;
const DEF_PERSISTENT = false;
 
/**
 * Utility function to get the message queue connection instance. A new connection will be created
 * if the host does not exist.
 *
 * @private
 * @param {Map<string, Connection>} connPool
 * @param {URL} hostUri
 * @returns {Connection}
 * @throws {Error} Wrong host scheme.
 */
function getConnection(connPool, hostUri) {
  const uri = hostUri.toString();
 
  let conn = connPool.get(uri);
  if (conn) {
    return conn;
  }
 
  let engine;
  switch (hostUri.protocol) {
    case 'amqp:':
    case 'amqps:':
      engine = gmq.amqp;
      break;
    case 'mqtt:':
    case 'mqtts:':
      engine = gmq.mqtt;
      break;
    default:
      throw Error(`unsupport scheme ${hostUri.protocol}`);
  }
  const c = new engine.Connection({ uri });
  conn = new Connection(c);
  connPool.set(uri, conn);
  return conn;
}
 
/**
 * Utility function to remove connection from the pool if the reference count meet zero.
 *
 * @private
 * @param {Map<string, Connection>} connPool
 * @param {string} hostUri
 * @param {number} count
 * @param {function} callback
 *   @param {?Error} callback.err
 */
function removeConnection(connPool, hostUri, count, callback) {
  const conn = connPool.get(hostUri);
  if (!conn) {
    return void process.nextTick(() => {
      callback(null);
    });
  }
 
  conn.count -= count;
  if (conn.count <= 0) {
    connPool.delete(hostUri);
  }
  conn.conn.removeAllListeners();
  conn.conn.close((err) => {
    callback(err || null);
  });
}
 
/**
 * The utility function for creating application/network queue. The return object contains:
 * - `[prefix].[unit].[code].uldata`
 * - `[prefix].[unit].[code].dldata`
 * - `[prefix].[unit].[code].dldata-resp`
 * - `[prefix].[unit].[code].dldata-result`
 * - `[prefix].[unit].[code].ctrl`
 *
 * @private
 * @param {Connection} conn
 * @param {Options} opts
 * @param {string} prefix
 * @param {bool} isNetwork
 * @returns {DataMqQueues}
 * @throws {Error} Wrong parameters.
 */
function newDataQueues(conn, opts, prefix, isNetwork) {
  if (!(conn instanceof Connection)) {
    throw Error('`conn` is not a Connection');
  } else if (!opts || typeof opts !== DataTypes.Object || Array.isArray(opts)) {
    throw Error('`opts` is not an object');
  } else if (!prefix || typeof prefix !== DataTypes.String) {
    throw Error('`prefix` is not a string');
  } else if (typeof isNetwork !== DataTypes.Boolean) {
    throw Error('`isNetwork` is not a boolean');
  } else if (opts.unitId !== undefined && typeof opts.unitId !== DataTypes.String) {
    throw Error('`opts.unitId` is not a string');
  } else if (opts.unitCode !== undefined && typeof opts.unitCode !== DataTypes.String) {
    throw Error('`opts.unitCode` is not a string');
  } else if (!opts.id || typeof opts.id !== DataTypes.String) {
    throw Error('`opts.id` is not a non-empty string');
  } else if (!opts.name || typeof opts.name !== DataTypes.String) {
    throw Error('`opts.name` is not a non-empty string');
  } else if (
    opts.prefetch !== undefined &&
    (!Number.isInteger(opts.prefetch) || opts.prefetch < 0 || opts.prefetch > 65535)
  ) {
    throw Error('`opts.prefetch` is not an integer between 1 and 65535');
  } else if (opts.persistent !== undefined && typeof opts.persistent !== DataTypes.Boolean) {
    throw Error('`opts.persistent` is not a boolean');
  } else if (opts.sharedPrefix !== undefined && typeof opts.sharedPrefix !== DataTypes.String) {
    throw Error('`opts.sharedPrefix` is not a string');
  }
 
  if ((opts.unitId && !opts.unitCode) || (!opts.unitId && opts.unitCode)) {
    throw Error('`opts.unitId` and `opts.unitCode` must both empty or non-empty');
  }
 
  const engine = conn.conn instanceof MqttConnection ? gmq.mqtt : gmq.amqp;
  const qNamePrefix = `${prefix}.${opts.unitCode || '_'}.${opts.name}`;
 
  let qOpts = {
    name: `${qNamePrefix}.uldata`,
    isRecv: !isNetwork,
    reliable: true,
    broadcast: false,
    prefetch: opts.prefetch || DEF_PREFETCH,
    persistent: opts.persistent || DEF_PERSISTENT,
    sharedPrefix: opts.sharedPrefix,
  };
  const uldata = new engine.Queue(qOpts, conn.conn);
 
  qOpts.name = `${qNamePrefix}.dldata`;
  qOpts.isRecv = isNetwork;
  const dldata = new engine.Queue(qOpts, conn.conn);
 
  qOpts.name = `${qNamePrefix}.dldata-resp`;
  qOpts.isRecv = !isNetwork;
  const dldataResp = isNetwork ? null : new engine.Queue(qOpts, conn.conn);
 
  qOpts.name = `${qNamePrefix}.dldata-result`;
  qOpts.isRecv = !isNetwork;
  const dldataResult = new engine.Queue(qOpts, conn.conn);
 
  qOpts.name = `${qNamePrefix}.ctrl`;
  qOpts.isRecv = true;
  const ctrl = isNetwork ? new engine.Queue(qOpts, conn.conn) : null;
 
  return {
    uldata,
    dldata,
    dldataResp,
    dldataResult,
    ctrl,
  };
}
 
module.exports = {
  Connection,
  getConnection,
  removeConnection,
  newDataQueues,
};