]> 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 9209380fc058e6d6583c02a941dec6fe791badaa..6619726afcf397f1f64e1f6d7b43c14e89d38096 100644 (file)
@@ -4,7 +4,7 @@ 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 {
   PodInstance,
   PodAttributes,
@@ -13,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
@@ -32,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.')
           }
@@ -78,6 +79,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
     countAll,
     incrementScores,
     list,
+    listForApi,
     listAllIds,
     listRandomPodIdsWithRequest,
     listBadPods,
@@ -86,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
@@ -94,7 +96,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
 
 // ------------------------------ METHODS ------------------------------
 
-toFormatedJSON = function (this: PodInstance) {
+toFormattedJSON = function (this: PodInstance) {
   const json = {
     id: this.id,
     host: this.host,
@@ -142,8 +144,23 @@ list = function () {
   return Pod.findAll()
 }
 
+listForApi = function (start: number, count: number, sort: string) {
+  const query = {
+    offset: start,
+    limit: count,
+    order: [ getSort(sort) ]
+  }
+
+  return Pod.findAndCountAll(query).then(({ rows, count }) => {
+    return {
+      data: rows,
+      total: count
+    }
+  })
+}
+
 listAllIds = function (transaction: Sequelize.Transaction) {
-  const query: Sequelize.FindOptions = {
+  const query = {
     attributes: [ 'id' ],
     transaction
   }
@@ -170,9 +187,7 @@ 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})`)
         }
       }
     }
@@ -216,15 +231,15 @@ updatePodsScore = function (goodPods: number[], badPods: number[]) {
 
   if (goodPods.length !== 0) {
     incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
-      logger.error('Cannot increment scores of good pods.', { error: err })
+      logger.error('Cannot increment scores of good pods.', err)
     })
   }
 
   if (badPods.length !== 0) {
-    incrementScores(badPods, PODS_SCORE.MALUS)
+    incrementScores(badPods, PODS_SCORE.PENALTY)
       .then(() => removeBadPods())
       .catch(err => {
-        if (err) logger.error('Cannot decrement scores of bad pods.', { error: err })
+        if (err) logger.error('Cannot decrement scores of bad pods.', err)
       })
   }
 }
@@ -232,20 +247,21 @@ updatePodsScore = function (goodPods: number[], badPods: number[]) {
 // ---------------------------------------------------------------------------
 
 // Remove pods with a score of 0 (too many requests where they were unreachable)
-function removeBadPods () {
-  return listBadPods()
-    .then(pods => {
-      const podsRemovePromises = pods.map(pod => pod.destroy())
-      return Promise.all(podsRemovePromises).then(() => pods.length)
-    })
-    .then(numberOfPodsRemoved => {
-      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.', { error: err })
-    })
+async function removeBadPods () {
+  try {
+    const pods = await listBadPods()
+
+    const podsRemovePromises = pods.map(pod => pod.destroy())
+    await Promise.all(podsRemovePromises)
+
+    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)
+  }
 }