1 import * as Sequelize from 'sequelize'
3 import { database as db } from '../../initializers/database'
4 import { AbstractRequestScheduler } from './abstract-request-scheduler'
5 import { logger } from '../../helpers'
9 } from '../../initializers'
10 import { RequestEndpoint } from '../../../shared'
12 export type RequestSchedulerOptions = {
14 endpoint: RequestEndpoint
17 transaction: Sequelize.Transaction
20 class RequestScheduler extends AbstractRequestScheduler {
24 // We limit the size of the requests
25 this.limitPods = REQUESTS_LIMIT_PODS
26 this.limitPerPod = REQUESTS_LIMIT_PER_POD
28 this.description = 'requests'
35 getRequestToPodModel () {
36 return db.RequestToPod
39 buildRequestObjects (requests: { [ toPodId: number ]: any }) {
40 const requestsToMakeGrouped = {}
42 Object.keys(requests).forEach(toPodId => {
43 requests[toPodId].forEach(data => {
44 const request = data.request
46 const hashKey = toPodId + request.endpoint
48 if (!requestsToMakeGrouped[hashKey]) {
49 requestsToMakeGrouped[hashKey] = {
51 endpoint: request.endpoint,
52 ids: [], // request ids, to delete them from the DB in the future
53 datas: [] // requests data,
57 requestsToMakeGrouped[hashKey].ids.push(request.id)
58 requestsToMakeGrouped[hashKey].datas.push(request.request)
62 return requestsToMakeGrouped
65 createRequest ({ type, endpoint, data, toIds, transaction }: RequestSchedulerOptions, callback: (err: Error) => void) {
66 // TODO: check the setPods works
69 // If there are no destination pods abort
70 if (toIds.length === 0) return callback(null)
72 toIds.forEach(toPod => {
84 const dbRequestOptions: Sequelize.CreateOptions = {
88 return db.Request.create(createQuery, dbRequestOptions).asCallback((err, request) => {
89 if (err) return callback(err)
91 return request.setPods(podIds, dbRequestOptions).asCallback(callback)
95 // ---------------------------------------------------------------------------
97 afterRequestsHook () {
98 // Flush requests with no pod
99 this.getRequestModel().removeWithEmptyTo(err => {
100 if (err) logger.error('Error when removing requests with no pods.', { error: err })
105 // ---------------------------------------------------------------------------