<commit_before>/**
 * @fileOverview The tokens model.
 */
var __ = require('lodash');
var Promise = require('bluebird');
var middlewarify = require('middlewarify');


var logger = require('../main/logger.main');
var EventBus = require('../main/event-bus.main');
var Model = require('./model-redis');
var period = require('./period-bucket.model');
var helpers = require('../util/helpers');
var kansasError = require('../util/error');

/**
 * The token model.
 *
 * @param {redis.RedisClient} client The redis client to use.
 * @param {Object} opts A dict with the following options:
 *   @param {string=} prefix Prefix to use for all keys.
 * @constructor
 * @extends {kansas.model.Redis}
 */
var Token = module.exports = Model.extend(function() {
  this.log = logger.getLogger('kansas.model.Token');

  // wire set/del/get
  middlewarify.make(this, 'set', this.create.bind(this), {beforeAfter: true});
  middlewarify.make(this, 'del', this.remove.bind(this), {beforeAfter: true});
  middlewarify.make(this, 'get', this.getActual.bind(this), {beforeAfter: true});
  middlewarify.make(this, 'getByOwnerId', this.getByOwnerIdActual.bind(this),
    {beforeAfter: true});

  // enforce policy token limits
  this.set.before(this.validateOwnerId.bind(this));
  this.set.before(this.validatePolicy.bind(this));
  this.set.before(this.enforcePolicyLimits.bind(this));

  this.namespace = 'token';
  this.idProp = 'token';

  this.scard = Promise.promisify(this.client.scard, this.client);
  this.smembers = Promise.promisify(this.client.smembers, this.client);
  this.getRedis = Promise.promisify(this.client.get, this.client);

  /** @type {?kansas.model.Policy} An instance of Policy model */
  this.policy = null;
});

/**
 * DI the policy instance to use.
 *
 * @param {kansas.model.Policy} policy The Policy model instance.
 */
Token.prototype.setPolicy = function(policy) {
  this.policy = policy;
};

/**
 * Will check if policy is valid.
 *
 * @param {Object} userValues The item to save, expects:
 *   @param {string} policyName The policy name.
 *   @param {string} ownerId Arbitrary string that identifies the owner.
 * @return {Promise} A promise.
 */
Token.prototype.validatePolicy = Promise.method(function(userValues) {
  if (!this.policy.has(userValues.policyName)) {
    var err = new kansasError.Policy('Policy with name "' +
      userValues.policyName + '" not found!');
    err.type = kansasError.Policy.Type.NOT_FOUND;

    this.log.info('validatePolicy() :: Policy not found:', userValues.policyName,
      'for ownerId:', userValues.ownerId, this.policy.store.toObject());
    throw err;
  }
});

/**
 * Will check if policy is valid.
 *
 * @param {Object} userValues The item to save, expects:
 *   @param {string} policyName The policy name.
 *   @param {string} ownerId Arbitrary string that identifies the owner.
 * @throws {kansas.error.Validation} If wont pass validation.
 */
Token.prototype.validateOwnerId = function(userValues) {
  if (typeof userValues.ownerId !== 'string' || !userValues.ownerId.length)  {
    var err = new kansasError.Validation('No proper "ownerId" was found.');
    throw err;
  }
};
/**
 * Will enforce the policy token limits.
 *
 * @param {Object} userValues The item to save, expects:
 *   @param {string} policyName The policy name.
 *   @param {string} ownerId Arbitrary string that identifies the owner.
 * @return {Promise} A promise.
 */
