All files / src/orm apollo.js

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 5761x 1x 1x   1x 1x   1x         1x 1x   1x         1x 1x   1x   1x     1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x   1x   1x 2x       2x   2x             2x 2x 2x 2x 2x 2x 2x     1x     63x 63x     9x   9x 600x     9x   9x       1x       1x 1x 1x 1x     1x       1x 1x       1x 1x   1x 1x       1x       1x   1x                                 1x 1x 1x       1x 1x 1x 1x   1x 1x       5x 5x   5x       4x       1x 1x 1x   1x   1x 1x         1x         1x 1x   1x         1x 1x           2x 2x 2x   2x 1x 1x     1x   2x 2x 2x       2x   2x 2x         2x         2x 2x 2x 2x   2x 2x 2x                     1x               2x 2x 2x   2x 1x 1x     1x   7x 7x 7x       7x     7x   7x 7x         7x         7x 7x   7x 7x   7x 7x   7x 7x 7x 7x 7x   7x         7x 7x             1x               2x 2x 2x   2x 1x 1x     1x   4x 4x 4x       4x     4x   4x 1x     4x 4x         4x         4x 4x 4x 4x 4x   4x 4x   4x 4x 4x 4x   4x         4x 4x             1x             2x 2x   2x 2x     2x           2x 2x 2x         2x 2x 1x 1x   2x 1x 1x   2x   2x             2x 2x       2x 2x           2x 2x       2x 2x           2x 2x       2x 2x 2x           2x 1x   1x         9x       9x 9x         9x 1x       1x   1x           1x               9x 1x     1x   1x               9x                               9x 9x       48x       2x   2x 1x     2x 1x     2x 2x 2x   2x 2x     2x   2x               1x  
const Promise = require('bluebird');
const util = require('util');
const _ = require('lodash');
 
let elasticsearch;
try {
  // eslint-disable-next-line import/no-extraneous-dependencies, import/no-unresolved
  elasticsearch = require('elasticsearch');
} catch (e) {
  elasticsearch = null;
}
 
let gremlin;
try {
  // eslint-disable-next-line import/no-extraneous-dependencies, import/no-unresolved
  gremlin = require('gremlin');
} catch (e) {
  gremlin = null;
}
 
let dseDriver;
try {
  // eslint-disable-next-line import/no-extraneous-dependencies, import/no-unresolved
  dseDriver = require('dse-driver');
} catch (e) {
  dseDriver = null;
}
 
const cql = Promise.promisifyAll(dseDriver || require('cassandra-driver'));
 
const BaseModel = require('./base_model');
const schemer = require('../validators/schema');
const normalizer = require('../utils/normalizer');
const buildError = require('./apollo_error.js');
 
const KeyspaceBuilder = require('../builders/keyspace');
const UdtBuilder = require('../builders/udt');
const UdfBuilder = require('../builders/udf');
const UdaBuilder = require('../builders/uda');
const ElassandraBuilder = require('../builders/elassandra');
const JanusGraphBuilder = require('../builders/janusgraph');
 
const DEFAULT_REPLICATION_FACTOR = 1;
 
const noop = () => {};
 
const Apollo = function f(connection, options) {
  Iif (!connection) {
    throw (buildError('model.validator.invalidconfig', 'Cassandra connection configuration undefined'));
  }
 
  options = options || {};
 
  Iif (!options.defaultReplicationStrategy) {
    options.defaultReplicationStrategy = {
      class: 'SimpleStrategy',
      replication_factor: DEFAULT_REPLICATION_FACTOR,
    };
  }
 
  this._options = options;
  this._models = {};
  this._keyspace = connection.keyspace;
  this._connection = connection;
  this._client = null;
  this._esclient = null;
  this._gremlin_client = null;
};
 
