ProcessBatchAnimeEpisodeGenerationCommand.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\DB;
  5. use App\Services\DeepSeek\DeepSeekService;
  6. /**
  7. * 批量生成分集子进程 worker
  8. * 由 batch:generate-episodes 调度,每个进程通过 MySQL 命名锁独占一个 anime_id,
  9. * 串行生成该 anime 的 pending 剧集(按集数顺序),直到没有待处理任务为止。
  10. */
  11. class ProcessBatchAnimeEpisodeGenerationCommand extends Command
  12. {
  13. /**
  14. * anime 处理锁前缀(配合 MySQL GET_LOCK 使用,同一 anime 同一时刻只允许一个进程处理)
  15. */
  16. public const LOCK_PREFIX = 'batch_episode_generation_anime_';
  17. /**
  18. * 单集最大重试次数,超过后停止重试并标记为失败
  19. */
  20. private const MAX_RETRY_COUNT = 5;
  21. /**
  22. * The name and signature of the console command.
  23. *
  24. * @var string
  25. */
  26. protected $signature = 'batch:generate-episodes:anime {anime_id : 动漫ID}';
  27. /**
  28. * The console command description.
  29. *
  30. * @var string
  31. */
  32. protected $description = '批量生成分集子进程:独占处理指定anime_id的待生成剧集';
  33. protected $deepSeekService;
  34. /**
  35. * Create a new command instance.
  36. *
  37. * @return void
  38. */
  39. public function __construct(DeepSeekService $deepSeekService)
  40. {
  41. parent::__construct();
  42. $this->deepSeekService = $deepSeekService;
  43. }
  44. /**
  45. * Execute the console command.
  46. *
  47. * @return int
  48. */
  49. public function handle()
  50. {
  51. set_time_limit(0);
  52. $animeId = (int) $this->argument('anime_id');
  53. $lockName = self::LOCK_PREFIX . $animeId;
  54. // 非阻塞抢占该 anime 的处理锁;抢不到说明已有其他进程正在处理
  55. $acquired = DB::selectOne('SELECT GET_LOCK(?, 0) AS acquired', [$lockName]);
  56. if (!$acquired || (int) $acquired->acquired !== 1) {
  57. dLog('command')->info("anime_id: {$animeId} 正在被其他进程处理,本次直接退出");
  58. return 0;
  59. }
  60. dLog('command')->info("anime_id: {$animeId} 抢占处理锁成功,开始处理...");
  61. try {
  62. $this->processAnimeEpisodes($animeId);
  63. } catch (\Throwable $e) {
  64. dLog('command')->error("anime_id: {$animeId} 处理异常: " . $e->getMessage());
  65. logDB('batch_episode_generation', 'error', "anime_id: {$animeId} 批量生成处理异常", [
  66. 'anime_id' => $animeId,
  67. 'error' => $e->getMessage(),
  68. 'trace' => $e->getTraceAsString()
  69. ]);
  70. } finally {
  71. // 更新任务中心:该 anime 的批量生成任务若已全部结束,同步状态和结果
  72. try {
  73. $this->deepSeekService->finishBatchGenerateEpisodesTaskCenters($animeId);
  74. } catch (\Throwable $e) {
  75. dLog('command')->error('批量生成分集任务中心同步异常: ' . $e->getMessage());
  76. }
  77. // 显式释放处理锁;即使进程异常退出,连接断开后 MySQL 也会自动释放
  78. DB::statement('SELECT RELEASE_LOCK(?)', [$lockName]);
  79. dLog('command')->info("anime_id: {$animeId} 处理结束,已释放处理锁");
  80. }
  81. return 0;
  82. }
  83. /**
  84. * 串行处理指定 anime 的所有待生成剧集
  85. *
  86. * @param int $animeId
  87. * @return void
  88. */
  89. private function processAnimeEpisodes($animeId)
  90. {
  91. while (true) {
  92. // 取该 anime 集数最小的 pending 任务
  93. $task = DB::table('mp_batch_episode_generation_details')
  94. ->where('anime_id', $animeId)
  95. ->where('status', 'pending')
  96. ->orderBy('episode_number')
  97. ->first();
  98. if (!$task) {
  99. dLog('command')->info('[' . date('Y-m-d H:i:s') . "] anime_id: {$animeId} 没有待处理的任务");
  100. return;
  101. }
  102. try {
  103. // 返回 false 表示该 anime 暂时无法继续(如前一集未完成),退出等待下一轮调度
  104. $keepGoing = $this->processEpisode($task);
  105. if (!$keepGoing) {
  106. dLog('command')->info("anime_id: {$animeId} 暂时无法继续生成,退出本次处理");
  107. return;
  108. }
  109. } catch (\Exception $e) {
  110. $animeLogInfo = isset($task) ? ' (anime_id: ' . $task->anime_id . ', 第' . $task->episode_number . '集)' : '';
  111. dLog('command')->error('[' . date('Y-m-d H:i:s') . '] 生成失败: ' . $e->getMessage() . $animeLogInfo);
  112. if (isset($task)) {
  113. // 更新重试次数
  114. $retryCount = $task->retry_count + 1;
  115. // 未超过最大重试次数则标记为待处理继续重试,超过后标记为失败并通知
  116. $this->markTaskRetryOrFail($task, $retryCount, $e->getMessage());
  117. // 记录错误日志
  118. logDB('batch_episode_generation', 'error', "anime_id: {$task->anime_id} 第{$task->episode_number}集生成失败", [
  119. 'anime_id' => $task->anime_id,
  120. 'episode_number' => $task->episode_number,
  121. 'error' => $e->getMessage(),
  122. 'trace' => $e->getTraceAsString()
  123. ]);
  124. }
  125. }
  126. // 与原有逻辑保持一致:每5秒处理一轮
  127. sleep(5);
  128. }
  129. }
  130. /**
  131. * 处理一个待生成的剧集(沿用原有校验与生成逻辑)
  132. *
  133. * @param object $task
  134. * @return bool true-可继续处理下一个任务,false-该anime暂时无法继续
  135. */
  136. private function processEpisode($task)
  137. {
  138. dLog('command')->info('[' . date('Y-m-d H:i:s') . '] 找到待处理任务 - Anime ID: ' . $task->anime_id . ', Episode: ' . $task->episode_number);
  139. // 检查前一集是否已完成(如果不是第1集)
  140. if ($task->episode_number > 1) {
  141. $prevEpisodeNumber = $task->episode_number - 1;
  142. // 优先判断前一集是否已在系统中生成(查询 mp_anime_episodes)。
  143. // 用户手动创建的前一集也视为已存在,直接跳过批量任务状态判断,
  144. // 避免批量任务前一集失败后卡住整个批量任务。
  145. $prevEpisodeExists = DB::table('mp_anime_episodes')
  146. ->where('anime_id', $task->anime_id)
  147. ->where('episode_number', $prevEpisodeNumber)
  148. ->where('is_default', 1)
  149. ->exists();
  150. if (!$prevEpisodeExists) {
  151. // 系统中不存在前一集时,才进行批量任务状态判断
  152. $prevTaskInBatch = DB::table('mp_batch_episode_generation_details')
  153. ->where('anime_id', $task->anime_id)
  154. ->where('episode_number', $prevEpisodeNumber)
  155. ->first();
  156. if ($prevTaskInBatch && $prevTaskInBatch->status !== 'completed') {
  157. dLog('command')->info('[' . date('Y-m-d H:i:s') . '] 前一集(第' . $prevEpisodeNumber . '集)尚未完成,跳过当前任务 (anime_id: ' . $task->anime_id . ')');
  158. return false;
  159. }
  160. dLog('command')->error('[' . date('Y-m-d H:i:s') . '] 前一集(第' . $prevEpisodeNumber . '集)不存在,无法继续生成 (anime_id: ' . $task->anime_id . ')');
  161. // 标记为失败
  162. DB::table('mp_batch_episode_generation_details')
  163. ->where('id', $task->id)
  164. ->update([
  165. 'status' => 'failed',
  166. 'error_message' => "前一集(第{$prevEpisodeNumber}集)不存在,无法继续生成",
  167. 'updated_at' => now()
  168. ]);
  169. return false;
  170. }
  171. }
  172. // 检查当前集是否已经存在(避免重复生成)
  173. $currentEpisodeExists = DB::table('mp_anime_episodes')
  174. ->where('anime_id', $task->anime_id)
  175. ->where('episode_number', $task->episode_number)
  176. ->where('is_default', 1)
  177. ->exists();
  178. if ($currentEpisodeExists) {
  179. dLog('command')->info('[' . date('Y-m-d H:i:s') . '] 第' . $task->episode_number . '集已存在,跳过生成 (anime_id: ' . $task->anime_id . ')');
  180. // 标记为已完成
  181. DB::table('mp_batch_episode_generation_details')
  182. ->where('id', $task->id)
  183. ->update([
  184. 'status' => 'completed',
  185. 'completed_at' => now(),
  186. // 'updated_at' => now()
  187. ]);
  188. return true;
  189. }
  190. // 标记为处理中
  191. DB::table('mp_batch_episode_generation_details')
  192. ->where('id', $task->id)
  193. ->update([
  194. 'status' => 'processing',
  195. 'updated_at' => now()
  196. ]);
  197. // 设置用户上下文(绑定到容器)
  198. app()->instance('siteData', [
  199. 'uid' => $task->uid,
  200. 'cpid' => $task->cpid
  201. ]);
  202. // 解析请求数据
  203. $requestData = json_decode($task->request_data, true);
  204. $requestData['episode_number'] = $task->episode_number;
  205. // 使用"继续策划下一集"逻辑
  206. $requestData['prompt'] = '继续策划下一集';
  207. dLog('command')->info('[' . date('Y-m-d H:i:s') . '] 开始生成第' . $task->episode_number . '集... (anime_id: ' . $task->anime_id . ')');
  208. // 调用非流式生成方法,并记录实际执行耗时
  209. $chatStartTime = microtime(true);
  210. try {
  211. $result = $this->deepSeekService->chatForAceNonStream($requestData);
  212. } finally {
  213. $chatDuration = round(microtime(true) - $chatStartTime, 2);
  214. dLog('command')->info('[' . date('Y-m-d H:i:s') . '] chatForAceNonStream 执行完成,耗时: ' . $chatDuration . ' 秒 (anime_id: ' . $task->anime_id . ', 第' . $task->episode_number . '集)');
  215. }
  216. // 检查是否有错误
  217. if (isset($result['error']) && $result['error']) {
  218. dLog('command')->error('[' . date('Y-m-d H:i:s') . '] 生成失败: ' . $result['error'] . ' (anime_id: ' . $task->anime_id . ', 第' . $task->episode_number . '集)');
  219. // 更新重试次数
  220. $retryCount = $task->retry_count + 1;
  221. // 未超过最大重试次数则标记为待处理继续重试,超过后标记为失败并通知
  222. $this->markTaskRetryOrFail($task, $retryCount, $result['error']);
  223. // 记录错误日志
  224. logDB('batch_episode_generation', 'error', "anime_id: {$task->anime_id} 第{$task->episode_number}集生成失败", [
  225. 'anime_id' => $task->anime_id,
  226. 'episode_number' => $task->episode_number,
  227. 'error' => $result['error']
  228. ]);
  229. return true;
  230. }
  231. // 标记为完成
  232. DB::table('mp_batch_episode_generation_details')
  233. ->where('id', $task->id)
  234. ->update([
  235. 'status' => 'completed',
  236. 'result_data' => json_encode($result, JSON_UNESCAPED_UNICODE),
  237. 'completed_at' => now(),
  238. // 'updated_at' => now()
  239. ]);
  240. dLog('command')->info('[' . date('Y-m-d H:i:s') . '] 第' . $task->episode_number . '集生成成功 (anime_id: ' . $task->anime_id . ')');
  241. return true;
  242. }
  243. /**
  244. * 任务失败处理:未超过最大重试次数则标记为待处理继续重试,
  245. * 超过后直接标记为失败并通过 sendNotice 发送报错通知。
  246. *
  247. * @param object $task
  248. * @param int $retryCount
  249. * @param string $error
  250. * @return void
  251. */
  252. private function markTaskRetryOrFail($task, $retryCount, $error)
  253. {
  254. if ($retryCount > self::MAX_RETRY_COUNT) {
  255. // 超过最大重试次数,标记为失败
  256. DB::table('mp_batch_episode_generation_details')
  257. ->where('id', $task->id)
  258. ->update([
  259. 'status' => 'failed',
  260. 'error_message' => '重试超过' . self::MAX_RETRY_COUNT . '次,已停止重试: ' . $error,
  261. 'retry_count' => $retryCount,
  262. 'updated_at' => now()
  263. ]);
  264. dLog('command')->error('[' . date('Y-m-d H:i:s') . '] 第' . $task->episode_number . '集重试超过' . self::MAX_RETRY_COUNT . '次,已标记为失败 (anime_id: ' . $task->anime_id . ')');
  265. // 发送报错通知(通知失败不影响任务状态)
  266. try {
  267. $notice = "批量分集生成失败(重试超过" . self::MAX_RETRY_COUNT . "次,已停止重试)\n"
  268. . "anime_id: {$task->anime_id}\n"
  269. . "集数: 第{$task->episode_number}集\n"
  270. . "错误: {$error}\n"
  271. . "时间: " . date('Y-m-d H:i:s');
  272. sendNotice($notice);
  273. } catch (\Throwable $e) {
  274. dLog('command')->error('[' . date('Y-m-d H:i:s') . '] 发送失败通知异常 (anime_id: ' . $task->anime_id . ', 第' . $task->episode_number . '集): ' . $e->getMessage());
  275. }
  276. return;
  277. }
  278. // 未超过最大重试次数,标记为待处理,下一轮重试
  279. DB::table('mp_batch_episode_generation_details')
  280. ->where('id', $task->id)
  281. ->update([
  282. 'status' => 'pending',
  283. 'error_message' => $error,
  284. 'retry_count' => $retryCount,
  285. 'updated_at' => now()
  286. ]);
  287. }
  288. }