GenerateExamPdfJob.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\Paper;
  4. use App\Services\ExamPdfExportService;
  5. use App\Services\QuestionBankService;
  6. use App\Services\PaperPayloadService;
  7. use App\Services\TaskManager;
  8. use Illuminate\Bus\Queueable;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  10. use Illuminate\Foundation\Bus\Dispatchable;
  11. use Illuminate\Queue\InteractsWithQueue;
  12. use Illuminate\Queue\SerializesModels;
  13. use Illuminate\Support\Facades\Log;
  14. class GenerateExamPdfJob implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public string $taskId;
  18. public string $paperId;
  19. /**
  20. * 【优化】增加任务超时时间,给Chrome充足渲染时间
  21. */
  22. public $timeout = 180; // 从90秒增加到180秒(3分钟)
  23. /**
  24. * 【保持】重试次数,配合并发控制
  25. */
  26. public $tries = 3;
  27. public function __construct(string $taskId, string $paperId)
  28. {
  29. $this->taskId = $taskId;
  30. $this->paperId = $paperId;
  31. $this->onQueue('pdf_generation');
  32. }
  33. public function handle(
  34. ExamPdfExportService $pdfExportService,
  35. QuestionBankService $questionBankService,
  36. PaperPayloadService $paperPayloadService,
  37. TaskManager $taskManager
  38. ): void {
  39. $jobId = $this->uuid ?? 'unknown';
  40. $startTime = microtime(true);
  41. try {
  42. Log::info('开始处理PDF生成队列任务', [
  43. 'job_id' => $jobId,
  44. 'task_id' => $this->taskId,
  45. 'paper_id' => $this->paperId,
  46. 'attempt' => $this->attempts(),
  47. ]);
  48. // 【并发控制】检查当前并发数量
  49. if (!$this->acquireLock()) {
  50. $waitTime = rand(5, 15); // 等待5-15秒后重试
  51. Log::warning('GenerateExamPdfJob: 并发限制,等待后重试', [
  52. 'job_id' => $jobId,
  53. 'wait_time' => $waitTime,
  54. 'current_concurrent' => $this->getConcurrentCount()
  55. ]);
  56. // 释放队列槽位,等待后重试
  57. $this->release($waitTime);
  58. return;
  59. }
  60. Log::info('GenerateExamPdfJob: 获得执行权限', [
  61. 'job_id' => $jobId,
  62. 'concurrent_count' => $this->getConcurrentCount()
  63. ]);
  64. // 【新增】快速检查:如果任务已完成,直接跳过
  65. $task = $taskManager->getTaskStatus($this->taskId);
  66. if ($task && $task['status'] === 'completed') {
  67. Log::info('【跳过执行】任务已完成,无需重复生成PDF', [
  68. 'task_id' => $this->taskId,
  69. 'paper_id' => $this->paperId,
  70. 'status' => $task['status']
  71. ]);
  72. return;
  73. }
  74. // 【修复】首先检查试卷是否存在
  75. $paperModel = Paper::with('questions')->find($this->paperId);
  76. if (!$paperModel) {
  77. Log::error('PDF生成队列任务失败:试卷不存在', [
  78. 'task_id' => $this->taskId,
  79. 'paper_id' => $this->paperId,
  80. 'attempt' => $this->attempts(),
  81. ]);
  82. // 如果试卷不存在,判断是否需要重试
  83. if ($this->attempts() < $this->tries) {
  84. Log::info('试卷不存在,将在2秒后重试', [
  85. 'task_id' => $this->taskId,
  86. 'paper_id' => $this->paperId,
  87. 'attempt' => $this->attempts(),
  88. 'next_attempt' => $this->attempts() + 1,
  89. ]);
  90. // 延迟2秒后重试(缩短间隔,减少对回调的影响)
  91. $this->release(2);
  92. return;
  93. } else {
  94. Log::error('试卷不存在且已达到最大重试次数,标记任务失败', [
  95. 'task_id' => $this->taskId,
  96. 'paper_id' => $this->paperId,
  97. 'attempts' => $this->attempts(),
  98. ]);
  99. $taskManager->markTaskFailed($this->taskId, "试卷不存在: {$this->paperId}");
  100. return;
  101. }
  102. }
  103. // 检查试卷是否有题目
  104. if ($paperModel->questions->isEmpty()) {
  105. Log::error('PDF生成队列任务失败:试卷没有题目数据', [
  106. 'task_id' => $this->taskId,
  107. 'paper_id' => $this->paperId,
  108. 'question_count' => 0,
  109. ]);
  110. if ($this->attempts() < $this->tries) {
  111. Log::info('试卷没有题目,将在1秒后重试', [
  112. 'task_id' => $this->taskId,
  113. 'paper_id' => $this->paperId,
  114. 'attempt' => $this->attempts(),
  115. ]);
  116. // 延迟1秒后重试(更短间隔)
  117. $this->release(1);
  118. return;
  119. } else {
  120. $taskManager->markTaskFailed($this->taskId, "试卷没有题目数据: {$this->paperId}");
  121. return;
  122. }
  123. }
  124. $taskManager->updateTaskProgress($this->taskId, 10, '开始生成试卷PDF...');
  125. // 生成试卷PDF
  126. $pdfUrl = $pdfExportService->generateExamPdf($this->paperId)
  127. ?? $questionBankService->exportExamToPdf($this->paperId)
  128. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $this->paperId, 'answer' => 'false']);
  129. $taskManager->updateTaskProgress($this->taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  130. // 生成判卷PDF
  131. $gradingPdfUrl = $pdfExportService->generateGradingPdf($this->paperId)
  132. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $this->paperId, 'answer' => 'true']);
  133. $taskManager->updateTaskProgress($this->taskId, 70, '判卷PDF生成完成,开始合并PDF...');
  134. // 【优化】生成合并PDF(试卷 + 判卷) - 使用快速合并模式
  135. $mergedPdfUrl = $pdfExportService->generateMergedPdf($this->paperId, function($percentage, $message) use ($taskManager) {
  136. // 进度更新:70% 开始,最高到 95%
  137. $progress = 70 + ($percentage / 100) * 25;
  138. $taskManager->updateTaskProgress($this->taskId, round($progress, 0), $message);
  139. });
  140. // 【新增】验证合并后的PDF URL
  141. if (!$mergedPdfUrl) {
  142. Log::error('PDF生成队列任务失败:合并PDF失败', [
  143. 'task_id' => $this->taskId,
  144. 'paper_id' => $this->paperId,
  145. 'attempt' => $this->attempts(),
  146. ]);
  147. if ($this->attempts() < $this->tries) {
  148. Log::info('合并PDF失败,将在3秒后重试', [
  149. 'task_id' => $this->taskId,
  150. 'paper_id' => $this->paperId,
  151. 'attempt' => $this->attempts(),
  152. 'next_attempt' => $this->attempts() + 1,
  153. ]);
  154. // 延迟3秒后重试
  155. $this->release(3);
  156. return;
  157. } else {
  158. Log::error('合并PDF失败且已达到最大重试次数,标记任务失败', [
  159. 'task_id' => $this->taskId,
  160. 'paper_id' => $this->paperId,
  161. 'attempts' => $this->attempts(),
  162. ]);
  163. $taskManager->markTaskFailed($this->taskId, "合并PDF失败: {$this->paperId}");
  164. return;
  165. }
  166. }
  167. Log::info('PDF合并成功验证', [
  168. 'task_id' => $this->taskId,
  169. 'paper_id' => $this->paperId,
  170. 'merged_pdf_url' => $mergedPdfUrl,
  171. 'url_length' => strlen($mergedPdfUrl)
  172. ]);
  173. // 构建完整的试卷内容
  174. $examContent = $paperPayloadService->buildExamContent($paperModel);
  175. // 标记任务完成(包含合并后的PDF URL)
  176. $taskManager->markTaskCompleted($this->taskId, [
  177. 'exam_content' => $examContent,
  178. 'pdfs' => [
  179. 'exam_paper_pdf' => $pdfUrl,
  180. 'grading_pdf' => $gradingPdfUrl,
  181. 'all_pdf' => $mergedPdfUrl, // 【新增】合并后的完整PDF
  182. ],
  183. ]);
  184. Log::info('PDF生成队列任务完成', [
  185. 'task_id' => $this->taskId,
  186. 'paper_id' => $this->paperId,
  187. 'pdf_url' => $pdfUrl,
  188. 'grading_pdf_url' => $gradingPdfUrl,
  189. 'merged_pdf_url' => $mergedPdfUrl,
  190. 'question_count' => $paperModel->questions->count(),
  191. ]);
  192. // 发送回调通知(在合并PDF完成后)
  193. $taskManager->sendCallback($this->taskId);
  194. } catch (\Exception $e) {
  195. $elapsed = microtime(true) - $startTime;
  196. Log::error('PDF生成队列任务失败', [
  197. 'job_id' => $jobId,
  198. 'task_id' => $this->taskId,
  199. 'paper_id' => $this->paperId,
  200. 'attempt' => $this->attempts(),
  201. 'max_attempts' => $this->tries,
  202. 'elapsed' => round($elapsed, 2) . 's',
  203. 'error' => $e->getMessage(),
  204. 'trace' => $e->getTraceAsString(),
  205. ]);
  206. // 如果是第一次失败且试卷可能还在创建中,等待后重试
  207. if ($this->attempts() < $this->tries && strpos($e->getMessage(), '不存在') !== false) {
  208. Log::info('检测到试卷不存在错误,将在2秒后重试', [
  209. 'task_id' => $this->taskId,
  210. 'paper_id' => $this->paperId,
  211. 'attempt' => $this->attempts(),
  212. ]);
  213. $this->release(2);
  214. return;
  215. }
  216. $taskManager->markTaskFailed($this->taskId, $e->getMessage());
  217. } finally {
  218. // 【并发控制】释放锁
  219. $this->releaseLock();
  220. $currentCount = $this->getConcurrentCount();
  221. Log::info('GenerateExamPdfJob: 任务完成', [
  222. 'job_id' => $jobId,
  223. 'total_elapsed' => round(microtime(true) - $startTime, 2) . 's',
  224. 'remaining_concurrent' => $currentCount
  225. ]);
  226. }
  227. }
  228. /**
  229. * 【并发控制】获取执行锁
  230. */
  231. private function acquireLock(): bool
  232. {
  233. $currentCount = $this->getConcurrentCount();
  234. if ($currentCount >= self::MAX_CONCURRENT_JOBS) {
  235. return false;
  236. }
  237. // 增加计数器
  238. Redis::incr(self::REDIS_KEY_CONCURRENT);
  239. // 设置锁过期时间(2小时)
  240. $lockKey = self::REDIS_KEY_LOCK_PREFIX . $this->taskId;
  241. Redis::setex($lockKey, 7200, 1);
  242. return true;
  243. }
  244. /**
  245. * 【并发控制】释放执行锁
  246. */
  247. private function releaseLock(): void
  248. {
  249. // 减少计数器
  250. $currentCount = Redis::decr(self::REDIS_KEY_CONCURRENT);
  251. if ($currentCount < 0) {
  252. Redis::set(self::REDIS_KEY_CONCURRENT, 0);
  253. }
  254. // 删除锁
  255. $lockKey = self::REDIS_KEY_LOCK_PREFIX . $this->taskId;
  256. Redis::del($lockKey);
  257. }
  258. /**
  259. * 【并发控制】获取当前并发数量
  260. */
  261. private function getConcurrentCount(): int
  262. {
  263. $count = Redis::get(self::REDIS_KEY_CONCURRENT);
  264. return $count ? (int)$count : 0;
  265. }
  266. }