<commit_before>'use strict'

const each = require('async/each')
const eachLimit = require('async/eachLimit')
const map = require('lodash/map')
const mongoose = require('mongoose')
const waterfall = require('async/waterfall')

const constants = require('../initializers/constants')
const logger = require('../helpers/logger')
const requests = require('../helpers/requests')

const Pod = mongoose.model('Pod')
const Video = mongoose.model('Video')

let timer = null
let lastRequestTimestamp = 0

// ---------------------------------------------------------------------------

const RequestSchema = mongoose.Schema({
  request: mongoose.Schema.Types.Mixed,
  to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Pod' } ]
})

RequestSchema.statics = {
  activate,
  deactivate,
  flush,
  forceSend,
  list,
  remainingMilliSeconds
}

RequestSchema.pre('save', function (next) {
  const self = this

  if (self.to.length === 0) {
    Pod.listAllIds(function (err, podIds) {
      if (err) return next(err)

      // No friends
      if (podIds.length === 0) return

      self.to = podIds
      return next()
    })
  } else {
    return next()
  }
})

mongoose.model('Request', RequestSchema)

// ------------------------------ STATICS ------------------------------

function activate () {
  logger.info('Requests scheduler activated.')
  lastRequestTimestamp = Date.now()

  const self = this
  timer = setInterval(function () {
    lastRequestTimestamp = Date.now()
    makeRequests.call(self)
  }, constants.REQUESTS_INTERVAL)
}

function deactivate () {
  logger.info('Requests scheduler deactivated.')
  clearInterval(timer)
  timer = null
}

function flush () {
  removeAll.call(this, function (err) {
    if (err) logger.error('Cannot flush the requests.', { error: err })
  })
}

function forceSend () {
  logger.info('Force requests scheduler sending.')
  makeRequests.call(this)
}

function list (callback) {
  this.find({ }, callback)
}

function remainingMilliSeconds () {
  if (timer === null) return -1

  return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
}

// ---------------------------------------------------------------------------

// Make a requests to friends of a certain type
function makeRequest (toPod, requestsToMake, callback) {
  if (!callback) callback = function () {}

  const params = {
    toPod: toPod,
    encrypt: true, // Security
    sign: true, // To prove our identity
    method: 'POST',
    path: '/api/' + constants.API_VERSION + '/remote/videos',
    data: requestsToMake // Requests we need to make
  }

  // Make multiple retry requests to all of pods
  // The function fire some useful callbacks
  requests.makeSecureRequest(params, function (err, res) {
    if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
      logger.error(
        'Error sending secure request to %s pod.',
        toPod.url,
        {
          error: err || new Error('Status code not 20x : ' + res.statusCode)
        }
      )

      return callback(false)
    }

    return callback(true)
  })
}

// Make all the requests of the scheduler
function makeRequests () {
  const self = this

  listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
    if (err) {
      logger.error('Cannot get the list of requests.', { err: err })
      return // Abort
    }

    // If there are no requests, abort
    if (requests.length === 0) {
      logger.info('No requests to make.')
      return
    }

    logger.info('Making requests to friends.')

    // Requests by pods id
    const requestsToMake = {}

    requests.forEach(function (poolRequest) {
      poolRequest.to.forEach(function (toPodId) {
        if (!requestsToMake[toPodId]) {
          requestsToMake[toPodId] = {
            ids: [],
            datas: []
          }
        }

        requestsToMake[toPodId].ids.push(poolRequest._id)
        requestsToMake[toPodId].datas.push(poolRequest.request)
      })
    })

    const goodPods = []
    const badPods = []

    eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
      const requestToMake = requestsToMake[toPodId]

      // FIXME: mongodb request inside a loop :/
      Pod.load(toPodId, function (err, toPod) {
        if (err) {
          logger.error('Error finding pod by id.', { err: err })
          return callbackEach()
        }

        // Maybe the pod is not our friend anymore so simply remove it
        if (!toPod) {
          removePodOf.call(self, requestToMake.ids, toPodId)
          return callbackEach()
        }

        makeRequest(toPod, requestToMake.datas, function (success) {
          if (success === true) {
            logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })

            // Remove the pod id of these request ids
            removePodOf.call(self, requestToMake.ids, toPodId)
            goodPods.push(toPodId)
          } else {
            badPods.push(toPodId)
          }

          callbackEach()
        })
      })
    }, function () {
      // All the requests were made, we update the pods score
      updatePodsScore(goodPods, badPods)
      // Flush requests with no pod
      removeWithEmptyTo.call(self)
    })
  })<commit_msg>Server: add informations when removing requests of unexisting pod<commit_after>'use strict'

const each = require('async/each')
const eachLimit = require('async/eachLimit')
const map = require('lodash/map')
const mongoose = require('mongoose')
const waterfall = require('async/waterfall')

