1 import express from 'express'
2 import { HttpStatusCode, Job, JobState, JobType, ResultList, UserRight } from '@shared/models'
3 import { isArray } from '../../helpers/custom-validators/misc'
4 import { JobQueue } from '../../lib/job-queue'
11 paginationValidatorBuilder,
14 } from '../../middlewares'
15 import { listJobsValidator } from '../../middlewares/validators/jobs'
17 const jobsRouter = express.Router()
19 jobsRouter.post('/pause',
21 ensureUserHasRight(UserRight.MANAGE_JOBS),
22 asyncMiddleware(pauseJobQueue)
25 jobsRouter.post('/resume',
27 ensureUserHasRight(UserRight.MANAGE_JOBS),
28 asyncMiddleware(resumeJobQueue)
31 jobsRouter.get('/:state?',
32 openapiOperationDoc({ operationId: 'getJobs' }),
34 ensureUserHasRight(UserRight.MANAGE_JOBS),
35 paginationValidatorBuilder([ 'jobs' ]),
40 asyncMiddleware(listJobs)
43 // ---------------------------------------------------------------------------
49 // ---------------------------------------------------------------------------
51 async function pauseJobQueue (req: express.Request, res: express.Response) {
52 await JobQueue.Instance.pause()
54 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
57 async function resumeJobQueue (req: express.Request, res: express.Response) {
58 await JobQueue.Instance.resume()
60 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
63 async function listJobs (req: express.Request, res: express.Response) {
64 const state = req.params.state as JobState
65 const asc = req.query.sort === 'createdAt'
66 const jobType = req.query.jobType
68 const jobs = await JobQueue.Instance.listForApi({
70 start: req.query.start,
71 count: req.query.count,
75 const total = await JobQueue.Instance.count(state, jobType)
77 const result: ResultList<Job> = {
79 data: await Promise.all(jobs.map(j => formatJob(j, state)))
82 return res.json(result)
85 async function formatJob (job: any, state?: JobState): Promise<Job> {
86 const error = isArray(job.stacktrace) && job.stacktrace.length !== 0
92 state: state || await job.getState(),
93 type: job.queue.name as JobType,
95 progress: await job.progress(),
96 priority: job.opts.priority,
98 createdAt: new Date(job.timestamp),
99 finishedOn: new Date(job.finishedOn),
100 processedOn: new Date(job.processedOn)