Source: libdynamodb.js

/*
* (c) Copyright, Real-Time Innovations, 2012.  All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/

var AWS = require("aws-sdk")
const fs = require('fs')
const CSV = require('csv-string')
const RTITypeUtilsTypeProvider = require('@connextdev/rticonnextdds-typeutils')
const typeprovider = new RTITypeUtilsTypeProvider()

/**
 * @class TypeRepoDbApi
 * @classdesc Implements the DynamoDB API for the type repository.
 * It contains methods for adding, getting, deleting, and querying types from the database.
 * It also contains methods for getting domains, groups, modules, and purposes from the database.
 */
class TypeRepoDbApi {
 
  /**
   * Represents a LibDynamoDB object.
   * It loads the credentials from the creds.json file and specifies the table name.
   * It also specifies the DynamoDB API version.
   * @constructor
   */
   constructor (settings) {

    settings = settings || {}

     //Specify table name
     this.mainTable = settings.mainTable? settings.mainTable : 'typeservice'
     this.domainsTable = settings.domainsTable? settings.domainsTable : 'TypeRepoDomains'
     this.groupsTable = settings.groupsTable? settings.groupsTable : 'TypeRepoGroups'
     this.modulesTable = settings.modulesTable? settings.modulesTable : 'TypeRepoModules' 
     this.credentialsFile = settings.credentialsFile? settings.credentialsFile : './creds.json'
 
    AWS.config.loadFromPath(this.credentialsFile) 
    //Specify aws dynamodb api
    this.docClient = new AWS.DynamoDB({apiVersion: '2012-08-10'})
    
   
  }
  
  

  /**
   * Retrieves the description of the table.
   * @returns {Promise<Object>} A promise that resolves to the table description.
   * The result will either contain the table description or an error.
   */
  describeTable () {
    var params = {
      TableName : this.mainTable
    }
    return this.docClient.describeTable(params).promise()
  }
  
  

  /**
   * Retrieves a type from the database based on the given type ID.
   * @param {string} type_id - The ID of the type to retrieve.
   * @returns {Promise<Object>} A promise that resolves to the retrieved type object.
   * The result will either contain the type object or an error.
   */
  getTypeFromDB (type_id) {
    //Define get params
    var params = {
      TableName : this.mainTable,
      Key : { 
        "typeid" : { "N" : type_id }
      }
    }
    //Return get transaction as a promise
    return this.docClient.getItem(params).promise()
  }
  
  

  /**
   * Deletes a type from the database.
   * 
   * @param {string} type_id - The ID of the type to be deleted.
   * @returns {Promise} A promise that resolves when the type is successfully deleted.
   */
  async deleteTypeFromDB (type_id) {
    /* Check if typeid exists */
    var domain_res = await this.getTypeFromDB(type_id).then(function (data) {
      if (data.Item) {
        return data.Item.domains
      }
    })
    await this.decrementDomains(domain_res.S)
    
    //Define delete params
    var deleteParams = {
      TableName : this.mainTable,
      Key : { 
        "typeid" : { "N" : type_id }
      }
    }
    //Return deleteItem transaction as a promise
    return this.docClient.deleteItem(deleteParams).promise()
  }

