| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Modules\Optimization\Components; |
| 4 |
|
| 5 |
use ImageOptimization\Classes\Async_Operation\{ |
| 6 |
Async_Operation, |
| 7 |
Async_Operation_Hook, |
| 8 |
Async_Operation_Queue, |
| 9 |
Exceptions\Async_Operation_Exception, |
| 10 |
}; |
| 11 |
|
| 12 |
use ImageOptimization\Modules\Optimization\Classes\Bulk_Optimization\{ |
| 13 |
Bulk_Optimization_Queue, |
| 14 |
Bulk_Optimization_Queue_Type, |
| 15 |
}; |
| 16 |
|
| 17 |
use ImageOptimization\Classes\Logger; |
| 18 |
use Throwable; |
| 19 |
|
| 20 |
// @codeCoverageIgnoreStart |
| 21 |
if ( ! defined( 'ABSPATH' ) ) { |
| 22 |
exit; // Exit if accessed directly. |
| 23 |
} |
| 24 |
// @codeCoverageIgnoreEnd |
| 25 |
|
| 26 |
class Bulk_Operation_Recovery { |
| 27 |
/** |
| 28 |
* Handle failed bulk operation and attempt to recover |
| 29 |
* |
| 30 |
* @param int $action_id The failed action ID |
| 31 |
*/ |
| 32 |
public function handle_failed_bulk_operation( $action_id ) { |
| 33 |
try { |
| 34 |
$action = Async_Operation::get_by_id( (int) $action_id ); |
| 35 |
} catch ( Async_Operation_Exception $aoe ) { |
| 36 |
Logger::error( "Failed to get bulk operation action {$action_id}: " . $aoe->getMessage() ); |
| 37 |
return; |
| 38 |
} |
| 39 |
|
| 40 |
$hook = $action->get_hook(); |
| 41 |
|
| 42 |
if ( ! in_array( $hook, [ |
| 43 |
Async_Operation_Hook::OPTIMIZE_BULK, |
| 44 |
Async_Operation_Hook::REOPTIMIZE_BULK, |
| 45 |
], true ) ) { |
| 46 |
return; |
| 47 |
} |
| 48 |
|
| 49 |
$args = $action->get_args(); |
| 50 |
$operation_id = $args['operation_id'] ?? null; |
| 51 |
|
| 52 |
if ( ! $operation_id ) { |
| 53 |
Logger::error( "Missing operation_id in failed bulk action {$action_id}" ); |
| 54 |
return; |
| 55 |
} |
| 56 |
|
| 57 |
Logger::info( "Bulk operation {$action_id} failed for operation_id {$operation_id}" ); |
| 58 |
|
| 59 |
$queue_type = Async_Operation_Hook::OPTIMIZE_BULK === $hook |
| 60 |
? Bulk_Optimization_Queue_Type::OPTIMIZATION |
| 61 |
: Bulk_Optimization_Queue_Type::REOPTIMIZATION; |
| 62 |
|
| 63 |
try { |
| 64 |
$queue = new Bulk_Optimization_Queue( $queue_type ); |
| 65 |
|
| 66 |
if ( ! $queue->has_more_images() ) { |
| 67 |
Logger::info( "No more images to process for operation_id {$operation_id}, deleting queue" ); |
| 68 |
|
| 69 |
$queue->delete(); |
| 70 |
|
| 71 |
return; |
| 72 |
} |
| 73 |
|
| 74 |
Async_Operation::create( |
| 75 |
$hook, |
| 76 |
[ 'operation_id' => $operation_id ], |
| 77 |
Async_Operation_Queue::OPTIMIZE |
| 78 |
); |
| 79 |
|
| 80 |
Logger::info( "Recreated bulk operation for operation_id {$operation_id}" ); |
| 81 |
|
| 82 |
} catch ( Throwable $t ) { |
| 83 |
Logger::error( "Failed to recover bulk operation {$operation_id}: " . $t->getMessage() ); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
public function __construct() { |
| 88 |
add_action( 'action_scheduler_failed_action', [ $this, 'handle_failed_bulk_operation' ], 5, 2 ); |
| 89 |
} |
| 90 |
} |
| 91 |
|