1 import { isEmpty } from 'lodash'
2 import * as Promise from 'bluebird'
4 import { database as db } from '../../initializers/database'
5 import { logger, makeSecureRequest } from '../../helpers'
6 import { AbstractRequestClass, AbstractRequestToPodClass, PodInstance } from '../../models'
11 } from '../../initializers'
13 abstract class AbstractRequestScheduler <T> {
14 requestInterval: number
18 protected lastRequestTimestamp: number
19 protected timer: NodeJS.Timer
20 protected description: string
23 this.lastRequestTimestamp = 0
25 this.requestInterval = REQUESTS_INTERVAL
28 abstract getRequestModel (): AbstractRequestClass<T>
29 abstract getRequestToPodModel (): AbstractRequestToPodClass
30 abstract buildRequestObjects (requestsGrouped: T): {}
33 logger.info('Requests scheduler activated.')
34 this.lastRequestTimestamp = Date.now()
36 this.timer = setInterval(() => {
37 this.lastRequestTimestamp = Date.now()
39 }, this.requestInterval)
43 logger.info('Requests scheduler deactivated.')
44 clearInterval(this.timer)
49 logger.info('Force requests scheduler sending.')
53 remainingMilliSeconds () {
54 if (this.timer === null) return -1
56 return REQUESTS_INTERVAL - (Date.now() - this.lastRequestTimestamp)
59 remainingRequestsCount () {
60 return this.getRequestModel().countTotalRequests()
64 return this.getRequestModel().removeAll()
67 // ---------------------------------------------------------------------------
69 // Make a requests to friends of a certain type
70 protected makeRequest (toPod: PodInstance, requestEndpoint: string, requestsToMake: Object) {
73 method: 'POST' as 'POST',
74 path: '/api/' + API_VERSION + '/remote/' + requestEndpoint,
75 data: requestsToMake // Requests we need to make
78 // Make multiple retry requests to all of pods
79 // The function fire some useful callbacks
80 return makeSecureRequest(params)
81 .then(({ response, body }) => {
82 if (response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204) {
83 throw new Error('Status code not 20x : ' + response.statusCode)
87 logger.error('Error sending secure request to %s pod.', toPod.host, { error: err })
93 // Make all the requests of the scheduler
94 protected makeRequests () {
95 return this.getRequestModel().listWithLimitAndRandom(this.limitPods, this.limitPerPod)
96 .then((requestsGrouped: T) => {
97 // We want to group requests by destinations pod and endpoint
98 const requestsToMake = this.buildRequestObjects(requestsGrouped)
100 // If there are no requests, abort
101 if (isEmpty(requestsToMake) === true) {
102 logger.info('No "%s" to make.', this.description)
103 return { goodPods: [], badPods: [] }
106 logger.info('Making "%s" to friends.', this.description)
111 return Promise.map(Object.keys(requestsToMake), hashKey => {
112 const requestToMake = requestsToMake[hashKey]
113 const toPod: PodInstance = requestToMake.toPod
115 return this.makeRequest(toPod, requestToMake.endpoint, requestToMake.datas)
117 logger.debug('Removing requests for pod %s.', requestToMake.toPod.id, { requestsIds: requestToMake.ids })
118 goodPods.push(requestToMake.toPod.id)
120 this.afterRequestHook()
122 // Remove the pod id of these request ids
123 return this.getRequestToPodModel().removeByRequestIdsAndPod(requestToMake.ids, requestToMake.toPod.id)
126 badPods.push(requestToMake.toPod.id)
127 logger.info('Cannot make request to %s.', toPod.host, { error: err })
129 }, { concurrency: REQUESTS_IN_PARALLEL }).then(() => ({ goodPods, badPods }))
131 .then(({ goodPods, badPods }) => {
132 this.afterRequestsHook()
134 // All the requests were made, we update the pods score
135 return db.Pod.updatePodsScore(goodPods, badPods)
137 .catch(err => logger.error('Cannot get the list of "%s".', this.description, { error: err.stack }))
140 protected afterRequestHook () {
141 // Nothing to do, let children reimplement it
144 protected afterRequestsHook () {
145 // Nothing to do, let children reimplement it
149 // ---------------------------------------------------------------------------
152 AbstractRequestScheduler