params['batch_id'] ?? 0 ); if ( $b > 0 ) { $batches[] = $b; } } $rows = (array) $wpdb->get_col( $wpdb->prepare( "SELECT params_json FROM {$wpdb->prefix}catalogrelay_jobs WHERE job_type = %s AND params_json LIKE %s ORDER BY id", RetryJobType::TYPE, '%"retry_of":' . $rootId . ',%' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from the prefix. foreach ( $rows as $json ) { $p = json_decode( (string) $json, true ); if ( is_array( $p ) && (int) ( $p['retry_of'] ?? 0 ) === $rootId && ! empty( $p['batch_id'] ) ) { $batches[] = (int) $p['batch_id']; } } return array_values( array_unique( $batches ) ); } /** * Why a job cannot be rolled back ('' when it can). * * @param Job $job Import job. * @return string not_import|not_finished|retry_running|no_rollback_point|expired|already_rolled_back|rolling_back */ public static function blocker( Job $job ): string { if ( ImportJobType::TYPE !== $job->type ) { return 'not_import'; } if ( ! $job->isTerminal() ) { return 'not_finished'; } if ( self::retryRunning( $job->id ) ) { return 'retry_running'; // Its writes would come after the preview (and before the rollback, which queues behind it). } $d = Container::requireCurrent(); $batches = self::chain( $job->id ); if ( ! $batches ) { return 'no_rollback_point'; } $any_open = false; foreach ( $batches as $id ) { $b = Ledger::batchFor( $d, $id ); if ( ! $b || ! $b->rollbackable ) { return 'no_rollback_point'; } if ( 'rolling_back' === $b->status ) { return 'rolling_back'; } if ( 'expired' === $b->status || ( null !== $b->expires_at && strtotime( $b->expires_at . ' UTC' ) <= time() ) ) { return 'expired'; } if ( 'rolled_back' !== $b->status ) { $any_open = true; } } return $any_open ? '' : 'already_rolled_back'; } /** * Whether a retry of the import has not finished (queued, running, paused or waiting for attention). * * @param int $rootId Import job. * @return bool */ private static function retryRunning( int $rootId ): bool { global $wpdb; $done = "'" . implode( "', '", Job::TERMINAL ) . "'"; // Constants, not user input. return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}catalogrelay_jobs WHERE job_type = %s AND status NOT IN ({$done}) AND params_json LIKE %s LIMIT 1", RetryJobType::TYPE, '%"retry_of":' . $rootId . ',%' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from the prefix, fixed status list. } /** * Start the preview job. * * @param int $jobId Import job. * @return int Preview job id. * @throws \RuntimeException With the blocker as message. */ public static function preview( int $jobId ): int { $d = Container::requireCurrent(); $job = JobStore::find( $d, $jobId ); if ( ! $job ) { throw new \RuntimeException( 'not_found' ); } $why = self::blocker( $job ); if ( '' !== $why ) { throw new \RuntimeException( $why ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- the message is returned as JSON or escaped on render, never echoed raw. } return JobEngine::enqueue( DryRunJobType::TYPE, array( 'v' => JobParams::VERSION, 'mode' => 'rollback_preview', 'source_job' => $jobId, 'batches' => self::chain( $jobId ), 'file' => array(), ), array( 'inline_s' => 2 ) ); } /** * The ledger rows to force that the preview listed as conflicts (a forced row is always one the user saw as a conflict). * * @param int $previewId Preview job. * @param int[] $force Ledger rows. * @return int[] */ private static function previewConflicts( int $previewId, array $force ): array { global $wpdb; $force = array_values( array_unique( array_filter( array_map( 'intval', $force ) ) ) ); if ( ! $force ) { return array(); } $in = implode( ', ', array_fill( 0, count( $force ), '%d' ) ); return array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT row_no FROM %i WHERE job_id = %d AND status = 'conflict' AND row_no IN ($in)", array_merge( array( Schema::table(), $previewId ), $force ) ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- placeholders generated from a list. } /** * Confirm: roll back every batch the preview judged, newest first. * * @param int $jobId Import job. * @param int $previewId Preview job. * @param string $hash Plan hash from the preview. * @param int[] $force Ledger rows to force-restore. * @return int[] Rollback job ids. * @throws \RuntimeException With a code when the confirmation is refused, or the library's exception (e.g. * JobsUnavailable) when a batch cannot be rolled back; RollbackInterrupted wraps either * once newer batches are already rolling back. */ public static function confirm( int $jobId, int $previewId, string $hash, array $force = array() ): array { $d = Container::requireCurrent(); $job = JobStore::find( $d, $jobId ); $preview = JobStore::find( $d, $previewId ); if ( ! $job || ! $preview || DryRunJobType::TYPE !== $preview->type || (int) ( $preview->params['source_job'] ?? 0 ) !== $jobId ) { throw new \RuntimeException( 'preview_mismatch' ); } $plan = JobRowsRepo::getSentinel( $previewId, 'plan' ); if ( ! $plan || ! PlanPreview::verifyFor( $d, (int) $plan['plan_id'], $hash ) ) { throw new \RuntimeException( 'preview_expired' ); } $lock = JobFactory::chainLock( $jobId ); if ( ! JobFactory::lock( $lock ) ) { throw new \RuntimeException( 'retry_running' ); // A retry of the import is being queued right now. } try { return self::rollBackChain( $d, $job, $preview, $force ); } finally { delete_option( $lock ); } } /** * Roll back the batches the preview judged, under the lock of the import's chain (no retry is queued in between). * * @param ProductDescriptor $d Product. * @param Job $job Import job. * @param Job $preview Preview job. * @param int[] $force Ledger rows to force-restore. * @return int[] Rollback job ids. * @throws \RuntimeException See confirm(). */ private static function rollBackChain( ProductDescriptor $d, Job $job, Job $preview, array $force ): array { $jobId = $job->id; $previewId = $preview->id; $why = self::blocker( $job ); if ( '' !== $why ) { throw new \RuntimeException( $why ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- the message is returned as JSON or escaped on render, never echoed raw. } $batches = array_values( array_map( 'intval', (array) ( $preview->params['batches'] ?? array() ) ) ); if ( self::chain( $jobId ) !== $batches ) { throw new \RuntimeException( 'preview_expired' ); // A retry joined the import after the preview: its writes were not previewed. } $force = self::previewConflicts( $previewId, $force ); $ids = array(); foreach ( array_reverse( $batches ) as $batch_id ) { $b = Ledger::batchFor( $d, $batch_id ); if ( ! $b || 'rolled_back' === $b->status ) { continue; } try { $ids[] = Ledger::rollbackBatch( $batch_id, array( 'exclusive_group' => ImportJobType::GROUP, 'force_rows' => $force, 'inline_s' => 2, ) ); } catch ( \RuntimeException $e ) { if ( $e instanceof RollbackRejected ) { $e = new \RuntimeException( $e->reason() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- the message is returned as JSON or escaped on render, never echoed raw. } if ( $ids ) { throw new RollbackInterrupted( $ids, $e ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- $ids are product IDs (int[]); not output. } throw $e; } } return $ids; } }