All files / src/networkWrapper/protocols/abstract common.js

95.74% Statements 90/94
95.52% Branches 64/67
92.59% Functions 25/27
95.74% Lines 90/94

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      2x                     127x   127x 127x 127x   127x 127x 127x 127x 127x 127x 127x 127x 127x 127x   127x 392x             272x       67x       57x                                               23x 23x   23x 4x     23x 3x               2x 2x                 1x             2x 1x 1x               12x             5x       8x   8x 2x     8x 4x 4x 4x 4x                 4x 1x     3x         2x             9x 9x   9x 8x 29x 6x       8x 1x     6x         9x 1x     6x                   6x 6x 27x 24x     24x   24x 24x         6x 5x 1x     4x 4x 3x       19x 1x     18x     1x       3x       4x 4x 4x 2x 2x 2x 2x 2x   2x 1x     2x     2x     4x         2x  
'use strict';
 
const
  KuzzleEventEmitter = require('../../../eventEmitter');
 
// read-only properties
let
  _host,
  _port,
  _ssl;
 
class AbstractWrapper extends KuzzleEventEmitter {
 
  constructor (options = {}) {
    super();
 
    _host = options.host;
    _port = typeof options.port === 'number' ? options.port : 7512;
    _ssl = typeof options.sslConnection === 'boolean' ? options.sslConnection : false;
 
    this.autoReplay = false;
    this.autoQueue = false;
    this.offlineQueue = [];
    this.offlineQueueLoader = null;
    this.queueFilter = null;
    this.queueMaxSize = 500;
    this.queueTTL = 120000;
    this.queuing = false;
    this.replayInterval = 10;
    this.state = 'offline';
 
    Object.keys(options).forEach(opt => {
      Iif (this.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(this, opt).writable) {
        this[opt] = options[opt];
      }
    });
  }
 
  get host () {
    return _host;
  }
 
  get port () {
    return _port;
  }
 
  get ssl () {
    return _ssl;
  }
 
  /**
   * @abstract
   * @returns {Promise<any>}
   */
  connect () {
    throw new Error('Method "connect" is not implemented');
  }
 
  /**
   * @abstract
   * @param request
   * @returns {Promise<any>}
   */
  send () {
    throw new Error('Method "send" is not implemented');
  }
 
  /**
   * Called when the client's connection is established
   */
  clientConnected (state, wasConnected) {
    this.state = state || 'ready';
    this.emit(wasConnected && 'reconnect' || 'connect');
 
    if (this.autoQueue) {
      this.stopQueuing();
    }
 
    if (this.autoReplay) {
      this.playQueue();
    }
  }
 
  /**
   * Called when the client's connection is closed
   */
  close () {
    this.state = 'offline';
    Iif (this.autoQueue) {
      this.startQueuing();
    }
  }
 
  /**
   * Empties the offline queue without replaying it.
   */
  flushQueue () {
    this.offlineQueue = [];
  }
 
  /**
   * Replays the requests queued during offline mode.
   */
  playQueue () {
    if (this.isReady()) {
      this._cleanQueue();
      this._dequeue();
    }
  }
 
  /**
   * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.
   */
  startQueuing () {
    this.queuing = true;
  }
 
  /**
   * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.
   */
  stopQueuing () {
    this.queuing = false;
  }
 
  query (request, options) {
    let queuable = options && (options.queuable !== false) || true;
 
    if (this.queueFilter) {
      queuable = queuable && this.queueFilter(request);
    }
 
    if (this.queuing && queuable) {
      this._cleanQueue();
      this.emit('offlineQueuePush', {request});
      return new Promise((resolve, reject) => {
        this.offlineQueue.push({
          resolve,
          reject,
          request,
          ts: Date.now()
        });
      });
    }
 
    if (this.isReady()) {
      return this._emitRequest(request);
    }
 
    return Promise.reject(new Error(`Unable to execute request: not connected to a Kuzzle server.
Discarded request: ${JSON.stringify(request)}`));
  }
 
  isReady () {
    return this.state === 'ready';
  }
 
  /**
   * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected
   */
  _cleanQueue () {
    const now = Date.now();
    let lastDocumentIndex = -1;
 
    if (this.queueTTL > 0) {
      this.offlineQueue.forEach((query, index) => {
        if (query.ts < now - this.queueTTL) {
          lastDocumentIndex = index;
        }
      });
 
      if (lastDocumentIndex !== -1) {
        this.offlineQueue
          .splice(0, lastDocumentIndex + 1)
          .forEach(droppedRequest => {
            this.emit('offlineQueuePop', droppedRequest.query);
          });
      }
    }
 
    if (this.queueMaxSize > 0 && this.offlineQueue.length > this.queueMaxSize) {
      this.offlineQueue
        .splice(0, this.offlineQueue.length - this.queueMaxSize)
        .forEach(droppedRequest => {
          this.emit('offlineQueuePop', droppedRequest.query);
        });
    }
  }
 
  /**
   * Play all queued requests, in order.
   */
  _dequeue () {
    const
      uniqueQueue = {},
      dequeuingProcess = () => {
        if (this.offlineQueue.length > 0) {
          this._emitRequest(this.offlineQueue[0].request)
            .then(this.offlineQueue[0].resolve)
            .catch(this.offlineQueue[0].reject);
          this.emit('offlineQueuePop', this.offlineQueue.shift());
 
          setTimeout(() => {
            dequeuingProcess();
          }, Math.max(0, this.replayInterval));
        }
      };
 
    if (this.offlineQueueLoader) {
      if (typeof this.offlineQueueLoader !== 'function') {
        throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof this.offlineQueueLoader);
      }
 
      const additionalQueue = this.offlineQueueLoader();
      if (Array.isArray(additionalQueue)) {
        this.offlineQueue = additionalQueue
          .concat(this.offlineQueue)
          .filter(query => {
            // throws if the request does not contain required attributes
            if (!query.request || query.request.requestId === undefined || !query.request.action || !query.request.controller) {
              throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');
            }
 
            return uniqueQueue.hasOwnProperty(query.request.requestId) ? false : (uniqueQueue[query.request.requestId] = true);
          });
      } else {
        throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);
      }
    }
 
    dequeuingProcess();
  }
 
  _emitRequest (request) {
    return new Promise((resolve, reject) => {
      this.once(request.requestId, response => {
        if (response.error) {
          const error = new Error(response.error.message);
          Object.assign(error, response.error);
          error.status = response.status;
          response.error = error;
          this.emit('queryError', error, request);
 
          if (request.action !== 'logout' && error.message === 'Token expired') {
            this.emit('tokenExpired');
          }
 
          return reject(error);
        }
 
        return resolve(response);
      });
 
      this.send(request);
    });
  }
}
 
module.exports = AbstractWrapper;