const constants = require('../initializers/constants')
const logger = require('../helpers/logger')
const requests = require('../helpers/requests')

const Pod = mongoose.model('Pod')
const Video = mongoose.model('Video')

let timer = null
let lastRequestTimestamp = 0

// ---------------------------------------------------------------------------

const RequestSchema = mongoose.Schema({
  request: mongoose.Schema.Types.Mixed,
  to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Pod' } ]
})

RequestSchema.statics = {
  activate,
  deactivate,
  flush,
  forceSend,
  list,
  remainingMilliSeconds
}

RequestSchema.pre('save', function (next) {
  const self = this

  if (self.to.length === 0) {
    Pod.listAllIds(function (err, podIds) {
      if (err) return next(err)

      // No friends
      if (podIds.length === 0) return

      self.to = podIds
      return next()
    })
  } else {
    return next()
  }
})

mongoose.model('Request', RequestSchema)

// ------------------------------ STATICS ------------------------------

function activate () {
  logger.info('Requests scheduler activated.')
  lastRequestTimestamp = Date.now()

  const self = this
  timer = setInterval(function () {
    lastRequestTimestamp = Date.now()
    makeRequests.call(self)
  }, constants.REQUESTS_INTERVAL)
}

function deactivate () {
  logger.info('Requests scheduler deactivated.')
  clearInterval(timer)
  timer = null
}

function flush () {
  removeAll.call(this, function (err) {
    if (err) logger.error('Cannot flush the requests.', { error: err })
  })
}

function forceSend () {
  logger.info('Force requests scheduler sending.')
  makeRequests.call(this)
}

function list (callback) {
  this.find({ }, callback)
}

function remainingMilliSeconds () {
  if (timer === null) return -1

  return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
}

// ---------------------------------------------------------------------------

// Make a requests to friends of a certain type
function makeRequest (toPod, requestsToMake, callback) {
  if (!callback) callback = function () {}

  const params = {
    toPod: toPod,
    encrypt: true, // Security
    sign: true, // To prove our identity
    method: 'POST',
    path: '/api/' + constants.API_VERSION + '/remote/videos',
    data: requestsToMake // Requests we need to make
  }

  // Make multiple retry requests to all of pods
  // The function fire some useful callbacks
  requests.makeSecureRequest(params, function (err, res) {
    if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
      logger.error(
        'Error sending secure request to %s pod.',
        toPod.url,
        {
          error: err || new Error('Status code not 20x : ' + res.statusCode)
        }
      )

      return callback(false)
    }

    return callback(true)
  })
}

// Make all the requests of the scheduler
function makeRequests () {
  const self = this

  listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
    if (err) {
      logger.error('Cannot get the list of requests.', { err: err })
      return // Abort
    }

    // If there are no requests, abort
    if (requests.length === 0) {
      logger.info('No requests to make.')
      return
    }

    logger.info('Making requests to friends.')

    // Requests by pods id
    const requestsToMake = {}

    requests.forEach(function (poolRequest) {
      poolRequest.to.forEach(function (toPodId) {
        if (!requestsToMake[toPodId]) {
          requestsToMake[toPodId] = {
            ids: [],
            datas: []
          }
        }

        requestsToMake[toPodId].ids.push(poolRequest._id)
        requestsToMake[toPodId].datas.push(poolRequest.request)
      })
    })

    const goodPods = []
    const badPods = []

    eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
      const requestToMake = requestsToMake[toPodId]

      // FIXME: mongodb request inside a loop :/
      Pod.load(toPodId, function (err, toPod) {
        if (err) {
          logger.error('Error finding pod by id.', { err: err })
          return callbackEach()
        }

        // Maybe the pod is not our friend anymore so simply remove it
        if (!toPod) {
          logger.info('Removing %d requests of unexisting pod %s.', requestToMake.ids.length, toPodId)
          removePodOf.call(self, requestToMake.ids, toPodId)
          return callbackEach()
        }

        makeRequest(toPod, requestToMake.datas, function (success) {
          if (success === true) {
            logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })

            // Remove the pod id of these request ids
            removePodOf.call(self, requestToMake.ids, toPodId)
            goodPods.push(toPodId)
          } else {
            badPods.push(toPodId)
          }

          callbackEach()
        })
      })
    }, function () {
      // All the requests were made, we update the pods score
      updatePodsScore(goodPods, badPods)
      // Flush requests with no pod
      removeWithEmptyTo.call(self)
    })
  })
{'fraction_non_alphanumeric': 0.15683907512303835, 'fraction_numerical': 0.00297149224626242, 'mean_word_length': 2.3302411873840447, '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': '5867105', 'n_tokens_mistral': 3156, 'n_tokens_neox': 3095, 'n_words': 823}