1 import { map } from 'lodash'
2 import * as Sequelize from 'sequelize'
4 import { FRIEND_SCORE, PODS_SCORE } from '../../initializers'
5 import { logger, isHostValid } from '../../helpers'
7 import { addMethodsToModel, getSort } from '../utils'
13 } from './pod-interface'
15 let Pod: Sequelize.Model<PodInstance, PodAttributes>
16 let toFormattedJSON: PodMethods.ToFormattedJSON
17 let countAll: PodMethods.CountAll
18 let incrementScores: PodMethods.IncrementScores
19 let list: PodMethods.List
20 let listForApi: PodMethods.ListForApi
21 let listAllIds: PodMethods.ListAllIds
22 let listRandomPodIdsWithRequest: PodMethods.ListRandomPodIdsWithRequest
23 let listBadPods: PodMethods.ListBadPods
24 let load: PodMethods.Load
25 let loadByHost: PodMethods.LoadByHost
26 let removeAll: PodMethods.RemoveAll
27 let updatePodsScore: PodMethods.UpdatePodsScore
29 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
30 Pod = sequelize.define<PodInstance, PodAttributes>('Pod',
33 type: DataTypes.STRING,
37 const res = isHostValid(value)
38 if (res === false) throw new Error('Host not valid.')
43 type: DataTypes.INTEGER,
44 defaultValue: FRIEND_SCORE.BASE,
65 const classMethods = [
73 listRandomPodIdsWithRequest,
80 const instanceMethods = [ toFormattedJSON ]
81 addMethodsToModel(Pod, classMethods, instanceMethods)
86 // ------------------------------ METHODS ------------------------------
88 toFormattedJSON = function (this: PodInstance) {
92 score: this.score as number,
93 createdAt: this.createdAt
99 // ------------------------------ Statics ------------------------------
101 function associate (models) {
102 Pod.belongsToMany(models.Request, {
104 through: models.RequestToPod,
109 countAll = function () {
113 incrementScores = function (ids: number[], value: number) {
115 score: Sequelize.literal('score +' + value)
121 [Sequelize.Op.in]: ids
124 // In this case score is a literal and not an integer so we do not validate it
128 return Pod.update(update, options)
135 listForApi = function (start: number, count: number, sort: string) {
139 order: [ getSort(sort) ]
142 return Pod.findAndCountAll(query).then(({ rows, count }) => {
150 listAllIds = function (transaction: Sequelize.Transaction) {
152 attributes: [ 'id' ],
156 return Pod.findAll(query).then(pods => {
157 return map(pods, 'id')
161 listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) {
162 return Pod.count().then(count => {
164 if (count === 0) return []
166 let start = Math.floor(Math.random() * count) - limit
167 if (start < 0) start = 0
169 const subQuery = `(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`
171 attributes: [ 'id' ],
179 [Sequelize.Op.in]: Sequelize.literal(subQuery)
184 return Pod.findAll(query).then(pods => {
185 return map(pods, 'id')
190 listBadPods = function () {
194 [Sequelize.Op.lte]: 0
199 return Pod.findAll(query)
202 load = function (id: number) {
203 return Pod.findById(id)
206 loadByHost = function (host: string) {
213 return Pod.findOne(query)
216 removeAll = function () {
220 updatePodsScore = function (goodPods: number[], badPods: number[]) {
221 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
223 if (goodPods.length !== 0) {
224 incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
225 logger.error('Cannot increment scores of good pods.', err)
229 if (badPods.length !== 0) {
230 incrementScores(badPods, PODS_SCORE.PENALTY)
231 .then(() => removeBadPods())
233 if (err) logger.error('Cannot decrement scores of bad pods.', err)
238 // ---------------------------------------------------------------------------
240 // Remove pods with a score of 0 (too many requests where they were unreachable)
241 async function removeBadPods () {
243 const pods = await listBadPods()
245 const podsRemovePromises = pods.map(pod => pod.destroy())
246 await Promise.all(podsRemovePromises)
248 const numberOfPodsRemoved = pods.length
250 if (numberOfPodsRemoved) {
251 logger.info('Removed %d pods.', numberOfPodsRemoved)
253 logger.info('No need to remove bad pods.')
256 logger.error('Cannot remove bad pods.', err)