All files / src Kuzzle.js

94.54% Statements 225/238
86.93% Branches 133/153
90.16% Functions 55/61
94.47% Lines 222/235

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 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645  2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x                                       108x   108x 1x       107x 318x 3x     104x   104x                 104x       104x       104x       104x   104x         104x 104x 104x 104x 104x 104x 104x 104x 104x     104x 104x     104x     104x     104x     104x     104x     104x     104x       104x 1x 1x   104x   104x   104x                       106x       11x 10x       1x       3x 2x       78x       7x 6x               1x       6x 4x     2x       6x       45x       11x       4x 3x       1x       19x       3x 2x       3x       2x 1x       2x       2x 1x       1x       7x       2x 1x       1x       2x       2x 1x                   110x 110x   110x 88x     61x   27x     49x               23x 1x     22x 5x     22x   22x   22x 48x 13x     48x 2x     48x     22x 6x 2x     6x   6x     22x 4x   4x     22x 28x 4x     28x 2x     28x   28x 7x     7x 1x           7x     21x     22x   22x                     21x 1x     20x                 2x 2x             1x                               22x 2x     20x 2x     18x 14x       18x 1x     18x 11x 7x       2x     16x 6x 2x     16x 16x   16x   16x 16x 1x     16x 1x     16x 3x 1x 1x 1x 1x                 2x 2x       13x             3x 3x             8x 8x             6x 5x 5x   6x               2x   2x         2x   2x 2x   2x                     945x 1x     944x 1x     943x 1x     942x   942x 1x     941x 1x     940x 4x   940x   940x       36x   36x 9x               1x 1x   1x 1x           1x                 1x                           4x 4x 10x 6x     6x   6x 6x         4x 2x       2x 2x   2x 2x       4x       4x             2x             2x         2x  
const
  KuzzleEventEmitter = require('./eventEmitter'),
  AuthController = require('./controllers/auth'),
  BulkController = require('./controllers/bulk'),
  CollectionController = require('./controllers/collection'),
  DocumentController = require('./controllers/document'),
  IndexController = require('./controllers/index'),
  RealtimeController = require('./controllers/realtime'),
  ServerController = require('./controllers/server'),
  SecurityController = require('./controllers/security'),
  MemoryStorageController = require('./controllers/memoryStorage'),
  BaseController = require('./controllers/base'),
  uuidv4 = require('./uuidv4'),
  proxify = require('./proxify');
 
const
  events = [
    'connected',
    'discarded',
    'disconnected',
    'loginAttempt',
    'networkError',
    'offlineQueuePush',
    'offlineQueuePop',
    'queryError',
    'reconnected',
    'tokenExpired'
  ];
 
class Kuzzle extends KuzzleEventEmitter {
 
  /**
   * @param protocol - the protocol to use
   * @param [options] - Kuzzle options
   */
  constructor(protocol, options = {}) {
    super();
 
    if (protocol === undefined || protocol === null) {
      throw new Error('"protocol" argument missing');
    }
 
    // check the existence of required methods
    for (const method of ['addListener', 'isReady', 'query']) {
      if (typeof protocol[method] !== 'function') {
        throw new Error(`Protocol instance must implement a "${method}" method`);
      }
    }
    this.protocol = protocol;
 
    this._protectedEvents = {
      connected: {},
      error: {},
      disconnected: {},
      reconnected: {},
      tokenExpired: {},
      loginAttempt: {}
    };
 
    this.autoResubscribe = typeof options.autoResubscribe === 'boolean'
      ? options.autoResubscribe
      : true;
 
    this.eventTimeout = typeof options.eventTimeout === 'number'
      ? options.eventTimeout
      : 200;
 
    this.sdkVersion = typeof SDKVERSION === 'undefined'
      ? require('../package').version
      : SDKVERSION;
 
    this.sdkName = `js@${this.sdkVersion}`;
 
    this.volatile = typeof options.volatile === 'object'
      ? options.volatile
      : {};
 
    // controllers
    this.useController(AuthController, 'auth');
    this.useController(BulkController, 'bulk');
    this.useController(CollectionController, 'collection');
    this.useController(DocumentController, 'document');
    this.useController(IndexController, 'index');
    this.useController(MemoryStorageController, 'ms');
    this.useController(RealtimeController, 'realtime');
    this.useController(SecurityController, 'security');
    this.useController(ServerController, 'server');
 
    // offline queue
    this._offlineQueue = [];
    this._autoQueue = typeof options.autoQueue === 'boolean'
      ? options.autoQueue
      : false;
    this._autoReplay = typeof options.autoReplay === 'boolean'
      ? options.autoReplay
      : false;
    this._offlineQueueLoader = typeof options.offlineQueueLoader === 'function'
      ? options.offlineQueueLoader
      : null;
    this._queueFilter = typeof options.queueFilter === 'function'
      ? options.queueFilter
      : null;
    this._queueMaxSize = typeof options.queueMaxSize === 'number'
      ? options.queueMaxSize
      : 500;
    this._queueTTL = typeof options.queueTTL === 'number'
      ? options.queueTTL
      : 120000;
    this._replayInterval = typeof options.replayInterval === 'number'
      ? options.replayInterval
      : 10;
    this._tokenExpiredInterval = typeof options.tokenExpiredInterval === 'number'
      ? options.tokenExpiredInterval
      : 1000;
 
    if (options.offlineMode === 'auto') {
      this._autoQueue = true;
      this._autoReplay = true;
    }
    this.queuing = false;
 
    this._lastTokenExpired = null;
 
    return proxify(this, {
      seal: true,
      name: 'kuzzle',
      exposeApi: true
    });
  }
 
