All files / lib/infrastructure amqp-manager.js

100% Statements 55/55
57.14% Branches 8/14
100% Functions 18/18
100% Lines 54/54

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          3x 3x 3x 3x 3x 3x 3x 3x   3x 3x                             22x                   22x 22x   22x               19x 19x               4x               5x               24x                 12x               4x                   12x 12x 12x 1x 1x   1x   11x       11x                 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x               3x 3x 3x 3x 3x 3x 3x                 1x 1x 1x   1x       1x 1x             1x       3x  
/**
 * @module AmqpManager
 */
 
 
const amqplib = require('amqplib');
const deepClone = require('../utils/deepClone');
const PublisherValidate = require('../validation/publisher');
const ConsumerValidate = require('../validation/consumer');
const ExplorerValidate = require('../validation/manager');
const Publisher = require('./publisher');
const Consumer = require('./consumer');
const msapi = require('@molfar/msapi-schemas');
 
const defaultPublisherOptions = msapi.produceStrict.snippet.json;
const defaultConsumerOptions =  msapi.consumeStrict.snippet.json;
 
/**
 * AmqpManager
 */
 
class AmqpManager {
  /**
   * посилання на amqp-manager
   */
  static #instance;
 
  /**
   * колекція ключ/значення
   */
  #pool = new Map();
 
  constructor() {}
 
  /**
   * Створює посилання на amqp-manager якщо його немає
   * @returns {Object} - {@see instance}
   * @alias module: AmqpManager
   */
  static getInstance() {
    if (!AmqpManager.#instance) {
      AmqpManager.#instance = new AmqpManager();
    }
    return AmqpManager.#instance;
  }
 
  /**
   * Створює нове посилання на amqp-manager
   * @returns {Object}
   */
  newInstance() {
    AmqpManager.#instance = null;
    return AmqpManager.getInstance();
  }
 
  /**
   * гетер для колекції
   * @returns {Map}
   */
  get pool() {
    return this.#pool;
  }
 
  /**
   * Задає значення для колекції
   * @param newPool нова колекція
   */
  set pool(newPool) {
    this.#pool = newPool;
  }
 
  /**
   * @returns {Map} повертає конфігурацію з'єднання
   * @param url url для з'єднання з AMQP-брокером
   */
  getConnectionConfig(url) {
    return this.#pool.get(url);
  }
 
  /**
   * Задає конфігурації з'єднання по клієнту
   * @param url url для з'єднання з AMQP-брокером
   * @param connection з'єднання з AMQP-брокером
   */
  setConnectionConfig(url, connection) {
    this.#pool.set(url, connection);
  }
 
  /**
   * @param client UUID клієнта
   * @returns {Map} Повертає конфігурацію з'єднання по клієнту
   */
  getClientConnection(client) {
    return [...this.#pool].find(([url, { clients }]) => clients.includes(client));
  }
 
  /**
   * Створює конфігурацію по клієнту
   * @param client UUID клієнта
   * @param options налаштування з'єднання з AMQP-брокером
   * @returns {} повертає з'єднання з AMQP-брокером
   */
  async getConnection(client, options) {
    ExplorerValidate.validateOptions(options);
    const existingConnection = this.getConnectionConfig(options.url);
    if (existingConnection) {
      if (!existingConnection.clients.includes(client)) {
        existingConnection.clients.push(client);
      }
      return existingConnection.connection;
    }
    this.setConnectionConfig(options.url, {
      connection: await amqplib.connect(options.url),
      clients: [client]
    });
    return this.getConnectionConfig(options.url).connection;
  }
 
  /**
   * Створює publisher
   * @params options налаштування публікувальника
   * @returns {Publisher} об'єкт класу {@link Publisher}
   */
  async createPublisher(options) {
    let calcOptions = deepClone(deepClone({}, defaultPublisherOptions), options || {});
    PublisherValidate.validateOptions(calcOptions);
    const publisher = new Publisher(this, calcOptions);
    await publisher.moduleInit();
    return publisher;
  }
 
  /**
   * Створює consumer
   * @returns {Object} об'єкт класу Consumer
   */
  async createConsumer(options) {
    const calcOptions = deepClone(deepClone({}, defaultConsumerOptions), options || {});
    ConsumerValidate.validateOptions(calcOptions);
    const consumer = new Consumer(this, calcOptions);
    await consumer.moduleInit();
    return consumer;
  }
 
  /**
   * Закриває з'днання по клієнту
   * @param client
   */
  async closeConnection(client) {
    const connectionConfig = this.getClientConnection(client);
    if (connectionConfig) {
      const clientIndex = connectionConfig[1].clients
        .findIndex(clientIteration => clientIteration === client);
      connectionConfig[1].clients.splice(clientIndex, 1);
      if (!connectionConfig[1].clients.length) {
        await connectionConfig[1].connection.close();
      }
    }
  }
 
  /**
   * Закриває з'єднання для всіх клієнтів
   */
  async clearAndShutdown() {
    const closeConnectionTasks = [];
    this.#pool.forEach(({ connection }) => {
      closeConnectionTasks.push(
        new Promise((resolve) => {
          connection.close().then(resolve);
        })
      );
    });
    await Promise.all(closeConnectionTasks);
    this.#pool.clear();
  }
 
  /**
   * @returns {size} повертає розмір pool-конфігурацій з'єднання
   */
  size() {
    return this.#pool.size;
  }
}
 
module.exports = AmqpManager.getInstance();