| 1 |
<?php |
| 2 |
/** |
| 3 |
* Reclaim expired import sessions and AI process records. |
| 4 |
* |
| 5 |
* @package Templately |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Templately\Modules\FullSiteImport\Cleanup; |
| 9 |
|
| 10 |
use Templately\Modules\FullSiteImport\Utils\AIUtils; |
| 11 |
use Templately\Modules\FullSiteImport\Utils\SessionData; |
| 12 |
use Templately\Modules\Utilities\Cleanup\CleanupTask; |
| 13 |
use Templately\Modules\Utilities\Cleanup\Context; |
| 14 |
use Templately\Modules\Utilities\Cleanup\RetentionKind; |
| 15 |
use Templately\Modules\Utilities\Cleanup\TaskResult; |
| 16 |
|
| 17 |
/** |
| 18 |
* The database half of import cleanup: the `templately_session_*` rows and the |
| 19 |
* `templately_ai_process_*` rows (plus their per-page sub-keys). |
| 20 |
* |
| 21 |
* This does NOT reimplement what "expired" or "active" means — it delegates to |
| 22 |
* `SessionData::cleanup_expired()`, whose signature and return shape are frozen |
| 23 |
* (other callers and tests depend on them). Only this module knows that a |
| 24 |
* session with incomplete progress markers is still running, and that judgement |
| 25 |
* stays here rather than migrating into the shared engine. |
| 26 |
*/ |
| 27 |
class SessionsTask implements CleanupTask { |
| 28 |
|
| 29 |
public function descriptor(): array { |
| 30 |
return [ |
| 31 |
'id' => 'fsi-sessions', |
| 32 |
'label' => __( 'Expired import records', 'templately' ), |
| 33 |
'group' => 'imports', |
| 34 |
// Rows only — an unwritable uploads directory must not stop this |
| 35 |
// from running. |
| 36 |
'scope' => 'records', |
| 37 |
'retention_kind' => RetentionKind::AGE, |
| 38 |
'destructive' => true, |
| 39 |
'schedulable' => true, |
| 40 |
]; |
| 41 |
} |
| 42 |
|
| 43 |
public function estimate( Context $context ): TaskResult { |
| 44 |
$threshold = $context->policy()->age_threshold( 'fsi-sessions' ); |
| 45 |
$expired = 0; |
| 46 |
|
| 47 |
foreach ( SessionData::get_all_data() as $session_id => $session_data ) { |
| 48 |
if ( SessionData::is_active( $session_id, $threshold ) ) { |
| 49 |
continue; |
| 50 |
} |
| 51 |
$expired++; |
| 52 |
} |
| 53 |
|
| 54 |
// Rows carry no meaningful byte figure; report the count so the UI can |
| 55 |
// say "12 records" rather than an implausible size. |
| 56 |
return TaskResult::empty()->add( $expired, 0 ); |
| 57 |
} |
| 58 |
|
| 59 |
public function run( Context $context ): TaskResult { |
| 60 |
if ( $context->is_dry_run() ) { |
| 61 |
return $this->estimate( $context ); |
| 62 |
} |
| 63 |
|
| 64 |
$days = $context->policy()->age_days( 'fsi-sessions' ); |
| 65 |
$outcome = SessionData::cleanup_expired( $days ); |
| 66 |
$processes = isset( $outcome['removed_process_ids'] ) ? count( (array) $outcome['removed_process_ids'] ) : 0; |
| 67 |
|
| 68 |
return TaskResult::empty()->add( (int) ( $outcome['removed_count'] ?? 0 ) + $processes, 0 ); |
| 69 |
} |
| 70 |
} |
| 71 |
|