  /**
   * Queries types from the database based on the specified criteria.
   * 
   * @param {string} domain - The domain to filter the types by.
   * @param {string} group - The group to filter the types by.
   * @param {string} modules - The modules to filter the types by.
   * @param {string} topic - The topic to filter the types by.
   * @param {string} type_name - The type name to filter the types by.
   * @param {number} contains - The flag indicating whether to perform exact match (0) or partial match (1) for filtering.
   * @param {number} start - The index of the first item to return.
   * @param {number} stop - The index of the last item to return.
   * @returns {Promise<Array<Object>>} - A promise that resolves to an array of type objects matching the specified criteria.
   * The result will either contain the array of type objects or an error.
   */
  async queryTypesFromDB (domain, group, modules, topic, type_name, contains, start, stop) {
    var params
    var filterExpression = ""
    var expressionAttributeValues = {}
    if (domain) {
      if (contains == 0) {
        filterExpression += "domains = :dddd"
      } else {
        filterExpression += "contains(domains, :dddd)"
      }
      expressionAttributeValues[":dddd"] = { "S" : domain } 
    }
    if (group) {
      if (domain) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "groups = :gggg"
      } else {
        filterExpression += "contains(groups, :gggg)"
      }
      expressionAttributeValues[":gggg"] = { "S" : group } 
    } 
    if (modules) {
      if (domain || group) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "modules = :mmmm"
      } else {
        filterExpression += "contains(modules, :mmmm)"
      }
      expressionAttributeValues[":mmmm"] = { "S" : modules } 
    }  
    if (topic) {
      if (domain || group || modules) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "topic = :oooo"
      } else {
        filterExpression += "contains(topic, :oooo)"
      }
      expressionAttributeValues[":oooo"] = { "S" : topic } 
    } 
    if (type_name) {
      if (domain || group || modules || topic) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "typename = :nnnn"
      } else {
        filterExpression += "contains(typename, :nnnn)"
      }
      expressionAttributeValues[":nnnn"] = { "S" : type_name }
    } 
    
    var projectionExpression = "typename, topic, domains, groups, modules, typeid, description, documentation, purpose, version, parent_type_id, ser_type_object_size, ser_type_code_size, ser_sample_min_size, ser_sample_max_size, contact"
    
    if (domain || group || modules || topic || type_name) {
      params = {
        TableName : this.mainTable,
        FilterExpression : filterExpression,
        ExpressionAttributeValues : expressionAttributeValues,
        ProjectionExpression : projectionExpression
      }

      var all_items = [];

      //Return query transaction promise
      var items = await this.docClient.scan(params).promise();
      for (var i = 0; i < items.Count; i++) {
        all_items.push(items.Items[i]);
      }
      while (items.LastEvaluatedKey) {
        params.ExclusiveStartKey = {typeid: {"N": items.LastEvaluatedKey.typeid.N}};
        var items = await this.docClient.scan(params).promise();
        for (var i = 0; i < items.Count; i++) {
            all_items.push(items.Items[i]);
        }
      }
      return all_items.slice(start, stop);
    } else {
      params = {
        TableName : this.mainTable,
        ProjectionExpression : projectionExpression
      }

      var all_items = [];

      //Return query transaction promise
      var items = await this.docClient.scan(params).promise();
      for (var i = 0; i < items.Count; i++) {
        all_items.push(items.Items[i]);
      }
      while (items.LastEvaluatedKey) {
        params.ExclusiveStartKey = {typeid: {"N": items.LastEvaluatedKey.typeid.N}};
        var items = await this.docClient.scan(params).promise();
        for (var i = 0; i < items.Count; i++) {
            all_items.push(items.Items[i]);
        }
      }
      return all_items.slice(start, stop);
    }
  }
  
  /**
   * Queries types from the database with the last index.
   *
   * @param {string} domain - The domain value.
   * @param {string} group - The group value.
   * @param {string} modules - The modules value.
   * @param {string} topic - The topic value.
   * @param {string} type_name - The type name value.
   * @param {number} contains - The contains value.
   * @param {number} last_typeid - The last type ID value.
   * @param {number} [limit=1000] - The limit value (default is 1000).
   * @returns {Promise<Array>} - A promise that resolves to an array of items.
   * The result will either contain the array of items or an error.
   */
   async queryTypesFromDBWithLastIndex(domain, group, modules, topic, type_name, contains, last_typeid, limit = 1000) {
    var params
    var filterExpression = ""
    var expressionAttributeValues = {}
    var lastEvaluatedIndex = undefined;
    if (last_typeid == 0 || !last_typeid) {
      lastEvaluatedIndex = undefined;
    } else {
      lastEvaluatedIndex = last_typeid
    }
    if (domain) {
      if (contains == 0) {
        filterExpression += "domains = :dddd"
      } else {
        filterExpression += "contains(domains, :dddd)"
      }
      expressionAttributeValues[":dddd"] = { "S" : domain } 
    }
    if (group) {
      if (domain) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "groups = :gggg"
      } else {
        filterExpression += "contains(groups, :gggg)"
      }
      expressionAttributeValues[":gggg"] = { "S" : group } 
    } 
    if (modules) {
      if (domain || group) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "modules = :mmmm"
      } else {
        filterExpression += "contains(modules, :mmmm)"
      }
      expressionAttributeValues[":mmmm"] = { "S" : modules } 
    }  
    if (topic) {
      if (domain || group || modules) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "topic = :oooo"
      } else {
        filterExpression += "contains(topic, :oooo)"
      }
      expressionAttributeValues[":oooo"] = { "S" : topic } 
    } 
    if (type_name) {
      if (domain || group || modules || topic) {
        filterExpression += " and "
      }
      if (contains == 0) {
        filterExpression += "typename = :nnnn"
      } else {
        filterExpression += "contains(typename, :nnnn)"
      }
      expressionAttributeValues[":nnnn"] = { "S" : type_name }
    } 
    
    var projectionExpression = "typename, topic, domains, groups, modules, typeid, description, documentation, purpose, version, parent_type_id, ser_type_object_size, ser_type_code_size, ser_sample_min_size, ser_sample_max_size, contact"
    
    if (domain || group || modules || topic || type_name) {
      // Define query params
      params = {
        TableName : this.mainTable,
        FilterExpression : filterExpression,
        ExpressionAttributeValues : expressionAttributeValues,
        ProjectionExpression : projectionExpression,
        Limit : limit
      }
      
      // If last evaluated key is valid, use it
      if (lastEvaluatedIndex) {
        params.ExclusiveStartKey = {typeid: {"N" : lastEvaluatedIndex}}
      }

      var all_items = [];
      
      // Perform initial query and store results.
      var items = await this.docClient.scan(params).promise();
      for (var i = 0; i < items.Count && all_items.length < limit; i++) {
        all_items.push(items.Items[i]);
      }
      
      // While there is more data in the DB, AND we have not reachedour limit
      while (items.LastEvaluatedKey && all_items.length < limit) {
        // Set exclusive start key to last evaluated key
        params.ExclusiveStartKey = {typeid: {"N": items.LastEvaluatedKey.typeid.N}};
        
        // Perform query and store results.
        var items = await this.docClient.scan(params).promise();
        for (var i = 0; i < items.Count && all_items.length < limit; i++) {
            all_items.push(items.Items[i]);
        }
      }
      
      /*var ctr = 0
      for (var i = 0; i < all_items.length; i++) {
        if (all_items[i]) {
          ctr += 1
        }
      }*/
      return all_items
    } else {
      // Define query params
      params = {
        TableName : this.mainTable,
        ProjectionExpression : projectionExpression,
        Limit : limit
      }
      
      // If last evaluated key is valid, use it
      if (lastEvaluatedIndex) {
        params.ExclusiveStartKey = {typeid: {"N" : lastEvaluatedIndex}}
      }

      var all_items = [];
      
      // Perform initial query and store results.
      var items = await this.docClient.scan(params).promise();
      for (var i = 0; i < items.Count && all_items.length < limit; i++) {
        all_items.push(items.Items[i]);
      }
      
      // While there is more data in the DB, AND we have not reachedour limit
      while (items.LastEvaluatedKey && all_items.length < limit) {
        // Set exclusive start key to last evaluated key
        params.ExclusiveStartKey = {typeid: {"N": items.LastEvaluatedKey.typeid.N}};
        
        // Perform query and store results.
        var items = await this.docClient.scan(params).promise();
        for (var i = 0; i < items.Count && all_items.length < limit; i++) {
            all_items.push(items.Items[i]);
        }
      }
      
      /*var ctr = 0
      for (var i = 0; i < all_items.length; i++) {
        if (all_items[i]) {
          ctr += 1
        }
      }*/
      return all_items
    }
  }

  /**
   * Retrieves the domains from the database.
   * @returns {Promise<Array>} A promise that resolves to an array of domain items.
   * The result will either contain the array of domain items or an error.
   */
  getDomainsFromDB() {
    var params = {
      TableName : this.domainsTable
    }
    const awsRequest = this.docClient.scan(params).promise()
    return awsRequest.then(function (data) {
      return data.Items
    })
  }

  

  /**
   * Increments the counters for a given domain in the TypeRepoDomains table.
   * 
   * @param {string} domain - The domain to increment the counters for.
   * @returns {Promise} A promise that resolves when the counters are incremented.
   *  The result will either contain the counters or an error.
   */
  async incrementDomains(domain) {
    var params = {
      TableName : this.domainsTable,
      ExpressionAttributeValues : {":dddd" : {"S": domain.toString()}},
      ProjectionExpression : "domains, counters",
      FilterExpression : "domains = :dddd"
    }
    var self = this;
    var res = await this.docClient.scan(params).promise().then(function (data) {
      var params2 = {}
      if (data.Items) {
        params2 = {
          TableName : self.domainsTable,
          Item : {
            "domains": {"S": domain},
            "counters": {"N":(parseInt(data.Items[0]["counters"].N) + 1).toString()}
          }
        }
      } else {
        params2 = {
          TableName : this.domainsTable,
          Item : {
            "domains": {"S": domain},
            "counters": {"N":"1"}
          }
        }
      }
      return params2
    })
      this.docClient.putItem(res).promise().then(function (data) {
        console.log("Domains incremented")
      })
  }
  

  /**
   * Increments the counters for a given group in the TypeRepoGroups table.
   * 
   * @param {string} group - The group to increment the counters for.
   * @returns {Promise} A promise that resolves when the counters are incremented.
   * The result will either contain the counters or an error.
   */
  async incrementGroups(group) {
    var params = {
      TableName : this.groupsTable,
      ExpressionAttributeValues : {":dddd" : {"S": group.toString()}},
      ProjectionExpression : "groups, counters",
      FilterExpression : "groups = :dddd"
    }
    var self = this
    var res = await this.docClient.scan(params).promise().then(function (data) {
      var params2 = {}
      if (data.Items) {
        params2 = {
          TableName : self.groupsTable,
          Item : {
            "groups": {"S": group},
            "counters": {"N":(parseInt(data.Items[0]["counters"].N) + 1).toString()}
          }
        }
      } else {
        params2 = {
          TableName : this.groupsTable,
          Item : {
            "groups": {"S": group},
            "counters": {"N":"1"}
          }
        }
      }
      return params2
    })
      this.docClient.putItem(res).promise().then(function (data) {
        console.log("Domains incremented")
      })
  }
  

  /**
   * Decrements the counters of a domain in the TypeRepoDomains table.
   * 
   * @param {string} domain - The domain to decrement.
   * @returns {Promise<void>} - A promise that resolves when the counters are decremented successfully.
   */
  async decrementDomains(domain) {
    var params = {
      TableName : this.domainsTable,
      ExpressionAttributeValues : {":dddd" : {"S": domain.toString()}},
      ProjectionExpression : "domains, counters",
      FilterExpression : "domains = :dddd"
    }
    var self = this
    var res = await this.docClient.scan(params).promise().then(function (data) {
      var params2 = {
        TableName : self.domainsTable,
        Item : {
          "domains": {"S": domain},
          "counters": {"N":(parseInt(data.Items[0]["counters"].N) - 1).toString()}
        }
      }
      return params2
    })
    await this.docClient.putItem(res).promise().then(function (data) {
      console.log("Domains decremented")
    })
  }
  
  

  /**
   * Retrieves groups from the DynamoDB table.
   * @returns {Promise<Array>} A promise that resolves to an array of group items.
   */
  getGroupsFromDB() {
    var params = {
      TableName : this.groupsTable
    }
    const awsRequest = this.docClient.scan(params).promise()
    return awsRequest.then(function (data) {
      return data.Items
    })
  }

  /**
   * Retrieves modules from the DynamoDB table.
   * @returns {Promise<Array>} A promise that resolves to an array of module items.
   */
  getModulesFromDB() {
    var params = {
      TableName : this.modulesTable
    }
    const awsRequest = this.docClient.scan(params).promise()
    return awsRequest.then(function (data) {
      return data.Items
    })
  }

  /**
   * Retrieves purposes from the database.
   * @returns {Promise<Object>} A promise that resolves to an object containing the purposes and their counts.
   */
  getPurposesFromDB() {
    var params = {
      TableName : this.mainTable
    }
    const awsRequest = this.docClient.scan(params).promise()
    return awsRequest.then(function (data) {
      var seen = {}
      for (var i = 0; i < data.Items.length; i++) {
          if (seen[data.Items[i].purpose.S] === undefined) {
              seen[data.Items[i].purpose.S] = 1
          } else {
              seen[data.Items[i].purpose.S]++
          }
      }
      return seen
    })
  }

  /**
   * tries to get information about the type to be used in the database.
   * not all the information are available for all types. 
   * For example for a typedef the samplesize is not available. 
   */
  createRecordFromType(xmlUrl, type_name) {
    var record = {}
    try {
      typeprovider.loadXmlFromUrl(xmlUrl)
    } catch (e) {
      throw new Error("Failed to load xmlUrl")
    }
    try {
      record.type_id = typeprovider.getTypeId(type_name)
    } catch (e) {
      console.log("No type id found")
    }
    try {
      record.ser_sample_min_size = typeprovider.getSerializedSampleMinSize(type_name, 0/*DDS_XCDR_DATA_REPRESENTATION*/)
    } catch (e) {
      console.log("No sample min size found")
    }
    try { 
      record.ser_sample_max_size = typeprovider.getSerializedSampleMaxSize(type_name, 0/*DDS_XCDR_DATA_REPRESENTATION*/)
    } catch (e) {
      console.log("No sample max size found")
    }
    try {
      record.ser_type_obj_size = typeprovider.getSerializedTypeObjectSize(type_name)
    } catch (e) {
      console.log("No type object size found")
    }
    try {
      record.ser_type_obj = typeprovider.getSerializedTypeObject(type_name)
    } catch (e) {
      console.log("No type object found")
    }
    return record
    
  }
  
  /**
   * Adds a type to the database.
   *
   * @param {string} path - The path of the type.
   * @param {string} type - The type to be added.
   * @param {string} [description=""] - The description of the type.
   * @param {string} [documentation=""] - The documentation of the type.
   * @param {string} [purpose=""] - The purpose of the type.
   * @param {string} [version=""] - The version of the type.
   * @param {number} [parent_type_id=-1] - The ID of the parent type.
   * @param {string} [topic=""] - The topic of the type.
   * @param {string} [domain=""] - The domain of the type.
   * @param {string} [group=""] - The group of the type.
   * @param {string} [contact=""] - The contact information for the type.
   * @returns {Promise} A promise that resolves when the type is added to the database.
   */
  async addTypeToDB (path, type, description="", documentation="", purpose="", version="", parent_type_id=-1, topic="", domain="", group="", contact="") {
    /* Create record to add */
    var record = this.createRecordFromType(path, type)
    if (type.includes("::")) {
      var ind = type.lastIndexOf("::")
      record.modules = type.substring(0, ind)
      record.type_name = type.substring(ind+2, type.length)
    } else {
      record.modules = ""
      record.type_name = type
    }
    record.description = description
    record.documentation = documentation
    record.purpose = purpose
    record.version = version
    record.parent_type_id = parent_type_id
    record.topic = topic
    record.domains = domain
    record.groups = group
    record.contact = contact
    
    /* Check if typeid exists */
    await this.getTypeFromDB(record.type_id).then(result => {
      /* If typeid doesn't exists, increment the domain in domain table */
      if (Object.keys(result).length === 0) {
          this.incrementDomains(record.domains)
          this.incrementGroups(record.groups)
          //this.incrementModules(record.modules)
      }
    }).catch( e => {
      console.log("ERROR: Couln't get type from db")
    });
    
    
    var params = {
      TableName : this.mainTable,
      Item : {
        "typeid" : { "N" : record.type_id },
        "modules" : { "S" : record.modules },
        "typename" : { "S" : record.type_name },
        "typeobject" : { "B" : record.ser_type_obj },
        "ser_sample_min_size" : { "N" : record.ser_sample_min_size.toString() },
        "ser_sample_max_size" : { "N" : record.ser_sample_max_size.toString() },
        "ser_type_object_size" : { "N" : record.ser_sample_min_size.toString() },
        "description" : { "S" : record.description },
        "documentation" : { "S" : record.documentation }, 
        "purpose" : { "S" : record.purpose },
        "version" : { "S" : record.version }, 
        "parent_type_id" : { "N" : record.parent_type_id.toString()}, 
        "topic" : { "S" : record.topic },
        "domains" : { "S" : record.domains },
        "groups" : { "S" : record.groups }
      }
    }
    return this.docClient.putItem(params).promise()
  }
}

module.exports.TypeRepoDbApi = TypeRepoDbApi