]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/pod/pod.ts
Use async/await in lib and initializers
[github/Chocobozzz/PeerTube.git] / server / models / pod / pod.ts
index 4c6e6302498f7db6ac26ea2abf4ee6524280e407..6619726afcf397f1f64e1f6d7b43c14e89d38096 100644 (file)
@@ -1,13 +1,11 @@
-import { each, waterfall } from 'async'
 import { map } from 'lodash'
 import * as Sequelize from 'sequelize'
 
 import { FRIEND_SCORE, PODS_SCORE } from '../../initializers'
 import { logger, isHostValid } from '../../helpers'
 
-import { addMethodsToModel } from '../utils'
+import { addMethodsToModel, getSort } from '../utils'
 import {
-  PodClass,
   PodInstance,
   PodAttributes,
 
@@ -15,10 +13,11 @@ import {
 } from './pod-interface'
 
 let Pod: Sequelize.Model<PodInstance, PodAttributes>
-let toFormatedJSON: PodMethods.ToFormatedJSON
+let toFormattedJSON: PodMethods.ToFormattedJSON
 let countAll: PodMethods.CountAll
 let incrementScores: PodMethods.IncrementScores
 let list: PodMethods.List
+let listForApi: PodMethods.ListForApi
 let listAllIds: PodMethods.ListAllIds
 let listRandomPodIdsWithRequest: PodMethods.ListRandomPodIdsWithRequest
 let listBadPods: PodMethods.ListBadPods
@@ -34,7 +33,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
         type: DataTypes.STRING,
         allowNull: false,
         validate: {
-          isHost: function (value) {
+          isHost: value => {
             const res = isHostValid(value)
             if (res === false) throw new Error('Host not valid.')
           }
@@ -80,6 +79,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
     countAll,
     incrementScores,
     list,
+    listForApi,
     listAllIds,
     listRandomPodIdsWithRequest,
     listBadPods,
@@ -88,7 +88,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
     updatePodsScore,
     removeAll
   ]
-  const instanceMethods = [ toFormatedJSON ]
+  const instanceMethods = [ toFormattedJSON ]
   addMethodsToModel(Pod, classMethods, instanceMethods)
 
   return Pod
@@ -96,12 +96,12 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
 
 // ------------------------------ METHODS ------------------------------
 
-toFormatedJSON = function () {
+toFormattedJSON = function (this: PodInstance) {
   const json = {
     id: this.id,
     host: this.host,
     email: this.email,
-    score: this.score,
+    score: this.score as number,
     createdAt: this.createdAt
   }
 
@@ -118,13 +118,11 @@ function associate (models) {
   })
 }
 
-countAll = function (callback: PodMethods.CountAllCallback) {
-  return Pod.count().asCallback(callback)
+countAll = function () {
+  return Pod.count()
 }
 
-incrementScores = function (ids: number[], value: number, callback?: PodMethods.IncrementScoresCallback) {
-  if (!callback) callback = function () { /* empty */ }
-
+incrementScores = function (ids: number[], value: number) {
   const update = {
     score: Sequelize.literal('score +' + value)
   }
@@ -139,33 +137,43 @@ incrementScores = function (ids: number[], value: number, callback?: PodMethods.
     validate: false
   }
 
-  return Pod.update(update, options).asCallback(callback)
+  return Pod.update(update, options)
 }
 
-list = function (callback: PodMethods.ListCallback) {
-  return Pod.findAll().asCallback(callback)
+list = function () {
+  return Pod.findAll()
 }
 
-listAllIds = function (transaction: Sequelize.Transaction, callback: PodMethods.ListAllIdsCallback) {
-  const query: any = {
-    attributes: [ 'id' ]
+listForApi = function (start: number, count: number, sort: string) {
+  const query = {
+    offset: start,
+    limit: count,
+    order: [ getSort(sort) ]
   }
 
-  if (transaction !== null) query.transaction = transaction
+  return Pod.findAndCountAll(query).then(({ rows, count }) => {
+    return {
+      data: rows,
+      total: count
+    }
+  })
+}
 
-  return Pod.findAll(query).asCallback(function (err: Error, pods) {
-    if (err) return callback(err)
+listAllIds = function (transaction: Sequelize.Transaction) {
+  const query = {
+    attributes: [ 'id' ],
+    transaction
+  }
 
-    return callback(null, map(pods, 'id'))
+  return Pod.findAll(query).then(pods => {
+    return map(pods, 'id')
   })
 }
 
-listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string, callback: PodMethods.ListRandomPodIdsWithRequestCallback) {
-  Pod.count().asCallback(function (err, count) {
-    if (err) return callback(err)
-
+listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) {
+  return Pod.count().then(count => {
     // Optimization...
-    if (count === 0) return callback(null, [])
+    if (count === 0) return []
 
     let start = Math.floor(Math.random() * count) - limit
     if (start < 0) start = 0
@@ -179,96 +187,81 @@ listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, ta
       limit: limit,
       where: {
         id: {
-          $in: [
-            Sequelize.literal(`SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins}`)
-          ]
+          $in: Sequelize.literal(`(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`)
         }
       }
     }
 
-    return Pod.findAll(query).asCallback(function (err, pods) {
-      if (err) return callback(err)
-
-      return callback(null, map(pods, 'id'))
+    return Pod.findAll(query).then(pods => {
+      return map(pods, 'id')
     })
   })
 }
 
-listBadPods = function (callback: PodMethods.ListBadPodsCallback) {
+listBadPods = function () {
   const query = {
     where: {
       score: { $lte: 0 }
     }
   }
 
-  return Pod.findAll(query).asCallback(callback)
+  return Pod.findAll(query)
 }
 
-load = function (id: number, callback: PodMethods.LoadCallback) {
-  return Pod.findById(id).asCallback(callback)
+load = function (id: number) {
+  return Pod.findById(id)
 }
 
-loadByHost = function (host: string, callback: PodMethods.LoadByHostCallback) {
+loadByHost = function (host: string) {
   const query = {
     where: {
       host: host
     }
   }
 
-  return Pod.findOne(query).asCallback(callback)
+  return Pod.findOne(query)
 }
 
-removeAll = function (callback: PodMethods.RemoveAllCallback) {
-  return Pod.destroy().asCallback(callback)
+removeAll = function () {
+  return Pod.destroy()
 }
 
 updatePodsScore = function (goodPods: number[], badPods: number[]) {
   logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
 
   if (goodPods.length !== 0) {
-    incrementScores(goodPods, PODS_SCORE.BONUS, function (err) {
-      if (err) logger.error('Cannot increment scores of good pods.', { error: err })
+    incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
+      logger.error('Cannot increment scores of good pods.', err)
     })
   }
 
   if (badPods.length !== 0) {
-    incrementScores(badPods, PODS_SCORE.MALUS, function (err) {
-      if (err) logger.error('Cannot decrement scores of bad pods.', { error: err })
-      removeBadPods()
-    })
+    incrementScores(badPods, PODS_SCORE.PENALTY)
+      .then(() => removeBadPods())
+      .catch(err => {
+        if (err) logger.error('Cannot decrement scores of bad pods.', err)
+      })
   }
 }
 
 // ---------------------------------------------------------------------------
 
 // Remove pods with a score of 0 (too many requests where they were unreachable)
-function removeBadPods () {
-  waterfall([
-    function findBadPods (callback) {
-      listBadPods(function (err, pods) {
-        if (err) {
-          logger.error('Cannot find bad pods.', { error: err })
-          return callback(err)
-        }
+async function removeBadPods () {
+  try {
+    const pods = await listBadPods()
 
-        return callback(null, pods)
-      })
-    },
+    const podsRemovePromises = pods.map(pod => pod.destroy())
+    await Promise.all(podsRemovePromises)
 
-    function removeTheseBadPods (pods, callback) {
-      each(pods, function (pod: any, callbackEach) {
-        pod.destroy().asCallback(callbackEach)
-      }, function (err) {
-        return callback(err, pods.length)
-      })
-    }
-  ], function (err, numberOfPodsRemoved) {
-    if (err) {
-      logger.error('Cannot remove bad pods.', { error: err })
-    } else if (numberOfPodsRemoved) {
+    const numberOfPodsRemoved = pods.length
+
+    if (numberOfPodsRemoved) {
       logger.info('Removed %d pods.', numberOfPodsRemoved)
     } else {
       logger.info('No need to remove bad pods.')
     }
-  })
+  } catch (err) {
+    logger.error('Cannot remove bad pods.', err)
+  }
 }