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 = [
71 listRandomPodIdsWithRequest,
78 const instanceMethods = [ toFormattedJSON ]
79 addMethodsToModel(Pod, classMethods, instanceMethods)
84 // ------------------------------ METHODS ------------------------------
86 toFormattedJSON = function (this: PodInstance) {
90 score: this.score as number,
91 createdAt: this.createdAt
97 // ------------------------------ Statics ------------------------------
99 countAll = function () {
103 incrementScores = function (ids: number[], value: number) {
105 score: Sequelize.literal('score +' + value)
111 [Sequelize.Op.in]: ids
114 // In this case score is a literal and not an integer so we do not validate it
118 return Pod.update(update, options)
125 listForApi = function (start: number, count: number, sort: string) {
129 order: [ getSort(sort) ]
132 return Pod.findAndCountAll(query).then(({ rows, count }) => {
140 listAllIds = function (transaction: Sequelize.Transaction) {
142 attributes: [ 'id' ],
146 return Pod.findAll(query).then(pods => {
147 return map(pods, 'id')
151 listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) {
152 return Pod.count().then(count => {
154 if (count === 0) return []
156 let start = Math.floor(Math.random() * count) - limit
157 if (start < 0) start = 0
159 const subQuery = `(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`
161 attributes: [ 'id' ],
169 [Sequelize.Op.in]: Sequelize.literal(subQuery)
174 return Pod.findAll(query).then(pods => {
175 return map(pods, 'id')
180 listBadPods = function () {
184 [Sequelize.Op.lte]: 0
189 return Pod.findAll(query)
192 load = function (id: number) {
193 return Pod.findById(id)
196 loadByHost = function (host: string) {
203 return Pod.findOne(query)
206 removeAll = function () {
210 updatePodsScore = function (goodPods: number[], badPods: number[]) {
211 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
213 if (goodPods.length !== 0) {
214 incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
215 logger.error('Cannot increment scores of good pods.', err)
219 if (badPods.length !== 0) {
220 incrementScores(badPods, PODS_SCORE.PENALTY)
221 .then(() => removeBadPods())
223 if (err) logger.error('Cannot decrement scores of bad pods.', err)
228 // ---------------------------------------------------------------------------
230 // Remove pods with a score of 0 (too many requests where they were unreachable)
231 async function removeBadPods () {
233 const pods = await listBadPods()
235 const podsRemovePromises = pods.map(pod => pod.destroy())
236 await Promise.all(podsRemovePromises)
238 const numberOfPodsRemoved = pods.length
240 if (numberOfPodsRemoved) {
241 logger.info('Removed %d pods.', numberOfPodsRemoved)
243 logger.info('No need to remove bad pods.')
246 logger.error('Cannot remove bad pods.', err)