Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | import { Injectable, BadRequestException, NotFoundException, Logger, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { InjectQueue } from '@nestjs/bullmq'; import { Queue } from 'bullmq'; import { ScheduledJobDefinition, JobExecution, QueueConfiguration, } from './schemas/scheduler.schema'; import { CacheService } from '../cache/cache.service'; import { SchedulerRegistry } from '@nestjs/schedule'; import { CronJob } from 'cron'; export type JobHandler = (payload: any) => Promise<any>; @Injectable() export class JobSchedulerService { private readonly logger = new Logger(JobSchedulerService.name); private readonly handlers = new Map<string, JobHandler>(); constructor( @InjectModel(ScheduledJobDefinition.name) private readonly defModel: Model<ScheduledJobDefinition>, @InjectModel(JobExecution.name) private readonly executionModel: Model<JobExecution>, @InjectModel(QueueConfiguration.name) private readonly queueConfigModel: Model<QueueConfiguration>, @InjectQueue('scheduler.jobs') private readonly schedulerQueue: Queue, private readonly cacheService: CacheService, private readonly schedulerRegistry: SchedulerRegistry, ) {} async onApplicationBootstrap() { await this.syncScheduledJobs(); } async syncScheduledJobs() { this.logger.log('Syncing scheduled jobs with orchestrator...'); const definitions = await this.defModel.find({ isActive: true }).exec(); // Remove existing dynamic crons const existingJobs = this.schedulerRegistry.getCronJobs(); existingJobs.forEach((job, name) => { if (name.startsWith('dyn-job-')) { this.schedulerRegistry.deleteCronJob(name); } }); for (const def of definitions) { this.scheduleCronJob(def); } } private scheduleCronJob(def: ScheduledJobDefinition) { try { const job = new CronJob(def.cron, async () => { this.logger.log(`Cron triggered for job: ${def.name}`); await this.triggerJob(def.name).catch((e) => { this.logger.error( `Failed to trigger scheduled job ${def.name}: ${e.message}`, ); }); }); this.schedulerRegistry.addCronJob(`dyn-job-${def.name}`, job); job.start(); this.logger.log( `Scheduled cron job ${def.name} with pattern ${def.cron}`, ); } catch (e) { this.logger.error( `Failed to schedule cron job ${def.name}: ${e.message}`, ); } } registerHandler(name: string, handler: JobHandler) { this.handlers.set(name, handler); this.logger.log(`Registered background job handler for: ${name}`); } async acquireLock(lockKey: string, ttlMs: number): Promise<boolean> { const ttlSeconds = Math.max(1, Math.ceil(ttlMs / 1000)); return this.cacheService.acquireLock(lockKey, ttlSeconds); } async releaseLock(lockKey: string): Promise<void> { await this.cacheService.releaseLock(lockKey); } async createJobDefinition(params: { name: string; cron: string; payload?: any; timeoutMs?: number; retries?: number; }): Promise<any> { const doc = await this.defModel.create(params); this.scheduleCronJob(doc); return doc; } async getDefinitions(): Promise<any[]> { return this.defModel.find().lean().exec(); } async triggerJob(name: string): Promise<any> { const def = await this.defModel .findOne({ name, isActive: true }) .lean() .exec(); if (!def) throw new NotFoundException( `Active job definition not found for name: ${name}`, ); const run = await this.executionModel.create({ jobName: name, queueName: 'scheduler.jobs', status: 'PENDING', }); await this.schedulerQueue.add( name, { executionId: (run as any)._id.toString(), payload: def.payload, }, { attempts: def.retries || 3, }, ); return { executionId: (run as any)._id.toString(), status: 'PENDING' }; } async processJob( jobName: string, jobData: { executionId: string; payload: any }, ): Promise<void> { const lockKey = `lock:job:${jobName}`; const acquired = await this.acquireLock(lockKey, 300000); // 5 min SLA lock if (!acquired) { this.logger.warn(`Job lock active for: ${jobName}. Skipping execution.`); return; } const run = await this.executionModel.findById(jobData.executionId).exec(); if (!run) { await this.releaseLock(lockKey); return; } const handler = this.handlers.get(jobName); if (!handler) { run.status = 'FAILED'; run.failedReason = `No handler registered for job: ${jobName}`; await run.save(); await this.releaseLock(lockKey); return; } const startTime = Date.now(); try { run.status = 'RUNNING'; run.startedAt = new Date(); await run.save(); await handler(jobData.payload); run.status = 'COMPLETED'; run.progress = 100; run.endedAt = new Date(); await run.save(); } catch (err: any) { run.status = 'FAILED'; run.failedReason = err.message || 'Unknown error'; run.endedAt = new Date(); await run.save(); } finally { await this.releaseLock(lockKey); } } async getExecutions(page = 1, limit = 20): Promise<any> { const skip = (page - 1) * limit; const [data, total] = await Promise.all([ this.executionModel .find() .skip(skip) .limit(limit) .sort({ createdAt: -1 }) .lean() .exec(), this.executionModel.countDocuments().exec(), ]); return { data: data.map((d) => ({ ...d, id: (d as any)._id.toString() })), meta: { total, page, limit, totalPages: Math.ceil(total / limit) }, }; } async getQueueHealth(): Promise<any> { // Health reports queue specs const counts = await this.schedulerQueue.getJobCounts(); return { name: 'scheduler.jobs', counts, isHealthy: true, }; } } export class JobHandlerRegistry { constructor(private readonly scheduler: JobSchedulerService) {} register(name: string, handler: JobHandler) { this.scheduler.registerHandler(name, handler); } } |