CleanupTaskLogic.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <?php
  2. namespace App\Module\Cleanup\Logics;
  3. use App\Module\Cleanup\Models\CleanupTask;
  4. use App\Module\Cleanup\Models\CleanupPlan;
  5. use App\Module\Cleanup\Models\CleanupBackup;
  6. use App\Module\Cleanup\Enums\TASK_STATUS;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. /**
  10. * 清理任务管理逻辑类
  11. *
  12. * 负责清理任务的创建、管理和状态控制
  13. */
  14. class CleanupTaskLogic
  15. {
  16. /**
  17. * 基于计划创建清理任务
  18. *
  19. * @param int $planId 计划ID
  20. * @param array $taskOptions 任务选项
  21. * @return array 创建结果
  22. */
  23. public static function createTask(int $planId, array $taskOptions = []): array
  24. {
  25. try {
  26. DB::beginTransaction();
  27. $plan = CleanupPlan::with('contents')->findOrFail($planId);
  28. if (!$plan->is_enabled) {
  29. throw new \Exception('计划已禁用,无法创建任务');
  30. }
  31. if ($plan->contents->isEmpty()) {
  32. throw new \Exception('计划没有配置内容,无法创建任务');
  33. }
  34. // 验证任务选项
  35. $validatedOptions = static::validateTaskOptions($taskOptions);
  36. // 统计任务信息
  37. $enabledContents = $plan->contents->where('is_enabled', true);
  38. $totalTables = $enabledContents->count();
  39. if ($totalTables === 0) {
  40. throw new \Exception('计划中没有启用的表配置,无法创建任务');
  41. }
  42. // 创建任务
  43. $task = CleanupTask::create([
  44. 'task_name' => $validatedOptions['task_name'] ?? "清理任务 - {$plan->plan_name}",
  45. 'plan_id' => $planId,
  46. 'status' => TASK_STATUS::PENDING->value,
  47. 'progress' => 0,
  48. 'current_step' => '准备中',
  49. 'total_tables' => $totalTables,
  50. 'processed_tables' => 0,
  51. 'total_records' => 0,
  52. 'deleted_records' => 0,
  53. 'backup_size' => 0,
  54. 'execution_time' => 0,
  55. 'backup_time' => 0,
  56. 'created_by' => $validatedOptions['created_by'] ?? 0,
  57. ]);
  58. DB::commit();
  59. return [
  60. 'success' => true,
  61. 'message' => '清理任务创建成功',
  62. 'data' => [
  63. 'task_id' => $task->id,
  64. 'task_name' => $task->task_name,
  65. 'plan_name' => $plan->plan_name,
  66. 'total_tables' => $totalTables,
  67. 'status' => TASK_STATUS::from($task->status)->getDescription(),
  68. ]
  69. ];
  70. } catch (\Exception $e) {
  71. DB::rollBack();
  72. Log::error('创建清理任务失败', [
  73. 'plan_id' => $planId,
  74. 'task_options' => $taskOptions,
  75. 'error' => $e->getMessage(),
  76. 'trace' => $e->getTraceAsString()
  77. ]);
  78. return [
  79. 'success' => false,
  80. 'message' => '创建清理任务失败: ' . $e->getMessage(),
  81. 'data' => null
  82. ];
  83. }
  84. }
  85. /**
  86. * 更新任务状态
  87. *
  88. * @param int $taskId 任务ID
  89. * @param TASK_STATUS $status 新状态
  90. * @param array $updateData 更新数据
  91. * @return array 更新结果
  92. */
  93. public static function updateTaskStatus(int $taskId, TASK_STATUS $status, array $updateData = []): array
  94. {
  95. try {
  96. $task = CleanupTask::findOrFail($taskId);
  97. $data = array_merge($updateData, [
  98. 'status' => $status->value,
  99. ]);
  100. // 根据状态设置时间戳
  101. switch ($status) {
  102. case TASK_STATUS::RUNNING:
  103. $data['started_at'] = now();
  104. break;
  105. case TASK_STATUS::BACKING_UP:
  106. $data['started_at'] = $data['started_at'] ?? now();
  107. break;
  108. case TASK_STATUS::COMPLETED:
  109. $data['completed_at'] = now();
  110. $data['progress'] = 100;
  111. break;
  112. case TASK_STATUS::FAILED:
  113. case TASK_STATUS::CANCELLED:
  114. $data['completed_at'] = now();
  115. break;
  116. }
  117. $task->update($data);
  118. return [
  119. 'success' => true,
  120. 'message' => '任务状态更新成功',
  121. 'data' => [
  122. 'task_id' => $task->id,
  123. 'status' => $status->getDescription(),
  124. 'progress' => $task->progress,
  125. ]
  126. ];
  127. } catch (\Exception $e) {
  128. Log::error('更新任务状态失败', [
  129. 'task_id' => $taskId,
  130. 'status' => $status->value,
  131. 'update_data' => $updateData,
  132. 'error' => $e->getMessage()
  133. ]);
  134. return [
  135. 'success' => false,
  136. 'message' => '更新任务状态失败: ' . $e->getMessage(),
  137. 'data' => null
  138. ];
  139. }
  140. }
  141. /**
  142. * 更新任务进度
  143. *
  144. * @param int $taskId 任务ID
  145. * @param int $processedTables 已处理表数
  146. * @param int $deletedRecords 已删除记录数
  147. * @param string $currentStep 当前步骤
  148. * @return array 更新结果
  149. */
  150. public static function updateTaskProgress(int $taskId, int $processedTables, int $deletedRecords, string $currentStep): array
  151. {
  152. try {
  153. $task = CleanupTask::findOrFail($taskId);
  154. $progress = $task->total_tables > 0 ? round(($processedTables / $task->total_tables) * 100, 2) : 0;
  155. $task->update([
  156. 'progress' => $progress,
  157. 'processed_tables' => $processedTables,
  158. 'deleted_records' => $deletedRecords,
  159. 'current_step' => $currentStep,
  160. ]);
  161. return [
  162. 'success' => true,
  163. 'data' => [
  164. 'task_id' => $task->id,
  165. 'progress' => $progress,
  166. 'processed_tables' => $processedTables,
  167. 'total_tables' => $task->total_tables,
  168. 'deleted_records' => $deletedRecords,
  169. 'current_step' => $currentStep,
  170. ]
  171. ];
  172. } catch (\Exception $e) {
  173. Log::error('更新任务进度失败', [
  174. 'task_id' => $taskId,
  175. 'processed_tables' => $processedTables,
  176. 'deleted_records' => $deletedRecords,
  177. 'current_step' => $currentStep,
  178. 'error' => $e->getMessage()
  179. ]);
  180. return [
  181. 'success' => false,
  182. 'message' => '更新任务进度失败: ' . $e->getMessage(),
  183. 'data' => null
  184. ];
  185. }
  186. }
  187. /**
  188. * 取消任务
  189. *
  190. * @param int $taskId 任务ID
  191. * @param string $reason 取消原因
  192. * @return array 取消结果
  193. */
  194. public static function cancelTask(int $taskId, string $reason = ''): array
  195. {
  196. try {
  197. $task = CleanupTask::findOrFail($taskId);
  198. // 检查任务状态
  199. $currentStatus = TASK_STATUS::from($task->status);
  200. if (in_array($currentStatus, [TASK_STATUS::COMPLETED, TASK_STATUS::FAILED, TASK_STATUS::CANCELLED])) {
  201. throw new \Exception('任务已完成或已取消,无法再次取消');
  202. }
  203. $task->update([
  204. 'status' => TASK_STATUS::CANCELLED->value,
  205. 'completed_at' => now(),
  206. 'error_message' => $reason ?: '用户取消',
  207. ]);
  208. return [
  209. 'success' => true,
  210. 'message' => '任务已取消',
  211. 'data' => [
  212. 'task_id' => $task->id,
  213. 'status' => TASK_STATUS::CANCELLED->getDescription(),
  214. ]
  215. ];
  216. } catch (\Exception $e) {
  217. Log::error('取消任务失败', [
  218. 'task_id' => $taskId,
  219. 'reason' => $reason,
  220. 'error' => $e->getMessage()
  221. ]);
  222. return [
  223. 'success' => false,
  224. 'message' => '取消任务失败: ' . $e->getMessage(),
  225. 'data' => null
  226. ];
  227. }
  228. }
  229. /**
  230. * 获取任务详情
  231. *
  232. * @param int $taskId 任务ID
  233. * @return array 任务详情
  234. */
  235. public static function getTaskDetails(int $taskId): array
  236. {
  237. try {
  238. $task = CleanupTask::with(['plan', 'backup'])->findOrFail($taskId);
  239. return [
  240. 'success' => true,
  241. 'data' => [
  242. 'task' => [
  243. 'id' => $task->id,
  244. 'task_name' => $task->task_name,
  245. 'status' => $task->status,
  246. 'status_name' => TASK_STATUS::from($task->status)->getDescription(),
  247. 'progress' => $task->progress,
  248. 'current_step' => $task->current_step,
  249. 'total_tables' => $task->total_tables,
  250. 'processed_tables' => $task->processed_tables,
  251. 'total_records' => $task->total_records,
  252. 'deleted_records' => $task->deleted_records,
  253. 'backup_size' => $task->backup_size,
  254. 'execution_time' => $task->execution_time,
  255. 'backup_time' => $task->backup_time,
  256. 'started_at' => $task->started_at,
  257. 'backup_completed_at' => $task->backup_completed_at,
  258. 'completed_at' => $task->completed_at,
  259. 'error_message' => $task->error_message,
  260. 'created_at' => $task->created_at,
  261. ],
  262. 'plan' => $task->plan ? [
  263. 'id' => $task->plan->id,
  264. 'plan_name' => $task->plan->plan_name,
  265. 'plan_type' => $task->plan->plan_type,
  266. 'description' => $task->plan->description,
  267. ] : null,
  268. 'backup' => $task->backup ? [
  269. 'id' => $task->backup->id,
  270. 'backup_name' => $task->backup->backup_name,
  271. 'backup_size' => $task->backup->backup_size,
  272. 'file_count' => $task->backup->file_count,
  273. 'status' => $task->backup->status,
  274. ] : null,
  275. ]
  276. ];
  277. } catch (\Exception $e) {
  278. Log::error('获取任务详情失败', [
  279. 'task_id' => $taskId,
  280. 'error' => $e->getMessage()
  281. ]);
  282. return [
  283. 'success' => false,
  284. 'message' => '获取任务详情失败: ' . $e->getMessage(),
  285. 'data' => null
  286. ];
  287. }
  288. }
  289. /**
  290. * 验证任务选项
  291. *
  292. * @param array $taskOptions 任务选项
  293. * @return array 验证后的选项
  294. */
  295. private static function validateTaskOptions(array $taskOptions): array
  296. {
  297. return [
  298. 'task_name' => $taskOptions['task_name'] ?? null,
  299. 'created_by' => $taskOptions['created_by'] ?? 0,
  300. ];
  301. }
  302. /**
  303. * 启动任务执行
  304. *
  305. * @param int $taskId 任务ID
  306. * @return array 启动结果
  307. */
  308. public static function startTask(int $taskId): array
  309. {
  310. try {
  311. $task = CleanupTask::findOrFail($taskId);
  312. // 检查任务状态
  313. if ($task->status !== TASK_STATUS::PENDING->value) {
  314. return [
  315. 'success' => false,
  316. 'message' => '只有待执行状态的任务可以启动'
  317. ];
  318. }
  319. // 更新任务状态为执行中
  320. $task->update([
  321. 'status' => TASK_STATUS::RUNNING->value,
  322. 'started_at' => now(),
  323. 'current_step' => '任务启动中...'
  324. ]);
  325. return [
  326. 'success' => true,
  327. 'message' => '任务启动成功',
  328. 'data' => $task->fresh()
  329. ];
  330. } catch (\Exception $e) {
  331. return [
  332. 'success' => false,
  333. 'message' => '启动任务失败:' . $e->getMessage()
  334. ];
  335. }
  336. }
  337. /**
  338. * 暂停任务执行
  339. *
  340. * @param int $taskId 任务ID
  341. * @return array 暂停结果
  342. */
  343. public static function pauseTask(int $taskId): array
  344. {
  345. try {
  346. $task = CleanupTask::findOrFail($taskId);
  347. // 检查任务状态
  348. if (!in_array($task->status, [TASK_STATUS::BACKING_UP->value, TASK_STATUS::RUNNING->value])) {
  349. return [
  350. 'success' => false,
  351. 'message' => '只有备份中或执行中的任务可以暂停'
  352. ];
  353. }
  354. // 更新任务状态为已暂停
  355. $task->update([
  356. 'status' => TASK_STATUS::PAUSED->value,
  357. 'current_step' => '任务已暂停'
  358. ]);
  359. return [
  360. 'success' => true,
  361. 'message' => '任务暂停成功',
  362. 'data' => $task->fresh()
  363. ];
  364. } catch (\Exception $e) {
  365. return [
  366. 'success' => false,
  367. 'message' => '暂停任务失败:' . $e->getMessage()
  368. ];
  369. }
  370. }
  371. /**
  372. * 恢复任务执行
  373. *
  374. * @param int $taskId 任务ID
  375. * @return array 恢复结果
  376. */
  377. public static function resumeTask(int $taskId): array
  378. {
  379. try {
  380. $task = CleanupTask::findOrFail($taskId);
  381. // 检查任务状态
  382. if ($task->status !== TASK_STATUS::PAUSED->value) {
  383. return [
  384. 'success' => false,
  385. 'message' => '只有已暂停的任务可以恢复'
  386. ];
  387. }
  388. // 更新任务状态为执行中
  389. $task->update([
  390. 'status' => TASK_STATUS::RUNNING->value,
  391. 'current_step' => '任务恢复执行中...'
  392. ]);
  393. return [
  394. 'success' => true,
  395. 'message' => '任务恢复成功',
  396. 'data' => $task->fresh()
  397. ];
  398. } catch (\Exception $e) {
  399. return [
  400. 'success' => false,
  401. 'message' => '恢复任务失败:' . $e->getMessage()
  402. ];
  403. }
  404. }
  405. /**
  406. * 停止任务执行
  407. *
  408. * @param int $taskId 任务ID
  409. * @return array 停止结果
  410. */
  411. public static function stopTask(int $taskId): array
  412. {
  413. try {
  414. $task = CleanupTask::findOrFail($taskId);
  415. // 检查任务状态
  416. if (!in_array($task->status, [TASK_STATUS::BACKING_UP->value, TASK_STATUS::RUNNING->value, TASK_STATUS::PAUSED->value])) {
  417. return [
  418. 'success' => false,
  419. 'message' => '只有备份中、执行中或已暂停的任务可以停止'
  420. ];
  421. }
  422. // 更新任务状态为已取消
  423. $task->update([
  424. 'status' => TASK_STATUS::CANCELLED->value,
  425. 'finished_at' => now(),
  426. 'current_step' => '任务已停止',
  427. 'error_message' => '任务被手动停止'
  428. ]);
  429. return [
  430. 'success' => true,
  431. 'message' => '任务停止成功',
  432. 'data' => $task->fresh()
  433. ];
  434. } catch (\Exception $e) {
  435. return [
  436. 'success' => false,
  437. 'message' => '停止任务失败:' . $e->getMessage()
  438. ];
  439. }
  440. }
  441. /**
  442. * 获取任务进度
  443. *
  444. * @param int $taskId 任务ID
  445. * @return array 进度信息
  446. */
  447. public static function getTaskProgress(int $taskId): array
  448. {
  449. try {
  450. $task = CleanupTask::findOrFail($taskId);
  451. return [
  452. 'success' => true,
  453. 'data' => [
  454. 'task_id' => $task->id,
  455. 'status' => $task->status,
  456. 'progress' => $task->progress,
  457. 'current_step' => $task->current_step,
  458. 'total_tables' => $task->total_tables,
  459. 'processed_tables' => $task->processed_tables,
  460. 'deleted_records' => $task->deleted_records,
  461. 'started_at' => $task->started_at,
  462. 'finished_at' => $task->finished_at,
  463. ]
  464. ];
  465. } catch (\Exception $e) {
  466. return [
  467. 'success' => false,
  468. 'message' => '获取任务进度失败:' . $e->getMessage()
  469. ];
  470. }
  471. }
  472. }