Files
parcer/server/src/worker.ts

75 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-10-07 01:16:49 +05:30
import { Queue, Worker } from 'bullmq';
import IORedis from 'ioredis';
2024-10-07 01:19:04 +05:30
import logger from './logger';
2024-10-07 01:21:19 +05:30
import { handleRunRecording } from "./workflow-management/scheduler";
2024-10-26 01:01:13 +05:30
import Robot from './models/Robot';
2024-10-26 00:59:00 +05:30
import { computeNextRun } from './utils/schedule';
2024-10-07 01:16:49 +05:30
2024-10-22 16:59:04 +05:30
const connection = new IORedis({
2024-10-30 12:04:38 +05:30
host: process.env.REDIS_HOST,
2024-10-30 04:06:29 +05:30
port: process.env.REDIS_PORT ? parseInt(process.env.REDIS_PORT, 10) : 6379,
2024-10-22 16:59:04 +05:30
maxRetriesPerRequest: null,
2024-10-07 01:16:49 +05:30
});
2024-10-22 16:59:04 +05:30
connection.on('connect', () => {
console.log('Connected to Redis!');
});
connection.on('error', (err) => {
console.error('Redis connection error:', err);
});
2024-10-07 01:16:49 +05:30
const workflowQueue = new Queue('workflow', { connection });
2024-10-22 16:59:04 +05:30
const worker = new Worker('workflow', async job => {
const { runId, userId, id } = job.data;
2024-10-22 16:59:04 +05:30
try {
const result = await handleRunRecording(id, userId);
2024-10-07 01:21:39 +05:30
return result;
} catch (error) {
2024-10-22 16:59:04 +05:30
logger.error('Error running workflow:', error);
throw error;
}
}, { connection });
2024-10-07 01:16:49 +05:30
2024-10-22 16:59:04 +05:30
worker.on('completed', async (job: any) => {
logger.log(`info`, `Job ${job.id} completed for ${job.data.runId}`);
const robot = await Robot.findOne({ where: { 'recording_meta.id': job.data.id } });
2024-10-26 00:55:20 +05:30
if (robot) {
// Update `lastRunAt` to the current time
const lastRunAt = new Date();
2024-10-26 00:55:20 +05:30
// Compute the next run date
2024-10-26 01:01:13 +05:30
if (robot.schedule && robot.schedule.cronExpression && robot.schedule.timezone) {
const nextRunAt = computeNextRun(robot.schedule.cronExpression, robot.schedule.timezone) || undefined;
await robot.update({
schedule: {
...robot.schedule,
lastRunAt,
nextRunAt,
},
});
} else {
logger.error('Robot schedule, cronExpression, or timezone is missing.');
}
2024-10-26 00:55:20 +05:30
}
});
2024-10-07 01:16:49 +05:30
2024-10-22 16:59:04 +05:30
worker.on('failed', async (job: any, err) => {
logger.log(`error`, `Job ${job.id} failed for ${job.data.runId}:`, err);
});
2024-10-07 01:16:49 +05:30
2024-10-22 16:59:04 +05:30
console.log('Worker is running...');
2024-10-07 01:28:48 +05:30
2024-10-22 16:59:04 +05:30
async function jobCounts() {
const jobCounts = await workflowQueue.getJobCounts();
}
2024-10-07 01:16:49 +05:30
2024-10-22 16:59:04 +05:30
jobCounts();
2024-10-07 01:19:35 +05:30
2024-10-22 16:59:04 +05:30
process.on('SIGINT', () => {
console.log('Worker shutting down...');
process.exit();
});
2024-10-22 16:58:48 +05:30
2024-11-19 16:55:40 +05:30
export { workflowQueue, worker };