ProcessAnalysisReportTaskJob.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Jobs;
  3. use App\Services\ExamAnalysisService;
  4. use App\Services\TaskManager;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. use Illuminate\Support\Facades\Log;
  11. use Throwable;
  12. class ProcessAnalysisReportTaskJob implements ShouldQueue
  13. {
  14. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  15. public int $tries = 3;
  16. public int $timeout = 300;
  17. public array $backoff = [5, 10, 20];
  18. public function __construct(
  19. public string $taskId,
  20. public string $paperId,
  21. public string $studentId,
  22. public ?string $recordId = null
  23. ) {
  24. // 与 PDF 相关重流程统一走 pdf 队列
  25. $this->onQueue((string) config('queue.workloads.pdf', 'pdf'));
  26. // 避免事务未提交时 worker 提前消费导致读到旧数据
  27. $this->afterCommit();
  28. }
  29. public function handle(ExamAnalysisService $examAnalysisService): void
  30. {
  31. try {
  32. Log::info('ProcessAnalysisReportTaskJob: 开始处理学情报告任务', [
  33. 'task_id' => $this->taskId,
  34. 'paper_id' => $this->paperId,
  35. 'student_id' => $this->studentId,
  36. 'record_id' => $this->recordId,
  37. 'attempt' => $this->attempts(),
  38. ]);
  39. $examAnalysisService->processReportGenerationTask(
  40. $this->taskId,
  41. $this->paperId,
  42. $this->studentId,
  43. $this->recordId
  44. );
  45. } catch (Throwable $e) {
  46. Log::error('ProcessAnalysisReportTaskJob: 处理失败,将交由队列重试/失败落库', [
  47. 'task_id' => $this->taskId,
  48. 'paper_id' => $this->paperId,
  49. 'student_id' => $this->studentId,
  50. 'record_id' => $this->recordId,
  51. 'attempt' => $this->attempts(),
  52. 'error' => $e->getMessage(),
  53. ]);
  54. throw $e;
  55. }
  56. }
  57. public function failed(Throwable $exception): void
  58. {
  59. try {
  60. $taskManager = app(TaskManager::class);
  61. $taskManager->markTaskFailed(
  62. $this->taskId,
  63. '学情报告生成失败:'.$exception->getMessage()
  64. );
  65. // 与成功路径保持一致:最终失败也发回调,避免调用方只等待回调而无结果。
  66. $taskManager->sendCallback($this->taskId);
  67. } catch (Throwable $innerException) {
  68. Log::error('ProcessAnalysisReportTaskJob: failed回调更新任务失败', [
  69. 'task_id' => $this->taskId,
  70. 'error' => $innerException->getMessage(),
  71. ]);
  72. }
  73. Log::error('ProcessAnalysisReportTaskJob: 队列任务最终失败', [
  74. 'task_id' => $this->taskId,
  75. 'paper_id' => $this->paperId,
  76. 'student_id' => $this->studentId,
  77. 'record_id' => $this->recordId,
  78. 'error' => $exception->getMessage(),
  79. ]);
  80. }
  81. }