dragonflight/services/mam-api/src/routes/jobs.js

123 lines
2.8 KiB
JavaScript

import express from 'express';
import pool from '../db/pool.js';
import { requireAuth } from '../middleware/auth.js';
import { Queue } from 'bullmq';
import { v4 as uuidv4 } from 'uuid';
const router = express.Router();
router.use(requireAuth);
// Initialize BullMQ queue for conform jobs
const parseRedisUrl = (url) => {
try {
const parsed = new URL(url);
return { host: parsed.hostname, port: parseInt(parsed.port, 10) || 6379 };
} catch {
return { host: 'localhost', port: 6379 };
}
};
const conformQueue = new Queue('conform', {
connection: parseRedisUrl(process.env.REDIS_URL || 'redis://queue:6379'),
});
// GET / - List jobs
router.get('/', async (req, res, next) => {
try {
const { type, status, asset_id } = req.query;
let query = 'SELECT * FROM jobs WHERE 1=1';
const params = [];
let paramCount = 1;
if (type) {
query += ` AND type = $${paramCount++}`;
params.push(type);
}
if (status) {
query += ` AND status = $${paramCount++}`;
params.push(status);
}
if (asset_id) {
query += ` AND asset_id = $${paramCount++}`;
params.push(asset_id);
}
query += ' ORDER BY created_at DESC';
const result = await pool.query(query, params);
res.json(result.rows);
} catch (err) {
next(err);
}
});
// GET /:id - Single job with progress
router.get('/:id', async (req, res, next) => {
try {
const { id } = req.params;
const result = await pool.query(
'SELECT * FROM jobs WHERE id = $1',
[id]
);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Job not found' });
}
const job = result.rows[0];
res.json(job);
} catch (err) {
next(err);
}
});
// POST /conform - Submit conform job
router.post('/conform', async (req, res, next) => {
try {
const { edl, project_id, output_format } = req.body;
if (!edl || !project_id || !output_format) {
return res.status(400).json({
error: 'edl, project_id, and output_format are required',
});
}
const jobId = uuidv4();
// Create job record in database
const result = await pool.query(
`INSERT INTO jobs (id, type, status, project_id, metadata, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
RETURNING *`,
[
jobId,
'conform',
'pending',
project_id,
JSON.stringify({ edl, output_format }),
]
);
const job = result.rows[0];
// Add to BullMQ queue with camelCase keys matching the worker's destructuring
await conformQueue.add('conform-task', {
jobId,
edl,
projectId: project_id,
outputFormat: output_format,
});
res.status(201).json(job);
} catch (err) {
next(err);
}
});
export default router;