]>
Commit | Line | Data |
---|---|---|
1 | import { map } from 'lodash' | |
2 | import * as Sequelize from 'sequelize' | |
3 | ||
4 | import { FRIEND_SCORE, PODS_SCORE } from '../../initializers' | |
5 | import { logger, isHostValid } from '../../helpers' | |
6 | ||
7 | import { addMethodsToModel } from '../utils' | |
8 | import { | |
9 | PodInstance, | |
10 | PodAttributes, | |
11 | ||
12 | PodMethods | |
13 | } from './pod-interface' | |
14 | ||
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 | |
27 | ||
28 | export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { | |
29 | Pod = sequelize.define<PodInstance, PodAttributes>('Pod', | |
30 | { | |
31 | host: { | |
32 | type: DataTypes.STRING, | |
33 | allowNull: false, | |
34 | validate: { | |
35 | isHost: function (value) { | |
36 | const res = isHostValid(value) | |
37 | if (res === false) throw new Error('Host not valid.') | |
38 | } | |
39 | } | |
40 | }, | |
41 | publicKey: { | |
42 | type: DataTypes.STRING(5000), | |
43 | allowNull: false | |
44 | }, | |
45 | score: { | |
46 | type: DataTypes.INTEGER, | |
47 | defaultValue: FRIEND_SCORE.BASE, | |
48 | allowNull: false, | |
49 | validate: { | |
50 | isInt: true, | |
51 | max: FRIEND_SCORE.MAX | |
52 | } | |
53 | }, | |
54 | email: { | |
55 | type: DataTypes.STRING(400), | |
56 | allowNull: false, | |
57 | validate: { | |
58 | isEmail: true | |
59 | } | |
60 | } | |
61 | }, | |
62 | { | |
63 | indexes: [ | |
64 | { | |
65 | fields: [ 'host' ], | |
66 | unique: true | |
67 | }, | |
68 | { | |
69 | fields: [ 'score' ] | |
70 | } | |
71 | ] | |
72 | } | |
73 | ) | |
74 | ||
75 | const classMethods = [ | |
76 | associate, | |
77 | ||
78 | countAll, | |
79 | incrementScores, | |
80 | list, | |
81 | listAllIds, | |
82 | listRandomPodIdsWithRequest, | |
83 | listBadPods, | |
84 | load, | |
85 | loadByHost, | |
86 | updatePodsScore, | |
87 | removeAll | |
88 | ] | |
89 | const instanceMethods = [ toFormatedJSON ] | |
90 | addMethodsToModel(Pod, classMethods, instanceMethods) | |
91 | ||
92 | return Pod | |
93 | } | |
94 | ||
95 | // ------------------------------ METHODS ------------------------------ | |
96 | ||
97 | toFormatedJSON = function (this: PodInstance) { | |
98 | const json = { | |
99 | id: this.id, | |
100 | host: this.host, | |
101 | email: this.email, | |
102 | score: this.score as number, | |
103 | createdAt: this.createdAt | |
104 | } | |
105 | ||
106 | return json | |
107 | } | |
108 | ||
109 | // ------------------------------ Statics ------------------------------ | |
110 | ||
111 | function associate (models) { | |
112 | Pod.belongsToMany(models.Request, { | |
113 | foreignKey: 'podId', | |
114 | through: models.RequestToPod, | |
115 | onDelete: 'cascade' | |
116 | }) | |
117 | } | |
118 | ||
119 | countAll = function () { | |
120 | return Pod.count() | |
121 | } | |
122 | ||
123 | incrementScores = function (ids: number[], value: number) { | |
124 | const update = { | |
125 | score: Sequelize.literal('score +' + value) | |
126 | } | |
127 | ||
128 | const options = { | |
129 | where: { | |
130 | id: { | |
131 | $in: ids | |
132 | } | |
133 | }, | |
134 | // In this case score is a literal and not an integer so we do not validate it | |
135 | validate: false | |
136 | } | |
137 | ||
138 | return Pod.update(update, options) | |
139 | } | |
140 | ||
141 | list = function () { | |
142 | return Pod.findAll() | |
143 | } | |
144 | ||
145 | listAllIds = function (transaction: Sequelize.Transaction) { | |
146 | const query: Sequelize.FindOptions = { | |
147 | attributes: [ 'id' ], | |
148 | transaction | |
149 | } | |
150 | ||
151 | return Pod.findAll(query).then(pods => { | |
152 | return map(pods, 'id') | |
153 | }) | |
154 | } | |
155 | ||
156 | listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) { | |
157 | return Pod.count().then(count => { | |
158 | // Optimization... | |
159 | if (count === 0) return [] | |
160 | ||
161 | let start = Math.floor(Math.random() * count) - limit | |
162 | if (start < 0) start = 0 | |
163 | ||
164 | const query = { | |
165 | attributes: [ 'id' ], | |
166 | order: [ | |
167 | [ 'id', 'ASC' ] | |
168 | ], | |
169 | offset: start, | |
170 | limit: limit, | |
171 | where: { | |
172 | id: { | |
173 | $in: [ | |
174 | Sequelize.literal(`SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins}`) | |
175 | ] | |
176 | } | |
177 | } | |
178 | } | |
179 | ||
180 | return Pod.findAll(query).then(pods => { | |
181 | return map(pods, 'id') | |
182 | }) | |
183 | }) | |
184 | } | |
185 | ||
186 | listBadPods = function () { | |
187 | const query = { | |
188 | where: { | |
189 | score: { $lte: 0 } | |
190 | } | |
191 | } | |
192 | ||
193 | return Pod.findAll(query) | |
194 | } | |
195 | ||
196 | load = function (id: number) { | |
197 | return Pod.findById(id) | |
198 | } | |
199 | ||
200 | loadByHost = function (host: string) { | |
201 | const query = { | |
202 | where: { | |
203 | host: host | |
204 | } | |
205 | } | |
206 | ||
207 | return Pod.findOne(query) | |
208 | } | |
209 | ||
210 | removeAll = function () { | |
211 | return Pod.destroy() | |
212 | } | |
213 | ||
214 | updatePodsScore = function (goodPods: number[], badPods: number[]) { | |
215 | logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length) | |
216 | ||
217 | if (goodPods.length !== 0) { | |
218 | incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => { | |
219 | logger.error('Cannot increment scores of good pods.', { error: err }) | |
220 | }) | |
221 | } | |
222 | ||
223 | if (badPods.length !== 0) { | |
224 | incrementScores(badPods, PODS_SCORE.MALUS) | |
225 | .then(() => removeBadPods()) | |
226 | .catch(err => { | |
227 | if (err) logger.error('Cannot decrement scores of bad pods.', { error: err }) | |
228 | }) | |
229 | } | |
230 | } | |
231 | ||
232 | // --------------------------------------------------------------------------- | |
233 | ||
234 | // Remove pods with a score of 0 (too many requests where they were unreachable) | |
235 | function removeBadPods () { | |
236 | return listBadPods() | |
237 | .then(pods => { | |
238 | const podsRemovePromises = pods.map(pod => pod.destroy()) | |
239 | return Promise.all(podsRemovePromises).then(() => pods.length) | |
240 | }) | |
241 | .then(numberOfPodsRemoved => { | |
242 | if (numberOfPodsRemoved) { | |
243 | logger.info('Removed %d pods.', numberOfPodsRemoved) | |
244 | } else { | |
245 | logger.info('No need to remove bad pods.') | |
246 | } | |
247 | }) | |
248 | .catch(err => { | |
249 | logger.error('Cannot remove bad pods.', { error: err }) | |
250 | }) | |
251 | } |