  get authenticated () {
    return this.auth.authenticationToken && !this.auth.authenticationToken.expired;
  }
 
  get autoQueue () {
    return this._autoQueue;
  }
 
  set autoQueue (value) {
    this._checkPropertyType('_autoQueue', 'boolean', value);
    this._autoQueue = value;
  }
 
  get autoReconnect () {
    return this.protocol.autoReconnect;
  }
 
  set autoReconnect (value) {
    this._checkPropertyType('autoReconnect', 'boolean', value);
    this.protocol.autoReconnect = value;
  }
 
  get autoReplay () {
    return this._autoReplay;
  }
 
  set autoReplay (value) {
    this._checkPropertyType('_autoReplay', 'boolean', value);
    this._autoReplay = value;
  }
 
  get connected () {
    return this.protocol.connected;
  }
 
  get host () {
    return this.protocol.host;
  }
 
  get jwt () {
    if (!this.auth.authenticationToken) {
      return null;
    }
 
    return this.auth.authenticationToken.encodedJwt;
  }
 
  set jwt (encodedJwt) {
    this.auth.authenticationToken = encodedJwt;
  }
 
  get offlineQueue () {
    return this._offlineQueue;
  }
 
  get offlineQueueLoader () {
    return this._offlineQueueLoader;
  }
 
  set offlineQueueLoader (value) {
    this._checkPropertyType('_offlineQueueLoader', 'function', value);
    this._offlineQueueLoader = value;
  }
 
  get port () {
    return this.protocol.port;
  }
 
  get queueFilter () {
    return this._queueFilter;
  }
 
  set queueFilter (value) {
    this._checkPropertyType('_queueFilter', 'function', value);
    this._queueFilter= value;
  }
 
  get queueMaxSize () {
    return this._queueMaxSize;
  }
 
  set queueMaxSize (value) {
    this._checkPropertyType('_queueMaxSize', 'number', value);
    this._queueMaxSize = value;
  }
 
  get queueTTL () {
    return this._queueTTL;
  }
 
  set queueTTL (value) {
    this._checkPropertyType('_queueTTL', 'number', value);
    this._queueTTL = value;
  }
 
  get reconnectionDelay () {
    return this.protocol.reconnectionDelay;
  }
 
  get replayInterval () {
    return this._replayInterval;
  }
 
  set replayInterval (value) {
    this._checkPropertyType('_replayInterval', 'number', value);
    this._replayInterval = value;
  }
 
  get sslConnection () {
    return this.protocol.sslConnection;
  }
 
  get tokenExpiredInterval () {
    return this._tokenExpiredInterval;
  }
 
  set tokenExpiredInterval (value) {
    this._checkPropertyType('_tokenExpiredInterval', 'number', value);
    this._tokenExpiredInterval = value;
  }
 
 
  /**
  * Emit an event to all registered listeners
  * An event cannot be emitted multiple times before a timeout has been reached.
  */
  emit (eventName, ...payload) {
    const
      now = Date.now(),
      protectedEvent = this._protectedEvents[eventName];
 
    if (protectedEvent) {
      if ( protectedEvent.lastEmitted
        && protectedEvent.lastEmitted > now - this.eventTimeout)
      {
        return false;
      }
      protectedEvent.lastEmitted = now;
    }
 
    super.emit(eventName, ...payload);
  }
 
