$metadata Attachment metadata. * @param int $attachment_id Attachment ID. * @return array */ public function on_metadata_generated( $metadata, $attachment_id ) { if ( ! $this->restorer->is_restoring() && $this->settings->flag( 'auto_optimize' ) && $this->capabilities->has_engine() ) { $mime = (string) get_post_mime_type( (int) $attachment_id ); if ( in_array( $mime, LibraryScanner::SUPPORTED_MIMES, true ) ) { $this->enqueue_optimize( (int) $attachment_id ); add_action( 'shutdown', array( $this, 'kick_after_upload' ) ); } } return $metadata; } /** * Queues an attachment for optimization. * * @param int $attachment_id Attachment ID. * @param string $run_id Bulk run ID, or empty. * @return void */ public function enqueue_optimize( int $attachment_id, string $run_id = '' ): void { $this->state->set_status( $attachment_id, 'pending' ); $this->enqueue_once( self::HOOK_OPTIMIZE, array( $attachment_id, $run_id, 0 ) ); } /** * Processes one attachment. * * @param int $attachment_id Attachment ID. * @param string $run_id Bulk run ID, or empty. * @param int $force 1 to re-optimize. * @return void */ public function handle_optimize( $attachment_id, $run_id = '', $force = 0 ): void { $attachment_id = (int) $attachment_id; $run_id = (string) $run_id; if ( '' !== $run_id ) { $run = $this->bulk->current(); if ( null === $run || $run['id'] !== $run_id || BulkRun::RUNNING !== $run['status'] ) { // Paused or cancelled: leave the image as it is. A resume queues it again. return; } } $this->state->refresh( $attachment_id ); $key = $this->lock->attachment_key( $attachment_id ); $token = $this->lock->acquire( $key ); if ( null === $token ) { as_schedule_single_action( time() + self::RETRY_DELAY, self::HOOK_OPTIMIZE, array( $attachment_id, $run_id, (int) $force ), self::GROUP ); return; } $this->begin_work( $attachment_id, $token ); $attempts = (int) get_post_meta( $attachment_id, AttachmentState::META_ATTEMPTS, true ) + 1; update_post_meta( $attachment_id, AttachmentState::META_ATTEMPTS, $attempts ); try { if ( $attempts > self::MAX_ATTEMPTS ) { $this->optimizer->record_failure( $attachment_id, 'worker_lost', 'Job kept stopping before it finished.' ); } else { if ( '' !== $run_id ) { $this->bulk->set_current_file( wp_basename( (string) get_attached_file( $attachment_id ) ) ); } $this->optimizer->optimize( $attachment_id, array( 'force' => (bool) $force ) ); } } catch ( Throwable $e ) { $this->optimizer->record_failure( $attachment_id, 'internal_error', $e->getMessage() ); } $exists = 'attachment' === get_post_type( $attachment_id ); if ( $exists && 'pending' === $this->state->status( $attachment_id ) ) { $this->state->set_status( $attachment_id, $this->settled_status( $attachment_id ) ); } if ( $exists && '' !== $run_id ) { update_post_meta( $attachment_id, AttachmentState::META_RUN, $run_id ); } delete_post_meta( $attachment_id, AttachmentState::META_ATTEMPTS ); $this->end_work( $attachment_id, $token ); if ( $exists && in_array( $this->state->status( $attachment_id ), array( OptimizeResult::OPTIMIZED, OptimizeResult::ALREADY_OPTIMAL ), true ) && $this->converter->is_enabled() ) { $this->enqueue_convert( $attachment_id ); } } /** * Queues an attachment for conversion to WebP and AVIF. * * @param int $attachment_id Attachment ID. * @param string $run_id Bulk run ID, or empty. * @return void */ public function enqueue_convert( int $attachment_id, string $run_id = '' ): void { update_post_meta( $attachment_id, AttachmentState::META_CONVERT_STATUS, 'pending' ); $this->enqueue_once( self::HOOK_CONVERT, array( $attachment_id, $run_id, 0 ) ); } /** * Creates one attachment's WebP and AVIF copies. * * @param int $attachment_id Attachment ID. * @param string $run_id Bulk run ID, or empty. * @param int $force 1 to render again. * @return void */ public function handle_convert( $attachment_id, $run_id = '', $force = 0 ): void { $attachment_id = (int) $attachment_id; $run_id = (string) $run_id; if ( '' !== $run_id ) { $run = $this->bulk->current(); if ( null === $run || $run['id'] !== $run_id || BulkRun::RUNNING !== $run['status'] ) { return; } } $this->state->refresh( $attachment_id ); $key = $this->lock->attachment_key( $attachment_id ); $token = $this->lock->acquire( $key ); if ( null === $token ) { as_schedule_single_action( time() + self::RETRY_DELAY, self::HOOK_CONVERT, array( $attachment_id, $run_id, (int) $force ), self::GROUP ); return; } $this->begin_work( $attachment_id, $token, BulkRun::JOB_CONVERT ); $attempts = (int) get_post_meta( $attachment_id, AttachmentState::META_ATTEMPTS, true ) + 1; update_post_meta( $attachment_id, AttachmentState::META_ATTEMPTS, $attempts ); try { if ( $attempts > self::MAX_ATTEMPTS ) { $this->converter->record_failure( $attachment_id, 'worker_lost', 'Job kept stopping before it finished.' ); } else { if ( '' !== $run_id ) { $this->bulk->set_current_file( wp_basename( (string) get_attached_file( $attachment_id ) ) ); } $this->converter->convert( $attachment_id, array( 'force' => (bool) $force ) ); } } catch ( Throwable $e ) { $this->converter->record_failure( $attachment_id, 'internal_error', $e->getMessage() ); } $exists = 'attachment' === get_post_type( $attachment_id ); if ( $exists && '' !== $run_id ) { update_post_meta( $attachment_id, AttachmentState::META_RUN, $run_id ); } delete_post_meta( $attachment_id, AttachmentState::META_ATTEMPTS ); $this->end_work( $attachment_id, $token ); } /** * Restores one attachment. * * @param int $attachment_id Attachment ID. * @return void */ public function handle_restore( $attachment_id ): void { $attachment_id = (int) $attachment_id; $this->state->refresh( $attachment_id ); $key = $this->lock->attachment_key( $attachment_id ); $token = $this->lock->acquire( $key ); if ( null === $token ) { as_schedule_single_action( time() + self::RETRY_DELAY, self::HOOK_RESTORE, array( $attachment_id ), self::GROUP ); return; } $this->begin_work( $attachment_id, $token ); try { $this->restorer->restore( $attachment_id ); } catch ( Throwable $e ) { $this->log->write( 'error', 'restore_failed', $attachment_id, $e->getMessage() ); } $this->end_work( $attachment_id, $token ); } /** * Queues restore jobs for everything with a backup, in chunks. * * @param int $after_id Exclusive lower bound. * @return void */ public function handle_restore_dispatch( $after_id = 0 ): void { $ids = $this->restorer->restorable_ids( (int) $after_id, self::RESTORE_CHUNK ); foreach ( $ids as $id ) { $this->enqueue_once( self::HOOK_RESTORE, array( $id ) ); } if ( count( $ids ) === self::RESTORE_CHUNK ) { $this->enqueue_once( self::HOOK_RESTORE_DISPATCH, array( (int) end( $ids ) ) ); } } /** * Queues restores for selected attachments, or for all when none are given. * * @param int[] $ids Attachment IDs. * @return int Jobs queued, or -1 when all backups are being dispatched in the background. */ public function enqueue_restore( array $ids = array() ): int { if ( array() === $ids ) { $this->enqueue_once( self::HOOK_RESTORE_DISPATCH, array( 0 ) ); $this->kick_queue( true ); return -1; } foreach ( $ids as $id ) { $this->enqueue_once( self::HOOK_RESTORE, array( (int) $id ) ); } $this->kick_queue( true ); return count( $ids ); } /** * Starts a bulk run. * * @param string $scope Library scope. * @return array Progress report. */ public function start_bulk( string $scope ): array { if ( $this->bulk->is_running() ) { return $this->bulk->progress(); } $total = $this->scanner->count_scope( $scope ); if ( 0 === $total ) { return $this->bulk->progress(); } $run = $this->bulk->start( $scope, $total ); $this->handle_pump( (string) $run['id'] ); $this->kick_queue( true ); return $this->bulk->progress(); } /** * Resumes a paused run. * * @return array Progress report. */ public function resume_bulk(): array { $this->bulk->resume(); $run = $this->bulk->current(); if ( null !== $run && BulkRun::RUNNING === $run['status'] ) { $this->handle_pump( (string) $run['id'] ); $this->kick_queue( true ); } return $this->bulk->progress(); } /** * Keeps a limited window of jobs queued, then re-queues itself behind them. * * Queueing behind the window paces the run by real progress without timers, and a * small window keeps the Action Scheduler tables small on very large libraries. * * @param string $run_id Run ID. * @return void */ public function handle_pump( $run_id ): void { $run_id = (string) $run_id; $run = $this->bulk->current(); if ( null === $run || $run['id'] !== $run_id || BulkRun::RUNNING !== $run['status'] ) { return; } $window = max( self::MIN_WINDOW, $this->settings->int( 'batch_size' ) * 4 ); $inflight = $this->inflight_count(); $ids = array(); $convert = BulkRun::JOB_CONVERT === ( $run['job'] ?? BulkRun::JOB_OPTIMIZE ); if ( $inflight < $window ) { $ids = $this->scanner->ids_in_scope( (string) $run['scope'], (int) $run['cursor'], $window - $inflight ); foreach ( $ids as $id ) { if ( $convert ) { $this->enqueue_convert( $id, $run_id ); } else { $this->enqueue_optimize( $id, $run_id ); } } if ( array() !== $ids ) { $this->bulk->update( array( 'cursor' => (int) end( $ids ) ) ); } } if ( array() !== $ids ) { as_enqueue_async_action( self::HOOK_PUMP, array( $run_id ), self::GROUP ); return; } if ( 0 === $inflight && array() === $this->requeue_lost_jobs( $run_id, $convert ) ) { $this->bulk->complete(); $this->log->write( 'info', 'bulk_completed', 0, $run_id ); return; } as_schedule_single_action( time() + self::WAIT_DELAY, self::HOOK_PUMP, array( $run_id ), self::GROUP ); } /** * Restarts the pump if a killed worker took it down, and reconciles stuck jobs. * * @return void */ public function handle_watchdog(): void { $this->ensure_pump(); } /** * Re-queues the pump for a running bulk run when none is scheduled. * * @return void */ public function ensure_pump(): void { $run = $this->bulk->current(); if ( null === $run || BulkRun::RUNNING !== $run['status'] ) { return; } $args = array( (string) $run['id'] ); if ( ! as_has_scheduled_action( self::HOOK_PUMP, $args, self::GROUP ) ) { as_enqueue_async_action( self::HOOK_PUMP, $args, self::GROUP ); } } /** * Counts jobs that should have run over an hour ago, which means the queue is stuck. * * @return int */ public function overdue_count(): int { return (int) ActionScheduler::store()->query_actions( array( 'group' => self::GROUP, 'status' => ActionScheduler_Store::STATUS_PENDING, 'date' => as_get_datetime_object( time() - HOUR_IN_SECONDS ), 'date_compare' => '<=', ), 'count' ); } /** * Daily housekeeping. * * @return void */ public function handle_maintenance(): void { $this->log->prune(); $this->backups->prune_expired(); Paths::clean_temp(); } /** * Schedules recurring work, checking at most once an hour. * * @return void */ public function schedule_recurring(): void { if ( false !== get_transient( self::RECURRING_MARKER ) ) { return; } set_transient( self::RECURRING_MARKER, 1, HOUR_IN_SECONDS ); if ( ! as_has_scheduled_action( self::HOOK_WATCHDOG, array(), self::GROUP ) ) { as_schedule_recurring_action( time() + 5 * MINUTE_IN_SECONDS, 5 * MINUTE_IN_SECONDS, self::HOOK_WATCHDOG, array(), self::GROUP ); } if ( ! as_has_scheduled_action( self::HOOK_MAINTENANCE, array(), self::GROUP ) ) { as_schedule_recurring_action( time() + HOUR_IN_SECONDS, DAY_IN_SECONDS, self::HOOK_MAINTENANCE, array(), self::GROUP ); } } /** * Removes all scheduled PixelKeep actions. * * @return void */ public function unschedule_all(): void { if ( function_exists( 'as_unschedule_all_actions' ) && class_exists( ActionScheduler::class, false ) && ActionScheduler::is_initialized() ) { as_unschedule_all_actions( '', array(), self::GROUP ); } delete_transient( self::RECURRING_MARKER ); } /** * Uses the configured batch size while a bulk run is active. * * @param int $size Default size. * @return int */ public function filter_batch_size( $size ) { return $this->bulk->is_running() ? $this->settings->int( 'batch_size' ) : $size; } /** * Allows the configured number of concurrent runners while a bulk run is active. * * @param int $count Default count. * @return int */ public function filter_concurrency( $count ) { return $this->bulk->is_running() ? max( (int) $count, $this->settings->int( 'concurrency' ) ) : $count; } /** * Starts the background runner through a non-blocking loopback request. * * Action Scheduler only does this from wp-admin. REST requests need to ask, and from * then on each runner re-dispatches itself, so work continues after the browser closes. * * Any admin page load sets Action Scheduler's 60-second dispatch lock, even with nothing * to do. Work that was just queued must not wait for it: someone may close the browser * right after clicking Start, and then nothing else would ever start the runner. * * @param bool $just_queued Whether new work was queued, which goes past the lock. * @return void */ public function kick_queue( bool $just_queued = false ): void { $lock = ActionScheduler::lock(); if ( ! $just_queued && $lock->is_locked( 'async-request-runner' ) ) { return; } $lock->set( 'async-request-runner' ); ( new ActionScheduler_AsyncRequest_QueueRunner( ActionScheduler::store() ) )->maybe_dispatch(); } /** * Starts the runner once an upload's request has finished. * * Uploads through the REST API are not admin requests, so without this they would wait for WP-Cron. * * @return void */ public function kick_after_upload(): void { $this->kick_queue( true ); } /** * Queues an action unless the same action with the same arguments is already waiting. * * Action Scheduler's own `unique` flag ignored the arguments before 4.0, which would allow one * image in the queue at a time, and any plugin can load an older or newer copy of the library. A rare duplicate from a race is harmless, * because each image's job takes a lock and does nothing once the image is settled. * * @param string $hook Action hook. * @param array $args Action arguments. * @return void */ private function enqueue_once( string $hook, array $args ): void { if ( ! as_has_scheduled_action( $hook, $args, self::GROUP ) ) { as_enqueue_async_action( $hook, $args, self::GROUP ); } } /** * Counts queued and running optimize jobs. * * @return int */ private function inflight_count(): int { $store = ActionScheduler::store(); $count = 0; foreach ( array( self::HOOK_OPTIMIZE, self::HOOK_CONVERT ) as $hook ) { foreach ( array( ActionScheduler_Store::STATUS_PENDING, ActionScheduler_Store::STATUS_RUNNING ) as $status ) { $count += (int) $store->query_actions( array( 'hook' => $hook, 'group' => self::GROUP, 'status' => $status, ), 'count' ); } } return $count; } /** * Re-queues images still marked pending when no job is left to handle them. * * This is how a killed worker's image gets finished: Action Scheduler eventually marks * that action failed without retrying, and the image is still pending here. * * @param string $run_id Run ID. * @param bool $convert Whether the run converts rather than optimizes. * @return int[] Re-queued IDs. */ private function requeue_lost_jobs( string $run_id, bool $convert ): array { $ids = $this->scanner->marked_pending_ids( self::MIN_WINDOW, $convert ? AttachmentState::META_CONVERT_STATUS : AttachmentState::META_STATUS ); foreach ( $ids as $id ) { if ( $convert ) { $this->enqueue_convert( $id, $run_id ); } else { $this->enqueue_optimize( $id, $run_id ); } } return $ids; } /** * Works out which status an attachment should fall back to after a no-op. * * @param int $attachment_id Attachment ID. * @return string */ private function settled_status( int $attachment_id ): string { $state = $this->state->get( $attachment_id ); return is_string( $state['status'] ?? null ) && 'pending' !== $state['status'] ? $state['status'] : OptimizeResult::SKIPPED; } /** * Starts tracking in-flight work, so an out-of-memory fatal can be recorded. * * @param int $attachment_id Attachment ID. * @param string $token Lock token. * @param string $job Kind of work. * @return void */ private function begin_work( int $attachment_id, string $token, string $job = BulkRun::JOB_OPTIMIZE ): void { $this->in_flight = array( 'id' => $attachment_id, 'token' => $token, 'job' => $job, ); $timeout = $this->settings->int( 'timeout' ); if ( function_exists( 'set_time_limit' ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Squiz.PHP.DiscouragedFunctions.Discouraged -- A background job, not a page view, needs its own time budget. Hosts may disable this; the job's deadline still applies. @set_time_limit( $timeout + 30 ); } if ( ! $this->shutdown_registered ) { $this->shutdown_registered = true; register_shutdown_function( array( $this, 'on_shutdown' ) ); } } /** * Stops tracking and releases the lock. * * @param int $attachment_id Attachment ID. * @param string $token Lock token. * @return void */ private function end_work( int $attachment_id, string $token ): void { $this->lock->release( $this->lock->attachment_key( $attachment_id ), $token ); $this->in_flight = null; } /** * Records PHP fatals, such as running out of memory, against the image that caused them. * * @return void */ public function on_shutdown(): void { if ( null === $this->in_flight ) { return; } $error = error_get_last(); if ( null === $error || ! in_array( $error['type'], array( E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_RECOVERABLE_ERROR ), true ) ) { return; } $id = $this->in_flight['id']; if ( BulkRun::JOB_CONVERT === $this->in_flight['job'] ) { $this->converter->record_failure( $id, 'fatal_error', (string) $error['message'] ); } else { $this->optimizer->record_failure( $id, 'fatal_error', (string) $error['message'] ); } delete_post_meta( $id, AttachmentState::META_ATTEMPTS ); $this->lock->release( $this->lock->attachment_key( $id ), $this->in_flight['token'] ); $this->in_flight = null; } }