*/ public static function labels(): array { return array( 'queued' => __( 'Queued', 'catalogrelay' ), 'running' => __( 'Running', 'catalogrelay' ), 'stalled' => __( 'Stalled (not responding)', 'catalogrelay' ), 'paused' => __( 'Paused', 'catalogrelay' ), 'cancelled' => __( 'Cancelled', 'catalogrelay' ), 'failed' => __( 'Failed', 'catalogrelay' ), 'needs_manual' => __( 'Needs attention', 'catalogrelay' ), 'completed' => __( 'Completed', 'catalogrelay' ), 'completed_with_warnings' => __( 'Completed with warnings', 'catalogrelay' ), 'completed_with_failures' => __( 'Completed with failed rows', 'catalogrelay' ), 'blocked' => __( 'Blocked (nothing was imported)', 'catalogrelay' ), 'rolling_back' => __( 'Rolling back', 'catalogrelay' ), 'rolled_back' => __( 'Rolled back', 'catalogrelay' ), 'rolled_back_partial' => __( 'Rolled back (some conflicts kept)', 'catalogrelay' ), 'rollback_unfinished' => __( 'Partly rolled back', 'catalogrelay' ), ); } /** * Status code of a job. * * @param Job $job Job. * @param array $progress JobProgressService::get() result. * @return string */ public static function code( Job $job, array $progress ): string { if ( ImportJobType::TYPE === $job->type ) { $rb = self::rollbackState( $job ); if ( '' !== $rb ) { return $rb; } } switch ( $job->status ) { case Job::QUEUED: return 'queued'; case Job::RUNNING: return ! empty( $progress['stalled'] ) ? 'stalled' : 'running'; case Job::PAUSED: return 'paused'; case Job::CANCELLED: return 'cancelled'; case Job::FAILED: return 'failed'; case Job::NEEDS_MANUAL: return 'needs_manual'; } $outcome = JobRowsRepo::getSentinel( $job->id, 'outcome' ); if ( $outcome && 'blocked' === ( $outcome['outcome'] ?? '' ) ) { return 'blocked'; } if ( Job::COMPLETED_WITH_FAILURE === $job->status ) { return 'completed_with_failures'; } $counts = JobRowsRepo::counts( $job->id ); if ( ! empty( $counts['warning'] ) ) { return 'completed_with_warnings'; } return 'completed'; } /** * Rolled back state of an import derived from its ledger batches (an expired batch keeps how it ended in its summary). * "rollback_unfinished": part of the chain was rolled back but rows are left that the rollback never reached (a batch * not rolled back, or a rollback cancelled midway); a new preview and confirmation roll back the rest. Any state but '' * keeps retries away (they would write over the rollback). * * @param Job $job Import job. * @return string '' or rolling_back|rolled_back|rolled_back_partial|rollback_unfinished */ public static function rollbackState( Job $job ): string { global $wpdb; $d = Container::requireCurrent(); $batches = RollbackService::chain( $job->id ); if ( ! $batches ) { return ''; } $rolled = 0; $partial = 0; $left = false; foreach ( $batches as $id ) { $b = Ledger::batchFor( $d, $id ); if ( ! $b ) { $left = true; continue; } if ( 'rolling_back' === $b->status ) { return 'rolling_back'; } $status = 'expired' === $b->status ? (string) ( $b->summary['status_before_expiry'] ?? '' ) : $b->status; if ( 'rolled_back' === $status ) { ++$rolled; } elseif ( 'rolled_back_partial' === $status ) { ++$partial; // Conflicts the rollback kept are "conflict" (or "restore_failed"); rows it never reached are still written. $left = $left || ( 'expired' !== $b->status && null !== $wpdb->get_var( $wpdb->prepare( "SELECT 1 FROM {$wpdb->prefix}catalogrelay_ledger WHERE batch_id = %d AND state IN ('written', 'captured') LIMIT 1", $id ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from the prefix. } else { $left = true; } } if ( 0 === $rolled + $partial ) { return ''; } if ( $left ) { return 'rollback_unfinished'; } return $partial > 0 ? 'rolled_back_partial' : 'rolled_back'; } /** * Full record for the UI. * * @param int $id Job id. * @return array|null */ public static function present( int $id ): ?array { $d = Container::requireCurrent(); $job = JobStore::find( $d, $id ); if ( $job && RollbackJob::TYPE === $job->type ) { return self::presentRollback( $job ); // The jobs table is the plugin's: its rollback jobs roll back imports. } if ( ! $job || 0 !== strpos( $job->type, 'catalogrelay.' ) ) { return null; } $progress = JobProgressService::get( $d, $id ); $progress = is_array( $progress ) ? $progress : array(); $code = self::code( $job, $progress ); $labels = self::labels(); $p = JobParams::of( $job ); $row = $job->row; $out = array( 'id' => $job->id, 'type' => substr( $job->type, strlen( 'catalogrelay.' ) ), 'mode' => $p->mode(), 'status' => $code, 'label' => $labels[ $code ] ?? $code, 'raw_status' => $job->status, 'total' => $job->total, 'processed' => $job->processed, 'failed' => $job->failed, 'skipped' => $job->skipped, 'stalled' => ! empty( $progress['stalled'] ), 'queue_pos' => (int) ( $progress['queue_pos'] ?? 0 ), 'as_stalled' => ! empty( $progress['as_stalled'] ), 'created_at' => (string) ( $row['created_at'] ?? '' ), 'started_at' => (string) ( $row['started_at'] ?? '' ), 'finished_at' => (string) ( $row['finished_at'] ?? '' ), 'retry_of' => $p->retryOf(), 'file_name' => (string) ( $p->data['file']['name'] ?? '' ), 'last_error' => (string) ( $row['last_error'] ?? '' ), ); if ( DryRunJobType::TYPE === $job->type && 'rollback_preview' !== $p->mode() && ! ScanBuilder::ready( $p ) && FileStore::hasSource( $p->ref() ) ) { $out['scan'] = array( 'scanned' => ScanBuilder::scanned( $p ), 'total' => $p->rows(), ); } elseif ( ImportJobType::TYPE === $job->type && ! ScanBuilder::ready( $p ) && ! $p->blocked() && FileStore::hasSource( $p->ref() ) && Job::RUNNING === $job->status ) { $out['scan'] = array( 'scanned' => ScanBuilder::scanned( $p ), 'total' => $p->rows(), ); } $out['images_pending'] = ImageQueue::pending( $job->id ); $out['warnings'] = (int) ( JobRowsRepo::counts( $job->id )['warning'] ?? 0 ); $totals = JobRowsRepo::getSentinel( $job->id, 'totals' ); if ( $totals ) { $out['totals'] = $totals; } if ( DryRunJobType::TYPE === $job->type ) { $plan = JobRowsRepo::getSentinel( $job->id, 'plan' ); if ( $plan ) { $out['plan'] = array( 'plan_id' => (int) $plan['plan_id'], 'hash' => (string) $plan['hash'], 'generated_at' => (string) ( $plan['generated_at'] ?? '' ), ); } } if ( ImportJobType::TYPE === $job->type || RetryJobType::TYPE === $job->type ) { $root = $p->retryOf() > 0 ? $p->retryOf() : $job->id; $fc = JobRowsRepo::failedCount( $root ); $root_job = $root === $job->id ? $job : JobStore::find( $d, $root ); $rolled = $fc > 0 && $root_job && '' !== self::rollbackState( $root_job ); // A retry would write over the rollback. $out['failed_rows'] = $fc; $out['source_available'] = FileStore::hasSource( $p->ref() ); $out['can'] = array( 'download_failed' => $fc > 0, 'retry' => $fc > 0 && $out['source_available'] && $job->isTerminal() && ! $rolled, 'retry_disabled' => $rolled ? 'rolled_back' : ( $fc > 0 && ! $out['source_available'] ? 'source_expired' : '' ), ); if ( ImportJobType::TYPE === $job->type ) { $blocker = RollbackService::blocker( $job ); $out['can']['rollback'] = '' === $blocker; $out['rollback_blocked'] = $blocker; if ( 'rolling_back' === $code ) { $out['rollback'] = self::activeRollback( $job ); // Its progress, queue state and controls (not the import's). } $exp = self::snapshotExpiry( $job ); if ( $exp ) { $out['snapshot_expires'] = $exp; } // Retry images: not once a part was rolled back (code() is then the rollback state), it would set them again; // not once the file is gone, it holds the image URLs (the route refuses with source_expired). $warn = JobRowsRepo::codeCounts( $job->id, 'warning' ); $out['can']['retry_images'] = (int) ( $warn['image_failed'] ?? 0 ) + (int) ( $warn['image_blocked'] ?? 0 ) > 0 && $out['source_available'] && ! in_array( $code, array( 'rolling_back', 'rolled_back', 'rolled_back_partial', 'rollback_unfinished' ), true ); } } $out['can']['resume'] = Job::PAUSED === $job->status; $out['can']['recover'] = ! empty( $progress['stalled'] ); $out['can']['cancel'] = in_array( $job->status, array( Job::QUEUED, Job::RUNNING, Job::PAUSED, Job::NEEDS_MANUAL ), true ); $out['can']['pause'] = in_array( $job->status, array( Job::QUEUED, Job::RUNNING ), true ); return $out; } /** * Record of a rollback job (core.ledger.rollback) for the UI. * * @param Job $job Rollback job. * @return array */ private static function presentRollback( Job $job ): array { $d = Container::requireCurrent(); $progress = JobProgressService::get( $d, $job->id ); $progress = is_array( $progress ) ? $progress : array(); $code = self::code( $job, $progress ); $labels = self::labels(); return array( 'id' => $job->id, 'type' => 'rollback', 'status' => $code, 'label' => $labels[ $code ] ?? $code, 'raw_status' => $job->status, 'total' => $job->total, 'processed' => $job->processed, 'failed' => $job->failed, 'skipped' => $job->skipped, 'stalled' => ! empty( $progress['stalled'] ), 'queue_pos' => (int) ( $progress['queue_pos'] ?? 0 ), 'as_stalled' => ! empty( $progress['as_stalled'] ), 'last_error' => (string) ( $job->row['last_error'] ?? '' ), 'can' => array( 'recover' => ! empty( $progress['stalled'] ), 'cancel' => Job::NEEDS_MANUAL === $job->status, ), ); } /** * The rollback job of an import that runs now (or waits): the batches are rolled back one job each, newest first. * * @param Job $job Import job. * @return array|null presentRollback() record. */ private static function activeRollback( Job $job ): ?array { $d = Container::requireCurrent(); $next = null; foreach ( RollbackService::chain( $job->id ) as $id ) { $b = Ledger::batchFor( $d, $id ); $rb = $b && 'rolling_back' === $b->status && $b->rollback_job_id ? JobStore::find( $d, (int) $b->rollback_job_id ) : null; if ( $rb && ! $rb->isTerminal() && ( ! $next || $rb->id < $next->id ) ) { $next = $rb; // The lowest id was queued first and runs first. } } return $next ? self::presentRollback( $next ) : null; } /** * Earliest snapshot expiry of the import's batches (UTC) or ''. * * @param Job $job Import job. * @return string */ private static function snapshotExpiry( Job $job ): string { $d = Container::requireCurrent(); $min = ''; foreach ( RollbackService::chain( $job->id ) as $id ) { $b = Ledger::batchFor( $d, $id ); if ( $b && $b->rollbackable && ! empty( $b->expires_at ) && ( '' === $min || $b->expires_at < $min ) ) { $min = (string) $b->expires_at; } } return $min; } }