Token.prototype.enforcePolicyLimits = Promise.method(function(userValues) {
  var indexKey = this.prefix + 'index:' + this.namespace + ':' +
    userValues.ownerId;
  var self = this;
  return this.scard(indexKey).then(function(total) {
    var policy = self.policy.get(userValues.policyName);

    self.log.finer('enforcePolicyLimits() :: OwnerId:', userValues.ownerId,
      'policyName:', userValues.policyName, 'Total tokens:', total,
      'Max Tokens:', policy.maxTokens);
<commit_msg>tweak wrong ownerid type error<commit_after>/**
 * @fileOverview The tokens model.
 */
var __ = require('lodash');
var Promise = require('bluebird');
var middlewarify = require('middlewarify');


var logger = require('../main/logger.main');
var EventBus = require('../main/event-bus.main');
var Model = require('./model-redis');
var period = require('./period-bucket.model');
var helpers = require('../util/helpers');
var kansasError = require('../util/error');

/**
 * The token model.
 *
 * @param {redis.RedisClient} client The redis client to use.
 * @param {Object} opts A dict with the following options:
 *   @param {string=} prefix Prefix to use for all keys.
 * @constructor
 * @extends {kansas.model.Redis}
 */
var Token = module.exports = Model.extend(function() {
  this.log = logger.getLogger('kansas.model.Token');

  // wire set/del/get
  middlewarify.make(this, 'set', this.create.bind(this), {beforeAfter: true});
  middlewarify.make(this, 'del', this.remove.bind(this), {beforeAfter: true});
  middlewarify.make(this, 'get', this.getActual.bind(this), {beforeAfter: true});
  middlewarify.make(this, 'getByOwnerId', this.getByOwnerIdActual.bind(this),
    {beforeAfter: true});

  // enforce policy token limits
  this.set.before(this.validateOwnerId.bind(this));
  this.set.before(this.validatePolicy.bind(this));
  this.set.before(this.enforcePolicyLimits.bind(this));

  this.namespace = 'token';
  this.idProp = 'token';

  this.scard = Promise.promisify(this.client.scard, this.client);
  this.smembers = Promise.promisify(this.client.smembers, this.client);
  this.getRedis = Promise.promisify(this.client.get, this.client);

  /** @type {?kansas.model.Policy} An instance of Policy model */
  this.policy = null;
});

/**
 * DI the policy instance to use.
 *
 * @param {kansas.model.Policy} policy The Policy model instance.
 */
Token.prototype.setPolicy = function(policy) {
  this.policy = policy;
};

/**
 * Will check if policy is valid.
 *
 * @param {Object} userValues The item to save, expects:
 *   @param {string} policyName The policy name.
 *   @param {string} ownerId Arbitrary string that identifies the owner.
 * @return {Promise} A promise.
 */
Token.prototype.validatePolicy = Promise.method(function(userValues) {
  if (!this.policy.has(userValues.policyName)) {
    var err = new kansasError.Policy('Policy with name "' +
      userValues.policyName + '" not found!');
    err.type = kansasError.Policy.Type.NOT_FOUND;

    this.log.info('validatePolicy() :: Policy not found:', userValues.policyName,
      'for ownerId:', userValues.ownerId, this.policy.store.toObject());
    throw err;
  }
});

/**
 * Will check if policy is valid.
 *
 * @param {Object} userValues The item to save, expects:
 *   @param {string} policyName The policy name.
 *   @param {string} ownerId Arbitrary string that identifies the owner.
 * @throws {kansas.error.Validation} If wont pass validation.
 */
Token.prototype.validateOwnerId = function(userValues) {
  if (typeof userValues.ownerId !== 'string' || !userValues.ownerId.length)  {
    var err = new kansasError.Validation('Property "ownerId" not of right type.');
    err.value = userValues.ownerId;
    throw err;
  }
};
/**
 * Will enforce the policy token limits.
 *
 * @param {Object} userValues The item to save, expects:
 *   @param {string} policyName The policy name.
 *   @param {string} ownerId Arbitrary string that identifies the owner.
 * @return {Promise} A promise.
 */
Token.prototype.enforcePolicyLimits = Promise.method(function(userValues) {
  var indexKey = this.prefix + 'index:' + this.namespace + ':' +
    userValues.ownerId;
  var self = this;
  return this.scard(indexKey).then(function(total) {
    var policy = self.policy.get(userValues.policyName);

    self.log.finer('enforcePolicyLimits() :: OwnerId:', userValues.ownerId,
      'policyName:', userValues.policyName, 'Total tokens:', total,
      'Max Tokens:', policy.maxTokens);

{'fraction_non_alphanumeric': 0.14985958641817718, 'fraction_numerical': 0.0, 'mean_word_length': 4.157998683344306, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3483354', 'n_tokens_mistral': 2472, 'n_tokens_neox': 2441, 'n_words': 623}