Server: request scheduler refractoring
[oweals/peertube.git] / server / lib / base-request-scheduler.js
1 'use strict'
2
3 const eachLimit = require('async/eachLimit')
4
5 const constants = require('../initializers/constants')
6 const db = require('../initializers/database')
7 const logger = require('../helpers/logger')
8 const requests = require('../helpers/requests')
9
10 module.exports = class BaseRequestScheduler {
11
12   constructor (options) {
13     this.lastRequestTimestamp = 0
14     this.timer = null
15   }
16
17   activate () {
18     logger.info('Requests scheduler activated.')
19     this.lastRequestTimestamp = Date.now()
20
21     this.timer = setInterval(() => {
22       this.lastRequestTimestamp = Date.now()
23       this.makeRequests()
24     }, constants.REQUESTS_INTERVAL)
25   }
26
27   deactivate () {
28     logger.info('Requests scheduler deactivated.')
29     clearInterval(this.timer)
30     this.timer = null
31   }
32
33   forceSend () {
34     logger.info('Force requests scheduler sending.')
35     this.makeRequests()
36   }
37
38   remainingMilliSeconds () {
39     if (this.timer === null) return -1
40
41     return constants.REQUESTS_INTERVAL - (Date.now() - this.lastRequestTimestamp)
42   }
43
44   // ---------------------------------------------------------------------------
45
46   // Make a requests to friends of a certain type
47   makeRequest (toPod, requestEndpoint, requestsToMake, callback) {
48     if (!callback) callback = function () {}
49
50     const params = {
51       toPod: toPod,
52       sign: true, // Prove our identity
53       method: 'POST',
54       path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
55       data: requestsToMake // Requests we need to make
56     }
57
58     // Make multiple retry requests to all of pods
59     // The function fire some useful callbacks
60     requests.makeSecureRequest(params, (err, res) => {
61       if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
62         err = err ? err.message : 'Status code not 20x : ' + res.statusCode
63         logger.error('Error sending secure request to %s pod.', toPod.host, { error: err })
64
65         return callback(false)
66       }
67
68       return callback(true)
69     })
70   }
71
72     // Make all the requests of the scheduler
73   makeRequests () {
74     this.getRequestModel().listWithLimitAndRandom(this.limitPods, this.limitPerPod, (err, requests) => {
75       if (err) {
76         logger.error('Cannot get the list of "%s".', this.description, { err: err })
77         return // Abort
78       }
79
80       // If there are no requests, abort
81       if (requests.length === 0) {
82         logger.info('No "%s" to make.', this.description)
83         return
84       }
85
86       // We want to group requests by destinations pod and endpoint
87       const requestsToMakeGrouped = this.buildRequestObjects(requests)
88
89       logger.info('Making "%s" to friends.', this.description)
90
91       const goodPods = []
92       const badPods = []
93
94       eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, (hashKey, callbackEach) => {
95         const requestToMake = requestsToMakeGrouped[hashKey]
96         const toPod = requestToMake.toPod
97
98         this.makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, (success) => {
99           if (success === false) {
100             badPods.push(requestToMake.toPod.id)
101             return callbackEach()
102           }
103
104           logger.debug('Removing requests for pod %s.', requestToMake.toPod.id, { requestsIds: requestToMake.ids })
105           goodPods.push(requestToMake.toPod.id)
106
107           // Remove the pod id of these request ids
108           this.getRequestToPodModel().removeByRequestIdsAndPod(requestToMake.ids, requestToMake.toPod.id, callbackEach)
109
110           this.afterRequestHook()
111         })
112       }, () => {
113         // All the requests were made, we update the pods score
114         db.Pod.updatePodsScore(goodPods, badPods)
115
116         this.afterRequestsHook()
117       })
118     })
119   }
120
121   flush (callback) {
122     this.getRequestModel().removeAll(callback)
123   }
124
125   afterRequestHook () {
126    // Nothing to do, let children reimplement it
127   }
128
129   afterRequestsHook () {
130    // Nothing to do, let children reimplement it
131   }
132 }