const each = require('async/each')
const eachLimit = require('async/eachLimit')
-const map = require('lodash/map')
+const values = require('lodash/values')
const mongoose = require('mongoose')
const waterfall = require('async/waterfall')
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' } ]
+ endpoint: {
+ type: String,
+ enum: [ values(constants.REQUEST_ENDPOINTS) ]
+ },
+ to: [
+ {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: 'Pod'
+ }
+ ]
})
RequestSchema.statics = {
deactivate,
flush,
forceSend,
- list
+ list,
+ remainingMilliSeconds
}
RequestSchema.pre('save', function (next) {
function activate () {
logger.info('Requests scheduler activated.')
- timer = setInterval(makeRequests.bind(this), constants.REQUESTS_INTERVAL)
+ 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 () {
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) {
+function makeRequest (toPod, requestEndpoint, requestsToMake, callback) {
if (!callback) callback = function () {}
const params = {
encrypt: true, // Security
sign: true, // To prove our identity
method: 'POST',
- path: '/api/' + constants.API_VERSION + '/remote/videos',
+ path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
data: requestsToMake // Requests we need to make
}
if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
logger.error(
'Error sending secure request to %s pod.',
- toPod.url,
+ toPod.host,
{
- error: err || new Error('Status code not 20x'),
- statusCode: res.statusCode
+ error: err || new Error('Status code not 20x : ' + res.statusCode)
}
)
function makeRequests () {
const self = this
- listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
+ // We limit the size of the requests (REQUESTS_LIMIT)
+ // We don't want to stuck with the same failing requests so we get a random list
+ listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
if (err) {
logger.error('Cannot get the list of requests.', { err: err })
return // Abort
logger.info('Making requests to friends.')
- // Requests by pods id
- const requestsToMake = {}
+ // We want to group requests by destinations pod and endpoint
+ const requestsToMakeGrouped = {}
requests.forEach(function (poolRequest) {
poolRequest.to.forEach(function (toPodId) {
- if (!requestsToMake[toPodId]) {
- requestsToMake[toPodId] = {
- ids: [],
- datas: []
+ const hashKey = toPodId + poolRequest.endpoint
+ if (!requestsToMakeGrouped[hashKey]) {
+ requestsToMakeGrouped[hashKey] = {
+ toPodId,
+ endpoint: poolRequest.endpoint,
+ ids: [], // pool request ids, to delete them from the DB in the future
+ datas: [] // requests data,
}
}
- requestsToMake[toPodId].ids.push(poolRequest._id)
- requestsToMake[toPodId].datas.push(poolRequest.request)
+ requestsToMakeGrouped[hashKey].ids.push(poolRequest._id)
+ requestsToMakeGrouped[hashKey].datas.push(poolRequest.request)
})
})
const goodPods = []
const badPods = []
- eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
- const requestToMake = requestsToMake[toPodId]
+ eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) {
+ const requestToMake = requestsToMakeGrouped[hashKey]
// FIXME: mongodb request inside a loop :/
- Pod.load(toPodId, function (err, toPod) {
+ Pod.load(requestToMake.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 them
+ // Maybe the pod is not our friend anymore so simply remove it
if (!toPod) {
- removePodOf.call(self, requestToMake.ids, toPodId)
+ const requestIdsToDelete = requestToMake.ids
+
+ logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPodId)
+ removePodOf.call(self, requestIdsToDelete, requestToMake.toPodId)
return callbackEach()
}
- makeRequest(toPod, requestToMake.datas, function (success) {
+ makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) {
if (success === true) {
- logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
+ logger.debug('Removing requests for %s pod.', requestToMake.toPodId, { requestsIds: requestToMake.ids })
+
+ goodPods.push(requestToMake.toPodId)
// Remove the pod id of these request ids
- removePodOf.call(self, requestToMake.ids, toPodId)
- goodPods.push(toPodId)
+ removePodOf.call(self, requestToMake.ids, requestToMake.toPodId, callbackEach)
} else {
- badPods.push(toPodId)
+ badPods.push(requestToMake.toPodId)
+ callbackEach()
}
-
- callbackEach()
})
})
}, function () {
})
},
- function listVideosOfTheseBadPods (pods, callback) {
- if (pods.length === 0) return callback(null)
-
- const urls = map(pods, 'url')
-
- Video.listByUrls(urls, function (err, videosList) {
- if (err) {
- logger.error('Cannot list videos urls.', { error: err, urls: urls })
- return callback(null, pods, [])
- }
-
- return callback(null, pods, videosList)
- })
- },
-
- function removeVideosOfTheseBadPods (pods, videosList, callback) {
- // We don't have to remove pods, skip
- if (typeof pods === 'function') {
- callback = pods
- return callback(null)
- }
-
- each(videosList, function (video, callbackEach) {
- video.remove(callbackEach)
- }, function (err) {
- if (err) {
- // Don't stop the process
- logger.error('Error while removing videos of bad pods.', { error: err })
- return
- }
-
- return callback(null, pods)
- })
- },
-
- function removeBadPodsFromDB (pods, callback) {
- // We don't have to remove pods, skip
- if (typeof pods === 'function') {
- callback = pods
- return callback(null)
- }
+ function removeTheseBadPods (pods, callback) {
+ if (pods.length === 0) return callback(null, 0)
each(pods, function (pod, callbackEach) {
pod.remove(callbackEach)
}, function (err) {
- if (err) return callback(err)
-
- return callback(null, pods.length)
+ return callback(err, pods.length)
})
}
], function (err, numberOfPodsRemoved) {
})
}
-function listWithLimit (limit, callback) {
- this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
+function listWithLimitAndRandom (limit, callback) {
+ const self = this
+
+ self.count(function (err, count) {
+ if (err) return callback(err)
+
+ let start = Math.floor(Math.random() * count) - limit
+ if (start < 0) start = 0
+
+ self.find().sort({ _id: 1 }).skip(start).limit(limit).exec(callback)
+ })
}
function removeAll (callback) {