jobs.service.ts478 lines, 15 KB
| 1 | import Queue from "bull"; |
| 2 | import { AppDataSource } from "../config/database"; |
| 3 | import { Video } from "../entities/video.entity"; |
| 4 | import { Transcription } from "../entities/transcription.entity"; |
| 5 | import { Analysis } from "../entities/analysis.entity"; |
| 6 | import { User } from "../entities/user.entity"; |
| 7 | import { VideoService } from "./video.service"; |
| 8 | import { TranscriptionService } from "./transcription.service"; |
| 9 | import { unlink } from "fs/promises"; |
| 10 | import { AIService } from "./ai.service"; |
| 11 | import { AppError } from "../utils/errors"; |
| 12 | import logger from "../utils/logger"; |
| 13 | import { StatusCodes } from "http-status-codes/build/cjs"; |
| 14 | |
| 15 | interface TranscriptionJob { |
| 16 | url: string; |
| 17 | videoInfo?: any; |
| 18 | userId: string; |
| 19 | } |
| 20 | |
| 21 | export class JobsService { |
| 22 | private static transcriptionQueue: Queue.Queue; |
| 23 | private static readonly videoRepository = AppDataSource.getRepository(Video); |
| 24 | private static readonly transcriptionRepository = |
| 25 | AppDataSource.getRepository(Transcription); |
| 26 | private static readonly analysisRepository = |
| 27 | AppDataSource.getRepository(Analysis); |
| 28 | private static readonly userRepository = AppDataSource.getRepository(User); |
| 29 | |
| 30 | static getTranscriptionQueue() { |
| 31 | return this.transcriptionQueue; |
| 32 | } |
| 33 | |
| 34 | static async initialize() { |
| 35 | const redisConfig = process.env.REDIS_URL || { |
| 36 | host: process.env.REDIS_HOST || "localhost", |
| 37 | port: parseInt(process.env.REDIS_PORT || "6379"), |
| 38 | ...(process.env.NODE_ENV === "production" && { |
| 39 | tls: { |
| 40 | rejectUnauthorized: true, |
| 41 | }, |
| 42 | }), |
| 43 | }; |
| 44 | |
| 45 | this.transcriptionQueue = new Queue<TranscriptionJob>("transcription", { |
| 46 | redis: redisConfig, |
| 47 | defaultJobOptions: { |
| 48 | attempts: 3, |
| 49 | backoff: { |
| 50 | type: "exponential", |
| 51 | delay: 2000, |
| 52 | }, |
| 53 | removeOnComplete: { |
| 54 | age: 24 * 3600, // 24 hours |
| 55 | count: 100, |
| 56 | }, |
| 57 | removeOnFail: { |
| 58 | age: 24 * 3600, // 24 hours |
| 59 | }, |
| 60 | }, |
| 61 | // Add connection options to prevent ECONNRESET errors filling logs |
| 62 | limiter: { |
| 63 | max: 10, |
| 64 | duration: 1000, |
| 65 | }, |
| 66 | settings: { |
| 67 | retryProcessDelay: 5000, |
| 68 | lockDuration: 30000, |
| 69 | stalledInterval: 30000, |
| 70 | maxStalledCount: 2, |
| 71 | }, |
| 72 | }); |
| 73 | |
| 74 | // Add event listener for Redis connection issues |
| 75 | const client = this.transcriptionQueue.client; |
| 76 | client.on("error", (error) => {}); |
| 77 | |
| 78 | await this.setupQueueHandlers(); |
| 79 | } |
| 80 | |
| 81 | static async setupQueueHandlers() { |
| 82 | this.transcriptionQueue.process(async (job) => { |
| 83 | const { url, userId } = job.data; |
| 84 | let audioPath: string | undefined; |
| 85 | let video: Video | null = null; |
| 86 | |
| 87 | try { |
| 88 | // create video or update existing one |
| 89 | video = await this.videoRepository.findOne({ where: { url } }); |
| 90 | if (!video) { |
| 91 | video = new Video(); |
| 92 | video.url = url; |
| 93 | video.status = "processing"; |
| 94 | video.user = { id: userId } as User; |
| 95 | } |
| 96 | |
| 97 | job.progress(10); |
| 98 | // get video info if not already present |
| 99 | const videoInfo = |
| 100 | job.data.videoInfo || (await VideoService.getVideoInfo(url)); |
| 101 | |
| 102 | // update video information |
| 103 | Object.assign(video, { |
| 104 | title: videoInfo.title, |
| 105 | description: videoInfo.description, |
| 106 | duration: videoInfo.duration, |
| 107 | author: videoInfo.author, |
| 108 | thumbnail: videoInfo.thumbnailUrl || videoInfo.thumbnail, |
| 109 | }); |
| 110 | await this.videoRepository.save(video); |
| 111 | job.progress(20); |
| 112 | // download audio |
| 113 | audioPath = await VideoService.downloadAudio(url); |
| 114 | |
| 115 | job.progress(40); |
| 116 | // transcribe audio |
| 117 | const transcriptionResult = await TranscriptionService.transcribe( |
| 118 | audioPath |
| 119 | ); |
| 120 | |
| 121 | // check for existing transcription and update or create new one |
| 122 | let transcription = await this.transcriptionRepository.findOne({ |
| 123 | where: { video: { id: video.id } }, |
| 124 | }); |
| 125 | |
| 126 | if (transcription) { |
| 127 | // update existing transcription |
| 128 | transcription.text = transcriptionResult.text; |
| 129 | transcription.confidence = transcriptionResult.confidence; |
| 130 | transcription.isMusic = transcriptionResult.isMusic || false; |
| 131 | transcription.audioPath = audioPath; |
| 132 | transcription.wordTimestamps = |
| 133 | transcriptionResult.wordTimestamps || []; |
| 134 | } else { |
| 135 | // create new transcription |
| 136 | transcription = new Transcription(); |
| 137 | transcription.video = video; |
| 138 | transcription.text = transcriptionResult.text; |
| 139 | transcription.confidence = transcriptionResult.confidence; |
| 140 | transcription.isMusic = transcriptionResult.isMusic || false; |
| 141 | transcription.audioPath = audioPath; |
| 142 | transcription.wordTimestamps = |
| 143 | transcriptionResult.wordTimestamps || []; |
| 144 | } |
| 145 | await this.transcriptionRepository.save(transcription); |
| 146 | |
| 147 | // Clean up local audio file AFTER transcription is saved |
| 148 | // GCS file is cleaned up within TranscriptionService |
| 149 | if (audioPath) { |
| 150 | logger.info(`Attempting to delete local audio file: ${audioPath}`); |
| 151 | await unlink(audioPath).catch((err: any) => |
| 152 | logger.warn( |
| 153 | `Failed to delete local audio file ${audioPath}: ${err.message}` |
| 154 | ) |
| 155 | ); |
| 156 | // Optionally clear the audioPath field in transcription after deletion |
| 157 | // transcription.audioPath = null; |
| 158 | // await this.transcriptionRepository.save(transcription); |
| 159 | } |
| 160 | job.progress(70); |
| 161 | |
| 162 | // dont proceed with AI analysis if it's a music video |
| 163 | if (transcriptionResult.isMusic) { |
| 164 | video.status = "completed"; |
| 165 | await this.videoRepository.save(video); |
| 166 | return { |
| 167 | videoInfo, |
| 168 | transcription: transcriptionResult, |
| 169 | status: "completed", |
| 170 | }; |
| 171 | } |
| 172 | |
| 173 | // analyze video |
| 174 | const analysisResult = await AIService.analyzeTranscription( |
| 175 | transcriptionResult.text, |
| 176 | videoInfo |
| 177 | ); |
| 178 | |
| 179 | // check for existing analysis and update or create new one |
| 180 | let analysis = await this.analysisRepository.findOne({ |
| 181 | where: { video: { id: video.id } }, |
| 182 | }); |
| 183 | |
| 184 | if (analysis) { |
| 185 | // Update existing analysis, explicitly including chapters |
| 186 | analysis.summary = analysisResult.summary; |
| 187 | analysis.keyPoints = analysisResult.keyPoints || []; |
| 188 | analysis.sentiment = analysisResult.sentiment; |
| 189 | analysis.topics = analysisResult.topics || []; |
| 190 | analysis.suggestedTags = analysisResult.suggestedTags || []; |
| 191 | analysis.chapters = analysisResult.chapters || []; |
| 192 | } else { |
| 193 | // Create new analysis |
| 194 | analysis = new Analysis(); |
| 195 | analysis.video = video; |
| 196 | analysis.summary = analysisResult.summary; |
| 197 | analysis.keyPoints = analysisResult.keyPoints || []; |
| 198 | analysis.sentiment = analysisResult.sentiment; |
| 199 | analysis.topics = analysisResult.topics || []; |
| 200 | analysis.suggestedTags = analysisResult.suggestedTags || []; |
| 201 | analysis.chapters = analysisResult.chapters || []; |
| 202 | } |
| 203 | await this.analysisRepository.save(analysis); |
| 204 | |
| 205 | video.status = "completed"; |
| 206 | await this.videoRepository.save(video); |
| 207 | |
| 208 | job.progress(100); |
| 209 | return { |
| 210 | videoInfo, |
| 211 | transcription: transcriptionResult, |
| 212 | analysis: analysisResult, |
| 213 | status: "completed", |
| 214 | }; |
| 215 | } catch (error) { |
| 216 | // Clean up audio file in case of error |
| 217 | if (audioPath) { |
| 218 | await unlink(audioPath).catch(() => {}); |
| 219 | } |
| 220 | |
| 221 | // Update video status to failed |
| 222 | if (video) { |
| 223 | video.status = "failed"; |
| 224 | await this.videoRepository.save(video); |
| 225 | } |
| 226 | |
| 227 | logger.error("Job processing error:", error); |
| 228 | |
| 229 | if ( |
| 230 | error instanceof AppError && |
| 231 | (error.message.includes("No speech detected") || |
| 232 | error.message.includes("This video is private") || |
| 233 | error.message.includes("This video is no longer available")) |
| 234 | ) { |
| 235 | return { |
| 236 | error: error.message, |
| 237 | status: "failed", |
| 238 | final: true, |
| 239 | }; |
| 240 | } |
| 241 | |
| 242 | throw error; |
| 243 | } |
| 244 | }); |
| 245 | |
| 246 | this.transcriptionQueue.on("completed", async (job, result) => { |
| 247 | try { |
| 248 | const user = await this.userRepository.findOne({ |
| 249 | where: { id: job.data.userId }, |
| 250 | }); |
| 251 | |
| 252 | if (user && result.videoInfo) { |
| 253 | //TODO: send a job completion email |
| 254 | } |
| 255 | } catch (error) { |
| 256 | logger.error("Error sending job completion email:", error); |
| 257 | } |
| 258 | }); |
| 259 | |
| 260 | this.transcriptionQueue.on("failed", async (job, error) => { |
| 261 | logger.error(`Job ${job.id} failed: ${error}`); |
| 262 | }); |
| 263 | |
| 264 | this.transcriptionQueue.on("error", (error) => { |
| 265 | logger.error("Transcription queue error:", error); |
| 266 | }); |
| 267 | |
| 268 | // clean up stuck jobs |
| 269 | this.transcriptionQueue.clean(24 * 3600 * 1000, "delayed"); |
| 270 | this.transcriptionQueue.clean(24 * 3600 * 1000, "wait"); |
| 271 | this.transcriptionQueue.clean(24 * 3600 * 1000, "active"); |
| 272 | } |
| 273 | |
| 274 | static async addTranscriptionJob(url: string, videoInfo?: any, user?: any) { |
| 275 | let video = await this.videoRepository.findOne({ where: { url } }); |
| 276 | if (!video) { |
| 277 | video = new Video(); |
| 278 | video.url = url; |
| 279 | video.status = "pending"; |
| 280 | video.user = user; |
| 281 | if (videoInfo) { |
| 282 | Object.assign(video, { |
| 283 | title: videoInfo.title, |
| 284 | description: videoInfo.description, |
| 285 | duration: videoInfo.duration, |
| 286 | author: videoInfo.author, |
| 287 | thumbnail: videoInfo.thumbnailUrl || videoInfo.thumbnail, |
| 288 | }); |
| 289 | } |
| 290 | |
| 291 | await this.videoRepository.save(video); |
| 292 | } |
| 293 | |
| 294 | const job = await this.transcriptionQueue.add({ |
| 295 | url, |
| 296 | videoInfo, |
| 297 | userId: user.id, |
| 298 | }); |
| 299 | |
| 300 | return { jobId: job.id }; |
| 301 | } |
| 302 | |
| 303 | static async getJobStatus(jobId: string) { |
| 304 | const job = await this.transcriptionQueue.getJob(jobId); |
| 305 | if (!job) { |
| 306 | throw new AppError(StatusCodes.NOT_FOUND, "Job not found"); |
| 307 | } |
| 308 | |
| 309 | const state = await job.getState(); |
| 310 | const progress = job.progress(); |
| 311 | const result = job.returnvalue; |
| 312 | const failedReason = job.failedReason; |
| 313 | const attempts = job.attemptsMade; |
| 314 | |
| 315 | //Get video status from database if available |
| 316 | let videoStatus = null; |
| 317 | if (result?.videoInfo?.url) { |
| 318 | const video = await this.videoRepository.findOne({ |
| 319 | where: { url: result.videoInfo.url }, |
| 320 | relations: ["transcription", "analysis"], |
| 321 | }); |
| 322 | if (video) { |
| 323 | videoStatus = { |
| 324 | id: video.id, |
| 325 | status: video.status, |
| 326 | hasTranscription: !!video.transcription, |
| 327 | hasAnalysis: !!video.analysis, |
| 328 | }; |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | return { |
| 333 | id: job.id, |
| 334 | state, |
| 335 | progress, |
| 336 | result, |
| 337 | failedReason, |
| 338 | attempts, |
| 339 | thumbnail: result?.videoInfo?.thumbnail || null, |
| 340 | videoStatus, |
| 341 | final: result?.final || state === "completed" || attempts >= 3, |
| 342 | }; |
| 343 | } |
| 344 | |
| 345 | static async getAllJobs(userId: string) { |
| 346 | // get jobs in different states |
| 347 | const activeJobs = await this.transcriptionQueue.getActive(); |
| 348 | const waitingJobs = await this.transcriptionQueue.getWaiting(); |
| 349 | const completedJobs = await this.transcriptionQueue.getCompleted(); |
| 350 | const delayedJobs = await this.transcriptionQueue.getDelayed(); |
| 351 | const failedJobs = await this.transcriptionQueue.getFailed(); |
| 352 | |
| 353 | // combine all jobs and sort by createdAt |
| 354 | const jobs = [ |
| 355 | ...activeJobs, |
| 356 | ...waitingJobs, |
| 357 | ...completedJobs, |
| 358 | ...delayedJobs, |
| 359 | ...failedJobs, |
| 360 | ]; |
| 361 | |
| 362 | // filter jobs by user ID and sort by timestamp (most recent first) |
| 363 | const userJobs = jobs.filter((job) => job.data.userId === userId); |
| 364 | userJobs.sort((a, b) => b.timestamp - a.timestamp); |
| 365 | |
| 366 | const jobDetails = await Promise.all( |
| 367 | userJobs.map(async (job) => { |
| 368 | const state = await job.getState(); |
| 369 | return { |
| 370 | id: job.id, |
| 371 | state, |
| 372 | progress: job.progress(), |
| 373 | data: job.data, |
| 374 | timestamp: job.timestamp, |
| 375 | processedOn: job.processedOn, |
| 376 | finishedOn: job.finishedOn, |
| 377 | attemptsMade: job.attemptsMade, |
| 378 | result: job.returnvalue, |
| 379 | failedReason: job.failedReason, |
| 380 | thumbnail: job.data?.videoInfo?.thumbnail || null, |
| 381 | duration: job.data?.videoInfo?.duration || null, |
| 382 | // get video status if available |
| 383 | videoStatus: job.data?.url |
| 384 | ? await this.getVideoStatus(job.data.url) |
| 385 | : null, |
| 386 | }; |
| 387 | }) |
| 388 | ); |
| 389 | |
| 390 | return jobDetails; |
| 391 | } |
| 392 | |
| 393 | // *** NEW METHOD: cancelJob *** |
| 394 | static async cancelJob(jobId: string): Promise<boolean> { |
| 395 | const job = await this.transcriptionQueue.getJob(jobId); |
| 396 | if (!job) { |
| 397 | logger.warn(`Attempted to cancel non-existent job: ${jobId}`); |
| 398 | throw new AppError(StatusCodes.NOT_FOUND, "Job not found"); |
| 399 | } |
| 400 | |
| 401 | const state = await job.getState(); |
| 402 | logger.info(`Attempting to cancel job ${jobId} in state: ${state}`); |
| 403 | |
| 404 | // Only allow cancellation for jobs not already finished |
| 405 | if (state === "completed" || state === "failed") { |
| 406 | logger.warn(`Job ${jobId} cannot be cancelled, state is ${state}`); |
| 407 | throw new AppError( |
| 408 | StatusCodes.BAD_REQUEST, |
| 409 | `Job is already ${state} and cannot be cancelled.` |
| 410 | ); |
| 411 | } |
| 412 | |
| 413 | try { |
| 414 | // For BullMQ, remove() is the way to prevent future processing/retries |
| 415 | // For active jobs, this won't stop current execution but prevents retries. |
| 416 | // Consider adding logic within the processor for graceful shutdown if needed. |
| 417 | await job.remove(); |
| 418 | logger.info(`Job ${jobId} removed (cancelled) successfully.`); |
| 419 | |
| 420 | // Optionally update the associated Video status in DB |
| 421 | try { |
| 422 | if (job.data.url) { |
| 423 | const video = await this.videoRepository.findOne({ |
| 424 | where: { url: job.data.url }, |
| 425 | }); |
| 426 | if ( |
| 427 | video && |
| 428 | video.status !== "completed" && |
| 429 | video.status !== "failed" |
| 430 | ) { |
| 431 | // Update status to 'failed' when cancelled |
| 432 | video.status = "failed"; |
| 433 | await this.videoRepository.save(video); |
| 434 | logger.info( |
| 435 | `Video status updated to failed for cancelled job ${jobId}` |
| 436 | ); |
| 437 | } |
| 438 | } |
| 439 | } catch (dbError) { |
| 440 | logger.error( |
| 441 | `Failed to update video status to failed for job ${jobId}`, |
| 442 | dbError |
| 443 | ); |
| 444 | // Don't fail the whole cancellation if DB update fails |
| 445 | } |
| 446 | |
| 447 | return true; |
| 448 | } catch (error: any) { |
| 449 | logger.error( |
| 450 | `Failed to remove (cancel) job ${jobId}: ${error.message}`, |
| 451 | error |
| 452 | ); |
| 453 | throw new AppError( |
| 454 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 455 | "Failed to cancel job" |
| 456 | ); |
| 457 | } |
| 458 | } |
| 459 | // *** END NEW METHOD *** |
| 460 | |
| 461 | // helper method to get video status |
| 462 | private static async getVideoStatus(url: string) { |
| 463 | const video = await this.videoRepository.findOne({ |
| 464 | where: { url }, |
| 465 | relations: ["transcription", "analysis"], |
| 466 | }); |
| 467 | if (!video) return null; |
| 468 | |
| 469 | return { |
| 470 | id: video.id, |
| 471 | status: video.status, |
| 472 | hasTranscription: !!video.transcription, |
| 473 | hasAnalysis: !!video.analysis, |
| 474 | title: video.title, |
| 475 | thumbnail: video.thumbnail, |
| 476 | }; |
| 477 | } |
| 478 | } |