  /**
   * Connects to a Kuzzle instance using the provided host name
   * @returns {Promise<Object>}
   */
  connect () {
    if (this.protocol.isReady()) {
      return Promise.resolve();
    }
 
    if (this.autoQueue) {
      this.startQueuing();
    }
 
    this.protocol.addListener('queryError', (err, query) => this.emit('queryError', err, query));
 
    this.protocol.addListener('tokenExpired', () => this.tokenExpired());
 
    this.protocol.addListener('connect', () => {
      if (this.autoQueue) {
        this.stopQueuing();
      }
 
      if (this.autoReplay) {
        this.playQueue();
      }
 
      this.emit('connected');
    });
 
    this.protocol.addListener('networkError', error => {
      if (this.autoQueue) {
        this.startQueuing();
      }
 
      this.realtime.disconnected();
 
      this.emit('networkError', error);
    });
 
    this.protocol.addListener('disconnect', () => {
      this.realtime.disconnected();
 
      this.emit('disconnected');
    });
 
    this.protocol.addListener('reconnect', () => {
      if (this.autoQueue) {
        this.stopQueuing();
      }
 
      if (this.autoReplay) {
        this.playQueue();
      }
 
      this.realtime.reconnected();
 
      if (this.auth.authenticationToken) {
        return this.auth.checkToken()
          .then(res => {
            // shouldn't obtain an error but let's invalidate the token anyway
            if (!res.valid) {
              this.auth.authenticationToken = null;
            }
          })
          .catch(() => {
            this.auth.authenticationToken = null;
          })
          .then(() => this.emit('reconnected'));
      }
 
      this.emit('reconnected');
    });
 
    this.protocol.addListener('discarded', data => this.emit('discarded', data));
 
    return this.protocol.connect();
  }
 
  /**
   * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their
   * insertion.
   *
   * @param {string} event - name of the global event to subscribe to
   * @param {function} listener - callback to invoke each time an event is fired
   */
  addListener (event, listener) {
    if (events.indexOf(event) === -1) {
      throw new Error(`[${event}] is not a known event. Known events: ${events.toString()}`);
    }
 
    return super.addListener(event, listener);
  }
 
  /**
   * Empties the offline queue without replaying it.
   *
   * @returns {Kuzzle}
   */
  flushQueue () {
    this._offlineQueue = [];
    return this;
  }
 
  /**
   * Disconnects from Kuzzle and invalidate this instance.
   */
  disconnect () {
    this.protocol.close();
  }
 
  /**
   * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.
   * Base method used to send read queries to Kuzzle
   *
   * Takes an optional argument object with the following properties:
   *    - volatile (object, default: null):
   *        Additional information passed to notifications to other users
   *
   * @param {object} request
   * @param {object} [options] - Optional arguments
   * @returns {Promise<object>}
   */
  query (request = {}, options = {}) {
    if (typeof request !== 'object' || Array.isArray(request)) {
      throw new Error(`Kuzzle.query: Invalid request: ${JSON.stringify(request)}`);
    }
 
    if (typeof options !== 'object' || Array.isArray(options)) {
      throw new Error(`Kuzzle.query: Invalid "options" argument: ${JSON.stringify(options)}`);
    }
 
    if (!request.requestId) {
      request.requestId = uuidv4();
    }
 
    // we follow the api but allow some more logical "mistakes" (the only allowed value for refresh arg is "wait_for")
    if (request.refresh) {
      request.refresh = 'wait_for';
    }
 
    if (!request.volatile) {
      request.volatile = this.volatile;
    } else if (
      typeof request.volatile !== 'object'
      || Array.isArray(request.volatile)
    ) {
      throw new Error(`Kuzzle.query: Invalid volatile argument received: ${JSON.stringify(request.volatile)}`);
    }
 
    for (const item of Object.keys(this.volatile)) {
      if (request.volatile[item] === undefined) {
        request.volatile[item] = this.volatile[item];
      }
    }
    request.volatile.sdkInstanceId = request.volatile.sdkInstanceId || this.protocol.id;
    request.volatile.sdkName = request.volatile.sdkName || this.sdkName;
 
    this.auth.authenticateRequest(request);
 
    let queuable = true;
    if (options && options.queuable === false) {
      queuable = false;
    }
 
    if (this.queueFilter) {
      queuable = queuable && this.queueFilter(request);
    }
 
    if (this.queuing) {
      if (queuable) {
        this._cleanQueue();
        this.emit('offlineQueuePush', {request});
        return new Promise((resolve, reject) => {
          this.offlineQueue.push({
            resolve,
            reject,
            request,
            ts: Date.now()
          });
        });
      }
 
      this.emit('discarded', {request});
      return Promise.reject(new Error(`Unable to execute request: not connected to a Kuzzle server.
Discarded request: ${JSON.stringify(request)}`));
    }
 
    return this.protocol.query(request);
  }
 
