GenerateAnalysisPdfJob.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Jobs;
  3. use App\Services\ExamPdfExportService;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use Illuminate\Support\Facades\Log;
  10. use Throwable;
  11. class GenerateAnalysisPdfJob implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. public string $paperId;
  15. public string $studentId;
  16. public ?string $recordId;
  17. public int $tries = 3;
  18. /**
  19. * 学情报告 HTML + 数据聚合比「整卷合并 PDF」更重,默认 60s 队列超时容易在 worker 侧被提前杀掉,
  20. * 表现为「卷子 PDF 正常、分析报告 PDF 一直失败」。与 {@see GenerateExamPdfJob} 对齐。
  21. */
  22. public int $timeout = 300;
  23. public array $backoff = [5, 10, 20];
  24. public function __construct(string $paperId, string $studentId, ?string $recordId = null)
  25. {
  26. $this->paperId = $paperId;
  27. $this->studentId = $studentId;
  28. $this->recordId = $recordId;
  29. // 指定使用 pdf 队列,由独立的 pdf-worker 容器处理
  30. $this->onQueue((string) config('queue.workloads.pdf', 'pdf'));
  31. // 避免事务未提交时 worker 提前消费导致读到未提交数据
  32. $this->afterCommit();
  33. }
  34. public function handle(ExamPdfExportService $pdfExportService): void
  35. {
  36. try {
  37. Log::info('开始处理学情分析PDF生成队列任务', [
  38. 'paper_id' => $this->paperId,
  39. 'student_id' => $this->studentId,
  40. 'record_id' => $this->recordId,
  41. 'attempt' => $this->attempts(),
  42. ]);
  43. // 生成学情分析PDF
  44. $pdfUrl = $pdfExportService->generateAnalysisReportPdf(
  45. $this->paperId,
  46. $this->studentId,
  47. $this->recordId
  48. );
  49. if (! $pdfUrl) {
  50. throw new \RuntimeException('学情分析PDF生成失败:返回空URL');
  51. }
  52. Log::info('学情分析PDF生成成功', [
  53. 'paper_id' => $this->paperId,
  54. 'student_id' => $this->studentId,
  55. 'record_id' => $this->recordId,
  56. 'pdf_url' => $pdfUrl,
  57. ]);
  58. } catch (\Throwable $e) {
  59. Log::error('学情分析PDF生成队列任务失败', [
  60. 'paper_id' => $this->paperId,
  61. 'student_id' => $this->studentId,
  62. 'record_id' => $this->recordId,
  63. 'error' => $e->getMessage(),
  64. 'trace' => $e->getTraceAsString(),
  65. 'attempt' => $this->attempts(),
  66. ]);
  67. throw $e;
  68. }
  69. }
  70. public function failed(Throwable $exception): void
  71. {
  72. Log::error('学情分析PDF生成队列任务最终失败', [
  73. 'paper_id' => $this->paperId,
  74. 'student_id' => $this->studentId,
  75. 'record_id' => $this->recordId,
  76. 'error' => $exception->getMessage(),
  77. ]);
  78. }
  79. }