]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/request.js
Server: fix remaining milli seconds before the next requests feature
[github/Chocobozzz/PeerTube.git] / server / models / request.js
index 2a407388a7f4358d139e953764d192f2983284bb..2d50d94e0c26805d2c2298c15b5a0d3132b0eedc 100644 (file)
@@ -1,37 +1,42 @@
 'use strict'
 
-const async = require('async')
+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 Pods = require('../models/pods')
 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: 'users' } ]
+  to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Pod' } ]
 })
 
 RequestSchema.statics = {
   activate,
   deactivate,
   flush,
-  forceSend
+  forceSend,
+  list,
+  remainingMilliSeconds
 }
 
 RequestSchema.pre('save', function (next) {
   const self = this
 
   if (self.to.length === 0) {
-    Pods.listAllIds(function (err, podIds) {
+    Pod.listAllIds(function (err, podIds) {
       if (err) return next(err)
 
       // No friends
@@ -51,12 +56,19 @@ mongoose.model('Request', RequestSchema)
 
 function activate () {
   logger.info('Requests scheduler activated.')
-  timer = setInterval(makeRequests.bind(this), constants.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 () {
@@ -70,6 +82,16 @@ function forceSend () {
   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
@@ -89,7 +111,13 @@ function makeRequest (toPod, requestsToMake, callback) {
   // 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') })
+      logger.error(
+        'Error sending secure request to %s pod.',
+        toPod.url,
+        {
+          error: err || new Error('Status code not 20x : ' + res.statusCode)
+        }
+      )
 
       return callback(false)
     }
@@ -102,7 +130,7 @@ function makeRequest (toPod, requestsToMake, callback) {
 function makeRequests () {
   const self = this
 
-  list.call(self, function (err, requests) {
+  listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
     if (err) {
       logger.error('Cannot get the list of requests.', { err: err })
       return // Abort
@@ -136,29 +164,23 @@ function makeRequests () {
     const goodPods = []
     const badPods = []
 
-    async.eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
+    eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
       const requestToMake = requestsToMake[toPodId]
 
       // FIXME: mongodb request inside a loop :/
-      Pods.findById(toPodId, function (err, toPod) {
+      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 them
+        // 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 (err) {
-            logger.error('Errors when sent request to %s.', toPod.url, { error: err })
-            // Do not stop the process just for one error
-            return callbackEach()
-          }
-
           if (success === true) {
             logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
 
@@ -183,9 +205,9 @@ function makeRequests () {
 
 // Remove pods with a score of 0 (too many requests where they were unreachable)
 function removeBadPods () {
-  async.waterfall([
+  waterfall([
     function findBadPods (callback) {
-      Pods.findBadPods(function (err, pods) {
+      Pod.listBadPods(function (err, pods) {
         if (err) {
           logger.error('Cannot find bad pods.', { error: err })
           return callback(err)
@@ -199,23 +221,25 @@ function removeBadPods () {
       if (pods.length === 0) return callback(null)
 
       const urls = map(pods, 'url')
-      const ids = map(pods, '_id')
 
       Video.listByUrls(urls, function (err, videosList) {
         if (err) {
           logger.error('Cannot list videos urls.', { error: err, urls: urls })
-          return callback(null, ids, [])
+          return callback(null, pods, [])
         }
 
-        return callback(null, ids, videosList)
+        return callback(null, pods, videosList)
       })
     },
 
-    function removeVideosOfTheseBadPods (podIds, videosList, callback) {
+    function removeVideosOfTheseBadPods (pods, videosList, callback) {
       // We don't have to remove pods, skip
-      if (typeof podIds === 'function') return podIds(null)
+      if (typeof pods === 'function') {
+        callback = pods
+        return callback(null)
+      }
 
-      async.each(videosList, function (video, callbackEach) {
+      each(videosList, function (video, callbackEach) {
         video.remove(callbackEach)
       }, function (err) {
         if (err) {
@@ -224,22 +248,30 @@ function removeBadPods () {
           return
         }
 
-        return callback(null, podIds)
+        return callback(null, pods)
       })
     },
 
-    function removeBadPodsFromDB (podIds, callback) {
+    function removeBadPodsFromDB (pods, callback) {
       // We don't have to remove pods, skip
-      if (typeof podIds === 'function') return podIds(null)
+      if (typeof pods === 'function') {
+        callback = pods
+        return callback(null)
+      }
 
-      Pods.removeAllByIds(podIds, callback)
+      each(pods, function (pod, callbackEach) {
+        pod.remove(callbackEach)
+      }, function (err) {
+        if (err) return callback(err)
+
+        return callback(null, pods.length)
+      })
     }
-  ], function (err, removeResult) {
+  ], function (err, numberOfPodsRemoved) {
     if (err) {
       logger.error('Cannot remove bad pods.', { error: err })
-    } else if (removeResult) {
-      const podsRemoved = removeResult.result.n
-      logger.info('Removed %d pods.', podsRemoved)
+    } else if (numberOfPodsRemoved) {
+      logger.info('Removed %d pods.', numberOfPodsRemoved)
     } else {
       logger.info('No need to remove bad pods.')
     }
@@ -249,18 +281,18 @@ function removeBadPods () {
 function updatePodsScore (goodPods, badPods) {
   logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
 
-  Pods.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
+  Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
     if (err) logger.error('Cannot increment scores of good pods.')
   })
 
-  Pods.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
+  Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
     if (err) logger.error('Cannot decrement scores of bad pods.')
     removeBadPods()
   })
 }
 
-function list (callback) {
-  this.find({ }, { _id: 1, request: 1, to: 1 }callback)
+function listWithLimit (limit, callback) {
+  this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
 }
 
 function removeAll (callback) {