]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/pod/pod.ts
Use async/await in lib and initializers
[github/Chocobozzz/PeerTube.git] / server / models / pod / pod.ts
CommitLineData
65fcc311 1import { map } from 'lodash'
e02643f3 2import * as Sequelize from 'sequelize'
9f10b292 3
74889a71
C
4import { FRIEND_SCORE, PODS_SCORE } from '../../initializers'
5import { logger, isHostValid } from '../../helpers'
9f10b292 6
8a02bd04 7import { addMethodsToModel, getSort } from '../utils'
e02643f3 8import {
e02643f3
C
9 PodInstance,
10 PodAttributes,
11
12 PodMethods
13} from './pod-interface'
14
15let Pod: Sequelize.Model<PodInstance, PodAttributes>
0aef76c4 16let toFormattedJSON: PodMethods.ToFormattedJSON
e02643f3
C
17let countAll: PodMethods.CountAll
18let incrementScores: PodMethods.IncrementScores
19let list: PodMethods.List
8a02bd04 20let listForApi: PodMethods.ListForApi
e02643f3
C
21let listAllIds: PodMethods.ListAllIds
22let listRandomPodIdsWithRequest: PodMethods.ListRandomPodIdsWithRequest
23let listBadPods: PodMethods.ListBadPods
24let load: PodMethods.Load
25let loadByHost: PodMethods.LoadByHost
26let removeAll: PodMethods.RemoveAll
27let updatePodsScore: PodMethods.UpdatePodsScore
28
127944aa
C
29export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
30 Pod = sequelize.define<PodInstance, PodAttributes>('Pod',
feb4bdfd
C
31 {
32 host: {
67bf9b96
C
33 type: DataTypes.STRING,
34 allowNull: false,
35 validate: {
075f16ca 36 isHost: value => {
65fcc311 37 const res = isHostValid(value)
67bf9b96
C
38 if (res === false) throw new Error('Host not valid.')
39 }
40 }
feb4bdfd
C
41 },
42 publicKey: {
67bf9b96
C
43 type: DataTypes.STRING(5000),
44 allowNull: false
feb4bdfd
C
45 },
46 score: {
47 type: DataTypes.INTEGER,
65fcc311 48 defaultValue: FRIEND_SCORE.BASE,
67bf9b96
C
49 allowNull: false,
50 validate: {
51 isInt: true,
65fcc311 52 max: FRIEND_SCORE.MAX
67bf9b96 53 }
4793c343
C
54 },
55 email: {
56 type: DataTypes.STRING(400),
ad4a8a1c
C
57 allowNull: false,
58 validate: {
59 isEmail: true
60 }
feb4bdfd 61 }
feb4bdfd
C
62 },
63 {
319d072e
C
64 indexes: [
65 {
5d67f289
C
66 fields: [ 'host' ],
67 unique: true
319d072e
C
68 },
69 {
70 fields: [ 'score' ]
71 }
e02643f3 72 ]
feb4bdfd
C
73 }
74 )
75
e02643f3
C
76 const classMethods = [
77 associate,
78
79 countAll,
80 incrementScores,
81 list,
8a02bd04 82 listForApi,
e02643f3
C
83 listAllIds,
84 listRandomPodIdsWithRequest,
85 listBadPods,
86 load,
87 loadByHost,
88 updatePodsScore,
89 removeAll
90 ]
0aef76c4 91 const instanceMethods = [ toFormattedJSON ]
e02643f3
C
92 addMethodsToModel(Pod, classMethods, instanceMethods)
93
feb4bdfd 94 return Pod
53572423
C
95}
96
53572423
C
97// ------------------------------ METHODS ------------------------------
98
0aef76c4 99toFormattedJSON = function (this: PodInstance) {
53572423 100 const json = {
feb4bdfd 101 id: this.id,
49abbbbe 102 host: this.host,
4793c343 103 email: this.email,
70c065d6 104 score: this.score as number,
feb4bdfd 105 createdAt: this.createdAt
53572423
C
106 }
107
108 return json
109}
110
a3ee6fa2
C
111// ------------------------------ Statics ------------------------------
112
feb4bdfd 113function associate (models) {
e02643f3 114 Pod.belongsToMany(models.Request, {
feb4bdfd
C
115 foreignKey: 'podId',
116 through: models.RequestToPod,
7920c273 117 onDelete: 'cascade'
feb4bdfd
C
118 })
119}
120
6fcd19ba
C
121countAll = function () {
122 return Pod.count()
9f10b292 123}
45239549 124
6fcd19ba 125incrementScores = function (ids: number[], value: number) {
feb4bdfd 126 const update = {
e02643f3 127 score: Sequelize.literal('score +' + value)
feb4bdfd
C
128 }
129
67bf9b96 130 const options = {
feb4bdfd
C
131 where: {
132 id: {
133 $in: ids
134 }
67bf9b96
C
135 },
136 // In this case score is a literal and not an integer so we do not validate it
137 validate: false
feb4bdfd
C
138 }
139
6fcd19ba 140 return Pod.update(update, options)
9f10b292 141}
45239549 142
6fcd19ba
C
143list = function () {
144 return Pod.findAll()
9f10b292 145}
8c308c2b 146
8a02bd04
C
147listForApi = function (start: number, count: number, sort: string) {
148 const query = {
149 offset: start,
150 limit: count,
151 order: [ getSort(sort) ]
152 }
153
154 return Pod.findAndCountAll(query).then(({ rows, count }) => {
155 return {
156 data: rows,
157 total: count
158 }
159 })
160}
161
6fcd19ba 162listAllIds = function (transaction: Sequelize.Transaction) {
556ddc31 163 const query = {
6fcd19ba
C
164 attributes: [ 'id' ],
165 transaction
feb4bdfd
C
166 }
167
6fcd19ba
C
168 return Pod.findAll(query).then(pods => {
169 return map(pods, 'id')
00057e85 170 })
528a9efa
C
171}
172
6fcd19ba
C
173listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, tableWithPodsJoins: string) {
174 return Pod.count().then(count => {
bd14d16a 175 // Optimization...
6fcd19ba 176 if (count === 0) return []
bd14d16a
C
177
178 let start = Math.floor(Math.random() * count) - limit
179 if (start < 0) start = 0
180
181 const query = {
182 attributes: [ 'id' ],
183 order: [
184 [ 'id', 'ASC' ]
185 ],
186 offset: start,
187 limit: limit,
188 where: {
189 id: {
556ddc31 190 $in: Sequelize.literal(`(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`)
bd14d16a
C
191 }
192 }
193 }
194
6fcd19ba
C
195 return Pod.findAll(query).then(pods => {
196 return map(pods, 'id')
bd14d16a
C
197 })
198 })
199}
200
6fcd19ba 201listBadPods = function () {
feb4bdfd
C
202 const query = {
203 where: {
204 score: { $lte: 0 }
205 }
206 }
207
6fcd19ba 208 return Pod.findAll(query)
9f10b292 209}
8c308c2b 210
6fcd19ba
C
211load = function (id: number) {
212 return Pod.findById(id)
9f10b292 213}
c45f7f84 214
6fcd19ba 215loadByHost = function (host: string) {
feb4bdfd
C
216 const query = {
217 where: {
218 host: host
219 }
220 }
221
6fcd19ba 222 return Pod.findOne(query)
9f10b292 223}
c45f7f84 224
6fcd19ba
C
225removeAll = function () {
226 return Pod.destroy()
a3ee6fa2 227}
9e167724 228
69818c93 229updatePodsScore = function (goodPods: number[], badPods: number[]) {
9e167724
C
230 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
231
232 if (goodPods.length !== 0) {
6fcd19ba 233 incrementScores(goodPods, PODS_SCORE.BONUS).catch(err => {
ad0997ad 234 logger.error('Cannot increment scores of good pods.', err)
9e167724
C
235 })
236 }
237
238 if (badPods.length !== 0) {
40298b02 239 incrementScores(badPods, PODS_SCORE.PENALTY)
6fcd19ba
C
240 .then(() => removeBadPods())
241 .catch(err => {
ad0997ad 242 if (err) logger.error('Cannot decrement scores of bad pods.', err)
6fcd19ba 243 })
9e167724
C
244 }
245}
246
247// ---------------------------------------------------------------------------
248
249// Remove pods with a score of 0 (too many requests where they were unreachable)
f5028693
C
250async function removeBadPods () {
251 try {
252 const pods = await listBadPods()
253
254 const podsRemovePromises = pods.map(pod => pod.destroy())
255 await Promise.all(podsRemovePromises)
256
257 const numberOfPodsRemoved = pods.length
258
259 if (numberOfPodsRemoved) {
260 logger.info('Removed %d pods.', numberOfPodsRemoved)
261 } else {
262 logger.info('No need to remove bad pods.')
263 }
264 } catch (err) {
265 logger.error('Cannot remove bad pods.', err)
266 }
9e167724 267}