3 const each = require('async/each')
4 const eachLimit = require('async/eachLimit')
5 const waterfall = require('async/waterfall')
6 const values = require('lodash/values')
8 const constants = require('../initializers/constants')
9 const logger = require('../helpers/logger')
10 const requests = require('../helpers/requests')
13 let lastRequestTimestamp = 0
15 // ---------------------------------------------------------------------------
17 module.exports = function (sequelize, DataTypes) {
18 const Request = sequelize.define('Request',
25 type: DataTypes.ENUM(values(constants.REQUEST_ENDPOINTS)),
46 // ------------------------------ STATICS ------------------------------
48 function associate (models) {
49 this.belongsToMany(models.Pod, {
54 through: models.RequestToPod,
59 function activate () {
60 logger.info('Requests scheduler activated.')
61 lastRequestTimestamp = Date.now()
64 timer = setInterval(function () {
65 lastRequestTimestamp = Date.now()
66 makeRequests.call(self)
67 }, constants.REQUESTS_INTERVAL)
70 function countTotalRequests (callback) {
72 include: [ this.sequelize.models.Pod ]
75 return this.count(query).asCallback(callback)
78 function deactivate () {
79 logger.info('Requests scheduler deactivated.')
84 function flush (callback) {
85 removeAll.call(this, function (err) {
86 if (err) logger.error('Cannot flush the requests.', { error: err })
92 function forceSend () {
93 logger.info('Force requests scheduler sending.')
94 makeRequests.call(this)
97 function remainingMilliSeconds () {
98 if (timer === null) return -1
100 return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
103 // ---------------------------------------------------------------------------
105 // Make a requests to friends of a certain type
106 function makeRequest (toPod, requestEndpoint, requestsToMake, callback) {
107 if (!callback) callback = function () {}
111 sign: true, // Prove our identity
113 path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
114 data: requestsToMake // Requests we need to make
117 // Make multiple retry requests to all of pods
118 // The function fire some useful callbacks
119 requests.makeSecureRequest(params, function (err, res) {
120 if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
122 'Error sending secure request to %s pod.',
125 error: err ? err.message : 'Status code not 20x : ' + res.statusCode
129 return callback(false)
132 return callback(true)
136 // Make all the requests of the scheduler
137 function makeRequests () {
139 const RequestToPod = this.sequelize.models.RequestToPod
141 // We limit the size of the requests
142 // We don't want to stuck with the same failing requests so we get a random list
143 listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT_PODS, constants.REQUESTS_LIMIT_PER_POD, function (err, requests) {
145 logger.error('Cannot get the list of requests.', { err: err })
149 // If there are no requests, abort
150 if (requests.length === 0) {
151 logger.info('No requests to make.')
155 logger.info('Making requests to friends.')
157 // We want to group requests by destinations pod and endpoint
158 const requestsToMakeGrouped = {}
159 Object.keys(requests).forEach(function (toPodId) {
160 requests[toPodId].forEach(function (data) {
161 const request = data.request
163 const hashKey = toPodId + request.endpoint
165 if (!requestsToMakeGrouped[hashKey]) {
166 requestsToMakeGrouped[hashKey] = {
168 endpoint: request.endpoint,
169 ids: [], // request ids, to delete them from the DB in the future
170 datas: [] // requests data,
174 requestsToMakeGrouped[hashKey].ids.push(request.id)
175 requestsToMakeGrouped[hashKey].datas.push(request.request)
182 eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) {
183 const requestToMake = requestsToMakeGrouped[hashKey]
184 const toPod = requestToMake.toPod
186 // Maybe the pod is not our friend anymore so simply remove it
188 const requestIdsToDelete = requestToMake.ids
190 logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPod.id)
191 RequestToPod.removePodOf.call(self, requestIdsToDelete, requestToMake.toPod.id)
192 return callbackEach()
195 makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) {
196 if (success === true) {
197 logger.debug('Removing requests for pod %s.', requestToMake.toPod.id, { requestsIds: requestToMake.ids })
199 goodPods.push(requestToMake.toPod.id)
201 // Remove the pod id of these request ids
202 RequestToPod.removePodOf(requestToMake.ids, requestToMake.toPod.id, callbackEach)
204 badPods.push(requestToMake.toPod.id)
209 // All the requests were made, we update the pods score
210 updatePodsScore.call(self, goodPods, badPods)
211 // Flush requests with no pod
212 removeWithEmptyTo.call(self, function (err) {
213 if (err) logger.error('Error when removing requests with no pods.', { error: err })
219 // Remove pods with a score of 0 (too many requests where they were unreachable)
220 function removeBadPods () {
224 function findBadPods (callback) {
225 self.sequelize.models.Pod.listBadPods(function (err, pods) {
227 logger.error('Cannot find bad pods.', { error: err })
231 return callback(null, pods)
235 function removeTheseBadPods (pods, callback) {
236 each(pods, function (pod, callbackEach) {
237 pod.destroy().asCallback(callbackEach)
239 return callback(err, pods.length)
242 ], function (err, numberOfPodsRemoved) {
244 logger.error('Cannot remove bad pods.', { error: err })
245 } else if (numberOfPodsRemoved) {
246 logger.info('Removed %d pods.', numberOfPodsRemoved)
248 logger.info('No need to remove bad pods.')
253 function updatePodsScore (goodPods, badPods) {
255 const Pod = this.sequelize.models.Pod
257 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
259 if (goodPods.length !== 0) {
260 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
261 if (err) logger.error('Cannot increment scores of good pods.', { error: err })
265 if (badPods.length !== 0) {
266 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
267 if (err) logger.error('Cannot decrement scores of bad pods.', { error: err })
268 removeBadPods.call(self)
273 function listWithLimitAndRandom (limitPods, limitRequestsPerPod, callback) {
275 const Pod = this.sequelize.models.Pod
277 Pod.listRandomPodIdsWithRequest(limitPods, function (err, podIds) {
278 if (err) return callback(err)
280 // We don't have friends that have requests
281 if (podIds.length === 0) return callback(null, [])
283 // The the first x requests of these pods
284 // It is very important to sort by id ASC to keep the requests order!
291 model: self.sequelize.models.Pod,
301 self.findAll(query).asCallback(function (err, requests) {
302 if (err) return callback(err)
304 const requestsGrouped = groupAndTruncateRequests(requests, limitRequestsPerPod)
305 return callback(err, requestsGrouped)
310 function groupAndTruncateRequests (requests, limitRequestsPerPod) {
311 const requestsGrouped = {}
313 requests.forEach(function (request) {
314 request.Pods.forEach(function (pod) {
315 if (!requestsGrouped[pod.id]) requestsGrouped[pod.id] = []
317 if (requestsGrouped[pod.id].length < limitRequestsPerPod) {
318 requestsGrouped[pod.id].push({
326 return requestsGrouped
329 function removeAll (callback) {
330 // Delete all requests
331 this.truncate({ cascade: true }).asCallback(callback)
334 function removeWithEmptyTo (callback) {
335 if (!callback) callback = function () {}
341 this.sequelize.literal('SELECT "requestId" FROM "RequestToPods"')
347 this.destroy(query).asCallback(callback)