PeerTube/server/lib/request/request-scheduler.ts

99 lines
2.6 KiB
TypeScript
Raw Normal View History

2017-06-10 15:15:25 -05:00
import * as Sequelize from 'sequelize'
2017-05-22 13:58:25 -05:00
import { database as db } from '../../initializers/database'
import { AbstractRequestScheduler } from './abstract-request-scheduler'
2017-05-15 15:22:03 -05:00
import { logger } from '../../helpers'
import { REQUESTS_LIMIT_PODS, REQUESTS_LIMIT_PER_POD } from '../../initializers'
import { RequestsGrouped } from '../../models'
2017-06-16 03:36:18 -05:00
import { RequestEndpoint } from '../../../shared'
2017-05-15 15:22:03 -05:00
2017-06-10 15:15:25 -05:00
export type RequestSchedulerOptions = {
type: string
2017-06-16 03:36:18 -05:00
endpoint: RequestEndpoint
2017-06-10 15:15:25 -05:00
data: Object
toIds: number[]
transaction: Sequelize.Transaction
}
class RequestScheduler extends AbstractRequestScheduler<RequestsGrouped> {
constructor () {
super()
// We limit the size of the requests
2017-05-15 15:22:03 -05:00
this.limitPods = REQUESTS_LIMIT_PODS
this.limitPerPod = REQUESTS_LIMIT_PER_POD
this.description = 'requests'
}
getRequestModel () {
return db.Request
}
getRequestToPodModel () {
return db.RequestToPod
}
buildRequestObjects (requestsGrouped: RequestsGrouped) {
const requestsToMakeGrouped = {}
Object.keys(requestsGrouped).forEach(toPodId => {
requestsGrouped[toPodId].forEach(data => {
const request = data.request
const pod = data.pod
const hashKey = toPodId + request.endpoint
if (!requestsToMakeGrouped[hashKey]) {
requestsToMakeGrouped[hashKey] = {
toPod: pod,
endpoint: request.endpoint,
ids: [], // request ids, to delete them from the DB in the future
datas: [] // requests data,
}
}
requestsToMakeGrouped[hashKey].ids.push(request.id)
requestsToMakeGrouped[hashKey].datas.push(request.request)
})
})
return requestsToMakeGrouped
}
createRequest ({ type, endpoint, data, toIds, transaction }: RequestSchedulerOptions) {
// If there are no destination pods abort
if (toIds.length === 0) return undefined
const createQuery = {
endpoint,
request: {
type: type,
data: data
}
}
2017-06-10 15:15:25 -05:00
const dbRequestOptions: Sequelize.CreateOptions = {
transaction
}
return db.Request.create(createQuery, dbRequestOptions)
.then(request => {
2017-07-07 09:57:28 -05:00
return request.setPods(toIds, dbRequestOptions)
})
}
// ---------------------------------------------------------------------------
afterRequestsHook () {
// Flush requests with no pod
this.getRequestModel().removeWithEmptyTo()
.catch(err => logger.error('Error when removing requests with no pods.', { error: err }))
}
}
2017-05-15 15:22:03 -05:00
// ---------------------------------------------------------------------------
export {
RequestScheduler
}