Apollo.prototype = {
 
  _generate_model(properties) {
    const Model = function f(...args) {
      BaseModel.apply(this, Array.prototype.slice.call(args));
    };
 
    util.inherits(Model, BaseModel);
 
    Object.keys(BaseModel).forEach((key) => {
      Model[key] = BaseModel[key];
    });
 
    Model._set_properties(properties);
 
    return Model;
  },
 
  create_es_client() {
    Iif (!elasticsearch) {
      throw (new Error('Configured to use elassandra, but elasticsearch module was not found, try npm install elasticsearch'));
    }
 
    const contactPoints = this._connection.contactPoints;
    const defaultHosts = [];
    contactPoints.forEach((host) => {
      defaultHosts.push({ host });
    });
 
    const esClientConfig = _.defaults({}, this._connection.elasticsearch, {
      hosts: defaultHosts,
      sniffOnStart: true,
    });
    this._esclient = new elasticsearch.Client(esClientConfig);
    return this._esclient;
  },
 
  _assert_es_index(callback) {
    const esClient = this.create_es_client();
    const indexName = this._keyspace;
 
    const elassandraBuilder = new ElassandraBuilder(esClient);
    elassandraBuilder.assert_index(indexName, indexName, callback);
  },
 
  create_gremlin_client() {
    Iif (!gremlin) {
      throw (new Error('Configured to use janus graph server, but gremlin module was not found, try npm install gremlin'));
    }
 
    const defaultHosts = this._connection.contactPoints;
 
    const gremlinConfig = _.defaults({}, this._connection.gremlin, {
      host: defaultHosts[0],
      port: 8182,
      storage: {
        backend: 'cassandrathrift',
        hostname: defaultHosts[0],
        port: 9160,
      },
      index: {
        search: {
          backend: 'elasticsearch',
          hostname: defaultHosts[0],
          port: 9200,
        },
      },
      options: {},
    });
    this._gremlin_client = gremlin.createClient(gremlinConfig.port, gremlinConfig.host, gremlinConfig.options);
    this._gremlin_config = gremlinConfig;
    return this._gremlin_client;
  },
 
  _assert_gremlin_graph(callback) {
    const gremlinClient = this.create_gremlin_client();
    const gremlinConfig = this._gremlin_config;
    const keyspaceName = this._keyspace;
    const graphName = `${keyspaceName}_graph`;
 
    const graphBuilder = new JanusGraphBuilder(gremlinClient, gremlinConfig);
    graphBuilder.assert_graph(graphName, callback);
  },
 
  get_system_client() {
    const connection = _.cloneDeep(this._connection);
    delete connection.keyspace;
 
    return new cql.Client(connection);
  },
 
  get_keyspace_name() {
    return this._keyspace;
  },
 
  _assert_keyspace(callback) {
    const client = this.get_system_client();
    const keyspaceName = this._keyspace;
    const options = this._options;
 
    const keyspaceBuilder = new KeyspaceBuilder(client);
 
    keyspaceBuilder.get_keyspace(keyspaceName, (err, keyspaceObject) => {
      Iif (err) {
        callback(err);
        return;
      }
 
      Iif (!keyspaceObject) {
        keyspaceBuilder.create_keyspace(keyspaceName, options.defaultReplicationStrategy, callback);
        return;
      }
 
      const dbReplication = normalizer.normalize_replication_option(keyspaceObject.replication);
      const ormReplication = normalizer.normalize_replication_option(options.defaultReplicationStrategy);
 
      Iif (!_.isEqual(dbReplication, ormReplication)) {
        keyspaceBuilder.alter_keyspace(keyspaceName, options.defaultReplicationStrategy, callback);
        return;
      }
 
      client.shutdown(() => {
        callback();
      });
    });
  },
 
  _assert_user_defined_types(callback) {
    const client = this._define_connection;
    const options = this._options;
    const keyspace = this._keyspace;
 
    if (!options.udts) {
      callback();
      return;
    }
 
    const udtBuilder = new UdtBuilder(client);
 
    Promise.mapSeries(Object.keys(options.udts), (udtKey) => new Promise((resolve, reject) => {
      const udtCallback = (err) => {
        Iif (err) {
          reject(err);
          return;
        }
        resolve();
      };
      udtBuilder.get_udt(udtKey, keyspace, (err, udtObject) => {
        Iif (err) {
          udtCallback(err);
          return;
        }
 
        Iif (!udtObject) {
          udtBuilder.create_udt(udtKey, options.udts[udtKey], udtCallback);
          return;
        }
 
        const udtKeys = Object.keys(options.udts[udtKey]);
        const udtValues = _.map(_.values(options.udts[udtKey]), normalizer.normalize_user_defined_type);
        const fieldNames = udtObject.field_names;
        const fieldTypes = _.map(udtObject.field_types, normalizer.normalize_user_defined_type);
 
        Eif (_.difference(udtKeys, fieldNames).length === 0 && _.difference(udtValues, fieldTypes).length === 0) {
          udtCallback();
          return;
        }
 
        throw (new Error(util.format(
          'User defined type "%s" already exists but does not match the udt definition. ' +
          'Consider altering or droping the type.',
          udtKey,
        )));
      });
    }))
      .then(() => {
        callback();
      })
      .catch((err) => {
        callback(err);
      });
  },
 
  _assert_user_defined_functions(callback) {
    const client = this._define_connection;
    const options = this._options;
    const keyspace = this._keyspace;
 
    if (!options.udfs) {
      callback();
      return;
    }
 
    const udfBuilder = new UdfBuilder(client);
 
    Promise.mapSeries(Object.keys(options.udfs), (udfKey) => new Promise((resolve, reject) => {
      const udfCallback = (err) => {
        Iif (err) {
          reject(err);
          return;
        }
        resolve();
      };
 
      udfBuilder.validate_definition(udfKey, options.udfs[udfKey]);
 
      udfBuilder.get_udf(udfKey, keyspace, (err, udfObject) => {
        Iif (err) {
          udfCallback(err);
          return;
        }
 
        Iif (!udfObject) {
          udfBuilder.create_udf(udfKey, options.udfs[udfKey], udfCallback);
          return;
        }
 
        const udfLanguage = options.udfs[udfKey].language;
        const resultLanguage = udfObject.language;
 
        const udfCode = options.udfs[udfKey].code;
        const resultCode = udfObject.body;
 
        const udfReturnType = normalizer.normalize_user_defined_type(options.udfs[udfKey].returnType);
        const resultReturnType = normalizer.normalize_user_defined_type(udfObject.return_type);
 
        const udfInputs = options.udfs[udfKey].inputs ? options.udfs[udfKey].inputs : {};
        const udfInputKeys = Object.keys(udfInputs);
        const udfInputValues = _.map(_.values(udfInputs), normalizer.normalize_user_defined_type);
        const resultArgumentNames = udfObject.argument_names;
        const resultArgumentTypes = _.map(udfObject.argument_types, normalizer.normalize_user_defined_type);
 
        Eif (udfLanguage === resultLanguage &&
          udfCode === resultCode &&
          udfReturnType === resultReturnType &&
          _.isEqual(udfInputKeys, resultArgumentNames) &&
          _.isEqual(udfInputValues, resultArgumentTypes)) {
          udfCallback();
          return;
        }
 
        udfBuilder.create_udf(udfKey, options.udfs[udfKey], udfCallback);
      });
    }))
      .then(() => {
        callback();
      })
      .catch((err) => {
        callback(err);
      });
  },
 
  _assert_user_defined_aggregates(callback) {
    const client = this._define_connection;
    const options = this._options;
    const keyspace = this._keyspace;
 
    if (!options.udas) {
      callback();
      return;
    }
 
    const udaBuilder = new UdaBuilder(client);
 
    Promise.mapSeries(Object.keys(options.udas), (udaKey) => new Promise((resolve, reject) => {
      const udaCallback = (err) => {
        Iif (err) {
          reject(err);
          return;
        }
        resolve();
      };
 
      udaBuilder.validate_definition(udaKey, options.udas[udaKey]);
 
      if (!options.udas[udaKey].initcond) {
        options.udas[udaKey].initcond = null;
      }
 
      udaBuilder.get_uda(udaKey, keyspace, (err, udaObjects) => {
        Iif (err) {
          udaCallback(err);
          return;
        }
 
        Iif (!udaObjects) {
          udaBuilder.create_uda(udaKey, options.udas[udaKey], udaCallback);
          return;
        }
 
        const inputTypes = _.map(options.udas[udaKey].input_types, normalizer.normalize_user_defined_type);
        const sfunc = options.udas[udaKey].sfunc.toLowerCase();
        const stype = normalizer.normalize_user_defined_type(options.udas[udaKey].stype);
        const finalfunc = options.udas[udaKey].finalfunc ? options.udas[udaKey].finalfunc.toLowerCase() : null;
        const initcond = options.udas[udaKey].initcond ? options.udas[udaKey].initcond.replace(/[\s]/g, '') : null;
 
        for (let i = 0; i < udaObjects.length; i++) {
          const resultArgumentTypes = _.map(udaObjects[i].argument_types, normalizer.normalize_user_defined_type);
 
          const resultStateFunc = udaObjects[i].state_func;
          const resultStateType = normalizer.normalize_user_defined_type(udaObjects[i].state_type);
          const resultFinalFunc = udaObjects[i].final_func;
          const resultInitcond = udaObjects[i].initcond ? udaObjects[i].initcond.replace(/[\s]/g, '') : null;
 
          Eif (sfunc === resultStateFunc &&
            stype === resultStateType &&
            finalfunc === resultFinalFunc &&
            initcond === resultInitcond &&
            _.isEqual(inputTypes, resultArgumentTypes)) {
            udaCallback();
            return;
          }
        }
        udaBuilder.create_uda(udaKey, options.udas[udaKey], udaCallback);
      });
    }))
      .then(() => {
        callback();
      })
      .catch((err) => {
        callback(err);
      });
  },
 
  _set_client(client) {
    const defineConnectionOptions = _.cloneDeep(this._connection);
 
    this._client = client;
    this._define_connection = new cql.Client(defineConnectionOptions);
 
    // Reset connections on all models
    Object.keys(this._models).forEach((i) => {
      this._models[i]._properties.cql = this._client;
      this._models[i]._properties.define_connection = this._define_connection;
    });
  },
 
  init(callback) {
    const onUserDefinedAggregates = (err) => {
      Iif (err) {
        callback(err);
        return;
      }
 
      const managementTasks = [];
      if (this._keyspace && this._options.manageESIndex) {
        this.assertESIndexAsync = Promise.promisify(this._assert_es_index);
        managementTasks.push(this.assertESIndexAsync());
      }
      if (this._keyspace && this._options.manageGraphs) {
        this.assertGremlinGraphAsync = Promise.promisify(this._assert_gremlin_graph);
        managementTasks.push(this.assertGremlinGraphAsync());
      }
      Promise.all(managementTasks)
        .then(() => {
          callback(null, this);
        })
        .catch((err1) => {
          callback(err1);
        });
    };
 
    const onUserDefinedFunctions = function f(err) {
      Iif (err) {
        callback(err);
        return;
      }
      try {
        this._assert_user_defined_aggregates(onUserDefinedAggregates.bind(this));
      } catch (e) {
        throw (buildError('model.validator.invaliduda', e.message));
      }
    };
 
    const onUserDefinedTypes = function f(err) {
      Iif (err) {
        callback(err);
        return;
      }
      try {
        this._assert_user_defined_functions(onUserDefinedFunctions.bind(this));
      } catch (e) {
        throw (buildError('model.validator.invalidudf', e.message));
      }
    };
 
    const onKeyspace = function f(err) {
      Iif (err) {
        callback(err);
        return;
      }
      this._set_client(new cql.Client(this._connection));
      try {
        this._assert_user_defined_types(onUserDefinedTypes.bind(this));
      } catch (e) {
        throw (buildError('model.validator.invalidudt', e.message));
      }
    };
 
    if (this._keyspace && this._options.createKeyspace !== false) {
      this._assert_keyspace(onKeyspace.bind(this));
    } else {
      onKeyspace.call(this);
    }
  },
 
  addModel(modelName, modelSchema) {
    Iif (!modelName || typeof (modelName) !== 'string') {
      throw (buildError('model.validator.invalidschema', 'Model name must be a valid string'));
    }
 
    try {
      schemer.validate_model_schema(modelSchema);
    } catch (e) {
      throw (buildError('model.validator.invalidschema', e.message));
    }
 
    if (modelSchema.options && modelSchema.options.timestamps) {
      const timestampOptions = {
        createdAt: modelSchema.options.timestamps.createdAt || 'createdAt',
        updatedAt: modelSchema.options.timestamps.updatedAt || 'updatedAt',
      };
      modelSchema.options.timestamps = timestampOptions;
 
      modelSchema.fields[modelSchema.options.timestamps.createdAt] = {
        type: 'timestamp',
        default: {
          $db_function: 'toTimestamp(now())',
        },
      };
      modelSchema.fields[modelSchema.options.timestamps.updatedAt] = {
        type: 'timestamp',
        default: {
          $db_function: 'toTimestamp(now())',
        },
      };
    }
 
    if (modelSchema.options && modelSchema.options.versions) {
      const versionOptions = {
        key: modelSchema.options.versions.key || '__v',
      };
      modelSchema.options.versions = versionOptions;
 
      modelSchema.fields[modelSchema.options.versions.key] = {
        type: 'timeuuid',
        default: {
          $db_function: 'now()',
        },
      };
    }
 
    const baseProperties = {
      name: modelName,
      schema: modelSchema,
      keyspace: this._keyspace,
      define_connection: this._define_connection,
      cql: this._client,
      esclient: this._esclient,
      gremlin_client: this._gremlin_client,
      get_constructor: this.getModel.bind(this, modelName),
      init: this.init.bind(this),
      dropTableOnSchemaChange: this._options.dropTableOnSchemaChange,
      createTable: this._options.createTable,
      migration: this._options.migration,
      disableTTYConfirmation: this._options.disableTTYConfirmation,
    };
 
    this._models[modelName] = this._generate_model(baseProperties);
    return this._models[modelName];
  },
 
  getModel(modelName) {
    return this._models[modelName] || null;
  },
 
  close(callback) {
    callback = callback || noop;
 
    if (this.orm._esclient) {
      this.orm._esclient.close();
    }
 
    if (this.orm._gremlin_client && this.orm._gremlin_client.connection && this.orm._gremlin_client.connection.ws) {
      this.orm._gremlin_client.connection.ws.close();
    }
 
    const clientsToShutdown = [];
    Eif (this.orm._client) {
      clientsToShutdown.push(this.orm._client.shutdown());
    }
    Eif (this.orm._define_connection) {
      clientsToShutdown.push(this.orm._define_connection.shutdown());
    }
 
    Promise.all(clientsToShutdown)
      .then(() => {
        callback();
      })
      .catch((err) => {
        callback(err);
      });
  },
};
 
module.exports = Apollo;