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 } from '../utils'
13 } from './pod-interface'
15 let Pod: Sequelize.Model<PodInstance, PodAttributes>
16 let toFormatedJSON: PodMethods.ToFormatedJSON
17 let countAll: PodMethods.CountAll
18 let incrementScores: PodMethods.IncrementScores
19 let list: PodMethods.List
20 let listAllIds: PodMethods.ListAllIds
21 let listRandomPodIdsWithRequest: PodMethods.ListRandomPodIdsWithRequest
22 let listBadPods: PodMethods.ListBadPods
23 let load: PodMethods.Load
24 let loadByHost: PodMethods.LoadByHost
25 let removeAll: PodMethods.RemoveAll
26 let updatePodsScore: PodMethods.UpdatePodsScore
28 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
29 Pod = sequelize.define<PodInstance, PodAttributes>('Pod',
32 type: DataTypes.STRING,
36 const res = isHostValid(value)
37 if (res === false) throw new Error('Host not valid.')
42 type: DataTypes.STRING(5000),
46 type: DataTypes.INTEGER,
47 defaultValue: FRIEND_SCORE.BASE,
55 type: DataTypes.STRING(400),
75 const classMethods = [
82 listRandomPodIdsWithRequest,
89 const instanceMethods = [ toFormatedJSON ]
90 addMethodsToModel(Pod, classMethods, instanceMethods)
95 // ------------------------------ METHODS ------------------------------
97 toFormatedJSON = function (this: PodInstance) {
102 score: this.score as number,
103 createdAt: this.createdAt
109 // ------------------------------ Statics ------------------------------
111 function associate (models) {
112 Pod.belongsToMany(models.Request, {
114 through: models.RequestToPod,
119 countAll = function () {
123 incrementScores = function (ids: number[], value: number) {
125 score: Sequelize.literal('score +' + value)
134 // In this case score is a literal and not an integer so we do not validate it
138 return Pod.update(update, options)
145 listAllIds = function (transaction: Sequelize.Transaction) {
146 const query: Sequelize.FindOptions = {
147 attributes: [ 'id' ],
151 return Pod.findAll(query).then(pods => {
152 return map(pods, 'id')
156 listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) {
157 return Pod.count().then(count => {
159 if (count === 0) return []
161 let start = Math.floor(Math.random() * count) - limit
162 if (start < 0) start = 0
165 attributes: [ 'id' ],
174 Sequelize.literal(`SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins}`)
180 return Pod.findAll(query).then(pods => {
181 return map(pods, 'id')
186 listBadPods = function () {
193 return Pod.findAll(query)
196 load = function (id: number) {
197 return Pod.findById(id)
200 loadByHost = function (host: string) {
207 return Pod.findOne(query)
210 removeAll = function () {
214 updatePodsScore = function (goodPods: number[], badPods: number[]) {
215 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
217 if (goodPods.length !== 0) {
218 incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
219 logger.error('Cannot increment scores of good pods.', err)
223 if (badPods.length !== 0) {
224 incrementScores(badPods, PODS_SCORE.MALUS)
225 .then(() => removeBadPods())
227 if (err) logger.error('Cannot decrement scores of bad pods.', err)
232 // ---------------------------------------------------------------------------
234 // Remove pods with a score of 0 (too many requests where they were unreachable)
235 function removeBadPods () {
238 const podsRemovePromises = pods.map(pod => pod.destroy())
239 return Promise.all(podsRemovePromises).then(() => pods.length)
241 .then(numberOfPodsRemoved => {
242 if (numberOfPodsRemoved) {
243 logger.info('Removed %d pods.', numberOfPodsRemoved)
245 logger.info('No need to remove bad pods.')
249 logger.error('Cannot remove bad pods.', err)