  /**
   * Starts the requests queuing.
   */
  startQueuing () {
    this.queuing = true;
    return this;
  }
 
  /**
   * Stops the requests queuing.
   */
  stopQueuing () {
    this.queuing = false;
    return this;
  }
 
  /**
   * Plays the requests queued during offline mode.
   */
  playQueue () {
    if (this.protocol.isReady()) {
      this._cleanQueue();
      this._dequeue();
    }
    return this;
  }
 
  /**
   * On token expiration, reset jwt and unsubscribe all rooms.
   * Throttles to avoid duplicate event triggers.
   */
  tokenExpired() {
    const now = Date.now();
 
    Iif ((now - this._lastTokenExpired) < this.tokenExpiredInterval) {
      // event was recently already fired
      return;
    }
 
    this._lastTokenExpired = now;
 
    this.auth.authenticationToken = null;
    this.realtime.tokenExpired();
 
    this.emit('tokenExpired');
  }
 
  /**
   * Adds a new controller and make it available in the SDK.
   *
   * @param {BaseController} ControllerClass
   * @param {string} accessor
   * @returns {Kuzzle}
   */
  useController (ControllerClass, accessor) {
    if (!(ControllerClass.prototype instanceof BaseController)) {
      throw new Error('Controllers must inherits from the BaseController class.');
    }
 
    if (!(accessor && accessor.length > 0)) {
      throw new Error('You must provide a valid accessor.');
    }
 
    if (this.__proxy__ ? this.__proxy__.hasProp(accessor) : this[accessor]) {
      throw new Error(`There is already a controller with the accessor '${accessor}'. Please use another one.`);
    }
 
    const controller = new ControllerClass(this);
 
    if (!(controller.name && controller.name.length > 0)) {
      throw new Error('Controllers must have a name.');
    }
 
    if (controller.kuzzle !== this) {
      throw new Error('You must pass the Kuzzle SDK instance to the parent constructor.');
    }
 
    if (this.__proxy__) {
      this.__proxy__.registerProp(accessor);
    }
    this[accessor] = controller;
 
    return this;
  }
 
  _checkPropertyType (prop, typestr, value) {
    const wrongType = typestr === 'array' ? !Array.isArray(value) : typeof value !== typestr;
 
    if (wrongType) {
      throw new Error(`Expected ${prop} to be a ${typestr}, ${typeof value} received`);
    }
  }
 
  /**
   * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected
   */
  _cleanQueue () {
    const now = Date.now();
    let lastDocumentIndex = -1;
 
    Eif (this.queueTTL > 0) {
      this.offlineQueue.forEach((query, index) => {
        if (query.ts < now - this.queueTTL) {
          lastDocumentIndex = index;
        }
      });
 
      Iif (lastDocumentIndex !== -1) {
        this.offlineQueue
          .splice(0, lastDocumentIndex + 1)
          .forEach(droppedRequest => {
            this.emit('offlineQueuePop', droppedRequest.query);
          });
      }
    }
 
    Iif (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.protocol.query(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) {
      Iif (typeof this.offlineQueueLoader !== 'function') {
        throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof this.offlineQueueLoader);
      }
 
      return Promise.resolve()
        .then(() => this.offlineQueueLoader())
        .then(additionalQueue => {
          Eif (Array.isArray(additionalQueue)) {
            this._offlineQueue = additionalQueue
              .concat(this.offlineQueue)
              .filter(query => {
                // throws if the request does not contain required attributes
                Iif (!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 Object.prototype.hasOwnProperty.call(
                  uniqueQueue,
                  query.request.requestId)
                  ? false
                  : (uniqueQueue[query.request.requestId] = true);
              });
 
            dequeuingProcess();
          } else {
            throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);
          }
        });
    }
 
    dequeuingProcess();
  }
 
}
 
module.exports = Kuzzle;