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.STRING(5000),
47 type: DataTypes.INTEGER,
48 defaultValue: FRIEND_SCORE.BASE,
56 type: DataTypes.STRING(400),
76 const classMethods = [
84 listRandomPodIdsWithRequest,
91 const instanceMethods = [ toFormattedJSON ]
92 addMethodsToModel(Pod, classMethods, instanceMethods)
97 // ------------------------------ METHODS ------------------------------
99 toFormattedJSON = function (this: PodInstance) {
104 score: this.score as number,
105 createdAt: this.createdAt
111 // ------------------------------ Statics ------------------------------
113 function associate (models) {
114 Pod.belongsToMany(models.Request, {
116 through: models.RequestToPod,
121 countAll = function () {
125 incrementScores = function (ids: number[], value: number) {
127 score: Sequelize.literal('score +' + value)
136 // In this case score is a literal and not an integer so we do not validate it
140 return Pod.update(update, options)
147 listForApi = function (start: number, count: number, sort: string) {
151 order: [ getSort(sort) ]
154 return Pod.findAndCountAll(query).then(({ rows, count }) => {
162 listAllIds = function (transaction: Sequelize.Transaction) {
164 attributes: [ 'id' ],
168 return Pod.findAll(query).then(pods => {
169 return map(pods, 'id')
173 listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) {
174 return Pod.count().then(count => {
176 if (count === 0) return []
178 let start = Math.floor(Math.random() * count) - limit
179 if (start < 0) start = 0
182 attributes: [ 'id' ],
190 $in: Sequelize.literal(`(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`)
195 return Pod.findAll(query).then(pods => {
196 return map(pods, 'id')
201 listBadPods = function () {
208 return Pod.findAll(query)
211 load = function (id: number) {
212 return Pod.findById(id)
215 loadByHost = function (host: string) {
222 return Pod.findOne(query)
225 removeAll = function () {
229 updatePodsScore = function (goodPods: number[], badPods: number[]) {
230 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
232 if (goodPods.length !== 0) {
233 incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
234 logger.error('Cannot increment scores of good pods.', err)
238 if (badPods.length !== 0) {
239 incrementScores(badPods, PODS_SCORE.PENALTY)
240 .then(() => removeBadPods())
242 if (err) logger.error('Cannot decrement scores of bad pods.', err)
247 // ---------------------------------------------------------------------------
249 // Remove pods with a score of 0 (too many requests where they were unreachable)
250 function removeBadPods () {
253 const podsRemovePromises = pods.map(pod => pod.destroy())
254 return Promise.all(podsRemovePromises).then(() => pods.length)
256 .then(numberOfPodsRemoved => {
257 if (numberOfPodsRemoved) {
258 logger.info('Removed %d pods.', numberOfPodsRemoved)
260 logger.info('No need to remove bad pods.')
264 logger.error('Cannot remove bad pods.', err)